From a7f70f605c115db8c718f46ee638fd72ae0b4425 Mon Sep 17 00:00:00 2001 From: Zeng Chuang Date: Tue, 24 Nov 2026 17:43:59 +0800 Subject: [PATCH 1/2] feat(harness): bind generated candidates to fixed evaluation attempts Agent-assisted-by: Codex (author/integrator) Signed-off-by: zengchuang --- docs/apps-module-migrations.json | 4 +- docs/contracts/generation-bounds.md | 10 +- docs/contracts/generation-lineage.md | 90 +++ docs/operations.md | 1 + src/inferrsi/harness/execution_service.py | 15 +- src/inferrsi/harness/generation_lineage.py | 182 ++++++ tests/test_harness_execute.py | 1 + tests/test_harness_generation_lineage.py | 621 +++++++++++++++++++++ 8 files changed, 913 insertions(+), 11 deletions(-) create mode 100644 docs/contracts/generation-lineage.md create mode 100644 src/inferrsi/harness/generation_lineage.py create mode 100644 tests/test_harness_generation_lineage.py diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 2c82fca8a..68a6c381d 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -43,6 +43,7 @@ "tests/test_benchmark_cpu_smoke.py", "tests/test_benchmark_preparation.py", "tests/test_harness_entry_verification.py", + "tests/test_harness_generation_lineage.py", "tests/test_result_delivery.py" ] }, @@ -71,7 +72,8 @@ "tests/test_apps_module_migrations.py", "tests/test_benchmark_assessment.py", "tests/test_benchmark_cpu_smoke.py", - "tests/test_harness_entry_verification.py" + "tests/test_harness_entry_verification.py", + "tests/test_harness_generation_lineage.py" ] }, { diff --git a/docs/contracts/generation-bounds.md b/docs/contracts/generation-bounds.md index 403282d40..b513e3284 100644 --- a/docs/contracts/generation-bounds.md +++ b/docs/contracts/generation-bounds.md @@ -43,8 +43,8 @@ It introduces no deadline or budget policy for existing ordinary commands. ## Remaining capability -This retention slice does not enable generation-lineage evaluation. The current -generation-chaining refusal remains in place. Future admission must separately -verify the fixed successful generation, retained candidate association, original -deadline and budget policy. Missing historical bounds cannot establish those -facts and must fail closed for that future operation. +Retention alone does not authorize generation-lineage evaluation. The separate +[same-Store CPU profile](generation-lineage.md) checks the fixed successful +generation, retained candidate association, original deadline and budget policy +before registration. Missing historical bounds cannot establish those facts and +remain a refusal for that operation. Ordinary execution and replay stay separate. diff --git a/docs/contracts/generation-lineage.md b/docs/contracts/generation-lineage.md new file mode 100644 index 000000000..ee4730b9e --- /dev/null +++ b/docs/contracts/generation-lineage.md @@ -0,0 +1,90 @@ +# Same-Store generation lineage for CPU evaluation + +The restricted profile in [#584](https://github.com/InferMatrixLab/InferRSI/issues/584) +admits an evaluation of an already generated candidate through the existing +`Harness.execute` port. The host still saves the complete request and allocates +a distinct evaluation attempt. Apps forwards the original `generation_record_ref`; +H owns authorization, input capture, execution and replay. No public DTO or +record field is added. + +This profile requires the same authorized RunStore and the existing trusted +local CPU evaluation target with its module root. It does not add scheduling, +automatic retries, another backend or budget-policy support. + +## Admission before registration + +After static request checks, H consults any existing registration first. Only +a fresh request reaches fixed preparation, target and lineage validation. +Public `execution_service.validate` has no Store authority and continues to +refuse non-null lineage. Use `Harness.execute` for Store-backed admission. + +H reads the generation's specified record version through its own Store and +compares the complete RecordRef. It requires the same run and owner, a successful +finished ordinary generation, known side effects and a sealed +[original-bounds snapshot](generation-bounds.md). Historical generations without +that snapshot remain usable by their original ordinary/replay paths, but cannot +authorize a new lineage evaluation. There is no backfill or `current` fallback. + +| Fixed source | Association checked by H | +| --- | --- | +| Original bounds and generation record | Original attempt/run/owner and request digest agree. The immutable generation-plan descriptor already binds registration to that original digest. | +| Original plan Ref | Read the pre-sealed H generation-plan bytes from the fixed internal slot and verify their size, SHA and v1 shape. This is not the worker's output manifest. | +| Generation record's `generation_plan` BoundInput | Exactly one verified file capture for the generation attempt, with the original expected/actual plan SHA and equal retained bytes. Its captured object locator may differ from the original plan locator. | +| Plan `output_contract.candidate_role` | Exactly one available retained artifact with that role, the generation attempt, an observed step and the declared format schema. | +| Evaluation candidate input | Its artifact namespace, complete `source_ref`, source locator and expected SHA match that original artifact; the supported snapshot is `file-v1`. | + +H independently verifies retained plan/candidate bytes before registering the +evaluation. It does not parse the worker's manifest, grade the candidate, or +authenticate worker-reported CandidateDescriptor metadata. Apps' existing +candidate collection owns that parsing contract. The H guarantee here is the +original retained artifact/byte association and the fixed execution facts. + +## Original limits and capture + +The original deadline must not already be expired. The evaluation deadline may +be earlier or equal, never later. Comparison preserves the Timestamp contract's +nanosecond precision and does not rewrite either timestamp or request identity. +The budget scope and policy must be identical to the original snapshot; normal +local target budget admission still applies. The full original budget remains +retained separately from admission, reservations and actual usage. + +At actual input capture, the authorized candidate is opened again through H's +own Store. Unrelated inputs retain their configured reader. Capture independently +checks the actual bytes against the frozen input identity. A source changed +after validation produces the existing committed `started=false` binding refusal +before any worker runs; it is not relabeled as a pre-registration failure. + +Manual-candidate evaluation (`generation_record_ref=null`) keeps its existing +path. Generation and evaluation records remain distinct, and the evaluation +record keeps the original generation Ref. Execution exit status remains a fact, +not a Benchmark claim verdict. + +## Errors and replay + +Fresh lineage refusals occur at `validate`, before a claim or worker start: + +| Condition | Existing code | +| --- | --- | +| Malformed requested RecordRef | `InvalidExecutionSpec` | +| Foreign Store authority, unsealed/unsuccessful generation, missing historical bounds or expired original deadline | `UnsupportedOperation` | +| Unknown fixed record/version | `RecordNotFound` | +| Full Ref, run/owner, plan/candidate association, deadline or budget identity mismatch | `IdentityMismatch` | +| Damaged committed record | `RecordIntegrityError` | +| Missing/inaccessible retained source | `ArtifactUnavailable` | +| Damaged bytes or malformed retained metadata | `ArtifactIntegrityError` | +| Unsupported generation-plan major version or candidate snapshot rule | `UnsupportedSchema` / `UnsupportedRuleVersion` | + +The existing registered-request table takes precedence. Reusing a registered +generation attempt ID with the evaluation's different digest therefore returns +`RequestConflict` at `claim`, as explicitly accepted in +[7087203358](https://github.com/InferMatrixLab/InferRSI/issues/584#issuecomment-7087203358). +It does not become a fresh lineage refusal. An identical-digest completed replay +returns its original RecordRef before reading sources or binding a target, even +after sources disappear, the target retires or time expires. Live/unknown +registrations retain `AttemptInProgress` / `RecoveryRequired`; no new attempt +or implicit rerun is introduced. + +Apps output publication remains separate from H commit: publication failure +preserves the already committed evaluation Ref and its generation association. +Replaying the saved request can publish that original result later. No execution +or evaluation verdict is manufactured to fill an unavailable artifact. diff --git a/docs/operations.md b/docs/operations.md index 7719e97b0..a35047b4c 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -56,6 +56,7 @@ Effect classes used below: | Seal a generation request before execution | Python `inferrsi.harness.generation.prepare_generation`; [original bounds](contracts/generation-bounds.md) | Local record-writing | Seals approved context, plan and original deadline/budget metadata; allocates no attempt, starts no process and does not enable generation-lineage evaluation | | Verify a frozen preparation binding before registration | Python `inferrsi.harness.prepared_binding.verify` / `read` / `project` | Read-only / pure projection | Fixed ArtifactRef and read-only stream capability; no registration, entry resolution or execution; [binding contract](contracts/harness-prepared-binding.md) | | Verify and execute one frozen source evaluation entry | Python `inferrsi.harness.api.Harness.execute` with trusted `LocalCpuTarget(module_root=...)` | Experiment-executing / record-writing | Fixed preparation and expected code digest; actual source captured after registration; T37 refusals start no worker; [source-entry contract](contracts/harness-entry-verification.md) | +| Evaluate one retained generated candidate | Python `inferrsi.harness.api.Harness.execute` with `generation_record_ref`; [same-Store lineage](contracts/generation-lineage.md) | Experiment-executing / record-writing | Same authorized Store, sealed successful generation and exact retained candidate; distinct attempt, original deadline/budget scope and policy; registered replay precedes fresh source reads; no worker-manifest parsing or automatic rerun | | Capture and seal evaluation proofs | Python `Harness(..., evidence_capture=...)`; [capture contract](contracts/harness-evidence-capture.md) | Read-only capture callback / record-writing | H authorizes attempt bytes, seals actual provenance and retains drafts before one commit; ordinary mode and replay never call the observer | | Assemble evidence capture by role | Python `apps.api.EvidenceCapture`; [host adapter](contracts/apps-evidence-capture.md) | Read-only byte assembly / injected pure projection | Reads only H-authorized candidate/report refs; no grading, producer sealing or record/archive writes; reentry is short-circuited by H | | Replay the same saved execution request | Python `inferrsi.harness.api.Harness.execute` | Existing-state query / fixed record-reading | Same attempt and canonical digest; existing state short-circuits fresh binding/execution; [replay and original limits](contracts/harness-evaluation-replay.md) | diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index 73c9c4a03..55af0919f 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -15,6 +15,7 @@ from inferrsi.contracts import json_v1 from inferrsi.harness import ( entry_code, + generation_lineage, input_binding, local_process, prepared_binding, @@ -27,7 +28,8 @@ # The ordinary CPU path preserves V05 null mode. Evaluation requires an explicit trusted # module root, a fixed preparation binding and an actual source-entry snapshot before start. -# Registered requests replay the original facts and limits. Generation chaining is a later slice. +# Registered requests replay their original facts and limits. +# Fresh lineage admission additionally requires the same authorized RunStore. ATTEMPT_FIELDS = ( "request_id", "run_id", "attempt_id", "owner", "target_request", "deadline_utc", "resources", "budget", "retry_of", "retry_reason", @@ -447,7 +449,7 @@ def _ordinary_path_errors(spec: Mapping) -> list[str]: return errors -def _validate_fresh(spec, target, artifact_reader, evaluation): +def _validate_fresh(spec, target, artifact_reader, evaluation, *, store=None): """Validate workspace, command, fixed bytes and target support for a fresh request.""" errors = [ f"steps[{step_index}].args[{arg_index}]: contains a NUL character" @@ -469,8 +471,8 @@ def _validate_fresh(spec, target, artifact_reader, evaluation): unsupported = [] if evaluation and target.module_root is None: unsupported.append("this target has no configured evaluation module root") - if spec["generation_record_ref"] is not None: - unsupported.append("generation chaining is not implemented in this slice") + if spec["generation_record_ref"] is not None and (store is None or not evaluation): + unsupported.append("generation lineage requires evaluation and its authorized Store") request = spec["target_request"] if (request["target_id"], request["config_revision"]) != ( target.target_id, target.config_revision @@ -480,6 +482,9 @@ def _validate_fresh(spec, target, artifact_reader, evaluation): raise PublicError( "UnsupportedOperation", stage="validate", message="; ".join(unsupported) ) + if spec["generation_record_ref"] is not None: + return generation_lineage.authorize(store, spec, artifact_reader) + return artifact_reader def validate(spec: object, target: LocalCpuTarget, *, artifact_reader=None) -> None: @@ -1180,7 +1185,7 @@ def execute( existing = store._reenter_if_registered(spec["attempt_id"], digest) if existing is not None: return run_store.flatten(existing, run_store.utc_now()) - _validate_fresh(spec, target, artifact_reader, evaluation) + artifact_reader = _validate_fresh(spec, target, artifact_reader, evaluation, store=store) # Another caller may have registered while the fixed preparation was read. claimed = store.claim(attempt, digest) if isinstance(claimed, run_store.CommittedRecord): diff --git a/src/inferrsi/harness/generation_lineage.py b/src/inferrsi/harness/generation_lineage.py new file mode 100644 index 000000000..478a48528 --- /dev/null +++ b/src/inferrsi/harness/generation_lineage.py @@ -0,0 +1,182 @@ +"""Same-Store generation-to-evaluation admission over H's sealed input facts.""" + +from copy import deepcopy +from decimal import Decimal +from hashlib import sha256 + +from inferrsi.contracts import json_v1 +from inferrsi.harness import prepared_binding, run_store +from inferrsi.harness.errors import PublicError + +_PLAN_FIELDS = {"schema_version", "provider", "output_contract", "context_refs", "attempt_id"} + + +def _require(condition, message, code="IdentityMismatch"): + if not condition: + raise PublicError(code, stage="validate", started=False, message=message) + + +def _read(store, ref): + _require( + run_store._has_fields(ref, {"location", "sha256", "size_bytes", "media_type"}) + and prepared_binding._is_path(ref["location"]) + and prepared_binding._is_sha256(ref["sha256"]) + and type(ref["size_bytes"]) is int and 0 <= ref["size_bytes"] <= json_v1.MAX_SAFE_INTEGER + and isinstance(ref["media_type"], str) and bool(ref["media_type"]), + "invalid retained generation ArtifactRef", "ArtifactIntegrityError", + ) + chunks, total, digest = [], 0, sha256() + with store.open(deepcopy(ref)) as stream: + while total <= ref["size_bytes"]: + chunk = stream.read(min(1024 * 1024, ref["size_bytes"] + 1 - total)) + if not chunk: + break + _require(isinstance(chunk, bytes), "retained source is not bytes", + "ArtifactIntegrityError") + chunks.append(chunk) + total += len(chunk) + digest.update(chunk) + _require(total == ref["size_bytes"] and digest.hexdigest() == ref["sha256"], + "retained generation bytes differ from their Ref", "ArtifactIntegrityError") + return b"".join(chunks) + + +def _time(value): + _require(run_store._is_timestamp(value), "invalid original timestamp", "ArtifactIntegrityError") + # Timestamp permits nanoseconds; datetime would truncate a sub-microsecond extension. + fraction = value[20:-1] if value[19] == "." else "0" + return value[:19], Decimal("0." + fraction) + + +def _source(store, spec): + ref = spec["generation_record_ref"] + _require(ref["artifact"]["location"] == run_store.record_location( + store.namespace, ref["attempt_id"], ref["record_version"], + ), "generation must belong to this authorized Store", "UnsupportedOperation") + _require(ref["attempt_id"] != spec["attempt_id"], "generation and evaluation reuse an attempt") + committed = store.committed(ref["attempt_id"], ref["record_version"]) + _require(committed.record_ref == ref, "generation RecordRef differs from the fixed record") + record = committed.payload + _require(all(record[key] == spec[key] for key in ("run_id", "owner")), + "generation belongs to another run or owner") + _require( + record["phase"] == "finished" and record["process_outcome"] == "exited" + and type(record["exit_code"]) is int and record["exit_code"] == 0 + and record["side_effect_unknown"] is False + and all(record[key] is None for key in ( + "candidate", "prepared_ref", "protocol_digest", "operation", "validation_scope", + "generation_record_ref", + )), "lineage requires a successful ordinary generation", "UnsupportedOperation", + ) + bounds = store._read_generation_bounds(ref["attempt_id"]) + _require(bounds is not None, "generation has no original-bounds snapshot", + "UnsupportedOperation") + _require(bounds["request_digest"] == record["request_digest"] + and all(bounds[key] == record[key] for key in ("attempt_id", "run_id", "owner")), + "generation differs from its original sealed binding") + from inferrsi.harness.execution_service import _request_errors + + _require(not _request_errors({**spec, "budget": bounds["budget"]}), + "invalid original budget snapshot", "ArtifactIntegrityError") + _require(_time(bounds["deadline_utc"]) > _time(run_store.utc_now()), + "original generation deadline has expired", "UnsupportedOperation") + _require(_time(spec["deadline_utc"]) <= _time(bounds["deadline_utc"]), + "evaluation extends the original generation deadline") + _require(all(spec["budget"][key] == bounds["budget"][key] + for key in ("scope_id", "policy_ref")), + "evaluation changes the original budget scope or policy") + + data = _read(store, bounds["generation_plan"]) + manifest = json_v1.decode(data) + _require(run_store._has_fields(manifest, _PLAN_FIELDS), + "invalid pre-sealed generation plan", "ArtifactIntegrityError") + _require(type(manifest["schema_version"]) is int and manifest["schema_version"] == 1, + "unsupported generation plan version", "UnsupportedSchema") + _require(manifest["attempt_id"] == record["attempt_id"], + "generation plan names another attempt") + plans = [item for item in record["bound_inputs"] if item["role"] == "generation_plan"] + _require(len(plans) == 1, "generation must have one captured pre-sealed plan") + plan = plans[0] + _require(plan["attempt_id"] == record["attempt_id"] + and plan["snapshot_format"] == "file-v1" and plan["identity_status"] == "matched" + and plan["expected_sha256"] == plan["actual_sha256"] + == bounds["generation_plan"]["sha256"] + and plan["retained_ref"] is not None, + "generation plan capture differs from its original binding") + _require(_read(store, plan["retained_ref"]) == data, + "captured generation plan differs from its sealed bytes", "ArtifactIntegrityError") + contract = manifest["output_contract"] + _require(isinstance(contract, dict) and run_store._is_id(contract.get("candidate_role")) + and prepared_binding._is_definition(contract.get("format_schema")), + "generation plan has no supported candidate role", "ArtifactIntegrityError") + outputs = [item for item in record["artifacts"] + if item["role"] == contract["candidate_role"]] + _require(len(outputs) == 1, "generation candidate role is absent or ambiguous") + output = outputs[0] + _require(output["attempt_id"] == record["attempt_id"] + and output["step_id"] in {step["step_id"] for step in record["steps"]} + and output["format_schema"] == contract["format_schema"], + "generation candidate producer or format differs") + _require(output["status"] == "available" and output["artifact"] is not None, + "generation candidate is not retained", "ArtifactUnavailable") + candidate = output["artifact"] + inputs = [item for item in spec["inputs"] if item["role"] == spec["candidate"]["input_role"]] + _require(len(inputs) == 1, "evaluation needs one candidate input") + item = inputs[0] + _require(item["source_namespace"] == "artifact" and item["source_ref"] == candidate + and item["source"] == candidate["location"] + and item["expected_sha256"] == candidate["sha256"], + "evaluation does not use the original retained candidate") + _require(item["snapshot_format"] == "file-v1", "unsupported generated candidate snapshot", + "UnsupportedRuleVersion") + _read(store, candidate) + return deepcopy(candidate) + + +class _CaptureReader: + """Read the authorized candidate again through H; delegate unrelated artifacts.""" + + def __init__(self, store, delegate, candidate): + self._store, self._delegate, self._candidate = store, delegate, deepcopy(candidate) + + def open(self, ref): + if ref == self._candidate: + return self._store.open(deepcopy(ref)) + if self._delegate is None: + raise PublicError("ArtifactUnavailable", stage="bind", started=False, + message="no reader for an unrelated input artifact") + return self._delegate.open(ref) + + +def authorize(store, spec, reader): + """Authorize only a fresh request, then return its read-only capture router.""" + try: + ref = spec["generation_record_ref"] + _require(run_store._has_fields(ref, {"attempt_id", "record_version", "artifact"}) + and run_store._is_id(ref["attempt_id"]) + and type(ref["record_version"]) is int + and 1 <= ref["record_version"] <= json_v1.MAX_SAFE_INTEGER + and run_store._has_fields(ref["artifact"], { + "location", "sha256", "size_bytes", "media_type", + }) + and prepared_binding._is_path(ref["artifact"]["location"]) + and prepared_binding._is_sha256(ref["artifact"]["sha256"]) + and type(ref["artifact"]["size_bytes"]) is int + and 0 <= ref["artifact"]["size_bytes"] <= json_v1.MAX_SAFE_INTEGER + and ref["artifact"]["media_type"] == "application/json", + "generation_record_ref must be a fixed RecordRef", "InvalidExecutionSpec") + return _CaptureReader(store, reader, _source(store, spec)) + except PublicError as exc: + raise PublicError( + exc.code, stage="validate", attempt_id=spec["attempt_id"], started=False, + retained_refs=exc.retained_refs, + field_errors=exc.field_errors, message=exc.message, + ) from exc + except OSError as exc: + raise PublicError("ArtifactUnavailable", stage="validate", started=False, + attempt_id=spec["attempt_id"], + message="generation lineage bytes are not accessible") from exc + except (AttributeError, KeyError, TypeError, ValueError, RecursionError) as exc: + raise PublicError("ArtifactIntegrityError", stage="validate", started=False, + attempt_id=spec["attempt_id"], + message="invalid retained generation lineage metadata") from exc diff --git a/tests/test_harness_execute.py b/tests/test_harness_execute.py index 94b26d45c..0473d6452 100644 --- a/tests/test_harness_execute.py +++ b/tests/test_harness_execute.py @@ -43,6 +43,7 @@ "inferrsi.harness.prepared_binding", "inferrsi.harness.entry_code", "inferrsi.harness.evidence_capture", + "inferrsi.harness.generation_lineage", "inferrsi.harness.atomic_json", "inferrsi.harness.run_store", "inferrsi.harness.errors", "inferrsi.harness.execution_spec", "inferrsi.contracts.json_v1", diff --git a/tests/test_harness_generation_lineage.py b/tests/test_harness_generation_lineage.py new file mode 100644 index 000000000..7f95faf55 --- /dev/null +++ b/tests/test_harness_generation_lineage.py @@ -0,0 +1,621 @@ +"""Carry a genuinely generated, retained candidate into the production CPU task.""" + +import sqlite3 +import subprocess +import sys +import threading +from copy import deepcopy +from dataclasses import replace +from hashlib import sha256 +from pathlib import Path + +import pytest + +from inferrsi.apps import api +from inferrsi.apps.storage import archive +from inferrsi.apps.storage.artifact_reader import ArtifactReader +from inferrsi.benchmark import assessment, cpu_smoke, preparation, proofs +from inferrsi.benchmark.workers import fixture_worker as worker +from inferrsi.contracts.json_v1 import decode, encode +from inferrsi.harness import execution_service, generation_lineage, run_store +from inferrsi.harness.api import Harness +from inferrsi.harness.errors import PublicError +from inferrsi.harness.generation import prepare_generation +from tests.test_apps_generation_plan import _fixed_input +from tests.test_apps_generation_plan import generation as generation +from tests.test_harness_generation_seal import cpu_generation as cpu_generation + + +@pytest.fixture +def lineage( + cpu_generation, tmp_path, request, monkeypatch, +): + store, target, generation_harness, draft, inputs = cpu_generation + variant = getattr(request, "param", None) + if variant in ("failed", "missing-candidate", "missing-role"): + original_plan = inputs["candidate_provider"].plan_generation + + def changed_plan(context, attempt): + value = original_plan(context, attempt) + if variant == "failed": + value["spec"]["steps"][0]["args"] = ["-c", "raise SystemExit(7)"] + elif variant == "missing-candidate": + value["spec"]["steps"][0]["args"] = [ + "-c", "from pathlib import Path; Path('output').mkdir(); " + "Path('output/manifest.json').write_bytes(b'{}')", + ] + else: + value["manifest"]["output_contract"]["candidate_role"] = "absent-candidate" + return value + + monkeypatch.setattr(inputs["candidate_provider"], "plan_generation", changed_plan) + with monkeypatch.context() as patch: + if variant == "legacy": + original_seal = store._seal_generation_input + + def old_writer(*args, **kwargs): + # A real pre-bounds writer calls the unchanged seal without this new option. + kwargs.pop("original_bounds", None) + return original_seal(*args, **kwargs) + + patch.setattr(store, "_seal_generation_input", old_writer) + generation_spec = prepare_generation(store, target, **inputs) + with monkeypatch.context() as patch: + if variant in ("history", "ambiguous"): + original_commit = run_store.Claim.commit + + def controlled_commit(claim, payload, artifacts=()): + # Controlled record metadata/history; the generator and capture remain real. + artifacts = tuple(artifacts) + if variant == "history": + original_commit(claim, {**payload, "phase": "finalizing"}, artifacts) + payload = {**payload, "record_version": claim.next_record_version} + else: + payload = deepcopy(payload) + candidate = next(item for item in payload["artifacts"] + if item["role"] == "candidate") + payload["artifacts"].append(deepcopy(candidate)) + return original_commit(claim, payload, artifacts) + + patch.setattr(run_store.Claim, "commit", controlled_commit) + generated = generation_harness.execute(generation_spec) + assert generated["exit_code"] == (7 if variant == "failed" else 0) + generation_ref = generated["record_ref"] + generation_before = store.committed(generated["attempt_id"]) + context_ref = store.read_delivered_context(generated["attempt_id"])["artifact"] + with store.open(context_ref) as stream: + context_bytes = stream.read() + assert context_bytes == draft.content + if variant in ("failed", "missing-candidate", "missing-role", "ambiguous"): + # Explicitly declared negative input; no successful collection or task result is claimed. + source = next((item["artifact"] for item in generated["artifacts"] + if item["role"] == "candidate" and item["status"] == "available"), + context_ref) + proposal = { + "candidate": {"candidate_id": "negative-declaration", "kind": "text", + "input_role": "candidate", "parent_id": None, "parent_digest": None, + "context_refs": [context_ref]}, + "inputs": [_fixed_input("candidate", source)], "generation_record_ref": generation_ref, + } + else: + proposal = inputs["candidate_provider"].collect_candidate(generated, artifacts=store) + assert proposal["generation_record_ref"] == generation_ref + + directory = tmp_path / "archive" + directory.mkdir() + config = { + "schema_version": 1, "archive_namespace": "apps", "harness_namespace": "generation", + "mounts": [ + {"kind": "directory", "namespace": "apps", "prefix": "archives/local", + "root": str(directory)}, + {"kind": "harness_sqlite", "namespace": "generation", "prefix": "stores/generation", + "root": str(store.root)}, + ], + } + service = cpu_smoke.prepare_service(control_domain=execution_service._CONTROL_DOMAIN) + prepared_output = api.prepare( + {"schema_version": 1, "request": cpu_smoke.default_request()}, + workspace=tmp_path, storage_config=config, prepare_benchmark=service.prepare, + encode_prepared=preparation.encode, validate_prepared=preparation.validate_prepared, + output_id="generated-prepare", + ) + assert prepared_output.result["exit_code"] == 0 + prepared_ref = prepared_output.result["prepared_ref"] + prepared = archive.read_prepared(config, prepared_ref) + reader = ArtifactReader(config) + with reader.open(prepared["protocol"]) as stream: + projector = proofs.ProofProjector(prepared, stream.read()) + evaluation_target = replace(target, module_root=Path(worker.__file__).parent) + harness = Harness( + store, evaluation_target, artifact_reader=reader, + evidence_capture=api.EvidenceCapture( + projector.project, candidate_role="candidate", report_role="grader", + ), + ) + attempt = harness.allocate(**{key: inputs["attempt"][key] for key in ( + "run_id", "owner", "target_request", "deadline_utc", "resources", "budget", + "retry_of", "retry_reason", + )}) + assert attempt["attempt_id"] != generated["attempt_id"] + assert attempt["deadline_utc"] == inputs["attempt"]["deadline_utc"] + assert attempt["budget"] == inputs["attempt"]["budget"] + port = api.EvaluationPort( + storage_config=config, output_root_for=lambda attempt_id: "evaluation/" + attempt_id, + assess_benchmark=assessment.assess, encode_assessment=assessment.encode, + validate_assessment=assessment.validate_assessment, + ) + spec = port.execution_for(prepared_ref, proposal, attempt, scope="p1") + assert spec["generation_record_ref"] == generation_ref + return { + "store": store, "target": target, "harness": harness, "inputs": inputs, + "generated": generated, "generation_spec": generation_spec, "proposal": proposal, + "config": config, "reader": reader, "port": port, "spec": spec, + "evaluation_target": evaluation_target, + "generation_before": generation_before, "context_ref": context_ref, + "context_bytes": context_bytes, + } + + +def test_generated_candidate_uses_a_separate_production_evaluation_attempt(lineage): + store, harness, spec, port = (lineage[key] for key in ("store", "harness", "spec", "port")) + generated = lineage["generated"] + generation_ref = generated["record_ref"] + evaluated = harness.execute(spec) + assert evaluated["exit_code"] == 0 + assert evaluated["generation_record_ref"] == generation_ref + assert evaluated["attempt_id"] == spec["attempt_id"] + summary = port.assess(evaluated) + assert summary["attempt_id"] == spec["attempt_id"] + # The generator emits UTF-8 context, deliberately not this task's correct sum. + assert [(claim["claim_id"], claim["verdict"]) for claim in summary["claims"]] == [ + ("F", "PASS"), ("C", "FAIL"), ("M", "PASS"), + ] + decision = archive.read_assessment(lineage["config"], summary["assessment_ref"]) + assert decision["record_ref"] == evaluated["record_ref"] + assert decision["record_ref"] != generation_ref + assert decision["candidate"] == lineage["proposal"]["candidate"] + view = api.read_attempt_view( + evaluated["record_ref"], storage_config=lineage["config"], + assessment_ref=summary["assessment_ref"], include_trace=True, + ) + assert view["execution"]["exit_code"] == 0 + assert view["assessment"]["claims"][1]["verdict"] == "FAIL" + generation_after = store.committed(generated["attempt_id"]) + assert generation_after.record_ref == lineage["generation_before"].record_ref + assert generation_after.payload_bytes == lineage["generation_before"].payload_bytes + with store.open(lineage["context_ref"]) as stream: + assert stream.read() == lineage["context_bytes"] + + +def _forbid_claim(monkeypatch, store): + def forbidden(*args, **kwargs): + pytest.fail("fresh lineage refusal registered an attempt") + monkeypatch.setattr(store, "claim", forbidden) + + +@pytest.mark.parametrize("change,code", [ + ("owner", "IdentityMismatch"), ("run", "IdentityMismatch"), + ("foreign-store", "UnsupportedOperation"), ("missing-record", "RecordNotFound"), + ("missing-version", "RecordNotFound"), ("ref-checksum", "IdentityMismatch"), + ("ref-size", "IdentityMismatch"), ("budget-scope", "IdentityMismatch"), + ("unregistered-self", "IdentityMismatch"), + ("budget-policy", "IdentityMismatch"), ("later-deadline", "IdentityMismatch"), + ("later-fraction", "IdentityMismatch"), + ("source-alias", "IdentityMismatch"), ("source-path", "IdentityMismatch"), + ("unverified-input", "InvalidExecutionSpec"), ("invalid-ref", "InvalidExecutionSpec"), + ("boolean-version", "InvalidExecutionSpec"), ("zero-version", "InvalidExecutionSpec"), +]) +def test_fresh_lineage_refusals_register_nothing(lineage, monkeypatch, change, code): + store = lineage["store"] + spec = deepcopy(lineage["spec"]) + ref = spec["generation_record_ref"] + candidate = next(item for item in spec["inputs"] + if item["role"] == spec["candidate"]["input_role"]) + if change == "owner": + spec["owner"] = "different-owner" + elif change == "run": + spec["run_id"] = "different-run" + elif change == "foreign-store": + ref["artifact"]["location"] = run_store.record_location( + "other", ref["attempt_id"], ref["record_version"], + ) + elif change in ("missing-record", "missing-version"): + if change == "missing-record": + ref["attempt_id"] = "absent-generation" + else: + ref["record_version"] += 1 + ref["artifact"]["location"] = run_store.record_location( + store.namespace, ref["attempt_id"], ref["record_version"], + ) + elif change == "ref-checksum": + ref["artifact"]["sha256"] = "0" * 64 + elif change == "ref-size": + ref["artifact"]["size_bytes"] += 1 + elif change == "unregistered-self": + ref["attempt_id"] = spec["attempt_id"] + ref["artifact"]["location"] = run_store.record_location( + store.namespace, ref["attempt_id"], ref["record_version"], + ) + elif change == "budget-scope": + spec["budget"]["scope_id"] = "different-scope" + elif change == "budget-policy": + spec["budget"]["policy_ref"] = {"name": "different-policy", "revision": "1"} + elif change == "later-deadline": + spec["deadline_utc"] = "2099-01-02T00:00:00Z" + elif change == "later-fraction": + spec["deadline_utc"] = "2099-01-01T00:00:00.0000001Z" + elif change == "source-alias": + alias = lineage["context_ref"] + assert alias["sha256"] == candidate["source_ref"]["sha256"] + assert alias != candidate["source_ref"] + candidate.update(source=alias["location"], source_ref=deepcopy(alias)) + elif change == "source-path": + candidate.update(source="candidate.txt", source_namespace="controller", source_ref=None) + elif change == "unverified-input": + candidate["expected_sha256"] = None + elif change == "invalid-ref": + spec["generation_record_ref"] = [] + else: + ref["record_version"] = True if change == "boolean-version" else 0 + _forbid_claim(monkeypatch, store) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(spec) + expected_started = None if change == "unverified-input" else False + assert (caught.value.code, caught.value.stage, caught.value.started) == ( + code, "validate", expected_started, + ) + with pytest.raises(PublicError, match="NoCommittedRecord"): + store.committed(spec["attempt_id"]) + + +@pytest.mark.parametrize("deadline", [ + "2098-01-01T00:00:00Z", "2099-01-01T00:00:00.000000000Z", +]) +def test_no_later_evaluation_deadline_keeps_original_bounds(lineage, deadline): + store, spec = lineage["store"], deepcopy(lineage["spec"]) + original = store._read_generation_bounds(lineage["generated"]["attempt_id"]) + spec["deadline_utc"] = deadline + result = lineage["harness"].execute(spec) + assert result["exit_code"] == 0 + assert result["generation_record_ref"] == lineage["generated"]["record_ref"] + assert store._read_generation_bounds(lineage["generated"]["attempt_id"]) == original + + +def test_expired_original_refuses_before_registration(lineage, monkeypatch): + _forbid_claim(monkeypatch, lineage["store"]) + monkeypatch.setattr(run_store, "utc_now", lambda: "2100-01-01T00:00:00Z") + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(lineage["spec"]) + assert (caught.value.code, caught.value.stage) == ("UnsupportedOperation", "validate") + + +def test_public_validation_without_store_cannot_authorize_lineage(lineage): + with pytest.raises(PublicError) as caught: + execution_service.validate(lineage["spec"], lineage["evaluation_target"], + artifact_reader=lineage["reader"]) + assert (caught.value.code, caught.value.stage) == ("UnsupportedOperation", "validate") + + +def test_registered_generation_attempt_reuse_keeps_conflict_precedence(lineage, monkeypatch): + spec = deepcopy(lineage["spec"]) + spec["attempt_id"] = spec["request_id"] = lineage["generated"]["attempt_id"] + _forbid_claim(monkeypatch, lineage["store"]) + monkeypatch.setattr(generation_lineage, "authorize", + lambda *args: pytest.fail("registered conflict read lineage")) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(spec) + assert (caught.value.code, caught.value.stage) == ("RequestConflict", "claim") + + +@pytest.mark.parametrize("lineage,code", [ + ("legacy", "UnsupportedOperation"), ("failed", "UnsupportedOperation"), + ("missing-candidate", "ArtifactUnavailable"), ("missing-role", "IdentityMismatch"), + ("ambiguous", "IdentityMismatch"), +], indirect=["lineage"]) +def test_real_generation_boundaries_refuse_before_claim(lineage, monkeypatch, code): + store, generated = lineage["store"], lineage["generated"] + before = store.committed(generated["attempt_id"]) + _forbid_claim(monkeypatch, store) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(lineage["spec"]) + assert (caught.value.code, caught.value.stage, caught.value.started) == ( + code, "validate", False, + ) + assert store.committed(generated["attempt_id"]).payload_bytes == before.payload_bytes + + +def _retained_path(lineage, family): + payload = lineage["generation_before"].payload + if family == "candidate": + ref = next(item["artifact"] for item in payload["artifacts"] + if item["role"] == "candidate") + else: + ref = next(item["retained_ref"] for item in payload["bound_inputs"] + if item["role"] == "generation_plan") + store = lineage["store"] + relative = ref["location"].removeprefix(f"stores/{store.namespace}/") + path = (store.root / relative).resolve() + assert path.is_relative_to((store.root / "objects").resolve()) + return path + + +@pytest.mark.parametrize("family", ["candidate", "plan-copy"]) +@pytest.mark.parametrize("damage,code", [ + ("missing", "ArtifactUnavailable"), ("corrupt", "ArtifactIntegrityError"), +]) +def test_retained_sources_are_verified_before_claim(lineage, monkeypatch, family, damage, code): + path = _retained_path(lineage, family) + if damage == "missing": + path.unlink() + else: + original = path.read_bytes() + assert original + path.write_bytes(bytes([original[0] ^ 1]) + original[1:]) + _forbid_claim(monkeypatch, lineage["store"]) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(lineage["spec"]) + assert (caught.value.code, caught.value.stage, caught.value.started) == ( + code, "validate", False, + ) + + +def test_candidate_changed_between_validation_and_capture_starts_no_worker(lineage, monkeypatch): + store = lineage["store"] + path = _retained_path(lineage, "candidate") + claim = store.claim + + def change_before_capture(attempt, digest): + value = claim(attempt, digest) + path.write_bytes(b"changed after admission") + return value + + monkeypatch.setattr(store, "claim", change_before_capture) + monkeypatch.setattr(execution_service, "_run_steps", + lambda *args: pytest.fail("damaged candidate started a worker")) + result = lineage["harness"].execute(lineage["spec"]) + assert result["started"] is False and result["process_outcome"] == "not_started" + assert result["generation_record_ref"] == lineage["generated"]["record_ref"] + assert any(item["role"] == "candidate" and "ArtifactIntegrityError" in item["reasons"] + for item in result["bound_inputs"]) + assert store.committed(result["attempt_id"]).record_ref == result["record_ref"] + monkeypatch.setattr(generation_lineage, "authorize", + lambda *args: pytest.fail("refusal replay read damaged lineage")) + assert lineage["harness"].execute(lineage["spec"])["record_ref"] == result["record_ref"] + + +def test_completed_replay_precedes_missing_sources_retired_target_and_expiry(lineage, monkeypatch): + store, spec = lineage["store"], lineage["spec"] + result = lineage["harness"].execute(spec) + for family in ("candidate", "plan-copy"): + _retained_path(lineage, family).unlink() + monkeypatch.setattr(run_store, "utc_now", lambda: "2100-01-01T00:00:00Z") + monkeypatch.setattr(generation_lineage, "authorize", + lambda *args: pytest.fail("completed replay revalidated lineage")) + _forbid_claim(monkeypatch, store) + retired = replace(lineage["evaluation_target"], target_id="retired", module_root=None) + replay = execution_service.execute(store, retired, spec) + assert replay["record_ref"] == result["record_ref"] + assert store.committed(spec["attempt_id"]).payload_bytes == store.committed( + spec["attempt_id"], result["record_ref"]["record_version"], + ).payload_bytes + + +def test_changed_registered_request_conflicts_before_any_fresh_read(lineage, monkeypatch): + spec = lineage["spec"] + result = lineage["harness"].execute(spec) + changed = deepcopy(spec) + changed["deadline_utc"] = "2099-01-02T00:00:00Z" + monkeypatch.setattr(generation_lineage, "authorize", + lambda *args: pytest.fail("conflict revalidated lineage")) + _forbid_claim(monkeypatch, lineage["store"]) + with pytest.raises(PublicError) as caught: + execution_service.execute(lineage["store"], lineage["evaluation_target"], changed) + assert (caught.value.code, caught.value.stage) == ("RequestConflict", "claim") + assert lineage["store"].committed(spec["attempt_id"]).record_ref == result["record_ref"] + + +@pytest.mark.parametrize("lineage", ["history"], indirect=True) +def test_nonterminal_fixed_ref_does_not_fall_forward_to_finished_current(lineage, monkeypatch): + store, generated = lineage["store"], lineage["generated"] + current = store.committed(generated["attempt_id"]) + older = store.committed(generated["attempt_id"], 1) + assert current.payload["phase"] == "finished" and current.record_ref["record_version"] == 2 + assert older.payload["phase"] == "finalizing" + spec = deepcopy(lineage["spec"]) + spec["generation_record_ref"] = older.record_ref + _forbid_claim(monkeypatch, store) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(spec) + assert (caught.value.code, caught.value.stage) == ("UnsupportedOperation", "validate") + assert store.committed(generated["attempt_id"]).record_ref == current.record_ref + assert store.committed(generated["attempt_id"], 1).payload_bytes == older.payload_bytes + + +def test_unsealed_ordinary_run_cannot_borrow_another_attempts_generation_plan(lineage, monkeypatch): + spec = deepcopy(lineage["generation_spec"]) + attempt = run_store.allocate_attempt(**{key: lineage["inputs"]["attempt"][key] for key in ( + "run_id", "owner", "target_request", "deadline_utc", "resources", "budget", + "retry_of", "retry_reason", + )}) + spec.update(attempt) + spec["output_root"] = "unsealed/" + attempt["attempt_id"] + generated = execution_service.execute( + lineage["store"], lineage["target"], spec, artifact_reader=lineage["store"], + ) + assert generated["exit_code"] == 0 + assert lineage["store"]._read_generation_bounds(generated["attempt_id"]) is None + evaluation = deepcopy(lineage["spec"]) + evaluation["generation_record_ref"] = generated["record_ref"] + _forbid_claim(monkeypatch, lineage["store"]) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(evaluation) + assert (caught.value.code, caught.value.stage) == ("UnsupportedOperation", "validate") + + +@pytest.mark.parametrize("fault,code", [ + ("record-bytes", "RecordIntegrityError"), ("bounds-bytes", "ArtifactIntegrityError"), + ("bounds-budget", "ArtifactIntegrityError"), +]) +def test_damaged_store_metadata_is_not_relabelled_as_foreign(lineage, monkeypatch, fault, code): + store = lineage["store"] + with store._connection() as connection: + if fault == "record-bytes": + # Fault injection in this disposable Store only; production triggers stay unchanged. + connection.execute("DROP TRIGGER records_no_update") + connection.execute("UPDATE records SET payload = ?", (b"damaged",)) + else: + connection.execute("DROP TRIGGER generation_inputs_no_update") + data = connection.execute( + "SELECT data FROM generation_inputs WHERE role = 'original-bounds'", + ).fetchone()[0] + bounds = decode(data) + bounds["budget"]["declared_by"] = [] + altered = encode(bounds) + checksum = sha256(altered if fault == "bounds-budget" else data).hexdigest() + connection.execute( + "UPDATE generation_inputs SET data = ?, sha256 = ? WHERE role = 'original-bounds'", + (altered, checksum), + ) + _forbid_claim(monkeypatch, store) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(lineage["spec"]) + assert (caught.value.code, caught.value.stage, caught.value.started) == ( + code, "validate", False, + ) + + +def test_failed_commit_after_real_evaluation_never_replays_the_worker(lineage, monkeypatch): + store = lineage["store"] + supervise, processes = execution_service.local_process._supervise, [] + + def counted(*args, **kwargs): + result = supervise(*args, **kwargs) + processes.append(result["pid"]) + return result + + def broken_append(*args, **kwargs): + raise sqlite3.OperationalError("local persistence-failure control") + + monkeypatch.setattr(execution_service.local_process, "_supervise", counted) + monkeypatch.setattr(store, "_append", broken_append) + with pytest.raises(PublicError) as caught: + lineage["harness"].execute(lineage["spec"]) + assert caught.value.code == "ExecutionPersistenceError" and caught.value.started is True + assert caught.value.latest_record_ref is None and caught.value.partial_record.started is True + assert len(processes) == 1 and processes[0] is not None + _forbid_claim(monkeypatch, store) + monkeypatch.setattr(generation_lineage, "authorize", + lambda *args: pytest.fail("recovery read fresh lineage")) + with pytest.raises(PublicError) as recovery: + lineage["harness"].execute(lineage["spec"]) + assert recovery.value.code == "RecoveryRequired" and recovery.value.started is not False + assert len(processes) == 1 + assert store.committed(lineage["generated"]["attempt_id"]).record_ref == ( + lineage["generated"]["record_ref"] + ) + + +@pytest.mark.parametrize("live", [True, False], ids=["live-owner", "owner-gone"]) +def test_registered_lineage_without_record_uses_existing_state(lineage, monkeypatch, live): + store, spec = lineage["store"], lineage["spec"] + claim = store.claim({key: spec[key] for key in execution_service.ATTEMPT_FIELDS}, + run_store.request_digest(spec)) + try: + if not live: + claim.release() + monkeypatch.setattr(generation_lineage, "authorize", + lambda *args: pytest.fail("registered request read lineage")) + _forbid_claim(monkeypatch, store) + with pytest.raises(PublicError) as caught: + execution_service.execute(store, lineage["evaluation_target"], spec) + assert caught.value.code == ("AttemptInProgress" if live else "RecoveryRequired") + assert caught.value.latest_record_ref is None + finally: + claim.release() + + +def test_cancelled_lineage_retains_not_started_facts_and_the_same_ref(lineage, monkeypatch): + cancellation = threading.Event() + cancellation.set() + monkeypatch.setattr(execution_service, "_run_steps", + lambda *args: pytest.fail("cancelled evaluation started a worker")) + result = lineage["harness"].execute(lineage["spec"], cancellation=cancellation) + assert result["started"] is False + assert result["generation_record_ref"] == lineage["generated"]["record_ref"] + monkeypatch.setattr(generation_lineage, "authorize", + lambda *args: pytest.fail("cancelled replay read lineage")) + _forbid_claim(monkeypatch, lineage["store"]) + assert lineage["harness"].execute(lineage["spec"])["record_ref"] == result["record_ref"] + + +def test_apps_publication_failure_keeps_committed_lineage_and_new_process_replays( + lineage, monkeypatch, tmp_path, +): + store, spec = lineage["store"], lineage["spec"] + request = { + "schema_version": 1, "prepared_ref": spec["prepared_ref"], + "attempt": {key: spec[key] for key in execution_service.ATTEMPT_FIELDS}, + "proposal": lineage["proposal"], "output_root": spec["output_root"], + } + # The host saves the whole original attempt before the first submission. + saved = tmp_path / "saved-execute.json" + saved.write_bytes(encode(request)) + (tmp_path / "storage.json").write_bytes(encode(lineage["config"])) + + def unavailable(*args, **kwargs): + raise OSError("local publication-failure control") + + with monkeypatch.context() as fault: + fault.setattr(archive, "_publish_directory", unavailable) + failed = api.execute( + decode(saved.read_bytes()), workspace=tmp_path, storage_config=lineage["config"], + execute_harness=lineage["harness"].execute, output_id="failed-lineage", + ) + committed = store.committed(spec["attempt_id"]) + assert failed.directory is None and failed.result["exit_code"] == 6 + assert failed.result["record_ref"] == committed.record_ref + assert failed.result["error"]["latest_record_ref"] == committed.record_ref + assert committed.payload["generation_record_ref"] == lineage["generated"]["record_ref"] + (tmp_path / "expected-ref.json").write_bytes(encode(committed.record_ref)) + _retained_path(lineage, "candidate").write_bytes(b"changed after original submission") + script = """ +import subprocess, sys +from pathlib import Path +sys.path.insert(0, sys.argv[1]) +from inferrsi.apps import api +from inferrsi.contracts.json_v1 import decode, encode +from inferrsi.harness import generation_lineage +from inferrsi.harness.api import Harness, LocalCpuTarget +from inferrsi.harness.run_store import Claim, RunStore +root = Path(sys.argv[2]) +load = lambda name: decode((root / name).read_bytes()) +store = RunStore(root / 'store', 'generation') +def forbidden(*args, **kwargs): + raise AssertionError('replay started or committed a new attempt') +subprocess.Popen = forbidden +Claim.commit = forbidden +store.claim = forbidden +generation_lineage.authorize = forbidden +retired = Harness(store, LocalCpuTarget('retired', '2', root / 'retired')) +output = api.execute(load('saved-execute.json'), workspace=root, + storage_config=load('storage.json'), execute_harness=retired.execute, + output_id='replayed-lineage') +assert output.result['exit_code'] == 0 +assert output.result['record_ref'] == load('expected-ref.json') +with store._connection() as connection: + assert connection.execute('SELECT count(*) FROM attempts').fetchone()[0] == 2 + assert connection.execute('SELECT count(*) FROM records').fetchone()[0] == 2 +assert (output.directory / 'manifest.json').is_file() +assert (output.directory / 'result.json').is_file() +for name in ('manifest.json', 'result.json'): + raw = (output.directory / name).read_bytes() + assert encode(decode(raw)) == raw +print(encode(output.result['record_ref']).decode('utf-8')) +""" + child = subprocess.run( + [sys.executable, "-I", "-B", "-c", script, + str(Path(__file__).resolve().parents[1] / "src"), str(tmp_path)], + cwd=tmp_path, capture_output=True, text=True, encoding="utf-8", check=True, + ) + assert decode(child.stdout.strip().encode("utf-8")) == committed.record_ref + assert store.committed(spec["attempt_id"]).payload_bytes == committed.payload_bytes From 3b80fee0df28d0a2d876bc45990c91bfc1feca6e Mon Sep 17 00:00:00 2001 From: Zeng Chuang Date: Tue, 24 Nov 2026 18:37:58 +0800 Subject: [PATCH 2/2] fix(harness): stream candidate integrity verification Agent-assisted-by: Codex (author/integrator) Signed-off-by: zengchuang --- src/inferrsi/harness/generation_lineage.py | 9 +++++---- tests/test_harness_generation_lineage.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/inferrsi/harness/generation_lineage.py b/src/inferrsi/harness/generation_lineage.py index 478a48528..232c765f4 100644 --- a/src/inferrsi/harness/generation_lineage.py +++ b/src/inferrsi/harness/generation_lineage.py @@ -16,7 +16,7 @@ def _require(condition, message, code="IdentityMismatch"): raise PublicError(code, stage="validate", started=False, message=message) -def _read(store, ref): +def _read(store, ref, *, collect=True): _require( run_store._has_fields(ref, {"location", "sha256", "size_bytes", "media_type"}) and prepared_binding._is_path(ref["location"]) @@ -33,12 +33,13 @@ def _read(store, ref): break _require(isinstance(chunk, bytes), "retained source is not bytes", "ArtifactIntegrityError") - chunks.append(chunk) + if collect: + chunks.append(chunk) total += len(chunk) digest.update(chunk) _require(total == ref["size_bytes"] and digest.hexdigest() == ref["sha256"], "retained generation bytes differ from their Ref", "ArtifactIntegrityError") - return b"".join(chunks) + return b"".join(chunks) if collect else None def _time(value): @@ -129,7 +130,7 @@ def _source(store, spec): "evaluation does not use the original retained candidate") _require(item["snapshot_format"] == "file-v1", "unsupported generated candidate snapshot", "UnsupportedRuleVersion") - _read(store, candidate) + _read(store, candidate, collect=False) return deepcopy(candidate) diff --git a/tests/test_harness_generation_lineage.py b/tests/test_harness_generation_lineage.py index 7f95faf55..5713c9a58 100644 --- a/tests/test_harness_generation_lineage.py +++ b/tests/test_harness_generation_lineage.py @@ -7,6 +7,7 @@ from copy import deepcopy from dataclasses import replace from hashlib import sha256 +from io import BytesIO from pathlib import Path import pytest @@ -156,6 +157,23 @@ def controlled_commit(claim, payload, artifacts=()): } +def test_large_candidate_integrity_check_does_not_collect_content(): + payload = b"x" * (3 * 1024 * 1024 + 17) + ref = { + "location": "stores/test/objects/large-candidate", + "sha256": sha256(payload).hexdigest(), + "size_bytes": len(payload), + "media_type": "application/octet-stream", + } + + class Store: + def open(self, actual): + assert actual == ref + return BytesIO(payload) + + assert generation_lineage._read(Store(), ref, collect=False) is None + + def test_generated_candidate_uses_a_separate_production_evaluation_attempt(lineage): store, harness, spec, port = (lineage[key] for key in ("store", "harness", "spec", "port")) generated = lineage["generated"]