diff --git a/docs/contracts/generation-bounds.md b/docs/contracts/generation-bounds.md new file mode 100644 index 000000000..403282d40 --- /dev/null +++ b/docs/contracts/generation-bounds.md @@ -0,0 +1,50 @@ +# Internal original generation bounds + +`inferrsi.harness.generation.prepare_generation` seals an approved context and +generation plan before execution registration. Its caller supplies the original +attempt, context request, candidate context and provider ports. It writes the +authorized RunStore and returns the ordinary execution specification; it does +not allocate an attempt, start a process or reserve a budget. + +New preparations retain an internal original-bounds snapshot alongside the +generation plan, in a separate internal retention slot. The snapshot contains: + +- Schema version, original attempt ID, run ID and owner. +- Original deadline and the complete declared budget, including policy, scope, + dimensions and enforcement requirements. +- The fixed generation-plan reference and the existing execution request digest. + +The snapshot and its checksum occupy an immutable SQLite row committed in the +same transaction as the generation plan. A failed plan commit exposes no snapshot; +the separately committed delivered context retains its existing recovery rules. +The generation-plan bytes, its public ArtifactRef, returned ExecutionSpec, +request-digest descriptor, execution-record fields and replay identity are unchanged. + +## Internal reads and historical compatibility + +Harness uses `RunStoreReader._read_generation_bounds(attempt_id)` internally. +It validates the checksum, attempt identity, original bounds shape, plan bytes +and fixed reference. It returns a fresh dictionary, or `None` for an absent plan +or a historical plan with no bounds slot. +Storage failures raise `ArtifactUnavailable`; malformed or mismatching retained +metadata raises `ArtifactIntegrityError`, at `read_generation_bounds`. Neither +error is silently relabeled as a missing historical snapshot. + +Historical rows are never backfilled. Repreparing the same historical request +uses its original plan and descriptor without updating either; an older sealing +caller can also reprepare a new plan using its unchanged descriptor. A changed plan +or request digest still conflicts. Ordinary execution and completed-attempt +replay retain their existing behavior. + +The checksum detects corruption within the trusted RunStore; it is not an +external source-authentication mechanism. The snapshot is internal metadata, +not a new public DTO, artifact location, admission result or spending record. +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. diff --git a/docs/operations.md b/docs/operations.md index 1db7ef029..208f7415f 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -53,6 +53,7 @@ Effect classes used below: | Rebuild scoped legacy evidence views | `python tools/rebuild_model_evidence.py --archive --output ` | CPU-only; creates a new output directory | Authenticates original bytes and pinned projection/code; no extraction, network, archived-code execution or campaign qualification | | Inspect evidence inventory / generate budget input | `python tools/validate_evidence.py [--budget-assets]` | Read-only | Offline layout/hash/schema checks; optional disposable #328 metadata view derived from campaign authority; no downloads | | Execute one ordinary local CPU command with a fixed record | Python `inferrsi.harness.api.Harness.allocate` / `execute` / `read` | Experiment-executing / record-writing | One explicit RunStore root and one trusted local CPU target; ordinary command mode only; a record holds execution facts, so exit 0 is not a verdict; no device, model or network fallback | +| 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) | | 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 | | 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 | diff --git a/src/inferrsi/harness/generation.py b/src/inferrsi/harness/generation.py index b5d02d073..3ba6142d0 100644 --- a/src/inferrsi/harness/generation.py +++ b/src/inferrsi/harness/generation.py @@ -99,8 +99,16 @@ def _bind_generation_plan(store, target, attempt, plan, delivery_ref): }) validate(spec, target) # Commit the binding with the manifest, outside the manifest's own bytes. + digest = run_store.request_digest(spec) + bounds = { + "schema_version": 1, + **{key: deepcopy(spec[key]) for key in ( + "attempt_id", "run_id", "owner", "deadline_utc", "budget", + )}, + "generation_plan": ref, "request_digest": digest, + } store._seal_generation_input( attempt_id, "generation-plan", data, - descriptor={"request_digest": run_store.request_digest(spec)}, + descriptor={"request_digest": digest}, original_bounds=encode(bounds), ) return spec diff --git a/src/inferrsi/harness/run_store.py b/src/inferrsi/harness/run_store.py index 7e6d3e8f9..55d0ed205 100644 --- a/src/inferrsi/harness/run_store.py +++ b/src/inferrsi/harness/run_store.py @@ -69,6 +69,10 @@ "generation-plan": "application/json", } _DELIVERY_FIELDS = frozenset({"items", "selection", "omissions", "limitations"}) +_BOUNDS_FIELDS = frozenset({ + "schema_version", "attempt_id", "run_id", "owner", "deadline_utc", "budget", + "generation_plan", "request_digest", +}) # Errno values meaning "another handle holds the lock" for msvcrt.locking and flock. _CONTENDED = frozenset({errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK, errno.EDEADLK}) _CHUNK = 1024 * 1024 @@ -838,6 +842,63 @@ def read_delivered_context(self, attempt_id: str) -> dict: ) return delivery + def _read_generation_bounds(self, attempt_id: str) -> dict | None: + """Read internal original bounds; historical plans are never backfilled.""" + stage = "read_generation_bounds" + if not _is_id(attempt_id): + raise PublicError("InvalidRequest", stage=stage, message="invalid attempt ID") + try: + with self._connection() as conn: + rows = conn.execute( + "SELECT role, sha256, data, descriptor FROM generation_inputs " + "WHERE attempt_hash = ? AND role IN ('generation-plan', 'original-bounds')", + (attempt_hash(attempt_id),), + ).fetchall() + except (sqlite3.Error, OSError) as exc: + raise PublicError( + "ArtifactUnavailable", stage=stage, message="generation bounds are not accessible", + ) from exc + if not rows: + return None + try: + parts = {row[0]: tuple(row)[1:] for row in rows} + if "generation-plan" not in parts: + raise ValueError("bounds have no committed generation plan") + digest, data, metadata = parts["generation-plan"] + descriptor = json_v1.decode(metadata) + if ( + not _has_fields(descriptor, {"request_digest"}) + or not isinstance(descriptor.get("request_digest"), str) + or not _DIGEST.fullmatch(descriptor["request_digest"]) + or hashlib.sha256(data).hexdigest() != digest + ): + raise ValueError("invalid generation plan binding") + if "original-bounds" not in parts: + return None + bounds_digest, bounds_data, bounds_metadata = parts["original-bounds"] + bounds = json_v1.decode(bounds_data) + if ( + not _has_fields(bounds, _BOUNDS_FIELDS) + or type(bounds["schema_version"]) is not int or bounds["schema_version"] != 1 + or bounds_metadata is not None + or hashlib.sha256(bounds_data).hexdigest() != bounds_digest + or bounds["request_digest"] != descriptor["request_digest"] + or bounds["attempt_id"] != attempt_id + or not all(_is_id(bounds[key]) for key in ("attempt_id", "run_id", "owner")) + or not _is_timestamp(bounds["deadline_utc"]) + or not _has_fields(bounds["budget"], _BUDGET_FIELDS) + or bounds["generation_plan"] != _generation_ref( + self.namespace, attempt_hash(attempt_id), "generation-plan", data, + ) + ): + raise ValueError("original bounds differ from their sealed identity") + except (AttributeError, TypeError, ValueError) as exc: + raise PublicError( + "ArtifactIntegrityError", stage=stage, + message="invalid committed generation bounds", + ) from exc + return copy.deepcopy(bounds) + def _find_delivery( self, attempt_id: str, *, preparation_digest: str | None = None, ) -> dict | None: @@ -953,8 +1014,13 @@ def _seal_delivered_context( def _seal_generation_input( self, attempt_id: str, role: str, data: bytes, *, descriptor: dict | None = None, + original_bounds: bytes | None = None, ) -> tuple: """Append one attempt input before registration, or return its existing delivery row.""" + if original_bounds is not None and ( + role != "generation-plan" or not isinstance(original_bounds, bytes) + ): + raise ValueError("original bounds belong to a generation-plan commit") key = attempt_hash(attempt_id) descriptor_bytes = None if descriptor is None else json_v1.encode(descriptor) values = (hashlib.sha256(data).hexdigest(), data, descriptor_bytes) @@ -979,6 +1045,13 @@ def _seal_generation_input( "(attempt_hash, role, sha256, data, descriptor) " "VALUES (?, ?, ?, ?, ?)", (key, role, *values), ) + if original_bounds is not None: + conn.execute( + "INSERT INTO generation_inputs " + "(attempt_hash, role, sha256, data, descriptor) " + "VALUES (?, 'original-bounds', ?, ?, NULL)", + (key, hashlib.sha256(original_bounds).hexdigest(), original_bounds), + ) elif role == "delivered-context": # Concurrent preparations compare request identity against the first commit. return tuple(row) diff --git a/tests/test_harness_generation_bounds.py b/tests/test_harness_generation_bounds.py new file mode 100644 index 000000000..187b3bd45 --- /dev/null +++ b/tests/test_harness_generation_bounds.py @@ -0,0 +1,259 @@ +"""Retain original generation bounds without changing sealed execution identity.""" + +import shutil +import sqlite3 +import subprocess +import sys +from contextlib import contextmanager +from copy import deepcopy +from hashlib import sha256 +from pathlib import Path + +import pytest + +from inferrsi.contracts.json_v1 import decode, encode +from inferrsi.harness import run_store +from inferrsi.harness.errors import PublicError +from inferrsi.harness.generation import prepare_generation +from tests.test_apps_generation_plan import generation as generation +from tests.test_harness_generation_seal import cpu_generation as cpu_generation + + +def expected_bounds(spec, plan_ref): + return { + "schema_version": 1, + **{key: deepcopy(spec[key]) for key in ( + "attempt_id", "run_id", "owner", "deadline_utc", "budget", + )}, + "generation_plan": plan_ref, "request_digest": run_store.request_digest(spec), + } + + +def test_bounds_are_committed_with_the_unchanged_plan_and_read_in_a_new_process( + cpu_generation, tmp_path, +): + store, target, harness, _, inputs = cpu_generation + reader = run_store.RunStoreReader(store.root, store.namespace) + attempt_id = inputs["attempt"]["attempt_id"] + assert reader._read_generation_bounds(attempt_id) is None + spec = prepare_generation(store, target, **inputs) + plan_ref = spec["inputs"][-1]["source_ref"] + expected = expected_bounds(spec, plan_ref) + assert reader._read_generation_bounds(attempt_id) == expected + original = encode(spec) + with reader.open(plan_ref) as stream: + plan_bytes = stream.read() + assert "original_bounds" not in decode(plan_bytes) + assert prepare_generation(store, target, **inputs) == spec + result = harness.execute(spec) + assert result["exit_code"] == 0 + assert result["request_digest"] == expected["request_digest"] + assert harness.execute(spec)["record_ref"] == result["record_ref"] + assert encode(spec) == original + borrowed = reader._read_generation_bounds(attempt_id) + borrowed["budget"]["scope_id"] = "caller mutation" + assert reader._read_generation_bounds(attempt_id) == expected + child = """ +import sys +sys.path.insert(0, sys.argv[1]) +from inferrsi.contracts.json_v1 import encode +from inferrsi.harness.run_store import RunStoreReader +sys.stdout.buffer.write(encode( + RunStoreReader(sys.argv[2], 'generation')._read_generation_bounds(sys.argv[3]) +)) +""" + received = subprocess.check_output( + [sys.executable, "-I", "-B", "-c", child, str(Path(__file__).resolve().parents[1] / "src"), + str(store.root), attempt_id], cwd=tmp_path, timeout=30, + ) + assert decode(received) == expected + + +def test_failed_plan_commit_publishes_no_bounds(cpu_generation, monkeypatch): + store, target, _, _, inputs = cpu_generation + reader = run_store.RunStoreReader(store.root, store.namespace) + attempt_id = inputs["attempt"]["attempt_id"] + original_transaction = run_store._transaction + writes = 0 + + @contextmanager + def fail_plan(connection, *args): + nonlocal writes + writes += 1 + with original_transaction(connection, *args): + yield + if writes == 2: + assert reader._read_generation_bounds(attempt_id) is None + raise sqlite3.OperationalError("synthetic failure before plan commit") + + with monkeypatch.context() as patch: + patch.setattr(run_store, "_transaction", fail_plan) + with pytest.raises(PublicError, match="ExecutionPersistenceError"): + prepare_generation(store, target, **inputs) + assert reader._read_generation_bounds(attempt_id) is None + assert reader.read_delivered_context(attempt_id) + with store._connection() as connection: + assert connection.execute("SELECT count(*) FROM attempts").fetchone()[0] == 0 + prepare_generation(store, target, **inputs) + assert reader._read_generation_bounds(attempt_id) is not None + + +def test_legacy_repreparation_and_replay_do_not_backfill_bounds(cpu_generation, monkeypatch): + store, target, harness, _, inputs = cpu_generation + original_seal = store._seal_generation_input + + def legacy_seal(id_, role, data, *, descriptor=None, **kwargs): + if role == "generation-plan": + descriptor = {"request_digest": descriptor["request_digest"]} + return original_seal(id_, role, data, descriptor=descriptor) + + with monkeypatch.context() as patch: + patch.setattr(store, "_seal_generation_input", legacy_seal) + spec = prepare_generation(store, target, **inputs) + attempt_id = spec["attempt_id"] + key = run_store.attempt_hash(attempt_id) + with store._connection() as connection: + old = tuple(connection.execute( + "SELECT sha256, data, descriptor FROM generation_inputs " + "WHERE attempt_hash = ? AND role = 'generation-plan'", (key,), + ).fetchone()) + assert store._read_generation_bounds(attempt_id) is None + assert prepare_generation(store, target, **inputs) == spec + result = harness.execute(spec) + assert result["exit_code"] == 0 + assert prepare_generation(store, target, **inputs) == spec + assert harness.execute(spec)["record_ref"] == result["record_ref"] + assert store._read_generation_bounds(attempt_id) is None + with store._connection() as connection: + assert tuple(connection.execute( + "SELECT sha256, data, descriptor FROM generation_inputs " + "WHERE attempt_hash = ? AND role = 'generation-plan'", (key,), + ).fetchone()) == old + + +def test_legacy_sealing_caller_can_reprepare_new_generation(cpu_generation, monkeypatch): + store, target, harness, _, inputs = cpu_generation + spec = prepare_generation(store, target, **inputs) + expected = store._read_generation_bounds(spec["attempt_id"]) + original_seal = store._seal_generation_input + + def legacy_seal(id_, role, data, *, descriptor=None, **kwargs): + if role == "generation-plan": + descriptor = {"request_digest": descriptor["request_digest"]} + return original_seal(id_, role, data, descriptor=descriptor) + + with monkeypatch.context() as patch: + patch.setattr(store, "_seal_generation_input", legacy_seal) + assert prepare_generation(store, target, **inputs) == spec + with store._connection() as connection: + descriptor = connection.execute( + "SELECT descriptor FROM generation_inputs WHERE role = 'generation-plan'", + ).fetchone()[0] + assert descriptor == encode({"request_digest": run_store.request_digest(spec)}) + assert store._read_generation_bounds(spec["attempt_id"]) == expected + assert harness.execute(spec)["exit_code"] == 0 + + +@pytest.mark.parametrize("fault", [ + "checksum", "attempt", "plan", "digest", "partial", "data", "orphan", +]) +def test_corrupt_bounds_fail_closed_without_mutating_the_original( + cpu_generation, tmp_path, fault, +): + store, target, _, _, inputs = cpu_generation + spec = prepare_generation(store, target, **inputs) + attempt_id = spec["attempt_id"] + expected = store._read_generation_bounds(attempt_id) + damaged = tmp_path / "damaged" + damaged.mkdir() + shutil.copyfile(store.root / run_store.INDEX_NAME, damaged / run_store.INDEX_NAME) + with sqlite3.connect(damaged / run_store.INDEX_NAME) as connection: + connection.execute("DROP TRIGGER generation_inputs_no_update") + plan_data = connection.execute( + "SELECT data FROM generation_inputs WHERE role = 'generation-plan'", + ).fetchone()[0] + digest, data = connection.execute( + "SELECT sha256, data FROM generation_inputs WHERE role = 'original-bounds'", + ).fetchone() + bounds = decode(data) + if fault == "checksum": + bounds["budget"]["scope_id"] = "damaged" + elif fault == "attempt": + bounds["attempt_id"] = "another-attempt" + elif fault == "plan": + bounds["generation_plan"]["sha256"] = "0" * 64 + elif fault == "digest": + bounds["request_digest"] = "sha256:" + "0" * 64 + elif fault == "partial": + bounds.pop("deadline_utc") + elif fault == "data": + plan_data += b" " + data = encode(bounds) + if fault in {"attempt", "plan", "digest", "partial"}: + digest = sha256(data).hexdigest() + connection.execute( + "UPDATE generation_inputs SET data = ?, sha256 = ? WHERE role = 'original-bounds'", + (data, digest), + ) + connection.execute( + "UPDATE generation_inputs SET data = ? WHERE role = 'generation-plan'", (plan_data,), + ) + if fault == "orphan": + connection.execute("DROP TRIGGER generation_inputs_no_delete") + connection.execute("DELETE FROM generation_inputs WHERE role = 'generation-plan'") + reader = run_store.RunStoreReader(damaged, store.namespace) + with pytest.raises(PublicError, match="ArtifactIntegrityError") as caught: + reader._read_generation_bounds(attempt_id) + assert caught.value.stage == "read_generation_bounds" + assert store._read_generation_bounds(attempt_id) == expected + + +def test_invalid_lookup_is_not_a_missing_historical_snapshot(cpu_generation): + store, _, _, _, _ = cpu_generation + with pytest.raises(PublicError, match="InvalidRequest"): + store._read_generation_bounds("../invalid") + + +def test_full_declared_budget_is_retained_without_reserving_or_admitting_it(cpu_generation): + store, target, harness, _, inputs = cpu_generation + inputs["attempt"]["budget"].update( + policy_ref={"name": "original-policy", "revision": "1"}, + scope_id="original-scope", declared_by="original-owner", + dimensions=[{"dimension": "api-cost", "unit": "USD", "limit": "1", + "reserve_estimate": None}], required_enforcement=["api-cost"], + ) + budget = deepcopy(inputs["attempt"]["budget"]) + spec = prepare_generation(store, target, **inputs) + assert store._read_generation_bounds(spec["attempt_id"])["budget"] == budget + with pytest.raises(PublicError, match="NoCommittedRecord"): + harness.read(spec["attempt_id"]) + with store._connection() as connection: + assert connection.execute("SELECT count(*) FROM attempts").fetchone()[0] == 0 + + +def test_bounds_storage_error_is_not_reported_as_a_missing_snapshot(cpu_generation, monkeypatch): + store, _, _, _, inputs = cpu_generation + reader = run_store.RunStoreReader(store.root, store.namespace) + + def unavailable(): + raise sqlite3.OperationalError("synthetic read failure") + + monkeypatch.setattr(reader, "_connection", unavailable) + with pytest.raises(PublicError, match="ArtifactUnavailable") as caught: + reader._read_generation_bounds(inputs["attempt"]["attempt_id"]) + assert caught.value.stage == "read_generation_bounds" + + +def test_internal_bounds_slot_is_not_a_new_public_artifact_location(cpu_generation): + store, target, _, _, inputs = cpu_generation + spec = prepare_generation(store, target, **inputs) + attempt_id = spec["attempt_id"] + data = encode(store._read_generation_bounds(attempt_id)) + digest = sha256(data).hexdigest() + guess = { + "location": (f"stores/{store.namespace}/generation/{run_store.attempt_hash(attempt_id)}" + f"/original-bounds/{digest}"), + "sha256": digest, "size_bytes": len(data), "media_type": "application/json", + } + with pytest.raises(PublicError, match="UnsafeArtifactPath"): + run_store.RunStoreReader(store.root, store.namespace).open(guess)