"""Parse and validate one experiment ``task.toml``. Every limit is mandatory: an unstated limit is a load error, never a default. """ from __future__ import annotations import hashlib import json import posixpath import re import tomllib from dataclasses import dataclass from pathlib import Path from typing import Literal from . import agents TASK_NAMES = {"t1", "t2", "t3", "t3flat", "t4"} RUNNERS = set(agents.NAMES) REQUIRED_LIMIT_KEYS = ("memory", "cpus", "pids", "agent_timeout_s", "eval_timeout_s") LIMIT_KEYS = REQUIRED_LIMIT_KEYS + ("check_timeout_s",) # optional: cap per compilation of a judge's own files TASK_KEYS = ("name", "agent_cwd", "prompt_file", "tools_in_container", "eval_recipe", "eval_set_version", "runners", "egress_allow") MOUNT_KEYS = ("at", "mode") MEMORY_RE = re.compile(r"^[1-9]\d*[mg]$") VERSION_RE = re.compile(r"^v\d+$") HOST_RE = re.compile(r"^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?" r"(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$") MOUNT_ROOT = "/work" class TaskError(ValueError): """A task.toml problem; the message starts with the offending key path.""" @dataclass(frozen=True) class Mount: name: str at: str mode: Literal["ro", "rw"] @dataclass(frozen=True) class Limits: memory: str cpus: float pids: int agent_timeout_s: int eval_timeout_s: int check_timeout_s: int | None = None @dataclass(frozen=True) class JudgeSpec: # complete mount set for judge containers; replaces Task.mounts for Role.JUDGE mounts: tuple[Mount, ...] @dataclass(frozen=True) class Task: name: str limits: Limits mounts: tuple[Mount, ...] agent_cwd: str prompt_file: str tools_in_container: tuple[str, ...] eval_recipe: str eval_set_version: str judge: JudgeSpec | None runners: tuple[str, ...] egress_allow: tuple[str, ...] def _fail(path: str, msg: str) -> TaskError: return TaskError(f"{path}: {msg}") def _table(raw: dict, key: str, path: str, *, required: bool = True) -> dict | None: if key not in raw: if required: raise _fail(path, "missing") return None value = raw[key] if not isinstance(value, dict): raise _fail(path, "must be a table") return value def _check_keys(table: dict, allowed, prefix: str, *, required=()) -> None: for key in table: if key not in allowed: raise _fail(f"{prefix}{key}", "unknown key") for key in required: if key not in table: raise _fail(f"{prefix}{key}", "missing") def _is_int(v) -> bool: return isinstance(v, int) and not isinstance(v, bool) def _str_list(value, path: str) -> list[str]: if not isinstance(value, list) or not all(isinstance(v, str) for v in value): raise _fail(path, "must be a list of strings") return value def _validate_limits(limits: dict) -> None: _check_keys(limits, LIMIT_KEYS, "limits.", required=REQUIRED_LIMIT_KEYS) if not isinstance(limits["memory"], str) or not MEMORY_RE.match(limits["memory"]): raise _fail("limits.memory", "must look like '8g' or '512m' (positive, lowercase unit)") cpus = limits["cpus"] if not (_is_int(cpus) or isinstance(cpus, float)) or not cpus > 0: raise _fail("limits.cpus", "must be a number > 0") for key in ("pids", "agent_timeout_s", "eval_timeout_s", "check_timeout_s"): if key in limits and (not _is_int(limits[key]) or limits[key] <= 0): raise _fail(f"limits.{key}", "must be an integer > 0") def _validate_mounts(mounts: dict, prefix: str, taken: set[str]) -> None: """Check one mount table; ``taken`` collects container paths across tables.""" for name, spec in mounts.items(): path = f"{prefix}{name}" if not isinstance(spec, dict): raise _fail(path, "must be a table with 'at' and 'mode'") _check_keys(spec, MOUNT_KEYS, f"{path}.", required=MOUNT_KEYS) at = spec["at"] if not isinstance(at, str) or not at.startswith("/"): raise _fail(f"{path}.at", "must be an absolute path") if posixpath.normpath(at) != at or not at.startswith(MOUNT_ROOT + "/"): raise _fail(f"{path}.at", f"must be a normalized path strictly under {MOUNT_ROOT}/") if at in taken: raise _fail(f"{path}.at", f"duplicate mount path {at}") taken.add(at) if spec["mode"] not in ("ro", "rw"): raise _fail(f"{path}.mode", "must be 'ro' or 'rw'") def validate(raw: dict) -> None: """Raise TaskError naming the key path of the first problem found.""" _check_keys(raw, ("task", "limits", "mounts", "judge"), "") task = _table(raw, "task", "task") _check_keys(task, TASK_KEYS, "task.", required=TASK_KEYS) _validate_limits(_table(raw, "limits", "limits")) for key in ("name", "eval_recipe"): if task[key] not in TASK_NAMES: raise _fail(f"task.{key}", f"must be one of {sorted(TASK_NAMES)}") for key in ("agent_cwd", "prompt_file"): if not isinstance(task[key], str) or not task[key]: raise _fail(f"task.{key}", "must be a non-empty string") if not task["agent_cwd"].startswith("/"): raise _fail("task.agent_cwd", "must be an absolute path") if not isinstance(task["eval_set_version"], str) or not VERSION_RE.match(task["eval_set_version"]): raise _fail("task.eval_set_version", "must look like 'v1'") for tool in _str_list(task["tools_in_container"], "task.tools_in_container"): if not tool or "/" in tool or tool in (".", ".."): raise _fail("task.tools_in_container", f"{tool!r} is not a bare file name") runners = _str_list(task["runners"], "task.runners") if not runners or not set(runners) <= RUNNERS or len(set(runners)) != len(runners): raise _fail("task.runners", f"must be a non-empty list of distinct values from {sorted(RUNNERS)}") hosts = _str_list(task["egress_allow"], "task.egress_allow") if not hosts: raise _fail("task.egress_allow", "must not be empty") for host in hosts: if not HOST_RE.match(host): raise _fail("task.egress_allow", f"{host!r} is not a hostname") mounts = _table(raw, "mounts", "mounts") taken: set[str] = set() _validate_mounts(mounts, "mounts.", taken) rw = [name for name, spec in mounts.items() if spec["mode"] == "rw"] if rw != ["answer"]: raise _fail("mounts", f"exactly one rw mount, named 'answer', is required (rw: {rw})") judge = _table(raw, "judge", "judge", required=False) if judge is not None: _check_keys(judge, ("mounts",), "judge.", required=("mounts",)) # A judge container gets its own complete mount set (it replaces the task mounts): # exactly one rw mount, the gold read-only, nothing shared with the attempt layout. judge_mounts = _table(judge, "mounts", "judge.mounts") _validate_mounts(judge_mounts, "judge.mounts.", set()) judge_rw = [name for name, spec in judge_mounts.items() if spec["mode"] == "rw"] if len(judge_rw) != 1: raise _fail("judge.mounts", f"exactly one rw mount is required for the judge (rw: {judge_rw})") if "gold" not in judge_mounts or judge_mounts["gold"]["mode"] != "ro": raise _fail("judge.mounts.gold", "a read-only 'gold' mount is required") def _mounts(table: dict) -> tuple[Mount, ...]: return tuple(Mount(name, spec["at"], spec["mode"]) for name, spec in table.items()) def _read(path: Path) -> dict: try: return tomllib.loads(Path(path).read_text(encoding="utf-8")) except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: raise _fail(str(path), f"cannot read task file: {exc}") from exc def load(path: Path) -> Task: raw = _read(path) validate(raw) t, lim = raw["task"], raw["limits"] judge = raw.get("judge") return Task( name=t["name"], limits=Limits(lim["memory"], lim["cpus"], lim["pids"], lim["agent_timeout_s"], lim["eval_timeout_s"], lim.get("check_timeout_s")), mounts=_mounts(raw["mounts"]), agent_cwd=t["agent_cwd"], prompt_file=t["prompt_file"], tools_in_container=tuple(t["tools_in_container"]), eval_recipe=t["eval_recipe"], eval_set_version=t["eval_set_version"], judge=JudgeSpec(_mounts(judge["mounts"])) if judge is not None else None, runners=tuple(t["runners"]), egress_allow=tuple(t["egress_allow"]), ) def fingerprint(path: Path) -> str: """SHA-256 of the parsed TOML in canonical JSON form (formatting-insensitive).""" canonical = json.dumps(_read(path), sort_keys=True, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() def docker_limit_args(limits: Limits) -> list[str]: cpus = limits.cpus cpus_text = str(int(cpus)) if float(cpus).is_integer() else repr(float(cpus)) return ["--memory", limits.memory, "--cpus", cpus_text, "--pids-limit", str(limits.pids)]