Skip to content

Commit 4e4ef3f

Browse files
loopx-agenthuangruiteng
authored andcommitted
Capture C1 composition failures as receipt diagnostics
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 036a95f commit 4e4ef3f

6 files changed

Lines changed: 122 additions & 24 deletions

File tree

‎docs/reference/required-work-context.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,15 @@ cannot be combined with socket handoff. Ordinary callers keep their existing
503503
presentation, and context delivery off keeps its original pending Goal reads.
504504
Unbound staged replans retain their existing review-owned original Goal read.
505505

506+
If complete Turn composition fails after quota admission, the capture contains
507+
the failure and original receipts for `quota context-read`. `quota context-project`
508+
refuses the diagnostic capture. A saved diagnostic carries no executable input
509+
or native claim source. Reconcile the original Turn receipt before recovery.
510+
511+
中文:额度 guard 已准入、完整 Turn 组合随后失败时,capture 保留失败与原回执,
512+
可通过 `quota context-read` 读回。`quota context-project` 会拒绝该诊断
513+
capture,活跃会话的认领来源保持原样。恢复前先核对原 Turn 回执。
514+
506515
After a Host claim, the ready guard uses the private
507516
`--prepared-capture-reference` route. It publishes the complete decision and
508517
returns its writer digest with the fields needed to verify the same Todo and

