diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index ebb039bb39..6b1e506e69 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -406,9 +406,19 @@ When a quota spend remains owed after verified writeback, obligation, Turn, registry/runtime route and spend source. Execute it unchanged. The typed blocked no-spend closeout has no spend command. In `spend_receipt_required`, the same idempotent spend -writer restores the receipt without another debit. Refresh and recovery never -spend automatically. JSON and normal/recovery Markdown expose the same step. -Rejected recovery reports observed progress without offering a spend command. +writer restores the receipt without another debit. Ordinary refresh and recovery +report the remaining step. An explicit `refresh-state --settle-turn` may execute +that command after verified writeback. A definitive `index_digest_conflict` with +`appended=false` allows one retry of the same command within the original timeout. +The retry rereads the original Turn and can replay a concurrent settlement. For +an ambiguous outcome, the adapter reads the receipts and returns any step still +owed. JSON and normal/recovery Markdown expose the same step. Rejected recovery +reports observed progress without offering a spend command. + +普通刷新与恢复返回原轮次剩余操作。显式指定 `refresh-state --settle-turn` 时,写回 +核验后可执行原结算命令。若确认 `index_digest_conflict` 且 `appended=false`,则在 +原超时窗口内用同一命令重试一次,重新读取原轮次,也可回读并发完成的结算。结果不明 +时读取回执并返回仍待执行的步骤。 The raw Python refresh API returns `writeback_receipt_required` until its CLI caller appends the refresh receipt and rereads the chain; it must not offer a spend command before that point. Older guards without a persisted spend source 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/cli_commands/refresh_settlement.py b/loopx/cli_commands/refresh_settlement.py index 5ab84ef984..7d3b4bdcdc 100644 --- a/loopx/cli_commands/refresh_settlement.py +++ b/loopx/cli_commands/refresh_settlement.py @@ -11,12 +11,14 @@ import sys from collections.abc import Mapping from pathlib import Path +from time import monotonic from typing import Any from ..command_invocation import loopx_cli_argv from ..control_plane.effect_program import ( SETTLEMENT_RECEIPT_SCHEMA_VERSION, SettlementStepKind, decode_settlement_receipt_payload, ) +from ..control_plane.quota.error_codes import QuotaRunIndexConflict from ..control_plane.quota.settlement import ( SettlementIdentity, attach_settlement_progress, read_heartbeat_settlement, render_owed_host_command, settlement_result_payload, @@ -98,6 +100,15 @@ def _has_verified_fresh_spend( ) +def _run_owed_spend(argv: list[str], workspace: Path | None, timeout: float) -> tuple[int, dict[str, Any]]: + result = subprocess.run(argv, cwd=workspace, capture_output=True, text=True, + encoding="utf-8", timeout=timeout, check=False) + value = json.loads(result.stdout) + if not isinstance(value, dict): + raise ValueError("quota settlement CLI returned a non-object result") + return result.returncode, value + + def settle_refreshed_turn( payload: dict[str, Any], *, registry_path: Path, runtime_root: Path, goal_id: str, agent_id: str, todo_id: str | None, @@ -107,8 +118,8 @@ def settle_refreshed_turn( ) -> None: """Follow one owed step, then verify its exact receipts; never collect a guard. - A failed/ambiguous child is not retried here. The original refresh or owed - command remains replayable under the shared exactly-once settlement owner. + A definitive run-index rejection allows one retry of the same owed command. + Ambiguous outcomes go through authoritative receipt readback. """ if payload.get("ok") is not True or payload.get("dry_run"): return @@ -171,17 +182,22 @@ def settle_refreshed_turn( "import sys; sys.path.insert(0, sys.argv.pop(1)); " "import runpy; runpy.run_module('loopx.entrypoint', run_name='__main__')" ) - result = subprocess.run( - [sys.executable, "-P", "-c", entry, str(Path(__file__).resolve().parents[2]), - "--format", "json", *command_args], - cwd=workspace, - capture_output=True, text=True, encoding="utf-8", timeout=60, check=False, - ) - value = json.loads(result.stdout) - if not isinstance(value, dict): - raise ValueError("quota settlement CLI returned a non-object result") - spent = value - if result.returncode or spent.get("ok") is not True: + argv = [sys.executable, "-P", "-c", entry, str(Path(__file__).resolve().parents[2]), + "--format", "json", *command_args] + timeout = 60 + deadline = monotonic() + timeout + returncode, spent = _run_owed_spend(argv, workspace, timeout) + conflict = QuotaRunIndexConflict.reason_code + if (returncode == 1 and spent.get("ok") is False and spent.get("appended") is False + and spent.get("error_code") == conflict and spent.get("status") == conflict + and spent.get("mode") == "spend-slot" and spent.get("goal_id") == goal_id + and (remaining := deadline - monotonic()) > 0): + # The CAS rejection proves the first invocation made no debit. + # A new invocation rereads the same Turn and can replay its receipt + # if another process has already settled it. + spent = {} + returncode, spent = _run_owed_spend(argv, workspace, remaining) + if returncode or spent.get("ok") is not True: error = str(spent.get("error") or spent.get("reason") or "quota settlement CLI failed") except (OSError, RuntimeError, ValueError, TypeError, KeyError, subprocess.TimeoutExpired, SystemExit) as exc: error = str(exc) 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/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/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..5fbe9a14ce 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,155 @@ 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 + + +@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 af1896b2db..8bac4b5104 100644 --- a/tests/control_plane/test_refresh_settle_turn.py +++ b/tests/control_plane/test_refresh_settle_turn.py @@ -1060,3 +1060,181 @@ def observe_child(command, **kwargs): assert replay["ok"] and replay["quota_spend"]["idempotent_replay"] and _spend_run_count(runtime) == 1 assert readbacks == ([TURN_ID] if response == "complete" else [TURN_ID, TURN_ID]) assert result["settlement_result"] == replay["settlement_result"] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("persistent_conflict", [False, True], ids=["once", "persistent"]) +def test_combined_settlement_recovers_only_one_rejected_index_write( + tmp_path, monkeypatch, provider, persistent_conflict, +): + from contextlib import redirect_stdout + from io import StringIO + from types import SimpleNamespace + + 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) + _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 concurrent_child(argv, **kwargs): + attempts.append(argv) + if persistent_conflict or len(attempts) == 1: + competing = [*argv[:5], *route, "quota", "spend-slot", "--execute", + "--source", "controller", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID] + # Inject another real CLI debit after the original preview. + # The rest of the child runs the unmodified package entry point. + 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) + argv = [*argv[:3], entry, *argv[4:]] + result = subprocess.run(argv, **kwargs) + if persistent_conflict or len(attempts) == 1: + failure = json.loads(result.stdout) + assert result.returncode == 1, failure + assert failure["error_code"] == "index_digest_conflict" and not failure["appended"] + return result + + refresh = ["refresh-state", *binding, "--classification", "verified", + "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress", + "--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=concurrent_child, TimeoutExpired=subprocess.TimeoutExpired)) + rc = main([*route, *refresh]) + outcome = json.loads(stdout.getvalue()) + assert len(attempts) == 2 and attempts[0] == attempts[1], outcome + assert outcome["settlement_identity"] == identity and outcome["appended"] + assert _heartbeat_receipt_count(runtime, TURN_ID) == 1 + assert _spend_run_count(runtime) == 2 # One original plus one competitor, or two competitors. + receipts = outcome["settlement_result"]["receipts"] + assert all(row["effect_id"] == identity["effect_id"] for row in receipts) + if persistent_conflict: + assert rc == 1 and outcome["settlement_progress"]["state"] == "spend_required", outcome + assert outcome["quota_spend"]["error_code"] == "index_digest_conflict" + assert [row["step_kind"] for row in receipts] == ["validation", "durable_writeback"] + owed = outcome["settlement_owed"] + assert owed["effect_id"] == identity["effect_id"] and owed["kind"] == "quota_spend" + else: + assert rc == 0 and outcome["settlement_progress"]["state"] == "settled", outcome + assert [row["step_kind"] for row in receipts] == ["validation", "durable_writeback", "quota_spend"] + 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}); + } + }); + } +});