LoopX Quota Spend Sources and Settlement Validation Rules: Complete Implementation Guide
LoopX implements three distinct quota spend sources—runtime_events, visible-goal, and heartbeat—and enforces strict settlement validation rules including identity consistency, step ordering, and idempotent replay to ensure accurate budget accounting.
The LoopX agent execution framework (available at huangruiteng/loopx) provides a sophisticated quota system that controls resource consumption across agent turns. Understanding the quota spend sources and settlement validation rules in LoopX is essential for control plane integrators, as these mechanisms ensure that quota is spent only after durable writeback and within defined budget limits.
Quota Spend Sources in LoopX
LoopX categorizes quota consumption into three distinct spend sources defined in loopx/control_plane/quota/spend_sources.py. Each source corresponds to a specific execution context and is stored in the spend_source field of the quota-spend payload.
Runtime Events (Default)
The runtime_events source represents the standard agent execution path. Defined as DEFAULT_SLOT_SPEND_SOURCE in loopx/control_plane/quota/spend_sources.py, this source is selected when the quota spend triggers from the normal runtime event loop, as implemented in loopx/quota.py (line 407).
Visible-Goal Scheduler Context
When execution originates from the visible-goal scheduler, LoopX uses the visible-goal source. The constant VISIBLE_GOAL_SLOT_SPEND_SOURCE identifies this path, selected when a goal is explicitly marked as visible in loopx/control_plane/quota/spend_sources.py (line 29). This distinguishes scheduler-driven work from standard runtime events.
Heartbeat-Driven Execution
The heartbeat source applies to periodic maintenance turns rather than direct commands. The heartbeat subsystem emits this source in loopx/control_plane/quota/effect_program.py (line 85) when driving turns via scheduled heartbeats, ensuring that background maintenance tasks are accounted for separately.
Determining the Source Programmatically
The helper function quota_spend_source_for_execution_context() examines the scheduler’s execution context and returns the appropriate string identifier. This function bridges the control plane logic with the quota runtime, ensuring that the correct source is attached to the payload before submission to the quota system.
Settlement Validation Rules in LoopX
Settlement validation ensures that quota spends are recorded only after successful turn completion and within budget constraints. The validation logic spans loopx/control_plane/turn_driver/settlement.py and loopx/control_plane/quota/settlement.py, performing checks that prevent over-consumption and ensure consistency.
Identity Consistency Requirements
All effects within a single turn must share identical settlement identity fields including goal_id, agent_id, todo_id, and effect_id. The test suite in tests/test_turn_loop_disposition.py (lines 128-129) verifies that mismatched identities trigger validation failures, ensuring that all effects are tied to the same logical turn.
Step Ordering Constraints
Settlement plans must follow the exact sequence: host_execute → typed_result → validation → durable_writeback → quota_spend. This ordering, validated in tests/test_turn_loop_disposition.py (lines 123-124), guarantees that quota is only spent after the state has been durably written, preventing budget loss for failed operations.
Budget Enforcement and Presence Checks
The settlement driver rejects plans that would exceed available budget, raising budget_rejected errors as demonstrated in tests/test_loopx_turn_executor.py (lines 2245-2247). Additionally, quota-spend effects appear only when the quota-should-run check succeeds, verified in tests/test_loopx_turn_transaction.py (lines 63-81), blocking quota spending for throttled turns.
Idempotent Replay Guarantees
For crash recovery safety, replaying a settled turn must not generate duplicate quota spends. The idempotent_replay flag in tests/test_goal_mode_mcp_settlement.py (lines 379-380) ensures that re-executing a turn with an existing settlement skips quota expenditure. The settlement-binding matching rule in tests/test_loopx_turn_driver.py (lines 2246-2248) further detects mismatches between a turn’s journal and its settlement plan.
Failure Propagation and No-Spend Scenarios
If any phase before quota spend fails (validation, write-back, etc.), the settlement result must report the failure without recording quota consumption, as tested in tests/test_loopx_turn_executor.py (lines 2242-2244). Diagnostic commands explicitly set spend_source to empty strings ("") to avoid affecting budgets, demonstrated in tests/test_quota_settlement_cli.py (line 2585), allowing quota-should-run queries without expenditure.
Implementation Examples
The following examples demonstrate how to determine spend sources and execute settlement validation in LoopX applications.
from loopx.control_plane.quota.spend_sources import quota_spend_source_for_execution_context
def build_quota_spend_payload(scheduler_ctx):
"""Construct a quota payload with the correct spend source."""
source = quota_spend_source_for_execution_context(scheduler_ctx)
payload = {
"spend_source": source, # "runtime_events", "visible-goal", or "heartbeat"
"quota_spend_command": "record_turn",
"amount": 1
}
return payload
from loopx.control_plane.turn_driver.settlement import execute_turn_driver_settlement
def run_turn(transaction):
"""Execute a turn and validate settlement before quota spend."""
result = execute_turn_driver_settlement(transaction)
if not result.ok:
# Errors include budget_rejected, writeback_rejected,
# or quota_spend_before_writeback
raise RuntimeError(f"Settlement failed: {result.failure}")
# On success, result.settlement_plan includes ordered steps ending with quota_spend
return result.settlement_plan
Summary
- LoopX defines three spend sources:
runtime_events(default agent execution),visible-goal(scheduler-driven goals), andheartbeat(periodic maintenance turns). - The
quota_spend_source_for_execution_context()function selects the appropriate source based on scheduler context inloopx/control_plane/quota/spend_sources.py. - Settlement validation enforces strict step ordering (
host_executethroughquota_spend), ensuring quota is only spent after durable writeback. - Budget enforcement rejects settlements that would exceed available quota, raising
budget_rejectederrors before recording spends. - Idempotent replay prevents duplicate quota charges during crash recovery, verified by settlement-binding matching.
- Failure propagation ensures that failed turns (validation errors, writeback failures) do not consume quota, maintaining accurate budget tracking.
Frequently Asked Questions
What are the three quota spend sources in LoopX?
LoopX recognizes three quota spend sources defined in loopx/control_plane/quota/spend_sources.py: runtime_events for standard agent execution paths, visible-goal for scheduler-driven visible goals, and heartbeat for periodic maintenance turns. The helper function quota_spend_source_for_execution_context() returns the appropriate source string based on the current execution context.
How does LoopX prevent duplicate quota spending during replay?
LoopX implements idempotent replay guards in the settlement driver (loopx/control_plane/turn_driver/settlement.py). When replaying a settled turn, the system checks the idempotent_replay flag and validates settlement-binding matching (verified in tests/test_goal_mode_mcp_settlement.py lines 379-380). If a settlement already exists for the turn identity, the quota spend step is skipped, preventing double-charging during crash recovery.
What happens if a turn fails before the quota spend phase?
If any phase before quota spend fails—such as validation or durable writeback—the settlement result reports the specific failure (e.g., writeback_rejected or validation errors) and no quota is consumed. This failure propagation mechanism, tested in tests/test_loopx_turn_executor.py (lines 2242-2244), ensures that the quota budget remains accurate when turns abort early, maintaining the invariant that quota is only spent for successfully completed turns.
Where are the spend source constants defined in the LoopX codebase?
The spend source constants DEFAULT_SLOT_SPEND_SOURCE and VISIBLE_GOAL_SLOT_SPEND_SOURCE are defined in loopx/control_plane/quota/spend_sources.py. The heartbeat source is referenced in loopx/control_plane/quota/effect_program.py (line 85), while the top-level quota API in loopx/quota.py (line 407) attaches these sources to the quota-spend payload sent to the runtime.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →