diff --git a/docs/contracts/production-proofs.md b/docs/contracts/production-proofs.md new file mode 100644 index 000000000..1ceb9e88e --- /dev/null +++ b/docs/contracts/production-proofs.md @@ -0,0 +1,83 @@ +# P1 worker-report codecs and capture drafts + +`inferrsi.benchmark.proofs` owns pure `encode_report`, `decode_report`, +`validate_report`, `project`, and `ProofProjector` ports. This is the Benchmark +codec/projector slice of the accepted capture boundary in +[#565](https://github.com/InferMatrixLab/InferRSI/issues/565#issuecomment-7063820381). +It does not implement a worker, grader predicate, baseline workload, sampler, +Harness capture lifecycle or Apps adapter. Their actual behavior and resource +pins remain prerequisites for shared production acceptance. + +## Closed raw report + +The frozen `fixture-grader@1` output contains exactly `schema_version: 1`, +`grader` and `samples`. The latter two are required and may be null for an +incomplete family. A non-null grader contains exactly `status` (`passed` or +`failed`) and `reasons` (portable identifiers). Samples contain the four frozen +identities A1/B1/B2/A2, baseline/candidate/candidate/baseline and rounds 1/1/2/2. +Each value is a positive canonical Decimal string with unit `ms`. + +No identity, Ref, producer, control domain or cleanup assertion is accepted from +the worker. JSON whitespace is allowed; duplicate keys, floating/nonfinite +numeric tokens, invalid Unicode and unsupported versions are rejected. Encoders +use the existing canonical v1 codec. Neither encoding nor validation opens files. + +## Frozen configuration and runtime inputs + +Construct `ProofProjector(prepared, protocol_bytes)` before attempting execution. +It snapshots the preparation and checks the existing task/grader/recipe/rule +support and complete protocol identity using the production preparation port. +Unsupported configuration raises `ProofError` with the existing portable code. + +Call `project(phase, facts, *, candidate_bytes, report_bytes)` on that object, or +use the one-shot function with `prepared` and `protocol_bytes` first. The two +phases are `preparing` and `finalizing`. Bytes are supplied by a host adapter; +this module receives no filesystem, network, process, archive or store handle. +`None` means the corresponding byte input is unavailable. An unexpected host +content type raises `TypeError` rather than becoming an evidence gap. + +`CONTEXT_FIELDS` specifies a closed version-1 wire projection of existing H +facts: request/run/attempt/digest, preparation/protocol/operation/scope/candidate, +actual bound inputs and target/runtime binding, steps, started/outcome/exit code, +cleanup and leases. Unavailable terminal fields are null. The host supplies a +defensive snapshot; no shared Python business DTO is introduced. + +The candidate bytes must match the actual retained input's digest, size, attempt +and capture fact. Any frozen candidate expectation also applies. Worker report +families require an actually started input-bound step with the observed entry, +revision and code digest matching the frozen recipe. Allowed control domains +must match the actual target; changing a locator does not change identity. +These checks do not authenticate a caller-provided context: H owns the context, +read capability and final producer sealing. + +## Draft output and refusal + +The return is `(draft_wire, proof_blobs)`. Draft wire has exactly +`schema_version`, `checks` and `errors`. Each check has the frozen check identity, +revision, subject, phase and artifact schema, plus status, reasons, `proof_key` +and source. Sources are `candidate_capture`, `worker_report`, `cleanup_capture`. +`proof_key` is null when no proof was produced. The separate map associates keys +with immutable canonical proof bytes. Errors contain a portable `code`, affected +`check_ids`, and an identifier `reason`. + +The preparing phase checks actual UTF-8 bytes and drafts format-proof@1. Invalid +UTF-8 gives a failed format proof, not a host error or an invented correctness +failure. This projector does not decide whether to start a worker. + +The finalizing phase projects completed grader/sample families into the existing +grader-proof@1 and samples-proof@1. Attempt/candidate/hash fields come from H +facts, never report declarations. A missing or invalid family is not_performed +without a proof. An explicit null family remains valid report syntax but emits +an `InvalidRequest` draft error with `report_family_incomplete` and its check ID; +H persists that diagnostic as a finalizing execution error after the worker ran. +Each incomplete family gets its own diagnostic. A valid grader result survives +invalid sample semantics, and +vice versa; invalid raw JSON or a foreign report envelope invalidates the report +itself. The cleanup proof comes only from observed cleanup and acquired-lease +release facts. Unknown or failed cleanup never becomes confirmed. + +H must validate drafts, retain raw and derived bytes before its record commit, +compute Refs itself and seal actual producer/domain/route/attempt fields. A draft +is neither a trustworthy CheckObservation nor a committed Ref. Existing offline +assessment and V21/V22 rules remain unchanged. This slice alone cannot make a +real execution record contain matching proofs or establish complete F/C/M. diff --git a/docs/operations.md b/docs/operations.md index 58a0c946a..77d899e5f 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -60,6 +60,7 @@ Effect classes used below: | Freeze a configured P1 preparation | Python `benchmark.preparation.PreparationService.prepare`; [production prepare](contracts/production-prepare.md) | Read-only resource access / pure encoding | Verifies supplied frozen worker/resource bytes and returns a preparation, protocol and role-keyed closure; Apps separately archives them before publishing a Ref | | Evaluate saved requests | CLI `evaluate prepare/execute/assess`; [saved-request CLI](apps-evaluate-cli.md) | Local archive/output writing; execute additionally runs the configured H target | Explicit saved request, output ID, storage and trusted runtime configuration; reuses Apps ports and results without allocating attempts, selecting feedback or retrying | | Assess one fixed P1 record offline | Python `benchmark.assessment.assess`; [production assess](contracts/production-assess.md) | Read-only retained evidence / pure encoding | Verifies the frozen protocol, actual capture and proof bytes; returns independent claims without launching a worker or writing an archive; Apps selects the primary key and archives the result | +| Project P1 worker reports into capture drafts | Python `benchmark.proofs` codecs / `ProofProjector.project`; [proof drafts](contracts/production-proofs.md) | Pure computation | Produces proof bytes from supplied capture facts and reports; H must authenticate, retain and seal them before commit; no worker or grader execution | | Seal a generation with frozen feedback authorization | Python `harness.generation.prepare_generation`; [opt-in feedback profile](contracts/generation-feedback-policy.md) | Local context / policy / generation-plan retention | Optional fixed policy and source record Refs authorize original scope/check proofs before provider calls. Absent-policy calls remain a trusted-host path; no automatic execution or policy-approval authentication | | Seal host-approved generation context without a policy Ref | Python `harness.generation.prepare_generation`; [feedback boundary](contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. Without the opt-in policy Ref, H seals supplied material and does not prove feedback-policy enforcement or execute a worker | | Visualize a recorded run or campaign | CLI `dashboard`; [dashboard](dashboard.md) | Report-generating / local read-only serving | Writes an offline HTML snapshot or serves an optional live view on loopback; does not run an agent or validate a claim | diff --git a/src/inferrsi/benchmark/proofs.py b/src/inferrsi/benchmark/proofs.py new file mode 100644 index 000000000..3661c04ea --- /dev/null +++ b/src/inferrsi/benchmark/proofs.py @@ -0,0 +1,301 @@ +"""Pure P1 worker-report codecs and drafts for a host-owned capture lifecycle. + +Drafts are not observations or committed references. Harness must authenticate +their source, retain the bytes and seal producer/attempt fields before commit. +This module neither runs a grader nor manufactures measurement samples. +""" + +from __future__ import annotations + +from decimal import Decimal +from hashlib import sha256 + +from ..contracts.json_v1 import CanonicalError +from ..contracts.json_v1 import decode as canonical_decode +from ..contracts.json_v1 import encode as canonical_encode +from . import assessment, preparation + +CONTEXT_FIELDS = frozenset( + "schema_version request_id run_id attempt_id request_digest prepared_ref protocol_digest " + "operation validation_scope candidate bound_inputs target_binding steps started " + "process_outcome exit_code cleanup resource_leases".split() +) +_ORDER = (("A1", "baseline", 1), ("B1", "candidate", 1), + ("B2", "candidate", 2), ("A2", "baseline", 2)) + + +class ProofError(ValueError): + """A declared codec/configuration rejection; no dependency on Harness types.""" + + def __init__(self, code: str, message: str): + super().__init__(message) + self.code = code + + +def _require(condition, message="Invalid proof projection input.", code="InvalidRequest"): + if not condition: + raise ProofError(code, message) + + +def _object(value, fields): + _require(isinstance(value, dict) and value.keys() == fields) + + +def _snapshot(value): + try: + return canonical_decode(canonical_encode(value)) + except CanonicalError: + raise ProofError("InvalidRequest", "Invalid canonical projection input.") from None + + +def _report_envelope(data): + if not isinstance(data, bytes): + raise TypeError("A worker report must be bytes.") + try: + value = assessment._proof_json(data) + except (CanonicalError, assessment.AssessmentError) as error: + raise ProofError("InvalidRequest", "Invalid worker report JSON.") from error + _object(value, {"schema_version", "grader", "samples"}) + _require(type(value["schema_version"]) is int and value["schema_version"] == 1, + "Unsupported worker report version.", "UnsupportedSchema") + return value + + +def _grader(value): + _object(value, {"status", "reasons"}) + _require(value["status"] in ("passed", "failed") + and isinstance(value["reasons"], list) + and all(preparation._id(reason) for reason in value["reasons"])) + + +def _samples(values): + _require(isinstance(values, list) and len(values) == len(_ORDER)) + for item, identity in zip(values, _ORDER): + _object(item, {"sample_id", "role", "round", "value", "unit"}) + _require(type(item["round"]) is int + and (item["sample_id"], item["role"], item["round"]) == identity + and item["unit"] == "ms" and isinstance(item["value"], str) + and preparation._DECIMAL.fullmatch(item["value"]) is not None + and Decimal(item["value"]) > 0) + + +def validate_report(value: dict) -> None: + """Validate the complete closed fixture-grader@1 report without I/O.""" + value = _report_envelope(canonical_encode(_snapshot(value))) + if value["grader"] is not None: + _grader(value["grader"]) + if value["samples"] is not None: + _samples(value["samples"]) + + +def encode_report(value: dict) -> bytes: + validate_report(value) + return canonical_encode(value) + + +def decode_report(data: bytes) -> dict: + """Raw report whitespace is allowed; strict v1 JSON and family rules apply.""" + value = _report_envelope(data) + validate_report(value) + return value + + +def _context(facts, prepared): + _object(facts, CONTEXT_FIELDS) + _require(type(facts["schema_version"]) is int and facts["schema_version"] == 1, + "Unsupported capture context.", "UnsupportedSchema") + _require(all(preparation._id(facts[key]) for key in ("request_id", "run_id", "attempt_id")) + and facts["request_id"] == facts["attempt_id"]) + digest = facts["request_digest"] + _require(isinstance(digest, str) and digest.startswith("sha256:") + and preparation._SHA.fullmatch(digest[7:]) is not None) + ref = facts["prepared_ref"] + _object(ref, {"schema_version", "prepared_id", "artifact"}) + try: + preparation._artifact(ref["artifact"]) + except preparation.PreparationError as error: + raise ProofError(error.code, str(error)) from error + _require(type(ref["schema_version"]) is int and ref["schema_version"] == 1 + and ref["prepared_id"] == prepared["prepared_id"] + and all(facts[key] == prepared[key] + for key in ("protocol_digest", "operation", "validation_scope")), + "Capture context differs from the preparation.", "IdentityMismatch") + candidate = facts["candidate"] + _require(isinstance(candidate, dict) and preparation._id(candidate.get("candidate_id")) + and all(candidate.get(key) == prepared["candidate_contract"][key] + for key in ("kind", "input_role")), + "Candidate contract differs.", "IdentityMismatch") + expected = prepared["expected_candidate"] + _require(expected is None or candidate["candidate_id"] == expected["candidate_id"], + "Candidate declaration differs.", "IdentityMismatch") + _require(isinstance(facts["bound_inputs"], list) and isinstance(facts["steps"], list) + and type(facts["started"]) is bool and isinstance(facts["target_binding"], dict)) + + +def _candidate_digest(facts, data, prepared): + if data is None: + return None + if not isinstance(data, bytes): + raise TypeError("Captured candidate content must be bytes or None.") + matches = [item for item in facts["bound_inputs"] if isinstance(item, dict) + and item.get("role") == facts["candidate"]["input_role"] + and item.get("attempt_id") == facts["attempt_id"]] + _require(len(matches) == 1, "Candidate capture is ambiguous.", "IdentityMismatch") + item = matches[0] + digest, ref = sha256(data).hexdigest(), item.get("retained_ref") + _require(isinstance(ref, dict) and item.get("actual_sha256") == ref.get("sha256") == digest + and type(ref.get("size_bytes")) is int and ref["size_bytes"] == len(data) + and item.get("captured_at") is not None and item.get("snapshot_format") == "file-v1", + "Candidate bytes differ from the actual capture.", "IdentityMismatch") + try: + preparation._artifact(ref) + assessment._timestamp(item["captured_at"]) + except (preparation.PreparationError, assessment.AssessmentError) as error: + raise ProofError("IdentityMismatch", "Invalid actual candidate capture.") from error + expected = prepared["expected_candidate"] + _require(expected is None or expected["sha256"] == digest, + "Actual candidate differs from its frozen expectation.", "IdentityMismatch") + return digest + + +def _worker_bound(facts, prepared): + if facts["started"] is not True: + return False + runtimes = facts["target_binding"].get("runtime_bindings_by_step") + if not isinstance(runtimes, list): + return False + started = {step.get("step_id") for step in facts["steps"] if isinstance(step, dict) + and step.get("status") != "not_started" and step.get("started_at") is not None + and preparation._id(step.get("step_id"))} + inputs = {step for item in facts["bound_inputs"] if isinstance(item, dict) + and item.get("role") == facts["candidate"]["input_role"] + and item.get("attempt_id") == facts["attempt_id"] + and isinstance(item.get("step_ids"), list) + for step in item["step_ids"] if preparation._id(step)} + recipe = prepared["recipe"] + return any(isinstance(runtime, dict) and preparation._id(runtime.get("step_id")) + and runtime.get("step_id") in started & inputs + and all(runtime.get(key) == recipe[key] for key in + ("runtime_role", "entrypoint", "entrypoint_revision", "code_sha256")) + for runtime in runtimes) + + +class ProofProjector: + """Freeze supported configuration before execution; project supplied bytes only.""" + + def __init__(self, prepared: dict, protocol_bytes: bytes): + self._prepared = _snapshot(prepared) + try: + preparation.validate_prepared(self._prepared, protocol_bytes) + except (CanonicalError, preparation.PreparationError) as error: + raise ProofError(getattr(error, "code", "InvalidRequest"), str(error)) from error + + def project(self, phase, facts, *, candidate_bytes, report_bytes): + """Return (draft wire, proof bytes), never producer identities or valid Refs.""" + _require(phase in ("preparing", "finalizing"), "Unsupported capture phase.") + if report_bytes is not None and not isinstance(report_bytes, bytes): + raise TypeError("A worker report must be bytes or None.") + prepared, facts = self._prepared, _snapshot(facts) + _context(facts, prepared) + if phase == "preparing": + _require(facts["started"] is False + and all(facts[key] is None for key in + ("process_outcome", "exit_code", "cleanup", "resource_leases")), + "Preparing capture must precede worker and terminal observations.", + "IdentityMismatch") + actual = _candidate_digest(facts, candidate_bytes, prepared) + required = {item["check_id"]: item for item in prepared["required_evidence"]} + draft, blobs = {"schema_version": 1, "checks": [], "errors": []}, {} + common = {"schema_version": 1, "attempt_id": facts["attempt_id"], + "operation": facts["operation"], "validation_scope": facts["validation_scope"]} + candidate = {**common, "candidate_id": facts["candidate"]["candidate_id"], + "actual_sha256": actual} + + def emit(key, source, status, proof=None, reasons=(), error=None): + rule = required[key] + allowed = (facts["target_binding"].get("control_domain") + in rule["allowed_control_domains"]) + if not allowed: + status, proof, reasons, error = ( + "not_performed", None, ["control_domain_mismatch"], "IdentityMismatch", + ) + proof_key = key if proof is not None else None + draft["checks"].append({ + **{field: rule[field] for field in + ("check_id", "checker_revision", "subject", "phase", "artifact_schema")}, + "status": status, "reasons": list(reasons), "proof_key": proof_key, + "source": source, + }) + if proof is not None: + blobs[key] = canonical_encode(proof) + if error: + draft["errors"].append({"code": error, "check_ids": [key], + "reason": reasons[0]}) + + if phase == "preparing": + if actual is None: + emit("format", "candidate_capture", "not_performed", + reasons=["candidate_bytes_unavailable"], error="ArtifactUnavailable") + else: + try: + candidate_bytes.decode("utf-8") + status, reasons = "passed", [] + except UnicodeError: + status, reasons = "failed", ["invalid_utf8"] + emit("format", "candidate_capture", status, { + **candidate, "claim_id": "F", "checker_revision": "1", + "status": status, "reasons": reasons, + }, reasons) + return _snapshot(draft), dict(blobs) + + report, report_error, report_reason = None, None, None + if report_bytes is None: + report_error, report_reason = "ArtifactUnavailable", "worker_report_unavailable" + elif actual is None: + report_error, report_reason = "ArtifactUnavailable", "candidate_bytes_unavailable" + elif not _worker_bound(facts, prepared): + report_error, report_reason = "IdentityMismatch", "worker_not_bound" + else: + try: + report = _report_envelope(report_bytes) + except ProofError as error: + report_error, report_reason = error.code, "invalid_worker_report" + + for key, field, validate in (("grader", "grader", _grader), + ("samples", "samples", _samples)): + if report is None: + emit(key, "worker_report", "not_performed", reasons=[report_reason], + error=report_error) + continue + family = report[field] + if family is None: + emit(key, "worker_report", "not_performed", reasons=["report_family_incomplete"], + error="InvalidRequest") + continue + try: + validate(family) + except ProofError as error: + emit(key, "worker_report", "not_performed", reasons=["invalid_report_family"], + error=error.code) + continue + status, reasons = (family["status"], family["reasons"]) if key == "grader" else ( + "passed", [], + ) + payload = ({"claim_id": "C", "checker_revision": "1", **family} + if key == "grader" else {"samples": family}) + emit(key, "worker_report", status, {**candidate, **payload}, reasons) + + if facts["cleanup"] is None or facts["resource_leases"] is None: + emit("cleanup", "cleanup_capture", "not_performed", reasons=["cleanup_unobserved"]) + else: + confirmed = assessment._cleanup_confirmed(facts) + emit("cleanup", "cleanup_capture", "passed" if confirmed else "failed", + {**common, "confirmed": confirmed}, [] if confirmed else ["cleanup_unconfirmed"]) + return _snapshot(draft), dict(blobs) + + +def project(prepared, protocol_bytes, phase, facts, *, candidate_bytes, report_bytes): + """One-shot pure projection; hosts may cache ProofProjector for frozen config.""" + return ProofProjector(prepared, protocol_bytes).project( + phase, facts, candidate_bytes=candidate_bytes, report_bytes=report_bytes, + ) diff --git a/tests/check_installed.py b/tests/check_installed.py index c09c29fca..611e5e7b7 100644 --- a/tests/check_installed.py +++ b/tests/check_installed.py @@ -834,8 +834,12 @@ def _inventory(root, prefix): "from inferrsi.benchmark.assessment import (\n" " AssessmentService, assess, decode, encode, validate_assessment,\n" ")\n" + "from inferrsi.benchmark.proofs import (\n" + " ProofProjector, decode_report, encode_report, project, validate_report,\n" + ")\n" "assert all(callable(port) for port in\n" - " (AssessmentService, assess, decode, encode, validate_assessment))\n" + " (AssessmentService, assess, decode, encode, validate_assessment,\n" + " ProofProjector, decode_report, encode_report, project, validate_report))\n" "for prefix in ('inferrsi.apps', 'inferrsi.harness', 'inferrsi.knowledge'):\n" " assert not [name for name in sys.modules if name == prefix\n" " or name.startswith(prefix + '.')], prefix\n" diff --git a/tests/test_benchmark_proofs.py b/tests/test_benchmark_proofs.py new file mode 100644 index 000000000..d4434a51f --- /dev/null +++ b/tests/test_benchmark_proofs.py @@ -0,0 +1,410 @@ +"""Pure capture-draft tests; no worker, process observation or acceptance claim.""" + +import json +import socket +import subprocess +from copy import deepcopy +from hashlib import sha256 +from pathlib import Path + +import pytest + +from inferrsi.benchmark import assessment, preparation, proofs +from inferrsi.contracts.json_v1 import decode, encode + +ROOT = Path(__file__).resolve().parents[1] +GOLDEN = ROOT / "docs/contracts/fixtures/t108-v4" + + +def report(): + return { + "schema_version": 1, "grader": {"status": "passed", "reasons": []}, + "samples": [{"sample_id": name, "role": role, "round": round_, "value": "1.25", + "unit": "ms"} for name, role, round_ in + (("A1", "baseline", 1), ("B1", "candidate", 1), + ("B2", "candidate", 2), ("A2", "baseline", 2))], + } + + +@pytest.fixture +def case(): + prepared_bytes = (GOLDEN / "prepared.json").read_bytes() + prepared = decode(prepared_bytes) + # Derive a new in-memory preparation; historical vector bytes are untouched. + prepared["expected_candidate"] = None + prepared["prepared_id"] = preparation.prepared_id(prepared) + prepared_bytes = preparation.encode(prepared) + protocol = (GOLDEN / "protocol.json").read_bytes() + data = b"captured candidate\n" + ref = {"location": "retained/candidate", "sha256": sha256(data).hexdigest(), + "size_bytes": len(data), "media_type": "text/plain"} + source = decode((GOLDEN / "record-payload.json").read_bytes()) + facts = {key: deepcopy(source[key]) for key in proofs.CONTEXT_FIELDS} + facts.update( + attempt_id="runtime-attempt-37", request_id="runtime-attempt-37", run_id="runtime-run-37", + request_digest="sha256:" + "a" * 64, + prepared_ref={"schema_version": 1, "prepared_id": prepared["prepared_id"], + "artifact": {"location": "retained/prepared", + "media_type": "application/json", + "sha256": sha256(prepared_bytes).hexdigest(), + "size_bytes": len(prepared_bytes)}}, + protocol_digest=prepared["protocol_digest"], candidate={ + "candidate_id": "runtime-candidate-37", "kind": "text", "input_role": "candidate", + "context_refs": [], "parent_id": None, "parent_digest": None, + }, + bound_inputs=[{"role": "candidate", "attempt_id": "runtime-attempt-37", + "retained_ref": ref, "actual_sha256": ref["sha256"], + "captured_at": "2099-01-01T00:00:00Z", "snapshot_format": "file-v1", + "step_ids": ["main"]}], + target_binding={"control_domain": "fixture-domain", "runtime_bindings_by_step": [{ + "step_id": "main", **{key: prepared["recipe"][key] for key in + ("runtime_role", "entrypoint", "entrypoint_revision", + "code_sha256")}, + }]}, + steps=[{"step_id": "main", "status": "exited", "started_at": "2099-01-01T00:00:00Z"}], + started=True, process_outcome="exited", exit_code=0, + cleanup={"status": "confirmed", "process_exit_confirmed": True}, + resource_leases={"applicability": "applicable", "leases": [{ + "release_confirmed": True, "release_confirmed_at": "2099-01-01T00:00:00Z", + }]}, + ) + return prepared, protocol, facts, data + + +def project(case, phase="finalizing", value=None, **kwargs): + prepared, protocol, facts, data = case + if phase == "preparing": + facts = deepcopy(facts) + facts.update(started=False, steps=[], process_outcome=None, exit_code=None, + cleanup=None, resource_leases=None) + kwargs.setdefault("candidate_bytes", data) + kwargs.setdefault("report_bytes", proofs.encode_report(report() if value is None else value)) + return proofs.project(prepared, protocol, phase, facts, **kwargs) + + +def by_id(draft): + return {check["check_id"]: check for check in draft["checks"]} + + +def test_report_codec_is_strict_but_preserves_input_whitespace_semantics(): + value = report() + assert proofs.decode_report(proofs.encode_report(value)) == value + assert proofs.decode_report(json.dumps(value, indent=2).encode()) == value + assert proofs.encode_report(value) == encode(value) + proofs.validate_report(value) + + +@pytest.mark.parametrize("phase", ["preparing", "finalizing"]) +def test_drafts_use_runtime_identity_and_existing_proof_schemas(case, phase): + prepared, _, facts, data = case + draft, blobs = project(case, phase) + assert draft["schema_version"] == 1 and draft["errors"] == [] + assert set(blobs) == ({"format"} if phase == "preparing" else {"grader", "samples", "cleanup"}) + required = {x["check_id"]: x for x in prepared["required_evidence"]} + for check in draft["checks"]: + assert "producer" not in check and "attempt_id" not in check + assert "evidence_refs" not in check and "artifact" not in check + raw = blobs[check["proof_key"]] + proof = assessment._proof(raw, required[check["check_id"]], facts, sha256(data).hexdigest()) + assert proof["attempt_id"] == "runtime-attempt-37" + if check["check_id"] != "cleanup": + assert proof["candidate_id"] == "runtime-candidate-37" + assert check["status"] == "passed" + + +@pytest.mark.parametrize("raw,code", [ + (b"{}", "InvalidRequest"), + (b'{"schema_version":1,"grader":null,"samples":null,"grader":null}', "InvalidRequest"), + (b'{"schema_version":2,"grader":null,"samples":null}', "UnsupportedSchema"), + (b'{"schema_version":true,"grader":null,"samples":null}', "UnsupportedSchema"), + (b'{"schema_version":1.0,"grader":null,"samples":null}', "InvalidRequest"), + (b'{"schema_version":1,"grader":NaN,"samples":null}', "InvalidRequest"), + (b'{"schema_version":1,"grader":"\\ud800","samples":null}', "InvalidRequest"), + (b"\xff", "InvalidRequest"), +]) +def test_bad_report_envelopes_refuse_without_fabricating_proofs(case, raw, code): + with pytest.raises(proofs.ProofError) as caught: + proofs.decode_report(raw) + assert caught.value.code == code + draft, blobs = project(case, report_bytes=raw) + assert by_id(draft)["grader"]["status"] == by_id(draft)["samples"]["status"] == "not_performed" + assert set(blobs) == {"cleanup"} + assert {x["code"] for x in draft["errors"]} == {code} + + +@pytest.mark.parametrize("extra", ["producer", "control_domain", "cleanup", "attempt_id", + "candidate_id", "actual_sha256", "record_ref"]) +def test_worker_cannot_supply_producer_identity_cleanup_or_references(case, extra): + value = report() + value[extra] = "forged" + draft, blobs = project(case, report_bytes=encode(value)) + assert set(blobs) == {"cleanup"} + assert all(by_id(draft)[key]["status"] == "not_performed" for key in ("grader", "samples")) + assert decode(blobs["cleanup"])["confirmed"] is True + + +@pytest.mark.parametrize("change", ["reversed", "duplicate", "float", "zero", "negative", + "noncanonical", "unit", "bool-round", "wrong-role", + "unknown-field", "missing", "null-item"]) +def test_invalid_samples_do_not_hide_an_independent_grader_result(case, change): + value = report() + sample = value["samples"][0] + if change == "reversed": + value["samples"].reverse() + elif change == "duplicate": + value["samples"][1] = deepcopy(sample) + elif change == "float": + sample["value"] = 1.25 + elif change == "zero": + sample["value"] = "0" + elif change == "negative": + sample["value"] = "-1" + elif change == "noncanonical": + sample["value"] = "1.0" + elif change == "unit": + sample["unit"] = "seconds" + elif change == "bool-round": + sample["round"] = True + elif change == "wrong-role": + sample["role"] = "candidate" + elif change == "unknown-field": + sample["producer"] = "forged" + elif change == "missing": + value["samples"].pop() + else: + value["samples"][0] = None + raw = json.dumps(value).encode() + draft, blobs = project(case, report_bytes=raw) + if change == "float": + # A forbidden JSON numeric token invalidates the raw envelope itself. + assert set(blobs) == {"cleanup"} + else: + assert set(blobs) == {"grader", "cleanup"} + assert by_id(draft)["grader"]["status"] == "passed" + assert by_id(draft)["samples"]["status"] == "not_performed" + with pytest.raises(proofs.ProofError): + proofs.decode_report(raw) + + +@pytest.mark.parametrize("grader", [{"status": "unknown", "reasons": []}, + {"status": "passed", "reasons": [None]}, None]) +def test_bad_or_incomplete_grader_keeps_valid_samples_and_cleanup(case, grader): + value = report() + value["grader"] = grader + draft, blobs = project(case, report_bytes=encode(value)) + assert set(blobs) == {"samples", "cleanup"} + assert by_id(draft)["grader"]["status"] == "not_performed" + assert by_id(draft)["samples"]["status"] == "passed" + + +@pytest.mark.parametrize("missing", [("grader",), ("samples",), ("grader", "samples")]) +def test_explicit_null_families_emit_diagnostics_without_losing_valid_siblings(case, missing): + value = report() + for field in missing: + value[field] = None + raw = proofs.encode_report(value) + assert proofs.decode_report(raw) == value + + _, complete_blobs = project(case) + draft, blobs = project(case, report_bytes=raw) + assert set(blobs) == {"grader", "samples", "cleanup"} - set(missing) + for field in missing: + check = by_id(draft)[field] + assert check["status"] == "not_performed" and check["proof_key"] is None + assert check["reasons"] == ["report_family_incomplete"] + assert {tuple(error["check_ids"]): (error["code"], error["reason"]) + for error in draft["errors"]} == { + (field,): ("InvalidRequest", "report_family_incomplete") for field in missing + } + assert all(raw == complete_blobs[field] for field, raw in blobs.items()) + + +def test_independent_failed_grade_is_not_rewritten_or_overlaid(case): + value = report() + value.update(grader={"status": "failed", "reasons": ["actual_grader_rejection"]}, samples=None) + draft, blobs = project(case, value=value) + assert by_id(draft)["grader"]["status"] == "failed" + assert decode(blobs["grader"])["reasons"] == ["actual_grader_rejection"] + assert by_id(draft)["samples"]["status"] == "not_performed" + assert draft["errors"] == [{"code": "InvalidRequest", "check_ids": ["samples"], + "reason": "report_family_incomplete"}] + + +@pytest.mark.parametrize("change", ["not-started", "entry-digest", "entry-name", "input-step", + "no-start-time", "bad-runtime-step"]) +def test_a_report_without_an_actual_bound_worker_is_not_trusted(case, change): + facts = case[2] + runtime = facts["target_binding"]["runtime_bindings_by_step"][0] + if change == "not-started": + facts["started"] = False + elif change == "entry-digest": + runtime["code_sha256"] = "b" * 64 + elif change == "entry-name": + runtime["entrypoint"] = "other_worker" + elif change == "input-step": + facts["bound_inputs"][0]["step_ids"] = ["other"] + elif change == "no-start-time": + facts["steps"][0]["started_at"] = None + else: + runtime["step_id"] = {} + draft, blobs = project(case) + assert set(blobs) == {"cleanup"} + assert {x["code"] for x in draft["errors"]} == {"IdentityMismatch"} + + +@pytest.mark.parametrize("change", ["attempt", "prepared", "protocol", "scope", "actual-sha", + "ref-sha", "ref-size", "capture-time", "duplicate-input"]) +def test_foreign_or_corrupt_capture_context_refuses(case, change): + facts = case[2] + bound = facts["bound_inputs"][0] + if change == "attempt": + bound["attempt_id"] = "foreign-attempt" + elif change == "prepared": + facts["prepared_ref"]["prepared_id"] = "sha256:" + "b" * 64 + elif change == "protocol": + facts["protocol_digest"] = "sha256:" + "b" * 64 + elif change == "scope": + facts["validation_scope"] = "foreign" + elif change == "actual-sha": + bound["actual_sha256"] = "b" * 64 + elif change == "ref-sha": + bound["retained_ref"]["sha256"] = "b" * 64 + elif change == "ref-size": + bound["retained_ref"]["size_bytes"] += 1 + elif change == "capture-time": + bound["captured_at"] = "not-a-time" + else: + facts["bound_inputs"].append(deepcopy(bound)) + with pytest.raises(proofs.ProofError) as error: + project(case) + assert error.value.code == "IdentityMismatch" + + +@pytest.mark.parametrize("phase", ["preparing", "finalizing"]) +def test_unsupported_actual_control_domain_refuses_each_affected_check(case, phase): + case[2]["target_binding"]["control_domain"] = "foreign-domain" + draft, blobs = project(case, phase) + assert blobs == {} and all(x["status"] == "not_performed" for x in draft["checks"]) + assert {x["code"] for x in draft["errors"]} == {"IdentityMismatch"} + + +@pytest.mark.parametrize("status,confirmed", [("confirmed", True), ("failed", False), + ("unknown", False)]) +def test_cleanup_proof_comes_from_controller_facts(case, status, confirmed): + case[2]["cleanup"]["status"] = status + draft, blobs = project(case) + assert decode(blobs["cleanup"])["confirmed"] is confirmed + assert by_id(draft)["cleanup"]["status"] == ("passed" if confirmed else "failed") + + +@pytest.mark.parametrize("change", ["release", "release-time", "process-exit", "unobserved"]) +def test_unknown_or_incomplete_cleanup_is_never_confirmed(case, change): + facts = case[2] + if change == "release": + facts["resource_leases"]["leases"][0]["release_confirmed"] = False + elif change == "release-time": + facts["resource_leases"]["leases"][0]["release_confirmed_at"] = None + elif change == "process-exit": + facts["cleanup"]["process_exit_confirmed"] = None + else: + facts["cleanup"] = None + draft, blobs = project(case) + if change == "unobserved": + assert by_id(draft)["cleanup"]["status"] == "not_performed" and "cleanup" not in blobs + else: + assert decode(blobs["cleanup"])["confirmed"] is False + + +def test_format_validation_reads_actual_bytes_and_can_fail_without_a_worker(case): + bad = b"\xff" + case[2]["bound_inputs"][0].update(actual_sha256=sha256(bad).hexdigest()) + case[2]["bound_inputs"][0]["retained_ref"].update(sha256=sha256(bad).hexdigest(), size_bytes=1) + case[2].update(started=False, steps=[], process_outcome=None, exit_code=None, + cleanup=None, resource_leases=None) + draft, blobs = project(case, "preparing", candidate_bytes=bad, report_bytes=None) + assert by_id(draft)["format"]["status"] == "failed" + assert decode(blobs["format"])["reasons"] == ["invalid_utf8"] + assert draft["errors"] == [] + + +@pytest.mark.parametrize("phase", ["preparing", "finalizing"]) +def test_missing_candidate_bytes_does_not_invent_a_positive_proof(case, phase): + draft, blobs = project(case, phase, candidate_bytes=None) + assert set(blobs) == (set() if phase == "preparing" else {"cleanup"}) + assert all(x["status"] == "not_performed" for x in draft["checks"] + if x["check_id"] != "cleanup") + + +def test_configuration_and_drafts_are_snapshotted_and_projection_is_pure(case, monkeypatch): + prepared, protocol, facts, data = case + frozen = deepcopy((prepared, facts)) + projector = proofs.ProofProjector(prepared, protocol) + prepared["required_evidence"].clear() + + def forbidden(*args, **kwargs): + pytest.fail("pure proof projection performed host I/O or execution") + + monkeypatch.setattr(Path, "open", forbidden) + monkeypatch.setattr(subprocess, "run", forbidden) + monkeypatch.setattr(socket, "create_connection", forbidden) + kwargs = {"candidate_bytes": data, "report_bytes": proofs.encode_report(report())} + first = projector.project("finalizing", facts, **kwargs) + clean = deepcopy(first) + first[0]["checks"][0]["artifact_schema"]["revision"] = "99" + first[1]["grader"] = b"mutated" + assert projector.project("finalizing", facts, **kwargs) == clean + assert facts == frozen[1] + + +@pytest.mark.parametrize("field", ["schema_version", "operation", "validation_scope", "grader"]) +def test_unsupported_frozen_configuration_refuses_before_projection(case, field): + prepared, protocol, _, _ = case + if field == "schema_version": + prepared[field] = 2 + elif field == "grader": + prepared[field]["revision"] = "2" + else: + prepared[field] = "other" + with pytest.raises(proofs.ProofError): + proofs.ProofProjector(prepared, protocol) + + +@pytest.mark.parametrize("argument", ["candidate_bytes", "report_bytes"]) +def test_unknown_host_content_types_propagate_as_programming_errors(case, argument): + with pytest.raises(TypeError): + project(case, **{argument: object()}) + + +@pytest.mark.parametrize("key", ["started", "process_outcome", "exit_code", "cleanup", + "resource_leases"]) +def test_a_late_context_cannot_be_relabelled_as_preparing(case, key): + prepared, protocol, facts, data = case + value = deepcopy(facts[key]) + facts.update(started=False, process_outcome=None, exit_code=None, cleanup=None, + resource_leases=None) + facts[key] = value + with pytest.raises(proofs.ProofError) as caught: + proofs.project(prepared, protocol, "preparing", facts, + candidate_bytes=data, report_bytes=None) + assert caught.value.code == "IdentityMismatch" + + +def test_a_frozen_expected_candidate_is_enforced(case): + prepared, protocol, facts, data = case + prepared["expected_candidate"] = { + "candidate_id": facts["candidate"]["candidate_id"], + "format_schema": {"name": "utf8-text", "revision": "1"}, + "sha256": sha256(data).hexdigest(), + } + prepared["prepared_id"] = preparation.prepared_id(prepared) + facts["prepared_ref"]["prepared_id"] = prepared["prepared_id"] + frozen_bytes = preparation.encode(prepared) + facts["prepared_ref"]["artifact"].update( + sha256=sha256(frozen_bytes).hexdigest(), size_bytes=len(frozen_bytes), + ) + projector = proofs.ProofProjector(prepared, protocol) + projector.project("finalizing", facts, candidate_bytes=data, report_bytes=encode(report())) + facts["candidate"]["candidate_id"] = "foreign-candidate" + with pytest.raises(proofs.ProofError) as caught: + projector.project("finalizing", facts, candidate_bytes=data, report_bytes=encode(report())) + assert caught.value.code == "IdentityMismatch"