"""Pinned, resumable phase ledger for trusted offline learning runners. This is not a scheduler, an authentication boundary or a model acceptance gate. The input root may be a read-only portable store with a separate writable state_root for this run's ledger. Plans declare the actual file dependency closure; metadata references are not recursively inferred. The caller supplies the bounded Worker/container runtime and whole-phase wall budget. Run and verification subprocesses have separate explicit deadlines. A completed phase is reused only while its input and output bytes still match. Any interrupted or failed attempt reserves its phase until trusted root reconciliation; time alone never authorizes a retry. Verifiers validate artifacts, not model quality. """ import argparse import json import re import sqlite3 import subprocess import sys import threading import time import uuid from contextlib import contextmanager from pathlib import Path from dataset_store import checksum, confined, digest SCHEMA = "missioncore.learning-execution/v1" MAX_JSON = 262144 MAX_LOG = 1048576 def encoded(value): data = json.dumps(value, sort_keys=True, ensure_ascii=True, allow_nan=False) if len(data.encode()) > MAX_JSON: raise ValueError("Execution record too large") return data def pin(root, name): path = confined(root, name) if not path.is_file(): raise ValueError("Missing regular artifact: " + name) return dict(sha256=checksum(path), bytes=path.stat().st_size) def check_pins(root, pins): for name, expected in pins.items(): if pin(root, name) != expected: raise ValueError("Artifact changed: " + name) def invoke(root, argv, timeout): """No shell; deadline and in-memory output cap, no unbounded log file.""" process = subprocess.Popen( [sys.executable, "-B", str(confined(root, argv[0])), *argv[1:]], cwd=root, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) output = bytearray() overflow = threading.Event() def collect(): while chunk := process.stdout.read(65536): if len(output) + len(chunk) > MAX_LOG: overflow.set() process.kill() return output.extend(chunk) reader = threading.Thread(target=collect, daemon=True) reader.start() try: process.wait(timeout=timeout) except BaseException: process.kill() process.wait(timeout=5) raise finally: reader.join(timeout=2) if not reader.is_alive(): process.stdout.close() if reader.is_alive(): raise ValueError("Runner left an unconfirmed output producer") if overflow.is_set(): raise ValueError("Runner diagnostic output exceeded limit") text = output.decode("utf-8", errors="strict") if process.returncode: raise ValueError(f"Runner returned {process.returncode}: {text[-4000:]}") return text class Execution: def __init__(self, root, *, state_root=None, clock=time.time, runner=invoke): self.root = Path(root).resolve() if state_root is None: self.root.mkdir(parents=True, exist_ok=True) self.state_root = self.root else: if not self.root.is_dir(): raise ValueError("Pinned input root must already exist") self.state_root = Path(state_root).resolve() self.state_root.mkdir(parents=True, exist_ok=True) self.clock, self.runner = clock, runner self.db = sqlite3.connect(self.state_root / "learning-execution.sqlite3", timeout=10) self.db.row_factory = sqlite3.Row self.db.execute("PRAGMA synchronous=FULL") self.db.executescript(""" CREATE TABLE IF NOT EXISTS learning_runs ( id TEXT PRIMARY KEY, plan TEXT NOT NULL, created REAL NOT NULL); CREATE TABLE IF NOT EXISTS learning_phases ( run TEXT NOT NULL, position INTEGER NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, token TEXT, started REAL, finished REAL, receipt TEXT, incident TEXT, reconciliation TEXT, PRIMARY KEY(run,name)); """) def close(self): self.db.close() @contextmanager def transaction(self): self.db.execute("BEGIN IMMEDIATE") try: yield self.db.commit() except BaseException: self.db.rollback() raise def register(self, plan): raw = encoded(plan) if set(plan) != {"schema", "objective", "inputs", "phases"} or plan["schema"] != SCHEMA: raise ValueError("Unsupported execution plan") if not isinstance(plan["objective"], str) or not 1 <= len(plan["objective"]) <= 4096: raise ValueError("Objective required") if not isinstance(plan["inputs"], dict) or not 1 <= len(plan["inputs"]) <= 1024: raise ValueError("Bounded pinned inputs required") for name, value in plan["inputs"].items(): if ( set(value) != {"sha256", "bytes"} or not re.fullmatch(r"[0-9a-f]{64}", value["sha256"]) or type(value["bytes"]) is not int or value["bytes"] < 0 ): raise ValueError("Exact input pin required") confined(self.root, name) phases = plan["phases"] if not isinstance(phases, list) or not 1 <= len(phases) <= 12: raise ValueError("One to twelve phases required") names, outputs = set(), set() for phase in phases: if set(phase) != { "name", "run", "verify", "outputs", "run_timeout_seconds", "verify_timeout_seconds", }: raise ValueError("Exact phase contract required") name = phase["name"] if ( not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,47}", name) or name in names ): raise ValueError("Unique phase name required") names.add(name) for action in ("run", "verify"): argv = phase[action] if ( not isinstance(argv, list) or not 1 <= len(argv) <= 16 or any(not isinstance(x, str) or len(x) > 4096 or "\x00" in x for x in argv) or argv[0] not in plan["inputs"] or not argv[0].endswith(".py") ): raise ValueError("Pinned Python command required") members = phase["outputs"] if not isinstance(members, list) or not 1 <= len(members) <= 32: raise ValueError("Declared phase outputs required") for member in members: confined(self.root, member) if member in outputs or member in plan["inputs"]: raise ValueError("Output aliases another output or input") outputs.add(member) for field, limit in (("run_timeout_seconds", 7200), ("verify_timeout_seconds", 300)): if type(phase[field]) is not int or not 1 <= phase[field] <= limit: raise ValueError("Bounded per-process deadline required") check_pins(self.root, plan["inputs"]) identity = digest(plan) with self.transaction(): if self.db.execute("SELECT 1 FROM learning_runs WHERE id=?", (identity,)).fetchone(): return identity if self.db.execute( "SELECT 1 FROM learning_phases WHERE state IN ('running','unknown')" ).fetchone(): raise ValueError("An unfinished executor still owns resources") total = self.db.execute( "SELECT COALESCE(SUM(length(CAST(plan AS BLOB))),0) FROM learning_runs" ).fetchone()[0] count = self.db.execute("SELECT COUNT(*) FROM learning_runs").fetchone()[0] if total + len(raw.encode()) > 16 * 1024**2 or count >= 512: raise ValueError("Execution ledger quota reached; archive closed runs") for name in outputs: if confined(self.root, name).exists(): raise ValueError("Unowned output already exists: " + name) self.db.execute( "INSERT INTO learning_runs VALUES(?,?,?)", (identity, raw, self.clock()) ) self.db.executemany( "INSERT INTO learning_phases(run,position,name,state) VALUES(?,?,?,'pending')", [(identity, i, p["name"]) for i, p in enumerate(phases)], ) return identity def status(self, identity): run = self.db.execute("SELECT * FROM learning_runs WHERE id=?", (identity,)).fetchone() if run is None: raise ValueError("Unknown execution") phases = [] for row in self.db.execute( "SELECT * FROM learning_phases WHERE run=? ORDER BY position", (identity,) ): receipt = json.loads(row["receipt"]) if row["receipt"] else None phases.append( dict( name=row["name"], state=row["state"], token=row["token"], started=row["started"], finished=row["finished"], receipt_sha256=digest(receipt) if receipt else None, output_count=len(receipt["outputs"]) if receipt else 0, artifact_count=len(receipt["artifacts"]) if receipt else 0, incident=row["incident"], reconciled=row["reconciliation"] is not None, ) ) return dict(id=identity, phases=phases) def _context(self, identity, name): row = self.db.execute("SELECT plan FROM learning_runs WHERE id=?", (identity,)).fetchone() if row is None: raise ValueError("Unknown execution") plan = json.loads(row["plan"]) phase = next((p for p in plan["phases"] if p["name"] == name), None) if phase is None: raise ValueError("Unknown phase") previous_artifacts = {} for previous in plan["phases"]: if previous["name"] == name: break row = self.db.execute( "SELECT state,receipt FROM learning_phases WHERE run=? AND name=?", (identity, previous["name"]), ).fetchone() if row["state"] != "complete": raise ValueError("Previous phase is not complete") for member, expected in json.loads(row["receipt"])["artifacts"].items(): if member in previous_artifacts and previous_artifacts[member] != expected: raise ValueError("Conflicting previous artifact pins: " + member) previous_artifacts[member] = expected # Merge only within this boundary. Every later pre/post/resume call hashes again. # Validate conflicts before reading payloads; never let a later receipt replace a pin. check_pins(self.root, plan["inputs"]) check_pins(self.root, previous_artifacts) return plan, phase def _verify(self, identity, phase, token): before = {name: pin(self.root, name) for name in phase["outputs"]} raw = self.runner(self.root, phase["verify"], phase["verify_timeout_seconds"]) if len(raw.encode()) > MAX_JSON: raise ValueError("Verifier receipt too large") verdict = json.loads(raw) if ( set(verdict) != {"valid", "outputs", "artifacts"} or verdict["valid"] is not True or verdict["outputs"] != before ): raise ValueError("Verifier did not validate exact declared outputs") artifacts = verdict["artifacts"] if ( not isinstance(artifacts, dict) or not 1 <= len(artifacts) <= 1024 or any(artifacts.get(name) != expected for name, expected in before.items()) ): raise ValueError("Verifier artifact closure must contain exact declared outputs") for expected in artifacts.values(): if ( not isinstance(expected, dict) or set(expected) != {"sha256", "bytes"} or not isinstance(expected["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", expected["sha256"]) or type(expected["bytes"]) is not int or expected["bytes"] < 0 ): raise ValueError("Exact artifact closure pins required") check_pins(self.root, artifacts) self._context(identity, phase["name"]) return dict( schema=SCHEMA, run=identity, phase=phase["name"], token=token, outputs=before, artifacts=artifacts, artifact_validation=True, model_acceptance=False, ) def execute(self, identity, name): with self.transaction(): _, phase = self._context(identity, name) row = self.db.execute( "SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name) ).fetchone() if row["state"] == "complete": receipt = json.loads(row["receipt"]) check_pins(self.root, receipt["artifacts"]) return receipt if ( row["state"] != "pending" or self.db.execute( "SELECT 1 FROM learning_phases WHERE state IN ('running','unknown')" ).fetchone() ): raise ValueError("Unfinished executor requires root reconciliation") if any(confined(self.root, x).exists() for x in phase["outputs"]): raise ValueError("Unowned phase output exists") used = self.db.execute( "SELECT COALESCE(SUM(COALESCE(length(CAST(receipt AS BLOB)),0) + " "COALESCE(length(CAST(reconciliation AS BLOB)),0)),0) FROM learning_phases" ).fetchone()[0] if used + MAX_JSON + 8192 > 32 * 1024**2: raise ValueError("Execution receipt quota reached; archive closed runs") token = uuid.uuid4().hex self.db.execute( "UPDATE learning_phases SET state='running',token=?,started=? " "WHERE run=? AND name=?", (token, self.clock(), identity, name), ) try: self.runner(self.root, phase["run"], phase["run_timeout_seconds"]) receipt = self._verify(identity, phase, token) with self.transaction(): self._finish(identity, name, token, receipt) return receipt except BaseException as error: with self.transaction(): self.db.execute( "UPDATE learning_phases SET state='unknown',incident=? " "WHERE run=? AND name=? AND token=? AND state='running'", (str(error)[:4096], identity, name, token), ) raise def _finish(self, identity, name, token, receipt): changed = self.db.execute( "UPDATE learning_phases SET state='complete',receipt=?,finished=? " "WHERE run=? AND name=? AND token=? AND state IN ('running','unknown')", (encoded(receipt), self.clock(), identity, name, token), ).rowcount if changed != 1: raise ValueError("Executor token is stale") def reconcile(self, identity, name, token, stopped_evidence): """Trusted root attests process termination. Never launches/retries fit. A lost acknowledgement can be recovered only by the same pinned verifier. Incomplete/invalid outputs retain ownership; caller must archive and close the failed experiment explicitly, rather than rerun into partial output. """ if not isinstance(stopped_evidence, str) or not 1 <= len(stopped_evidence) <= 4096: raise ValueError("Root termination evidence required") _, phase = self._context(identity, name) row = self.db.execute( "SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name) ).fetchone() if row["state"] not in ("running", "unknown") or row["token"] != token: raise ValueError("No matching unfinished executor") receipt = self._verify(identity, phase, token) with self.transaction(): self._finish(identity, name, token, receipt) self.db.execute( "UPDATE learning_phases SET reconciliation=? WHERE run=? AND name=?", (stopped_evidence, identity, name), ) return receipt def close_failed(self, identity, name, token, stopped_evidence, archive): """Trusted root closes a stopped, archived failure; outputs are preserved.""" if not isinstance(stopped_evidence, str) or not 1 <= len(stopped_evidence) <= 4096: raise ValueError("Root termination evidence required") if not isinstance(archive, dict) or len(archive) != 1: raise ValueError("One verified failure archive required") check_pins(self.root, archive) with self.transaction(): row = self.db.execute( "SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name) ).fetchone() if row is None or row["state"] not in ("running", "unknown") or row["token"] != token: raise ValueError("No matching unfinished executor") receipt = dict( stopped_evidence=stopped_evidence, archive=archive, outputs_preserved=True, retry_authorized=False, ) self.db.execute( "UPDATE learning_phases SET state='failed',finished=?,reconciliation=? " "WHERE run=? AND name=?", (self.clock(), encoded(receipt), identity, name), ) return receipt def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("root", type=Path) parser.add_argument("--state-root", type=Path) sub = parser.add_subparsers(dest="action", required=True) register = sub.add_parser("register") register.add_argument("manifest", type=Path) for action in ("status", "execute", "reconcile", "close-failed"): command = sub.add_parser(action) command.add_argument("identity") if action != "status": command.add_argument("phase") if action in ("reconcile", "close-failed"): command.add_argument("token") command.add_argument("stopped_evidence") if action == "close-failed": command.add_argument("archive") args = parser.parse_args() run = Execution(args.root, state_root=args.state_root) try: if args.action == "register": data = args.manifest.read_bytes() if len(data) > MAX_JSON: raise ValueError("Manifest too large") result = run.register(json.loads(data)) elif args.action == "status": result = run.status(args.identity) elif args.action == "execute": result = run.execute(args.identity, args.phase) elif args.action == "reconcile": result = run.reconcile(args.identity, args.phase, args.token, args.stopped_evidence) else: result = run.close_failed( args.identity, args.phase, args.token, args.stopped_evidence, {args.archive: pin(run.root, args.archive)}, ) print(encoded(result)) finally: run.close() if __name__ == "__main__": main()