Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 159 additions & 11 deletions src/inferrsi/harness/executor/_ordinary.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@
import hashlib
import json
import os
import stat
import sys
import time
from pathlib import Path

from ..records.artifact_primitives import sha256
from ..records.artifact_primitives import digest, sha256
from . import _benchmark_child

RECEIPT_VERSION = 1
_SHORT_CHECK_RESULT = "execution/short-check/result.json"
_LIVE_OBSERVATIONS = ("observed_empty", "live", "unobservable")
_PROCESS_FIELDS = (
("pid", "pid"), ("process_group_id", "process_group_id"), ("status", "status"),
("started_at", "process_started_at"), ("ended_at", "process_ended_at"),
)


def validate_frozen_files(frozen, expected):
paths = list(frozen.rglob("*"))
Expand Down Expand Up @@ -128,12 +137,21 @@ def _project_step(root, output, plan, end, step, source, baseline, *, sequential
launch_path=output / f"launch-{step['id']}.json")


def _read_short_check_result(directory):
from ..records.evidence import bounded_record_bytes

raw, state = bounded_record_bytes(directory, _SHORT_CHECK_RESULT, 1024 * 1024)
return raw, {
"path": _SHORT_CHECK_RESULT,
"sha256": hashlib.sha256(raw).hexdigest() if raw is not None else None,
"state": state,
}


def inspect_short_reference_check(root, directory, check, short_check, *, anchor=None):
from inferrsi.harness.evaluator.reference_guard import evaluate_short_check_result
from inferrsi.harness.records.evidence import bounded_record_bytes

relative = "execution/short-check/result.json"
raw, _ = bounded_record_bytes(directory, relative, 1024 * 1024)
raw, reference = _read_short_check_result(directory)
try:
result = json.loads(raw) if raw is not None else None
except (ValueError, RecursionError):
Expand All @@ -146,8 +164,8 @@ def inspect_short_reference_check(root, directory, check, short_check, *, anchor
return {**short_check, "reason": reason, "value": value, "current": value,
"unit": check["unit"], "metric_key": check["metric_key"], "anchor": anchor,
"drift_pct": drift, "max_drift_pct": check["max_drift_pct"],
"receipt_path": (directory / relative).relative_to(root).as_posix(),
"receipt_sha256": hashlib.sha256(raw).hexdigest() if raw is not None else None}
"receipt_path": (directory / reference["path"]).relative_to(root).as_posix(),
"receipt_sha256": reference["sha256"]}


def execute_short_reference_check(root, directory, plan, end, *, check, anchor=None):
Expand Down Expand Up @@ -180,8 +198,135 @@ def execute_short_reference_check(root, directory, plan, end, *, check, anchor=N
}, anchor=anchor)


def _project_execution_steps(settings, pending):
from ..evaluator.project import project_side_steps

kind = pending["kind"]
side = "baseline" if kind in ("baseline", "refresh") else "candidate"
steps = project_side_steps(settings, side)
if kind == "refresh" and pending.get("parent_sha256") is not None:
steps.extend(project_side_steps(settings, "candidate", prefix="parent-"))
return side, steps


def _binding(plan, pending):
context = plan.get("target_review", {}).get("context", {})
return {
"schema_version": RECEIPT_VERSION,
"attempt_id": pending["attempt_id"],
"scope": {
"plan_sha256": digest(plan),
"device_scope": context.get("device_scope"),
"measurement_scope": plan["evaluation_settings"].get("scope"),
"kind": pending["kind"],
"reference_epoch": pending.get("reference_epoch"),
},
}


def _execution_receipt(plan, pending, steps):
return {**_binding(plan, pending), "steps": steps}


def _result_reference(directory, step_id):
from ..records.service_io import safe_path

if step_id == "short-check":
_, reference = _read_short_check_result(directory)
return reference
relative = f"execution/{step_id}/result.json"
try:
path = safe_path(directory, relative)
if not stat.S_ISREG(path.lstat().st_mode):
return None
checksum = sha256(path)
Comment thread
Inference1 marked this conversation as resolved.
Resolved
except FileNotFoundError:
checksum = None
except (OSError, ValueError, RuntimeError):
return None
return {"path": relative, "sha256": checksum}


def _matches_process(launch, process):
record = launch.get("record", {})
return record.get("state") == "ended" and all(
record.get(key) == process.get(field) for key, field in _PROCESS_FIELDS
)


def _step_receipt(directory, step_id, phase, process, launch):
record = launch.get("record", {})
observation = launch["observation"]
if record and not _matches_process(launch, process):
observation = "invalid_record"
return {
"id": step_id,
"phase": phase,
"launch": {"path": f"execution/launch-{step_id}.json", "sha256": launch["sha256"]},
"result": _result_reference(directory, step_id),
"process": {key: record.get(key) for key in ("pid", "process_group_id")},
"cleanup_observation": observation,
}


def _capture_step(directory, step_id, phase, process):
from .launch_records import inspect_launch_record

launch = inspect_launch_record(directory, f"execution/launch-{step_id}.json")
return _step_receipt(directory, step_id, phase, process, launch)


def _matches_step(directory, row, step_id, phase, process, launch):
if (not isinstance(row, dict) or not isinstance(process, dict)
or launch is None or not _matches_process(launch, process)):
return False
current = _step_receipt(directory, step_id, phase, process, launch)
result = current["result"]
if result is None or result.get("state") not in (None, "present", "file_absent"):
return False
recorded = row.get("cleanup_observation")
if current["cleanup_observation"] in _LIVE_OBSERVATIONS and recorded in _LIVE_OBSERVATIONS:
current["cleanup_observation"] = recorded
return row == current


