diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index a60b5342..73408ddc 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -22,12 +22,12 @@ "docs/operations.md", "src/inferrsi/apps/api.py", "src/inferrsi/apps/archive.py", - "src/inferrsi/apps/workflows/benchmark_compare.py", "src/inferrsi/apps/delivery/__init__.py", "src/inferrsi/apps/handoff/bridge.py", "src/inferrsi/apps/handoff/candidate_provider.py", "src/inferrsi/apps/storage/artifact_reader.py", "src/inferrsi/apps/views/attempt.py", + "src/inferrsi/apps/workflows/benchmark_compare.py", "tests/check_installed.py", "tests/test_apps_assess.py", "tests/test_apps_module_migrations.py", @@ -36,9 +36,10 @@ "tests/test_apps_prepare.py", "tests/test_apps_publication.py", "tests/test_apps_replay.py", + "tests/test_benchmark_assessment.py", "tests/test_benchmark_preparation.py", - "tests/test_result_delivery.py", - "tests/test_benchmark_assessment.py" + "tests/test_harness_entry_verification.py", + "tests/test_result_delivery.py" ] }, { @@ -62,7 +63,8 @@ "tests/test_apps_assess.py", "tests/test_apps_generation_plan.py", "tests/test_apps_module_migrations.py", - "tests/test_benchmark_assessment.py" + "tests/test_benchmark_assessment.py", + "tests/test_harness_entry_verification.py" ] }, { @@ -129,7 +131,6 @@ ], "consumers": [ "docs/apps-output.md", - "tests/test_harness_prepared_binding.py", "docs/architecture.md", "docs/module-layout.md", "docs/operations.md", @@ -142,8 +143,10 @@ "tests/test_apps_execution_binding.py", "tests/test_apps_generation_plan.py", "tests/test_apps_module_migrations.py", + "tests/test_benchmark_assessment.py", "tests/test_benchmark_preparation.py", - "tests/test_benchmark_assessment.py" + "tests/test_harness_entry_verification.py", + "tests/test_harness_prepared_binding.py" ] }, { diff --git a/docs/contracts/harness-entry-verification.md b/docs/contracts/harness-entry-verification.md new file mode 100644 index 00000000..5d3fe199 --- /dev/null +++ b/docs/contracts/harness-entry-verification.md @@ -0,0 +1,65 @@ +# Harness source-entry verification + +The local CPU target can opt into the first frozen evaluation task with +`LocalCpuTarget(..., module_root=)`. The host owns +this configuration. Requests cannot supply the root. Existing targets with no +module root retain their ordinary-command behavior and refuse evaluation mode +before registration. + +The first target supports a standalone source entry named +`module_root/.py` with `entrypoint_kind="python_module"`. It reads a +regular file inside that root, without importing worker code or package +initializers. Dotted packages, bytecode/native modules and native executables +remain unsupported on this evaluation target. No ambient module/path fallback +is attempted. Ordinary-command module/executable resolution is unchanged. + +## Ordering and retained facts + +1. Static shape and fixed-preparation declaration checks run before registration. + Malformed bindings still produce no attempt or record. +2. RunStore registers the request and ordinary admission runs. +3. Harness copies the actual entry into its private attempt capture directory, + independently checks the retained bytes, and compares their SHA-256 with the + expected digest already bound to the frozen preparation. +4. A mismatch yields a fixed `not_started` record. Its + `entry_code_identity` check is `failed`, the runtime binding contains the + observed actual digest, and the check references the retained source bytes. +5. An unavailable/unsupported entry yields a fixed `not_started` record with a + `not_performed` check and no source reference. A source-module binding keeps + the actual digest null and the unresolved argv empty. No mismatch is invented. +6. A matching standalone module executes from its captured source file using the + current Python interpreter with `-I -B`. The workspace and `PYTHONPATH` cannot + replace the bound entry, and subsequent changes to its original source file + do not change the bytes being executed. Package execution is outside this + target's supported range. The runtime binding records the resolved command. + +Runtime bindings describe resolution, not proof of a process launch. On an N1 +mismatch, `argv` is the would-be command over the captured source and the step +remains `not_started`; `started` and step facts determine whether anything ran. +On N2 it is empty because the source command could not be resolved. This target +intentionally binds the frozen recipe's single worker step; declaration checks +reject multiple steps, so each private entry directory holds one snapshot. + +Both refusal cases launch zero worker processes, acquire no process lease, and +retain the preparation/protocol/candidate identity in the fixed record. The +source proof uses `python-source@1`; its SHA is the observed byte identity, not +the frozen expectation copied into an observation. The complete interpreter is +not archived. Re-reading the fixed revision preserves those facts. + +The entry capture is a Harness write. A capture failure uses the existing +`ExecutionPersistenceError` path with `started=false`. Record commit failure +also preserves that known start state and cannot produce a committed RecordRef. +There is no process fallback after an entry failure. + +## Delivery boundary + +These checks implement the post-registration T37-N1/N2 boundary separately from +the pre-registration binding tests. A real matching source entry is a positive +control. CPU execution facts and exit zero are not a Benchmark verdict. + +The production preparation/Apps archive cross-tests use the accepted D023 / +`t108-v4` family and actual source bytes. Their small software worker does not +claim complete F/C/M evidence, a service gain, or whole-Issue production +acceptance. Existing ordinary CPU supervision is reused; evaluation deadline, +budget and T40 acceptance remain the later Harness unit, including its separate +launch-boundary prerequisite. diff --git a/docs/contracts/harness-prepared-binding.md b/docs/contracts/harness-prepared-binding.md index 15db9301..0f4d7580 100644 --- a/docs/contracts/harness-prepared-binding.md +++ b/docs/contracts/harness-prepared-binding.md @@ -45,8 +45,9 @@ and a null step timeout without rewriting historical fixtures. Its canonical bytes must agree between the Apps binder and Harness `request_digest`. The vector is documentary; its historical code pin is not an available worker. -This slice keeps valid evaluation-mode execution explicitly unsupported. -Actual entry resolution and code-byte verification after registration (T37), -attempt deadlines/budget enforcement with a null step timeout, and evaluation -replay (T40) are later delivery slices. It does not establish production CPU -acceptance or completion of the governing Harness or Apps Issues. +Targets without an explicit `module_root` keep valid evaluation-mode execution +unsupported before registration. A configured source target performs the separate +[post-registration entry check](harness-entry-verification.md) (T37). Attempt +deadlines/budget acceptance with a null step timeout and evaluation replay (T40) +remain separate delivery work. Declaration checks alone do not establish +production CPU acceptance or completion of the governing Harness or Apps Issues. diff --git a/docs/operations.md b/docs/operations.md index 1db7ef02..607c82ba 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -54,6 +54,7 @@ Effect classes used below: | 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 | | 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) | | 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 | | 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/harness/api.py b/src/inferrsi/harness/api.py index cc69e8f5..3643dc7f 100644 --- a/src/inferrsi/harness/api.py +++ b/src/inferrsi/harness/api.py @@ -43,7 +43,7 @@ def allocate( ) def execute(self, spec: Mapping, *, cancellation=None) -> dict: - """The flat ExecutionRecord of one ordinary command request, or a PublicError. + """The flat ExecutionRecord of one supported local CPU request, or a PublicError. ``cancellation`` is a host handle with ``is_set()``, such as ``threading.Event``. """ diff --git a/src/inferrsi/harness/entry_code.py b/src/inferrsi/harness/entry_code.py new file mode 100644 index 00000000..ef8ed3e6 --- /dev/null +++ b/src/inferrsi/harness/entry_code.py @@ -0,0 +1,60 @@ +"""Capture a trusted local source entry without importing or executing worker code.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +from . import input_binding + +_MODULE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*", re.ASCII) + + +class EntryUnavailable(Exception): + """The supported entry bytes cannot be resolved; no actual digest is known.""" + + def __init__(self, reason: str): + super().__init__(reason) + self.reason = reason + + +class EntryCaptureError(Exception): + """A resolved entry could not be retained safely before execution.""" + + +@dataclass(frozen=True) +class CapturedEntry: + path: Path + sha256: str + size_bytes: int + + +def capture_module(root: Path, module: str, directory: Path) -> CapturedEntry: + """Snapshot one source module from an explicit trusted root. + + The first CPU binding supports a standalone ``.py`` entry. Dotted + package names, bytecode/native modules and import hooks are not resolved by + this port. In particular, neither a package initializer nor a worker module + is imported to locate its code. The caller owns the private capture directory. + """ + if not isinstance(module, str) or _MODULE.fullmatch(module) is None: + raise EntryUnavailable("entry_kind_unsupported") + name = module + ".py" + try: + stream = input_binding.open_regular(root, name) + except (OSError, input_binding.BindingError): + raise EntryUnavailable("entry_bytes_unavailable") from None + destination = directory / name + with stream: + # A capture directory belongs to one registered attempt. Never replace + # an existing entry snapshot on an interrupted or repeated operation. + if destination.exists(): + raise EntryCaptureError("entry snapshot already exists") + try: + digest, size = input_binding.copy_stream(stream, destination) + if input_binding.file_sha256(destination) != (digest, size): + raise EntryCaptureError("entry snapshot differs from the captured bytes") + except OSError as error: + raise EntryCaptureError("entry snapshot could not be retained") from error + return CapturedEntry(destination, digest, size) diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index 0a85a809..8e676015 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -12,12 +12,12 @@ from pathlib import Path from inferrsi.contracts import json_v1 -from inferrsi.harness import input_binding, local_process, prepared_binding, run_store +from inferrsi.harness import entry_code, input_binding, local_process, prepared_binding, run_store from inferrsi.harness.errors import PublicError -# H02 single local-CPU execute in ordinary command mode (V05 null set). Evaluation-mode -# specs are checked before registration (V05/V28/V32 and their fixed preparation) and then -# refused: the T37 entry-code check and generation chaining are later slices. +# 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. +# Generation chaining and the remaining evaluation replay/limit acceptance are later slices. ATTEMPT_FIELDS = ( "request_id", "run_id", "attempt_id", "owner", "target_request", "deadline_utc", "resources", "budget", "retry_of", "retry_reason", @@ -57,6 +57,7 @@ _STREAM_MEDIA_TYPE = "application/octet-stream" _INPUT_MEDIA_TYPE = "application/octet-stream" _INPUT_SCHEMA = {"name": "input-identity", "revision": "1"} +_ENTRY_SCHEMA = {"name": "python-source", "revision": "1"} # The one snapshot format this slice captures: the bytes of one regular file. SNAPSHOT_FORMAT = "file-v1" # The only capability this target provides: one command tree in an OS-owned domain. @@ -73,7 +74,10 @@ class LocalCpuTarget: ``work_root`` holds per-attempt workspaces (``workspaces/``) and private capture snapshots. ``controller_root`` / ``target_root`` authorize input sources of - those namespaces; ``None`` leaves that namespace unauthorized. + those namespaces; ``None`` leaves that namespace unauthorized. ``module_root`` + explicitly enables evaluation through standalone source entries under that trusted + root. The retained source is executed directly in an isolated Python interpreter; + package imports and ambient cwd/PYTHONPATH entry resolution are not used. """ target_id: str @@ -81,6 +85,7 @@ class LocalCpuTarget: work_root: Path controller_root: Path | None = None target_root: Path | None = None + module_root: Path | None = None def __post_init__(self) -> None: errors = [ @@ -88,7 +93,7 @@ def __post_init__(self) -> None: for name in ("target_id", "config_revision") if not run_store._is_id(getattr(self, name)) ] - for name in ("work_root", "controller_root", "target_root"): + for name in ("work_root", "controller_root", "target_root", "module_root"): value = getattr(self, name) if value is None: continue @@ -403,10 +408,8 @@ def validate(spec: object, target: LocalCpuTarget, *, artifact_reader=None) -> N # request. The reader is the read-only port; H does not write or register anything. prepared_binding.verify(spec, artifact_reader) unsupported = [] - if evaluation: - # The T37 pre-start entry-code check runs after registration and is a later slice. - # Until it exists, no evaluation-mode candidate may start. - unsupported.append("evaluation-mode entry verification is not implemented in this slice") + 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") request = spec["target_request"] @@ -578,8 +581,8 @@ def _capture_input(ctx: _Context, index: int, item: Mapping, target: LocalCpuTar "checker_revision": "1", "subject": item["role"], "phase": "preparing", - "operation": None, - "validation_scope": None, + "operation": ctx.spec["operation"], + "validation_scope": ctx.spec["validation_scope"], "attempt_id": ctx.attempt_id, "status": {"matched": "passed", "mismatched": "failed", "not_performed": "not_performed", "error": "execution_error"}[status], @@ -600,6 +603,48 @@ def _argv(step: Mapping) -> list[str] | None: return None if executable is None else [executable, *step["args"]] +def _bind_entry(ctx: _Context, step: Mapping, target: LocalCpuTarget): + """Observe/capture the supported entry after registration, before workspace execution.""" + actual, ref, argv = None, None, [] + reason = "entry_kind_unsupported" + if step["entrypoint_kind"] == "python_module": + try: + captured = entry_code.capture_module( + target.module_root, step["entrypoint"], ctx.captures / "entry", + ) + except entry_code.EntryUnavailable as error: + reason = error.reason + except entry_code.EntryCaptureError as error: + raise _RetentionFailure("entry capture failed") from error + else: + actual = captured.sha256 + ref = ctx.object_ref(captured.path, actual, captured.size_bytes, "text/x-python") + # Execute exactly the retained source, with no cwd/PYTHONPATH module fallback. + # This first target supports standalone source modules, not Python packages. + argv = [sys.executable, "-I", "-B", str(captured.path), *step["args"]] + reason = ("entry_code_matched" if actual == step["expected_code_sha256"] + else "entry_code_sha256_differs") + status = ("not_performed" if actual is None else + "passed" if actual == step["expected_code_sha256"] else "failed") + runtime = { + "step_id": step["step_id"], "runtime_role": step["runtime_role"], + "executable": sys.executable, "entrypoint": step["entrypoint"], + "entrypoint_revision": step["entrypoint_revision"], "code_sha256": actual, + "argv": argv, "environment_identity": None, + } if step["entrypoint_kind"] == "python_module" else None + check = { + "check_id": "entry_code_identity", "checker_revision": "1", "subject": step["step_id"], + "phase": "preparing", "operation": ctx.spec["operation"], + "validation_scope": ctx.spec["validation_scope"], "attempt_id": ctx.attempt_id, + "status": status, "producer": { + "kind": "harness_capture", "identity": _HARNESS, "revision": "1", + "control_domain": _CONTROL_DOMAIN, "capture_route": "entry-source-snapshot", + }, "evidence_refs": [] if ref is None else [ref], "artifact_schema": _ENTRY_SCHEMA, + "reasons": [reason], + } + return argv, runtime, check + + def _retain_stream(ctx: _Context, stream, name: str, media_type: str) -> dict | None: """Snapshot one produced file from its open stream; None when the copy fails.""" target = ctx.captures / name @@ -854,12 +899,12 @@ def _payload(ctx: _Context, **facts) -> dict: "target_binding": facts["target_binding"], "retry_of": spec["retry_of"], "retry_reason": spec["retry_reason"], - "generation_record_ref": None, - "prepared_ref": None, - "protocol_digest": None, - "operation": None, - "validation_scope": None, - "candidate": None, + "generation_record_ref": copy.deepcopy(spec["generation_record_ref"]), + "prepared_ref": copy.deepcopy(spec["prepared_ref"]), + "protocol_digest": spec["protocol_digest"], + "operation": spec["operation"], + "validation_scope": spec["validation_scope"], + "candidate": copy.deepcopy(spec["candidate"]), "record_version": 1, "recorded_at": run_store.utc_now(), "bound_inputs": facts["bound_inputs"], @@ -913,7 +958,22 @@ def _run_claimed(ctx, target, digest, reader, deadline, cancellation) -> dict: binding = _target_binding(target, capability_checks, []) if errors: return _refusal(ctx, digest, binding, admission, [], [], errors, "admission_rejected") - argvs = [_argv(step) for step in ctx.spec["steps"]] + evaluation = ctx.spec["prepared_ref"] is not None + entry_checks = [] + if evaluation: + entries = [_bind_entry(ctx, step, target) for step in ctx.spec["steps"]] + argvs = [entry[0] for entry in entries] + binding["runtime_bindings_by_step"] = [ + entry[1] for entry in entries if entry[1] is not None + ] + entry_checks = [entry[2] for entry in entries] + if any(check["status"] != "passed" for check in entry_checks): + code = ("entry_code_mismatch" if any(check["status"] == "failed" + for check in entry_checks) else "entrypoint_unavailable") + return _refusal(ctx, digest, binding, admission, [], entry_checks, + [_error(code, "binding", "evaluation entry binding refused")], code) + else: + argvs = [_argv(step) for step in ctx.spec["steps"]] if None in argvs: errors = [_error("entrypoint_unavailable", "binding", "an executable entry is not found")] return _refusal(ctx, digest, binding, admission, [], [], errors, "entrypoint_unavailable") @@ -921,7 +981,9 @@ def _run_claimed(ctx, target, digest, reader, deadline, cancellation) -> dict: ctx.workspace.mkdir(parents=True) except FileExistsError: errors = [_error("workspace_exists", "binding", "the attempt workspace already exists")] - return _refusal(ctx, digest, binding, admission, [], [], errors, "workspace_exists") + return _refusal( + ctx, digest, binding, admission, [], entry_checks, errors, "workspace_exists", + ) except OSError as exc: raise _RetentionFailure("workspace creation failed") from exc captured = [ @@ -929,7 +991,7 @@ def _run_claimed(ctx, target, digest, reader, deadline, cancellation) -> dict: for index, item in enumerate(ctx.spec["inputs"]) ] bound = [item[0] for item in captured] - checks = [item[1] for item in captured] + checks = entry_checks + [item[1] for item in captured] failed = [b for b in bound if b["identity_status"] in ("mismatched", "error")] if failed: # H02-3: the actual binding is refused after registration and before any start. @@ -952,7 +1014,7 @@ def _run_claimed(ctx, target, digest, reader, deadline, cancellation) -> dict: outcome, exit_code = _outcome(steps) cleanup, leases = _cleanup(runs) launched = {step["step_id"] for step, run in runs if run["pid"] is not None} - binding["runtime_bindings_by_step"] = [ + ordinary_runtime = [ { "step_id": step["step_id"], "runtime_role": step["runtime_role"], @@ -967,6 +1029,8 @@ def _run_claimed(ctx, target, digest, reader, deadline, cancellation) -> dict: for step, argv in zip(ctx.spec["steps"], argvs) if step["step_id"] in launched ] + if not evaluation: + binding["runtime_bindings_by_step"] = ordinary_runtime codes = {"timed_out": "timeout", "cancelled": "cancelled", "execution_error": "execution_error", "not_started": "deadline_exhausted"} run_errors = ( diff --git a/tests/check_installed.py b/tests/check_installed.py index 5689ceb5..4a0ce9ad 100644 --- a/tests/check_installed.py +++ b/tests/check_installed.py @@ -32,6 +32,7 @@ subprocess.run([ sys.executable, "-I", "-B", "-c", "import sys; from inferrsi.harness import prepared_binding as p; " + "from inferrsi.harness import entry_code; assert callable(entry_code.capture_module); " "assert all(callable(getattr(p, n)) for n in ('read', 'project', 'verify')); " "assert not any(n == root or n.startswith(root + '.') for n in sys.modules " "for root in ('inferrsi.apps', 'inferrsi.benchmark', 'inferrsi.knowledge'))", diff --git a/tests/fixtures/harness-prepared-binding/README.md b/tests/fixtures/harness-prepared-binding/README.md index e235960c..5d6e1789 100644 --- a/tests/fixtures/harness-prepared-binding/README.md +++ b/tests/fixtures/harness-prepared-binding/README.md @@ -9,6 +9,8 @@ with request digest This is immutable contract-conformance input, not observed execution evidence or an available worker implementation. Tests compare the canonical Apps binder, -Harness digest and read-only prepared projection. No process is started. T37 -entry verification and production T40 replay remain separate PR-2/PR-3 work. +Harness digest and read-only prepared projection. No process is started by these +binding tests. Post-registration T37 is covered separately in +`tests/test_harness_entry_verification.py`; deadline/budget and production T40 +replay remain PR-3 work. The original documentary fixtures are not rewritten. diff --git a/tests/test_harness_entry_code.py b/tests/test_harness_entry_code.py new file mode 100644 index 00000000..9af659f8 --- /dev/null +++ b/tests/test_harness_entry_code.py @@ -0,0 +1,39 @@ +"""Actual entry-byte capture is separate from preparation declaration checks.""" + +from hashlib import sha256 + +import pytest + +from inferrsi.harness import entry_code + + +def test_capture_reads_actual_source_without_importing_or_executing_it(tmp_path): + root = tmp_path / "trusted" + root.mkdir() + source = b"raise RuntimeError('this worker must never be imported during binding')\n" + (root / "fixture_worker.py").write_bytes(source) + result = entry_code.capture_module(root, "fixture_worker", tmp_path / "captures") + assert result.path.read_bytes() == source + assert (result.sha256, result.size_bytes) == (sha256(source).hexdigest(), len(source)) + (root / "fixture_worker.py").write_bytes(b"changed after capture\n") + assert result.path.read_bytes() == source + + +@pytest.mark.parametrize("module", ["missing", "package.worker", "../outside", "worker.py"]) +def test_unresolvable_entry_has_no_actual_digest_or_capture(tmp_path, module): + with pytest.raises(entry_code.EntryUnavailable): + entry_code.capture_module(tmp_path, module, tmp_path / "captures") + assert not (tmp_path / "captures").exists() + + +def test_existing_snapshot_is_preserved_instead_of_replaced(tmp_path): + root = tmp_path / "trusted" + root.mkdir() + (root / "worker.py").write_bytes(b"new bytes") + captures = tmp_path / "captures" + captures.mkdir() + retained = captures / "worker.py" + retained.write_bytes(b"already retained") + with pytest.raises(entry_code.EntryCaptureError): + entry_code.capture_module(root, "worker", captures) + assert retained.read_bytes() == b"already retained" diff --git a/tests/test_harness_entry_verification.py b/tests/test_harness_entry_verification.py new file mode 100644 index 00000000..d47c3302 --- /dev/null +++ b/tests/test_harness_entry_verification.py @@ -0,0 +1,240 @@ +"""T37 happens after registration; declaration-only refusals remain in their own test file.""" + +import json +import sqlite3 +import subprocess +import sys +from copy import deepcopy +from hashlib import sha256 +from pathlib import Path + +import pytest +from jsonschema import Draft202012Validator + +from inferrsi.apps import api +from inferrsi.apps.handoff.bridge import bind_execution +from inferrsi.apps.storage.archive import read_prepared +from inferrsi.apps.storage.artifact_reader import ArtifactReader +from inferrsi.benchmark import preparation as benchmark +from inferrsi.contracts.json_v1 import decode +from inferrsi.harness import execution_service, run_store +from inferrsi.harness.api import Harness, LocalCpuTarget +from inferrsi.harness.errors import PublicError +from tests.test_benchmark_preparation import preparation as preparation + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture +def evaluation(preparation, tmp_path): + service, request, sources, _, _, config, _ = preparation + output = api.prepare( + {"schema_version": 1, "request": request}, workspace=tmp_path, + storage_config=config, prepare_benchmark=service.prepare, + encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, + ) + assert output.result["exit_code"] == 0 + ref = output.result["prepared_ref"] + prepared = read_prepared(config, ref) + vector = decode((ROOT / "tests/fixtures/harness-prepared-binding/d023-null-timeout.json") + .read_bytes()) + controller, modules = tmp_path / "controller", tmp_path / "modules" + controller.mkdir() + modules.mkdir() + source = sources["worker-code"].read_bytes() + (modules / "fixture_worker.py").write_bytes(source) + candidate = b"raise RuntimeError('candidate input must never replace the trusted worker')\n" + (controller / "candidate.txt").write_bytes(candidate) + proposal = {key: deepcopy(vector[key]) + for key in ("candidate", "inputs", "generation_record_ref")} + proposal["inputs"][0].update( + source="candidate.txt", source_namespace="controller", source_ref=None, + expected_sha256=sha256(candidate).hexdigest(), + ) + request = { + "schema_version": 1, "prepared_ref": ref, + "attempt": {key: vector[key] for key in execution_service.ATTEMPT_FIELDS}, + "proposal": proposal, "output_root": vector["output_root"], + } + spec = bind_execution(request, prepared) + store = run_store.RunStore(tmp_path / "store", "test") + target = LocalCpuTarget( + "fixture-cpu", "1", work_root=tmp_path / "work", controller_root=controller, + module_root=modules, + ) + reader = ArtifactReader(config) + return {"spec": spec, "store": store, "target": target, "modules": modules, + "source": source, "reader": reader, "harness": Harness(store, target, + artifact_reader=reader)} + + +def assert_fixed_refusal(case, record, status, actual): + schema = json.loads((ROOT / "docs/contracts/schemas/contract-v1.schema.json") + .read_text(encoding="utf-8")) + Draft202012Validator({**schema, "$ref": "#/$defs/ExecutionRecord"}).validate(record) + assert record["started"] is False and record["phase"] == "finished" + assert record["process_outcome"] == "not_started" and record["exit_code"] is None + assert record["prepared_ref"] == case["spec"]["prepared_ref"] + assert record["candidate"] == case["spec"]["candidate"] + check = record["checks"][0] + assert check["check_id"] == "entry_code_identity" and check["status"] == status + assert check["operation"] == "evaluate" and check["validation_scope"] == "p1" + runtime = record["target_binding"]["runtime_bindings_by_step"][0] + assert runtime["code_sha256"] == actual + assert all(step["status"] == "not_started" for step in record["steps"]) + if actual is not None: + assert runtime["argv"][1:3] == ["-I", "-B"] + assert record["resource_leases"]["leases"] == [] + saved = case["store"].read(record["attempt_id"], record["record_version"]) + assert saved["record_ref"] == record["record_ref"] + assert saved["checks"] == record["checks"] + with sqlite3.connect(case["store"].root / run_store.INDEX_NAME) as connection: + assert connection.execute("SELECT count(*) FROM attempts").fetchone()[0] == 1 + assert connection.execute("SELECT count(*) FROM records").fetchone()[0] == 1 + + +@pytest.mark.parametrize("failure", ["mismatch", "missing"]) +def test_t37_entry_failure_commits_a_not_started_record(evaluation, monkeypatch, failure): + case = evaluation + source = case["modules"] / "fixture_worker.py" + if failure == "mismatch": + observed = b"raise RuntimeError('changed worker must not start')\n" + source.write_bytes(observed) + actual = sha256(observed).hexdigest() + else: + source.unlink() + actual = None + + def forbidden(*args, **kwargs): + pytest.fail("T37-N1/N2 launched a process") + + monkeypatch.setattr(execution_service.local_process, "_supervise", forbidden) + record = case["harness"].execute(case["spec"]) + assert_fixed_refusal( + case, record, "failed" if failure == "mismatch" else "not_performed", actual, + ) + refs = record["checks"][0]["evidence_refs"] + if failure == "mismatch": + assert len(refs) == 1 and refs[0]["sha256"] == actual + with case["reader"].open(refs[0]) as stream: + assert stream.read() == observed + else: + assert refs == [] + assert record["target_binding"]["runtime_bindings_by_step"][0]["argv"] == [] + + +@pytest.mark.parametrize("interference", ["workspace-shadow", "changed-origin"]) +def test_matching_entry_executes_its_snapshot_and_retains_the_observed_digest( + evaluation, monkeypatch, interference, +): + case = evaluation + supervise = execution_service.local_process._supervise + observed_pids = [] + + def counted(*args, **kwargs): + result = supervise(*args, **kwargs) + observed_pids.append(result["pid"]) + return result + + monkeypatch.setattr(execution_service.local_process, "_supervise", counted) + if interference == "workspace-shadow": + case["spec"]["inputs"][0]["materialized_path"] = "fixture_worker.py" + case["spec"]["steps"][0]["args"][0] = "fixture_worker.py" + else: + original = execution_service.entry_code.capture_module + + def capture_then_change(*args, **kwargs): + result = original(*args, **kwargs) + (case["modules"] / "fixture_worker.py").write_bytes( + b"raise RuntimeError('mutable origin is not the bound entry')\n", + ) + return result + + monkeypatch.setattr(execution_service.entry_code, "capture_module", capture_then_change) + record = case["harness"].execute(case["spec"]) + assert record["started"] is True and record["process_outcome"] == "exited" + assert record["exit_code"] == 0 + assert len(observed_pids) == 1 and observed_pids[0] is not None + check = record["checks"][0] + assert check["status"] == "passed" + actual = sha256(case["source"]).hexdigest() + assert record["target_binding"]["runtime_bindings_by_step"][0]["code_sha256"] == actual + assert record["target_binding"]["runtime_bindings_by_step"][0]["argv"][1:3] == ["-I", "-B"] + with case["reader"].open(check["evidence_refs"][0]) as stream: + assert stream.read() == case["source"] + assert "verdict" not in record + + +@pytest.mark.parametrize("failure", ["mismatch", "missing"]) +def test_t37_commit_failure_preserves_not_started_and_no_committed_record( + evaluation, monkeypatch, failure, +): + case = evaluation + source = case["modules"] / "fixture_worker.py" + if failure == "missing": + source.unlink() + else: + source.write_bytes(b"changed worker\n") + + def fail_commit(*args, **kwargs): + raise sqlite3.OperationalError("fixture commit failure") + + monkeypatch.setattr(case["store"], "_append", fail_commit) + monkeypatch.setattr(execution_service.local_process, "_supervise", + lambda *a, **k: pytest.fail("failed T37 commit started a process")) + with pytest.raises(PublicError) as caught: + case["harness"].execute(case["spec"]) + assert caught.value.code == "ExecutionPersistenceError" + assert caught.value.started is False + assert caught.value.latest_record_ref is None + assert caught.value.partial_record is not None + assert caught.value.partial_record.started is False + with pytest.raises(PublicError) as missing: + case["store"].read(case["spec"]["attempt_id"]) + assert missing.value.code == "NoCommittedRecord" + + +def test_t37_fixed_mismatch_and_source_bytes_can_be_read_in_a_fresh_process( + evaluation, monkeypatch, +): + case = evaluation + changed = b"raise RuntimeError('mismatching worker never executes')\n" + source = case["modules"] / "fixture_worker.py" + source.write_bytes(changed) + monkeypatch.setattr(execution_service.local_process, "_supervise", + lambda *a, **k: pytest.fail("mismatching worker started")) + record = case["harness"].execute(case["spec"]) + source.unlink() + script = ( + "import sys,json,hashlib; from inferrsi.harness.run_store import RunStore,RunStoreReader; " + "s=RunStore(sys.argv[1],'test'); r=s.read(sys.argv[2],1); " + "ref=r['checks'][0]['evidence_refs'][0]; " + "stream=RunStoreReader(s.root,'test').open(ref); raw=stream.read(); stream.close(); " + "print(json.dumps([r['record_ref'],r['started'],r['checks'][0]['status']," + "r['target_binding']['runtime_bindings_by_step'][0]['code_sha256']," + "hashlib.sha256(raw).hexdigest()]))" + ) + child = subprocess.run( + [sys.executable, "-c", script, str(case["store"].root), record["attempt_id"]], + check=True, capture_output=True, text=True, timeout=30, + ) + actual = sha256(changed).hexdigest() + assert json.loads(child.stdout) == [record["record_ref"], False, "failed", actual, actual] + + +def test_entry_capture_write_failure_is_not_an_unresolvable_entry(evaluation, monkeypatch): + case = evaluation + + def fail_capture(*args, **kwargs): + raise execution_service.entry_code.EntryCaptureError("fixture capture failure") + + monkeypatch.setattr(execution_service.entry_code, "capture_module", fail_capture) + monkeypatch.setattr(execution_service.local_process, "_supervise", + lambda *a, **k: pytest.fail("failed capture started a worker")) + with pytest.raises(PublicError) as caught: + case["harness"].execute(case["spec"]) + assert caught.value.code == "ExecutionPersistenceError" + assert caught.value.started is False and caught.value.latest_record_ref is None + with pytest.raises(PublicError) as missing: + case["store"].read(case["spec"]["attempt_id"]) + assert missing.value.code == "NoCommittedRecord" diff --git a/tests/test_harness_execute.py b/tests/test_harness_execute.py index ac1f6eb3..36114610 100644 --- a/tests/test_harness_execute.py +++ b/tests/test_harness_execute.py @@ -40,6 +40,7 @@ "inferrsi.harness.api", "inferrsi.harness.execution_service", "inferrsi.harness.input_binding", "inferrsi.harness.local_process", "inferrsi.harness.prepared_binding", + "inferrsi.harness.entry_code", "inferrsi.harness.atomic_json", "inferrsi.harness.run_store", "inferrsi.harness.errors", "inferrsi.harness.execution_spec", "inferrsi.contracts.json_v1",