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
feat(examples): add bounded agent stage latency trials
svonava2326f19b2b9a
diff --git a/examples/agent-stage-latency/.gitignore b/examples/agent-stage-latency/.gitignorenew file mode 100644index 000000000..f04da9734--- /dev/null+++ b/examples/agent-stage-latency/.gitignore@@ -0,0 +1,4 @@+/inputs/+/packets/+/runs/+/reports/diff --git a/examples/agent-stage-latency/README.md b/examples/agent-stage-latency/README.mdnew file mode 100644index 000000000..767930087--- /dev/null+++ b/examples/agent-stage-latency/README.md@@ -0,0 +1,200 @@+# Measure four independent agent stages++Prepare a fixed set of public requests, explicitly run it on any SIE HTTP(S)+endpoint, and score client wall times offline. The four stages are independent+workloads. This example measures each stage; it does not measure a full agent+turn or establish quality parity on a new endpoint.++| Stage | SIE operation | Paired rival | Frozen public workload |+| --- | --- | --- | --- |+| G: guardrails | Qwen3Guard 4B, `chat_completions`, raw user text, temperature 0, 64 output tokens | Haiku 4.5, exact short-verdict user prompt, temperature 0, 10 output tokens, no thinking | Human-labelled ToxicChat and Aegis test prompts from [guardrails](../guardrails) |+| M: caller masking | GLiNER PII + NuNER Zero, `extract`, 36 ordered labels, 300-unit windows/50 overlap, score ≥ 0.6, union, name propagation and bracket masking | Haiku 4.5, recorded PII system prompt and JSON schema, temperature 0, 4096 output tokens, no thinking; exact mentions mapped and masked in the caller | 660 frozen Gretel English documents from [redact](../redact) |+| E: one-query embedding | Qwen3-Embedding 4B, one `Item`, `is_query=True`, dense 2560 dimensions | OpenAI `text-embedding-3-large`, one raw input string, float encoding, 3072 dimensions | 440 held-out questions from [lookalike-search](../lookalike-search); no corpus encoding or retrieval |+| R: reranking | Qwen3-Reranker 4B, `score`, one question and all 20 candidates in their original order; both w2 rules as `instruction` | Cohere `rerank-v4.0-pro`, `Instruction: {rule}\nQuery: {question}`, all 20 documents | 499 frozen questions from [rerank](../rerank), each with final-rule and proposed-rule requests |++[sources.json](sources.json) pins exactly nine files to immutable public+Hugging Face revisions, byte counts and SHA-256 hashes: four evidence+manifests, three evidence input files, and the two guardrails source files.+It also records the request templates and their canonical digests. Downloads+are anonymous. No recorded vectors or rival replies are needed for timing.+ToxicChat is CC-BY-NC-4.0, Aegis is CC-BY-4.0, Gretel is Apache-2.0, and the+rerank evidence records Apache-2.0/public-domain Federal Register provenance.+Embedding-question provenance and source terms are linked in `sources.json`.+Downloaded workload text can contain harmful prompts and synthetic personal+data; these remain workload inputs.++Cohere's historical HTTP body/API version was not retained. This new trial+uses the [documented v2 rerank request](https://docs.cohere.com/v2/reference/rerank)+with explicit `top_n=20` and `max_tokens_per_doc=4096`. The historical redaction+409 ms figure timed two concurrent whole-document extractions. The windowed,+composed masking operation here is a new measurement.++## Run from the repository root++Use the locked workspace SDK and managed tools. Fetch, prepare and score use+only Python's standard library and require no API keys. A localhost SIE+endpoint can run without authentication.++```sh+mise exec -- uv sync --frozen --no-dev --package sie-sdk++mise exec -- python examples/agent-stage-latency/fetch.py \+ --out examples/agent-stage-latency/inputs/trial-1++mise exec -- python examples/agent-stage-latency/prepare.py \+ --inputs examples/agent-stage-latency/inputs/trial-1 \+ --out examples/agent-stage-latency/packets/trial-1.json \+ --phase confirmatory --n 8 --warmup 1 --seed 20261004 \+ --stages G M E R --arms sie \+ --request-timeout 30 --wall-limit 900 --placement-label local-demo++mise exec -- python -m json.tool examples/agent-stage-latency/packets/trial-1.json++mise exec -- uv run --frozen --project . --no-sync --package sie-sdk python \+ examples/agent-stage-latency/run.py \+ --packet examples/agent-stage-latency/packets/trial-1.json \+ --out examples/agent-stage-latency/runs/trial-1.jsonl \+ --sie-base-url http://127.0.0.1:8000 --execute++mise exec -- python examples/agent-stage-latency/score.py \+ --packet examples/agent-stage-latency/packets/trial-1.json \+ --journal examples/agent-stage-latency/runs/trial-1.jsonl \+ --out examples/agent-stage-latency/reports/trial-1.json+```++The illustrative `n=8` is not a statistical recommendation. Before a+confirmatory run, externally choose and freeze n, seed, stages/order, phase,+arm mode, placement label and timing budgets. The placement label must be a+nonsecret name using letters, digits, dots, underscores or hyphens. Supply the+actual endpoint with `--sie-base-url` or `SIE_BASE_URL`; there is no default+endpoint. `SIE_API_KEY` is optional and is passed explicitly to this origin.+URLs with userinfo, query strings or fragments are rejected.++For paired runs prepare with `--arms paired`. Only selected rivals need their+credentials: `ANTHROPIC_API_KEY` for G/M, `OPENAI_API_KEY` for E and+`COHERE_API_KEY` for R. Missing selected credentials fail before inference.+Set keys through your environment, never in packets or command arguments.+Preparation and scoring never contact these providers. Running without+`--execute` fails before constructing a client.++Every output destination must be fresh, including an empty existing download+directory. The example never replaces inputs, packets, journals or reports.+The runner creates `trial-1.jsonl.end.json` beside its journal. Preserve both+files: the exclusive terminal record binds the full journal bytes to the+packet, including any partial final line left by a deadline or interrupt.++## Pilot and disjoint confirmation++A separately prepared pilot can inform an externally selected confirmatory n.+Use a fresh output and exclude the whole earlier packet, including its+warmups. `--exclude-packet` prevents selecting those base identities or semantic+inputs again. Reusing a seed alone does not exclude earlier requests. Multiple+`--exclude-packet` arguments are supported; include every prior packet in this+study.++```sh+mise exec -- python examples/agent-stage-latency/prepare.py \+ --inputs examples/agent-stage-latency/inputs/trial-1 \+ --out examples/agent-stage-latency/packets/pilot-1.json \+ --phase pilot --n 4 --warmup 1 --seed 20261004 \+ --stages G M E R --arms paired \+ --request-timeout 30 --wall-limit 900 --placement-label local-demo++mise exec -- python examples/agent-stage-latency/prepare.py \+ --inputs examples/agent-stage-latency/inputs/trial-1 \+ --out examples/agent-stage-latency/packets/confirm-1.json \+ --exclude-packet examples/agent-stage-latency/packets/pilot-1.json \+ --phase confirmatory --n 16 --warmup 1 --seed 20261004 \+ --stages G M E R --arms paired \+ --request-timeout 30 --wall-limit 1800 --placement-label local-demo+```++Run and score each with its own packet/journal paths using the commands above.+Never extend n by repeatedly inspecting ordinary confidence intervals. If n+exceeds the remaining distinct population, preparation fails before inference.++n counts base evidence units per selected stage. R creates two observations+per question; M creates one extraction per model per window, with no redundant+whole-document call for long texts. The packet prints exact planned semantic+call counts, persists every envelope/window/offset and freezes within-case arm+order using the seed. Cases and paired arms execute serially. M alone runs two+concurrent model paths, with a separate client for each model and serial+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.+There is no outer retry campaign: capacity waits and OOM retries are disabled.+The SDK can still retry admission/model-loading responses; those attempts and+their full elapsed time remain recorded.++One declared request timeout sets the connect/read/provision component budgets.+The remaining wall budget caps call budgets. A parent-owned process enforces+the total child deadline, including blocked requests and SDK retry sleeps,+then stops/reaps the child. Terminal-record writing and reaping add a small+amount of cleanup time after that deadline. Discovery and client setup are+outside 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.++Only selected model names, dimensions and safe revision digests are retained+from metadata discovery. Catalog `weights_revision` and response+`execution_revision` are separate fields; the latter may be a gateway bundle+digest. Different or missing revisions are accepted and reported. Responses+also retain model IDs and execution identity/binding digests when supplied.+New endpoint timing does not reproduce historical quality or deployment+identity. Auth headers, arbitrary catalog telemetry and exception messages+are omitted; exact configured credentials echoed in replies are replaced by+`[REDACTED_CREDENTIAL]`.++Scoring validates packet/request bindings, the journal hash chain, observation+and 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.+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.++Confirmatory comparisons use only successful, complete base-case pairs. R's+two rule variants stay together; if any variant fails, that whole base cluster+is excluded. Warmup and pilot observations never enter the estimate. At least+two complete base clusters are required. A seeded paired percentile bootstrap+resamples entire base clusters and estimates `rival median - SIE median` in+seconds and `rival median / SIE median`; a ratio above one favors SIE. Defaults+are 5000 resamples and seed 1729, both frozen in the packet, with linear+quantiles at `(n-1)p`. Excluded pairs/clusters and failure counts accompany+each interval. SIE-only packets have no paired rival estimate.++The paired report also includes each arm's absolute median and its 95%+percentile interval from those same paired base-cluster resamples. These use+the complete paired cohort, distinct from each arm's all-successful p50/p90.+`qualifying` means the run is complete and its comparison is statistically+estimable under this protocol; it does not mean a latency, quality or power+objective was met. No target or win rule is imposed by this example.++Interpret stages independently because their cohorts and placements differ.+Any arithmetic combination is a **sum of stage medians**, with those limits;+it is not a measured median full agent turn, model-compute latency, throughput,+quality parity or cost optimization.++## Validate without inference++After the locked SDK and root dev tools are installed, run from the repository+root. Tests use tiny embedded fixtures and localhost fake HTTP servers; no+weights or paid providers are contacted.++```sh+mise exec -- uv run --frozen --project . --no-sync ruff format --check examples/agent-stage-latency+mise exec -- uv run --frozen --project . --no-sync ruff check --select E,F,I,UP,B examples/agent-stage-latency+mise exec -- uv run --frozen --project . --no-sync ty check examples/agent-stage-latency+mise exec -- uv run --frozen --project . --no-sync pytest -c pyproject.toml -q examples/agent-stage-latency/tests+```++Canonical identities use UTF-8 JSON with sorted keys, compact separators,+unescaped Unicode, no NaN and no newline. Digest fields hash the object before+their own insertion. The packet binds source pins and the checked-in protocol,+preparation and execution code. Retain that code revision to regenerate+byte-identical packets and score an earlier run.diff --git a/examples/agent-stage-latency/fetch.py b/examples/agent-stage-latency/fetch.pynew file mode 100644index 000000000..a31baf8e4--- /dev/null+++ b/examples/agent-stage-latency/fetch.py@@ -0,0 +1,106 @@+"""Anonymously fetch exactly nine pinned public files; never replace previous inputs."""++from __future__ import annotations++import argparse+import json+import os+import shutil+import urllib.request+from pathlib import Path+from typing import Any++from protocol import canonical, digest, require, safe_path, sha256, sources+++def write_exclusive(path: Path, value: Any) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("xb") as output:+ output.write(canonical(value) + b"\n")+ output.flush()+ os.fsync(output.fileno())+++def verify_inputs(root: Path, catalog: dict[str, Any] | None = None) -> dict[str, bytes]:+ catalog = sources() if catalog is None else catalog+ marker = json.loads((root / "verified.json").read_bytes())+ require(marker == {"source_digest": digest(catalog)}, "Wrong input source marker")+ files: dict[str, bytes] = {}+ for entry in catalog["files"]:+ name = safe_path(entry["path"])+ require(name not in files, "Duplicate allowlist file")+ body = (root / name).read_bytes()+ require(len(body) == entry["bytes"] and sha256(body) == entry["sha256"], "Input bytes or digest differ")+ files[name] = body+ for stage in ("G", "M", "E", "R"):+ manifest = json.loads(files[f"{stage}/manifest.json"])+ expected_task = {"G": "guardrails", "M": "redact", "E": "lookalike-search", "R": "rerank-relevance-rules"}[+ stage+ ]+ require(manifest.get("task") == expected_task, "Wrong-source manifest")+ entries = manifest.get("files_sha256", manifest.get("files", {}))+ if isinstance(entries, list):+ indexed = {safe_path(e["path"]): e for e in entries}+ require(len(indexed) == len(entries), "Duplicate manifest paths")+ else:+ require(isinstance(entries, dict), "Malformed manifest files")+ indexed = {safe_path(name): {"sha256": value} for name, value in entries.items()}+ for name, body in files.items():+ if name.startswith(f"{stage}/") and name != f"{stage}/manifest.json" and stage != "G":+ remote_name = "inputs/" + name.split("/", 1)[1]+ require(remote_name in indexed, "Input missing from source manifest")+ check = indexed[remote_name]+ require(+ sha256(body) == check["sha256"] and check.get("bytes", len(body)) == len(body),+ "Manifest input digest differs",+ )+ return files+++def fetch_inputs(destination: Path, catalog: dict[str, Any] | None = None) -> None:+ catalog = sources() if catalog is None else catalog+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.mkdir() # exclusive reservation, including empty existing directories+ staging = destination / ".staging"+ staging.mkdir()+ try:+ for entry in catalog["files"]:+ name = safe_path(entry["path"])+ request = urllib.request.Request(entry["url"], headers={"User-Agent": "sie-examples/agent-stage-latency"})+ with urllib.request.urlopen(request, timeout=60) as response:+ body = response.read(entry["bytes"] + 1)+ require(+ len(body) == entry["bytes"] and sha256(body) == entry["sha256"], "Downloaded bytes or digest differ"+ )+ target = staging / name+ target.parent.mkdir(parents=True, exist_ok=True)+ with target.open("xb") as output:+ output.write(body)+ write_exclusive(staging / "verified.json", {"source_digest": digest(catalog)})+ verify_inputs(staging, catalog)+ for child in staging.iterdir():+ if child.name != "verified.json":+ child.rename(destination / child.name)+ (staging / "verified.json").rename(destination / "verified.json")+ staging.rmdir()+ except BaseException:+ # Only this invocation's exclusively reserved directory is removed.+ shutil.rmtree(destination)+ raise+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--out", type=Path, required=True)+ args = parser.parse_args()+ try:+ fetch_inputs(args.out)+ except (OSError, ValueError):+ raise SystemExit(+ "Fetch failed; no verified inputs published. Choose a fresh destination and check the public pins."+ ) from None+ print("Verified the nine pinned public input files.")+++if __name__ == "__main__":+ main()diff --git a/examples/agent-stage-latency/prepare.py b/examples/agent-stage-latency/prepare.pynew file mode 100644index 000000000..6198b966b--- /dev/null+++ b/examples/agent-stage-latency/prepare.py@@ -0,0 +1,292 @@+"""Prepare a fixed, offline execution packet from verified public inputs."""++from __future__ import annotations++import argparse+import csv+import io+import json+import random+import re+from pathlib import Path+from typing import Any++from fetch import verify_inputs, write_exclusive+from protocol import (+ M_POLICY,+ RULES,+ STAGES,+ digest,+ positive,+ protocol_digest,+ requests,+ require,+ sha256,+ source_digest,+ sources,+)+++def unit(stage: str, cohort: str, original_id: str, data: dict[str, Any]) -> dict[str, Any]:+ return {+ "stage": stage,+ "cohort_sha256": cohort,+ "original_id": original_id,+ "base_id": digest({"stage": stage, "cohort_sha256": cohort, "original_id": original_id}),+ "input_digest": digest(data),+ "data": data,+ }+++def populations(root: Path) -> dict[str, list[dict[str, Any]]]:+ files = verify_inputs(root) # all bytes checked before parsing or sampling+ result: dict[str, list[dict[str, Any]]] = {stage: [] for stage in STAGES}+ body = files["G/toxicchat.csv"]+ for index, row in enumerate(csv.DictReader(io.StringIO(body.decode("utf-8"), newline=""))):+ if row["human_annotation"] == "True":+ result["G"].append(unit("G", sha256(body), f"toxicchat:{index}", {"text": row["user_input"]}))+ body = files["G/aegis.json"]+ seen = set()+ for index, row in enumerate(json.loads(body)):+ text = str(row["prompt"])+ if row["prompt_label_source"] == "human" and text != "REDACTED" and text not in seen:+ seen.add(text)+ result["G"].append(unit("G", sha256(body), f"aegis:{index}", {"text": text}))+ body = files["M/gretel-main.jsonl"]+ for row in (json.loads(line) for line in body.splitlines()):+ result["M"].append(unit("M", sha256(body), str(row["uid"]), {"text": row["text"]}))+ body = files["E/questions.json"]+ for row in json.loads(body)["questions"]:+ result["E"].append(unit("E", sha256(body), str(row["id"]), {"text": row["question"]}))+ body = files["R/cases_test.json"]+ for row in json.loads(body)["cases"]:+ candidates = [{"id": c["id"], "text": c["text"]} for c in row["candidates"]]+ require(len(candidates) == 20 and len({c["id"] for c in candidates}) == 20, "Expected 20 distinct candidates")+ result["R"].append(unit("R", sha256(body), str(row["id"]), {"query": row["query"], "candidates": candidates}))+ for stage, count in {"G": 4768, "M": 660, "E": 440, "R": 499}.items():+ require(+ len(result[stage]) == count and len({u["base_id"] for u in result[stage]}) == count,+ "Incomplete eligible population",+ )+ return result+++def validate_config(config: dict[str, Any]) -> None:+ require(type(config["n"]) is int and config["n"] > 0, "n must be a positive base-unit count")+ require(type(config["warmup"]) is int and config["warmup"] >= 0, "warmup must be nonnegative")+ require(type(config["seed"]) is int, "Declare an integer seed")+ require(+ config["phase"] in ("pilot", "confirmatory") and config["arms"] in ("sie", "paired"),+ "Unknown phase or arm mode",+ )+ require(+ bool(config["stages"])+ and len(set(config["stages"])) == len(config["stages"])+ and set(config["stages"]) <= set(STAGES),+ "Invalid stage order",+ )+ require(+ all(positive(config[k]) for k in ("request_timeout_s", "wall_limit_s")), "Timeouts must be finite and positive"+ )+ require(+ bool(re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", config["placement_label"])),+ "Use a nonsecret placement label of 1-64 letters/digits/._-",+ )+ bootstrap = config["bootstrap"]+ require(+ type(bootstrap["seed"]) is int and type(bootstrap["resamples"]) is int and bootstrap["resamples"] >= 100,+ "Invalid bootstrap seed/count",+ )+ require(+ bootstrap["quantile"] == "linear-(n-1)p" and bootstrap["minimum_clusters"] == 2, "Unknown statistical protocol"+ )+++def observation(selected: dict[str, Any], phase: str, rule: str | None, arms: list[str]) -> dict[str, Any]:+ identity = {"base_id": selected["base_id"], "phase": phase, "rule": rule, "repetition": 0}+ return {+ **identity,+ "observation_id": digest(identity),+ "stage": selected["stage"],+ "unit": selected,+ "arm_order": arms,+ "requests": {arm: requests(selected["stage"], selected["data"], arm, rule) for arm in arms},+ }+++def build_packet(+ population: dict[str, list[dict[str, Any]]], config: dict[str, Any], prior: list[dict[str, Any]] | None = None+) -> dict[str, Any]:+ validate_config(config)+ prior = prior or []+ excluded_ids = {o["base_id"] for p in prior for o in p["observations"]}+ excluded_inputs = {(o["stage"], o["unit"]["input_digest"]) for p in prior for o in p["observations"]}+ picked: dict[tuple[str, str], list[dict[str, Any]]] = {}+ for stage in config["stages"]:+ eligible = sorted(population[stage], key=lambda u: u["base_id"])+ random.Random(digest({"seed": config["seed"], "stage": stage})).shuffle(eligible)+ chosen = []+ for candidate in eligible:+ key = (stage, candidate["input_digest"])+ if candidate["base_id"] not in excluded_ids and key not in excluded_inputs:+ chosen.append(candidate)+ excluded_ids.add(candidate["base_id"])+ excluded_inputs.add(key)+ if len(chosen) == config["n"] + config["warmup"]:+ break+ require(len(chosen) == config["n"] + config["warmup"], "n exceeds the remaining distinct eligible population")+ picked[("warmup", stage)] = chosen[: config["warmup"]]+ picked[(config["phase"], stage)] = chosen[config["warmup"] :]+ observations = []+ for phase in ("warmup", config["phase"]):+ for stage in config["stages"]:+ for selected in picked[(phase, stage)]:+ for rule in RULES if stage == "R" else [None]:+ arms = ["sie", "rival"] if config["arms"] == "paired" else ["sie"]+ random.Random(+ digest({"seed": config["seed"], "base_id": selected["base_id"], "rule": rule})+ ).shuffle(arms)+ observations.append(observation(selected, phase, rule, arms))+ calls = {+ stage: {+ arm: sum(len(o["requests"].get(arm, [])) for o in observations if o["stage"] == stage)+ for arm in (["sie", "rival"] if config["arms"] == "paired" else ["sie"])+ }+ for stage in config["stages"]+ }+ content = {+ "schema": 1,+ "source_digest": source_digest(),+ "protocol_digest": protocol_digest(),+ "config": config,+ "m_policy": M_POLICY,+ "excluded_packet_digests": sorted(p["packet_digest"] for p in prior),+ "planned_semantic_calls": calls,+ "observations": observations,+ }+ return {**content, "packet_digest": digest(content)}+++def load_packet(path: Path) -> dict[str, Any]:+ packet = json.loads(path.read_bytes())+ content = {k: v for k, v in packet.items() if k != "packet_digest"}+ require(packet["packet_digest"] == digest(content), "Packet digest differs")+ require(+ packet["schema"] == 1+ and packet["source_digest"] == source_digest()+ and packet["protocol_digest"] == protocol_digest(),+ "Unknown source or protocol binding",+ )+ config = packet["config"]+ validate_config(config)+ require(packet["m_policy"] == M_POLICY, "Composition policy differs")+ seen_ids, seen_inputs, seen_observations = {}, {}, set()+ cohorts = {+ stage: {+ e["sha256"]+ for e in sources()["files"]+ if e["path"].startswith(stage + "/") and not e["path"].endswith("manifest.json")+ }+ for stage in STAGES+ }+ for obs in packet["observations"]:+ selected = obs["unit"]+ require(+ selected == unit(obs["stage"], selected["cohort_sha256"], selected["original_id"], selected["data"]),+ "Unit identity differs",+ )+ require(selected["cohort_sha256"] in cohorts[obs["stage"]], "Unknown input cohort")+ require(+ obs["stage"] in config["stages"] and obs["phase"] in ("warmup", config["phase"]),+ "Unknown observation phase/stage",+ )+ require(obs["base_id"] == selected["base_id"] and obs["repetition"] == 0, "Observation identity differs")+ for key, seen in ((obs["base_id"], seen_ids), ((obs["stage"], selected["input_digest"]), seen_inputs)):+ require(+ key not in seen or seen[key] == (obs["base_id"], obs["phase"]),+ "Base/input overlaps phases or identities",+ )+ seen[key] = (obs["base_id"], obs["phase"])+ require(obs["observation_id"] not in seen_observations, "Duplicate observation")+ seen_observations.add(obs["observation_id"])+ require(+ obs == observation(selected, obs["phase"], obs["rule"], obs["arm_order"]),+ "Request envelope or observation digest differs",+ )+ arms = ["sie", "rival"] if config["arms"] == "paired" else ["sie"]+ random.Random(digest({"seed": config["seed"], "base_id": selected["base_id"], "rule": obs["rule"]})).shuffle(+ arms+ )+ require(obs["arm_order"] == arms, "Frozen arm order differs")+ for phase, count in (("warmup", config["warmup"]), (config["phase"], config["n"])):+ for stage in config["stages"]:+ rows = [o for o in packet["observations"] if o["phase"] == phase and o["stage"] == stage]+ require(+ len({o["base_id"] for o in rows}) == count and len(rows) == count * (2 if stage == "R" else 1),+ "Fixed phase population differs",+ )+ calls = {+ stage: {+ arm: sum(len(o["requests"].get(arm, [])) for o in packet["observations"] if o["stage"] == stage)+ for arm in (["sie", "rival"] if config["arms"] == "paired" else ["sie"])+ }+ for stage in config["stages"]+ }+ require(packet["planned_semantic_calls"] == calls, "Planned call counts differ")+ return packet+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--inputs", type=Path, required=True)+ parser.add_argument("--out", type=Path, required=True)+ parser.add_argument("--n", type=int, required=True, help="base evidence units per selected stage")+ parser.add_argument("--seed", type=int, required=True)+ parser.add_argument("--stages", nargs="+", choices=STAGES, required=True)+ parser.add_argument("--arms", choices=("sie", "paired"), required=True)+ parser.add_argument("--phase", choices=("pilot", "confirmatory"), required=True)+ parser.add_argument("--warmup", type=int, default=0)+ parser.add_argument("--exclude-packet", type=Path, action="append", default=[])+ parser.add_argument(+ "--request-timeout", type=float, required=True, help="connect, read and SDK provision budget in seconds"+ )+ parser.add_argument("--wall-limit", type=float, required=True)+ parser.add_argument("--placement-label", required=True, help="nonsecret label for this declared trial placement")+ parser.add_argument("--bootstrap-seed", type=int, default=1729)+ parser.add_argument("--bootstrap-resamples", type=int, default=5000)+ args = parser.parse_args()+ config = {+ "n": args.n,+ "seed": args.seed,+ "stages": args.stages,+ "arms": args.arms,+ "phase": args.phase,+ "warmup": args.warmup,+ "request_timeout_s": args.request_timeout,+ "wall_limit_s": args.wall_limit,+ "placement_label": args.placement_label,+ "bootstrap": {+ "seed": args.bootstrap_seed,+ "resamples": args.bootstrap_resamples,+ "quantile": "linear-(n-1)p",+ "minimum_clusters": 2,+ },+ }+ try:+ require(not args.out.exists(), "Packet destination already exists")+ packet = build_packet(populations(args.inputs), config, [load_packet(p) for p in args.exclude_packet])+ write_exclusive(args.out, packet)+ except (OSError, ValueError, KeyError, TypeError):+ raise SystemExit(+ "Preparation failed; check verified inputs, fixed trial settings, exclusions and the fresh output path."+ ) from None+ print(+ json.dumps(+ {"packet_digest": packet["packet_digest"], "planned_semantic_calls": packet["planned_semantic_calls"]},+ indent=2,+ )+ )+++if __name__ == "__main__":+ main()diff --git a/examples/agent-stage-latency/protocol.py b/examples/agent-stage-latency/protocol.pynew file mode 100644index 000000000..b4b9eaf41--- /dev/null+++ b/examples/agent-stage-latency/protocol.py@@ -0,0 +1,365 @@+"""Frozen public request semantics, canonical identities, and caller composition."""++from __future__ import annotations++import hashlib+import json+import math+import re+from pathlib import Path, PurePosixPath+from typing import Any++HERE = Path(__file__).resolve().parent+STAGES = ("G", "M", "E", "R")+MODELS = {+ "G": ["Qwen/Qwen3Guard-Gen-4B"],+ "M": ["urchade/gliner_multi_pii-v1", "numind/NuNER_Zero"],+ "E": ["Qwen/Qwen3-Embedding-4B"],+ "R": ["Qwen/Qwen3-Reranker-4B"],+}+RIVALS = {"G": "anthropic", "M": "anthropic", "E": "openai", "R": "cohere"}+REQUEST_LABELS = [+ "person", "street address", "city", "county", "postal code", "gps coordinates", "date of birth",+ "phone number", "fax number", "email address", "url", "ip address", "mac address", "social security number",+ "national id number", "tax id number", "medical record number", "health plan beneficiary number",+ "account number", "credit card number", "cvv", "pin", "password", "api key", "http cookie", "username",+ "customer id", "employee id", "certificate or license number", "license plate",+ "vehicle identification number", "device identifier", "biometric identifier", "unique identifier",+ "passport number", "driver's license number",+] # fmt: skip+RULES = {+ "in-force": (+ "Return the final rule the agency has adopted on this subject, not a proposed rule. "+ "A proposal that is still open for comment is not relevant."+ ),+ "proposed": (+ "Return the proposed rule the agency has published for comment on this subject, not a final rule. "+ "A rule already adopted is not relevant."+ ),+}+GUARD_PROMPT = (+ "Is the following user message harmful? Answer with exactly one word: harmful or unharmful.\n\nMessage:\n{prompt}"+)+PII_PROMPT = (+ "Find every piece of personally identifiable information in the text. Use these types: {labels}. "+ "Copy each mention exactly as it appears in the text. Return an empty list if there is none."+)+SCHEMA = {+ "type": "object",+ "additionalProperties": False,+ "required": ["entities"],+ "properties": {+ "entities": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": False,+ "required": ["text", "type"],+ "properties": {"text": {"type": "string"}, "type": {"type": "string", "enum": REQUEST_LABELS}},+ },+ },+ },+}+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}+PROVIDER_URLS = {+ "anthropic": "https://api.anthropic.com",+ "openai": "https://api.openai.com",+ "cohere": "https://api.cohere.com",+}+++def require(condition: bool, message: str) -> None:+ if not condition:+ raise ValueError(message)+++def canonical(value: Any) -> bytes:+ """UTF-8 JSON, sorted keys, compact separators, unescaped Unicode, no NaN, no newline."""+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")+++def sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def digest(value: Any) -> str:+ return sha256(canonical(value))+++def sources() -> dict[str, Any]:+ return json.loads((HERE / "sources.json").read_bytes())+++def source_digest() -> str:+ return digest(sources())+++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")})+++def safe_path(value: str) -> str:+ path = PurePosixPath(value)+ require(+ bool(value)+ and not path.is_absolute()+ and ".." not in path.parts+ and str(path) == value+ and "\\" not in value+ and all(ord(c) >= 32 for c in value),+ "Unsafe manifest path",+ )+ return value+++def positive(value: Any) -> bool:+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value > 0+++def windows(text: str) -> list[tuple[int, int]]:+ words = [match.span() for match in WORD.finditer(text)]+ if len(words) <= 300:+ return [(0, len(text))]+ out = []+ for first in range(0, len(words), 250):+ last = min(first + 300, len(words)) - 1+ out.append((words[first][0], words[last][1]))+ if last == len(words) - 1:+ break+ return out+++def propagated(text: str, spans: list[dict[str, Any]]) -> list[dict[str, Any]]:+ tokens = sorted(+ {t for s in spans if s["label"] == "person" for t in NAME_TOKEN.findall(text[s["start"] : s["end"]])}+ )+ added = []+ for token in tokens:+ pattern = re.compile(r"(?<![^\W\d_])" + re.escape(token) + r"(?![^\W\d_])")+ for match in pattern.finditer(text):+ if not any(s["start"] <= match.start() and s["end"] >= match.end() for s in spans):+ added.append({"start": match.start(), "end": match.end(), "label": "person", "derived": True})+ return added+++def compose(text: str, paths: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:+ merged: dict[tuple[int, int, str], dict[str, Any]] = {}+ for entities in paths:+ for entity in entities:+ if (entity.get("score") or 0) < 0.6:+ continue+ key = (entity["start"], entity["end"], entity["label"])+ if key not in merged or entity["score"] > (merged[key].get("score") or 0):+ merged[key] = dict(entity)+ spans = sorted(merged.values(), key=lambda s: (s["start"], s["end"]))+ return sorted(spans + propagated(text, spans), key=lambda s: (s["start"], s["end"]))+++def llm_spans(text: str, output: dict[str, Any]) -> tuple[list[dict[str, Any]], int]:+ require(set(output) == {"entities"} and isinstance(output["entities"], list), "Malformed PII schema")+ spans, seen, unmatched = [], set(), 0+ for entity in output["entities"]:+ require(isinstance(entity, dict) and set(entity) == {"text", "type"}, "Malformed PII entity")+ require(isinstance(entity["text"], str) and entity["type"] in REQUEST_LABELS, "Malformed PII entity")+ needle = entity["text"]+ at = text.find(needle) if needle else -1+ unmatched += at == -1+ while at != -1:+ end = at + len(needle)+ if (at, end) not in seen:+ seen.add((at, end))+ spans.append({"start": at, "end": end, "label": entity["type"]})+ at = text.find(needle, at + 1)+ return spans, unmatched+++def masked(text: str, spans: list[dict[str, Any]]) -> str:+ labels: dict[tuple[int, int], str] = {}+ merged: list[list[int]] = []+ for span in spans:+ labels.setdefault((span["start"], span["end"]), span["label"])+ for span in sorted(spans, key=lambda s: (s["start"], s["end"])):+ if merged and span["start"] < merged[-1][1]:+ merged[-1][1] = max(merged[-1][1], span["end"])+ else:+ merged.append([span["start"], span["end"]])+ out, at = [], 0+ for start, end in merged:+ label = next((label for (s, _), label in labels.items() if s == start), "pii")+ out.extend([text[at:start], f"[{label.upper()}]"])+ at = end+ return "".join([*out, text[at:]])+++def requests(stage: str, data: dict[str, Any], arm: str, rule: str | None = None) -> list[dict[str, Any]]:+ """Semantic calls; SDK-added wire IDs and physical retries are recorded separately."""+ require(stage in STAGES and arm in ("sie", "rival"), "Unknown stage or arm")+ text = data.get("text", "")+ if arm == "sie":+ if stage == "G":+ calls = [+ {+ "method": "chat_completions",+ "model": MODELS[stage][0],+ "body": {+ "messages": [{"role": "user", "content": text}],+ "temperature": 0,+ "max_tokens": 64,+ },+ }+ ]+ elif stage == "M":+ calls = [+ {+ "method": "extract",+ "model": model,+ "window": index,+ "offset": start,+ "body": {+ "item": {"text": text[start:end]},+ "labels": REQUEST_LABELS,+ },+ }+ for model in MODELS[stage]+ for index, (start, end) in enumerate(windows(text))+ ]+ elif stage == "E":+ calls = [+ {"method": "encode", "model": MODELS[stage][0], "body": {"item": {"text": text}, "is_query": True}}+ ]+ else:+ require(rule in RULES, "Unknown rerank rule")+ calls = [+ {+ "method": "score",+ "model": MODELS[stage][0],+ "body": {+ "query": {"text": data["query"]},+ "items": data["candidates"],+ "instruction": RULES[rule or ""],+ },+ }+ ]+ elif stage in ("G", "M"):+ body: dict[str, Any] = {+ "model": "claude-haiku-4-5",+ "temperature": 0,+ "max_tokens": 10 if stage == "G" else 4096,+ "messages": [{"role": "user", "content": GUARD_PROMPT.format(prompt=text) if stage == "G" else text}],+ }+ if stage == "M":+ body.update(+ {+ "system": PII_PROMPT.format(labels=", ".join(REQUEST_LABELS)),+ "output_config": {"format": {"type": "json_schema", "schema": SCHEMA}},+ }+ )+ calls = [+ {+ "method": "messages",+ "provider": "anthropic",+ "model": body["model"],+ "path": "/v1/messages",+ "body": body,+ }+ ]+ elif stage == "E":+ body = {"model": "text-embedding-3-large", "input": text, "dimensions": 3072, "encoding_format": "float"}+ calls = [+ {+ "method": "embeddings",+ "provider": "openai",+ "model": body["model"],+ "path": "/v1/embeddings",+ "body": body,+ }+ ]+ else:+ require(rule in RULES, "Unknown rerank rule")+ body = {+ "model": "rerank-v4.0-pro",+ "query": f"Instruction: {RULES[rule or '']}\nQuery: {data['query']}",+ "documents": [c["text"] for c in data["candidates"]],+ "top_n": 20,+ "max_tokens_per_doc": 4096,+ }+ calls = [{"method": "rerank", "provider": "cohere", "model": body["model"], "path": "/v2/rerank", "body": body}]+ return [{**call, "request_digest": digest(call)} for call in calls]+++def call_id(observation_id: str, arm: str, index: int) -> str:+ return digest({"observation_id": observation_id, "arm": arm, "index": index})+++def validate_reply(stage: str, arm: str, reply: dict[str, Any], data: dict[str, Any], call: dict[str, Any]) -> Any:+ """Validate actual projected replies before treating a call as successful."""+ require(+ isinstance(reply, dict) and not reply.get("item_error") and not reply.get("malformed_reply"),+ "Per-item or malformed reply",+ )+ if stage == "G":+ text = reply["text"]+ require(isinstance(text, str) and not reply.get("refusal"), "Malformed guard reply")+ pattern = r"Safety:\s*(Safe|Unsafe|Controversial)" if arm == "sie" else r"^\s*(harmful|unharmful)\s*$"+ match = re.search(pattern, text, re.IGNORECASE)+ if match is None:+ raise ValueError("Malformed guard verdict")+ return {"text": text, "verdict": match.group(1).lower()}+ if stage == "M":+ if arm == "rival":+ require(not reply.get("refusal"), "PII refusal")+ spans, unmatched = llm_spans(data["text"], json.loads(reply["text"]))+ return {"spans": spans, "unmatched_mentions": unmatched, "masked": masked(data["text"], spans)}+ require(isinstance(reply.get("entities"), list), "Missing entities")+ length = len(call["body"]["item"]["text"])+ for entity in reply["entities"]:+ start, end = entity["start"], entity["end"]+ require(type(start) is int and type(end) is int and 0 <= start < end <= length, "Invalid Unicode span")+ require(entity["label"] in REQUEST_LABELS, "Unknown entity label")+ score = entity.get("score")+ require(+ score is None+ or (+ isinstance(score, (int, float))+ and not isinstance(score, bool)+ and math.isfinite(score)+ and 0 <= score <= 1+ ),+ "Invalid entity score",+ )+ return [+ {**entity, "start": entity["start"] + call["offset"], "end": entity["end"] + call["offset"]}+ for entity in reply["entities"]+ ]+ if stage == "E":+ vector = reply["dense"]+ expected = 2560 if arm == "sie" else 3072+ require(isinstance(vector, list) and len(vector) == expected, "Embedding dimension differs")+ require(+ all(isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) for x in vector),+ "Invalid embedding value",+ )+ return {"dimensions": len(vector)}+ scores = reply["scores"]+ ids = [c["id"] for c in data["candidates"]]+ if arm == "rival":+ results = reply["results"]+ require(+ len(results) == 20 and {r["index"] for r in results if type(r["index"]) is int} == set(range(20)),+ "Invalid provider rerank indices",+ )+ require(+ len(scores) == 20 and len({s["item_id"] for s in scores}) == 20 and {s["item_id"] for s in scores} == set(ids),+ "Rerank candidate set differs",+ )+ require(+ all(+ isinstance(s["score"], (int, float)) and not isinstance(s["score"], bool) and math.isfinite(s["score"])+ for s in scores+ ),+ "Invalid rerank score",+ )+ return {"scores": scores}diff --git a/examples/agent-stage-latency/run.py b/examples/agent-stage-latency/run.pynew file mode 100644index 000000000..36464656a--- /dev/null+++ b/examples/agent-stage-latency/run.py@@ -0,0 +1,701 @@+"""Explicitly execute a frozen packet against a supplied SIE URL within a hard wall deadline."""++from __future__ import annotations++import argparse+import contextlib+import importlib.metadata+import json+import logging+import math+import multiprocessing+import os+import re+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit++from fetch import write_exclusive+from prepare import load_packet+from protocol import (+ MODELS,+ PROVIDER_URLS,+ RIVALS,+ call_id,+ canonical,+ compose,+ digest,+ masked,+ requests,+ require,+ sha256,+ validate_reply,+)++ERROR_CODES = frozenset(+ {+ "ADMISSION_QUEUE_FULL",+ "MODEL_LOADING",+ "MODEL_LOAD_FAILED",+ "RESOURCE_EXHAUSTED",+ "INVALID_ARGUMENT",+ "UNAUTHENTICATED",+ "PERMISSION_DENIED",+ "NOT_FOUND",+ "UNAVAILABLE",+ "INTERNAL",+ "DEADLINE_EXCEEDED",+ "RATE_LIMITED",+ "ITEM_ERROR",+ "MALFORMED_REPLY",+ "HTTP_ERROR",+ "WALL_DEADLINE",+ "CALL_FAILED",+ }+)+ERROR_CLASSES = frozenset(+ {+ "RequestError",+ "ServerError",+ "SIEConnectionError",+ "ProvisioningError",+ "ReadTimeout",+ "ConnectTimeout",+ "WriteTimeout",+ "PoolTimeout",+ "ConnectError",+ "ReadError",+ "RemoteProtocolError",+ "HTTPStatusError",+ "ValueError",+ "KeyError",+ "TypeError",+ "JSONDecodeError",+ "CallFailure",+ "TimeoutError",+ "AssertionError",+ "AttributeError",+ "SIEError",+ "PoolError",+ "LoraLoadingError",+ "ModelLoadingError",+ "ModelLoadFailedError",+ "InputTooLongError",+ "RateLimitError",+ "InsufficientCreditsError",+ "SpendLimitError",+ "AccountInactiveError",+ "AccountStateUnavailableError",+ "ResourceExhaustedError",+ "IncompleteBatchError",+ }+)+++def endpoint(value: str) -> tuple[str, str]:+ """Reject secret-bearing URLs before constructing a client or displaying an error."""+ try:+ parsed = urlsplit(value)+ require(parsed.scheme in ("http", "https") and bool(parsed.hostname), "Invalid endpoint")+ require(+ not parsed.username and not parsed.password and not parsed.query and not parsed.fragment, "Invalid endpoint"+ )+ require(+ not any(ord(c) <= 32 for c in value) and not any(c in value for c in ("\\", "%", "?", "#", "@")),+ "Invalid endpoint",+ )+ require(parsed.port is None or 1 <= parsed.port <= 65535, "Invalid endpoint")+ require(bool(re.fullmatch(r"[A-Za-z0-9./_:-]*", parsed.path)), "Invalid endpoint path")+ origin = f"{parsed.scheme}://{parsed.netloc}"+ return value.rstrip("/"), origin+ except (ValueError, TypeError):+ raise ValueError("Use an absolute HTTP(S) endpoint without userinfo, query or fragment.") from None+++def public_id(value: Any) -> str | None:+ return value if isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_./:-]{1,180}", value) else None+++def revision(value: Any) -> str | None:+ return value if isinstance(value, str) and re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", value) else None+++def sanitize(value: Any, credentials: list[str]) -> Any:+ if isinstance(value, str):+ for secret in credentials:+ if secret:+ value = value.replace(secret, "[REDACTED_CREDENTIAL]")+ return value+ if isinstance(value, dict):+ return {str(k): sanitize(v, credentials) for k, v in value.items()}+ if isinstance(value, (list, tuple)):+ return [sanitize(v, credentials) for v in value]+ if isinstance(value, float) and not math.isfinite(value):+ return "[NONFINITE]"+ if value is None or isinstance(value, (bool, int, float)):+ return value+ if hasattr(value, "tolist"):+ return sanitize(value.tolist(), credentials)+ return "[UNSERIALIZABLE]"+++def stable_error(error: BaseException) -> dict[str, Any]:+ name = type(error).__name__+ result: dict[str, Any] = {"class": name if name in ERROR_CLASSES else "UnexpectedError"}+ code = getattr(error, "code", getattr(error, "error_code", None))+ if isinstance(code, str) and code in ERROR_CODES:+ result["code"] = code+ status = getattr(error, "status_code", None)+ if type(status) is int and 100 <= status <= 599:+ result["status"] = status+ if isinstance(error, (ValueError, KeyError, TypeError)):+ result.setdefault("code", "MALFORMED_REPLY")+ return result+++class CallFailure(Exception):+ def __init__(self, code: str, status_code: int | None = None) -> None:+ super().__init__(code)+ self.code = code+ self.status_code = status_code+++class Journal:+ """One serialized, fsynced hash chain shared by both M model paths."""++ def __init__(self, path: Path, packet: dict[str, Any], credentials: list[str], *, create: bool = False) -> None:+ self.path = path+ self.packet = packet+ self.credentials = credentials+ self.lock = threading.Lock()+ path.parent.mkdir(parents=True, exist_ok=True)+ self.output = path.open("xb" if create else "ab")+ rows = [] if create else [json.loads(line) for line in path.read_bytes().splitlines()]+ self.sequence = len(rows)+ self.previous = rows[-1]["entry_digest"] if rows else None++ def append(self, event: str, **fields: Any) -> None:+ with self.lock:+ content = sanitize(+ {+ "event": event,+ "sequence": self.sequence,+ "previous_digest": self.previous,+ "packet_digest": self.packet["packet_digest"],+ "protocol_digest": self.packet["protocol_digest"],+ "source_digest": self.packet["source_digest"],+ **fields,+ },+ self.credentials,+ )+ row = {**content, "entry_digest": digest(content)}+ self.output.write(canonical(row) + b"\n")+ self.output.flush()+ os.fsync(self.output.fileno())+ self.previous = row["entry_digest"]+ self.sequence += 1++ def close(self) -> None:+ self.output.close()+++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,+ "request_digest": digest(obs["requests"][arm]),+ }+++def subcall_identity(obs: dict[str, Any], arm: str, index: int) -> dict[str, Any]:+ call = obs["requests"][arm][index]+ return operation_identity(obs, arm) | {+ "call_id": call_id(obs["observation_id"], arm, index),+ "request_digest": call["request_digest"],+ "request_index": index,+ "model": call["model"],+ "window": call.get("window"),+ "offset": call.get("offset"),+ }+++class TransportEvidence:+ def __init__(self, journal: Journal) -> None:+ self.journal = journal+ self.local = threading.local()++ def begin(self, identity: dict[str, Any]) -> None:+ self.local.identity = identity+ self.local.dispatches = 0++ def request(self, request: Any) -> None:+ self.local.dispatches += 1+ 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(+ "response",+ **self.local.identity,+ dispatch_index=self.local.dispatches,+ status=response.status_code,+ elapsed_s=time.perf_counter() - self.local.dispatched_at,+ execution_revision=revision(response.headers.get("X-SIE-Model-Revision")),+ )+++def project_reply(stage: str, arm: str, raw: Any, data: dict[str, Any]) -> dict[str, Any]:+ """Keep workload replies and allowlisted execution evidence; omit arbitrary telemetry."""+ if not isinstance(raw, dict):+ return {"malformed_reply": True}+ reply: dict[str, Any] = {"returned_model": public_id(raw.get("model"))}+ request = raw.get("request")+ if isinstance(request, dict):+ reply["execution_identity_sha256"] = revision(request.get("execution_identity_sha256"))+ reply["execution_binding_sha256"] = revision(request.get("execution_binding_sha256"))+ if raw.get("error"):+ reply["item_error"] = {"code": "ITEM_ERROR"}+ if stage == "G" or (stage == "M" and arm == "rival"):+ if arm == "sie":+ choices = raw.get("choices") or []+ message = choices[0].get("message", {}) if choices and isinstance(choices[0], dict) else {}+ reply.update(+ {+ "text": message.get("content"),+ "refusal": message.get("refusal"),+ "finish_reason": public_id(choices[0].get("finish_reason")) if choices else None,+ }+ )+ else:+ blocks = raw.get("content")+ if isinstance(blocks, list):+ reply["content"] = [+ {"type": public_id(b.get("type")), "text": b.get("text")} for b in blocks if isinstance(b, dict)+ ]+ reply["text"] = "".join(+ b.get("text", "")+ for b in blocks+ if isinstance(b, dict) and b.get("type") == "text" and isinstance(b.get("text"), str)+ )+ reply["refusal"] = raw.get("stop_reason") == "refusal"+ reply["stop_reason"] = public_id(raw.get("stop_reason"))+ elif stage == "M":+ entities = raw.get("entities")+ reply["entities"] = (+ [{k: e.get(k) for k in ("start", "end", "label", "score", "text")} for e in entities if isinstance(e, dict)]+ if isinstance(entities, list)+ else None+ )+ if isinstance(entities, list) and sum(isinstance(e, dict) for e in entities) != len(entities):+ reply["entities"] = None+ elif stage == "E":+ if arm == "sie":+ reply["dense"] = raw.get("dense")+ else:+ rows = raw.get("data")+ if isinstance(rows, list) and len(rows) == 1 and isinstance(rows[0], dict) and rows[0].get("index") == 0:+ reply["dense"] = rows[0].get("embedding")+ else:+ reply["dense"] = None+ elif arm == "sie":+ scores = raw.get("scores")+ reply["scores"] = (+ [+ {"item_id": s.get("item_id"), "score": s.get("score"), "rank": s.get("rank")}+ for s in scores+ if isinstance(s, dict)+ ]+ if isinstance(scores, list)+ else []+ )+ if isinstance(scores, list) and len(reply["scores"]) != len(scores):+ reply["malformed_reply"] = True+ else:+ results = raw.get("results")+ reply["results"] = (+ [+ {"index": r.get("index"), "relevance_score": r.get("relevance_score")}+ for r in results+ if isinstance(r, dict)+ ]+ if isinstance(results, list)+ else []+ )+ reply["scores"] = []+ for row in reply["results"]:+ index = row["index"]+ if type(index) is int and 0 <= index < len(data["candidates"]):+ reply["scores"].append({"item_id": data["candidates"][index]["id"], "score": row["relevance_score"]})+ usage = raw.get("usage")+ if isinstance(usage, dict):+ reply["usage"] = {+ k: usage[k]+ for k in ("input_tokens", "output_tokens", "prompt_tokens", "total_tokens")+ if type(usage.get(k)) is int and usage[k] >= 0+ }+ return reply+++class Executor:+ def __init__(self, packet: dict[str, Any], journal: Journal, config: dict[str, Any]) -> None:+ # Optional live dependencies are imported only in the opted-in child.+ import httpx+ from sie_sdk import SIEClient++ self.packet = packet+ self.journal = journal+ self.config = config+ self.clients: dict[str, Any] = {}+ self.evidence: dict[str, TransportEvidence] = {}+ timeout = min(packet["config"]["request_timeout_s"], self.remaining())+ for stage in packet["config"]["stages"]:+ for model in MODELS[stage]:+ hooks = TransportEvidence(journal)+ transport = httpx.Client(+ base_url=config["sie_url"],+ timeout=timeout,+ follow_redirects=False,+ trust_env=False,+ event_hooks={"request": [hooks.request], "response": [hooks.response]},+ )+ client = SIEClient(+ config["sie_url"],+ api_key=config["credentials"].get("sie", ""),+ timeout_s=timeout,+ connect_timeout_s=timeout,+ read_timeout_s=timeout,+ http_client=transport,+ )+ self.clients[model] = client+ self.evidence[model] = hooks+ if packet["config"]["arms"] == "paired":+ for provider in {RIVALS[s] for s in packet["config"]["stages"]}:+ hooks = TransportEvidence(journal)+ headers = (+ {"x-api-key": config["credentials"][provider], "anthropic-version": "2023-06-01"}+ if provider == "anthropic"+ else {"Authorization": f"Bearer {config['credentials'][provider]}"}+ )+ self.clients[provider] = httpx.Client(+ base_url=config["provider_urls"][provider],+ headers=headers,+ timeout=timeout,+ follow_redirects=False,+ trust_env=False,+ event_hooks={"request": [hooks.request], "response": [hooks.response]},+ )+ self.evidence[provider] = hooks++ def remaining(self) -> float:+ remaining = self.config["deadline"] - time.monotonic()+ if remaining <= 0:+ raise CallFailure("WALL_DEADLINE")+ return remaining++ def discover(self) -> None:+ model = next(iter(self.clients))+ self.journal.append("discovery_intent", call_id="metadata")+ self.evidence[model].begin({"call_id": "metadata"})+ start = time.perf_counter()+ try:+ listed = self.clients[model].list_models()+ selected = {m for s in self.packet["config"]["stages"] for m in MODELS[s]}+ safe = [+ {+ "name": m.get("name"),+ "weights_revision": revision(m.get("revision")),+ "dims": m.get("dims") if type(m.get("dims")) is int else None,+ }+ for m in listed+ if isinstance(m, dict) and m.get("name") in selected+ ]+ self.journal.append(+ "discovery_result",+ call_id="metadata",+ status="success",+ models=safe,+ elapsed_s=time.perf_counter() - start,+ )+ except Exception as error:+ self.journal.append(+ "discovery_result",+ call_id="metadata",+ status="failed",+ error=stable_error(error),+ elapsed_s=time.perf_counter() - start,+ )++ def call(self, obs: dict[str, Any], arm: str, index: int) -> Any:+ from sie_sdk import Item++ call = obs["requests"][arm][index]+ identity = subcall_identity(obs, arm, index)+ 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)+ start = time.perf_counter()+ reply = None+ try:+ timeout = min(self.packet["config"]["request_timeout_s"], self.remaining())+ body = call["body"]+ if arm == "rival":+ response = client.post(call["path"], json=body, timeout=timeout)+ if not 200 <= response.status_code < 300:+ raise CallFailure("HTTP_ERROR", response.status_code)+ raw = response.json()+ else:+ options = {"wait_for_capacity": False, "max_oom_retries": 0, "provision_timeout_s": timeout}+ if call["method"] == "chat_completions":+ raw = client.chat_completions(call["model"], **body, **options)+ elif call["method"] == "extract":+ raw = client.extract(call["model"], Item(**body["item"]), labels=body["labels"], **options)+ elif call["method"] == "encode":+ raw = client.encode(call["model"], Item(**body["item"]), is_query=True, **options)+ else:+ raw = client.score(+ call["model"],+ Item(**body["query"]),+ [Item(**item) for item in body["items"]],+ instruction=body["instruction"],+ **options,+ )+ reply = sanitize(project_reply(obs["stage"], arm, raw, obs["unit"]["data"]), self.journal.credentials)+ if reply.get("item_error"):+ raise CallFailure("ITEM_ERROR")+ validated = validate_reply(obs["stage"], arm, reply, obs["unit"]["data"], call)+ except Exception as error:+ self.journal.append(+ "call_result",+ **identity,+ status="failed",+ reply=reply,+ error=stable_error(error),+ elapsed_s=time.perf_counter() - start,+ physical_dispatches=hooks.local.dispatches,+ sdk_retry_count=client.last_retry_count if arm == "sie" else 0,+ 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(+ "call_result",+ **identity,+ status="success",+ reply=reply,+ elapsed_s=time.perf_counter() - start,+ physical_dispatches=hooks.local.dispatches,+ sdk_retry_count=client.last_retry_count if arm == "sie" else 0,+ execution_revision=revision(client.last_model_revision) if arm == "sie" else None,+ )+ return validated++ def operation(self, obs: dict[str, Any], arm: str) -> None:+ identity = operation_identity(obs, arm)+ self.journal.append("operation_intent", **identity)+ start = time.perf_counter()+ result = None+ try:+ # Regeneration includes M's tokenizer/windowing inside its measured boundary.+ expected = requests(obs["stage"], obs["unit"]["data"], arm, obs["rule"])+ require(expected == obs["requests"][arm], "Frozen request differs")+ 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++ with ThreadPoolExecutor(max_workers=2) as pool:+ futures = [pool.submit(model_path, model) for model in MODELS["M"]]+ outputs = [future.result() for future in futures]+ spans = compose(obs["unit"]["data"]["text"], outputs)+ result = {"spans": spans, "masked": masked(obs["unit"]["data"]["text"], spans)}+ else:+ result = self.call(obs, arm, 0)+ except Exception as error:+ self.journal.append(+ "operation_result",+ **identity,+ status="failed",+ error=stable_error(error),+ result=result,+ elapsed_s=time.perf_counter() - start,+ )+ return+ self.journal.append(+ "operation_result", **identity, status="success", result=result, elapsed_s=time.perf_counter() - start+ )++ def close(self) -> None:+ for client in self.clients.values():+ client.close()+++def child_main(connection: Any) -> None:+ # SDK errors may include connection URLs. Only stable records leave this child.+ with Path(os.devnull).open("w") as sink, contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):+ logging.disable(logging.CRITICAL)+ journal = None+ executor = None+ try:+ config = connection.recv()+ packet = load_packet(Path(config["packet_path"]))+ journal = Journal(Path(config["journal"]), packet, list(config["credentials"].values()))+ executor = Executor(packet, journal, config)+ executor.discover()+ for obs in packet["observations"]:+ for arm in obs["arm_order"]:+ executor.remaining()+ executor.operation(obs, arm)+ connection.send("finished")+ except BaseException:+ connection.send("child_failure")+ finally:+ if executor is not None:+ with contextlib.suppress(BaseException):+ executor.close()+ if journal is not None:+ with contextlib.suppress(BaseException):+ journal.close()+ connection.close()+++def run_trial(+ packet_path: Path,+ journal_path: Path,+ sie_url: str,+ credentials: dict[str, str],+ *,+ execute: bool = False,+ provider_urls: dict[str, str] | None = None,+) -> str:+ require(execute, "Execution requires --execute")+ require(not journal_path.with_name(journal_path.name + ".end.json").exists(), "Run terminal record already exists")+ packet = load_packet(packet_path)+ sie_url, origin = endpoint(sie_url)+ selected_credentials = {"sie": credentials.get("sie", "")}+ selected_urls = {}+ provider_origins = {}+ if packet["config"]["arms"] == "paired":+ for provider in {RIVALS[s] for s in packet["config"]["stages"]}:+ require(bool(credentials.get(provider)), "A selected paired provider credential is missing")+ selected_credentials[provider] = credentials[provider]+ selected_urls[provider], provider_origins[provider] = endpoint((provider_urls or PROVIDER_URLS)[provider])+ try:+ sdk_version = importlib.metadata.version("sie-sdk")+ except importlib.metadata.PackageNotFoundError:+ raise ValueError("Install the workspace sie-sdk before execution") from None+ started = time.monotonic()+ deadline = started + packet["config"]["wall_limit_s"]+ journal = Journal(journal_path, packet, list(selected_credentials.values()), create=True)+ journal.append(+ "run_start",+ sie_origin=origin,+ provider_origins=provider_origins,+ placement_label=packet["config"]["placement_label"],+ sdk_version=sdk_version,+ timeout_budgets_s={+ "connect": packet["config"]["request_timeout_s"],+ "read": packet["config"]["request_timeout_s"],+ "provision": packet["config"]["request_timeout_s"],+ },+ wall_limit_s=packet["config"]["wall_limit_s"],+ )+ journal.close()+ context = multiprocessing.get_context("spawn")+ parent, child = context.Pipe()+ process = context.Process(target=child_main, args=(child,))+ reason = "child_failure"+ try:+ process.start()+ child.close()+ # Credentials travel in a private pipe, never command-line arguments.+ parent.send(+ {+ "packet_path": str(packet_path.resolve()),+ "journal": str(journal_path.resolve()),+ "sie_url": sie_url,+ "credentials": selected_credentials,+ "provider_urls": selected_urls,+ "deadline": deadline,+ }+ )+ process.join(max(0, deadline - time.monotonic()))+ if process.is_alive():+ reason = "deadline"+ elif parent.poll():+ reason = parent.recv()+ except KeyboardInterrupt:+ reason = "interrupted"+ except Exception:+ reason = "child_failure"+ finally:+ if process.pid is not None:+ if process.is_alive():+ process.terminate()+ process.join(1)+ if process.is_alive():+ process.kill()+ process.join()+ parent.close()+ child.close()+ # A terminated write may leave a truncated final line. Preserve it and+ # append the parent's terminal record to a distinct, exclusive sidecar.+ end = {+ "packet_digest": packet["packet_digest"],+ "reason": reason,+ "protocol_digest": packet["protocol_digest"],+ "source_digest": packet["source_digest"],+ "journal_digest": sha256(journal_path.read_bytes()),+ "elapsed_s": time.monotonic() - started,+ "child_exitcode": process.exitcode,+ }+ write_exclusive(journal_path.with_name(journal_path.name + ".end.json"), {**end, "end_digest": digest(end)})+ return reason+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--packet", type=Path, required=True)+ parser.add_argument(+ "--out", type=Path, required=True, help="new JSONL journal; creates a separate .end.json record"+ )+ parser.add_argument("--sie-base-url", default=None)+ parser.add_argument("--execute", action="store_true", help="send the frozen requests; may incur API charges")+ args = parser.parse_args()+ if not args.execute:+ parser.error("Use --execute to opt in to inference.")+ try:+ packet = load_packet(args.packet)+ require(+ not args.out.exists() and not args.out.with_name(args.out.name + ".end.json").exists(),+ "Run output already exists",+ )+ needed = {RIVALS[s] for s in packet["config"]["stages"]} if packet["config"]["arms"] == "paired" else set()+ keys = {"sie": os.environ.get("SIE_API_KEY", "")}+ for provider, variable in {+ "anthropic": "ANTHROPIC_API_KEY",+ "openai": "OPENAI_API_KEY",+ "cohere": "COHERE_API_KEY",+ }.items():+ if provider in needed:+ keys[provider] = os.environ.get(variable, "")+ reason = run_trial(+ args.packet, args.out, args.sie_base_url or os.environ.get("SIE_BASE_URL", ""), keys, execute=True+ )+ except Exception:+ raise SystemExit(+ "Execution could not start. Check the packet, fresh output, nonsecret endpoint and selected credentials."+ ) from None+ print(f"Run ended: {reason}. Score the preserved journal offline.")+ if reason != "finished":+ raise SystemExit(1)+++if __name__ == "__main__":+ main()diff --git a/examples/agent-stage-latency/score.py b/examples/agent-stage-latency/score.pynew file mode 100644index 000000000..6aa665e6d--- /dev/null+++ b/examples/agent-stage-latency/score.py@@ -0,0 +1,464 @@+"""Strict offline accounting and paired base-cluster bootstrap; no network or credentials."""++from __future__ import annotations++import argparse+import json+import random+import statistics+from collections import defaultdict+from pathlib import Path+from typing import Any++from fetch import write_exclusive+from prepare import load_packet+from protocol import MODELS, compose, digest, masked, positive, require, sha256, validate_reply+from run import operation_identity, subcall_identity+++def quantile(values: list[float], probability: float) -> float:+ ordered = sorted(values)+ at = (len(ordered) - 1) * probability+ lower = int(at)+ upper = min(lower + 1, len(ordered) - 1)+ return ordered[lower] + (ordered[upper] - ordered[lower]) * (at - lower)+++def elapsed_summary(values: list[float]) -> dict[str, Any]:+ return (+ {"count": len(values), "p50_s": quantile(values, 0.5), "p90_s": quantile(values, 0.9)}+ if values+ else {"count": 0, "p50_s": None, "p90_s": None}+ )+++def stage_qualifies(stage: dict[str, Any], paired: bool) -> bool:+ if paired:+ return bool(stage["paired_latency"].get("qualifying", False))+ return stage["accounting"]["sie"]["successful"] > 0+++def paired_bootstrap(clusters: list[list[tuple[float, float]]], settings: dict[str, Any]) -> dict[str, Any]:+ require(all(positive(s) and positive(r) for cluster in clusters for s, r in cluster), "Invalid paired timing")+ cohort = "successful complete paired base-case clusters"+ if len(clusters) < settings["minimum_clusters"]:+ rows = [pair for cluster in clusters for pair in cluster]+ return {+ "status": "insufficient",+ "cohort": cohort,+ "base_clusters": len(clusters),+ "pairs": len(rows),+ "sie_median_s": statistics.median(s for s, _ in rows) if rows else None,+ "rival_median_s": statistics.median(r for _, r in rows) if rows else None,+ "sie_median_percentile_95": None,+ "rival_median_percentile_95": None,+ }++ def estimate(rows: list[tuple[float, float]]) -> tuple[float, float, float, float]:+ sie = statistics.median(s for s, _ in rows)+ rival = statistics.median(r for _, r in rows)+ return rival - sie, rival / sie, sie, rival++ point = estimate([pair for cluster in clusters for pair in cluster])+ randomizer = random.Random(settings["seed"])+ samples = [+ estimate([pair for _ in clusters for pair in randomizer.choice(clusters)]) for _ in range(settings["resamples"])+ ]+ return {+ "status": "estimated",+ "cohort": cohort,+ "base_clusters": len(clusters),+ "pairs": sum(map(len, clusters)),+ "difference_rival_minus_sie_s": point[0],+ "ratio_rival_over_sie": point[1],+ "sie_median_s": point[2],+ "rival_median_s": point[3],+ "sie_median_percentile_95": [quantile([s[2] for s in samples], p) for p in (0.025, 0.975)],+ "rival_median_percentile_95": [quantile([s[3] for s in samples], p) for p in (0.025, 0.975)],+ "difference_percentile_95": [quantile([s[0] for s in samples], p) for p in (0.025, 0.975)],+ "ratio_percentile_95": [quantile([s[1] for s in samples], p) for p in (0.025, 0.975)],+ "bootstrap": settings,+ }+++def read_journal(path: Path, packet: dict[str, Any]) -> tuple[list[dict[str, Any]], dict[str, Any] | None, str | None]:+ body = path.read_bytes()+ rows, previous, truncated = [], None, None+ lines = body.splitlines(keepends=True)+ for index, line in enumerate(lines):+ if not line.endswith(b"\n"):+ require(index == len(lines) - 1, "Malformed journal boundary")+ truncated = sha256(line)+ break+ try:+ row = json.loads(line)+ except (ValueError, UnicodeDecodeError):+ require(index == len(lines) - 1 and not line.endswith(b"\n"), "Malformed journal row")+ truncated = sha256(line)+ break+ content = {k: v for k, v in row.items() if k != "entry_digest"}+ require(+ row["entry_digest"] == digest(content) and row["previous_digest"] == previous and row["sequence"] == index,+ "Journal hash chain differs",+ )+ require(+ all(row[k] == packet[k] for k in ("packet_digest", "protocol_digest", "source_digest")),+ "Mixed packet/source/protocol",+ )+ previous = row["entry_digest"]+ rows.append(row)+ end_path = path.with_name(path.name + ".end.json")+ end = json.loads(end_path.read_bytes()) if end_path.exists() else None+ if end is not None:+ require(+ end["end_digest"] == digest({k: v for k, v in end.items() if k != "end_digest"}),+ "Terminal record digest differs",+ )+ require(+ all(end[k] == packet[k] for k in ("packet_digest", "protocol_digest", "source_digest")),+ "Mixed terminal record",+ )+ require(+ end["journal_digest"] == sha256(body)+ and end["reason"] in ("finished", "deadline", "interrupted", "child_failure"),+ "Terminal journal binding differs",+ )+ require(positive(end["elapsed_s"]), "Invalid total duration")+ require(truncated is None or end["reason"] != "finished", "Truncated journal cannot be finished")+ return rows, end, truncated+++def accounting(keys: list[Any], intents: dict[Any, Any], outcomes: dict[Any, Any]) -> dict[str, Any]:+ 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),+ "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),+ "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": [+ {"identity": str(k), "error": outcomes[k]["error"], "elapsed_s": outcomes[k]["elapsed_s"]}+ for k in keys+ if k in outcomes and outcomes[k]["status"] == "failed"+ ],+ }+++def score_trial(packet_path: Path, journal_path: Path) -> dict[str, Any]:+ packet = load_packet(packet_path)+ rows, end, truncated = read_journal(journal_path, packet)+ require(+ bool(rows) and rows[0]["event"] == "run_start" and sum(r["event"] == "run_start" for r in rows) == 1,+ "Missing/duplicate run metadata",+ )+ config = packet["config"]+ require(+ rows[0]["wall_limit_s"] == config["wall_limit_s"] and rows[0]["placement_label"] == config["placement_label"],+ "Run trial settings differ",+ )+ require(+ rows[0]["timeout_budgets_s"] == {k: config["request_timeout_s"] for k in ("connect", "read", "provision")},+ "Run request budgets differ",+ )+ operations, calls = {}, {}+ for obs in packet["observations"]:+ for arm in obs["arm_order"]:+ operations[(obs["observation_id"], arm)] = (obs, operation_identity(obs, arm))+ for index in range(len(obs["requests"][arm])):+ identity = subcall_identity(obs, arm, index)+ calls[identity["call_id"]] = (obs, identity)+ op_intents, op_results, call_intents, call_results = {}, {}, {}, {}+ dispatches: dict[str, list[dict[str, Any]]] = defaultdict(list)+ responses: dict[str, list[dict[str, Any]]] = defaultdict(list)+ discovery_intent, discovery_result = None, None+ active_operation = None+ expected_op_order = list(operations)+ next_operation = 0+ active_calls = set()+ for row in rows[1:]:+ event = row["event"]+ if event in ("discovery_intent", "discovery_result"):+ require(row["call_id"] == "metadata" and not op_intents, "Unexpected discovery")+ if event == "discovery_intent":+ require(discovery_intent is None and discovery_result is None, "Duplicate discovery intent")+ discovery_intent = row+ else:+ require(discovery_intent is not None and discovery_result is None, "Unexpected discovery terminal")+ require(+ row["status"] in ("success", "failed") and positive(row["elapsed_s"]), "Invalid discovery outcome"+ )+ discovery_result = row+ continue+ if event in ("operation_intent", "operation_result"):+ key = (row["observation_id"], row["arm"])+ require(+ key in operations and all(row[k] == v for k, v in operations[key][1].items()),+ "Unexpected operation identity/request",+ )+ if event == "operation_intent":+ require(+ key not in op_intents+ and active_operation is None+ and next_operation < len(expected_op_order)+ and key == expected_op_order[next_operation],+ "Duplicate, overlapping or reordered operation",+ )+ op_intents[key] = row+ active_operation = key+ next_operation += 1+ else:+ require(+ key in op_intents and key not in op_results and active_operation == key and not active_calls,+ "Unexpected operation terminal",+ )+ require(+ row["status"] in ("success", "failed") and positive(row["elapsed_s"]),+ "Invalid operation duration/status",+ )+ if row["status"] == "failed":+ require(isinstance(row.get("error"), dict), "Missing failure evidence")+ expected_calls = [+ cid for cid, (_, identity) in calls.items() if (identity["observation_id"], identity["arm"]) == key+ ]+ if row["status"] == "success":+ require(+ all(cid in call_results and call_results[cid]["status"] == "success" for cid in expected_calls),+ "Success hides missing/failed constituent calls",+ )+ obs = operations[key][0]+ validated = [+ validate_reply(+ obs["stage"],+ row["arm"],+ call_results[cid]["reply"],+ obs["unit"]["data"],+ obs["requests"][row["arm"]][calls[cid][1]["request_index"]],+ )+ for cid in expected_calls+ ]+ if obs["stage"] == "M" and row["arm"] == "sie":+ paths = [+ [+ entity+ for cid, entities in zip(expected_calls, validated, strict=True)+ if calls[cid][1]["model"] == model+ for entity in entities+ ]+ for model in MODELS["M"]+ ]+ spans = compose(obs["unit"]["data"]["text"], paths)+ require(row["result"]["spans"] == spans, "Caller composition result differs")+ require(+ "[REDACTED_CREDENTIAL]" in row["result"]["masked"]+ or row["result"]["masked"] == masked(obs["unit"]["data"]["text"], spans),+ "Caller mask differs",+ )+ else:+ require(row["result"] == validated[0], "Operation result differs from its constituent reply")+ require(+ all(+ row["elapsed_s"] >= call_results[cid]["elapsed_s"]+ for cid in expected_calls+ if cid in call_results+ ),+ "Operation timer excludes a subcall",+ )+ op_results[key] = row+ active_operation = None+ continue+ if event in ("call_intent", "call_result", "dispatch", "response"):+ cid = row["call_id"]+ if cid == "metadata":+ require(+ event in ("dispatch", "response") and discovery_intent is not None and discovery_result is None,+ "Unexpected metadata HTTP event",+ )+ else:+ require(+ cid in calls and all(row[k] == v for k, v in calls[cid][1].items()),+ "Unexpected subcall identity/request",+ )+ op_key = (row["observation_id"], row["arm"])+ require(active_operation == op_key, "Subcall outside its operation")+ if event == "call_intent":+ require(cid not in call_intents, "Duplicate call intent")+ call_intents[cid] = row+ active_calls.add(cid)+ obs, identity = calls[cid]+ limit = 2 if obs["stage"] == "M" and row["arm"] == "sie" else 1+ require(len(active_calls) <= limit, "Exceeded dispatch concurrency")+ require(+ not any(calls[other][1]["model"] == identity["model"] for other in active_calls if other != cid),+ "Overlapping windows in one model path",+ )+ elif event == "call_result":+ require(+ cid in call_intents and cid not in call_results and cid in active_calls,+ "Duplicate/unstarted call terminal",+ )+ require(+ row["status"] in ("success", "failed") and positive(row["elapsed_s"]), "Invalid subcall outcome"+ )+ require(+ row["physical_dispatches"] == len(dispatches[cid])+ and type(row["sdk_retry_count"]) is int+ and row["sdk_retry_count"] >= 0,+ "Retry dispatch count differs",+ )+ if row["status"] == "success":+ obs, identity = calls[cid]+ validate_reply(+ obs["stage"],+ row["arm"],+ row["reply"],+ obs["unit"]["data"],+ obs["requests"][row["arm"]][identity["request_index"]],+ )+ require(+ len(responses[cid]) == len(dispatches[cid]) and bool(dispatches[cid]),+ "Successful call lacks completed HTTP evidence",+ )+ else:+ require(isinstance(row.get("error"), dict), "Missing subcall failure evidence")+ call_results[cid] = row+ active_calls.remove(cid)+ elif event == "dispatch":+ require(cid == "metadata" or cid in active_calls, "Dispatch before durable 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)+ else:+ require(cid == "metadata" or cid in active_calls, "Response after terminal")+ require(+ row["dispatch_index"] == len(responses[cid]) + 1 and len(dispatches[cid]) == row["dispatch_index"],+ "Unexpected physical response",+ )+ require(+ type(row["status"]) is int and 100 <= row["status"] <= 599 and positive(row["elapsed_s"]),+ "Invalid HTTP result",+ )+ responses[cid].append(row)+ continue+ raise ValueError("Unknown journal event")+ complete = (+ end is not None+ and end["reason"] == "finished"+ and truncated is None+ and len(op_results) == len(operations)+ and len(call_results) == len(calls)+ )+ result: dict[str, Any] = {+ "schema": 1,+ "packet_digest": packet["packet_digest"],+ "protocol_digest": packet["protocol_digest"],+ "complete": complete,+ "qualifying_confirmatory": complete and config["phase"] == "confirmatory",+ "ending": end,+ "truncated_tail_sha256": truncated,+ "discovery": discovery_result,+ "statistics_scope": "client wall time; successful complete base-case pairs, independent stages",+ "phases": {},+ "stages": {},+ }+ for phase in ("warmup", config["phase"]):+ result["phases"][phase] = {}+ for stage in config["stages"]:+ arms = ["sie", "rival"] if config["arms"] == "paired" else ["sie"]+ result["phases"][phase][stage] = {}+ for arm in arms:+ op_keys = [+ key+ for key, (obs, _) in operations.items()+ if obs["stage"] == stage and obs["phase"] == phase and key[1] == arm+ ]+ call_keys = [+ cid+ for cid, (obs, identity) in calls.items()+ 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)+ 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["sdk_retries"] = sum(+ call_results[cid]["sdk_retry_count"] for cid in call_keys if cid in call_results+ )+ result["phases"][phase][stage][arm] = summary+ if phase != "confirmatory":+ continue+ selected = [o for o in packet["observations"] if o["stage"] == stage and o["phase"] == phase]+ by_base: dict[str, list[dict[str, Any]]] = defaultdict(list)+ for obs in selected:+ by_base[obs["base_id"]].append(obs)+ clusters = []+ if config["arms"] == "paired":+ for group in by_base.values():+ if all(+ (o["observation_id"], arm) in op_results+ and op_results[(o["observation_id"], arm)]["status"] == "success"+ for o in group+ for arm in ("sie", "rival")+ ):+ clusters.append(+ [+ (+ op_results[(o["observation_id"], "sie")]["elapsed_s"],+ op_results[(o["observation_id"], "rival")]["elapsed_s"],+ )+ for o in group+ ]+ )+ comparison = (+ paired_bootstrap(clusters, config["bootstrap"])+ if config["arms"] == "paired"+ else {"status": "sie_only", "pairs": 0, "base_clusters": 0}+ )+ comparison["excluded_base_clusters"] = len(by_base) - len(clusters) if config["arms"] == "paired" else 0+ comparison["excluded_pairs"] = len(selected) - sum(map(len, clusters)) if config["arms"] == "paired" else 0+ comparison["qualifying"] = complete and comparison["status"] == "estimated"+ result["stages"][stage] = {"accounting": result["phases"][phase][stage], "paired_latency": comparison}+ if config["phase"] == "pilot":+ result["stages"] = {+ stage: {+ "accounting": result["phases"]["pilot"][stage],+ "paired_latency": {"status": "pilot_only", "qualifying": False},+ }+ for stage in config["stages"]+ }+ result["qualifying_confirmatory"] = (+ complete+ and config["phase"] == "confirmatory"+ and all(stage_qualifies(stage, config["arms"] == "paired") for stage in result["stages"].values())+ )+ return result+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--packet", type=Path, required=True)+ parser.add_argument("--journal", type=Path, required=True)+ parser.add_argument("--out", type=Path, help="new report destination; otherwise prints the report")+ args = parser.parse_args()+ try:+ if args.out is not None:+ require(not args.out.exists(), "Report already exists")+ report = score_trial(args.packet, args.journal)+ if args.out is not None:+ write_exclusive(args.out, report)+ else:+ print(json.dumps(report, indent=2))+ except (OSError, ValueError, KeyError, TypeError):+ raise SystemExit(+ "Scoring rejected the packet or journal. "+ "Preserve the original files; check their bindings and completeness."+ ) from None+++if __name__ == "__main__":+ main()diff --git a/examples/agent-stage-latency/sources.json b/examples/agent-stage-latency/sources.jsonnew file mode 100644index 000000000..c3c86b11d--- /dev/null+++ b/examples/agent-stage-latency/sources.json@@ -0,0 +1,665 @@+{+ "schema": 1,+ "canonical_json": "UTF-8, sort_keys=true, compact separators, ensure_ascii=false, allow_nan=false, no newline",+ "files": [+ {+ "path": "G/manifest.json",+ "repository": "superlinked/sie-task-evidence",+ "revision": "b45775c419e37212cef67f485610eda88ee29491",+ "remote_path": "guardrails/manifest.json",+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/b45775c419e37212cef67f485610eda88ee29491/guardrails/manifest.json",+ "bytes": 9562,+ "sha256": "0045cf212716365526d8fe9054401ed0ae1c8461b93660b6b2b5f3944c921f23",+ "license": "Public evidence provenance metadata"+ },+ {+ "path": "M/manifest.json",+ "repository": "superlinked/sie-task-evidence",+ "revision": "31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb",+ "remote_path": "redact/manifest.json",+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb/redact/manifest.json",+ "bytes": 7067,+ "sha256": "8170519b9ad94c35dd53f2d22d96689d41e9c0e26d9c0fc25bba83230cbee4dc",+ "license": "Public evidence provenance metadata"+ },+ {+ "path": "M/gretel-main.jsonl",+ "repository": "superlinked/sie-task-evidence",+ "revision": "31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb",+ "remote_path": "redact/inputs/gretel-main.jsonl",+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb/redact/inputs/gretel-main.jsonl",+ "bytes": 1152633,+ "sha256": "26a852c436e63adc7612870add49fe6afb24f9c4cf49d6233e57e59d0ccd7787",+ "license": "Apache-2.0; gretelai/synthetic_pii_finance_multilingual, English test split"+ },+ {+ "path": "E/manifest.json",+ "repository": "superlinked/sie-task-evidence",+ "revision": "b939e41046eef6a0c2a9ee60c152161fd3fb7e04",+ "remote_path": "lookalike-search/manifest.json",+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/b939e41046eef6a0c2a9ee60c152161fd3fb7e04/lookalike-search/manifest.json",+ "bytes": 1445,+ "sha256": "831c4a8e6d14596d0695c0dc2ab949288c7d9db5e542173e068e5eb31d8b9751",+ "license": "Public evidence provenance metadata"+ },+ {+ "path": "E/questions.json",+ "repository": "superlinked/sie-task-evidence",+ "revision": "b939e41046eef6a0c2a9ee60c152161fd3fb7e04",+ "remote_path": "lookalike-search/inputs/questions.json",+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/b939e41046eef6a0c2a9ee60c152161fd3fb7e04/lookalike-search/inputs/questions.json",+ "bytes": 130139,+ "sha256": "70b20ed7f9f43d6bc5d3d0d531b0d2557384c1f362b44fa17c49e68caa531c54",+ "license": "Public held-out questions; see source publications at https://superlinked.com/reference/search/SOURCES.md for provenance and terms"+ },+ {+ "path": "R/manifest.json",+ "repository": "superlinked/sie-task-evidence",+ "revision": "e5b19d7589fc3a982fcfeeabb071cf833c22455f",+ "remote_path": "rerank-relevance-rules/manifest.json",+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/e5b19d7589fc3a982fcfeeabb071cf833c22455f/rerank-relevance-rules/manifest.json",+ "bytes": 2508,+ "sha256": "8fe1d86a33ff633890780236387125f6002dde45853f6e7fa53815d6c1c306d4",+ "license": "Apache-2.0; Federal Register source corpus public domain"+ },+ {+ "path": "R/cases_test.json",+ "repository": "superlinked/sie-task-evidence",+ "revision": "e5b19d7589fc3a982fcfeeabb071cf833c22455f",+ "remote_path": "rerank-relevance-rules/inputs/cases_test.json",+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/e5b19d7589fc3a982fcfeeabb071cf833c22455f/rerank-relevance-rules/inputs/cases_test.json",+ "bytes": 11667804,+ "sha256": "1d32077e5679be1afa8ed40a0b1893ee8181225c02b7ff6aeafdf29d9ee0c203",+ "license": "Apache-2.0; Federal Register source corpus public domain"+ },+ {+ "path": "G/toxicchat.csv",+ "repository": "lmsys/toxic-chat",+ "revision": "29df8e4dba60e1f4af4b4075c0705c5b313548a8",+ "remote_path": "data/0124/toxic-chat_annotation_test.csv",+ "url": "https://huggingface.co/datasets/lmsys/toxic-chat/resolve/29df8e4dba60e1f4af4b4075c0705c5b313548a8/data/0124/toxic-chat_annotation_test.csv",+ "bytes": 8090164,+ "sha256": "3c2e49889626f7738dca0a29bface0ba0a0595b2ffdd17f0e02f19df7c3c4c9b",+ "license": "CC-BY-NC-4.0"+ },+ {+ "path": "G/aegis.json",+ "repository": "nvidia/Aegis-AI-Content-Safety-Dataset-2.0",+ "revision": "d86bb8bedff51d25ac834ab7838f1cc61acb7a2c",+ "remote_path": "test.json",+ "url": "https://huggingface.co/datasets/nvidia/Aegis-AI-Content-Safety-Dataset-2.0/resolve/d86bb8bedff51d25ac834ab7838f1cc61acb7a2c/test.json",+ "bytes": 1731373,+ "sha256": "b0a6d602260524866053cb34105194f074f2c2906e3691b68d43b9e6e9318f35",+ "license": "CC-BY-4.0"+ }+ ],+ "request_bindings": {+ "G": {+ "source_example": "guardrails",+ "requests": {+ "sie": {+ "None": [+ {+ "method": "chat_completions",+ "model": "Qwen/Qwen3Guard-Gen-4B",+ "body": {+ "messages": [+ {+ "role": "user",+ "content": "{source_text}"+ }+ ],+ "temperature": 0,+ "max_tokens": 64+ },+ "request_digest": "0ed41436f97c1d4020d54893932bf6269246d22f1e1c53a51e3ef714f7d12c1a"+ }+ ]+ },+ "rival": {+ "None": [+ {+ "method": "messages",+ "provider": "anthropic",+ "model": "claude-haiku-4-5",+ "path": "/v1/messages",+ "body": {+ "model": "claude-haiku-4-5",+ "temperature": 0,+ "max_tokens": 10,+ "messages": [+ {+ "role": "user",+ "content": "Is the following user message harmful? Answer with exactly one word: harmful or unharmful.\n\nMessage:\n{source_text}"+ }+ ]+ },+ "request_digest": "01ebd694ea1be7c761054d432444a3d93ff01fec3be5ffa9127afd66a70ae86d"+ }+ ]+ }+ }+ },+ "M": {+ "source_example": "redact",+ "requests": {+ "sie": {+ "None": [+ {+ "method": "extract",+ "model": "urchade/gliner_multi_pii-v1",+ "window": 0,+ "offset": 0,+ "body": {+ "item": {+ "text": "{source_text}"+ },+ "labels": [+ "person",+ "street address",+ "city",+ "county",+ "postal code",+ "gps coordinates",+ "date of birth",+ "phone number",+ "fax number",+ "email address",+ "url",+ "ip address",+ "mac address",+ "social security number",+ "national id number",+ "tax id number",+ "medical record number",+ "health plan beneficiary number",+ "account number",+ "credit card number",+ "cvv",+ "pin",+ "password",+ "api key",+ "http cookie",+ "username",+ "customer id",+ "employee id",+ "certificate or license number",+ "license plate",+ "vehicle identification number",+ "device identifier",+ "biometric identifier",+ "unique identifier",+ "passport number",+ "driver's license number"+ ]+ },+ "request_digest": "34e0fb4236a76aea2c142b0ebbb2b4cf40c8366dccf2989a3d6e3df22ed656ff"+ },+ {+ "method": "extract",+ "model": "numind/NuNER_Zero",+ "window": 0,+ "offset": 0,+ "body": {+ "item": {+ "text": "{source_text}"+ },+ "labels": [+ "person",+ "street address",+ "city",+ "county",+ "postal code",+ "gps coordinates",+ "date of birth",+ "phone number",+ "fax number",+ "email address",+ "url",+ "ip address",+ "mac address",+ "social security number",+ "national id number",+ "tax id number",+ "medical record number",+ "health plan beneficiary number",+ "account number",+ "credit card number",+ "cvv",+ "pin",+ "password",+ "api key",+ "http cookie",+ "username",+ "customer id",+ "employee id",+ "certificate or license number",+ "license plate",+ "vehicle identification number",+ "device identifier",+ "biometric identifier",+ "unique identifier",+ "passport number",+ "driver's license number"+ ]+ },+ "request_digest": "ef6fe30c7d65f3ec148273b810f5ef7d66ab604d0668255f08962658422d0ad7"+ }+ ]+ },+ "rival": {+ "None": [+ {+ "method": "messages",+ "provider": "anthropic",+ "model": "claude-haiku-4-5",+ "path": "/v1/messages",+ "body": {+ "model": "claude-haiku-4-5",+ "temperature": 0,+ "max_tokens": 4096,+ "messages": [+ {+ "role": "user",+ "content": "{source_text}"+ }+ ],+ "system": "Find every piece of personally identifiable information in the text. Use these types: person, street address, city, county, postal code, gps coordinates, date of birth, phone number, fax number, email address, url, ip address, mac address, social security number, national id number, tax id number, medical record number, health plan beneficiary number, account number, credit card number, cvv, pin, password, api key, http cookie, username, customer id, employee id, certificate or license number, license plate, vehicle identification number, device identifier, biometric identifier, unique identifier, passport number, driver's license number. Copy each mention exactly as it appears in the text. Return an empty list if there is none.",+ "output_config": {+ "format": {+ "type": "json_schema",+ "schema": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "entities"+ ],+ "properties": {+ "entities": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "text",+ "type"+ ],+ "properties": {+ "text": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "enum": [+ "person",+ "street address",+ "city",+ "county",+ "postal code",+ "gps coordinates",+ "date of birth",+ "phone number",+ "fax number",+ "email address",+ "url",+ "ip address",+ "mac address",+ "social security number",+ "national id number",+ "tax id number",+ "medical record number",+ "health plan beneficiary number",+ "account number",+ "credit card number",+ "cvv",+ "pin",+ "password",+ "api key",+ "http cookie",+ "username",+ "customer id",+ "employee id",+ "certificate or license number",+ "license plate",+ "vehicle identification number",+ "device identifier",+ "biometric identifier",+ "unique identifier",+ "passport number",+ "driver's license number"+ ]+ }+ }+ }+ }+ }+ }+ }+ }+ },+ "request_digest": "3443b024663b2f1ef58fad1a5ddd0496458dc30d18c71d3a3bbaebdf5c7311a7"+ }+ ]+ }+ },+ "composition": {+ "window_units": 300,+ "overlap": 50,+ "score_floor": 0.6,+ "model_paths": 2,+ "serial_windows": true+ }+ },+ "E": {+ "source_example": "lookalike-search",+ "requests": {+ "sie": {+ "None": [+ {+ "method": "encode",+ "model": "Qwen/Qwen3-Embedding-4B",+ "body": {+ "item": {+ "text": "{source_text}"+ },+ "is_query": true+ },+ "request_digest": "61dd8890dcd4f31947e94470d95bf95fe3617e2d31c18e35d8602fc5fdaa4d38"+ }+ ]+ },+ "rival": {+ "None": [+ {+ "method": "embeddings",+ "provider": "openai",+ "model": "text-embedding-3-large",+ "path": "/v1/embeddings",+ "body": {+ "model": "text-embedding-3-large",+ "input": "{source_text}",+ "dimensions": 3072,+ "encoding_format": "float"+ },+ "request_digest": "c0a44db9987a091d19d2c3430caaea070e7190f1907f4efa8d27bad3355e5dea"+ }+ ]+ }+ }+ },+ "R": {+ "source_example": "rerank",+ "requests": {+ "sie": {+ "in-force": [+ {+ "method": "score",+ "model": "Qwen/Qwen3-Reranker-4B",+ "body": {+ "query": {+ "text": "{source_query}"+ },+ "items": [+ {+ "id": "{candidate_0_id}",+ "text": "{candidate_0_text}"+ },+ {+ "id": "{candidate_1_id}",+ "text": "{candidate_1_text}"+ },+ {+ "id": "{candidate_2_id}",+ "text": "{candidate_2_text}"+ },+ {+ "id": "{candidate_3_id}",+ "text": "{candidate_3_text}"+ },+ {+ "id": "{candidate_4_id}",+ "text": "{candidate_4_text}"+ },+ {+ "id": "{candidate_5_id}",+ "text": "{candidate_5_text}"+ },+ {+ "id": "{candidate_6_id}",+ "text": "{candidate_6_text}"+ },+ {+ "id": "{candidate_7_id}",+ "text": "{candidate_7_text}"+ },+ {+ "id": "{candidate_8_id}",+ "text": "{candidate_8_text}"+ },+ {+ "id": "{candidate_9_id}",+ "text": "{candidate_9_text}"+ },+ {+ "id": "{candidate_10_id}",+ "text": "{candidate_10_text}"+ },+ {+ "id": "{candidate_11_id}",+ "text": "{candidate_11_text}"+ },+ {+ "id": "{candidate_12_id}",+ "text": "{candidate_12_text}"+ },+ {+ "id": "{candidate_13_id}",+ "text": "{candidate_13_text}"+ },+ {+ "id": "{candidate_14_id}",+ "text": "{candidate_14_text}"+ },+ {+ "id": "{candidate_15_id}",+ "text": "{candidate_15_text}"+ },+ {+ "id": "{candidate_16_id}",+ "text": "{candidate_16_text}"+ },+ {+ "id": "{candidate_17_id}",+ "text": "{candidate_17_text}"+ },+ {+ "id": "{candidate_18_id}",+ "text": "{candidate_18_text}"+ },+ {+ "id": "{candidate_19_id}",+ "text": "{candidate_19_text}"+ }+ ],+ "instruction": "Return the final rule the agency has adopted on this subject, not a proposed rule. A proposal that is still open for comment is not relevant."+ },+ "request_digest": "88c5d7d241ee58c06ff2220d919dc78ef8e242bf3be100f36ebcf837117c17df"+ }+ ],+ "proposed": [+ {+ "method": "score",+ "model": "Qwen/Qwen3-Reranker-4B",+ "body": {+ "query": {+ "text": "{source_query}"+ },+ "items": [+ {+ "id": "{candidate_0_id}",+ "text": "{candidate_0_text}"+ },+ {+ "id": "{candidate_1_id}",+ "text": "{candidate_1_text}"+ },+ {+ "id": "{candidate_2_id}",+ "text": "{candidate_2_text}"+ },+ {+ "id": "{candidate_3_id}",+ "text": "{candidate_3_text}"+ },+ {+ "id": "{candidate_4_id}",+ "text": "{candidate_4_text}"+ },+ {+ "id": "{candidate_5_id}",+ "text": "{candidate_5_text}"+ },+ {+ "id": "{candidate_6_id}",+ "text": "{candidate_6_text}"+ },+ {+ "id": "{candidate_7_id}",+ "text": "{candidate_7_text}"+ },+ {+ "id": "{candidate_8_id}",+ "text": "{candidate_8_text}"+ },+ {+ "id": "{candidate_9_id}",+ "text": "{candidate_9_text}"+ },+ {+ "id": "{candidate_10_id}",+ "text": "{candidate_10_text}"+ },+ {+ "id": "{candidate_11_id}",+ "text": "{candidate_11_text}"+ },+ {+ "id": "{candidate_12_id}",+ "text": "{candidate_12_text}"+ },+ {+ "id": "{candidate_13_id}",+ "text": "{candidate_13_text}"+ },+ {+ "id": "{candidate_14_id}",+ "text": "{candidate_14_text}"+ },+ {+ "id": "{candidate_15_id}",+ "text": "{candidate_15_text}"+ },+ {+ "id": "{candidate_16_id}",+ "text": "{candidate_16_text}"+ },+ {+ "id": "{candidate_17_id}",+ "text": "{candidate_17_text}"+ },+ {+ "id": "{candidate_18_id}",+ "text": "{candidate_18_text}"+ },+ {+ "id": "{candidate_19_id}",+ "text": "{candidate_19_text}"+ }+ ],+ "instruction": "Return the proposed rule the agency has published for comment on this subject, not a final rule. A rule already adopted is not relevant."+ },+ "request_digest": "20cd1146bbdf56ea36730d774af5f042fdff912ee382061838586b8820b01ba5"+ }+ ]+ },+ "rival": {+ "in-force": [+ {+ "method": "rerank",+ "provider": "cohere",+ "model": "rerank-v4.0-pro",+ "path": "/v2/rerank",+ "body": {+ "model": "rerank-v4.0-pro",+ "query": "Instruction: Return the final rule the agency has adopted on this subject, not a proposed rule. A proposal that is still open for comment is not relevant.\nQuery: {source_query}",+ "documents": [+ "{candidate_0_text}",+ "{candidate_1_text}",+ "{candidate_2_text}",+ "{candidate_3_text}",+ "{candidate_4_text}",+ "{candidate_5_text}",+ "{candidate_6_text}",+ "{candidate_7_text}",+ "{candidate_8_text}",+ "{candidate_9_text}",+ "{candidate_10_text}",+ "{candidate_11_text}",+ "{candidate_12_text}",+ "{candidate_13_text}",+ "{candidate_14_text}",+ "{candidate_15_text}",+ "{candidate_16_text}",+ "{candidate_17_text}",+ "{candidate_18_text}",+ "{candidate_19_text}"+ ],+ "top_n": 20,+ "max_tokens_per_doc": 4096+ },+ "request_digest": "d8c36300a0713bf9113a77fbae5040cddcd694799ec4c5a9b819233b61e70d35"+ }+ ],+ "proposed": [+ {+ "method": "rerank",+ "provider": "cohere",+ "model": "rerank-v4.0-pro",+ "path": "/v2/rerank",+ "body": {+ "model": "rerank-v4.0-pro",+ "query": "Instruction: Return the proposed rule the agency has published for comment on this subject, not a final rule. A rule already adopted is not relevant.\nQuery: {source_query}",+ "documents": [+ "{candidate_0_text}",+ "{candidate_1_text}",+ "{candidate_2_text}",+ "{candidate_3_text}",+ "{candidate_4_text}",+ "{candidate_5_text}",+ "{candidate_6_text}",+ "{candidate_7_text}",+ "{candidate_8_text}",+ "{candidate_9_text}",+ "{candidate_10_text}",+ "{candidate_11_text}",+ "{candidate_12_text}",+ "{candidate_13_text}",+ "{candidate_14_text}",+ "{candidate_15_text}",+ "{candidate_16_text}",+ "{candidate_17_text}",+ "{candidate_18_text}",+ "{candidate_19_text}"+ ],+ "top_n": 20,+ "max_tokens_per_doc": 4096+ },+ "request_digest": "64d8220eb638ddd7e54e2190d1e6ef271537479f4caa1791ffa7c9b760846552"+ }+ ]+ }+ },+ "provider_settings_provenance": "New-trial documented Cohere v2 request; historical body and API version were not retained. https://docs.cohere.com/v2/reference/rerank"+ }+ }+}diff --git a/examples/agent-stage-latency/tests/test_example.py b/examples/agent-stage-latency/tests/test_example.pynew file mode 100644index 000000000..0cc1c0c00--- /dev/null+++ b/examples/agent-stage-latency/tests/test_example.py@@ -0,0 +1,875 @@+"""Credential-free protocol, durability and accounting tests using the real SDK."""++from __future__ import annotations++import contextlib+import json+import multiprocessing+import random+import struct+import subprocess+import sys+import threading+import time+from collections import Counter+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any++import msgpack+import pytest++HERE = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(HERE))++import fetch # noqa: E402+import prepare # noqa: E402+import protocol # noqa: E402+import run # noqa: E402+import score # noqa: E402+++def config(**changes: Any) -> dict[str, Any]:+ return {+ "n": 2,+ "seed": 19,+ "stages": list(protocol.STAGES),+ "arms": "paired",+ "phase": "confirmatory",+ "warmup": 0,+ "request_timeout_s": 3.0,+ "wall_limit_s": 15.0,+ "placement_label": "local-fixture",+ "bootstrap": {"seed": 17, "resamples": 100, "quantile": "linear-(n-1)p", "minimum_clusters": 2},+ **changes,+ }+++def population(count: int = 8, *, long: bool = False) -> dict[str, list[dict[str, Any]]]:+ result = {}+ for stage in protocol.STAGES:+ cohort = next(+ e["sha256"]+ for e in protocol.sources()["files"]+ if e["path"].startswith(stage + "/") and not e["path"].endswith("manifest.json")+ )+ rows = []+ for index in range(count):+ text = f"Élodie {index} met Élodie."+ if long:+ text += " café-name " * 620 + "終わり"+ data = (+ {+ "query": f"Question {index}",+ "candidates": [+ {"id": f"c{candidate}", "text": f"Candidate {candidate}"} for candidate in range(20)+ ],+ }+ if stage == "R"+ else {"text": text}+ )+ rows.append(prepare.unit(stage, cohort, f"fixture:{index}", data))+ result[stage] = rows+ return result+++def packet_file(tmp_path: Path, *, long: bool = False, **changes: Any) -> tuple[Path, dict[str, Any]]:+ packet = prepare.build_packet(population(long=long), config(**changes))+ path = tmp_path / "packet.json"+ fetch.write_exclusive(path, packet)+ assert prepare.load_packet(path) == packet+ return path, packet+++def journal_rows(path: Path) -> list[dict[str, Any]]:+ return [json.loads(line) for line in path.read_bytes().splitlines() if line.endswith(b"}")]+++def rechain(path: Path, rows: list[dict[str, Any]]) -> None:+ previous = None+ with path.open("wb") as output:+ for sequence, row in enumerate(rows):+ content = {k: v for k, v in row.items() if k != "entry_digest"} | {+ "sequence": sequence,+ "previous_digest": previous,+ }+ previous = protocol.digest(content)+ output.write(protocol.canonical({**content, "entry_digest": previous}) + b"\n")+ end_path = path.with_name(path.name + ".end.json")+ if end_path.exists():+ end = json.loads(end_path.read_bytes())+ end["journal_digest"] = protocol.sha256(path.read_bytes())+ end["end_digest"] = protocol.digest({k: v for k, v in end.items() if k != "end_digest"})+ end_path.write_bytes(protocol.canonical(end) + b"\n")+++class FakeServer:+ def __init__(+ self,+ journal: Path,+ *,+ delay: float = 0,+ fail_at: int | None = None,+ retry: bool = False,+ malformed: bool = False,+ catalog: bool = True,+ revision_headers: bool = True,+ loading_sleep: bool = False,+ ) -> None:+ self.journal = journal+ self.delay = delay+ self.fail_at = fail_at+ self.retry = retry+ self.malformed = malformed+ self.catalog = catalog+ self.revision_headers = revision_headers+ self.loading_sleep = loading_sleep+ self.lock = threading.Lock()+ self.captures: list[dict[str, Any]] = []+ self.errors: list[str] = []+ self.active = 0+ self.maximum = 0+ self.counts: Counter[str] = Counter()+ self.observed = threading.Event()+ fixture = self++ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, format: str, *args: Any) -> None:+ pass++ def reply(+ self, payload: Any, status: int = 200, *, native: bool = False, headers: dict[str, str] | None = None+ ) -> None:+ body = msgpack.packb(payload, use_bin_type=True) if native else json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/msgpack" if native else "application/json")+ self.send_header("Content-Length", str(len(body)))+ for key, value in (headers or {}).items():+ self.send_header(key, value)+ self.end_headers()+ with contextlib.suppress(BrokenPipeError, ConnectionResetError):+ self.wfile.write(body)++ def do_GET(self) -> None:+ models = [+ {"name": model, "revision": "e" * 40, "dims": 2560, "worker_host": "private-telemetry-sentinel"}+ for group in protocol.MODELS.values()+ for model in group+ ]+ self.reply({"models": models} if fixture.catalog else {"models": []})++ def do_POST(self) -> None:+ body = self.rfile.read(int(self.headers["Content-Length"]))+ data = (+ msgpack.unpackb(body, raw=False)+ if self.headers.get("Content-Type") == "application/msgpack"+ else json.loads(body)+ )+ model = self.path.split("/v1/extract/", 1)[-1] if "/v1/extract/" in self.path else data.get("model", "")+ with fixture.lock:+ fixture.active += 1+ fixture.maximum = max(fixture.maximum, fixture.active)+ fixture.counts[self.path] += 1+ ordinal = fixture.counts[self.path]+ fixture.captures.append(+ {+ "path": self.path,+ "body": data,+ "model": model,+ "auth": self.headers.get("Authorization"),+ "api_key": self.headers.get("x-api-key"),+ "port": self.client_address[1],+ }+ )+ 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")+ fixture.observed.set()+ try:+ if fixture.delay:+ time.sleep(fixture.delay)+ if fixture.loading_sleep and self.path.startswith("/v1/encode/"):+ self.reply(+ {"detail": {"code": "MODEL_LOADING", "message": "loading"}},+ 503,+ headers={"Retry-After": "10"},+ )+ return+ if fixture.retry and ordinal == 1 and "NuNER_Zero" in self.path:+ self.reply(+ {"detail": {"code": "MODEL_LOADING", "message": "loading"}},+ 503,+ headers={"Retry-After": "0.01"},+ )+ return+ revision = "a" * 64 if "gliner" in self.path else "b" * 64+ headers = {+ "X-SIE-Model-Revision": revision,+ "X-SIE-Execution-Identity-SHA256": "c" * 64,+ "X-SIE-Execution-Binding-SHA256": "d" * 64,+ }+ if not fixture.revision_headers:+ headers = {}+ if self.path == "/v1/chat/completions":+ text = "fake-auth-sentinel" if fixture.malformed else "Safety: Safe"+ self.reply(+ {+ "model": data["model"],+ "choices": [+ {"message": {"role": "assistant", "content": text}, "finish_reason": "stop"}+ ],+ },+ headers=headers,+ )+ elif self.path.startswith("/v1/extract/"):+ text = data["items"][0]["text"]+ at = text.find("Élodie")+ entities = (+ [{"text": "Élodie", "start": at, "end": at + 6, "label": "person", "score": 0.6}]+ if at >= 0+ else []+ )+ item: dict[str, Any] = {"entities": entities}+ if fixture.fail_at is not None and "gliner" in self.path and ordinal == fixture.fail_at:+ item = {+ "entities": [],+ "error": {"code": "INVALID_ARGUMENT", "message": "fake-auth-sentinel"},+ }+ self.reply({"model": model, "items": [item]}, native=True, headers=headers)+ elif self.path.startswith("/v1/encode/"):+ self.reply(+ {+ "model": protocol.MODELS["E"][0],+ "items": [+ {+ "dense": {+ "dims": 2560,+ "values": {+ b"nd": True,+ b"type": "<f4",+ b"kind": b"",+ b"shape": [2560],+ b"data": struct.pack("<2560f", *([0.125] * 2560)),+ },+ }+ }+ ],+ },+ native=True,+ headers=headers,+ )+ elif self.path.startswith("/v1/score/"):+ self.reply(+ {+ "model": protocol.MODELS["R"][0],+ "scores": [+ {"item_id": item["id"], "score": 1 / (rank + 1), "rank": rank + 1}+ for rank, item in enumerate(reversed(data["items"]))+ ],+ },+ native=True,+ headers=headers,+ )+ elif self.path == "/v1/messages":+ text = (+ "unharmful"+ if data["max_tokens"] == 10+ else json.dumps({"entities": [{"text": "Élodie", "type": "person"}]})+ )+ self.reply(+ {+ "model": "claude-haiku-4-5",+ "content": [{"type": "text", "text": text}],+ "stop_reason": "end_turn",+ }+ )+ elif self.path == "/v1/embeddings":+ self.reply({"model": data["model"], "data": [{"index": 0, "embedding": [0.25] * 3072}]})+ elif self.path == "/v2/rerank":+ self.reply(+ {+ "results": [+ {"index": index, "relevance_score": index / 20} for index in reversed(range(20))+ ]+ }+ )+ else:+ fixture.errors.append("Unplanned endpoint")+ self.reply({}, 404)+ finally:+ with fixture.lock:+ fixture.active -= 1++ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self.server.daemon_threads = True+ self.url = f"http://127.0.0.1:{self.server.server_port}"+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)++ def __enter__(self) -> FakeServer:+ self.thread.start()+ return self++ def __exit__(self, *args: Any) -> None:+ self.server.shutdown()+ self.server.server_close()+ self.thread.join()+++def tiny_catalog(tmp_path: Path) -> tuple[Path, dict[str, Any]]:+ bodies = {+ "G/toxicchat.csv": b"fixture",+ "G/aegis.json": b"[]",+ "M/gretel-main.jsonl": b"{}\n",+ "E/questions.json": b"{}",+ "R/cases_test.json": b"{}",+ }+ for stage, task in {+ "G": "guardrails",+ "M": "redact",+ "E": "lookalike-search",+ "R": "rerank-relevance-rules",+ }.items():+ entries = {+ "inputs/" + name.split("/", 1)[1]: protocol.sha256(body)+ for name, body in bodies.items()+ if name.startswith(stage + "/")+ }+ bodies[f"{stage}/manifest.json"] = protocol.canonical({"task": task, "files_sha256": entries})+ catalog = {+ "files": [+ {"path": name, "bytes": len(body), "sha256": protocol.sha256(body), "url": (tmp_path / name).as_uri()}+ for name, body in sorted(bodies.items())+ ]+ }+ for name, body in bodies.items():+ target = tmp_path / name+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(body)+ return tmp_path, catalog+++def test_fetch_allowlist_verification_and_exclusive_staging(tmp_path: Path) -> None:+ source, catalog = tiny_catalog(tmp_path / "source")+ output = tmp_path / "downloaded"+ fetch.fetch_inputs(output, catalog)+ assert len(fetch.verify_inputs(output, catalog)) == 9+ with pytest.raises(FileExistsError):+ fetch.fetch_inputs(output, catalog)+ (output / "M/gretel-main.jsonl").write_bytes(b"tamper")+ with pytest.raises(ValueError, match="digest"):+ fetch.verify_inputs(output, catalog)+ (source / "E/questions.json").unlink()+ with pytest.raises(OSError):+ fetch.fetch_inputs(tmp_path / "failed", catalog)+ assert not (tmp_path / "failed").exists()++[email protected]("path", ["../escape", "/absolute", "a/../b", "a\\b", "a//b", "a/./b"])+def test_unsafe_paths(path: str) -> None:+ with pytest.raises(ValueError):+ protocol.safe_path(path)++[email protected]("change", ["wrong_task", "unsafe_manifest", "missing_file", "wrong_source"])+def test_input_source_and_manifest_rejection(tmp_path: Path, change: str) -> None:+ root, catalog = tiny_catalog(tmp_path)+ if change in ("wrong_task", "unsafe_manifest"):+ path = root / "M/manifest.json"+ manifest = json.loads(path.read_bytes())+ if change == "wrong_task":+ manifest["task"] = "different"+ else:+ manifest["files_sha256"]["../outside"] = "0" * 64+ body = protocol.canonical(manifest)+ path.write_bytes(body)+ entry = next(e for e in catalog["files"] if e["path"] == "M/manifest.json")+ entry.update(bytes=len(body), sha256=protocol.sha256(body))+ if change == "missing_file":+ (root / "E/questions.json").unlink()+ fetch.write_exclusive(+ root / "verified.json", {"source_digest": "wrong" if change == "wrong_source" else protocol.digest(catalog)}+ )+ with pytest.raises((ValueError, FileNotFoundError)):+ fetch.verify_inputs(root, catalog)+++def test_packet_determinism_phase_exclusion_counts_and_tampering(tmp_path: Path) -> None:+ settings = config(warmup=1)+ pilot = prepare.build_packet(population(), settings | {"phase": "pilot"})+ trial = prepare.build_packet(population(), settings, [pilot])+ assert protocol.canonical(trial) == protocol.canonical(prepare.build_packet(population(), settings, [pilot]))+ assert {o["base_id"] for o in pilot["observations"]}.isdisjoint(o["base_id"] for o in trial["observations"])+ assert {(o["stage"], o["unit"]["input_digest"]) for o in pilot["observations"]}.isdisjoint(+ (o["stage"], o["unit"]["input_digest"]) for o in trial["observations"]+ )+ assert trial["planned_semantic_calls"] == {+ "G": {"sie": 3, "rival": 3},+ "M": {"sie": 6, "rival": 3},+ "E": {"sie": 3, "rival": 3},+ "R": {"sie": 6, "rival": 6},+ }+ assert {tuple(o["arm_order"]) for o in trial["observations"]} == {("sie", "rival"), ("rival", "sie")}+ with pytest.raises(ValueError, match="remaining"):+ prepare.build_packet(population(4), settings, [pilot])+ path = tmp_path / "packet.json"+ fetch.write_exclusive(path, trial)+ assert prepare.load_packet(path) == trial+ trial["observations"][0]["unit"]["data"]["text"] += " tampered"+ path.write_bytes(protocol.canonical(trial))+ with pytest.raises(ValueError, match="digest"):+ prepare.load_packet(path)+ with pytest.raises(FileExistsError):+ fetch.write_exclusive(path, {})+++def test_semantic_input_duplicates_cannot_enter_different_phases() -> None:+ rows = population(3)+ duplicate = dict(rows["G"][0])+ duplicate = prepare.unit("G", duplicate["cohort_sha256"], "different-id", duplicate["data"])+ rows["G"].append(duplicate)+ with pytest.raises(ValueError, match="remaining"):+ prepare.build_packet(rows, config(stages=["G"], n=3, warmup=1))+++def test_exact_four_stage_request_bindings() -> None:+ data = population(1)+ guard = protocol.requests("G", data["G"][0]["data"], "sie")[0]+ rival = protocol.requests("G", data["G"][0]["data"], "rival")[0]+ assert guard["method"] == "chat_completions" and guard["body"] == {+ "messages": [{"role": "user", "content": "Élodie 0 met Élodie."}],+ "temperature": 0,+ "max_tokens": 64,+ }+ assert (+ rival["body"]["messages"][0]["content"]+ == "Is the following user message harmful? Answer with exactly one word: harmful or unharmful."+ "\n\nMessage:\nÉlodie 0 met Élodie."+ )+ assert rival["body"]["max_tokens"] == 10 and "system" not in rival["body"] and "thinking" not in rival["body"]+ pii = protocol.requests("M", data["M"][0]["data"], "rival")[0]["body"]+ assert pii["max_tokens"] == 4096 and pii["system"] == protocol.PII_PROMPT.format(+ labels=", ".join(protocol.REQUEST_LABELS)+ )+ assert pii["output_config"]["format"]["schema"] == protocol.SCHEMA and len(protocol.REQUEST_LABELS) == 36+ embed = protocol.requests("E", data["E"][0]["data"], "rival")[0]["body"]+ assert embed == {+ "model": "text-embedding-3-large",+ "input": "Élodie 0 met Élodie.",+ "dimensions": 3072,+ "encoding_format": "float",+ }+ for rule in protocol.RULES:+ sie = protocol.requests("R", data["R"][0]["data"], "sie", rule)[0]+ cohere = protocol.requests("R", data["R"][0]["data"], "rival", rule)[0]+ assert [c["id"] for c in sie["body"]["items"]] == [f"c{i}" for i in range(20)]+ assert sie["body"]["instruction"] == protocol.RULES[rule]+ assert (+ cohere["path"] == "/v2/rerank"+ and cohere["body"]["query"] == f"Instruction: {protocol.RULES[rule]}\nQuery: Question 0"+ )+ assert cohere["body"]["top_n"] == 20 and cohere["body"]["max_tokens_per_doc"] == 4096+++def test_unicode_windows_composition_and_masking() -> None:+ text = "Élodie étudie. Élodie, élodie and Élodie2."+ span = {"start": 0, "end": 6, "label": "person", "score": 0.6}+ overlap = {"start": 0, "end": 13, "label": "street address", "score": 0.7}+ spans = protocol.compose(+ text, [[span], [span | {"score": 0.9}, overlap, {"start": 7, "end": 13, "label": "city", "score": 0.599}]]+ )+ assert len(spans) == 4 and spans[0]["score"] == 0.9+ assert protocol.masked(text, spans) == "[PERSON]. [PERSON], élodie and [PERSON]2."+ long = " " + "café-name " * 620 + "終わり "+ ranges = protocol.windows(long)+ assert len(ranges) == 3 and ranges[0][0] == 1+ words = list(protocol.WORD.finditer(long))+ assert ranges == [+ (words[0].start(), words[299].end()),+ (words[250].start(), words[549].end()),+ (words[500].start(), words[-1].end()),+ ]+ calls = protocol.requests("M", {"text": long}, "sie")+ assert len(calls) == 6 and {c["model"] for c in calls} == set(protocol.MODELS["M"])+ assert [c["offset"] for c in calls[:3]] == [a for a, _ in ranges]+ entity = {"start": 0, "end": 4, "label": "city", "score": 0.6, "text": "café"}+ adjusted = protocol.validate_reply("M", "sie", {"entities": [entity]}, {"text": long}, calls[1])[0]+ assert adjusted["start"] == ranges[1][0] and long[adjusted["start"] : adjusted["end"]] == "café"+ llm, unmatched = protocol.llm_spans(+ text, {"entities": [{"text": "Élodie", "type": "person"}, {"text": "absent", "type": "person"}]}+ )+ assert len(llm) == 3 and unmatched == 1+++def test_real_sdk_and_provider_adapters_durable_paired_flow(tmp_path: Path) -> None:+ path, packet = packet_file(tmp_path)+ journal = tmp_path / "run.jsonl"+ keys = {provider: "fake-auth-sentinel" for provider in ("sie", "anthropic", "openai", "cohere")}+ with FakeServer(journal, retry=True) as server:+ assert (+ run.run_trial(+ path,+ journal,+ server.url,+ keys,+ execute=True,+ provider_urls={p: server.url for p in protocol.PROVIDER_URLS},+ )+ == "finished"+ )+ assert not server.errors and 1 <= server.maximum <= 2+ captures = server.captures+ report = score.score_trial(path, journal)+ assert report["complete"] and report["qualifying_confirmatory"]+ assert all(stage["paired_latency"]["status"] == "estimated" for stage in report["stages"].values())+ assert report["stages"]["R"]["paired_latency"]["base_clusters"] == 2+ assert report["stages"]["R"]["paired_latency"]["pairs"] == 4+ rows = journal_rows(journal)+ assert "fake-auth-sentinel" not in journal.read_text() and "private-telemetry-sentinel" not in journal.read_text()+ assert {m["weights_revision"] for m in report["discovery"]["models"]} == {"e" * 40}+ model_replies = [r for r in rows if r["event"] == "call_result" and r["stage"] == "M" and r["arm"] == "sie"]+ assert all(r["execution_revision"] == ("a" * 64 if "gliner" in r["model"] else "b" * 64) for r in model_replies)+ assert sum(r["sdk_retry_count"] for r in model_replies) == 1+ assert report["stages"]["M"]["accounting"]["sie"]["physical_dispatches"] == 5+ assert all(c["auth"] == "Bearer fake-auth-sentinel" for c in captures if c["path"] != "/v1/messages")+ assert all(c["api_key"] == "fake-auth-sentinel" for c in captures if c["path"] == "/v1/messages")+ extract_ports = {model: {c["port"] for c in captures if c["model"] == model} for model in protocol.MODELS["M"]}+ assert extract_ports[protocol.MODELS["M"][0]].isdisjoint(extract_ports[protocol.MODELS["M"][1]])+ for capture in captures:+ route, body = capture["path"], capture["body"]+ if route.startswith("/v1/encode/"):+ assert len(body["items"]) == 1 and body["params"]["options"]["is_query"] is True+ if route == "/v1/chat/completions":+ assert body["max_tokens"] == 64 and body["temperature"] == 0+ assert len(body["messages"]) == 1 and body["messages"][0]["role"] == "user"+ if route.startswith("/v1/extract/"):+ assert body["params"]["labels"] == protocol.REQUEST_LABELS+ if route.startswith("/v1/score/"):+ assert len(body["items"]) == 20 and [i["id"] for i in body["items"]] == [f"c{i}" for i in range(20)]+ if route in ("/v1/messages", "/v1/embeddings", "/v2/rerank"):+ assert any(+ c["body"] == body and c["path"] == route+ for obs in packet["observations"]+ for c in obs["requests"]["rival"]+ )+ preserved = journal.read_bytes()+ with pytest.raises((FileExistsError, ValueError)):+ run.run_trial(path, journal, "http://127.0.0.1:1", keys, execute=True)+ assert journal.read_bytes() == preserved+++def test_long_m_partial_success_and_no_outer_retry(tmp_path: Path) -> None:+ path, packet = packet_file(tmp_path, long=True, stages=["M"], n=1, arms="sie")+ journal = tmp_path / "partial.jsonl"+ with FakeServer(journal, fail_at=2, delay=0.01) as server:+ assert run.run_trial(path, journal, server.url, {}, execute=True) == "finished"+ assert server.maximum == 2 and not server.errors+ assert server.counts["/v1/extract/urchade/gliner_multi_pii-v1"] == 2+ assert server.counts["/v1/extract/numind/NuNER_Zero"] == 3+ rows = journal_rows(journal)+ earlier = [r for r in rows if r["event"] == "call_result"]+ assert len(earlier) == 5 and sum(r["status"] == "failed" for r in earlier) == 1+ failed = next(r for r in earlier if r["status"] == "failed")+ assert failed["error"]["code"] == "ITEM_ERROR" and failed["reply"]["item_error"]+ assert packet["planned_semantic_calls"]["M"]["sie"] == 6+ report = score.score_trial(path, journal)+ arm = report["stages"]["M"]["accounting"]["sie"]+ assert not report["complete"] and arm["planned"] == arm["failed"] == 1+ assert arm["semantic_calls"]["unattempted"] == 1 and arm["semantic_calls"]["successful"] == 4++[email protected]("with_auth", [False, True])+def test_optional_auth_absent_catalog_and_sie_only(tmp_path: Path, with_auth: bool) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie")+ journal = tmp_path / "local.jsonl"+ keys = {"sie": "fake-auth-sentinel"} if with_auth else {}+ with FakeServer(journal, catalog=False, revision_headers=False) as server:+ assert run.run_trial(path, journal, server.url, keys, execute=True) == "finished"+ assert server.captures[0]["auth"] == ("Bearer fake-auth-sentinel" if with_auth else None)+ assert len(server.captures) == 1+ report = score.score_trial(path, journal)+ assert report["complete"] and report["discovery"]["models"] == []+ assert report["stages"]["E"]["accounting"]["sie"]["successful"] == 1+ assert next(r for r in journal_rows(journal) if r["event"] == "call_result")["execution_revision"] is None+ assert report["stages"]["E"]["paired_latency"]["status"] == "sie_only"+++def test_caller_mask_is_inside_operation_timer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ path, packet = packet_file(tmp_path, stages=["M"], n=1, arms="sie")+ journal_path = tmp_path / "timer.jsonl"+ original = run.masked++ def delayed_mask(text: str, spans: list[dict[str, Any]]) -> str:+ time.sleep(0.04)+ return original(text, spans)++ monkeypatch.setattr(run, "masked", delayed_mask)+ journal = run.Journal(journal_path, packet, [], create=True)+ with FakeServer(journal_path) as server:+ executor = run.Executor(+ packet,+ journal,+ {"sie_url": server.url, "credentials": {}, "provider_urls": {}, "deadline": time.monotonic() + 5},+ )+ executor.operation(packet["observations"][0], "sie")+ executor.close()+ journal.close()+ rows = journal_rows(journal_path)+ operation = next(r for r in rows if r["event"] == "operation_result")+ calls = [r for r in rows if r["event"] == "call_result"]+ assert operation["status"] == "success" and operation["elapsed_s"] >= max(r["elapsed_s"] for r in calls) + 0.04+++def test_request_timeout_retains_failed_duration(tmp_path: Path) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie", request_timeout_s=0.1)+ journal = tmp_path / "timeout.jsonl"+ with FakeServer(journal, delay=0.4) as server:+ assert run.run_trial(path, journal, server.url, {}, execute=True) == "finished"+ assert len(server.captures) == 1+ report = score.score_trial(path, journal)+ arm = report["stages"]["E"]["accounting"]["sie"]+ assert arm["planned"] == arm["attempted"] == arm["failed"] == 1+ assert arm["all_terminal_attempt_elapsed"]["p50_s"] >= 0.1+ assert arm["successful_operation_latency"]["count"] == 0++[email protected]("loading_sleep", [False, True])+def test_wall_deadline_reaps_child_and_preserves_unresolved_intent(tmp_path: Path, loading_sleep: bool) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie", wall_limit_s=1.5)+ journal = tmp_path / "deadline.jsonl"+ before = {p.pid for p in multiprocessing.active_children()}+ with FakeServer(journal, delay=0 if loading_sleep else 3, loading_sleep=loading_sleep) as server:+ start = time.monotonic()+ assert run.run_trial(path, journal, server.url, {}, execute=True) == "deadline"+ assert time.monotonic() - start < 2.5 and server.observed.is_set()+ assert {p.pid for p in multiprocessing.active_children()} == before+ report = 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"] == 1+ calls = 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+++def test_interrupt_preserves_intent_and_reaps_child(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie")+ journal = tmp_path / "interrupt.jsonl"+ real_context = multiprocessing.get_context("spawn")+ before = {p.pid for p in multiprocessing.active_children()}+ with FakeServer(journal, delay=3) as server:++ class ProcessProxy:+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self.process = real_context.Process(*args, **kwargs)+ self.first_join = True++ def __getattr__(self, name: str) -> Any:+ return getattr(self.process, name)++ def join(self, timeout: float | None = None) -> None:+ if self.first_join:+ self.first_join = False+ assert server.observed.wait(3)+ raise KeyboardInterrupt+ self.process.join(timeout)++ class ContextProxy:+ Process = ProcessProxy+ Pipe = real_context.Pipe++ monkeypatch.setattr(run.multiprocessing, "get_context", lambda _: ContextProxy())+ assert run.run_trial(path, journal, server.url, {}, execute=True) == "interrupted"+ assert {p.pid for p in multiprocessing.active_children()} == before+ report = score.score_trial(path, journal)+ assert not report["complete"] and report["ending"]["reason"] == "interrupted"+ assert report["stages"]["E"]["accounting"]["sie"]["semantic_calls"]["unresolved"] == 1+++def test_truncated_tail_and_terminal_binding(tmp_path: Path) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie", wall_limit_s=1.5)+ journal = tmp_path / "tail.jsonl"+ with FakeServer(journal, delay=3) as server:+ assert run.run_trial(path, journal, server.url, {}, execute=True) == "deadline"+ with journal.open("ab") as output:+ output.write(b'{"partial":')+ end_path = journal.with_name(journal.name + ".end.json")+ end = json.loads(end_path.read_bytes())+ end["journal_digest"] = protocol.sha256(journal.read_bytes())+ end["end_digest"] = protocol.digest({k: v for k, v in end.items() if k != "end_digest"})+ end_path.write_bytes(protocol.canonical(end))+ report = score.score_trial(path, journal)+ assert not report["complete"] and report["truncated_tail_sha256"] == protocol.sha256(b'{"partial":')+ assert report["stages"]["E"]["accounting"]["sie"]["unresolved"] == 1+ end["journal_digest"] = "0" * 64+ end["end_digest"] = protocol.digest({k: v for k, v in end.items() if k != "end_digest"})+ end_path.write_bytes(protocol.canonical(end))+ with pytest.raises(ValueError, match="binding"):+ score.score_trial(path, journal)+++def test_malformed_reply_keeps_actual_redacted_reply(tmp_path: Path) -> None:+ path, _ = packet_file(tmp_path, stages=["G"], n=1, arms="sie")+ journal = tmp_path / "malformed.jsonl"+ with FakeServer(journal, malformed=True) as server:+ run.run_trial(path, journal, server.url, {"sie": "fake-auth-sentinel"}, execute=True)+ text = journal.read_text()+ assert "fake-auth-sentinel" not in text and "[REDACTED_CREDENTIAL]" in text+ report = score.score_trial(path, journal)+ assert report["stages"]["G"]["accounting"]["sie"]["failed"] == 1+ assert (+ next(r for r in journal_rows(journal) if r["event"] == "call_result")["reply"]["text"]+ == "[REDACTED_CREDENTIAL]"+ )+++ "url",+ [+ "http://user:query-secret@localhost",+ "http://localhost?token=query-secret",+ "http://localhost#query-secret",+ "http://localhost/%71uery-secret",+ ],+)+def test_endpoint_secret_rejection_before_client_or_journal(tmp_path: Path, url: str) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1, arms="sie")+ output = tmp_path / "unsafe.jsonl"+ with pytest.raises(ValueError) as error:+ run.run_trial(path, output, url, {"sie": "fake-auth-sentinel"}, execute=True)+ assert "query-secret" not in str(error.value) and "fake-auth-sentinel" not in str(error.value)+ assert not output.exists()+++def test_opt_in_missing_paired_keys_and_transport_sanitizing(+ tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ path, _ = packet_file(tmp_path, stages=["E"], n=1)+ output = tmp_path / "run.jsonl"+ with pytest.raises(ValueError, match="execute"):+ run.run_trial(path, output, "http://127.0.0.1:1", {})+ with pytest.raises(ValueError, match="credential"):+ run.run_trial(path, output, "http://127.0.0.1:1", {}, execute=True)+ assert not output.exists()+ assert (+ run.run_trial(+ path,+ output,+ "http://127.0.0.1:1",+ {"sie": "fake-auth-sentinel", "openai": "fake-openai-sentinel"},+ execute=True,+ provider_urls={"openai": "http://127.0.0.1:1"},+ )+ == "finished"+ )+ assert all(value not in output.read_text() for value in ("fake-auth-sentinel", "fake-openai-sentinel"))+ captured = capsys.readouterr()+ assert "sentinel" not in captured.out + captured.err+ report = score.score_trial(path, output)+ assert report["stages"]["E"]["accounting"]["sie"]["failed"] == 1++[email protected]("change", ["missing", "duplicate", "unexpected", "protocol", "derived_mask"])+def test_strict_journal_rejects_unexpected_or_nonqualifies_missing(tmp_path: Path, change: str) -> None:+ path, _ = packet_file(tmp_path, stages=["M"], n=1, arms="sie")+ journal = tmp_path / "journal.jsonl"+ with FakeServer(journal) as server:+ run.run_trial(path, journal, server.url, {}, execute=True)+ rows = journal_rows(journal)+ index = next(i for i, row in enumerate(rows) if row["event"] == "operation_result")+ if change == "missing":+ rows.pop(index)+ elif change == "duplicate":+ rows.insert(index + 1, dict(rows[index]))+ elif change == "unexpected":+ rows[index]["observation_id"] = "unexpected"+ elif change == "protocol":+ rows[index]["protocol_digest"] = "0" * 64+ else:+ rows[index]["result"]["masked"] = "wrong mask"+ rechain(journal, rows)+ if change == "missing":+ result = score.score_trial(path, journal)+ assert not result["complete"] and result["stages"]["M"]["accounting"]["sie"]["unresolved"] == 1+ else:+ with pytest.raises(ValueError):+ score.score_trial(path, journal)+++def test_paired_cluster_bootstrap_known_statistics() -> None:+ settings = config()["bootstrap"]+ clusters = [[(1.0, 4.0), (3.0, 6.0)], [(2.0, 5.0), (4.0, 7.0)]]+ result = score.paired_bootstrap(clusters, settings)+ assert result == score.paired_bootstrap(clusters, settings)+ assert result["difference_rival_minus_sie_s"] == 3.0 and result["ratio_rival_over_sie"] == 2.2+ assert result["difference_percentile_95"] == [3.0, 3.0]+ assert result["ratio_percentile_95"] == [2.0, 2.5]+ assert result["sie_median_s"] == 2.5 and result["rival_median_s"] == 5.5+ assert result["sie_median_percentile_95"] == [2.0, 3.0]+ assert result["rival_median_percentile_95"] == [5.0, 6.0]+ assert result["cohort"] == "successful complete paired base-case clusters"+ assert result["pairs"] == 4 and result["base_clusters"] == 2+ assert score.paired_bootstrap([clusters[0]], settings)["status"] == "insufficient"+ # Independently enumerate the same seeded whole-cluster choices.+ chooser = random.Random(settings["seed"])+ ratios = []+ for _ in range(settings["resamples"]):+ sampled = [pair for _ in clusters for pair in chooser.choice(clusters)]+ ratios.append(score.quantile([r for _, r in sampled], 0.5) / score.quantile([s for s, _ in sampled], 0.5))+ assert result["ratio_percentile_95"] == [score.quantile(ratios, p) for p in (0.025, 0.975)]+++def test_offline_cli_help_and_opt_in_error(tmp_path: Path) -> None:+ for script in ("fetch.py", "prepare.py", "run.py", "score.py"):+ result = subprocess.run(+ [sys.executable, str(HERE / script), "--help"], capture_output=True, text=True, check=False+ )+ assert result.returncode == 0 and "usage:" in result.stdout+ result = subprocess.run(+ [sys.executable, str(HERE / "run.py"), "--packet", "absent.json", "--out", str(tmp_path / "out.jsonl")],+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 2 and "--execute" in result.stderr and not (tmp_path / "out.jsonl").exists()+ assert "API_KEY" not in result.stdout + result.stderr+++def test_source_templates_match_builders_and_no_external_runtime_defaults() -> None:+ sources = protocol.sources()+ assert len(sources["files"]) == 9+ assert all(entry["revision"] in entry["url"] and len(entry["sha256"]) == 64 for entry in sources["files"])+ for stage in protocol.STAGES:+ for arm, rules in sources["request_bindings"][stage]["requests"].items():+ for rule, calls in rules.items():+ data = {+ "text": "{source_text}",+ "query": "{source_query}",+ "candidates": [+ {"id": f"{{candidate_{i}_id}}", "text": f"{{candidate_{i}_text}}"} for i in range(20)+ ],+ }+ assert calls == protocol.requests(stage, data, arm, None if rule == "None" else rule)+ assert "api.superlinked.com" not in (HERE / "run.py").read_text()+++ "stage,arm,reply",+ [+ ("G", "sie", {"text": "no verdict"}),+ ("G", "rival", {"text": "unharmful extra"}),+ ("M", "sie", {"entities": [], "item_error": {"code": "ITEM_ERROR"}}),+ ("E", "sie", {"dense": [0.0] * 12}),+ ("E", "rival", {"dense": [float("nan")] * 3072}),+ ("R", "rival", {"scores": [], "results": [{"index": 0}] * 20}),+ ],+)+def test_reply_failures_never_become_success(stage: str, arm: str, reply: dict[str, Any]) -> None:+ selected = population(1)[stage][0]+ call = protocol.requests(stage, selected["data"], arm, "in-force" if stage == "R" else None)[0]+ with pytest.raises(ValueError):+ protocol.validate_reply(stage, arm, reply, selected["data"], call)