diff --git a/docs/contracts/harness-entry-verification.md b/docs/contracts/harness-entry-verification.md index 5d3fe1993..e345a1fb0 100644 --- a/docs/contracts/harness-entry-verification.md +++ b/docs/contracts/harness-entry-verification.md @@ -60,6 +60,6 @@ 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. +acceptance. Existing ordinary CPU supervision is reused. The +[original-limit/T40 contract](harness-evaluation-replay.md) describes the next +unit; complete CPU acceptance retains its separate launch-boundary prerequisite. diff --git a/docs/contracts/harness-evaluation-replay.md b/docs/contracts/harness-evaluation-replay.md new file mode 100644 index 000000000..ba64bad80 --- /dev/null +++ b/docs/contracts/harness-evaluation-replay.md @@ -0,0 +1,61 @@ +# Harness evaluation replay and original limits + +`Harness.execute` accepts the saved canonical ExecutionSpec. Static schema and +field checks run first. Harness then snapshots the request and checks its +existing RunStore identity/digest before reading preparation bytes, resolving a +target, admitting a budget, binding source or starting a process. + +| Existing state | Outcome | +| --- | --- | +| Finished committed attempt, same digest | Original fixed RecordRef and payload; no new binding, registration or worker | +| Same attempt, different digest | RequestConflict before artifact IO or target checks | +| Live owner, no terminal record | AttemptInProgress; attempt count unchanged | +| Owner gone or persistence failed without a record | RecoveryRequired; no implicit resume or new worker | +| No registered attempt | Validate fixed preparation/support, then atomically claim and execute | + +The non-registering lookup does not replace the atomic claim. A caller can +register while another is reading the preparation; the later claim still +applies the same digest/state table. A corrupt or unavailable RunStore is an +error, never permission to start again. Lookup failures do not fabricate a +known start state. + +Finished positive and refusal records both remain fixed. Repairing a missing +or mismatching source does not turn replay into a new run. The currently +configured target may be retired and the preparation reader unavailable on the +Harness replay path. The original record remains authoritative. Apps performs +its own saved-request binding before handing the ExecutionSpec to Harness; this +does not change Apps archive retention requirements. + +## Identity, deadline and budget + +The original request retains its attempt, request digest, target request, +deadline and complete budget. Host callbacks receive no mutable alias to the +internal request snapshot. A changed deadline, budget scope or preparation Ref +changes the digest and conflicts with an existing attempt. Reentry never +allocates a new identity, resets a deadline, reserves capacity or charges again. + +Fresh evaluation requests keep the original absolute attempt deadline when +step timeout is null. Known expiry/cancellation stops before source capture. +Mid-run expiry and explicit caller cancellation use the existing process-domain +supervisor and retain process exit, cleanup and lease release as separate facts. + +The initial CPU target keeps the existing free-CPU budget support boundary. +Unsupported policies, dimensions or enforcement requirements are explicitly +rejected before worker binding. Reserved/charged amounts remain unknown or +inapplicable rather than invented zeros. Actual observed usage and the original +budget admission remain in the fixed record. This slice adds no budget provider, +currency model or numeric acceptance gate. + +## Verification boundary + +The software tests combine real production preparation, Apps archives and the +configured source target. They cover completed/refused replay, digest conflicts, +live-owner and abandoned state, real running replay, real null-timeout expiry, +caller cancellation with a descendant, fixed cleanup facts, commit failure after +a real start, cross-process replay and registration races. Execution facts do +not provide a complete Benchmark F/C/M proof or a service-gain claim. + +The launch-boundary prerequisite still has its own delivery and review. The +deadline/step-timeout check during log setup must be integrated and verified +before whole CPU acceptance of this slice. The replay implementation does not +duplicate that supervisor change or close the governing Harness/Apps Issues. diff --git a/docs/contracts/harness-prepared-binding.md b/docs/contracts/harness-prepared-binding.md index 0f4d75804..16b39589f 100644 --- a/docs/contracts/harness-prepared-binding.md +++ b/docs/contracts/harness-prepared-binding.md @@ -31,8 +31,10 @@ with the fixed preparation. Disagreement is `IdentityMismatch`. It also checks: and input/output paths must not overlap. Required frozen capabilities cannot be dropped; additional declared capabilities remain subject to admission. -Malformed or conflicting declarations are `InvalidExecutionSpec`. All of these -refusals precede `RunStore.claim`: neither attempt nor record is registered. +Malformed or conflicting declarations are `InvalidExecutionSpec`. For a fresh +request these refusals precede `RunStore.claim`: neither attempt nor record is +registered. Existing request state is handled after static field checks and +before preparation IO by the [replay contract](harness-evaluation-replay.md). The public projection does not interpret candidate formats, grading rules, evidence requirements or scores, and does not recompute Benchmark's semantic prepared ID. The fixed ArtifactRef authenticates the preparation bytes; Apps @@ -47,7 +49,8 @@ The vector is documentary; its historical code pin is not an available worker. 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 +[post-registration entry check](harness-entry-verification.md) (T37). The +[original-limit/replay path](harness-evaluation-replay.md) covers the next +delivery unit, whose complete CPU acceptance retains its launch prerequisite. +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 fc54ebff0..9ca2d8674 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) | +| 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) | | 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 | | Seal host-approved generation context | Python `harness.generation.prepare_generation`; [feedback boundary](contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. H seals the supplied material; this port does not execute a worker or prove feedback-policy enforcement | diff --git a/src/inferrsi/harness/execution_service.py b/src/inferrsi/harness/execution_service.py index 8e676015e..b70e52e86 100644 --- a/src/inferrsi/harness/execution_service.py +++ b/src/inferrsi/harness/execution_service.py @@ -364,12 +364,8 @@ def _request_errors(spec: Mapping) -> list[str]: return errors -def validate(spec: object, target: LocalCpuTarget, *, artifact_reader=None) -> None: - """Refuse a request before registration (D021 priority: version, fields, support). - - An evaluation-mode spec is also checked against its fixed preparation, read through - ``artifact_reader`` (V05, V28, V32). Nothing here registers an attempt or writes a record. - """ +def _validate_fields(spec: object) -> bool: + """Check static fields before querying existing request state or opening artifacts.""" if isinstance(spec, Mapping): version = spec.get("schema_version") if type(version) is int and version != 1: @@ -403,6 +399,11 @@ def validate(spec: object, target: LocalCpuTarget, *, artifact_reader=None) -> N "InvalidExecutionSpec", stage="validate", message="illegal ExecutionSpec", field_errors=errors, ) + return bool(evaluation) + + +def _validate_fresh(spec, target, artifact_reader, evaluation): + """Validate fixed bytes and target support only for a request not yet registered.""" if evaluation: # Malformed or inconsistent bindings are refused here, before the RunStore sees the # request. The reader is the read-only port; H does not write or register anything. @@ -423,6 +424,12 @@ def validate(spec: object, target: LocalCpuTarget, *, artifact_reader=None) -> N ) +def validate(spec: object, target: LocalCpuTarget, *, artifact_reader=None) -> None: + """Validate a fresh request before registration; this port has no RunStore state.""" + evaluation = _validate_fields(spec) + _validate_fresh(spec, target, artifact_reader, evaluation) + + def _error(code: str, stage: str, message: str) -> dict: return {"code": code, "stage": stage, "message": message, "retryable": False} @@ -945,7 +952,7 @@ def _refusal(ctx, digest, binding, admission, bound, checks, errors, reason) -> ctx, request_digest=digest, target_binding=binding, bound_inputs=bound, phase="finished", started=False, process_outcome="not_started", exit_code=None, steps=[_not_started_step(step, reason) for step in ctx.spec["steps"]], - cancellation={"requested": False, "requested_at": None, "source": None}, + cancellation=_cancellation(ctx, []), cleanup=cleanup, checks=checks, budget_admission=admission, usage=_usage([]), resource_leases=leases, errors=errors, ) @@ -959,6 +966,16 @@ def _run_claimed(ctx, target, digest, reader, deadline, cancellation) -> dict: if errors: return _refusal(ctx, digest, binding, admission, [], [], errors, "admission_rejected") evaluation = ctx.spec["prepared_ref"] is not None + if evaluation: + if cancellation is not None and cancellation.is_set(): + ctx.cancel_seen_at = run_store.utc_now() + return _refusal(ctx, digest, binding, admission, [], [], [], "cancelled") + if time.monotonic() >= deadline: + return _refusal( + ctx, digest, binding, admission, [], [], + [_error("deadline_exhausted", "binding", "original attempt deadline exhausted")], + "deadline_exhausted", + ) entry_checks = [] if evaluation: entries = [_bind_entry(ctx, step, target) for step in ctx.spec["steps"]] @@ -1057,11 +1074,16 @@ def execute( cancellation=None, artifact_reader=None, ) -> dict: - """H ``execute``: register, admit, bind, run and commit one ordinary command request.""" - validate(spec, target, artifact_reader=artifact_reader) + """Execute one request or return its existing state before any new binding or start.""" + evaluation = _validate_fields(spec) + spec = copy.deepcopy(dict(spec)) digest = run_store.request_digest(spec) attempt = {name: copy.deepcopy(spec[name]) for name in ATTEMPT_FIELDS} - # Re-entry is decided by the store before any binding or start (V14 / D021 section 3). + 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) + # Another caller may have registered while the fixed preparation was read. claimed = store.claim(attempt, digest) if isinstance(claimed, run_store.CommittedRecord): return run_store.flatten(claimed, run_store.utc_now()) diff --git a/src/inferrsi/harness/run_store.py b/src/inferrsi/harness/run_store.py index 55d0ed205..d1dc0c457 100644 --- a/src/inferrsi/harness/run_store.py +++ b/src/inferrsi/harness/run_store.py @@ -1067,6 +1067,34 @@ def _seal_generation_input( ) from exc return values + def _reenter_if_registered( + self, attempt_id: str, request_digest: str, + ) -> CommittedRecord | None: + """Apply existing request state without registering or refreshing an attempt. + + Harness has checked the request's static shape and computed this digest. + A missing row permits fresh binding validation; ``claim`` still arbitrates + a concurrent registration after that validation finishes. + """ + lock_path = self.root / "locks" / f"{attempt_hash(attempt_id)}.lock" + try: + with self._connection() as conn, _transaction(conn): + row = conn.execute( + "SELECT * FROM attempts WHERE request_id = ?", (attempt_id,), + ).fetchone() + return None if row is None else self._reenter( + conn, row, request_digest, lock_path, + ) + except _IntegrityFault as error: + raise PublicError( + "RecordIntegrityError", stage="claim", attempt_id=attempt_id, message=str(error), + ) from error + except (sqlite3.Error, OSError, _StorageFault) as error: + raise PublicError( + "ExecutionPersistenceError", stage="claim", attempt_id=attempt_id, + started=None, message=f"request-state lookup failed: {_describe(error)}", + ) from error + def claim(self, attempt: Mapping, request_digest: str) -> Claim | CommittedRecord: """Register an attempt atomically, or apply the D021 re-entry table to its registration. diff --git a/tests/fixtures/harness-prepared-binding/README.md b/tests/fixtures/harness-prepared-binding/README.md index 5d6e17898..8d0d8b008 100644 --- a/tests/fixtures/harness-prepared-binding/README.md +++ b/tests/fixtures/harness-prepared-binding/README.md @@ -11,6 +11,7 @@ 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 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. +`tests/test_harness_entry_verification.py`; deadline/budget and T40 replay have +their own tests in `tests/test_harness_evaluation_replay.py`. Whole production +integration retains its separate acceptance dependencies. The original documentary fixtures are not rewritten. diff --git a/tests/test_harness_entry_verification.py b/tests/test_harness_entry_verification.py index d47c3302a..727c213f4 100644 --- a/tests/test_harness_entry_verification.py +++ b/tests/test_harness_entry_verification.py @@ -5,6 +5,7 @@ import subprocess import sys from copy import deepcopy +from datetime import datetime, timedelta, timezone from hashlib import sha256 from pathlib import Path @@ -26,10 +27,22 @@ @pytest.fixture -def evaluation(preparation, tmp_path): - service, request, sources, _, _, config, _ = preparation +def evaluation(preparation, tmp_path, request): + service, prepare_request, sources, protocol, _, config, _ = preparation + settings = getattr(request, "param", {}) + if "worker_code" in settings: + source = settings["worker_code"] + sources["worker-code"].write_bytes(source) + protocol = deepcopy(protocol) + digest = sha256(source).hexdigest() + protocol["worker_recipe"]["code_sha256"] = digest + resource = next(item for item in protocol["resources"] if item["role"] == "worker-code") + resource["artifact"].update(sha256=digest, size_bytes=len(source)) + service = benchmark.PreparationService( + protocol, resources=lambda role: sources[role].open("rb"), worker_role="worker-code", + ) output = api.prepare( - {"schema_version": 1, "request": request}, workspace=tmp_path, + {"schema_version": 1, "request": prepare_request}, workspace=tmp_path, storage_config=config, prepare_benchmark=service.prepare, encode_prepared=benchmark.encode, validate_prepared=benchmark.validate_prepared, ) @@ -38,6 +51,10 @@ def evaluation(preparation, tmp_path): prepared = read_prepared(config, ref) vector = decode((ROOT / "tests/fixtures/harness-prepared-binding/d023-null-timeout.json") .read_bytes()) + if "deadline_seconds" in settings: + vector["deadline_utc"] = ( + datetime.now(timezone.utc) + timedelta(seconds=settings["deadline_seconds"]) + ).isoformat().replace("+00:00", "Z") controller, modules = tmp_path / "controller", tmp_path / "modules" controller.mkdir() modules.mkdir() diff --git a/tests/test_harness_evaluation_replay.py b/tests/test_harness_evaluation_replay.py new file mode 100644 index 000000000..570b50087 --- /dev/null +++ b/tests/test_harness_evaluation_replay.py @@ -0,0 +1,343 @@ +"""Evaluation reentry is decided before preparation, target binding or a new launch.""" + +import json +import sqlite3 +import subprocess +import sys +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy + +import pytest + +from inferrsi.contracts.json_v1 import encode +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 +from tests.test_harness_entry_verification import evaluation as evaluation + + +def counts(case): + with sqlite3.connect(case["store"].root / run_store.INDEX_NAME) as connection: + return (connection.execute("SELECT count(*) FROM attempts").fetchone()[0], + connection.execute("SELECT count(*) FROM records").fetchone()[0]) + + +def replay_only(case, monkeypatch): + def forbidden(*args, **kwargs): + pytest.fail("replay attempted artifact IO, source binding, clock reset or execution") + + class Never: + open = forbidden + + monkeypatch.setattr(execution_service.local_process, "_supervise", forbidden) + monkeypatch.setattr(execution_service.entry_code, "capture_module", forbidden) + monkeypatch.setattr(execution_service, "_deadline_seconds", forbidden) + monkeypatch.setattr(execution_service, "_budget", forbidden) + monkeypatch.setattr(execution_service, "_capabilities", forbidden) + retired = LocalCpuTarget("retired", "2", work_root=case["target"].work_root / "retired") + return Harness(case["store"], retired, artifact_reader=Never()) + + +@pytest.mark.parametrize("initial", ["exited", "mismatch", "missing"]) +def test_completed_evaluation_replays_the_original_ref_without_rebinding( + evaluation, monkeypatch, initial, +): + case = evaluation + saved = deepcopy(case["spec"]) + source = case["modules"] / "fixture_worker.py" + if initial == "mismatch": + source.write_bytes(b"changed source\n") + elif initial == "missing": + source.unlink() + record = case["harness"].execute(saved) + assert record["started"] is (initial == "exited") + if initial == "exited": + assert record["exit_code"] == 0 + source.unlink() + else: + # Repairing the source does not authorize a new execution of this attempt. + source.write_bytes(case["source"]) + replayed = replay_only(case, monkeypatch).execute(saved) + assert replayed["record_ref"] == record["record_ref"] + assert replayed["target_binding"] == record["target_binding"] + assert replayed["request_digest"] == run_store.request_digest(saved) + assert replayed["budget_admission"] == record["budget_admission"] + assert saved == case["spec"] + assert counts(case) == (1, 1) + + +@pytest.mark.parametrize("field", ["deadline", "budget", "prepared-ref"]) +def test_changed_evaluation_digest_conflicts_without_any_binding(evaluation, monkeypatch, field): + case = evaluation + original = case["harness"].execute(case["spec"]) + changed = deepcopy(case["spec"]) + if field == "deadline": + changed["deadline_utc"] = "2098-01-01T00:00:00Z" + elif field == "budget": + changed["budget"]["scope_id"] = "another-scope" + else: + changed["prepared_ref"]["artifact"]["sha256"] = "0" * 64 + with pytest.raises(PublicError) as caught: + replay_only(case, monkeypatch).execute(changed) + assert caught.value.code == "RequestConflict" + assert counts(case) == (1, 1) + assert case["store"].read(original["attempt_id"])["record_ref"] == original["record_ref"] + + +def test_failed_commit_after_a_real_start_never_replays_the_worker(evaluation, monkeypatch): + case = evaluation + supervise = execution_service.local_process._supervise + observed = [] + + def counted(*args, **kwargs): + result = supervise(*args, **kwargs) + observed.append(result["pid"]) + return result + + monkeypatch.setattr(execution_service.local_process, "_supervise", counted) + monkeypatch.setattr(case["store"], "_append", + lambda *a, **k: (_ for _ in ()).throw(sqlite3.OperationalError("fixture"))) + with pytest.raises(PublicError) as failed: + case["harness"].execute(case["spec"]) + assert failed.value.code == "ExecutionPersistenceError" and failed.value.started is True + assert len(observed) == 1 and observed[0] is not None + assert counts(case) == (1, 0) + with pytest.raises(PublicError) as incomplete: + replay_only(case, monkeypatch).execute(case["spec"]) + assert incomplete.value.code == "RecoveryRequired" + assert incomplete.value.started is not False + assert counts(case) == (1, 0) and len(observed) == 1 + + +@pytest.mark.parametrize("live", [True, False], ids=["live-owner", "owner-gone"]) +def test_existing_attempt_without_a_record_never_implicitly_starts(evaluation, monkeypatch, live): + case = evaluation + attempt = {key: case["spec"][key] for key in execution_service.ATTEMPT_FIELDS} + claim = case["store"].claim(attempt, run_store.request_digest(case["spec"])) + try: + if not live: + claim.release() + with pytest.raises(PublicError) as caught: + replay_only(case, monkeypatch).execute(case["spec"]) + assert caught.value.code == ("AttemptInProgress" if live else "RecoveryRequired") + assert caught.value.latest_record_ref is None + assert counts(case) == (1, 0) + finally: + claim.release() + + +def test_caller_mutation_during_preparation_read_cannot_change_the_saved_request( + evaluation, +): + case = evaluation + original = deepcopy(case["spec"]) + + class Mutating: + def open(self, ref): + case["spec"]["budget"]["scope_id"] = "mutated-caller" + case["spec"]["output_root"] = "mutated-caller" + return case["reader"].open(ref) + + harness = Harness(case["store"], case["target"], artifact_reader=Mutating()) + result = harness.execute(case["spec"]) + assert result["request_digest"] == run_store.request_digest(original) + assert result["budget_admission"]["scope_id"] == original["budget"]["scope_id"] + assert result["started"] is True and result["exit_code"] == 0 + + +SLEEPING_WORKER = ( + b"import json,pathlib,subprocess,sys,time\n" + b"child=subprocess.Popen([sys.executable,'-I','-B','-c','import time; time.sleep(60)'])\n" + b"out=pathlib.Path(sys.argv[2]); out.parent.mkdir(parents=True,exist_ok=True)\n" + b"out.write_text(json.dumps({'child_pid':child.pid}),encoding='utf-8')\n" + b"time.sleep(60)\n" +) + + +def assert_confirmed_cleanup(record): + assert record["cleanup"]["status"] == "confirmed" + assert record["cleanup"]["process_exit_confirmed"] is True + assert record["resource_leases"]["leases"] + assert all(lease["release_confirmed"] is True + for lease in record["resource_leases"]["leases"]) + assert all(lease["release_confirmed_at"] is not None + for lease in record["resource_leases"]["leases"]) + + +@pytest.mark.parametrize("evaluation", [ + {"worker_code": SLEEPING_WORKER, "deadline_seconds": 3}, +], indirect=True) +def test_null_step_timeout_uses_original_attempt_deadline_and_cleans_the_domain(evaluation): + case = evaluation + saved = deepcopy(case["spec"]) + assert saved["steps"][0]["timeout_seconds"] is None + record = case["harness"].execute(saved) + assert record["started"] is True and record["process_outcome"] == "timed_out" + assert record["steps"][0]["status"] == "timed_out" + assert record["request_digest"] == run_store.request_digest(saved) + assert saved["deadline_utc"] == case["spec"]["deadline_utc"] + assert record["budget_admission"]["scope_id"] == saved["budget"]["scope_id"] + assert_confirmed_cleanup(record) + + +@pytest.mark.parametrize("evaluation", [ + {"worker_code": SLEEPING_WORKER, "deadline_seconds": 20}, +], indirect=True) +def test_live_cpu_replay_and_cancellation_preserve_identity_without_new_starts( + evaluation, monkeypatch, +): + case = evaluation + saved = deepcopy(case["spec"]) + cancellation = threading.Event() + command = execution_service.local_process._supervise + starts = [] + + def counted(*args, **kwargs): + starts.append(1) + return command(*args, **kwargs) + + monkeypatch.setattr(execution_service.local_process, "_supervise", counted) + marker = case["target"].work_root / "workspaces" / saved["output_root"] / "outputs/grader.json" + with ThreadPoolExecutor(max_workers=1) as pool: + original = pool.submit(case["harness"].execute, saved, cancellation=cancellation) + try: + stop = time.monotonic() + 10 + while not marker.exists() and not original.done() and time.monotonic() < stop: + time.sleep(0.01) + assert marker.exists(), "the real worker did not publish its running marker" + assert starts == [1] + assert counts(case) == (1, 0) + replay = replay_only(case, monkeypatch) + with pytest.raises(PublicError) as caught: + replay.execute(saved) + assert caught.value.code == "AttemptInProgress" + assert counts(case) == (1, 0) and starts == [1] + changed = deepcopy(saved) + changed["budget"]["scope_id"] = "conflict-during-run" + with pytest.raises(PublicError) as conflict: + replay.execute(changed) + assert conflict.value.code == "RequestConflict" + assert starts == [1] + finally: + cancellation.set() + record = original.result(timeout=15) + assert record["started"] is True and record["process_outcome"] == "cancelled" + assert record["cancellation"]["requested"] is True + assert record["cancellation"]["source"] == "caller" + assert_confirmed_cleanup(record) + again = replay.execute(saved) + assert again["record_ref"] == record["record_ref"] + assert counts(case) == (1, 1) and starts == [1] + + +@pytest.mark.parametrize("limit", ["expired", "cancelled", "budget"]) +def test_known_limits_refuse_before_source_capture_and_preserve_original_budget( + evaluation, monkeypatch, limit, +): + case = evaluation + saved = deepcopy(case["spec"]) + cancellation = threading.Event() + if limit == "expired": + saved["deadline_utc"] = "2000-01-01T00:00:00Z" + elif limit == "cancelled": + cancellation.set() + else: + saved["budget"]["dimensions"] = [ + {"dimension": "wall-time", "unit": "second", "limit": "1", "reserve_estimate": None}, + ] + + def forbidden(*args, **kwargs): + pytest.fail("a refused original limit reached source capture or process execution") + + monkeypatch.setattr(execution_service.entry_code, "capture_module", forbidden) + monkeypatch.setattr(execution_service.local_process, "_supervise", forbidden) + record = case["harness"].execute(saved, cancellation=cancellation) + assert record["started"] is False and record["process_outcome"] == "not_started" + assert record["request_digest"] == run_store.request_digest(saved) + assert record["budget_admission"]["scope_id"] == saved["budget"]["scope_id"] + if limit == "cancelled": + assert record["cancellation"]["requested"] is True + elif limit == "budget": + assert record["budget_admission"]["decision"] == "rejected" + assert all(item["reserved_capacity"] is None and item["charged_capacity"] is None + for item in record["budget_admission"]["dimensions"]) + assert counts(case) == (1, 1) + + +def test_completed_request_replays_in_a_new_controller_without_archive_or_target(evaluation): + case = evaluation + saved = deepcopy(case["spec"]) + record = case["harness"].execute(saved) + case["modules"].joinpath("fixture_worker.py").unlink() + script = ( + "import json,sys; from pathlib import Path; " + "from inferrsi.contracts.json_v1 import decode; " + "from inferrsi.harness import execution_service; " + "from inferrsi.harness.api import Harness,LocalCpuTarget; " + "from inferrsi.harness.run_store import RunStore; " + "s=RunStore(sys.argv[1],'test'); spec=decode(sys.stdin.buffer.read()); " + "target=LocalCpuTarget('retired','2',work_root=Path(sys.argv[1]).parent/'retired'); " + "execution_service.prepared_binding.verify=lambda *a,**k: " + "(_ for _ in ()).throw(RuntimeError('replay read preparation')); " + "execution_service.local_process._supervise=lambda *a,**k: " + "(_ for _ in ()).throw(RuntimeError('replay started a worker')); " + "r=Harness(s,target).execute(spec); " + "print(json.dumps([r['record_ref'],r['request_digest'],r['budget_admission']]))" + ) + child = subprocess.run( + [sys.executable, "-c", script, str(case["store"].root)], input=encode(saved), + check=True, capture_output=True, timeout=30, + ) + assert json.loads(child.stdout) == [ + record["record_ref"], record["request_digest"], record["budget_admission"], + ] + assert counts(case) == (1, 1) + + +def test_registration_race_after_lookup_still_uses_the_atomic_claim(evaluation, monkeypatch): + case = evaluation + saved = deepcopy(case["spec"]) + attempt = {key: saved[key] for key in execution_service.ATTEMPT_FIELDS} + held = [] + + class Racing: + def open(self, ref): + if not held: + held.append(case["store"].claim(attempt, run_store.request_digest(saved))) + return case["reader"].open(ref) + + monkeypatch.setattr(execution_service.local_process, "_supervise", + lambda *a, **k: pytest.fail("registration race started another worker")) + monkeypatch.setattr(execution_service.entry_code, "capture_module", + lambda *a, **k: pytest.fail("registration race bound a new entry")) + try: + with pytest.raises(PublicError) as caught: + Harness(case["store"], case["target"], artifact_reader=Racing()).execute(saved) + assert caught.value.code == "AttemptInProgress" + assert len(held) == 1 and counts(case) == (1, 0) + finally: + for claim in held: + claim.release() + + +@pytest.mark.parametrize("malformed", ["version", "missing-code"]) +def test_static_shape_errors_still_precede_existing_state_lookup( + evaluation, monkeypatch, malformed, +): + case = evaluation + original = case["harness"].execute(case["spec"]) + changed = deepcopy(case["spec"]) + if malformed == "version": + changed["schema_version"] = 2 + else: + del changed["steps"][0]["expected_code_sha256"] + monkeypatch.setattr(case["store"], "_reenter_if_registered", + lambda *a, **k: pytest.fail("malformed request queried existing state")) + with pytest.raises(PublicError) as caught: + case["harness"].execute(changed) + assert caught.value.code == ("UnsupportedSchema" if malformed == "version" + else "InvalidExecutionSpec") + assert case["store"].read(original["attempt_id"])["record_ref"] == original["record_ref"]