Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(examples): keep journal replay outside latency timing
svonava10564f889640
diff --git a/examples/agent-stage-latency/README.md b/examples/agent-stage-latency/README.mdindex f8281d29d..02b47153f 100644--- a/examples/agent-stage-latency/README.md+++ b/examples/agent-stage-latency/README.md@@ -127,10 +127,15 @@ windows inside each path. No repetitions or automatic sample extension occur.## Read the report-The journal syncs metadata and intents before dispatch, then records each-physical HTTP attempt, reply, stable error, elapsed duration and observable-SDK retry count. An SDK per-item error, malformed verdict, bad vector or-invalid ranking remains a failure. Earlier M subcalls survive a later error.+The journal syncs metadata and the complete frozen `operation_intent` before+any constituent dispatch. During that operation, a short-lock memory buffer+captures call intents, physical HTTP attempts, replies, stable errors, elapsed+durations and observable SDK retry counts. After the stage timer stops, those+snapshots are replayed in their original interleaving through the fsynced hash+chain. An `operation_result` seals the complete captured event count and is+synced before the next operation. No background writer is used. An SDK per-item+error, malformed verdict, bad vector or invalid ranking remains a failure.+Ordinary failed M operations join both paths and preserve earlier subcalls.There is no outer retry campaign: capacity waits and OOM retries are disabled.The SDK can still retry admission/model-loading responses; those attempts andtheir full elapsed time remain recorded.@@ -141,10 +146,13 @@ the total child deadline, including blocked requests and SDK retry sleeps,then stops/reaps the child. Terminal-record writing and reaping add a smallamount of cleanup time after that deadline. Discovery and client setup areoutside measured operations. Stage timing includes request building/windowing,-transport, SDK processing, caller composition/masking and journal work inside-that boundary. Constituent call timers exclude their own intent/result appends.+transport, SDK processing, reply projection/sanitization/validation, caller+composition/masking and memory event capture. Durable journal replay is outside+stage and call timing but inside the total wall budget. Constituent call timers+start after intent capture and stop after body processing and validation,+before result capture. No calibration value is subtracted from these timers.Each physical `response.headers_elapsed_s` stops at the response headers,-before consuming the body, and includes the dispatch observer's journal append.+before consuming the body; it starts after dispatch event capture.It differs from `call_result.elapsed_s`, which includes body consumption andSDK processing, and from the complete-stage `operation_result.elapsed_s`.The scorer requires the frozen next window in each M model path and checks@@ -171,11 +179,25 @@ are omitted; exact configured credentials echoed in replies are replaced byScoring validates packet/request bindings, the journal hash chain, observationand subcall identities, unique terminals, execution order and reply shapes.-It reports planned, attempted, successful, failed, unresolved and unattempted-counts per phase/stage/arm, with the fixed denominator beside latency results.+It reports planned, observed attempted, successful, failed, unresolved,+unattempted and `attempt_status_unknown` counts per phase/stage/arm, with the+fixed denominator beside latency results. A stop before or during replay can+lose replies, calls or retries that occurred. Missing call intents in a started+operation without a complete seal are attempt-status-unknown; its observed+attempt count is a lower bound when `attempted_count_exact` is false. A sealed+failed operation permits its never-started windows to be known unattempted.+Later operations without durable intent are unattempted. Physical-dispatch and+SDK-retry totals are observed lower bounds whenever their corresponding+`physical_dispatches_exact` or `sdk_retries_exact` flag is false; zero observed+does not establish zero actual activity. Completed captured call records remain+diagnostic evidence even when the operation seal is absent. Persistence errors+stop the child without sealing that operation or starting the next.Successful-operation p50/p90 and all-terminal elapsed p50/p90 are separate.Partial runs remain incomplete and nonqualifying. A missing earlier outcome-is never repaired into a better history.+is never repaired into a better history. The versioned timing/checkpoint policy+is bound into `protocol_digest` and included in the report; prepare a fresh+packet after changing the runner. Packets from earlier timing policies are+rejected, so those measurements cannot silently mix.Confirmatory comparisons use only successful, complete base-case pairs. R'stwo rule variants stay together; if any variant fails, that whole base clusterdiff --git a/examples/agent-stage-latency/protocol.py b/examples/agent-stage-latency/protocol.pyindex 3b849ff41..5ae0ca560 100644--- a/examples/agent-stage-latency/protocol.py+++ b/examples/agent-stage-latency/protocol.py@@ -63,6 +63,16 @@ SCHEMA = {WORD = re.compile(r"\w+(?:[-_]\w+)*|\S")NAME_TOKEN = re.compile(r"[^\W\d_]{3,}")M_POLICY = {"window_units": 300, "overlap": 50, "score_floor": 0.6, "model_paths": 2, "serial_windows": True}+TIMING_POLICY = {+ "version": 2,+ "clock": "perf_counter",+ "stage": "request-building-through-joined-caller-composition",+ "call": "after-intent-capture-through-body-validation",+ "headers": "after-dispatch-capture-through-response-headers",+ "checkpoint": "durable-operation-intent-buffered-events-sealed-operation-result",+ "replay": "after-stage-timer-before-next-operation",+ "unsealed_missing_calls": "attempt-status-unknown",+}PROVIDER_URLS = {"anthropic": "https://api.anthropic.com","openai": "https://api.openai.com",@@ -98,7 +108,12 @@ def source_digest() -> str:def protocol_digest() -> str:# These are behavior bindings, never endpoint eligibility requirements.- return digest({name: sha256((HERE / name).read_bytes()) for name in ("protocol.py", "prepare.py", "run.py")})+ return digest(+ {+ "timing_policy": TIMING_POLICY,+ "files": {name: sha256((HERE / name).read_bytes()) for name in ("protocol.py", "prepare.py", "run.py")},+ }+ )def safe_path(value: str) -> str:diff --git a/examples/agent-stage-latency/run.py b/examples/agent-stage-latency/run.pyindex 5f6fa755e..fb85d5f2a 100644--- a/examples/agent-stage-latency/run.py+++ b/examples/agent-stage-latency/run.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport argparseimport contextlib+import copyimport importlib.metadataimport jsonimport logging@@ -205,6 +206,37 @@ class Journal:self.output.close()+class EvidenceCaptureError(Exception):+ pass+++class OperationEvents:+ """Snapshot one operation's safe events without persistence in its timers."""++ def __init__(self) -> None:+ self.lock = threading.Lock()+ self.events: list[tuple[str, dict[str, Any]]] = []+ self.failed = False++ def append(self, event: str, **fields: Any) -> None:+ try:+ require(event in ("call_intent", "dispatch", "response", "call_result"), "Unexpected buffered event")+ captured = copy.deepcopy(fields)+ with self.lock:+ self.events.append((event, captured))+ except Exception:+ self.failed = True+ raise EvidenceCaptureError from None++ def flush(self, journal: Journal) -> None:+ # Both M paths have joined before replay. A capture or flush failure must+ # escape to the child supervisor without a misleading operation seal.+ if self.failed:+ raise EvidenceCaptureError+ for event, fields in self.events:+ journal.append(event, **fields)++def operation_identity(obs: dict[str, Any], arm: str) -> dict[str, Any]:return {k: obs[k] for k in ("observation_id", "base_id", "stage", "phase", "rule", "repetition", "arm_order")} | {"arm": arm,@@ -229,17 +261,18 @@ class TransportEvidence:self.journal = journalself.local = threading.local()- def begin(self, identity: dict[str, Any]) -> None:+ def begin(self, identity: dict[str, Any], events: OperationEvents | None = None) -> None:self.local.identity = identityself.local.dispatches = 0+ self.local.sink = events if events is not None else self.journaldef request(self, request: Any) -> None:self.local.dispatches += 1+ self.local.sink.append("dispatch", **self.local.identity, dispatch_index=self.local.dispatches)self.local.dispatched_at = time.perf_counter()- self.journal.append("dispatch", **self.local.identity, dispatch_index=self.local.dispatches)def response(self, response: Any) -> None:- self.journal.append(+ self.local.sink.append("response",**self.local.identity,dispatch_index=self.local.dispatches,@@ -455,7 +488,7 @@ class Executor:elapsed_s=time.perf_counter() - start,)- def call(self, obs: dict[str, Any], arm: str, index: int) -> Any:+ def call(self, obs: dict[str, Any], arm: str, index: int, events: OperationEvents) -> Any:from sie_sdk import Itemcall = obs["requests"][arm][index]@@ -463,8 +496,8 @@ class Executor:client_key = call["model"] if arm == "sie" else call["provider"]client = self.clients[client_key]hooks = self.evidence[client_key]- self.journal.append("call_intent", **identity)- hooks.begin(identity)+ events.append("call_intent", **identity)+ hooks.begin(identity, events)start = time.perf_counter()reply = Nonetry:@@ -495,8 +528,10 @@ class Executor:if reply.get("item_error"):raise CallFailure("ITEM_ERROR")validated = validate_reply(obs["stage"], arm, reply, obs["unit"]["data"], call)+ except (EvidenceCaptureError, MemoryError):+ raiseexcept Exception as error:- self.journal.append(+ events.append("call_result",**identity,status="failed",@@ -508,7 +543,7 @@ class Executor:execution_revision=revision(client.last_model_revision) if arm == "sie" else None,)raise CallFailure(stable_error(error).get("code", "CALL_FAILED")) from None- self.journal.append(+ events.append("call_result",**identity,status="success",@@ -523,6 +558,7 @@ class Executor:def operation(self, obs: dict[str, Any], arm: str) -> None:identity = operation_identity(obs, arm)self.journal.append("operation_intent", **identity)+ events = OperationEvents()start = time.perf_counter()result = Nonetry:@@ -532,11 +568,17 @@ class Executor:if obs["stage"] == "M" and arm == "sie":def model_path(model: str) -> list[dict[str, Any]]:- entities = []- for index, call in enumerate(expected):- if call["model"] == model:- entities.extend(self.call(obs, arm, index))- return entities+ try:+ entities = []+ for index, call in enumerate(expected):+ if call["model"] == model:+ entities.extend(self.call(obs, arm, index, events))+ return entities+ except (EvidenceCaptureError, MemoryError):+ # Another future may raise an ordinary call failure first.+ # Resource loss in either joined path forbids a seal.+ events.failed = True+ raisewith ThreadPoolExecutor(max_workers=2) as pool:futures = [pool.submit(model_path, model) for model in MODELS["M"]]@@ -544,19 +586,23 @@ class Executor:spans = compose(obs["unit"]["data"]["text"], outputs)result = {"spans": spans, "masked": masked(obs["unit"]["data"]["text"], spans)}else:- result = self.call(obs, arm, 0)+ result = self.call(obs, arm, 0, events)+ except (EvidenceCaptureError, MemoryError):+ raiseexcept Exception as error:- self.journal.append(- "operation_result",- **identity,- status="failed",- error=stable_error(error),- result=result,- elapsed_s=time.perf_counter() - start,- )- return+ outcome = {"status": "failed", "error": stable_error(error)}+ else:+ outcome = {"status": "success"}+ elapsed = time.perf_counter() - start+ events.flush(self.journal)self.journal.append(- "operation_result", **identity, status="success", result=result, elapsed_s=time.perf_counter() - start+ "operation_result",+ **identity,+ **outcome,+ result=result,+ elapsed_s=elapsed,+ evidence_sealed=True,+ captured_event_count=len(events.events),)def close(self) -> None:diff --git a/examples/agent-stage-latency/score.py b/examples/agent-stage-latency/score.pyindex 67139c847..57be0fcd5 100644--- a/examples/agent-stage-latency/score.py+++ b/examples/agent-stage-latency/score.py@@ -13,7 +13,7 @@ from typing import Anyfrom fetch import write_exclusivefrom prepare import load_packet-from protocol import MODELS, compose, digest, masked, positive, require, sha256, validate_reply+from protocol import MODELS, TIMING_POLICY, compose, digest, masked, positive, require, sha256, validate_replyfrom run import operation_identity, subcall_identity@@ -129,16 +129,21 @@ def read_journal(path: Path, packet: dict[str, Any]) -> tuple[list[dict[str, Anyreturn rows, end, truncated-def accounting(keys: list[Any], intents: dict[Any, Any], outcomes: dict[Any, Any]) -> dict[str, Any]:+def accounting(+ keys: list[Any], intents: dict[Any, Any], outcomes: dict[Any, Any], unknown: set[Any] | None = None+) -> dict[str, Any]:+ unknown = unknown or set()terminal = [outcomes[k] for k in keys if k in outcomes]successful = [r for r in terminal if r["status"] == "success"]return {"planned": len(keys),"attempted": sum(k in intents for k in keys),+ "attempted_count_exact": not any(k in unknown for k in keys),"successful": len(successful),"failed": len(terminal) - len(successful),"unresolved": sum(k in intents and k not in outcomes for k in keys),- "unattempted": sum(k not in intents for k in keys),+ "unattempted": sum(k not in intents and k not in unknown for k in keys),+ "attempt_status_unknown": sum(k in unknown for k in keys),"successful_operation_latency": elapsed_summary([r["elapsed_s"] for r in successful]),"all_terminal_attempt_elapsed": elapsed_summary([r["elapsed_s"] for r in terminal]),"failures": [@@ -184,6 +189,7 @@ def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:active_calls = set()next_in_path: dict[tuple[str, str, str], int] = defaultdict(int)failed_paths = set()+ captured_counts: dict[tuple[str, str], int] = defaultdict(int)for row in rows[1:]:event = row["event"]if event in ("discovery_intent", "discovery_result"):@@ -225,6 +231,12 @@ def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:row["status"] in ("success", "failed") and positive(row["elapsed_s"]),"Invalid operation duration/status",)+ require(+ row.get("evidence_sealed") is True+ and type(row.get("captured_event_count")) is int+ and row["captured_event_count"] == captured_counts[key],+ "Missing or incomplete operation evidence seal",+ )if row["status"] == "failed":require(isinstance(row.get("error"), dict), "Missing failure evidence")expected_calls = [@@ -297,6 +309,7 @@ def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:)op_key = (row["observation_id"], row["arm"])require(active_operation == op_key, "Subcall outside its operation")+ captured_counts[op_key] += 1if event == "call_intent":require(cid not in call_intents, "Duplicate call intent")obs, identity = calls[cid]@@ -352,7 +365,7 @@ def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:call_results[cid] = rowactive_calls.remove(cid)elif event == "dispatch":- require(cid == "metadata" or cid in active_calls, "Dispatch before durable intent")+ require(cid == "metadata" or cid in active_calls, "Dispatch before captured call intent")require(row["dispatch_index"] == len(dispatches[cid]) + 1, "Physical dispatch sequence differs")require(len(dispatches[cid]) == len(responses[cid]), "Overlapping physical retries")dispatches[cid].append(row)@@ -381,6 +394,7 @@ def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:"schema": 1,"packet_digest": packet["packet_digest"],"protocol_digest": packet["protocol_digest"],+ "timing_policy": TIMING_POLICY,"complete": complete,"qualifying_confirmatory": complete and config["phase"] == "confirmatory","ending": end,@@ -388,7 +402,7 @@ def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:"discovery": discovery_result,"discovery_attempted": discovery_intent is not None,"discovery_unresolved": discovery_intent is not None and discovery_result is None,- "statistics_scope": "client wall time; successful complete base-case pairs, independent stages",+ "statistics_scope": "client operation time excluding journal replay; successful complete base-case pairs","phases": {},"stages": {},}@@ -409,14 +423,25 @@ def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:if obs["stage"] == stage and obs["phase"] == phase and identity["arm"] == arm]summary = accounting(op_keys, op_intents, op_results)- summary["semantic_calls"] = accounting(call_keys, call_intents, call_results)+ unknown_calls = {+ cid+ for cid in call_keys+ if cid not in call_intents+ and (calls[cid][1]["observation_id"], arm) in op_intents+ and (calls[cid][1]["observation_id"], arm) not in op_results+ }+ summary["semantic_calls"] = accounting(call_keys, call_intents, call_results, unknown_calls)summary["semantic_calls"]["successful_call_latency"] = summary["semantic_calls"].pop("successful_operation_latency")summary["physical_dispatches"] = sum(len(dispatches[cid]) for cid in call_keys)+ summary["physical_dispatches_exact"] = all(+ key not in op_intents or key in op_results for key in op_keys+ )summary["sdk_retries"] = sum(call_results[cid]["sdk_retry_count"] for cid in call_keys if cid in call_results)+ summary["sdk_retries_exact"] = summary["physical_dispatches_exact"]result["phases"][phase][stage][arm] = summaryif phase != "confirmatory":continuediff --git a/examples/agent-stage-latency/tests/test_example.py b/examples/agent-stage-latency/tests/test_example.pyindex 736466f7d..038a8c3c9 100644--- a/examples/agent-stage-latency/tests/test_example.py+++ b/examples/agent-stage-latency/tests/test_example.py@@ -13,8 +13,10 @@ import sysimport threadingimport timefrom collections import Counter+from concurrent.futures import Futurefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path+from types import SimpleNamespacefrom typing import Anyimport msgpack@@ -106,6 +108,117 @@ def rechain(path: Path, rows: list[dict[str, Any]], *, total_elapsed_s: float |end_path.write_bytes(protocol.canonical(end) + b"\n")+def diagnostic_journal(path: Path, packet: dict[str, Any]) -> run.Journal:+ journal = run.Journal(path, packet, [], create=True)+ settings = packet["config"]+ journal.append(+ "run_start",+ wall_limit_s=settings["wall_limit_s"],+ placement_label=settings["placement_label"],+ timeout_budgets_s={k: settings["request_timeout_s"] for k in ("connect", "read", "provision")},+ )+ journal.append("discovery_intent", call_id="metadata")+ journal.append("discovery_result", call_id="metadata", status="success", models=[], elapsed_s=0.001)+ return journal+++def diagnostic_end(path: Path, packet: dict[str, Any], reason: str) -> None:+ end = {k: packet[k] for k in ("packet_digest", "protocol_digest", "source_digest")} | {+ "reason": reason,+ "journal_digest": protocol.sha256(path.read_bytes()),+ "elapsed_s": 1.0,+ "child_exitcode": -15 if reason == "interrupted" else 0,+ }+ fetch.write_exclusive(path.with_name(path.name + ".end.json"), end | {"end_digest": protocol.digest(end)})+++def synthetic_executor(packet: dict[str, Any], journal: run.Journal, advance: Any = lambda _: None) -> run.Executor:+ """Exercise actual calls, hooks and composition without a socket or inference."""+ executor = object.__new__(run.Executor)+ executor.packet, executor.journal = packet, journal+ executor.config = {"deadline": time.monotonic() + 60}+ executor.clients, executor.evidence = {}, {}++ class Client:+ last_retry_count = 0+ last_model_revision = "a" * 64++ def __init__(self, model: str, hooks: run.TransportEvidence) -> None:+ self.model, self.hooks = model, hooks++ def invoke(self, reply: dict[str, Any]) -> dict[str, Any]:+ assert journal_rows(journal.path)[-1]["event"] == "operation_intent"+ self.hooks.request(None)+ advance(1)+ self.hooks.response(SimpleNamespace(status_code=200, headers={"X-SIE-Model-Revision": "a" * 64}))+ advance(2)+ return {"model": self.model, **reply}++ def encode(self, *args: Any, **kwargs: Any) -> dict[str, Any]:+ return self.invoke({"dense": [0.125] * 2560})++ def extract(self, *args: Any, **kwargs: Any) -> dict[str, Any]:+ return self.invoke({"entities": []})++ def close(self) -> None:+ pass++ for stage in packet["config"]["stages"]:+ for model in protocol.MODELS[stage]:+ hooks = run.TransportEvidence(journal)+ executor.evidence[model] = hooks+ executor.clients[model] = Client(model, hooks)+ return executor+++def checkpoint_worker(packet_path: Path, journal_path: Path, connection: Any, checkpoint: str) -> None:+ """Pause at an acknowledged boundary so the parent can really terminate us."""+ packet = prepare.load_packet(packet_path)+ journal = run.Journal(journal_path, packet, [])+ executor = synthetic_executor(packet, journal)++ def pause() -> None:+ connection.send(checkpoint)+ connection.recv()++ original_capture, original_append = run.OperationEvents.append, journal.append++ def capture(events: run.OperationEvents, event: str, **fields: Any) -> None:+ original_capture(events, event, **fields)+ if checkpoint == "after_response" and event == "response":+ pause()++ def append(event: str, **fields: Any) -> None:+ if checkpoint == "partial_flush" and event == "response":+ journal.output.write(b'{"partial":')+ journal.output.flush()+ os.fsync(journal.output.fileno())+ pause()+ original_append(event, **fields)+ if (checkpoint, event) in {+ ("after_intent", "operation_intent"),+ ("mid_flush", "call_intent"),+ ("after_seal", "operation_result"),+ }:+ pause()++ original_result = Future.result++ def result(future: Any, *args: Any, **kwargs: Any) -> Any:+ value = original_result(future, *args, **kwargs)+ if checkpoint == "after_m_path":+ pause()+ return value++ with pytest.MonkeyPatch.context() as patch:+ patch.setattr(run.OperationEvents, "append", capture)+ patch.setattr(journal, "append", append)+ patch.setattr(Future, "result", result)+ if checkpoint == "before_flush":+ patch.setattr(run.OperationEvents, "flush", lambda *_: pause())+ executor.operation(packet["observations"][0], "sie")++class FakeServer:def __init__(self,@@ -198,8 +311,8 @@ class FakeServer:})rows = journal_rows(fixture.journal)- if not any(r["event"] == "call_intent" for r in rows):- fixture.errors.append("Server observed dispatch before a durable intent")+ if not any(r["event"] == "operation_intent" for r in rows):+ fixture.errors.append("Server observed dispatch before a durable operation intent")fixture.observed.set()try:if fixture.delay:@@ -672,6 +785,8 @@ def test_long_m_partial_success_and_no_outer_retry(tmp_path: Path) -> None:arm = report["stages"]["M"]["accounting"]["sie"]assert not report["complete"] and arm["planned"] == arm["failed"] == 1assert arm["semantic_calls"]["unattempted"] == 1 and arm["semantic_calls"]["successful"] == 4+ assert arm["semantic_calls"]["attempt_status_unknown"] == 0 and arm["semantic_calls"]["attempted_count_exact"]+ assert arm["physical_dispatches_exact"] and arm["sdk_retries_exact"]@pytest.mark.parametrize("with_auth,catalog_status", [(False, 200), (True, 200), (False, 404), (False, 501)])@@ -744,17 +859,23 @@ def test_wall_deadline_reaps_child_and_preserves_unresolved_intent(tmp_path: Patstart = time.monotonic()assert run.run_trial(path, journal, server.url, {}, execute=True) == "deadline"assert time.monotonic() - start < 2.5 and server.observed.is_set()+ actual_dispatches = len(server.captures)assert {p.pid for p in multiprocessing.active_children()} == beforereport = score.score_trial(path, journal)assert not report["complete"] and report["ending"]["reason"] == "deadline"arm = report["stages"]["E"]["accounting"]["sie"]assert arm["unresolved"] + arm["failed"] == 1calls = arm["semantic_calls"]- assert calls["failed"] + calls["unresolved"] == 1 and calls["successful"] == 0- if loading_sleep:- assert any(row["event"] == "response" and row["status"] == 503 for row in journal_rows(journal))- else:- assert calls["unresolved"] == 1+ assert calls["failed"] + calls["unresolved"] + calls["attempt_status_unknown"] == 1+ assert calls["successful"] == 0+ assert calls["unattempted"] == 0+ assert calls["attempted"] + calls["attempt_status_unknown"] == 1+ assert arm["physical_dispatches"] <= actual_dispatches+ assert arm["physical_dispatches_exact"] == arm["sdk_retries_exact"] == (arm["unresolved"] == 0)+ if arm["physical_dispatches_exact"]:+ assert arm["physical_dispatches"] == actual_dispatches+ if not calls["attempted"]:+ assert calls["attempt_status_unknown"] == 1 and arm["physical_dispatches"] == arm["sdk_retries"] == 0@pytest.mark.parametrize("code,expected", [("WALL_DEADLINE", "deadline"), ("CALL_FAILED", "child_failure")])@@ -874,7 +995,8 @@ def test_interrupt_preserves_intent_and_reaps_child(tmp_path: Path, monkeypatch:assert {p.pid for p in multiprocessing.active_children()} == beforereport = score.score_trial(path, journal)assert not report["complete"] and report["ending"]["reason"] == "interrupted"- assert report["stages"]["E"]["accounting"]["sie"]["semantic_calls"]["unresolved"] == 1+ calls = report["stages"]["E"]["accounting"]["sie"]["semantic_calls"]+ assert calls["attempt_status_unknown"] == 1 and calls["unresolved"] == calls["unattempted"] == 0def test_truncated_tail_and_terminal_binding(tmp_path: Path) -> None:@@ -1054,6 +1176,7 @@ def long_m_history(tmp_path: Path) -> tuple[Path, Path, list[dict[str, Any]], lidef replace_m_calls(rows: list[dict[str, Any]], calls: list[dict[str, Any]]) -> list[dict[str, Any]]:begin = next(i for i, row in enumerate(rows) if row["event"] == "operation_intent")end = next(i for i, row in enumerate(rows) if row["event"] == "operation_result")+ rows[end]["captured_event_count"] = len(calls)return rows[: begin + 1] + calls + rows[end:]@@ -1286,6 +1409,281 @@ def test_offline_cli_help_and_opt_in_error(tmp_path: Path) -> None:assert "API_KEY" not in result.stdout + result.stderr+def test_persistence_is_outside_timers_but_inside_wall_budget(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _, packet = packet_file(tmp_path, stages=["E"], n=1, arms="sie")+ path = tmp_path / "timing.jsonl"+ journal = diagnostic_journal(path, packet)+ clock = {"now": 1.0}++ def advance(seconds: float) -> None:+ clock["now"] += seconds++ monkeypatch.setattr(run.time, "perf_counter", lambda: clock["now"])+ monkeypatch.setattr(run.time, "monotonic", lambda: clock["now"])+ original_append, original_capture = journal.append, run.OperationEvents.append+ persisted = []++ def append(event: str, **fields: Any) -> None:+ original_append(event, **fields)+ advance(100)+ persisted.append(event)++ def capture(events: run.OperationEvents, event: str, **fields: Any) -> None:+ original_capture(events, event, **fields)+ advance(0.25)++ monkeypatch.setattr(journal, "append", append)+ monkeypatch.setattr(run.OperationEvents, "append", capture)+ executor = synthetic_executor(packet, journal, advance)+ executor.config["deadline"] = clock["now"] + 600+ executor.operation(packet["observations"][0], "sie")+ journal.close()+ rows = journal_rows(path)+ operation = rows[-1]+ assert operation["evidence_sealed"] and operation["captured_event_count"] == 4+ assert operation["elapsed_s"] == 4.0+ assert next(r for r in rows if r["event"] == "call_result")["elapsed_s"] == 3.5+ assert next(r for r in rows if r["event"] == "response")["headers_elapsed_s"] == 1.0+ assert persisted == ["operation_intent", "call_intent", "dispatch", "response", "call_result", "operation_result"]+ assert clock["now"] == 605.0+ with pytest.raises(run.CallFailure, match="WALL_DEADLINE"):+ executor.remaining()+++def test_m_buffer_preserves_interleaving_without_serializing_paths(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ packet_path, packet = packet_file(tmp_path, long=True, stages=["M"], n=1, arms="sie")+ path = tmp_path / "interleaving.jsonl"+ journal = diagnostic_journal(path, packet)+ barrier = threading.Barrier(2)+ captured = []+ original_flush = run.OperationEvents.flush+ original_append = journal.append++ def advance(seconds: float) -> None:+ if seconds == 1:+ barrier.wait(timeout=3)++ def flush(events: run.OperationEvents, target: run.Journal) -> None:+ captured.extend(events.events)+ original_flush(events, target)++ def append(event: str, **fields: Any) -> None:+ assert threading.current_thread() is threading.main_thread(), "M worker persisted during measured work"+ original_append(event, **fields)++ monkeypatch.setattr(run.OperationEvents, "flush", flush)+ monkeypatch.setattr(journal, "append", append)+ executor = synthetic_executor(packet, journal, advance)+ executor.operation(packet["observations"][0], "sie")+ journal.close()+ diagnostic_end(path, packet, "finished")+ rows = journal_rows(path)+ replayed = rows[4:-1]+ assert len(captured) == len(replayed) == 24+ for (event, fields), row in zip(captured, replayed, strict=True):+ assert event == row["event"] and all(row[k] == value for k, value in fields.items())+ for model in protocol.MODELS["M"]:+ ordered = [r for r in replayed if r["model"] == model and r["event"] in ("call_intent", "call_result")]+ assert [r["event"] for r in ordered] == ["call_intent", "call_result"] * 3+ assert [r["window"] for r in ordered] == [0, 0, 1, 1, 2, 2]+ report = score.score_trial(packet_path, path)+ counts = report["stages"]["M"]["accounting"]["sie"]+ assert report["complete"] and counts["physical_dispatches_exact"] and counts["sdk_retries_exact"]+ assert counts["semantic_calls"]["successful"] == 6+++def test_buffer_snapshots_nested_values_and_redacts_before_persistence(tmp_path: Path) -> None:+ _, packet = packet_file(tmp_path, stages=["E"], n=1, arms="sie")+ path = tmp_path / "snapshot.jsonl"+ journal = run.Journal(path, packet, ["fake-auth-sentinel"], create=True)+ events = run.OperationEvents()+ reply = {"text": "fake-auth-sentinel", "usage": {"input_tokens": 3}, "dense": [0.5]}+ identity = {"arm_order": ["sie", "rival"]}+ events.append("call_result", reply=reply, **identity, sdk_retry_count=1, execution_revision="a" * 64)+ reply["usage"]["input_tokens"] = 99+ reply["dense"][0] = 99.0+ identity["arm_order"].reverse()+ events.flush(journal)+ journal.close()+ row = journal_rows(path)[0]+ assert row["reply"] == {"text": "[REDACTED_CREDENTIAL]", "usage": {"input_tokens": 3}, "dense": [0.5]}+ assert row["arm_order"] == ["sie", "rival"] and row["sdk_retry_count"] == 1+ assert "fake-auth-sentinel" not in path.read_text()+++ "checkpoint,stage,attempted,unknown,physical",+ [+ ("after_intent", "E", 0, 1, 0),+ ("after_response", "E", 0, 1, 0),+ ("after_m_path", "M", 0, 6, 0),+ ("before_flush", "M", 0, 6, 0),+ ("mid_flush", "M", 1, 5, 0),+ ("partial_flush", "E", 1, 0, 1),+ ("after_seal", "E", 1, 0, 1),+ ],+)+def test_real_termination_preserves_only_durable_checkpoints(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ checkpoint: str,+ stage: str,+ attempted: int,+ unknown: int,+ physical: int,+) -> None:+ # Pytest importlib mode does not otherwise expose this namespace module to spawn.+ monkeypatch.syspath_prepend(str(HERE.parents[1]))+ packet_path, packet = packet_file(tmp_path, long=stage == "M", stages=[stage], n=2, arms="sie")+ path = tmp_path / "stopped.jsonl"+ diagnostic_journal(path, packet).close()+ context = multiprocessing.get_context("spawn")+ parent, child = context.Pipe()+ process = context.Process(target=checkpoint_worker, args=(packet_path, path, child, checkpoint))+ try:+ process.start()+ child.close()+ assert parent.poll(10) and parent.recv() == checkpoint+ process.terminate()+ process.join(3)+ assert not process.is_alive()+ finally:+ if process.is_alive():+ process.kill()+ process.join()+ parent.close()+ child.close()+ diagnostic_end(path, packet, "interrupted")+ report = score.score_trial(packet_path, path)+ counts = report["stages"][stage]["accounting"]["sie"]+ calls = counts["semantic_calls"]+ assert not report["complete"] and not report["qualifying_confirmatory"]+ assert counts["planned"] == 2 and counts["unattempted"] == 1+ assert calls["planned"] == packet["planned_semantic_calls"][stage]["sie"]+ assert calls["attempted"] == attempted and calls["attempt_status_unknown"] == unknown+ assert calls["attempted_count_exact"] == (unknown == 0)+ assert counts["physical_dispatches"] == physical and counts["sdk_retries"] == 0+ assert counts["physical_dispatches_exact"] == counts["sdk_retries_exact"] == (checkpoint == "after_seal")+ assert calls["planned"] == sum(+ calls[k] for k in ("successful", "failed", "unresolved", "unattempted", "attempt_status_unknown")+ )+ if checkpoint == "after_seal":+ assert counts["successful"] == calls["successful"] == calls["unattempted"] == 1+ else:+ assert counts["unresolved"] == 1 and counts["successful_operation_latency"]["count"] == 0+ assert calls["successful"] == calls["failed"] == 0+ assert (report["truncated_tail_sha256"] is not None) == (checkpoint == "partial_flush")++[email protected]("failure", ["capture", "flush", "m_memory"])+def test_observer_failure_stops_child_without_seal_or_next_operation(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: str+) -> None:+ stage = "M" if failure == "m_memory" else "E"+ packet_path, packet = packet_file(tmp_path, stages=[stage], n=2, arms="sie")+ path = tmp_path / "observer-failure.jsonl"+ diagnostic_journal(path, packet).close()+ original_journal = run.Journal++ class FailingJournal(original_journal):+ def append(self, event: str, **fields: Any) -> None:+ if failure == "flush" and event == "dispatch":+ self.output.write(b'{"partial":')+ self.output.flush()+ os.fsync(self.output.fileno())+ raise OSError("synthetic persistence failure")+ super().append(event, **fields)++ class Executor(run.Executor):+ def __init__(self, packet: dict[str, Any], journal: run.Journal, config: dict[str, Any]) -> None:+ self.__dict__.update(synthetic_executor(packet, journal).__dict__)+ if failure == "m_memory":++ def ordinary_failure(*args: Any, **kwargs: Any) -> Any:+ raise run.CallFailure("CALL_FAILED")++ def memory_failure(*args: Any, **kwargs: Any) -> Any:+ raise MemoryError++ monkeypatch.setattr(self.clients[protocol.MODELS["M"][0]], "extract", ordinary_failure)+ monkeypatch.setattr(self.clients[protocol.MODELS["M"][1]], "extract", memory_failure)++ def discover(self) -> None:+ pass++ class Connection:+ messages: list[str] = []++ def recv(self) -> dict[str, Any]:+ return {"packet_path": str(packet_path), "journal": str(path), "credentials": {}}++ def send(self, message: str) -> None:+ self.messages.append(message)++ def close(self) -> None:+ pass++ original_capture = run.OperationEvents.append++ def capture(events: run.OperationEvents, event: str, **fields: Any) -> None:+ if failure == "capture" and event == "response":+ events.failed = True+ raise run.EvidenceCaptureError+ original_capture(events, event, **fields)++ monkeypatch.setattr(run, "Journal", FailingJournal)+ monkeypatch.setattr(run, "Executor", Executor)+ monkeypatch.setattr(run.OperationEvents, "append", capture)+ connection = Connection()+ run.child_main(connection)+ assert connection.messages == ["child_failure"]+ rows = journal_rows(path)+ assert sum(r["event"] == "operation_intent" for r in rows) == 1+ assert not any(r["event"] == "operation_result" for r in rows)+ diagnostic_end(path, packet, "child_failure")+ report = score.score_trial(packet_path, path)+ assert not report["complete"]+ assert report["stages"][stage]["accounting"]["sie"]["unattempted"] == 1++[email protected]("change", ["missing", "count", "premature"])+def test_invalid_evidence_seals_are_rejected(+ long_m_history: tuple[Path, Path, list[dict[str, Any]], list[list[dict[str, Any]]]], change: str+) -> None:+ packet_path, path, rows, _ = long_m_history+ terminal = next(r for r in rows if r["event"] == "operation_result")+ if change == "missing":+ terminal.pop("evidence_sealed")+ elif change == "count":+ terminal["captured_event_count"] -= 1+ else:+ rows.remove(terminal)+ terminal.update(status="failed", result=None, error={"code": "CALL_FAILED"})+ at = next(i for i, r in enumerate(rows) if r["event"] == "call_result")+ rows.insert(at, terminal)+ rechain(path, rows)+ with pytest.raises(ValueError, match="seal|operation terminal"):+ score.score_trial(packet_path, path)+++def test_old_timing_binding_is_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ path, packet = packet_file(tmp_path, stages=["E"], n=1, arms="sie")+ current = protocol.protocol_digest()+ legacy = protocol.digest(+ {name: protocol.sha256((HERE / name).read_bytes()) for name in ("protocol.py", "prepare.py", "run.py")}+ )+ assert legacy != current+ packet["protocol_digest"] = legacy+ packet["packet_digest"] = protocol.digest({k: v for k, v in packet.items() if k != "packet_digest"})+ path.write_bytes(protocol.canonical(packet))+ with pytest.raises(ValueError, match="protocol binding"):+ prepare.load_packet(path)+ monkeypatch.setitem(protocol.TIMING_POLICY, "version", 1)+ assert protocol.protocol_digest() != current++def test_source_templates_match_builders_and_no_external_runtime_defaults() -> None:sources = protocol.sources()assert len(sources["files"]) == 9