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 reproducible photo transcription study (#630)
svonavaa826a9554de2
diff --git a/examples/photo-transcription/.gitignore b/examples/photo-transcription/.gitignorenew file mode 100644index 000000000..6c11b425c--- /dev/null+++ b/examples/photo-transcription/.gitignore@@ -0,0 +1,2 @@+/data/+/native-*/diff --git a/examples/photo-transcription/README.md b/examples/photo-transcription/README.mdnew file mode 100644index 000000000..e9da37477--- /dev/null+++ b/examples/photo-transcription/README.md@@ -0,0 +1,112 @@+# Photo transcription fidelity++Audit a frozen set of 24 photographed receipts and handwritten documents, then+collect once-only transcriptions from an existing SIE deployment. The offline+scorer needs only Python; native collection uses `sie_sdk.SIEClient`.++The [public source packet](https://huggingface.co/datasets/superlinked/sie-task-evidence/tree/fd29e7a2813e90deec6ac27e1fcdc22a5e237c44/ocr-photo-transcription/2026-10-08/source-provider-v2)+contains twelve CORD receipts, twelve GNHK handwritten documents, original+JPEGs and annotations, full gold text, source-context decisions and all 48+saved provider transcriptions. The downloader pins the dataset revision and+checksum-list hash, then checks every file. Source images are CC BY 4.0; the+packet includes publisher attribution, license evidence and modification notices.++## Reproduce the saved comparison++From this directory, with Python 3.12:++```bash+python fetch.py data+python score.py data+```++This downloads about 32 MB and makes no inference calls. The source-adjacent-v2+decisions reproduce **16/24 Luna** and **24/24 Sol** photos with complete+transcription and no critical errors. `native` is `null` until you collect and+review native results. The saved provider file is a **projection**, with usage,+request semantics and detached original wire-body hashes; it is not the original+transport recording. Reproducing its decisions does not rerun those providers.++The unit is one photographed document. A pass requires every assessable+critical amount, date, identifier and proper name to preserve its source role,+plus every readable gold line to be represented. Equivalent grouping, case,+spacing and predeclared date/quantity variants are allowed; a correct number on+the wrong line is a failure. This is a purposively balanced exploratory pilot,+not a representative population estimate or a claim of statistically established+model superiority. Publisher training splits and unknown model training exposure+are recorded in the manifest.++## Collect from a remote SIE endpoint++Install the SDK from this checkout using the repository's ordinary development+setup, or run `python -m pip install -e packages/sie_sdk` from the repository+root in a Python 3.12 environment. Set `SIE_URL` to an existing deployment.+For authentication, set `SIE_BASE_URL` to the same endpoint and `SIE_API_KEY`+to its key; the SDK confines that environment credential to the matching origin.+The scripts do not start a server or run a model on your machine.++```bash+python collect.py data native-glm \+ --model zai-org/GLM-OCR \+ --instruction 'Text Recognition:'+```++An alternative endpoint can be supplied with `--sie-url`. Choose a model already+served there and freeze its checkpoint/runtime configuration separately. For+models with a plain default OCR task, omit `--instruction`; do not carry a+Florence task token into another model. The collector sends each full JPEG,+original item ID, `profile=default`, `max_new_tokens=8192` and `num_beams=1`.+`--max-new-tokens` accepts a smaller predeclared limit, never a larger one.++The public SDK uses an injected HTTP transport to save the actual MessagePack+request and reply bodies. It records at most one inference POST attempt per+photo, rejects non-success replies before automatic model-loading retries, and+stops after a failed request. No authentication headers are saved. Later photos+remain explicitly **unattempted**, rather than being silently retried or scored+as model failures. A timeout may have reached the server, so its attempt still+counts. Bounded same-origin result retrievals use GET, are recorded separately,+and do not replay inference. Endpoint health GETs are not inference attempts. Output directories must+be new, preserving an earlier run instead of overwriting it.++## Review complete source fidelity++`native-glm/review-template.json` has one entry for each nonempty completed+transcription. Review against the **full photograph**, gold lines, local roles,+normalization policy and `source-amendments.json`, with model identity withheld.+Copy it to `decisions.json`, identify the actual human or AI reviewer, and fill+every critical-occurrence and readable-line decision. Record the review rationale+separately; do not describe AI review as human adjudication.++Critical outcomes are `preserved`, `changed`, `missing`, `misassociated`,+`invented` or `not_assessable`. Line outcomes are `represented`, `missing` or+`not_assessable`. The last option is restricted to the declared publisher-blurred+logo in `cord/train-0012` (critical index 15, line 0). The source-only amendment+for `gnhk/train-eng_NA_144` corrects the handwritten year from the original gold+2019 to **2018**; the original gold bytes remain unchanged. Apply both amendments+uniformly, rather than choosing an interpretation based on which model benefits.++```bash+python score.py data \+ --native-calls native-glm/calls.jsonl \+ --decisions native-glm/decisions.json+```++The scorer binds reviews to the exact image and transcription hashes, requires+all frozen case slots, and separates unattempted/unreviewed cases from failures.+It reports paired counts against each preserved provider arm. String matching+alone cannot reproduce semantic source-context review, and the script does not+claim to replace that review or supply a confidence interval from this pilot.++## Validate without credentials or inference++After the repository's ordinary development setup, from the repository root:++```bash+mise exec -- uv run --frozen --project . --no-sync pytest -q examples/photo-transcription/tests+mise exec -- uv run --frozen --project . --no-sync ruff check --select E,F,I,UP,B examples/photo-transcription+mise exec -- uv run --frozen --project . --no-sync ruff format --check examples/photo-transcription+```++The tests use synthetic source packets and the real SDK with a mock HTTP+transport. They check full-JPEG request controls, once-only model-loading failure,+hash tampering, full-cohort retention and incomplete-review handling.diff --git a/examples/photo-transcription/collect.py b/examples/photo-transcription/collect.pynew file mode 100644index 000000000..611536369--- /dev/null+++ b/examples/photo-transcription/collect.py@@ -0,0 +1,165 @@+"""Collect one native SIE transcription per frozen photo from a remote endpoint."""++from __future__ import annotations++import argparse+import json+import os+import time+from pathlib import Path+from typing import Any++from fidelity import digest, load_packet+++class PhysicalAttemptError(RuntimeError):+ """A native call failed or would exceed the once-only physical attempt."""+++def collect(+ packet: Path,+ output: Path,+ model: str,+ base_url: str,+ instruction: str | None = None,+ max_new_tokens: int = 8192,+) -> dict[str, Any]:+ import httpx # Optional: only native collection needs the SDK transport.+ from sie_sdk import SIEClient # Optional for the offline scorer.++ if not model or not 1 <= max_new_tokens <= 8192:+ raise ValueError("A model and a bounded output limit are required")+ manifest, _ = load_packet(packet)+ output.mkdir(parents=True, exist_ok=False)+ calls: list[dict[str, Any]] = []+ current: dict[str, Any] = {}+ inference_path = httpx.URL(base_url).path.rstrip("/") + f"/v1/extract/{model}"+ wire_dir = output / "wire"+ wire_dir.mkdir()++ def request_hook(request: Any) -> None:+ if request.method == "POST" and request.url.path == inference_path:+ if current["attempts"]:+ raise PhysicalAttemptError("A second physical inference attempt is forbidden")+ current["attempts"] = 1+ payload = request.content+ (wire_dir / f"{current['index']:02d}-request.msgpack").write_bytes(payload)+ current["request_body_sha256"] = digest(payload)++ def response_hook(response: Any) -> None:+ if current.get("attempts") and response.request.method in {"POST", "GET"}:+ payload = response.read()+ hop = len(current["response_hops"])+ (wire_dir / f"{current['index']:02d}-response-{hop:02d}.bin").write_bytes(payload)+ current["response_body_sha256"] = digest(payload)+ current["http_status"] = response.status_code+ current["response_hops"].append(+ {+ "method": response.request.method,+ "http_status": response.status_code,+ "body_sha256": digest(payload),+ }+ )+ # The SDK may retrieve a same-origin in-flight result with GET.+ # It validates that 303 destination; this never replays inference.+ if response.status_code != 303 and not 200 <= response.status_code < 300:+ raise PhysicalAttemptError(f"HTTP {response.status_code}; no automatic resubmission")++ transport = httpx.Client(+ base_url=base_url,+ timeout=180,+ follow_redirects=False,+ event_hooks={"request": [request_hook], "response": [response_hook]},+ )+ # Public SDK transport injection captures actual payloads without auth headers.+ # Reject error replies before the SDK's model-loading retry branch runs.+ with transport, SIEClient(base_url=base_url, timeout_s=180, http_client=transport) as client:+ stopped = False+ for index, source in enumerate(manifest["records"]):+ current = {+ "index": index,+ "case_id": source["id"],+ "image_sha256": source["input_image"]["sha256"],+ "requested_model": model,+ "attempts": 0,+ "status": "unattempted",+ "response_hops": [],+ }+ if not stopped:+ started = time.monotonic()+ try:+ result = client.extract(+ model,+ {+ "id": source["id"],+ "images": [+ {"data": (packet / source["input_image"]["path"]).read_bytes(), "format": "jpeg"}+ ],+ },+ instruction=instruction,+ options={"profile": "default", "max_new_tokens": max_new_tokens, "num_beams": 1},+ wait_for_capacity=False,+ max_oom_retries=0,+ )+ if result.get("id") != source["id"] or len(result["entities"]) != 1:+ raise ValueError("Expected one OCR entity for the original item ID")+ text = result["entities"][0]["text"]+ if not isinstance(text, str):+ raise ValueError("Native text must be a string")+ current.update(+ text=text,+ transcription_sha256=digest(text.encode()),+ returned_model=result.get("model"),+ status="completed" if text.strip() else "empty",+ )+ (output / f"{index:02d}-decoded.json").write_text(json.dumps(result, indent=2) + "\n")+ except Exception as error:+ current["status"] = "error" if current["attempts"] else "unattempted"+ current["error_type"] = type(error).__name__+ stopped = True+ current["client_elapsed_s"] = time.monotonic() - started+ calls.append(dict(current))+ (output / "calls.jsonl").write_text("".join(json.dumps(row) + "\n" for row in calls))+ review = [+ {+ "case_id": row["case_id"],+ "image_sha256": row["image_sha256"],+ "transcription_sha256": row["transcription_sha256"],+ "reviewer": "",+ "critical_outcomes": [""] * len(manifest["records"][row["index"]]["critical_values"]),+ "line_outcomes": [""] * len(manifest["records"][row["index"]]["reviewed_lines"]),+ }+ for row in calls+ if row["status"] == "completed"+ ]+ (output / "review-template.json").write_text(json.dumps(review, indent=2) + "\n")+ summary = {+ "frozen_photos": len(calls),+ "physical_inference_posts": sum(row["attempts"] for row in calls),+ "completed": sum(row["status"] == "completed" for row in calls),+ "stopped": stopped,+ }+ (output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")+ return summary+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("packet", type=Path)+ parser.add_argument("output", type=Path)+ parser.add_argument("--model", required=True)+ parser.add_argument("--sie-url", default=os.environ.get("SIE_URL"))+ parser.add_argument("--instruction")+ parser.add_argument("--max-new-tokens", type=int, default=8192)+ args = parser.parse_args()+ if not args.sie_url:+ parser.error("Provide --sie-url or SIE_URL for an existing remote deployment")+ print(+ json.dumps(+ collect(args.packet, args.output, args.model, args.sie_url, args.instruction, args.max_new_tokens), indent=2+ )+ )+++if __name__ == "__main__":+ main()diff --git a/examples/photo-transcription/dataset.py b/examples/photo-transcription/dataset.pynew file mode 100644index 000000000..9a1574ed6--- /dev/null+++ b/examples/photo-transcription/dataset.py@@ -0,0 +1,46 @@+"""Immutable public source packet and file-integrity checks."""++from __future__ import annotations++import hashlib+from pathlib import Path++REVISION = "fd29e7a2813e90deec6ac27e1fcdc22a5e237c44"+PREFIX = "ocr-photo-transcription/2026-10-08/source-provider-v2"+BASE_URL = f"https://huggingface.co/datasets/superlinked/sie-task-evidence/resolve/{REVISION}/{PREFIX}/"+CHECKSUM_SHA256 = "1a10fe5a68bd9ef8da5e699cdd71caae3b1f84dceafe413b0350030640b8eaf2"+++def digest(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def packet_path(directory: Path, relative: str) -> Path:+ path = Path(relative)+ if path.is_absolute() or not path.parts or ".." in path.parts:+ raise ValueError("Packet paths must be relative and stay inside the packet")+ resolved = (directory / path).resolve()+ if not resolved.is_relative_to(directory.resolve()):+ raise ValueError("Packet symlinks must stay inside the packet")+ return resolved+++def checksums(data: bytes) -> dict[str, str]:+ if digest(data) != CHECKSUM_SHA256:+ raise ValueError("Checksum list differs from the pinned source packet")+ entries: dict[str, str] = {}+ for line in data.decode().splitlines():+ checksum, separator, relative = line.partition(" ")+ if not separator or len(checksum) != 64 or any(ch not in "0123456789abcdef" for ch in checksum):+ raise ValueError("Invalid SHA256SUMS entry")+ packet_path(Path.cwd(), relative)+ if relative in entries:+ raise ValueError("Duplicate checksum path")+ entries[relative] = checksum+ return entries+++def verify_packet(directory: Path) -> None:+ for relative, checksum in checksums((directory / "SHA256SUMS").read_bytes()).items():+ if digest(packet_path(directory, relative).read_bytes()) != checksum:+ raise ValueError(f"Packet file changed: {relative}")diff --git a/examples/photo-transcription/fetch.py b/examples/photo-transcription/fetch.pynew file mode 100644index 000000000..5635d4129--- /dev/null+++ b/examples/photo-transcription/fetch.py@@ -0,0 +1,39 @@+"""Download the pinned public photos, gold, protocol and saved-provider projection."""++from __future__ import annotations++import argparse+import urllib.request+from pathlib import Path++from dataset import BASE_URL, checksums, digest, packet_path, verify_packet+++def download(directory: Path) -> None:+ directory.mkdir(parents=True, exist_ok=True)+ with urllib.request.urlopen(BASE_URL + "SHA256SUMS", timeout=60) as response:+ checksum_bytes = response.read()+ entries = checksums(checksum_bytes)+ for relative, checksum in entries.items():+ target = packet_path(directory, relative)+ if target.exists() and digest(target.read_bytes()) == checksum:+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ with urllib.request.urlopen(BASE_URL + relative, timeout=60) as response:+ data = response.read()+ if digest(data) != checksum:+ raise ValueError(f"Downloaded file hash mismatch: {relative}")+ target.write_bytes(data)+ (directory / "SHA256SUMS").write_bytes(checksum_bytes)+ verify_packet(directory)+ print(f"Verified {len(entries)} files and the pinned checksum list in {directory}")+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("directory", type=Path)+ download(parser.parse_args().directory)+++if __name__ == "__main__":+ main()diff --git a/examples/photo-transcription/fidelity.py b/examples/photo-transcription/fidelity.pynew file mode 100644index 000000000..1be978136--- /dev/null+++ b/examples/photo-transcription/fidelity.py@@ -0,0 +1,149 @@+"""Verify the photographed source and its recorded transcription decisions."""++from __future__ import annotations++import json+from collections import Counter+from pathlib import Path+from typing import Any++from dataset import digest, verify_packet+++def load_packet(directory: Path) -> tuple[dict[str, Any], dict[str, Any]]:+ verify_packet(directory)+ manifest = json.loads((directory / "manifest.json").read_text())+ projection = json.loads((directory / "provider-projection.json").read_text())+ records = manifest["records"]+ if manifest["n"] != 24 or len(records) != 24:+ raise ValueError("Expected the complete 24-photo cohort")+ cases = {row["id"]: row for row in records}+ if len(cases) != 24 or len({row["source_cluster"] for row in records}) != 24:+ raise ValueError("Source IDs and physical-document clusters must be unique")+ if Counter(row["domain"] for row in records) != {"receipt": 12, "handwriting": 12}:+ raise ValueError("Expected twelve receipts and twelve handwritten documents")+ for row in records:+ if digest(row["gold_text"].encode()) != row["gold_sha256"]:+ raise ValueError(f"Gold hash mismatch: {row['id']}")+ for field in ("source_image", "input_image"):+ info = row[field]+ relative = Path(info["path"])+ if relative.is_absolute() or ".." in relative.parts:+ raise ValueError("Source paths must stay inside the packet")+ if digest((directory / relative).read_bytes()) != info["sha256"]:+ raise ValueError(f"Image hash mismatch: {row['id']}")+ rows = projection["provider_records"]+ if len(rows) != 48:+ raise ValueError("Expected every recorded provider response")+ for arm in ("luna", "sol"):+ arm_rows = [row for row in rows if row["arm"] == arm]+ if len(arm_rows) != 24 or {row["case_id"] for row in arm_rows} != set(cases):+ raise ValueError(f"Incomplete provider cohort: {arm}")+ for row in rows:+ source = cases[row["case_id"]]+ if row["image_sha256"] != source["input_image"]["sha256"]:+ raise ValueError("Provider response is bound to a different image")+ if digest(row["text"].encode()) != row["transcription_sha256"]:+ raise ValueError("Recorded transcription changed")+ if row["attempts"] != 1 or row["phase"] != "main":+ raise ValueError("Expected one main attempt per recorded provider")+ return manifest, projection+++def recorded_report(projection: dict[str, Any]) -> dict[str, Any]:+ rows = projection["provider_records"]+ report: dict[str, Any] = {"metric": "Complete transcription and no critical source errors"}+ for arm in ("luna", "sol"):+ selected = [row for row in rows if row["arm"] == arm]+ report[arm] = {+ "n": len(selected),+ "passed": sum(row["source_grounded"]["source_grounded_primary_outcome"] == "pass" for row in selected),+ }+ report["native"] = None+ report["source"] = "Preserved source-adjacent-v2 decisions; not a new model run"+ return report+++def native_report(+ manifest: dict[str, Any], calls: list[dict[str, Any]], decisions: list[dict[str, Any]]+) -> dict[str, Any]:+ """Apply complete source-context reviews, never string-only value matching."""+ cases = {row["id"]: row for row in manifest["records"]}+ if len(calls) != len(cases) or {row["case_id"] for row in calls} != set(cases):+ raise ValueError("Retain every frozen case, including unattempted cases")+ reviewed = {row["case_id"]: row for row in decisions}+ if len(reviewed) != len(decisions) or set(reviewed) - set(cases):+ raise ValueError("Duplicate or foreign source decisions")+ outcomes: dict[str, str] = {}+ for call in calls:+ case_id = call["case_id"]+ source = cases[case_id]+ if call["image_sha256"] != source["input_image"]["sha256"]:+ raise ValueError("Native call is bound to a different image")+ if call["status"] == "unattempted":+ if call["attempts"] != 0:+ raise ValueError("Unattempted rows cannot contain physical attempts")+ outcomes[case_id] = "unattempted"+ continue+ if call["attempts"] != 1:+ raise ValueError("Expected exactly one physical native attempt")+ if call["status"] in ("error", "empty"):+ outcomes[case_id] = "fail"+ continue+ if call["status"] != "completed":+ raise ValueError("Unknown native call status")+ text = call["text"]+ if not isinstance(text, str) or not text.strip():+ raise ValueError("Completed native calls must contain nonempty text")+ text_hash = digest(text.encode())+ if text_hash != call["transcription_sha256"]:+ raise ValueError("Native transcription changed")+ decision = reviewed.get(case_id)+ if decision is None:+ outcomes[case_id] = "unreviewed"+ continue+ if (+ not isinstance(decision.get("reviewer"), str)+ or not decision["reviewer"].strip()+ or decision["transcription_sha256"] != text_hash+ ):+ raise ValueError("Review identity and exact transcription binding are required")+ if decision["image_sha256"] != call["image_sha256"]:+ raise ValueError("Review is bound to a different source")+ critical = decision["critical_outcomes"]+ lines = decision["line_outcomes"]+ if len(critical) != len(source["critical_values"]) or len(lines) != len(source["reviewed_lines"]):+ raise ValueError("Every source occurrence and readable line needs a decision")+ if any(+ value not in {"preserved", "changed", "missing", "misassociated", "invented", "not_assessable"}+ for value in critical+ ):+ raise ValueError("Unknown critical-value decision")+ if any(value not in {"represented", "missing", "not_assessable"} for value in lines):+ raise ValueError("Unknown source-line decision")+ # The single declared publisher-blurred logo is the only excluded source.+ excluded_critical = {15} if case_id == "cord/train-0012" else set()+ excluded_lines = {0} if case_id == "cord/train-0012" else set()+ if any(critical[index] != "not_assessable" for index in excluded_critical) or any(+ lines[index] != "not_assessable" for index in excluded_lines+ ):+ raise ValueError("The publisher-blurred logo must be recorded as not assessable")+ if any(value == "not_assessable" and index not in excluded_critical for index, value in enumerate(critical)):+ raise ValueError("An undeclared critical occurrence cannot be excluded")+ if any(value == "not_assessable" and index not in excluded_lines for index, value in enumerate(lines)):+ raise ValueError("An undeclared readable line cannot be excluded")+ passed = all(value == "preserved" for index, value in enumerate(critical) if index not in excluded_critical)+ passed = passed and all(+ value == "represented" for index, value in enumerate(lines) if index not in excluded_lines+ )+ outcomes[case_id] = "pass" if passed else "fail"+ counts = Counter(outcomes.values())+ return {+ "n_frozen": len(cases),+ "passed": counts["pass"],+ "failed": counts["fail"],+ "unattempted": counts["unattempted"],+ "unreviewed": counts["unreviewed"],+ "complete_reviewed_cohort": not counts["unattempted"] and not counts["unreviewed"],+ "outcomes": outcomes,+ }diff --git a/examples/photo-transcription/score.py b/examples/photo-transcription/score.pynew file mode 100644index 000000000..f5d404423--- /dev/null+++ b/examples/photo-transcription/score.py@@ -0,0 +1,45 @@+"""Reproduce saved decisions or report a fully source-reviewed native run."""++from __future__ import annotations++import argparse+import json+from pathlib import Path++from fidelity import load_packet, native_report, recorded_report+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("packet", type=Path)+ parser.add_argument("--native-calls", type=Path)+ parser.add_argument("--decisions", type=Path)+ args = parser.parse_args()+ manifest, projection = load_packet(args.packet)+ report = recorded_report(projection)+ if args.native_calls:+ calls = [json.loads(line) for line in args.native_calls.read_text().splitlines() if line]+ decisions = json.loads(args.decisions.read_text()) if args.decisions else []+ native = native_report(manifest, calls, decisions)+ report["native"] = native+ for arm in ("luna", "sol"):+ baseline = {+ row["case_id"]: row["source_grounded"]["source_grounded_primary_outcome"] == "pass"+ for row in projection["provider_records"]+ if row["arm"] == arm+ }+ pairs = {key: value for key, value in native["outcomes"].items() if value in {"pass", "fail"}}+ report["native"][f"paired_{arm}"] = {+ "n": len(pairs),+ "both_pass": sum(value == "pass" and baseline[key] for key, value in pairs.items()),+ "native_only": sum(value == "pass" and not baseline[key] for key, value in pairs.items()),+ "rival_only": sum(value == "fail" and baseline[key] for key, value in pairs.items()),+ "neither_pass": sum(value == "fail" and not baseline[key] for key, value in pairs.items()),+ }+ elif args.decisions:+ parser.error("--decisions requires --native-calls")+ print(json.dumps(report, indent=2))+++if __name__ == "__main__":+ main()diff --git a/examples/photo-transcription/tests/conftest.py b/examples/photo-transcription/tests/conftest.pynew file mode 100644index 000000000..67a587464--- /dev/null+++ b/examples/photo-transcription/tests/conftest.py@@ -0,0 +1,6 @@+"""Expose the runnable example to the repository's importlib test mode."""++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))diff --git a/examples/photo-transcription/tests/test_fidelity.py b/examples/photo-transcription/tests/test_fidelity.pynew file mode 100644index 000000000..5125c12a4--- /dev/null+++ b/examples/photo-transcription/tests/test_fidelity.py@@ -0,0 +1,258 @@+"""Credential-free source integrity and real-SDK collector controls."""++from __future__ import annotations++import json++import collect as collector+import dataset+import httpx+import msgpack+import pytest+from fidelity import load_packet, native_report, recorded_report+++def packet(tmp_path, monkeypatch):+ directory = tmp_path / "data"+ directory.mkdir()+ records = []+ providers = []+ for index in range(24):+ image = b"\xff\xd8\xff" + f"complete-original-photo-{index}".encode() + b"\xff\xd9"+ image_path = f"images/{index}.jpg"+ (directory / "images").mkdir(exist_ok=True)+ (directory / image_path).write_bytes(image)+ text = f"Source value {index}"+ row = {+ "id": f"photo-{index}",+ "source_cluster": f"document-{index}",+ "domain": "receipt" if index < 12 else "handwriting",+ "gold_text": text,+ "gold_sha256": dataset.digest(text.encode()),+ "critical_values": [{"role": "value", "surface": str(index)}],+ "reviewed_lines": [text],+ "source_image": {"path": image_path, "sha256": dataset.digest(image)},+ "input_image": {"path": image_path, "sha256": dataset.digest(image)},+ }+ records.append(row)+ for arm in ("luna", "sol"):+ providers.append(+ {+ "arm": arm,+ "case_id": row["id"],+ "text": text,+ "image_sha256": row["input_image"]["sha256"],+ "transcription_sha256": dataset.digest(text.encode()),+ "phase": "main",+ "attempts": 1,+ "source_grounded": {+ "source_grounded_primary_outcome": "pass" if arm == "sol" or index < 16 else "fail"+ },+ }+ )+ (directory / "manifest.json").write_text(json.dumps({"n": 24, "records": records}))+ (directory / "provider-projection.json").write_text(json.dumps({"provider_records": providers}))+ checksum_bytes = "".join(+ f"{dataset.digest(path.read_bytes())} {path.relative_to(directory).as_posix()}\n"+ for path in sorted(directory.rglob("*"))+ if path.is_file()+ ).encode()+ (directory / "SHA256SUMS").write_bytes(checksum_bytes)+ monkeypatch.setattr(dataset, "CHECKSUM_SHA256", dataset.digest(checksum_bytes))+ return directory+++def test_saved_counts_and_every_packet_file_are_verified(packet):+ _, projection = load_packet(packet)+ report = recorded_report(projection)+ assert report["luna"]["passed"] == 16+ assert report["sol"]["passed"] == 24+ assert report["native"] is None+ path = packet / "provider-projection.json"+ path.write_text(path.read_text().replace('"pass"', '"fail"', 1))+ with pytest.raises(ValueError, match="Packet file changed"):+ load_packet(packet)+++def test_checksum_list_cannot_be_rewritten(packet):+ (packet / "SHA256SUMS").write_text("0" * 64 + " manifest.json\n")+ with pytest.raises(ValueError, match="pinned source packet"):+ load_packet(packet)++[email protected]("relative", ["../secret", "/secret"])+def test_packet_paths_cannot_escape(packet, relative):+ with pytest.raises(ValueError, match="relative"):+ dataset.packet_path(packet, relative)+++def calls_and_decisions(manifest):+ calls = []+ decisions = []+ for source in manifest["records"]:+ calls.append(+ {+ "case_id": source["id"],+ "image_sha256": source["input_image"]["sha256"],+ "attempts": 1,+ "status": "completed",+ "text": source["gold_text"],+ "transcription_sha256": source["gold_sha256"],+ }+ )+ decisions.append(+ {+ "case_id": source["id"],+ "image_sha256": source["input_image"]["sha256"],+ "transcription_sha256": source["gold_sha256"],+ "reviewer": "Synthetic test reviewer",+ "critical_outcomes": ["preserved"] * len(source["critical_values"]),+ "line_outcomes": ["represented"] * len(source["reviewed_lines"]),+ }+ )+ return calls, decisions+++def test_unknowns_and_submitted_failures_are_distinct(packet):+ manifest, _ = load_packet(packet)+ calls, decisions = calls_and_decisions(manifest)+ calls[0].update(status="unattempted", attempts=0)+ calls[1]["status"] = "error"+ calls[2]["status"] = "empty"+ decisions = decisions[4:]+ report = native_report(manifest, calls, decisions)+ assert (report["passed"], report["failed"], report["unattempted"], report["unreviewed"]) == (20, 2, 1, 1)+ assert report["complete_reviewed_cohort"] is False+ with pytest.raises(ValueError, match="every frozen case"):+ native_report(manifest, calls[:-1], decisions)+++def test_exact_transcription_binding_and_source_roles(packet):+ manifest, _ = load_packet(packet)+ calls, decisions = calls_and_decisions(manifest)+ decisions[0]["critical_outcomes"] = ["misassociated"]+ assert native_report(manifest, calls, decisions)["failed"] == 1+ decisions[1]["transcription_sha256"] = "0" * 64+ with pytest.raises(ValueError, match="exact transcription binding"):+ native_report(manifest, calls, decisions)+++def test_only_declared_blurred_source_can_be_excluded(packet):+ manifest, _ = load_packet(packet)+ calls, decisions = calls_and_decisions(manifest)+ decisions[0]["critical_outcomes"] = ["not_assessable"]+ with pytest.raises(ValueError, match="undeclared critical"):+ native_report(manifest, calls, decisions)+ source = manifest["records"][0]+ source.update(id="cord/train-0012", critical_values=[{}] * 16, reviewed_lines=["blurred logo", "visible line"])+ calls[0]["case_id"] = source["id"]+ decisions[0].update(+ case_id=source["id"],+ critical_outcomes=["preserved"] * 15 + ["not_assessable"],+ line_outcomes=["not_assessable", "represented"],+ )+ assert native_report(manifest, calls, decisions)["passed"] == 24+++def mock_transport(monkeypatch, handler):+ original = httpx.Client++ def configured(**kwargs):+ return original(**kwargs, transport=httpx.MockTransport(handler), trust_env=False)++ monkeypatch.setattr(httpx, "Client", configured)+ monkeypatch.delenv("SIE_API_KEY", raising=False)++[email protected]("base_url", ["https://ocr.example.test", "https://ocr.example.test/prefix"])+def test_actual_sdk_sends_full_jpeg_and_exact_controls_once(packet, tmp_path, monkeypatch, base_url):+ seen = []++ def handle(request):+ seen.append(request)+ payload = msgpack.unpackb(request.content, raw=False)+ item = payload["items"][0]+ body = {+ "model": "test/native",+ "items": [+ {"id": item["id"], "entities": [{"text": "Full source transcript", "label": "text", "score": 1.0}]}+ ],+ }+ return httpx.Response(+ 200, content=msgpack.packb(body, use_bin_type=True), headers={"content-type": "application/msgpack"}+ )++ mock_transport(monkeypatch, handle)+ monkeypatch.setenv("SIE_BASE_URL", base_url)+ monkeypatch.setenv("SIE_API_KEY", "synthetic-fixture-credential")+ output = tmp_path / "run"+ report = collector.collect(packet, output, "test/native", base_url, "Text Recognition:")+ assert report["physical_inference_posts"] == 24+ assert len(seen) == 24+ manifest, _ = load_packet(packet)+ for request, source in zip(seen, manifest["records"], strict=True):+ body = msgpack.unpackb(request.content, raw=False)+ assert body["items"][0]["id"] == source["id"]+ assert body["items"][0]["images"][0]["data"] == (packet / source["input_image"]["path"]).read_bytes()+ assert body["params"] == {+ "instruction": "Text Recognition:",+ "options": {"profile": "default", "max_new_tokens": 8192, "num_beams": 1},+ }+ assert (output / "wire/00-request.msgpack").read_bytes() == seen[0].content+ assert seen[0].headers["Authorization"] == "Bearer synthetic-fixture-credential"+ assert all(b"synthetic-fixture-credential" not in path.read_bytes() for path in output.rglob("*") if path.is_file())+ calls = [json.loads(line) for line in (output / "calls.jsonl").read_text().splitlines()]+ assert all(row["returned_model"] == "test/native" for row in calls)+ assert len(json.loads((output / "review-template.json").read_text())) == 24+ with pytest.raises(FileExistsError):+ collector.collect(packet, output, "test/native", "https://ocr.example.test")+++def test_loading_error_is_one_post_and_preserves_all_remaining_cases(packet, tmp_path, monkeypatch):+ seen = []++ def handle(request):+ seen.append(request)+ return httpx.Response(503, json={"error": {"code": "MODEL_LOADING", "message": "Still loading"}})++ mock_transport(monkeypatch, handle)+ output = tmp_path / "failed"+ report = collector.collect(packet, output, "test/native", "https://ocr.example.test")+ calls = [json.loads(line) for line in (output / "calls.jsonl").read_text().splitlines()]+ assert len(seen) == report["physical_inference_posts"] == 1+ assert calls[0]["status"] == "error"+ assert calls[0]["error_type"] == "PhysicalAttemptError"+ assert len(calls) == 24+ assert all(row["status"] == "unattempted" and row["attempts"] == 0 for row in calls[1:])+ assert json.loads((output / "review-template.json").read_text()) == []+++def test_in_flight_result_get_is_recorded_without_replaying_inference(packet, tmp_path, monkeypatch):+ seen = []+ item_id = ""++ def handle(request):+ nonlocal item_id+ seen.append(request.method)+ if request.method == "POST":+ item_id = msgpack.unpackb(request.content, raw=False)["items"][0]["id"]+ return httpx.Response(303, headers={"location": "/result?__modal_attempt_token=synthetic-token"})+ body = {+ "items": [{"id": item_id, "entities": [{"text": "Completed source text", "label": "text", "score": 1.0}]}]+ }+ return httpx.Response(+ 200, content=msgpack.packb(body, use_bin_type=True), headers={"content-type": "application/msgpack"}+ )++ mock_transport(monkeypatch, handle)+ output = tmp_path / "continuations"+ report = collector.collect(packet, output, "test/native", "https://ocr.example.test")+ assert seen == ["POST", "GET"] * 24+ assert report["physical_inference_posts"] == 24+ assert report["completed"] == 24+ calls = [json.loads(line) for line in (output / "calls.jsonl").read_text().splitlines()]+ for row in calls:+ assert [hop["method"] for hop in row["response_hops"]] == ["POST", "GET"]+ assert row["response_body_sha256"] == row["response_hops"][-1]["body_sha256"]+ assert (output / "wire/00-response-01.bin").exists()