From e82b86a53005afe54b2c5ec37ce1bfbbedbcaf41 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:13:29 +0800 Subject: [PATCH 1/2] fix(quota): report spend index conflicts on the CLI Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/quota_failure_report.py | 12 ++++ loopx/control_plane/quota/error_codes.py | 8 +++ loopx/control_plane/quota/spend_commit.py | 9 +-- ...test_quota_authority_settlement_journey.py | 55 ++++++++++++++++++- 4 files changed, 75 insertions(+), 9 deletions(-) diff --git a/loopx/cli_commands/quota_failure_report.py b/loopx/cli_commands/quota_failure_report.py index 1de65a1b0b..f3c267af7d 100644 --- a/loopx/cli_commands/quota_failure_report.py +++ b/loopx/cli_commands/quota_failure_report.py @@ -41,6 +41,7 @@ QuotaCommandValidationError, QuotaDecisionTransportError, QuotaIdentityPreconditionError, + QuotaRunIndexConflict, quota_error_code, ) from ..file_lock import lock_timeout_error_fields @@ -168,6 +169,17 @@ def quota_failure_payload( diagnostic_code = getattr(error, "diagnostic_code", None) if isinstance(error, EffectRuntimeRemoteError) and isinstance(diagnostic_code, str): payload["diagnostic_code"] = diagnostic_code + if isinstance(error, QuotaRunIndexConflict): + payload.update( + status=error.reason_code, + reason="the quota run index changed before the spend could commit", + appended=False, + recommended_action=( + "for a bound spend, rerun quota should-run with the same Turn " + "identity and follow its returned settlement command. For an " + "unbound spend, obtain a fresh preview before retrying." + ), + ) if isinstance(error, HeartbeatReceiptIdentityConflictError): payload.update({ "status": "heartbeat_receipt_identity_conflict", diff --git a/loopx/control_plane/quota/error_codes.py b/loopx/control_plane/quota/error_codes.py index e2e9e37641..f1aa270762 100644 --- a/loopx/control_plane/quota/error_codes.py +++ b/loopx/control_plane/quota/error_codes.py @@ -32,6 +32,12 @@ class HeartbeatReceiptIdentityConflictError(ValueError): """Public-safe diagnostic for a same-turn settlement identity conflict.""" +class QuotaRunIndexConflict(ValueError): + """A quota spend was definitively rejected by the run-index CAS.""" + + reason_code = "index_digest_conflict" + + class QuotaIdentityPrecondition(StrEnum): """Typed identity admission preconditions for scoped quota decisions.""" @@ -233,6 +239,8 @@ def quota_error_code(exc: BaseException) -> str: return exc.error_code if isinstance(exc, HeartbeatReceiptIdentityConflictError): return "heartbeat_receipt_identity_conflict" + if isinstance(exc, QuotaRunIndexConflict): + return exc.reason_code if isinstance(exc, PermissionError): return "quota_state_permission_denied" if isinstance(exc, OSError): diff --git a/loopx/control_plane/quota/spend_commit.py b/loopx/control_plane/quota/spend_commit.py index 5ddc370ba6..b8b5e2f677 100644 --- a/loopx/control_plane/quota/spend_commit.py +++ b/loopx/control_plane/quota/spend_commit.py @@ -17,8 +17,9 @@ ) from ..runtime.time import now_local_iso from ..todos.contract import normalize_todo_claimed_by -from .decision_summary import compact_quota_decision, quota_decision_agent_id from .accounting_admission import quota_accounting_admission +from .decision_summary import compact_quota_decision, quota_decision_agent_id +from .error_codes import QuotaRunIndexConflict from .spend_sources import DEFAULT_SLOT_SPEND_SOURCE @@ -26,12 +27,6 @@ QUOTA_SPEND_COMMIT_RESULT_SCHEMA = "loopx_quota_spend_commit_result_v0" -class QuotaRunIndexConflict(ValueError): - """A quota spend was definitively rejected by the run-index CAS.""" - - reason_code = "index_digest_conflict" - - def quota_spend_index_digest(index_path: Path) -> str | None: try: content = index_path.read_bytes() diff --git a/tests/control_plane/test_quota_authority_settlement_journey.py b/tests/control_plane/test_quota_authority_settlement_journey.py index 6d6e0c259c..4051c6f680 100644 --- a/tests/control_plane/test_quota_authority_settlement_journey.py +++ b/tests/control_plane/test_quota_authority_settlement_journey.py @@ -16,10 +16,12 @@ from codex_checkpoint_fixture import selected_context_values from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection -from loopx.control_plane.todos.active_state_todo_parser import parse_active_state_todos +from loopx.control_plane.quota import slot_accounting from loopx.control_plane.quota.settlement import read_heartbeat_settlement -from loopx.rollout_event_log import rollout_event_log_path +from loopx.control_plane.todos.active_state_todo_parser import parse_active_state_todos +from loopx.entrypoint import main as cli_main from loopx.presentation.renderers.quota_event_markdown import render_quota_slot_preview_markdown +from loopx.rollout_event_log import rollout_event_log_path from loopx.state_refresh import render_state_refresh_markdown from loopx.todos import list_goal_todos @@ -901,3 +903,52 @@ def test_returned_command_settles_and_repairs_receipts_without_another_debit(tmp assert code == 0, next_wake assert next_wake["effective_action"] != "unsettled_host_turn_recovery" assert cli._spend_run_count(runtime) == 1 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_spend_index_conflict_keeps_its_diagnostic_and_retries_the_same_turn( + tmp_path, monkeypatch, capsys, provider, +): + project, runtime, registry = cli._write_fixture(tmp_path) + cli._initialize_fixture_authority(project, runtime, provider=provider) + code, guard = _guard(project, runtime, registry) + assert code == 0, guard + code, refreshed = _refresh(project, runtime, registry) + assert code == 0, refreshed + command = refreshed["settlement_owed"]["command"] + + commit = slot_accounting.record_quota_slot_spend_from_preview + + def spend_with_competing_write(preview, status, **kwargs): + # Commit another real spend after the original preview captured its basis. + code, competing = cli._run_cli( + registry, runtime, "quota", "spend-slot", "--execute", "--source", "controller", + "--goal-id", cli.GOAL_ID, "--agent-id", cli.AGENT_ID, cwd=project, + ) + assert code == 0 and competing["appended"] is True, competing + return commit(preview, status, **kwargs) + + with monkeypatch.context() as patch: + patch.chdir(project) + patch.setattr( + slot_accounting, "record_quota_slot_spend_from_preview", spend_with_competing_write, + ) + code = cli_main(shlex.split(command)[1:]) + rejected = json.loads(capsys.readouterr().out) + assert code == 1 and rejected["ok"] is False, rejected + assert cli._spend_run_count(runtime) == 1 + assert rejected["error_code"] == "index_digest_conflict", rejected + assert rejected["status"] == "index_digest_conflict" + assert rejected["appended"] is False + assert "same Turn" in rejected["recommended_action"] + + code, still_owed = _refresh(project, runtime, registry) + assert code == 0 and still_owed["settlement_owed"]["command"] == command, still_owed + code, recovered = _execute(command, project, runtime, registry) + assert code == 0 and recovered["settlement_progress"]["state"] == "settled", recovered + assert recovered["settlement_identity"] == refreshed["settlement_identity"] + assert recovered["appended"] is True + code, replay = _execute(command, project, runtime, registry) + assert code == 0 and replay["appended"] is False, replay + assert replay["settlement_identity"] == recovered["settlement_identity"] + assert cli._spend_run_count(runtime) == 2 From 78c3a7156ddf06d5ab8551e6c5a9d56572e3b489 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:10:20 +0800 Subject: [PATCH 2/2] fix(quota): treat pending spend after verified writeback as settlement_pending Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../quota/settlement_readback.ts | 7 +- ...test_quota_authority_settlement_journey.py | 103 ++++++++++++++++++ .../control_plane/test_refresh_settle_turn.py | 97 +++++++++++++++++ .../quota_settlement_readback.test.ts | 75 ++++++++++++- 4 files changed, 280 insertions(+), 2 deletions(-) diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index 67b4b1be40..7548dafe24 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -1596,9 +1596,14 @@ function readQuotaSettlementFromRequest( // A committed observation closes its exact Turn independently of whether // the monitor still appears in the current Todo frontier. Reuse the monitor // reducer so completion, retirement or archival cannot reopen that Turn. + // Once a durable writeback is verified and quota spend (or its receipt) is + // still owed, the Turn is settlement_pending regardless of optional boundary + // or checkpoint flags; completed spends without those proofs remain open. + const spendPendingAfterWriteback = writeback.failure === null && spend.failure !== null; const replayPhase = monitorPhase === "settled" ? "settled" : receiptBoundReplayPhase({ binding_kind: identity.binding_kind, - writeback_completes_binding: todoBoundReplan || noSpendKind !== null || progressWriteback || replanWriteback, + writeback_completes_binding: todoBoundReplan || noSpendKind !== null || progressWriteback || + replanWriteback || spendPendingAfterWriteback, completion_receipt_present: completionEvent !== null, supersede_receipt_present: supersedeEvent?.status === "done" && optionalString(supersedeEvent.todo_id) === identity.todo_id, diff --git a/tests/control_plane/test_quota_authority_settlement_journey.py b/tests/control_plane/test_quota_authority_settlement_journey.py index 4051c6f680..5fbe9a14ce 100644 --- a/tests/control_plane/test_quota_authority_settlement_journey.py +++ b/tests/control_plane/test_quota_authority_settlement_journey.py @@ -952,3 +952,106 @@ def spend_with_competing_write(preview, status, **kwargs): assert code == 0 and replay["appended"] is False, replay assert replay["settlement_identity"] == recovered["settlement_identity"] assert cli._spend_run_count(runtime) == 2 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_default_refresh_spend_conflict_recovers_across_profiles_and_remote_wait( + tmp_path, monkeypatch, capsys, provider, +): + from loopx.control_plane.quota.settlement import read_heartbeat_settlement + + project, runtime, registry = cli._write_fixture(tmp_path) + reg_data = json.loads(registry.read_text(encoding="utf-8")) + reg_data["goals"][0]["quota"]["allowed_slots"] = 10 + registry.write_text(json.dumps(reg_data, indent=2), encoding="utf-8") + cli._initialize_fixture_authority(project, runtime, provider=provider) + + code, guard = _guard(project, runtime, registry) + assert code == 0, guard + code, refreshed = cli._run_cli( + registry, runtime, "refresh-state", + "--goal-id", cli.GOAL_ID, "--agent-id", cli.AGENT_ID, + "--todo-id", cli.TODO_ID, "--turn-instance-id", cli.TURN_ID, + "--classification", "verified", "--delivery-batch-scale", "implementation", + "--delivery-outcome", "outcome_progress", "--no-global-sync", + "--suppress-external-sinks", cwd=project, + ) + assert code == 0, refreshed + assert refreshed["settlement_progress"]["state"] == "spend_required", refreshed + command = refreshed["settlement_owed"]["command"] + + commit = slot_accounting.record_quota_slot_spend_from_preview + + def spend_with_competing_write(preview, status, **kwargs): + comp_code, competing = cli._run_cli( + registry, runtime, "quota", "spend-slot", "--execute", "--source", "controller", + "--goal-id", cli.GOAL_ID, "--agent-id", cli.AGENT_ID, cwd=project, + ) + assert comp_code == 0 and competing["appended"] is True, competing + return commit(preview, status, **kwargs) + + with monkeypatch.context() as patch: + patch.chdir(project) + patch.setattr( + slot_accounting, "record_quota_slot_spend_from_preview", spend_with_competing_write, + ) + code = cli_main(shlex.split(command)[1:]) + rejected = json.loads(capsys.readouterr().out) + assert code == 1 and rejected["error_code"] == "index_digest_conflict", rejected + assert rejected["appended"] is False and cli._spend_run_count(runtime) == 1 + + readback = read_heartbeat_settlement( + runtime, + goal_id=cli.GOAL_ID, + agent_id=cli.AGENT_ID, + todo_id=cli.TODO_ID, + turn_instance_id=cli.TURN_ID, + registry_path=registry, + ) + assert readback is not None and readback.replay_phase.value == "settlement_pending" + + for extra in ( + ["--codex-app", "--todo-id", cli.TODO_ID], + ["--codex-app"], + ["--runtime-profile", "generic_cli"], + [], + ): + code, rerun = cli._run_cli( + registry, runtime, "quota", "should-run", + "--goal-id", cli.GOAL_ID, "--agent-id", cli.AGENT_ID, + "--turn-instance-id", cli.TURN_ID, *extra, cwd=project, + ) + assert code == 0, (extra, rerun) + assert rerun["decision"] == "unsettled_host_turn_recovery", (extra, rerun) + assert rerun["effective_action"] == "unsettled_host_turn_recovery", (extra, rerun) + assert rerun["unsettled_host_turn_recovery"]["repair"] == "quota_spend", (extra, rerun) + assert rerun["settlement_progress"]["state"] == "spend_required", (extra, rerun) + assert rerun["settlement_owed"]["command"] == command, (extra, rerun) + assert rerun["interaction_contract"]["cli_channel"]["next_cli_actions"] == [command] + + # Remote authority wait gating on readback.replay_phase == SETTLEMENT_PENDING must also recover. + remote_reg = json.loads(registry.read_text(encoding="utf-8")) + remote_reg["goals"][0]["remote_authority"] = {"enabled": True} + registry.write_text(json.dumps(remote_reg, indent=2), encoding="utf-8") + try: + for extra in (["--codex-app", "--todo-id", cli.TODO_ID], ["--codex-app"], []): + code, remote_rerun = cli._run_cli( + registry, runtime, "quota", "should-run", + "--goal-id", cli.GOAL_ID, "--agent-id", cli.AGENT_ID, + "--turn-instance-id", cli.TURN_ID, *extra, cwd=project, + ) + assert code == 0, (extra, remote_rerun) + assert remote_rerun["decision"] == "unsettled_host_turn_recovery", (extra, remote_rerun) + assert remote_rerun["effective_action"] == "unsettled_host_turn_recovery", (extra, remote_rerun) + assert remote_rerun["unsettled_host_turn_recovery"]["repair"] == "quota_spend", (extra, remote_rerun) + assert remote_rerun["settlement_owed"]["command"] == command, (extra, remote_rerun) + finally: + registry.write_text(json.dumps(reg_data, indent=2), encoding="utf-8") + + code, recovered = _execute(command, project, runtime, registry) + assert code == 0 and recovered["appended"] is True, recovered + assert recovered["settlement_progress"]["state"] == "settled", recovered + assert cli._spend_run_count(runtime) == 2 + + code, next_turn = _guard(project, runtime, registry, turn_id=f"{cli.TURN_ID}-next") + assert code == 0 and next_turn["effective_action"] != "unsettled_host_turn_recovery", next_turn diff --git a/tests/control_plane/test_refresh_settle_turn.py b/tests/control_plane/test_refresh_settle_turn.py index 9e97d77f85..8bac4b5104 100644 --- a/tests/control_plane/test_refresh_settle_turn.py +++ b/tests/control_plane/test_refresh_settle_turn.py @@ -1141,3 +1141,100 @@ def commit_after_competitor(preview, status, **kwargs): rc, replay = _run_cli(registry, runtime, *refresh, cwd=project) assert rc == 0 and replay["idempotent_replay"] and replay["settlement_result"]["receipts"] == receipts assert _spend_run_count(runtime) == 2 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("omit_boundary", [True, False], ids=["default_boundary", "in_flight_boundary"]) +def test_persistent_unthrottled_settle_turn_conflict_recovers_via_should_run( + tmp_path, monkeypatch, provider, omit_boundary, +): + from contextlib import redirect_stdout + from io import StringIO + from types import SimpleNamespace + import shlex + import subprocess + + from loopx.cli_commands import refresh_settlement + from loopx.entrypoint import main + + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + reg_data = json.loads(registry.read_text(encoding="utf-8")) + reg_data["goals"][0]["quota"]["allowed_slots"] = 10 + registry.write_text(json.dumps(reg_data, indent=2), encoding="utf-8") + _initialize_fixture_authority(project, runtime, provider=provider) + route = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, + "--turn-instance-id", TURN_ID] + rc, guard = _run_cli(registry, runtime, "quota", "should-run", "--codex-app", *binding, cwd=project) + assert rc == 0, guard + identity = guard["heartbeat_receipt"]["settlement_identity"] + attempts = [] + + def persistent_conflict_child(argv, **kwargs): + attempts.append(argv) + competing = [*argv[:5], *route, "quota", "spend-slot", "--execute", + "--source", "controller", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID] + interleave = f""" +import json +import subprocess +from loopx.control_plane.quota import slot_accounting +commit = slot_accounting.record_quota_slot_spend_from_preview +def commit_after_competitor(preview, status, **kwargs): + result = subprocess.run({competing!r}, capture_output=True, text=True, check=True) + assert json.loads(result.stdout)["appended"] is True, result.stdout + return commit(preview, status, **kwargs) +slot_accounting.record_quota_slot_spend_from_preview = commit_after_competitor +""" + entry = argv[3].replace("import runpy;", interleave + "\nimport runpy;", 1) + result = subprocess.run([*argv[:3], entry, *argv[4:]], **kwargs) + failure = json.loads(result.stdout) + assert result.returncode == 1 and failure["error_code"] == "index_digest_conflict", failure + assert failure["appended"] is False + return result + + refresh = ["refresh-state", *binding, "--classification", "verified", + "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress", + *([] if omit_boundary else ["--delivery-boundary", "in_flight_continuation"]), + "--no-global-sync", "--suppress-external-sinks", "--settle-turn", "--settlement-receipt"] + stdout = StringIO() + with monkeypatch.context() as patch, redirect_stdout(stdout): + patch.chdir(project) + patch.setattr(refresh_settlement, "subprocess", SimpleNamespace( + run=persistent_conflict_child, TimeoutExpired=subprocess.TimeoutExpired)) + rc = main([*route, *refresh]) + outcome = json.loads(stdout.getvalue()) + assert rc == 1 and len(attempts) == 2 and attempts[0] == attempts[1], outcome + assert outcome["settlement_progress"]["state"] == "spend_required", outcome + owed_command = outcome["settlement_owed"]["command"] + assert _spend_run_count(runtime) == 2 + + for extra in ( + ["--codex-app", "--todo-id", TODO_ID], + ["--codex-app"], + ["--runtime-profile", "generic_cli"], + [], + ): + rc, rerun = _run_cli( + registry, runtime, "quota", "should-run", + "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--turn-instance-id", TURN_ID, *extra, cwd=project, + ) + assert rc == 0, (extra, rerun) + assert rerun["decision"] == "unsettled_host_turn_recovery", (extra, rerun) + assert rerun["effective_action"] == "unsettled_host_turn_recovery", (extra, rerun) + assert rerun["unsettled_host_turn_recovery"]["repair"] == "quota_spend", (extra, rerun) + assert rerun["settlement_progress"]["state"] == "spend_required", (extra, rerun) + assert rerun["settlement_owed"]["command"] == owed_command, (extra, rerun) + assert rerun["interaction_contract"]["cli_channel"]["next_cli_actions"] == [owed_command] + + settled_out = StringIO() + with monkeypatch.context() as patch, redirect_stdout(settled_out): + patch.chdir(project) + rc_retry = main(shlex.split(owed_command)[1:]) + assert rc_retry == 0 + settled = json.loads(settled_out.getvalue()) + assert settled["appended"] is True, settled + assert settled["settlement_progress"]["state"] == "settled", settled + assert settled["settlement_identity"] == identity, settled + assert _spend_run_count(runtime) == 3 diff --git a/tests/control_plane_ts/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts index ced46eb8a6..a7634d6793 100644 --- a/tests/control_plane_ts/quota_settlement_readback.test.ts +++ b/tests/control_plane_ts/quota_settlement_readback.test.ts @@ -1944,7 +1944,10 @@ test(`${kind} no-spend closeout retains exact receipt identity and historical de const debited = await readQuotaSettlement(request(spent)); assert.equal((debited.spend as any).payload.ok, true); assert.equal((debited.progress as any).closeout_kind, undefined); - assert.equal((await readQuotaSettlement(request(malformed))).replay_phase, "open"); + const rejected = await readQuotaSettlement(request(malformed)); + assert.equal((rejected.progress as any).state, "spend_required"); + assert.equal((rejected.progress as any).closeout_kind, undefined); + assert.equal(rejected.replay_phase, "settlement_pending"); } finally { await Promise.all([missing, missingWriteback, spent, malformed].map(path => rm(path, { recursive: true, force: true }))); @@ -2702,3 +2705,73 @@ test("readback exposes matching supersede_event when records are included", asyn await rm(runtimeRoot, {recursive: true, force: true}); } }); + +test("default verified writeback without boundary or completion enters settlement_pending until spend settles", async t => { + const missingRequiredCheckpoint = { + schema_version: "vision_checkpoint_v0", + agent_id: agentId, + decision: "missing_required", + satisfied: false, + delivery_boundary: "semantic_closeout", + triggers: [{kind: "material_delivery_outcome", delivery_outcome: "outcome_progress"}], + }; + const cases: { + name: string; + options: Parameters[0]; + removeEvent?: string; + expectedProgress: string; + expectedReplayPhase: string; + }[] = [ + { + name: "default writeback without checkpoint stays settlement_pending", + options: {writeback: true, spend: false}, + expectedProgress: "spend_required", + expectedReplayPhase: "settlement_pending", + }, + { + name: "default writeback with missing_required semantic checkpoint stays settlement_pending", + options: {writeback: true, spend: false, visionCheckpoint: missingRequiredCheckpoint}, + expectedProgress: "spend_required", + expectedReplayPhase: "settlement_pending", + }, + { + name: "spend run without quota_spend receipt stays settlement_pending", + options: {writeback: true, spend: true, visionCheckpoint: missingRequiredCheckpoint}, + removeEvent: "quota_spend", + expectedProgress: "spend_receipt_required", + expectedReplayPhase: "settlement_pending", + }, + { + name: "completed spend without completion or accepted checkpoint stays open", + options: {writeback: true, spend: true, visionCheckpoint: missingRequiredCheckpoint}, + expectedProgress: "settled", + expectedReplayPhase: "open", + }, + { + name: "monitor poll precedence remains settled even when writeback exists without spend", + options: {monitor: true, writeback: true, spend: false}, + expectedProgress: "spend_required", + expectedReplayPhase: "settled", + }, + ]; + for (const entry of cases) { + await t.test(entry.name, async () => { + const runtimeRoot = await fixture(entry.options); + try { + if (entry.removeEvent) { + const log = join(runtimeRoot, "goals", goalId, "rollout-event-log.jsonl"); + const rows = (await readFile(log, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + await writeFile( + log, + rows.filter(row => row.event_kind !== entry.removeEvent).map(row => JSON.stringify(row)).join("\n") + "\n", + ); + } + const readback = await readQuotaSettlement(request(runtimeRoot)); + assert.equal((readback.progress as any)?.state, entry.expectedProgress); + assert.equal(readback.replay_phase, entry.expectedReplayPhase); + } finally { + await rm(runtimeRoot, {recursive: true, force: true}); + } + }); + } +});