From 630685cd299241eccbb68ce6162f3e76483f0418 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:25:42 +0800 Subject: [PATCH 1/5] Retain interrupted optimization attempts safely Agent-assisted-by: Codex / unknown [effort=unknown] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- .gitattributes | 1 + docs/benchmarks/optimization-benchmarks.md | 16 +- pyproject.toml | 1 + src/inferrsi/apps/cli/arguments.py | 5 + src/inferrsi/apps/delivery/projection.py | 50 +- src/inferrsi/apps/views/dashboard_data.py | 19 +- .../apps/workflows/benchmark_compare.py | 4 +- src/inferrsi/harness/atomic_json.py | 24 +- src/inferrsi/harness/attempt_recovery.py | 122 +++++ src/inferrsi/harness/launch_records.py | 99 ++++ src/inferrsi/harness/local_process.py | 21 +- src/inferrsi/harness/optimization.py | 238 ++++++++-- src/inferrsi/harness/optimization_session.py | 65 ++- src/inferrsi/harness/session_runtime.py | 87 ++++ src/inferrsi/harness/task_protocol.py | 18 +- src/inferrsi/harness/trials/external.py | 3 + tests/apps/test_optimization_session.py | 429 +++++++++++++++++- tests/apps/test_project_optimization.py | 56 +++ tests/apps/test_project_service_reuse.py | 4 + tests/benchmark/test_benchmark_compare.py | 35 +- tests/fixtures/optimization-session/README.md | 3 +- .../pre-recovery-closure-session/calls.log | 1 + .../campaign.json | 6 + .../frozen/TASK.md | 1 + .../frozen/baseline.py | 1 + .../frozen/benchmark.py | 11 + .../frozen/optimization.py | 8 + .../pre-recovery-closure-session/plan.json | 63 +++ .../candidate.py | 1 + .../execution/execution.json | 20 + .../execution/stderr.log | 0 .../execution/stdout.log | 0 .../measurement/result.json | 1 + .../pre-recovery-closure-session/state.json | 44 ++ .../work/candidate.py | 1 + tests/fixtures/session_process.py | 53 +++ tests/repository/check_installed.py | 5 +- tests/repository/check_session_imports.py | 86 ++++ 38 files changed, 1475 insertions(+), 127 deletions(-) create mode 100644 src/inferrsi/harness/attempt_recovery.py create mode 100644 src/inferrsi/harness/launch_records.py create mode 100644 src/inferrsi/harness/session_runtime.py create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/calls.log create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/campaign.json create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/TASK.md create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/baseline.py create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/benchmark.py create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/optimization.py create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/plan.json create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/candidate.py create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/execution.json create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/stderr.log create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/stdout.log create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/measurement/result.json create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/state.json create mode 100644 tests/fixtures/optimization-session/pre-recovery-closure-session/work/candidate.py create mode 100644 tests/fixtures/session_process.py create mode 100644 tests/repository/check_session_imports.py diff --git a/.gitattributes b/.gitattributes index b3c39dd35..7b797e8c4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,6 +7,7 @@ # A session started by an older runtime keeps its exact bytes; its plan pins file hashes. /tests/fixtures/optimization-session/pre-infra-removal-session/** -text /tests/fixtures/optimization-session/pre-trials-rename-session/** -text +/tests/fixtures/optimization-session/pre-recovery-closure-session/** -text whitespace=cr-at-eol # Reusable guidance is editable text, not a frozen evidence bundle. /evidence/README.md text eol=lf /evidence/_template/** text eol=lf diff --git a/docs/benchmarks/optimization-benchmarks.md b/docs/benchmarks/optimization-benchmarks.md index 3c205a65b..76e45afe2 100644 --- a/docs/benchmarks/optimization-benchmarks.md +++ b/docs/benchmarks/optimization-benchmarks.md @@ -218,10 +218,18 @@ is retained separately from the per-round cumulative series. These are labelled caller exports. Monetary cost remains unknown. For an interrupted coordinator, run `session recover --session `. -It collects the existing execution record and task output and settles the same -attempt. Recovery performs no new candidate execution. If the execution record -is unavailable, inspect the original process and resource cleanup before further -action. Recovery also regenerates a summary from already settled state. +Recovery uses the existing execution receipt and task output to settle the same +attempt. An interrupted round without a complete result retains its candidate and +launch evidence, uses one planned round, and records `INCONCLUSIVE`. If final +evaluation is interrupted, inspect the retained attempt before explicitly running +`final` again within the original deadline. + +When a launch has no cleanup receipt, Linux recovery can check its recorded process +group from the same boot and PID namespace. A live or unconfirmed launch blocks +further execution. After inspecting and cleaning up every unconfirmed process and +resource, use `recover --confirm-domain-empty` to record that confirmation. Recovery +refuses confirmation while it can observe a live group. A settled session can also +regenerate its summary with `recover`. ## Ownership and future automatic Agent launch diff --git a/pyproject.toml b/pyproject.toml index c56aedd10..32e5c9a52 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -73,6 +73,7 @@ extend-exclude = [ "tests/fixtures/legacy", "tests/fixtures/optimization-session/pre-infra-removal-session", "tests/fixtures/optimization-session/pre-trials-rename-session", + "tests/fixtures/optimization-session/pre-recovery-closure-session", ] [tool.ruff.lint] diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 5842128f2..11f8ea2dc 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -251,6 +251,11 @@ def _optimization_actions(stages, *, project=False): help="JSON mechanism with expected region/counter directions") if name == "final": stage.add_argument("--reason", help="Why the caller stopped an up-to-budget search") + if name == "recover": + stage.add_argument( + "--confirm-domain-empty", action="store_true", + help="Attest that the interrupted optimization attempt has no live processes", + ) if name in ("round", "final"): stage.add_argument("--usage-export", type=Path) if project and name in ("round", "baseline", "refresh-references"): diff --git a/src/inferrsi/apps/delivery/projection.py b/src/inferrsi/apps/delivery/projection.py index a8db9337b..e8830fa61 100644 --- a/src/inferrsi/apps/delivery/projection.py +++ b/src/inferrsi/apps/delivery/projection.py @@ -296,7 +296,7 @@ def iterative(snapshot, result): if ( not isinstance(value, dict) or value.get("status") - not in ("completed", "candidate_failure", "infrastructure_failure") + not in ("completed", "candidate_failure", "infrastructure_failure", "interrupted") or value.get("verdict") not in ("PASS", "FAIL", "INCONCLUSIVE") ): value = None @@ -322,11 +322,22 @@ def iterative(snapshot, result): if record.get("candidate_sha256") else None ) - evidence_refs = [ - snapshot.file( + interrupted = (value or {}).get("status") == "interrupted" + execution = historical.get("execution") or {} + if interrupted: + recovery = historical.get("recovery") + evidence_refs = [] + if (isinstance(recovery, dict) and isinstance(recovery.get("path"), str) + and isinstance(recovery.get("sha256"), str)): + evidence_refs.append(snapshot.file( + recovery["path"], "recovery", recovery["sha256"] + )) + else: + gap(result, "RECOVERY_EVIDENCE_MISSING", ref, "Recovery evidence is unavailable") + else: + evidence_refs = [snapshot.file( directory + "/execution/execution.json", "execution", record.get("execution_sha256") - ) - ] + )] for name, expected in (value or {}).get("evidence_files", {}).items(): evidence_refs.append(snapshot.file(directory + "/" + name, "measurement", expected)) usage_source = (record.get("observations") or {}).get("usage_source") @@ -394,21 +405,34 @@ def iterative(snapshot, result): "knowledge_refs": record.get("knowledge_refs"), "knowledge_attribution": "agent_declared", "change_summary": record.get("change_summary"), - "execution_state": historical.get("execution", {}).get("status"), - "execution_returncode": historical.get("execution", {}).get("returncode"), + "execution_state": "interrupted" if interrupted else execution.get("status"), + "execution_returncode": execution.get("returncode"), "assessment_ref": assessment_ref, "assessment_provenance": provenance if value else None, "verdict": (value or {}).get("verdict"), "reason": (value or {}).get("reason"), "score": (value or {}).get("score"), "metric_refs": list(range(metric_start, len(result["metrics"]))), - "selection_decision": "retained" - if best_after.get("candidate_id") == (record.get("candidate_id")) - else "not_retained", + "selection_decision": ( + "interrupted" if interrupted else "retained" + if best_after.get("candidate_id") == record.get("candidate_id") + else "not_retained" + ), "best_candidate": best_after, "best_score": best_after.get("score"), } ) + for record in state.get("final_attempts", []): + directory = record["path"] + recovery = record["recovery"] + result.setdefault("final_attempts", []).append({ + "attempt_id": directory.rsplit("/", 1)[-1], + "status": "interrupted", + "assessment_ref": snapshot.file( + directory + "/observation.json", "assessment", record["observation_sha256"] + ), + "recovery_ref": snapshot.file(recovery["path"], "recovery", recovery["sha256"]), + }) if pending := state.get("pending"): result["rounds"].append( { @@ -441,6 +465,10 @@ def iterative(snapshot, result): "started_at": timestamp(state.get("started_at")), "ended_at": timestamp(state.get("settled_at")), } + if gate := state.get("cleanup_unconfirmed"): + result["execution"]["cleanup_unconfirmed"] = snapshot.file( + gate["path"], "recovery", gate["recovery_sha256"] + ) rounds_complete = ( len(rounds) == plan["round_limit"] if plan["round_mode"] == "exact" @@ -450,7 +478,7 @@ def iterative(snapshot, result): rounds_complete and final_value is not None and final_value.get("status") in ("completed", "candidate_failure") - and final_observation.get("execution", {}).get("status") in ("completed", "failed") + and (final_observation.get("execution") or {}).get("status") in ("completed", "failed") and state.get("pending") is None ) result["completion"] = { diff --git a/src/inferrsi/apps/views/dashboard_data.py b/src/inferrsi/apps/views/dashboard_data.py index f825a8c9a..cf5e3b24d 100644 --- a/src/inferrsi/apps/views/dashboard_data.py +++ b/src/inferrsi/apps/views/dashboard_data.py @@ -749,12 +749,16 @@ def _managed_dashboard(root: Path, campaign: dict) -> dict: gain = assessment.get("improvement_pct") if gain is None and speedup is not None: gain = (speedup - 1) * 100 - decision = ("adopted" if record["best_after"].get("candidate_id") == candidate_id + recovery = record.get("recovery") + decision = ("interrupted" if recovery else + "adopted" if record["best_after"].get("candidate_id") == candidate_id and record["best_after"]["kind"] == "candidate" else "rejected") - facts = file_ref(root, root / record["path"] / "execution/execution.json", "execution") + facts = (file_ref(root, root / recovery["path"], "recovery") if recovery else + file_ref(root, root / record["path"] / "execution/execution.json", "execution")) judged = file_ref(root, root / record["path"] / "observation.json", "assessment") row.update( - run_id=Path(record["path"]).name, state=record["execution"]["status"], + run_id=Path(record["path"]).name, + state="interrupted" if recovery else record["execution"]["status"], status_state="present", evaluation_state="present", verdict=assessment["verdict"], quality="failed" if assessment.get("quality_passed") is False else "passed" if assessment.get("quality_passed") is True else "not_recorded", @@ -768,7 +772,8 @@ def _managed_dashboard(root: Path, campaign: dict) -> dict: direction=(metrics["direction"] if metrics.get("direction") in ( "minimize", "maximize") else plan["selection"]["direction"]), decision=decision, - outcome="quality_failed" if assessment.get("quality_passed") is False else + outcome="interrupted" if recovery else + "quality_failed" if assessment.get("quality_passed") is False else "unverified", # No synthetic environment qualification or noise estimate. artifacts={**row["artifacts"], "execution": facts, "assessment": judged, "status": facts, "evaluation": judged}, @@ -797,6 +802,12 @@ def _managed_dashboard(root: Path, campaign: dict) -> dict: displayed_summary["final_reference"] = ( file_ref(root, root / state["final"]["path"] / "observation.json", "final_assessment") if state["final"] else None) + if attempts := state.get("final_attempts"): + displayed_summary["interrupted_finals"] = [ + file_ref(root, root / record["recovery"]["path"], "recovery") for record in attempts + ] + if gate := state.get("cleanup_unconfirmed"): + displayed_summary["cleanup_unconfirmed"] = file_ref(root, root / gate["path"], "recovery") return { "campaign_id": sanitized_text(campaign["campaign_id"]), "synthetic": False, "rounds": rounds, "rounds_state": "present", "corrupt_round_lines": [], diff --git a/src/inferrsi/apps/workflows/benchmark_compare.py b/src/inferrsi/apps/workflows/benchmark_compare.py index bc1319ea6..a385a3e0e 100644 --- a/src/inferrsi/apps/workflows/benchmark_compare.py +++ b/src/inferrsi/apps/workflows/benchmark_compare.py @@ -829,7 +829,9 @@ def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=Non "knowledge_attribution": "agent_declared; delivery is not proof of use", "speedup": assessment.get("speedup", assessment.get("score")), "best_speedup": record["best_after"]["score"], "quality": assessment["verdict"], - "adopted": record["best_after"].get("candidate_id") == record["candidate_id"], + "assessment_status": assessment["status"], + "adopted": (assessment["status"] != "interrupted" and + record["best_after"].get("candidate_id") == record["candidate_id"]), }) if (host["state"] != "completed" or not delivery["acceptance"]["delivery_accepted"] or delivery["completion"]["status"] != "completed"): diff --git a/src/inferrsi/harness/atomic_json.py b/src/inferrsi/harness/atomic_json.py index 42d3606ac..4e051fad5 100644 --- a/src/inferrsi/harness/atomic_json.py +++ b/src/inferrsi/harness/atomic_json.py @@ -13,22 +13,36 @@ REPLACE_DELAY_SECONDS = 0.05 -def atomic_write_json(path: Path, value: object) -> None: +def sync_directory(path: Path) -> None: + if os.name == "posix": + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def atomic_write_json(path: Path, value: object, *, durable: bool = False) -> None: path = Path(path) # A per-writer temporary name keeps two writers from sharing one file. temporary = path.with_name(f"{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp") - temporary.write_text( - json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8" - ) + payload = json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n" try: + with temporary.open("w", encoding="utf-8") as stream: + stream.write(payload) + if durable: + stream.flush() + os.fsync(stream.fileno()) for attempt in range(REPLACE_ATTEMPTS): try: temporary.replace(path) - return + break except PermissionError: if attempt + 1 == REPLACE_ATTEMPTS: raise time.sleep(REPLACE_DELAY_SECONDS) + if durable: + sync_directory(path.parent) finally: if temporary.exists(): temporary.unlink() diff --git a/src/inferrsi/harness/attempt_recovery.py b/src/inferrsi/harness/attempt_recovery.py new file mode 100644 index 000000000..17d61866e --- /dev/null +++ b/src/inferrsi/harness/attempt_recovery.py @@ -0,0 +1,122 @@ +"""Retain cleanup observations independently of execution and assessment receipts.""" + +import hashlib +import json +import time +import uuid +from pathlib import Path + +from .atomic_json import atomic_write_json +from .launch_records import observe +from .records.evidence import bounded_record_bytes + +_CLEAR = {"not_spawned", "recorded_empty", "observed_empty"} +_FIELDS = ( + "state", "argv_sha256", "platform", "intent_at", "boot_id", "pid_namespace", + "spawned", "pid", "process_group_id", "started_at", "ended_at", "status", "domain_empty", +) + + +def _entries(root, directory, prefix): + try: + if any(parent.is_symlink() for parent in (directory, *directory.parents) + if parent.is_relative_to(root) and parent != root): + raise ValueError("Unsafe launch directory") + return { + path.relative_to(root).as_posix() for path in directory.iterdir() + if path.name.startswith(prefix) and path.suffix == ".json" + } + except FileNotFoundError: + return set() + + +def _launch(root, path): + raw, state = bounded_record_bytes(root, path, 16 * 1024) + stage = Path(path).stem + result = {"path": path, "stage": stage, "sha256": None, "observation": state} + if raw is None: + return result + result["sha256"] = hashlib.sha256(raw).hexdigest() + try: + record = json.loads(raw) + if (not isinstance(record, dict) or record.get("schema_version") != 1 + or record.get("stage") != stage): + raise ValueError("Invalid launch record") + except (ValueError, RecursionError): + result["observation"] = "invalid_record" + else: + result["record"] = {key: record[key] for key in _FIELDS if key in record} + result["observation"] = observe(record) + return result + + +def scan(root, attempt, *, receipt_present, earlier=()): + """Observe every stage before the coordinator can start another child.""" + directory = root / attempt + paths = {entry["path"] for entry in earlier if entry["path"]} + entries = [] + for location, prefix in ((directory, "protocol-"), (directory / "execution", "launch-")): + try: + paths.update(_entries(root, location, prefix)) + except (OSError, ValueError): + entries.append({"path": None, "stage": prefix.rstrip("-"), "sha256": None, + "observation": "unreadable_directory"}) + entries.extend(_launch(root, path) for path in sorted(paths)) + # Legacy attempts with an execution receipt may have no launch files. + if not entries and not receipt_present: + entries.append({"path": None, "stage": "unknown", "sha256": None, + "observation": "no_launch_record"}) + return entries + + +def retained(root, reference, attempt): + raw, _ = bounded_record_bytes(root, reference["path"], 1024 * 1024) + if raw is None or hashlib.sha256(raw).hexdigest() != reference["sha256"]: + raise ValueError("Retained recovery record changed") + record = json.loads(raw) + if (record.get("schema_version") != 1 or record.get("session") != root.name + or record.get("attempt") != attempt): + raise ValueError("Retained recovery record belongs to another attempt") + return record + + +def _write(root, path, attempt, **detail): + full = root / path + full.parent.mkdir(parents=True, exist_ok=True) + atomic_write_json(full, {"schema_version": 1, "session": root.name, "attempt": attempt, + "observed_at": time.time(), **detail}, durable=True) + return {"path": path, "sha256": hashlib.sha256(full.read_bytes()).hexdigest()} + + +def capture(root, attempt, launches, receipt_present): + path = f"{attempt}/recovery.json" + if (root / path).exists(): + path = f"{attempt}/recovery-{uuid.uuid4().hex}.json" + return _write(root, path, attempt, launches=launches, execution_receipt_present=receipt_present) + + +def _identity(entry): + return entry["path"], entry["stage"], entry["sha256"], entry["observation"] + + +def unconfirmed(root, state, attempt, launches): + acknowledged = set() + for reference in state.get("recovery_confirmations", ()): + if reference["attempt"] == attempt: + proof = retained(root, reference, attempt) + acknowledged.update(_identity(entry) for entry in proof["confirmed_stages"]) + return [entry for entry in launches if entry["observation"] not in _CLEAR and ( + entry["observation"] in ("live", "unreadable_directory") + or _identity(entry) not in acknowledged + )] + + +def confirm(root, state, gate, launches, blocked, *, manual): + if any(entry["observation"] == "live" for entry in launches): + raise ValueError("Cannot confirm cleanup while a recorded process group is live") + attempt = gate["attempt"] + ref = _write(root, f"recoveries/confirm-{uuid.uuid4().hex}.json", attempt, + recovery_sha256=gate["recovery_sha256"], + basis="manual" if manual else "observed_empty", launches=launches, + confirmed_stages=blocked if manual else []) + state.setdefault("recovery_confirmations", []).append({**ref, "attempt": attempt}) diff --git a/src/inferrsi/harness/launch_records.py b/src/inferrsi/harness/launch_records.py new file mode 100644 index 000000000..07f0c3cbb --- /dev/null +++ b/src/inferrsi/harness/launch_records.py @@ -0,0 +1,99 @@ +"""Durable launch facts for recoverable optimization attempts.""" + +import json +import os +import sys +from datetime import datetime, timezone +from itertools import count +from pathlib import Path + +from .artifact_primitives import digest +from .atomic_json import atomic_write_json, sync_directory + + +def linux_process_domain() -> tuple[str | None, str | None]: + if sys.platform != "linux": + return None, None + try: + boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip() + namespace = os.readlink("/proc/self/ns/pid") + except (OSError, UnicodeError): + return None, None + return boot_id or None, namespace or None + + +class LaunchRecord: + """Publish intent before spawning and retain the supervisor's observations.""" + + def __init__(self, path: Path, argv: list[str]): + self.path = path + boot_id, namespace = linux_process_domain() + self.record = { + "schema_version": 1, + "stage": path.stem, + "state": "intent", + "argv_sha256": digest(argv), + "platform": sys.platform, + "intent_at": datetime.now(timezone.utc).isoformat(), + "boot_id": boot_id, + "pid_namespace": namespace, + } + with path.open("x", encoding="utf-8") as stream: + json.dump(self.record, stream, indent=2) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + sync_directory(path.parent) + + @classmethod + def numbered(cls, directory: Path, stage: str, argv: list[str]) -> "LaunchRecord": + for index in count(1): + try: + return cls(directory / f"{stage}-{index:04d}.json", argv) + except FileExistsError: + continue + + def launched(self, run: dict) -> None: + self.record.update( + state="launched", spawned=True, pid=run["pid"], + process_group_id=run["process_group_id"], started_at=run["started_at"], + ) + atomic_write_json(self.path, self.record, durable=True) + + def ended(self, run: dict, spawned: bool | None) -> None: + self.record.update( + state="ended", spawned=spawned, pid=run["pid"], + process_group_id=run["process_group_id"], started_at=run["started_at"], + ended_at=run["ended_at"], status=run["status"], domain_empty=run["domain_empty"], + ) + atomic_write_json(self.path, self.record, durable=True) + + +def observe(record: dict) -> str: + """Use an empty-group probe only within its recorded Linux boot and PID namespace.""" + state = record.get("state") + if state == "intent": + return "launch_unconfirmed" + if state not in ("launched", "ended"): + return "invalid_record" + pid, group = record.get("pid"), record.get("process_group_id") + if state == "ended" and record.get("spawned") is False: + return "not_spawned" if pid is None and group is None else "invalid_record" + if record.get("spawned") is not True or type(pid) is not int or pid <= 0: + return "launch_unconfirmed" + if state == "ended" and record.get("domain_empty") is True: + return "recorded_empty" + if (record.get("platform") != "linux" or sys.platform != "linux" + or type(group) is not int or group != pid): + return "unobservable" + boot_id, namespace = linux_process_domain() + if (not boot_id or not namespace or boot_id != record.get("boot_id") + or namespace != record.get("pid_namespace")): + return "unobservable" + try: + os.killpg(group, 0) + except ProcessLookupError: + return "observed_empty" + except OSError: + return "unobservable" + return "live" diff --git a/src/inferrsi/harness/local_process.py b/src/inferrsi/harness/local_process.py index a92cfb5b8..134237ebb 100644 --- a/src/inferrsi/harness/local_process.py +++ b/src/inferrsi/harness/local_process.py @@ -7,6 +7,7 @@ from pathlib import Path from .atomic_json import atomic_write_json +from .launch_records import LaunchRecord # H local process control domain (moved from infra in H02): one command inside its # Windows Job or POSIX process group, deadline and cancellation, and tree cleanup. @@ -257,6 +258,7 @@ def _supervise( *, cancellation=None, step_limited: bool = False, + launch: LaunchRecord | None = None, ) -> dict: """Run one command inside its own process domain and return the observed facts. @@ -282,11 +284,13 @@ def _supervise( "elapsed_seconds": None, } started, process, windows_job, attached, launched = time.monotonic(), None, None, False, None + spawned = None timeout_before_launch = ("step timeout expired before command start" if step_limited else "whole-run deadline exhausted before command start") try: remaining = deadline - started if remaining <= 0: + spawned = False run.update(status="timeout", error=timeout_before_launch) else: options = ( @@ -298,10 +302,12 @@ def _supervise( windows_job = _WindowsJob() with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr: if cancellation is not None and cancellation.is_set(): + spawned = False run.update(status="cancelled", error="cancellation requested", cancellation_requested_at=_utc_now(), cancellation_source="caller") return run if time.monotonic() >= deadline: + spawned = False run.update(status="timeout", error=timeout_before_launch) return run process = subprocess.Popen( @@ -314,6 +320,7 @@ def _supervise( shell=False, **options, ) + spawned = True launched = time.monotonic() run["started_at"] = _utc_now() run["pid"] = process.pid @@ -321,6 +328,8 @@ def _supervise( if windows_job is not None: windows_job.attach(process) attached = True + if launch is not None: + launch.launched(run) try: _wait(process, deadline, cancellation) run.update( @@ -373,13 +382,17 @@ def _supervise( windows_job.emptied if windows_job is not None else _group_empty(process.pid) ) run["ended_at"] = _utc_now() - run["process_seconds"] = time.monotonic() - launched + if launched is not None: + run["process_seconds"] = time.monotonic() - launched run["elapsed_seconds"] = time.monotonic() - started + if launch is not None: + launch.ended(run, spawned) return run def execute_command(command: tuple[str, ...], cwd: Path, trial_dir: Path, deadline: float, *, - environment: dict | None = None, include_cleanup: bool = False) -> dict: + environment: dict | None = None, include_cleanup: bool = False, + launch_path: Path | None = None) -> dict: """Legacy trial record: execute argv under a whole-run deadline in trial_dir.""" trial_dir.mkdir(parents=True) result_path = trial_dir / "result.json" @@ -397,8 +410,10 @@ def execute_command(command: tuple[str, ...], cwd: Path, trial_dir: Path, deadli } environment = os.environ.copy() if environment is None else environment.copy() environment["INFERRSI_RESULT_PATH"] = str(result_path) + options = {"launch": LaunchRecord(launch_path, argv)} if launch_path is not None else {} run = _supervise( - argv, cwd, environment, trial_dir / "stdout.log", trial_dir / "stderr.log", deadline + argv, cwd, environment, trial_dir / "stdout.log", trial_dir / "stderr.log", deadline, + **options, ) # Same keys, order and values as the record built before H02. record.update(status=run["status"], returncode=run["returncode"]) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 8908ac270..3fc368711 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -7,7 +7,7 @@ import uuid from pathlib import Path -from . import candidates +from . import attempt_recovery, candidates from .artifact_primitives import digest, file_lock, sha256 from .atomic_json import atomic_write_json from .records.evidence import bounded_record_bytes, sanitized_text @@ -108,19 +108,30 @@ def _read_context(root, reference): return record +class _FrozenInputError(ValueError): + pass + + +def _validate_frozen(root, plan): + frozen = root / "frozen" + try: + paths = list(frozen.rglob("*")) + if frozen.is_symlink() or any(path.is_symlink() for path in paths): + raise ValueError("Frozen task resources cannot contain symbolic links") + actual = {p.relative_to(frozen).as_posix(): sha256(p) for p in paths if p.is_file()} + if actual != plan["frozen_files"]: + raise ValueError("Frozen task resources changed (content or file set)") + if candidates.identity(root / plan["baseline_path"]) != plan["baseline_sha256"]: + raise ValueError("Frozen baseline changed") + except (OSError, ValueError) as error: + raise _FrozenInputError(str(error)) from error + + def _load(root, *, read_only=False): plan, state = _control(root) if plan.get("evaluation_mode") == "service_reuse": return _service_load(root, plan, state, read_only=read_only) - frozen = root / "frozen" - paths = list(frozen.rglob("*")) - if frozen.is_symlink() or any(path.is_symlink() for path in paths): - raise ValueError("Frozen task resources cannot contain symbolic links") - actual = {p.relative_to(frozen).as_posix(): sha256(p) for p in paths if p.is_file()} - if actual != plan["frozen_files"]: - raise ValueError("Frozen task resources changed (content or file set)") - if candidates.identity(root / plan["baseline_path"]) != plan["baseline_sha256"]: - raise ValueError("Frozen baseline changed") + _validate_frozen(root, plan) if candidates.identity(root / state["best"]["path"]) != state["best"]["sha256"]: raise ValueError("Selected candidate changed") diagnoses = _diagnosis_index(state) @@ -130,7 +141,8 @@ def _load(root, *, read_only=False): if context.get("kind") not in ("external_search", "external_read"): _check_context_diagnosis(plan, diagnoses, context, retained) contexts[context["path"]] = context - for record in [*state["rounds"], *([state["final"]] if state["final"] else [])]: + for record in [*state["rounds"], *state.get("final_attempts", ()), + *([state["final"]] if state["final"] else [])]: directory = root / record["path"] raw = (directory / "observation.json").read_bytes() if hashlib.sha256(raw).hexdigest() != record["observation_sha256"]: @@ -148,7 +160,7 @@ def _load(root, *, read_only=False): path = ref.partition("#")[0] if path not in submitted or submitted[path] != contexts.get(path): raise ValueError("Cited knowledge context differs from the submitted snapshot") - if record is not state["final"] and ( + if record["kind"] == "round" and ( plan.get("diagnosis_required") or diagnoses or record.get("diagnosis_id") ): if observation.get("diagnosis_id") != record.get("diagnosis_id"): @@ -156,7 +168,12 @@ def _load(root, *, read_only=False): _check_activity_diagnosis(plan, diagnoses, observation) if candidates.identity(directory / plan["candidate_name"]) != record["candidate_sha256"]: raise ValueError("Retained round candidate changed") - if sha256(directory / "execution/execution.json") != record["execution_sha256"]: + if record["assessment"]["status"] == "interrupted": + if (record["execution"] is not None or observation.get("execution") is not None + or observation.get("recovery") != record.get("recovery")): + raise ValueError("Interrupted attempt differs from its retained observation") + attempt_recovery.retained(root, record["recovery"], record["path"]) + elif sha256(directory / "execution/execution.json") != record["execution_sha256"]: raise ValueError("Retained execution record changed") source = record["observations"]["usage_source"] if source and sha256(directory / "agent-usage.json") != source["sha256"]: @@ -164,6 +181,10 @@ def _load(root, *, read_only=False): for name, expected in record["assessment"].get("evidence_files", {}).items(): if sha256(directory / name) != expected: raise ValueError("Retained task evidence changed") + if gate := state.get("cleanup_unconfirmed"): + _recovery_snapshot(root, gate) + for reference in state.get("recovery_confirmations", ()): + attempt_recovery.retained(root, reference, reference["attempt"]) return plan, state @@ -172,44 +193,67 @@ def status(root: Path) -> dict: if plan.get("evaluation_mode") == "service_reuse": plan, control = _service_load(root, plan, control, read_only=True) return _service_status(root, plan, control) - _, control = _control(root) if control["state"] == "blocked" and control.get("integrity_error"): # A diagnostic is still readable after rejected input drift. Never expose # a selected score or a usable summary from an invalid evidence tree. return {"session": str(root), "state": "blocked", "next_action": "blocked", "can_finalize": False, "pending": control["pending"], "integrity_error": control["integrity_error"], "summary": None} - plan, state = _load(root) + try: + plan, state = _load(root) + except _FrozenInputError: + if control["pending"] is None: + raise + with _locked(root): + plan, control = _control(root) + try: + _validate_frozen(root, plan) + except _FrozenInputError as error: + if control["pending"] is not None: + return _reject_frozen_attempt(root, plan, control, error) + if not control.get("integrity_error"): + raise + return status(root) next_action = ( "record_bottleneck_diagnosis" if plan.get("diagnosis_required") and not _diagnosis(state) else "edit_candidate_and_submit_round" ) - if len(state["rounds"]) == plan["round_limit"]: + final_eligible = bool(state["rounds"]) and ( + plan["round_mode"] == "up_to" or len(state["rounds"]) == plan["round_limit"] + ) + if len(state["rounds"]) == plan["round_limit"] or ( + state.get("final_attempts") and final_eligible + ): next_action = "independently_retest_selected_candidate_with_final" - search_remaining = state["deadline"] - time.time() - plan["final_reserve_seconds"] + remaining = state["deadline"] - time.time() + search_remaining = remaining - plan["final_reserve_seconds"] if search_remaining <= 0 and state["final"] is None: next_action = ("independently_retest_selected_candidate_with_final" - if state["rounds"] and plan["round_mode"] == "up_to" + if final_eligible else "search_budget_exhausted_incomplete_session") - if time.time() >= state["deadline"] and state["final"] is None: + if remaining <= 0 and state["final"] is None: next_action = "deadline_exhausted_incomplete_session" if state["pending"] is not None: next_action = "recover_existing_attempt_without_relaunch" if state["state"] in ("completed", "blocked"): next_action = state["state"] + gate = state.get("cleanup_unconfirmed") + if gate is not None: + next_action = "confirm_interrupted_process_cleanup" return { "session": str(root), "state": state["state"], "next_action": next_action, "completed_rounds": len(state["rounds"]), "round_limit": plan["round_limit"], - "remaining_seconds": max(0, state["deadline"] - time.time()), + "remaining_seconds": max(0, remaining), "remaining_search_seconds": max(0, search_remaining), "round_mode": plan["round_mode"], "can_finalize": (state["state"] == "active" and state["pending"] is None - and time.time() < state["deadline"] and bool(state["rounds"]) - and (plan["round_mode"] == "up_to" - or len(state["rounds"]) == plan["round_limit"])), + and remaining > 0 and final_eligible), "task_instructions": str(root / "frozen/TASK.md"), "working_candidate": str(root / plan["working_candidate"]), "best": state["best"], "pending": state["pending"], + **({"cleanup_unconfirmed": gate, "recovery_command": "recover --confirm-domain-empty"} + if gate is not None else {}), + **({"final_attempts": state["final_attempts"]} if state.get("final_attempts") else {}), **({"external_knowledge": plan["external_knowledge"]} if "external_knowledge" in plan else {}), "latest_observation": state["rounds"][-1] if state["rounds"] else None, @@ -546,7 +590,10 @@ def _settle(root, plan, state, pending, execution, assess): if state.get("integrity_error"): raise ValueError(state["integrity_error"]) if execution.get("coordinator_error"): - raise ValueError(execution["coordinator_error"]) + message = execution["coordinator_error"] + if error_type := execution.get("coordinator_error_type"): + raise TaskProtocolError("protocol_exception", message, error_type=error_type) + raise ValueError(message) # A task result cannot override an interrupted or unknown execution. # A normal nonzero exit may carry a deliberate candidate rejection. if (execution.get("status") not in ("completed", "failed") @@ -580,14 +627,15 @@ def _settle(root, plan, state, pending, execution, assess): if (type(baseline_score) not in (int, float) or not math.isfinite(baseline_score) or baseline_score <= 0): raise ValueError("The task must supply the measured baseline objective") - except Exception as error: + except (Exception, SystemExit) as error: assessment = _failure(error) score = assessment.get("score") # Normalized so every record carries the key, even for a scoreless ineligible round. assessment["score"] = score if assessment["status"] == "completed" else None record = {**pending, "assessment": assessment, "execution": execution, - "execution_sha256": sha256(directory / "execution/execution.json"), - "elapsed_seconds": execution.get("elapsed_seconds")} + "execution_sha256": (sha256(directory / "execution/execution.json") + if execution is not None else None), + "elapsed_seconds": (execution or {}).get("elapsed_seconds")} if pending["kind"] == "round": best_score = state["best"]["score"] if best_score is None and assessment["status"] == "completed": @@ -617,12 +665,17 @@ def _settle(root, plan, state, pending, execution, assess): state["state"] = "completed" if assessment["status"] == "completed" else "blocked" if assessment["status"] == "infrastructure_failure": state["state"] = "blocked" + return _publish_attempt(root, plan, state, record) + + +def _publish_attempt(root, plan, state, record): if state["state"] in ("completed", "blocked"): state["settled_at"] = time.time() state["pending"] = None - atomic_write_json(directory / "observation.json", record) - record["observation_sha256"] = sha256(directory / "observation.json") - atomic_write_json(root / "state.json", state) + observation = root / record["path"] / "observation.json" + atomic_write_json(observation, record, durable=True) + record["observation_sha256"] = sha256(observation) + atomic_write_json(root / "state.json", state, durable=True) summary = _summary(root, plan, state) if state.get("integrity_error"): summary.update(integrity_error=state["integrity_error"], optimization_speedup=None, @@ -700,11 +753,11 @@ def evaluate_round(root: Path, *, candidate: Path | None, hypothesis: str, state["pending"] = pending if final: state["stop_reason"] = reason or "fixed_round_budget_completed" - atomic_write_json(root / "state.json", state) + atomic_write_json(root / "state.json", state, durable=True) deadline = state["deadline"] - (0 if final else plan["final_reserve_seconds"]) try: execution = execute(root, directory, plan, deadline) - except Exception as error: + except (Exception, SystemExit) as error: # A completed child may have persisted its receipt before the caller # failed. Collect it without launching the same candidate again. path = directory / "execution/execution.json" @@ -715,6 +768,8 @@ def evaluate_round(root: Path, *, candidate: Path | None, hypothesis: str, else: execution = {"status": "error", "returncode": None, "coordinator_error": str(error), "cleanup_verified": None} + if _type_name(error) == "SystemExit": + execution["coordinator_error_type"] = "SystemExit" # No receipt does not prove termination. The resulting blocked # session cannot launch more work or claim device cleanup. path.parent.mkdir(exist_ok=True) @@ -733,28 +788,113 @@ def read_records(root: Path) -> tuple[dict, dict, dict]: return plan, state, summary -def recover(root: Path, assess) -> dict: +def _recovery_snapshot(root, gate): + return attempt_recovery.retained( + root, {"path": gate["path"], "sha256": gate["recovery_sha256"]}, gate["attempt"] + ) + + +def _reject_frozen_attempt(root, plan, state, error): + pending = state["pending"] + path = root / pending["path"] / "execution/execution.json" + try: + execution = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + execution = None + if not isinstance(execution, dict): + execution = None + state["integrity_error"] = str(error) + state.pop("cleanup_unconfirmed", None) + return _settle(root, plan, state, pending, execution, None) + + +def _interrupted(root, plan, state, pending, reference): + record = { + **pending, "execution": None, "execution_sha256": None, "elapsed_seconds": None, + "assessment": {"status": "interrupted", "verdict": "INCONCLUSIVE", "score": None, + "reason": "Coordinator stopped before retaining an execution receipt"}, + "recovery": reference, + "selection": {"outcome": "interrupted", "metric": plan["selection"]["metric"], + "score": None, "best_score_before": state["best"]["score"]}, + "best_after": dict(state["best"]), + } + if pending["kind"] == "round": + state["rounds"].append(record) + else: + state.setdefault("final_attempts", []).append(record) + return _publish_attempt(root, plan, state, record) + + +def _recover_attempt(root, plan, state, assess, *, manual): + pending = state["pending"] + gate = state.get("cleanup_unconfirmed") + attempt = gate["attempt"] if gate else pending["path"] + path = root / attempt / "execution/execution.json" + receipt_present = pending is not None and path.is_file() + earlier = list(_recovery_snapshot(root, gate)["launches"]) if gate else [] + for reference in state.get("recovery_confirmations", ()): + if reference["attempt"] == attempt: + earlier.extend(attempt_recovery.retained(root, reference, attempt)["launches"]) + launches = attempt_recovery.scan( + root, attempt, receipt_present=receipt_present, earlier=earlier, + ) + blocked = attempt_recovery.unconfirmed(root, state, attempt, launches) + if gate is None and (blocked or not receipt_present): + reference = attempt_recovery.capture(root, attempt, launches, receipt_present) + if blocked: + state["state"] = "blocked" + state["cleanup_unconfirmed"] = { + "attempt": attempt, "path": reference["path"], + "recovery_sha256": reference["sha256"], + "stages": [entry["stage"] for entry in blocked], + } + if not receipt_present: + return _interrupted(root, plan, state, pending, reference) + atomic_write_json(root / "state.json", state, durable=True) + return status(root) + if gate is not None: + if blocked and not manual: + return status(root) + if any(entry["observation"] == "unreadable_directory" for entry in blocked): + raise ValueError("Cannot confirm cleanup until the launch directory is readable") + attempt_recovery.confirm(root, state, gate, launches, blocked, manual=manual) + del state["cleanup_unconfirmed"] + state.pop("settled_at", None) + state["state"] = "active" + # Persist the release before assessment can create a new launch record. + atomic_write_json(root / "state.json", state, durable=True) + if pending is None: + atomic_write_json(root / "summary.json", _summary(root, plan, state)) + return status(root) + if not receipt_present: + return _interrupted(root, plan, state, pending, { + "path": gate["path"], "sha256": gate["recovery_sha256"], + }) + execution = json.loads(path.read_text(encoding="utf-8")) + if pending.get("mechanism") is not None or pending.get("mechanism_sha256") is not None: + # An interrupted attempt cannot prove which declaration was bound to execution. + pending = {**pending, "mechanism": None, "mechanism_sha256": None, + "mechanism_unverified_after_recovery": True} + return _settle(root, plan, state, pending, execution, assess) + + +def recover(root: Path, assess, *, confirm_domain_empty=False) -> dict: with _locked(root): - _, control = _control(root) + control_plan, control = _control(root) if control["state"] == "blocked" and control.get("integrity_error"): return status(root) - plan, state = _load(root) - pending = state["pending"] - if pending is None: + try: + plan, state = _load(root) + except _FrozenInputError as error: + if control["pending"] is None: + raise + return _reject_frozen_attempt(root, control_plan, control, error) + if confirm_domain_empty and not state.get("cleanup_unconfirmed"): + raise ValueError("No interrupted cleanup is awaiting confirmation") + if state["pending"] is None and not state.get("cleanup_unconfirmed"): atomic_write_json(root / "summary.json", _summary(root, plan, state)) return status(root) - path = root / pending["path"] / "execution/execution.json" - if not path.is_file(): - raise ValueError("Execution record unavailable, inspect cleanup before recovery") - execution = json.loads(path.read_text(encoding="utf-8")) - if pending.get("mechanism") is not None or pending.get("mechanism_sha256") is not None: - # The candidate ran with write access to every file that could hold the - # declaration after submission, so an interrupted attempt cannot prove which - # declaration was bound. Settle it without one: the explanation is reported as - # not declared and, under require_explanation, the round is not adopted. - pending = {**pending, "mechanism": None, "mechanism_sha256": None, - "mechanism_unverified_after_recovery": True} - return _settle(root, plan, state, pending, execution, assess) + return _recover_attempt(root, plan, state, assess, manual=confirm_domain_empty) def _service_initialize(root, plan): diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index ad4e379ab..e37dc099f 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -10,7 +10,9 @@ import shlex import sys import time +from functools import partial from importlib.resources import files +from itertools import count from pathlib import Path @@ -35,16 +37,19 @@ def _session_execute(root, directory, plan, deadline): return _project_execute(root, directory, plan, deadline) task = root / "frozen" arguments = run_protocol(task, plan["frozen_files"]["optimization.py"], "arguments", + launch_directory=directory, candidate=directory / "candidate.py", output=directory / "measurement", settings=plan["evaluation_settings"]) + execution = directory / "execution" command = (*plan["evaluation_prefix"], plan["python"], str(Path(__file__).resolve()), + "--session-launch-directory", str(execution), str(task / "benchmark.py"), *arguments) timeout = min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time())) - environment = runtime_environment() + environment = dict(os.environ) environment["PYTHONDONTWRITEBYTECODE"] = "1" - return execute_trial(command, root, directory / "execution", time.monotonic() + timeout, - None, environment=environment) + return execute_trial(command, root, execution, time.monotonic() + timeout, + None, environment=environment, launch_path=execution / "launch-task.json") def _session_assess(root, directory, plan, execution, mechanism=None): @@ -55,7 +60,8 @@ def _session_assess(root, directory, plan, execution, mechanism=None): return assess(directory, plan["evaluation_settings"], execution, mechanism=mechanism) return run_protocol(root / "frozen", plan["frozen_files"]["optimization.py"], "assess", - directory=directory, settings=plan["evaluation_settings"], + launch_directory=directory, directory=directory, + settings=plan["evaluation_settings"], execution=execution) @@ -88,11 +94,15 @@ def _project_execute(root, directory, plan, deadline): for key, value in values.items(): arg = arg.replace("{" + key + "}", value) command.append(arg) - environment = runtime_environment() - environment["PYTHONPATH"] = str(source) + os.pathsep + environment["PYTHONPATH"] + environment = dict(os.environ) + inherited = environment.get("PYTHONPATH") + environment["PYTHONPATH"] = ( + os.pathsep.join((str(source), inherited)) if inherited else str(source) + ) environment["PYTHONDONTWRITEBYTECODE"] = "1" execution = execute_trial((*plan["evaluation_prefix"], *command), source, - output / step["id"], end, None, environment=environment) + output / step["id"], end, None, environment=environment, + launch_path=output / f"launch-{step['id']}.json") record["steps"].append({"id": step["id"], **execution}) actual = {"baseline": identity(baseline, declared["baseline"]), "candidate": identity(candidate, declared["candidate"])} @@ -113,18 +123,10 @@ def _project_execute(root, directory, plan, deadline): def _runtime_identity(): from inferrsi.harness.artifact_primitives import sha256 + from inferrsi.harness.session_runtime import source_files root = Path(str(files("inferrsi"))) - names = ("harness/optimization_session.py", "harness/optimization.py", - "harness/local_process.py", - "harness/serving/server.py", "harness/trials/external.py", - "harness/atomic_json.py", "harness/artifact_primitives.py", - "harness/usage.py", "harness/agent_sessions.py", "harness/task_protocol.py", - "harness/protocol_child.py", - "harness/candidates.py", "harness/project.py", "harness/measurement.py", - "harness/records/knowledge_capture.py", "apps/workflows/campaign.py", - "knowledge/context_projection.py") - return {name: sha256(root / name) for name in names} + return {name: sha256(root / name) for name in source_files(root)} def session_command(args, *, task_source: Path | None = None, knowledge_reader=None, @@ -293,6 +295,8 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N or plan.get("schema_version") == 3 or manifest.get("evaluation_mode") == "service_reuse" ): + if getattr(args, "confirm_domain_empty", False): + raise ValueError("Service-reuse cleanup requires --cleanup-receipt") if args.session_action == "profile": try: return optimization.service_command(root, args) @@ -349,7 +353,9 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N page=args.page, external_provider_for=external_provider_for, ) if args.session_action == "recover": - return optimization.recover(root, _session_assess) + return optimization.recover( + root, _session_assess, confirm_domain_empty=getattr(args, "confirm_domain_empty", False) + ) final = args.session_action == "final" mechanism = None if not final and getattr(args, "mechanism_file", None) is not None: @@ -380,7 +386,13 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N ) -def _run_entry(entry: str, arguments: list[str]) -> None: +def _nested_trial(execute_trial, directory, sequence, *args, **kwargs): + return execute_trial( + *args, launch_path=directory / f"launch-nested-{next(sequence):04d}.json", **kwargs + ) + + +def _run_entry(entry: str, arguments: list[str], *, launch_directory: Path | None = None) -> None: # Direct-file launch avoids importing a caller's cwd/inferrsi.py. Once the # bundled runner is selected, remove its directory so task imports cannot # resolve generic names such as project or candidates from Harness. @@ -388,13 +400,22 @@ def _run_entry(entry: str, arguments: list[str]) -> None: sys.path[:] = [path for path in sys.path if Path(path).resolve() != runner] # Extended-path launches on Windows may leave cwd before PYTHONPATH. Select # this runner's package root explicitly before importing its executor. - sys.path.insert(0, str(runner.parent.parent)) - from inferrsi.harness.trials.external import execute_trial + runtime_root = str(runner.parent.parent) + sys.path.insert(0, runtime_root) + try: + from inferrsi.harness.trials.external import execute_trial + finally: + sys.path.remove(runtime_root) + if launch_directory is not None: + execute_trial = partial(_nested_trial, execute_trial, launch_directory, count(1)) sys.argv = [entry, *arguments] sys.path.insert(0, str(Path(entry).parent)) runpy.run_path(entry, run_name="__main__", init_globals={"execute_trial": execute_trial}) if __name__ == "__main__": - _run_entry(sys.argv[1], sys.argv[2:]) + if sys.argv[1] == "--session-launch-directory": + _run_entry(sys.argv[3], sys.argv[4:], launch_directory=Path(sys.argv[2])) + else: + _run_entry(sys.argv[1], sys.argv[2:]) diff --git a/src/inferrsi/harness/session_runtime.py b/src/inferrsi/harness/session_runtime.py new file mode 100644 index 000000000..1baff243d --- /dev/null +++ b/src/inferrsi/harness/session_runtime.py @@ -0,0 +1,87 @@ +"""Identify the installed session code and the two context capture entry points. + +The identity pins previously retained contexts through their individual hashes. +New captures may use the currently installed Knowledge internals. Version metadata +is generated at build time and does not define the session execution contract. +""" + +import ast +from importlib.util import resolve_name + +_ROOTS = ( + "inferrsi.harness.optimization_session", + "inferrsi.apps.workflows.campaign", + "inferrsi.knowledge.context_projection", +) + + +def included_module(name): + return ( + (name == "inferrsi" or name.startswith("inferrsi.")) + and name != "inferrsi._version" + and (not name.startswith("inferrsi.knowledge.") or name == _ROOTS[2]) + ) + + +def _imports(tree, package, path): + nodes = list(ast.walk(tree)) + importlib_aliases = {"importlib"} + import_function_aliases = {"__import__"} + for node in nodes: + if isinstance(node, ast.Import): + for alias in node.names: + yield alias.name + if alias.name == "importlib": + importlib_aliases.add(alias.asname or alias.name) + elif isinstance(node, ast.ImportFrom): + name = node.module or "" + if node.level: + name = resolve_name("." * node.level + name, package) + yield name + for alias in node.names: + yield f"{name}.{alias.name}" + if (name, alias.name) in (("builtins", "__import__"), + ("importlib", "import_module")): + import_function_aliases.add(alias.asname or alias.name) + for node in nodes: + if not isinstance(node, ast.Call): + continue + func = node.func + if not (isinstance(func, ast.Name) and func.id in import_function_aliases + or isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) + and ((func.value.id in importlib_aliases and func.attr == "import_module") + or (func.value.id == "builtins" and func.attr == "__import__"))): + continue + argument = node.args[0] if node.args else None + if not isinstance(argument, ast.Constant) or not isinstance(argument.value, str): + raise ValueError( + f"Session runtime import must name a literal module in {path}:{node.lineno}" + ) + yield resolve_name(argument.value, package) + + +def source_files(root): + """Derive the internal import closure, including package initializers and lazy imports.""" + pending = list(_ROOTS) + visited, sources = set(), set() + while pending: + name = pending.pop() + if name in visited or not included_module(name): + continue + visited.add(name) + parts = name.split(".") + location = root.joinpath(*parts[1:]) + path = location / "__init__.py" + if path.is_file(): + package = name + else: + path = location.with_suffix(".py") + if not path.is_file(): + continue # A from-import name can be an attribute instead of a module. + package = name.rpartition(".")[0] + if name != "inferrsi": + pending.append(name.rpartition(".")[0]) + relative = path.relative_to(root).as_posix() + sources.add(relative) + pending.extend(_imports(ast.parse(path.read_bytes(), relative), package, relative)) + return sorted(sources) diff --git a/src/inferrsi/harness/task_protocol.py b/src/inferrsi/harness/task_protocol.py index df2684a96..83825a654 100644 --- a/src/inferrsi/harness/task_protocol.py +++ b/src/inferrsi/harness/task_protocol.py @@ -17,6 +17,7 @@ from . import local_process, protocol_child from .artifact_primitives import sha256 +from .launch_records import LaunchRecord # One protocol operation must finish within this time; the child and every process in # its group or Job are then stopped and the operation fails with kind "timeout". @@ -90,12 +91,14 @@ def _response_problem(response, operation: str) -> str | None: return None -def run(root: Path, protocol_sha256: str, operation: str, *, deadline=None, **arguments): +def run(root: Path, protocol_sha256: str, operation: str, *, deadline=None, + launch_directory: Path | None = None, **arguments): """Run one operation of ``root/optimization.py`` whose bytes have ``protocol_sha256``. Path arguments must be absolute. The child's stderr tail is copied to this process's stderr after every operation. A protocol ``SystemExit`` is raised again with its - exit code; every other failure raises ``TaskProtocolError``. Descendants that the + exit code unless the caller journals the operation inside a managed attempt. Managed + calls and other failures raise ``TaskProtocolError``. Descendants that the protocol leaves running are stopped with the child. An optional absolute monotonic deadline further bounds the shared protocol timeout. """ @@ -123,12 +126,17 @@ def run(root: Path, protocol_sha256: str, operation: str, *, deadline=None, **ar work = Path(temporary) (work / "request.json").write_bytes(data) argv = [sys.executable, "-I", "-B", str(CHILD_ENTRY), str(work / "request.json")] + options = {} + if launch_directory is not None: + options["launch"] = LaunchRecord.numbered( + launch_directory, f"protocol-{operation}", argv + ) # The scratch directory is the working directory, so a stray relative write # cannot land among the frozen resources. record = local_process._supervise( argv, work, dict(os.environ), work / "stdout", work / "stderr", min(time.monotonic() + timeout, deadline) if deadline is not None - else time.monotonic() + timeout) + else time.monotonic() + timeout, **options) stderr = _tail(work / "stderr") if (work / "stderr").is_file() else "" # Diagnostics contract: after every operation, whatever its result, the last # STDERR_TAIL_BYTES of the child's stderr (protocol prints included) are copied to @@ -163,6 +171,10 @@ def run(root: Path, protocol_sha256: str, operation: str, *, deadline=None, **ar return response["result"] error = response["error"] if error["kind"] == "system_exit": + if launch_directory is not None: + raise TaskProtocolError( + "protocol_exception", f"exit code {error['exit_code']}", error_type="SystemExit" + ) raise SystemExit(error["exit_code"]) if error["kind"] == "protocol_exception": raise TaskProtocolError("protocol_exception", error["message"], error_type=error["type"]) diff --git a/src/inferrsi/harness/trials/external.py b/src/inferrsi/harness/trials/external.py index b98826ad6..9ef4058c8 100644 --- a/src/inferrsi/harness/trials/external.py +++ b/src/inferrsi/harness/trials/external.py @@ -18,6 +18,7 @@ def execute_trial( metric: Callable[[dict, str], float] | None = None, environment: dict | None = None, include_cleanup: bool = False, + launch_path: Path | None = None, ) -> dict: """Run one command and retain its record. @@ -30,6 +31,8 @@ def execute_trial( options = {"environment": environment} if environment is not None else {} if include_cleanup: options["include_cleanup"] = True + if launch_path is not None: + options["launch_path"] = launch_path record = execute_command(command, cwd, trial_dir, deadline, **options) result_path = Path(record["result_path"]) if metric_key is not None: diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index 5a63f7321..7faa5bbea 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -7,14 +7,16 @@ import subprocess import sys from pathlib import Path +from types import SimpleNamespace import pytest from inferrsi.apps.cli import main from inferrsi.benchmark import registry -from inferrsi.harness import optimization_session +from inferrsi.harness import optimization, optimization_session from inferrsi.harness.optimization import _locked from tests.fixtures.diagnosis import diagnosis_args +from tests.fixtures.session_process import kill_controller, target_python @pytest.fixture @@ -71,10 +73,7 @@ def diagnose(root, capsys): def submit(root, factor, capsys, usage=None): - candidate = root / "work/candidate.py" - candidate.write_text(f"FACTOR = {factor}\n", encoding="utf-8") - args = ["benchmarks", "session", "round", "--session", str(root), - "--candidate", str(candidate), "--hypothesis", f"Test factor {factor}"] + args = round_arguments(root, factor) if usage is not None: export = root / "usage-export.json" export.write_text(json.dumps(usage), encoding="utf-8") @@ -83,6 +82,13 @@ def submit(root, factor, capsys, usage=None): return json.loads(capsys.readouterr().out) +def round_arguments(root, factor): + candidate = root / "work/candidate.py" + candidate.write_text(f"FACTOR = {factor}\n", encoding="utf-8") + return ["benchmarks", "session", "round", "--session", str(root), + "--candidate", str(candidate), "--hypothesis", f"Test factor {factor}"] + + def test_started_task_uses_frozen_protocol_without_registry(session, capsys, monkeypatch): def unavailable(*args): raise AssertionError("The running campaign must not rediscover its task") @@ -98,6 +104,96 @@ def unavailable(*args): assert (session / "calls.log").read_text().splitlines() == ["2", "3", "4", "4"] +def test_packaged_round_uses_target_dependencies(task, tmp_path, capsys, monkeypatch): + python = target_python(tmp_path, monkeypatch, optimization_session) + benchmark = task / "benchmark.py" + benchmark.write_text( + "from session_target_dependency import VALUE\nassert VALUE == 2\n" + + benchmark.read_text(encoding="utf-8"), encoding="utf-8", + ) + root = tmp_path / "session" + assert main([*start_args(task, root), "--python", str(python)]) == 0 + capsys.readouterr() + diagnose(root, capsys) + assert submit(root, 2, capsys)["latest_observation"]["assessment"]["score"] == 2 + + +@pytest.mark.parametrize("recorded,current,probe,result", [ + (("boot", "pid:[123]"), ("boot", "pid:[123]"), ProcessLookupError, "observed_empty"), + (("other", "pid:[123]"), ("boot", "pid:[123]"), None, "unobservable"), + ((None, "pid:[123]"), ("boot", "pid:[123]"), None, "unobservable"), + (("boot", "pid:[123]"), (None, "pid:[123]"), None, "unobservable"), + (("boot", "pid:[456]"), ("boot", "pid:[123]"), None, "unobservable"), + (("boot", None), ("boot", "pid:[123]"), None, "unobservable"), + (("boot", "pid:[123]"), ("boot", None), None, "unobservable"), + (("boot", "pid:[123]"), ("boot", "pid:[123]"), PermissionError, "unobservable"), + (("boot", "pid:[123]"), ("boot", "pid:[123]"), None, "live"), +]) +def test_group_observation_requires_the_recorded_boot_and_namespace( + monkeypatch, recorded, current, probe, result, +): + from inferrsi.harness import launch_records + + calls = [] + + def killpg(group, signal): + calls.append((group, signal)) + if probe: + raise probe() + + monkeypatch.setattr(launch_records, "sys", SimpleNamespace(platform="linux")) + monkeypatch.setattr(launch_records, "os", SimpleNamespace(killpg=killpg)) + monkeypatch.setattr(launch_records, "linux_process_domain", lambda: current) + assert launch_records.observe({ + "state": "launched", "spawned": True, "pid": 42, "process_group_id": 42, + "platform": "linux", "boot_id": recorded[0], "pid_namespace": recorded[1], + }) == result + assert calls == ([(42, 0)] if all(recorded) and recorded == current else []) + assert launch_records.observe({"state": "ended", "pid": None}) == "launch_unconfirmed" + assert launch_records.observe({"state": "ended", "spawned": False}) == "not_spawned" + + +@pytest.mark.skipif(sys.platform != "linux", reason="requires a Linux process-group observation") +def test_killed_controller_does_not_restart_live_assessor(task, tmp_path, capsys): + marker, release = tmp_path / "assessor-started", tmp_path / "release-assessor" + protocol = task / "optimization.py" + header = "def assess(directory, settings, execution):\n" + protocol.write_text(protocol.read_text(encoding="utf-8").replace( + header, header + ( + " import time\n from pathlib import Path\n" + f" with Path({str(marker)!r}).open('a') as stream:\n" + " stream.write('assess\\n')\n" + " deadline = time.monotonic() + 30\n" + f" while not Path({str(release)!r}).exists() and time.monotonic() < deadline:\n" + " time.sleep(0.02)\n" + ) + ), encoding="utf-8") + root = tmp_path / "session" + assert main(start_args(task, root)) == 0 + capsys.readouterr() + diagnose(root, capsys) + args = round_arguments(root, 2) + driver = "import sys; from inferrsi.apps.cli import main; sys.exit(main(sys.argv[1:]))" + try: + kill_controller(driver, args, marker) + attempt, = (root / "rounds/round-01").iterdir() + launch = attempt / "protocol-assess-0001.json" + original = launch.read_bytes() + assert json.loads(original)["state"] in ("intent", "launched") + assert (attempt / "execution/execution.json").is_file() + recover = ["benchmarks", "session", "recover", "--session", str(root)] + for _ in range(2): + assert main(recover) == 2 + view = json.loads(capsys.readouterr().out) + assert view["cleanup_unconfirmed"]["stages"] == ["protocol-assess-0001"] + assert list(attempt.glob("protocol-assess-*.json")) == [launch] + assert launch.read_bytes() == original + assert marker.read_text(encoding="utf-8").splitlines() == ["assess"] + assert not (root / "recoveries").exists() + finally: + release.touch() + + def test_generic_job_precedes_child_start_and_collects_child_final(tmp_path, task, capsys): """Software control: synthetic host receipts, real task subprocesses, no Agent launch.""" root, job = tmp_path / "child-campaign", tmp_path / "agent-job" @@ -239,6 +335,8 @@ def fail(*args, **kwargs): assert main(["benchmarks", "session", "final", "--session", str(session)]) == 0 result = json.loads(capsys.readouterr().out) assert result["state"] == "completed" and result["delivery"]["status"] == "error" + assert main(["benchmarks", "session", "status", "--session", str(session)]) == 0 + assert json.loads(capsys.readouterr().out)["state"] == "completed" calls = (session / "calls.log").read_bytes() monkeypatch.setattr(delivery, "export_bundle", original) assert main(["export", "--input", str(session), @@ -299,6 +397,279 @@ def crash_after_execution(*args): assert (session / "calls.log").read_text().splitlines() == ["2"] +@pytest.fixture +def held_child(): + children = [] + + def start(log): + command = [sys.executable, "-c", + "from pathlib import Path; import sys, time; " + "Path(sys.argv[1]).write_text('started\\n'); " + "print('ready', flush=True); time.sleep(60)", str(log)] + child = subprocess.Popen(command, stdout=subprocess.PIPE) + children.append(child) + assert child.stdout.readline().strip() == b"ready" + return child, command + + yield start + for child in children: + if child.poll() is None: + child.terminate() + child.wait(timeout=10) + child.stdout.close() + + +def test_recovery_counts_an_interrupted_round_once_and_keeps_every_step( + session, capsys, monkeypatch, held_child, +): + from inferrsi.apps.delivery import read_bundle + from inferrsi.apps.views.dashboard import dashboard_snapshot + from inferrsi.harness import launch_records + + best = submit(session, 2, capsys)["best"] + calls = session / "step-calls.log" + child = None + + def stop_during_second_step(root, attempt, plan, deadline): + nonlocal child + execution = attempt / "execution" + execution.mkdir() + first = launch_records.LaunchRecord(execution / "launch-first.json", ["first"]) + first.ended({"pid": 42, "process_group_id": None, "started_at": None, + "ended_at": None, "status": "completed", "domain_empty": True}, True) + marker = execution / "launch-second.json" + launch_records.LaunchRecord(marker, ["second"]) + child, _ = held_child(calls) + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(optimization_session, "_session_execute", stop_during_second_step) + with pytest.raises(KeyboardInterrupt): + submit(session, 9, capsys) + command = ["benchmarks", "session"] + target = ["--session", str(session)] + assert main([*command, "recover", *target]) == 2 + view = json.loads(capsys.readouterr().out) + assert view["state"] == "blocked" and view["completed_rounds"] == 2 + assert view["pending"] is None and view["best"] == best + assert view["recovery_command"] == "recover --confirm-domain-empty" + gate = view["cleanup_unconfirmed"] + assert gate["stages"] == ["launch-second"] + record = view["latest_observation"] + assert record["execution"] is None and record["assessment"]["score"] is None + assert record["assessment"]["status"] == record["selection"]["outcome"] == "interrupted" + assert record["assessment"]["verdict"] == "INCONCLUSIVE" + receipt = session / record["recovery"]["path"] + proof = json.loads(receipt.read_bytes()) + assert [entry["observation"] for entry in proof["launches"]] == [ + "recorded_empty", "launch_unconfirmed", + ] + before = (session / "state.json").read_bytes(), receipt.read_bytes() + for action in ("status", "recover"): + assert main([*command, action, *target]) == 2 + assert json.loads(capsys.readouterr().out)["completed_rounds"] == 2 + assert ((session / "state.json").read_bytes(), receipt.read_bytes()) == before + attempt = session / record["path"] + assert not (attempt / "execution/execution.json").exists() + assert not list(attempt.rglob("*cleanup*")) + dashboard = dashboard_snapshot(session)["data"] + assert dashboard["candidates"][1]["state"] == "interrupted" + assert dashboard["candidates"][1]["measured_score"] is None + output = session / "delivery" / "interrupted" + assert main(["export", "--input", str(session), "--output", str(output)]) == 0 + capsys.readouterr() + delivery = read_bundle(output) + assert delivery["rounds"][1]["execution_state"] == "interrupted" + assert delivery["rounds"][1]["record_verified"] + assert not delivery["acceptance"]["delivery_accepted"] + assert child is not None and child.poll() is None + child.terminate() + child.wait(timeout=10) + assert main([*command, "recover", *target, "--confirm-domain-empty"]) == 0 + view = json.loads(capsys.readouterr().out) + assert view["state"] == "active" and view["completed_rounds"] == 2 + confirmation, = (session / "recoveries").glob("confirm-*.json") + confirmation = json.loads(confirmation.read_bytes()) + assert confirmation["recovery_sha256"] == gate["recovery_sha256"] + assert confirmation["basis"] == "manual" + assert [entry["stage"] for entry in confirmation["confirmed_stages"]] == ["launch-second"] + assert calls.read_text().splitlines() == ["started"] + assert (session / "calls.log").read_text().splitlines() == ["2"] + submit(session, 3, capsys) + assert main([*command, "final", *target]) == 0 + assert json.loads(capsys.readouterr().out)["state"] == "completed" + summary = json.loads((session / "summary.json").read_bytes()) + assert summary["completed_rounds"] == 3 + assert summary["curve"][1]["assessment"]["score"] is None + assert (session / "calls.log").read_text().splitlines() == ["2", "3", "3"] + + +def test_recover_never_spawns_a_second_assessor_with_a_receipt( + session, capsys, monkeypatch, held_child, +): + from inferrsi.harness import launch_records + + execute = optimization_session._session_execute + calls = session / "assessor-calls.log" + + def stop_after_execution(*args): + execute(*args) + raise KeyboardInterrupt + + def stop_after_assessor_spawn(root, attempt, plan, execution): + launch_records.LaunchRecord.numbered(attempt, "protocol-assess", ["assess"]) + held_child(calls) + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(optimization_session, "_session_execute", stop_after_execution) + with pytest.raises(KeyboardInterrupt): + submit(session, 2, capsys) + pending = json.loads((session / "state.json").read_bytes())["pending"] + attempt = session / pending["path"] + receipt = attempt / "execution/execution.json" + before = receipt.read_bytes() + command = ["benchmarks", "session", "recover", "--session", str(session)] + monkeypatch.setattr(optimization_session, "_session_assess", stop_after_assessor_spawn) + with pytest.raises(KeyboardInterrupt): + main(command) + launch = attempt / "protocol-assess-0001.json" + marker = launch.read_bytes() + for _ in range(2): + assert main(command) == 2 + view = json.loads(capsys.readouterr().out) + assert view["pending"]["path"] == pending["path"] + assert view["completed_rounds"] == 0 + assert view["cleanup_unconfirmed"]["stages"] == ["protocol-assess-0001"] + assert launch.read_bytes() == marker + assert not (attempt / "protocol-assess-0002.json").exists() + assert not list(attempt.rglob("*cleanup*")) + assert receipt.read_bytes() == before + assert calls.read_text().splitlines() == ["started"] + assert (session / "calls.log").read_text().splitlines() == ["2"] + + +def test_interrupted_final_requires_an_explicit_retry(session, capsys, monkeypatch): + for factor in (2, 3, 4): + submit(session, factor, capsys) + + def stop(*args): + raise KeyboardInterrupt + + command = ["benchmarks", "session"] + target = ["--session", str(session)] + with monkeypatch.context() as patch: + patch.setattr(optimization_session, "_session_execute", stop) + with pytest.raises(KeyboardInterrupt): + main([*command, "final", *target]) + assert main([*command, "recover", *target]) == 2 + state = json.loads((session / "state.json").read_bytes()) + assert state["final"] is None and len(state["rounds"]) == 3 + attempt, = state["final_attempts"] + assert attempt["assessment"]["status"] == "interrupted" + assert attempt["execution"] is None + assert (session / attempt["recovery"]["path"]).is_file() + assert not (session / "delivery").exists() + capsys.readouterr() + assert main([*command, "recover", *target, "--confirm-domain-empty"]) == 0 + view = json.loads(capsys.readouterr().out) + assert view["can_finalize"] and view["next_action"].endswith("with_final") + assert (session / "calls.log").read_text().splitlines() == ["2", "3", "4"] + assert main([*command, "final", *target]) == 0 + assert json.loads(capsys.readouterr().out)["state"] == "completed" + state = json.loads((session / "state.json").read_bytes()) + assert state["final_attempts"] == [attempt] and state["final"]["path"] != attempt["path"] + assert (session / "calls.log").read_text().splitlines() == ["2", "3", "4", "4"] + + +@pytest.mark.parametrize("operation", ["status", "recover"]) +@pytest.mark.parametrize("has_receipt", [False, True]) +def test_frozen_drift_settles_a_pending_attempt( + session, monkeypatch, capsys, operation, has_receipt, +): + execute = optimization_session._session_execute + + def stop(*args): + if has_receipt: + execute(*args) + raise KeyboardInterrupt + + def should_not_assess(*args): + pytest.fail("Frozen drift cannot start an assessment") + + monkeypatch.setattr(optimization_session, "_session_execute", stop) + monkeypatch.setattr(optimization_session, "_session_assess", should_not_assess) + with pytest.raises(KeyboardInterrupt): + submit(session, 2, capsys) + (session / "frozen/TASK.md").write_text("Changed task\n", encoding="utf-8") + assert main(["benchmarks", "session", operation, "--session", str(session)]) == 2 + view = json.loads(capsys.readouterr().out) + assert view["state"] == "blocked" and view["pending"] is None + assert not view["can_finalize"] and view["summary"] is None + assert "Frozen task resources changed" in view["integrity_error"] + state = json.loads((session / "state.json").read_bytes()) + record, = state["rounds"] + assert record["assessment"]["verdict"] == "INCONCLUSIVE" + assert record["assessment"]["score"] is None + assert (session / record["path"] / "execution/execution.json").exists() == has_receipt + + +@pytest.mark.parametrize("operation,args", [ + ("arguments", "candidate, output, settings"), ("assess", "directory, settings, execution"), +]) +@pytest.mark.parametrize("code", ["", "7"]) +def test_child_system_exit_settles_as_a_protocol_failure( + task, tmp_path, capsys, operation, args, code, +): + path = task / "optimization.py" + header = f"def {operation}({args}):\n" + path.write_text(path.read_text(encoding="utf-8").replace( + header, f"{header} raise SystemExit({code})\n"), encoding="utf-8") + root = tmp_path / "session" + assert main(start_args(task, root)) == 0 + capsys.readouterr() + diagnose(root, capsys) + assert main(round_arguments(root, 2)) == 2 + view = json.loads(capsys.readouterr().out) + assert view["state"] == "blocked" and view["pending"] is None + assert "cleanup_unconfirmed" not in view + assessment = view["latest_observation"]["assessment"] + assert assessment["verdict"] == "INCONCLUSIVE" + assert assessment["reason"].startswith("SystemExit:") + assert (root / "calls.log").is_file() == (operation == "assess") + command = ["benchmarks", "session", "recover", "--session", str(root)] + assert main(command) == 2 + capsys.readouterr() + with pytest.raises(SystemExit) as error: + main([*command, "--confirm-domain-empty"]) + assert error.value.code == 2 + + +@pytest.mark.parametrize("mode,rounds,can_finalize", [ + ("exact", 3, True), ("exact", 1, False), ("up_to", 1, True), ("up_to", 0, False), +]) +def test_reserve_status_agrees_with_final_eligibility(task, tmp_path, capsys, monkeypatch, + mode, rounds, can_finalize): + from inferrsi.apps.cli.arguments import parser + + root = tmp_path / "session" + args = parser().parse_args(start_args(task, root)) + args.round_mode = mode + optimization_session.session_command(args, task_source=task) + diagnose(root, capsys) + for index in range(rounds): + submit(root, index + 2, capsys) + deadline = json.loads((root / "state.json").read_bytes())["deadline"] + monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: deadline - 1)) + status = optimization.status(root) + assert status["remaining_search_seconds"] == 0 + assert status["can_finalize"] is can_finalize + assert status["next_action"] == ( + "independently_retest_selected_candidate_with_final" if can_finalize + else "search_budget_exhausted_incomplete_session" + ) + + def test_executor_exception_without_receipt_blocks_without_claiming_cleanup( session, monkeypatch, capsys, ): @@ -955,18 +1326,37 @@ def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executo assert "infra/executors/local.py" not in identity for name in identity: assert (root / name).is_file(), name - # #498 slice 2: the server helpers moved to harness/serving/server.py. A new plan binds - # that canonical file by its installed bytes, and the old Infra path is gone. - import hashlib - assert "infra/processes.py" not in identity - server = (root / "harness/serving/server.py").read_bytes() - assert identity["harness/serving/server.py"] == hashlib.sha256(server).hexdigest() + assert "harness/serving/server.py" not in identity + assert "harness/execution_service.py" not in identity + assert "benchmark/assessment.py" not in identity + evidence = (root / "harness/records/evidence.py").read_bytes() + assert identity["harness/records/evidence.py"] == hashlib.sha256(evidence).hexdigest() from inferrsi.harness.artifact_primitives import sha256 assert identity["apps/workflows/campaign.py"] == sha256(root / "apps/workflows/campaign.py") + +def test_runtime_identity_rejects_computed_dynamic_imports(tmp_path, monkeypatch): + identity = optimization_session._runtime_identity() + installed = Path(str(optimization_session.files("inferrsi"))) + for name in identity: + target = tmp_path / name + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(installed / name, target) + path = tmp_path / "harness/records/evidence.py" + with path.open("a", encoding="utf-8") as stream: + stream.write( + "\ndef read_dynamic(name):\n" + " from importlib import import_module as load\n" + " return load('inferrsi.' + name)\n" + ) + monkeypatch.setattr(optimization_session, "files", lambda _: tmp_path) + with pytest.raises(ValueError, match="Session runtime import must name a literal module"): + optimization_session._runtime_identity() + + PRE_SERVING = (Path(__file__).resolve().parents[1] / "fixtures" / "optimization-session" / "pre-serving-runtime-identity.json") @@ -1011,6 +1401,7 @@ def _session_bytes(root): ("pre-infra-removal-session", "infra/artifacts.py"), # #558 renamed harness/scenarios to harness/trials. ("pre-trials-rename-session", "harness/scenarios/external.py"), + ("pre-recovery-closure-session", "harness/serving/server.py"), ]) def test_a_session_planned_before_a_runtime_change_is_refused_and_left_unchanged( tmp_path, capsys, fixture, removed_file, @@ -1027,7 +1418,7 @@ def test_a_session_planned_before_a_runtime_change_is_refused_and_left_unchanged assert state["rounds"] == [] and state["pending"]["kind"] == "round" receipt = json.loads(before[state["pending"]["path"] + "/execution/execution.json"]) assert receipt["status"] == "completed" and receipt["returncode"] == 0 - assert before["calls.log"] == b"2\n" + assert before["calls.log"].splitlines() == [b"2"] assert removed_file in json.loads(before["plan.json"])["runtime_identity"] assert removed_file not in optimization_session._runtime_identity() for action in ("status", "recover"): @@ -1036,12 +1427,10 @@ def test_a_session_planned_before_a_runtime_change_is_refused_and_left_unchanged assert _session_bytes(session) == before -def test_changed_installed_server_bytes_refuse_an_untouched_plan( +def test_changed_transitive_runtime_bytes_refuse_an_untouched_plan( session, capsys, monkeypatch, tmp_path, ): - # Review of bf65c76: change the installed server, not the plan. A disposable copy of - # the identity files stands in for the installation; the plan from start is untouched. - import shutil + # A disposable copy of the installed identity files stands in for a newer wheel. from importlib.resources import files installed = Path(str(files("inferrsi"))) @@ -1054,8 +1443,12 @@ def test_changed_installed_server_bytes_refuse_an_untouched_plan( before = path.read_bytes() capsys.readouterr() assert main(["benchmarks", "session", "status", "--session", str(session)]) == 0 - server = copy / "harness/serving/server.py" - server.write_bytes(server.read_bytes() + b"\n# changed canonical bytes\n") + evidence = copy / "harness/records/evidence.py" + if not evidence.exists(): + # On the baseline the transitive module is installed but was omitted from the map. + evidence.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(installed / "harness/records/evidence.py", evidence) + evidence.write_bytes(evidence.read_bytes() + b"\n# changed transitive bytes\n") capsys.readouterr() output = _refused(session, capsys, "status") assert "Optimization runtime changed" in output.out + output.err diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index 4d6476615..cd918d5c5 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -10,8 +10,10 @@ from inferrsi.apps.cli import main from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard +from inferrsi.harness import optimization_session from inferrsi.harness.optimization import read_records from tests.fixtures.diagnosis import diagnosis_args +from tests.fixtures.session_process import kill_controller, target_python @pytest.fixture @@ -74,6 +76,60 @@ def submit(project, capsys, metric): return code, json.loads(capsys.readouterr().out) +def test_ab_ba_round_uses_target_dependencies(project, tmp_path, capsys, monkeypatch): + python = target_python(tmp_path, monkeypatch, optimization_session) + for name in ("measure.py", "quality.py"): + path = project[1] / name + path.write_text( + "from session_target_dependency import VALUE\nassert VALUE == 2\n" + + path.read_text(encoding="utf-8"), encoding="utf-8", + ) + start(project, capsys, extra=("--python", str(python))) + code, view = submit(project, capsys, 12) + assert code == 0 + assert view["latest_observation"]["assessment"]["verdict"] == "PASS" + + +@pytest.mark.skipif(sys.platform != "linux", reason="requires a Linux process-group observation") +def test_killed_controller_keeps_second_step_unconfirmed(project, tmp_path, capsys): + repo, protocol, _, root = project + marker, release = tmp_path / "second-step-started", tmp_path / "release-second-step" + # The baseline quality check finishes before the candidate's quality check. + quality = protocol / "quality.py" + quality.write_text(quality.read_text(encoding="utf-8") + ( + "import time\n" + "if Path(sys.argv[1]).name == 'candidate':\n" + f" with Path({str(marker)!r}).open('a') as stream:\n" + " stream.write('candidate\\n')\n" + " deadline = time.monotonic() + 30\n" + f" while not Path({str(release)!r}).exists() and time.monotonic() < deadline:\n" + " time.sleep(0.02)\n" + ), encoding="utf-8") + start(project, capsys) + (repo / "config.json").write_text('{"metric": 12}', encoding="utf-8") + args = ["campaign", "round", "--directory", str(root), "--candidate", str(repo), + "--hypothesis", "Candidate with a larger measured value"] + driver = "import sys; from inferrsi.apps.cli import main; sys.exit(main(sys.argv[1:]))" + try: + kill_controller(driver, args, marker) + attempt, = (root / "rounds/round-01").iterdir() + launches = list((attempt / "execution").glob("launch-*.json")) + assert len(launches) == 2 + statuses = {json.loads(path.read_bytes())["state"] for path in launches} + assert statuses in ({"ended", "intent"}, {"ended", "launched"}) + recover = ["campaign", "recover", "--directory", str(root)] + for _ in range(2): + assert main(recover) == 2 + view = json.loads(capsys.readouterr().out) + assert view["completed_rounds"] == 1 and view["state"] == "blocked" + assert len(view["cleanup_unconfirmed"]["stages"]) == 1 + assert marker.read_text(encoding="utf-8").splitlines() == ["candidate"] + assert not (attempt / "execution/execution.json").exists() + assert not (root / "recoveries").exists() + finally: + release.touch() + + def test_project_lifecycle_never_imports_benchmark(project): """Reject any Benchmark import in a fresh process, including the CLI entry.""" repo, _, _, root = project diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index e3839373d..e16489ce1 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -94,6 +94,10 @@ def test_one_service_order_and_independent_final_ignores_workspace(campaign): assert {row["version"] for row in events(campaign, final["final"])} == {"accepted"} assert "profile" not in [row["stage"] for row in events(campaign, final["final"])] project_service.no_fingerprints(optimization.read_records(campaign["root"])[2]) + assert call(campaign, "status")["state"] == "completed" + output = campaign["root"] / "delivery" / "check" + assert main(["export", "--input", str(campaign["root"]), "--output", str(output)]) == 0 + assert json.loads(campaign["capsys"].readouterr().out)["status"] == "published" @pytest.mark.parametrize("failure", ["failed", "missing", "empty"]) diff --git a/tests/benchmark/test_benchmark_compare.py b/tests/benchmark/test_benchmark_compare.py index 9d5542e2b..7d98552ac 100644 --- a/tests/benchmark/test_benchmark_compare.py +++ b/tests/benchmark/test_benchmark_compare.py @@ -94,7 +94,7 @@ def finish(experiment, trial, *, factor=2, final=True, model="synthetic-model", final_score=None, legacy_session_id=None, python=None, environment_digest="a" * 64, knowledge=False, token_coverage=False, usage_counts=None, collect=True, session_id=None, host_state="completed", window=True, legacy_attempt=1, - card_timing=None, card_context_budgets=(None,)): + card_timing=None, card_context_budgets=(None,), round_submit=main): root, _, capsys = experiment opened = time.time() dispatch = operation(experiment, "dispatch", trial) @@ -150,9 +150,11 @@ def deliver_required_cards(): assert binding["started_at"] >= diagnosis["recorded_at"] candidate = Path(start["working_candidate"]) (campaign / candidate).write_text(f"FACTOR = {factor}\n", encoding="utf-8") - assert main(["benchmarks", "session", "round", "--session", str(campaign), - "--candidate", str(campaign / candidate), "--hypothesis", "Synthetic hypothesis", - "--strategy", "Synthetic strategy"]) == 0 + assert round_submit([ + "benchmarks", "session", "round", "--session", str(campaign), + "--candidate", str(campaign / candidate), "--hypothesis", "Synthetic hypothesis", + "--strategy", "Synthetic strategy", + ]) == 0 capsys.readouterr() if card_timing == "after_round": deliver_required_cards() @@ -190,6 +192,31 @@ def deliver_required_cards(): return campaign, trial_result +def test_compare_keeps_interrupted_round_in_the_trace(experiment, monkeypatch): + from inferrsi.harness import optimization_session + + _, initial, capsys = experiment + + def interrupted(*args): + raise KeyboardInterrupt + + def round_submit(args): + with monkeypatch.context() as patch: + patch.setattr(optimization_session, "_session_execute", interrupted) + with pytest.raises(KeyboardInterrupt): + main(args) + recover = ["benchmarks", "session", "recover", *args[3:5]] + assert main(recover) == 2 + capsys.readouterr() + return main([*recover, "--confirm-domain-empty"]) + + _, retained = finish(experiment, initial["trials"][0]["id"], round_submit=round_submit) + row, = retained["trace"] + assert row["assessment_status"] == "interrupted" + assert row["quality"] == "INCONCLUSIVE" + assert row["speedup"] is None and row["adopted"] is False + + def test_metrics_summary_is_first_and_complete_token_ratio_has_explicit_direction(experiment): root, initial, _ = experiment on, off = [trial["id"] for trial in initial["trials"]] diff --git a/tests/fixtures/optimization-session/README.md b/tests/fixtures/optimization-session/README.md index 898682c9c..d6078f19e 100644 --- a/tests/fixtures/optimization-session/README.md +++ b/tests/fixtures/optimization-session/README.md @@ -15,6 +15,7 @@ that is not settled: | --- | --- | --- | --- | | `pre-infra-removal-session/` | `main` `6bdc86ee` | #498 slice 5 removed `infra/` | `infra/artifacts.py` | | `pre-trials-rename-session/` | `75b9872`, `main` `7a7ab84` plus a docs-only commit | #558 renamed `harness/scenarios` to `harness/trials` | `harness/scenarios/external.py` | +| `pre-recovery-closure-session/` | `main` `fbddabaa` | #595 derives the optimization-session runtime import closure | `harness/serving/server.py` | The current runtime refuses every one of them for `status` and `recover` before any operation runs and leaves every file unchanged. `tests/apps/test_optimization_session.py` checks this against the @@ -41,7 +42,7 @@ To redo it for a later runtime change: build and install the old and the new whe environments, start the session with the old one (the synthetic task of `tests/apps/test_optimization_session.py`, `--rounds 3 --max-minutes 5 --evaluation-timeout-seconds 15 --python python`, run from a neutral directory so no host path enters the plan), stop its coordinator -after the child completes, remove the empty `.session.lock`, and keep everything else. Add the new +after the child completes, omit `.session.lock`, and keep everything else. Add the new directory and its removed identity file to both tests. To resume such a session, use the runtime that started it: the same commit, installed. diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/calls.log b/tests/fixtures/optimization-session/pre-recovery-closure-session/calls.log new file mode 100644 index 000000000..78c6baefd --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/calls.log @@ -0,0 +1 @@ +2 diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/campaign.json b/tests/fixtures/optimization-session/pre-recovery-closure-session/campaign.json new file mode 100644 index 000000000..86f7ed4d8 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/campaign.json @@ -0,0 +1,6 @@ +{ + "campaign_id": "pre-recovery-closure-session", + "managed_optimization": true, + "plan_digest": "02a6e26bd3bd377d6e1eb349d82555c451c847ca49b55b251b4a56dd2c265957", + "task": "test-work" +} diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/TASK.md b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/TASK.md new file mode 100644 index 000000000..35c8bfc46 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/TASK.md @@ -0,0 +1 @@ +Synthetic protocol control diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/baseline.py b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/baseline.py new file mode 100644 index 000000000..431fac18e --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/baseline.py @@ -0,0 +1 @@ +FACTOR = 1 diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/benchmark.py b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/benchmark.py new file mode 100644 index 000000000..fa9794659 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/benchmark.py @@ -0,0 +1,11 @@ +import json, runpy, sys +from pathlib import Path +value = runpy.run_path(sys.argv[1])['FACTOR'] +output = Path(sys.argv[2]) +output.mkdir() +with Path('calls.log').open('a') as stream: + stream.write(str(value) + '\n') +status = 'completed' if value > 0 else 'candidate_failure' +result = {'status': status, 'verdict': 'PASS' if value > 0 else 'FAIL', + 'score': value if value > 0 else None} +(output / 'result.json').write_text(json.dumps(result)) diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/optimization.py b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/optimization.py new file mode 100644 index 000000000..c730a6261 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/frozen/optimization.py @@ -0,0 +1,8 @@ +import json +def validate_arguments(args): + assert not args + return {} +def arguments(candidate, output, settings): + return [str(candidate), str(output)] +def assess(directory, settings, execution): + return json.loads((directory / 'measurement/result.json').read_text()) diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/plan.json b/tests/fixtures/optimization-session/pre-recovery-closure-session/plan.json new file mode 100644 index 000000000..76511aace --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/plan.json @@ -0,0 +1,63 @@ +{ + "schema_version": 2, + "condition": "synthetic-recovery-control", + "round_limit": 3, + "max_seconds": 300.0, + "round_mode": "exact", + "final_reserve_seconds": 15.0, + "knowledge_allowed": true, + "evaluation_timeout_seconds": 15.0, + "evaluation_prefix": [], + "python": "python", + "runtime_identity": { + "harness/optimization_session.py": "31d77e13343eacd63b65f7accd116e8d4f436315ac7e262ba072db431caa42de", + "harness/optimization.py": "005a4c32de0e7189fa1d94eb5c4150d21d78046bcdc5cd76ff287c1d1e421290", + "harness/local_process.py": "b862f4d67d71d087449ce16c0c97dbc9e39d849401b825d3ea5eaeb675e8b792", + "harness/serving/server.py": "2ca1984373423b190b13523fa76ce760e74cc851bbd29b0e532d8d7e92e62c8d", + "harness/trials/external.py": "700421015f9154b86e32f26e00f1c40647860c30f9ac03bb3c05c192121ecab0", + "harness/atomic_json.py": "a3ddf62eb4c7589a60944fd05c079d0518bd2e3397bc9d240d46543233b83c0d", + "harness/artifact_primitives.py": "f10fde1f28a7e97853cbb379ea058b9bcf0c4786a7d43ea5ec6983f8569c8c99", + "harness/usage.py": "bcb8a35f83e683c1e3343c2438214ad89f35eeb4dd940eccfd54b3489bb70855", + "harness/agent_sessions.py": "df5369abaa0d219c79710f496245324f7bddd67319cde896cea3284f68ae6fae", + "harness/task_protocol.py": "b4e96788447d45edc54434b78b5df749ed013d100aab8ab7d75656edecef7d8c", + "harness/protocol_child.py": "2cfd5848e711cedeef181981ec6fa2be453ee061f57c32f74954c82625528c95", + "harness/candidates.py": "49aad5645c65516093c7e14514f1bd7ec25d25ee082e6188f552ec415f86698a", + "harness/project.py": "568f1f3a389926eab37cc4d6fb7351f4ef76ecc0280af6b2f85868fb323b6276", + "harness/measurement.py": "6eee529a46b88e7f2598d0c663624993f96ee1ed30ca257265ed3e3792e07450", + "harness/records/knowledge_capture.py": "6a5501d9fdc6bbdc523dc98e59722eae297069a7ad6c024c9d3c7c8f38a42a22", + "apps/workflows/campaign.py": "26b3767357f028929248a69615b6524f1186c30eb47f963114614eeff2f26289", + "knowledge/context_projection.py": "ef89a0b2ecddbb0460573edc65a8b5ef704989e03d3d2fa615ca529ef0debe2a" + }, + "task": "test-work", + "task_source": "benchmark", + "candidate_kind": "file", + "candidate_name": "candidate.py", + "baseline_path": "frozen/baseline.py", + "working_candidate": "work/candidate.py", + "selection": { + "direction": "maximize", + "initial_score": 1.0, + "metric": "speedup" + }, + "evaluation_settings": {}, + "frozen_files": { + "baseline.py": "d9df1aa140b5050625fe8e130ec631cc25c4a11f732e369c5d018021cfc3e315", + "benchmark.py": "6dbbd0c7b2934c3165daed8aa25dcd438b90642d80dff0df602c6bdada0a77c2", + "optimization.py": "5471859e242258a4080decdbf30acde554c68c6b9b559a73fd5a5f788721f816", + "TASK.md": "1045d0e6f05105ea7f990b60fd6669a394aadbd561a7ed40cb7c0954c23ff7dc" + }, + "report_metadata": { + "benchmark_metrics": { + "metrics_schema_version": 1, + "counting_rule": "retained-round-v1", + "token_scope": "trial_agent_session", + "objective": { + "key": "speedup", + "unit": "ratio", + "direction": "maximize" + } + } + }, + "diagnosis_required": true, + "baseline_sha256": "d9df1aa140b5050625fe8e130ec631cc25c4a11f732e369c5d018021cfc3e315" +} diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/candidate.py b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/candidate.py new file mode 100644 index 000000000..71cc6f755 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/candidate.py @@ -0,0 +1 @@ +FACTOR = 2 diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/execution.json b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/execution.json new file mode 100644 index 000000000..5aa3d982d --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/execution.json @@ -0,0 +1,20 @@ +{ + "status": "completed", + "argv": [ + "python", + "D:\\e595b\\Lib\\site-packages\\inferrsi\\harness\\optimization_session.py", + "D:\\tmp\\595wheels\\fixture-source\\pre-recovery-closure-session\\frozen\\benchmark.py", + "D:\\tmp\\595wheels\\fixture-source\\pre-recovery-closure-session\\rounds\\round-01\\attempt-31933d6970594cc18875ed81c1bfedff\\candidate.py", + "D:\\tmp\\595wheels\\fixture-source\\pre-recovery-closure-session\\rounds\\round-01\\attempt-31933d6970594cc18875ed81c1bfedff\\measurement" + ], + "cwd": "D:\\tmp\\595wheels\\fixture-source\\pre-recovery-closure-session", + "returncode": 0, + "result_path": "D:\\tmp\\595wheels\\fixture-source\\pre-recovery-closure-session\\rounds\\round-01\\attempt-31933d6970594cc18875ed81c1bfedff\\execution\\result.json", + "stdout_path": "D:\\tmp\\595wheels\\fixture-source\\pre-recovery-closure-session\\rounds\\round-01\\attempt-31933d6970594cc18875ed81c1bfedff\\execution\\stdout.log", + "stderr_path": "D:\\tmp\\595wheels\\fixture-source\\pre-recovery-closure-session\\rounds\\round-01\\attempt-31933d6970594cc18875ed81c1bfedff\\execution\\stderr.log", + "metric": null, + "metric_error": null, + "pid": 43872, + "process_group_id": null, + "elapsed_seconds": 0.3910000000614673 +} diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/stderr.log b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/stderr.log new file mode 100644 index 000000000..e69de29bb diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/stdout.log b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/execution/stdout.log new file mode 100644 index 000000000..e69de29bb diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/measurement/result.json b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/measurement/result.json new file mode 100644 index 000000000..a43af2955 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff/measurement/result.json @@ -0,0 +1 @@ +{"status": "completed", "verdict": "PASS", "score": 2} \ No newline at end of file diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/state.json b/tests/fixtures/optimization-session/pre-recovery-closure-session/state.json new file mode 100644 index 000000000..de0414674 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/state.json @@ -0,0 +1,44 @@ +{ + "schema_version": 1, + "plan_digest": "02a6e26bd3bd377d6e1eb349d82555c451c847ca49b55b251b4a56dd2c265957", + "started_at": 1795604490.891264, + "deadline": 1795604790.891264, + "state": "active", + "rounds": [], + "contexts": [], + "pending": { + "kind": "round", + "path": "rounds/round-01/attempt-31933d6970594cc18875ed81c1bfedff", + "candidate_id": "candidate-001", + "hypothesis": "Synthetic recovery control", + "strategy": null, + "knowledge_refs": null, + "observations": { + "usage": null, + "tool_calls": null, + "usage_source": null + }, + "diagnosis_id": "diagnosis-c23e299343e246c5a63c9c110183db02", + "mechanism": null, + "mechanism_sha256": null, + "candidate_sha256": "7c36fdce2c60c79132ebde2f2b52bce065b618bb6e13ec0b826dbcdb5d7bfe89", + "contexts": [], + "started_at": 1795604491.180566 + }, + "final": null, + "best": { + "path": "frozen/baseline.py", + "sha256": "d9df1aa140b5050625fe8e130ec631cc25c4a11f732e369c5d018021cfc3e315", + "score": 1.0, + "kind": "baseline" + }, + "diagnoses": [ + { + "id": "diagnosis-c23e299343e246c5a63c9c110183db02", + "bottleneck": "Reference operation", + "measurement_summary": "Synthetic workload: reference operation took 4 ms.", + "reference_epoch": null, + "recorded_at": 1795604491.0265083 + } + ] +} diff --git a/tests/fixtures/optimization-session/pre-recovery-closure-session/work/candidate.py b/tests/fixtures/optimization-session/pre-recovery-closure-session/work/candidate.py new file mode 100644 index 000000000..71cc6f755 --- /dev/null +++ b/tests/fixtures/optimization-session/pre-recovery-closure-session/work/candidate.py @@ -0,0 +1 @@ +FACTOR = 2 diff --git a/tests/fixtures/session_process.py b/tests/fixtures/session_process.py new file mode 100644 index 000000000..adab54e53 --- /dev/null +++ b/tests/fixtures/session_process.py @@ -0,0 +1,53 @@ +"""Subprocess controls for testing the optimization session boundary.""" + +import os +import subprocess +import sys +import time +import venv +from pathlib import Path + + +def target_python(tmp_path, monkeypatch, runtime): + """Model a coordinator whose site-packages shadow a target-only dependency.""" + environment = tmp_path / "target" + venv.EnvBuilder(with_pip=False, symlinks=os.name != "nt").create(environment) + python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + target_site = Path(subprocess.check_output( + [str(python), "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], + text=True, + ).strip()) + (target_site / "session_target_dependency.py").write_text("VALUE = 2\n", encoding="utf-8") + coordinator = tmp_path / "coordinator-site" + (coordinator / "inferrsi").mkdir(parents=True) + (coordinator / "session_target_dependency.py").write_text("VALUE = 99\n", encoding="utf-8") + execute = runtime._session_execute + + def execute_with_coordinator_site(*args): + with monkeypatch.context() as patch: + patch.setattr(runtime, "files", lambda name: coordinator / name) + return execute(*args) + + monkeypatch.setattr(runtime, "_session_execute", execute_with_coordinator_site) + return python + + +def kill_controller(program, arguments, marker): + """Wait for the test child to run, then kill only its controller.""" + source = Path(__file__).resolve().parents[2] / "src" + environment = {**os.environ, "PYTHONPATH": str(source)} + with subprocess.Popen( + [sys.executable, "-c", program, *arguments], env=environment, cwd=marker.parent, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) as controller: + try: + deadline = time.monotonic() + 10 + while (not marker.is_file() and controller.poll() is None + and time.monotonic() < deadline): + time.sleep(0.02) + assert marker.is_file(), f"Child did not start, controller exit: {controller.poll()}" + assert controller.poll() is None + finally: + if controller.poll() is None: + controller.kill() + controller.wait(timeout=10) diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index efa83968a..99c3055d9 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -997,12 +997,13 @@ def assert_not_importable(name): assert observed["busy_status"] != "published" and observed["busy_published"] is False, observed assert observed["released_status"] == "published", observed assert observed["released_kind"] == "progress", observed -# #498 slice 5 and #558: real sessions that main planned before a change to the runtime -# identity, each with the identity file that change removed. The installed wheel must refuse +# Real sessions that main planned before a change to the runtime identity, each with +# the identity file that change removed. The installed wheel must refuse # every one before status or recover dispatches and leave every file of it as it was. PRE_CHANGE_SESSIONS = { "pre-infra-removal-session": "infra/artifacts.py", "pre-trials-rename-session": "harness/scenarios/external.py", + "pre-recovery-closure-session": "harness/serving/server.py", } sessions_root = Path(os.environ["INFERRSI_PRE_CHANGE_SESSIONS"]) assert sorted(path.name for path in sessions_root.iterdir() if path.name.endswith("-session")) == ( diff --git a/tests/repository/check_session_imports.py b/tests/repository/check_session_imports.py new file mode 100644 index 000000000..45dc17bf3 --- /dev/null +++ b/tests/repository/check_session_imports.py @@ -0,0 +1,86 @@ +"""Corroborate the static session closure using real paths in an installed wheel.""" + +import json +import subprocess +import sys +import sysconfig +from pathlib import Path +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[2] +SESSION_TESTS = "tests/apps/test_optimization_session.py" +SERVICE_TESTS = "tests/apps/test_project_service_reuse.py" +CASES = { + "standard": ( + SESSION_TESTS, "final_report_error_preserves_execution_outcome_and_can_be_exported_later", + ), + "recover": (SESSION_TESTS, "recovery_counts_an_interrupted_round_once_and_keeps_every_step"), + "service": (SERVICE_TESTS, "one_service_order_and_independent_final_ignores_workspace"), +} + + +def observe(case, output): + import pytest + + from inferrsi.harness import optimization_session + from inferrsi.harness.session_runtime import included_module + + path = Path(optimization_session.__file__).resolve() + assert path.is_relative_to(sysconfig.get_path("purelib")), path + root = path.parents[1] + modules, phases = set(), set() + active = None + + def profile(frame, event, _): + nonlocal active + if event == "return" and frame is active: + active = None + if event != "call": + return + name = frame.f_globals.get("__name__", "") + function = frame.f_code.co_name + if (name, function) == ("inferrsi.harness.optimization_session", "session_command"): + active = frame + phases.add(frame.f_locals["args"].session_action) + if (name, function) == ("inferrsi.apps.delivery", "export_bundle"): + phases.add("export") + if active is not None and included_module(name): + modules.add(name) + + filename, node = CASES[case] + sys.setprofile(profile) + try: + result = pytest.main(["-o", "pythonpath=.", f"{filename}::test_{node}"]) + finally: + sys.setprofile(None) + assert result == 0, (case, result) + expected = {"round", "final", "status", "export"} + if case == "recover": + expected.add("recover") + assert expected <= phases, (case, expected - phases) + observed = {Path(sys.modules[name].__file__).resolve().relative_to(root).as_posix() + for name in modules} + assert observed + Path(output).write_text(json.dumps(sorted(observed)), encoding="utf-8") + + +def check(cases): + from inferrsi.harness.optimization_session import _runtime_identity + + union = set() + with TemporaryDirectory() as directory: + for case in cases: + output = Path(directory) / f"{case}.json" + subprocess.run([sys.executable, "-I", __file__, "--observe", case, str(output)], + cwd=ROOT, check=True) + union.update(json.loads(output.read_text(encoding="utf-8"))) + missing = union.difference(_runtime_identity()) + assert not missing, f"Installed session modules outside the frozen identity: {sorted(missing)}" + print(f"{len(union)} observed session modules covered across {', '.join(cases)}") + + +if __name__ == "__main__": + if sys.argv[1:2] == ["--observe"]: + observe(*sys.argv[2:]) + else: + check(sys.argv[1:] or list(CASES)) From e5afa1dccb3b3df171a1c4c8feb4d92dd33f6a89 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:39:18 +0800 Subject: [PATCH 2/5] Publish complete launch intents and record rejected spawns Agent-assisted-by: Codex / unknown [effort=unknown] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/harness/atomic_json.py | 24 ++++++++------ src/inferrsi/harness/launch_records.py | 10 ++---- src/inferrsi/harness/local_process.py | 9 +++--- tests/apps/test_optimization_session.py | 43 +++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 21 deletions(-) diff --git a/src/inferrsi/harness/atomic_json.py b/src/inferrsi/harness/atomic_json.py index 4e051fad5..d4decc462 100644 --- a/src/inferrsi/harness/atomic_json.py +++ b/src/inferrsi/harness/atomic_json.py @@ -22,7 +22,9 @@ def sync_directory(path: Path) -> None: os.close(descriptor) -def atomic_write_json(path: Path, value: object, *, durable: bool = False) -> None: +def atomic_write_json( + path: Path, value: object, *, durable: bool = False, exclusive: bool = False, +) -> None: path = Path(path) # A per-writer temporary name keeps two writers from sharing one file. temporary = path.with_name(f"{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp") @@ -33,14 +35,18 @@ def atomic_write_json(path: Path, value: object, *, durable: bool = False) -> No if durable: stream.flush() os.fsync(stream.fileno()) - for attempt in range(REPLACE_ATTEMPTS): - try: - temporary.replace(path) - break - except PermissionError: - if attempt + 1 == REPLACE_ATTEMPTS: - raise - time.sleep(REPLACE_DELAY_SECONDS) + if exclusive: + # Publish the complete file without replacing an earlier launch record. + os.link(temporary, path) + else: + for attempt in range(REPLACE_ATTEMPTS): + try: + temporary.replace(path) + break + except PermissionError: + if attempt + 1 == REPLACE_ATTEMPTS: + raise + time.sleep(REPLACE_DELAY_SECONDS) if durable: sync_directory(path.parent) finally: diff --git a/src/inferrsi/harness/launch_records.py b/src/inferrsi/harness/launch_records.py index 07f0c3cbb..4b603736f 100644 --- a/src/inferrsi/harness/launch_records.py +++ b/src/inferrsi/harness/launch_records.py @@ -1,6 +1,5 @@ """Durable launch facts for recoverable optimization attempts.""" -import json import os import sys from datetime import datetime, timezone @@ -8,7 +7,7 @@ from pathlib import Path from .artifact_primitives import digest -from .atomic_json import atomic_write_json, sync_directory +from .atomic_json import atomic_write_json def linux_process_domain() -> tuple[str | None, str | None]: @@ -38,12 +37,7 @@ def __init__(self, path: Path, argv: list[str]): "boot_id": boot_id, "pid_namespace": namespace, } - with path.open("x", encoding="utf-8") as stream: - json.dump(self.record, stream, indent=2) - stream.write("\n") - stream.flush() - os.fsync(stream.fileno()) - sync_directory(path.parent) + atomic_write_json(path, self.record, durable=True, exclusive=True) @classmethod def numbered(cls, directory: Path, stage: str, argv: list[str]) -> "LaunchRecord": diff --git a/src/inferrsi/harness/local_process.py b/src/inferrsi/harness/local_process.py index 134237ebb..4e33ddbe0 100644 --- a/src/inferrsi/harness/local_process.py +++ b/src/inferrsi/harness/local_process.py @@ -284,13 +284,12 @@ def _supervise( "elapsed_seconds": None, } started, process, windows_job, attached, launched = time.monotonic(), None, None, False, None - spawned = None + spawned = False timeout_before_launch = ("step timeout expired before command start" if step_limited else "whole-run deadline exhausted before command start") try: remaining = deadline - started if remaining <= 0: - spawned = False run.update(status="timeout", error=timeout_before_launch) else: options = ( @@ -302,14 +301,13 @@ def _supervise( windows_job = _WindowsJob() with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr: if cancellation is not None and cancellation.is_set(): - spawned = False run.update(status="cancelled", error="cancellation requested", cancellation_requested_at=_utc_now(), cancellation_source="caller") return run if time.monotonic() >= deadline: - spawned = False run.update(status="timeout", error=timeout_before_launch) return run + spawned = None process = subprocess.Popen( argv, cwd=cwd, @@ -363,6 +361,9 @@ def _supervise( ), ) except (OSError, subprocess.SubprocessError) as exc: + if process is None and isinstance(exc, (FileNotFoundError, PermissionError)): + # A rejected executable or working directory never runs the command. + spawned = False if process is not None and process.poll() is None: run["termination_requested"] = True _stop_tree(process, windows_job) diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index 7faa5bbea..4a38c60cf 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -6,6 +6,7 @@ import shutil import subprocess import sys +import time from pathlib import Path from types import SimpleNamespace @@ -419,6 +420,48 @@ def start(log): child.stdout.close() +def test_launch_intent_appears_only_after_flush_and_cannot_replace_prior_intent( + tmp_path, monkeypatch, +): + from inferrsi.harness.launch_records import LaunchRecord + + path = tmp_path / "launch-step.json" + + def fail_before_publication(_descriptor): + assert not path.exists() + raise OSError("launch record flush failed") + + with monkeypatch.context() as patch: + patch.setattr(os, "fsync", fail_before_publication) + with pytest.raises(OSError, match="launch record flush failed"): + LaunchRecord(path, ["first"]) + assert not list(tmp_path.iterdir()) + + LaunchRecord(path, ["first"]) + intent = path.read_bytes() + with pytest.raises(FileExistsError): + LaunchRecord(path, ["second"]) + assert path.read_bytes() == intent + + +def test_missing_executable_is_recorded_as_never_spawned(tmp_path): + from inferrsi.harness.launch_records import observe + from inferrsi.harness.local_process import execute_command + + execution = tmp_path / "execution" + launch_path = execution / "launch-01.json" + result = execute_command( + (str(tmp_path / "missing-executable"),), tmp_path, execution, + time.monotonic() + 30, launch_path=launch_path, + ) + assert result["status"] == "error" + record = json.loads(launch_path.read_bytes()) + assert record["state"] == "ended" + assert record["spawned"] is False + assert record["pid"] is None and record["process_group_id"] is None + assert observe(record) == "not_spawned" + + def test_recovery_counts_an_interrupted_round_once_and_keeps_every_step( session, capsys, monkeypatch, held_child, ): From 7704df312ee062e845baf7f35ac603d574f7c604 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:51:42 +0800 Subject: [PATCH 3/5] Keep durable recovery writes separate from the shared JSON helper Agent-assisted-by: Codex / unknown [effort=unknown] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/harness/atomic_json.py | 42 +++++++++++++++++------- src/inferrsi/harness/attempt_recovery.py | 6 ++-- src/inferrsi/harness/launch_records.py | 8 ++--- src/inferrsi/harness/optimization.py | 12 +++---- 4 files changed, 44 insertions(+), 24 deletions(-) diff --git a/src/inferrsi/harness/atomic_json.py b/src/inferrsi/harness/atomic_json.py index d4decc462..f98dfee01 100644 --- a/src/inferrsi/harness/atomic_json.py +++ b/src/inferrsi/harness/atomic_json.py @@ -3,6 +3,7 @@ import json import os +import tempfile import time import uuid from pathlib import Path @@ -22,19 +23,40 @@ def sync_directory(path: Path) -> None: os.close(descriptor) -def atomic_write_json( - path: Path, value: object, *, durable: bool = False, exclusive: bool = False, -) -> None: +def atomic_write_json(path: Path, value: object) -> None: path = Path(path) # A per-writer temporary name keeps two writers from sharing one file. temporary = path.with_name(f"{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp") + temporary.write_text( + json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8" + ) + try: + for attempt in range(REPLACE_ATTEMPTS): + try: + temporary.replace(path) + return + except PermissionError: + if attempt + 1 == REPLACE_ATTEMPTS: + raise + time.sleep(REPLACE_DELAY_SECONDS) + finally: + if temporary.exists(): + temporary.unlink() + + +def durable_write_json(path: Path, value: object, *, exclusive: bool = False) -> None: + """Flush a recovery record before publication and sync its directory.""" payload = json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n" + staged = tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", dir=path.parent, + prefix=f"{path.name}.", suffix=".tmp", delete=False, + ) + temporary = Path(staged.name) try: - with temporary.open("w", encoding="utf-8") as stream: + with staged as stream: stream.write(payload) - if durable: - stream.flush() - os.fsync(stream.fileno()) + stream.flush() + os.fsync(stream.fileno()) if exclusive: # Publish the complete file without replacing an earlier launch record. os.link(temporary, path) @@ -47,8 +69,6 @@ def atomic_write_json( if attempt + 1 == REPLACE_ATTEMPTS: raise time.sleep(REPLACE_DELAY_SECONDS) - if durable: - sync_directory(path.parent) + sync_directory(path.parent) finally: - if temporary.exists(): - temporary.unlink() + temporary.unlink(missing_ok=True) diff --git a/src/inferrsi/harness/attempt_recovery.py b/src/inferrsi/harness/attempt_recovery.py index 17d61866e..c75f8ba4e 100644 --- a/src/inferrsi/harness/attempt_recovery.py +++ b/src/inferrsi/harness/attempt_recovery.py @@ -6,7 +6,7 @@ import uuid from pathlib import Path -from .atomic_json import atomic_write_json +from .atomic_json import durable_write_json from .launch_records import observe from .records.evidence import bounded_record_bytes @@ -83,8 +83,8 @@ def retained(root, reference, attempt): def _write(root, path, attempt, **detail): full = root / path full.parent.mkdir(parents=True, exist_ok=True) - atomic_write_json(full, {"schema_version": 1, "session": root.name, "attempt": attempt, - "observed_at": time.time(), **detail}, durable=True) + durable_write_json(full, {"schema_version": 1, "session": root.name, "attempt": attempt, + "observed_at": time.time(), **detail}) return {"path": path, "sha256": hashlib.sha256(full.read_bytes()).hexdigest()} diff --git a/src/inferrsi/harness/launch_records.py b/src/inferrsi/harness/launch_records.py index 4b603736f..9f5a83fc6 100644 --- a/src/inferrsi/harness/launch_records.py +++ b/src/inferrsi/harness/launch_records.py @@ -7,7 +7,7 @@ from pathlib import Path from .artifact_primitives import digest -from .atomic_json import atomic_write_json +from .atomic_json import durable_write_json def linux_process_domain() -> tuple[str | None, str | None]: @@ -37,7 +37,7 @@ def __init__(self, path: Path, argv: list[str]): "boot_id": boot_id, "pid_namespace": namespace, } - atomic_write_json(path, self.record, durable=True, exclusive=True) + durable_write_json(path, self.record, exclusive=True) @classmethod def numbered(cls, directory: Path, stage: str, argv: list[str]) -> "LaunchRecord": @@ -52,7 +52,7 @@ def launched(self, run: dict) -> None: state="launched", spawned=True, pid=run["pid"], process_group_id=run["process_group_id"], started_at=run["started_at"], ) - atomic_write_json(self.path, self.record, durable=True) + durable_write_json(self.path, self.record) def ended(self, run: dict, spawned: bool | None) -> None: self.record.update( @@ -60,7 +60,7 @@ def ended(self, run: dict, spawned: bool | None) -> None: process_group_id=run["process_group_id"], started_at=run["started_at"], ended_at=run["ended_at"], status=run["status"], domain_empty=run["domain_empty"], ) - atomic_write_json(self.path, self.record, durable=True) + durable_write_json(self.path, self.record) def observe(record: dict) -> str: diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 3fc368711..722546a51 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -9,7 +9,7 @@ from . import attempt_recovery, candidates from .artifact_primitives import digest, file_lock, sha256 -from .atomic_json import atomic_write_json +from .atomic_json import atomic_write_json, durable_write_json from .records.evidence import bounded_record_bytes, sanitized_text from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES from .task_protocol import TaskProtocolError @@ -673,9 +673,9 @@ def _publish_attempt(root, plan, state, record): state["settled_at"] = time.time() state["pending"] = None observation = root / record["path"] / "observation.json" - atomic_write_json(observation, record, durable=True) + durable_write_json(observation, record) record["observation_sha256"] = sha256(observation) - atomic_write_json(root / "state.json", state, durable=True) + durable_write_json(root / "state.json", state) summary = _summary(root, plan, state) if state.get("integrity_error"): summary.update(integrity_error=state["integrity_error"], optimization_speedup=None, @@ -753,7 +753,7 @@ def evaluate_round(root: Path, *, candidate: Path | None, hypothesis: str, state["pending"] = pending if final: state["stop_reason"] = reason or "fixed_round_budget_completed" - atomic_write_json(root / "state.json", state, durable=True) + durable_write_json(root / "state.json", state) deadline = state["deadline"] - (0 if final else plan["final_reserve_seconds"]) try: execution = execute(root, directory, plan, deadline) @@ -850,7 +850,7 @@ def _recover_attempt(root, plan, state, assess, *, manual): } if not receipt_present: return _interrupted(root, plan, state, pending, reference) - atomic_write_json(root / "state.json", state, durable=True) + durable_write_json(root / "state.json", state) return status(root) if gate is not None: if blocked and not manual: @@ -862,7 +862,7 @@ def _recover_attempt(root, plan, state, assess, *, manual): state.pop("settled_at", None) state["state"] = "active" # Persist the release before assessment can create a new launch record. - atomic_write_json(root / "state.json", state, durable=True) + durable_write_json(root / "state.json", state) if pending is None: atomic_write_json(root / "summary.json", _summary(root, plan, state)) return status(root) From 853dcf1329931dc636d20e8731b362c8349524c8 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:11:18 +0800 Subject: [PATCH 4/5] Align managed recovery tests with frozen ranking policy Supply the managed policy in the direct reserve fixture and forward launch journaling separately from assessor payload fields. Agent-assisted-by: Codex / unknown [effort=unknown] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- tests/apps/test_optimization_session.py | 5 ++++- tests/apps/test_session_ranking_policy.py | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index d73292679..f0a89208a 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -694,11 +694,14 @@ def test_child_system_exit_settles_as_a_protocol_failure( def test_reserve_status_agrees_with_final_eligibility(task, tmp_path, capsys, monkeypatch, mode, rounds, can_finalize): from inferrsi.apps.cli.arguments import parser + from inferrsi.knowledge.ranking_policy import managed_ranking_policy root = tmp_path / "session" args = parser().parse_args(start_args(task, root)) args.round_mode = mode - optimization_session.session_command(args, task_source=task) + optimization_session.session_command( + args, ranking_policy_for=managed_ranking_policy, task_source=task, + ) diagnose(root, capsys) for index in range(rounds): submit(root, index + 2, capsys) diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index 3ef5438a3..2b5b0b61a 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -122,14 +122,14 @@ def test_packaged_assessor_receives_identical_evidence_across_policies(task, tmp calls = [] real_run = task_protocol.run - def observe(frozen, source_hash, operation, **inputs): + def observe(frozen, source_hash, operation, *, launch_directory=None, **inputs): if operation == "assess": assert set(inputs) == {"directory", "settings", "execution"} directory = inputs["directory"] calls.append((source_hash, inputs["settings"], inputs["execution"]["status"], (directory / "candidate.py").read_bytes(), read(directory / "measurement/result.json"))) - return real_run(frozen, source_hash, operation, **inputs) + return real_run(frozen, source_hash, operation, launch_directory=launch_directory, **inputs) monkeypatch.setattr(task_protocol, "run", observe) outcomes = [] From 8afb3f7cc9ec33f2b2ccefb40471b799b14da433 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:11:01 +0800 Subject: [PATCH 5/5] Preserve cleanup evidence when frozen inputs drift Expose the retained unconfirmed cleanup receipt with the terminal integrity diagnostic. Observe and record outstanding launches before rejecting a pending attempt that has no cleanup snapshot yet. Agent-assisted-by: Codex / unknown [effort=unknown] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/harness/optimization.py | 39 ++++++++++++----- tests/apps/test_optimization_session.py | 58 +++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 11 deletions(-) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index bed5215df..31c0a4557 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -233,9 +233,11 @@ def status(root: Path) -> dict: if control["state"] == "blocked" and control.get("integrity_error"): # A diagnostic is still readable after rejected input drift. Never expose # a selected score or a usable summary from an invalid evidence tree. + gate = control.get("cleanup_unconfirmed") return {"session": str(root), "state": "blocked", "next_action": "blocked", "can_finalize": False, "pending": control["pending"], - "integrity_error": control["integrity_error"], "summary": None} + "integrity_error": control["integrity_error"], "summary": None, + **({"cleanup_unconfirmed": gate} if gate is not None else {})} try: plan, state = _load(root) except _FrozenInputError: @@ -831,9 +833,22 @@ def _recovery_snapshot(root, gate): ) +def _record_recovery_snapshot(root, state, attempt, launches, blocked, *, receipt_present): + reference = attempt_recovery.capture(root, attempt, launches, receipt_present) + if blocked: + state["state"] = "blocked" + state["cleanup_unconfirmed"] = { + "attempt": attempt, "path": reference["path"], + "recovery_sha256": reference["sha256"], + "stages": [entry["stage"] for entry in blocked], + } + return reference + + def _reject_frozen_attempt(root, plan, state, error): pending = state["pending"] - path = root / pending["path"] / "execution/execution.json" + attempt = pending["path"] + path = root / attempt / "execution/execution.json" try: execution = json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): @@ -841,7 +856,14 @@ def _reject_frozen_attempt(root, plan, state, error): if not isinstance(execution, dict): execution = None state["integrity_error"] = str(error) - state.pop("cleanup_unconfirmed", None) + if state.get("cleanup_unconfirmed") is None: + receipt_present = execution is not None + launches = attempt_recovery.scan(root, attempt, receipt_present=receipt_present) + blocked = attempt_recovery.unconfirmed(root, state, attempt, launches) + if blocked: + _record_recovery_snapshot( + root, state, attempt, launches, blocked, receipt_present=receipt_present + ) return _settle(root, plan, state, pending, execution, None) @@ -877,14 +899,9 @@ def _recover_attempt(root, plan, state, assess, *, manual): ) blocked = attempt_recovery.unconfirmed(root, state, attempt, launches) if gate is None and (blocked or not receipt_present): - reference = attempt_recovery.capture(root, attempt, launches, receipt_present) - if blocked: - state["state"] = "blocked" - state["cleanup_unconfirmed"] = { - "attempt": attempt, "path": reference["path"], - "recovery_sha256": reference["sha256"], - "stages": [entry["stage"] for entry in blocked], - } + reference = _record_recovery_snapshot( + root, state, attempt, launches, blocked, receipt_present=receipt_present + ) if not receipt_present: return _interrupted(root, plan, state, pending, reference) durable_write_json(root / "state.json", state) diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index f0a89208a..28ad3d225 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -657,6 +657,64 @@ def should_not_assess(*args): assert (session / record["path"] / "execution/execution.json").exists() == has_receipt +@pytest.mark.parametrize("operation", ["status", "recover"]) +@pytest.mark.parametrize("recorded_gate", [False, True]) +def test_frozen_drift_retains_unconfirmed_launch( + session, monkeypatch, capsys, operation, recorded_gate, +): + from inferrsi.harness.launch_records import LaunchRecord + + def stop_during_assessment(root, attempt, plan, execution): + LaunchRecord.numbered(attempt, "protocol-assess", ["assess"]) + raise KeyboardInterrupt + + def unexpected_restart(*args, **kwargs): + pytest.fail("Invalid frozen inputs cannot start an execution or assessment") + + with monkeypatch.context() as patch: + patch.setattr(optimization_session, "_session_assess", stop_during_assessment) + with pytest.raises(KeyboardInterrupt): + submit(session, 2, capsys) + monkeypatch.setattr(optimization_session, "_session_execute", unexpected_restart) + monkeypatch.setattr(optimization_session, "_session_assess", unexpected_restart) + + state_path = session / "state.json" + pending = json.loads(state_path.read_bytes())["pending"] + command = ["benchmarks", "session"] + target = ["--session", str(session)] + if recorded_gate: + assert main([*command, "recover", *target]) == 2 + before = json.loads(capsys.readouterr().out) + assert before["pending"] == pending + + (session / "frozen/TASK.md").write_text("Changed task\n", encoding="utf-8") + assert main([*command, operation, *target]) == 2 + view = json.loads(capsys.readouterr().out) + assert view["state"] == "blocked" and view["pending"] is None + assert "Frozen task resources changed" in view["integrity_error"] + assert not view["can_finalize"] and view["summary"] is None + assert "recovery_command" not in view + gate = view["cleanup_unconfirmed"] + assert gate["attempt"] == pending["path"] + assert gate["stages"] == ["protocol-assess-0001"] + if recorded_gate: + assert gate == before["cleanup_unconfirmed"] + receipt = (session / gate["path"]).read_bytes() + assert hashlib.sha256(receipt).hexdigest() == gate["recovery_sha256"] + assert json.loads(receipt)["execution_receipt_present"] + + settled = state_path.read_bytes() + state = json.loads(settled) + assert state["cleanup_unconfirmed"] == gate + record, = state["rounds"] + assert record["assessment"]["verdict"] == "INCONCLUSIVE" + assert main([*command, "recover", *target, "--confirm-domain-empty"]) == 2 + assert json.loads(capsys.readouterr().out) == view + assert state_path.read_bytes() == settled + assert (session / gate["path"]).read_bytes() == receipt + assert (session / "calls.log").read_text().splitlines() == ["2"] + + @pytest.mark.parametrize("operation,args", [ ("arguments", "candidate, output, settings"), ("assess", "directory, settings, execution"), ])