"""Small manifest/gate sweep around unchanged stock Legion single-case runs. One local progress file; no financial ledger, distributed registry, Slurm, provider shim, model retry, or checkpoint framework. Held (unscored) attempts are never regenerated unless the operator passes --retry-held N: each held attempt is then retried at most N times, its directory is preserved as `.held-K`, and completed attempts (including failures) are never rerun. """ from __future__ import annotations import argparse import asyncio import copy import fcntl import hashlib import json import os import re import sys from pathlib import Path import yaml def digest(value): return hashlib.sha256( json.dumps( value, sort_keys=True, separators=(",", ":"), allow_nan=False ).encode() ).hexdigest() def read(path): return json.loads(Path(path).read_text()) def save(path, value): path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(".tmp") temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") temporary.chmod(0o600) temporary.replace(path) # Held attempts are retried only when saved evidence shows an infrastructure cause. # Grader/evidence disagreements, missing rewards, unknown errors and run-guard # timeouts stay held: retrying them would resample exactly the runs a check flagged. # "agent_never_reached_team" is held (not scored) but NOT retried on its own: a model that never calls # the team looks the same, so it is retried only with an infrastructure signature in run.json. RETRYABLE_REASONS = {"user_interrupted", "interrupted_before_completion"} # Legion host statuses that mean the run ended on its own; such a run is never relabelled as interrupted. TERMINAL_HOST_STATUSES = {"finished", "completed", "failed", "timed_out", "abandoned", "cancelled", "error"} def host_never_ended(case_directory): """True only if no Legion host record exists or every record is still non-terminal (e.g. "running").""" statuses = [] for path in Path(case_directory).glob("legion/*/run.json"): try: statuses.append(str(read(path).get("status") or "")) except (OSError, ValueError): return False return all(status not in TERMINAL_HOST_STATUSES for status in statuses) RETRYABLE_ERROR_SIGNATURES = ( "'git', 'clone'", "'git', 'checkout'", "'git', 'fetch'", "'git', 'ls-remote'", # task acquisition "toomanyrequests", "error pulling image", "initializing source docker://", # registry "cannot change network policy after start", # node lacks nft modules "Agent install failed", # Pi install (network) "No space left on device", "RuntimeError: Connection error.", # provider connection drop "Failed to download verifier directory", # Harbor artifact copy ) NON_RETRYABLE_ERROR_SIGNATURES = ("disagrees with the read candidate", "No reward file found", "EvidenceError") def held_cause(case_directory, attempt): """'infrastructure' only with positive evidence; otherwise 'unverified'.""" if attempt.get("reason") in RETRYABLE_REASONS: return "infrastructure" texts = [] for path in Path(case_directory).glob("legion/*/run.json"): try: run = read(path) except (OSError, ValueError): continue texts.append(str(run.get("error") or "")) texts += [str(p.get("error") or "") for p in run.get("participants") or []] text = "\n".join(texts) if any(sig in text for sig in NON_RETRYABLE_ERROR_SIGNATURES): return "unverified" return "infrastructure" if any(sig in text for sig in RETRYABLE_ERROR_SIGNATURES) else "unverified" class Sweep: def __init__( self, config, dataset, manifests, output, *, concurrency=1, include_controls=False, executor=None, retry_held=0, ): from collab_harbor.provenance import runtime_code_identity from collab_harbor.scoring import _manifest_schedule from collab_harbor.sources import checked_relative if concurrency < 1 or len(config.agents.roster()) != 1: raise ValueError( "Use positive concurrency and one original evaluated seat (agents.count=1)" ) if not re.fullmatch(r"[0-9a-fA-F]{40}", config.task.revision): raise ValueError( "Pin task.revision to an immutable Hub commit before a sweep" ) self.config, self.dataset, self.output = ( config, Path(dataset).resolve(), Path(output).resolve(), ) self.concurrency, self.executor = concurrency, executor or self.execute if not isinstance(retry_held, int) or retry_held < 0: raise ValueError("retry_held must be a non-negative integer") self.retry_held = retry_held self.groups, self.cases, self.aliases = {}, {}, [] for relative in manifests: path = self.dataset / checked_relative(str(relative)) if any(parent.is_symlink() for parent in (path, *path.parents)): raise ValueError("Manifest paths cannot contain symlinks") original = read(path) _manifest_schedule(original) manifest = copy.deepcopy(original) manifest["tasks"] = [ row for row in original["tasks"] if include_controls or row["identity"]["variant"] != "control" ] manifest["sweep_selection"] = { "original_manifest_sha256": hashlib.sha256( path.read_bytes() ).hexdigest(), "include_controls": include_controls, "excluded_control_rows": len(original["tasks"]) - len(manifest["tasks"]), } _manifest_schedule(manifest) group = str(relative) self.groups[group] = manifest rows = {row["task_id"]: row for row in manifest["tasks"]} for row in rows.values(): canonical = row.get("canonical_task_id", row["task_id"]) if canonical not in rows: raise ValueError( "Canonical alias must be declared in its selected manifest" ) source = rows[canonical] if source["identity"]["variant"] != row["identity"]["variant"]: raise ValueError( "Canonical aliases cannot change original run roles" ) if canonical in self.cases and self.cases[canonical] != source: raise ValueError("A canonical task has inconsistent source rows") self.cases[canonical] = source gate = next( item for item in rows.values() if item["identity"]["scenario_id"] == row["identity"]["scenario_id"] and item["identity"]["variant"] == "solo" and item["identity"]["seed"] == 0 ) self.aliases.append( { "group": group, "task": row["task_id"], "canonical": canonical, "gate": gate.get("canonical_task_id", gate["task_id"]), "role": row["identity"]["variant"], } ) base = config.model_dump(mode="json") # Task selector/name/output vary per case; the actual experiment settings # and original-role endpoint configuration stay bound across resume. base.pop("name", None) base.pop("output_dir", None) base["task"].pop("selector", None) routes = { key: os.environ.get(key) for key in ( "HARNESS_VLLM_ENDPOINTS", "HARNESS_OPENAI_COMPAT", "HARNESS_OPENAI_EFFORT", "CI_TEAM_BUDGET_USD", "ANTHROPIC_BASE_URL", "OPENAI_BASE_URL", "ANTHROPIC_WORKSPACE_ID", "CI_MODEL_PROVIDER", "CI_MODEL_UPSTREAM", "CI_MODEL_BODY", ) } self.binding = digest( { "base_config": base, "runtime_sha256": runtime_code_identity()["sha256"], "manifests": self.groups, "role_routes_hash": digest(routes), "sweep_source_sha256": hashlib.sha256( Path(__file__).read_bytes() ).hexdigest(), } ) self.state = {"schema_version": 1, "binding": self.binding, "attempts": {}} def eligibility(self, case): if self.cases[case]["identity"]["variant"] == "solo": return "ready" parents = {row["gate"] for row in self.aliases if row["canonical"] == case} outcomes = [self.state["attempts"].get(parent, {}) for parent in parents] if any( row.get("status") == "complete" and row.get("record", {}).get("pass") is True and not row["record"].get("refused") and not row["record"].get("judge_failed") for row in outcomes ): return "ready" if all(row.get("status") == "complete" for row in outcomes): return "not_required" return "waiting_for_gate" def collect(self, case): from collab_harbor.legion_results import load_runs, unavailable_reason from collab_harbor.takeover_verdicts import effective_record directory = self.output / "cases" / case hosts = list((directory / "legion").glob("*/run.json")) results = list((directory / "legion").glob("*/trials/*/verifier/result.json")) if len(hosts) != 1 or len(results) != 1: return {"status": "held", "reason": "missing_trusted_host_or_verifier"} run = load_runs(results, hosts)[0] if ( run.get("fixture") is not False or run.get("identity") != self.cases[case]["identity"] ): raise ValueError( "Fixture data or mismatched canonical identity cannot enter a real sweep" ) reason = unavailable_reason(run) if reason: return { "status": "held", "reason": reason, "host_manifest": str(hosts[0]), "verifier": str(results[0]), } if run["status"] == "abandoned": evidence = run.get("partial_evidence") or {} if (evidence.get("observations") and "delivered_request_ids" in evidence and not evidence["delivered_request_ids"] and not evidence.get("actions")): # The team created a request but the agent never received one through # /read and never answered: it could not reach the team service # (network/infrastructure), not a model failure. return {"status": "held", "reason": "agent_never_reached_team", "host_manifest": str(hosts[0])} record = { "seed": run["identity"]["seed"], "pass": False, "refused": False, "judge_failed": False, "gave_in": False, } elif run["status"] == "finished": group = next( row["group"] for row in self.aliases if row["canonical"] == case ) record = effective_record(run, self.groups[group]) else: return {"status": "held", "reason": "nonterminal_native_evidence"} return { "status": "complete", "record": record, "host_manifest": str(hosts[0]), "verifier": str(results[0]), "source_hashes": { "host": hashlib.sha256(hosts[0].read_bytes()).hexdigest(), "verifier": hashlib.sha256(results[0].read_bytes()).hexdigest(), }, } async def execute(self, case): from collab_harbor.legion_config import Config directory = self.output / "cases" / case directory.mkdir(parents=True, exist_ok=True) value = self.config.model_dump(mode="json") value["name"] = self.config.name[:40] + "-" + digest(case)[:8] value["task"]["selector"] = case value["output_dir"] = str(directory / "legion") Config.model_validate(value) config_path = directory / "config.yaml" config_path.write_text(yaml.safe_dump(value, sort_keys=False)) config_path.chmod(0o600) with (directory / "launcher.log").open("wb") as log: (directory / "launcher.log").chmod(0o600) process = await asyncio.create_subprocess_exec( sys.executable, "-B", "-m", "collab_harbor.run_benchmark", "--config", str(config_path), stdout=log, stderr=asyncio.subprocess.STDOUT, ) try: await ( process.wait() ) # Only stock Legion owns the configured one-hour deadline. except asyncio.CancelledError: if process.returncode is None: process.terminate() # Explicit user cancellation only. await asyncio.shield(process.wait()) raise return self.collect(case) async def run(self): self.output.mkdir(parents=True, exist_ok=True, mode=0o700) self.output.chmod(0o700) with (self.output / ".sweep.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) state_path = self.output / "progress.json" if state_path.exists(): self.state = read(state_path) if self.state.get("binding") != self.binding: raise ValueError( "Changed source/model/manifest/config cannot resume this sweep" ) for group, manifest in self.groups.items(): save(self.output / "scoring-manifests" / group, manifest) for case, attempt in list(self.state["attempts"].items()): if attempt["status"] == "complete" and self.executor == self.execute: current = self.collect(case) if current != attempt: raise ValueError( "A completed attempt changed; held for source review" ) if ( attempt["status"] in {"running", "held"} and self.executor == self.execute ): current = self.collect(case) # Read-only recovery; never generate again. if (attempt["status"] == "running" or attempt.get("reason") == "interrupted_before_completion") and ( current.get("status") == "held" and current.get("reason") == "missing_trusted_host_or_verifier" and host_never_ended(self.output / "cases" / case)): # The sweep process died while this run was in flight (e.g. a spot # node was preempted): no result exists, an infrastructure cause. A later # re-collect keeps that reason instead of the generic one. current = {**current, "reason": "interrupted_before_completion"} self.state["attempts"][case] = current if self.retry_held: self._retire_held() save(state_path, self.state) active = {} async def one(case): try: self.state["attempts"][case] = await self.executor(case) except asyncio.CancelledError: self.state["attempts"][case] = { "status": "held", "reason": "user_interrupted", } raise except Exception as error: self.state["attempts"][case] = { "status": "held", "reason": type(error).__name__, } finally: save(state_path, self.state) try: while True: ready = [] for case in self.cases: if case in self.state["attempts"]: continue eligibility = self.eligibility(case) if eligibility == "not_required": self.state["attempts"][case] = { "status": "not_required", "reason": "original_gate_not_passed_or_excluded", } elif eligibility == "ready": ready.append(case) for case in ready[: max(0, self.concurrency - len(active))]: self.state["attempts"][case] = {"status": "running"} save(state_path, self.state) active[case] = asyncio.create_task(one(case)) if not active: break done, _ = await asyncio.wait( active.values(), return_when=asyncio.FIRST_COMPLETED ) for case, task in list(active.items()): if task in done: await task del active[case] finally: for task in active.values(): task.cancel() await asyncio.gather(*active.values(), return_exceptions=True) save(state_path, self.state) return self.state def _retire_held(self): """Move held (unscored) attempts aside so they run again; keep their evidence.""" retired = self.state.setdefault("retired_attempts", {}) for case, attempt in list(self.state["attempts"].items()): if attempt.get("status") != "held": continue if "time" in str(attempt.get("reason", "")).lower(): continue # a run guard timeout can be agent-caused: never resample it if held_cause(self.output / "cases" / case, attempt) != "infrastructure": continue # no positive evidence of an infrastructure cause: keep it held history = retired.setdefault(case, []) if len(history) >= self.retry_held: continue directory = self.output / "cases" / case moved = directory.with_name(f"{case}.held-{len(history) + 1}") if moved.exists(): raise FileExistsError(f"Refusing to overwrite preserved attempt {moved}") if directory.exists(): directory.rename(moved) history.append({**attempt, "preserved_directory": str(moved), "retry_cause": "infrastructure"}) del self.state["attempts"][case] def complete(self): return all( self.state["attempts"].get(case, {}).get("status") in {"complete", "not_required"} for case in self.cases ) def scores(self): from collab_harbor.legion_results import load_runs from collab_harbor.scoring import score_runs reports = {} for group, manifest in self.groups.items(): canonical = { row["canonical"] for row in self.aliases if row["group"] == group } attempts = [self.state["attempts"].get(case, {}) for case in canonical] files = [row["verifier"] for row in attempts if row.get("verifier")] hosts = sorted( {row["host_manifest"] for row in attempts if row.get("host_manifest")} ) reports[group] = ( score_runs(load_runs(files, hosts), manifest, allow_incomplete=True) if files else {"complete": False, "reason": "no_verified_runs"} ) save(self.output / "scores.json", reports) return reports def main(): from collab_harbor.legion_config import Config from collab_harbor.run_benchmark import ( metadata, original_role_configuration, validate_recipe, ) from collab_harbor.sources import checked_relative from collab_harbor.vendor import verify_lock parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", type=Path, required=True) parser.add_argument( "--dataset-root", type=Path, required=True, help="Matching pinned Hub snapshot already downloaded", ) parser.add_argument( "--manifest", action="append", help="Explicit relative manifest; otherwise every catalog group", ) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--concurrency", type=int, default=1) parser.add_argument( "--include-controls", action="store_true", help="Explicitly add optional baseline/control measurements; default is solo plus three test seeds", ) parser.add_argument("--plan-only", action="store_true") parser.add_argument( "--retry-held", type=int, default=0, help="Retry each held (unscored infrastructure) attempt at most N times; old attempts are kept", ) args = parser.parse_args() config = Config.load(args.config) model, profile = metadata(config) validate_recipe(config, model, profile["version"]) manifests = args.manifest or ( [row["manifest"] for row in read(args.dataset_root / "catalog.json")["groups"]] if (args.dataset_root / "catalog.json").is_file() else ["manifest.json"] ) first = read(args.dataset_root / checked_relative(manifests[0]))["tasks"][0] from collab_harbor.compact_runtime import ensure_upstream upstream = ensure_upstream( args.dataset_root / checked_relative(first["path"]) / "tests" ) verify_lock(upstream) sys.path.insert(0, str(upstream / "src")) sweep = Sweep( config, args.dataset_root, manifests, args.output, concurrency=args.concurrency, include_controls=args.include_controls, retry_held=args.retry_held, ) if args.plan_only: print( json.dumps( { "physical_cases_maximum": len(sweep.cases), "logical_rows": len(sweep.aliases), "provider_calls": 0, "include_controls": args.include_controls, } ) ) return original_role_configuration( os.environ ) # Validate original panel config before any paid case. for case, row in sweep.cases.items(): task = args.dataset_root / checked_relative(row["path"]) if not (task / "environment/model-compat/model_gateway.py").is_file(): raise ValueError( "Rebuilt task-local model-compat sidecar required; old published revision is incompatible" ) asyncio.run(sweep.run()) sweep.scores() print( json.dumps( { "progress": str(args.output / "progress.json"), "scores": str(args.output / "scores.json"), "held_attempt_retries_allowed": args.retry_held, "retired_held_attempts": sum( len(rows) for rows in sweep.state.get("retired_attempts", {}).values() ), "complete": sweep.complete(), } ) ) return 0 if sweep.complete() else 1 if __name__ == "__main__": raise SystemExit(main())