Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions docs/quota-allocation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions loopx/cli_commands/quota_failure_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
QuotaCommandValidationError,
QuotaDecisionTransportError,
QuotaIdentityPreconditionError,
QuotaRunIndexConflict,
quota_error_code,
)
from ..file_lock import lock_timeout_error_fields
Expand Down Expand Up @@ -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",
Expand Down
42 changes: 29 additions & 13 deletions loopx/cli_commands/refresh_settlement.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions loopx/control_plane/quota/error_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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):
Expand Down
7 changes: 6 additions & 1 deletion loopx/control_plane/quota/settlement_readback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
9 changes: 2 additions & 7 deletions loopx/control_plane/quota/spend_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,16 @@
)
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


QUOTA_SPEND_COMMIT_REQUEST_SCHEMA = "loopx_quota_spend_commit_request_v0"
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()
Expand Down
158 changes: 156 additions & 2 deletions tests/control_plane/test_quota_authority_settlement_journey.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Loading
Loading