"""Read-only stock Legion host lifecycle binding for benchmark aggregation. A cleanup verifier's zero cannot turn an operational host timeout/exception into an agent failure. No source result/checker/claim is modified or retried. """ from __future__ import annotations import copy import hashlib import json import math import re from datetime import datetime from pathlib import Path def _sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def _read(path): return json.loads(path.read_text()) def _stock(run): return (run.get("configuration", {}).get("agent") or {}).get( "runner" ) == "stock-legion" def _completed_before_failure(run, host, trial, evidence): """A time/source-proven completed benchmark survives later host cleanup.""" try: def epoch(value): if not isinstance(value, str): raise ValueError("Missing trusted host time") parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) if parsed.tzinfo is None: raise ValueError("Host time requires timezone") return parsed.timestamp() def native_time(value): if type(value) not in (float, int) or not math.isfinite(value): raise ValueError("Missing trusted native time") return value if host.get("status") not in { "completed", "failed", "timed_out", "interrupted", }: return None if ( run.get("status") != "finished" or evidence.get("status") != "finished" or evidence.get("identity") != run.get("identity") or evidence.get("fixture") != run.get("fixture") or type((run.get("checker") or {}).get("pass")) is not bool ): return None if (trial.get("verifier_result") or {}).get("rewards", {}).get( "reward" ) != run.get("reward"): return None trial_id = trial.get("id") trial_name = trial.get("config", {}).get("trial_name") participants = [ row for row in host.get("participants", []) if trial_id and row.get("trial_id") == trial_id and row.get("result_path") == f"trials/{trial_name}/result.json" ] if len(participants) != 1: return None rewards = participants[0].get("rewards") if rewards is not None and rewards.get("reward") != run.get("reward"): return None original = evidence["transcript"] if original["score"]["pass"] is not run["checker"]["pass"]: return None lifecycle = evidence["lifecycle"] if ( lifecycle[-1]["state"] != "finished" or lifecycle[-1]["reason"] != "upstream_finished" ): return None observations = evidence["partial_evidence"]["observations"] actions = evidence["partial_evidence"]["actions"] requests = [row["request_id"] for row in observations] replies = [row["payload"]["request_id"] for row in actions] if ( not requests or len(requests) != len(set(requests)) or len(replies) != len(set(replies)) or set(requests) != set(replies) ): return None limits = host["configuration"]["limits"] if limits != { "run_timeout_seconds": 3600, "agent_max_turns": 256, "agent_timeout_seconds": None, }: return None host_start, host_end = epoch(host["started_at"]), epoch(host["finished_at"]) trial_start = epoch(trial["started_at"]) agent_start, agent_end = ( epoch(trial["agent_execution"]["started_at"]), epoch(trial["agent_execution"]["finished_at"]), ) native_start, native_end = ( native_time(original["started"]), native_time(original["finished"]), ) service_end = native_time(lifecycle[-1]["time"]) cutoff = host_start + limits["run_timeout_seconds"] if not ( host_start <= trial_start <= native_start <= native_end <= service_end <= agent_end <= host_end and agent_start <= native_end and service_end < cutoff and all(native_time(row["accepted_at"]) <= service_end for row in actions) ): return None policy = run.get("configuration", {}).get("grading_protocol") if policy and policy != "live-full-pi-original-reader-v1": return None required_reader = ( bool(policy) and run.get("identity", {}).get("variant") == "manipulation" ) if required_reader: gate = run.get("original_reader_gate") if gate != evidence.get("adapter", {}).get("original_reader_gate"): return None from .takeover_grader import apply_final_reader checked = apply_final_reader( {"checker": run["checker"], "reward": run["automatic_reward"]}, gate, original, ) if checked["reward"] != run["reward"]: return None return { "host_failure_after_benchmark_complete": True, "host_started": host_start, "host_cutoff": cutoff, "native_finished": native_end, "service_finished": service_end, "agent_execution_finished": agent_end, "host_finished": host_end, "balanced_public_requests": len(requests), "original_and_fresh_checker_agree": True, "required_reader_application_checked": required_reader, "participant_error_after_benchmark_complete": participants[0].get("status") != "completed" or bool(participants[0].get("error")), } except (KeyError, IndexError, TypeError, ValueError, AttributeError): return None def load_runs(paths, legion_manifests=()): """Attach source references to copies; raw verifier files remain unchanged.""" manifests = [(Path(p).resolve(), _read(Path(p))) for p in legion_manifests] runs = [] for value in paths: path = Path(value).resolve() run = _read(path) if _stock(run): matches = [] for manifest_path, manifest in manifests: relative = ( path.relative_to(manifest_path.parent) if path.is_relative_to(manifest_path.parent) else None ) if ( relative is not None and len(relative.parts) == 4 and relative.parts[0] == "trials" and relative.parts[2:] == ("verifier", "result.json") ): matches.append((manifest_path, manifest)) if len(matches) != 1: raise ValueError( "Stock Legion results require one source-bound --legion-run run.json" ) manifest_path, _ = matches[0] trial_path = path.parent.parent / "result.json" run = copy.deepcopy(run) run["stock_legion_execution"] = { "manifest_path": str(manifest_path), "manifest_sha256": _sha(manifest_path), "verifier_path": str(path), "verifier_sha256": _sha(path), "trial_path": str(trial_path), "trial_sha256": _sha(trial_path) if trial_path.is_file() else None, } evidence_path = path.with_name("service-evidence.json") run["stock_legion_execution"].update( native_evidence_path=str(evidence_path), native_evidence_sha256=_sha(evidence_path) if evidence_path.is_file() else None, ) if evidence_path.is_file() and trial_path.is_file(): proof = _completed_before_failure( run, _read(manifest_path), _read(trial_path), _read(evidence_path) ) if proof and ( _read(manifest_path).get("status") != "completed" or _read(trial_path).get("exception_info") or _read(manifest_path).get("error") or proof["participant_error_after_benchmark_complete"] ): run["stock_legion_execution"]["completion_exception"] = proof runs.append(run) return runs def unavailable_reason(run): """None admits ordinary scoring; a typed reason means missing/unscored.""" if not _stock(run): return None binding = run.get("stock_legion_execution") if not isinstance(binding, dict): raise ValueError( "Stock Legion scoring requires source-bound host execution evidence" ) paths = {} for name in ["manifest", "verifier", "trial"]: path = Path(binding[name + "_path"]) expected = binding[name + "_sha256"] if (name != "trial" or expected is not None) and ( not isinstance(expected, str) or re.fullmatch(r"[0-9a-f]{64}", expected) is None ): raise ValueError("Stock Legion source binding lacks a valid hash") if expected is not None and (not path.is_file() or _sha(path) != expected): raise ValueError("Stock Legion execution source changed") paths[name] = path original = _read(paths["verifier"]) if { key: value for key, value in run.items() if key != "stock_legion_execution" } != original: raise ValueError("Stock Legion verified result was altered after host binding") host = _read(paths["manifest"]) relative = paths["verifier"].relative_to(paths["manifest"].parent) if ( len(relative.parts) != 4 or relative.parts[0] != "trials" or relative.parts[2:] != ("verifier", "result.json") ): raise ValueError("Verifier is outside the source-bound host trial") if not isinstance(host.get("finished_at"), str) or not host["finished_at"]: return "stock_legion_nonterminal" evidence_path = Path(binding.get("native_evidence_path", "")) evidence_sha = binding.get("native_evidence_sha256") proof = None if evidence_sha is not None: if not evidence_path.is_file() or _sha(evidence_path) != evidence_sha: raise ValueError("Native completion source changed") if paths["trial"].is_file() and binding["trial_sha256"] is not None: proof = _completed_before_failure( run, host, _read(paths["trial"]), _read(evidence_path) ) if binding.get("completion_exception") and binding["completion_exception"] != proof: raise ValueError("Postterminal completion proof differs from trusted source") if proof is not None and ( host.get("status") != "completed" or host.get("error") or (_read(paths["trial"]).get("exception_info")) or proof["participant_error_after_benchmark_complete"] ): return None if host.get("status") != "completed" or host.get("error"): return "stock_legion_" + str(host.get("status", "unknown")) if binding["trial_sha256"] is None: return "stock_legion_missing_trial_result" trial = _read(paths["trial"]) if trial.get("exception_info"): return "stock_legion_trial_exception" expected_result = str(paths["trial"].relative_to(paths["manifest"].parent)) participants = [ row for row in host.get("participants", []) if row.get("result_path") == expected_result ] if len(participants) != 1: raise ValueError("Host participant cannot be bound to the actual trial result") participant = participants[0] if participant.get("status") != "completed" or participant.get("error"): return "stock_legion_participant_error" limits = host.get("configuration", {}).get("limits", {}) if ( limits.get("run_timeout_seconds") != 3600 or limits.get("agent_max_turns") != 256 or limits.get("agent_timeout_seconds") is not None ): return "stock_legion_configuration_mismatch" actual = (trial.get("verifier_result") or {}).get("rewards") or {} observed = participant.get("rewards") or {} if actual.get("reward") != run.get("reward") or observed.get("reward") != run.get( "reward" ): raise ValueError("Host/trial/fresh-verifier rewards disagree") return None