def receipt_mismatches(directory, plan, pending, execution, launches):
"""Return unbound launch paths, or None when the receipt envelope is invalid."""
receipt = execution.get("execution_receipt")
binding = _binding(plan, pending)
if (pending.get("execution_receipt_version", RECEIPT_VERSION) != RECEIPT_VERSION
or not isinstance(receipt, dict) or type(receipt.get("schema_version")) is not int
or any(receipt.get(key) != value for key, value in binding.items())):
return None

_, definitions = _project_execution_steps(plan["evaluation_settings"], pending)
steps = execution["steps"]
definitions = definitions[:len(steps)]
if [step["id"] for step in steps] != [step["id"] for step in definitions]:
return None
executed = [(step["id"], definition["phase"], step)
for definition, step in zip(definitions, steps)]
if "short_check" in execution:
executed.insert(0, ("short-check", "short-check", execution["short_check"].get("process")))
rows = receipt.get("steps")
if not isinstance(rows, list) or len(rows) != len(executed):
return None

prefix = f"{pending['path']}/execution/launch-"
by_path = {entry["path"]: entry for entry in launches
if entry["path"] and entry["path"].startswith(prefix)}
mismatches = set(by_path)
for row, (step_id, phase, process) in zip(rows, executed):
path = f"{prefix}{step_id}.json"
if _matches_step(directory, row, step_id, phase, process, by_path.get(path)):
mismatches.remove(path)
else:
mismatches.add(path)
return mismatches


def execute_project_single_side(root, directory, plan, deadline, pending):
from inferrsi.harness.evaluator.project import inspect_project_step, project_side_steps
from inferrsi.harness.evaluator.project import inspect_project_step
from inferrsi.harness.executor.candidates import identity, members, retain
from inferrsi.harness.records.atomic_json import atomic_write_json

Expand All @@ -190,6 +335,7 @@ def execute_project_single_side(root, directory, plan, deadline, pending):
workspace = output / "workspace"
workspace.mkdir(parents=True)
record = {"status": "completed", "returncode": 0, "steps": [], "source_checks": []}
receipt_steps = []
started = time.monotonic()
end = started + min(plan["evaluation_timeout_seconds"], max(0, deadline - time.time()))
guard_reason = pending.get("reference_block_reason")
Expand All @@ -199,22 +345,22 @@ def execute_project_single_side(root, directory, plan, deadline, pending):
root, directory, plan, end, check=check, anchor=pending.get("short_check_anchor"),
)
record["short_check"] = observation
receipt_steps.append(
_capture_step(directory, "short-check", "short-check", observation["process"]),
)
guard_reason = observation["reason"]
if guard_reason:
record.update(status="skipped", reference_block_reason=guard_reason)
else:
settings = plan["evaluation_settings"]
baseline, candidate = workspace / "baseline", workspace / "candidate"
source = directory / plan["candidate_name"]
side = "baseline" if kind in ("baseline", "refresh") else "candidate"
side, steps = _project_execution_steps(settings, pending)
retain(source if side == "baseline" else root / plan["baseline_path"], baseline)
steps = project_side_steps(settings, side)
sources = {"baseline": baseline}
if side == "candidate" or pending.get("parent_sha256") is not None:
retain(directory / "parent" if kind == "refresh" else source, candidate)
sources["candidate"] = candidate
if kind == "refresh":
steps.extend(project_side_steps(settings, "candidate", prefix="parent-"))
declared = {key: list(members(source)) for key, source in sources.items()}
expected = {key: identity(source) for key, source in sources.items()}
for step in steps:
Expand All @@ -223,6 +369,7 @@ def execute_project_single_side(root, directory, plan, deadline, pending):
baseline, sequential=True)
record["steps"].append({"id": step["id"], "started_at": step_start,
"ended_at": time.time(), **result})
receipt_steps.append(_capture_step(directory, step["id"], step["phase"], result))
try:
actual = {key: identity(source, declared[key]) for key, source in sources.items()}
except (OSError, ValueError):
Expand All @@ -236,5 +383,6 @@ def execute_project_single_side(root, directory, plan, deadline, pending):
if inspect_project_step(directory, settings, step, result)["status"] != "completed":
break
record["elapsed_seconds"] = time.monotonic() - started
record["execution_receipt"] = _execution_receipt(plan, pending, receipt_steps)
atomic_write_json(output / "execution.json", record)
return record
29 changes: 29 additions & 0 deletions src/inferrsi/harness/executor/launch_records.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Durable launch facts for recoverable optimization attempts."""

import hashlib
import json
import os
import sys
from datetime import datetime, timezone
Expand All @@ -8,6 +10,12 @@

from ..records.artifact_primitives import digest
from ..records.atomic_json import durable_write_json
from ..records.evidence import bounded_record_bytes

_FIELDS = (
"state", "argv_sha256", "platform", "intent_at", "boot_id", "pid_namespace",
"spawned", "pid", "process_group_id", "started_at", "ended_at", "status", "domain_empty",
)


def linux_process_domain() -> tuple[str | None, str | None]:
Expand Down Expand Up @@ -91,3 +99,24 @@ def observe(record: dict) -> str:
except OSError:
return "unobservable"
return "live"


def inspect_launch_record(root: Path, path: str) -> dict:
"""Read, hash and observe the same bounded launch record."""
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
29 changes: 2 additions & 27 deletions src/inferrsi/harness/manager/_attempt_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@
import json
import time
import uuid
from pathlib import Path

from ..executor.launch_records import observe
from ..executor.launch_records import inspect_launch_record
from ..records.atomic_json import durable_write_json
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):
Expand All @@ -30,26 +25,6 @@ def _entries(root, directory, prefix):
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
Expand All @@ -61,7 +36,7 @@ def scan(root, attempt, *, receipt_present, earlier=()):
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))
entries.extend(inspect_launch_record(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,
Expand Down
Loading
Loading