diff --git a/loopx/capabilities/native_chat/report_failure_ledger.py b/loopx/capabilities/native_chat/report_failure_ledger.py new file mode 100644 index 0000000000..5ff039c05b --- /dev/null +++ b/loopx/capabilities/native_chat/report_failure_ledger.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +from collections.abc import Mapping +import hashlib +import json +from pathlib import Path +from typing import cast + +from ..periodic_report.cadence_journal import cadence_journal_path +from ..periodic_report.field_shapes import REPORT_IDENTITY_PATTERN +from ..periodic_report.private_generation import attempt_directory +from .report_failure_probe import ( + ProofMapping, + ProofObject, + _is_antigravity_turn_id, + _mapping, + _object_dict, +) + +REPORT_FAILURE_PROOF = "native-terminal-failure.json" +CONTRADICTED_REPORT_FAILURES = "contradicted-report-failures.json" +CONTRADICTED_FAILURES_SCHEMA = "periodic_report_contradicted_failures_v0" + + +def report_failure_binding( + original: ProofMapping, + window: ProofMapping, +) -> dict[str, str] | None: + """Bind a terminal report host failure to one cadence window and native result.""" + request = _mapping(original.get("loopx_request")) + actor = _mapping(request.get("actor")) + result = _mapping(_mapping(original.get("response")).get("native_loopx")) + failure = _mapping(result.get("host_failure")) + if ( + original.get("origin") != "native_loopx" + or original.get("loopx_execution") is not True + or original.get("status") != "completed" + or original.get("session_id") != actor.get("session_id") + or request.get("work_kind") != "report" + or request.get("report_window_id") != window.get("window_id") + or request.get("report_subscription_revision") != window.get("subscription_revision") + or actor.get("goal_id") != window.get("goal_id") + or actor.get("agent_id") != window.get("agent_id") + or result.get("status") != "failed" + or result.get("result_kind") != "host_failure" + or failure.get("retryable") is not False + ): + return None + identity: dict[str, str] = {} + for key, value in ( + ("session_id", original.get("session_id")), + ("chat_turn_id", original.get("turn_id")), + ("provider_turn_id", original.get("upstream_turn_id")), + ("turn_instance_id", request.get("turn_instance_id")), + ("window_id", window.get("window_id")), + ("subscription_revision", window.get("subscription_revision")), + ): + if not isinstance(value, str) or not value: + return None + identity[key] = value + encoded = json.dumps( + result, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + identity["native_result_sha256"] = hashlib.sha256(encoded).hexdigest() + return identity + + +def _read_report_failure_record( + runtime_root: Path, + window: ProofMapping, +) -> ProofObject | None: + path = attempt_directory(runtime_root, _object_dict(window)) / REPORT_FAILURE_PROOF + try: + if path.parent.is_symlink() or path.is_symlink() or not path.is_file(): + return None + proof = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return cast(ProofObject, proof) if isinstance(proof, dict) else None + + +def _is_valid_retained_proof( + proof: ProofMapping | None, + binding: Mapping[str, str], +) -> bool: + if _is_antigravity_turn_id(binding.get("provider_turn_id")): + return ( + isinstance(proof, dict) + and set(proof) + == { + "binding", + "provider_thread_id", + "adapter_kind", + "cascade_idle", + "no_final_response", + } + and proof["binding"] == binding + and proof["adapter_kind"] == "antigravity_ls" + and proof["cascade_idle"] is True + and proof["no_final_response"] is True + and isinstance(proof["provider_thread_id"], str) + and bool(proof["provider_thread_id"]) + ) + return ( + isinstance(proof, dict) + and set(proof) == {"binding", "provider_thread_id", "only_original_user_item"} + and proof["binding"] == binding + and proof["only_original_user_item"] is True + and isinstance(proof["provider_thread_id"], str) + and bool(proof["provider_thread_id"]) + ) + + +def _is_contradicted_proof( + proof: object, + binding: Mapping[str, str], +) -> bool: + if not isinstance(proof, dict): + return False + thread_id = proof.get("provider_thread_id") + return ( + set(proof) + == {"binding", "provider_thread_id", "only_original_user_item", "contradicted"} + and proof["binding"] == binding + and proof["only_original_user_item"] is False + and proof["contradicted"] is True + and (thread_id is None or (isinstance(thread_id, str) and bool(thread_id))) + ) + + +def _is_exact_contradiction( + proof: object, + binding: Mapping[str, str], + thread_id: str | None, +) -> bool: + return ( + isinstance(proof, Mapping) + and _is_contradicted_proof(proof, binding) + and proof.get("provider_thread_id") == thread_id + ) + + +def _contradiction_ledger_path(runtime_root: Path, window: ProofMapping) -> Path | None: + goal_id = window.get("goal_id") + if not isinstance(goal_id, str) or not REPORT_IDENTITY_PATTERN.fullmatch(goal_id): + return None + return ( + cadence_journal_path(runtime_root, goal_id).parent + / CONTRADICTED_REPORT_FAILURES + ) + + +def _binding_key(binding: Mapping[str, str]) -> str: + encoded = json.dumps( + dict(binding), ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + return hashlib.sha256(encoded).hexdigest() + + +def _read_contradiction_ledger(ledger_path: Path) -> tuple[str, ProofObject]: + try: + if ( + ledger_path.parent.parent.is_symlink() + or ledger_path.parent.is_symlink() + or ledger_path.is_symlink() + ): + return "untrusted", {} + if not ledger_path.exists(): + return "absent", {} + if not ledger_path.is_file(): + return "untrusted", {} + data = json.loads(ledger_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return "untrusted", {} + if ( + not isinstance(data, dict) + or set(data) != {"schema_version", "entries"} + or data.get("schema_version") != CONTRADICTED_FAILURES_SCHEMA + or not isinstance(data.get("entries"), dict) + ): + return "untrusted", {} + return "ok", cast(ProofObject, data["entries"]) + + +def _durable_contradiction_status( + runtime_root: Path, + binding: Mapping[str, str], + window: ProofMapping, +) -> str: + ledger_path = _contradiction_ledger_path(runtime_root, window) + if ledger_path is None: + return "untrusted" + status, entries = _read_contradiction_ledger(ledger_path) + if status != "ok": + return status + entry = entries.get(_binding_key(binding)) + if entry is None: + return "absent" + return "contradicted" if _is_contradicted_proof(entry, binding) else "untrusted" + + +def _binding_attempt_state( + runtime_root: Path, + binding: Mapping[str, str], + window: ProofMapping, +) -> tuple[bool, ProofObject | None]: + """Read attempt record before durable contradiction ledger so concurrent commits cannot lose.""" + record = _read_report_failure_record(runtime_root, window) + if _is_contradicted_proof(record, binding): + return True, record + if _durable_contradiction_status(runtime_root, binding, window) != "absent": + return True, None + return False, record + + +def read_retained_report_failure( + runtime_root: Path, + original: ProofMapping, + window: ProofMapping, +) -> bool: + """Scope retained provider evidence to the same failure and cadence window.""" + binding = report_failure_binding(original, window) + if binding is None: + return False + contradicted, record = _binding_attempt_state(runtime_root, binding, window) + return (not contradicted) and _is_valid_retained_proof(record, binding) + + +def is_report_failure_contradicted( + runtime_root: Path, + original: ProofMapping, + window: ProofMapping, +) -> bool: + """Return True when live provider history has already contradicted this Turn's proof.""" + binding = report_failure_binding(original, window) + if binding is None: + return False + contradicted, _ = _binding_attempt_state(runtime_root, binding, window) + return contradicted diff --git a/loopx/capabilities/native_chat/report_failure_probe.py b/loopx/capabilities/native_chat/report_failure_probe.py new file mode 100644 index 0000000000..eedb874a65 --- /dev/null +++ b/loopx/capabilities/native_chat/report_failure_probe.py @@ -0,0 +1,369 @@ +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from pathlib import Path +import subprocess +import time +from typing import Protocol, cast + +from ...chat_agent import CodexChatAgentError + +ProofObject = dict[str, object] +ProofMapping = Mapping[str, object] + + +class TurnLoader(Protocol): + def load_turn(self, session_id: str, turn_id: str, /) -> ProofMapping | None: ... + + +class ReportProofStore(TurnLoader, Protocol): + def load_session(self, session_id: str, /) -> ProofMapping | None: ... + + def events_after( + self, session_id: str, turn_id: str, event_id: str | None, / + ) -> Sequence[ProofMapping]: ... + + +class ReportProofController(Protocol): + @property + def coordination_runtime_root(self) -> Path: ... + + @property + def codex_bin(self) -> str: ... + + @property + def codex_home(self) -> Path: ... + + +def _mapping(value: object) -> ProofMapping: + return cast(ProofMapping, value) if isinstance(value, Mapping) else {} + + +def _object_dict(value: ProofMapping) -> ProofObject: + return cast(ProofObject, value) if isinstance(value, dict) else dict(value) + + +def _is_antigravity_turn_id(value: object) -> bool: + return isinstance(value, str) and value.startswith("agy_turn_") + + +def _is_completed_host_failure_report(original: ProofMapping) -> object | None: + result = _mapping(_mapping(original.get("response")).get("native_loopx")) + request = _mapping(original.get("loopx_request")) + upstream_turn_id = original.get("upstream_turn_id") + if ( + original.get("status") != "completed" + or request.get("work_kind") != "report" + or result.get("result_kind") != "host_failure" + or not upstream_turn_id + ): + return None + return upstream_turn_id + + +def valid_report_failure_proof( + original: ProofMapping, + threads: Sequence[str], + proof: ProofMapping | None, +) -> bool: + """Return True when a live provider observation proves a terminal host failure with no generated answer.""" + upstream_turn_id = original.get("upstream_turn_id") + if ( + not isinstance(proof, Mapping) + or proof.get("contradicted") is True + or proof.get("turn_id") != upstream_turn_id + or proof.get("thread_id") not in threads + ): + return False + if _is_antigravity_turn_id(upstream_turn_id): + return ( + proof.get("adapter_kind") == "antigravity_ls" + and proof.get("cascade_idle") is True + and proof.get("no_final_response") is True + ) + return proof.get("only_original_user_item") is True and bool( + proof.get("codex_error_info") + ) + + +def proof_targets_original_turn( + original: ProofMapping, + threads: Sequence[str], + proof: ProofMapping | None, +) -> bool: + """Ensure an observation refers to this exact original thread/turn.""" + if not isinstance(proof, Mapping): + return False + thread_id = proof.get("thread_id") + turn_id = proof.get("turn_id") + return ( + isinstance(thread_id, str) + and thread_id in threads + and turn_id == original.get("upstream_turn_id") + ) + + +def probe_report_failure( + controller: ReportProofController, + store: ReportProofStore, + original: ProofMapping, + *, + include_contradiction: bool = False, + contradiction_detail: bool = False, + swallow_probe_errors: bool | None = None, +) -> tuple[list[str], ProofObject | None] | None: + """Query the original Session's native threads without starting or resuming work.""" + upstream_turn_id = _is_completed_host_failure_report(original) + if not upstream_turn_id or _is_antigravity_turn_id(upstream_turn_id): + return None + from .codex_adapter import CodexAppServerAdapter + from .codex_context import checked_session_home + + session = store.load_session(cast(str, original["session_id"])) + if not session or not session.get("codex_home") or not session.get("upstream_thread_id"): + return None + history = session.get("upstream_context_history") or [] + if not isinstance(history, list) or any( + not isinstance(item, dict) + or not isinstance(item.get("thread_id"), str) + or not item["thread_id"] + for item in history + ): + return None + # Context replacement retains native provenance on this same Session. + # Read the original refusal there; exclude non-Codex cascades. + raw_threads: list[str] = [ + *( + [cast(str, session["upstream_thread_id"])] + if session.get("agent_id") != "antigravity" + else [] + ), + *( + cast(str, item["thread_id"]) + for item in reversed(history) + if item.get("agent_id") != "antigravity" + ), + ] + threads = list(dict.fromkeys(raw_threads)) + if not threads: + return None + swallow = include_contradiction if swallow_probe_errors is None else swallow_probe_errors + try: + proof = CodexAppServerAdapter.failed_request_observation( + codex_bin=controller.codex_bin, + codex_home=Path(cast(str | Path, session["codex_home"])), + thread_ids=threads, + model_auth_home=checked_session_home(controller.codex_home, session), + turn_id=cast(str, upstream_turn_id), + include_contradiction=include_contradiction, + contradiction_detail=contradiction_detail, + ) + except (CodexChatAgentError, OSError, ValueError, RuntimeError, subprocess.SubprocessError): + if not swallow: + raise + proof = None + return threads, cast(ProofObject | None, proof) + + +def _extract_antigravity_turn_cascade( + store: ReportProofStore, + original: ProofMapping, +) -> tuple[ProofObject, str, list[ProofObject]] | None: + """Resolve one Antigravity cascade and stored events when no final answer exists.""" + upstream_turn_id = original.get("upstream_turn_id") + session = store.load_session(cast(str, original["session_id"])) + if ( + not session + or original.get("delta_count") != 0 + or not _is_antigravity_turn_id(upstream_turn_id) + ): + return None + try: + events = store.events_after( + cast(str, original["session_id"]), cast(str, original["turn_id"]), None + ) + except (OSError, ValueError): + return None + started_id: object = None + started_count = 0 + for row in events: + if row.get("kind") in {"answer.final", "turn.native_result"}: + return None + payload = row.get("payload") + if ( + row.get("kind") == "turn.started" + and isinstance(payload, Mapping) + and payload.get("upstream_turn_id") == upstream_turn_id + ): + started_count += 1 + started_id = payload.get("threadId") + if started_count != 1 or not isinstance(started_id, str) or not started_id: + return None + return _object_dict(session), started_id, [_object_dict(row) for row in events] + + +def _antigravity_trajectory_steps( + url: str, + csrf_token: str, + cascade_id: str, + traj: ProofMapping, +) -> list[ProofObject] | None: + """Load complete trajectory steps from an idle Antigravity cascade.""" + from .antigravity_adapter import _read_trajectory_steps, _rpc_post + + trajectory = _mapping(traj.get("trajectory")) + if trajectory.get("cascadeId") != cascade_id: + return None + total = traj.get("numTotalSteps") + inline_steps = trajectory.get("steps") + if type(total) is int and total > 0: + if ( + isinstance(inline_steps, list) + and len(inline_steps) == total + and all(isinstance(step, dict) for step in inline_steps) + ): + return [cast(ProofObject, step) for step in inline_steps] + try: + loaded = _read_trajectory_steps( + lambda offset, end: _rpc_post( + url, + csrf_token, + "GetCascadeTrajectorySteps", + { + "cascadeId": cascade_id, + "stepOffset": offset, + "startIndex": offset, + "endIndex": end, + }, + timeout=5.0, + ).get("steps"), + start=0, + total=total, + ) + if loaded is None: + return None + after = _rpc_post( + url, csrf_token, "GetCascadeTrajectory", {"cascadeId": cascade_id}, timeout=2.5 + ) + except (CodexChatAgentError, OSError, ValueError): + return None + if ( + after.get("status") != "CASCADE_RUN_STATUS_IDLE" + or after.get("numTotalSteps") != total + or _mapping(after.get("trajectory")).get("cascadeId") != cascade_id + ): + return None + return [cast(ProofObject, step) for _, step in loaded[0]] + if total == 0 or (total is None and isinstance(inline_steps, list) and len(inline_steps) == 0): + return [] + return None + + +def _antigravity_has_running_step(steps: Sequence[ProofMapping]) -> bool: + return any(step.get("status") == "CORTEX_STEP_STATUS_RUNNING" for step in steps) + + +def _antigravity_has_final_response(steps: Sequence[ProofMapping]) -> bool: + for step in steps: + if step.get("type") != "CORTEX_STEP_TYPE_PLANNER_RESPONSE": + continue + planner = step.get("plannerResponse") + if not isinstance(planner, Mapping) or planner.get("toolCalls"): + continue + answer = planner.get("modifiedResponse") or planner.get("response") + if isinstance(answer, str) and answer.strip(): + return True + return False + + +def _probe_antigravity_report_failure( + store: ReportProofStore, + original: ProofMapping, +) -> tuple[list[str], ProofObject | None] | None: + """Query the Antigravity LS trajectory without starting or resuming work.""" + upstream_turn_id = _is_completed_host_failure_report(original) + if not _is_antigravity_turn_id(upstream_turn_id): + return None + extracted = _extract_antigravity_turn_cascade(store, original) + if extracted is None: + return None + _, cascade_id, _ = extracted + from .antigravity_adapter import _rpc_post, discover_antigravity_language_server + + found = discover_antigravity_language_server( + include_model_config=False, + deadline=time.monotonic() + 3.0, + ) + if found is None: + return [cascade_id], None + url = str(found["url"]) + csrf_token = str(found["csrf_token"]) + try: + traj = _rpc_post( + url, csrf_token, "GetCascadeTrajectory", {"cascadeId": cascade_id}, timeout=2.5 + ) + except (CodexChatAgentError, OSError, ValueError): + return [cascade_id], None + if _mapping(traj.get("trajectory")).get("cascadeId") != cascade_id: + return [cascade_id], None + base_proof: ProofObject = { + "adapter_kind": "antigravity_ls", + "turn_id": upstream_turn_id, + "thread_id": cascade_id, + } + if traj.get("status") != "CASCADE_RUN_STATUS_IDLE": + return [cascade_id], { + **base_proof, + "in_progress": True, + "target_in_progress": True, + "contradicted": True, + } + steps = _antigravity_trajectory_steps(url, csrf_token, cascade_id, traj) + if steps is None: + return [cascade_id], None + if _antigravity_has_running_step(steps): + return [cascade_id], { + **base_proof, + "in_progress": True, + "target_in_progress": True, + "contradicted": True, + } + if _antigravity_has_final_response(steps): + return [cascade_id], { + **base_proof, + "cascade_idle": True, + "no_final_response": False, + "contradicted": True, + "explicit_contradiction": True, + } + return [cascade_id], {**base_proof, "cascade_idle": True, "no_final_response": True} + + +def observe_antigravity_report_failure( + store: ReportProofStore, + original: ProofMapping, +) -> ProofObject | None: + """Read an Antigravity report timeout/failure observation without starting work.""" + extracted = _extract_antigravity_turn_cascade(store, original) + if extracted is None: + return None + session, cascade_id, events = extracted + upstream_turn_id = str(original["upstream_turn_id"]) + native_timeout = any( + row.get("kind") == "agent.phase" + and isinstance(row.get("payload"), Mapping) + and cast(ProofMapping, row["payload"]).get("method") == "native/timeout" + for row in events + ) + from .antigravity_adapter import AntigravityAdapter + + return cast( + ProofObject | None, + AntigravityAdapter.failed_report_observation( + cascade_id=cascade_id, + turn_id=upstream_turn_id, + native_timeout=native_timeout, + model_id=cast(str | None, session.get("agent_model_id")), + reasoning_effort=cast(str | None, session.get("agent_reasoning_effort")), + ), + ) diff --git a/loopx/capabilities/native_chat/report_failure_proof.py b/loopx/capabilities/native_chat/report_failure_proof.py index b43e123ade..3e1e31d70d 100644 --- a/loopx/capabilities/native_chat/report_failure_proof.py +++ b/loopx/capabilities/native_chat/report_failure_proof.py @@ -2,196 +2,100 @@ from __future__ import annotations from collections.abc import Callable, Mapping, Sequence -from contextlib import nullcontext -import hashlib -import json +from contextlib import AbstractContextManager, nullcontext import logging from pathlib import Path -import subprocess -import time -from typing import Any +from typing import cast from ...file_lock import try_exclusive_file_lock from ...registry import atomic_write_json -from ..periodic_report.cadence_journal import cadence_journal_path -from ..periodic_report.field_shapes import REPORT_IDENTITY_PATTERN from ..periodic_report.private_generation import attempt_directory +from .report_failure_ledger import ( + CONTRADICTED_FAILURES_SCHEMA as CONTRADICTED_FAILURES_SCHEMA, + CONTRADICTED_REPORT_FAILURES as CONTRADICTED_REPORT_FAILURES, + REPORT_FAILURE_PROOF as REPORT_FAILURE_PROOF, + _binding_attempt_state, + _binding_key as _binding_key, + _contradiction_ledger_path as _contradiction_ledger_path, + _durable_contradiction_status as _durable_contradiction_status, + _is_contradicted_proof as _is_contradicted_proof, + _is_exact_contradiction, + _is_valid_retained_proof as _is_valid_retained_proof, + _read_contradiction_ledger as _read_contradiction_ledger, + _read_report_failure_record as _read_report_failure_record, + is_report_failure_contradicted as is_report_failure_contradicted, + read_retained_report_failure as read_retained_report_failure, + report_failure_binding as report_failure_binding, +) +from .report_failure_probe import ( + ProofMapping as ProofMapping, + ProofObject as ProofObject, + ReportProofController as ReportProofController, + ReportProofStore as ReportProofStore, + TurnLoader as TurnLoader, + _antigravity_has_final_response as _antigravity_has_final_response, + _antigravity_has_running_step as _antigravity_has_running_step, + _antigravity_trajectory_steps as _antigravity_trajectory_steps, + _extract_antigravity_turn_cascade as _extract_antigravity_turn_cascade, + _is_antigravity_turn_id as _is_antigravity_turn_id, + _is_completed_host_failure_report, + _mapping, + _object_dict, + _probe_antigravity_report_failure as _probe_antigravity_report_failure, + observe_antigravity_report_failure as observe_antigravity_report_failure, + probe_report_failure as probe_report_failure, + proof_targets_original_turn as proof_targets_original_turn, + valid_report_failure_proof as valid_report_failure_proof, +) -REPORT_FAILURE_PROOF = "native-terminal-failure.json" -CONTRADICTED_REPORT_FAILURES = "contradicted-report-failures.json" -CONTRADICTED_FAILURES_SCHEMA = "periodic_report_contradicted_failures_v0" _LOG = logging.getLogger(__name__) -def report_failure_binding(original: Mapping[str, Any], window: dict[str, Any]) -> dict[str, str] | None: - """Bind a terminal report host failure to one cadence window and native result.""" - request = original.get("loopx_request") or {} - actor = request.get("actor") or {} - result = (original.get("response") or {}).get("native_loopx") or {} - failure = result.get("host_failure") or {} - if (original.get("origin") != "native_loopx" or original.get("loopx_execution") is not True - or original.get("status") != "completed" or original.get("session_id") != actor.get("session_id") - or request.get("work_kind") != "report" or request.get("report_window_id") != window.get("window_id") - or request.get("report_subscription_revision") != window.get("subscription_revision") - or actor.get("goal_id") != window.get("goal_id") or actor.get("agent_id") != window.get("agent_id") - or result.get("status") != "failed" or result.get("result_kind") != "host_failure" - or failure.get("retryable") is not False): - return None - identity = { - "session_id": original.get("session_id"), - "chat_turn_id": original.get("turn_id"), - "provider_turn_id": original.get("upstream_turn_id"), - "turn_instance_id": request.get("turn_instance_id"), - "window_id": window.get("window_id"), - "subscription_revision": window.get("subscription_revision"), - } - if any(not isinstance(value, str) or not value for value in identity.values()): - return None - encoded = json.dumps(result, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() - return {**identity, "native_result_sha256": hashlib.sha256(encoded).hexdigest()} - - -def _read_report_failure_record(runtime_root: Path, window: dict[str, Any]) -> dict[str, Any] | None: - path = attempt_directory(runtime_root, window) / REPORT_FAILURE_PROOF - try: - if path.parent.is_symlink() or path.is_symlink() or not path.is_file(): - return None - proof = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return None - return proof if isinstance(proof, dict) else None - - -def _is_antigravity_turn_id(value: object) -> bool: - return isinstance(value, str) and value.startswith("agy_turn_") - - -def _is_valid_retained_proof(proof: dict[str, Any] | None, binding: dict[str, str]) -> bool: - if _is_antigravity_turn_id(binding.get("provider_turn_id")): - return ( - isinstance(proof, dict) - and set(proof) == {"binding", "provider_thread_id", "adapter_kind", "cascade_idle", "no_final_response"} - and proof["binding"] == binding - and proof["adapter_kind"] == "antigravity_ls" - and proof["cascade_idle"] is True - and proof["no_final_response"] is True - and isinstance(proof["provider_thread_id"], str) - and bool(proof["provider_thread_id"]) - ) - return ( - isinstance(proof, dict) - and set(proof) == {"binding", "provider_thread_id", "only_original_user_item"} - and proof["binding"] == binding - and proof["only_original_user_item"] is True - and isinstance(proof["provider_thread_id"], str) - and bool(proof["provider_thread_id"]) - ) - - -def _is_contradicted_proof(proof: dict[str, Any] | None, binding: dict[str, str]) -> bool: - if not isinstance(proof, dict): - return False - thread_id = proof.get("provider_thread_id") - return ( - set(proof) == {"binding", "provider_thread_id", "only_original_user_item", "contradicted"} - and proof["binding"] == binding - and proof["only_original_user_item"] is False - and proof["contradicted"] is True - and (thread_id is None or isinstance(thread_id, str) and bool(thread_id)) - ) - - -def _failure_proof_lock(folder: Path, *, operation: str, generation_locked: bool): +def _failure_proof_lock( + folder: Path, + *, + operation: str, + generation_locked: bool, +) -> AbstractContextManager[object]: if generation_locked: return nullcontext(folder / "generation.lock") - return try_exclusive_file_lock( - folder / "generation.lock", - preserve_holder=True, - operation=operation, + return cast( + AbstractContextManager[object], + try_exclusive_file_lock( + folder / "generation.lock", + preserve_holder=True, + operation=operation, + ), ) -def _contradiction_ledger_path(runtime_root: Path, window: Mapping[str, Any]) -> Path | None: - goal_id = window.get("goal_id") - if not isinstance(goal_id, str) or not REPORT_IDENTITY_PATTERN.fullmatch(goal_id): - return None - return cadence_journal_path(runtime_root, goal_id).parent / CONTRADICTED_REPORT_FAILURES - - -def _binding_key(binding: Mapping[str, str]) -> str: - encoded = json.dumps(dict(binding), ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() - return hashlib.sha256(encoded).hexdigest() - - -def _read_contradiction_ledger(ledger_path: Path) -> tuple[str, dict[str, Any]]: - try: - if ledger_path.parent.parent.is_symlink() or ledger_path.parent.is_symlink() or ledger_path.is_symlink(): - return "untrusted", {} - if not ledger_path.exists(): - return "absent", {} - if not ledger_path.is_file(): - return "untrusted", {} - data = json.loads(ledger_path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return "untrusted", {} - if (not isinstance(data, dict) or set(data) != {"schema_version", "entries"} - or data.get("schema_version") != CONTRADICTED_FAILURES_SCHEMA - or not isinstance(data.get("entries"), dict)): - return "untrusted", {} - return "ok", data["entries"] - - -def _durable_contradiction_status( - runtime_root: Path, binding: dict[str, str], window: Mapping[str, Any], -) -> str: - ledger_path = _contradiction_ledger_path(runtime_root, window) - if ledger_path is None: - return "untrusted" - status, entries = _read_contradiction_ledger(ledger_path) - if status != "ok": - return status - entry = entries.get(_binding_key(binding)) - if entry is None: - return "absent" - return "contradicted" if _is_contradicted_proof(entry, binding) else "untrusted" - - -def read_retained_report_failure(runtime_root: Path, original: Mapping[str, Any], window: dict[str, Any]) -> bool: - """Scope retained provider evidence to the same failure and cadence window.""" - binding = report_failure_binding(original, window) - if binding is None: - return False - if _durable_contradiction_status(runtime_root, binding, window) != "absent": - return False - return _is_valid_retained_proof(_read_report_failure_record(runtime_root, window), binding) - - -def is_report_failure_contradicted(runtime_root: Path, original: Mapping[str, Any], window: dict[str, Any]) -> bool: - """Return True when live provider history has already contradicted this Turn's proof.""" - binding = report_failure_binding(original, window) - if binding is None: - return False - if _durable_contradiction_status(runtime_root, binding, window) != "absent": - return True - return _is_contradicted_proof(_read_report_failure_record(runtime_root, window), binding) - - def retain_report_failure( - runtime_root: Path, store: Any, original: Mapping[str, Any], window: dict[str, Any], proof: Mapping[str, Any], - *, generation_locked: bool = False, + runtime_root: Path, + store: TurnLoader, + original: ProofMapping, + window: ProofMapping, + proof: ProofMapping, + *, + generation_locked: bool = False, ) -> None: """Idempotently record a verified pre-execution failure under the generation lock.""" binding = report_failure_binding(original, window) thread_id = proof.get("thread_id") - if binding is None or proof.get("turn_id") != binding["provider_turn_id"] or not isinstance(thread_id, str) or not thread_id: + if ( + binding is None + or proof.get("turn_id") != binding["provider_turn_id"] + or not isinstance(thread_id, str) + or not thread_id + ): return - is_ag = _is_antigravity_turn_id(binding["provider_turn_id"]) - if is_ag: - if (proof.get("adapter_kind") != "antigravity_ls" - or proof.get("cascade_idle") is not True - or proof.get("no_final_response") is not True): + if _is_antigravity_turn_id(binding["provider_turn_id"]): + if ( + proof.get("adapter_kind") != "antigravity_ls" + or proof.get("cascade_idle") is not True + or proof.get("no_final_response") is not True + ): return - record: dict[str, Any] = { + record: ProofObject = { "binding": binding, "provider_thread_id": thread_id, "adapter_kind": "antigravity_ls", @@ -208,66 +112,86 @@ def retain_report_failure( } if _durable_contradiction_status(runtime_root, binding, window) != "absent": return - folder = attempt_directory(runtime_root, window) + folder = attempt_directory(runtime_root, _object_dict(window)) if folder.is_symlink() or not folder.is_dir(): return path = folder / REPORT_FAILURE_PROOF with _failure_proof_lock( - folder, operation="retain_report_failure_observation", generation_locked=generation_locked, + folder, operation="retain_report_failure_observation", generation_locked=generation_locked ) as ownership: if ownership is None or path.exists() or path.is_symlink(): return # Read the original again after metadata I/O. Never overwrite a # prior receipt, contradiction, or copy the provider's live quota observation. - current = store.load_turn(original["session_id"], original["turn_id"]) + current = store.load_turn(cast(str, original["session_id"]), cast(str, original["turn_id"])) if current is not None and report_failure_binding(current, window) == binding: atomic_write_json(path, record) def _invalidate_attempt_proof( - runtime_root: Path, window: dict[str, Any], binding: dict[str, str], - *, thread_id: str | None, generation_locked: bool, write_contradiction: bool, + runtime_root: Path, + window: ProofMapping, + binding: Mapping[str, str], + *, + thread_id: str | None, + generation_locked: bool, + write_contradiction: bool, ) -> None: - folder = attempt_directory(runtime_root, window) + folder = attempt_directory(runtime_root, _object_dict(window)) if folder.is_symlink() or not folder.is_dir(): return path = folder / REPORT_FAILURE_PROOF try: with _failure_proof_lock( - folder, operation="contradict_report_failure_observation", generation_locked=generation_locked, + folder, + operation="contradict_report_failure_observation", + generation_locked=generation_locked, ) as ownership: if ownership is None or path.is_symlink(): return existing = _read_report_failure_record(runtime_root, window) - if _is_contradicted_proof(existing, binding) and existing.get("provider_thread_id") == thread_id: + if _is_exact_contradiction(existing, binding, thread_id): return if not _is_contradicted_proof(existing, binding) and path.exists(): path.unlink(missing_ok=True) if not write_contradiction: return - atomic_write_json(path, { - "binding": binding, - "provider_thread_id": thread_id, - "only_original_user_item": False, - "contradicted": True, - }) + atomic_write_json( + path, + { + "binding": binding, + "provider_thread_id": thread_id, + "only_original_user_item": False, + "contradicted": True, + }, + ) persisted = _read_report_failure_record(runtime_root, window) - if not _is_contradicted_proof(persisted, binding) or persisted.get("provider_thread_id") != thread_id: - _LOG.warning("Attempt-level report failure proof readback did not match after durable contradiction") + if not _is_exact_contradiction(persisted, binding, thread_id): + _LOG.warning( + "Attempt-level report failure proof readback did not match after durable contradiction" + ) except OSError: _LOG.warning("Could not invalidate attempt-level report failure proof") def contradict_report_failure( - runtime_root: Path, store: Any, original: Mapping[str, Any], window: dict[str, Any], - proof: Mapping[str, Any] | None = None, *, generation_locked: bool = False, + runtime_root: Path, + store: TurnLoader, + original: ProofMapping, + window: ProofMapping, + proof: ProofMapping | None = None, + *, + generation_locked: bool = False, ) -> None: """Durably invalidate a report Turn's failure proof after live contradiction.""" binding = report_failure_binding(original, window) if binding is None: raise ValueError("contradiction requires a valid report failure binding") - if (isinstance(proof, Mapping) and proof.get("turn_id") is not None - and proof.get("turn_id") != binding["provider_turn_id"]): + if ( + isinstance(proof, Mapping) + and proof.get("turn_id") is not None + and proof.get("turn_id") != binding["provider_turn_id"] + ): raise ValueError("contradiction proof turn does not match original report failure") ledger_path = _contradiction_ledger_path(runtime_root, window) if ledger_path is None: @@ -276,31 +200,40 @@ def contradict_report_failure( if parent.parent.is_symlink() or parent.is_symlink(): raise OSError("periodic report directory is unavailable for durable contradiction") parent.mkdir(parents=True, exist_ok=True) - existing_attempt = _read_report_failure_record(runtime_root, window) - thread_id = proof.get("thread_id") if isinstance(proof, Mapping) else None - if not isinstance(thread_id, str) or not thread_id: + raw_thread = proof.get("thread_id") if isinstance(proof, Mapping) else None + thread_id: str | None = ( + raw_thread if isinstance(raw_thread, str) and raw_thread else None + ) + if thread_id is None: + existing_attempt = _read_report_failure_record(runtime_root, window) existing_thread = existing_attempt.get("provider_thread_id") if existing_attempt else None - thread_id = existing_thread if isinstance(existing_thread, str) and existing_thread else None + if isinstance(existing_thread, str) and existing_thread: + thread_id = existing_thread try: with try_exclusive_file_lock( - ledger_path, preserve_holder=True, operation="persist_contradicted_report_failure", + ledger_path, preserve_holder=True, operation="persist_contradicted_report_failure" ) as ledger_ownership: if ledger_ownership is None or ledger_path.is_symlink(): raise OSError("durable report contradiction lock or path is unavailable") # Read the original again after metadata I/O before recording the # contradiction for this exact Turn, window and native result digest. - current = store.load_turn(original["session_id"], original["turn_id"]) + current = store.load_turn( + cast(str, original["session_id"]), cast(str, original["turn_id"]) + ) if current is None or report_failure_binding(current, window) != binding: - raise RuntimeError("original report failure binding changed before contradiction persistence") + raise RuntimeError( + "original report failure binding changed before contradiction persistence" + ) status, entries = _read_contradiction_ledger(ledger_path) if status == "untrusted": raise OSError("durable report contradiction ledger is corrupt or untrusted") key = _binding_key(binding) existing_entry = entries.get(key) - if not isinstance(thread_id, str) or not thread_id: - ledger_thread = existing_entry.get("provider_thread_id") if isinstance(existing_entry, dict) else None - thread_id = ledger_thread if isinstance(ledger_thread, str) and ledger_thread else None - if not (_is_contradicted_proof(existing_entry, binding) and existing_entry.get("provider_thread_id") == thread_id): + if thread_id is None and isinstance(existing_entry, Mapping): + ledger_thread = existing_entry.get("provider_thread_id") + if isinstance(ledger_thread, str) and ledger_thread: + thread_id = ledger_thread + if not _is_exact_contradiction(existing_entry, binding, thread_id): updated_entries = dict(entries) updated_entries[key] = { "binding": binding, @@ -308,273 +241,43 @@ def contradict_report_failure( "only_original_user_item": False, "contradicted": True, } - atomic_write_json(ledger_path, { - "schema_version": CONTRADICTED_FAILURES_SCHEMA, - "entries": updated_entries, - }) + atomic_write_json( + ledger_path, + {"schema_version": CONTRADICTED_FAILURES_SCHEMA, "entries": updated_entries}, + ) readback_status, readback_entries = _read_contradiction_ledger(ledger_path) persisted = readback_entries.get(key) if readback_status == "ok" else None - if not _is_contradicted_proof(persisted, binding) or persisted.get("provider_thread_id") != thread_id: + if not _is_exact_contradiction(persisted, binding, thread_id): raise OSError("durable report contradiction failed readback verification") except OSError: # Best-effort cleanup of any removable positive attempt file before failing closed. _invalidate_attempt_proof( - runtime_root, window, binding, thread_id=thread_id, - generation_locked=generation_locked, write_contradiction=False, + runtime_root, + window, + binding, + thread_id=thread_id, + generation_locked=generation_locked, + write_contradiction=False, ) raise _invalidate_attempt_proof( - runtime_root, window, binding, thread_id=thread_id, - generation_locked=generation_locked, write_contradiction=True, - ) - - -def valid_report_failure_proof( - original: Mapping[str, Any], threads: Sequence[str], proof: Mapping[str, Any] | None, -) -> bool: - """Return True when a live provider observation proves a terminal host failure with no generated answer.""" - upstream_turn_id = original.get("upstream_turn_id") - if _is_antigravity_turn_id(upstream_turn_id): - return ( - isinstance(proof, Mapping) - and proof.get("contradicted") is not True - and proof.get("adapter_kind") == "antigravity_ls" - and proof.get("turn_id") == upstream_turn_id - and proof.get("thread_id") in threads - and proof.get("cascade_idle") is True - and proof.get("no_final_response") is True - ) - return (isinstance(proof, Mapping) and proof.get("contradicted") is not True - and proof.get("turn_id") == upstream_turn_id and proof.get("thread_id") in threads - and proof.get("only_original_user_item") is True and bool(proof.get("codex_error_info"))) - - -def proof_targets_original_turn( - original: Mapping[str, Any], threads: Sequence[str], proof: Mapping[str, Any] | None, -) -> bool: - """Ensure an observation refers to this exact original thread/turn.""" - if not isinstance(proof, Mapping): - return False - thread_id = proof.get("thread_id") - turn_id = proof.get("turn_id") - return isinstance(thread_id, str) and thread_id in threads and turn_id == original.get("upstream_turn_id") - - -def probe_report_failure( - controller: Any, store: Any, original: Mapping[str, Any], *, - include_contradiction: bool = False, contradiction_detail: bool = False, - swallow_probe_errors: bool | None = None, -) -> tuple[list[str], dict[str, Any] | None] | None: - """Query the original Session's native threads without starting or resuming work.""" - result = (original.get("response") or {}).get("native_loopx") or {} - request = original.get("loopx_request") or {} - upstream_turn_id = original.get("upstream_turn_id") - if (original.get("status") != "completed" or request.get("work_kind") != "report" - or result.get("result_kind") != "host_failure" or not upstream_turn_id): - return None - if _is_antigravity_turn_id(upstream_turn_id): - return None - from ...chat_agent import CodexChatAgentError - from .codex_adapter import CodexAppServerAdapter - from .codex_context import checked_session_home - - session = store.load_session(original["session_id"]) - if not session or not session.get("codex_home") or not session.get("upstream_thread_id"): - return None - history = session.get("upstream_context_history") or [] - if not isinstance(history, list) or any(not isinstance(item, dict) - or not isinstance(item.get("thread_id"), str) or not item["thread_id"] - for item in history): - return None - # Context replacement retains native provenance on this same Session. - # Read the original refusal there; exclude non-Codex cascades. - raw_threads = [ - *([session["upstream_thread_id"]] if session.get("agent_id") != "antigravity" else []), - *(item["thread_id"] for item in reversed(history) if item.get("agent_id") != "antigravity"), - ] - threads = list(dict.fromkeys(raw_threads)) - if not threads: - return None - swallow = include_contradiction if swallow_probe_errors is None else swallow_probe_errors - try: - proof = CodexAppServerAdapter.failed_request_observation(codex_bin=controller.codex_bin, - codex_home=Path(session["codex_home"]), thread_ids=threads, - model_auth_home=checked_session_home(controller.codex_home, session), - turn_id=upstream_turn_id, include_contradiction=include_contradiction, - contradiction_detail=contradiction_detail) - except (CodexChatAgentError, OSError, ValueError, RuntimeError, subprocess.SubprocessError): - if not swallow: - raise - proof = None - return threads, proof - - -def _extract_antigravity_turn_cascade( - store: Any, original: Mapping[str, Any], -) -> tuple[dict[str, Any], str, list[dict[str, Any]]] | None: - """Resolve one Antigravity cascade and stored events when no final answer exists.""" - upstream_turn_id = original.get("upstream_turn_id") - session = store.load_session(original["session_id"]) - if not session or original.get("delta_count") != 0 or not _is_antigravity_turn_id(upstream_turn_id): - return None - try: - events = store.events_after(original["session_id"], original["turn_id"], None) - except (OSError, ValueError): - return None - if any(row.get("kind") in {"answer.final", "turn.native_result"} for row in events): - return None - started = [ - (row.get("payload") or {}).get("threadId") - for row in events - if row.get("kind") == "turn.started" and isinstance(row.get("payload"), Mapping) - and row["payload"].get("upstream_turn_id") == upstream_turn_id - ] - if len(started) != 1 or not isinstance(started[0], str) or not started[0]: - return None - return session, started[0], events - - -def _antigravity_trajectory_steps( - url: str, csrf_token: str, cascade_id: str, traj: Mapping[str, Any], -) -> list[dict[str, Any]] | None: - """Load complete trajectory steps from an idle Antigravity cascade.""" - from ...chat_agent import CodexChatAgentError - from .antigravity_adapter import _read_trajectory_steps, _rpc_post - - if (traj.get("trajectory") or {}).get("cascadeId") != cascade_id: - return None - total = traj.get("numTotalSteps") - inline_steps = (traj.get("trajectory") or {}).get("steps") - if type(total) is int and total > 0: - if isinstance(inline_steps, list) and len(inline_steps) == total and all(isinstance(s, dict) for s in inline_steps): - return inline_steps - try: - loaded = _read_trajectory_steps( - lambda offset, end: _rpc_post( - url, - csrf_token, - "GetCascadeTrajectorySteps", - {"cascadeId": cascade_id, "stepOffset": offset, "startIndex": offset, "endIndex": end}, - timeout=5.0, - ).get("steps"), - start=0, - total=total, - ) - if loaded is None: - return None - after = _rpc_post(url, csrf_token, "GetCascadeTrajectory", {"cascadeId": cascade_id}, timeout=2.5) - except (CodexChatAgentError, OSError, ValueError): - return None - if (after.get("status") != "CASCADE_RUN_STATUS_IDLE" - or after.get("numTotalSteps") != total - or (after.get("trajectory") or {}).get("cascadeId") != cascade_id): - return None - return [step for _, step in loaded[0]] - if total == 0 or (total is None and isinstance(inline_steps, list) and len(inline_steps) == 0): - return [] - return None - - -def _antigravity_has_running_step(steps: Sequence[Mapping[str, Any]]) -> bool: - return any(step.get("status") == "CORTEX_STEP_STATUS_RUNNING" for step in steps) - - -def _antigravity_has_final_response(steps: Sequence[Mapping[str, Any]]) -> bool: - for step in steps: - if step.get("type") != "CORTEX_STEP_TYPE_PLANNER_RESPONSE": - continue - planner = step.get("plannerResponse") - if not isinstance(planner, Mapping) or planner.get("toolCalls"): - continue - answer = planner.get("modifiedResponse") or planner.get("response") - if isinstance(answer, str) and answer.strip(): - return True - return False - - -def _probe_antigravity_report_failure( - store: Any, original: Mapping[str, Any], -) -> tuple[list[str], dict[str, Any] | None] | None: - """Query the Antigravity LS trajectory without starting or resuming work.""" - result = (original.get("response") or {}).get("native_loopx") or {} - request = original.get("loopx_request") or {} - upstream_turn_id = original.get("upstream_turn_id") - if (original.get("status") != "completed" or request.get("work_kind") != "report" - or result.get("result_kind") != "host_failure" or not _is_antigravity_turn_id(upstream_turn_id)): - return None - extracted = _extract_antigravity_turn_cascade(store, original) - if extracted is None: - return None - _, cascade_id, _ = extracted - from ...chat_agent import CodexChatAgentError - from .antigravity_adapter import _rpc_post, discover_antigravity_language_server - - found = discover_antigravity_language_server( - include_model_config=False, - deadline=time.monotonic() + 3.0, - ) - if found is None: - return [cascade_id], None - url = str(found["url"]) - csrf_token = str(found["csrf_token"]) - try: - traj = _rpc_post(url, csrf_token, "GetCascadeTrajectory", {"cascadeId": cascade_id}, timeout=2.5) - except (CodexChatAgentError, OSError, ValueError): - return [cascade_id], None - if (traj.get("trajectory") or {}).get("cascadeId") != cascade_id: - return [cascade_id], None - base_proof = { - "adapter_kind": "antigravity_ls", - "turn_id": upstream_turn_id, - "thread_id": cascade_id, - } - if traj.get("status") != "CASCADE_RUN_STATUS_IDLE": - return [cascade_id], {**base_proof, "in_progress": True, "target_in_progress": True, "contradicted": True} - steps = _antigravity_trajectory_steps(url, csrf_token, cascade_id, traj) - if steps is None: - return [cascade_id], None - if _antigravity_has_running_step(steps): - return [cascade_id], {**base_proof, "in_progress": True, "target_in_progress": True, "contradicted": True} - if _antigravity_has_final_response(steps): - return [cascade_id], { - **base_proof, - "cascade_idle": True, - "no_final_response": False, - "contradicted": True, - "explicit_contradiction": True, - } - return [cascade_id], {**base_proof, "cascade_idle": True, "no_final_response": True} - - -def observe_antigravity_report_failure(store: Any, original: Mapping[str, Any]) -> dict[str, Any] | None: - """Read an Antigravity report timeout/failure observation without starting work.""" - extracted = _extract_antigravity_turn_cascade(store, original) - if extracted is None: - return None - session, cascade_id, events = extracted - upstream_turn_id = str(original["upstream_turn_id"]) - native_timeout = any( - row.get("kind") == "agent.phase" and isinstance(row.get("payload"), Mapping) - and row["payload"].get("method") == "native/timeout" - for row in events - ) - from .antigravity_adapter import AntigravityAdapter - return AntigravityAdapter.failed_report_observation( - cascade_id=cascade_id, - turn_id=upstream_turn_id, - native_timeout=native_timeout, - model_id=session.get("agent_model_id"), - reasoning_effort=session.get("agent_reasoning_effort"), + runtime_root, + window, + binding, + thread_id=thread_id, + generation_locked=generation_locked, + write_contradiction=True, ) -def observe_report_failure(controller: Any, store: Any, original: Mapping[str, Any]) -> dict[str, Any] | None: +def observe_report_failure( + controller: ReportProofController, + store: ReportProofStore, + original: ProofMapping, +) -> ProofObject | None: """Read the original native failure without starting or resuming work.""" - result = (original.get("response") or {}).get("native_loopx") or {} - request = original.get("loopx_request") or {} - upstream_turn_id = original.get("upstream_turn_id") - if (original.get("status") != "completed" or request.get("work_kind") != "report" - or result.get("result_kind") != "host_failure" or not upstream_turn_id): + upstream_turn_id = _is_completed_host_failure_report(original) + if not upstream_turn_id: return None if _is_antigravity_turn_id(upstream_turn_id): return observe_antigravity_report_failure(store, original) @@ -586,39 +289,56 @@ def observe_report_failure(controller: Any, store: Any, original: Mapping[str, A def _try_retain_report_failure( - runtime_root: Path, store: Any, original: Mapping[str, Any], window: dict[str, Any], - proof: Mapping[str, Any], *, generation_locked: bool = False, + runtime_root: Path, + store: TurnLoader, + original: ProofMapping, + window: ProofMapping, + proof: ProofMapping, + *, + generation_locked: bool = False, ) -> None: try: retain_report_failure( - runtime_root, store, original, window, proof, generation_locked=generation_locked, + runtime_root, store, original, window, proof, generation_locked=generation_locked ) except (OSError, ValueError, TypeError, KeyError): _LOG.warning("An original report's terminal failure proof could not be retained") def handle_contradicted_report_observation( - runtime_root: Path, store: Any, original: Mapping[str, Any], window: dict[str, Any] | None, - threads: Sequence[str], proof: Mapping[str, Any], *, generation_locked: bool = False, + runtime_root: Path, + store: TurnLoader, + original: ProofMapping, + window: ProofMapping | None, + threads: Sequence[str], + proof: ProofMapping, + *, + generation_locked: bool = False, ) -> None: """Persist durable contradictions while holding transient in-progress threads safely.""" if window is None or not proof_targets_original_turn(original, threads, proof): return if proof.get("in_progress") is True: - if proof.get("target_in_progress") is True and read_retained_report_failure(runtime_root, original, window): + if proof.get("target_in_progress") is True and read_retained_report_failure( + runtime_root, original, window + ): contradict_report_failure( - runtime_root, store, original, window, proof, generation_locked=generation_locked, + runtime_root, store, original, window, proof, generation_locked=generation_locked ) return if proof.get("explicit_contradiction") is True: contradict_report_failure( - runtime_root, store, original, window, proof, generation_locked=generation_locked, + runtime_root, store, original, window, proof, generation_locked=generation_locked ) def verify_report_window_failure( - controller: Any, store: Any, original: Mapping[str, Any], window: dict[str, Any], *, - probe_fn: Callable[..., tuple[list[str], dict[str, Any] | None] | None] | None = None, + controller: ReportProofController, + store: ReportProofStore, + original: ProofMapping, + window: ProofMapping, + *, + probe_fn: Callable[..., tuple[list[str], ProofObject | None] | None] | None = None, generation_locked: bool = False, ) -> bool: """Query live provider history first; fall back to un-contradicted proof only if unavailable.""" @@ -632,49 +352,60 @@ def verify_report_window_failure( probed = _probe_antigravity_report_failure(store, original) else: probed = probe_report_failure( - controller, store, original, include_contradiction=True, contradiction_detail=True, + controller, store, original, include_contradiction=True, contradiction_detail=True ) if probed is None: return False threads, proof = probed if proof is not None: - if proof.get("contradicted") is True or not valid_report_failure_proof(original, threads, proof): + if proof.get("contradicted") is True or not valid_report_failure_proof( + original, threads, proof + ): handle_contradicted_report_observation( - runtime_root, store, original, window, threads, proof, generation_locked=generation_locked, + runtime_root, store, original, window, threads, proof, generation_locked=generation_locked ) return False - if is_report_failure_contradicted(runtime_root, original, window): + contradicted, _ = _binding_attempt_state(runtime_root, binding, window) + if contradicted: return False _try_retain_report_failure( - runtime_root, store, original, window, proof, generation_locked=generation_locked, + runtime_root, store, original, window, proof, generation_locked=generation_locked ) return True - if is_report_failure_contradicted(runtime_root, original, window): - return False - return read_retained_report_failure(runtime_root, original, window) + contradicted, retained_record = _binding_attempt_state(runtime_root, binding, window) + return (not contradicted) and _is_valid_retained_proof(retained_record, binding) def resolve_report_quota_observation( - controller: Any, store: Any, original: Mapping[str, Any], *, - report_window: dict[str, Any] | None = None, - probe_fn: Callable[..., tuple[list[str], dict[str, Any] | None] | None] | None = None, - fallback_observe_fn: Callable[[Mapping[str, Any]], dict[str, Any] | None] | None = None, -) -> dict[str, Any] | None: + controller: ReportProofController, + store: ReportProofStore, + original: ProofMapping, + *, + report_window: ProofMapping | None = None, + probe_fn: Callable[..., tuple[list[str], ProofObject | None] | None] | None = None, + fallback_observe_fn: Callable[[ProofMapping], ProofObject | None] | None = None, +) -> ProofObject | None: """Inspect live quota recovery for the original Turn without rewriting prior contradictions.""" runtime_root = controller.coordination_runtime_root - if report_window is not None and is_report_failure_contradicted(runtime_root, original, report_window): + if report_window is not None and is_report_failure_contradicted( + runtime_root, original, report_window + ): return None if fallback_observe_fn is not None: proof = fallback_observe_fn(original) else: probed = ( probe_fn( - original, include_contradiction=True, contradiction_detail=True, swallow_probe_errors=True, + original, include_contradiction=True, contradiction_detail=True, swallow_probe_errors=True ) if probe_fn is not None else probe_report_failure( - controller, store, original, - include_contradiction=True, contradiction_detail=True, swallow_probe_errors=True, + controller, + store, + original, + include_contradiction=True, + contradiction_detail=True, + swallow_probe_errors=True, ) ) if probed is None: @@ -682,8 +413,12 @@ def resolve_report_quota_observation( threads, proof = probed if proof is None: return None - if proof.get("contradicted") is True or not valid_report_failure_proof(original, threads, proof): - handle_contradicted_report_observation(runtime_root, store, original, report_window, threads, proof) + if proof.get("contradicted") is True or not valid_report_failure_proof( + original, threads, proof + ): + handle_contradicted_report_observation( + runtime_root, store, original, report_window, threads, proof + ) return None if proof is not None and report_window is not None: _try_retain_report_failure(runtime_root, store, original, report_window, proof) @@ -691,38 +426,69 @@ def resolve_report_quota_observation( def build_report_quota_request( - controller: Any, store: Any, original: Mapping[str, Any], *, - report_window: dict[str, Any] | None = None, - fallback_observe_fn: Callable[[Mapping[str, Any]], dict[str, Any] | None] | None = None, -) -> dict[str, Any] | None: + controller: ReportProofController, + store: ReportProofStore, + original: ProofMapping, + *, + report_window: ProofMapping | None = None, + fallback_observe_fn: Callable[[ProofMapping], ProofObject | None] | None = None, +) -> ProofObject | None: """Observe quota recovery, never resume or rewrite the failed native Turn.""" - request = original.get("loopx_request") or {} - if request.get("report_quota_recovery") is not None or request.get("report_timeout_recovery") is not None: + request = _mapping(original.get("loopx_request")) + if ( + request.get("report_quota_recovery") is not None + or request.get("report_timeout_recovery") is not None + ): return None proof = resolve_report_quota_observation( - controller, store, original, report_window=report_window, fallback_observe_fn=fallback_observe_fn, + controller, store, original, report_window=report_window, fallback_observe_fn=fallback_observe_fn ) - if (not proof or proof.get("only_original_user_item") is not True - or proof.get("codex_error_info") != "usageLimitExceeded" or proof.get("quota_available") is not True): + if ( + not proof + or proof.get("only_original_user_item") is not True + or proof.get("codex_error_info") != "usageLimitExceeded" + or proof.get("quota_available") is not True + ): return None - return {**request, "turn_instance_id": request["turn_instance_id"] + ".quota-recovery", - "report_quota_recovery": {"original_turn_id": original["turn_id"], "native_observation": proof}} + return { + **request, + "turn_instance_id": cast(str, request["turn_instance_id"]) + ".quota-recovery", + "report_quota_recovery": { + "original_turn_id": original["turn_id"], + "native_observation": proof, + }, + } def build_report_timeout_request( - original: Mapping[str, Any], *, - observe_fn: Callable[[Mapping[str, Any]], dict[str, Any] | None], -) -> dict[str, Any] | None: + original: ProofMapping, + *, + observe_fn: Callable[[ProofMapping], ProofObject | None], +) -> ProofObject | None: """Observe idle Antigravity timeout for one bounded isolated-cascade retry.""" - request = original.get("loopx_request") or {} + request = _mapping(original.get("loopx_request")) upstream_turn_id = original.get("upstream_turn_id") - if (request.get("report_quota_recovery") is not None or request.get("report_timeout_recovery") is not None - or not isinstance(upstream_turn_id, str) or not upstream_turn_id.startswith("agy_turn_")): + if ( + request.get("report_quota_recovery") is not None + or request.get("report_timeout_recovery") is not None + or not _is_antigravity_turn_id(upstream_turn_id) + ): return None proof = observe_fn(original) - if (not proof or proof.get("adapter_kind") != "antigravity_ls" - or proof.get("cascade_idle") is not True or proof.get("no_final_response") is not True - or proof.get("native_timeout") is not True or proof.get("quota_available") is not True): + if ( + not proof + or proof.get("adapter_kind") != "antigravity_ls" + or proof.get("cascade_idle") is not True + or proof.get("no_final_response") is not True + or proof.get("native_timeout") is not True + or proof.get("quota_available") is not True + ): return None - return {**request, "turn_instance_id": request["turn_instance_id"] + ".timeout-recovery", - "report_timeout_recovery": {"original_turn_id": original["turn_id"], "native_observation": proof}} + return { + **request, + "turn_instance_id": cast(str, request["turn_instance_id"]) + ".timeout-recovery", + "report_timeout_recovery": { + "original_turn_id": original["turn_id"], + "native_observation": proof, + }, + } diff --git a/tests/capabilities/test_report_failure_proof_contract.py b/tests/capabilities/test_report_failure_proof_contract.py new file mode 100644 index 0000000000..e3bedd57cc --- /dev/null +++ b/tests/capabilities/test_report_failure_proof_contract.py @@ -0,0 +1,567 @@ +from __future__ import annotations + +import ast +from datetime import datetime, timezone +import json +from pathlib import Path +import subprocess +import sys +from typing import cast + +import pytest + +from loopx.capabilities.native_chat import ( + report_failure_ledger, + report_failure_probe, + report_failure_proof, +) +from loopx.capabilities.native_chat.report_failure_proof import ( + CONTRADICTED_FAILURES_SCHEMA, + CONTRADICTED_REPORT_FAILURES, + REPORT_FAILURE_PROOF, + build_report_quota_request, + build_report_timeout_request, + contradict_report_failure, + is_report_failure_contradicted, + probe_report_failure, + proof_targets_original_turn, + read_retained_report_failure, + report_failure_binding, + retain_report_failure, + valid_report_failure_proof, + verify_report_window_failure, +) +from loopx.capabilities.periodic_report.cadence_journal import ( + admit_cadence_window, + cadence_journal_path, +) +from loopx.capabilities.periodic_report.private_generation import attempt_directory + +REPO_ROOT = Path(__file__).resolve().parents[2] +_IGNORE_MARKER = "type" + ": ignore" +_PINNED_EXPORTS = ( + "REPORT_FAILURE_PROOF", + "CONTRADICTED_REPORT_FAILURES", + "CONTRADICTED_FAILURES_SCHEMA", + "report_failure_binding", + "_read_report_failure_record", + "_is_antigravity_turn_id", + "_is_valid_retained_proof", + "_is_contradicted_proof", + "_failure_proof_lock", + "_contradiction_ledger_path", + "_binding_key", + "_read_contradiction_ledger", + "_durable_contradiction_status", + "read_retained_report_failure", + "is_report_failure_contradicted", + "retain_report_failure", + "_invalidate_attempt_proof", + "contradict_report_failure", + "valid_report_failure_proof", + "proof_targets_original_turn", + "probe_report_failure", + "_extract_antigravity_turn_cascade", + "_antigravity_trajectory_steps", + "_antigravity_has_running_step", + "_antigravity_has_final_response", + "_probe_antigravity_report_failure", + "observe_antigravity_report_failure", + "observe_report_failure", + "_try_retain_report_failure", + "handle_contradicted_report_observation", + "verify_report_window_failure", + "resolve_report_quota_observation", + "build_report_quota_request", + "build_report_timeout_request", +) + + +def _any_ast_refs(path: Path) -> int: + tree = ast.parse(path.read_text(encoding="utf-8")) + count = 0 + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id == "Any": + count += 1 + elif isinstance(node, ast.Attribute) and node.attr == "Any": + count += 1 + elif isinstance(node, ast.alias) and node.name == "Any": + count += 1 + return count + + +_SAMPLE_SUBSCRIPTION: dict[str, object] = { + "enabled": True, + "profile_preset": "portfolio-progress", + "effective_revision": "sha256:" + "1" * 64, + "schedule": { + "schema_version": "periodic_report_schedule_v0", + "schedule_id": "daily-report", + "timezone": "UTC", + "rrule": "FREQ=DAILY;BYHOUR=9;BYMINUTE=0", + "start_date": "2026-01-01", + }, +} + + +def _sample_window(runtime_root: Path) -> dict[str, object]: + admitted = admit_cadence_window( + runtime_root=runtime_root, + goal_id="goal-1", + agent_id="agent-1", + subscription=_SAMPLE_SUBSCRIPTION, + now=datetime(2026, 1, 2, 10, tzinfo=timezone.utc), + ) + return dict(cast(dict[str, object], admitted["window"])) + + +def _sample_original( + window: dict[str, object], + *, + upstream_turn_id: str = "codex-turn-1", + retryable: bool = False, +) -> dict[str, object]: + return { + "origin": "native_loopx", + "loopx_execution": True, + "status": "completed", + "session_id": "sess-1", + "turn_id": "chat-turn-1", + "upstream_turn_id": upstream_turn_id, + "loopx_request": { + "actor": {"session_id": "sess-1", "goal_id": "goal-1", "agent_id": "agent-1"}, + "work_kind": "report", + "report_window_id": window["window_id"], + "report_subscription_revision": window["subscription_revision"], + "turn_instance_id": "report." + str(window["window_id"]), + }, + "response": { + "native_loopx": { + "status": "failed", + "result_kind": "host_failure", + "host_failure": {"retryable": retryable, "kind": "unknown"}, + } + }, + } + + +class _MemoryStore: + def __init__(self, turns: dict[tuple[str, str], dict[str, object]]) -> None: + self._turns = turns + + def load_turn(self, session_id: str, turn_id: str) -> dict[str, object] | None: + return self._turns.get((session_id, turn_id)) + + def load_session(self, session_id: str) -> dict[str, object] | None: + return None + + def events_after( + self, session_id: str, turn_id: str, event_id: str | None + ) -> list[dict[str, object]]: + return [] + + +class _FakeController: + def __init__(self, root: Path) -> None: + self.coordination_runtime_root = root + self.codex_bin = "codex" + self.codex_home = root + + +def test_report_failure_split_zero_any_ceilings_and_exports() -> None: + paths = [ + REPO_ROOT / "loopx/capabilities/native_chat/report_failure_probe.py", + REPO_ROOT / "loopx/capabilities/native_chat/report_failure_ledger.py", + REPO_ROOT / "loopx/capabilities/native_chat/report_failure_proof.py", + Path(__file__).resolve(), + ] + for path in paths: + text = path.read_text(encoding="utf-8") + assert _any_ast_refs(path) == 0, path + assert _IGNORE_MARKER not in text, path + assert len(text.splitlines()) < 750, path + + main_lines = ( + REPO_ROOT / "loopx/capabilities/native_chat/report_failure_proof.py" + ).read_text(encoding="utf-8").splitlines() + assert len(main_lines) <= 550 + + for symbol in _PINNED_EXPORTS: + assert hasattr(report_failure_proof, symbol), symbol + + assert report_failure_proof.probe_report_failure is report_failure_probe.probe_report_failure + assert ( + report_failure_proof.report_failure_binding + is report_failure_ledger.report_failure_binding + ) + + +def test_binding_proof_shapes_malformed_inputs_and_key_presence(tmp_path: Path) -> None: + window = _sample_window(tmp_path) + original = _sample_original(window) + binding = report_failure_binding(original, window) + assert binding is not None + assert binding["window_id"] == window["window_id"] + + assert report_failure_binding(_sample_original(window, retryable=True), window) is None + assert report_failure_binding({"origin": "native_loopx", "loopx_request": "bad", "response": 123}, window) is None + + assert ( + valid_report_failure_proof( + original, + ["thread-1"], + { + "thread_id": "thread-1", + "turn_id": "codex-turn-1", + "only_original_user_item": True, + "codex_error_info": "usageLimitExceeded", + }, + ) + is True + ) + assert ( + valid_report_failure_proof( + original, + ["thread-1"], + { + "thread_id": "thread-1", + "turn_id": "codex-turn-1", + "only_original_user_item": True, + "codex_error_info": "usageLimitExceeded", + "contradicted": True, + }, + ) + is False + ) + assert ( + valid_report_failure_proof( + _sample_original(window, upstream_turn_id="agy_turn_1"), + ["cascade-1"], + { + "adapter_kind": "antigravity_ls", + "thread_id": "cascade-1", + "turn_id": "agy_turn_1", + "cascade_idle": True, + "no_final_response": True, + }, + ) + is True + ) + assert proof_targets_original_turn(original, ["thread-1"], cast(dict[str, object], "bad")) is False + assert proof_targets_original_turn(original, ["thread-1"], {"thread_id": 123, "turn_id": "codex-turn-1"}) is False + + # Contradiction ledger rejects corrupt schema/JSON fail-closed and distinguishes explicit null vs deleted key. + ledger_path = cadence_journal_path(tmp_path, "goal-1").parent / CONTRADICTED_REPORT_FAILURES + ledger_path.parent.mkdir(parents=True, exist_ok=True) + ledger_path.write_text("{corrupt", encoding="utf-8") + assert is_report_failure_contradicted(tmp_path, original, window) is True + assert read_retained_report_failure(tmp_path, original, window) is False + + explicit_null_entry = { + "binding": binding, + "provider_thread_id": None, + "only_original_user_item": False, + "contradicted": True, + } + assert report_failure_ledger._is_contradicted_proof(explicit_null_entry, binding) is True + missing_key_entry = dict(explicit_null_entry) + del missing_key_entry["provider_thread_id"] + assert report_failure_ledger._is_contradicted_proof(missing_key_entry, binding) is False + + ledger_path.write_text( + json.dumps({"schema_version": CONTRADICTED_FAILURES_SCHEMA, "entries": {}}), + encoding="utf-8", + ) + assert is_report_failure_contradicted(tmp_path, original, window) is False + assert probe_report_failure(_FakeController(tmp_path), _MemoryStore({}), _sample_original(window, upstream_turn_id="agy_turn_1")) is None + + +def test_quota_timeout_request_builders_and_single_pass_verification( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + window = _sample_window(tmp_path) + codex_original = _sample_original(window) + store = _MemoryStore({("sess-1", "chat-turn-1"): codex_original}) + controller = _FakeController(tmp_path) + folder = attempt_directory(tmp_path, window) + folder.mkdir(parents=True, exist_ok=True) + + quota_req = build_report_quota_request( + controller, + store, + codex_original, + report_window=window, + fallback_observe_fn=lambda _orig: { + "turn_id": "codex-turn-1", + "thread_id": "thread-1", + "only_original_user_item": True, + "codex_error_info": "usageLimitExceeded", + "quota_available": True, + }, + ) + assert quota_req is not None + assert quota_req["turn_instance_id"] == f"report.{window['window_id']}.quota-recovery" + assert build_report_quota_request( + controller, + store, + { + **codex_original, + "loopx_request": {**cast(dict[str, object], codex_original["loopx_request"]), "report_quota_recovery": {}}, + }, + fallback_observe_fn=lambda _orig: None, + ) is None + + ag_original = _sample_original(window, upstream_turn_id="agy_turn_9") + timeout_req = build_report_timeout_request( + ag_original, + observe_fn=lambda _orig: { + "adapter_kind": "antigravity_ls", + "cascade_idle": True, + "no_final_response": True, + "native_timeout": True, + "quota_available": True, + }, + ) + assert timeout_req is not None + assert timeout_req["turn_instance_id"] == f"report.{window['window_id']}.timeout-recovery" + + # Verify fallback path (proof=None) performs only 1 post-probe ledger+record read instead of 2+2. + ledger_reads = 0 + record_reads = 0 + orig_read_ledger = report_failure_ledger._read_contradiction_ledger + orig_read_record = report_failure_ledger._read_report_failure_record + + def count_ledger(path: Path) -> tuple[str, dict[str, object]]: + nonlocal ledger_reads + ledger_reads += 1 + return orig_read_ledger(path) + + def count_record(root: Path, win: dict[str, object]) -> dict[str, object] | None: + nonlocal record_reads + record_reads += 1 + return orig_read_record(root, win) + + monkeypatch.setattr(report_failure_ledger, "_read_contradiction_ledger", count_ledger) + monkeypatch.setattr(report_failure_proof, "_read_contradiction_ledger", count_ledger) + monkeypatch.setattr(report_failure_ledger, "_read_report_failure_record", count_record) + monkeypatch.setattr(report_failure_proof, "_read_report_failure_record", count_record) + ledger_path = cadence_journal_path(tmp_path, "goal-1").parent / CONTRADICTED_REPORT_FAILURES + ledger_path.parent.mkdir(parents=True, exist_ok=True) + ledger_path.write_text( + json.dumps({"schema_version": CONTRADICTED_FAILURES_SCHEMA, "entries": {}}), + encoding="utf-8", + ) + verified = verify_report_window_failure( + controller, + store, + codex_original, + window, + probe_fn=lambda _orig, **_kw: (["thread-1"], None), + ) + assert verified is True + assert (folder / REPORT_FAILURE_PROOF).is_file() + assert ledger_reads == 2 # 1 pre-probe + 1 single post-probe check + assert record_reads == 1 # single post-probe retained record check + + # Verify Antigravity retain_report_failure rejects non-idle proofs and retains valid agy_turn_ proofs. + ag_root = tmp_path / "ag-retain" + ag_win = _sample_window(ag_root) + ag_orig = _sample_original(ag_win, upstream_turn_id="agy_turn_retain_1") + ag_store = _MemoryStore({("sess-1", "chat-turn-1"): ag_orig}) + attempt_directory(ag_root, ag_win).mkdir(parents=True, exist_ok=True) + retain_report_failure( + ag_root, + ag_store, + ag_orig, + ag_win, + {"turn_id": "agy_turn_retain_1", "thread_id": "cascade-1", "adapter_kind": "antigravity_ls", "cascade_idle": False, "no_final_response": True}, + ) + assert read_retained_report_failure(ag_root, ag_orig, ag_win) is False + retain_report_failure( + ag_root, + ag_store, + ag_orig, + ag_win, + {"turn_id": "agy_turn_retain_1", "thread_id": "cascade-1", "adapter_kind": "antigravity_ls", "cascade_idle": True, "no_final_response": True}, + ) + assert read_retained_report_failure(ag_root, ag_orig, ag_win) is True + + # Verify contradict_report_failure skips pre-read of attempt file when proof supplies thread_id. + record_reads = 0 + contradict_report_failure( + tmp_path, + store, + codex_original, + window, + {"contradicted": True, "turn_id": "codex-turn-1", "thread_id": "thread-1"}, + ) + # 2 reads come strictly from _invalidate_attempt_proof (existing + readback), 0 pre-ledger read. + assert record_reads == 2 + assert is_report_failure_contradicted(tmp_path, codex_original, window) is True + + +def test_paired_origin_main_behavioral_parity_report_failure_proof( + tmp_path: Path, +) -> None: + rev = subprocess.run( + ["git", "-C", str(REPO_ROOT), "rev-parse", "--verify", "origin/main"], + text=True, + capture_output=True, + ) + if rev.returncode != 0: + pytest.skip("origin/main ref unavailable in shallow checkout") + + baseline_code = subprocess.check_output( + [ + "git", + "-C", + str(REPO_ROOT), + "show", + "origin/main:loopx/capabilities/native_chat/report_failure_proof.py", + ], + text=True, + ) + script = """ +import sys, types +from datetime import datetime, timezone +from pathlib import Path +from loopx.capabilities.native_chat import report_failure_proof as head_mod +from loopx.capabilities.periodic_report.cadence_journal import admit_cadence_window +from loopx.capabilities.periodic_report.private_generation import attempt_directory + +spec_mod = types.ModuleType("loopx.capabilities.native_chat.baseline_report_failure_proof") +spec_mod.__package__ = "loopx.capabilities.native_chat" +exec(compile(open(sys.argv[1], encoding="utf-8").read(), "origin_main_rfp.py", "exec"), spec_mod.__dict__) + +root_base = Path(sys.argv[2]) / "base" +root_head = Path(sys.argv[2]) / "head" +subscription = { + "enabled": True, + "profile_preset": "portfolio-progress", + "effective_revision": "sha256:" + "1" * 64, + "schedule": { + "schema_version": "periodic_report_schedule_v0", + "schedule_id": "daily-report", + "timezone": "UTC", + "rrule": "FREQ=DAILY;BYHOUR=9;BYMINUTE=0", + "start_date": "2026-01-01", + }, +} +window = admit_cadence_window( + runtime_root=root_base, goal_id="goal-1", agent_id="agent-1", + subscription=subscription, now=datetime(2026, 1, 2, 10, tzinfo=timezone.utc), +)["window"] +admit_cadence_window( + runtime_root=root_head, goal_id="goal-1", agent_id="agent-1", + subscription=subscription, now=datetime(2026, 1, 2, 10, tzinfo=timezone.utc), +) +original = { + "origin": "native_loopx", + "loopx_execution": True, + "status": "completed", + "session_id": "sess-1", + "turn_id": "chat-turn-1", + "upstream_turn_id": "codex-turn-1", + "loopx_request": { + "actor": {"session_id": "sess-1", "goal_id": "goal-1", "agent_id": "agent-1"}, + "work_kind": "report", + "report_window_id": window["window_id"], + "report_subscription_revision": window["subscription_revision"], + "turn_instance_id": "report." + window["window_id"], + }, + "response": { + "native_loopx": { + "status": "failed", + "result_kind": "host_failure", + "host_failure": {"retryable": False, "kind": "unknown"}, + } + }, +} +class Store: + def load_turn(self, sid, tid): return original if (sid, tid) == ("sess-1", "chat-turn-1") else None + def load_session(self, sid): return None + def events_after(self, sid, tid, ev): return [] +class Ctrl: + def __init__(self, root): self.coordination_runtime_root = root; self.codex_bin = "codex"; self.codex_home = root + +for root in (root_base, root_head): + attempt_directory(root, window).mkdir(parents=True, exist_ok=True) + +proof = {"turn_id": "codex-turn-1", "thread_id": "t1", "only_original_user_item": True, "codex_error_info": "usageLimitExceeded", "quota_available": True} +assert head_mod.report_failure_binding(original, window) == spec_mod.report_failure_binding(original, window) +assert head_mod.valid_report_failure_proof(original, ["t1"], proof) == spec_mod.valid_report_failure_proof(original, ["t1"], proof) +assert head_mod.verify_report_window_failure(Ctrl(root_head), Store(), original, window, probe_fn=lambda *_a, **_kw: (["t1"], proof)) == spec_mod.verify_report_window_failure(Ctrl(root_base), Store(), original, window, probe_fn=lambda *_a, **_kw: (["t1"], proof)) +assert head_mod.verify_report_window_failure(Ctrl(root_head), Store(), original, window, probe_fn=lambda *_a, **_kw: (["t1"], None)) == spec_mod.verify_report_window_failure(Ctrl(root_base), Store(), original, window, probe_fn=lambda *_a, **_kw: (["t1"], None)) +assert head_mod.build_report_quota_request(Ctrl(root_head), Store(), original, report_window=window, fallback_observe_fn=lambda _o: proof) == spec_mod.build_report_quota_request(Ctrl(root_base), Store(), original, report_window=window, fallback_observe_fn=lambda _o: proof) +bad_proof = {"turn_id": "codex-turn-1", "thread_id": "t1", "contradicted": True, "explicit_contradiction": True} +assert head_mod.verify_report_window_failure(Ctrl(root_head), Store(), original, window, probe_fn=lambda *_a, **_kw: (["t1"], bad_proof)) == spec_mod.verify_report_window_failure(Ctrl(root_base), Store(), original, window, probe_fn=lambda *_a, **_kw: (["t1"], bad_proof)) +assert head_mod.is_report_failure_contradicted(root_head, original, window) == spec_mod.is_report_failure_contradicted(root_base, original, window) is True +assert head_mod.read_retained_report_failure(root_head, original, window) == spec_mod.read_retained_report_failure(root_base, original, window) is False +print("PARITY_OK") +""" + baseline_file = tmp_path / "origin_main_rfp.py" + baseline_file.write_text(baseline_code, encoding="utf-8") + proc = subprocess.run( + [sys.executable, "-c", script, str(baseline_file), str(tmp_path)], + cwd=str(REPO_ROOT), + text=True, + capture_output=True, + ) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.strip() == "PARITY_OK" + + +def test_interleaving_durable_contradiction_prevents_window_replacement( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + window = _sample_window(tmp_path) + original = _sample_original(window) + store = _MemoryStore({("sess-1", "chat-turn-1"): original}) + controller = _FakeController(tmp_path) + folder = attempt_directory(tmp_path, window) + folder.mkdir(parents=True, exist_ok=True) + retain_report_failure( + tmp_path, store, original, window, + {"turn_id": "codex-turn-1", "thread_id": "thread-1", "only_original_user_item": True}, + ) + assert (folder / REPORT_FAILURE_PROOF).is_file() + + orig_read_record = report_failure_ledger._read_report_failure_record + triggered = False + record_reads = 0 + + def interleaved_read_record(root: Path, win: dict[str, object]) -> dict[str, object] | None: + nonlocal triggered, record_reads + record_reads += 1 + rec = orig_read_record(root, win) + if not triggered: + triggered = True + # Commit durable contradiction while generation.lock holds off attempt overwrite. + contradict_report_failure( + root, store, original, win, + {"contradicted": True, "turn_id": "codex-turn-1", "thread_id": "thread-1"}, + ) + return rec + + monkeypatch.setattr(report_failure_ledger, "_read_report_failure_record", interleaved_read_record) + monkeypatch.setattr(report_failure_proof, "_read_report_failure_record", interleaved_read_record) + + admitted = admit_cadence_window( + runtime_root=tmp_path, + goal_id="goal-1", + agent_id="agent-1", + subscription=_SAMPLE_SUBSCRIPTION, + now=datetime(2026, 1, 4, 10, tzinfo=timezone.utc), + can_replace_failed_window=lambda w: verify_report_window_failure( + controller, store, original, w, + probe_fn=lambda *_a, **_kw: (["thread-1"], None), + generation_locked=True, + ), + ) + assert triggered is True + assert record_reads == 1 + assert admitted["mutated"] is False + assert admitted["window"]["window_id"] == window["window_id"] + assert is_report_failure_contradicted(tmp_path, original, window) is True + assert read_retained_report_failure(tmp_path, original, window) is False