File size: 24,502 Bytes
32084d2 5873600 9653a0f 0082d1f 32084d2 0082d1f 32084d2 0082d1f 32084d2 0082d1f 9653a0f 4fea7d1 9653a0f 32084d2 9653a0f 5873600 a9b5504 5873600 32084d2 b710f09 5873600 32084d2 5873600 9653a0f 5873600 32084d2 5873600 32084d2 5873600 32084d2 5873600 4fea7d1 0082d1f 4fea7d1 5873600 9653a0f 5873600 9653a0f 5873600 32084d2 5873600 32084d2 5873600 b710f09 5873600 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | """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 `<case>.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())
|