‎loopx/cli_commands/quota_failure_report.py‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -499,19 +499,12 @@ def _bounded_quota_transport_failure(
499499
return result if _failure_output_size(result) <= limit else _compact_quota_failure()
500500

501501

502-
def quota_decision_transport_failure_payload(
502+
def quota_decision_transport_diagnostic(
503503
args: argparse.Namespace,
504504
committed: Mapping[str, object],
505505
error: Exception,
506-
*,
507-
capture_directory: Path | None,
508-
capture_sha256: str | None = None,
509506
) -> dict[str, object]:
510-
"""Report a post-guard failure with the original receipt and capture.
511-
512-
The saved digest, when available, comes from publication rather than
513-
reopening the path to establish a new identity.
514-
"""
507+
"""Keep receipt evidence from a failed delivery without projecting work."""
515508
typed_transport = isinstance(error, QuotaDecisionTransportError)
516509
reason = (
517510
" ".join(str(error).split())[:500] if typed_transport
@@ -539,6 +532,19 @@ def quota_decision_transport_failure_payload(
539532
if not typed_transport:
540533
failure["error_class"] = type(error).__name__
541534
failure.update(verbose_debug_fields(error, verbose=bool(getattr(args, "verbose", False))))
535+
return failure
536+
537+
538+
def quota_decision_transport_failure_payload(
539+
args: argparse.Namespace,
540+
committed: Mapping[str, object],
541+
error: Exception,
542+
*,
543+
capture_directory: Path | None,
544+
capture_sha256: str | None = None,
545+
) -> dict[str, object]:
546+
"""Report the failure with the digest returned by the capture writer."""
547+
failure = quota_decision_transport_diagnostic(args, committed, error)
542548
limit = getattr(args, "max_page_output_bytes", None) if args.format == "json" else None
543549
reader = getattr(args, "_quota_failure_reader", None)
544550
if limit is not None:

‎loopx/cli_commands/quota_native_context.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
111111
_validate_context_page_window(args.offset, args.page_bytes, output_limit)
112112
path, _, payload = _read_capture(args.capture_file, args.capture_sha256,
113113
private=hook_session is not None)
114+
if payload.get("ok") is False:
115+
raise ValueError("The saved capture is diagnostic. Read it with quota context-read.")
114116
identity = payload.get("agent_identity")
115117
receipt = payload.get("heartbeat_receipt")
116118
if (payload.get("ok") is not True or not isinstance(identity, dict) or not isinstance(receipt, dict)

‎loopx/cli_commands/quota_presentation.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
def compose_quota_work_contract(payload: dict[str, object], args: argparse.Namespace, *,
1313
scheduler_context: Mapping[str, object] | SchedulerExecutionContextResolution | None,
1414
capture_directory: Path | None,
15-
native_context: bool,
1615
record_capture: Callable[[dict[str, object], str], None] | None = None) -> dict[str, object]:
1716
"""Compose every decided should-run source once before capture and display."""
1817
if args.quota_command != "should-run" or not isinstance(payload.get("interaction_contract"), Mapping):
@@ -26,15 +25,16 @@ def compose_quota_work_contract(payload: dict[str, object], args: argparse.Names
2625
composed_settlement=True)
2726
except (EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc:
2827
from .quota_capture import capture_decision
28+
from .quota_failure_report import quota_decision_transport_diagnostic
2929

30-
# Admission already happened. Keep its source/receipt; never emit a
31-
# false v1, discard the receipt or rerun the guard to recover context.
30+
error = QuotaDecisionTransportError("Complete Turn context could not be composed.")
31+
# Admission may be durable. Retain its receipts through the existing
32+
# failure projection so saved-context readers cannot deliver the
33+
# unsigned input or register it as a current native claim source.
3234
capture_decision(
33-
capture_directory, payload, args=args, native_context=native_context, record_capture=record_capture,
35+
capture_directory, quota_decision_transport_diagnostic(args, payload, error), record_capture=record_capture,
3436
)
35-
raise QuotaDecisionTransportError(
36-
"Complete Turn context could not be composed. Read the saved original decision and receipt; do not rerun admission."
37-
) from exc
37+
raise error from exc
3838

3939

4040
def project_scheduler_observation(payload: Mapping[str, object]) -> dict[str, object]:

‎loopx/cli_commands/quota_result_delivery.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,6 @@ def _publish_quota_result(
323323
args,
324324
scheduler_context=scheduler_context,
325325
capture_directory=capture_directory,
326-
native_context=native_context,
327326
record_capture=record_capture,
328327
)
329328
captured_digest = capture_decision(

‎tests/control_plane/test_quota_decision_capture.py‎

Lines changed: 89 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,87 @@ def test_refused_selection_handoff_is_typed_and_keeps_the_committed_capture(tmp_
854854
assert _heartbeat_receipt_count(runtime, TURN_ID) >= 1
855855

856856

857+
@pytest.mark.parametrize('provider', ['file', 'sqlite'])
858+
@pytest.mark.parametrize('delivery', ['off', 'on'])
859+
def test_failed_complete_composition_captures_only_recovery_evidence(
860+
tmp_path, monkeypatch, capsys, provider, delivery,
861+
):
862+
from loopx.cli import main
863+
from loopx.control_plane.effect_runtime import EffectRuntimeStartupError
864+
from loopx.control_plane.quota import turn_envelope
865+
from loopx.control_plane.turn_driver import codex_context
866+
from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime
867+
from tests.control_plane.test_quota_settlement_cli import _spend_run_count
868+
869+
isolate_sqlite_runtime(tmp_path, monkeypatch)
870+
project, runtime, registry = _write_fixture(tmp_path)
871+
project = project.resolve()
872+
monkeypatch.chdir(project)
873+
state = _configure_read_only_todo(project)
874+
mode = 'hard_lease' if delivery == 'on' else 'soft_claim'
875+
initialize_canonical_source_fixture(runtime, GOAL_ID, state_path=state, provider=provider, handoff_mode=mode)
876+
original_state = state.read_bytes()
877+
capture, native = tmp_path / 'failure', tmp_path / 'native'
878+
delivery_args = ['--codex-app', '--context-delivery', delivery]
879+
if delivery == 'on':
880+
native.mkdir(mode=0o700)
881+
session = 'composition-failure-session'
882+
monkeypatch.setenv('CODEX_THREAD_ID', session)
883+
assert codex_context.codex_context_hook(str(native), {
884+
'session_id': session, 'cwd': str(project), 'hook_event_name': 'SessionStart', 'source': 'startup',
885+
}) == {}
886+
delivery_args += ['--codex-context-dir', str(native)]
887+
native_before = {path.name: path.read_bytes() for path in native.glob('*') if path.is_file()}
888+
binding = ['--goal-id', GOAL_ID, '--agent-id', AGENT_ID, '--turn-instance-id', TURN_ID]
889+
captured = []
890+
run_typed = turn_envelope._turn_envelope_result
891+
892+
def interrupt_compose(action, **kwargs):
893+
if action == 'compose_complete':
894+
captured.append(kwargs['payload'])
895+
raise EffectRuntimeStartupError('fixture composition unavailable', diagnostic_code='fixture_unavailable')
896+
return run_typed(action, **kwargs)
897+
898+
with monkeypatch.context() as fault:
899+
fault.setattr(turn_envelope, '_turn_envelope_result', interrupt_compose)
900+
code = main(['--registry', str(registry), '--runtime-root', str(runtime), '--format', 'json',
901+
'quota', 'should-run', *binding, '--todo-id', TODO_ID, *delivery_args, '--decision-output-dir', str(capture)])
902+
failure = json.loads(capsys.readouterr().out)
903+
assert code == 1 and failure['ok'] is False
904+
assert failure['error_code'] == 'quota_decision_transport_failed'
905+
assert len(captured) == 1 and captured[0]['ok'] is True
906+
original_receipt = captured[0]['heartbeat_receipt']
907+
assert failure['heartbeat_receipt'] == original_receipt
908+
assert original_receipt['settlement_identity']['todo_id'] == TODO_ID
909+
if delivery == 'on':
910+
assert captured[0]['execution_preparation']['state'] == 'claim_required'
911+
before_readback = _heartbeat_receipt_count(runtime, TURN_ID)
912+
assert before_readback == 1
913+
914+
saved = capture / 'decision.json'
915+
reference = failure['captured_decision']
916+
assert saved.read_bytes() and reference['sha256'] == sha256(saved.read_bytes()).hexdigest()
917+
code, projection = _run_cli(registry, runtime, 'quota', 'context-project', *binding, *delivery_args,
918+
'--capture-file', reference['path'], '--capture-sha256', reference['sha256'], cwd=project)
919+
assert code == 1 and projection['ok'] is False
920+
assert 'diagnostic' in projection['reason']
921+
diagnostic = json.loads(saved.read_bytes())
922+
assert diagnostic['ok'] is False and diagnostic['should_run'] is False
923+
assert 'interaction_contract' not in diagnostic and 'execution_preparation' not in diagnostic
924+
assert diagnostic['heartbeat_receipt'] == original_receipt
925+
reader = shlex.split(reference['command'])
926+
code, page = _run_cli(registry, runtime, *reader[reader.index('quota'):],
927+
'--select', '/heartbeat_receipt', cwd=project)
928+
assert code == 0 and page['ok'] and page['eof']
929+
assert json.loads(page['content'])['selections'] == [
930+
{'pointer': '/heartbeat_receipt', 'value': original_receipt},
931+
]
932+
assert {path.name: path.read_bytes() for path in native.glob('*') if path.is_file()} == native_before
933+
assert _heartbeat_receipt_count(runtime, TURN_ID) == before_readback
934+
assert _spend_run_count(runtime) == 0
935+
assert state.read_bytes() == original_state
936+
937+
857938
@pytest.mark.parametrize('provider', ['file', 'sqlite'])
858939
@pytest.mark.parametrize('turn_envelope', [False, True])
859940
def test_native_recovery_failure_keeps_original_receipt_and_capture(
@@ -877,10 +958,7 @@ def test_native_recovery_failure_keeps_original_receipt_and_capture(
877958

878959
def refuse_recovery(payload, **kwargs):
879960
saved = kwargs['capture_directory'] / 'decision.json'
880-
attempts.append(saved.read_bytes())
881-
if turn_envelope:
882-
assert payload['schema_version'] == 'loopx_turn_envelope_v0'
883-
assert 'heartbeat_receipt' not in payload
961+
attempts.append((payload, saved.read_bytes()))
884962
raise QuotaDecisionTransportError(
885963
'Current context recovery could not be published or safely invalidated. '
886964
'Read the saved original decision/receipt; do not rerun admission.'
@@ -900,15 +978,19 @@ def refuse_recovery(payload, **kwargs):
900978
assert code == 1 and failure['ok'] is False
901979
assert failure['error_code'] == 'quota_decision_transport_failed'
902980
assert failure['status'] == 'decision_transport_failed'
981+
assert failure['reason'].startswith('Current context recovery could not be published')
903982
saved = list(captures.glob('*/decision.json'))
904983
assert len(saved) == len(attempts) == 1
905-
assert saved[0].read_bytes() == attempts[0]
906-
original = json.loads(attempts[0])
984+
projected, raw = attempts[0]
985+
assert saved[0].read_bytes() == raw
986+
original = json.loads(raw)
907987
assert original['ok'] is True
988+
assert projected['schema_version'] == original['schema_version'] == 'loopx_turn_envelope_v1'
989+
assert projected['heartbeat_receipt'] == original['heartbeat_receipt']
908990
assert failure['heartbeat_receipt'] == original['heartbeat_receipt']
909991
assert failure['rollout_event'] == original['rollout_event']
910992
assert failure['captured_decision']['path'] == str(saved[0])
911-
assert failure['captured_decision']['sha256'] == sha256(attempts[0]).hexdigest()
993+
assert failure['captured_decision']['sha256'] == sha256(raw).hexdigest()
912994
assert _heartbeat_receipt_count(runtime, TURN_ID) == 1
913995
assert _spend_run_count(runtime) == 0
914996
assert state.read_bytes() == original_state

0 commit comments

Comments
 (0)