diff --git a/app/nullius/catalogue/benchmarks/locomo/driver.py b/app/nullius/catalogue/benchmarks/locomo/driver.py index c02ba303..d924c0dd 100644 --- a/app/nullius/catalogue/benchmarks/locomo/driver.py +++ b/app/nullius/catalogue/benchmarks/locomo/driver.py @@ -94,6 +94,15 @@ def units(dataset, setup=None): return {"units": out} +def describe(dataset, **_): + out = {} + for unit in units(dataset)["units"]: + q = question(unit)[1] + text = q["question"] + out[unit] = {"title": text, "text": text, "categories": {"category": str(q["category"])}} + return {"units": out} + + # What goes into the memory for each session: the run's ``rag_mode`` option, LoCoMo's --rag-mode - dialog # (the conversation), or the authors' own released extractions, observation (facts per speaker) and # summary (one per session). How a fact or a summary is put as a turn is ours: a fact is its speaker's @@ -259,7 +268,7 @@ def oracle(unit, dir): return {"answer": gold(q)} -HANDLERS = {"units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} +HANDLERS = {"describe": describe, "units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} for line in sys.stdin: try: req = json.loads(line) diff --git a/app/nullius/catalogue/benchmarks/locomo/standard.json b/app/nullius/catalogue/benchmarks/locomo/standard.json index 1eb810a2..c6e3d3cf 100644 --- a/app/nullius/catalogue/benchmarks/locomo/standard.json +++ b/app/nullius/catalogue/benchmarks/locomo/standard.json @@ -14,6 +14,7 @@ "license": "CC-BY-NC-4.0" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" diff --git a/app/nullius/catalogue/benchmarks/longmemeval/driver.py b/app/nullius/catalogue/benchmarks/longmemeval/driver.py index 69e9320b..f10b131a 100644 --- a/app/nullius/catalogue/benchmarks/longmemeval/driver.py +++ b/app/nullius/catalogue/benchmarks/longmemeval/driver.py @@ -148,6 +148,15 @@ def units(dataset, setup=None): return {"units": [q for q in index() if kind == "all" or TYPES[q] == kind]} +def describe(dataset, **_): + out = {} + for unit in units(dataset)["units"]: + q = entry(unit) + text = q["question"] + out[unit] = {"title": text, "text": text, "categories": {"question_type": str(q["question_type"])}} + return {"units": out} + + def setup(unit, dir): q = entry(unit) dates = q.get("haystack_dates") or [""] * len(q["haystack_session_ids"]) @@ -373,7 +382,7 @@ def score_setup(unit, dir, judge): ("expansion_join", "separate"), ("gen_length", "upstream"))}}} -HANDLERS = {"units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} +HANDLERS = {"describe": describe, "units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} for line in sys.stdin: try: req = json.loads(line) diff --git a/app/nullius/catalogue/benchmarks/longmemeval/standard.json b/app/nullius/catalogue/benchmarks/longmemeval/standard.json index 7a2003fc..8ebf24a0 100644 --- a/app/nullius/catalogue/benchmarks/longmemeval/standard.json +++ b/app/nullius/catalogue/benchmarks/longmemeval/standard.json @@ -14,6 +14,7 @@ "license": "MIT" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" diff --git a/app/nullius/catalogue/benchmarks/osworld1/driver.py b/app/nullius/catalogue/benchmarks/osworld1/driver.py index 709c1aea..67695c65 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/driver.py +++ b/app/nullius/catalogue/benchmarks/osworld1/driver.py @@ -9,6 +9,8 @@ units - every task of the dataset (one of the upstream's evaluation_examples/test_*.json), as domain__id, in the file's order +describe - each task's instruction (its title the first words) and its domain, + from the task's file alone setup - the task's instruction, for the null control. For an agent (participant "agent", which the definition's driver.participant asks Nullius to send): runner.py started in the trial's @@ -164,6 +166,19 @@ def units(dataset=None, setup=None): return {"units": [f"{d}__{e}" for d, ids in meta.items() for e in ids]} +def describe(dataset=None, **_): + """Each task of the dataset from its file alone: the instruction as its text (its title the first words), + its domain as a category.""" + out = {} + for unit in units()["units"]: + domain, _eid, example = _task(unit) + text = str(example.get("instruction") or "") + line = " ".join(text.split()) + title = line if len(line) <= 100 else line[:100].rsplit(" ", 1)[0] + " ..." + out[unit] = {"title": title, "text": text, "categories": {"domain": domain}} + return {"units": out} + + def setup(unit, dir, participant=None, **_): until = time.time() + SETUP_SECONDS - REAP_SECONDS - REMOVE_SECONDS - ANSWER_SECONDS # an agent's setup's own instruction = _task(unit)[2]["instruction"] @@ -856,7 +871,8 @@ def score(unit, dir, transcript=None, answer=None, setup=None, **_): return _scored(where, "nop.py, DesktopEnv.evaluate") -HANDLERS = {"units": units, "setup": setup, "task_given": task_given, "answer": answer, "score": score, "end": end} +HANDLERS = {"units": units, "describe": describe, "setup": setup, "task_given": task_given, "answer": answer, + "score": score, "end": end} def main(): diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 42b94424..d669ffb5 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -28,6 +28,14 @@ }, "participant": true, "unit_end": true, + "describe": true, + "list_command": [ + "python3", + "{here}/driver.py", + "{here}/agents.json", + "{here}/nop.py", + "{here}/runner.py" + ], "task_given": true }, "mcp_servers": { @@ -50,6 +58,7 @@ { "id": "test_nogdrive", "label": "Without Google Drive", + "subset_of": "test_all", "summary": "The upstream's test_nogdrive.json: every task but the 8 that need a Google account's credentials.", "path": "evaluation_examples/test_nogdrive.json", "sha256": "fcb9497e93a8986407345d3012c872c9c2fed253420730fbea64ccfcace67dbb", @@ -66,6 +75,7 @@ { "id": "test_small", "label": "Small", + "subset_of": "test_all", "summary": "The upstream's test_small.json: a few tasks of each domain.", "path": "evaluation_examples/test_small.json", "sha256": "bb29275171b78728d71825b125af311d74e66bb2a6d693c45c497d380b1fc640", @@ -74,6 +84,7 @@ { "id": "test_infeasible", "label": "Infeasible", + "subset_of": "test_all", "summary": "The upstream's test_infeasible.json: tasks that cannot be done, passed by answering FAIL.", "path": "evaluation_examples/test_infeasible.json", "sha256": "1b447d0462b1bdac4b660e0dd6e6add6d01c17a9e684702c701abcffda409abb", @@ -264,6 +275,7 @@ { "id": "test_nogdrive", "label": "Without Google Drive", + "subset_of": "test_all", "summary": "The upstream's test_nogdrive.json: every task but the 8 that need a Google account's credentials. The live MBTA booking task is retired at this release.", "path": "evaluation_examples/test_nogdrive.json", "sha256": "9270c11fe809eb4c4e35a78a47cdb50717ea76557c1b9164c183e8e8b8d9ce91", @@ -280,6 +292,7 @@ { "id": "test_small", "label": "Small", + "subset_of": "test_all", "summary": "The upstream's test_small.json: a few tasks of each domain.", "path": "evaluation_examples/test_small.json", "sha256": "bb29275171b78728d71825b125af311d74e66bb2a6d693c45c497d380b1fc640", @@ -288,6 +301,7 @@ { "id": "test_infeasible", "label": "Infeasible", + "subset_of": "test_all", "summary": "The upstream's test_infeasible.json: tasks that cannot be done, passed by answering FAIL.", "path": "evaluation_examples/test_infeasible.json", "sha256": "1b447d0462b1bdac4b660e0dd6e6add6d01c17a9e684702c701abcffda409abb", @@ -310,6 +324,14 @@ }, "participant": true, "unit_end": true, + "describe": true, + "list_command": [ + "python3", + "{here}/driver.py", + "{here}/agents.json", + "{here}/nop.py", + "{here}/runner.py" + ], "task_given": true }, "setups": { diff --git a/app/nullius/execution.py b/app/nullius/execution.py index bcb809a1..183230b4 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -48,6 +48,11 @@ ``catalogue/`` are mirrored back beside the run record; remote proofs do not replace the local user's active definitions. +A run that has ended can take one more part in its own folder, where it +ran (``Execution.again``): the standard's ``rerun`` of chosen tasks of one +of its jobs, started from the job's page. It is prepared, launched, +followed and mirrored as a part is; each job's end stays its first part's. + An agent's run that fails with more to come pauses the run and the page asks: continue or stop. Every state change lands in ``runs//run.json``; ``restore`` reads those records when Nullius starts and reattaches to what @@ -255,6 +260,7 @@ class Plan: docker: bool = False # a runner that needs docker on its target though it is not Harbor (the standard's container backend) keyless: bool = False # nothing in it calls a model (the standard's controls): handed no key and no endpoint at all licences: dict = field(default_factory=dict) # the standard's on a host: {"benchmark", "names", "providers"} - what it is sent of that benchmark's licences + caps: dict = field(default_factory=dict) # a job's spending cap set on its page, {job: USD}: its next part runs under it def steps(self) -> List[dict]: return [p for p in self.parts if p.get("script")] or [{"id": "run", "label": "the run", "script": self.script}] @@ -381,17 +387,7 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl # the first command cut short. self._run_plain = run or subprocess_run self._run = run or (lambda argv, timeout=600.0, stdin=None: subprocess_run(argv, timeout, stdin, stop=self._stop)) - # an endpoint of the run's own (url_var: an OpenAI-compatible one) may check no key: it is sent the placeholder - self._key = (key if key is not None else env.get(plan.key_var, "")) or (settings.MODEL_KEY_PLACEHOLDER if plan.url_var else "") - self._url = url if url is not None else (providers.base_of(plan.url_var, env) if plan.url_var else plan.base_url) - if plan.keyless: # a run that calls no model is given nothing it could leak - self._key, self._url = "", "" - # the agent keys Settings holds (CURSOR_API_KEY, ...): a Harbor run's agent may need its own vendor's; the standard's never gets one - self._agent_keys = dict(agent_keys) if agent_keys is not None else (settings.agent_key_values(env) if plan.runner == "harbor" else {}) - if plan.runner == "standard" and (plan.recipe or {}).get("backend") == "boat": - from nullius.standard.backends import boat # the Boat key, to the standard run that starts VMs with it, and to no other command - if boat.key(env): - self._agent_keys[boat.NAME] = boat.key(env) + self._credentials(key, url, env, agent_keys) # the benchmark's licences a standard run on a host is sent: read from its store at each launch, unless given self._licences_given = licences self._redact: List[str] = [] # the licences' values sent, as text: never in a log line @@ -443,6 +439,22 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl if self.state in ALIVE: self._read_log() + def _credentials(self, key: Optional[str], url: Optional[str], env, agent_keys: Optional[Dict[str, str]] = None) -> None: + """The key, the endpoint and the agent keys the run is sent, read from ``env`` unless given: when it + starts, and again when it runs a part again (``again``).""" + plan = self.plan + # an endpoint of the run's own (url_var: an OpenAI-compatible one) may check no key: it is sent the placeholder + self._key = (key if key is not None else env.get(plan.key_var, "")) or (settings.MODEL_KEY_PLACEHOLDER if plan.url_var else "") + self._url = url if url is not None else (providers.base_of(plan.url_var, env) if plan.url_var else plan.base_url) + if plan.keyless: # a run that calls no model is given nothing it could leak + self._key, self._url = "", "" + # the agent keys Settings holds (CURSOR_API_KEY, ...): a Harbor run's agent may need its own vendor's; the standard's never gets one + self._agent_keys = dict(agent_keys) if agent_keys is not None else (settings.agent_key_values(env) if plan.runner == "harbor" else {}) + if plan.runner == "standard" and (plan.recipe or {}).get("backend") == "boat": + from nullius.standard.backends import boat # the Boat key, to the standard run that starts VMs with it, and to no other command + if boat.key(env): + self._agent_keys[boat.NAME] = boat.key(env) + def _read_log(self) -> None: self._unread = False try: @@ -554,17 +566,29 @@ def part_for(self, job_id: str) -> Optional[str]: job = next((j for j in self.plan.jobs if str(j.get("name")) == job_id), None) if job is None: return None + steps = [p for p in steps if not p.get("again")] # a part run again later writes no job of its own for p in steps: if job.get("agent") == p["id"] or job_id == f"{self.plan.name}-{p['id']}": return p["id"] return steps[0]["id"] if len(steps) == 1 else None + def again_of(self, job_id: str) -> Optional[dict]: + """The part running tasks of this job again (``again``), while it is the run's part under way; else None.""" + steps = self.plan.steps() + if self.state not in ALIVE or self.part >= len(steps): + return None + return steps[self.part] if steps[self.part].get("again") == job_id else None + def job_state(self, job_id: str) -> Optional[tuple]: """``(state, finished_at)`` for one job of this run once it has ended: a complete, error-free standard result when jobs share a part, then its own part's result when that part ran to its end - an arm that answered every question is done though a later one failed - else the - run's, once the run has ended. None while it is still to come.""" + run's, once the run has ended. None while it is still to come, or + while tasks of it run again (``again_of``); once they have, the job's + end is still its own part's.""" + if self.again_of(job_id) is not None: + return None part = self.part_for(job_id) # Conformance runs several kits in one process. Its exit code belongs # to the whole step, not to each kit that already finished cleanly. @@ -615,7 +639,7 @@ def live_state(self, job_id: str) -> Optional[str]: if self.state not in ALIVE: return None part = self.part_for(job_id) - if self.state in ("preparing", "stopping") or part is None or part == self.launched: + if self.state in ("preparing", "stopping") or part is None or part == self.launched or self.again_of(job_id) is not None: return self.state return NOT_RUN if self.state == "paused" else "queued" @@ -758,22 +782,81 @@ def _main(self) -> None: problem = self.plan.check() if problem: return self._fail("plan", problem) - harbor_model = "NULLIUS_HARBOR" in (self.plan.script + "".join(p.get("script", "") for p in self.plan.parts)) and self.plan.model - if not self._key and harbor_model: - return self._fail("credentials", f"{self.plan.key_var} is not set in Settings; the run would have no model key") - if not self._key and self.plan.runner != "harbor" and not self.plan.keyless: - return self._fail("credentials", f"{self.plan.key_var} is not set in Settings; the producers and the judge would have no model key") - if not self._url and self.plan.url_var and not self.plan.keyless and (harbor_model or self.plan.runner != "harbor"): - return self._fail("credentials", f"{self.plan.url_var} is not set in Settings; an OpenAI-compatible endpoint has no default, so the run would have nowhere to send its calls") - broken = self._line_break() - if broken: - return self._fail("credentials", broken) + missing = self._missing() + if missing: + return self._fail("credentials", missing) if not self._prepare(fresh=True): return self._parts() except Exception as e: # a step that raised is a failed run, not a dead thread self._fail(self.step or "run", f"{type(e).__name__}: {e}") + def _missing(self) -> Optional[str]: + """Why the run's key or endpoint cannot be sent, or None: not set, or holding a line break.""" + harbor_model = "NULLIUS_HARBOR" in (self.plan.script + "".join(p.get("script", "") for p in self.plan.parts)) and self.plan.model + if not self._key and harbor_model: + return f"{self.plan.key_var} is not set in Settings; the run would have no model key" + if not self._key and self.plan.runner != "harbor" and not self.plan.keyless: + return f"{self.plan.key_var} is not set in Settings; the producers and the judge would have no model key" + if not self._url and self.plan.url_var and not self.plan.keyless and (harbor_model or self.plan.runner != "harbor"): + return f"{self.plan.url_var} is not set in Settings; an OpenAI-compatible endpoint has no default, so the run would have nowhere to send its calls" + return self._line_break() + + def again(self, part: dict, env=os.environ) -> "Execution": + """One more part, in this ended run's folder where it ran - here, or on + its host: a standard ``rerun`` of chosen tasks of one of its jobs + (``part["again"]``, the job; ``standard/pages/recipe.py`` ``again``). The run + is taken up as it was started: the target made ready again (its folder + is its own, so its name is not asked), the running backend and + catalogue sent again, the key and the endpoint read now from ``env`` + and sent over stdin, the part launched detached and followed, the job + mirrored back as it goes. The part's files are its own + (``run-``): nothing of a part before is read as its. Its end is + the run's; each job's own end stays its first part's (``job_state``). + ValueError while the run lives.""" + with self._turn: + if self.state in ALIVE: + raise ValueError(f"{self.plan.name} is {self.state}: a run takes one more part once it has ended") + self.plan.parts.append(dict(part)) + self._credentials(None, None, env) + self.part = [p["id"] for p in self.plan.steps()].index(part["id"]) + self.state, self.step, self.exit_code, self.error, self.question, self.finished = "preparing", "", None, None, None, None + self.pid, self._live, self.log_offset, self.progress = None, None, 0, None + self._stop, self._decision = threading.Event(), threading.Event() + self.log(f"— {part['label']}, on {self.plan.host.label if self.on_host else 'this machine'}") + self._save() + self.thread = threading.Thread(target=self._main_again, name=f"run-{self.plan.name}", daemon=True) + self.thread.start() + return self + + def _main_again(self) -> None: + try: + missing = self._missing() + if missing: + return self._fail("credentials", missing) + if not self._prepare(fresh=False, again=True): + return + self._parts() + except Exception as e: + self._fail(self.step or "run", f"{type(e).__name__}: {e}") + + def holds(self, job_id: str) -> Optional[str]: + """Why this run cannot run tasks of its job ``job_id`` again where it + ran, or None when it can: the job's record is there - asked of its + host now, whose copy Delete launch may have taken.""" + if job_id not in {str(j.get("name")) for j in self.plan.jobs}: + return f"{self.plan.name} wrote no job {job_id}" + if not self.on_host: + return None if os.path.isfile(os.path.join(self.jobs, job_id, "result.json")) else f"This machine no longer holds {job_id}" + record = _rq(f"{self._run_dir()}/jobs/{job_id}/result.json") + rc, out = self._run_plain(self.plan.host.argv(f"[ -f {record} ] && echo @held || echo @gone", timeout=15), 30) + words = out.split() + if rc == 0 and "@held" in words: + return None + if rc == 0 and "@gone" in words: + return f"{self.plan.host.label} no longer holds {job_id}: nothing was started" + return f"{self.plan.host.label} did not say whether it holds {job_id}: " + redact.redact(out.strip()[-200:]) + def _main_resumed(self) -> None: try: self.log(f"— Nullius is back; picking the run up at {self.plan.steps()[min(self.part, len(self.plan.steps()) - 1)]['label']}") @@ -916,6 +999,7 @@ def _trial_lines(self) -> None: said = False for name in names: feed = os.path.join(self.jobs, name, "events.jsonl") + ends: Dict[str, int] = {} try: with open(feed, encoding="utf-8", errors="replace") as fh: for raw in fh: @@ -925,8 +1009,12 @@ def _trial_lines(self) -> None: ev = json.loads(raw) except ValueError: continue - key = (name, ev.get("trial")) - if ev.get("event") != "trial.end" or key in self._seen_trials: + if ev.get("event") != "trial.end" or ev.get("back"): + continue # a try put back after a Stop ended nothing new + # a trial run again ends once more in the same feed: its later ends are said too, each once + k = ends[str(ev.get("trial"))] = ends.get(str(ev.get("trial")), 0) + 1 + key = (name, ev.get("trial") if k == 1 else f"{ev.get('trial')}#{k}") + if key in self._seen_trials: continue with self._turn: # _save reads the set from the page's thread too self._seen_trials.add(key) @@ -989,7 +1077,7 @@ def _copy_back(self, run: Optional[Callable] = None, timeout: float = 900.0) -> return result - def _prepare(self, fresh: bool = True) -> bool: + def _prepare(self, fresh: bool = True, again: bool = False) -> bool: """The target ready for the parts: the tasks, and what the run needs there - for a Harbor recipe docker, here or on a host, and the Harbor it pins or, without a pin, the harbor @@ -1000,9 +1088,10 @@ def _prepare(self, fresh: bool = True) -> bool: there already, and stops before anything is sent when it is: a leftover of the same name would otherwise read as this run's parts, claimed or ended already. - A restored run's directory is its own.""" + A restored run's directory is its own, and so is the directory of a + run taken up ``again``, which is checked and said as a fresh one is.""" self.harbor = "harbor" - if fresh and not self.on_host and (self.plan.runner == "harbor" or self.plan.docker): + if (fresh or again) and not self.on_host and (self.plan.runner == "harbor" or self.plan.docker): # before a pin is built: a run here without docker would start, and every trial fail at its container why = (docker_here(self._sh) if self.plan.runner == "harbor" else docker_here(self._sh, "this recipe runs its units in containers", container.DOCKER)) @@ -1010,7 +1099,7 @@ def _prepare(self, fresh: bool = True) -> bool: self._fail("docker", why) return False pin = self.plan.harbor_pin if self.plan.runner == "harbor" else {} - if fresh and (self.on_host or pin): + if (fresh or again) and (self.on_host or pin): self.log(progress.line("plan", stages=",".join( (["harbor"] if pin else []) + (["connect", *(["uv"] if pin or self.plan.runner != "harbor" else []), *(["tasks"] if self.plan.tasks else []), *(["app"] if self.plan.runner == STANDARD else [])] @@ -1140,10 +1229,12 @@ def _app_here(self) -> Optional[tuple]: The exact code imported here travels, including source edits, so installed wheels and editable checkouts have the same behaviour. - Configuration and credential stores are not payload inputs. + Configuration and credential stores are not payload inputs; the + task sets the recipe runs are, from the user catalogue. """ try: - return standard_payload.build(app_root(self.root), catalogue=self._catalogue) + return standard_payload.build(app_root(self.root), catalogue=self._catalogue, + sets=standard_payload.recipe_sets(self.plan.recipe)) except (OSError, ValueError) as e: self._fail("app", "the standard runner could not be packed: " + str(e)[-300:]) return None diff --git a/app/nullius/migrate.py b/app/nullius/migrate.py index 5def150f..41c580c4 100644 --- a/app/nullius/migrate.py +++ b/app/nullius/migrate.py @@ -152,7 +152,7 @@ def add(dest, data, mode=0o600): bundled = Path(__file__).resolve().parent / "catalogue" source_catalogue = checkout / "app" / "nullius" / "catalogue" pending.catalogue_snapshot = source_catalogue.resolve() == bundled.resolve() - for kind in ("benchmarks", "agents", "features", "capabilities"): + for kind in ("benchmarks", "agents", "features", "capabilities", "sets"): parent = source_catalogue / kind _no_symlinks(parent) if not parent.exists(): diff --git a/app/nullius/runs/cli.py b/app/nullius/runs/cli.py index 48646b7a..fe9aa390 100644 --- a/app/nullius/runs/cli.py +++ b/app/nullius/runs/cli.py @@ -84,11 +84,17 @@ def job_row(job: parse.Job) -> dict: "state": job.state, "n_trials": len(job.trials), "n_planned": job.n_planned, + # a job begun on a part of its plan: how the part was named, and how many of the planned tasks have run + "start_with": job.start_with, + "n_tasks": job.n_tasks, + "n_tasks_run": job.n_tasks_run, "counts": job.counts, "n_resolved": job.n_resolved, "n_infra": job.n_infra, "raw_solve_rate": job.raw_solve_rate, "adjusted_solve_rate": job.adjusted_solve_rate, + # the mean graded score, over the trials run: a benchmark scored, not solved, has it and no rate + "mean_score": job.mean_score, "started_at": _stamp(job.started_at), "finished_at": _stamp(job.finished_at), } @@ -319,6 +325,10 @@ def _show(args) -> int: print(f" {row['n_trials']} trial(s) of {row['n_planned']} planned: " f"resolved {row['n_resolved']} · infra {row['n_infra']} · " f"raw {rate(row['raw_solve_rate'])} · adjusted {rate(row['adjusted_solve_rate'])}") + if job.start_with: + words = (job.runner_items or ["task", "tasks"])[1] + print(f" begun on a part: {row['n_tasks_run']} of {row['n_tasks']} planned {words} run; " + f"the rates are over those run") mix = " · ".join(f"{k} {v}" for k, v in row["counts"].items() if v) if mix: print(f" outcomes: {mix}") diff --git a/app/nullius/runs/live.py b/app/nullius/runs/live.py index d0bab9d7..72af6d5e 100644 --- a/app/nullius/runs/live.py +++ b/app/nullius/runs/live.py @@ -22,6 +22,8 @@ :data:`PROGRESS`: its step limit beside its ``step``, its agent's model calls answered and the run's cap on them. A trial's snapshot holds these three only once its feed reported one, so a feed without them folds as it always did. +A ``trial.end`` with ``back`` is a try put back in its place after the try +that followed it was stopped: the card is that try's again, at its attempt. Four rules are load-bearing, and each has a test: @@ -58,7 +60,7 @@ import json import statistics -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from datetime import datetime, timezone from pathlib import Path @@ -229,6 +231,7 @@ class TrialState: #: (ts, {token field: value}) per report — only the keys that report #: carried — for the rate window; see Board.tokens_per_sec. _series: list = field(default_factory=list, repr=False) + _previous: TrialState | None = field(default=None, repr=False) @property def state(self) -> str: @@ -338,7 +341,7 @@ def winners(self) -> list[dict]: by_task: dict = {} for t in self.trials: if t.task is not None and t.agent is not None: - by_task.setdefault(t.task, []).append(t) + by_task.setdefault(t.task, []).append(t._previous or t) order = [a for a in self.lane_order() if a is not None] out = [] for task, members in by_task.items(): @@ -509,7 +512,7 @@ def _ended(c: dict, finished_at: datetime | None) -> dict: def _counts(trials: list, n_total: int | None) -> dict: """The count block over a list of trials. ``n_total`` is what the feed declared for the job; a lane passes the trials it has seen.""" - done = [t for t in trials if t.outcome is not None] + done = [t._previous or t for t in trials if t.outcome is not None or t._previous is not None] return { # Unknown until job.prepare/job.start says, or a trial appears: a # "0 tasks" header during preparation would be a lie. @@ -527,6 +530,7 @@ def _counts(trials: list, n_total: int | None) -> dict: def _mean_reward(trials: list) -> float | None: + trials = [t._previous or t for t in trials] rewards = [t.reward for t in trials if t.outcome is not None and t.reward is not None] return sum(rewards) / len(rewards) if rewards else None @@ -556,6 +560,7 @@ def fold(events: list[Event], now: datetime | None = None, notices: list[str] | ``ts`` — replay of a finished file is exact; a live board passes the clock).""" board = Board(notices=list(notices or [])) by_id: dict[str, TrialState] = {} + manual = False def trial_of(e: Event) -> TrialState: t = by_id.get(e.trial) @@ -592,7 +597,9 @@ def trial_of(e: Event) -> TrialState: if not board.agents: board.agents = list(d.get("agents") or []) elif e.event == "job.start": + manual = board.finished_at is not None and bool(d.get("tasks")) board.started_at = e.ts + board.finished_at = None # a job begun again after its end (chosen tasks run again) runs until its next end board.n_total = _num(d.get("n_total"), int) board.n_concurrent = _num(d.get("n_concurrent"), int) board.wall_sec = _num(d.get("wall_sec")) @@ -606,6 +613,9 @@ def trial_of(e: Event) -> TrialState: elif e.event == "trial.phase": t = trial_of(e) if t.outcome is not None: + if manual: + # Result aggregates keep the earlier try while the card follows its replacement. + t._previous = replace(t) # A phase after the trial ended: Harbor retries a trial under its own name (max_retries), so this is # its next attempt, running again; what the attempt before it ended with is kept beside it. t.attempt += 1 @@ -644,6 +654,14 @@ def trial_of(e: Event) -> TrialState: t.last_line = d["line"] elif e.event == "trial.end": t = trial_of(e) + t._previous = None + if d.get("back") is True and t.outcome in (None, "cancelled") and t.attempt > 1: + # A stopped try restores the earlier result even after its cancellation end. + # The restored cost is no longer an earlier attempt's cost. + t.attempt -= 1 + t.retried.pop() + if t.cost_before is not None and _num(d.get("cost_usd")) is not None: + t.cost_before = (t.cost_before - _num(d["cost_usd"])) or None t.outcome = d["outcome"] t.reward = _num(d.get("reward")) t.score, t.parts = _num(d.get("score")), _num(d.get("parts"), int) diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index 720f3853..1b66916e 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -31,7 +31,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "19" +SCHEMA = "21" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — @@ -67,6 +67,42 @@ def _retried_cost(trial_dir: str, n: int) -> float | None: return sum(costs) if costs else None +def _rerun_mark(res: dict) -> dict: + """``standard.rerun`` of a standard trial's result, read leniently: the try a person asked for, its time and + reason as text; {} otherwise.""" + std = res.get("standard") if isinstance(res.get("standard"), dict) else {} + mark = std.get("rerun") + if not isinstance(mark, dict): + return {} + return {"by": str(mark.get("by") or "hand"), "at": str(mark.get("at") or ""), "reason": redact(str(mark.get("reason") or "")), + "replaced": mark.get("replaced") if isinstance(mark.get("replaced"), dict) else {}} + + +def _reruns(res: dict) -> list: + """A job's ``reruns`` (``standard/runner/rerun.py``), each read leniently: what a page lists of each re-run.""" + rows = res.get("reruns") + num = lambda v: v if isinstance(v, (int, float)) and not isinstance(v, bool) else None + said = lambda v: {str(k): x for k, x in v.items() if isinstance(x, (str, int, float))} if isinstance(v, dict) else {} + out = [] + for r in rows if isinstance(rows, list) else (): + if not isinstance(r, dict): + continue + replaced = [x for x in r.get("replaced") or [] if isinstance(x, dict)] if isinstance(r.get("replaced"), list) else [] + begun = [x for x in r.get("begun") or [] if isinstance(x, dict)] if isinstance(r.get("begun"), list) else [] + empty = [str(t) for t in r.get("no_result") or [] if isinstance(t, str)] if isinstance(r.get("no_result"), list) else [] + out.append({"at": str(r.get("at") or ""), "finished_at": str(r.get("finished_at") or ""), + "reason": redact(str(r.get("reason") or "")), + "trials": [str(t) for t in r.get("trials") or [] if isinstance(t, str)] if isinstance(r.get("trials"), list) else [], + "replaced": [{"trial": str(x.get("trial") or ""), "unit": str(x.get("unit") or ""), "try": num(x.get("try")), + "was": said(x.get("was")), "now": said(x.get("now"))} for x in replaced], + # the tasks it began, planned and never begun before; the trials it took that had no result + **({"begun": [{"trial": str(x.get("trial") or ""), "unit": str(x.get("unit") or ""), "now": said(x.get("now"))} + for x in begun]} if begun else {}), + **({"no_result": empty} if empty else {}), + "max_usd": num(r.get("max_usd")), "spent_usd": num(r.get("spent_usd")), "stopped": r.get("stopped") is True}) + return out + + def _retries_of(res: dict) -> int: """``standard.retries`` of a standard trial's result or job's config: the retries the trial took, or each attempt could take. 0 otherwise.""" @@ -296,6 +332,10 @@ class Trial: # `standard.retries`). 0 when it did not, or does not say: Harbor retries # under the trial's own name and keeps no count in it. n_retries: int = 0 + # A try a person asked for after the run ended (``standard.rerun``: by + # "hand", ``at``, ``reason``, the result it ``replaced``); {} for every + # other try. + rerun: dict = field(default_factory=dict) # What the tries before this one cost, summed: kept in the job's # `retried/` (`tries`), never a trial of their own, but paid for all the # same, so the job's cost counts them (`Job.total_cost_usd`). None when @@ -452,6 +492,19 @@ class Job: launch_id: str = "" # Source job names explicitly recorded by standard merge. merged_from: list[str] = field(default_factory=list) + # The task set a Nullius standard job ran (config ``standard.task_set``): its name, its label (its name for a + # job from before labels) and id, its benchmark, and ``units``, its number of ids. {} for every other job. + task_set: dict = field(default_factory=dict) + # A Nullius standard job planned on a whole and begun on a part of it (config ``standard.start_with``): how the + # part was named, ``by`` count, file, set or ids (named one by one), and ``name`` (the file's, the set's label, + # "the tasks chosen" for ids; "" for a count), + # and ``units``, the part's number of units. {} for every other job: the plan is then the job's from the start. + start_with: dict = field(default_factory=dict) + # Each time chosen trials of a Nullius standard job were run again in it (``result.json`` ``reruns``, + # ``standard/runner/rerun.py``): {at, reason, trials, replaced [{trial, unit, try, was, now}], begun [{trial, unit, + # now}] and no_result [trial] when it had any, max_usd, spent_usd, stopped}, oldest first. [] for a job never + # run again. + reruns: list = field(default_factory=list) # How the job was launched, as its config.json recorded it with Harbor's # defaults filled in (launch_of). Empty when config.json is absent. launch: dict = field(default_factory=dict) @@ -493,6 +546,13 @@ def n_planned(self) -> int: recorded one, else the task count from the config.""" return self.n_total_trials or self.n_tasks + @property + def n_tasks_run(self) -> int: + """How many of the job's tasks have an attempt that ended: of ``n_tasks`` planned, for a job begun on a + part of its plan (``start_with``) the tasks run so far.""" + return len({re.sub(r"(__u\d+)r\d+$", r"\1", t.trial_name) if self.standard else t.task_name + for t in self.trials}) + @property def is_running(self) -> bool: """Trials still executing or queued — the run isn't over yet.""" @@ -857,6 +917,7 @@ def parse_trial(job_id: str, trial_dir: str) -> Trial | None: has_trace=os.path.isfile(trace_path), n_rate_limited_retries=count_rate_limits(os.path.join(trial_dir, "agent", "gateway.log")), n_retries=_retries_of(res), + rerun=_rerun_mark(res), retried_cost_usd=_retried_cost(trial_dir, _retries_of(res)), env_type=((res.get("config") or {}).get("environment") or {}).get("type", ""), started_at=_iso(res.get("started_at")), @@ -1198,8 +1259,21 @@ def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job: job.launch_id = str(std.get("launch") or "") merged = std.get("merged_from") job.merged_from = [s["job"] for s in merged if isinstance(s, dict) and isinstance(s.get("job"), str) and s["job"]] if isinstance(merged, list) else [] + ts = std.get("task_set") if isinstance(std.get("task_set"), dict) else {} + job.task_set = ({"name": str(ts["name"]), "label": str(ts.get("label") or ts["name"]), + "id": str(ts.get("id") or ""), "benchmark": str(std.get("benchmark") or ""), + "units": len(ts["units"]) if isinstance(ts.get("units"), list) else 0} + if isinstance(ts.get("name"), str) and ts["name"] else {}) + sw = std.get("start_with") if isinstance(std.get("start_with"), dict) else {} + if isinstance(sw.get("units"), list): + src = sw.get("units_file") if isinstance(sw.get("units_file"), dict) else sw.get("task_set") if isinstance(sw.get("task_set"), dict) else {} + by = "file" if sw.get("units_file") else "set" if sw.get("task_set") else "count" if "count" in sw else "ids" + job.start_with = {"by": by, "units": len(sw["units"]), + "name": (str(src.get("label") or src.get("name") or "") if by == "set" else "the tasks chosen" if by == "ids" + else str(src.get("name") or ""))} job.budget = _budget(res.get("budget")) job.identity = identity_of(cfg, res, job.agent_version) + job.reruns = _reruns(res) job.standard = bool(std) setup = std.get("setup") if isinstance(std.get("setup"), dict) else {} was = (std.get("benchmark_options") or {}).get("agent") if isinstance(std.get("benchmark_options"), dict) else None diff --git a/app/nullius/standard/calls/ledger.py b/app/nullius/standard/calls/ledger.py index 6eb85de8..a0381c08 100644 --- a/app/nullius/standard/calls/ledger.py +++ b/app/nullius/standard/calls/ledger.py @@ -119,15 +119,25 @@ def __init__(self, path: str): self.path = path @classmethod - def create(cls, path: str, max_usd: Optional[float] = None, unit_max_usd: Optional[float] = None) -> "Ledger": - """``max_usd``: the run's cap, or None for a run with a cap per unit alone. ``unit_max_usd``: each unit's.""" + def create(cls, path: str, max_usd: Optional[float] = None, unit_max_usd: Optional[float] = None, + seen: Optional[dict] = None) -> "Ledger": + """``max_usd``: the run's cap, or None for a run with a cap per unit alone. ``unit_max_usd``: each unit's. + ``seen``: the replies earlier parts of the job had from each model ([count, output tokens]), so that a later + part's first calls are booked at their average, not guessed.""" os.makedirs(os.path.dirname(path), exist_ok=True) led = cls(path) led._write({"max_usd": None if max_usd is None else float(max_usd), "unit_max_usd": None if unit_max_usd is None else float(unit_max_usd), - "spent_usd": 0.0, "unsettled_usd": 0.0, "held": {}, "closed": False, "seen": {}, "units": {}, "of": {}}) + "spent_usd": 0.0, "unsettled_usd": 0.0, "held": {}, "closed": False, "seen": dict(seen or {}), "units": {}, "of": {}}) return led + def replies(self) -> dict: + """The replies this ledger has had from each model, {model: [count, output tokens]}; {} when it cannot be read.""" + try: + return {m: list(v) for m, v in self._read()["seen"].items()} + except (OSError, ValueError, KeyError, TypeError): + return {} + @contextlib.contextmanager def _locked(self): try: diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 9449e5fe..2998b417 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -12,6 +12,11 @@ PYTHONPATH=app python3 -m nullius.standard.cli prove BENCHMARK[@VERSION] [--dataset D] [--limit N] [--bench-option NAME=VALUE ...] [--job nop|oracle=JOB_DIR ...] PYTHONPATH=app python3 -m nullius.standard.cli run ... --shard I/N [--launch ID] PYTHONPATH=app python3 -m nullius.standard.cli merge JOB_DIR... -o OUT [--force] + PYTHONPATH=app python3 -m nullius.standard.cli set create|list|show|rename|delete|import ... + PYTHONPATH=app python3 -m nullius.standard.cli run ... --set NAME + PYTHONPATH=app python3 -m nullius.standard.cli run ... --start-with N|FILE|set:NAME|ids:ID,ID... + PYTHONPATH=app python3 -m nullius.standard.cli units BENCHMARK --dataset D [--search TEXT] [--category FIELD=VALUE ...] [--json] + PYTHONPATH=app python3 -m nullius.standard.cli rerun JOB_DIR (--unit ID ... | --units FILE | --unfinished | --next N | --set NAME) [--reason TEXT] [-j N] [--retries N] [--max-usd USD] PYTHONPATH=app python3 -m nullius.standard.cli fidelity AGENT --model M [--provider P] [--option NAME=VALUE ...] [--passes N] --unsandboxed An agent runs commands as you on the local backend, which is not a sandbox: @@ -43,7 +48,15 @@ ``--limit``), the job recording its shard and its launch (``--launch``); ``--units FILE`` runs only the units a file lists (``run.units_file``: one id a line), read on the machine the command runs on, ``--from-run`` or not; ``merge`` -puts a launch's shard jobs together into one job (``standard/runner/merge.py``). ``--option`` +puts a launch's shard jobs together into one job (``standard/runner/merge.py``); ``rerun`` runs +chosen tasks of an ended job again in that job, with its settings, each earlier +try kept (``standard/runner/rerun.py``). ``run --start-with`` plans the whole and +begins a part of it; ``rerun --next``, ``--set`` or ``--unfinished`` runs the +rest in the job later. ``set`` +keeps a named list of a benchmark's units in the user catalogue, frozen once +made (``standard/runner/sets.py``), and ``run --set NAME`` runs one: its dataset taken +from it, the job recording which set ran. ``units`` lists a +dataset's tasks, searched and counted by category (``standard/runner/units.py``). ``--option`` sets one of the agent's or capability's options (``options`` in its definition); the rest keep the vendor's defaults, and the job's config records them all. ``--served-by [MODEL=]SLUG[,SLUG...]`` lets only those serving providers answer @@ -88,7 +101,8 @@ from nullius.standard.calls import exchanges from nullius.standard.contract import definitions, match, ports, proofs from nullius.standard.proofs import conform, fidelity, pins, prove -from nullius.standard.runner import job, merge, run, shard +from nullius.standard.runner import job, merge, rerun, run, sets, shard +from nullius.standard.runner import units as unit_list ENV_FILE = paths.settings_file() @@ -550,6 +564,14 @@ def _bench(key): def cmd_run(a): b = _bench(a.benchmark) + task_set, dataset, bench_options = None, a.dataset, options(a.bench_option) + if a.task_set is not None: + # the set's dataset over the run's, refused where it differs: before anything starts + try: + task_set, dataset = sets.for_run(b, a.task_set, dataset=a.dataset, units_given=a.units is not None) + except sets.Refused as e: + print("refused:", e) + return 2 if a.other in definitions.CONTROLS: other = definitions.control(b, a.other) if other is None: @@ -583,18 +605,25 @@ def cmd_run(a): price_list.update() except ValueError as e: unreachable = str(e) + try: + part = start_with(b, a.start_with) if a.start_with is not None else None + except (run.Refused, sets.Refused) as e: + print("refused:", e) + return 2 held, spill = licences(b, from_run=a.from_run) try: - job, failed = run.run_and_report(b, other, model=a.model or "", provider=a.provider, dataset=a.dataset, limit=a.limit, + job, failed = run.run_and_report(b, other, model=a.model or "", provider=a.provider, dataset=dataset, limit=a.limit, concurrency=a.concurrency, jobs_root=a.jobs, name=a.name, unsandboxed=a.unsandboxed, judge_model=a.judge_model, backend=a.backend, boat_size=a.boat_size, relay_container=a.relay_container, simulator_model=a.simulator_model, options=options(a.option), shard=_shard(a.shard), launch=a.launch, - shard_by=a.shard_by, licences=held, bench_options=options(a.bench_option), repeat=a.repeat, retries=a.retries, + shard_by=a.shard_by, licences=held, bench_options=bench_options, repeat=a.repeat, retries=a.retries, remove_images=a.remove_images, prices=prices(a.price), max_usd=a.max_usd, max_usd_per_unit=a.max_usd_per_unit, prices_unreachable=unreachable, constraints=given, timeouts=timeouts(a.timeout), max_turns=a.max_turns, max_calls=a.max_calls, exchanges=a.exchanges, exchanges_max_mb=a.exchanges_max_mb, **({"units_file": run.units_file(a.units)} if a.units is not None else {}), + **({"task_set": task_set} if task_set else {}), + **({"start_with": part} if part else {}), **({"served_by": run.served_by(a.served_by, a.model or "")} if a.served_by else {}), **({"env": run_env(a.provider)} if a.from_run else {})) except run.Refused as e: @@ -610,6 +639,33 @@ def cmd_run(a): return 3 if failed else 0 +def start_with(bench: dict, value: str) -> dict: + """``run --start-with``: the part a run begins with (``run.Run``'s ``start_with``). A whole number is a count, + ``set:NAME`` a task set of the benchmark, ``ids:ID,ID,...`` the units named there (the run builder's form), + anything else a file of ids (``run.units_file``).""" + value = value.strip() + if value.isdigit(): + if int(value) < 1: + raise run.Refused(f"--start-with {value}: begin with one unit at least") + return {"count": int(value)} + if value.startswith("ids:"): + ids = value[4:].split(",") + if not value[4:] or any(not u or u != u.strip() or u.startswith("#") for u in ids): + raise run.Refused(f"--start-with ids:ID,ID,...: ids separated by commas, none empty or with a space around it") + twice = sorted({u for u in ids if ids.count(u) > 1}) + if twice: + raise run.Refused(f"--start-with ids: {', '.join(twice)} given more than once") + return {"ids": ids} + if value.startswith("set:"): + name, rev = sets.split_ref(value[4:]) + entry = sets.load(bench["key"], name) + return {"task_set": sets.record(entry, sets.latest(entry, rev)), "dataset": entry["dataset"]} + try: + return {"units_file": run.units_file(value)} + except run.Refused as e: + raise run.Refused(str(e).replace("--units", "--start-with", 1)) + + def boat_credentials(a, bench, other, vals) -> dict: """Only the selected provider and declared benchmark licences cross SSH stdin.""" import base64 @@ -739,6 +795,280 @@ def cmd_merge(a): return 0 +SET_EPILOG = """\ +A set is frozen once made: another list of tasks is another set. Its name is +any words; the name commands take is made from them, in lower case with +hyphens ("first ten" makes first-ten), with -2 and on for a second equal one. + +examples: + nullius standard set create humaneval "first ten" --dataset humaneval --units ten.txt --description "a quick look" + nullius standard set create humaneval misses --from-job jobs_standard/JOB --outcome failed,infra + nullius standard set create osworld1@044bc33 "chrome tabs" --dataset test_nogdrive --search tab --category domain=chrome + nullius standard set show humaneval first-ten --json + nullius standard set rename humaneval misses "misses of June" + nullius standard set delete humaneval misses-of-june + nullius standard run humaneval reference --model M --set first-ten --unsandboxed + +exit codes: + 0 done + 1 unexpected error (a traceback: report it) + 2 usage, or refused: a name not allowed, a list the set cannot hold, an import that conflicts, + an entry of the earlier format + 3 not found: no such benchmark, set, file or job +""" + + +def _refused(e: Exception) -> int: + print(f"refused: {e}", file=sys.stderr) + return 3 if isinstance(e, (sets.NotFound, unit_list.NotFound)) else 2 + + +def _listed_units(path: str) -> list: + """A ``--units`` file's ids, read by the rules ``run --units`` reads it by.""" + if not os.path.isfile(path): + raise sets.NotFound(f"--units {path}: no such file") + try: + return run.units_file(path)["units"] + except run.Refused as e: + raise sets.Refused(str(e)) + + +def _set_rows(entry: dict) -> dict: + last = sets.latest(entry) + return {"benchmark": entry["benchmark"], "name": entry["name"], "label": sets.label_of(entry), "id": entry["id"], + "units": len(last["units"]), "dataset": entry["dataset"], "version": entry.get("version") or "", + "description": entry.get("description") or ""} + + +def _find_bench(key): + """A benchmark of the catalogue, or a conformance kit, by its key; None when there is none.""" + return definitions.get("benchmark", key) or next((k for k in definitions.kits() if k["key"] == key), None) + + +def cmd_set_create(a): + b = _find_bench(a.benchmark) + if b is None: + raise sets.NotFound(f"no benchmark {a.benchmark!r}") + filtered = a.search is not None or bool(a.category) + if sum((a.units is not None, a.from_job is not None, filtered)) != 1: + raise sets.Refused("set create: --units FILE, --from-job JOB_DIR, or --search and --category") + if a.from_job is None and (a.outcome or a.unit): + raise sets.Refused("--outcome and --unit choose a job's trials: give them with --from-job") + if a.units is not None: + dataset = sets._dataset(b, a.dataset) + got = {"dataset": dataset, "units": _listed_units(a.units), "note": f"from {os.path.basename(a.units)}"} + elif filtered: + # the ids the listing matches today, under the benchmark's default options; the note keeps the filter + dataset = sets._dataset(b, a.dataset) + chosen = unit_list.categories_of(a.category) + found = unit_list.find(b, dataset, search=a.search or "", categories=chosen, size=None) + if not found["total"]: + raise sets.Refused(f"no task of {dataset} matches {unit_list.filter_text(a.search or '', chosen)}") + got = {"dataset": dataset, "units": [t["id"] for t in found["tasks"]], + "note": f"matched by {unit_list.filter_text(a.search or '', chosen)}"} + else: + got = sets.from_job(b, a.from_job, a.outcome, a.unit) + if a.dataset and a.dataset != got["dataset"]: + raise sets.Refused(f"--dataset {a.dataset}: the job ran the dataset {got['dataset']}") + entry = sets.create(b, a.label, dataset=got["dataset"], units=got["units"], description=a.description, note=got["note"]) + print(f"wrote {sets.path_of(entry['benchmark'], entry['name'])}: {_named(entry)}, " + f"{len(got['units'])} {b['units']['nouns'] if len(got['units']) != 1 else b['units']['noun']} of {entry['dataset']}" + + (f" at {sets.version_label(b, entry['version'])}" if entry.get("version") else "")) + return 0 + + +def _named(entry: dict) -> str: + """A set as a line of output names it: its name, and its label when that is other words.""" + label = sets.label_of(entry) + return entry["name"] if label == entry["name"] else f"{entry['name']} ({label})" + + +def cmd_set_list(a): + got, bad = sets.entries(a.benchmark) + for problem in bad: + print("problem:", problem, file=sys.stderr) + rows = [_set_rows(e) for e in got] + if a.json: + print(json.dumps(rows, indent=2)) + return 0 + for r in rows: + print(f"{r['benchmark']:<16} {r['name']:<24} {r['units']:>6} units of {r['dataset']}" + + (f" at {r['version']}" if r["version"] else "") + + (f" {r['label']}" if r["label"] != r["name"] else "") + (f" {r['description']}" if r["description"] else "")) + return 0 + + +def cmd_set_show(a): + name, rev = sets.split_ref(a.ref) + entry = sets.load(a.benchmark, name) + got = sets.latest(entry, rev) + if a.json: + print(json.dumps({**{k: entry[k] for k in sets.HEADER if k in entry}, "label": sets.label_of(entry), + "date": got["date"], "note": got["note"], "hash": got["hash"], "units": got["units"]}, indent=2)) + return 0 + bench = _find_bench(a.benchmark) + print(f"{_named(entry)}: {len(got['units'])} units of {entry['benchmark']} {entry['dataset']}" + + (f", made at {sets.version_label(bench, entry['version'])}" if entry.get("version") else "")) + if entry.get("description"): + print(f" {entry['description']}") + print(f" id {entry['id']}") + print(f" {got['date']} {got['hash'][:12]}" + (f" {got['note']}" if got["note"] else "")) + print("units:") + for u in got["units"]: + print(f" {u}") + return 0 + + +def cmd_set_rename(a): + entry = sets.rename(a.benchmark, a.name, a.new) + print(f"renamed {a.name} to {_named(entry)} ({sets.path_of(entry['benchmark'], entry['name'])}): its id and its " + "tasks kept; jobs that ran it find it by its id") + return 0 + + +def cmd_set_delete(a): + path = sets._file_of(a.benchmark, a.name, None) + entry = sets.delete(a.benchmark, a.name) + if entry is None: + print(f"deleted {path}: an entry this version could not read") + return 0 + print(f"deleted {path}: {_named(entry)}, {len(sets.latest(entry)['units'])} units; jobs that ran it keep their record") + return 0 + + +def cmd_set_import(a): + entry, added = sets.import_path(a.path) + if added: + print(f"{_named(entry)} of {entry['benchmark']}: imported into {sets.path_of(entry['benchmark'], entry['name'])}") + else: + print(f"{_named(entry)} of {entry['benchmark']}: here already, with the same tasks") + return 0 + + +def cmd_set(a): + try: + return {"create": cmd_set_create, "list": cmd_set_list, "show": cmd_set_show, + "rename": cmd_set_rename, "delete": cmd_set_delete, "import": cmd_set_import}[a.set_cmd](a) + except (sets.Refused, unit_list.Refused) as e: + return _refused(e) + + +UNITS_EPILOG = """\ +examples: + nullius standard units humaneval --dataset humaneval + nullius standard units osworld1 --dataset test_nogdrive --search "tab" --category domain=chrome --category domain=vlc + nullius standard units longmemeval --dataset longmemeval_oracle --bench-option question_type=multi-session --json + +exit codes: + 0 listed, a match of no task included + 1 unexpected error (a traceback: report it) + 2 usage, or refused: an option or a category not known, a program the listing needs not on this machine, + a driver that could not list the dataset + 3 not found: no such benchmark or dataset + +A first listing fetches what it needs first (the upstream, the dataset, the driver's environment unless the +benchmark names a light listing command), said in one line on stderr; later listings read the cache. +""" + + +def cmd_units(a): + try: + b = _find_bench(a.benchmark) + if b is None: + raise unit_list.NotFound(f"no benchmark {a.benchmark!r}") + try: + given = options(a.bench_option, "--bench-option") + except SystemExit as e: + raise unit_list.Refused(str(e)) + chosen = unit_list.categories_of(a.category) + before = unit_list.state(b, a.dataset, given) + if before["state"] == "refused": + raise unit_list.Refused(before["reason"]) + if before["fetch"]: + print(f"first listing of {a.dataset}: fetching " + ", then ".join(f["text"] for f in before["fetch"]), + file=sys.stderr, flush=True) + found = unit_list.find(b, a.dataset, given, search=a.search or "", categories=chosen, size=None) + except unit_list.Refused as e: + return _refused(e) + if a.json: + print(json.dumps(found, indent=2, ensure_ascii=False)) + return 0 + words = b["units"] + print(f"{found['total']} of {found['of']} {words['nouns']} of {a.dataset}" + + ("" if found["described"] else " (its driver gives ids alone: a search reads the ids)")) + for field, values in found["categories"].items(): + print(f"{field}: " + ", ".join(f"{v['value']} {v['count']}" for v in values)) + for t in found["tasks"]: + print(f" {t['id']}" + (f" {t['title']}" if t["title"] else "")) + return 0 + + +RERUN_EPILOG = """examples: + nullius standard rerun jobs_standard/JOB --unit HumanEval/12 --reason "the provider failed" + nullius standard rerun jobs_standard/JOB --units again.txt --max-usd 2 + nullius standard rerun jobs_standard/JOB --unfinished --max-usd 5 + nullius standard rerun jobs_standard/JOB --next 20 + nullius standard rerun jobs_standard/JOB --set chrome-tabs + +exit codes: + 0 the tasks ran, or --unfinished or --set found none to run (a refusal on stderr otherwise) + 2 refused before anything moved, or a bad flag + 3 no such job directory""" + + +def cmd_rerun(a): + if not os.path.isdir(a.job): + print(f"no such directory: {a.job}", file=sys.stderr) + return 3 + try: + ids = list(a.unit or []) + (run.units_file(a.units)["units"] if a.units is not None else []) + with open(os.path.join(a.job, "config.json"), encoding="utf-8") as f: + std = json.load(f).get("standard") or {} + given = std.get("constraints") or {} + except run.Refused as e: + print("refused:", e, file=sys.stderr) + return 2 + except (OSError, ValueError, AttributeError): + std, given = {}, {} + if isinstance(given, dict) and given.get("cpu_set") is not None: + try: + limits.confine(given) # before any thread, as for its run + except OSError as e: + print(f"refused: constraints: cpu_set: {e.strerror or e}", file=sys.stderr) + return 2 + unreachable = None + if a.max_usd is not None: + try: + price_list.update() + except ValueError as e: + unreachable = str(e) + # started by Nullius (--from-run): the key it was handed, and on a host the licences its launcher handed it + bench = definitions.get("benchmark", str(std.get("benchmark_ref") or std.get("benchmark") or "")) if isinstance(std, dict) else None + held, spill = licences(bench, from_run=a.from_run) if bench else (None, None) + provider = str(std.get("provider") or "openai") if isinstance(std, dict) else "openai" + try: + part = None + if a.task_set is not None: + # a set of the job's benchmark: its tasks the job planned and has not run + name, rev = sets.split_ref(a.task_set) + entry = sets.load(str(std.get("benchmark") or "") if isinstance(std, dict) else "", name) + part = {"task_set": sets.record(entry, sets.latest(entry, rev)), "dataset": entry["dataset"]} + got = rerun.rerun(a.job, ids, reason=a.reason or "", concurrency=a.concurrency, retries=a.retries, + max_usd=a.max_usd, prices_unreachable=unreachable, licences=held, every_unfinished=a.unfinished, + count=a.next, task_set=part, **({"env": run_env(provider)} if a.from_run else {})) + except sets.NotFound as e: + print("refused:", e, file=sys.stderr) + return 3 + except (run.Refused, sets.Refused) as e: + print("refused:", e, file=sys.stderr) + return 2 + finally: + if spill: + shutil.rmtree(spill, ignore_errors=True) + print(got["job"]) + return 0 + + def cmd_fidelity(a): o = definitions.get("agent", a.other) if not o: @@ -843,7 +1173,14 @@ def main(argv=None): p.add_argument("--units", metavar="FILE", help="only the units this file lists, one id a line (# starts a comment): in the dataset's order, " "before --shard and --limit; the job's config records the file's name, sha256 and units") + p.add_argument("--set", dest="task_set", metavar="NAME", + help="only the units of this task set (nullius standard set): its dataset is the run's, the " + "options the run's own; the job's config records the set") p.add_argument("--limit", type=int) + p.add_argument("--start-with", metavar="N|FILE|set:NAME|ids:ID,ID...", + help="plan the whole (the dataset, or what --units, --set, --limit name) and begin with a part: " + "its first N units, the units a file lists, a task set's, or the units named after ids:, " + "separated by commas; the rest stay planned with no attempt, for rerun to run in the job later") p.add_argument("-j", "--concurrency", type=int, default=4) p.add_argument("--judge-model", help="a benchmark scored by a model: this judge instead of its official one") p.add_argument("--simulator-model", help="a benchmark whose user a model plays: this model instead of its official one") @@ -910,6 +1247,80 @@ def main(argv=None): g.add_argument("jobs", nargs="+", metavar="JOB_DIR") g.add_argument("-o", "--out", required=True, help="the merged job's directory (its name is the job's)") g.add_argument("--force", action="store_true", help="merge shards of different launches, versions, models or agents") + st = sub.add_parser("set", help="task sets: named lists of a benchmark's units, frozen once made", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + ss = st.add_subparsers(dest="set_cmd", required=True, metavar="COMMAND") + sc = ss.add_parser("create", help="a new task set, from a units file or from a job's trials", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sc.add_argument("benchmark", metavar="BENCH") + sc.add_argument("label", metavar="NAME", + help="any words; the name commands take is made from them (lower case, hyphens, -2 for a second one)") + sc.add_argument("--dataset", help="the dataset the set is cut from (from a job: the job's)") + source = sc.add_mutually_exclusive_group() + source.add_argument("--units", metavar="FILE", help="the units a file lists, one id a line (# starts a comment)") + source.add_argument("--from-job", metavar="JOB_DIR", help="the units a standard job ran (each trial's full unit id)") + sc.add_argument("--outcome", action="append", metavar="O,...", + help="with --from-job: the trials of these outcomes (the pages' names, or passed, failed, infra)") + sc.add_argument("--unit", action="append", metavar="ID", help="with --from-job: this unit too (repeatable)") + sc.add_argument("--search", metavar="TEXT", + help="the tasks whose id, title or text hold each word (nullius standard units): those matched today") + sc.add_argument("--category", action="append", metavar="FIELD=VALUE", + help="the tasks of this category's value (repeatable: values of one field widen, fields narrow)") + sc.add_argument("--description", default="") + sl = ss.add_parser("list", help="the task sets, of one benchmark or all", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sl.add_argument("benchmark", metavar="BENCH", nargs="?") + sl.add_argument("--json", action="store_true", help="one JSON array of rows") + sw = ss.add_parser("show", help="one task set: what it holds", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sw.add_argument("benchmark", metavar="BENCH") + sw.add_argument("ref", metavar="NAME", help="the set's name") + sw.add_argument("--json", action="store_true", help="the set as one JSON document") + sr = ss.add_parser("rename", help="another name for a task set: its id and tasks kept", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sr.add_argument("benchmark", metavar="BENCH") + sr.add_argument("name", metavar="NAME") + sr.add_argument("new", metavar="NEW", help="any words; the name commands take is made from them again") + sd = ss.add_parser("delete", help="remove a task set from this catalogue: jobs that ran it keep their record", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sd.add_argument("benchmark", metavar="BENCH") + sd.add_argument("name", metavar="NAME") + si = ss.add_parser("import", help="a task set from its file, or from a job that ran one, into this catalogue", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + si.add_argument("path", metavar="PATH", help="an entry's .json file, or a job's directory") + un = sub.add_parser("units", help="a dataset's tasks: their ids, titles and categories, searched and counted", + epilog=UNITS_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + un.add_argument("benchmark", metavar="BENCH") + un.add_argument("--dataset", required=True, help="the dataset whose tasks are listed") + un.add_argument("--bench-option", action="append", metavar="NAME=VALUE", + help="a benchmark option the driver lists under (repeatable); the others at their defaults") + un.add_argument("--search", metavar="TEXT", help="the tasks whose id, title or text hold each word, whatever the case") + un.add_argument("--category", action="append", metavar="FIELD=VALUE", + help="the tasks of this category's value (repeatable: values of one field widen, fields narrow)") + un.add_argument("--json", action="store_true", + help="one JSON document: total, of, described, tasks and each category's values with their counts") + rr = sub.add_parser("rerun", help="run chosen tasks of an ended job again in that job, each earlier try kept", + formatter_class=argparse.RawDescriptionHelpFormatter, epilog=RERUN_EPILOG) + rr.add_argument("job", metavar="JOB_DIR", help="a job of the standard that has ended") + named = rr.add_mutually_exclusive_group() + named.add_argument("--unit", action="append", metavar="ID", + help="a trial's name, or a unit's id for each of its attempts (repeatable): run again whatever its result") + named.add_argument("--units", metavar="FILE", help="the ids a file lists, one a line (# starts a comment)") + named.add_argument("--unfinished", action="store_true", + help="every planned trial with no result (never begun or killed), cut off by the run's spending cap, " + "or ended by a Stop; excludes scores and agent errors") + named.add_argument("--next", type=int, metavar="N", + help="the next N planned tasks with no result, in the plan's order, each with all its attempts") + named.add_argument("--set", dest="task_set", metavar="NAME", + help="the planned tasks with no result that this task set of the job's dataset names") + rr.add_argument("--reason", help="why, kept in the job's record of the re-run") + rr.add_argument("-j", "--concurrency", type=int, help="units at once (default: the job's)") + rr.add_argument("--retries", type=_retries, default=RETRIES, metavar="N", + help=f"run a failed try again, up to N times, as a run's --retries; 0 to {MAX_RETRIES}, default {RETRIES}") + rr.add_argument("--max-usd", type=float, metavar="USD", + help="the job's spending cap from now on, for this part and every later one: each part has what the parts before it left") + rr.add_argument("--from-run", action="store_true", + help="started by Nullius: the key is OPENAI_API_KEY (and OPENAI_BASE_URL), saved settings are not read") tr = sub.add_parser("traces", help="give past standard trials a trace, from the files they kept") tr.add_argument("root", metavar="DIR", help="a job, or a folder of jobs") tr.add_argument("--dry-run", action="store_true", help="say what it would write, and write nothing") @@ -917,16 +1328,17 @@ def main(argv=None): help="started by Nullius: the key is OPENAI_API_KEY (and OPENAI_BASE_URL), saved settings are not read") # Bootstrap decides whether settings may be read before these modules are # imported. Keep --from-run exact here too, so --from-r cannot bypass it. - for parser in (ap, *sub.choices.values()): + for parser in (ap, *sub.choices.values(), *ss.choices.values()): parser.allow_abbrev = False a = ap.parse_args(argv) - if a.cmd in ("run", "prove", "conform", "fidelity"): + if a.cmd in ("run", "prove", "conform", "fidelity", "rerun"): _exit_on_term() progress.ECHO = sys.stderr # each stage as a line (nullius/progress.py): stdout stays the job and its units if not getattr(a, "from_run", False): settings.load(ENV_FILE) return {"list": cmd_list, "check": cmd_check, "fit": cmd_fit, "pins": cmd_pins, "new": cmd_new, "conform": cmd_conform, "run": cmd_run, - "fidelity": cmd_fidelity, "prove": cmd_prove, "merge": cmd_merge, "traces": cmd_traces}[a.cmd](a) + "fidelity": cmd_fidelity, "prove": cmd_prove, "merge": cmd_merge, "rerun": cmd_rerun, "traces": cmd_traces, + "set": cmd_set, "units": cmd_units}[a.cmd](a) if __name__ == "__main__": diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 6803ee47..f1ae1aab 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1572,6 +1572,11 @@ def problems(d: dict, kind: str) -> List[str]: bad.append("driver.participant: true or false - whether setup is told the participant's kind") if "unit_end" in drv and not isinstance(drv["unit_end"], bool): bad.append("driver.unit_end: true or false - whether the driver is told each unit's end") + if "describe" in drv and not isinstance(drv["describe"], bool): + bad.append("driver.describe: true or false - whether the driver answers describe") + if "list_command" in drv: + # a listing's start: the standard library and the dataset's files, never the driver's install + bad += _command("driver.list_command", drv["list_command"], {"here"}) if "task_given" in drv and not isinstance(drv["task_given"], bool): bad.append("driver.task_given: true or false - whether the driver is told when the agent is given its task") bad += _mcp_servers(d.get("mcp_servers"), isinstance(drv, dict) and "install" in drv) @@ -1599,6 +1604,19 @@ def problems(d: dict, kind: str) -> List[str]: bad.append(f"{w}.sha256: the file's digest") if not isinstance(x.get("units"), int) or x["units"] < 1: bad.append(f"{w}.units: how many units it holds") + # a list cut from another of the benchmark's lists, which holds every unit it holds: the pages draw it as + # that dataset's own task set. One level: the list it names is cut from none + by_id = {x.get("id"): x for x in ds if isinstance(x, dict)} + for i, x in enumerate(ds): + if not isinstance(x, dict) or "subset_of" not in x: + continue + whole = by_id.get(x["subset_of"]) if isinstance(x["subset_of"], str) else None + if whole is None or whole is x: + bad.append(f"datasets[{i}].subset_of: the id of another of its datasets, the list this one is cut from") + elif "subset_of" in whole: + bad.append(f"datasets[{i}].subset_of: {x['subset_of']} is cut from another list; name one cut from none") + elif isinstance(x.get("units"), int) and isinstance(whole.get("units"), int) and x["units"] > whole["units"]: + bad.append(f"datasets[{i}].subset_of: it holds more units than {x['subset_of']}") u = d.get("units") or {} if not (isinstance(u.get("noun"), str) and isinstance(u.get("nouns"), str)): bad.append("units: {noun, nouns}") diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 27e76da6..321f6842 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -35,6 +35,7 @@ from __future__ import annotations import math +import os import re import shlex from typing import Callable, Dict, List, Optional @@ -46,7 +47,8 @@ from nullius.standard.contract import definitions, match, ports from nullius.standard.proofs import prove from nullius.standard.requirements import hostreq -from nullius.standard.runner import run +from nullius.standard.runner import run, sets +from nullius.standard.runner import units as listing from nullius.standard.runner.retries import MAX_RETRIES CHOOSE_PROVIDER = "Choose a provider: OpenRouter, OpenAI, Anthropic or a custom provider." @@ -148,6 +150,7 @@ def _bench_page(b: dict) -> dict: controls = [{**{k: c[k] for k in ("key", "label", "source", "from", "expect")}, "must": prove.must_score(c["expect"])} for c in (definitions.control(b, w) for w in definitions.CONTROLS) if c] versioned = definitions.version_of(b) is not None + task_sets = sets.rows(b["key"]) return {"key": b["key"], "label": b["label"], "summary": b["summary"], "family": b["family"], "kind": _capability_kind(b), "ref": definitions.ref_of(b) if "_version" in b else b["key"], "version": b["_version"] if versioned else "", @@ -193,10 +196,15 @@ def _bench_page(b: dict) -> dict: for n, r in hostreq.all_of(b).items()}, "datasets": [{"id": d["id"], "label": d.get("label") or d["id"], "summary": d.get("summary", ""), "units": d.get("units"), "environment": d.get("environment") or "", + # the list it is cut from, when the benchmark declares one: drawn as that dataset's own task set + "subset_of": d.get("subset_of") or "", "controls": [dict(c, **{k: status[d["id"]][c["key"]][k] for k in ("proven", "short", "failed")}) for c in controls], "proofs": {k: status[d["id"]][k]["proven"] for k in ("units", "leak")}, - "failed": {k: status[d["id"]][k]["failed"] for k in ("units", "leak") if status[d["id"]][k]["failed"]}} + "failed": {k: status[d["id"]][k]["failed"] for k in ("units", "leak") if status[d["id"]][k]["failed"]}, + # the user's task sets cut from it (standard/runner/sets.py), each with the version it was made at + "sets": [dict(s, version_label=sets.version_label(b, s["version"]) if s["version"] else "") + for s in task_sets if s["dataset"] == d["id"]]} for d in b["datasets"]]} @@ -455,6 +463,101 @@ def add(step, message, shown=False, field=None, unset=False): unknown = [x for x in wanted if x not in {y["id"] for y in b["datasets"]}] if not dss or unknown: add("dataset", f"Choose one or more of {b['label']}'s datasets" + (f" ({', '.join(unknown)} is not one)" if unknown else "") + ".") + # a chosen dataset's task set (``task_sets``: {dataset: NAME}), run in place of all its tasks; a recipe from + # before sets were frozen may name one NAME@N + set_of = {} # {dataset: {name, label, units, ids}} + asked = recipe.get("task_sets") or {} + if not isinstance(asked, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in asked.items()): + add("dataset", "Task sets are a dataset with a set's name each.") + asked = {} + for ds_id, ref in asked.items(): + if ds_id not in {x["id"] for x in dss}: + add("dataset", f"The task set {ref} is for {ds_id}, a dataset not chosen.") + continue + try: + set_name, rev = sets.split_ref(ref) + except sets.Refused as e: + add("dataset", f"Task set {ref}: {e}.") + continue + try: + if not os.path.isfile(sets.path_of(b["key"], set_name)): + add("dataset", f"{b['label']} has no task set {set_name}: choose another, or all of {ds_id}'s tasks.") + continue + entry = sets.load(b["key"], set_name) + except sets.Refused as e: + add("dataset", sets.plain(e, b["key"], set_name)) + continue + try: + got = sets.latest(entry, rev) + except sets.Refused as e: + add("dataset", f"Task set {ref}: {e}.") + continue + if entry["dataset"] != ds_id: + add("dataset", f"The task set {sets.label_of(entry)} is cut from the dataset {entry['dataset']}, not {ds_id}.") + continue + set_of[ds_id] = {"name": set_name, "label": sets.label_of(entry), "units": len(got["units"]), "ids": set(got["units"])} + # a chosen dataset's plan begun on a part (``start_with``: {dataset: [ID, ...], the tasks the page ticked, or + # from a recipe before it, N or set:NAME}): the rest run later + start_of = {} # {dataset: {"value": the --start-with word, "units": N, "label": what Review says}} + asked = recipe.get("start_with") or {} + if not isinstance(asked, dict) or not all(isinstance(k, str) and (isinstance(v, str) or isinstance(v, list) and all(isinstance(i, str) for i in v)) + for k, v in asked.items()): + add("dataset", "Start with is a dataset with its tasks each.") + asked = {} + for ds_id, given in asked.items(): + if ds_id not in {x["id"] for x in dss}: + add("dataset", f"Start with {'its tasks' if isinstance(given, list) else given} is for {ds_id}, a dataset not chosen.") + continue + if isinstance(given, list): + # the tasks ticked, given inline: ids:A,B,... (an id with a comma or a space cannot be) + ids = list(dict.fromkeys(given)) + if not ids: + add("dataset", "Start with: tick at least one task, or start with all of it.") + elif any(not i or "," in i or i != i.strip() for i in ids): + add("dataset", "Start with: an id holding a comma or a space cannot be ticked here; give the tasks in a file.") + elif ds_id in set_of and set(ids) - set_of[ds_id]["ids"]: + add("dataset", f"Start with: {len(set(ids) - set_of[ds_id]['ids'])} of the tasks ticked are not in the task set " + f"{set_of[ds_id]['label']}.") + else: + start_of[ds_id] = {"value": "ids:" + ",".join(ids), "units": len(ids), "label": "the tasks ticked"} + continue + if given.isdigit(): + if int(given) < 1: + add("dataset", "Start with a number of tasks of at least 1.") + continue + start_of[ds_id] = {"value": given, "units": int(given), "label": f"the first {int(given)}"} + continue + if not given.startswith("set:"): + add("dataset", "Start with all of the tasks, a number of them, or a task set.") + continue + try: + set_name, rev = sets.split_ref(given[4:]) + except sets.Refused as e: + add("dataset", f"Start with {given[4:]}: {e}.") + continue + try: + if not os.path.isfile(sets.path_of(b["key"], set_name)): + add("dataset", f"{b['label']} has no task set {set_name} to start with: choose another, or start with all.") + continue + entry = sets.load(b["key"], set_name) + except sets.Refused as e: + add("dataset", sets.plain(e, b["key"], set_name)) + continue + try: + got = sets.latest(entry, rev) + except sets.Refused as e: + add("dataset", f"Start with {given[4:]}: {e}.") + continue + if entry["dataset"] != ds_id: + add("dataset", f"Start with: the task set {sets.label_of(entry)} is cut from the dataset {entry['dataset']}, not {ds_id}.") + continue + outside = set(got["units"]) - set_of[ds_id]["ids"] if ds_id in set_of else set() + if outside: + add("dataset", f"Start with: the task set {sets.label_of(entry)} names {len(outside)} of {ds_id}'s tasks outside " + f"the task set {set_of[ds_id]['label']}.") + continue + start_of[ds_id] = {"value": f"set:{set_name}", "units": len(got["units"]), + "label": f"task set {sets.label_of(entry)}"} side = "agent" if b["family"] == "agent" else "capability" # A control the benchmark declares (nop, oracle) is a choice beside the agents or capabilities: it runs # nothing as you and calls no model - a judged benchmark's judge only - so it asks for neither. @@ -692,6 +795,20 @@ def add(step, message, shown=False, field=None, unset=False): alone = refs and {"original" if ref == "original" or (":" in ref and definitions.own_agent(base, ref)) else ref for ref in refs} == {"original"} units = (((b.get("setups") or {}).get("original") or {}).get("units") if alone else None) or b.get("units") or {} add("limits", f"Number of {units.get('nouns', 'units')}: a whole number of at least 1, or empty for all.", field="limit") + # the tasks ticked, against the plan a lower number or another option left: read from the listing the task + # picker made (its definition is ``base``, the label not yet the title), and only when it is in the cache, so + # compiling starts nothing; ids pasted where no listing is cached are checked by the run at its start + for ds_id, start in start_of.items(): + given = (recipe.get("start_with") or {}).get(ds_id) + if not isinstance(given, list) or listing.state(base, ds_id, chosen_opts)["state"] != "cached": + continue + plan = listing.find(base, ds_id, chosen_opts, size=None, within=set_of.get(ds_id, {}).get("ids"), + limit=limit if isinstance(limit, int) else None) + start["planned"] = plan["total"] + dropped = [i for i in given if i not in {t["id"] for t in plan["tasks"]}] + if dropped: + errors.append({"step": STEP["dataset"], "dataset": ds_id, "dropped": dropped, + "message": "Start with: tasks outside the current plan: " + ", ".join(dropped) + "."}) # empty: one at a time; on Boat, as many as the account runs at once (the run caps it to that, boat.slots) conc = _int(recipe.get("concurrency") or (MAX_CONCURRENT if backend == "boat" else 1), 1, MAX_CONCURRENT) if conc is None: @@ -699,6 +816,8 @@ def add(step, message, shown=False, field=None, unset=False): targets, why_not = where_of(recipe.get("where", "local")) if why_not: add("where", why_not) + elif start_of and len(targets) > 1: + add("where", "A run begun on a part of its plan runs on one machine: choose one, or start with all.") elif backend == "container" and "local" in targets and docker_unusable is not None: why = docker_unusable() if why: @@ -800,10 +919,23 @@ def pinned(p: dict) -> Dict[str, List[str]]: nouns = (b.get("units") or {}).get("nouns", "units") if picks and all(p.get("setup") for p in picks): # only setups: a unit is theirs (a conversation) nouns = picks[0]["o"]["units"]["nouns"] - each = [None if picks and all(p.get("setup") for p in picks) else x.get("units") for x in dss] # a setup's count is not the dataset's + each = [None if picks and all(p.get("setup") for p in picks) else (set_of[x["id"]]["units"] if x["id"] in set_of else x.get("units")) + for x in dss] # a setup's count is not the dataset's; a task set's is its own total = sum(each) if all(each) else None n = sum(min(limit, t) for t in each) if isinstance(limit, int) and total else (limit or total) of = len(targets) + # a plan begun on a part: what it plans and what it begins, by dataset + planned_of = {x["id"]: min(limit, e) if isinstance(limit, int) and e else (limit if isinstance(limit, int) else e) + for x, e in zip(dss, each)} + planned_of.update({ds_id: s["planned"] for ds_id, s in start_of.items() if "planned" in s}) + planned = sum(planned_of.values()) if all(planned_of.values()) else None + starts = [start_of.get(x["id"], {}).get("units", planned_of[x["id"]]) for x in dss] + begin = sum(starts) if all(starts) else None + for ds_id, s in start_of.items(): + if planned_of.get(ds_id) and s["units"] > planned_of[ds_id]: + add("dataset", f"Start with {s['units']} {nouns}: {ds_id} plans {planned_of[ds_id]}.") + if errors: + return out many = len(dss) > 1 pairs = [(x, p) for x in dss for p in picks] @@ -825,7 +957,9 @@ def command_for(d: dict, p: dict, index: int) -> str: o, control, given = p["o"], p["control"], p["given"] m = p["model"] if p.get("setup") else model words = ["nullius", "standard", "run", definitions.ref_of(b), o["_ref"], *(["--model", m] if m else []), "--provider", provider, - "--dataset", d["id"], *(["--limit", str(limit)] if isinstance(limit, int) else []), "-j", str(conc), + "--dataset", d["id"], *(["--set", set_of[d["id"]]["name"]] if d["id"] in set_of else []), + *(["--limit", str(limit)] if isinstance(limit, int) else []), + *(["--start-with", start_of[d["id"]]["value"]] if d["id"] in start_of else []), "-j", str(conc), *[w for k, v in options_for_pick(d, p).items() for w in ("--bench-option", f"{k}={v}")], *(["--attempts", str(repeat)] if repeat > 1 else []), *(["--retries", str(retries)] if retries else []), @@ -904,6 +1038,20 @@ def script_for(d: dict, p: dict, command: str, index: int) -> str: "providers": {s["name"]: s["provider"] for s in declared if s.get("provider")}} + noun_one = (b.get("units") or {}).get("noun", "unit") + if picks and all(p.get("setup") for p in picks): + noun_one = picks[0]["o"]["units"]["noun"] + + def first_words(ds_id: str) -> str: + """What a part's start runs first and what it leaves for later, in a sentence of Review.""" + m, whole = start_of[ds_id]["units"], planned_of.get(ds_id) + rest = (whole - m) if whole else None + ran = f"{m} {noun_one if m == 1 else nouns} {'runs' if m == 1 else 'run'} first ({start_of[ds_id]['label']})" + if rest == 0: + return ran + ", and nothing is left for later" + left = "the rest stay" if rest is None else f"the other {rest} {'stays' if rest == 1 else 'stay'}" + return f"{ran}; {left} planned, to run later from the job's page" + def row(p: dict) -> list: o = p["o"] if p["control"]: @@ -919,7 +1067,11 @@ def row(p: dict) -> list: out["review"] = [[STEP["benchmark"], "Benchmark", f"{b['label']} · needs {', '.join(b['needs'])}"], [STEP["runner"], "Runner", "Nullius"], [STEP["dataset"], "Datasets" if many else "Dataset", - ", ".join(f"{x.get('label') or x['id']}" + (f" · {x['units']} {nouns}" if x.get("units") else "") for x in dss)], + ", ".join(f"{x.get('label') or x['id']}" + (f" · task set {set_of[x['id']]['label']}" + + ("" if x["id"] in start_of else f" · {set_of[x['id']]['units']} {nouns}") + if x["id"] in set_of else f" · {x['units']} {nouns}" if x.get("units") and x["id"] not in start_of else "") + # begun on a part: what runs first, and what stays for later + + (f" · {first_words(x['id'])}" if x["id"] in start_of else "") for x in dss)], *[[STEP["limits" if (b.get("options") or {})[k].get("limit") else "dataset" if (b.get("options") or {})[k].get("step") else "agent"], (b.get("options") or {})[k].get("label") or k.replace("_", " ").capitalize(), _shown((b.get("options") or {})[k], v, per_ds[next(x["id"] for x in dss if per_ds[x["id"]].get(k) == v)]) + ("" if k in chosen_opts else " (its default)") + ("" if all(per_ds[x["id"]].get(k) == v for x in dss) else f" · {', '.join(x.get('label') or x['id'] for x in dss if per_ds[x['id']].get(k) == v)}")] @@ -937,10 +1089,12 @@ def row(p: dict) -> list: + (f" · user simulator {sim_model or (b.get('simulator') or {}).get('model')}" + (" (leaderboard)" if lb.get("simulator") else "" if sim_model else " (official)") if b.get("simulator") else "") + (f" · judge {judge_model or b['score']['judge']['model']}" + ("" if judge_model else " (official)") if (b.get("score") or {}).get("judge") else "") + "".join(f" · {SERVED_LABEL[r_]} served by {', '.join(s)}" for r_, s in served.items())], - [STEP["limits"], "Scope", f"{'first ' + str(n) if isinstance(limit, int) else 'all ' + str(total or '')} {nouns}" + [STEP["limits"], "Scope", (f"{begin} first, {planned - begin if planned else 'the rest'} later" if start_of and begin + else f"{planned or 'all'} planned, {begin or 'all'} to begin" if set_of or start_of + else f"{'first ' + str(n) if isinstance(limit, int) else 'all ' + str(total or '')} {nouns}") + (" of each shard" if of > 1 and isinstance(limit, int) else "") + (" · as many at a time as Boat allows" if backend == "boat" and not recipe.get("concurrency") else f" · {conc} at a time") - + (" of each dataset" if many and isinstance(limit, int) else "") + + (" of each dataset" if many and isinstance(limit, int) and not (set_of or start_of) else "") + (f" · {len(pairs)} jobs, one after the other" if len(pairs) > 1 else "") + (f" · {repeat} attempts each (pass^1 to pass^{repeat})" if repeat > 1 else "") + (f" · up to {retries} {'retry' if retries == 1 else 'retries'} an attempt" if retries else "") @@ -976,7 +1130,8 @@ def row(p: dict) -> list: if any(p["control"] for p in picks) and any(definitions.own_image(e) for e in (b.get("environments") or {}).values()): notes.append(f"Each {(b.get('units') or {}).get('noun', 'unit')} of {b['label']} is its own image: the control " "runs in it, so docker is needed where it runs, whatever the backend.") - if not isinstance(limit, int): + # Run asks first before every task of the datasets; a task set or a start on a part is a choice of tasks made already + if not isinstance(limit, int) and not set_of and not start_of: out["confirm"] = f"Run all {total or ''} {nouns} of {b['label']}{' (' + ', '.join(x.get('label') or x['id'] for x in dss) + ')' if many else ''} with {', '.join(p['o']['label'] for p in picks)}?".replace(" ", " ") return out @@ -1006,6 +1161,20 @@ def where_label(target: str) -> str: return "this machine" if target == "local" else hosts.parse(target).label +def again(job: str, trials: List[str], *, reason: str = "", max_usd: Optional[float] = None, n: int = 1) -> dict: + """The part that runs the trials ``trials`` of the ended job ``job`` again, in that job, where its run ran + (``execution.Execution.again``): ``cli rerun`` on the job's folder under ``$NULLIUS_JOBS``, from the same + tree a run's command is, with the key it is handed (``--from-run``). ``n``: its number among the run's re-runs.""" + words = [*(w for t in trials for w in ("--unit", t)), *(["--reason", reason] if reason else []), + *(["--max-usd", f"{max_usd:.6f}".rstrip("0").rstrip(".")] if max_usd else []), "--from-run"] + command = ('nullius standard rerun "${NULLIUS_JOBS:-jobs_standard}"/' + shlex.quote(job) + " " + + " ".join(shlex.quote(w) for w in words)) + k = len(trials) + return {"id": f"again-{n}", "label": f"{k} {'task' if k == 1 else 'tasks'} of {job} again", "again": job, + "trials": list(trials), "script": "#!/usr/bin/env bash\n# Chosen tasks of an ended job, run again in that job.\n" + + _script(command)} + + def conformance(kind: str, key: str, *, model: str, provider: str, unsandboxed: bool, stamp: str, backend: str = "local") -> dict: """The check an Agents or Capabilities page starts: every kit the agent or capability can take, as one command (``cli conform``), the jobs it will diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index 80a3860e..02c7c0b0 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -576,6 +576,7 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str options: Optional[dict] = None, launch: str = "", shard: Optional[dict] = None, repeat: int = 1, retries: int = 0, bench_options: Optional[dict] = None, simulator: str = "", prices: Optional[dict] = None, units_file: Optional[dict] = None, + task_set: Optional[dict] = None, start_with: Optional[dict] = None, constraints: Optional[dict] = None, timeouts: Optional[dict] = None, max_turns: Optional[int] = None, max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None, exchanges: str = "", exchanges_max_mb: Optional[int] = None): @@ -585,7 +586,12 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str say what differed. ``launch`` and ``shard``: a shard of a launch run over several machines (``shard``), which ``merge`` reads back. ``units_file``: the file a run's units were listed in (``run.units_file``), its name, its - sha256 and its units, said only for such a run. ``repeat``: how + sha256 and its units, said only for such a run. ``task_set``: the task + set a run's units came from (``sets.record``): its id, name, revision, + hash and units, and what ``set import`` rebuilds the entry from, said + only for such a run. ``start_with``: a run begun on a part of its plan + (``run.Run.part_record``): how the part was named and its units, said only + for such a run; ``units`` is then the whole plan's. ``repeat``: how many times each unit was run, each an attempt, said only when more than once; ``retries``: how many times an attempt could be tried again after a failure a further try might mend (``retries.retryable``), always said. @@ -613,6 +619,8 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str **({"simulator": simulator} if simulator else {}), **({"options": options} if options else {}), **({"benchmark_options": bench_options} if bench_options else {}), **_control(other), **_setup(other), **({"launch": launch} if launch else {}), **({"shard": shard} if shard else {}), **({"units_file": units_file} if units_file else {}), + **({"task_set": task_set} if task_set else {}), + **({"start_with": start_with} if start_with else {}), **({"repeat": repeat} if repeat > 1 else {}), "retries": retries, **({"prices": prices} if prices else {}), **({"constraints": constraints} if constraints else {}), **({"timeouts": timeouts} if timeouts else {}), **({"max_turns": max_turns} if max_turns else {}), diff --git a/app/nullius/standard/runner/merge.py b/app/nullius/standard/runner/merge.py index 1f4b49a9..1d1322f4 100644 --- a/app/nullius/standard/runner/merge.py +++ b/app/nullius/standard/runner/merge.py @@ -17,7 +17,10 @@ different units, or a shard of a list and one of none: the merged job records one list. The units are compared in any order; a list's name, comments, line endings and sha256 may differ from shard to shard, and the -merged job records the first shard's list. Units no shard ran +merged job records the first shard's list. Shards of different task sets +(``sets``), of different revisions of one, or of a set and none, are refused +as the other differences are, unless ``force``; the merged job keeps the +first shard's set. Units no shard ran are not a refusal - a shard may be missing, or stopped early - and are said: the shards absent, and the units a shard planned and has no trial for. A trial whose record names another job, benchmark, version, control or agent @@ -45,7 +48,8 @@ ("benchmark version", ("standard", "benchmark_version")), ("dataset", ("datasets", 0, "name")), ("agent or capability", ("standard", "plugged")), ("model", ("agents", 0, "model_name")), ("backend", ("standard", "backend")), ("serving providers", ("standard", "served_by")), - ("number of shards", ("standard", "shard", "of")), ("retries per attempt", ("standard", "retries"))) + ("number of shards", ("standard", "shard", "of")), ("retries per attempt", ("standard", "retries")), + ("task set", ("standard", "task_set"))) LISTED = 1000 @@ -78,11 +82,23 @@ def _at(d, path): def _same(cfg: dict, path) -> object: - """What a shard's config says at ``path`` (``SAME``); ``retries`` absent reads as none.""" + """What a shard's config says at ``path`` (``SAME``); ``retries`` absent reads as none. + A task set is its name, revision, id and hash: the record's other fields follow from them.""" got = _at(cfg, path) + if path == ("standard", "task_set"): + return (tuple(got.get(k) for k in ("name", "revision", "id", "hash")) + if isinstance(got, dict) else None) return got or 0 if path == ("standard", "retries") else got +def _shown(cfg: dict, path) -> object: + got = _same(cfg, path) + if path == ("standard", "task_set") and got is not None: + name, revision, identity, digest = got + return f"{name}@{revision} ({str(identity)[:8]}, {str(digest)[:12]})" + return got + + def _listed(cfg: dict) -> Optional[tuple]: """The units a shard's list holds (``standard.units_file``), sorted; None for a shard of no list.""" units = _at(cfg, ("standard", "units_file", "units")) @@ -172,7 +188,7 @@ def check(job_dirs: List[str], force: bool = False) -> dict: for label, path in SAME: seen = {json.dumps(_same(s["config"], path), sort_keys=True) for s in shards} # a mapping by its content if len(seen) > 1: - differ.append(f"{label}: " + ", ".join(f"{s['name']} {_same(s['config'], path)!r}" for s in shards)) + differ.append(f"{label}: " + ", ".join(f"{s['name']} {_shown(s['config'], path)!r}" for s in shards)) if differ and not force: raise Refused("the shards are not of one launch - " + "; ".join(differ) + " (--force merges them anyway)") # every trial by its unit: two of one unit are never merged, force or not @@ -238,7 +254,7 @@ def check(job_dirs: List[str], force: bool = False) -> dict: short = total - len(by_unit) if short > 0: # a shard of a list of units counts the listed ones as its whole (run.units_file) - listed = any(_at(s["config"], ("standard", "units_file")) for s in shards) + listed = any(_at(s["config"], ("standard", "units_file")) or _at(s["config"], ("standard", "task_set")) for s in shards) whole = f"{total} listed units" if listed else f"dataset's {total} units" notes.append(f"{short} of the {whole} are not in the merge") return {"shards": shards, "by_unit": by_unit, "notes": notes, "missing": missing, "units_total": total, "differ": differ} @@ -258,9 +274,13 @@ def _budget(budgets: list) -> Optional[dict]: if not whole and not number(each): return None spent = [x.get("spent_usd") for x in budgets] + totals = [x["spent_total_usd"] if number(x.get("spent_total_usd")) else + x["spent_usd"] + (x.get("unsettled_usd") or 0) if number(x.get("spent_usd")) else None for x in budgets] unsettled = round(sum(x.get("unsettled_usd") or 0 for x in budgets), 6) return {"max_usd": round(sum(x["max_usd"] for x in budgets), 6) if whole else None, "spent_usd": None if any(not isinstance(v, (int, float)) for v in spent) else round(sum(spent), 6), + **({"spent_total_usd": sum(totals)} if all(number(v) for v in totals) + and any(number(x.get("spent_total_usd")) for x in budgets) else {}), **({"unsettled_usd": unsettled} if unsettled else {}), "stopped": whole and any(x.get("stopped") for x in budgets), # how many shards there were and how many stopped: each at its own share, not the launch at the sum **({"shards": len(budgets), "shards_stopped": sum(1 for x in budgets if x.get("stopped"))} if whole else {}), diff --git a/app/nullius/standard/runner/payload.py b/app/nullius/standard/runner/payload.py index 1a86ad81..8f98c3ba 100644 --- a/app/nullius/standard/runner/payload.py +++ b/app/nullius/standard/runner/payload.py @@ -20,6 +20,7 @@ from nullius import paths from nullius.standard.contract import definitions +from nullius.standard.runner import sets as task_sets PACKAGE = Path(__file__).resolve().parents[2] FORMAT = 1 @@ -40,9 +41,9 @@ def _safe(relative: str) -> bool: and p.suffix.lower() not in {".pem", ".key", ".p12", ".pfx", ".pyc"}) -def _read(root: Path, relative: str) -> tuple[bytes, int]: +def _read(root: Path, relative: str, *, task_set: bool = False) -> tuple[bytes, int]: """Read a regular file below root, refusing symlinks at every segment.""" - if not _safe(relative): + if not (_safe(relative) or task_set and _safe(str(Path(relative).parent))): raise ValueError(f"not a runner resource: {relative}") p = root for segment in Path(relative).parts: @@ -191,7 +192,7 @@ def _cached(destination: Path, marker: str, files: dict) -> bool: valid = found == expected and manifest.read_text() == marker if valid: for name, value in files.items(): - if _read(destination / "app/nullius", name) != value: + if _read(destination / "app/nullius", name, task_set=name.startswith("catalogue/sets/")) != value: valid = False break if not valid: @@ -199,11 +200,27 @@ def _cached(destination: Path, marker: str, files: dict) -> bool: return True -def build(cache: str, *, package: Path | None = None, catalogue: str | None = None) -> tuple[str, str]: +def recipe_sets(recipe: dict) -> list[tuple[str, str]]: + """The task sets a standard recipe runs (``task_sets``) and those it begins with (``start_with``, set:NAME), + as (benchmark, name): what its snapshot carries.""" + asked = (recipe or {}).get("task_sets") + begun = (recipe or {}).get("start_with") + bench = str((recipe or {}).get("benchmark") or "").partition("@")[0] + if not bench: + return [] + refs = [ref for ref in (asked.values() if isinstance(asked, dict) else []) if isinstance(ref, str) and ref] + refs += [ref[4:] for ref in (begun.values() if isinstance(begun, dict) else []) if isinstance(ref, str) and ref.startswith("set:")] + return sorted({(bench, ref.partition("@")[0]) for ref in refs if ref}) + + +def build(cache: str, *, package: Path | None = None, catalogue: str | None = None, + sets: list[tuple[str, str]] | None = None) -> tuple[str, str]: """Return (content ID, snapshot root), with ``app/nullius`` below it. A user entry replaces the whole bundled entry. Nothing is created in either input tree. The staged tree is replaced atomically, and the address covers the exact bytes being sent. + ``sets``: the task sets of the user catalogue the run reads, each + (benchmark, name), carried at ``catalogue/sets//.json``. """ package = Path(package) if package is not None else PACKAGE if package.is_symlink(): @@ -240,6 +257,15 @@ def build(cache: str, *, package: Path | None = None, catalogue: str | None = No except json.JSONDecodeError: continue # Unfinished JSON drafts are not runnable catalogue entries. files.update({f"catalogue/{kind}/{name}/{r}": value for r, value in contents.items()}) + for bench, name in sets or (): + try: + task_sets.check_name(name) + except task_sets.Refused as e: + raise ValueError(str(e)) from None + relative = f"sets/{bench}/{name}.json" + if not _KEY.fullmatch(bench) or "/" in name or not (user / relative).is_file(): + raise ValueError(f"the task set {name} of {bench} is not in the catalogue") + files[f"catalogue/{relative}"] = _read(user, relative, task_set=True) kits = package / "standard" / "kits" if kits.is_dir(): if kits.is_symlink(): diff --git a/app/nullius/standard/runner/rerun.py b/app/nullius/standard/runner/rerun.py new file mode 100644 index 00000000..53ddf48c --- /dev/null +++ b/app/nullius/standard/runner/rerun.py @@ -0,0 +1,622 @@ +"""Chosen tasks of a finished job, run again in that job. + +The user names trials of a job that has ended - a trial by its name, or a +unit by its id for each of its attempts - and each runs again where it is, by +the path an automatic retry takes (``run.Run.try_again``): the trial's folder +moves into the job's ``retried/.try-N``, kept whole with its calls and +its cost, and the unit runs again under the trial's name, with its place in +the dataset and its attempt. A try that is stopped puts the one before it +back. Every task named runs again, whatever its result was; the new result +takes its place, and the tries before it stay readable beside it. + +A task the job planned and has no result for is taken the same way +(:func:`unfinished`). What a job planned is in its live feed +(``events.jsonl``): the run's ``job.start`` names its units, and a +``trial.queued`` line names each trial before any begins (:func:`planned`). +A trial never begun runs as its first try. A trial whose run was killed has +a folder and no ``result.json``: the folder is kept as the try it was, in +``retried/``, with ``no-result.json`` in it, and the trial runs again. A +trial the run's spending cap cut off, or a Stop ended, has a result that says +so: ``unfinished`` takes it too, since its run was interrupted, not judged. +A job whose feed does not say what it planned (a merged job keeps none) has +only its trials to run again. + +A job begun on a part of its plan (``run --start-with``) has the rest planned +with no attempt: :func:`more` takes a further part of them, a number of them +in the plan's order or those a task set of the job's dataset names, each with +all its attempts, and ``every_unfinished`` takes all of them. + +The settings are the job's own, read from its ``config.json`` and never +given again; the endpoint and the key come from the environment, as for a +run. The benchmark and the agent must resolve to the versions the job ran. +Refused before anything moves: no task named, an id the job does not hold, a +job still running (no ``result.json`` yet, or a re-run of it under way), a +merge of shards that differed (``merge --force``: a trial's settings may not +be the config's), and a benchmark or an agent that resolves to another +version now. A merged job is not refused for its hard links: a re-run renames +a trial's folder and writes the new try into a new one, and no linked file is +written. + +What is recorded: the try asked for gets ``standard.rerun`` (by hand, when, +the reason, the result it replaced, or ``begun`` for a task's first try) and +``standard.retries``, the tries before it, as an automatic retry's does. The +job's ``result.json`` is recomputed from its trials as a merged job's is +(``merge.result_of``); its start and its end stay the first run's, and +``reruns`` lists each re-run: when, the reason, the trials, the results +replaced, the tasks begun (``begun``), those that had no result +(``no_result``), the cap, what it had left of it and its spend. + +A job has one spending cap (:func:`budget`): the first run's, or the one a +later part is given (``max_usd``), which holds from then on. A later part's +ledger opens with the cap less what the job has spent; a part is refused +when nothing is left, or when the part before stopped at the cap and it has +not changed since. The job's ``budget`` keeps the cap, ``spent_total_usd`` +(every part) and ``changes``, each change of the cap. A job with no cap has +none until one is given. The live feed gets the re-run's +``job.start``, its trials' events and its ``job.end``, numbered on from the +file's last line. +""" +from __future__ import annotations + +import fcntl +import json +import os +import re +import shutil +import tempfile +import time +from typing import Callable, Dict, List, Optional + +from nullius.harbor import feed as live_feed +from nullius.standard.backends import boat +from nullius.standard.calls import ledger as ledgers +from nullius.standard.contract import definitions +from nullius.standard.runner import job, merge, run + +LOCK = "rerun.lock" # in the job's .work: held while a re-run of it runs +NO_RESULT = "no-result.json" # in a kept try that ended with no result: when it was found so +# what is left of a cap at or under which nothing is: unrounded sums of calls leave float noise, eight calls of +# 0.1 under a cap of 0.8 leaving 1.1e-16 +NOTHING_LEFT_USD = 1e-9 +_TAG = re.compile(r"__u(\d{4,})(?:r(\d+))?$") + + +def _number(v) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) + + +def said(res: dict) -> dict: + """What a try ended with, as a re-run's record keeps it: its error's kind, or its reward or score.""" + exc = res.get("exception_info") or {} + if exc.get("exception_type"): + return {"error": exc["exception_type"]} + return dict((res.get("verifier_result") or {}).get("rewards") or {}) + + +def _cost(res: dict) -> Optional[float]: + c = (res.get("agent_result") or {}).get("cost_usd") + return c if _number(c) else None + + +def _ledger_spent(path: str, fallback: float) -> float: + """The unrounded cost and bookings of a part, or its recorded total when its ledger is unavailable.""" + try: + state = ledgers.Ledger(path).state() + except ledgers.Unavailable: + return fallback + return state["spent_usd"] + state["unsettled_usd"] + state["held_usd"] + + +def _spent(job_dir: str, res: dict) -> float: + """What the job has spent, every part counted, with what stayed booked for calls whose cost was never known: the + total its budget keeps; for a job recorded before it kept one, its first run's and each later part's added; for + a job no cap counted, the cost its trials recorded, every try.""" + b = res.get("budget") if isinstance(res.get("budget"), dict) else {} + if _number(b.get("spent_total_usd")): + return float(b["spent_total_usd"]) + if _number(b.get("spent_usd")): + first = b["spent_usd"] + (b.get("unsettled_usd") if _number(b.get("unsettled_usd")) else 0) + later = [_ledger_spent(os.path.join(job_dir, ".work", f"rerun-{k}", "ledger", "ledger.json"), + r["spent_usd"] if _number(r.get("spent_usd")) else 0) + for k, r in enumerate(res.get("reruns") or [], 1) if isinstance(r, dict)] + return _ledger_spent(os.path.join(job_dir, ".work", "ledger", "ledger.json"), first) + sum(later) + tries = [os.path.join(job_dir, n) for n in merge._trials(job_dir)] + tries += [os.path.join(job_dir, "retried", k) for n in merge._trials(job_dir) for k in merge._tries(job_dir, n)] + return sum(c for c in (_cost(merge._read(os.path.join(t, "result.json"))) for t in tries) if c is not None) + + +def budget(job_dir: str, res: Optional[dict] = None, cap: Optional[float] = None) -> Optional[dict]: + """The job's one spending cap as its next part has it: {"max_usd", "spent_usd" (every part), "left_usd", + "closed" (nothing left, or the last part stopped at the cap and it has not changed since), "changed", "was"}. + ``cap``: the job's cap from now on, in place of its own. None for a job with no cap and none given.""" + res = merge._read(os.path.join(job_dir, "result.json")) if res is None else res + b = res.get("budget") if isinstance(res.get("budget"), dict) else {} + was = float(b["max_usd"]) if _number(b.get("max_usd")) else None + if cap is None and was is None: + return None + use = float(cap) if cap is not None else was + spent = _spent(job_dir, res) + changed = use != was + # a merged job's "stopped" says that some shard stopped at its share, not that the job's cap is spent + stopped = b.get("closed") is True if "closed" in b else (b.get("stopped") is True and not res.get("reruns") and not b.get("shards")) + left = use - spent + left = left if left > NOTHING_LEFT_USD else 0.0 + return {"max_usd": use, "spent_usd": spent, "left_usd": left, "closed": left <= 0 or (stopped and not changed), + "changed": changed, "was": was} + + +def spent_out(b: dict, fix: str = "raise it with --max-usd USD") -> str: + """Why a later part is refused when the job's cap has nothing left (:func:`budget`), and what to do.""" + return (f"the job's spending cap of {ledgers.usd(b['max_usd'])} USD is spent ({ledgers.usd(b['spent_usd'])} spent" + + ("" if b["left_usd"] <= 0 else ", and a call did not fit what was left") + f"): {fix}") + + +def running(job_dir: str) -> bool: + """Whether a re-run of the job is under way: another process holds its lock.""" + path = os.path.join(job_dir, ".work", LOCK) + if not os.path.isfile(path): + return False + with open(path, "a") as f: + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return True + fcntl.flock(f, fcntl.LOCK_UN) + return False + + +def _hold(job_dir: str): + """The job's lock, held until the file is closed; refused when another re-run holds it.""" + os.makedirs(os.path.join(job_dir, ".work"), exist_ok=True) + f = open(os.path.join(job_dir, ".work", LOCK), "a") + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + f.close() + raise run.Refused(f"{os.path.basename(job_dir)} is being run again already: wait for that re-run to end") + return f + + +def _last_seq(path: str) -> int: + """The last ``seq`` of a feed, which the re-run's lines go on from: its board folds them in that order.""" + n = 0 + try: + with open(path, encoding="utf-8") as f: + for line in f: + try: + seq = json.loads(line).get("seq") + except (ValueError, AttributeError): + continue + if isinstance(seq, int) and not isinstance(seq, bool): + n = max(n, seq) + except OSError: + pass + return n + + +def earlier_version(d: dict) -> Optional[str]: + """Of a benchmark's definition with versions (as its file has it), the one a job that records none ran: such a + job is older than the versions, and ran the pin the definition held then. That pin stays as the one version + whose own ``upstream`` names a branch and no tag, repository or commit of its own: it runs the shared commit. + None when no version, or more than one, is such.""" + vs = d.get("versions") if isinstance(d.get("versions"), dict) else {} + pinned = [v for v, blk in vs.items() if isinstance(blk, dict) and isinstance(blk.get("upstream"), dict) + and blk["upstream"].get("branch") and not any(k in blk["upstream"] for k in ("tag", "repository", "tested"))] + return pinned[0] if len(pinned) == 1 and (d.get("upstream") or {}).get("tested") else None + + +def _ran_before_versions(bench: dict, root: Optional[str]) -> Optional[dict]: + """The version of ``bench`` a job that records none ran (:func:`earlier_version`), resolved; None if it cannot be told.""" + folder = definitions.entry_dir("benchmark", bench.get("key") or "", root) + path = definitions.definition_path(folder, "benchmark") if folder else "" + d = definitions._read(path, "benchmark", bench["key"])[0] if path and os.path.isfile(path) else None + v = earlier_version(d or {}) + return definitions.get("benchmark", f"{bench['key']}@{v}", root) if v else None + + +def resolve(cfg: dict, results: List[dict], root: Optional[str] = None, say: Optional[Callable[[str], None]] = None) -> tuple: + """(benchmark, agent or other) a job ran, from today's catalogue; refused, naming the difference, when either + is gone or resolves to another version than the job recorded (its config, its trials' ``agent_info``). A job + that records no version of a benchmark that has versions now ran the one it had before + (:func:`earlier_version`): taken as that one, and ``say`` told.""" + std = cfg["standard"] + ref = std.get("benchmark_ref") or std.get("benchmark") or "" + bench = definitions.get("benchmark", ref, root) or next((k for k in definitions.kits() if k["key"] == ref), None) + if bench is None: + raise run.Refused(f"the job ran the benchmark {ref}, which the catalogue no longer holds") + ran = {k: std[k] for k in ("benchmark_version", "benchmark_ref") if std.get(k)} + earlier = _ran_before_versions(bench, root) if not ran and job._version(bench) else None + if earlier is not None: + (say or (lambda s: None))(f"{os.path.basename(str(std.get('job') or cfg.get('job_name') or 'the job'))} records no " + f"version of {ref}: taken as {earlier['_ref']}, {definitions.version_label(earlier)}, " + f"the one {ref} had before it had versions") + bench = earlier + elif job._version(bench) != ran: + now = job._version(bench).get("benchmark_version") or "no version" + if not ran: + raise run.Refused(f"the job records no version of {ref}, and its definition does not say which of its versions " + f"({', '.join(bench.get('_versions') or [])}) the job ran: start a new run to compare") + raise run.Refused(f"the job ran {ref} {ran.get('benchmark_version') or 'with no version'}, and it resolves to " + f"{now} now: start a new run to compare") + kind, plugged = std.get("kind") or "agent", str(std.get("plugged") or "") + if kind == "control": + other = definitions.control(bench, plugged) + elif kind == "upstream": + # a benchmark with agents of its own: the one the job ran, by the upstream's name its run was given + given = std.get("benchmark_options") if isinstance(std.get("benchmark_options"), dict) else {} + other, _ = definitions.setup(bench, plugged, str((std.get("setup") or {}).get("asked") or ""), std.get("provider") or "", + str(given.get("agent") or "")) + else: + other = definitions.get(kind, plugged, root) + if other is None: + raise run.Refused(f"the job ran {plugged}, which the catalogue no longer holds") + recorded = sorted({str((r.get("agent_info") or {}).get("version") or "") for r in results}) + now = str((other.get("upstream") or {}).get("version") or "") + if recorded and recorded != [now]: + raise run.Refused(f"the job ran {plugged} {', '.join(v or 'with no version' for v in recorded)}, and {plugged} " + f"resolves to {now or 'no version'} now: start a new run to compare") + return bench, other + + +def planned(job_dir: str) -> Optional[List[tuple]]: + """Each trial the job's run set out to run, (its name, its unit) in the run's order, as its live feed says + before the first unit begins: the run's ``job.start`` names its units, then a ``trial.queued`` line names + each trial at its place (``run.Run.start``). None when the feed says none: no feed (a merged job keeps + none), or one that names no trial.""" + out, units = [], None + try: + with open(os.path.join(job_dir, live_feed.FEED), encoding="utf-8") as f: + for line in f: + try: + e = json.loads(line) + except ValueError: + continue + if not isinstance(e, dict): + continue + if units is None: + if e.get("event") == "job.start": + units = [str(u) for u in e.get("tasks") or []] if isinstance(e.get("tasks"), list) else [] + continue + if e.get("event") != "trial.queued": + break # the plan ends where the first unit begins + pos, name = e.get("position"), e.get("trial") + if not units or not isinstance(name, str) or not isinstance(pos, int) or isinstance(pos, bool) or pos < 0: + return None + out.append((name, units[pos % len(units)])) + except OSError: + return None + return out or None + + +def unfinished(job_dir: str, plan: Optional[List[tuple]] = None) -> Dict[str, dict]: + """The trials the job planned (:func:`planned`) that have no result, by name: {"unit", "folder"}, ``folder`` + true when its run began and was killed before it wrote one. {} for a job that does not say what it planned.""" + out = {} + for name, unit in (planned(job_dir) if plan is None else plan) or []: + here = os.path.join(job_dir, name) + if not os.path.isfile(os.path.join(here, "result.json")): + out[name] = {"unit": unit, "folder": os.path.isdir(here) and not os.path.islink(here)} + return out + + +def interrupted(res: Optional[dict]) -> bool: + """Whether a trial's result is its run's interruption, not a judgement: the run's spending cap cut it off, + or a Stop ended it.""" + return ((res or {}).get("exception_info") or {}).get("exception_type") in (ledgers.ERROR, run.CANCELLED) + + +def _kept(job_dir: str, name: str) -> int: + """The last try of ``name`` kept in the job's ``retried/``; 0 when none is.""" + kept = os.path.join(job_dir, "retried") + tries = [int(k[len(name) + 5:]) for k in (os.listdir(kept) if os.path.isdir(kept) else ()) + if k.startswith(name + ".try-") and k[len(name) + 5:].isdigit()] + return max(tries, default=0) + + +def more(job_dir: str, plan: List[tuple], empty: Dict[str, dict], *, count: Optional[int] = None, + task_set: Optional[dict] = None, dataset: str = "", noun: tuple = ("task", "tasks")) -> List[str]: + """A further part of the planned tasks not yet run (``empty``, :func:`unfinished`): the first ``count`` of them + in the plan's order, or those the set ``task_set`` names ({"task_set": its record, "dataset": its dataset}); + each task with every attempt of it that has no result. Refused for a set of another dataset than the job's + (``dataset``), a set naming a task the job did not plan, and a count above the tasks left.""" + many = lambda n: noun[0] if n == 1 else noun[1] + left = list(dict.fromkeys(u for n, u in plan if n in empty)) + if task_set is not None: + rec = task_set["task_set"] + if task_set.get("dataset") != dataset: + raise run.Refused(f"the task set {rec['name']} is cut from the dataset {task_set.get('dataset')}, and " + f"{os.path.basename(job_dir)} planned {dataset}") + planned_units = {u for _, u in plan} + outside = [u for u in rec["units"] if u not in planned_units] + if outside: + raise run.Refused(f"the task set {rec.get('label') or rec['name']} names {len(outside)} {many(len(outside))} " + f"{os.path.basename(job_dir)} did not plan: " + ", ".join(outside[:5]) + + (", ..." if len(outside) > 5 else "")) + wanted = set(rec["units"]) + take = {u for u in left if u in wanted} + else: + if isinstance(count, bool) or not isinstance(count, int) or count < 1: + raise run.Refused(f"--next {count!r}: a whole number of {noun[1]}, at least 1") + if count > len(left): + raise run.Refused(f"--next {count}: {len(left)} {many(len(left))} of the plan {'is' if len(left) == 1 else 'are'} " + "left to run") + take = set(left[:count]) + return [n for n, u in plan if n in empty and u in take] + + +def chosen(job_dir: str, ids: List[str], trials: Dict[str, dict], empty: Optional[Dict[str, dict]] = None) -> List[str]: + """The trials ``ids`` name, in the order named, each once: an id is a trial's name, or a unit's id for each + of its attempts; a trial planned with no result (``empty``, :func:`unfinished`) too. Refused for no id, or + for ids the job does not hold.""" + empty = empty or {} + if not ids: + raise run.Refused("no task named: --unit ID (repeatable), --units FILE or --unfinished") + by_unit: Dict[str, List[str]] = {} + for name, res in trials.items(): + by_unit.setdefault(str((res.get("standard") or {}).get("unit") or name), []).append(name) + for name, x in empty.items(): + by_unit.setdefault(x["unit"], []).append(name) + unknown = [i for i in ids if i not in trials and i not in empty and i not in by_unit] + if unknown: + raise run.Refused(f"{os.path.basename(job_dir)} holds no trial or unit {', '.join(unknown)}") + return list(dict.fromkeys(n for i in ids for n in ([i] if i in trials or i in empty else sorted(by_unit[i])))) + + +def rerun(job_dir: str, ids: List[str], *, reason: str = "", concurrency: Optional[int] = None, retries: int = 0, + max_usd: Optional[float] = None, env=os.environ, say: Callable[[str], None] = print, licences=None, + prices_unreachable: Optional[str] = None, root: Optional[str] = None, every_unfinished: bool = False, + count: Optional[int] = None, task_set: Optional[dict] = None) -> dict: + """Run the trials ``ids`` name (:func:`chosen`) of the ended job ``job_dir`` again, in that job. ``retries``: + automatic retries of each re-run try, as a run's; ``max_usd``: the job's spending cap from now on; ``concurrency``: + the job's unless given. ``root``: a catalogue folder to resolve the definitions in (the user's and the + bundled ones by default). ``every_unfinished``: in place of ``ids``, each trial the job planned that has no + result, or whose run its cap or a Stop interrupted (:func:`interrupted`). ``count`` or ``task_set``: in + place of ``ids``, a further part of the planned tasks not yet run (:func:`more`). Returns the record added to the + job's ``reruns``, or {"job", "trials": []} with nothing written when there is no such trial; ``run.Refused`` + before anything moves.""" + job_dir = os.path.abspath(job_dir.rstrip("/")) + cfg, old = merge._read(os.path.join(job_dir, "config.json")), merge._read(os.path.join(job_dir, "result.json")) + if cfg.get("runner") != "standard" or not isinstance(cfg.get("standard"), dict): + raise run.Refused(f"{job_dir}: not a job of the Nullius standard (no config.json naming it)") + if not old or running(job_dir): + raise run.Refused(f"{os.path.basename(job_dir)} is still running: a job is run again once it has ended") + if os.path.islink(os.path.join(job_dir, "retried")): + raise run.Refused("retried is a symbolic link: use a directory inside the job") + std = cfg["standard"] + if std.get("merged_despite"): + raise run.Refused(f"{os.path.basename(job_dir)} merges shards that differed ({'; '.join(std['merged_despite'])}): " + "a trial's settings may not be its config's. Run it again in its shard's job") + names = merge._trials(job_dir) + trials = {n: merge._read(os.path.join(job_dir, n, "result.json")) for n in names} + plan = planned(job_dir) + empty = unfinished(job_dir, plan or []) + if (every_unfinished or count is not None or task_set is not None) and plan is None: + raise run.Refused(f"{os.path.basename(job_dir)} does not record the tasks it planned (its live feed names " + "none): name its trials with --unit") + if every_unfinished: + ids = [n for n, _ in plan if n in empty or interrupted(trials.get(n))] + if not ids: + say(f"nothing to run: every task {os.path.basename(job_dir)} planned has a result") + return {"job": job_dir, "trials": []} + elif count is not None or task_set is not None: + ids = more(job_dir, plan, empty, count=count, task_set=task_set, + dataset=str(((cfg.get("datasets") or [{}])[0] or {}).get("name") or "").partition("/")[2], + noun=tuple(cfg.get("runner_items") or ("task", "tasks"))[:2]) + if not ids: + say(f"nothing to run: every task of the set {task_set['task_set']['name']} {os.path.basename(job_dir)} " + "planned has a result") + return {"job": job_dir, "trials": []} + picked = chosen(job_dir, ids, trials, empty) + if max_usd is not None and not (isinstance(max_usd, (int, float)) and 0 < max_usd < float("inf")): + raise run.Refused(f"--max-usd {max_usd!r}: the job's spending cap in USD, above zero") + capped = budget(job_dir, old, max_usd) # one cap for the job: this part has what its earlier parts left + if capped is not None and capped["closed"]: + raise run.Refused(spent_out(capped)) + bench, other = resolve(cfg, list(trials.values()), root, say=say) + model = str(((cfg.get("agents") or [{}])[0] or {}).get("model_name") or "") + dataset = str(((cfg.get("datasets") or [{}])[0] or {}).get("name") or "").partition("/")[2] + prices = ((std.get("prices") or {}).get("models") or {}) + r = run.Run(bench, other, model=str((std.get("setup") or {}).get("asked") or model), provider=std.get("provider") or "openai", + dataset=dataset or None, concurrency=concurrency or cfg.get("n_concurrent_trials") or 4, + jobs_root=os.path.dirname(job_dir), name=os.path.basename(job_dir), say=say, env=env, + unsandboxed=bool(std.get("unsandboxed")), judge_model=std.get("judge") or None, + backend=std.get("backend") or "local", boat_size=std.get("boat_size") or boat.SIZE, + options=std.get("options") or None, bench_options=std.get("benchmark_options") or None, + repeat=int(std.get("repeat") or 1), retries=retries, simulator_model=std.get("simulator") or None, + licences=licences, prices={m: {k: v for k, v in row.items() if k != "source"} for m, row in prices.items()}, + max_usd=capped["left_usd"] if capped else None, max_usd_per_unit=(old.get("budget") or {}).get("unit_max_usd"), + prices_unreachable=prices_unreachable, constraints=std.get("constraints") or None, + timeouts=std.get("timeouts") or None, max_turns=std.get("max_turns"), max_calls=std.get("max_calls"), + served_by=std.get("served_by") or None) + # each trial's unit, its place and its attempt, as the runner named it; the try it is run again as. + # ``fresh``: a trial with no folder, begun now as the try after those kept (none, for a task never begun) + work, first_try, fresh = [], {}, {} + for name in picked: + unit = str((trials[name].get("standard") or {}).get("unit") or "") if name in trials else empty[name]["unit"] + tag = _TAG.search(name) + i, a = (int(tag.group(1)), int(tag.group(2) or 1)) if tag else (-1, 1) + if not tag or r.trial_name(i, unit, a) != name: + raise run.Refused(f"{name} is not a trial this runner named: it cannot be run again in place") + if name not in trials and os.path.islink(os.path.join(job_dir, name)): + raise run.Refused(f"{name} is a symbolic link: use a directory inside the job") + if name not in trials and not empty[name]["folder"]: + fresh[name] = _kept(job_dir, name) + else: + # a trial's folder with no result was the try after those kept + first_try[name] = (int((trials[name].get("standard") or {}).get("retries") or 0) if name in trials + else _kept(job_dir, name)) + 1 + if os.path.lexists(os.path.join(job_dir, "retried", f"{name}.try-{first_try[name]}")): + raise run.Refused(f"retried/{name}.try-{first_try[name]} is there already, and {name} does not count it: " + "the job's tries do not add up") + work.append((i, unit, a)) + held = _hold(job_dir) + try: + if every_unfinished: + counts = [sum(name in empty for name in picked)] + counts += [sum(said(trials.get(name) or {}).get("error") == error for name in picked) + for error in (ledgers.ERROR, run.CANCELLED)] + say(f"unfinished: {counts[0]} no result, {counts[1]} spending cap, {counts[2]} stopped") + return _again(r, job_dir, old, cfg, trials, picked, work, first_try, reason, t0=time.time(), fresh=fresh, + empty=empty, capped=capped) + finally: + held.close() + + +def _begin(r: "run.Run", name: str, iur: tuple, retry: int, work_unit) -> Optional[dict]: + """A trial with no folder, begun: its unit's own run, as the run's first pass does, at try ``retry`` + 1. A + try that does not end - not begun, or stopped under it - leaves no folder: the task stands as it was.""" + here = os.path.join(r.job_dir, name) + r.feed.emit("trial.queued", name, agent=job.agent_name(r.other), position=0) + res = None + try: + res = work_unit((*iur, retry)) + if res is not None and r._stopped.is_set() and (res.get("exception_info") or {}).get("exception_type") == run.CANCELLED: + res = None + finally: + if res is None and os.path.lexists(here): + gone = here + ".stopped" + os.replace(here, gone) + shutil.rmtree(gone, ignore_errors=True) + return res + + +def _again(r: "run.Run", job_dir: str, old: dict, cfg: dict, trials: Dict[str, dict], picked: List[str], work: list, + first_try: Dict[str, int], reason: str, t0: float, fresh: Optional[Dict[str, int]] = None, + empty: Optional[Dict[str, dict]] = None, capped: Optional[dict] = None) -> dict: + """The re-run itself, the job held (:func:`rerun`). ``capped``: the job's cap as this part has it (:func:`budget`).""" + fresh, empty = fresh or {}, empty or {} + killed = [name for name in picked if name in empty and name not in fresh] + r._tries = dict(first_try, **fresh) + n = len(old.get("reruns") or []) + 1 + if (r.max_usd is not None or r.unit_max_usd is not None) and r.base: + # a ledger of its own, opened with what the job's cap has left and the replies its earlier parts had: theirs stay + seen: Dict[str, list] = {} + for k, path in enumerate([os.path.join(job_dir, ".work", "ledger", "ledger.json")] + [ + os.path.join(job_dir, ".work", f"rerun-{k}", "ledger", "ledger.json") for k in range(1, n)]): + replies = ledgers.Ledger(path).replies() if os.path.isfile(path) else {} + part = old["reruns"][k - 1] if k else {} + # Earlier shared-cap records already inherited replies and identified the part by its remaining budget. + if replies and (part.get("cumulative_replies") or "left_usd" in part): + seen = {} + for model, (count, tokens) in replies.items(): + seen[model] = [seen.get(model, [0, 0])[0] + count, seen.get(model, [0, 0])[1] + tokens] + r.ledger = ledgers.Ledger.create(os.path.join(job_dir, ".work", f"rerun-{n}", "ledger", "ledger.json"), r.max_usd, + r.unit_max_usd, seen=seen) + p = r.progress + if r.cap_dropped: + r.say(f"warning: {r.cap_dropped} ({r.cap_why})") + elif capped: + r.say(f"the job's spending cap: {ledgers.usd(capped['max_usd'])} USD" + + (f" from now on (was {ledgers.usd(capped['was'])})" if capped["changed"] and capped["was"] is not None else + " from now on" if capped["changed"] else "") + + f", {ledgers.usd(capped['spent_usd'])} spent, {ledgers.usd(capped['left_usd'])} left for this part") + r.known_models() + r.ready() # refused here, the job reads as it did: nothing has moved + p.emit("plan", stages="units") # a further part of the job: its units said after the first's + r.n_units = len(work) + p.emit("units", "start", n=len(work), of=len(trials) + len(empty), noun=r.bench["units"]["nouns"]) + path = os.path.join(job_dir, live_feed.FEED) + r.feed = live_feed.Writer(path, r.name) + r.feed.seq = _last_seq(path) + r.feed.emit("job.start", n_total=int(old.get("n_total_trials") or len(trials)), n_concurrent=r.concurrency, + agents=[job.agent_name(r.other)], tasks=[u for _, u, _ in work], + **({"budget": {k: v for k, v in (("max_usd", capped["max_usd"] if capped and r.max_usd is not None else None), + ("unit_max_usd", r.unit_max_usd)) if v is not None}} + if r.ledger is not None else {})) + mark = {"by": "hand", "at": job.iso(t0), **({"reason": reason} if reason else {})} + + def first(iur, work_unit): + name = r.trial_name(*iur) + if name in fresh: + res = _begin(r, name, iur, fresh[name], work_unit) + else: + if name in killed: # kept as the try it was, marked: it holds no result + fd, marker = tempfile.mkstemp(dir=os.path.join(job_dir, name)) + os.fchmod(fd, 0o644) # readable as the trial's other files are + try: + with os.fdopen(fd, "w") as f: + json.dump({"found_at": mark["at"], "result": None}, f) + os.replace(marker, os.path.join(job_dir, name, NO_RESULT)) + finally: + if os.path.exists(marker): + os.unlink(marker) + res = r.try_again(name, iur, first_try[name], work_unit) + if res is not None: # the try asked for: its record says so, before a retry may move it + how = {"begun": True} if name in fresh else {"replaced": said(trials.get(name) or {})} + how.update({"no_result": True} if name in killed else {}) + res["standard"] = dict(res.get("standard") or {}, rerun=dict(mark, **how)) + job._write(os.path.join(job_dir, name, "result.json"), json.dumps(res, indent=1)) + return res + + record: dict = {} + + def write(ended: List[dict], budget: Optional[dict]) -> None: + now = {name: merge._read(os.path.join(job_dir, name, "result.json")) for name in merge._trials(job_dir)} + every = list(now.values()) + out = dict(old, **{k: v for k, v in merge.result_of([{"result": old, "trials": list(now)}], every).items() if k != "budget"}) + if r.repeat > 1: + hat = job.pass_hat(every) + out.pop("pass_hat_k", None) + out.update({"pass_hat_k": hat} if hat else {}) + if not (cfg["standard"].get("merged_from")): # a merged job's is its shards': this job has no relay of its own + who = job.served_total(every, job.served(r.benchmark_calls(), getattr(r, "serving", None))) + out.pop("served", None) + out.update({"served": who} if who else {}) + replaced, begun, costs = [], [], [] + for name in picked: + res = now.get(name) or {} + k, last = fresh.get(name, first_try.get(name)), int((res.get("standard") or {}).get("retries") or 0) + if not res or (name not in fresh and last < k): + continue # not begun, or stopped: the try before is back + unit = str((res.get("standard") or {}).get("unit") or "") + if name in fresh: # its first try ran now, and each try after it + begun.append({"trial": name, "unit": unit, "now": said(res)}) + else: + replaced.append({"trial": name, "unit": unit, "try": k, "was": said(trials.get(name) or {}), "now": said(res)}) + costs += [_cost(res)] + [_cost(merge._read(os.path.join(job_dir, "retried", f"{name}.try-{t}", "result.json"))) + for t in range(k + 1, last + 1)] + known = [c for c in costs if c is not None] + spent = budget["spent_usd"] if budget else (round(sum(known), 6) if known else None) + record.update({"at": job.iso(t0), "finished_at": job.iso(time.time()), **({"reason": reason} if reason else {}), + "trials": list(picked), "replaced": replaced, **({"begun": begun} if fresh else {}), + **({"no_result": list(killed)} if killed else {}), + **({"cumulative_replies": True} if r.ledger is not None else {}), + "max_usd": capped["max_usd"] if capped and r.max_usd is not None else r.max_usd, + **({"left_usd": r.max_usd} if capped and r.max_usd is not None else {}), "spent_usd": spent, + **({"stopped": True} if r._stopped.is_set() or (budget or {}).get("stopped") else {})}) + out["reruns"] = list(old.get("reruns") or []) + [dict(record)] + if capped: + # the job's one cap: what every part spent, each change of the cap, and whether this part stopped at it + used = (budget["spent_usd"] or 0) + (budget.get("unsettled_usd") or 0) if budget else (spent or 0) + if r.ledger is not None: + used = _ledger_spent(r.ledger.path, used) + whole = dict(old.get("budget") or {}, max_usd=capped["max_usd"], spent_total_usd=capped["spent_usd"] + used, + closed=bool((budget or {}).get("stopped"))) + if capped["changed"]: + whole["changes"] = list(whole.get("changes") or []) + [{"at": job.iso(t0), "max_usd": capped["max_usd"], "was": capped["was"]}] + out["budget"] = whole + job._write(os.path.join(job_dir, "result.json"), json.dumps(out, indent=1)) + + ended, budget, u0 = r.run_units(work, write, first) + p.emit("units", "done", seconds=round(time.time() - u0, 1)) + p.emit("done", n=len(ended), seconds=round(time.time() - t0, 1)) + if budget and budget.get("max_usd") is not None and capped: + r.say(f"spent {ledgers.usd(budget['spent_usd'] or 0)} USD" + + (", stopped at the job's cap" if budget.get("stopped") else "") + + f"; the job has spent {ledgers.usd(capped['spent_usd'] + (budget['spent_usd'] or 0))} of its " + f"{ledgers.usd(capped['max_usd'])} USD cap") + if fresh: + r.say(f"run: {len(record['begun'])} of {len(fresh)} begun" + + "".join(f"; {x['trial']}: {_word(x['now'])}" for x in record["begun"])) + if len(picked) > len(fresh): + r.say(f"ran again: {len(record['replaced'])} of {len(picked) - len(fresh)} replaced" + + "".join(f"; {x['trial']}: {'no result' if x['trial'] in killed else _word(x['was'])} -> {_word(x['now'])}" + for x in record["replaced"])) + return dict(record, job=job_dir) + + +def _word(result: dict) -> str: + """A try's result in a line: ``error KIND``, ``reward 1.0``, ``score 0.5``.""" + if "error" in result: + return f"error {result['error']}" + return " ".join(f"{k} {v}" for k, v in result.items()) or "no verdict" diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 26a638de..caca1368 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -81,7 +81,7 @@ from nullius.standard.contract import definitions, match from nullius.standard.protocols import acp, jsonl from nullius.standard.requirements import hostreq, install -from nullius.standard.runner import job, pace as pacing, shard as shards +from nullius.standard.runner import job, pace as pacing, sets, shard as shards from nullius.standard.runner.retries import RETRIES, retryable # the totals a unit's end carries onto the live board, from its trial's agent_result @@ -716,6 +716,7 @@ class Run: timeouts: Dict[str, float] = {} # the run's own time limits by phase (__init__) forced_turns: Optional[int] = None max_calls: Optional[int] = None # the run's cap on a unit's agent's model calls (__init__) + _tries: Dict[str, int] = {} # by trial, the try a re-run by hand begins it with (``rerun``); none in a run exchanges: str = "off" # whether a unit's relay keeps its agent's calls whole (__init__: whole by default) exchanges_max_mb: int = exchange_store.MAX_MB def __init__(self, bench: dict, other: dict, *, model: str, provider: str, dataset: Optional[str] = None, @@ -728,7 +729,7 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas licences: Optional[Licences] = None, bench_options: Optional[dict] = None, which=shutil.which, remove_images: bool = False, prices: Optional[dict] = None, max_usd: Optional[float] = None, max_usd_per_unit: Optional[float] = None, prices_unreachable: Optional[str] = None, - units_file: Optional[dict] = None, + units_file: Optional[dict] = None, task_set: Optional[dict] = None, start_with: Optional[dict] = None, constraints: Optional[dict] = None, timeouts: Optional[dict] = None, max_turns: Optional[int] = None, max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None, boat_size: str = boat.SIZE, relay_container: bool = False, exchanges: str = exchange_store.DEFAULT, @@ -754,6 +755,18 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas an id the dataset does not hold refuses the run before any unit starts. The job's config records the file's name, its sha256 and its units. + ``task_set``: a task set's record (``sets.record``): its units run as + a file's would, and the job's config keeps the record. Refused beside + ``units_file``. + ``start_with``: the part of the plan the run begins with (``run --start-with``): + ``{"count": N}``, the plan's first N units; ``{"units_file": ...}`` or + ``{"task_set": ..., "dataset": D}``, the plan's units the file or the set + lists. The plan is the whole (the dataset, the file, the set, the shard and + the limit, as without it): the job records it, its feed queues each of its + trials, and only the part's begin, each with all its attempts; the rest + stand planned with no attempt, for ``rerun`` to run in the job later. + Refused before any unit starts for a part that names a unit outside the + plan, more units than it holds, or a set of another dataset. ``repeat``: each unit run that many times (a conformance check run for confidence, ``conform``), each run a trial of its own tagged ``u0042r2``; once by default, tagged ``u0042``. Each is an @@ -982,7 +995,21 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas self.provider_env = env # where the provider's model list is asked (``known_models``) self.key_header = "authorization" if keyless else key_header(provider, other, env) self.limit, self.concurrency = limit, limits.concurrency(max(1, int(concurrency)), self.constraints) + if units_file and task_set: + raise Refused("a run takes its units from a file or from a task set, not both") self.units_file = units_file + self.task_set = task_set + if start_with is not None: + n = start_with.get("count", 1) + if isinstance(n, bool) or not isinstance(n, int) or n < 1: + raise Refused(f"--start-with {n!r}: a whole number of units, at least 1") + if shard and shard[1] > 1: + raise Refused("--start-with and --shard: a run begun on a part of its plan is run on one machine") + given = start_with.get("task_set") and start_with.get("dataset") + if given and given != self.ds["id"]: + raise Refused(f"--start-with: the task set {start_with['task_set']['name']} is cut from the dataset " + f"{given}, and the run plans {self.ds['id']}") + self.start_with = start_with self.repeat = max(1, int(repeat or 1)) self.retries = max(0, int(retries or 0)) self.retry_if = retry_if or retryable @@ -1149,46 +1176,68 @@ def _start(self, lck, mine) -> str: container.sweep(self.name) raise everything = [str(u) for u in units] - listed = self.units_file["units"] if self.units_file else None + listed = self.units_file["units"] if self.units_file else self.task_set["units"] if self.task_set else None + why, unknown = "", [] if listed is not None: held = set(everything) unknown = [u for u in listed if u not in held] if unknown: - # what the run holds is let go as when its driver cannot list the units: on the container - # backend that includes the containers its driver or its doors started - for d in self.drivers: - d.close() - if self.bench_relay is not None: - self.bench_relay.stop() - if self.backend == "container" or self.relay_container: - container.sweep(self.name) - # the record a refusal in ready() leaves, which the runs list reads (execution's refused): - # the job's folder with its progress.jsonl, the driver's working folders and logs taken out - work = os.path.join(self.job_dir, ".work") - for name in os.listdir(work): - path = os.path.join(work, name) - if name in ("driver", "driver-home"): - shutil.rmtree(path, ignore_errors=True) - elif name.startswith("driver-") and name.endswith(".log"): - os.remove(path) words = self.bench["units"] - why = (f"{self.units_file['name']} lists {len(unknown)} {words['noun'] if len(unknown) == 1 else words['nouns']} " - f"that {self.bench['label']}'s dataset {self.ds['id']} does not hold: " + ", ".join(unknown)) - p.emit("refused", detail=why) - raise Refused(why) + if self.units_file: + why = (f"{self.units_file['name']} lists {len(unknown)} {words['noun'] if len(unknown) == 1 else words['nouns']} " + f"that {self.bench['label']}'s dataset {self.ds['id']} does not hold: " + ", ".join(unknown)) + elif self.task_set.get("version") and self.task_set["version"] != str(self.bench.get("_version") or ""): + # made at another version of the benchmark, whose list may hold other tasks + label = self.task_set.get("label") or self.task_set["name"] + ours, theirs = (sets.version_label(self.bench, v) for v in (str(self.bench.get("_version") or ""), self.task_set["version"])) + why = (f"the task set {label} was made at {self.bench['label']} {theirs}, and {unknown[0]} is not a task of " + f"{self.ds['id']} at {ours}, the version this run is at" + + (f" ({len(unknown) - 1} more are not either)" if len(unknown) > 1 else "") + + f": run it at {theirs}, or make a set at {ours}") + else: + # a set holds no option: its ids are checked against the listing under this run's own + given = ", ".join(f"{k}={v}" for k, v in sorted(self.bench_options.items())) or "none" + why = (f"{len(unknown)} of the {len(listed)} ids of the task set {self.task_set.get('label') or self.task_set['name']} " + f"are not listed by {self.bench['label']}'s dataset {self.ds['id']} " + f"under the run's options ({given}): " + ", ".join(unknown[:5]) + (", ..." if len(unknown) > 5 else "")) # the list and the shard, then the limit; each unit keeps its place in the whole dataset (its trial's tag) mine = shards.select(everything, *self.shard, by=self.shard_by) if self.shard else list(enumerate(everything)) if listed is not None: wanted = set(listed) mine = [(i, u) for i, u in mine if u in wanted] mine = mine[: self.limit] if self.limit else mine + part = None + if not why and self.start_with is not None: + part, why = self.part_of([u for _, u in mine]) + if why: + # what the run holds is let go as when its driver cannot list the units: on the container + # backend that includes the containers its driver or its doors started + for d in self.drivers: + d.close() + if self.bench_relay is not None: + self.bench_relay.stop() + if self.backend == "container" or self.relay_container: + container.sweep(self.name) + # the record a refusal in ready() leaves, which the runs list reads (execution's refused): + # the job's folder with its progress.jsonl, the driver's working folders and logs taken out + work = os.path.join(self.job_dir, ".work") + for name in os.listdir(work): + path = os.path.join(work, name) + if name in ("driver", "driver-home"): + shutil.rmtree(path, ignore_errors=True) + elif name.startswith("driver-") and name.endswith(".log"): + os.remove(path) + p.emit("refused", detail=why) + raise Refused(why) units = [u for _, u in mine] - self.n_units = len(units) + begin = units if part is None else part + self.n_units = len(begin) if getattr(self, "boat", None) is not None: - why = self.boat.starts(len(units) * self.repeat) + why = self.boat.starts(len(begin) * self.repeat) if why: self.say(why) - p.emit("units", "start", n=len(units) * self.repeat, of=len(everything), noun=self.bench["units"]["nouns"], + p.emit("units", "start", n=len(begin) * self.repeat, of=len(everything), noun=self.bench["units"]["nouns"], + **({"planned": len(units) * self.repeat} if part is not None else {}), **({"detail": self.cap_dropped} if self.cap_dropped else {})) job.write_config(self.job_dir, job=self.name, bench=self.bench, other=self.other, model=self.model, provider=self.provider, dataset=self.ds["id"], units=units, concurrency=self.concurrency, @@ -1198,20 +1247,105 @@ def _start(self, lck, mine) -> str: options=self.options, launch=self.launch or "", bench_options=self.bench_options, # a shard of a list splits the listed units: they are its whole shard=shards.record(*self.shard, len(everything) if listed is None else len(listed), units, self.limit, by=self.shard_by) - if self.shard else None, units_file=self.units_file, + if self.shard else None, units_file=self.units_file, task_set=self.task_set, + start_with=self.part_record(part) if part is not None else None, repeat=self.repeat, retries=self.retries, prices=self.prices_record(), constraints=self.constraints, served_by=self.serving, timeouts=self.timeouts, max_turns=self.forced_turns, max_calls=self.max_calls, exchanges=self.exchanges, exchanges_max_mb=self.exchanges_max_mb, simulator=self.simulator_model if self.other["_kind"] in ("agent", "upstream") and self.simulator_model else "") # every unit once, then every unit again: a repeat cut short still has each unit's first run work = [(i, u, r) for r in range(1, self.repeat + 1) for i, u in mine] - self.n_units = len(work) # what the progress counts: every run of every unit + # begun on a part: the plan's every trial queued, the part's begun; the rest stand planned for a re-run + begun = set(part or ()) + first = work if part is None else [(i, u, r) for i, u, r in work if u in begun] + self.n_units = len(first) # what the progress counts: every run of every unit self.feed = live_feed.Writer(os.path.join(self.job_dir, live_feed.FEED), self.name) self.feed.emit("job.start", n_total=len(work), n_concurrent=self.concurrency, agents=[job.agent_name(self.other)], tasks=units, **({"budget": {k: v for k, v in (("max_usd", self.max_usd), ("unit_max_usd", self.unit_max_usd)) if v is not None}} if self.ledger is not None else {})) # the live board says the cap for pos, (i, u, r) in enumerate(work): self.feed.emit("trial.queued", self.trial_name(i, u, r), agent=job.agent_name(self.other), position=pos) + results, budget, u0 = self.run_units(first, lambda results, budget: job.write_result( + self.job_dir, self.name, t0, time.time(), results, len(work), budget=budget, + served=job.served(self.benchmark_calls(), getattr(self, "serving", None)))) + # the units' stage says why it ended early: a line of its own would be a stage that never starts + p.emit("units", "done", seconds=round(time.time() - u0, 1), + **({"detail": f"stopped at the spending cap of {ledgers.usd(budget['max_usd'])} USD: " + f"{len(budget['cut_off'])} cut off, {len(budget['not_run'])} not run"} if budget and budget["stopped"] else {})) + self.n_verdicts, self.n_ended = sum(1 for x in results if x.get("verifier_result")), len(results) + if budget and budget["stopped"]: + spent = "unknown" if budget["spent_usd"] is None else ledgers.usd(budget["spent_usd"]) + self.say(f"stopped: a call did not fit the spending cap of {ledgers.usd(budget['max_usd'])} USD " + f"({spent} spent): {len(budget['cut_off'])} cut off, {len(budget['not_run'])} not run") + elif budget and budget["max_usd"] is not None: + self.say(f"spent {ledgers.usd(budget['spent_usd'] or 0)} of the {ledgers.usd(budget['max_usd'])} USD cap") + elif budget: + self.say(f"spent {ledgers.usd(budget['spent_usd'] or 0)} USD") + if budget and budget.get("over_unit"): + self.say(f"{len(budget['over_unit'])} of the {self.bench['units']['nouns']} reached the cap of " + f"{ledgers.usd(budget['unit_max_usd'])} USD each and were cut off there") + if self.halted: + self.say(f"stopped: the endpoint refused {REFUSED_IN_A_ROW} units in a row ({self.halted[0]}: " + f"{redact(str(self.halted[1]))[:200]}); the {len(first) - len(results)} units not begun were not run") + rewards = [(r.get("verifier_result") or {}).get("rewards", {}) for r in results] + if self.bench["score"]["kind"] == "pass": + ok = sum(1 for w in rewards if w.get("reward") == 1.0) + p.emit("done", n=len(results), passed=ok, seconds=round(time.time() - t0, 1)) + self.say(f"done: {self.counted(results)}, {ok} passed") + else: + scores = [w["score"] for w in rewards if "score" in w] + mean = job.mean_score(results) + p.emit("done", n=len(results), scored=len(scores), mean=round(mean, 3) if mean is not None else None, + seconds=round(time.time() - t0, 1)) + self.say(f"done: {self.counted(results)}, {len(scores)} scored" + + (f", mean {mean:.3f}" if mean is not None else "")) + if part is not None: + words, ran = self.bench["units"], len({(x.get("standard") or {}).get("unit") for x in results}) + self.say(f"{ran} of {len(units)} planned {words['noun'] if len(units) == 1 else words['nouns']} run" + + (f"; the rest in this job: nullius standard rerun {self.job_dir} --unfinished (or --next N, --set NAME)" + if len(begin) < len(units) else "")) + return self.job_dir + + def part_of(self, plan: List[str]) -> tuple: + """(the units of ``plan`` the run begins with, in the plan's order; why it is refused, or "").""" + given, words = self.start_with or {}, self.bench["units"] + many = lambda n: words["noun"] if n == 1 else words["nouns"] + if "count" in given: + n = given["count"] + if n > len(plan): + return None, (f"--start-with {n}: more {words['nouns']} than the plan holds, {len(plan)} " + f"{many(len(plan))} of {self.ds['id']}") + return plan[:n], "" + source = given.get("units_file") or given.get("task_set") or ({"units": given["ids"]} if "ids" in given else {}) + named = (f"set:{source['name']}" if given.get("task_set") else ("ids:" + ",".join(given["ids"][:3]) + (",..." if len(given["ids"]) > 3 else "")) if "ids" in given + else source.get("name", "")) + held = set(plan) + outside = [u for u in source.get("units") or [] if u not in held] + if outside: + return None, (f"--start-with {named} names {len(outside)} {many(len(outside))} outside the plan of " + f"{len(plan)} {many(len(plan))}: " + ", ".join(outside[:5]) + (", ..." if len(outside) > 5 else "")) + wanted = set(source.get("units") or []) + return [u for u in plan if u in wanted], "" + + def part_record(self, part: List[str]) -> dict: + """What the job's config keeps of the part it began with (``standard.start_with``): how it was named - + a count, a file (its name, sha256 and units) or a task set (``sets.record``); ids named on the command + line, nothing more - and its units, in the plan's order.""" + given = self.start_with or {} + how = ({"count": given["count"]} if "count" in given else {"units_file": given["units_file"]} if given.get("units_file") + else {"task_set": given["task_set"]} if given.get("task_set") else {}) + return dict(how, units=list(part)) + + def run_units(self, work: list, write: Callable[[List[dict], Optional[dict]], None], first=None) -> tuple: + """The units of ``work`` ((i, unit, r) each), as many at once as the + concurrency, then each attempt's retries (``run_again``). Whatever + ends them - their end, a Stop, an error - what the run holds is let + go, the spending cap's record is read, ``write`` is given the + attempts that ended (each its last try) and that record, and the feed + says the job's end. ``first``: how each item begins, given the item + and the unit's own run: the unit run (by default), or a further try + of a trial already in the job (``try_again``, a re-run by hand). + Returns (the attempts that ended, the cap's record, when they began).""" results = [] u0 = time.time() self._halt, self._refused, self.halted = threading.Event(), [], None @@ -1249,7 +1383,7 @@ def work_unit(iur): if (self.backend == "container" or self.relay_container) and self.base and container.on_loopback(self.base): self.loopback = container.Loopback(self.base, image=self.image, job=self.name).start() for iur in work: - futures.append(pool.submit(work_unit, iur)) + futures.append(pool.submit(work_unit, iur) if first is None else pool.submit(first, iur, work_unit)) pending = set(futures) while pending: # timed: Python runs signal handlers only in this thread, and Stop's SIGTERM can reach another thread @@ -1284,42 +1418,10 @@ def work_unit(iur): self.loopback.stop() budget = self.budget([self.attempt_name(u, r) for n, (_, u, r) in enumerate(work) if n >= len(begun) or not begun[n]]) self.capped = bool(budget and budget["stopped"]) - job.write_result(self.job_dir, self.name, t0, time.time(), results, len(work), budget=budget, - served=job.served(self.benchmark_calls(), getattr(self, "serving", None))) + write(results, budget) errored = sum(1 for x in results if x.get("exception_info")) self.feed.emit("job.end", n_completed=len(results) - errored, n_errored=errored, n_cancelled=len(work) - len(results)) - # the units' stage says why it ended early: a line of its own would be a stage that never starts - p.emit("units", "done", seconds=round(time.time() - u0, 1), - **({"detail": f"stopped at the spending cap of {ledgers.usd(budget['max_usd'])} USD: " - f"{len(budget['cut_off'])} cut off, {len(budget['not_run'])} not run"} if budget and budget["stopped"] else {})) - self.n_verdicts, self.n_ended = sum(1 for x in results if x.get("verifier_result")), len(results) - if budget and budget["stopped"]: - spent = "unknown" if budget["spent_usd"] is None else ledgers.usd(budget["spent_usd"]) - self.say(f"stopped: a call did not fit the spending cap of {ledgers.usd(budget['max_usd'])} USD " - f"({spent} spent): {len(budget['cut_off'])} cut off, {len(budget['not_run'])} not run") - elif budget and budget["max_usd"] is not None: - self.say(f"spent {ledgers.usd(budget['spent_usd'] or 0)} of the {ledgers.usd(budget['max_usd'])} USD cap") - elif budget: - self.say(f"spent {ledgers.usd(budget['spent_usd'] or 0)} USD") - if budget and budget.get("over_unit"): - self.say(f"{len(budget['over_unit'])} of the {self.bench['units']['nouns']} reached the cap of " - f"{ledgers.usd(budget['unit_max_usd'])} USD each and were cut off there") - if self.halted: - self.say(f"stopped: the endpoint refused {REFUSED_IN_A_ROW} units in a row ({self.halted[0]}: " - f"{redact(str(self.halted[1]))[:200]}); the {len(work) - len(results)} units not begun were not run") - rewards = [(r.get("verifier_result") or {}).get("rewards", {}) for r in results] - if self.bench["score"]["kind"] == "pass": - ok = sum(1 for w in rewards if w.get("reward") == 1.0) - p.emit("done", n=len(results), passed=ok, seconds=round(time.time() - t0, 1)) - self.say(f"done: {self.counted(results)}, {ok} passed") - else: - scores = [w["score"] for w in rewards if "score" in w] - mean = job.mean_score(results) - p.emit("done", n=len(results), scored=len(scores), mean=round(mean, 3) if mean is not None else None, - seconds=round(time.time() - t0, 1)) - self.say(f"done: {self.counted(results)}, {len(scores)} scored" - + (f", mean {mean:.3f}" if mean is not None else "")) - return self.job_dir + return results, budget, u0 def counted(self, results: List[dict]) -> str: """What ended, as the run's last line says it: ``3 problems``, and @@ -1396,7 +1498,7 @@ def run_again(self, results: List[dict], work: list, work_unit, done: Dict[str, return self.progress.emit("units", "progress", detail=f"trying {len(todo)} again: retry {retry} of {self.retries}") self.say(f"trying again: {len(todo)}, retry {retry} of {self.retries}") - tries = {pool.submit(self.try_again, name, by_name[name], retry, work_unit): name for name in todo} + tries = {pool.submit(self.try_again, name, by_name[name], self._tries.get(name, 0) + retry, work_unit): name for name in todo} pending = set(tries) while pending: # Poll so this thread can handle Stop. @@ -1444,8 +1546,26 @@ def try_again(self, name: str, iur: tuple, retry: int, work_unit) -> Optional[di os.rmdir(os.path.dirname(keep)) except OSError: pass + self._back(name, iur[1], here) return res + def _back(self, name: str, unit: str, here: str) -> None: + """The try before, back in its place: said on the feed as its end once more (``back``), so the live + board's card reads it, and not a try that never ended.""" + if self.feed is None: + return + try: + with open(os.path.join(here, "result.json"), encoding="utf-8") as f: + res = json.load(f) + except (OSError, ValueError): + return + ei = res.get("exception_info") or {} + exc = (str(ei["exception_type"]), str(ei.get("exception_message") or "")) if ei.get("exception_type") else None + self.feed.emit("trial.end", name, task=unit, agent=self.other["key"], back=True, + **job.feed_outcome(self.bench["score"]["kind"], (res.get("verifier_result") or {}).get("rewards") or {}, exc), + **{k: v for k, v in (res.get("agent_result") or {}).items() if k in FEED_TOTALS}, + durations=job.feed_durations(res)) + def ready(self) -> None: """What the run needs before its first unit, each a stage said as it goes - or as there already: the base image (docker), the benchmark's @@ -1669,6 +1789,7 @@ def _unit(self, i: int, unit: str, r: int = 1, retry: int = 0) -> Optional[dict] rl, environment, box, changes = None, None, None, None image, finished = None, False # its own image; whether it ended, or was broken off (a Stop) retry_ok = True # whether its failure is one a further try may mend + again = retry - self._tries.get(name, 0) # the run's own retry this try is: its tries before the run counted out try: try: # a setup's unit needs none: the upstream's answerer reads its data itself. The unit is set up @@ -1844,7 +1965,7 @@ def sent(): install.prune(self.other, home) # its declared caches: the trial is written, no one reads them now verdict = "error " + exc[0] if exc else f"reward {score.get('reward')}" self.say(f" {unit}: {verdict}") - self.said_unit(unit, score, exc, retry) + self.said_unit(unit, score, exc, again) if self.feed is not None: self.feed.emit("trial.end", name, task=unit, agent=self.other["key"], **job.feed_outcome(self.bench["score"]["kind"], score, exc), @@ -1866,7 +1987,7 @@ def sent(): self._counted[name] = tag if image: self._held_images[name] = image - if not (retry < self.retries and self.retry_if(res) and not self._stopped.is_set() + if not (again < self.retries and self.retry_if(res) and not self._stopped.is_set() and not (getattr(self, "_halt", None) is not None and self._halt.is_set()) and not self.cap_spent(i, r)): self.let_go(name) # its rate limit's end stays: the next unit's pause reads it (``paced``) return res diff --git a/app/nullius/standard/runner/sets.py b/app/nullius/standard/runner/sets.py new file mode 100644 index 00000000..083b1101 --- /dev/null +++ b/app/nullius/standard/runner/sets.py @@ -0,0 +1,588 @@ +"""Task sets: a named list of a benchmark's units, kept in the user catalogue. + +An entry is ``sets//.json`` under the user catalogue +(``paths.catalogue_dir``, ``NULLIUS_CATALOGUE``): a plain file to copy or keep +in git. A set is a group of tasks, run as a benchmark's own dataset is: it +holds an id minted when it is made, its label and the name made from it, its +description, the benchmark, the version of the benchmark it was made at, the +dataset it is cut from, and its list, and nothing that binds a run (no +benchmark option, no setup). The label is the text a person typed; the name +is what commands take: the label in lower case with hyphens, ``-2`` and on +for a second equal one (``name_for``). + +A set is frozen: nothing changes its list once made, and another list is +another set. The file keeps one entry in ``revisions``: its number, its date, +a note, the unit ids and a content hash over the benchmark, the dataset and +the sorted ids. A file made before sets were frozen may hold several; it reads +as its latest, and is never rewritten for it. Two runs ran the same set when +their jobs name the same id. Two entries with equal lists stay two sets. An +entry holding any other field is refused where it is read; one of the earlier +format, which kept a run's options, is refused as such (``Earlier``), and +``plain`` says it on a page without its path. ``rename`` gives a set another +label, and the name made from it, its id and list kept, so a job that ran it +finds it by its id (``by_id``); ``delete`` removes its file, and a job that +ran it keeps its record. + +``record`` is what a job's ``config.json`` keeps of the set it ran +(``standard.task_set``): its id, name, label, the number of its list, the +hash, the units and the version it was made at. With the job's benchmark and +dataset that is enough for ``import_path`` to rebuild the entry on another +machine, its description empty and its list dated by the import. The same id +with another list is refused there. +""" +from __future__ import annotations + +import hashlib +import json +import os +import re +import tempfile +import unicodedata +import uuid +from datetime import datetime, timezone +from typing import Iterable, List, Optional, Tuple + +from nullius import paths +from nullius.runs import classify +from nullius.standard.contract import definitions + +SCHEMA = "nullius.task-set/v1" +FOLDER = "sets" +# A name stays inside its benchmark's folder: no slash, no leading dot, no ``..`` +_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$") +NAME_MAX = 64 +LABEL_MAX = 80 +# the base of a name made from a label that holds no Latin letter or digit +FALLBACK = "task-set" +_TAG = re.compile(r"__u(\d+)(?:r\d+)?$") +# The outcome groups ``--outcome`` takes beside the pages' outcome names: a pass, a verdict against the +# agent (its failures and its own errors, as the attempts' pass count reads them), the infrastructure's +GROUPS = { + "passed": {classify.RESOLVED}, + "failed": {classify.PATCH_FAILED_TESTS, classify.FAILED_VERIFICATION, classify.PATCH_NOT_APPLIED, + classify.NO_PATCH, classify.AGENT_ERROR}, + "infra": set(classify.INFRA_OUTCOMES), +} +HEADER = ("id", "name", "label", "description", "benchmark", "version", "dataset") +# what an entry of the earlier format held beside its header: a run's options, bound to the set +EARLIER = ("benchmark_version", "benchmark_options", "setup") +REVISION = ("revision", "date", "note", "units", "hash") +RECORD = ("id", "name", "revision", "hash", "units") +# what the record of a newer job holds beside those: what its page shows, and what a run checks the set against +RECORD_MORE = ("label", "version") + + +class Refused(Exception): + """The set cannot be made, changed, read or run as asked; the message says why.""" + + +class NotFound(Refused): + """No such set, file or job.""" + + +class Earlier(Refused): + """An entry of the earlier format, which kept a run's options: refused where it is read.""" + + +def root_dir(root: Optional[str] = None) -> str: + return root if root is not None else paths.catalogue_dir() + + +def check_name(name: str) -> str: + if not isinstance(name, str) or not _NAME.match(name) or ".." in name: + raise Refused(f"{name!r} is not a task set's name: letters, digits, '.', '_' and '-', " + "starting with a letter or a digit, at most 64, no '..'") + return name + + +def check_label(label: str) -> str: + """The words a person names a set with, trimmed: any words with at least one letter or digit, at most 80 + characters, on one line.""" + text = label.strip() if isinstance(label, str) else "" + if not text: + raise Refused("a task set needs a name") + if len(text) > LABEL_MAX: + raise Refused(f"a task set's name is at most {LABEL_MAX} characters") + if any(unicodedata.category(c) == "Cc" for c in text): + raise Refused("a task set's name is one line") + if not any(c.isalnum() for c in text): + raise Refused("a task set's name needs a letter or a digit") + return text + + +def slug(label: str) -> str: + """The name a label makes: its Latin letters and digits in lower case, every other run of characters one + hyphen, at most 64; ``task-set`` when nothing is left. "Custom task set" makes ``custom-task-set``.""" + plain = unicodedata.normalize("NFKD", label or "").encode("ascii", "ignore").decode("ascii") + s = re.sub(r"[^a-z0-9]+", "-", plain.lower()).strip("-") + return s[:NAME_MAX].rstrip("-") or FALLBACK + + +def name_for(benchmark: str, label: str, root: Optional[str] = None, but: str = "") -> str: + """The name a set of ``benchmark`` labelled ``label`` takes: its ``slug``, or the first ``-`` from 2 + that no other set of the benchmark has (``but``, the set's own name when it is renamed, counts as free).""" + base = slug(check_label(label)) + folder = _folder(benchmark, root) + taken = {f[:-5] for f in os.listdir(folder) if f.endswith(".json")} if os.path.isdir(folder) else set() + taken.discard(but) + if base not in taken: + return base + for i in range(2, 10000): + name = f"{base[:NAME_MAX - len(str(i)) - 1].rstrip('-')}-{i}" + if name not in taken: + return name + raise Refused(f"every name made from {label!r} is taken") + + +def label_of(entry: dict) -> str: + """What a person reads a set by: its label, or the name of a set made before labels.""" + return entry.get("label") or entry["name"] + + +def version_label(bench: Optional[dict], version: str) -> str: + """A version a set was made at as a reader names it (``main (044bc33)``); the version's key itself when the + benchmark's definition no longer knows it.""" + return ((bench or {}).get("_labels") or {}).get(version) or version + + +def version_of(bench: dict) -> str: + """The version of the benchmark a set made from ``bench`` records: its resolved version, "" when it has none.""" + return str(bench.get("_version") or "") + + +def _bench_key(benchmark: str) -> str: + if not isinstance(benchmark, str) or not definitions._KEY.match(benchmark): + raise Refused(f"{benchmark!r} is not a benchmark's key") + return benchmark + + +def _contained(path: str, folder: str) -> str: + resolved = os.path.realpath(path) + if os.path.commonpath((resolved, folder)) != folder: + raise Refused(f"{path}: outside the task set folder {folder}") + return resolved + + +def _folder(benchmark: Optional[str], root: Optional[str]) -> str: + folder = os.path.join(os.path.realpath(root_dir(root)), FOLDER) + if benchmark is not None: + folder = os.path.join(folder, _bench_key(benchmark)) + return _contained(folder, folder) + + +def path_of(benchmark: str, name: str, root: Optional[str] = None) -> str: + folder = _folder(benchmark, root) + return _contained(os.path.join(folder, check_name(name) + ".json"), folder) + + +def split_ref(ref: str) -> Tuple[str, Optional[int]]: + """``NAME``, or ``NAME@N`` as recipes and commands made before sets were frozen name one: (name, N or None). + ``latest`` reads N.""" + name, at, rev = str(ref).partition("@") + if not at: + return check_name(name), None + if not rev.isdigit() or int(rev) < 1: + raise Refused(f"{ref!r}: a task set's name") + return check_name(name), int(rev) + + +def content_hash(benchmark: str, dataset: str, units: Iterable[str]) -> str: + """The sha256 over what makes the membership: the benchmark, the dataset and the ids sorted (an order, a + comment, a file's name say nothing).""" + doc = {"benchmark": benchmark, "dataset": dataset, "units": sorted(set(str(u) for u in units))} + return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest() + + +def _hash_of(entry: dict, units: Iterable[str]) -> str: + return content_hash(entry["benchmark"], entry["dataset"], units) + + +def _now() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _ids(units: Iterable[str], what: str) -> List[str]: + ids = [str(u) for u in units] + if any(not u or u.startswith("#") or u != u.strip() for u in ids): + raise Refused(f"{what}: an id is a word with no space around it, not empty and not starting with #") + twice = sorted({u for u in ids if ids.count(u) > 1}) + if twice: + raise Refused(f"{what} lists {', '.join(twice)} more than once") + if not ids: + raise Refused(f"{what} lists no unit") + return ids + + +def check(entry: dict, where: str) -> dict: + """``entry`` as read from ``where``, its shape and every list's hash checked.""" + if not isinstance(entry, dict) or entry.get("schema") != SCHEMA: + raise Refused(f"{where}: not a task set (schema {SCHEMA})") + other = sorted(set(entry) - {"schema", *HEADER, "revisions"}) + if other and set(other) & set(EARLIER): + raise Earlier(f"{where}: holds {', '.join(other)}, which a task set does not hold: an entry of the earlier " + "format, which kept a run's options. Delete it and make it again") + if other: + raise Refused(f"{where}: holds {', '.join(other)}, which a task set does not hold: a set is its dataset " + "and its ids, and a run gives its own options") + for k in ("id", "name", "benchmark", "dataset"): + if not isinstance(entry.get(k), str) or not entry[k]: + raise Refused(f"{where}: no {k}") + check_name(entry["name"]) + _bench_key(entry["benchmark"]) + if not isinstance(entry.get("description"), str): + raise Refused(f"{where}: description is text") + for k in ("label", "version"): + if k in entry and (not isinstance(entry[k], str) or not entry[k]): + raise Refused(f"{where}: {k} is text") + revs = entry.get("revisions") + if not isinstance(revs, list) or not revs: + raise Refused(f"{where}: no list of units") + seen = set() + for r in revs: + n = r.get("revision") if isinstance(r, dict) else None + if not isinstance(n, int) or isinstance(n, bool) or n < 1 or n in seen: + raise Refused(f"{where}: a list's number is a whole number, each once") + seen.add(n) + if not isinstance(r.get("date"), str) or not r["date"]: + raise Refused(f"{where}: list {n} has no date") + if not isinstance(r.get("note"), str): + raise Refused(f"{where}: list {n}'s note is text") + if not isinstance(r.get("units"), list) or any(not isinstance(u, str) for u in r["units"]): + raise Refused(f"{where}: list {n} lists no units") + _ids(r["units"], f"{where}: list {n}") + if r.get("hash") != _hash_of(entry, r["units"]): + raise Refused(f"{where}: list {n}'s hash is not that of its units and dataset: " + "the file was changed by hand") + return entry + + +def _read(path: str) -> dict: + try: + with open(path, encoding="utf-8") as f: + return json.load(f) + except FileNotFoundError: + raise NotFound(f"{path}: no such file") + except (OSError, ValueError) as e: + raise Refused(f"{path}: cannot read it as JSON: {e}") + + +def load(benchmark: str, name: str, root: Optional[str] = None) -> dict: + path = path_of(benchmark, name, root) + if not os.path.isfile(path): + raise NotFound(f"no task set {name!r} of {benchmark} (in {os.path.dirname(path)})") + entry = check(_read(path), path) + if entry["name"] != name or entry["benchmark"] != benchmark: + raise Refused(f"{path}: it names {entry['benchmark']}/{entry['name']}, not {benchmark}/{name}") + return entry + + +def latest(entry: dict, rev: Optional[int] = None) -> dict: + """The list ``entry`` holds: its latest, the only one of a set made since sets were frozen. ``rev``, the number a + recipe or a command from before named it by, is taken when it is that list's, and refused otherwise.""" + last = max(entry["revisions"], key=lambda r: r["revision"]) + if rev is not None and rev != last["revision"]: + raise NotFound(f"{entry['name']}@{rev} names an earlier list of the task set {label_of(entry)}: a set is " + f"read as its latest list now; name it {entry['name']}") + return last + + +# the name the modules that read a set by its list number knew it by +revision = latest + + +def entries(benchmark: Optional[str] = None, root: Optional[str] = None) -> Tuple[List[dict], List[str]]: + """Every entry (of ``benchmark``), by benchmark and name; and the files that could not be read.""" + base = _folder(None, root) + got, bad = [], [] + try: + benches = sorted(os.listdir(base)) if benchmark is None else [_bench_key(benchmark)] + except FileNotFoundError: + return [], [] + for b in benches: + if not definitions._KEY.match(b): + continue + try: + folder = _folder(b, root) + except Refused as e: + bad.append(str(e)) + continue + if not os.path.isdir(folder): + continue + for fname in sorted(os.listdir(folder)): + if not fname.endswith(".json") or fname.startswith("."): + continue + try: + got.append(load(b, fname[:-5], root)) + except Refused as e: + bad.append(str(e)) + return got, bad + + +def rows(benchmark: str, root: Optional[str] = None) -> List[dict]: + """The readable entries of ``benchmark`` as a page lists them, by name: {name, label, description, dataset, + version, units, date}, ``units`` the number of its ids, ``date`` the day its list was made, ``version`` "" + for a set made before sets recorded one.""" + out = [] + for e in entries(benchmark, root)[0]: + last = latest(e) + out.append({"name": e["name"], "label": label_of(e), "description": e.get("description") or "", "dataset": e["dataset"], + "version": e.get("version") or "", "units": len(last["units"]), "date": last["date"]}) + return out + + +def by_id(benchmark: str, set_id: str, name: str = "", root: Optional[str] = None) -> Optional[dict]: + """The readable entry of ``benchmark`` holding the id ``set_id``, whatever its name now; None when there is none. + ``name``, the name it was known by, is read first.""" + if not set_id: + return None + if name: + try: + entry = load(benchmark, name, root) + except Refused: + entry = None + if entry is not None and entry["id"] == set_id: + return entry + try: + return next((e for e in entries(benchmark, root)[0] if e["id"] == set_id), None) + except Refused: + return None + + +def plain(e: Refused, benchmark: str, name: str) -> str: + """Why the set ``name`` could not be read, in a line for a page: no file's path.""" + if isinstance(e, Earlier): + return f"The task set {name} is of an earlier format, which kept a run's options: delete it and make it again." + if isinstance(e, NotFound): + return f"There is no task set {name}." + return f"The task set {name} cannot be read: nullius standard set show {benchmark} {name} says why." + + +def write(entry: dict, root: Optional[str] = None) -> str: + """The entry written whole, in place of the old file at once.""" + path = path_of(entry["benchmark"], entry["name"], root) + os.makedirs(os.path.dirname(path), exist_ok=True) + ordered = {"schema": SCHEMA, **{k: entry[k] for k in HEADER if k in entry}, + "revisions": sorted(entry["revisions"], key=lambda r: r["revision"])} + fd, tmp = tempfile.mkstemp(prefix=".set-", suffix=".json", dir=os.path.dirname(path)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(ordered, f, indent=2, ensure_ascii=False) + f.write("\n") + os.replace(tmp, path) + except BaseException: + if os.path.exists(tmp): + os.unlink(tmp) + raise + return path + + +def _dataset(bench: dict, dataset: Optional[str]) -> str: + ids = [d["id"] for d in bench.get("datasets") or []] + if not dataset: + raise Refused(f"--dataset: the dataset the set is cut from, one of {', '.join(ids)}") + if dataset not in ids: + raise Refused(f"{bench['label']} has no dataset {dataset!r}: {', '.join(ids)}") + return dataset + + +def create(bench: dict, label: str, *, dataset: str, units: List[str], description: str = "", note: str = "", + root: Optional[str] = None) -> dict: + """A new entry labelled ``label``, its name made from it (``name_for``), at the version ``bench`` is; written. + A label another set has already gives the next free name.""" + label = check_label(label) + entry = {"id": uuid.uuid4().hex, "name": name_for(bench["key"], label, root), "label": label, + "description": description or "", "benchmark": bench["key"], + **({"version": version_of(bench)} if version_of(bench) else {}), "dataset": _dataset(bench, dataset)} + path = path_of(bench["key"], entry["name"], root) + if os.path.lexists(path): + raise Refused(f"a task set {entry['name']!r} of {bench['key']} exists already ({path})") + ids = _ids(units, f"the set {label}") + entry["revisions"] = [{"revision": 1, "date": _now(), "note": note or "", "units": ids, "hash": _hash_of(entry, ids)}] + write(entry, root) + return entry + + +def _file_of(benchmark: str, name: str, root: Optional[str]) -> str: + """The entry's file as named in its folder (a link stays a link), refused when it leads out of the folder.""" + path_of(benchmark, name, root) + path = os.path.join(_folder(benchmark, root), name + ".json") + if not os.path.isfile(path): + raise NotFound(f"no task set {name!r} of {benchmark} (in {os.path.dirname(path)})") + return path + + +def rename(benchmark: str, name: str, label: str, root: Optional[str] = None) -> dict: + """The entry labelled ``label`` and named by it (``name_for``, its own name free), its id, description and list + kept: written under the new name, then the old file removed. Refused: a label it has already or one not + allowed, and an entry that cannot be read.""" + old = _file_of(benchmark, name, root) + entry = load(benchmark, name, root) + label = check_label(label) + if label == label_of(entry): + raise Refused(f"the task set {name} is named {label!r} already") + new = name_for(benchmark, label, root, but=name) + if new != name and os.path.lexists(os.path.join(_folder(benchmark, root), new + ".json")): + raise Refused(f"a task set {new!r} of {benchmark} exists already") + entry = dict(entry, name=new, label=label) + write(entry, root) + if new != name: + os.unlink(old) + return entry + + +def delete(benchmark: str, name: str, root: Optional[str] = None) -> Optional[dict]: + """Remove the entry's file: the entry as it was, or None when it could not be read (an earlier format, a file + changed by hand). A job that ran it keeps its record.""" + path = _file_of(benchmark, name, root) + try: + entry = load(benchmark, name, root) + except NotFound: + raise + except Refused: + entry = None + os.unlink(path) + return entry + + +def _job_config(job_dir: str) -> dict: + cfg_path = os.path.join(job_dir, "config.json") + if not os.path.isfile(cfg_path): + raise NotFound(f"{job_dir}: no job (no config.json)") + cfg = _read(cfg_path) + if cfg.get("runner") != "standard" or not isinstance(cfg.get("standard"), dict): + raise Refused(f"{job_dir}: not a job of the Nullius standard") + return cfg + + +def _place(trial: str) -> int: + m = _TAG.search(trial) + return int(m.group(1)) if m else 1 << 30 + + +def outcome_names(given: Optional[List[str]]) -> set: + """``--outcome O,...`` (repeatable): the pages' outcome names, or passed, failed, infra.""" + out = set() + for word in (w.strip() for g in given or [] for w in g.split(",")): + if not word: + continue + if word in GROUPS: + out |= GROUPS[word] + elif word in classify.ORDER: + out.add(word) + else: + raise Refused(f"--outcome {word}: one of {', '.join(classify.ORDER)}, or {', '.join(GROUPS)}") + return out + + +def _job_dataset(cfg: dict) -> str: + return str(((cfg.get("datasets") or [{}])[0].get("name") or "")).rpartition("/")[2] + + +def from_job(bench: dict, job_dir: str, outcomes: Optional[List[str]] = None, named: Optional[List[str]] = None) -> dict: + """What a set made from a job holds: {dataset, units, note}. The trials of the + ``outcomes`` and the units ``named`` (each the full id a trial's ``standard.unit`` records), every unit + the job ran when neither is given; a unit of several attempts is taken when any of them is.""" + from nullius.runs import parse + from nullius.standard.runner import job + job_dir = os.path.abspath(job_dir.rstrip("/")) + cfg = _job_config(job_dir) + std = cfg["standard"] + if std.get("benchmark") != bench["key"]: + raise Refused(f"{job_dir} ran {std.get('benchmark')}, not {bench['key']}") + dataset = _job_dataset(cfg) + wanted = outcome_names(outcomes) + trials = [] + for trial_dir in job.trial_dirs(job_dir): + res = _read(os.path.join(trial_dir, "result.json")) + unit = (res.get("standard") or {}).get("unit") + if unit is None: + continue + t = parse.parse_trial(os.path.basename(job_dir), trial_dir) + trials.append((_place(os.path.basename(trial_dir)), str(unit), t.outcome if t else classify.UNKNOWN)) + trials.sort() + held = list(dict.fromkeys(u for _, u, _ in trials)) + if not held: + raise Refused(f"{job_dir}: no trial records its unit") + names = list(dict.fromkeys(named or [])) + unknown = [u for u in names if u not in held] + if unknown: + raise Refused(f"{job_dir} has no trial of {', '.join(unknown)}") + if wanted or names: + chosen = {u for _, u, o in trials if o in wanted} | set(names) + units = [u for u in held if u in chosen] + else: + units = held + if not units: + raise Refused(f"{job_dir} has no trial of the outcomes {', '.join(sorted(wanted))}") + said = ([f"outcomes {','.join(outcomes)}"] if outcomes else []) + ([f"{len(names)} named"] if names else []) + return {"dataset": dataset, "units": units, "note": f"from the job {cfg.get('job_name') or os.path.basename(job_dir)}" + + (f": {'; '.join(said)}" if said else "")} + + +def record(entry: dict, rev: Optional[dict] = None) -> dict: + """What a job's config keeps of the set it ran (``standard.task_set``): its id, name, label, the number and + hash of its list, its units, and the version it was made at when it recorded one.""" + rev = rev or latest(entry) + return {"id": entry["id"], "name": entry["name"], "label": label_of(entry), "revision": rev["revision"], + "hash": rev["hash"], "units": rev["units"], **({"version": entry["version"]} if entry.get("version") else {})} + + +def for_run(bench: dict, ref: str, *, dataset: Optional[str] = None, units_given: bool = False, + root: Optional[str] = None) -> Tuple[dict, str]: + """``run --set NAME``: (the record the job keeps, the dataset), the set's dataset taken over the run's. + A ``--units`` beside it, or another ``--dataset``, is refused. The run's benchmark options are its own, as + on the whole dataset: the run then refuses an id its driver does not list under them.""" + name, rev = split_ref(ref) + if units_given: + raise Refused(f"--set {ref} and --units: the set lists the units, give one or the other") + entry = load(bench["key"], name, root) + got = latest(entry, rev) + if dataset and dataset != entry["dataset"]: + raise Refused(f"--dataset {dataset}: the task set {name} is cut from the dataset {entry['dataset']}") + return record(entry, got), entry["dataset"] + + +def import_path(path: str, root: Optional[str] = None) -> Tuple[dict, bool]: + """(the entry, whether it was written): an entry's file, or a job that ran a set (its ``standard.task_set``), + written here when no set of that name is. When one is, with the same id and the same list, nothing is written. + Refused: the entry here has another id, another entry holds the id, or the same id holds another list here.""" + path = os.path.abspath(path.rstrip("/")) + if os.path.isdir(path): + cfg = _job_config(path) + rec = cfg["standard"].get("task_set") + if not isinstance(rec, dict): + raise NotFound(f"{path}: the job ran no task set") + missing = [k for k in RECORD if k not in rec] + if missing: + raise Refused(f"{path}: its task set's record has no {', '.join(missing)}") + incoming = {"schema": SCHEMA, "id": rec["id"], "name": rec["name"], + **{k: rec[k] for k in RECORD_MORE if k in rec}, "description": "", + "benchmark": cfg["standard"].get("benchmark"), "dataset": _job_dataset(cfg), + "revisions": [{"revision": rec["revision"], "date": _now(), + "note": f"from the job {cfg.get('job_name') or os.path.basename(path)}", + "units": rec["units"], "hash": rec["hash"]}]} + elif os.path.isfile(path): + incoming = _read(path) + else: + raise NotFound(f"{path}: no such file or job") + check(incoming, path) + bench, name = incoming["benchmark"], incoming["name"] + others, _ = entries(bench, root) + holder = next((e for e in others if e["id"] == incoming["id"] and e["name"] != name), None) + if holder: + raise Refused(f"the set {incoming['id']} is here already, named {holder['name']}") + target = path_of(bench, name, root) + if not os.path.exists(target): + incoming = {k: v for k, v in incoming.items() if k != "schema"} + write(incoming, root) + return incoming, True + here = load(bench, name, root) + if here["id"] != incoming["id"]: + raise Refused(f"a task set {name!r} of {bench} with another id is here already ({target})") + if here["dataset"] != incoming["dataset"]: + raise Refused(f"the set {name} here differs in its dataset: {here['dataset']!r}, not {incoming['dataset']!r}") + mine, theirs = latest(here), latest(incoming) + if mine["hash"] != theirs["hash"]: + raise Refused(f"the set {name} holds another list here (hash {mine['hash'][:12]}, not {theirs['hash'][:12]}): " + "the same id with another list") + return here, False diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py new file mode 100644 index 00000000..70454417 --- /dev/null +++ b/app/nullius/standard/runner/units.py @@ -0,0 +1,320 @@ +"""A benchmark's tasks listed with what each is about, searched and counted by category: what +``nullius standard units`` prints and what a page asks for, a page at a time (``find``). + +The driver is started as ``prove`` starts it, with the options given and the others at their defaults, after +the same preparation as a run's: the upstream at its tested commit, the dataset's file checked by its +sha256, the driver's own environment, each made once when it is not there. A definition whose +``driver.list_command`` names a lighter start (the standard library and the dataset's files alone) is +listed by it instead, after the upstream and the dataset alone: its driver's environment is never made for +a listing. A run checks its ids with the driver all the same. The driver is given no licence and no key, +and it starts no unit. Its ``units`` gives the ids; when its definition says ``driver.describe``, its +``describe`` gives each a title, a text and named categories, read from the dataset's files alone. A driver +without it gives ids, and a search reads the ids. ``state`` says, before a listing and with no side effect, +whether it is in the cache, what a first listing fetches, or why it cannot be made. + +The listing is kept in the user cache (``paths.cache_dir()``, ``standard-units//``) under a digest +of what makes it: the benchmark's definition, the files its driver (or its listing command) is started +with, the dataset and the option values. +The same listing again reads that file and starts nothing. + +A search is words: a task matches when each word is in its id, its title or its text, whatever the case. A +category filter is FIELD=VALUE: values of one field widen the match (either), fields narrow it (both). Each +field's values are counted over the tasks the search and the other fields' filters match, so a value chosen +leaves its field's other values counted. +""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import tempfile +from typing import Dict, List, Optional + +from nullius import ondisk, paths +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install +from nullius.standard.runner import run + +PAGE = 100 # tasks a page +FOLDER = "standard-units" +SECONDS = 300 # a driver's time for each of its two answers + + +class Refused(Exception): + """The listing cannot be made as asked; the message says why.""" + + +class NotFound(Refused): + """No such benchmark or dataset.""" + + +def dataset_of(bench: dict, dataset: Optional[str]) -> dict: + ids = [d["id"] for d in bench.get("datasets") or []] + if not dataset: + raise Refused(f"--dataset: one of {', '.join(ids)}") + got = next((d for d in bench.get("datasets") or [] if d["id"] == dataset), None) + if got is None: + raise NotFound(f"{bench.get('label') or bench['key']} has no dataset {dataset!r}: {', '.join(ids)}") + return got + + +def option_values(bench: dict, dataset: str, given: Optional[dict] = None) -> Dict[str, str]: + """The options the driver lists under: those given, the others at their defaults.""" + values, bad = definitions.bench_options_of(bench, dataset, given) + if bad: + raise Refused("; ".join(bad)) + return {str(k): str(v) for k, v in sorted(values.items())} + + +def categories_of(given: Optional[List[str]]) -> Dict[str, List[str]]: + """``--category FIELD=VALUE`` (repeatable): the values asked of each field, in the order given.""" + out: Dict[str, List[str]] = {} + for word in given or []: + field, eq, value = str(word).partition("=") + if not eq or not field.strip() or not value.strip(): + raise Refused(f"--category {word}: FIELD=VALUE") + values = out.setdefault(field.strip(), []) + if value.strip() not in values: + values.append(value.strip()) + return out + + +def filter_text(search: str = "", categories: Optional[Dict[str, List[str]]] = None) -> str: + """The filter as the command line gives it, for a note.""" + words = ([f"--search {json.dumps(search, ensure_ascii=False)}"] if search else []) + words += [f"--category {f}={v}" for f, values in (categories or {}).items() for v in values] + return " ".join(words) + + +def _light(bench: dict) -> Optional[List[str]]: + """The definition's ``driver.list_command``: a start that answers ``units`` and ``describe`` with the + standard library and the dataset's files alone; None when it names none.""" + return (bench.get("driver") or {}).get("list_command") or None + + +def _digest(bench: dict, ds: dict, values: dict) -> str: + h = hashlib.sha256() + definition = {k: v for k, v in bench.items() if not k.startswith("_") or k == "_version"} + h.update(json.dumps([definition, ds, values], sort_keys=True, default=str).encode()) + here = bench.get("_here") + for word in _light(bench) or (bench.get("driver") or {}).get("command") or []: + # the files the driver is started with, beside its definition: a change to its code lists again + path = str(word).replace("{here}", here or "") if str(word).startswith("{here}/") else None + if path and os.path.isfile(path): + h.update(str(word).encode() + b"\0" + ondisk.sha256_of(path).encode()) + return h.hexdigest() + + +def _cache_contained(path: str) -> str: + root = os.path.realpath(paths.cache_dir()) + resolved = os.path.realpath(path) + if os.path.commonpath((resolved, root)) != root: + raise Refused(f"{path}: outside the cache root {root}") + return resolved + + +def cache_path(bench: dict, ds: dict, values: dict) -> str: + return _cache_contained(os.path.join(paths.cache_dir(), FOLDER, bench["key"], _digest(bench, ds, values) + ".json")) + + +def _start(bench: dict, ds: dict, values: dict, work: str) -> jsonl.Proc: + light = _light(bench) + try: + up = install.upstream(bench) + data = install.dataset(bench, ds, up) + cmd, extra = (install.words(light, {"here": bench["_here"]}), {}) if light else install.driver_argv(bench) + except (install.InstallFailed, OSError) as e: + raise Refused(f"cannot prepare {bench['key']}'s dataset {ds['id']} for its listing: {e}") + home, cwd = os.path.join(work, "driver-home"), os.path.join(work, "driver") + os.makedirs(home) + os.makedirs(cwd) + env = run.base_env(home, {**extra, "NULLIUS_UPSTREAM": up or "", "NULLIUS_DATASET": data or "", + "NULLIUS_DATASET_ID": ds["id"], "PYTHONPATH": run.driver_path(), + "PYTHONDONTWRITEBYTECODE": "1", "NULLIUS_VERSION": str(bench.get("_version") or ""), + **run.option_env(values)}) + try: + return jsonl.Proc(cmd, cwd, env, os.path.join(work, "driver.log")).start() + except OSError as e: + raise Refused(f"cannot start {bench['key']}'s driver for its listing: {e}") + + +def _described(got: object, ids: List[str]) -> Dict[str, dict]: + """``describe``'s reply checked: {"units": {ID: {"title", "text", "categories": {FIELD: VALUE}}}}.""" + units = got.get("units") if isinstance(got, dict) else None + if not isinstance(units, dict): + raise Refused("describe: the reply holds no units mapping") + out = {} + for u in ids: + d = units.get(u) or {} + cats = d.get("categories") if isinstance(d.get("categories"), dict) else {} + out[u] = {"title": str(d.get("title") or ""), "text": str(d.get("text") or ""), + "categories": {str(k): str(v) for k, v in cats.items() if v is not None and str(v) != ""}} + return out + + +def _list(bench: dict, ds: dict, values: dict) -> dict: + folder = _cache_contained(os.path.join(paths.cache_dir(), FOLDER)) + os.makedirs(folder, exist_ok=True) + work = tempfile.mkdtemp(prefix=".listing-", dir=folder) + try: + p = _start(bench, ds, values, work) + try: + ids = [str(u) for u in p.request("units", dataset=ds["id"], timeout=SECONDS).get("units") or []] + said = (_described(p.request("describe", dataset=ds["id"], timeout=SECONDS), ids) + if (bench.get("driver") or {}).get("describe") else {}) + except jsonl.Failed as e: + raise Refused(f"{bench['key']}'s driver could not list the dataset {ds['id']}: {e}") + finally: + p.close() + finally: + shutil.rmtree(work, ignore_errors=True) + tasks = [{"id": u, **said.get(u, {"title": "", "text": "", "categories": {}})} for u in ids] + return {"described": bool(said), "tasks": tasks} + + +def listing(bench: dict, dataset: str, options: Optional[dict] = None) -> dict: + """{described, tasks: [{id, title, text, categories}]}: every task of the dataset under the options, in + the driver's order, from the cache when it holds this listing.""" + ds = dataset_of(bench, dataset) + values = option_values(bench, ds["id"], options) + path = cache_path(bench, ds, values) + try: + with open(path, encoding="utf-8") as f: + got = json.load(f) + if isinstance(got, dict) and isinstance(got.get("tasks"), list): + return got + except (OSError, ValueError): + pass + got = _list(bench, ds, values) + path = _cache_contained(path) + os.makedirs(os.path.dirname(path), exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".units-", suffix=".json", dir=os.path.dirname(path)) + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(got, f, ensure_ascii=False) + os.replace(tmp, path) + return got + + +def _cached(path: str) -> bool: + try: + with open(path, encoding="utf-8") as f: + got = json.load(f) + return isinstance(got, dict) and isinstance(got.get("tasks"), list) + except (OSError, ValueError): + return False + + +def _program(word: str) -> Optional[str]: + """The program a command's first word names, when it is not on this machine.""" + there = os.access(word, os.X_OK) if os.sep in word else shutil.which(word) is not None + return None if there else word + + +def state(bench: dict, dataset: str, options: Optional[dict] = None) -> dict: + """What a listing of ``dataset`` under ``options`` needs before it is made, said without making, fetching or + starting anything: {state, fetch: [{what, text}], reason}. ``state`` is one of + + - ``cached``: the listing is in the cache; ``find`` reads it and starts nothing. + - ``light``: the definition's ``driver.list_command`` makes it with the standard library and the dataset's + files; ``fetch`` names what is fetched first (``upstream``, ``dataset``), empty when it is here. + - ``full``: the driver makes it from its own environment on this machine; ``fetch`` also names that + environment (``environment``) when it is not installed. + - ``refused``: it cannot be made; ``reason`` says why (an option, a program not on this machine, a + dataset's file not there). + + ``reason`` is empty but for ``refused``. Raises ``NotFound`` for a dataset the benchmark does not have.""" + ds = dataset_of(bench, dataset) + key = bench["key"] + + def refused(why: str) -> dict: + return {"state": "refused", "fetch": [], "reason": why} + + try: + values = option_values(bench, ds["id"], options) + path = cache_path(bench, ds, values) + except Refused as e: + return refused(str(e)) + if _cached(path): + return {"state": "cached", "fetch": [], "reason": ""} + prepare = f"cannot prepare {key}'s dataset {ds['id']} for its listing: " + fetch, needs = [], [] + up = bench.get("upstream") or {} + up_dir = install.upstream_dir(bench) + if up_dir and not install.ready(up_dir): + fetch.append({"what": "upstream", "text": f"the upstream {up['repository']} at {str(up['tested'])[:12]}"}) + needs.append("git") + if ds.get("url"): + if not os.path.isfile(install.download_path(ds["url"], ds["sha256"])): + fetch.append({"what": "dataset", "text": f"the dataset {ds['url']}"}) + elif ds.get("path") and (not up_dir or install.ready(up_dir)): + if not os.path.isfile(os.path.join(up_dir or bench["_here"], ds["path"])): + folder = "upstream" if up_dir else "definition folder" + return refused(prepare + f"dataset {ds['id']}: {ds['path']} is not in the {folder}") + light = _light(bench) + if not light: + inst = definitions.driver_install(bench)["install"] + where = install.driver_dir(bench) + if where and not install.ready(where): + tools = (["uv"] if any(inst.get(k) for k in ("pip", "project", "indexes", "wheels")) else []) \ + + (["npm"] if inst.get("npm") else []) + fetch.append({"what": "environment", + "text": "the driver's environment" + (f", installed with {' and '.join(tools)}" if tools else "")}) + needs += tools + first = (light or (bench.get("driver") or {}).get("command") or [""])[0] + if first and "{install}" not in first: # a program of the machine's, or a file beside the definition + needs.append(install.words([first], {"here": bench["_here"]})[0]) + missing = next((w for w in needs if _program(w)), None) + if missing: + return refused(prepare + f"{missing} is not on this machine") + return {"state": "light" if light else "full", "fetch": fetch, "reason": ""} + + +def _matches(task: dict, words: List[str]) -> bool: + hay = " ".join((task["id"], task["title"], task["text"])).lower() + return all(w in hay for w in words) + + +def find(bench: dict, dataset: str, options: Optional[dict] = None, search: str = "", + categories: Optional[Dict[str, List[str]]] = None, page: int = 1, size: Optional[int] = PAGE, + within: Optional[List[str]] = None, limit: Optional[int] = None) -> dict: + """The tasks of ``dataset`` under ``options`` that the search text and the category values match, a page + of ``size`` (all of them when None), page 1 first; ``within``, ids that bound it (a task set's), the others + left out as if the dataset did not hold them. The plan's ``limit`` applies before search and paging: + {total, page, pages, of, described, tasks: [{id, title, text, categories}], + categories: {FIELD: [{value, count}, ...]}}. ``total`` counts every match, ``of`` the dataset's tasks; + each field's values are counted over the tasks the search and the other fields' filters match, the most + first. A field no task has is refused; a page past the last is empty.""" + if not isinstance(page, int) or page < 1: + raise Refused(f"page {page}: 1, 2, ...") + got = listing(bench, dataset, options) + tasks, chosen = got["tasks"], categories or {} + if within is not None: + bound = set(within) + tasks = [t for t in tasks if t["id"] in bound] + if limit is not None: + tasks = tasks[:limit] + fields = sorted({f for t in tasks for f in t["categories"]}) + unknown = [f for f in chosen if f not in fields] + if unknown: + raise Refused(f"--category {unknown[0]}: no such category" + + (f"; the categories are {', '.join(fields)}" if fields else "; these tasks have none")) + words = [w for w in str(search or "").lower().split() if w] + searched = [t for t in tasks if _matches(t, words)] + + def kept(t: dict, but: Optional[str] = None) -> bool: + return all(t["categories"].get(f) in values for f, values in chosen.items() if f != but) + + matched = [t for t in searched if kept(t)] + counts = {} + for f in fields: + n: Dict[str, int] = {} + for t in searched: + if f in t["categories"] and kept(t, but=f): + n[t["categories"][f]] = n.get(t["categories"][f], 0) + 1 + counts[f] = [{"value": v, "count": c} for v, c in sorted(n.items(), key=lambda vc: (-vc[1], vc[0]))] + per = size if size else max(1, len(matched)) + start = (page - 1) * per + return {"total": len(matched), "page": page, "pages": max(1, -(-len(matched) // per)), "of": len(tasks), + "described": got["described"], "tasks": matched[start:start + per], "categories": counts} diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index 2e465487..62fb1851 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -108,6 +108,8 @@ nav: - Conform an agent or a capability: cli/conform.md - Fidelity: cli/fidelity.md - Shard and merge: cli/shard-and-merge.md + - Task sets: cli/task-sets.md + - Run tasks again: cli/rerun.md - Pages from a shell: cli/pages.md - Exit codes and output: cli/exit-codes.md - Settings: diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index d3fa7ce7..ec1b2078 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -170,10 +170,13 @@ if (!b) return r; const was = standardBench(r), same = !!was && was.key === b.key; // another version of it keeps the choices if (!same) { r.model_choice = 'any'; delete r.served_by; } + if (was !== b) { delete r.task_sets; delete r.start_with; } r.benchmark = key; const kept = same ? datasetsOf(r).filter(id => b.datasets.some(d => d.id === id)) : []; r.datasets = kept.length ? kept : [b.datasets[0].id]; delete r.dataset; + keepTaskSets(r); + keepStartWith(r); const fitting = standardOthers(r).filter(o => !o.why.length); const keys = fitting.map(o => o.key), first = fitting.find(o => o.own) || fitting.find(o => o.setup && o.key === 'original') || fitting.find(o => !o.control && !o.setup); @@ -187,12 +190,56 @@ if (was !== b || r.name === 'standard-experiment') { r.name = b.key + '-experiment'; r.title = b.label + ' experiment'; } return r; } + // A benchmark whose lists name the list they are cut from (``subset_of``): the dataset a list is drawn under, its + // own id for one cut from none. A choice of another list of that dataset takes the place of the one chosen, its task + // set and its start dropped with it. + const nestedDatasets = b => !!b && (b.datasets || []).some(d => d.subset_of); + const wholeOf = (b, id) => ((b && b.datasets || []).find(d => d.id === id) || {}).subset_of || id; + function swapDataset(r, was, now) { + r.datasets = [...new Set(datasetsOf(r).map(id => id === was ? now : id))]; + delete r.dataset; + if (was !== now) { if (r.task_sets) delete r.task_sets[was]; if (r.start_with) delete r.start_with[was]; } + else if (r.task_sets) delete r.task_sets[now]; + keepTaskSets(r); + return keepStartWith(r); + } + // A chosen dataset's task set, NAME, run in place of all its tasks (recipe.py: task_sets, {dataset: NAME}); + // '' for all of them. A dataset no longer chosen keeps none. + function setTaskSet(r, dataset, ref) { + r.task_sets = {...(r.task_sets || {})}; + if (ref) r.task_sets[dataset] = ref; else delete r.task_sets[dataset]; + // tasks ticked to start with were ticked in the plan's list: another plan asks for them again + if (Array.isArray((r.start_with || {})[dataset])) setStartWith(r, dataset, ''); + return keepTaskSets(r); + } + function keepTaskSets(r) { + const on = datasetsOf(r), kept = Object.entries(r.task_sets || {}).filter(([k, v]) => on.includes(k) && typeof v === 'string' && v); + if (kept.length) r.task_sets = Object.fromEntries(kept); else delete r.task_sets; + return r; + } + // A chosen dataset's plan begun on a part (recipe.py: start_with, {dataset: [ID, ...]}): '' for all of it, the ids + // of the tasks ticked (an empty list while none is), or from a recipe before, N or set:NAME; the rest run later in + // the job. A dataset no longer chosen keeps none. + function setStartWith(r, dataset, value) { + r.start_with = {...(r.start_with || {})}; + if (Array.isArray(value)) r.start_with[dataset] = value.filter(v => typeof v === 'string' && v); + else if (value) r.start_with[dataset] = String(value); else delete r.start_with[dataset]; + return keepStartWith(r); + } + function keepStartWith(r) { + const on = datasetsOf(r), kept = Object.entries(r.start_with || {}).filter(([k, v]) => on.includes(k) + && (typeof v === 'string' && v || Array.isArray(v) && v.every(i => typeof i === 'string'))); + if (kept.length) r.start_with = Object.fromEntries(kept); else delete r.start_with; + return r; + } // A saved standard recipe read back: known fields only, each of its type. function standardFromJSON(raw) { const r = createStandard(typeof raw.benchmark === 'string' ? raw.benchmark : ''); for (const key of ['name', 'title', 'model', 'where', 'model_choice']) if (typeof raw[key] === 'string') r[key] = raw[key]; const sets = Array.isArray(raw.datasets) ? raw.datasets.filter(k => typeof k === 'string') : typeof raw.dataset === 'string' && raw.dataset ? [raw.dataset] : null; if (sets && sets.length) r.datasets = [...new Set(sets)]; + if (raw.task_sets && typeof raw.task_sets === 'object' && !Array.isArray(raw.task_sets)) { r.task_sets = {...raw.task_sets}; keepTaskSets(r); } + if (raw.start_with && typeof raw.start_with === 'object' && !Array.isArray(raw.start_with)) { r.start_with = {...raw.start_with}; keepStartWith(r); } const picked = Array.isArray(raw.others) ? raw.others.filter(k => typeof k === 'string') : typeof raw.other === 'string' && raw.other ? [raw.other] : null; if (picked) r.others = [...new Set(picked)]; if (Array.isArray(raw.where) && raw.where.length && raw.where.every(w => typeof w === 'string')) r.where = raw.where.length > 1 ? [...raw.where] : raw.where[0]; @@ -822,7 +869,14 @@ } function prefill(query) { // ?standard=[&other=]: the standard's recipe for that pair (the Agents and Capabilities pages link here). - if(query.standard)return createStandard(query.standard,query.other||''); + if(query.standard) { + const r = createStandard(query.standard, query.other || ''); + if ((standardBench(r)?.datasets || []).some(d => d.id === query.dataset)) { + r.datasets = [query.dataset]; + if (query.set) setTaskSet(r, query.dataset, query.set); + } + return r; + } // nothing asked for: the Nullius runner, chosen first; a Harbor recipe comes from its own card if(!query.agent&&!query.dataset&&!query.model&&!query.n_tasks&&standard().benchmarks.length)return createStandard(); const r=create(), known=schema.agents.find(a=>[a.id,a.arg,a.label].includes(query.agent))||(query.agent&&schema.agents.find(a=>String(a.arg||'').includes(':')&&String(a.arg).split(':').pop()===query.agent)); @@ -873,5 +927,5 @@ at: String(d.at || ''), saved: typeof d.saved === 'string' ? d.saved : ''}; } catch (e) { return e && e.message === RUNNER_GONE ? {recipe: null, gone: RUNNER_GONE} : null; } } - return {STANDARD_PHASES,STEPS,STEP,runners,RUNNER_GONE,isStandard,standard,standardBase,standardBench,standardOthers,ownAgentsOf,ownChosen,runsOf,standardKeyless,paperModels,paperListed,paperOffered,leaderboard,setModelChoice,servedRoles,servedList,setServed,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; + return {setTaskSet,keepTaskSets,setStartWith,keepStartWith,nestedDatasets,wholeOf,swapDataset,STANDARD_PHASES,STEPS,STEP,runners,RUNNER_GONE,isStandard,standard,standardBase,standardBench,standardOthers,ownAgentsOf,ownChosen,runsOf,standardKeyless,paperModels,paperListed,paperOffered,leaderboard,setModelChoice,servedRoles,servedList,setServed,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; }); diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 19bd5154..d813f583 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -11,6 +11,11 @@ #nullius-builder .nb-errorlist { background: var(--nb-soft); border-left: 2px solid var(--bad); padding: 12px 15px; margin-bottom: 16px; border-radius: 0 6px 6px 0; } #nullius-builder .nb-errorlist button { color: var(--bad); background: none; border: none; padding: 4px 0; text-align: left; display: block; font-size: 12px; } #nullius-builder .nb-saved { width: min(640px, calc(100vw - 32px)); max-height: min(70vh, 640px); } +#nullius-builder .tasks-dialog { width: min(920px, calc(100vw - 32px)); max-height: calc(100vh - 48px); } +#nullius-builder .tasks-dialog .tasks-browse { padding: 0; border: 0; background: none; } +#nullius-builder .tasks-dialog details.tasks-paste { border-top: 0; margin-top: 0; padding-top: 0; } +#nullius-builder .tasks-dialog-acts { display: flex; justify-content: flex-end; margin-top: 20px; } +#nullius-builder .std-yoursets { margin-top: 10px; } #nullius-builder .nb-dialoghead { display: flex; justify-content: space-between; align-items: center; gap: 12px; } #nullius-builder .nb-dialoghead h2 { margin: 0; } #nullius-builder .nb-dialogclose { flex: none; display: grid; place-items: center; padding: 0; width: 32px; height: 32px; border: 0; border-radius: 8px; background: none; color: var(--nb-muted); font-size: 20px; line-height: 1; cursor: pointer; } @@ -250,6 +255,8 @@ /* a limit the benchmark or the agent declares: its placeholder reads as a value; Nullius's default stays grey */ #nullius-builder .nb-field input.nb-declared::placeholder { color: var(--nb-text); opacity: 1; } +/* A chosen dataset's tasks: all of them, or one of its task sets. */ +#nullius-builder .nb-pick-grid + .std-sethead, #nullius-builder .nb-field + .std-sethead { margin-top: 26px; } /* Where: machine kind, its machines, then isolation. Fixed values are not controls. */ #nullius-builder .std-machines { display: inline-flex; gap: 3px; padding: 3px; border: 1px solid var(--nb-line); border-radius: 999px; } #nullius-builder .std-machines button { padding: 6px 16px; border: 0; border-radius: 999px; background: transparent; color: var(--nb-text); font: 14px/1.4 var(--sans); } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 8fc82f99..4ababb0d 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -731,17 +731,121 @@ + (C.leaderboard(rec) ? tile({attr:'model-choice',key:'leaderboard',title:'Like the leaderboard',on:on==='leaderboard'}) : '') + `${tile({attr:'model-choice',key:'any',title:'Any of your choice',on:on==='any'})}`; } + // A chosen dataset's tasks: all of them, or one of its task sets (its name, its number of tasks), small cards, a + // select past five; and the page of its tasks, where a set is made. A recipe from before sets were frozen may name + // one NAME@N: it is that set. + function taskSetChoice(rec, b, x, u) { + const on = (rec.task_sets || {})[x.id] || '', sets = x.sets || [], ref = s => s.name; + const all = 'All ' + (x.units ? x.units + ' ' : '') + u.nouns; + const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(x.id)}`; + const picked = sets.find(s => on === s.name || on.split('@')[0] === s.name); + // a set made at another version of the benchmark says which: the run refuses a task that version lacks + const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; + const choice = sets.length + 1 > 5 + ? `' + : `
` + [tile({attr: 'std-taskset', key: '', data: ` data-of="${esc(x.id)}"`, on: !on, title: all}), + ...sets.map(s => tile({attr: 'std-taskset', key: ref(s), data: ` data-of="${esc(x.id)}"`, on: s === picked, title: s.label, tip: s.description || '', + meta: `${s.units} ${s.units === 1 ? u.noun : u.nouns}${made(s)}`})), + ...(on && !picked ? [tile({attr: 'std-taskset', key: on, data: ` data-of="${esc(x.id)}"`, on: true, title: on})] : [])].join('') + '
'; + // the dataset's name only where several are chosen: one chosen is the one above + const head = C.datasetsOf(rec).length > 1 ? esc(x.label) + ': which tasks?' : 'Which tasks?'; + return `` + choice; + } + // a dataset's proofs as its card shows them: its controls, then whether its ids are stable and nothing leaks + const datasetChecks = (b, x) => (x.controls || []).map(c => controlChip(c)).join('') + checkChip('stable', (x.proofs || {}).units, (x.failed || {}).units, 'the same ids twice, each unique') + + ((b.controls || []).some(c => c.key === 'oracle') ? checkChip('no leak', (x.proofs || {}).leak, (x.failed || {}).leak, 'nothing of the reference shows before the run') : ''); + // Which tasks? of a benchmark whose lists are cut from one (subset_of): all of it, the benchmark's own sets (its + // lists cut from it), then the user's sets of any of them. A choice names the list the run runs (data-was: the + // one chosen before) and, for a user's set, the set + function familyChoice(rec, b, x, u) { + const whole = b.datasets.find(d => d.id === C.wholeOf(b, x.id)) || x, cuts = b.datasets.filter(d => d.subset_of === whole.id); + const on = (rec.task_sets || {})[x.id] || '', many = n => n + ' ' + (n === 1 ? u.noun : u.nouns), was = ` data-was="${esc(x.id)}"`; + const mine = [whole, ...cuts].flatMap(d => (d.sets || []).map(s => ({...s, of: d}))); + const picked = mine.find(s => s.of.id === x.id && s.name === on.split('@')[0]); + const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; + const own = [tile({attr: 'std-family', key: whole.id, data: was, on: x.id === whole.id && !on, title: 'All of it', meta: whole.units ? many(whole.units) : ''}), + ...cuts.map(d => tile({attr: 'std-family', key: d.id, data: was, on: x.id === d.id && !on, title: d.label, tip: d.summary || '', + meta: d.units ? many(d.units) : '', foot: datasetChecks(b, d)}))]; + const yours = [...mine.map(s => tile({attr: 'std-family-set', key: s.name, data: was + ` data-in="${esc(s.of.id)}"`, on: s === picked, title: s.label, + tip: s.description || '', meta: many(s.units) + made(s)})), + ...(on && !picked ? [tile({attr: 'std-family-set', key: on, data: was + ` data-in="${esc(x.id)}"`, on: true, title: on})] : [])]; + const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(picked ? picked.of.id : whole.id)}`; + const head = C.datasetsOf(rec).length > 1 ? esc(whole.label) + ': which tasks?' : 'Which tasks?'; + return `` + + `
${own.join('')}
` + (yours.length ? `
${yours.join('')}
` : ''); + } + // A chosen dataset's plan begun on a part: all of it, or specific tasks, ticked in the list of the plan's tasks (the + // dataset's, or the set's it runs; pickTasks), the rest planned and run later from the job's page. A recipe from + // before holds a number or a task set: shown chosen, as it is, until another choice. + function startChoice(rec, b, x, u) { + const on = (rec.start_with || {})[x.id] || '', ids = Array.isArray(on) ? on : null, data = ` data-of="${esc(x.id)}"`; + const set = typeof on === 'string' && on.startsWith('set:') ? (x.sets || []).find(s => s.name === on.slice(4).split('@')[0]) : null; + const older = typeof on === 'string' && on ? (/^\d+$/.test(on) ? 'The first ' + on : set ? set.label : on.slice(4)) : ''; + const tiles = [tile({attr: 'std-start', key: '', data, on: !on, title: 'All of it'}), + tile({attr: 'std-start-pick', key: x.id, on: !!ids, title: 'Specific ' + u.nouns, meta: ids ? ids.length + ' chosen' : ''}), + ...(older ? [tile({attr: 'std-start', key: on, data, on: true, title: older})] : [])]; + return `

${C.datasetsOf(rec).length > 1 ? esc(x.label) + ': start with' : 'Start with'}

` + + (ids ? `` : '') + + `
${tiles.join('')}
`; + } + // Specific tasks: the tasks page's list (catalogue/tasks.js) in a dialog, of the dataset's tasks at the recipe's + // version, or of the set it runs; each tick goes into the recipe at once. Closed with none ticked: all of it. + function pickTasks(id) { + const rec = r(), b = C.standardBench(rec), x = b && b.datasets.find(d => d.id === id), dialog = document.getElementById('nb-tasks'); + if (!x || !dialog || !globalThis.nulliusTasks) return; + const u = unitsOf(rec), plan = ((rec.task_sets || {})[id] || '').split('@')[0], set = plan && (x.sets || []).find(s => s.name === plan); + const page = document.getElementById('nb-tasks-list').content.firstElementChild.cloneNode(true); + const base = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(id)}`; + Object.assign(page.dataset, {listing: base + '/listing', prepare: base + '/prepare', rows: base + '/rows', csrf: schema.csrf || '', + local: schema.local ? 'true' : 'false', nouns: u.nouns, version: b.version || '', within: set ? set.name : '', + limit: rec.limit || '', options: JSON.stringify({...(rec.model_choice === 'leaderboard' ? (b.leaderboard || {}).bench_options : {}), ...rec.bench_options})}); + document.getElementById('nb-tasks-body').replaceChildren(page); + document.getElementById('nb-tasks-title').textContent = 'Start with: ' + (set ? set.label : x.label); + const was = (rec.start_with || {})[id]; + globalThis.nulliusTasks(page, {chosen: Array.isArray(was) ? was : [], onChange: ids => { C.setStartWith(r(), id, ids); }}); + if (!Array.isArray(was)) C.setStartWith(rec, id, []); + const close = () => { + const now = (r().start_with || {})[id]; + if (Array.isArray(now) && !now.length) C.setStartWith(r(), id, ''); + dialog.close(); renderForm(); refreshPlan(); + }; + document.getElementById('nb-tasks-done').onclick = close; + document.getElementById('nb-tasks-close').onclick = close; + dialog.oncancel = e => { e.preventDefault(); close(); }; + dialog.showModal(); + } + // the tasks ticked that the plan no longer holds (a lower number, another option): unticked, said once + function dropStartTasks(rec, errors) { + let changed = false; + for (const e of errors || []) { + const chosen = (rec.start_with || {})[e.dataset]; + if (!e.dropped || !Array.isArray(chosen)) continue; + const gone = chosen.filter(id => e.dropped.includes(id)), u = unitsOf(rec); + if (!gone.length) continue; + C.setStartWith(rec, e.dataset, chosen.filter(id => !e.dropped.includes(id))); + window.nulliusNotify?.(`Unticked ${gone.length} ${gone.length === 1 ? u.noun : u.nouns} no longer in the plan: ${gone.join(', ')}.`); + changed = true; + } + return changed; + } function standardForm(rec) { const st = C.standard(), b = C.standardBench(rec); if (!b) return note('Choose a benchmark first', button('Benchmark step', `data-step="${S.benchmark}"`, 'nb-inlinebutton')); const u = unitsOf(rec); - if (step === S.dataset) + if (step === S.dataset) { + // a benchmark whose lists name the one they are cut from: one dataset each list cut from none, its cuts drawn + // under Which tasks? as its own task sets (familyChoice); the recipe still names the list a run runs + const nested = C.nestedDatasets(b), chosen = C.datasetsOf(rec); + const shown = nested ? b.datasets.filter(x => !x.subset_of) : b.datasets; + const on = x => nested ? chosen.some(id => C.wholeOf(b, id) === x.id) : chosen.includes(x.id); return `

Which datasets?

` - + `
${b.datasets.map(x => tile({attr: 'std-dataset', key: x.id, on: C.datasetsOf(rec).includes(x.id), title: x.label, - tip: x.summary || '', meta: x.units ? x.units + ' ' + u.nouns : '', - foot: (x.controls || []).map(c => controlChip(c)).join('') + checkChip('stable', (x.proofs || {}).units, (x.failed || {}).units, 'the same ids twice, each unique') - + ((b.controls || []).some(c => c.key === 'oracle') ? checkChip('no leak', (x.proofs || {}).leak, (x.failed || {}).leak, 'nothing of the reference shows before the run') : '')})).join('')}
` - + benchOptions(rec, b, 'dataset') + credentialWarnings(b, b.datasets.filter(x => C.datasetsOf(rec).includes(x.id))); + + `
${shown.map(x => tile({attr: 'std-dataset', key: x.id, on: on(x), title: x.label, + tip: x.summary || '', meta: x.units ? x.units + ' ' + u.nouns : '', foot: datasetChecks(b, x)})).join('')}
` + + b.datasets.filter(x => chosen.includes(x.id)).map(x => (nested ? familyChoice(rec, b, x, u) : taskSetChoice(rec, b, x, u)) + startChoice(rec, b, x, u)).join('') + + benchOptions(rec, b, 'dataset') + credentialWarnings(b, b.datasets.filter(x => chosen.includes(x.id))); + } if (step === S.agent) { const agent = b.family === 'agent', all = C.standardOthers(rec), others = all.filter(o => !o.control && (!o.setup || o.own)); const setups = all.filter(o => o.setup && !o.own), controls = all.filter(o => o.control); @@ -791,9 +895,12 @@ if (step === S.limits) { const sets = b.datasets.filter(x => C.datasetsOf(rec).includes(x.id)), per = sets.length > 1 ? ' of each dataset' : ''; // empty is the default, shown as the placeholder: every unit, one at a time, one attempt - const ds = sets.length === 1 ? sets[0] : null, all = ds && ds.units ? String(ds.units) : 'all'; + const ds = sets.length === 1 ? sets[0] : null, mine = ds && (ds.sets || []).find(s => s.name === ((rec.task_sets || {})[ds.id] || '').split('@')[0]); + const all = mine ? String(mine.units) : ds && ds.units ? String(ds.units) : 'all', most = /^\d+$/.test(all) ? all : ''; + // the field takes that many at most: more would be all of them return '

Scope

' - + field('Number of ' + u.nouns, 'limit', rec.limit, {type: 'number', min: 1, placeholder: all, hint: 'The first ones' + per + ', in its order.'}) + + field('Number of ' + u.nouns, 'limit', rec.limit, {type: 'number', min: 1, max: most, placeholder: all, + hint: 'Empty: all' + (most ? ' ' + most : '') + per + '. Else the first ones, in order.'}) + field('Concurrent ' + u.nouns, 'concurrency', rec.concurrency, {type: 'number', min: 1, max: 32, placeholder: rec.backend === 'boat' ? String((schema.standardHere || {}).boatSlots || 'Boat\'s limit') : '1'}) + '
' + '
' + field('Attempts per ' + u.noun, 'repeat', rec.repeat || '', {type: 'number', min: 1, max: 32, placeholder: '1', hint: 'Each ' + esc(u.noun) + ' is run and scored this many times.'}) @@ -873,6 +980,10 @@ const rec = r(), key = JSON.stringify(rec); if (key === runnerKey) return; runnerKey = key; + if (Object.values(rec.start_with || {}).some(Array.isArray)) { + runnerOut = {errors: [{step: S.dataset, message: 'Checking the tasks ticked.'}], notes: [], review: []}; + if (step === REVIEW) renderForm(); + } clearTimeout(runnerTimer); runnerTimer = setTimeout(async () => { let out; @@ -884,11 +995,14 @@ runnerServed = accepted.served; if (step === S.model) syncServed(); if (!accepted.current) return; + const dropped = dropStartTasks(r(), out.errors); runnerOut = out; runnerOutKey = key; - if (step === REVIEW) renderForm(); + if (step === REVIEW || dropped && step === S.dataset) renderForm(); refreshPlan(); }, 120); } + // the number of units a run takes, as typed: a number past the most the field takes is that most + const atMost = (el, value) => el.max !== '' && value !== '' && Number(value) > Number(el.max) ? Number(el.max) : value; const field = (label,key,value,{type='text',hint='',list='',min='',max='',placeholder='',declared=false}={}) => ``; const select = (label,key,value,options) => ``; const fixed = (label,value,whose='official') => ``; @@ -1088,7 +1202,7 @@ if(blocked)return `
${button('▶ Run on '+esc(where),'id="nb-run" disabled data-held title="'+esc(blocked)+'"','nb-button nb-primary')}

${esc(blocked)} ${button('Model step','data-step="'+S.model+'"','nb-inlinebutton')} · ${button('Settings','data-href="/settings#'+C.needsOf(C.choiceOf(rec))+'"','nb-inlinebutton')}

`; if(C.isStandard(rec)){ const out=runnerOut||{errors:[{message:'Compiling the recipe…'}]}, noun=C.isStandard(rec)?unitsOf(rec).noun:'item'; - return `
${(out.errors||[]).length?(runnerOut?[]:out.errors).map(e=>`

${esc(e.message)}

`).join(''):`
${button('▶ Run on '+esc(where),'id="nb-run"','nb-button nb-primary')}
`+(out.confirm?`

No ${esc(noun)} limit: ${esc(out.confirm.replace(/^Run /,'').replace(/\?$/,''))}. Run asks before it starts.

`:'')}
`; + return `
${(out.errors||[]).length?(runnerOut?[]:out.errors).map(e=>`

${esc(e.message)}

`).join(''):`
${button('▶ Run on '+esc(where),'id="nb-run"','nb-button nb-primary')}
`+(out.confirm?`

${/^Run /.test(out.confirm)?`No ${esc(noun)} limit: `+esc(out.confirm.replace(/^Run /,'').replace(/\?$/,'')):esc(out.confirm.replace(/\?$/,''))}. Run asks before it starts.

`:'')}
`; } const plan=C.runnable(rec), listed=C.compile(rec).errors.map(e=>e.message); // the red box's, not said twice return `
${plan.errors.length?plan.errors.filter(e=>!listed.includes(e)).map(e=>`

${esc(e)}

`).join(''):`
${button('▶ Run on '+esc(where),'id="nb-run"'+(C.validate(rec).errors.length?' disabled data-held':''),'nb-button nb-primary')}
`+(plan.confirm?`

No task limit: ${esc(plan.confirm.replace(/^Run /,'').replace(/\?$/,''))}. Run asks before it starts.

`:'')}
`; @@ -1178,7 +1292,12 @@ else if(d.runner){toRunner(d.runner,C.benchKey(r()));} else if(d.stdBench){C.setStandardBenchmark(r(),d.stdBench);} else if(d.stdOther){const rec=r(),c=C.chosenOf(rec);rec.others=c.includes(d.stdOther)?c.filter(k=>k!==d.stdOther):[...c,d.stdOther];delete rec.other;if(rec.options)delete rec.options[d.stdOther];} // a check - else if(d.stdDataset){const rec=r(),c=C.datasetsOf(rec);rec.datasets=c.includes(d.stdDataset)?(c.length>1?c.filter(k=>k!==d.stdDataset):c):[...c,d.stdDataset];delete rec.dataset;} + else if(d.stdDataset){const rec=r(),c=C.datasetsOf(rec),b=C.standardBench(rec),mine=c.filter(k=>C.wholeOf(b,k)===d.stdDataset);rec.datasets=mine.length?(c.length>mine.length?c.filter(k=>!mine.includes(k)):c):[...c,d.stdDataset];delete rec.dataset;C.keepTaskSets(rec);C.keepStartWith(rec);} + else if(d.stdFamily!==undefined){C.swapDataset(r(),d.was,d.stdFamily);} + else if(d.stdFamilySet!==undefined){C.swapDataset(r(),d.was,d.in);C.setTaskSet(r(),d.in,d.stdFamilySet);} + else if(d.stdTaskset!==undefined){C.setTaskSet(r(),d.of,d.stdTaskset);} + else if(d.stdStart!==undefined){C.setStartWith(r(),d.of,d.stdStart);} + else if(d.stdStartPick!==undefined){pickTasks(d.stdStartPick);return;} // the standard's machines: each a toggle, one at least; several split the run into shards else if(d.stdWhere){const rec=r(),list=C.whereList(rec),on=list.includes(d.stdWhere),next=on?list.filter(w=>w!==d.stdWhere):[...list,d.stdWhere];if(!next.length)return;rec.where=next.length>1?next:next[0];} // hosts or Boat sandboxes: a sandbox run starts from this machine alone @@ -1228,7 +1347,7 @@ if(d.stdUnsandboxed!==undefined)return; // a box's value is no tick: its change sets the recipe if(d.providerModel){d.typing='true';syncServed();localErrors();return;} // what is typed in a model field filters its list: a pick, Enter or leaving the field sets it if(d.field){const p=d.field.startsWith('param:')?C.parameters().find(p=>p.key===d.field.slice(6)):null; - const value=el.type==='number'?(el.value===''?'':Number(el.value)):el.value; + const typed=el.type==='number'?(el.value===''?'':Number(el.value)):el.value,value=d.field==='limit'?atMost(el,typed):typed; if(p)rec.params[p.key]=p.type==='optional-boolean'?(value==='__default__'?null:value==='true'):value; else if(d.field==='timeoutMultiplier'){rec.timeoutMultiplier=value;rec.agentMinutes='';} else if(d.field.startsWith('adapterPath:')){const id=d.field.slice(12);if(String(value).trim())rec.adapterPaths[id]=String(value).trim();else delete rec.adapterPaths[id];} @@ -1253,6 +1372,7 @@ const el=event.target; if(el.dataset.providerModel)commitModel(el); // a change undone by hand since the focus fires no change event if(el.type==='number'&&(el.dataset.field||el.dataset.stdMinutes||el.dataset.benchOptSelect)&&el.validity&&el.validity.badInput){el.value='';window.nulliusNotify?.(`${el.getAttribute('aria-label')}: enter a number.`,{error:true,key:'bad-number'});} + else if(el.dataset.field==='limit'&&el.value!==''&&atMost(el,Number(el.value))!==Number(el.value)){el.value=el.max;window.nulliusNotify?.(`${el.getAttribute('aria-label')}: at most ${el.max}, all of them.`,{key:'at-most'});} }); // a provider picked in a Served by, or slugs typed there and Enter: they join its list, after the ones there root.addEventListener('nb-pick',event=>{const role=event.target.dataset.servedBy;if(!role)return;C.addServed(r(),role,event.detail);syncServed();refreshPlan();}); @@ -1263,6 +1383,7 @@ else if(d.stdUnsandboxed!==undefined){r().unsandboxed=el.checked;refreshPlan();} else if(d.stdVersion!==undefined){ // in place: only the card's count changes on this step, so nothing else is drawn again C.setStandardBenchmark(r(),el.value);benchTasks();render(false,false);} + else if(d.stdTasksetSelect!==undefined){C.setTaskSet(r(),d.stdTasksetSelect,el.value);renderForm();refreshPlan();} // an option at its default is left out: the recipe names only what was changed. A select's value can show or hide // the options that apply under it (`when`): the step is drawn again and the focus goes back to the select, or to the // menu button controls.js puts after it once this change is handled; a typed value is left as it is diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 4087a55b..4a8a88d4 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -428,3 +428,77 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .bench-main > .bench-section > h2, .bench-main > .bench-cols > .bench-section > h2 { margin-bottom: 18px; } .std-option-range { margin-top: 12px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: var(--text-dim); font-size: 14px; } @media (max-width: 640px) { .bench-main > .bench-section, .bench-main > .bench-cols > .bench-section { padding: 16px; } } + +/* A benchmark's task sets, and a dataset's tasks: browsed, ticked and kept as a set (catalogue/tasks.html). */ +.bench-sets td, .bench-sets th { vertical-align: top; } +.bench-sets small { display: block; } +.bench-setlinks { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; } +.bench-sets-group { margin: 14px 0 0; } +.bench-ownsets { margin-top: 8px; } +.bench-newset { position: relative; } +.bench-newset > summary { list-style: none; } +.bench-newset > summary::-webkit-details-marker { display: none; } +.bench-newset-menu { left: auto; right: 0; max-width: calc(100vw - 32px); } +.tasks-page { display: flex; flex-direction: column; gap: 20px; } +.tasks-page .bench-blocked { margin: 0; } +.tasks-page .tasks-warn { border-color: color-mix(in srgb, var(--patch_failed_tests) 45%, var(--border)); } +.tasks-note { overflow-wrap: anywhere; } +.tasks-browse { padding: 22px; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); min-width: 0; } +.tasks-bar { display: flex; flex-direction: column; gap: 14px; } +.tasks-find { flex: none; max-width: 520px; } +.tasks-cats { display: flex; flex-direction: column; gap: 10px; } +.tasks-cats .filter-pills { align-items: center; } +.tasks-catname { min-width: 64px; } +.tasks-cats .filter-pill { min-height: 34px; padding: 6px 12px; } +.tasks-n { color: var(--text-faint); } +.filter-pill[aria-pressed="true"] .tasks-n { color: inherit; opacity: .8; } +.tasks-sel { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border-soft); } +.tasks-sel b { margin-right: 6px; } +.tasks-paste { position: relative; } +.tasks-paste > summary { list-style: none; } +.tasks-paste > summary::-webkit-details-marker { display: none; } +.tasks-paste-box { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; margin-top: 8px; width: min(420px, calc(100vw - 64px)); } +.tasks-paste-box textarea { width: 100%; box-sizing: border-box; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; } +.tasks-count { margin: 14px 0 6px; } +.tasks-scroll { overflow-x: auto; } +.tasks-table th, .tasks-table td { padding: .6rem .7rem; } +.tasks-table td:nth-child(2) { overflow-wrap: anywhere; } +.tasks-table td.tasks-text { width: 100%; max-width: 0; } +.tasks-row { display: flex; align-items: baseline; gap: 10px; width: 100%; min-width: 0; } +.tasks-row .tasks-title { flex: 1 1 auto; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.tasks-row .tasks-whole { display: none; flex: 1 1 100%; white-space: pre-wrap; line-height: 1.45; } +.tasks-table .tasks-id { display: none; flex: none; margin: 0; } +.tasks-table tr:hover .tasks-id, .tasks-table tr:focus-within .tasks-id { display: inline; } +/* the row's tooltip shows on hover alone: while its box, or its text where the box is disabled, has the keyboard's + focus, the whole text is in place */ +.tasks-table tr:has(:focus-visible) .tasks-row { flex-wrap: wrap; } +.tasks-table tr:has(:focus-visible) .tasks-title { display: none; } +.tasks-table tr:has(:focus-visible) .tasks-whole { display: block; } +.tasks-tick { width: 1%; } +.tasks-tick input { width: 18px; height: 18px; margin: 0; } +.tasks-title { display: block; line-height: 1.45; } +.tasks-table tr[data-id]:has(input:enabled) { cursor: pointer; } +.tasks-table small { display: block; margin-top: 2px; } +.tasks-tags { display: none; } +.tasks-pages { display: flex; align-items: center; gap: 12px; margin-top: 14px; } +.tasks-savebar { position: sticky; bottom: 12px; z-index: 2; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin-top: 14px; padding: 10px 16px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface-2); box-shadow: var(--shadow); } +.tasks-savebar.tasks-gone { visibility: hidden; } +.tasks-save { padding: 22px; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); } +.tasks-form { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 12px; } +.tasks-form + .tasks-form { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border-soft); } +.tasks-field { display: flex; flex-direction: column; gap: 6px; flex: 0 1 240px; } +.tasks-field.tasks-wide { flex: 1 1 320px; } +.tasks-paste-box textarea:focus { outline: none; border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } +.tasks-msg { margin: 12px 0 0; min-height: 1.2em; } +.tasks-msg.bad { color: var(--bad); } +#task-sets { scroll-margin-top: calc(var(--topbar-height) + 24px); } +.tasks-rename[open] summary { border-color: var(--accent); } +.tasks-rename .bench-delete-ask { border-color: var(--border); } +.tasks-rename .tasks-field { flex: 1 1 100%; } +@media (max-width: 640px) { + .tasks-browse, .tasks-save { padding: 16px; } .tasks-field, .tasks-field.tasks-wide { flex: 1 1 100%; } .tasks-catname { min-width: 0; width: 100%; } + .tasks-table th:nth-child(3), .tasks-table td.tasks-catcol { display: none; } + .tasks-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; } + .tasks-table th, .tasks-table td { padding: .55rem .4rem; } + .tasks-page .bench-delete-ask { left: 0; right: auto; } +} diff --git a/app/static/catalogue/tasks.js b/app/static/catalogue/tasks.js new file mode 100644 index 00000000..04a1dee7 --- /dev/null +++ b/app/static/catalogue/tasks.js @@ -0,0 +1,203 @@ +// A dataset's tasks (templates/catalogue/tasks.html): the server gives a page of 100 tasks for a search and category +// values (web/catalogue.py, standard/runner/units.py); this page keeps the chosen ids alone. The listing is asked for once the +// page has loaded: in the cache, it shows at once; one that can be made lightly is started out of the request and +// the page asks again until it is ready; one that needs the benchmark's full environment is never started here. +// The run builder mounts the same list in a dialog (nulliusTasks, data-manual): the tasks of a dataset or of one of +// its sets (data-within), its ticks given back through onChange. +(() => { +function mount(page, opts = {}) { + const $ = id => page.querySelector('#' + id), d = page.dataset, nouns = d.nouns || 'tasks'; + const writable = d.writable === 'true'; + const chosen = new Set(opts.chosen || JSON.parse(($('tasks-chosen-ids') || {}).textContent || '[]')); + const changed = () => opts.onChange && opts.onChange([...chosen]); + // opened from a set: its members first; Show all browses the dataset + const st = {q: '', cats: {}, page: 1, showing: !!d.set && chosen.size > 0, ready: false, total: 0, pages: 1}; + const label = field => field.charAt(0).toUpperCase() + field.slice(1).replace(/_/g, ' '); + const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c])); + // the listing at the version the page shows (data-version, empty for the benchmark's default) + const at = url => { + const params = new URLSearchParams(); + if (d.version) params.set('version', d.version); + if (d.options) params.set('options', d.options); + return String(params) ? url + (url.includes('?') ? '&' : '?') + params : url; + }; + const post = (url, body) => nulliusFetch(at(url), {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': d.csrf}, body: JSON.stringify(body)}); + const count = n => `${n.toLocaleString('en-US')} ${n === 1 ? nouns.replace(/s$/, '') : nouns}`; + + function say(text, warn) { + if (page.isConnected === false) return; + const el = $('tasks-state'); el.hidden = !text; el.textContent = text || ''; el.classList.toggle('tasks-warn', !!warn); + } + function chosenLine() { + $('tasks-chosen').textContent = `${chosen.size.toLocaleString('en-US')} chosen`; + if ($('tasks-bar-chosen')) $('tasks-bar-chosen').textContent = $('tasks-chosen').textContent; + $('tasks-show').disabled = !chosen.size && !st.showing; + } + // a task on one line: its title cut to the width, the whole text in the row's tooltip and, while its box (its text + // where the box is disabled) has the keyboard's focus, in place; its id beside it on hover or focus. A click + // anywhere on the row ticks it. + function row(t) { + const tags = Object.values(t.categories || {}).map(v => `${esc(v)}`).join(' '); + const whole = t.text || t.title || t.id; + return `` + + `${esc(t.title || t.id)}` + + `${esc(whole)}${t.title ? `${esc(t.id)}` : ''}` + + `${t.unknown ? 'not in the listing' : ''}` + + (tags ? `${tags}` : '') + `${tags}`; + } + function draw(tasks) { + $('tasks-rows').innerHTML = tasks.map(row).join(''); + $('tasks-table').hidden = !tasks.length; + const fields = [...new Set(tasks.flatMap(t => Object.keys(t.categories || {})))]; + $('tasks-cat-head').hidden = !fields.length; + $('tasks-cat-head').textContent = fields.map(label).join(' · '); + page.querySelectorAll('#tasks-rows td.tasks-catcol').forEach(td => { td.hidden = !fields.length; }); + } + function facets(cats) { + $('tasks-cats').innerHTML = Object.entries(cats || {}).map(([field, values]) => + `
${esc(label(field))}` + + values.map(v => ``).join('') + + '
').join(''); + } + function pager() { + const nav = $('tasks-pages'); + nav.hidden = st.showing || st.pages <= 1; + $('tasks-page-of').textContent = `Page ${st.page} of ${st.pages}`; + nav.querySelector('[data-page=prev]').disabled = st.page <= 1; + nav.querySelector('[data-page=next]').disabled = st.page >= st.pages; + } + function query(extra) { + const u = new URLSearchParams(); + if (st.q) u.set('q', st.q); + Object.entries(st.cats).forEach(([f, vs]) => vs.forEach(v => u.append('cat', `${f}=${v}`))); + Object.entries(extra || {}).forEach(([k, v]) => u.set(k, v)); + if (d.version) u.set('version', d.version); + if (d.within) u.set('within', d.within); + if (d.options) u.set('options', d.options); + if (d.limit) u.set('limit', d.limit); + return d.listing + '?' + u; + } + let polling = null, asked = 0; + // not in the cache: the server's line for its state; a light listing started once, out of any request, then asked + // again every few seconds until it is ready + function notReady(got) { + if ($('tasks-match')) $('tasks-match').hidden = true; + const light = got.state === 'light' && !got.error; + say(got.say, !light); + if (!light) return; + clearTimeout(polling); + if (!got.preparing && d.local !== 'true') return say('The list is prepared from a browser on the application host. Ids can still be pasted.', true); + if (!got.preparing && !asked++) + return post(d.prepare, {}).then(r => r.json()).then(g => { + if (page.isConnected === false) return; + say(g.say || got.say); polling = setTimeout(load, 2500); + }) + .catch(() => say('The list could not be started. Reload the page.', true)); + polling = setTimeout(load, 2500); + } + async function load() { + if (page.isConnected === false) return; // a list the builder's dialog has since replaced asks nothing more + let got; + try { got = await (await nulliusFetch(query({page: st.page}))).json(); } catch { return say('The list could not be read. Reload the page.', true); } + if (page.isConnected === false) return; + if (!got.ok) return say(got.error || 'The list could not be read.', true); + if (!got.ready) { $('tasks-count').textContent = ''; draw([...chosen].map(id => ({id}))); pager(); chosenLine(); return notReady(got); } + say(''); + st.ready = true; st.total = got.total; st.pages = got.pages; st.page = got.page; + facets(got.categories); + const m = $('tasks-match'); + if (m) { m.hidden = !writable || !got.total || st.showing; m.textContent = `Select the ${got.total.toLocaleString('en-US')} that match`; } + if (st.showing) return showSelected(); + draw(got.tasks); + $('tasks-count').textContent = `${count(got.total)}` + (got.total !== got.of ? ` of ${got.of.toLocaleString('en-US')}` : '') + + (got.described ? '' : ' · its driver gives ids alone'); + pager(); chosenLine(); + } + async function showSelected() { + const ids = [...chosen]; + let got = {tasks: ids.map(id => ({id})), unknown: []}; + try { got = await (await post(d.rows, {units: ids})).json(); } catch { /* the ids alone */ } + if (page.isConnected === false) return; + const unknown = new Set(got.unknown || []); + draw([...got.tasks, ...[...unknown].map(id => ({id, unknown: true}))]); + $('tasks-count').textContent = `${count(ids.length)} chosen` + (unknown.size ? ` · ${unknown.size} not in the listing` : ''); + pager(); chosenLine(); + } + + function setShowing(showing) { + st.showing = showing; + $('tasks-show').setAttribute('aria-pressed', String(showing)); + $('tasks-show').textContent = showing ? 'Show all' : 'Show selected'; + } + let typing = null; + $('tasks-q').addEventListener('input', e => { clearTimeout(typing); typing = setTimeout(() => { st.q = e.target.value.trim(); setShowing(false); st.page = 1; load(); }, 250); }); + $('tasks-cats').addEventListener('click', e => { + const b = e.target.closest('[data-field]'); if (!b) return; + const f = b.dataset.field, v = b.dataset.value, vs = st.cats[f] || []; + st.cats[f] = vs.includes(v) ? vs.filter(x => x !== v) : [...vs, v]; + if (!st.cats[f].length) delete st.cats[f]; + setShowing(false); st.page = 1; load(); + }); + // a click anywhere on a row ticks it, as its box would; the box, a link or a button keeps its own action, and a + // drag that selects words is no click + $('tasks-rows').addEventListener('click', e => { + if (e.target.closest('input, a, button') || String(globalThis.getSelection?.() || '')) return; + e.target.closest('tr[data-id]')?.querySelector('input[type=checkbox]')?.click(); + }); + $('tasks-rows').addEventListener('change', e => { + const box = e.target.closest('input[type=checkbox]'); if (!box) return; + const id = box.closest('tr').dataset.id; + box.checked ? chosen.add(id) : chosen.delete(id); chosenLine(); changed(); + }); + $('tasks-pages').addEventListener('click', e => { + const b = e.target.closest('[data-page]'); if (!b) return; + st.page += b.dataset.page === 'next' ? 1 : -1; load(); + }); + $('tasks-show').addEventListener('click', () => { + setShowing(!st.showing); load(); + }); + $('tasks-match')?.addEventListener('click', async () => { + const got = await (await nulliusFetch(query({ids: 1}))).json(); + if (page.isConnected === false) return; + if (got.ok && got.ready) { got.ids.forEach(id => chosen.add(id)); changed(); load(); } + }); + $('tasks-clear')?.addEventListener('click', () => { chosen.clear(); changed(); load(); }); + $('tasks-paste-add')?.addEventListener('click', async () => { + const ids = [...new Set($('tasks-paste').value.split(/[\s,]+/).map(s => s.trim()).filter(s => s && !s.startsWith('#')))]; + ids.forEach(id => chosen.add(id)); changed(); + $('tasks-paste').value = ''; $('tasks-paste').closest('details').open = false; + window.nulliusNotify?.(`${count(ids.length)} added.`); + load(); + }); + + const msg = (text, bad) => { const el = $('tasks-msg'); if (el && page.isConnected !== false) { el.textContent = text; el.classList.toggle('bad', !!bad); } }; + async function save(body) { + if (!chosen.size) return msg('Tick at least one task.', true); + let got; + try { got = await (await post(d.save, {...body, units: [...chosen]})).json(); } catch { return msg('Not saved: the server did not answer.', true); } + if (page.isConnected === false) return; + if (!got.ok) return msg(got.error, true); + location.href = got.open; + } + $('tasks-create')?.addEventListener('submit', e => { + e.preventDefault(); const f = e.target; + save({name: f.elements.namedItem('name').value.trim(), description: f.elements.namedItem('description').value.trim(), + ...(d.version ? {version: d.version} : {})}); + }); + // the count and the way to save stay in view under the rows; the bar steps aside once the form is in view + const bar = $('tasks-savebar'), form = page.querySelector('.tasks-save'); + if (bar && form && 'IntersectionObserver' in window) + new IntersectionObserver(([e]) => bar.classList.toggle('tasks-gone', e.isIntersecting)).observe(form); + $('tasks-to-save')?.addEventListener('click', e => { + const field = form?.querySelector('input'); if (!field) return; + e.preventDefault(); form.scrollIntoView({block: 'nearest'}); field.focus({preventScroll: true}); + }); + setShowing(st.showing); + chosenLine(); + load(); + return {chosen}; +} +globalThis.nulliusTasks = mount; +const page = document.getElementById('tasks-page'); +if (page && !page.dataset.manual) mount(page, {chosen: JSON.parse(document.getElementById('tasks-chosen-ids')?.textContent || '[]')}); +})(); diff --git a/app/static/runs/board.css b/app/static/runs/board.css index de763873..2d92885d 100644 --- a/app/static/runs/board.css +++ b/app/static/runs/board.css @@ -212,6 +212,7 @@ .rp .kv .k { font-size: 12.5px; color: var(--text-faint); } .rp .kv .v { font: 500 15px/1 var(--sans); color: var(--text); } .rp .b-tot .sp { margin-left: -16px; } +.rp .b-tot .cap-spent { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } .rp .pop { position: relative; } .rp .pop > summary { display: inline-flex; align-items: center; min-height: 24px; font: 12px var(--sans); color: var(--text-dim); white-space: nowrap; } .rp .pop > summary:hover, .rp .pop[open] > summary { color: var(--text); } @@ -349,6 +350,35 @@ .rp .nfh { display: inline; } } +/* tasks run again: the ticks, the choice at the bar's end, the question (the Delete dialog's frame), the record */ +.rp .pick, .rp .pick-why { margin-left: auto; } +.rp .pick { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.rp .pick-n { white-space: nowrap; } +.rp .pick-row { float: left; margin: 4px 8px 0 0; accent-color: var(--accent); } +.rp .pick-row + .task { display: block; overflow: hidden; } /* a name that wraps stays beside its tick */ +.rp .tt:has(.pick-row) td:first-child { min-width: 172px; } /* the tick's room, beside the name's */ +/* a task with no result: a hollow mark, no outcome's colour */ +.rp .oc-no_result { --oc: transparent; } +.rp .sw.oc-no_result, .rp .odot.oc-no_result { box-shadow: inset 0 0 0 1.5px var(--text-faint); } +/* a task of the plan not run yet: a dashed mark, no outcome's colour */ +.rp .oc-not_run { --oc: transparent; } +.rp .sw.oc-not_run, .rp .odot.oc-not_run { outline: 1.5px dashed var(--text-faint); outline-offset: -1.5px; } +/* the sets that name tasks not run: one line each, its tasks not run at its end */ +.rp .popm.plan-sets-menu { left: auto; right: 0; grid-template-columns: auto; } +.rp .popm .plan-set { display: flex; justify-content: space-between; gap: 14px; padding: 4px 2px; color: var(--text); text-align: left; } +.rp .popm .plan-set:hover { color: var(--accent); } +.rp .tt .again-now { color: var(--text-dim); } +dialog.std-how.rerun-ask { width: min(520px, calc(100vw - 32px)); } +.rerun-ask p { margin: 6px 0 0; } +.rerun-ask p[data-error] { color: var(--bad); } +.rerun-ask .rerun-names { max-height: 9.6em; overflow: auto; margin: 10px 0 0; padding-left: 1.2em; overflow-wrap: anywhere; } +.rerun-ask label { display: block; margin-top: 14px; } +.rerun-ask input { display: block; width: 100%; margin-top: 4px; } +.rerun-acts { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; margin-top: 20px; } +.rp dl.reruns dd p { margin: 0 0 4px; color: var(--text); } +.rp .rerun-rows { margin: 0 0 4px; padding: 0; list-style: none; overflow-wrap: anywhere; } +.rp .rerun-unit { margin-right: 6px; } + .rp .more { margin-top: 14px; display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } .rp .more > details { background: var(--surface); border: 1px solid var(--hair); border-radius: var(--radius); padding: 7px 16px; } .rp .more > details > summary { display: flex; align-items: center; gap: 10px; font-size: 13px; color: var(--text-dim); min-height: 26px; } diff --git a/app/static/runs/board.js b/app/static/runs/board.js index 2872b5c3..2818c48d 100644 --- a/app/static/runs/board.js +++ b/app/static/runs/board.js @@ -160,7 +160,73 @@ document.addEventListener('focusout', hide); addEventListener('scroll', hide, { passive: true }); + // ---- tasks to run again: a tick per trial, the rows the filters show at once, the count, then the question ---- + // a task with no result (data-first, "none" when its run ended with none) is run, not run again: the words say which + const ticks = $$('#trial-rows .pick-row'), ask = $('#rerun-ask'); + if (ticks.length && ask) { + const pickN = $('#pick-count'), go = $('#rerun-open'), form = $('form', ask), err = $('[data-error]', ask); + const chosen = () => ticks.filter(x => x.checked), first = x => 'first' in x.dataset; + const tasks = n => n + (n === 1 ? ' task' : ' tasks'); + const where = $('p.muted', ask), again = where.textContent; + const recount = () => { const c = chosen(), n = c.length; pickN.textContent = n + ' chosen'; go.disabled = !n; + go.textContent = n && c.every(first) ? 'Run selected' : 'Run selected again'; }; + ticks.forEach(x => x.addEventListener('change', recount)); + $('#pick-shown').addEventListener('click', () => { rows.forEach(r => { const x = $('.pick-row', r); if (x && r.matched) x.checked = true; }); recount(); }); + // the rest, or a set's tasks not yet run: those rows ticked alone, then the same question + $$('#rerun-pick [data-pick]').forEach(b => b.addEventListener('click', () => { + const want = new Set(b.dataset.pick.split(' ')); ticks.forEach(x => { x.checked = want.has(x.value); }); + const menu = b.closest('details'); if (menu) menu.open = false; + recount(); go.click(); + })); + go.addEventListener('click', () => { + // tasks with no result alone: one short question, no names and no reason; else the names, and a reason asked + const picked = chosen(), fresh = picked.filter(first).length, short = picked.length > 0 && fresh === picked.length; + const words = short ? `Run the ${tasks(picked.length)} ${picked.some(x => x.dataset.first === 'none') ? 'with no result' : 'not yet run'}, on ${ask.dataset.where}?` + : 'Run ' + tasks(picked.length) + (!fresh ? ' again' : fresh < picked.length ? ', ' + (picked.length - fresh) + ' again' : ''); + $('#rerun-ask-h').textContent = words; + $('[data-go]', ask).textContent = short ? 'Run' : words; + where.textContent = fresh && where.dataset.first ? where.dataset.first : again; + const names = $('[data-names]', ask), reason = $('[data-reason]', ask); + where.hidden = names.hidden = reason.hidden = short; + if (short) form.elements.reason.value = ''; + names.replaceChildren(...(short ? [] : picked).map(x => { const li = document.createElement('li'); li.textContent = x.getAttribute('aria-label').replace(/^Choose /, ''); return li; })); + err.hidden = true; $('[data-go]', ask).disabled = 'spent' in $('[data-go]', ask).dataset; ask.showModal(); + }); + form.addEventListener('submit', async e => { + if (!e.submitter || e.submitter.value !== 'run') return; + e.preventDefault(); + const b = e.submitter; b.disabled = true; err.hidden = true; + try { + const r = await nulliusFetch(ask.dataset.post, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': ask.dataset.csrf }, + body: JSON.stringify({ trials: chosen().flatMap(x => (x.dataset.trials || x.value).split(' ')), reason: form.elements.reason.value }) }); + const j = await r.json().catch(() => ({})); + if (r.ok && j.ok) { const u = new URL(location.href); u.searchParams.delete('view'); location.assign(u); return; } + throw new Error(j.error || 'refused: HTTP ' + r.status); + } catch (x) { err.textContent = String(x.message || x); err.hidden = false; b.disabled = false; } + }); + recount(); + } + apply(); + + // ---- the job's one spending cap: Change asks for the cap from the next part on ---- + const capAsk = $('#cap-ask'), capOpen = $('#cap-change'); + if (capAsk && capOpen) { + const capForm = $('form', capAsk), capErr = $('[data-error]', capAsk); + capOpen.addEventListener('click', () => { capErr.hidden = true; capAsk.showModal(); }); + capForm.addEventListener('submit', async e => { + if (!e.submitter || e.submitter.value !== 'save') return; + e.preventDefault(); + const b = e.submitter; b.disabled = true; capErr.hidden = true; + try { + const r = await nulliusFetch(capAsk.dataset.post, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': capAsk.dataset.csrf }, + body: JSON.stringify({ max_usd: capForm.elements.max_usd.value }) }); + const j = await r.json().catch(() => ({})); + if (r.ok && j.ok) { location.reload(); return; } + throw new Error(j.error || 'refused: HTTP ' + r.status); + } catch (x) { capErr.textContent = String(x.message || x); capErr.hidden = false; b.disabled = false; } + }); + } })(); // Each checkbox independently excludes one flag kind. The GET form works without JavaScript. diff --git a/app/static/runs/live-board.css b/app/static/runs/live-board.css index 58fd7f6d..46db6f9d 100644 --- a/app/static/runs/live-board.css +++ b/app/static/runs/live-board.css @@ -34,6 +34,10 @@ .lb-meta b { color: var(--text); font: 500 12.5px var(--mono); } .lb-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)) repeat(2, minmax(0, 1.2fr)); border-bottom: 1px solid var(--lb-hair); } +/* a part of the plan running: Not run beside Queued, the row one column wider */ +@media (min-width: 1001px) { + .lb-stats:has(> .lb-stat:nth-child(7)) { grid-template-columns: repeat(5, minmax(0, 1fr)) repeat(2, minmax(0, 1.2fr)); } +} .lb-stat { padding: 11px 18px 12px; border-right: 1px solid var(--lb-hair); min-width: 0; } .lb-stat:last-child { border-right: 0; } .lb-stat .k { display: block; color: var(--text-dim); font-size: 12px; white-space: nowrap; } @@ -103,6 +107,7 @@ .lb-row .task { display: inline-block; font: 500 12.5px var(--mono); width: max-content; max-width: 22rem; overflow-wrap: anywhere; vertical-align: bottom; } .lb-row small { font-size: 11.5px; color: var(--text-faint); margin-left: 6px; } .lb-phase { display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; font-size: 12.5px; } +.lb-queued .lb-phase { color: var(--text-dim); } .lb-ticks { display: inline-flex; gap: 3px; } .lb-ticks s { width: 11px; height: 4px; border-radius: 2px; background: var(--lb-track); text-decoration: none; } .lb-ticks s.done { background: var(--text-dim); } .lb-ticks s.now { background: var(--c); } diff --git a/app/static/runs/live-board.js b/app/static/runs/live-board.js index c11e726f..c42f1c2b 100644 --- a/app/static/runs/live-board.js +++ b/app/static/runs/live-board.js @@ -9,7 +9,8 @@ * * One board, top to bottom: a header line, one stats strip, the outcome bar * with its filter chips (and, for more than one agent, the lanes and a winner - * per task), every trial as a tile, one table with a row per trial in flight and, below them, each that ended, + * per task), every trial as a tile, one table with a row per trial in flight, then, while a part of a job's plan + * runs, each of its trials not yet begun (Queued) and, below them, each that ended, * and a drawer for one trial, where its phases are drawn on its own clock. * * Rules the fold already enforces are respected here rather than re-derived: @@ -55,6 +56,8 @@ return (t.n_input_tokens || 0) + (t.n_output_tokens || 0); } const pressure = t => (t.timeout_sec && t.elapsed_sec != null ? t.elapsed_sec / t.timeout_sec : 0); + // A planned trial outside the part of the plan now running (the snapshot's `part`): not run, not queued. + const outside = (s, t) => Array.isArray(s.part) && t.state === 'queued' && !s.part.includes(t.trial); // the steps of the limit where the benchmark counts them (a bar while the trial runs), else the bare count function stepsCell(t, bar) { if (t.step == null) return '—'; @@ -115,7 +118,10 @@ const pct = x => `${Math.round(100 * x)}%`; function renderStats(s, state, oc) { const C = s.counts || {}; - const queued = C.total != null ? Math.max(0, C.total - C.completed - C.running) : null; + const later = (s.trials || []).filter(t => outside(s, t)).length; + // while a part runs, its trials not begun, as its table lists them: a task run again counts as done and as running + const queued = Array.isArray(s.part) ? (s.trials || []).filter(t => t.state === 'queued' && s.part.includes(t.trial)).length + : C.total != null ? Math.max(0, C.total - C.completed - C.running - later) : null; const rate = s.elapsed_sec > 60 && C.completed ? C.completed / (s.elapsed_sec / 60) : null; const ran = C.completed - (oc.infra_error || 0) - (oc.budget || 0); const when = state === 'finished' ? 'on the feed' : 'so far'; // the feed's outcomes, not the classifier's: Results has those @@ -128,7 +134,8 @@ + stat(`Adjusted ${when}`, ran > 0 ? pct(oc.resolved / ran) : '—', 'rate', !(ran > 0)); return stat('Done', `${C.completed}/${C.total == null ? '?' : C.total}`) + stat('Running', String(C.running)) - + (C.not_run ? stat('Not run', String(C.not_run)) : stat('Queued', queued == null ? '—' : String(queued), '', queued == null)) + + (C.not_run ? stat('Not run', String(C.not_run)) : stat('Queued', queued == null ? '—' : String(queued), '', queued == null) + + (later ? stat('Not run', String(later)) : '')) + stat('Rate', rate ? `${rate.toFixed(1)}/min` : '—', '', !rate) + rates; } @@ -171,13 +178,13 @@ return `
${agents.map(a => ``).join('')}${rows}
Winner per task${esc(a)}winner

Each agent's best reward on the task so far; a winner is named once every trial of the task ended and one best is strictly higher. A tie names nobody.

`; } - function renderTiles(trials, opts, agents, ended) { + function renderTiles(trials, opts, agents, ended, s) { return trials.map(t => { const st = t.state === 'done' ? 'done' : t.state === 'running' ? 'running' : 'queued'; const cls = st === 'done' ? ` lbo-${esc(t.outcome || 'cancelled')}` : st === 'running' ? ` lbp-${esc(t.phase)}` : ''; const w = st === 'running' && t.timeout_sec ? ` style="--p:${Math.min(1, pressure(t)).toFixed(3)}"` : ''; const dim = opts.filter && t.outcome !== opts.filter ? ' dim' : ''; - const label = `${shortTask(t)}${agents.length > 1 ? ' · ' + (t.agent || '') : ''}: ${st === 'done' ? (OUTCOME_LABEL[t.outcome] || 'ended') : st === 'running' ? PHASE_LABEL[t.phase] || t.phase : ended ? 'not run' : 'queued'}`; + const label = `${shortTask(t)}${agents.length > 1 ? ' · ' + (t.agent || '') : ''}: ${st === 'done' ? (OUTCOME_LABEL[t.outcome] || 'ended') : st === 'running' ? PHASE_LABEL[t.phase] || t.phase : ended || outside(s, t) ? 'not run' : 'queued'}`; return ``; }).join(''); } @@ -199,11 +206,14 @@ } const ended = (t) => ((s.timeline || {})[t.trial] || {}).ended || ''; const done = trials.filter(t => t.state === 'done').sort((a, b) => ended(a).localeCompare(ended(b))); - if (!running.length && !done.length) return '

Nothing is running at this poll.

'; - const busy = running.length > FLIGHT_SHOWN, many = done.length > FLIGHT_SHOWN; + // the tasks of the part now running that have not begun: a row each, under the running ones + const queued = Array.isArray(s.part) ? trials.filter(t => t.state === 'queued' && s.part.includes(t.trial)) : []; + if (!running.length && !done.length && !queued.length) return '

Nothing is running at this poll.

'; + const busy = running.length > FLIGHT_SHOWN, many = done.length > FLIGHT_SHOWN, waits = queued.length > FLIGHT_SHOWN; const order = busy ? running.slice().sort((a, b) => pressure(b) - pressure(a)) : running; const rows = opts.showAll ? order : order.slice(0, FLIGHT_SHOWN); const doneRows = opts.showAll ? done : done.slice(-FLIGHT_SHOWN); + const queuedRows = opts.showAll ? queued : queued.slice(0, FLIGHT_SHOWN); // a column appears once some trial reported it; a single missing cell is "—" const has = {steps: trials.some(t => t.step != null), calls: trials.some(t => t.calls != null), tokens: trials.some(t => tokensOf(t) != null), line: trials.some(t => t.activity || t.last_line)}; const body = rows.map(t => { @@ -216,6 +226,13 @@ ${has.steps ? stepsCell(t, true) : ''}${has.calls ? callsCell(t) : ''} ${has.tokens ? `${count(tok)}` : ''} ${has.line ? `${line ? redacted(line) : '—'}` : ''}`; + }).join('') + queuedRows.map(t => { + // a trial never begun may have no task named yet: its name less the runner's tag (__u0042, __u0042r2) + const dim = opts.filter ? ' dim' : '', none = '—', named = t.task ? t : {trial: String(t.trial).replace(/__u\d{4,}(?:r\d+)?$/, '')}; + return ` + ${esc(shortTask(named))}${agents.length > 1 ? `${esc(t.agent || '')}` : ''} + Queued— + ${has.steps ? '—' : ''}${has.calls ? none : ''}${has.tokens ? none : ''}${has.line ? '—' : ''}`; }).join('') + doneRows.map(t => { // an ended trial: its outcome, its time in all, its tokens, and its page const tok = tokensOf(t), line = t.activity || t.last_line, href = trialHref(t, opts); @@ -229,8 +246,9 @@ ${has.line ? `${line ? redacted(line) : '—'}` : ''}${href ? `Open →` : ''}`; }).join(''); const said = [busy ? (opts.showAll ? `All ${running.length} in flight` : `${rows.length} of ${running.length} in flight`) + ', nearest their limit first' : '', + waits ? (opts.showAll ? `all ${queued.length} queued` : `the first ${queuedRows.length} of ${queued.length} queued`) : '', many ? (opts.showAll ? `all ${done.length} ended` : `the last ${doneRows.length} of ${done.length} ended`) : ''].filter(Boolean).join(' · '); - const more = busy || many ? `
${said}
` : ''; + const more = busy || many || waits ? `
${said}
` : ''; return `
${has.steps ? '' : ''}${has.calls ? '' : ''}${has.tokens ? '' : ''}${has.line ? '' : ''}${body}
${busy ? 'Trial, the running nearest their limit first' : 'Trial'}Phase, or how it endedTime in phase, of its limitStepsModel callsTokensLast line, redacted
${more}`; } // One trial: its phases on its own clock, from the feed's own phase events @@ -266,7 +284,7 @@ const events = (s.tail || []).filter(e => e.trial === t.trial).slice(-6); const state = t.state === 'done' ? `${OUTCOME_LABEL[t.outcome] || 'Ended'}${t.total_sec != null ? ', ' + clock(t.total_sec) + ' in all' : ''}` : t.state === 'running' ? `${PHASE_LABEL[t.phase] || t.phase}, ${clock(t.elapsed_sec)}${t.timeout_sec ? ' of ' + clock(t.timeout_sec) : ''}` - : stateOf(s) === 'finished' ? 'Not run' : `Queued${t.position != null ? ', position ' + (t.position + 1) : ''}`; + : stateOf(s) === 'finished' || outside(s, t) ? 'Not run' : `Queued${t.position != null ? ', position ' + (t.position + 1) : ''}`; const href = trialHref(t, opts); return `

${esc(shortTask(t))}${esc(state)}${t.agent ? ' · ' + esc(t.agent) : ''}

${t0 == null ? 'not started' : hms(starts[keys[0]])}${tl.ended ? 'ended ' + hms(tl.ended) : limEnd ? 'limit ' + clock(limEnd - t0) + ' in' : ''}
@@ -304,7 +322,7 @@ winners: renderWinners(winners), tilesLabel: `All ${trials.length} trial${trials.length === 1 ? '' : 's'}`, manyTiles: trials.length > MANY_TILES, - tiles: renderTiles(trials, opts, agents, state === 'finished'), + tiles: renderTiles(trials, opts, agents, state === 'finished', s), flight: renderFlight(s, state, opts, oc, agents), drawer: picked ? renderDrawer(s, picked, opts) : '', }; diff --git a/app/static/style.css b/app/static/style.css index 7f6b8ae3..def26335 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -360,6 +360,13 @@ tr.tone-good .jbar .fill { background: #4cc26a; } tr.tone-warn .jbar .fill { bac .run-meta > span + span::before { content: "·"; color: var(--text-faint); margin-right: 14px; } .run-meta > .mono { color: var(--text); } @media(max-width:640px){.run-meta > span + span::before{display:none}.run-meta{font-size:13px}} +.run-saveset { position: relative; } +.run-saveset > summary { list-style: none; } +.run-saveset > summary::-webkit-details-marker { display: none; } +.run-saveset-form { position: absolute; right: 0; top: calc(100% + 6px); z-index: 20; display: flex; flex-direction: column; gap: 10px; width: min(300px, calc(100vw - 32px)); padding: 14px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); box-shadow: 0 8px 24px rgba(0, 0, 0, .12); } +.run-saveset-form label { display: flex; flex-direction: column; gap: 5px; } +.run-saveset-form .btn { align-self: flex-start; } +@media (max-width: 640px) { .run-saveset-form { position: static; margin-top: 8px; box-shadow: none; } } .bar { display: flex; height: 8px; border-radius: 99px; overflow: hidden; @@ -1096,6 +1103,7 @@ tr.control-row td { color: var(--text-dim); } .try-tab[aria-current="page"] { color: var(--text); border-bottom-color: var(--accent); font-weight: 600; } .try-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .try-dur { color: var(--text-faint); font-weight: 400; font-variant-numeric: tabular-nums; } +.try-why { margin: .45rem 0 0; overflow-wrap: anywhere; } .attempt-table .num { text-align: right; font-variant-numeric: tabular-nums; } .attempt-table tr[aria-current="true"] td { background: var(--accent-soft); } .attempt-table tr.replaced td { opacity: .55; } diff --git a/app/templates/builder/new_run.html b/app/templates/builder/new_run.html index 6defe04c..cb4446ad 100644 --- a/app/templates/builder/new_run.html +++ b/app/templates/builder/new_run.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% from '_page.html' import page_head %} +{% from 'catalogue/_tasks_list.html' import tasks_list %} {% block title %}Run builder — Nullius{% endblock %} {% block crumb %}/ run builder{% endblock %} {% block head %}{# the Agent step's cards #} @@ -34,6 +35,16 @@

Give this recipe a name.

+ {#- Start with specific tasks: the tasks page's list of the plan's tasks, mounted afresh each time (catalogue/tasks.js) -#} + +

Start with

+
+
+
+
@@ -53,4 +64,5 @@

Give this recipe a name.

+ {% endblock %} diff --git a/app/templates/catalogue/_tasks_list.html b/app/templates/catalogue/_tasks_list.html new file mode 100644 index 00000000..74bd154f --- /dev/null +++ b/app/templates/catalogue/_tasks_list.html @@ -0,0 +1,28 @@ +{#- A dataset's tasks as a list to search and tick: the tasks page's, and the run builder's when it starts on specific + tasks (static/catalogue/tasks.js mounts either). -#} +{% macro tasks_list(nouns) %} +
+ +
+
+
+ 0 chosen + + +
Paste ids +
+
+
+ +
+

+
+ + + + +
+ +{% endmacro %} diff --git a/app/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index be84e2e4..7e41b31c 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -206,6 +206,38 @@

{{ d.title }}

{% endif %} + {% if std %} + {#- The benchmark's own task sets, its lists cut from another (subset_of), as the builder draws them; then the user's + task sets of it (standard/runner/sets.py), each with the version it was made at; and each dataset's tasks to choose from. -#} + {% set cuts = std.datasets|selectattr('subset_of')|list %}{% set wholes = std.datasets|rejectattr('subset_of')|list %} +
+

Task sets{% if task_sets or cuts %} {{ task_sets|length + cuts|length }}{% endif %}

+ {#- a new set is made on the page of the tasks it is cut from: one dataset's at once, else a choice of them #} + {% if local %}{% if wholes|length == 1 %}New task set + {% else %}
New task set + +
{% endif %}{% endif %} +
+ {% if cuts %} +

From {{ b.title }}

+ + {% if task_sets %}

Yours

{% endif %} + {% endif %} + {% if task_sets %} +
+ {% set made = task_sets|selectattr('version_label')|list %} + {% if made %}{% endif %} + {% for s in task_sets %} + + + {% if made %}{% endif %} + {% endfor %} +
NameDataset{{ std.units.nouns|capitalize }}Made atDate
{{ s.label }}{% if s.description %}{{ s.description }}{% endif %}{{ (std.datasets|selectattr('id', 'equalto', s.dataset)|map(attribute='label')|first) or s.dataset }}{{ s.units }}{{ s.version_label }}{{ s.date[:10] }}
+ {% endif %} + +
+ {% endif %} + {% for y in views %}{% set sfx = '' if y.default else '-' ~ y.version %} {% if y.b.good_to_know %} diff --git a/app/templates/catalogue/tasks.html b/app/templates/catalogue/tasks.html new file mode 100644 index 00000000..8b919452 --- /dev/null +++ b/app/templates/catalogue/tasks.html @@ -0,0 +1,84 @@ +{% extends "base.html" %} +{% from '_page.html' import page_head %} +{% from 'catalogue/_tasks_list.html' import tasks_list %} +{% block title %}{{ label if entry else ds.label or ds.id }} · {{ title }} — Nullius{% endblock %} +{% block crumb %}/ benchmarks / {{ bench.key }} / {{ ds.id }}{% if entry %} / {{ label }}{% endif %}{% endblock %} +{% block head %}{% endblock %} +{% block body %} +{#- One page for a dataset's tasks: the browser keeps the ids ticked, the server gives a page of 100 at a time + (standard/runner/units.py). Opened from a set (?set=NAME), its tasks start ticked; a set does not change, and other + ticks are saved as a new set. -#} +
+ {% set mark %}{% endset %} + {% set tags %}{{ 'Task set' if entry else 'Tasks' }}{{ title }} · {{ ds.label or ds.id }}{% endset %} + {% set actions %} + Build a run + {#- renaming and deleting ask first, in place; one question open at a time #} + {% if writable and entry %}
+ Rename +
+ + + + +
+
{% endif %} + {% if writable and (entry or broken) %}{% set n = rev.units|length if entry else 0 %}
+ Delete +
+ + Delete the task set {{ label if entry else broken }}{% if entry %}: {{ n }} {{ noun if n == 1 else nouns }}{% endif %}? Runs made from it stay. + + +
+
{% endif %} + {% endset %} + {{ page_head(label if entry else ds.label or ds.id, sub=tags, actions=actions, mark=mark) }} + {% if entry and entry.description %}

{{ entry.description }}

{% endif %} + {% if writable and not entry and not broken %}

Tick the {{ nouns }} to keep, then save them as a task set.

{% endif %} + {% if problem %}

{{ problem }}

{% endif %} + + {% if entry %} +
+
{{ nouns|capitalize }}{{ rev.units|length }}
+
Dataset{{ ds.label or ds.id }}
+ {% if made_at %}
Made at{{ made_at }}
{% endif %} +
Date{{ rev.date[:10] }}
+
In commands{{ entry.name }}
+ {% if rev.note %}
Note{{ rev.note }}
{% endif %} +
+ {% endif %} + + + +
+ {{ tasks_list(nouns) }} + {% if writable %} + + {% endif %} +
+ + {% if writable %} +
+

{{ 'Save as a new set' if entry else 'Save as task set' }}

+
+ + + +
+ +
+ {% endif %} +
+ +{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/templates/runs/index.html b/app/templates/runs/index.html index 51a2c7b1..e50aec9b 100644 --- a/app/templates/runs/index.html +++ b/app/templates/runs/index.html @@ -52,7 +52,8 @@ {%- if kind == 'control' %} — {%- else %} - {% if j and j.scored_only %}—{% elif j and part == 'fold' %}{{ j.n_resolved }}/{{ j.trials|length }}{% if r.not_run %}{{ r.not_run }} of {{ r.total }} not run{% endif %}{% elif j %}{{ j.n_resolved }}/{{ j.n_planned or j.trials|length }}{% else %}0{% if g.n_tasks %}/{{ g.n_tasks }}{% endif %}{% endif %} + {% if j and j.scored_only %}—{% elif j and part == 'fold' %}{{ j.n_resolved }}/{{ j.trials|length }}{% if r.not_run %}{{ r.not_run }} of {{ r.total }} not run{% endif %}{% elif j and j.start_with %}{{ j.n_resolved }}/{{ j.trials|length }}{% elif j %}{{ j.n_resolved }}/{{ j.n_planned or j.trials|length }}{% else %}0{% if g.n_tasks %}/{{ g.n_tasks }}{% endif %}{% endif %} + {%- if j and j.start_with and part != 'fold' and j.n_tasks_run < j.n_tasks %}{{ j.n_tasks_run }} of {{ j.n_tasks }} tasks run{% endif %} {%- endif %} {% if j and (j.total_input_tokens or j.total_output_tokens) %}{{ (j.total_input_tokens + j.total_output_tokens)|tokens(j.kind) }}{% else %}—{% endif %} {% if j and j.total_cost_usd is not none %}{{ j.total_cost_usd|usd(j.kind) }}{% else %}—{% endif %} @@ -222,7 +223,7 @@

{{ g.dataset_title if L.dataset else (L.name or g.dataset_title) }}{% if g.n {# present/planned exposes a partial run; the tooltip carries Harbor's retry and error counters, which have nowhere else to live. #} + title="{{ j.trials|length }} on disk{% if j.n_planned %} of {{ j.n_planned }} planned{% endif %}{% if j.start_with %} · begun on a part of its plan, {{ j.n_tasks_run }} of {{ j.n_tasks }} tasks run{% endif %}{% if j.n_retries %} · {{ j.n_retries }} retried{% endif %}{% if j.n_errored_trials %} · {{ j.n_errored_trials }} errored{% endif %}"> {{- j.trials|length }}{% if j.n_planned and j.n_planned != j.trials|length %}/{{ j.n_planned }}{% endif -%} {% if v %} diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index c14e0166..001c69e5 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -6,6 +6,7 @@ {% block title %}{{ job.job_id }} — Nullius{% endblock %} {% block crumb %}/ {{ job.job_id }}{% endblock %} {% block head %} +{# the dialogs' frame #} {% endblock %} {% block body %}{% set oc = job.counts %} @@ -41,6 +42,7 @@ {% if job.dataset %}{% call identity_card(benchmark_rows) %} {% if benchmark %}
Benchmark{{ benchmark }}
{% endif %}
Dataset{{ job.dataset|dsname }}
+ {% if job.task_set %}
Task set{% if set_link.link %}{{ set_link.name }}{% else %}{{ set_link.name }}{% endif %}
{% endif %} {% endcall %}{% endif %} {% if job.agent_label or job.model_name %} {% call identity_card(agent_rows) %} @@ -53,8 +55,8 @@ {{ control.label }}{% endif %} {% call identity_card(limit_rows) %} -
Trials{{ job.trials|length }}{% if job.n_planned and job.n_planned != job.trials|length %} of {{ job.n_planned }} planned{% endif %}
- {% if job.duration_min is not none %}
Duration{{ job.duration_min|runtime }}
{% endif %} +
Trials{% if job.start_with %}{{ job.n_tasks_run }} of {{ job.n_tasks }} planned tasks run{% else %}{{ job.trials|length }}{% if job.n_planned and job.n_planned != job.trials|length %} of {{ job.n_planned }} planned{% endif %}{% endif %}
+ {% if job.duration_min is not none %}
Duration{{ job|run_min|runtime }}
{% endif %} {% if job.n_retries %}
Retried{{ job.n_retries }}
{% endif %} {% endcall %}

{% endset %} @@ -65,7 +67,17 @@ title="Open the run builder with what this run recorded: its agents and their parameters, model, dataset and task filter, limits, timeouts and Harbor; anything a recipe cannot say is named there">New run like this{% endif %} {% set controls = feasibility_controls(job) %}{% if controls %}Feasibility · {{ controls|join(' + ') }}{% endif %} {% if job.harbor_command %}{% endif %}{% endset %} + title="{{ job.harbor_command }}">Copy command{% endif %} + {% if set_saving %}
+ Save as task set +
+ + + + +
+
{% endif %}{% endset %} {{ page_head(job.job_id, sub=meta, actions=actions) }} {% set board_ready = live_board and live_board.initial and live_board.initial.state != 'unknown' %} @@ -92,11 +104,15 @@
{% endif %} -{% if job.budget and job.budget.stopped and job.budget.max_usd %} -{# The run's own spending cap ended it (a Nullius standard run's --max-usd): nothing failed, so the notice is neutral. #} +{%- set shard_stop = job.budget and job.budget.stopped and job.budget.shards and not job.reruns %} +{% if (job_cap and (job_cap.closed or (shard_stop and not job_cap.changed))) or (not job_cap and job.budget and job.budget.stopped and job.budget.max_usd) %} +{# The run's own spending cap ended it (a Nullius standard run's --max-usd), or some of its shards at their share: + nothing failed, so the notice is neutral. It names the job's one cap and all it spent, as the cap's line does; the + units cut off are the first run's alone #} +{%- set spent = job_cap.spent_usd if job_cap else job.budget.spent_usd %}
- {% if job.budget.shards %}{{ job.budget.shards_stopped }} of {{ job.budget.shards }} shards stopped at their share of the spending cap{% else %}Stopped at its spending cap{% endif %} of {{ job.budget.max_usd|cap }}{% if job.budget.spent_usd is not none %}, with {{ job.budget.spent_usd|cap }} spent{% endif %}: - {{ job.budget.cut_off|length }} cut off, {{ job.budget.not_run|length }} not run. + {% if shard_stop %}{{ job.budget.shards_stopped }} of {{ job.budget.shards }} shards stopped at their share of the spending cap{% else %}Stopped at its spending cap{% endif %} of {{ (job_cap or job.budget).max_usd|cap }}{% if spent is not none %}, with {{ spent|cap }} spent{% endif %}{% if job.reruns %}.{% else %}: + {{ job.budget.cut_off|length }} cut off, {{ job.budget.not_run|length }} not run.{% endif %}
{% endif %} @@ -127,6 +143,21 @@
{% endif %} {% endif %} +{%- if rerunning and live_board and not live_board.running %} + +{% endif %} {#- Board counts are whole-run and never change under a filter; the trial rows are rendered here, and job.js only filters, sorts and links them. Every lane and tally count is nullius.judge.lanes, which is reconcile's. -#} @@ -180,6 +211,7 @@
raw rate
—
{% if job.mean_score_planned is not none %}
planned
{{ '%.2f'|format(job.mean_score_planned) }}
{% endif %} + {% if job.start_with %}
tasks run
{{ job.n_tasks_run }} of {{ job.n_tasks }}
{% endif %}
infra
{{ job.n_infra }}
@@ -227,6 +259,7 @@
{% if not job.has_verdict or job.raw_solve_rate != job.adjusted_solve_rate %}
raw rate
{{ job.raw_solve_rate|pct }}
{% endif %} + {% if job.start_with %}
tasks run
{{ job.n_tasks_run }} of {{ job.n_tasks }}
{% endif %} {% if job.n_infra %}
infra
{{ job.n_infra }}
{% endif %} {% if job.n_regressions %}
broke tests
{{ job.n_regressions }}
{% endif %}
@@ -343,16 +376,19 @@
in · cached · out
input{{ '{:,}'.format(job.total_input_tokens) }}cached (part of input){{ '{:,}'.format(job.total_cache_tokens) }}output{{ '{:,}'.format(job.total_output_tokens) }}
Cost{{ job.total_cost_usd|usd(job.kind) }}
- {% if job.budget and job.budget.max_usd %}
Spending cap{{ job.budget.max_usd|cap }}
+ {% if job_cap or (job.budget and job.budget.max_usd) %}
Spending cap{{ (job_cap or job.budget).max_usd|cap }}
+ {% if job_cap %}
{{ job_cap.spent_usd|cap }} spent{% if again and again.where %} · {% elif rerunning %} · change it when this part ends{% endif %}
{% endif %} {% if job.budget.not_run %}
{{ job.budget.not_run|length }} not run -
{% for u in job.budget.not_run %}{{ u }}{% endfor %}
{% endif %}{% endif %} +
{% for u in job.budget.not_run %}{{ u }}{% endfor %}
{% endif %} + {% elif again and again.where and job.standard %}
Spending capnone
+
{% endif %} {% if job.budget and job.budget.unit_max_usd %}
Cap per {{ job.runner_items[0] if job.runner_items else 'trial' }}{{ job.budget.unit_max_usd|cap }}
{% if job.budget.over_unit %}
{{ job.budget.over_unit|length }} reached it
{% for u in job.budget.over_unit %}{{ u }}{% endfor %}
{% endif %}{% endif %} {% if job.mean_score is not none %}
Mean score{{ '%.2f'|format(job.mean_score) }}
{% endif %} {% if job.mean_score_planned is not none %}
Mean over planned{{ '%.2f'|format(job.mean_score_planned) }}
{% endif %} {% for g in job.score_by_group %}
{{ job.parts_by|capitalize }} {{ g.group }}{{ '%.2f'|format(g.mean) }} {{ g.n }}
{% endfor %} - {% if job.duration_min %}
Duration{{ job.duration_min|runtime }}
{% endif %} + {% if job.duration_min %}
Duration{{ job|run_min|runtime }}
{% endif %} @@ -360,10 +396,10 @@ {# the trials: one filter row names every active filter, whichever mark set it #}
-

Trials

{{ job.trials|length }} +

Trials

{{ job.trials|length + waiting|length }}
OutcomeAll▾
- {% for k in ORDER %}{% if oc[k] %}{{ LABELS[k] }}{{ oc[k] }}{% endif %}{% endfor %} + {% for k in ORDER %}{% if oc[k] %}{{ LABELS[k] }}{{ oc[k] }}{% endif %}{% endfor %}{% for o, label in (('not_run', 'Not run'), ('no_result', 'No result')) %}{% set n = waiting|selectattr('outcome', 'eq', o)|list|length %}{% if n %}{{ label }}{{ n }}{% endif %}{% endfor %}
{% if judgement and judgement.causes %}
Judge causeAll▾ @@ -377,7 +413,22 @@

Trials

{{ f }}{{ n }}{% endfor %}
{% endif %} - + + {%- if again and again.where %} +
+ + 0 chosen + + {%- set rest = waiting|rejectattr('running')|list %} + {%- if rest %} + {%- if plan_sets %} +
Run a set +
{% for s in plan_sets %}{% endfor %}
+ {%- endif %} + + {%- endif %} +
+ {% elif again %}{{ again.why }}{% endif %}

{% from 'runs/_ending.html' import ending %} @@ -390,17 +441,20 @@

Trials

- {% if show_fa %}{% endif %}{% if job.retries %}{% endif %}{% if show_cause %}{% endif %}{% if show_flags %}{% endif %}{% if show_ins %}{% endif %} + {% if show_fa %}{% endif %}{% if show_tries %}{% endif %}{% if show_cause %}{% endif %}{% if show_flags %}{% endif %}{% if show_ins %}{% endif %} {% if vocab.gained %}{% endif %}{% if vocab.held %}{% endif %} - + {% if n_judge %}{% endif %} {% if vocab.gained or vocab.held %}{% endif %} @@ -411,7 +465,7 @@

Trials

Task {% if show_fa %}{% endif %} - {% if job.retries %}{% endif %} + {% if show_tries %}{% endif %} {% if show_cause %}{% endif %} {% if show_flags %}{% endif %} {% if show_ins %}{% endif %} @@ -439,7 +493,7 @@

Trials

{{ attempt_count(group, false) }} {% if group.n_infra %}{{ group.n_infra }} infra{% endif %}{% for a in group.trials %}{{ 'Attempt ' ~ loop.index }}: {{ '%.2f'|format(a.score) if a.outcome == 'scored' and a.score is not none else a.outcome_label }}{{ ', ' if not loop.last }}{% endfor %} {% if show_fa %}{% endif %} - {% if job.retries %}{% endif %} + {% if show_tries %}{% endif %} {% if show_cause %}{% endif %} {% if show_flags %}{% endif %} {% if show_ins %}{% endif %} @@ -457,15 +511,16 @@

Trials

- {%- if group %} - - {%- else %} - - {%- endif %} + {%- set name = 'attempt ' ~ k if group else task_labels[t.trial_name] %} + {% if show_fa %}{% endif %} - {% if job.retries %}{% endif %} + {% if show_tries %}{% endif %} {% if show_cause %} - + {% endfor %} - + {% for w in waiting %}{#- a task the job planned with no result: never begun, or begun and ended with none #} + + + {%- set said = 'Not run' if w.outcome == 'not_run' else 'No result' %} + + + + {% endfor %}
Judge{% if tq %}instructions scored {{ tq.judged }}/{{ tq.tasks }}{% endif %}TestsOutcomeUser judgeRetriesRetriesCause{% if show_flags %} · flags{% endif %}FlagsInstruction{{ task_flag(t) }}{{ instruction(t) }}attempt {{ k }}{{ task_labels[t.trial_name] }}{% if picking %}{% endif -%} + {%- if url %}{{ name }} + {%- else %}{{ name }}{% endif %} + {%- if again_now %} running again{% endif %} {% set plain = t.outcome in ('resolved', 'scored') %}{# one form for every trial: its number, its square, and its outcome in words unless it passed or was scored #} {%- if t.score is not none and (job.scored_only or t.outcome == 'scored') %}{{ '%.2f'|format(t.score) }} @@ -479,7 +534,7 @@

Trials

{{ t.exception_type }}{{ t.exception_message }} {%- else %}{{ t.exception_type }}{% endif %}{% endif %}
{% if not group %}{{ task_flag(t) }}{% endif %}{{ trial_label(t) }}{% if t.n_retries %}{{ t.n_retries }}/{{ job.retries }}{% else %}0/{{ job.retries }}{% endif %}{% if t.n_retries %}{{ t.n_retries }}{% if job.retries %}/{{ job.retries }}{% endif %}{% else %}0{{ '/' ~ job.retries if job.retries }}{% endif %} {%- if t.outcome == 'resolved' %}not asked {%- elif jr and jr.cause %}{{ jr.cause }} @@ -499,17 +554,71 @@

Trials

{{ t.dur_env|secs }}
{{ t.dur_agent|secs }} {{ t.dur_verifier|secs }}→{% if url %}→{% endif %}
{% if picking %}{% endif -%} + {{ w.unit }}{% if w.running %} running{% endif %}—{{ said }} + {%- if w.outcome == 'no_result' %} {{ 'begun, ended with none' if w.folder else 'never run' }}{% endif %}
+{%- if picking %} +{#- what Run selected again asks: the count, the names and a reason, the budget left; for tasks that never ran, one short + question and the budget left. The page fills the words and the names from the ticks #} + +
+

Run 0 tasks again

+

On {{ again.where }}, in this job: each result replaces the task's, and the earlier tries stay.

+
    + + {%- if job_cap %} +

    {% if job_cap.closed %}Budget for the whole run: {{ job_cap.max_usd|cap }}, {% if job_cap.left_usd > 0 %}{{ job_cap.spent_usd|cap }} spent; the last part stopped at it{% else %}all spent{% endif %}. Change it to run more.{% else %}Budget for the whole run: {{ job_cap.max_usd|cap }}, {{ job_cap.left_usd|cap }} left.{% endif %}

    + {%- endif %} + +
    +
    +
    +{#- the job's one spending cap, changed for its next part #} + +
    +

    Spending cap for the whole run

    +

    {% if job_cap %}{{ job_cap.spent_usd|cap }} spent so far. {% endif %}The new cap applies from the next part.

    + + +
    +
    +
    +{% endif %} {# behind a click: what the run recorded about its install, and the page's one block of prose #}
    + {%- if job.reruns %} +
    + Run later{{ job.reruns|length }} +
    + {% for r in job.reruns|reverse %} +
    {{ r.at[:16]|replace('T', ' ') }}{{ 'Z' if r.at.endswith('+00:00') }}{% if r.stopped %} stopped{% endif %}
    +
    {% if r.reason %}

    {{ r.reason }}

    {% endif %} +
      {% for x in r.replaced %}
    • {{ x.unit or x.trial }}{% for k, v in x.was.items() %} {{ k }} {{ v }}{% endfor %}{% if x.trial in (r.no_result or []) %} no result{% endif %} → {% for k, v in x.now.items() %}{{ k }} {{ v }} {% endfor %}try {{ x.try }}
    • {% endfor %} + {%- for x in r.begun or [] %}
    • {{ x.unit or x.trial }} first run → {% for k, v in x.now.items() %}{{ k }} {{ v }} {% endfor %}
    • {% endfor %} + {%- set left = r.trials|reject('in', r.replaced|map(attribute='trial')|list + (r.begun or [])|map(attribute='trial')|list)|list %}{% if left %}
    • {{ left|length }} not replaced: {{ left|join(', ') }}
    • {% endif %}
    + {% set n = r.trials|n_tasks %}{{ n }} task{{ '' if n == 1 else 's' }}{% if r.spent_usd is not none %} · {{ r.spent_usd|usd }} spent{% endif %}
    + {% endfor %} +
    + {%- if job_cap %} +

    Spending cap for the whole run {{ job_cap.max_usd|cap }} · {{ job_cap.spent_usd|cap }} spent

    + {%- endif %} +
    + {% endif %} {% if job.harbor_command %}
    Configuration diff --git a/app/templates/traces/_attempts.html b/app/templates/traces/_attempts.html index 87f4bacd..0c5c27bb 100644 --- a/app/templates/traces/_attempts.html +++ b/app/templates/traces/_attempts.html @@ -19,16 +19,21 @@ {# An attempt's tries, when its runner kept the ones before its last (parse.tries): one tab each, the last the one that counts. `current` is the - try on screen. #} + try on screen. A try a person asked for after the run ended says so, with + the reason they gave (parse.Trial.rerun), on its tab and under the tabs; a task + of the plan a later part began says it was its first run. #} {% macro try_tabs(job, tries, current, workspace=none) -%} +{%- if current.rerun and current.rerun.reason %} +

    {{ (current|try_mark(job))|capitalize }}: {{ current.rerun.reason }}

    {% endif %} {%- endmacro %} {# How a run did at one task over its attempts, as its adjusted rate reads diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index dc95d5c9..a0631da1 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -400,6 +400,7 @@ "n_running_trials", "n_scored_parts", "n_tasks", + "n_tasks_run", "n_total_trials", "parts_by", "preparing", @@ -407,6 +408,7 @@ "raw_solve_rate", "reasoning_effort", "reports_regressions", + "reruns", "retries", "runner", "runner_commit", @@ -415,8 +417,10 @@ "score_by_group", "scored_only", "standard", + "start_with", "started_at", "state", + "task_set", "total_cache_tokens", "total_cost_usd", "total_input_tokens", @@ -469,6 +473,7 @@ "patch_exists", "phases", "reasoning_effort", + "rerun", "retried_cost_usd", "reward", "score", diff --git a/app/tests/fixtures/standard/ordinary-result.json b/app/tests/fixtures/standard/ordinary-result.json new file mode 100644 index 00000000..95c7fb75 --- /dev/null +++ b/app/tests/fixtures/standard/ordinary-result.json @@ -0,0 +1,18 @@ +{ + "id": "job", + "started_at": "2026-01-01T00:00:00+00:00", + "finished_at": "2026-01-01T00:00:00+00:00", + "n_total_trials": 3, + "stats": { + "n_completed_trials": 3, + "n_errored_trials": 0, + "n_cancelled_trials": 0, + "n_running_trials": 0, + "n_pending_trials": 0, + "n_retries": 0 + }, + "served": { + "calls": {}, + "unnamed": 1 + } +} \ No newline at end of file diff --git a/app/tests/test_cli_contract.py b/app/tests/test_cli_contract.py index 06c25f58..155abe19 100644 --- a/app/tests/test_cli_contract.py +++ b/app/tests/test_cli_contract.py @@ -15,6 +15,7 @@ import hashlib import json import os +import re import shutil import socket import subprocess @@ -236,6 +237,65 @@ def test_help_and_json_results_across_the_named_failure_kinds(self): self.assertEqual([r["job_id"] for r in listed], ["failed-job"]) self.assertFalse(os.path.exists(os.path.join(self.tmp, "out"))) + def test_running_tasks_again_documents_its_help_and_refuses_on_one_line(self): + """Human help and machine-readable results are tested, including empty + inputs, invalid arguments, unavailable resources, failed jobs and + authorization failures: here for running chosen tasks of a job again, + whose refusals write nothing and leave stdout empty.""" + out = self.sh("standard.cli", "rerun", "--help") + self.assertEqual(out.returncode, 0, out.stderr) + for line in ("usage:", "rerun", "JOB_DIR", "examples:", "exit codes:"): + self.assertIn(line, out.stdout) + help_text = " ".join(out.stdout.split()) + for kind in ("no result", "spending cap", "ended by a Stop"): + self.assertIn(kind, help_text) + self.assertIn("excludes scores and agent errors", help_text) + self.assertEqual(out.stderr, "") + job = Path(self.tmp, "job") + write_json(job / "config.json", {"job_name": "job", "runner": "standard", + "standard": {"benchmark": "humaneval", "plugged": "nop", "kind": "control"}}) + write_json(job / "result.json", {"id": "job", "n_total_trials": 1, "stats": {}}) + write_json(job / "a__u0000" / "result.json", {"trial_name": "a__u0000", "standard": {"unit": "a"}}) + Path(self.tmp, "ids.txt").write_text("a\n") + before = tree_digest(job) + cases = [ + (["rerun", os.path.join(self.tmp, "nowhere"), "--unit", "a"], 3, "no such directory"), + (["rerun", str(job)], 2, "refused: no task named"), + (["rerun", str(job), "--unit", "nosuch"], 2, "refused: job holds no trial or unit nosuch"), + (["rerun", str(job), "--unit", "a", "--units", os.path.join(self.tmp, "ids.txt")], 2, "usage:"), + (["rerun", str(job), "--unit", "a", "--retries", "x"], 2, "usage:"), + (["rerun", str(job), "--unit", "a", "--unfinished"], 2, "usage:"), + (["rerun", str(job), "--unfinished"], 2, "refused: job does not record the tasks it planned"), + (["rerun", str(job), "--next", "2"], 2, "refused: job does not record the tasks it planned"), + (["rerun", str(job), "--next", "x"], 2, "usage:"), + (["rerun", str(job), "--unit", "a", "--next", "1"], 2, "usage:"), + (["rerun", str(job), "--set", "nosuch"], 3, "refused: no task set 'nosuch' of humaneval"), + (["rerun", str(job), "--set", "a/b"], 2, "refused: 'a/b' is not a task set's name"), + ] + for args, code, said in cases: + with self.subTest(args=args[2:]): + out = self.sh("standard.cli", *args) + self.assertEqual(out.returncode, code, out.stderr) + self.assertIn(said, out.stderr) + self.assertEqual(out.stdout, "", "a failure leaves stdout empty") + if said.startswith("refused"): + self.assertEqual(len(out.stderr.strip().splitlines()), 1) + self.assertEqual(tree_digest(job), before) + # a job whose feed says what it planned, every task with a result: nothing to run, said, exit 0 + with open(job / "events.jsonl", "w") as f: + f.write(json.dumps({"seq": 1, "event": "job.start", "trial": None, "tasks": ["a"]}) + "\n") + f.write(json.dumps({"seq": 2, "event": "trial.queued", "trial": "a__u0000", "position": 0}) + "\n") + before = tree_digest(job) + out = self.sh("standard.cli", "rerun", str(job), "--unfinished") + self.assertEqual((out.returncode, out.stderr), (0, "")) + self.assertEqual(out.stdout.splitlines(), ["nothing to run: every task job planned has a result", str(job)]) + self.assertEqual(tree_digest(job), before) + out = self.sh("standard.cli", "rerun", str(job), "--next", "1") # more than are left + self.assertEqual((out.returncode, out.stdout), (2, "")) + self.assertEqual(out.stderr.strip(), "refused: --next 1: 0 tasks of the plan are left to run") + self.assertEqual(tree_digest(job), before) + self.assertTmpHolds("job", "ids.txt") + def test_documented_exit_codes_no_secrets_and_no_unintended_writes(self): """Commands work non-interactively with documented exit codes and no secrets in output; read/preview checks produce no unintended writes, @@ -289,6 +349,71 @@ def test_a_key_in_the_recorded_command_is_not_echoed_by_show_json(self): self.assertNotIn(KEY, out.stdout) +# ── task-sets.md ──────────────────────────────────────────────────────────── + +class TaskSetCommands(Scratch): + def test_help_and_refusals_of_the_task_set_commands(self): + """Each set command, and units, has help with its examples and exit codes; a + refusal is one line on stderr with nothing on stdout, 2 for a usage + error or a refusal, 3 for what is not found, and writes nothing.""" + cat = os.path.join(self.tmp, "catalogue") + env = {"NULLIUS_CATALOGUE": cat, "NULLIUS_HOME": os.path.join(self.tmp, "profile")} + for sub in (("set",), ("set", "create"), ("set", "list"), ("set", "show"), ("set", "rename"), + ("set", "delete"), ("set", "import"), ("units",)): + with self.subTest(help=sub): + out = self.sh("standard.cli", *sub, "--help", env=env) + self.assertEqual(out.returncode, 0, out.stderr) + for line in ("usage:", "examples:", "exit codes:"): + self.assertIn(line, out.stdout) + self.assertEqual(out.stderr, "") + listed = write_json(Path(self.tmp, "ten.txt"), "HumanEval/0\nHumanEval/1\n") + cases = [ + (["set", "create", "humaneval"], 2, "usage:"), + (["set", "create", "humaneval", "..", "--dataset", "humaneval", "--units", listed], 2, "needs a letter or a digit"), + (["set", "show", "humaneval", "a/b"], 2, "not a task set's name"), + (["set", "create", "humaneval", "ok", "--dataset", "nope", "--units", listed], 2, "no dataset 'nope'"), + (["set", "create", "no-such-bench", "ok", "--dataset", "x", "--units", listed], 3, "no benchmark"), + (["set", "show", "humaneval", "nowhere"], 3, "no task set 'nowhere'"), + (["set", "update", "humaneval", "nowhere", "--add", "HumanEval/2"], 2, "invalid choice: 'update'"), # a set is frozen + (["set", "rename", "humaneval", "nowhere", "elsewhere"], 3, "no task set 'nowhere'"), + (["set", "rename", "humaneval", "nowhere"], 2, "usage:"), + (["set", "delete", "humaneval", "nowhere"], 3, "no task set 'nowhere'"), + (["set", "import", os.path.join(self.tmp, "absent.json")], 3, "no such file or job"), + (["set", "create", "humaneval", "ok", "--dataset", "humaneval", "--units", listed, "--bench-option", "a=b"], 2, + "unrecognized arguments: --bench-option"), + (["set", "create", "humaneval", "ok", "--dataset", "humaneval"], 2, "--units FILE, --from-job"), + (["units", "humaneval"], 2, "usage:"), + (["units", "humaneval", "--dataset", "nope"], 3, "no dataset 'nope'"), + (["units", "no-such-bench", "--dataset", "x"], 3, "no benchmark"), + (["units", "humaneval", "--dataset", "humaneval", "--category", "kind"], 2, "FIELD=VALUE"), + ] + for args, code, said in cases: + with self.subTest(args=args): + out = self.sh("standard.cli", *args, env=env) + self.assertEqual(out.returncode, code, out.stderr) + self.assertIn(said, out.stderr) + self.assertEqual(out.stdout, "") + # a listing that needs a program this machine lacks is refused before it fetches anything + out = self.sh("standard.cli", "units", "humaneval", "--dataset", "humaneval", + env=dict(env, PATH=os.path.join(self.tmp, "no-programs"))) + self.assertEqual((out.returncode, out.stdout), (2, "")) + self.assertEqual(out.stderr, "refused: cannot prepare humaneval's dataset humaneval for its listing: " + "git is not on this machine\n") + self.assertFalse(os.path.exists(cat)) + out = self.sh("standard.cli", "set", "list", "--json", env=env) + self.assertEqual((out.returncode, json.loads(out.stdout), out.stderr), (0, [], "")) + + def test_the_index_of_commands_names_each_set_command_there_is_and_no_other(self): + """The commands' index (docs/cli/README.md) names the set commands one by one: the ones ``set`` takes.""" + out = self.sh("standard.cli", "set", "--help", env={"NULLIUS_HOME": os.path.join(self.tmp, "profile")}) + self.assertEqual(out.returncode, 0, out.stderr) + taken = set(re.findall(r"^ ([a-z]+) ", out.stdout, re.M)) # the help's list of commands + row = next(line for line in (APP.parent / "docs" / "cli" / "README.md").read_text(encoding="utf-8").splitlines() + if line.startswith("| [Task sets]")) + listed = row[row.index("`set create`"):].split(";")[0] + self.assertEqual({name.removeprefix("set ") for name in re.findall(r"`([^`]+)`", listed)}, taken) + + # ── import.md ─────────────────────────────────────────────────────────────── class ImportContract(Scratch): diff --git a/app/tests/test_dataset_subsets.py b/app/tests/test_dataset_subsets.py new file mode 100644 index 00000000..8d101820 --- /dev/null +++ b/app/tests/test_dataset_subsets.py @@ -0,0 +1,70 @@ +"""A benchmark's list cut from another of its lists (``subset_of`` on a dataset of its definition): the field is +optional and names another list, one cut from none, that holds at least as many units; OSWorld1 declares its three +cuts of All tasks at each of its versions; a run still names the list it runs, so a recipe of a cut compiles as +before. No key, no network.""" +from __future__ import annotations + +import copy +import unittest + +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe + + +def clean(d: dict) -> dict: + return copy.deepcopy({k: v for k, v in d.items() if not k.startswith("_")}) + + +class TheField(unittest.TestCase): + def setUp(self): + self.osw = clean(definitions.get("benchmark", "osworld1")) + + def said(self, d): + return [p for p in definitions.problems(d, "benchmark") if "subset_of" in p] + + def test_it_is_optional_and_the_declared_lists_pass(self): + self.assertEqual(self.said(self.osw), []) + plain = copy.deepcopy(self.osw) + for x in plain["datasets"]: + x.pop("subset_of", None) + self.assertEqual(self.said(plain), []) + + def test_it_names_another_list_cut_from_none_holding_as_many_units(self): + ids = [x["id"] for x in self.osw["datasets"]] + nogdrive, whole, small = ids.index("test_nogdrive"), ids.index("test_all"), ids.index("test_small") + for change, said in (((nogdrive, "subset_of", "nowhere"), f"datasets[{nogdrive}].subset_of: the id of another of its datasets"), + ((whole, "subset_of", "test_all"), f"datasets[{whole}].subset_of: the id of another of its datasets"), + ((small, "subset_of", "test_nogdrive"), f"datasets[{small}].subset_of: test_nogdrive is cut from another list"), + ((nogdrive, "subset_of", 3), f"datasets[{nogdrive}].subset_of: the id of another of its datasets"), + ((whole, "units", 10), f"datasets[{nogdrive}].subset_of: it holds more units than test_all")): + with self.subTest(change=change): + d = copy.deepcopy(self.osw) + i, k, v = change + d["datasets"][i][k] = v + self.assertTrue(any(p.startswith(said) for p in self.said(d)), self.said(d)) + + +class Declared(unittest.TestCase): + def test_osworld1_declares_its_three_cuts_of_all_tasks_at_each_version(self): + for v in ("desktop-env-v1.0.3", "044bc33"): + with self.subTest(version=v): + b = definitions.get("benchmark", f"osworld1@{v}") + self.assertEqual({x["id"]: x.get("subset_of") for x in b["datasets"]}, + {"test_all": None, "test_nogdrive": "test_all", "test_small": "test_all", "test_infeasible": "test_all"}) + whole = next(x for x in b["datasets"] if x["id"] == "test_all") + self.assertTrue(all(x["units"] <= whole["units"] for x in b["datasets"])) + self.assertEqual([x["subset_of"] for x in recipe._bench_page(b)["datasets"]], + ["test_all" if x.get("subset_of") else "" for x in b["datasets"]]) + + def test_a_run_still_names_the_list_it_runs(self): + b = definitions.get("benchmark", "osworld1@044bc33") + out = recipe.compile({"version": 1, "harness": "standard", "name": "osw", "title": "t", "benchmark": "osworld1@044bc33", + "datasets": ["test_nogdrive"], "others": ["nop"], "provider": "openai", "model": "", "where": "local", + "concurrency": 1}, {"benchmark": [b], "agent": [], "capability": []}) + self.assertEqual(out["errors"], [], out["errors"]) + self.assertIn("--dataset test_nogdrive ", out["shards"][0]["command"]) + self.assertEqual(next(r for r in out["review"] if r[1] == "Dataset")[2], "Without Google Drive · 361 tasks") + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index dad1c853..bb335416 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -828,6 +828,16 @@ def test_app_is_sent_at_its_content_address_and_the_part_runs_from_it(self): self.assertEqual(json.loads((self.tmp / "runs" / "std-shard-2of2" / "run.json").read_text())["catalogue_on_target"], "~/.nullius/runs/std-shard-2of2/catalogue") + def test_the_snapshot_a_host_is_sent_carries_the_recipes_task_sets(self): + self.plan.recipe = {"harness": "standard", "benchmark": "fakebench@1", "task_sets": {"all": "dev@2", "more": "other"}} + ex = self.run_it() + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + self.assertEqual(execution.standard_payload.build.call_args.kwargs["sets"], [("fakebench", "dev"), ("fakebench", "other")]) + self.plan.recipe = {} + self.plan.name = "std-plain" + self.run_it() + self.assertEqual(execution.standard_payload.build.call_args.kwargs["sets"], []) + def test_gaias_hugging_face_token_is_handed_from_data_providers_alone(self): # over the launcher's stdin as a licence is, read from Settings → Data providers; a value GAIA's own folder # holds under that name is never sent diff --git a/app/tests/test_execution_again.py b/app/tests/test_execution_again.py new file mode 100644 index 00000000..bfc86f85 --- /dev/null +++ b/app/tests/test_execution_again.py @@ -0,0 +1,184 @@ +"""One more part in an ended run's folder (``Execution.again``): chosen tasks of +its job run again where the run ran, here or on its host, the key read again and +sent as a run's, the job's own end kept.""" +from __future__ import annotations + +import json +import os +import shlex +import shutil +from pathlib import Path +from unittest import mock + +from nullius import execution, hosts +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.runner import run + +from tests.execution_support import Base, HostBase + + +def part(script, n=1, job="j1", trials=("t1",)): + return {"id": f"again-{n}", "label": f"{len(trials)} task of {job} again", "again": job, "trials": list(trials), "script": script} + + +class Here(Base): + """A run on this machine, ended, then one more part in its folder: real bash, setsid, files.""" + + def plan(self): + made = 'mkdir -p "$NULLIUS_JOBS/j1" && echo "{}" > "$NULLIUS_JOBS/j1/result.json"' + return execution.Plan(name="std-here", script="", runner="standard", model="m-1", key_var="OPENAI_API_KEY", url_var="", + parts=[{"id": "fake", "label": "Fake", "script": made}], jobs=[{"name": "j1", "agent": "fake/0.1"}]) + + def test_a_part_runs_again_in_the_run_s_folder_with_the_key_read_now(self): + ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start()) + self.assertEqual(ex.state, "done", ex.lines) + first = ex.job_state("j1") + self.assertIsNone(ex.holds("j1")) + gate = self.tmp / "go" + script = f'until [ -e {shlex.quote(str(gate))} ]; do sleep 0.02; done; echo "again key=${{#API_TOKEN}} jobs=$NULLIUS_JOBS"' + with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-second-key-2"}): + ex.again(part(script)) + self.until(ex, "running") + # while it runs, the job is going again: no end of its own, the run's state for it, its tasks named + self.assertIsNone(ex.job_state("j1")) + self.assertEqual(ex.live_state("j1"), "running") + self.assertEqual(ex.again_of("j1")["trials"], ["t1"]) + with self.assertRaises(ValueError): + ex.again(part("true", n=2)) # one part at a time + gate.write_text("") + self.wait(ex) + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + d = self.tmp / "runs" / "std-here" + self.assertEqual((d / "run-again-1.exit").read_text().strip(), "0") + self.assertEqual((d / "run-fake.exit").read_text().strip(), "0") # the first part's files are its own + self.assertIn(f"again key=15 jobs={d / 'jobs'}", "\n".join(ex.lines)) # the key Settings holds now + self.assertNotIn("sk-second-key-2", (d / "run.json").read_text()) + # the job's end is still its own part's; the run's record holds both parts + self.assertEqual(ex.job_state("j1"), first) + self.assertIsNone(ex.again_of("j1")) + rec = json.loads((d / "run.json").read_text()) + self.assertEqual([p["id"] for p in rec["plan"]["parts"]], ["fake", "again-1"]) + self.assertEqual(sorted(rec["ends"]), ["again-1", "fake"]) + self.assertEqual(ex.part_for("j1"), "fake") + # a restart reads it as it was + execution.EXECUTIONS.clear() + back = execution.Execution(execution.Plan.from_dict(rec["plan"]), root=str(self.tmp / "runs"), record=rec) + self.assertEqual((back.state, back.job_state("j1")), ("done", first)) + + def test_a_part_run_again_that_fails_fails_the_run_and_not_the_job(self): + ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start()) + first = ex.job_state("j1") + self.wait(ex.again(part("echo 'refused: no such trial' >&2; exit 2"), env={"OPENAI_API_KEY": "sk-first-key-0001"})) + self.assertEqual((ex.state, ex.exit_code), ("failed", 2)) + self.assertIn("refused: no such trial", "\n".join(ex.lines)) + self.assertEqual(ex.job_state("j1"), first) + self.assertIsNone(ex.refused("j1")) + self.assertFalse(ex.never_ran("j1")) + + def test_the_cli_s_rerun_is_the_command_and_its_words_reach_it(self): + """The generated command runs precisely the named tasks of a finished job.""" + dest = self.tmp / "catalogue/benchmarks/fakebench" + shutil.copytree(Path(__file__).parent / "fixtures/standard/catalogue/benchmarks/fakebench", dest) + spec = json.loads((dest / "standard.json").read_text()) + spec["controls"] = {"nop": {"source": "nullius", "from": "Empty answer."}} + (dest / "standard.json").write_text(json.dumps(spec)) + (dest / "driver.py").write_text( + 'from nullius.standard.protocols.jsonl import serve\n' + 'serve({"units": lambda dataset: {"units": ["t1", "t 2", "untouched"]}, ' + '"setup": lambda unit, dir: {"prompt": ""}, ' + '"score": lambda **kw: {"reward": 0.0}})\n') + bench = definitions.get("benchmark", "fakebench", str(self.tmp / "catalogue")) + plan = self.plan() + plan.parts[0]["script"] = "true" + ex = self.wait(execution.Execution(plan, root=str(self.tmp / "runs"), key="sk-first-key-0001").start()) + path = Path(run.run(bench, definitions.control(bench, "nop"), model="", provider="custom", + jobs_root=ex.jobs, name="j1", env={}, concurrency=1, say=lambda s: None)) + names = {json.loads((p / "result.json").read_text())["standard"]["unit"]: p.name + for p in path.iterdir() if (p / "result.json").is_file()} + untouched = (path / names["untouched"] / "result.json").read_bytes() + self.wait(ex.again(recipe.again("j1", ["t1", "t 2"], reason="the provider's 'failure'", n=1), env={"OPENAI_API_KEY": "sk-first-key-0001"})) + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + (record,) = json.loads((path / "result.json").read_text())["reruns"] + self.assertEqual(record["trials"], [names["t1"], names["t 2"]]) + self.assertEqual([r["unit"] for r in record["replaced"]], ["t1", "t 2"]) + self.assertEqual(record["reason"], "the provider's 'failure'") + self.assertEqual(sorted(p.name for p in (path / "retried").iterdir()), + sorted(names[u] + ".try-1" for u in ("t1", "t 2"))) + self.assertEqual((path / names["untouched"] / "result.json").read_bytes(), untouched) + + def test_a_job_no_longer_here_is_said(self): + ex = self.wait(execution.Execution(self.plan(), root=str(self.tmp / "runs"), key="sk-first-key-0001").start()) + os.remove(self.tmp / "runs" / "std-here" / "jobs" / "j1" / "result.json") + self.assertEqual(ex.holds("j1"), "This machine no longer holds j1") + self.assertEqual(ex.holds("j2"), "std-here wrote no job j2") + + +class Recipe(Base): + def test_the_part_names_the_job_the_trials_the_reason_and_the_cap(self): + got = recipe.again("job-1", ["a__u0001", "b c"], reason="it's flaky", max_usd=0.25, n=3) + self.assertEqual((got["id"], got["again"], got["trials"], got["label"]), ("again-3", "job-1", ["a__u0001", "b c"], "2 tasks of job-1 again")) + line = next(l for l in got["script"].splitlines() if l.startswith("exec nullius standard ")) + self.assertEqual(shlex.split(line.replace('"${NULLIUS_JOBS:-jobs_standard}"', "JOBS"))[3:], + ["rerun", "JOBS/job-1", "--unit", "a__u0001", "--unit", "b c", "--reason", "it's flaky", "--max-usd", "0.25", "--from-run"]) + self.assertNotIn("--reason", recipe.again("job-1", ["a"])["script"]) + self.assertNotIn("--max-usd", recipe.again("job-1", ["a"])["script"]) + + +class OnHost(HostBase): + """A standard run on a host, ended, then one more part sent there: its folder is the run's own, the + server's tree and the key go as a run's, the job comes back as a run's does.""" + COMMIT = "c0ffee" * 6 + "c0ff" + + def setUp(self): + super().setUp() + self.plan = execution.Plan(name="std-host", script="", host=hosts.parse("bench"), runner="standard", model="m-1", + parts=[{"id": "fake", "label": "Fake", "script": "exec true\n"}], + jobs=[{"name": "std-host", "agent": "fake/0.1"}]) + self.plan.key_var, self.plan.url_var = "OPENAI_API_KEY", "" + (self.tmp / "standard-app" / self.COMMIT / "app").mkdir(parents=True) + payload = mock.patch.object(execution.standard_payload, "build", return_value=(self.COMMIT, str(self.tmp / "standard-app" / self.COMMIT))) + payload.start(); self.addCleanup(payload.stop) + self.held = True + + def answer(self, argv, timeout=0, stdin=None): + if argv[0] != "rsync" and "printf 'ok" in argv[-1]: + self.calls.append((argv, stdin)) + return 0, "ok\nuv=yes\ndocker=yes\nharbor=no\nhostname=gpu-1\n" + if argv[0] != "rsync" and "@held" in argv[-1]: + self.calls.append((argv, stdin)) + return 0, "@held\n" if self.held else "@gone\n" + return super().answer(argv, timeout, stdin) + + def test_the_part_is_sent_to_the_run_s_host_in_its_folder_with_the_key_and_the_job_comes_back(self): + ex = self.wait(execution.Execution(self.plan, root=str(self.tmp / "runs"), run=self.answer, key="sk-first-key-0001", url="").start()) + self.assertEqual(ex.state, "done", ex.lines) + self.assertIsNone(ex.holds("std-host")) + self.calls.clear(); self.polls = 0 + with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-again-key-00003"}): + ex.again(recipe.again("std-host", ["t1"], reason="flaky", n=1)) + self.wait(ex) + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + commands = self.ssh_commands() + self.assertFalse(any("@taken" in c for c in commands)) # its folder is its own: no name asked + rsyncs = [c for c, _ in self.calls if c[0] == "rsync"] + self.assertEqual(rsyncs[0][-2:], [str(self.tmp / "standard-app" / self.COMMIT) + "/", f"bench:~/.nullius/app/{self.COMMIT}"]) + self.assertIn("bench:~/.nullius/runs/std-host/jobs/", {c[-2] for c in rsyncs[1:]}) # the job mirrored back + sent = next(c for c in commands if "cat > " in c and "run-again-1.sh" in c) + self.assertIn('"$HOME/.nullius/runs/std-host/run-again-1.sh"', sent) + script = next(s for c, s in self.calls if c[0] == "ssh" and "run-again-1.sh" in c[-1] and "cat > " in c[-1]) + self.assertIn('rerun "${NULLIUS_JOBS:-jobs_standard}"/std-host --unit t1 --reason flaky --from-run', script) + launch, stdin = next((c, s) for c, s in self.calls if c[0] == "ssh" and "setsid nohup" in c[-1]) + self.assertIn('NULLIUS_JOBS="$HOME/.nullius/runs/std-host/jobs"', launch[-1]) + self.assertIn(f'NULLIUS_STANDARD="$HOME/.nullius/app/{self.COMMIT}"', launch[-1]) + self.assertIn("run-again-1.sh", launch[-1]) + self.assertEqual(stdin, "sk-again-key-00003\n\n@end\n") # the key as a run's: stdin, read now + self.assertNotIn("sk-again-key-00003", launch[-1]) + + def test_a_host_that_no_longer_holds_the_job_is_said_and_nothing_is_sent(self): + ex = self.wait(execution.Execution(self.plan, root=str(self.tmp / "runs"), run=self.answer, key="sk-first-key-0001", url="").start()) + self.held = False + self.calls.clear() + self.assertEqual(ex.holds("std-host"), "bench no longer holds std-host: nothing was started") + self.assertEqual([c for c, _ in self.calls if c[0] == "rsync" or "setsid" in c[-1]], []) + self.assertIn('[ -f "$HOME/.nullius/runs/std-host/jobs/std-host/result.json" ]', self.ssh_commands()[0]) diff --git a/app/tests/test_live.py b/app/tests/test_live.py index b81e198c..d05d94f6 100644 --- a/app/tests/test_live.py +++ b/app/tests/test_live.py @@ -111,6 +111,41 @@ def test_out_of_order_seq_is_folded_in_order_and_noted(self): class Fold(unittest.TestCase): + def test_an_ordinary_run_with_named_tasks_keeps_automatic_retry_aggregates(self): + board = board_of(ev(1, "job.start", trial=None, n_total=1, tasks=["task"]), + ev(2, "trial.phase", task="task", phase="agent_run"), + ev(3, "trial.end", outcome="infra_error", cost_usd=0.25), + ev(4, "trial.phase", phase="agent_run")).snapshot() + self.assertEqual((board["counts"]["running"], board["counts"]["completed"]), (1, 0)) + self.assertIsNone(board["mean_reward"]) + self.assertEqual(board["totals"]["cost_usd"], 0.25) + + def test_manual_reruns_keep_the_previous_result_in_the_totals_until_replaced(self): + for outcome, reward in (("resolved", 1.0), ("unresolved", 0.0), ("scored", 0.5)): + with self.subTest(outcome=outcome): + lines = [ev(1, "job.start", trial=None, n_total=1, agents=["agent"]), + ev(2, "trial.phase", task="task", agent="agent", phase="agent_run"), + ev(3, "trial.end", outcome=outcome, reward=reward, cost_usd=0.25), + ev(4, "job.end", trial=None), + ev(5, "job.start", trial=None, n_total=1, agents=["agent"], tasks=["task"])] + before = board_of(*lines).snapshot() + lines += [ev(6, "trial.queued", position=0), ev(7, "trial.phase", phase="agent_run")] + during = board_of(*lines).snapshot() + self.assertEqual((during["state"], during["trials"][0]["state"]), ("running", "running")) + self.assertEqual(during["counts"]["running"], 1) + for key in ("completed", "resolved", "unresolved", "scored", "errored", "cancelled"): + self.assertEqual(during["counts"].get(key), before["counts"].get(key), key) + self.assertEqual(during["mean_reward"], reward) + self.assertEqual(during["totals"]["cost_usd"], 0.25) + self.assertEqual(during["lanes"][0]["mean_reward"], reward) + lines += [ev(8, "trial.progress", cost_usd=0.03)] + self.assertAlmostEqual(board_of(*lines).snapshot()["totals"]["cost_usd"], 0.28) + lines += [ev(9, "trial.end", outcome="unresolved", reward=0.0, cost_usd=0.03)] + after = board_of(*lines).snapshot() + self.assertEqual((after["counts"]["completed"], after["counts"]["unresolved"]), (1, 1)) + self.assertEqual((after["mean_reward"], after["lanes"][0]["mean_reward"]), (0.0, 0.0)) + self.assertAlmostEqual(after["totals"]["cost_usd"], 0.28) + def test_the_last_phase_event_wins_and_time_in_phase_is_now_minus_its_ts(self): b = board_of(ev(1, "trial.phase", phase="env_setup", timeout_sec=300), ev(2, "trial.phase", phase="agent_run", timeout_sec=540), @@ -259,6 +294,32 @@ def at(sec): return (start + timedelta(seconds=sec)).isoformat().replace("+00:00 self.assertEqual(b.totals()["cost_usd"], 0.2) # the attempt before was paid for: the board's cost counts it self.assertIsNone(b.tokens_per_sec()) # one report of the attempt's own: no baseline, no rate + def test_a_job_begun_again_after_its_end_runs_until_its_next_end(self): + # chosen tasks of an ended job run again in it (the standard's rerun): a second job.start over the job's + # whole count, the task's next attempt, a second job.end + start = datetime(2026, 11, 18, 9, 0, 0, tzinfo=timezone.utc) + def at(sec): return (start + timedelta(seconds=sec)).isoformat().replace("+00:00", "Z") + lines = [ev(1, "job.start", trial=None, ts=at(0), n_total=2, n_concurrent=2), + ev(2, "trial.phase", trial="a", ts=at(0), phase="agent_run"), + ev(3, "trial.phase", trial="b", ts=at(0), phase="agent_run"), + ev(4, "trial.end", trial="a", ts=at(10), outcome="resolved", reward=1.0), + ev(5, "trial.end", trial="b", ts=at(12), outcome="unresolved", reward=0.0, cost_usd=0.2), + ev(6, "job.end", trial=None, ts=at(13)), + ev(7, "job.start", trial=None, ts=at(500), n_total=2, n_concurrent=1), + ev(8, "trial.queued", trial="b", ts=at(500), position=0), + ev(9, "trial.phase", trial="b", ts=at(501), phase="agent_run")] + b = board_of(*lines, now=start + timedelta(seconds=510)) + self.assertEqual(b.state, "running") + c = b.counts() + self.assertEqual((c["total"], c["running"], c["completed"], c["pending"]), (2, 1, 1, 0)) + card = next(t for t in b.snapshot()["trials"] if t["trial"] == "b") + self.assertEqual((card["state"], card["attempt"], card["retried"]), ("running", 2, ["unresolved"])) + lines += [ev(10, "trial.end", trial="b", ts=at(520), outcome="resolved", reward=1.0, cost_usd=0.1), + ev(11, "job.end", trial=None, ts=at(521))] + b = board_of(*lines, now=start + timedelta(seconds=600)) + self.assertEqual((b.state, b.counts()["completed"]), ("finished", 2)) + self.assertAlmostEqual(b.totals()["cost_usd"], 0.3) # both attempts paid for + def test_eta_counts_down_while_a_trial_runs(self): # the same median, read later: a running trial's time so far comes off its share, so the ETA moves start = datetime(2026, 9, 12, 18, 0, 0, tzinfo=timezone.utc) diff --git a/app/tests/test_locomo_rag.py b/app/tests/test_locomo_rag.py index beb6e227..74ebadb1 100644 --- a/app/tests/test_locomo_rag.py +++ b/app/tests/test_locomo_rag.py @@ -107,6 +107,21 @@ def close(self): self.p.stdout.close() +class Listing(unittest.TestCase): + def test_describe_gives_question_text_and_excludes_category_five(self): + with tempfile.TemporaryDirectory() as root: + driver = Driver(root, {}) + try: + ids = driver.ask(op="units", dataset="locomo10")["units"] + got = driver.ask(op="describe", dataset="locomo10") + finally: + driver.close() + self.assertEqual(got, {"units": {"conv-1:0": {"title": "What did A say?", "text": "What did A say?", + "categories": {"category": "4"}}}}) + self.assertEqual(list(got["units"]), ids) + self.assertIs(BENCH["driver"].get("describe"), True) + + class Retrieval(unittest.TestCase): def run_unit(self, **options): with tempfile.TemporaryDirectory() as root: diff --git a/app/tests/test_longmemeval_setups.py b/app/tests/test_longmemeval_setups.py index e3959b4c..a1d6f7b5 100644 --- a/app/tests/test_longmemeval_setups.py +++ b/app/tests/test_longmemeval_setups.py @@ -166,6 +166,18 @@ def run_driver(self, reqs, options, keep=None, questions=None, files=None): out = subprocess.run([sys.executable, DRIVER], input=lines, capture_output=True, text=True, env=env, timeout=60) return [json.loads(ln) for ln in out.stdout.splitlines()] + def test_describe_gives_question_text_and_respects_the_type_filter(self): + for kind in ("all", "knowledge-update"): + with self.subTest(kind=kind): + got = self.run_driver([{"op": "units", "dataset": "longmemeval_oracle"}, + {"op": "describe", "dataset": "longmemeval_oracle"}], + {"question_type": kind}, questions=self.QUESTIONS) + expected = {qid: {"title": "Q?", "text": "Q?", "categories": {"question_type": category}} + for qid, category in self.QUESTIONS if kind == "all" or category == kind} + self.assertEqual(got[1], {"units": expected}) + self.assertEqual(list(got[1]["units"]), got[0]["units"]) + self.assertIs(BENCH["driver"].get("describe"), True) + def test_the_original_runs_run_generation_as_the_script_does_and_scores_with_evaluate_qa(self): judge = {"model": "gpt-4o-2024-08-06", "base_url": "http://judge/v1", "key": "k"} got = self.run_driver([ diff --git a/app/tests/test_migrate.py b/app/tests/test_migrate.py index 1de42710..60ff0db5 100644 --- a/app/tests/test_migrate.py +++ b/app/tests/test_migrate.py @@ -9,6 +9,7 @@ from unittest.mock import patch from nullius import migrate, paths, settings +from nullius.standard.runner import sets class Migration(unittest.TestCase): @@ -80,6 +81,26 @@ def test_workspaces_judgements_and_custom_entries_survive_without_moving_raw_run self.assertEqual(settings.in_file(paths.settings_file())["RUNS_DIR"], str(self.checkout / "runs")) self.assertTrue((workspace / "workspace.json").exists()) + def test_task_sets_and_the_lists_of_one_made_before_survive_migration(self): + source = self.checkout / "app/nullius/catalogue" + bench = {"key": "fakebench", "datasets": [{"id": "all"}]} + entry = sets.create(bench, "dev", dataset="all", units=["good"], root=str(source)) + # a set made before sets were frozen holds a second list + entry["revisions"].append({"revision": 2, "date": "2026-11-18T10:00:00Z", "note": "one more", "units": ["good", "model"], + "hash": sets.content_hash("fakebench", "all", ["good", "model"])}) + sets.write(entry, root=str(source)) + entry = sets.load("fakebench", "dev", str(source)) + original = Path(sets.path_of("fakebench", "dev", str(source))).read_bytes() + code, output = self.run_cli() + self.assertEqual(code, 0, output) + self.assertIn("catalogue_entries: 1", output) + self.assertFalse(self.profile.exists()) + self.assertEqual(self.run_cli("--apply")[0], 0) + self.assertEqual(sets.load("fakebench", "dev"), entry) + dest = Path(sets.path_of("fakebench", "dev")) + self.assertEqual(dest.read_bytes(), original) + self.assertEqual(Path(sets.path_of("fakebench", "dev", str(source))).read_bytes(), original) + def test_licences_are_opt_in_and_copied_privately(self): secret = self.root / "legacy-secrets/bench" secret.mkdir(parents=True) diff --git a/app/tests/test_parse.py b/app/tests/test_parse.py index 71f40f79..e09344ea 100644 --- a/app/tests/test_parse.py +++ b/app/tests/test_parse.py @@ -380,6 +380,23 @@ class SurfacedFields(unittest.TestCase): """The reader exposes agent versions and job statistics, including the running-trial count that distinguishes active jobs from completed ones.""" + def test_planned_tasks_run_distinguishes_ids_with_the_same_display_name(self): + units = ["group/1", "group-1", "t2", "t3", "t4", "t5"] + with tempfile.TemporaryDirectory() as tmp: + _write_json(os.path.join(tmp, "config.json"), + {"standard": {"benchmark": "fakebench", "repeat": 2}, + "datasets": [{"name": "fakebench/all", "n_tasks": 6}]}) + for k, unit in enumerate(units): + for attempt in (1, 2): + name = f"{unit.replace('/', '-')}__u{k:04d}r{attempt}" + _write_json(os.path.join(tmp, name, "result.json"), + {"task_name": f"fakebench/{unit.replace('/', '-')}", "trial_name": name, + "standard": {"unit": unit}, "verifier_result": {"rewards": {"reward": 1}}}) + parsed = parse.parse_job(tmp) + self.assertEqual(parsed.n_tasks_run, k + 1) + self.assertEqual(len(parsed.trials), (k + 1) * 2) + self.assertEqual(parsed.n_tasks_run, parsed.n_tasks) + def _job(self, result): with tempfile.TemporaryDirectory() as tmp: _write_json(os.path.join(tmp, "result.json"), result) diff --git a/app/tests/test_part_run_recipe.py b/app/tests/test_part_run_recipe.py new file mode 100644 index 00000000..2c6ac168 --- /dev/null +++ b/app/tests/test_part_run_recipe.py @@ -0,0 +1,198 @@ +"""A recipe's plan begun on a part (``start_with``): all of it, or the tasks ticked (``[ID, ...]``, the builder's +form), or from a recipe before, a number of its tasks or a task set of its dataset; compiled to ``--start-with`` +(``ids:A,B`` for the ticks), said in Review as what runs first and what stays for later, refused where the run +would refuse it; the set it begins with carried to a host, and a run there begun on it. No key, no network: the +runs are the fake benchmark's control.""" +from __future__ import annotations + +import io +import json +import os +import shutil +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.runner import payload, rerun, run, sets, units +from tests.test_task_set_recipe import NOP, ROOT, Scratch + + +class StartWith(Scratch): + def test_a_start_on_a_part_asks_nothing_at_run_and_review_counts_what_it_plans_and_begins(self): + for datasets, limit, planned, begun in ((["all", "more"], None, 8, 5), + (["all", "more"], 2, 4, 3), + (["all"], 2, 2, 1)): + with self.subTest(datasets=datasets, limit=limit): + out = self.compile(datasets=datasets, limit=limit, start_with={"all": "1"}) + self.assertEqual(out["errors"], []) + self.assertEqual(out["confirm"], "") + self.assertTrue(next(r[2] for r in out["review"] if r[1] == "Scope").startswith(f"{begun} first, {planned - begun} later")) + # every task of the datasets, with none chosen: Run asks first + self.assertTrue(self.compile(datasets=["all", "more"])["confirm"].startswith("Run all 8 tasks of Fake bench (all, more) with ")) + + def test_the_tasks_ticked_a_number_or_a_set_compile_to_the_option_and_review_says_what_runs_first(self): + sets.create(self.b, "first", dataset="all", units=["good", "slow"]) + later = "; the other 2 stay planned, to run later from the job's page" + for given, word, said in ((["slow", "good"], "ids:slow,good", "all · 2 tasks run first (the tasks ticked)" + later), + ("2", "2", "all · 2 tasks run first (the first 2)" + later), + ("set:first", "set:first", "all · 2 tasks run first (task set first)" + later)): + with self.subTest(given=given): + out = self.compile(start_with={"all": given}) + self.assertEqual(out["errors"], []) + self.assertIn(f"--dataset all --start-with {word} -j 1", out["shards"][0]["command"]) + self.assertEqual(next(r for r in out["review"] if r[1] == "Dataset")[2], said) + self.assertTrue(next(r[2] for r in out["review"] if r[1] == "Scope").startswith("2 first, 2 later")) + self.assertEqual(out["confirm"], "") + # the plan a set or a limit cuts is what is planned + sets.create(self.b, "dev", dataset="all", units=["good", "wrong", "slow"]) + out = self.compile(task_sets={"all": "dev"}, start_with={"all": ["wrong"]}) + self.assertEqual(out["errors"], []) + self.assertIn("--set dev --start-with ids:wrong", out["shards"][0]["command"]) + self.assertIn("· 1 task runs first (the tasks ticked); the other 2 stay planned", next(r for r in out["review"] if r[1] == "Dataset")[2]) + out = self.compile(task_sets={"all": "dev"}, start_with={"all": ["wrong", "good", "slow"]}) + self.assertIn("· 3 tasks run first (the tasks ticked), and nothing is left for later", next(r for r in out["review"] if r[1] == "Dataset")[2]) + out = self.compile(limit=3, start_with={"all": "1"}) + self.assertIn("--limit 3 --start-with 1", out["shards"][0]["command"]) + self.assertIn("· 1 task runs first (the first 1); the other 2 stay planned", next(r for r in out["review"] if r[1] == "Dataset")[2]) + + def test_what_the_run_would_refuse_is_refused_on_its_step(self): + sets.create(self.b, "other-ds", dataset="more", units=["good"]) + sets.create(self.b, "dev", dataset="all", units=["good"]) + sets.create(self.b, "wide", dataset="all", units=["good", "slow"]) + for kw, step, said in (({"start_with": {"all": "5"}}, "dataset", "Start with 5 tasks: all plans 4."), + ({"start_with": {"all": "0"}}, "dataset", "Start with a number of tasks of at least 1."), + ({"start_with": {"all": "set:other-ds"}}, "dataset", + "Start with: the task set other-ds is cut from the dataset more, not all."), + ({"start_with": {"all": "set:nosuch"}}, "dataset", "Fake bench has no task set nosuch to start with"), + ({"start_with": {"all": "first.txt"}}, "dataset", "Start with all of the tasks, a number of them, or a task set."), + ({"start_with": {"all": []}}, "dataset", "Start with: tick at least one task, or start with all of it."), + ({"start_with": {"all": ["a,b"]}}, "dataset", "Start with: an id holding a comma or a space cannot be ticked here"), + ({"start_with": {"all": [3]}}, "dataset", "Start with is a dataset with its tasks each."), + ({"task_sets": {"all": "dev"}, "start_with": {"all": ["good", "slow"]}}, "dataset", + "Start with: 1 of the tasks ticked are not in the task set dev."), + ({"start_with": {"more": "1"}}, "dataset", "Start with 1 is for more, a dataset not chosen."), + ({"task_sets": {"all": "dev"}, "start_with": {"all": "set:wide"}}, "dataset", + "Start with: the task set wide names 1 of all's tasks outside the task set dev."), + ({"start_with": {"all": "1"}, "where": ["local", "bench"]}, "where", + "A run begun on a part of its plan runs on one machine")): + with self.subTest(kw=kw): + out = self.compile(**kw) + self.assertIn(recipe.STEP[step], [e["step"] for e in out["errors"]], out["errors"]) + self.assertTrue(any(e["message"].startswith(said) for e in out["errors"]), out["errors"]) + + def test_the_tasks_ticked_run_first_and_the_rest_stay_planned(self): + out = self.compile(start_with={"all": ["slow", "good"]}) + jobs = self.tmp / "jobs" + command = out["shards"][0]["command"].replace('--from-run --jobs "${NULLIUS_JOBS:-jobs_standard}"', f"--jobs {jobs}") + words = command.split()[3:] + out_, err = io.StringIO(), io.StringIO() + with mock.patch.object(cli, "_bench", return_value=self.b), mock.patch.object(cli, "_exit_on_term"), \ + mock.patch.object(cli.settings, "load"), redirect_stdout(out_), redirect_stderr(err): + code = cli.main(["run", *words]) + self.assertEqual(code, 0, out_.getvalue() + err.getvalue()) + cfg = json.loads((jobs / "fake-sets" / "config.json").read_text()) + self.assertEqual(cfg["standard"]["start_with"], {"units": ["good", "slow"]}) # in the plan's order + self.assertEqual(sorted(d for d in os.listdir(jobs / "fake-sets") if "__u" in d), ["good__u0000", "slow__u0002"]) + self.assertEqual(sorted(x["unit"] for x in rerun.unfinished(str(jobs / "fake-sets")).values()), ["model", "wrong"]) + + def test_a_recipe_without_it_compiles_as_before(self): + self.assertEqual(self.compile(), self.compile(start_with={})) + self.assertNotIn("--start-with", self.compile()["shards"][0]["command"]) + + +class TicksAgainstThePlan(Scratch): + """The tasks ticked, checked again at each compile against the plan the listing in the cache gives: a tick the + plan no longer holds is refused on the Dataset step with the ids it drops. The stand-in's file has versions, so + its title (``Fake bench 1.0``) is not its label, as at a real benchmark with versions.""" + def setUp(self): + super().setUp() + profile = mock.patch.dict(os.environ, {"NULLIUS_HOME": str(self.tmp / "profile")}) # a cache of its own + profile.start() + self.addCleanup(profile.stop) + root = self.tmp / "versioned" + shutil.copytree(os.path.join(ROOT, "benchmarks", "fakebench"), root / "benchmarks" / "fakebench") + spec = json.loads((root / "benchmarks" / "fakebench" / "standard.json").read_text()) + spec.update(upstream={"license": "unknown"}, default="1.0", versions={"1.0": {}, "2.0": {}}) + (root / "benchmarks" / "fakebench" / "standard.json").write_text(json.dumps(spec)) + self.b = dict(definitions.get("benchmark", "fakebench", str(root)), controls=NOP, + datasets=[{"id": "all", "units": 4}, {"id": "more", "units": 4}]) + self.defs = {"benchmark": [self.b], "agent": [], "capability": []} + self.assertNotEqual(definitions.title(self.b), self.b["label"]) + + def test_a_tick_the_lowered_number_leaves_out_is_refused_and_a_tick_inside_passes(self): + units.listing(self.b, "all") # as the task picker lists it + out = self.compile(limit=1, start_with={"all": ["wrong"]}) + self.assertEqual([(e["step"], e.get("dropped")) for e in out["errors"]], [(recipe.STEP["dataset"], ["wrong"])]) + self.assertEqual(out["errors"][0]["message"], "Start with: tasks outside the current plan: wrong.") + runner = run.Run(self.b, definitions.control(self.b, "nop"), model="", provider="openai", + jobs_root=str(self.tmp / "jobs"), name="limited", env={}, say=lambda s: None, + limit=1, start_with={"ids": ["wrong"]}) + with self.assertRaisesRegex(run.Refused, "outside the plan of 1 task: wrong"): + runner.start() # what Run would say at its start, said at Review now + out = self.compile(limit=1, start_with={"all": ["good"]}) + self.assertEqual(out["errors"], []) + self.assertIn("--limit 1 --start-with ids:good", out["shards"][0]["command"]) + self.assertEqual(self.compile(start_with={"all": ["wrong"]})["errors"], []) + + def test_review_checks_the_listing_under_the_changed_benchmark_options(self): + self.b["options"] = {"mode": {"summary": "Tasks", "values": ["long", "short"], "default": "long"}} + rows = {"long": ["good", "wrong"], "short": ["good"]} + + def made(bench, ds, values): + return {"tasks": [{"id": i, "title": "", "text": "", "categories": {}} for i in rows[values["mode"]]], + "described": False} + with mock.patch.object(units, "_list", made): + for mode in rows: + units.listing(self.b, "all", {"mode": mode}) + with mock.patch.object(units, "_list", side_effect=AssertionError("listed again")): + self.assertEqual(self.compile(start_with={"all": ["wrong"]})["errors"], []) + out = self.compile(bench_options={"mode": "short"}, start_with={"all": ["wrong"]}) + self.assertEqual(out["errors"][0]["dropped"], ["wrong"]) + out = self.compile(bench_options={"mode": "short"}, start_with={"all": ["good"]}) + self.assertEqual(out["errors"], []) + self.assertIn("nothing is left for later", next(r[2] for r in out["review"] if r[1] == "Dataset")) + + def test_a_listing_not_in_the_cache_asks_nothing(self): + self.assertNotEqual(units.state(self.b, "all")["state"], "cached") + with mock.patch.object(units, "listing", side_effect=AssertionError("listed")): + out = self.compile(limit=1, start_with={"all": ["pasted-id"]}) + self.assertEqual(out["errors"], []) # Run checks them at its start + self.assertIn("--start-with ids:pasted-id", out["shards"][0]["command"]) + + def test_ids_pasted_for_a_listing_that_needs_the_full_environment_are_accepted(self): + with mock.patch.object(units, "state", return_value={"state": "full", "fetch": [], "reason": ""}), \ + mock.patch.object(units, "listing", side_effect=AssertionError("listed")): + out = self.compile(start_with={"all": ["pasted-a", "pasted-b"]}) + self.assertEqual(out["errors"], []) + self.assertIn("--start-with ids:pasted-a,pasted-b", out["shards"][0]["command"]) + + +class OnAHost(Scratch): + def test_the_snapshot_carries_the_set_begun_with_and_the_run_there_plans_the_whole(self): + entry = sets.create(self.b, "first", dataset="all", units=["wrong"]) + r = self.recipe(start_with={"all": "set:first"}) + self.assertEqual(payload.recipe_sets(r), [("fakebench", "first")]) + self.assertEqual(payload.recipe_sets(self.recipe(start_with={"all": "2"})), []) + empty = self.tmp / "empty-package" + shutil.copytree(Path(payload.PACKAGE), empty, ignore=shutil.ignore_patterns("__pycache__", "catalogue", "kits")) + _, here = payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), sets=payload.recipe_sets(r)) + run_catalogue = self.tmp / "host" / "catalogue" + shutil.copytree(Path(here) / "app/nullius/catalogue", run_catalogue) + shutil.rmtree(self.cat) + jobs = self.tmp / "host" / "jobs" + out, err = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(run_catalogue)}), \ + mock.patch.object(cli, "_bench", return_value=self.b), mock.patch.object(cli, "_exit_on_term"), \ + mock.patch.object(cli.settings, "load"), redirect_stdout(out), redirect_stderr(err): + code = cli.main(["run", "fakebench", "nop", "--dataset", "all", "--start-with", "set:first", "-j", "1", + "--name", "begun", "--jobs", str(jobs)]) + self.assertEqual(code, 0, out.getvalue() + err.getvalue()) + cfg = json.loads((jobs / "begun" / "config.json").read_text()) + self.assertEqual(cfg["standard"]["start_with"], {"task_set": sets.record(entry), "units": ["wrong"]}) + self.assertEqual(cfg["datasets"][0]["n_tasks"], 4) + self.assertEqual(sorted(d for d in os.listdir(jobs / "begun") if "__u" in d), ["wrong__u0001"]) + self.assertEqual(len(rerun.unfinished(str(jobs / "begun"))), 3) + self.assertIn("1 of 4 planned tasks run; the rest in this job: nullius standard rerun", out.getvalue()) diff --git a/app/tests/test_standard_part.py b/app/tests/test_standard_part.py new file mode 100644 index 00000000..b8bb124f --- /dev/null +++ b/app/tests/test_standard_part.py @@ -0,0 +1,225 @@ +"""A run planned on a whole and begun on a part of it (``run --start-with``), the rest run later in the same job +by ``rerun``, against a fake benchmark of six tasks and the fake agent. No key, no network: the provider is a +local fake endpoint.""" +from __future__ import annotations + +import io +import json +import os +import shutil +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path + +from nullius.runs import classify, cli as runs_cli, live, parse +from nullius.standard import cli as std_cli +from nullius.standard.contract import definitions +from nullius.standard.runner import rerun, run, sets +from tests import test_standard_rerun as base + +ROOT = base.ROOT +UNITS = [f"t{i}" for i in range(6)] +SIX_DRIVER = '''from nullius.standard.protocols.jsonl import serve +serve({"units": lambda dataset: {"units": [f"t{i}" for i in range(6)]}, "setup": lambda unit, dir: {"prompt": "model hi"}, + "score": lambda unit, dir, transcript, answer: {"reward": 1.0, "passed": True, "detail": {}}}) +''' +# what differs between two runs of the same plan by their clocks and their names alone +VOLATILE = {"started_at", "finished_at", "at", "found_at", "id", "job_name", "job", "date", "seconds", "ts"} + + +def steady(doc): + """A record with what a clock or a job's name puts in it left out.""" + if isinstance(doc, dict): + return {k: steady(v) for k, v in doc.items() if k not in VOLATILE and not k.endswith("_sec") and not k.endswith("_ms")} + if isinstance(doc, list): + return [steady(v) for v in doc] + return doc + + +class RecordComparison(unittest.TestCase): + def test_cost_changes_are_not_discarded(self): + self.assertNotEqual(steady({"agent_result": {"cost_usd": base.CALL}}), + steady({"agent_result": {"cost_usd": 42}})) + + +class PartTest(unittest.TestCase): + setUpClass, tearDownClass = base.RerunTest.__dict__["setUpClass"], base.RerunTest.__dict__["tearDownClass"] + setUp, read = base.RerunTest.setUp, base.RerunTest.read + + def catalogue(self) -> str: + root = os.path.join(self.tmp, "catalogue") + if not os.path.isdir(root): + shutil.copytree(ROOT, root) + bench = Path(root, "benchmarks", "fakebench") + (bench / "driver.py").write_text(SIX_DRIVER) + spec = json.loads((bench / "standard.json").read_text()) + spec["datasets"] = [{"id": "all", "units": 6}, {"id": "other", "units": 6}] + (bench / "standard.json").write_text(json.dumps(spec)) + agent = Path(root, "agents", "fake", "agent.json") + agent.write_text(agent.read_text().replace("{here}/../../..", os.path.dirname(ROOT))) + return root + + def plan(self, name="job", lines=None, **kw) -> str: + root = self.catalogue() + b, o = definitions.get("benchmark", "fakebench", root), definitions.get("agent", "fake", root) + return run.run(b, o, model="m-1", provider="custom", jobs_root=self.tmp, env=self.env, + say=(lines.append if lines is not None else lambda s: None), unsandboxed=True, name=name, + concurrency=2, dataset="all", prices=base.PRICES, **kw) + + def again(self, job_dir, ids, **kw) -> dict: + return rerun.rerun(job_dir, ids, env=self.env, say=lambda s: None, root=self.catalogue(), **kw) + + def a_set(self, name, units, dataset="all") -> dict: + b = definitions.get("benchmark", "fakebench", self.catalogue()) + entry = sets.create(b, name, dataset=dataset, units=units, root=os.path.join(self.tmp, "sets")) + return {"task_set": sets.record(entry, sets.revision(entry)), "dataset": entry["dataset"]} + + def units_file(self, units) -> dict: + path = os.path.join(self.tmp, "first.txt") + Path(path).write_text("\n".join(units) + "\n") + return {"units_file": run.units_file(path)} + + def show(self, job_dir) -> tuple: + out = io.StringIO() + with redirect_stdout(out): + runs_cli.main(["show", os.path.dirname(job_dir), os.path.basename(job_dir)]) + return out.getvalue(), runs_cli.job_row(parse.parse_job(job_dir)) + + def test_a_plan_of_six_begun_on_two_by_a_count_a_file_and_a_set(self): + for how, given in (("count", {"count": 2}), ("file", self.units_file(["t3", "t1"])), + ("set", self.a_set("first-two", ["t1", "t3"])), ("ids", {"ids": ["t3", "t1"]})): + with self.subTest(how=how): + lines = [] + job_dir = self.plan(name=f"job-{how}", start_with=given, lines=lines) + cfg, res = self.read(job_dir, "config.json"), self.read(job_dir, "result.json") + part = ["t0", "t1"] if how == "count" else ["t1", "t3"] # in the plan's order + self.assertEqual(cfg["datasets"][0]["n_tasks"], 6) # the plan is the whole + self.assertEqual(cfg["standard"]["start_with"]["units"], part) + self.assertEqual(set(cfg["standard"]["start_with"]) - {"units"}, {"count": {"count"}, "file": {"units_file"}, + "set": {"task_set"}, "ids": set()}[how]) + self.assertEqual(res["n_total_trials"], 6) + self.assertNotIn("budget", res) + self.assertEqual([n for n, _ in rerun.planned(job_dir)], [f"t{i}__u{i:04d}" for i in range(6)]) + self.assertEqual(sorted(x["unit"] for x in rerun.unfinished(job_dir).values()), sorted(set(UNITS) - set(part))) + j = parse.parse_job(job_dir) + self.assertEqual((len(j.trials), j.n_planned, j.n_tasks, j.n_tasks_run, j.state), (2, 6, 6, 2, "finished")) + self.assertEqual(j.start_with, {"by": how, "units": 2, + "name": {"count": "", "file": "first.txt", "set": "first-two", "ids": "the tasks chosen"}[how]}) + self.assertEqual(j.raw_solve_rate, 1.0) # over the tasks run + text, row = self.show(job_dir) + self.assertIn("2 trial(s) of 6 planned", text) + self.assertIn("begun on a part: 2 of 6 planned tasks run; the rates are over those run", text) + self.assertEqual((row["state"], row["n_trials"], row["n_planned"], row["n_tasks"], row["n_tasks_run"]), + ("finished", 2, 6, 6, 2)) + self.assertEqual(row["start_with"], j.start_with) + self.assertEqual(row["mean_score"], j.mean_score) + self.assertIn("2 of 6 planned tasks run; the rest in this job: nullius standard rerun", lines[-1]) + board = live.load(live.feed_path(job_dir)).snapshot() + self.assertEqual((board["state"], board["counts"]["total"], board["counts"]["completed"], + board["counts"].get("not_run")), ("finished", 6, 2, 4)) + + def test_two_more_by_name_then_the_rest_read_as_a_job_run_whole(self): + part = self.plan(name="part", start_with={"count": 2}) + got = self.again(part, ["t3", "t2"], reason="two more") + self.assertEqual([x["unit"] for x in got["begun"]], ["t3", "t2"]) + self.assertEqual(parse.parse_job(part).n_tasks_run, 4) + got = self.again(part, [], every_unfinished=True) + self.assertEqual([x["unit"] for x in got["begun"]], ["t4", "t5"]) + whole = self.plan(name="whole") + j, w = parse.parse_job(part), parse.parse_job(whole) + self.assertEqual((len(j.trials), j.n_planned, j.n_tasks_run, j.n_resolved, j.state), (6, 6, 6, 6, "finished")) + self.assertEqual({t.trial_name: t.outcome for t in j.trials}, {t.trial_name: t.outcome for t in w.trials}) + self.assertEqual(self.read(part, "result.json")["stats"]["n_cancelled_trials"], 0) + # the records, but for the parts' own (start_with, the re-runs and their summary, each later trial's mark) + cfg = self.read(part, "config.json") + del cfg["standard"]["start_with"] + self.assertEqual(steady(cfg), steady(self.read(whole, "config.json"))) + res = self.read(part, "result.json") + self.assertEqual([len(r["begun"]) for r in res.pop("reruns")], [2, 2]) + res.pop("standard") + self.assertEqual(steady(res), steady(self.read(whole, "result.json"))) + for t in w.trials: + mine = self.read(part, t.trial_name, "result.json") + self.assertEqual(mine["standard"].pop("rerun", {}).get("begun", True), True) + self.assertEqual(steady(mine), steady(self.read(whole, t.trial_name, "result.json")), t.trial_name) + self.assertEqual(sorted(os.listdir(part)), sorted(os.listdir(whole))) + + def test_two_attempts_each_a_task_begun_gets_both(self): + job_dir = self.plan(start_with={"count": 2}, repeat=2) + j = parse.parse_job(job_dir) + self.assertEqual((len(j.trials), j.n_planned, j.n_tasks_run), (4, 12, 2)) + self.assertEqual(sorted(t.trial_name for t in j.trials), + ["t0__u0000r1", "t0__u0000r2", "t1__u0001r1", "t1__u0001r2"]) + got = self.again(job_dir, [], count=1) + self.assertEqual(sorted(x["trial"] for x in got["begun"]), ["t2__u0002r1", "t2__u0002r2"]) + got = self.again(job_dir, [], task_set=self.a_set("late", ["t5", "t0"])) + self.assertEqual(sorted(x["trial"] for x in got["begun"]), ["t5__u0005r1", "t5__u0005r2"]) # t0 had run + self.assertEqual(sorted({x["unit"] for x in rerun.unfinished(job_dir).values()}), ["t3", "t4"]) + lines = [] + got = rerun.rerun(job_dir, [], task_set=self.a_set("done", ["t0"]), env=self.env, say=lines.append, + root=self.catalogue()) + self.assertEqual((got["trials"], lines), ([], ["nothing to run: every task of the set done job planned has a result"])) + + def test_the_refusals_start_nothing(self): + root = self.catalogue() + cases = [({"count": 7}, "--start-with 7: more tasks than the plan holds, 6 tasks of all"), + (self.units_file(["t1", "t9"]), "--start-with first.txt names 1 task outside the plan of 6 tasks: t9"), + (self.a_set("elsewhere", ["t1"], dataset="other"), + "--start-with: the task set elsewhere is cut from the dataset other, and the run plans all")] + for n, (given, why) in enumerate(cases): + with self.subTest(why=why): + with self.assertRaises(run.Refused) as e: + self.plan(name=f"no-{n}", start_with=given) + self.assertIn(why, str(e.exception)) + folder = os.path.join(self.tmp, f"no-{n}") + self.assertFalse(os.path.exists(folder) and any(x.startswith("t") for x in os.listdir(folder))) + with self.assertRaises(run.Refused): + self.plan(name="no-shard", start_with={"count": 1}, shard=(1, 2)) + job_dir = self.plan(start_with={"count": 2}) + whole = base.digest(job_dir) + for kw, why in (({"count": 5}, "--next 5: 4 tasks of the plan are left to run"), + ({"count": 0}, "--next 0: a whole number of tasks, at least 1"), + ({"task_set": self.a_set("wide", ["t1"], dataset="other")}, + "the task set wide is cut from the dataset other, and job planned all")): + with self.subTest(why=why): + with self.assertRaises(run.Refused) as e: + self.again(job_dir, [], **kw) + self.assertIn(why, str(e.exception)) + self.assertEqual(base.digest(job_dir), whole) + # a set naming a task the job did not plan: a plan cut by --limit + limited = self.plan(name="limited", start_with={"count": 1}, limit=3) + with self.assertRaises(run.Refused) as e: + self.again(limited, [], task_set=self.a_set("Beyond the plan", ["t2", "t4"])) + self.assertIn("the task set Beyond the plan names 1 task limited did not plan: t4", str(e.exception)) + + def test_the_command_line_names_the_part_four_ways(self): + b = definitions.get("benchmark", "fakebench", self.catalogue()) + self.assertEqual(std_cli.start_with(b, "3"), {"count": 3}) + Path(self.tmp, "ids.txt").write_text("t2\n# a comment\nt0\n") + self.assertEqual(std_cli.start_with(b, os.path.join(self.tmp, "ids.txt"))["units_file"]["units"], ["t2", "t0"]) + with self.assertRaises(run.Refused) as e: + std_cli.start_with(b, os.path.join(self.tmp, "none.txt")) + self.assertIn("--start-with", str(e.exception)) + with self.assertRaises(run.Refused): + std_cli.start_with(b, "0") + entry = sets.create(b, "quick", dataset="all", units=["t4"]) # the profile's own catalogue + got = std_cli.start_with(b, "set:quick@1") + self.assertEqual((got["dataset"], got["task_set"]["units"], got["task_set"]["id"]), ("all", ["t4"], entry["id"])) + with self.assertRaises(sets.NotFound): + std_cli.start_with(b, "set:nothing") + # ids inline, as the run builder writes them + self.assertEqual(std_cli.start_with(b, "ids:t2,t0"), {"ids": ["t2", "t0"]}) + for bad, said in (("ids:", "ids separated by commas"), ("ids:t1,,t2", "ids separated by commas"), + ("ids:t1, t2", "with a space around it"), ("ids:t1,t1", "t1 given more than once")): + with self.subTest(bad=bad), self.assertRaises(run.Refused) as e: + std_cli.start_with(b, bad) + self.assertIn(said, str(e.exception)) + # an id outside the plan refuses the run before any unit, naming it + with self.assertRaises(run.Refused) as e: + self.plan(name="outside", start_with={"ids": ["t1", "nope"]}) + self.assertIn("--start-with ids:t1,nope names 1 task outside the plan of 6 tasks: nope", str(e.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_standard_rerun.py b/app/tests/test_standard_rerun.py new file mode 100644 index 00000000..dda9eccb --- /dev/null +++ b/app/tests/test_standard_rerun.py @@ -0,0 +1,877 @@ +"""Chosen tasks of an ended job run again in that job (``standard/runner/rerun.py``), +against the fake benchmark and agent: the new try takes the trial's place, +the earlier tries stay readable, the job's result is recomputed and each +re-run recorded. No key, no network: the provider is a local fake endpoint.""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import tempfile +import threading +import unittest +from http.server import ThreadingHTTPServer +from pathlib import Path +from unittest import mock + +from nullius.harbor import feed +from nullius.runs import classify, live, parse +from nullius.standard.calls import ledger +from nullius.standard.contract import definitions +from nullius.standard.protocols import acp +from nullius.standard.requirements import install +from nullius.standard.runner import job, merge, pace as pacing, rerun, run +from tests import test_standard_run as base + +ROOT = base.ROOT +UNITS = {"name": "units.txt", "sha256": "0" * 64, "units": ["good", "wrong", "model"]} +PRICES = {"m-1": {"input": 1.0, "output": 10.0, "max_output": 10}} # a call: 11 in, 3 out, 0.000041 USD +CALL = 0.000041 +usd = rerun.ledgers.usd + + +def digest(root) -> dict: + root = Path(root) + return {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(root.rglob("*")) if p.is_file()} + + +def said(text): + """The fake agent's prompt, turned into another for the re-run's tries (``acp.Client.prompt``).""" + real = acp.Client.prompt + + def prompt(client, sid, given, timeout=600): + for want in text.get(given, [given]): + out = real(client, sid, want, timeout=timeout) + return out + return mock.patch.object(acp.Client, "prompt", prompt) + + +class RerunRecords(unittest.TestCase): + def setUp(self): + self.tmp = Path(self.enterContext(tempfile.TemporaryDirectory())) + self.root = self.tmp / "catalogue" + dest = self.root / "benchmarks/fakebench" + shutil.copytree(Path(ROOT) / "benchmarks/fakebench", dest) + spec = json.loads((dest / "standard.json").read_text()) + spec["controls"] = {"nop": {"source": "nullius", "from": "Empty answer."}} + (dest / "standard.json").write_text(json.dumps(spec)) + self.bench = definitions.get("benchmark", "fakebench", str(self.root)) + self.other = definitions.control(self.bench, "nop") + self.enterContext(mock.patch.object(install, "HOME", str(self.tmp / "installs"))) + + def job(self): + return Path(run.run(self.bench, self.other, model="", provider="custom", jobs_root=str(self.tmp), + name="job", concurrency=1, units_file=dict(UNITS, units=["good", "wrong"]), + env={}, say=lambda s: None)) + + def test_a_job_never_run_again_keeps_the_result_a_run_writes(self): + # Freeze the clock and transport. The runner still schedules and writes every trial. + with mock.patch.object(run.time, "time", return_value=1767225600.0), \ + mock.patch.object(run.Run, "known_models"), \ + mock.patch.object(run.Run, "unit_relay", return_value=None), \ + mock.patch.object(run.Run, "drive_agent", return_value=("", None, {})), \ + mock.patch.object(run.Run, "benchmark_calls", return_value=[{"status": 200, "reply": {}}]): + path = Path(run.run(self.bench, definitions.get("agent", "fake", ROOT), model="m-1", provider="custom", + jobs_root=str(self.tmp), name="job", units_file=UNITS, prices=PRICES, concurrency=2, + env={"MODEL_API_URL": "http://127.0.0.1:1/v1", "MODEL_API_KEY": "fake"}, + unsandboxed=True, say=lambda s: None)) + expected = Path(__file__).parent / "fixtures/standard/ordinary-result.json" + self.assertEqual(json.loads((path / "result.json").read_text()), json.loads(expected.read_text())) + self.assertFalse((path / "retried").exists()) + + def test_a_linked_archive_is_refused_before_any_trial_moves(self): + path = self.job() + outside = self.tmp / "outside" + outside.mkdir() + (path / "retried").symlink_to(outside, target_is_directory=True) + before = digest(path) + for exists in (True, False): + with self.subTest(target_exists=exists): + if not exists: + outside.rmdir() + with self.assertRaisesRegex(run.Refused, "retried.*link"): + rerun.rerun(str(path), ["good", "wrong"], root=str(self.root), env={}, say=lambda s: None) + self.assertEqual(digest(path), before) + self.assertEqual(list(outside.iterdir()) if outside.exists() else [], []) + self.assertEqual(outside.exists(), exists) + self.assertTrue((path / "retried").is_symlink()) + + def test_a_no_result_marker_replaces_links_without_writing_their_target(self): + path = self.job() + outside = self.tmp / "evidence.bin" + outside.write_bytes(b"\x00original evidence\xff") + for unit, link in (("good", os.link), ("wrong", os.symlink)): + name = next(n for n, u in rerun.planned(str(path)) if u == unit) + (path / name / "result.json").unlink() + link(outside, path / name / rerun.NO_RESULT) + with self.subTest(link=link.__name__): + rerun.rerun(str(path), [unit], root=str(self.root), env={}, say=lambda s: None) + kept = path / "retried" / f"{name}.try-1" / rerun.NO_RESULT + self.assertEqual(outside.read_bytes(), b"\x00original evidence\xff") + self.assertFalse(kept.is_symlink()) + self.assertEqual(kept.stat().st_mode & 0o777, 0o644) + self.assertNotEqual(kept.stat().st_ino, outside.stat().st_ino) + self.assertIsNone(json.loads(kept.read_text())["result"]) + + def test_unfinished_counts_interruptions_before_starting_and_keeps_verdicts(self): + path = Path(run.run(self.bench, self.other, model="", provider="custom", jobs_root=str(self.tmp), + name="job", concurrency=1, repeat=3, units_file=dict(UNITS, units=["good", "wrong"]), + env={}, say=lambda s: None)) + names = [name for name, _ in rerun.planned(str(path))] + for name, error in zip(names[:4], (None, "NonZeroAgentExitCodeError", "SpendingCapError", run.CANCELLED)): + result = path / name / "result.json" + res = json.loads(result.read_text()) + res["exception_info"] = {"exception_type": error} if error else None + res["verifier_result"] = None if error else {"rewards": {"score": 0.5}} + result.write_text(json.dumps(res)) + shutil.rmtree(path / names[4]) + (path / names[5] / "result.json").unlink() + verdicts = {name: digest(path / name) for name in names[:2]} + lines = [] + ready = run.Run.ready + + def check_before_start(r): + self.assertEqual(lines, ["unfinished: 2 no result, 1 spending cap, 1 stopped"]) + return ready(r) + + with mock.patch.object(run.Run, "ready", check_before_start): + got = rerun.rerun(str(path), [], every_unfinished=True, root=str(self.root), env={}, say=lines.append) + self.assertEqual(got["trials"], names[2:]) + self.assertEqual([entry["trial"] for entry in got["begun"]], [names[4]]) + self.assertEqual(got["no_result"], [names[5]]) + self.assertEqual({name: digest(path / name) for name in names[:2]}, verdicts) + + def test_stop_emits_cancellation_before_restoring_the_previous_try(self): + path = self.job() + name = "good__u0000" + result = path / name / "result.json" + original = json.loads(result.read_text()) + original["agent_result"]["cost_usd"] = 0.25 + result.write_text(json.dumps(original)) + writer = feed.Writer(str(path / "events.jsonl"), "job") + writer.seq = rerun._last_seq(str(path / "events.jsonl")) + writer.emit("trial.end", name, outcome="unresolved", reward=0.0, cost_usd=0.25) + + def stop(r, *args): + r._stopped.set() + raise OSError("the control was stopped") + + with mock.patch.object(run.Run, "control_answer", stop): + rerun.rerun(str(path), ["good"], root=str(self.root), env={}, say=lambda s: None) + events = live.read_events(path / "events.jsonl").events + ends = [e.data for e in events if e.event == "trial.end" and e.trial == name] + self.assertEqual([e["outcome"] for e in ends[-2:]], ["cancelled", "unresolved"]) + self.assertTrue(ends[-1]["back"]) + self.assertEqual(json.loads(result.read_text()), original) + self.assertFalse((path / "retried").exists()) + board = live.fold(events).snapshot() + card = next(t for t in board["trials"] if t["trial"] == name) + self.assertEqual((board["state"], card["state"], card["outcome"]), ("finished", "done", "unresolved")) + self.assertEqual((card.get("attempt", 1), board["totals"]["cost_usd"]), (1, 0.25)) + + +class RerunTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.up = ThreadingHTTPServer(("127.0.0.1", 0), base.Echo) + threading.Thread(target=cls.up.serve_forever, daemon=True).start() + cls.env = {"MODEL_API_URL": f"http://127.0.0.1:{cls.up.server_address[1]}/v1", "MODEL_API_KEY": "sk-real"} + + @classmethod + def tearDownClass(cls): + cls.up.shutdown() + + def setUp(self): + self.tmp = tempfile.mkdtemp() + self._home = install.HOME + install.HOME = os.path.join(self.tmp, "home") + self.addCleanup(setattr, install, "HOME", self._home) + self.addCleanup(shutil.rmtree, self.tmp, True) + base.Echo.status, base.Echo.refused, base.Echo.limited, base.Echo.retry_after, base.Echo.listed = 200, None, 0, None, None + self.addCleanup(setattr, pacing, "FIRST", pacing.FIRST) + pacing.FIRST = 0.5 + + def job(self, name="job", **kw) -> str: + b, o = definitions.get("benchmark", "fakebench", ROOT), definitions.get("agent", "fake", ROOT) + kw = dict(dict(units_file=UNITS, prices=PRICES, concurrency=2), **kw) + return run.run(b, o, model="m-1", provider="custom", jobs_root=self.tmp, env=self.env, say=lambda s: None, + unsandboxed=True, name=name, **kw) + + def again(self, job_dir, ids, **kw) -> dict: + return rerun.rerun(job_dir, ids, env=self.env, say=lambda s: None, root=ROOT, **kw) + + def read(self, *path) -> dict: + with open(os.path.join(*path)) as f: + return json.load(f) + + def trials(self, job_dir): + j = parse.parse_job(job_dir) + return {t.trial_name.split("__")[0]: t for t in j.trials}, j + + def test_a_task_that_failed_then_passes(self): + job_dir = self.job() + before, j0 = self.trials(job_dir) + first, config = self.read(job_dir, "result.json"), Path(job_dir, "config.json").read_bytes() + self.assertEqual(before["model"].outcome, classify.FAILED_VERIFICATION) + with said({"model hi": ["model hi", "write answer.txt 42"]}): # a paid call, then the answer + got = self.again(job_dir, ["model"], reason="the provider failed") + name = before["model"].trial_name + after, j1 = self.trials(job_dir) + self.assertEqual(after["model"].outcome, classify.RESOLVED) + self.assertEqual((j0.n_resolved, j1.n_resolved), (1, 2)) + self.assertEqual(len(j1.trials), 3) # the try before is not a trial of its own + self.assertEqual([(n, t.trial_name, t.outcome) for n, t in parse.tries(after["model"])], + [(1, f"{name}.try-1", classify.FAILED_VERIFICATION), (2, name, classify.RESOLVED)]) + self.assertAlmostEqual(j0.total_cost_usd, CALL) + self.assertAlmostEqual(j1.total_cost_usd, 2 * CALL) # the job's cost: every try's + res = self.read(job_dir, "result.json") + self.assertEqual((res["started_at"], res["finished_at"], res["n_total_trials"]), + (first["started_at"], first["finished_at"], first["n_total_trials"])) + self.assertEqual(res["standard"]["passed"], 2) + self.assertEqual(res["stats"]["n_retries"], 1) + self.assertEqual(Path(job_dir, "config.json").read_bytes(), config) # the settings are the job's + (entry,) = res["reruns"] + self.assertEqual(entry["reason"], "the provider failed") + self.assertEqual(entry["trials"], [name]) + self.assertEqual(entry["replaced"], [{"trial": name, "unit": "model", "try": 1, "was": {"reward": 0.0}, "now": {"reward": 1.0}}]) + self.assertIsNone(entry["max_usd"]) + self.assertAlmostEqual(entry["spent_usd"], CALL) + self.assertNotIn("stopped", entry) + self.assertEqual(got["replaced"], entry["replaced"]) + mark = self.read(job_dir, name, "result.json")["standard"] + self.assertEqual((mark["retries"], mark["rerun"]["by"], mark["rerun"]["reason"], mark["rerun"]["replaced"]), + (1, "hand", "the provider failed", {"reward": 0.0})) + self.assertEqual(mark["rerun"]["at"], entry["at"]) + self.assertNotIn("rerun", self.read(job_dir, "retried", f"{name}.try-1", "result.json")["standard"]) + # the feed goes on numbered, and its board reads the job ended, the trial at its second attempt + with open(os.path.join(job_dir, "events.jsonl")) as f: + seqs = [json.loads(line)["seq"] for line in f] + self.assertEqual(seqs, list(range(1, len(seqs) + 1))) + board = live.load(live.feed_path(job_dir)).snapshot() + self.assertEqual(board["state"], "finished") + card = next(t for t in board["trials"] if t["trial"] == name) + self.assertEqual((card["outcome"], card["attempt"], card["retried"]), ("resolved", 2, ["unresolved"])) + self.assertFalse(rerun.running(job_dir)) + + def test_a_task_that_passed_then_fails(self): + job_dir = self.job() + before, j0 = self.trials(job_dir) + with said({"write answer.txt 42": ["write answer.txt 41"]}): + self.again(job_dir, ["good"]) + after, j1 = self.trials(job_dir) + self.assertEqual((before["good"].outcome, after["good"].outcome), (classify.RESOLVED, classify.FAILED_VERIFICATION)) + self.assertEqual((j0.n_resolved, j1.n_resolved), (1, 0)) + res = self.read(job_dir, "result.json") + self.assertEqual(res["standard"]["passed"], 0) + self.assertEqual(res["reruns"][0]["replaced"][0]["was"], {"reward": 1.0}) + self.assertNotIn("reason", res["reruns"][0]) + self.assertEqual([t.outcome for _, t in parse.tries(after["good"])], [classify.RESOLVED, classify.FAILED_VERIFICATION]) + + def test_two_tasks_one_of_them_twice_in_a_row(self): + job_dir = self.job() + before, _ = self.trials(job_dir) + with said({"write answer.txt 41": ["write answer.txt 42"]}): + self.again(job_dir, ["good", "wrong", "good"]) # a task named twice runs once + self.again(job_dir, ["wrong"], reason="once more") + after, j = self.trials(job_dir) + wrong, good = before["wrong"].trial_name, before["good"].trial_name + self.assertEqual(sorted(os.listdir(os.path.join(job_dir, "retried"))), + sorted([f"{good}.try-1", f"{wrong}.try-1", f"{wrong}.try-2"])) + self.assertEqual([(n, t.trial_name, t.outcome) for n, t in parse.tries(after["wrong"])], + [(1, f"{wrong}.try-1", classify.FAILED_VERIFICATION), (2, f"{wrong}.try-2", classify.RESOLVED), + (3, wrong, classify.FAILED_VERIFICATION)]) + self.assertEqual([t.n_retries for _, t in parse.tries(after["wrong"])], [0, 1, 2]) + reruns = self.read(job_dir, "result.json")["reruns"] + self.assertEqual([(e["trials"], [x["try"] for x in e["replaced"]]) for e in reruns], [([good, wrong], [1, 1]), ([wrong], [2])]) + self.assertEqual(reruns[1]["replaced"][0]["was"], {"reward": 1.0}) + self.assertEqual(self.read(job_dir, "result.json")["stats"]["n_retries"], 3) + self.assertEqual(j.n_retries, 3) + + def test_a_stop_during_a_rerun_puts_the_try_before_back(self): + """Stop is a SystemExit in the CLI, landing on the re-run's own thread: whether the try was waiting or + running, the trial is the one it was, and the job reads as before.""" + job_dir = self.job() + before, j0 = self.trials(job_dir) + trials = {t.trial_name: digest(os.path.join(job_dir, t.trial_name)) for t in j0.trials} + real = run.Run.unit + for where in ("waiting", "running"): + with self.subTest(where=where): + def unit(r, i, u, rr=1, retry=0, where=where): + if retry: + if where == "running": # broken off as it ran: a folder, no result + os.makedirs(os.path.join(r.job_dir, r.trial_name(i, u, rr), "workspace")) + raise SystemExit(143) + return real(r, i, u, rr, retry) + with mock.patch.object(run.Run, "unit", unit), self.assertRaises(SystemExit): + self.again(job_dir, ["model"]) + after, j1 = self.trials(job_dir) + self.assertEqual({t.trial_name: digest(os.path.join(job_dir, t.trial_name)) for t in j1.trials}, trials) + self.assertFalse(os.path.exists(os.path.join(job_dir, "retried"))) + self.assertEqual([(t.trial_name, t.outcome, t.n_retries) for t in j1.trials], + [(t.trial_name, t.outcome, t.n_retries) for t in j0.trials]) + self.assertAlmostEqual(j1.total_cost_usd, j0.total_cost_usd) + self.assertEqual(self.read(job_dir, "result.json")["reruns"][-1]["replaced"], []) + self.assertTrue(self.read(job_dir, "result.json")["reruns"][-1]["stopped"]) + self.assertFalse(rerun.running(job_dir)) + + def test_a_stop_after_the_try_began_leaves_the_board_on_the_try_before(self): + """The try had said its phase on the feed when the Stop came: the try before is back on disk, and the feed + says so, so the board reads the card's earlier outcome at its first attempt, and the job ended.""" + job_dir = self.job() + before, _ = self.trials(job_dir) + name = before["model"].trial_name + real = run.Run.unit + + def unit(r, i, u, rr=1, retry=0): + if retry: + r.feed.emit("trial.phase", r.trial_name(i, u, rr), phase="agent_run") + raise SystemExit(143) + return real(r, i, u, rr, retry) + with mock.patch.object(run.Run, "unit", unit), self.assertRaises(SystemExit): + self.again(job_dir, ["model"]) + board = live.load(live.feed_path(job_dir)).snapshot() + self.assertEqual(board["state"], "finished") + card = next(t for t in board["trials"] if t["trial"] == name) + self.assertEqual((card["state"], card["outcome"], card["reward"]), ("done", "unresolved", 0.0)) + self.assertNotIn("attempt", card) + self.assertAlmostEqual(board["totals"]["cost_usd"], CALL) # the try before, counted once + + def test_each_refusal_moves_nothing(self): + job_dir = self.job() + real = definitions.get + + def newer(kind, ref, root=None): # the agent's definition moved on to another version since the run + got = real(kind, ref, root) + return dict(got, upstream={"version": "0.2"}) if got and kind == "agent" else got + whole = digest(job_dir) + cases = [ + ("no task", [], {}, "no task named"), + ("an id it does not hold", ["model", "nosuch"], {}, "holds no trial or unit nosuch"), + ("a changed agent", ["model"], {"get": newer}, "the job ran fake with no version, and fake resolves to 0.2 now"), + ] + for what, ids, kw, words in cases: + with self.subTest(what), mock.patch.object(definitions, "get", kw.get("get", real)): + with self.assertRaises(run.Refused) as e: + self.again(job_dir, ids) + self.assertIn(words, str(e.exception)) + self.assertEqual(digest(job_dir), whole) + with self.subTest("a re-run under way"): + held = rerun._hold(job_dir) + try: + self.assertTrue(rerun.running(job_dir)) + whole = digest(job_dir) + with self.assertRaises(run.Refused) as e: + self.again(job_dir, ["model"]) + self.assertIn("is still running", str(e.exception)) + self.assertEqual(digest(job_dir), whole) + finally: + held.close() + with self.subTest("a job that has not ended"): + os.rename(os.path.join(job_dir, "result.json"), os.path.join(self.tmp, "result.json")) + whole = digest(job_dir) + with self.assertRaises(run.Refused) as e: + self.again(job_dir, ["model"]) + self.assertIn("is still running", str(e.exception)) + self.assertEqual(digest(job_dir), whole) + + def test_a_merged_job_reruns_in_place_and_leaves_its_shards_as_they_were(self): + """``merge`` hard-links the shards' files into the merged job: a re-run renames a trial's folder and writes + its new try into a new one, so no shard's file changes. A merge of shards that differed is refused.""" + shards = [self.job(f"shard-{i}", shard=(i, 2), launch="one") for i in (1, 2)] + before = {s: digest(s) for s in shards} + out = os.path.join(self.tmp, "merged") + merge.merge(shards, out) + name = next(t for t in merge._trials(out) if t.startswith("wrong__")) + with said({"write answer.txt 41": ["write answer.txt 42"]}): + self.again(out, ["wrong"]) + self.assertEqual({s: digest(s) for s in shards}, before) + self.assertEqual(self.read(out, name, "result.json")["standard"]["retries"], 1) + self.assertEqual(self.read(out, "retried", f"{name}.try-1", "result.json")["standard"]["shard_job"], + next(s for s in ("shard-1", "shard-2") if os.path.isdir(os.path.join(self.tmp, s, name)))) + self.assertEqual(self.read(out, "result.json")["standard"]["passed"], 2) + forced = os.path.join(self.tmp, "forced") + merge.merge([shards[0], self.job("other", shard=(2, 2), launch="another")], forced, force=True) + whole = digest(forced) + with self.assertRaises(run.Refused) as e: + self.again(forced, ["good"]) + self.assertIn("merges shards that differed", str(e.exception)) + self.assertEqual(digest(forced), whole) + + def test_a_rerun_stops_at_its_cap_and_records_its_spend(self): + job_dir = self.job(concurrency=1) + before, _ = self.trials(job_dir) + self.assertIsNone(rerun.budget(job_dir)) # no cap, none given: none + got = self.again(job_dir, ["model", "good"], max_usd=CALL + 0.00001, concurrency=1) + after, _ = self.trials(job_dir) + self.assertEqual(after["model"].outcome, classify.SPENDING_CAP) # cut off at what the cap had left + self.assertEqual(after["good"].n_retries, 0) # never begun: it stands as it was + self.assertEqual(got["max_usd"], CALL + 0.00001) + self.assertAlmostEqual(got["left_usd"], 0.00001) # the first run's call counted against it + self.assertEqual(got["spent_usd"], 0.0) + self.assertTrue(got["stopped"]) + self.assertEqual([x["trial"] for x in got["replaced"]], [before["model"].trial_name]) + b = self.read(job_dir, "result.json")["budget"] # the job had none: it has this one from now on + self.assertEqual((b["max_usd"], b["spent_total_usd"], b["closed"]), (CALL + 0.00001, CALL, True)) + self.assertEqual([(c["max_usd"], c["was"]) for c in b["changes"]], [(CALL + 0.00001, None)]) + self.assertEqual(self.read(job_dir, ".work", "rerun-1", "ledger", "ledger.json")["max_usd"], CALL + 0.00001 - CALL) + + +class OneBudget(unittest.TestCase): + """A job has one spending cap: each later part has what the parts before it left, a new cap holds from then on, + and a part is refused when nothing is left.""" + setUpClass, tearDownClass = RerunTest.__dict__["setUpClass"], RerunTest.__dict__["tearDownClass"] + setUp, job, again, read, trials = RerunTest.setUp, RerunTest.job, RerunTest.again, RerunTest.read, RerunTest.trials + + def ledger(self, job_dir, n): + return self.read(job_dir, ".work", f"rerun-{n}", "ledger", "ledger.json") + + def test_a_later_part_has_what_the_parts_before_it_left(self): + job_dir = self.job(concurrency=1, max_usd=0.0001) + self.assertEqual(self.read(job_dir, "result.json")["budget"]["spent_usd"], CALL) + self.assertEqual(rerun.budget(job_dir), {"max_usd": 0.0001, "spent_usd": CALL, "left_usd": 0.0001 - CALL, + "closed": False, "changed": False, "was": 0.0001}) + lines = [] + got = rerun.rerun(job_dir, ["model"], env=self.env, say=lines.append, root=ROOT) # no cap given: the job's + self.assertEqual(self.ledger(job_dir, 1)["max_usd"], 0.0001 - CALL) + self.assertEqual((got["max_usd"], got["left_usd"], got["spent_usd"]), (0.0001, 0.0001 - CALL, CALL)) + b = self.read(job_dir, "result.json")["budget"] + self.assertEqual((b["max_usd"], b["spent_usd"], b["spent_total_usd"], b["closed"]), (0.0001, CALL, 2 * CALL, False)) + self.assertNotIn("changes", b) + self.assertIn(f"the job's spending cap: 0.0001 USD, {usd(CALL)} spent, {usd(0.0001 - CALL)} left for this part", lines) + self.assertIn(f"spent {usd(CALL)} USD; the job has spent {usd(2 * CALL)} of its 0.0001 USD cap", lines) + # the third call does not fit what is left: that part stops at the cap, and the next is refused until it changes + got = self.again(job_dir, ["model"]) + self.assertEqual(self.ledger(job_dir, 2)["seen"], self.ledger(job_dir, 1)["seen"]) + self.assertTrue(got["stopped"]) + self.assertTrue(self.read(job_dir, "result.json")["budget"]["closed"]) + whole = digest(job_dir) + with self.assertRaises(run.Refused) as e: + self.again(job_dir, ["good"]) + self.assertEqual(str(e.exception), f"the job's spending cap of 0.0001 USD is spent ({usd(2 * CALL)} spent, and a call did not " + "fit what was left): raise it with --max-usd USD") + self.assertEqual(digest(job_dir), whole) + got = self.again(job_dir, ["model"], max_usd=0.001) # a new cap holds from then on + self.assertEqual(self.ledger(job_dir, 3)["max_usd"], 0.001 - 2 * CALL) + b = self.read(job_dir, "result.json")["budget"] + self.assertEqual((b["max_usd"], b["spent_total_usd"], b["closed"]), (0.001, 3 * CALL, False)) + self.assertEqual([(c["max_usd"], c["was"]) for c in b["changes"]], [(0.001, 0.0001)]) + self.again(job_dir, ["model"]) + self.assertEqual(self.ledger(job_dir, 4)["max_usd"], 0.001 - 3 * CALL) + self.assertEqual(len(self.read(job_dir, "result.json")["budget"]["changes"]), 1) # the same cap is no change + + def test_a_part_is_refused_when_the_cap_is_at_or_under_what_was_spent(self): + job_dir = self.job(concurrency=1, max_usd=0.0001) + whole = digest(job_dir) + for cap in (CALL, CALL / 2): + with self.subTest(cap=cap), self.assertRaises(run.Refused) as e: + self.again(job_dir, ["model"], max_usd=cap) + self.assertEqual(str(e.exception), f"the job's spending cap of {usd(cap)} USD is spent ({usd(CALL)} spent): " + "raise it with --max-usd USD") + self.assertEqual(digest(job_dir), whole) + for bad in (0, -1.0, float("inf")): + with self.subTest(bad=bad), self.assertRaises(run.Refused): + self.again(job_dir, ["model"], max_usd=bad) + + def test_a_job_with_no_cap_has_none_unless_one_is_given(self): + job_dir = self.job(concurrency=1) + self.again(job_dir, ["model"]) + res = self.read(job_dir, "result.json") + self.assertNotIn("budget", res) + self.assertFalse(os.path.exists(os.path.join(job_dir, ".work", "rerun-1", "ledger"))) + self.assertIsNone(res["reruns"][0]["max_usd"]) + # given one: what its uncapped parts' trials cost, every try, counts against it + self.assertEqual(rerun.budget(job_dir, cap=0.001)["spent_usd"], 2 * CALL) + + def test_a_job_recorded_before_one_budget_counts_each_part_s_spend(self): + job_dir = self.job(concurrency=1, max_usd=0.0001) + res = self.read(job_dir, "result.json") + res["reruns"] = [{"at": "2026-11-18T10:00:00+00:00", "trials": [], "replaced": [], "max_usd": 5.0, "spent_usd": 0.00002}, + {"at": "2026-11-18T11:00:00+00:00", "trials": [], "replaced": [], "max_usd": None, "spent_usd": None}] + Path(job_dir, "result.json").write_text(json.dumps(res)) + self.assertEqual(rerun.budget(job_dir), {"max_usd": 0.0001, "spent_usd": CALL + 0.00002, + "left_usd": 0.0001 - (CALL + 0.00002), "closed": False, + "changed": False, "was": 0.0001}) + j = parse.parse_job(job_dir) # and it reads as it did + self.assertEqual((j.budget["max_usd"], [r["max_usd"] for r in j.reruns]), (0.0001, [5.0, None])) + + +class BudgetAccounting(unittest.TestCase): + def setUp(self): + self.tmp = Path(self.enterContext(tempfile.TemporaryDirectory())) + self.bench = definitions.get("benchmark", "fakebench", ROOT) + self.agent = definitions.get("agent", "fake", ROOT) + for method in ("ready", "known_models", "let_go"): + self.enterContext(mock.patch.object(run.Run, method)) + self.enterContext(mock.patch.object(run.Run, "benchmark_calls", return_value=[])) + + def job(self, cap, cost, output): + path = self.tmp / "job" + path.mkdir() + job.write_config(str(path), job="job", bench=self.bench, other=self.agent, model="m-1", provider="custom", + dataset="all", units=["model"], concurrency=1, granted=True, + prices={"models": {"m-1": {"input": 0.0, "output": cost * 1e6 / output}}}) + trial = self.trial(path / "model__u0000", cost, output) + first = ledger.Ledger.create(str(path / ".work/ledger/ledger.json"), cap) + booking, _ = first.reserve(cost) + first.settle(booking, cost, model="m-1", output=output) + runner = mock.Mock(ledger=first, max_usd=cap, unit_max_usd=None, _cut=[]) + job.write_result(str(path), "job", 1, 2, [trial], 1, budget=run.Run.budget(runner, [])) + writer = feed.Writer(str(path / "events.jsonl"), "job") + writer.emit("job.start", n_total=1, tasks=["model"]) + writer.emit("trial.queued", trial["trial_name"], position=0) + writer.emit("trial.end", trial["trial_name"], outcome="resolved", reward=1) + writer.emit("job.end") + return path + + def trial(self, path, cost, output, retry=0, refused=False): + return job.write_trial(str(path), job="job", bench=self.bench, other=self.agent, model="m-1", unit="model", + t0=1, t1=2, produce=(1, 2), score=None if refused else {"reward": 1}, + exception=(ledger.ERROR, "call does not fit") if refused else None, + calls=[] if refused else [{"status": 200, "reply": {"usage": {"output": output}}, "cost_usd": cost}], + trajectory=None, retries=retry) + + def part(self, path, cost, output, amount=None): + admitted = [] + + def simulate(r, index, task, attempt, retry=0): + booking, state = r.ledger.reserve(cost if amount is None else amount, model="m-1") + admitted.append((bool(booking), state["amount"])) + if booking: + r.ledger.settle(booking, cost, model="m-1", output=output) + return self.trial(Path(r.job_dir) / r.trial_name(index, task, attempt), cost, output, + retry, refused=booking is None) + + with mock.patch.object(run.Run, "unit", simulate): + record = rerun.rerun(str(path), ["model"], root=ROOT, say=lambda s: None, + env={"MODEL_API_URL": "http://127.0.0.1:1/v1", "MODEL_API_KEY": "fake"}) + return record, admitted + + def test_small_parts_keep_unrounded_spending_under_one_cap(self): + cost, cap = 0.0000004, 0.000001 + path = self.job(cap, cost, 1) + calls = 1 + for _ in range(5): + try: + _, admitted = self.part(path, cost, 1) + except run.Refused: + break + calls += sum(sent for sent, _ in admitted) + self.assertLessEqual(calls * cost, cap + cost) + self.assertEqual(calls, 2) + result = json.loads((path / "result.json").read_text()) + self.assertEqual(result["budget"]["spent_total_usd"], calls * cost) + self.assertEqual(rerun.budget(str(path))["left_usd"], cap - calls * cost) + self.assertTrue(rerun.budget(str(path))["closed"]) + parsed = parse.parse_job(str(path)) + self.assertEqual(parsed.budget["spent_usd"], 0) + self.assertTrue(all(r["spent_usd"] == 0 for r in parsed.reruns)) + + def test_a_spend_equal_to_the_cap_but_for_float_noise_closes_the_job(self): + # eight calls of 0.1 under a cap of 0.8 add up to 0.7999999999999999: nothing is left, and no part opens on it + path = self.job(0.8, 0.1, 1) + noisy = 0.0 + for _ in range(8): + noisy += 0.1 # as a ledger adds its calls + result = json.loads((path / "result.json").read_text()) + result["budget"].update(spent_total_usd=noisy, closed=False) + (path / "result.json").write_text(json.dumps(result)) + self.assertGreater(0.8 - noisy, 0) + got = rerun.budget(str(path)) + self.assertEqual((got["closed"], got["left_usd"]), (True, 0.0)) + with self.assertRaises(run.Refused) as e: + self.part(path, 0.1, 1) + self.assertEqual(str(e.exception), "the job's spending cap of 0.80 USD is spent (0.80 spent): raise it with --max-usd USD") + + def test_next_part_inherits_cumulative_replies_once(self): + path = self.job(1.61, 1, 100) + row = {"input": 0.0, "output": 10000.0} + self.part(path, 0.01, 1, amount=lambda usual: ledger.bound({"max_tokens": 1}, b"{}", row, seen=usual)) + result = json.loads((path / "result.json").read_text()) + result["reruns"][0].pop("cumulative_replies", None) + (path / "result.json").write_text(json.dumps(result)) + record, admitted = self.part(path, 0.01, 1, amount=lambda usual: ledger.bound({}, b"{}", row, seen=usual)) + self.assertEqual(admitted, [(True, 0.51)]) + self.assertFalse(record.get("stopped", False)) + state = json.loads((path / ".work/rerun-2/ledger/ledger.json").read_text()) + self.assertEqual(state["seen"]["m-1"], [3, 102]) + + def test_older_per_part_replies_are_combined_before_inheritance(self): + path = self.job(1.61, 1, 100) + self.part(path, 0.01, 1) + result = json.loads((path / "result.json").read_text()) + result["budget"].pop("spent_total_usd") + result["reruns"][0].pop("cumulative_replies", None) + result["reruns"][0].pop("left_usd") + (path / "result.json").write_text(json.dumps(result)) + older = path / ".work/rerun-1/ledger/ledger.json" + state = json.loads(older.read_text()) + state["seen"]["m-1"] = [1, 1] + older.write_text(json.dumps(state)) + before = older.read_bytes() + row = {"input": 0.0, "output": 10000.0} + for part, amount, seen in ((2, 0.51, [3, 102]), (3, 0.34, [4, 103])): + _, admitted = self.part(path, 0.01, 1, amount=lambda usual: ledger.bound({}, b"{}", row, seen=usual)) + self.assertEqual(admitted, [(True, amount)]) + state = json.loads((path / f".work/rerun-{part}/ledger/ledger.json").read_text()) + self.assertEqual(state["seen"]["m-1"], seen) + self.assertEqual(older.read_bytes(), before) + + +class NoVersion(unittest.TestCase): + """A job that records no version of a benchmark that has versions now is older than them: it ran the pin the + definition held then, the one version that runs the shared commit.""" + + def test_the_version_that_runs_the_shared_pin_is_the_earlier_one(self): + up = {"repository": "https://example.org/b", "tested": "a" * 40} + for versions, want in [({"v2": {"upstream": {"tag": "v2", "tested": "b" * 40}}, "old": {"upstream": {"branch": "main"}}}, "old"), + ({"v2": {"upstream": {"tag": "v2", "tested": "b" * 40}}, "v1": {"upstream": {"tag": "v1"}}}, None), + ({"a": {"upstream": {"branch": "main"}}, "b": {"upstream": {"branch": "dev"}}}, None), + ({"fork": {"upstream": {"branch": "main", "repository": "https://example.org/fork"}}}, None), + ({}, None)]: + with self.subTest(versions=list(versions)): + self.assertEqual(rerun.earlier_version({"upstream": up, "default": "v2", "versions": versions}), want) + self.assertIsNone(rerun.earlier_version({"upstream": {}, "versions": {"old": {"upstream": {"branch": "main"}}}})) + + def test_a_job_of_osworld1_from_before_its_versions_is_taken_as_the_earlier_one(self): + bench = definitions.get("benchmark", "osworld1") + self.assertEqual(bench["_version"], "desktop-env-v1.0.3") # what a bare key resolves to now + lines = [] + std = {"benchmark": "osworld1", "plugged": "nop", "kind": "control"} # recorded before versions: none + got, other = rerun.resolve({"job_name": "old-job", "standard": std}, [], say=lines.append) + self.assertEqual((got["_ref"], other["key"]), ("osworld1@044bc33", "nop")) + self.assertEqual(lines, ["old-job records no version of osworld1: taken as osworld1@044bc33, main (044bc33), " + "the one osworld1 had before it had versions"]) + lines.clear() + std = dict(std, **rerun.job._version(definitions.get("benchmark", "osworld1@044bc33"))) + self.assertEqual(rerun.resolve({"standard": std}, [], say=lines.append)[0]["_ref"], "osworld1@044bc33") + self.assertEqual(lines, []) # a recorded version is the one run + + def test_without_one_earlier_version_the_job_is_refused_with_what_to_do(self): + bench = dict(definitions.get("benchmark", "osworld1")) + with mock.patch.object(rerun, "_ran_before_versions", lambda b, root: None), \ + mock.patch.object(rerun.definitions, "get", lambda kind, ref, root=None: bench), self.assertRaises(run.Refused) as e: + rerun.resolve({"standard": {"benchmark": "osworld1", "plugged": "nop", "kind": "control"}}, []) + self.assertEqual(str(e.exception), "the job records no version of osworld1, and its definition does not say which of " + "its versions (desktop-env-v1.0.3, 044bc33) the job ran: start a new run to compare") + + +class OwnAgent(unittest.TestCase): + """A later part of a job of one of a benchmark's own agents runs that agent again, named as its job names it.""" + + def test_the_agent_the_job_ran_is_the_one_resolved(self): + bench = definitions.get("benchmark", "osworld1") + for upstream, key, model in (("openai_cua", "openai-cua", "computer-use-preview"), ("", "m3", "MiniMax-M3")): + std = {"benchmark": "osworld1", **rerun.job._version(bench), "plugged": "original", "kind": "upstream", + "provider": "openrouter", "setup": {"name": "original", "agent": key, "asked": model}, + **({"benchmark_options": {"agent": upstream}} if upstream else {})} + with self.subTest(agent=key): + _, other = rerun.resolve({"standard": std}, []) + self.assertEqual((other["agent"], rerun.job.agent_name(other), other["asked"]), (key, key, model)) + + def test_a_trial_begun_in_a_later_part_is_queued_under_the_jobs_agent(self): + # the board names a queued trial by the job's agent, as the first part did, not by the setup it runs under + got, tmp = [], tempfile.mkdtemp(prefix="nullius-own-agent-") + self.addCleanup(shutil.rmtree, tmp, True) + + class Feed: + def emit(self, event, trial=None, **kw): + got.append((event, trial, kw.get("agent"))) + + r = mock.Mock(job_dir=tmp, other={"key": "original", "agent": "openai-cua"}, feed=Feed()) + r._stopped.is_set.return_value = False + self.assertIsNone(rerun._begin(r, "t__1", (0, "t", 1), 0, lambda iur: None)) + self.assertEqual(got, [("trial.queued", "t__1", "openai-cua")]) + + +# five units, each one model call of 0.00003 USD (3 tokens out at 10 USD a million), each scored a pass +FIVE_DRIVER = '''from nullius.standard.protocols.jsonl import serve +serve({"units": lambda dataset: {"units": [f"t{i}" for i in range(5)]}, "setup": lambda unit, dir: {"prompt": "model hi"}, + "score": lambda unit, dir, transcript, answer: {"reward": 1.0, "passed": True, "detail": {}}}) +''' + + +class FinishTest(unittest.TestCase): + """The tasks a job planned and has no result for - never begun, or begun and killed - run in that job.""" + setUpClass, tearDownClass = RerunTest.__dict__["setUpClass"], RerunTest.__dict__["tearDownClass"] + setUp, job, again, read, trials = RerunTest.setUp, RerunTest.job, RerunTest.again, RerunTest.read, RerunTest.trials + + def capped(self) -> tuple: + """Five tasks, one at a time, under a cap of 0.00008 USD: two pass, the third's call does not fit and it is + cut off, and the last two are never begun. (the job, the catalogue it ran from)""" + root = os.path.join(self.tmp, "catalogue") + shutil.copytree(ROOT, root) + with open(os.path.join(root, "benchmarks", "fakebench", "driver.py"), "w") as f: + f.write(FIVE_DRIVER) + agent = Path(root, "agents", "fake", "agent.json") # the fake agent's script, where the fixtures keep it + agent.write_text(agent.read_text().replace("{here}/../../..", os.path.dirname(ROOT))) + b, o = definitions.get("benchmark", "fakebench", root), definitions.get("agent", "fake", root) + job_dir = run.run(b, o, model="m-1", provider="custom", jobs_root=self.tmp, env=self.env, say=lambda s: None, + unsandboxed=True, name="five", concurrency=1, max_usd=0.00008, + prices={"m-1": {"input": 0.0, "output": 10.0, "max_output": 3}}) + return job_dir, root + + def test_a_job_its_cap_stopped_is_finished_in_that_job(self): + job_dir, root = self.capped() + first, config = self.read(job_dir, "result.json"), Path(job_dir, "config.json").read_bytes() + self.assertEqual((first["budget"]["stopped"], first["budget"]["cut_off"], first["budget"]["not_run"]), (True, ["t2"], ["t3", "t4"])) + names = [n for n, _ in rerun.planned(job_dir)] + self.assertEqual(names, [f"t{i}__u{i:04d}" for i in range(5)]) # what the feed says it planned + self.assertEqual(rerun.unfinished(job_dir), {n: {"unit": n[:2], "folder": False} for n in names[3:]}) + j0 = parse.parse_job(job_dir) + self.assertEqual((j0.n_planned, len(j0.trials), j0.n_resolved), (5, 3, 2)) + whole = digest(job_dir) + with self.assertRaises(run.Refused) as e: # one cap for the job: spent + rerun.rerun(job_dir, [], every_unfinished=True, env=self.env, say=lambda s: None, root=root) + self.assertEqual(str(e.exception), "the job's spending cap of 0.00008 USD is spent (0.00006 spent, and a call did not " + "fit what was left): raise it with --max-usd USD") + self.assertEqual(digest(job_dir), whole) + said_lines = [] + got = rerun.rerun(job_dir, [], every_unfinished=True, env=self.env, say=said_lines.append, root=root, reason="finish", + max_usd=0.001) + j1 = parse.parse_job(job_dir) + self.assertEqual((j1.n_planned, len(j1.trials), j1.n_resolved), (5, 5, 5)) + self.assertEqual({t.trial_name: t.outcome for t in j1.trials}, {n: classify.RESOLVED for n in names}) + res = self.read(job_dir, "result.json") + self.assertEqual((res["n_total_trials"], res["stats"]["n_completed_trials"], res["stats"]["n_cancelled_trials"]), (5, 5, 0)) + self.assertEqual(res["standard"]["passed"], 5) # the rate, over the five + self.assertEqual((res["started_at"], res["finished_at"]), (first["started_at"], first["finished_at"])) + changes = res["budget"].pop("changes") + self.assertEqual([(c["max_usd"], c["was"]) for c in changes], [(0.001, 0.00008)]) + self.assertEqual(res["budget"], dict(first["budget"], max_usd=0.001, spent_total_usd=2 * 0.00003 + 3 * 0.00003, closed=False)) + self.assertEqual(Path(job_dir, "config.json").read_bytes(), config) + (entry,) = res["reruns"] + self.assertEqual(entry["trials"], names[2:]) + self.assertEqual(entry["replaced"], [{"trial": names[2], "unit": "t2", "try": 1, "was": {"error": "SpendingCapError"}, + "now": {"reward": 1.0}}]) + self.assertEqual(entry["begun"], [{"trial": n, "unit": n[:2], "now": {"reward": 1.0}} for n in names[3:]]) + self.assertNotIn("no_result", entry) + self.assertEqual((entry["max_usd"], entry["left_usd"]), (0.001, 0.00094)) # the job's new cap, less what was spent + self.assertAlmostEqual(entry["spent_usd"], 3 * 0.00003) + self.assertEqual(got["begun"], entry["begun"]) + self.assertEqual((parse.parse_job(job_dir).reruns[0]["begun"], j0.reruns), (entry["begun"], [])) + for n in names[3:]: # each its first try + std = self.read(job_dir, n, "result.json")["standard"] + self.assertEqual((std.get("retries", 0), std["rerun"]["begun"], std["rerun"]["reason"]), (0, True, "finish")) + self.assertNotIn("replaced", std["rerun"]) + self.assertEqual([x for x in os.listdir(os.path.join(job_dir, "retried"))], [f"{names[2]}.try-1"]) + self.assertTrue(any(s.startswith("run: 2 of 2 begun") for s in said_lines), said_lines) + self.assertTrue(any(s.startswith("ran again: 1 of 1 replaced") for s in said_lines), said_lines) + # the board reads the job ended, every card done + board = live.load(live.feed_path(job_dir)).snapshot() + self.assertEqual(board["state"], "finished") + self.assertEqual(sorted((t["trial"], t["outcome"]) for t in board["trials"]), [(n, "resolved") for n in names]) + # finished whole: nothing more to take, said, and nothing written + whole, said_lines = digest(job_dir), [] + got = rerun.rerun(job_dir, [], every_unfinished=True, env=self.env, say=said_lines.append, root=root) + self.assertEqual((got["trials"], said_lines), ([], ["nothing to run: every task five planned has a result"])) + self.assertEqual(digest(job_dir), whole) + + def test_a_task_never_begun_is_named_by_its_unit(self): + job_dir, root = self.capped() + got = rerun.rerun(job_dir, ["t4"], env=self.env, say=lambda s: None, root=root, max_usd=0.001) + self.assertEqual(([x["trial"] for x in got["begun"]], got["replaced"]), (["t4__u0004"], [])) + self.assertEqual(sorted(rerun.unfinished(job_dir)), ["t3__u0003"]) + + def test_a_task_killed_mid_run_is_kept_marked_and_run(self): + """Killed in the job's first run (a folder, no result), and killed in a re-run, after the try before it was + moved into retried/: each folder is kept as the try it was, marked, and the task runs again.""" + job_dir = self.job() + before, _ = self.trials(job_dir) + model, good = before["model"].trial_name, before["good"].trial_name + os.remove(os.path.join(job_dir, model, "result.json")) # the first run's try, killed + os.makedirs(os.path.join(job_dir, "retried")) + os.replace(os.path.join(job_dir, good), os.path.join(job_dir, "retried", f"{good}.try-1")) + os.makedirs(os.path.join(job_dir, good, "workspace")) # a re-run's try, killed + + def inventory(folder): + return {str(p.relative_to(folder)): p.read_bytes() if p.is_file() else None + for p in folder.rglob("*") if p.relative_to(folder) != Path(rerun.NO_RESULT)} + + for name in (model, good): + workspace = Path(job_dir, name, "workspace") + (workspace / "empty").mkdir() + (workspace / "nested").mkdir() + (workspace / "nested" / "evidence.bin").write_bytes(b"\x00kept evidence\xff") + inventories = {name: inventory(Path(job_dir, name)) for name in (model, good)} + self.assertEqual(rerun.unfinished(job_dir), {model: {"unit": "model", "folder": True}, good: {"unit": "good", "folder": True}}) + self.assertEqual(len(parse.parse_job(job_dir).trials), 1) + got = self.again(job_dir, [], every_unfinished=True) + after, j = self.trials(job_dir) + self.assertEqual(len(j.trials), 3) + self.assertEqual(sorted(got["no_result"]), sorted([model, good])) + self.assertEqual((j.reruns[0]["no_result"], "begun" in j.reruns[0]), (got["no_result"], False)) + self.assertEqual({x["trial"]: (x["try"], x["was"]) for x in got["replaced"]}, {model: (1, {}), good: (2, {})}) + for name, n in ((model, 1), (good, 2)): + kept = os.path.join(job_dir, "retried", f"{name}.try-{n}") + self.assertEqual(inventory(Path(kept)), inventories[name]) + self.assertFalse(os.path.exists(os.path.join(kept, "result.json"))) + self.assertIsNone(self.read(kept, rerun.NO_RESULT)["result"]) + self.assertEqual(self.read(job_dir, name, "result.json")["standard"]["retries"], n) + self.assertTrue(self.read(job_dir, name, "result.json")["standard"]["rerun"]["no_result"]) + self.assertEqual(after["good"].outcome, classify.RESOLVED) + # the tries a page lists: the one kept with a result, and the last; the one with none is not a try to open + self.assertEqual([(n, t.trial_name) for n, t in parse.tries(after["good"])], [(1, f"{good}.try-1"), (3, good)]) + self.assertEqual(rerun.unfinished(job_dir), {}) + + def test_a_trial_a_stop_ended_is_taken_with_the_tasks_never_begun(self): + """A Stop ends the unit under way with a result that says so, and the units after it are never begun: both + are what the stop left, and --unfinished takes them; a judged trial is not taken.""" + job_dir, root = self.capped() + name = "t1__u0001" + res = self.read(job_dir, name, "result.json") + res["exception_info"], res["verifier_result"] = {"exception_type": run.CANCELLED, "exception_message": "stopped"}, None + Path(job_dir, name, "result.json").write_text(json.dumps(res)) + got = rerun.rerun(job_dir, [], every_unfinished=True, env=self.env, say=lambda s: None, root=root, max_usd=0.001) + self.assertEqual(got["trials"], ["t1__u0001", "t2__u0002", "t3__u0003", "t4__u0004"]) + self.assertEqual([(x["trial"], x["was"]) for x in got["replaced"]], + [(name, {"error": run.CANCELLED}), ("t2__u0002", {"error": "SpendingCapError"})]) + + def test_a_stop_leaves_a_task_never_begun_as_it_was(self): + job_dir, root = self.capped() + whole = digest(job_dir) + + def unit(r, i, u, rr=1, retry=0): + os.makedirs(os.path.join(r.job_dir, r.trial_name(i, u, rr), "workspace")) + raise SystemExit(143) + with mock.patch.object(run.Run, "unit", unit), self.assertRaises(SystemExit): + rerun.rerun(job_dir, ["t3"], env=self.env, say=lambda s: None, root=root, max_usd=0.001) + self.assertEqual(sorted(rerun.unfinished(job_dir)), ["t3__u0003", "t4__u0004"]) + self.assertFalse(any(n.startswith("t3__") for n in os.listdir(job_dir))) + entry = self.read(job_dir, "result.json")["reruns"][-1] + self.assertEqual((entry["begun"], entry["stopped"]), ([], True)) + self.assertEqual({k for k, v in digest(job_dir).items() if whole.get(k) != v}, {"result.json", "events.jsonl", "progress.jsonl", ".work/rerun.lock", + ".work/rerun-1/ledger/ledger.json"}) + + def test_each_refusal_moves_nothing(self): + job_dir, root = self.capped() + whole = digest(job_dir) + for what, ids, words in (("an id it never planned", ["t9"], "holds no trial or unit t9"), + ("a trial name it never planned", ["t3__u0009"], "holds no trial or unit t3__u0009")): + with self.subTest(what), self.assertRaises(run.Refused) as e: + rerun.rerun(job_dir, ids, env=self.env, say=lambda s: None, root=root) + self.assertIn(words, str(e.exception)) + self.assertEqual(digest(job_dir), whole) + with self.subTest("a job still running"): + os.rename(os.path.join(job_dir, "result.json"), os.path.join(self.tmp, "result.json")) + whole = digest(job_dir) + with self.assertRaises(run.Refused) as e: + rerun.rerun(job_dir, [], every_unfinished=True, env=self.env, say=lambda s: None, root=root) + self.assertIn("is still running", str(e.exception)) + self.assertEqual(digest(job_dir), whole) + os.rename(os.path.join(self.tmp, "result.json"), os.path.join(job_dir, "result.json")) + with self.subTest("a job whose feed does not say what it planned"): + os.rename(os.path.join(job_dir, "events.jsonl"), os.path.join(self.tmp, "events.jsonl")) + whole = digest(job_dir) + with self.assertRaises(run.Refused) as e: + rerun.rerun(job_dir, [], every_unfinished=True, env=self.env, say=lambda s: None, root=root) + self.assertIn("does not record the tasks it planned", str(e.exception)) + with self.assertRaises(run.Refused) as e: + rerun.rerun(job_dir, ["t3"], env=self.env, say=lambda s: None, root=root) + self.assertIn("holds no trial or unit t3", str(e.exception)) + self.assertEqual(digest(job_dir), whole) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_standard_sets.py b/app/tests/test_standard_sets.py new file mode 100644 index 00000000..ec5962ce --- /dev/null +++ b/app/tests/test_standard_sets.py @@ -0,0 +1,661 @@ +"""Task sets (``standard/runner/sets.py``): a named list of a benchmark's units in the +user catalogue, with an id, a label and the name made from it, the version it +was made at, and no option. The content hash says the same for the same ids in +any order and changes with an id or the dataset; a set is frozen: nothing adds +to its list, and a file of several lists from before reads as its latest, +unchanged; a label makes a name in lower case with hyphens, a second equal one +``-2``; a name that would leave the benchmark's folder is refused; a set is +made from a file or from a job's trials by outcome or by name; an entry comes +in from its file or from a job that ran it. ``run --set`` takes the set's +dataset, refuses what contradicts it, runs under any options it is given, +refuses ids its driver does not list under them (naming both versions for a set +made at another), and records the set in the job's config. No key, no network: +the runs are a control's.""" +from __future__ import annotations + +import copy +import io +import json +import os +import shutil +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from unittest import mock + +from nullius import progress +from nullius.harbor import feed +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import job, merge, run, sets, shard + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +NOP = {"nop": {"source": "nullius", "from": "nothing said"}} +MODE = {"mode": {"summary": "a mode the listing follows", "values": ["plain", "hard"], "default": "plain"}} +DATASET = ["good", "wrong", "slow", "model"] + + +def read(path): + with open(path) as f: + return json.load(f) + + +class Scratch(unittest.TestCase): + """A catalogue of its own (``NULLIUS_CATALOGUE``), the fake benchmark with a control and an option.""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="nullius-sets-") + self.addCleanup(shutil.rmtree, self.tmp, True) + self.cat = os.path.join(self.tmp, "catalogue") + self.jobs = os.path.join(self.tmp, "jobs") + self.b = dict(definitions.get("benchmark", "fakebench", ROOT), controls=NOP, options=MODE) + for patch in (mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": self.cat}), mock.patch.object(install, "HOME", os.path.join(self.tmp, "home")), + mock.patch.object(cli, "_bench", return_value=self.b), mock.patch.object(cli, "_find_bench", return_value=self.b), + mock.patch.object(cli, "_exit_on_term"), mock.patch.object(cli.settings, "load"), + mock.patch.object(progress, "ECHO", None)): + patch.start() + self.addCleanup(patch.stop) + + def file(self, text, name="units.txt"): + path = os.path.join(self.tmp, name) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return path + + def cli(self, *args): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + code = cli.main(list(args)) + return code, out.getvalue(), err.getvalue() + + def make(self, label, text, *extra): + name = sets.name_for("fakebench", label) + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file(text), *extra) + self.assertEqual(code, 0, err) + return sets.load("fakebench", name) + + def trials(self, job_dir): + return sorted(d for d in os.listdir(job_dir) if "__u" in d) + + +class Hash(Scratch): + def test_the_same_ids_in_another_order_or_from_a_file_with_comments_hash_the_same(self): + a = self.make("a", "good\nmodel\n") + b = self.make("b", "# the same two\n\n model \r\ngood\n") + self.assertEqual(sets.revision(a)["hash"], sets.revision(b)["hash"]) + self.assertNotEqual(a["id"], b["id"]) # two entries of equal lists stay two sets + self.assertEqual(sets.content_hash("fakebench", "all", ["good", "model"]), + sets.content_hash("fakebench", "all", ["model", "good"])) + + def test_it_changes_with_an_id_or_the_dataset(self): + base = sets.content_hash("fakebench", "all", ["good", "model"]) + for other in (sets.content_hash("fakebench", "all", ["good", "slow"]), + sets.content_hash("fakebench", "responding", ["good", "model"])): + self.assertNotEqual(base, other) + self.assertEqual(sets.revision(self.make("plain", "good\nmodel\n"))["hash"], base) + + def test_a_file_changed_by_hand_is_refused_where_it_is_read(self): + self.make("edited", "good\nmodel\n") + path = sets.path_of("fakebench", "edited") + entry = read(path) + entry["revisions"][0]["units"].append("slow") + with open(path, "w") as f: + json.dump(entry, f) + with self.assertRaisesRegex(sets.Refused, "changed by hand"): + sets.load("fakebench", "edited") + + +class NoOption(Scratch): + def test_set_create_takes_no_benchmark_option(self): + for source in (["--units", self.file("good\n")], ["--search", "good"]): + with self.subTest(source=source[0]): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err), self.assertRaises(SystemExit) as stop: + cli.main(["set", "create", "fakebench", "dev", "--dataset", "all", *source, "--bench-option", "mode=hard"]) + self.assertEqual((stop.exception.code, out.getvalue()), (2, "")) + self.assertIn("usage:", err.getvalue()) + self.assertIn("unrecognized arguments: --bench-option", err.getvalue()) + self.assertFalse(os.path.exists(self.cat)) + + def test_the_entry_holds_no_option_and_an_earlier_entry_that_does_is_refused_where_it_is_read(self): + entry = self.make("dev", "good\nmodel\n") + self.assertEqual(sorted(read(sets.path_of("fakebench", "dev"))), + ["benchmark", "dataset", "description", "id", "label", "name", "revisions", "schema"]) + self.assertEqual(sorted(sets.record(entry, sets.revision(entry))), ["hash", "id", "label", "name", "revision", "units"]) + for field, value in (("benchmark_options", {"mode": "hard"}), ("setup", "yours"), ("benchmark_version", "1")): + with self.subTest(field=field): + path = sets.path_of("fakebench", "dev") + with open(path, "w") as f: + json.dump(dict(entry, schema=sets.SCHEMA, **{field: value}), f) + with self.assertRaisesRegex(sets.Refused, f"holds {field}, which a task set does not hold"): + sets.load("fakebench", "dev") + code, out, err = self.cli("set", "show", "fakebench", "dev") + self.assertEqual((code, out), (2, "")) + self.assertIn(f"holds {field}", err) + + +class Frozen(Scratch): + def earlier(self, name="dev"): + """A set made before sets were frozen, as its file was written then: two lists, no label, no version.""" + folder = os.path.join(self.cat, "sets", "fakebench") + os.makedirs(folder, exist_ok=True) + lists = [["good", "model"], ["good", "model", "slow"]] + entry = {"schema": sets.SCHEMA, "id": "a" * 32, "name": name, "description": "from before", "benchmark": "fakebench", + "dataset": "all", "revisions": [{"revision": i, "date": f"2026-11-1{i}T10:00:00Z", "note": "", "units": u, + "hash": sets.content_hash("fakebench", "all", u)} for i, u in enumerate(lists, 1)]} + path = os.path.join(folder, name + ".json") + with open(path, "w") as f: + json.dump(entry, f, indent=2) + return path + + def test_a_set_of_several_lists_from_before_reads_as_its_latest_and_is_not_rewritten(self): + path = self.earlier() + with open(path, "rb") as f: + before = f.read() + entry = sets.load("fakebench", "dev") + self.assertEqual((sets.label_of(entry), sets.latest(entry)["units"]), ("dev", ["good", "model", "slow"])) + self.assertEqual(sets.rows("fakebench"), [{"name": "dev", "label": "dev", "description": "from before", "dataset": "all", + "version": "", "units": 3, "date": "2026-11-12T10:00:00Z"}]) + code, out, err = self.cli("set", "show", "fakebench", "dev") + self.assertEqual(code, 0, err) + self.assertTrue(out.startswith("dev: 3 units of fakebench all\n"), out) + self.assertNotIn("revision", out) + # a recipe or a command from before names its latest list as NAME@2: the same set; NAME@1 is refused + self.assertEqual(sets.for_run(self.b, "dev@2")[0]["units"], ["good", "model", "slow"]) + code, out, err = self.cli("set", "show", "fakebench", "dev@1") + self.assertEqual((code, out), (3, "")) + self.assertIn("dev@1 names an earlier list of the task set dev: a set is read as its latest list now; name it dev", err) + code, out, err = self.run_nop("--set", "dev", "--name", "from-before") + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(os.path.join(self.jobs, "from-before")), ["good__u0000", "model__u0003", "slow__u0002"]) + with open(path, "rb") as f: + self.assertEqual(f.read(), before) + + def run_nop(self, *args): + return self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "-j", "2", *args) + + +class Names(Scratch): + def test_a_label_makes_a_name_in_lower_case_with_hyphens_and_a_second_one_takes_two(self): + for label, name in (("Custom task set", "custom-task-set"), ("custom task set", "custom-task-set-2"), + (" Custom task set! ", "custom-task-set-3"), ("Café au lait", "cafe-au-lait"), + ("a/b", "a-b"), ("../up", "up"), ("x..y", "x-y"), ("ÉTÉ 2026", "ete-2026"), ("日本", "task-set"), + ("dev", "dev")): + with self.subTest(label=label): + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file("good\n")) + self.assertEqual(code, 0, err) + entry = sets.load("fakebench", name) + self.assertEqual(entry["label"], label.strip()) + self.assertTrue(out.startswith(f"wrote {sets.path_of('fakebench', name)}: "), out) + self.assertEqual(sets.slug("b" * 70), "b" * 64) + self.assertEqual(sets.name_for("fakebench", "b" * 70), "b" * 64) + sets.create(self.b, "b" * 70, dataset="all", units=["good"]) + self.assertEqual(sets.name_for("fakebench", "b" * 70), "b" * 62 + "-2") + + def test_a_label_with_no_letter_or_digit_on_two_lines_or_too_long_is_refused(self): + for label, said in (("", "needs a name"), (" ", "needs a name"), ("..", "needs a letter or a digit"), + ("a\nb", "one line"), ("x" * 81, "at most 80 characters")): + with self.subTest(label=label): + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file("good\n")) + self.assertEqual((code, out), (2, "")) + self.assertIn(said, err) + self.assertFalse(os.path.exists(os.path.join(self.cat, "sets", "fakebench"))) + + def test_a_name_that_would_leave_the_benchmarks_folder_is_refused(self): + for name in ("a/b", "..", "", ".hidden", "../up", "a\\b", "x..y"): + with self.subTest(name=name): + code, out, err = self.cli("set", "show", "fakebench", name) + self.assertEqual((code, out), (2, "")) + self.assertIn("not a task set's name", err) + + def test_links_cannot_escape_through_parent_folders_or_an_entry(self): + entry = self.make("dev", "good\n") + exported = self.file(json.dumps(read(sets.path_of("fakebench", "dev"))), "export.json") + for relative in ("sets", "sets/fakebench", "sets/fakebench/dev.json"): + with self.subTest(path=relative): + path = os.path.join(self.cat, relative) + outside = os.path.join(self.tmp, "outside") + os.rename(path, outside) + os.symlink(outside, path) + try: + for action in (lambda: sets.load("fakebench", "dev"), + lambda: sets.write(entry), + lambda: sets.rename("fakebench", "dev", "other"), + lambda: sets.import_path(exported)): + with self.assertRaisesRegex(sets.Refused, "outside"): + action() + if relative != "sets/fakebench/dev.json": + with self.assertRaisesRegex(sets.Refused, "outside"): + sets.create(self.b, "new", dataset="all", units=["good"]) + with mock.patch.object(sets.os, "listdir", wraps=os.listdir) as listed: + try: + found, bad = sets.entries() + except sets.Refused as e: + self.assertIn("outside", str(e)) + else: + self.assertEqual(found, []) + self.assertTrue(any("outside" in problem for problem in bad)) + self.assertNotIn(mock.call(path), listed.call_args_list) + finally: + os.unlink(path) + os.rename(outside, path) + self.assertEqual(sets.load("fakebench", "dev"), entry) + self.assertFalse(os.path.exists(sets.path_of("fakebench", "new"))) + + def test_a_label_that_exists_makes_another_set(self): + first = self.make("dev", "good\n") + code, out, err = self.cli("set", "create", "fakebench", "dev", "--dataset", "all", "--units", self.file("model\n")) + self.assertEqual(code, 0, err) + self.assertIn(": dev-2 (dev), 1 task of all", out) + self.assertEqual(sets.load("fakebench", "dev"), first) + self.assertEqual(sets.revision(sets.load("fakebench", "dev-2"))["units"], ["model"]) + + +class RenameAndDelete(Scratch): + def test_a_rename_keeps_the_id_and_the_list_makes_the_name_again_and_the_id_finds_it(self): + first = self.make("dev", "good\nmodel\n", "--description", "two of them") + code, out, err = self.cli("set", "rename", "fakebench", "dev", "Misses of June") + self.assertEqual((code, err), (0, "")) + self.assertTrue(out.startswith("renamed dev to misses-of-june (Misses of June) ("), out) + self.assertIn("its id and its tasks kept", out) + got = sets.load("fakebench", "misses-of-june") + self.assertEqual((got["id"], got["label"], got["description"], got["revisions"]), + (first["id"], "Misses of June", "two of them", first["revisions"])) + self.assertEqual(sorted(os.listdir(os.path.join(self.cat, "sets", "fakebench"))), ["misses-of-june.json"]) + self.assertEqual(sets.by_id("fakebench", first["id"], "dev")["name"], "misses-of-june") + # another set made under the old name is another set: the id still finds the renamed one + self.make("dev", "good\n") + self.assertEqual(sets.by_id("fakebench", first["id"], "dev")["name"], "misses-of-june") + self.assertIsNone(sets.by_id("fakebench", "0" * 32, "dev")) + # a label that makes the same name changes the label alone; one another set holds makes the next name + self.assertEqual(sets.rename("fakebench", "misses-of-june", "misses of june")["name"], "misses-of-june") + self.assertEqual(sets.rename("fakebench", "misses-of-june", "Dev")["name"], "dev-2") + + def test_its_own_label_an_empty_one_and_a_set_not_there_are_refused(self): + dev = self.make("dev", "good\n") + other = self.make("other", "model\n") + for new, code, said in (("dev", 2, "is named 'dev' already"), ("", 2, "needs a name"), ("..", 2, "letter or a digit")): + with self.subTest(new=new): + got = self.cli("set", "rename", "fakebench", "dev", new) + self.assertEqual(got[:2], (code, "")) + self.assertIn(said, got[2]) + got = self.cli("set", "rename", "fakebench", "nowhere", "x") + self.assertEqual(got[:2], (3, "")) + self.assertIn("no task set 'nowhere'", got[2]) + self.assertEqual((sets.load("fakebench", "dev"), sets.load("fakebench", "other")), (dev, other)) + self.assertEqual(sorted(os.listdir(os.path.join(self.cat, "sets", "fakebench"))), ["dev.json", "other.json"]) + self.assertEqual(sets.rename("fakebench", "dev", "other")["name"], "other-2") + + def test_a_delete_removes_the_file_and_says_what_it_held(self): + self.make("Dev set", "good\nmodel\n") + path = sets.path_of("fakebench", "dev-set") + code, out, err = self.cli("set", "delete", "fakebench", "dev-set") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.strip(), f"deleted {path}: dev-set (Dev set), 2 units; jobs that ran it keep their record") + self.assertFalse(os.path.exists(path)) + code, out, err = self.cli("set", "delete", "fakebench", "dev-set") + self.assertEqual((code, out), (3, "")) + self.assertIn("no task set 'dev-set'", err) + + def test_a_delete_of_a_link_removes_the_link_and_not_the_set_it_leads_to(self): + self.make("dev", "good\n") + folder = os.path.join(self.cat, "sets", "fakebench") + path = os.path.join(folder, "alias.json") + os.symlink(os.path.join(folder, "dev.json"), path) + code, out, err = self.cli("set", "delete", "fakebench", "alias") + self.assertEqual(code, 0, err) + self.assertEqual(out.strip(), f"deleted {path}: an entry this version could not read") + self.assertEqual(sorted(os.listdir(folder)), ["dev.json"]) + self.assertEqual(sets.revision(sets.load("fakebench", "dev"))["units"], ["good"]) + + def test_an_entry_of_the_earlier_format_is_refused_plainly_and_can_be_deleted(self): + entry = self.make("old", "good\n") + path = sets.path_of("fakebench", "old") + with open(path, "w") as f: + json.dump(dict(entry, schema=sets.SCHEMA, benchmark_options={"mode": "hard"}, setup="yours"), f) + with self.assertRaises(sets.Earlier) as refused: + sets.load("fakebench", "old") + self.assertIn(path, str(refused.exception)) + said = sets.plain(refused.exception, "fakebench", "old") + self.assertEqual(said, "The task set old is of an earlier format, which kept a run's options: delete it and make it again.") + self.assertNotIn(self.tmp, said) + code, out, err = self.cli("set", "rename", "fakebench", "old", "new") + self.assertEqual((code, out), (2, "")) + self.assertIn("earlier format", err) + code, out, err = self.cli("set", "delete", "fakebench", "old") + self.assertEqual((code, out.strip(), err), (0, f"deleted {path}: an entry this version could not read", "")) + self.assertFalse(os.path.exists(path)) + + +class FromAJob(Scratch): + def job(self, name="graded"): + """A job as a run writes it: good passed, wrong failed, slow rate limited, a unit whose id has a slash passed.""" + d = os.path.join(self.jobs, name) + os.makedirs(d) + other = dict(definitions.control(self.b, "nop"), _kind="control") + units = ["good", "wrong", "slow", "group/model"] + job.write_config(d, job=name, bench=self.b, other=other, model="", provider="openai", dataset="all", units=units, + concurrency=1, granted=False, bench_options={"mode": "hard"}) + ends = {"good": ({"reward": 1.0}, None), "wrong": ({"reward": 0.0}, None), "slow": (None, ("RateLimitError", "429")), + "group/model": ({"reward": 1.0}, None)} + results = [] + for place, u in enumerate(units): + score, exc = ends[u] + trial = os.path.join(d, f"{u.rpartition('/')[2]}__u{place:04d}") + os.makedirs(trial) + results.append(job.write_trial(trial, job=name, bench=self.b, other=other, model="", unit=u, t0=1.0, t1=2.0, + produce=(1.0, 2.0), score=score, exception=exc, calls=[], trajectory=None)) + job.write_result(d, name, 1.0, 3.0, results, len(units)) + return d + + def test_outcome_takes_the_trials_of_those_outcomes_by_their_full_unit_ids(self): + d = self.job() + for name, outcome, want in (("passed", "passed", ["good", "group/model"]), ("misses", "failed,infra", ["wrong", "slow"]), + ("limited", "rate_limited", ["slow"])): + with self.subTest(outcome=outcome): + code, out, err = self.cli("set", "create", "fakebench", name, "--from-job", d, "--outcome", outcome) + self.assertEqual(code, 0, err) + entry = sets.load("fakebench", name) + self.assertEqual(sets.revision(entry)["units"], want) + self.assertEqual(entry["dataset"], "all") + self.assertNotIn("benchmark_options", entry) # the job ran under mode=hard; the set holds none + self.assertEqual(sets.revision(entry)["hash"], sets.content_hash("fakebench", "all", want)) + self.assertIn(f"outcomes {outcome}", sets.revision(entry)["note"]) + + def test_unit_takes_the_ones_named(self): + d = self.job() + code, out, err = self.cli("set", "create", "fakebench", "two", "--from-job", d, "--unit", "group/model", "--unit", "wrong") + self.assertEqual(code, 0, err) + self.assertEqual(sets.revision(sets.load("fakebench", "two"))["units"], ["wrong", "group/model"]) + code, out, err = self.cli("set", "create", "fakebench", "none", "--from-job", d, "--unit", "model") + self.assertEqual((code, out), (2, "")) + self.assertIn("no trial of model", err) # the trial's name is not its unit's id + code, out, err = self.cli("set", "create", "fakebench", "bad", "--from-job", d, "--outcome", "sideways") + self.assertEqual(code, 2) + self.assertIn("--outcome sideways", err) + + +class Import(Scratch): + def test_an_entry_comes_in_from_its_file_and_another_list_under_its_id_is_refused(self): + entry = self.make("dev", "good\nmodel\n") + exported = os.path.join(self.tmp, "dev.json") + shutil.copy(sets.path_of("fakebench", "dev"), exported) + elsewhere = os.path.join(self.tmp, "elsewhere") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", exported) + self.assertEqual(code, 0, err) + self.assertEqual(read(sets.path_of("fakebench", "dev")), read(exported)) + code, out, err = self.cli("set", "import", exported) + self.assertEqual(code, 0, err) + self.assertIn("here already", out) + # here, the same id with another list + other = read(exported) + other["revisions"][0]["units"] = ["good", "wrong"] + other["revisions"][0]["hash"] = sets.content_hash("fakebench", "all", ["good", "wrong"]) + with open(exported, "w") as f: + json.dump(other, f) + code, out, err = self.cli("set", "import", exported) + self.assertEqual((code, out), (2, "")) + self.assertIn("the same id with another list", err) + self.assertEqual(sets.load("fakebench", "dev")["id"], entry["id"]) + self.assertEqual(sets.revision(sets.load("fakebench", "dev"))["units"], ["good", "model"]) + + def test_import_checks_every_consumed_field_before_storing_an_entry_or_job_record(self): + entry = dict(self.make("dev", "good\n"), schema=sets.SCHEMA) + cases = [("entry", k, None, True) for k in ("id", "name", "description", "benchmark", "dataset")] + cases += [("entry", k, v, False) for k, v in (("label", ""), ("label", 1), ("version", []), ("version", ""))] + cases += [("revision", k, None, True) for k in sets.REVISION] + cases += [("entry", k, v, False) for k, v in ( + ("id", 1), ("name", []), ("description", {}), ("benchmark", False), ("dataset", {}), + ("benchmark_options", {}), ("setup", "yours"))] + cases += [("revision", k, v, False) for k, v in ( + ("revision", True), ("date", None), ("date", []), ("date", ""), ("note", None), + ("note", {}), ("units", [1]), ("units", [{}]), ("units", "good"), ("hash", []))] + rec = sets.record(entry, sets.revision(entry)) + jobs = [(k, None, True) for k in sets.RECORD] + jobs += [(k, v, False) for k, v in (("id", 1), ("name", []), ("revision", True), ("revision", 0), + ("units", [1]), ("units", "good"), ("units", []), ("hash", []), + ("hash", "0" * 64))] + source_job = os.path.join(self.tmp, "source-job") + os.makedirs(source_job) + for index, (section, field, value, missing) in enumerate(cases + [("job",) + c for c in jobs]): + elsewhere = os.path.join(self.tmp, f"elsewhere-{index}") + with self.subTest(section=section, field=field, value=value, missing=missing): + if section == "job": + got = dict(rec) + target = got + else: + got = copy.deepcopy(entry) + target = got if section == "entry" else got["revisions"][0] + if missing: + del target[field] + else: + target[field] = value + if section == "job": + self.file(json.dumps({"runner": "standard", "datasets": [{"name": "fakebench/all"}], + "standard": {"benchmark": "fakebench", "task_set": got}}), + "source-job/config.json") + path = source_job + else: + path = self.file(json.dumps(got), "incoming.json") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", path) + self.assertEqual((code, out), (2, ""), err) + self.assertTrue(err.startswith("refused: "), err) + self.assertFalse(os.path.exists(elsewhere)) + + def test_an_entry_comes_in_from_a_job_that_ran_it(self): + entry = self.make("dev", "model\ngood\n", "--description", "two of them") + code, out, err = self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "--set", "dev", "--bench-option", "mode=hard", + "--name", "ran") + self.assertEqual(code, 0, out + err) + elsewhere = os.path.join(self.tmp, "elsewhere") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", os.path.join(self.jobs, "ran")) + self.assertEqual(code, 0, err) + got = sets.load("fakebench", "dev") + # the record holds the set's id, name, label, hash and units: the rest is the job's or the import's + self.assertEqual({k: got[k] for k in ("id", "name", "label", "benchmark", "dataset", "description")}, + {**{k: entry[k] for k in ("id", "name", "label", "benchmark", "dataset")}, "description": ""}) + self.assertEqual([{k: r[k] for k in ("revision", "units", "hash")} for r in got["revisions"]], + [{k: r[k] for k in ("revision", "units", "hash")} for r in entry["revisions"]]) + self.assertEqual(got["revisions"][0]["note"], "from the job ran") + # the entry exported from here then adds nothing there: the same id, revision and hash + code, out, err = self.cli("set", "import", sets.path_of("fakebench", "dev", self.cat)) + self.assertEqual(code, 0, err) + self.assertIn("here already", out) + code, out, err = self.cli("set", "import", self.jobs) + self.assertEqual((code, out), (3, "")) + self.assertIn("no job", err) + # another set under the name: refused, the entry here unchanged + shutil.rmtree(os.path.join(self.cat, "sets")) + self.make("dev", "model\ngood\n") + code, out, err = self.cli("set", "import", os.path.join(self.jobs, "ran")) + self.assertEqual(code, 2) + self.assertIn("another id", err) + + +class Running(Scratch): + def run_cli(self, *args): + return self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "-j", "2", *args) + + def test_an_empty_set_is_refused_before_any_unit(self): + code, out, err = self.run_cli("--set", "", "--name", "empty") + self.assertEqual(code, 2, out + err) + self.assertIn("not a task set's name", out) + self.assertFalse(os.path.exists(self.jobs)) + + def test_each_contradiction_is_refused_before_any_unit_with_a_plain_message(self): + self.make("dev", "good\nmodel\n") + for args, said in ((["--dataset", "responding"], "--dataset responding: the task set dev is cut from the dataset all"), + (["--units", self.file("good\n")], "the set lists the units, give one or the other"), + (["--set", "nowhere"], "no task set 'nowhere' of fakebench")): + with self.subTest(args=args): + code, out, err = self.run_cli(*(["--set", "dev"] if "--set" not in args else []), *args) + self.assertEqual(code, 2, out + err) + self.assertEqual(len(out.strip().splitlines()), 1, out) + self.assertTrue(out.startswith("refused: "), out) + self.assertIn(said, out) + self.assertFalse(os.path.exists(self.jobs)) # no job was begun + code, out, err = self.run_cli("--set", "dev", "--dataset", "all", "--bench-option", "mode=hard", "--name", "agrees") + self.assertEqual(code, 0, out + err) + + def test_two_runs_under_two_values_of_an_option_both_start_and_record_the_same_set(self): + entry = self.make("dev", "good\nwrong\n") + rev = sets.revision(entry) + records = [] + for value in ("plain", "hard"): + with self.subTest(value=value): + code, out, err = self.run_cli("--set", "dev", "--bench-option", f"mode={value}", "--name", value) + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(os.path.join(self.jobs, value)), ["good__u0000", "wrong__u0001"]) + cfg = read(os.path.join(self.jobs, value, "config.json")) + self.assertEqual(cfg["standard"]["benchmark_options"], {"mode": value}) + records.append(cfg["standard"]["task_set"]) + self.assertEqual(records[0], records[1]) + self.assertEqual({k: records[0][k] for k in ("id", "revision", "hash")}, + {"id": entry["id"], "revision": 1, "hash": rev["hash"]}) + self.assertEqual(rev["hash"], sets.content_hash("fakebench", "all", ["good", "wrong"])) # no option in it + + def listing_by_mode(self): + """The fake benchmark whose driver leaves slow and model out of its listing under mode=hard.""" + here = os.path.join(self.tmp, "fakebench") + shutil.copytree(self.b["_here"], here) + path = os.path.join(here, "driver.py") + with open(path) as f: + text = f.read() + text = text.replace(' units.remove("slow")\n', + ' units.remove("slow")\n' + ' if os.environ.get("NULLIUS_OPTION_MODE") == "hard":\n' + ' units = [u for u in units if u not in ("slow", "model")]\n') + with open(path, "w") as f: + f.write(text) + self.b["_here"] = here + + def test_ids_the_driver_does_not_list_under_the_runs_options_refuse_it_before_any_unit(self): + self.listing_by_mode() + self.make("dev", "good\nslow\nmodel\nwrong\n") + code, out, err = self.run_cli("--set", "dev", "--bench-option", "mode=hard", "--name", "hard") + self.assertEqual(code, 2, out + err) + self.assertIn("2 of the 4 ids of the task set dev are not listed by Fake bench's dataset all under the run's " + "options (mode=hard): slow, model", out) + job_dir = os.path.join(self.jobs, "hard") + self.assertEqual(self.trials(job_dir), []) + self.assertFalse(os.path.exists(os.path.join(job_dir, "config.json"))) + code, out, err = self.run_cli("--set", "dev", "--bench-option", "mode=plain", "--name", "plain") + self.assertEqual(code, 0, out + err) + + def test_the_message_names_the_first_five_ids_not_listed(self): + self.make("dev", "good\n" + "".join(f"gone{i}\n" for i in range(7))) + record = sets.record(sets.load("fakebench", "dev"), sets.revision(sets.load("fakebench", "dev"))) + r = run.Run(self.b, definitions.control(self.b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=record) + with self.assertRaises(run.Refused) as e: + r.start() + self.assertIn("7 of the 8 ids of the task set dev are not listed by Fake bench's dataset all under the run's " + "options (mode=plain): gone0, gone1, gone2, gone3, gone4, ...", str(e.exception)) + self.assertEqual(self.trials(r.job_dir), []) + self.assertFalse(os.path.exists(os.path.join(r.job_dir, "config.json"))) + + def test_the_units_run_are_the_sets_and_limit_and_shard_apply_after(self): + self.make("dev", "model\nwrong\nslow\n") + code, out, err = self.run_cli("--set", "dev", "--name", "whole") + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(out.strip().splitlines()[-1]), ["model__u0003", "slow__u0002", "wrong__u0001"]) + # the set, then the shard, then the limit: shard 1 of 2 holds wrong and model of the three, and the limit keeps wrong + self.assertEqual([shard.of(u, 2) for u in DATASET], [1, 1, 2, 1]) + code, out, err = self.run_cli("--set", "dev", "--shard", "1/2", "--limit", "1", "--name", "part-shard-1of2") + self.assertEqual(code, 0, out + err) + part = out.strip().splitlines()[-1] + self.assertEqual(self.trials(part), ["wrong__u0001"]) + rec = read(os.path.join(part, "config.json"))["standard"]["shard"] + self.assertEqual((rec["units_total"], rec["planned"], rec["limit"]), (3, ["wrong"], 1)) + with open(os.path.join(part, feed.FEED)) as f: + self.assertEqual(next(e for e in map(json.loads, f) if e["event"] == "job.start")["tasks"], ["wrong"]) + + def test_the_config_records_the_set_and_the_runs_options(self): + self.b["datasets"] = [*self.b["datasets"], {"id": "responding", "units": 3}] + self.make("Dev set", "good\nmodel\n", "--dataset", "responding") + code, out, err = self.run_cli("--set", "dev-set", "--bench-option", "mode=hard", "--name", "first") + self.assertEqual(code, 0, out + err) + cfg = read(os.path.join(self.jobs, "first", "config.json")) + entry = sets.load("fakebench", "dev-set") + self.assertEqual(cfg["standard"]["task_set"], sets.record(entry)) + self.assertEqual(cfg["standard"]["task_set"], + {"id": entry["id"], "name": "dev-set", "label": "Dev set", "revision": 1, "hash": entry["revisions"][0]["hash"], + "units": ["good", "model"]}) + self.assertEqual(cfg["standard"]["benchmark_options"], {"mode": "hard"}) + self.assertNotIn("units_file", cfg["standard"]) + self.assertEqual(cfg["datasets"], [{"name": "fakebench/responding", "n_tasks": 2}]) + + def versions(self): + """The fake benchmark at two versions, each its own copy of the entry: at "2", its driver no longer lists slow.""" + here = os.path.join(self.tmp, "fakebench-2") + shutil.copytree(self.b["_here"], here) + path = os.path.join(here, "driver.py") + with open(path) as f: + text = f.read() + with open(path, "w") as f: + f.write(text.replace(' units.remove("slow")\n', + ' units.remove("slow")\n' + ' units = [u for u in units if u != "slow"]\n')) + one = dict(self.b, _version="1", _versions=["1", "2"], _default="2", _ref="fakebench@1", _labels={"1": "v1 (one)", "2": "v2"}) + return one, dict(one, _version="2", _ref="fakebench@2", _here=here) + + def test_a_set_made_at_a_version_records_it_and_a_run_at_another_that_lacks_a_task_is_refused(self): + one, two = self.versions() + entry = sets.create(one, "From one", dataset="all", units=["good", "slow"]) + self.assertEqual((entry["version"], sets.record(entry)["version"]), ("1", "1")) + self.assertEqual(sets.rows("fakebench")[0]["version"], "1") + r = run.Run(two, definitions.control(two, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=sets.record(entry)) + with self.assertRaises(run.Refused) as e: + r.start() + self.assertIn("the task set From one was made at Fake bench v1 (one), and slow is not a task of all at v2, the " + "version this run is at: run it at v1 (one), or make a set at v2", str(e.exception)) + self.assertEqual(self.trials(r.job_dir), []) + # at the version it was made at, or at another that holds all its tasks, it runs + for b, label in ((one, ""), (two, "Only good")): + if label: + entry = sets.create(one, label, dataset="all", units=["good"]) + r = run.Run(b, definitions.control(b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=sets.record(entry), name=f"at-{b['_version']}-{entry['name']}") + r.start() + self.assertEqual(len(self.trials(r.job_dir)), len(sets.latest(entry)["units"])) + + def test_a_run_without_a_set_records_none(self): + code, out, err = self.run_cli("--name", "plain") + self.assertEqual(code, 0, out + err) + cfg = read(os.path.join(self.jobs, "plain", "config.json")) + self.assertEqual(sorted(cfg["standard"]), ["backend", "benchmark", "benchmark_options", "control", "exchanges", + "exchanges_max_mb", "kind", "needs", "permissions_granted", "plugged", + "provider", "retries", "unsandboxed"]) + + +class Listing(Scratch): + def test_list_and_show_say_each_set_with_its_name_and_label(self): + self.make("dev", "good\nmodel\n", "--description", "two of them") + self.make("All four", "\n".join(DATASET)) + code, out, err = self.cli("set", "list", "--json") + self.assertEqual(code, 0, err) + rows = json.loads(out) + self.assertEqual([(r["name"], r["label"], r["units"]) for r in rows], [("all-four", "All four", 4), ("dev", "dev", 2)]) + self.assertTrue(all("revision" not in r for r in rows)) + code, out, err = self.cli("set", "list", "fakebench") + self.assertEqual(code, 0, err) + self.assertIn("two of them", out) + self.assertIn("All four", out) + code, out, err = self.cli("set", "show", "fakebench", "dev") + self.assertEqual(code, 0, err) + self.assertTrue(out.startswith("dev: 2 units of fakebench all\n"), out) + self.assertNotIn("revision", out) + self.assertEqual(out.strip().splitlines()[-2:], [" good", " model"]) + code, out, err = self.cli("set", "show", "fakebench", "all-four", "--json") + self.assertEqual((code, json.loads(out)["label"], len(json.loads(out)["units"])), (0, "All four", 4)) + code, out, err = self.cli("set", "list", "otherbench", "--json") + self.assertEqual((code, json.loads(out)), (0, [])) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_standard_shard.py b/app/tests/test_standard_shard.py index 89bebcc9..e26ed062 100644 --- a/app/tests/test_standard_shard.py +++ b/app/tests/test_standard_shard.py @@ -18,7 +18,7 @@ from nullius import workspace from nullius.runs import launches, parse from nullius.standard.proofs import prove -from nullius.standard.runner import job, merge, shard +from nullius.standard.runner import job, merge, rerun, shard BENCH = {"key": "fakebench", "_ref": "fakebench", "family": "agent", "needs": ["agent.workspace/v1"], "units": {"noun": "task", "nouns": "tasks"}, "score": {"kind": "pass", "says": "the tests pass"}} @@ -66,7 +66,7 @@ def test_a_shard_is_i_of_n(self): def write_shard(root, name, units, index, of, *, total=10, launch="L1", model="gpt-5-mini", bench=BENCH, other=AGENT, planned=None, t0=1_760_000_000.0, failed=(), budget=None, backend="local", bench_options=None, - reward=lambda place: float(place % 2)): + reward=lambda place: float(place % 2), task_set=None): """A shard job as a run writes it: its config, a trial per unit (tagged by the unit's place in the whole dataset), its result.""" d = os.path.join(root, name) @@ -74,7 +74,7 @@ def write_shard(root, name, units, index, of, *, total=10, launch="L1", model="g planned = list(units) if planned is None else planned job.write_config(d, job=name, bench=bench, other=other, model=model, provider="openai", dataset="all", units=planned, concurrency=2, granted=True, launch=launch, shard=shard.record(index, of, total, planned), backend=backend, - bench_options=bench_options) + bench_options=bench_options, task_set=task_set) results = [] for k, u in enumerate(units): place = int(u.split("-")[1]) @@ -180,6 +180,36 @@ def test_the_merged_job_carries_the_shards_spending_caps_as_one(self): self.assertNotIn("budget", read(os.path.join(part["out"], "result.json"))) self.assertEqual(parse.parse_job(part["out"]).budget, {}) + def test_the_merged_budget_keeps_later_parts_and_accepts_older_shards(self): + # Each shard spent 1 initially and 7 in a later part. + for totals, spent in (((8, 8), 16), ((8, None), 9.25), ((None, None), 2.5)): + with self.subTest(totals=totals), tempfile.TemporaryDirectory(dir=self.tmp) as root: + dirs = [] + for i, total in enumerate(totals): + budget = {"max_usd": 10, "spent_usd": 1} + if total is None: + budget["unsettled_usd"] = 0.25 + else: + budget["spent_total_usd"] = total + dirs.append(write_shard(root, f"shard-{i}", [f"t-{i}"], i + 1, 2, total=2, budget=budget)) + before = [read(os.path.join(d, "result.json")) for d in dirs] + out = merge.merge(dirs, os.path.join(root, "merged"))["out"] + got = rerun.budget(out) + self.assertEqual((got["max_usd"], got["spent_usd"], got["left_usd"]), (20, spent, 20 - spent)) + self.assertEqual([read(os.path.join(d, "result.json")) for d in dirs], before) + + def test_a_merged_job_one_shard_of_which_stopped_at_its_share_keeps_what_the_others_left(self): + # two shards capped at 10 each: one stopped at 9.90, the other spent 1; the merged job has 9.10 left + with tempfile.TemporaryDirectory(dir=self.tmp) as root: + dirs = [write_shard(root, f"shard-{i}", [f"t-{i}"], i + 1, 2, total=2, + budget={"max_usd": 10, "spent_usd": spent, "stopped": stopped, "cut_off": [], "not_run": []}) + for i, (spent, stopped) in enumerate(((9.9, True), (1, False)))] + out = merge.merge(dirs, os.path.join(root, "merged"))["out"] + self.assertEqual(read(os.path.join(out, "result.json"))["budget"]["shards_stopped"], 1) + got = rerun.budget(out) + self.assertEqual((got["max_usd"], got["closed"]), (20, False)) + self.assertAlmostEqual(got["left_usd"], 9.1) + def test_a_recorded_cap_is_read_leniently_and_an_amount_missing_is_not_zero(self): self.assertEqual(parse._budget(None), {}) self.assertEqual(parse._budget({"max_usd": "2", "spent_usd": 1}), {}) # no cap named: no cap @@ -212,6 +242,31 @@ def test_shards_of_different_launches_models_or_versions_are_refused_unless_forc got = merge.merge([a, b], os.path.join(self.tmp, "forced"), force=True) self.assertIn("merged_despite", read((os.path.join(got["out"], "config.json")))["standard"]) + def test_shards_of_two_task_sets_or_revisions_are_refused_unless_forced_and_the_merge_keeps_the_set(self): + units = sorted(self.split[1] + self.split[2] + self.split[3]) + def of(name="dev", rev=1, id_="a" * 32, digest=None): + return {"id": id_, "name": name, "revision": rev, "hash": digest or f"{rev}" * 64, "units": units} + a = write_shard(self.tmp, "a", self.split[1], 1, 3, task_set=of()) + # the whole id and hash are compared: one changed in its last character is another set, never named whole + changed = ("a" * 31 + "b", "1" * 63 + "b") + for name, rec in (("b-rev", of(rev=2)), ("b-other", of(name="other", id_="b" * 32)), + ("b-id", of(id_=changed[0])), ("b-hash", of(digest=changed[1])), ("b-none", None)): + with self.subTest(other=name): + b = write_shard(self.tmp, name, self.split[2], 2, 3, task_set=rec) + with self.assertRaisesRegex(merge.Refused, "task set: a 'dev@1 ") as refused: + merge.merge([a, b], os.path.join(self.tmp, "never")) + self.assertFalse(os.path.exists(os.path.join(self.tmp, "never"))) + self.assertFalse([value for value in changed if value in str(refused.exception)]) + got = merge.merge([a, b], os.path.join(self.tmp, "forced-" + name), force=True) + cfg = read(os.path.join(got["out"], "config.json"))["standard"] + self.assertEqual(cfg["task_set"], of()) + self.assertTrue(any(d.startswith("task set: ") for d in cfg["merged_despite"])) + b = write_shard(self.tmp, "b", self.split[2], 2, 3, task_set=of()) + got = merge.merge([a, b], os.path.join(self.tmp, "out", "run")) + cfg = read(os.path.join(got["out"], "config.json"))["standard"] + self.assertEqual(cfg["task_set"], of()) + self.assertNotIn("merged_despite", cfg) + def test_a_shard_recorded_with_docker_is_of_one_launch_with_a_container_shard(self): a = write_shard(self.tmp, "a", self.split[1], 1, 3, backend="docker") # the container backend's earlier name b = write_shard(self.tmp, "b", self.split[2], 2, 3, backend="container") diff --git a/app/tests/test_standard_units.py b/app/tests/test_standard_units.py index c7326721..8e172f98 100644 --- a/app/tests/test_standard_units.py +++ b/app/tests/test_standard_units.py @@ -193,6 +193,22 @@ def test_lists_of_the_same_units_merge_whatever_their_files_names_comments_or_or got = merge.merge([left, right], os.path.join(self.jobs, "merged")) self.assertEqual(got["trials"], 2) + def test_a_list_and_a_task_set_together_are_refused_before_any_unit(self): + listed = run.units_file(self.file("good\n")) + record = {"id": "0" * 32, "name": "dev", "revision": 1, "hash": "0" * 64, "units": ["model"]} + with self.assertRaisesRegex(run.Refused, "from a file or from a task set, not both"): + run.Run(self.b, definitions.control(self.b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, units_file=listed, task_set=record) + self.assertFalse(os.path.exists(self.jobs)) + + def test_a_task_sets_units_run_as_a_lists_do_and_its_record_is_kept(self): + record = {"id": "0" * 32, "name": "dev", "revision": 2, "hash": "0" * 64, "units": ["model", "wrong"]} + job = self.go(task_set=record, limit=1) + self.assertEqual(self.trials(job), ["wrong__u0001"]) + cfg = read(os.path.join(job, "config.json"))["standard"] + self.assertEqual(cfg["task_set"], record) + self.assertNotIn("units_file", cfg) + class FromTheCommandLine(unittest.TestCase): """``nullius standard run ... --units FILE``: the file read where the command runs, with or diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py new file mode 100644 index 00000000..82166c1f --- /dev/null +++ b/app/tests/test_standard_units_listing.py @@ -0,0 +1,546 @@ +"""The listing of a dataset's tasks (``standard/runner/units.py``, ``nullius standard units``): a search by the words +of an id, a title or a text; category values, either within a field and both across fields, each value +counted; 100 tasks a page with the total on every page; a driver without ``describe`` listed and searched by +its ids; the listing cached by its options; ``set create --search`` and ``--category`` storing the ids the +listing gives and the filter in its note; OSWorld1's ``describe`` from its task files. A definition's +``driver.list_command`` listing with no driver environment, OSWorld1's giving the driver's ids in its order; +``state`` giving each of its answers and starting nothing; the command's one line before a first listing that +fetches. No key, no network: each driver is a script of the test's own, the fake benchmark's or OSWorld1's on +task files of the test's own.""" +from __future__ import annotations + +import contextlib +import io +import json +import os +import shutil +import sys +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius import paths +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.runner import sets, units + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +OSWORLD1 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "catalogue", + "benchmarks", "osworld1") +# 250 tasks: t000 ... t249; kind by i % 3, size by i % 2; under mode=short only the first 20 +DRIVER = r'''import json, os, sys +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "started"), "a") as f: + f.write("started\n") +KINDS = ("alpha", "beta", "gamma") +N = 20 if os.environ.get("NULLIUS_OPTION_MODE") == "short" else 250 +IDS = [f"t{i:03d}" for i in range(N)] +def about(i): + title = "Open the spreadsheet" if i == 7 else f"Task number {i}" + text = "Rename the folder called Quokka" if i == 11 else f"Do thing {i} on the desktop" + return {"title": title, "text": text, "categories": {"kind": KINDS[i % 3], "size": "small" if i % 2 else "large"}} +for line in sys.stdin: + req = json.loads(line) + op = req.pop("op") + if op == "units": + out = {"units": IDS} + elif op == "describe": + out = {"units": {u: about(i) for i, u in enumerate(IDS)}} + else: + out = {"error": "no such op"} + print(json.dumps(out), flush=True) +''' +MODE = {"mode": {"summary": "how many tasks the listing gives", "values": ["long", "short"], "default": "long"}} + + +class Scratch(unittest.TestCase): + """A profile and a catalogue of the test's own; ``self.b`` a benchmark whose driver describes 250 tasks.""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="nullius-units-") + self.addCleanup(shutil.rmtree, self.tmp, True) + self.cat = os.path.join(self.tmp, "catalogue") + here = os.path.join(self.tmp, "described") + os.makedirs(here) + with open(os.path.join(here, "driver.py"), "w") as f: + f.write(DRIVER) + self.started = os.path.join(here, "started") + fake = definitions.get("benchmark", "fakebench", ROOT) + self.b = dict(fake, key="described", label="Described bench", _here=here, options=MODE, + datasets=[{"id": "all", "units": 250}], + driver={"command": [sys.executable, "{here}/driver.py"], "describe": True}) + self.plain = dict(fake) + for patch in (mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": self.cat, + "NULLIUS_HOME": os.path.join(self.tmp, "profile")}), + mock.patch.object(cli, "_find_bench", side_effect=lambda key: {"described": self.b, + "fakebench": self.plain}.get(key)), + mock.patch.object(cli.settings, "load")): + patch.start() + self.addCleanup(patch.stop) + + def starts(self) -> int: + if not os.path.exists(self.started): + return 0 + with open(self.started) as f: + return len(f.read().splitlines()) + + def cli(self, *args): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + code = cli.main(list(args)) + return code, out.getvalue(), err.getvalue() + + def ids(self, got): + return [t["id"] for t in got["tasks"]] + + +class Search(Scratch): + def test_the_plan_limit_follows_the_set_and_precedes_search_and_paging(self): + got = units.find(self.b, "all", {"mode": "short"}, within=["t007", "t019", "t024"], limit=1) + self.assertEqual((self.ids(got), got["of"]), (["t007"], 1)) + self.assertEqual(units.find(self.b, "all", limit=1, search="t007")["tasks"], []) + got = units.find(self.b, "all", limit=101, page=2) + self.assertEqual((self.ids(got), got["of"]), (["t100"], 101)) + self.assertEqual(units.find(self.b, "all", {"mode": "short"}, limit=100)["of"], 20) + + def test_a_word_of_an_id_a_title_or_a_text_finds_its_tasks_whatever_the_case(self): + for search, want in (("t042", ["t042"]), ("SPREADSHEET", ["t007"]), ("quokka folder", ["t011"]), + ("number 24", ["t024", "t124", "t224"] + [f"t{i}" for i in range(240, 250)])): + with self.subTest(search=search): + got = units.find(self.b, "all", search=search) + self.assertEqual((self.ids(got), got["total"], got["of"]), (want, len(want), 250)) + t = units.find(self.b, "all", search="t011")["tasks"][0] + self.assertEqual(t, {"id": "t011", "title": "Task number 11", "text": "Rename the folder called Quokka", + "categories": {"kind": "gamma", "size": "small"}}) + + def test_no_match_gives_an_empty_page_and_a_total_of_0(self): + got = units.find(self.b, "all", search="wombat") + self.assertEqual((got["tasks"], got["total"], got["pages"], got["of"]), ([], 0, 1, 250)) + self.assertEqual(got["categories"], {"kind": [], "size": []}) + + +class Categories(Scratch): + def test_one_value_two_values_of_one_field_and_two_fields_together(self): + one = units.find(self.b, "all", categories={"kind": ["alpha"]}, size=None) + self.assertEqual(one["total"], 84) # 0, 3, ..., 249 + self.assertTrue(all(t["categories"]["kind"] == "alpha" for t in one["tasks"])) + either = units.find(self.b, "all", categories={"kind": ["alpha", "beta"]}, size=None) + self.assertEqual(either["total"], 84 + 83) + both = units.find(self.b, "all", categories={"kind": ["alpha"], "size": ["small"]}, size=None) + self.assertEqual(both["total"], 42) # the odd ones of 0, 3, ..., 249 + self.assertTrue(all(t["categories"] == {"kind": "alpha", "size": "small"} for t in both["tasks"])) + + def test_each_value_is_counted_over_the_search_and_the_other_fields_filters(self): + got = units.find(self.b, "all") + self.assertEqual(got["categories"], {"kind": [{"value": "alpha", "count": 84}, {"value": "beta", "count": 83}, + {"value": "gamma", "count": 83}], + "size": [{"value": "large", "count": 125}, {"value": "small", "count": 125}]}) + chosen = units.find(self.b, "all", categories={"kind": ["alpha"]}) + # the field chosen keeps its other values' counts; the other field is counted over the alpha tasks + self.assertEqual(chosen["categories"]["kind"], got["categories"]["kind"]) + self.assertEqual(chosen["categories"]["size"], [{"value": "large", "count": 42}, {"value": "small", "count": 42}]) + searched = units.find(self.b, "all", search="number 24", categories={"size": ["small"]}) + self.assertEqual(self.ids(searched), ["t241", "t243", "t245", "t247", "t249"]) + self.assertEqual(searched["categories"]["size"], [{"value": "large", "count": 8}, {"value": "small", "count": 5}]) + + def test_a_field_no_task_has_is_refused(self): + with self.assertRaisesRegex(units.Refused, "--category colour: no such category; the categories are kind, size"): + units.find(self.b, "all", categories={"colour": ["red"]}) + self.assertEqual(units.find(self.b, "all", categories={"kind": ["delta"]})["total"], 0) + + +class Pages(Scratch): + def test_250_tasks_come_as_three_pages_with_the_same_total(self): + pages = [units.find(self.b, "all", page=n) for n in (1, 2, 3, 4)] + self.assertEqual([len(p["tasks"]) for p in pages], [100, 100, 50, 0]) + self.assertEqual({(p["total"], p["pages"]) for p in pages}, {(250, 3)}) + self.assertEqual(sum((self.ids(p) for p in pages), []), [f"t{i:03d}" for i in range(250)]) + with self.assertRaisesRegex(units.Refused, "page 0"): + units.find(self.b, "all", page=0) + + +class WithoutDescribe(Scratch): + def test_the_listing_gives_ids_and_a_search_matches_ids(self): + got = units.find(self.plain, "all") + self.assertEqual((self.ids(got), got["described"], got["categories"]), (["good", "wrong", "slow", "model"], False, {})) + self.assertEqual(got["tasks"][0], {"id": "good", "title": "", "text": "", "categories": {}}) + self.assertEqual(self.ids(units.find(self.plain, "all", search="MOD")), ["model"]) + with self.assertRaisesRegex(units.Refused, "no such category; these tasks have none"): + units.find(self.plain, "all", categories={"kind": ["alpha"]}) + code, out, err = self.cli("units", "fakebench", "--dataset", "all", "--search", "od") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.splitlines(), ["2 of 4 tasks of all (its driver gives ids alone: a search reads the ids)", + " good", " model"]) + + +class Cache(Scratch): + def test_cache_links_cannot_read_or_write_outside_the_cache_root(self): + path = Path(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"})) + outside = Path(self.tmp, "outside-cache") + outside.mkdir() + cached = outside / "listing.json" + cached.write_text(json.dumps({"tasks": [], "described": False})) + for link, target in ((path.parent.parent, outside), (path.parent, outside), (path, cached)): + with self.subTest(link=link.name): + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(target, target_is_directory=target.is_dir()) + before = {p.name: p.read_bytes() for p in outside.iterdir()} + try: + with self.assertRaisesRegex(units.Refused, "outside the cache root"): + units.listing(self.b, "all") + self.assertEqual(units.state(self.b, "all")["state"], "refused") + self.assertEqual(self.starts(), 0) + self.assertEqual({p.name: p.read_bytes() for p in outside.iterdir()}, before) + finally: + link.unlink() + + def test_a_linked_cache_root_keeps_the_listing_under_its_resolved_root(self): + root = Path(paths.cache_dir()) + destination = Path(self.tmp, "cache-disk") + destination.mkdir() + root.parent.mkdir(parents=True, exist_ok=True) + root.symlink_to(destination, target_is_directory=True) + got = units.listing(self.b, "all") + path = Path(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"})) + self.assertTrue(path.resolve().is_relative_to(destination)) + self.assertEqual(json.loads(path.read_text()), got) + self.assertEqual(units.state(self.b, "all")["state"], "cached") + self.assertEqual(units.listing(self.b, "all"), got) + self.assertEqual(self.starts(), 1) + + def test_the_second_listing_starts_no_driver_and_another_option_lists_again(self): + units.find(self.b, "all") + units.find(self.b, "all", search="t1", page=2) + self.assertEqual(self.starts(), 1) + short = units.find(self.b, "all", {"mode": "short"}) + self.assertEqual((short["total"], self.starts()), (20, 2)) + units.find(self.b, "all", {"mode": "long"}) # the default, given: the same listing + self.assertEqual(self.starts(), 2) + self.assertTrue(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"}).startswith(paths.cache_dir())) + with self.assertRaisesRegex(units.Refused, "mode"): + units.find(self.b, "all", {"mode": "sideways"}) + with self.assertRaisesRegex(units.NotFound, "no dataset 'nope'"): + units.find(self.b, "nope") + + def test_a_driver_that_cannot_list_is_refused_with_its_words(self): + with open(os.path.join(self.b["_here"], "driver.py"), "w") as f: + f.write("import sys\nprint('the data is not there', file=sys.stderr)\nsys.exit(3)\n") + with self.assertRaisesRegex(units.Refused, "could not list the dataset all: .*the data is not there"): + units.find(self.b, "all") + self.assertEqual(os.listdir(os.path.join(paths.cache_dir(), units.FOLDER)), []) # nothing kept, no work left + + +class CommandLine(Scratch): + def test_the_command_prints_the_count_the_categories_and_the_tasks(self): + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "number 24", + "--category", "size=small") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.splitlines(), ["5 of 250 tasks of all", "kind: alpha 2, beta 2, gamma 1", "size: large 8, small 5", + " t241 Task number 241", " t243 Task number 243", " t245 Task number 245", + " t247 Task number 247", " t249 Task number 249"]) + code, out, err = self.cli("units", "described", "--dataset", "all", "--category", "kind=beta", "--json") + got = json.loads(out) + self.assertEqual((code, got["total"], got["pages"], len(got["tasks"])), (0, 83, 1, 83)) + + def test_the_longmemeval_help_example_names_a_known_dataset(self): + import shlex + example = next(line for line in cli.UNITS_EPILOG.splitlines() if "units longmemeval" in line) + args = shlex.split(example) + bench = definitions.get("benchmark", "longmemeval") + dataset = args[args.index("--dataset") + 1] + self.assertEqual(units.dataset_of(bench, dataset)["id"], "longmemeval_oracle") + self.assertEqual(units.option_values(bench, dataset, {"question_type": "multi-session"})["question_type"], + "multi-session") + + def test_refusals_are_one_line_on_stderr(self): + for args, code, said in ((["units", "nowhere", "--dataset", "all"], 3, "no benchmark 'nowhere'"), + (["units", "described", "--dataset", "nope"], 3, "no dataset 'nope'"), + (["units", "described", "--dataset", "all", "--category", "kind"], 2, "FIELD=VALUE"), + (["units", "described", "--dataset", "all", "--bench-option", "mode=x"], 2, "mode"), + (["units", "described", "--dataset", "all", "--bench-option", "broken"], 2, "NAME=VALUE")): + with self.subTest(args=args): + got, out, err = self.cli(*args) + self.assertEqual((got, out), (code, "")) + self.assertTrue(err.startswith("refused: ") and said in err and len(err.splitlines()) == 1, err) + + +class SetFromAFilter(Scratch): + def test_the_ids_stored_are_the_ones_the_listing_gives_and_the_note_holds_the_filter(self): + code, out, err = self.cli("set", "create", "described", "picked", "--dataset", "all", "--search", "number 24", + "--category", "kind=alpha", "--category", "kind=beta") + self.assertEqual(code, 0, err) + entry = sets.load("described", "picked") + listed = units.find(self.b, "all", search="number 24", categories={"kind": ["alpha", "beta"]}, size=None) + self.assertEqual(sets.revision(entry)["units"], self.ids(listed)) + self.assertEqual(sets.revision(entry)["units"], ["t024", "t124", "t240", "t241", "t243", "t244", "t246", "t247", "t249"]) + self.assertEqual(sets.revision(entry)["note"], + 'matched by --search "number 24" --category kind=alpha --category kind=beta') + code, out, err = self.cli("set", "create", "described", "by-kind", "--dataset", "all", "--category", "kind=gamma") + self.assertEqual(code, 0, err) + self.assertEqual(len(sets.revision(sets.load("described", "by-kind"))["units"]), 83) + + def test_a_filter_that_matches_nothing_or_beside_another_source_is_refused(self): + for args, said in ((["--search", "wombat"], "no task of all matches --search \"wombat\""), + (["--search", "t1", "--units", os.path.join(self.tmp, "x.txt")], "--units FILE, --from-job"), + ([], "--units FILE, --from-job")): + with self.subTest(args=args): + code, out, err = self.cli("set", "create", "described", "none", "--dataset", "all", *args) + self.assertEqual((code, out), (2, "")) + self.assertIn(said, err) + self.assertFalse(os.path.exists(os.path.join(self.cat, "sets"))) + + +ASKED = AssertionError("the listing asked for the driver's environment") +HEAVY = {"command": ["{install}/.venv/bin/python", "{here}/driver.py"], + "install": {"python": "3.12", "pip": ["nothing-installed==1.0"]}, "describe": True} + + +def no_environment(): + """Each way to the driver's environment fails the test.""" + stack = contextlib.ExitStack() + for name in ("driver_argv", "driver_packages", "packages"): + stack.enter_context(mock.patch.object(units.install, name, side_effect=ASKED)) + return stack + + +class LightCommand(Scratch): + def test_the_light_command_lists_and_the_drivers_environment_is_never_asked_for(self): + light = dict(self.b, driver=dict(HEAVY, list_command=[sys.executable, "{here}/driver.py"])) + with no_environment(): + got = units.find(light, "all", size=None) + self.assertEqual((got["total"], got["described"], self.starts()), (250, True, 1)) + self.assertEqual(got["tasks"], units.find(self.b, "all", size=None)["tasks"]) # as the driver's own start + with mock.patch.object(units.install, "upstream", return_value=None) as up, \ + mock.patch.object(units.install, "dataset", return_value=None) as data, no_environment(): + units.listing(dict(light, options={}), "all") # another definition: listed again + self.assertEqual((up.call_count, data.call_count), (1, 1)) # the upstream and the dataset, prepared + + def test_a_light_command_that_cannot_start_is_refused(self): + light = dict(self.b, driver=dict(HEAVY, list_command=["/nonexistent/python3", "{here}/driver.py"])) + with no_environment(), self.assertRaisesRegex(units.Refused, "cannot start described's driver for its listing"): + units.listing(light, "all") + + +class Definition(unittest.TestCase): + def test_a_list_command_is_checked_as_the_other_commands_are(self): + bench = {"schema": "nullius.benchmark/v1", "key": "fixture", "label": "Fixture", "summary": "A task.", + "family": "agent", "needs": ["agent.task/v1"], "driver": dict(HEAVY), + "datasets": [{"id": "all", "units": 1}], "units": {"noun": "task", "nouns": "tasks"}, + "score": {"kind": "pass", "says": "the answer is right"}} + ok = dict(bench, driver=dict(HEAVY, list_command=["python3", "{here}/driver.py"])) + self.assertEqual(definitions.problems(ok, "benchmark"), []) + for words, said in (([], "driver.list_command: a list of words"), + ("python3 {here}/driver.py", "driver.list_command: a list of words"), + (["python3", 3], "driver.list_command: a list of words"), + (["python3 -I", "{here}/driver.py"], "driver.list_command: 'python3 -I' is not a plain word"), + (["{install}/.venv/bin/python", "{here}/driver.py"], + "driver.list_command: {install} is not a slot (here)")): + with self.subTest(words=words): + self.assertIn(said, definitions.problems(dict(bench, driver=dict(HEAVY, list_command=words)), "benchmark")) + with open(os.path.join(OSWORLD1, "standard.json"), encoding="utf-8") as f: + osworld1 = json.load(f) + # its agent option is filled from its agents.json on loading: each version is checked as the loader reads it + for ref in ("osworld1", "osworld1@044bc33"): + with self.subTest(ref=ref): + self.assertEqual(definitions.problems(definitions.get("benchmark", ref, root=definitions.CATALOGUE), "benchmark"), []) + self.assertEqual(osworld1["driver"]["list_command"][1:], osworld1["driver"]["command"][1:]) + for v, block in osworld1["versions"].items(): # a version's driver replaces the shared one whole + driver = block.get("driver") or osworld1["driver"] + with self.subTest(version=v): + self.assertIs(driver.get("describe"), True) + self.assertEqual(driver.get("list_command"), osworld1["driver"]["list_command"]) + + +class State(Scratch): + """``units.state`` asked with every fetch and start failing the test, the files it could touch the same after.""" + + def tree(self) -> list: + got = [] + for top in (self.tmp, units.install.HOME): + for root, dirs, files in os.walk(top): + for name in dirs + files: + path = os.path.join(root, name) + got.append((path, Path(path).read_bytes() if name in files else None)) + return sorted(got) + + def asked(self, bench, dataset="all", options=None, programs=("git", "uv", "npm")): + before, started = self.tree(), self.starts() + with contextlib.ExitStack() as stack: + for name in ("upstream", "dataset", "download", "driver_argv", "driver_packages", "packages"): + stack.enter_context(mock.patch.object(units.install, name, side_effect=AssertionError(name))) + stack.enter_context(mock.patch.object(units.jsonl, "Proc", side_effect=AssertionError("a driver started"))) + stack.enter_context(mock.patch.object(units.shutil, "which", + side_effect=lambda w: f"/usr/bin/{w}" if w in programs else None)) + got = units.state(bench, dataset, options) + self.assertEqual((self.tree(), self.starts()), (before, started)) + return got + + def fetching(self, **driver) -> dict: + return dict(self.b, upstream={"repository": "https://example.org/upstream.git", "tested": "a" * 40}, + datasets=[{"id": "all", "url": "https://example.org/all.json", "sha256": "b" * 64, "units": 250}], + driver=dict(HEAVY, **driver)) + + def test_cached(self): + units.find(self.b, "all") + self.assertEqual(self.asked(self.b), {"state": "cached", "fetch": [], "reason": ""}) + self.assertEqual(self.asked(self.b, options={"mode": "short"})["state"], "full") # not listed under it + + def test_light_and_what_it_fetches(self): + light = [sys.executable, "{here}/driver.py"] + self.assertEqual(self.asked(dict(self.b, driver=dict(HEAVY, list_command=light))), + {"state": "light", "fetch": [], "reason": ""}) + got = self.asked(self.fetching(list_command=light)) + self.assertEqual((got["state"], got["reason"]), ("light", "")) + self.assertEqual(got["fetch"], [{"what": "upstream", "text": "the upstream https://example.org/upstream.git at aaaaaaaaaaaa"}, + {"what": "dataset", "text": "the dataset https://example.org/all.json"}]) + + def test_a_prepared_upstream_must_hold_the_datasets_file(self): + up = Path(self.tmp, "upstream") + up.mkdir() + bench = dict(self.fetching(list_command=[sys.executable, "{here}/driver.py"]), + datasets=[{"id": "all", "path": "absent.json", "sha256": "b" * 64, "units": 250}]) + with mock.patch.object(units.install, "upstream_dir", return_value=str(up)): + self.assertEqual(self.asked(bench)["state"], "light") + self.assertEqual([f["what"] for f in self.asked(bench)["fetch"]], ["upstream"]) + (up / units.install.MARK).touch() + got = self.asked(bench) + self.assertEqual((got["state"], got["fetch"]), ("refused", [])) + self.assertIn("absent.json is not in the upstream", got["reason"]) + + def test_a_present_dataset_is_not_checksummed_by_state(self): + data = Path(self.b["_here"], "data.json") + data.write_text("{}") + bench = dict(self.b, datasets=[{"id": "all", "path": "data.json", "sha256": "b" * 64, "units": 250}], + driver=dict(HEAVY, list_command=[sys.executable, "{here}/driver.py"])) + sha256 = units.ondisk.sha256_of + + def digest(path): + self.assertNotEqual(Path(path), data) + return sha256(path) + + with mock.patch.object(units.ondisk, "sha256_of", side_effect=digest): + self.assertEqual(self.asked(bench), {"state": "light", "fetch": [], "reason": ""}) + + def test_full_and_the_environment_it_installs(self): + self.assertEqual(self.asked(self.b), {"state": "full", "fetch": [], "reason": ""}) + got = self.asked(self.fetching()) + self.assertEqual((got["state"], [f["what"] for f in got["fetch"]]), ("full", ["upstream", "dataset", "environment"])) + self.assertEqual(got["fetch"][2]["text"], "the driver's environment, installed with uv") + + def test_refused_with_its_reason(self): + for bench, options, programs, said in ( + (self.b, {"mode": "sideways"}, ("git", "uv"), "mode"), + (self.fetching(), None, ("git",), "cannot prepare described's dataset all for its listing: " + "uv is not on this machine"), + (self.fetching(list_command=[sys.executable, "{here}/driver.py"]), None, ("uv",), "git is not on this machine"), + (dict(self.b, driver=dict(HEAVY, list_command=["python3", "{here}/driver.py"])), None, ("git",), + "python3 is not on this machine"), + (dict(self.b, datasets=[{"id": "all", "path": "absent.json", "sha256": "c" * 64, "units": 1}]), None, + ("git",), "dataset all: absent.json is not in the definition folder")): + with self.subTest(said=said): + got = self.asked(bench, options=options, programs=programs) + self.assertEqual((got["state"], got["fetch"]), ("refused", [])) + self.assertIn(said, got["reason"]) + with self.assertRaisesRegex(units.NotFound, "no dataset 'nope'"): + self.asked(self.b, "nope") + + +class FirstListing(Scratch): + def test_the_command_says_in_one_line_what_a_first_listing_fetches(self): + data = os.path.join(self.tmp, "fetched.json") + self.b = dict(self.b, datasets=[{"id": "all", "url": "https://example.org/all.json", "sha256": "b" * 64, + "units": 250}]) + + def fetched(url, sha256, progress=None): + open(data, "w").close() + return data + + with mock.patch.object(units.install, "download", side_effect=fetched) as download: + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") + self.assertEqual((code, out.splitlines()[0], err), (0, "1 of 250 tasks of all", + "first listing of all: fetching the dataset " + "https://example.org/all.json\n")) + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") + self.assertEqual((code, err, download.call_count, self.starts()), (0, "", 1, 1)) # the second from the cache + + def test_a_program_not_on_this_machine_is_refused_before_anything_is_fetched(self): + self.b = dict(self.b, driver=dict(HEAVY, list_command=["/nonexistent/python3", "{here}/driver.py"])) + with no_environment(): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual((code, out, self.starts()), (2, "", 0)) + self.assertEqual(err, "refused: cannot prepare described's dataset all for its listing: " + "/nonexistent/python3 is not on this machine\n") + + +def osworld1_upstream(tmp: str, tasks: dict) -> str: + """An upstream folder of OSWorld's shape holding ``tasks`` ({domain: {id: instruction}}); its dataset file's path.""" + for domain, ids in tasks.items(): + os.makedirs(os.path.join(tmp, "evaluation_examples", "examples", domain)) + for eid, instruction in ids.items(): + with open(os.path.join(tmp, "evaluation_examples", "examples", domain, eid + ".json"), "w") as f: + json.dump({"id": eid, "instruction": instruction}, f) + meta = os.path.join(tmp, "test_small.json") + with open(meta, "w") as f: + json.dump({d: list(ids) for d, ids in tasks.items()}, f) + return meta + + +class OSWorld1Light(Scratch): + def test_its_light_listing_gives_the_drivers_ids_in_its_order_with_no_environment(self): + up = os.path.join(self.tmp, "upstream") + meta = osworld1_upstream(up, {"vlc": {"v2": "Play the video.", "v1": "Mute it."}, "chrome": {"c1": "Open a tab."}}) + bench = definitions.get("benchmark", "osworld1") + with mock.patch.object(units.install, "upstream", return_value=up), \ + mock.patch.object(units.install, "dataset", return_value=meta), no_environment(): + got = units.listing(bench, "test_small") + earlier = units.listing(definitions.get("benchmark", "osworld1@044bc33"), "test_small") + self.assertEqual(earlier["tasks"], got["tasks"]) # each version lists by the same light start + import importlib.util + spec = importlib.util.spec_from_file_location("osworld1_driver_units", os.path.join(OSWORLD1, "driver.py")) + driver = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"NULLIUS_UPSTREAM": up, "NULLIUS_DATASET": meta}), \ + mock.patch.object(sys, "argv", ["driver.py"]): + spec.loader.exec_module(driver) + ids = driver.units(dataset="test_small")["units"] + self.assertEqual([t["id"] for t in got["tasks"]], ids) + self.assertEqual(ids, ["vlc__v2", "vlc__v1", "chrome__c1"]) + self.assertEqual(got["tasks"][0], {"id": "vlc__v2", "title": "Play the video.", "text": "Play the video.", + "categories": {"domain": "vlc"}}) + + +class OSWorld1(unittest.TestCase): + def test_describe_gives_each_tasks_instruction_and_domain_from_its_file(self): + tmp = tempfile.mkdtemp(prefix="nullius-osworld1-") + self.addCleanup(shutil.rmtree, tmp, True) + long = "Please " + "open the settings and change the theme " * 4 + "now." + tasks = {"chrome": {"c1": "Open a new tab."}, "vlc": {"v1": long}} + for domain, ids in tasks.items(): + os.makedirs(os.path.join(tmp, "evaluation_examples", "examples", domain)) + for eid, instruction in ids.items(): + with open(os.path.join(tmp, "evaluation_examples", "examples", domain, eid + ".json"), "w") as f: + json.dump({"id": eid, "instruction": instruction}, f) + meta = os.path.join(tmp, "test_small.json") + with open(meta, "w") as f: + json.dump({d: list(ids) for d, ids in tasks.items()}, f) + import importlib.util + spec = importlib.util.spec_from_file_location("osworld1_driver_describe", os.path.join(OSWORLD1, "driver.py")) + driver = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"NULLIUS_UPSTREAM": tmp, "NULLIUS_DATASET": meta}), \ + mock.patch.object(sys, "argv", ["driver.py"]): + spec.loader.exec_module(driver) + got = driver.describe(dataset="test_small")["units"] + self.assertIs(driver.HANDLERS["describe"], driver.describe) + self.assertEqual(list(got), ["chrome__c1", "vlc__v1"]) + self.assertEqual(got["chrome__c1"], {"title": "Open a new tab.", "text": "Open a new tab.", + "categories": {"domain": "chrome"}}) + self.assertEqual(got["vlc__v1"]["text"], long) + self.assertTrue(got["vlc__v1"]["title"].endswith(" ...") and len(got["vlc__v1"]["title"]) <= 104) + self.assertTrue(long.startswith(got["vlc__v1"]["title"][:-4])) + self.assertEqual(got["vlc__v1"]["categories"], {"domain": "vlc"}) + with open(os.path.join(OSWORLD1, "standard.json")) as f: + self.assertIs(json.load(f)["driver"]["describe"], True) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_task_set_recipe.py b/app/tests/test_task_set_recipe.py new file mode 100644 index 00000000..a5395c1a --- /dev/null +++ b/app/tests/test_task_set_recipe.py @@ -0,0 +1,141 @@ +"""A task set in the builder's recipe and on a host: ``task_sets`` compiles to ``--set NAME`` beside the +dataset, its label and count in the Review step; a set of another benchmark or dataset is refused; the runner snapshot a +host receives carries the recipe's sets, and a run started from it there reads the set and records it. No key, +no network: the runs are the fake benchmark's control.""" +from __future__ import annotations + +import io +import json +import os +import shutil +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius import progress +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.requirements import install +from nullius.standard.runner import payload, sets + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +NOP = {"nop": {"source": "nullius", "from": "nothing said"}} + + +class Scratch(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-set-recipe-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.cat = self.tmp / "catalogue" + self.b = dict(definitions.get("benchmark", "fakebench", ROOT), controls=NOP, + datasets=[{"id": "all", "units": 4}, {"id": "more", "units": 4}]) + self.memo = definitions.get("benchmark", "fakememo", ROOT) + for patch in (mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(self.cat)}), + mock.patch.object(install, "HOME", str(self.tmp / "home")), mock.patch.object(progress, "ECHO", None)): + patch.start() + self.addCleanup(patch.stop) + self.defs = {"benchmark": [self.b, self.memo], "agent": [], "capability": []} + + def recipe(self, **kw): + r = {"version": 1, "harness": "standard", "name": "fake-sets", "title": "t", "benchmark": "fakebench", "datasets": ["all"], + "others": ["nop"], "provider": "openai", "model": "", "concurrency": 1, "where": "local"} + r.update(kw) + return r + + def compile(self, **kw): + return recipe.compile(self.recipe(**kw), self.defs) + + +class TheRecipe(Scratch): + def test_a_set_compiles_to_set_name_and_review_names_its_label_and_its_count(self): + sets.create(self.b, "Dev set", dataset="all", units=["good", "wrong", "slow"]) + # a recipe from before sets were frozen names it NAME@1: the same set + for ref, n in (("dev-set", 3), ("dev-set@1", 3)): + with self.subTest(ref=ref): + out = self.compile(task_sets={"all": ref}) + self.assertEqual(out["errors"], []) + self.assertIn("--dataset all --set dev-set -j 1", out["shards"][0]["command"]) + dataset_row = next(r for r in out["review"] if r[1] == "Dataset") + self.assertEqual(dataset_row[2], f"all · task set Dev set · {n} tasks") + self.assertNotIn("revision", json.dumps(out["review"])) + self.assertTrue(next(r for r in out["review"] if r[1] == "Scope")[2].startswith(f"{n} planned, {n} to begin")) + self.assertEqual(out["confirm"], "") # the set is the choice of tasks: Run asks nothing more + out = self.compile(task_sets={"all": "dev-set"}, limit=2, where=["local", "me@bench"]) # a shard's limit is its own + self.assertTrue(next(r for r in out["review"] if r[1] == "Scope")[2].startswith("2 planned, 2 to begin of each shard")) + + def test_a_set_of_another_benchmark_or_dataset_or_a_dataset_not_chosen_is_refused(self): + sets.create(self.memo, "theirs", dataset=self.memo["datasets"][0]["id"], units=["x"]) + sets.create(self.b, "other-ds", dataset="more", units=["good"]) + sets.create(self.b, "dev", dataset="all", units=["good"]) + for kw, said in (({"task_sets": {"all": "theirs"}}, "Fake bench has no task set theirs: choose another, or all of all's tasks."), + ({"task_sets": {"all": "other-ds"}}, "The task set other-ds is cut from the dataset more, not all."), + ({"task_sets": {"more": "dev"}}, "The task set dev is for more, a dataset not chosen."), + ({"task_sets": {"all": "dev@4"}}, "Task set dev@4: dev@4 names an earlier list of the task set dev: " + "a set is read as its latest list now; name it dev."), + ({"task_sets": {"all": "a/b"}}, "Task set a/b: 'a/b' is not a task set's name"), + ({"task_sets": ["dev"]}, "Task sets are a dataset with a set's name each.")): + with self.subTest(kw=kw): + out = self.compile(**kw) + self.assertEqual([e["step"] for e in out["errors"]], [recipe.STEP["dataset"]]) + self.assertTrue(out["errors"][0]["message"].startswith(said), out["errors"][0]["message"]) + + def test_a_recipe_without_a_set_compiles_as_before(self): + sets.create(self.b, "dev", dataset="all", units=["good"]) + plain, empty = self.compile(), self.compile(task_sets={}) + self.assertEqual(plain, empty) + self.assertEqual(plain["shards"][0]["command"], + 'nullius standard run fakebench nop --provider openai --dataset all -j 1 ' + '--name fake-sets --from-run --jobs "${NULLIUS_JOBS:-jobs_standard}"') + self.assertEqual(next(r for r in plain["review"] if r[1] == "Dataset")[2], "all · 4 tasks") + + def test_the_builder_offers_each_datasets_sets(self): + sets.create(self.b, "dev", dataset="all", units=["good", "wrong"], description="two") + page = recipe._bench_page(self.b) + self.assertEqual([[(s["name"], s["label"], s["units"], s["description"]) for s in d["sets"]] for d in page["datasets"]], + [[("dev", "dev", 2, "two")], []]) + self.assertTrue(all("revision" not in s for d in page["datasets"] for s in d["sets"])) + + +class OnAHost(Scratch): + """What the app sends a host for a recipe with a set: the snapshot holds the set's entry; the run there, reading + the copy of the snapshot's catalogue a host run reads, runs the set and records it.""" + + def test_the_snapshot_carries_the_recipes_sets_and_the_run_there_records_the_set(self): + entry = sets.create(self.b, "settings", dataset="all", units=["good", "wrong"]) + r = self.recipe(task_sets={"all": "settings"}) + self.assertEqual(payload.recipe_sets(r), [("fakebench", "settings")]) + self.assertEqual(payload.recipe_sets(self.recipe()), []) + empty = self.tmp / "empty-package" + shutil.copytree(Path(payload.PACKAGE), empty, ignore=shutil.ignore_patterns("__pycache__", "catalogue", "kits")) + key0, _ = payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat)) + key, here = payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), sets=payload.recipe_sets(r)) + self.assertNotEqual(key, key0) + self.assertEqual(payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), + sets=payload.recipe_sets(r)), (key, here)) + carried = Path(here) / "app/nullius/catalogue/sets/fakebench/settings.json" + self.assertEqual(json.loads(carried.read_text())["id"], entry["id"]) + for name in ("gone", "../settings"): + with self.assertRaises(ValueError): + payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), sets=[("fakebench", name)]) + # on the host: the snapshot's catalogue copied for the run (execution: cp -R .../app/nullius/catalogue), read there + run_catalogue = self.tmp / "host" / "runs" / "fake-sets" / "catalogue" + shutil.copytree(Path(here) / "app/nullius/catalogue", run_catalogue) + shutil.rmtree(self.cat) # nothing of this machine's catalogue is left to read + jobs = self.tmp / "host" / "runs" / "fake-sets" / "jobs" + out, err = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(run_catalogue)}), \ + mock.patch.object(cli, "_bench", return_value=self.b), mock.patch.object(cli, "_exit_on_term"), \ + mock.patch.object(cli.settings, "load"), redirect_stdout(out), redirect_stderr(err): + code = cli.main(["run", "fakebench", "nop", "--dataset", "all", "--set", "settings", "-j", "1", "--name", "fake-sets", + "--jobs", str(jobs)]) + self.assertEqual(code, 0, out.getvalue() + err.getvalue()) + cfg = json.loads((jobs / "fake-sets" / "config.json").read_text()) + self.assertEqual(cfg["standard"]["task_set"], sets.record(entry)) + self.assertEqual(sorted(d for d in os.listdir(jobs / "fake-sets") if "__u" in d), ["good__u0000", "wrong__u0001"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_attempt_routes.py b/app/ui_tests/test_attempt_routes.py index d8143cd4..24a8fd35 100644 --- a/app/ui_tests/test_attempt_routes.py +++ b/app/ui_tests/test_attempt_routes.py @@ -265,17 +265,18 @@ def try_tabs(html): (False, kept, "Attempt 2 · Try 2", '1/1'), (False, "/trial/retried-run/0001__u0000r3", "Attempt 3", '0/1')]) - def test_no_retries_column_without_the_runs_limit(self): - # a trial that says it was retried, in a run that allowed none: Harbor - # says no attempt's retries, so there is no count to put over a limit + def test_tries_without_the_runs_limit_show_their_count_and_no_limit(self): + # a trial that says it was tried before, in a run that allowed no retries (run again by hand): the job's + # page shows the column with its count and no limit to put it over; the attempts page has no column run = written_job(self.root, "unlimited-run", [("u__a", "u", 0, 1, None), ("u__b", "u", 2, 0, None)]) path = self.root / "unlimited-run" / "u__a" / "result.json" res = json.loads(path.read_text()); res["standard"] = {"unit": "u", "retries": 1}; path.write_text(json.dumps(res)) run = parse.parse_job(str(self.root / "unlimited-run")) self.assertEqual(run.retries, 0) self.stack.enter_context(patch.object(workspace, "load_jobs", return_value=[run])) - self.assertNotIn("Retries", self.get("/job/unlimited-run")) - self.assertNotIn("run-retries", self.get("/job/unlimited-run")) + html = self.get("/job/unlimited-run") + self.assertIn('Retries', html) + self.assertEqual(re.findall(r'(.*?)', html), ["1", '0']) self.assertNotIn("Retries", self.get("/trial/unlimited-run/u__a/attempts")) def test_an_unknown_trial_has_no_attempts_page(self): diff --git a/app/ui_tests/test_builder_limits.py b/app/ui_tests/test_builder_limits.py index 5854667e..8486e997 100644 --- a/app/ui_tests/test_builder_limits.py +++ b/app/ui_tests/test_builder_limits.py @@ -69,3 +69,21 @@ def test_a_click_on_a_card_of_what_the_record_keeps_reaches_the_command_line(sel else: # the default: the run is told nothing self.assertNotIn("exchanges", kept) self.assertNotIn("--exchanges", out["script"]) + + def test_the_number_of_tasks_says_all_of_them_and_takes_that_many_at_most(self): + field = lambda html: re.search(r'
    ', self.section("gaia"), re.S).group(1) + self.assertIn('New task set', head) + self.assertIn('
    ', head) # a menu: not a disclosure, no chevron + for d in gaia["datasets"]: # several datasets: a choice of them, each its tasks' page + self.assertIn(f'{d.get("label") or d["id"]}', head) + [only] = _GET("benchmark", "humaneval")["datasets"] + one = self.section("humaneval") # one dataset: the button is its link + self.assertIn(f'New task set', one) + self.assertNotIn("bench-newset", one) + r = self.client.get("/benchmarks/humaneval", headers={"X-Forwarded-For": "192.0.2.4"}); self.addCleanup(r.close) + self.assertNotIn("New task set", r.get_data(as_text=True)) # saving is a browser's on the application host + + def test_it_lists_the_benchmarks_sets_with_the_version_each_was_made_at(self): + osw = _GET("benchmark", "osworld1") + sets.create(osw, "Chrome tabs", dataset="test_nogdrive", units=["a", "b", "c", "d"], description="four of them") + earlier = _GET("benchmark", "osworld1@044bc33") + sets.create(earlier, "Chrome tabs", dataset="test_nogdrive", units=["a"]) + text = visible(self.section("osworld1")) + own = len([d for d in osw["datasets"] if d.get("subset_of")]) # the benchmark's own sets, counted too + self.assertIn(f"Task sets {2 + own}", text) + self.assertNotIn("Revision", text) + label = next(d.get("label") or d["id"] for d in osw["datasets"] if d["id"] == "test_nogdrive") + self.assertRegex(text, re.escape(f"Chrome tabs four of them {label} 4 {osw['_version']} ") + r"\d{4}-\d\d-\d\d") + self.assertRegex(text, re.escape(f"Chrome tabs {label} 1 main (044bc33) ") + r"\d{4}-\d\d-\d\d") + self.assertIn('href="/benchmarks/osworld1/tasks/test_nogdrive?set=chrome-tabs"', self.section("osworld1")) + self.assertIn('href="/benchmarks/osworld1/tasks/test_nogdrive?set=chrome-tabs-2"', self.section("osworld1")) + + +class TheBenchmarksOwnSets(Case): + """A benchmark whose lists name the one they are cut from: its page and the builder draw one dataset, and its cuts as + the benchmark's own task sets, before the user's.""" + + def section(self, key): + html = self.get(f"/benchmarks/{key}").get_data(as_text=True) + return re.search(r'
    ', html, re.S).group(0) + + def test_the_page_lists_its_own_sets_then_the_users_and_one_dataset_to_cut_from(self): + osw = _GET("benchmark", "osworld1") + cuts = [d for d in osw["datasets"] if d.get("subset_of")] + part = self.section("osworld1") + text = visible(part) + self.assertIn(f"Task sets {len(cuts)}", text) + self.assertIn("From OSWorld1", text) + for d in cuts: + self.assertIn(f'href="/benchmarks/osworld1/tasks/{d["id"]}"', part) + self.assertIn(f"{d['label']} · {d['units']} tasks", text) + self.assertNotIn("Yours", text) + # New task set opens the whole list's tasks: one dataset, no menu + self.assertIn('New task set', part) + self.assertNotIn("bench-newset", part) + sets.create(osw, "Chrome tabs", dataset="test_nogdrive", units=["a", "b"]) + text = visible(self.section("osworld1")) + self.assertIn(f"Task sets {len(cuts) + 1}", text) + self.assertLess(text.index("From OSWorld1"), text.index("Yours")) + self.assertLess(text.index("Yours"), text.index("Chrome tabs")) + # a benchmark that declares nothing is drawn as before + self.assertNotIn("From ", visible(self.section("gaia"))) + + def node_program(self, body): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the dataset step") + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + folder = Path(__file__).resolve().parents[1] / "static/builder" + page = (folder / "command-builder.js").read_text(encoding="utf-8") + cut = lambda start, end: page[page.index(start):page.index(end, page.index(start))] + line = lambda name: re.search(r"^ const %s = .*$" % name, page, re.M).group(0) + "\n" + program = (f"const schema={json.dumps(schema)};const C=require({json.dumps(str(folder / 'command-builder-core.js'))})(schema);\n" + + line("esc") + cut(" const SOURCE_SAYS =", " // The yes to an agent") + cut(" const tile = t =>", " // The grids drawn by the server") + + cut(" // a dataset's proofs as its card shows them", " // Specific tasks:") + body) + return json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True, timeout=10).stdout) + + def test_the_builder_draws_all_of_it_the_benchmarks_own_sets_then_the_users(self): + osw = _GET("benchmark", "osworld1") + sets.create(osw, "Chrome tabs", dataset="test_nogdrive", units=["a", "b"]) + got = self.node_program( + "const r=C.createStandard('osworld1'),b=C.standardBench(r),u={noun:'task',nouns:'tasks'};" + "const first=JSON.parse(JSON.stringify(r.datasets));" + "const x=()=>b.datasets.find(d=>d.id===r.datasets[0]);const drawn=familyChoice(r,b,x(),u);" + "C.swapDataset(r,'test_nogdrive','test_small');const small=JSON.parse(JSON.stringify(r));" + "C.swapDataset(r,'test_small','test_nogdrive');C.setTaskSet(r,'test_nogdrive','chrome-tabs');const mine=familyChoice(r,b,x(),u);" + "C.swapDataset(r,'test_nogdrive','test_all');const whole=JSON.parse(JSON.stringify(r));" + "process.stdout.write(JSON.stringify({first,drawn,small,mine,whole,nested:C.nestedDatasets(b),root:C.wholeOf(b,'test_small')}));") + self.assertEqual((got["first"], got["nested"], got["root"]), (["test_nogdrive"], True, "test_all")) + titles = re.findall(r"(.*?)", got["drawn"]) + self.assertEqual(titles, ["All of it", "Without Google Drive", "Small", "Infeasible", "Chrome tabs"]) + self.assertEqual(re.findall(r'aria-pressed="true"[^>]*>.*?(.*?)', got["drawn"]), ["Without Google Drive"]) + self.assertIn('aria-label="Your task sets"', got["drawn"]) + self.assertEqual(re.findall(r"

    (.*?)

    ", got["drawn"]), ["Which tasks?"]) + self.assertEqual((got["small"]["datasets"], got["small"].get("task_sets")), (["test_small"], None)) + self.assertEqual(re.findall(r'aria-pressed="true"[^>]*>.*?(.*?)', got["mine"]), ["Chrome tabs"]) + self.assertEqual((got["whole"]["datasets"], got["whole"].get("task_sets")), (["test_all"], None)) + + def test_a_benchmark_that_declares_nothing_is_drawn_as_before(self): + got = self.node_program("const b=C.standardBench(C.createStandard('gaia'));" + "process.stdout.write(JSON.stringify({nested:C.nestedDatasets(b),n:b.datasets.length}));") + self.assertEqual(got["nested"], False) + self.assertGreater(got["n"], 1) + + +class BuilderCase(Case): + """The fixture catalogue's benchmarks in the builder; a set of the fake bench's dataset.""" + + def setUp(self): + super().setUp() + load = definitions.load + self.stack.enter_context(patch.object(definitions, "load", lambda kind, root=None, every=False: load(kind, FIXTURES, every=every))) + units.listing(self.fake, "all") + sets.create(self.fake, "dev", dataset="all", units=["good", "wrong"], description="two of them") + + +class TheBuilder(BuilderCase): + """The dataset step offers each dataset's sets; the Review step, compiled by the server, names the set and its + number of tasks.""" + + def test_the_schema_offers_the_sets_and_review_names_the_chosen_one(self): + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + fake = next(b for b in schema["standard"]["benchmarks"] if b["key"] == "fakebench") + self.assertEqual([(s["name"], s["label"], s["units"]) for s in fake["datasets"][0]["sets"]], [("dev", "dev", 2)]) + recipe = {"version": 1, "harness": "standard", "name": "fake-0101-120000", "title": "t", "benchmark": "fakebench", "dataset": "all", + "other": "fake", "provider": "openai", "model": "gpt-5-mini", "concurrency": 1, "unsandboxed": True, "where": "local", + "task_sets": {"all": "dev"}} + out = self.post("/new-run/runner", {"recipe": recipe}) + self.assertEqual(out["errors"], []) + self.assertIn(["Dataset", "all · task set dev · 2 tasks"], [r[1:] for r in out["review"]]) + self.assertEqual(out["confirm"], "") # the set is the choice of tasks: Run asks nothing more + + +class TheDatasetStep(BuilderCase): + """Which tasks? and Start with, under the chosen datasets: the dataset's name in their titles only when several + are chosen.""" + + def test_the_picker_and_selection_follow_limits_and_benchmark_options(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the dataset step") + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + folder = Path(__file__).resolve().parents[1] / "static/builder" + page = (folder / "command-builder.js").read_text() + cut = lambda start, end: page[page.index(start):page.index(end, page.index(start))] + program = (f"const schema={json.dumps(schema)};const C=require({json.dumps(str(folder / 'command-builder-core.js'))})(schema);\n" + + cut(" function pickTasks(", " function standardForm(") + + cut(" function compileRunner(", " // the number of units")) + program += r""" +const assert = require('node:assert/strict'), timers = [], notices = []; +const rec = C.createStandard('fakebench'), r = () => rec; +const S = {model: 3, dataset: 2}, REVIEW = 6, step = S.dataset; +const unitsOf = () => ({noun: 'task', nouns: 'tasks'}), window = {nulliusNotify: text => notices.push(text)}; +let runnerKey = '', runnerOut, runnerTimer, runnerServed, result; +const setTimeout = f => { timers.push(f); return timers.length; }, clearTimeout = () => {}; +const refreshPlan = () => {}, renderForm = () => {}; +const acceptCompile = (rec, served, out, key, current) => ({served, current: key === current && key === JSON.stringify(rec)}); +let nulliusFetch = async (url, args) => { + assert.equal(JSON.parse(args.body).recipe.limit, rec.limit); + return {json: async () => result}; +}; +const mount = {dataset: {}}, dialog = {showModal() {}}, elements = { + 'nb-tasks': dialog, 'nb-tasks-list': {content: {firstElementChild: {cloneNode: () => mount}}}, + 'nb-tasks-body': {replaceChildren: p => assert.equal(p, mount)}, 'nb-tasks-title': {}, + 'nb-tasks-close': {}, 'nb-tasks-done': {} +}; +const document = {getElementById: id => elements[id]}; +let picked; +globalThis.nulliusTasks = (p, options) => { picked = options; }; +(async () => { + rec.limit = 2; rec.bench_options = {mode: 'short'}; + C.setStartWith(rec, 'all', ['good', 'wrong']); + pickTasks('all'); + assert.equal(mount.dataset.limit, 2); + assert.deepEqual(JSON.parse(mount.dataset.options), {mode: 'short'}); + assert.deepEqual(picked.chosen, ['good', 'wrong']); + for (const change of ['limit', 'option']) { + C.setStartWith(rec, 'all', ['good', 'wrong']); + if (change === 'limit') rec.limit = 1; + else rec.bench_options.mode = 'long'; + result = {errors: [{dataset: 'all', dropped: ['wrong'], message: 'Outside the plan.'}]}; + compileRunner(); + assert.equal(runnerOut.errors[0].message, 'Checking the tasks ticked.'); + await timers.shift()(); + assert.deepEqual(rec.start_with.all, ['good']); + assert.equal(notices.at(-1), 'Unticked 1 task no longer in the plan: wrong.'); + } + assert.equal(notices.length, 2); + // the recipe the drop changed compiles again: Review waits for that answer alone, and no notice repeats + const clean = {errors: [], notes: [], review: [[6, 'Scope', '1 first, nothing later']]}; + result = clean; + compileRunner(); + assert.equal(runnerOut.errors[0].message, 'Checking the tasks ticked.'); + await timers.shift()(); + assert.equal(runnerOut, clean); + assert.equal(notices.length, 2); + // an answer for an older recipe leaves the wait to the latest one, which ends it + rec.limit = 2; compileRunner(); + const older = timers.shift(); + rec.limit = 3; compileRunner(); + await older(); + assert.equal(runnerOut.errors[0].message, 'Checking the tasks ticked.'); + await timers.shift()(); + assert.equal(runnerOut, clean); + // a failed request ends the wait too, with its own error + rec.limit = 4; compileRunner(); + const fetched = nulliusFetch; + nulliusFetch = async () => { throw new Error('offline'); }; + await timers.shift()(); + nulliusFetch = fetched; + assert.match(runnerOut.errors[0].message, /^The recipe could not be compiled here: /); + // with the ticked ids named once each, even when the answer names an id no longer ticked + rec.limit = 1; C.setStartWith(rec, 'all', ['good', 'wrong', 'slow']); + result = {errors: [{dataset: 'all', dropped: ['wrong', 'slow', 'model'], message: 'Outside the plan.'}]}; + compileRunner(); await timers.shift()(); + assert.deepEqual(rec.start_with.all, ['good']); + assert.equal(notices.at(-1), 'Unticked 2 tasks no longer in the plan: wrong, slow.'); + assert.equal(notices.length, 3); + C.setStartWith(rec, 'all', ['wrong']); + result = {errors: [{dataset: 'all', dropped: ['wrong'], message: 'Outside the plan.'}]}; + compileRunner(); await timers.shift()(); + assert.deepEqual(rec.start_with.all, []); +})().catch(e => { console.error(e); process.exitCode = 1; }); +""" + got = subprocess.run([node, "-e", program], stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10) + self.assertEqual(got.returncode, 0, got.stderr) + + def test_the_titles_name_the_dataset_only_when_several_are_chosen(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the dataset step") + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + folder = Path(__file__).resolve().parents[1] / "static/builder" + page = (folder / "command-builder.js").read_text(encoding="utf-8") + cut = lambda start, end: page[page.index(start):page.index(end, page.index(start))] + line = lambda name: re.search(r"^ const %s = .*$" % name, page, re.M).group(0) + "\n" + program = (f"const schema={json.dumps(schema)};const C=require({json.dumps(str(folder / 'command-builder-core.js'))})(schema);\n" + + line("esc") + cut(" const tile = t =>", " // The grids drawn by the server") + cut(" function taskSetChoice(", " function standardForm(") + + "const r=C.createStandard('fakebench'),b=C.standardBench(r),x=b.datasets[0],u={noun:'task',nouns:'tasks'};" + + "r.datasets=[x.id];const one=taskSetChoice(r,b,x,u)+startChoice(r,b,x,u);" + + "r.datasets=[x.id,'more'];const two=taskSetChoice(r,b,x,u)+startChoice(r,b,x,u);" + + "process.stdout.write(JSON.stringify({one,two,label:x.label}));") + got = json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True, timeout=10).stdout) + heads = lambda h: re.findall(r"

    (.*?)

    ", h) + self.assertEqual(heads(got["one"]), ["Which tasks?", "Start with"]) + self.assertEqual(heads(got["two"]), [f"{got['label']}: which tasks?", f"{got['label']}: start with"]) + + +class TheBuilderAfterAChange(BuilderCase): + """A deleted set is no longer offered and a saved recipe that names it is refused plainly; a renamed one is offered + under its new name.""" + + RECIPE = {"version": 1, "harness": "standard", "name": "fake-0101-120000", "title": "t", "benchmark": "fakebench", "dataset": "all", + "other": "fake", "provider": "openai", "model": "gpt-5-mini", "concurrency": 1, "unsandboxed": True, "where": "local"} + + def offered(self): + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + fake = next(b for b in schema["standard"]["benchmarks"] if b["key"] == "fakebench") + return [(s["name"], s["label"], s["units"]) for s in fake["datasets"][0]["sets"]] + + def errors(self, ref): + return self.post("/new-run/runner", {"recipe": dict(self.RECIPE, task_sets={"all": ref})})["errors"] + + def test_a_renamed_set_is_offered_under_its_new_name(self): + sets.rename("fakebench", "dev", "A pair") + self.assertEqual(self.offered(), [("a-pair", "A pair", 2)]) + self.assertEqual(self.errors("a-pair"), []) + self.assertEqual(self.errors("a-pair@1"), []) # a recipe from before sets were frozen + + def test_a_deleted_set_is_not_offered_and_a_saved_recipe_naming_it_is_refused_plainly(self): + sets.delete("fakebench", "dev") + self.assertEqual(self.offered(), []) + self.assertEqual([e["message"] for e in self.errors("dev")], ["Fake bench has no task set dev: choose another, or all of all's tasks."]) + + def test_a_saved_recipe_naming_an_entry_of_the_earlier_format_is_refused_without_its_path(self): + path = sets.path_of("fakebench", "dev") + with open(path) as f: + earlier = dict(json.load(f), benchmark_options={"mode": "hard"}) + with open(path, "w") as f: + json.dump(earlier, f) + self.assertEqual(self.offered(), []) + said = [e["message"] for e in self.errors("dev")] + self.assertEqual(said, ["The task set dev is of an earlier format, which kept a run's options: delete it and make it again."]) + + +class TheRecipeCore(BuilderCase): + """The builder's core keeps a chosen dataset's set, by its name, in the recipe: read back from a saved recipe, dropped + with its dataset, and dropped when the benchmark changes.""" + + def test_build_a_run_carries_the_dataset_and_the_open_set(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the recipe core") + self.b["datasets"].append({"id": "more", "units": 250}) + sets.create(self.b, "picked", dataset="more", units=["t001"]) + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + schema["standard"]["benchmarks"].append(recipe._bench_page(self.b)) + core = Path(__file__).resolve().parents[1] / "static/builder/command-builder-core.js" + for query, task_sets in (("", {}), ("?set=picked", {"more": "picked"})): + with self.subTest(query=query): + html = self.get("/benchmarks/described/tasks/more" + query).get_data(as_text=True) + link = unescape(re.search(r'href="([^"]+)">Build a run', html).group(1)) + program = (f"const C=require({json.dumps(str(core))})({json.dumps(schema)});" + f"const query=Object.fromEntries(new URL({json.dumps(link)},'http://localhost').searchParams);" + "const r=C.prefill(query);" + "process.stdout.write(JSON.stringify([r.benchmark,r.datasets,r.task_sets||{}]));") + result = subprocess.run([node, "-e", program], stdin=subprocess.DEVNULL, + check=True, capture_output=True, text=True, timeout=10) + self.assertEqual(json.loads(result.stdout), ["described", ["more"], task_sets]) + + def test_task_sets_follow_the_chosen_datasets(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the recipe core") + import subprocess + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + core = Path(__file__).resolve().parents[1] / "static" / "builder" / "command-builder-core.js" + program = (f"const C=require({json.dumps(str(core))})({json.dumps(schema)});\n" + "const r=C.fromJSON({version:1,harness:'standard',benchmark:'fakebench',datasets:['all'],others:['fake']," + "task_sets:{all:'dev@1',gone:'x@1',bad:3}});\n" + "const read=JSON.parse(JSON.stringify(r.task_sets));\n" + "C.setTaskSet(r,'all','');const cleared=r.task_sets===undefined;\n" + "C.setTaskSet(r,'all','dev@1');r.datasets=[];C.keepTaskSets(r);const dropped=r.task_sets===undefined;\n" + "r.datasets=['all'];C.setTaskSet(r,'all','dev@1');C.setStandardBenchmark(r,'fakememo');\n" + "process.stdout.write(JSON.stringify({read,cleared,dropped,other:r.task_sets===undefined}));") + got = json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + self.assertEqual(got, {"read": {"all": "dev@1"}, "cleared": True, "dropped": True, "other": True}) + + +class TheJobPage(Case): + """Jobs of the fake bench, one that ran a set and one that ran none.""" + + def setUp(self): + super().setUp() + bench = self.fake + self.entry = sets.create(bench, "dev", dataset="all", units=["good", "wrong", "slow"]) + record = sets.record(self.entry) + root = self.tmp / "jobs" + other = {"key": "nop", "_kind": "control", "_ref": "nop"} + for name, ts, results in (("of-a-set", record, {"good": 1.0, "wrong": 0.0, "slow": 1.0}), ("whole", None, {"good": 1.0})): + d = root / name + d.mkdir(parents=True) + job.write_config(str(d), job=name, bench=bench, other=other, model="", provider="openai", dataset="all", + units=list(results), concurrency=1, granted=False, task_set=ts) + rows = [] + for k, (u, r) in enumerate(results.items()): + trial = d / f"{u}__u{k:04d}" + trial.mkdir() + rows.append(job.write_trial(str(trial), job=name, bench=bench, other=other, model="", unit=u, + t0=1_760_000_000.0 + k, t1=1_760_000_005.0 + k, produce=(1_760_000_000.0 + k, 1_760_000_004.0 + k), + score={"reward": r}, exception=None, calls=[], trajectory=None)) + job.write_result(str(d), name, 1_760_000_000.0, 1_760_000_060.0, rows, len(results)) + self.stack.enter_context(patch.object(web.shared, "WS_HOME", str(self.tmp / "ws"))) + self.stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []})) + web.shared.open_workspace(workspace.create(str(self.tmp / "ws"), [str(root)], label="sets")) + + def page(self, name): + return self.get(f"/job/{name}?view=results").get_data(as_text=True) + + def meta(self, html): + head = re.search(r'
    ', html, re.S).group(0) + return visible(head.split('
    ')[0]).replace(" ,", ",") + + def test_the_page_names_the_set_with_a_link_and_a_job_of_no_set_nothing_more(self): + html = self.page("of-a-set") + self.assertIn("Dataset all Task set dev", self.meta(html)) # a cell of the dataset's card + self.assertNotIn("revision", self.meta(html)) + self.assertIn('href="/benchmarks/fakebench/tasks/all?set=dev"', html) + self.assertNotIn("Task set", self.meta(self.page("whole"))) + + def test_a_job_that_recorded_a_set_and_its_revision_before_labels_still_shows_its_set(self): + path = self.tmp / "jobs" / "of-a-set" / "config.json" + cfg = json.loads(path.read_text()) + cfg["standard"]["task_set"] = {k: cfg["standard"]["task_set"][k] for k in sets.RECORD} + path.write_text(json.dumps(cfg)) + sets.rename("fakebench", "dev", "The trio") + html = self.page("of-a-set") + self.assertIn("Task set The trio", self.meta(html)) + self.assertIn('href="/benchmarks/fakebench/tasks/all?set=the-trio"', html) + + def test_a_set_not_in_the_catalogue_is_named_without_a_link(self): + os.remove(sets.path_of("fakebench", "dev")) + html = self.page("of-a-set") + self.assertIn("Task set dev", self.meta(html)) + self.assertNotIn("/tasks/all?set=dev", html) + + def test_a_renamed_set_is_named_by_its_new_name_with_its_link(self): + sets.rename("fakebench", "dev", "trio") + sets.create(self.fake, "dev", dataset="all", units=["good"]) # another set under the old name + html = self.page("of-a-set") + self.assertIn("Task set trio", self.meta(html)) + self.assertIn('href="/benchmarks/fakebench/tasks/all?set=trio"', html) + self.assertNotIn("/tasks/all?set=dev", html) + + def test_a_deleted_set_is_named_without_a_link(self): + sets.delete("fakebench", "dev") + html = self.page("of-a-set") + self.assertIn("Task set dev", self.meta(html)) + self.assertNotIn("/tasks/all?set=", html) + + def test_save_as_task_set_stores_the_full_unit_ids_of_the_rows_shown(self): + self.assertIn("Save the tasks shown", self.page("of-a-set")) + r = self.client.post("/job/of-a-set/task-set", data={"csrf": self.csrf, "name": "Solved ones", "outcome": "resolved"}, + headers={"Origin": "http://localhost"}); self.addCleanup(r.close) + self.assertEqual(r.status_code, 302) + self.assertEqual(r.headers["Location"], "/benchmarks/fakebench/tasks/all?set=solved-ones") + entry = sets.load("fakebench", "solved-ones") + self.assertEqual((entry["label"], sets.revision(entry)["units"]), ("Solved ones", ["good", "slow"])) + r = self.client.post("/job/whole/task-set", data={"csrf": self.csrf, "name": "every"}, + headers={"Origin": "http://localhost"}); self.addCleanup(r.close) + self.assertEqual(sets.revision(sets.load("fakebench", "every"))["units"], ["good"]) + r = self.client.post("/job/whole/task-set", data={"csrf": self.csrf, "name": "every"}, + headers={"Origin": "http://localhost"}); self.addCleanup(r.close) + self.assertEqual(r.status_code, 302) + self.assertEqual(sets.revision(sets.load("fakebench", "every-2"))["units"], ["good"]) # the same words: another set + + def test_the_job_page_takes_a_set_s_name_by_the_tasks_page_s_rule(self): + name_field = lambda html, form: re.search(r']*>', re.search(form, html, re.S).group(0)).group(0) + here = name_field(self.page("of-a-set"), r'
    ') + there = name_field(self.get("/benchmarks/fakebench/tasks/all").get_data(as_text=True), r'.*?
    ') + most = lambda field: re.search(r'maxlength="(\d+)"', field).group(1) + self.assertEqual((most(here), most(there)), ("80", "80")) + self.assertNotIn("spellcheck", here) # words, not an id + label = "The good & the slow ones, kept from the run of " + "x" * 30 # 77 characters, spaces and signs + r = self.client.post("/job/of-a-set/task-set", data={"csrf": self.csrf, "name": label}, + headers={"Origin": "http://localhost"}); self.addCleanup(r.close) + self.assertEqual(r.status_code, 302) + saved = [e for e in sets.entries("fakebench")[0] if e.get("label") == label] + self.assertEqual(len(saved), 1) + self.assertTrue(saved[0]["name"].startswith("the-good-the-slow-ones-kept-from-the-run-of-")) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/web/catalogue.py b/app/web/catalogue.py index b3b9ea7f..27cf622a 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -7,6 +7,7 @@ import json import os import re +import threading import time from flask import abort, flash, jsonify, redirect, render_template, request, url_for @@ -16,6 +17,7 @@ from nullius.standard.pages import howto from nullius.standard.proofs import prove from nullius.standard.pages import recipe as standard_recipe +from nullius.standard.runner import sets, units from .core import app from . import execute @@ -108,7 +110,11 @@ def benchmark_page(key): std, ds, data = shown["std"], cat.datasets_of(b), shown["data"] versions = views if len(views) > 1 else [] jobs = {j.job_id for j in shared._jobs_for_request()} if std else set() + # the user's sets, each with the version it was made at as this benchmark's definition names it + named = standard_definitions.get("benchmark", b.key) if std else None + task_sets = [dict(s, version_label=sets.version_label(named, s["version"]) if s["version"] else "") for s in sets.rows(b.key)] if std else [] return render_template("catalogue/benchmark.html", cat=cat, b=b, csrf=shared._csrf_token(), papers=citation.parse(b.citation), data=data, + task_sets=task_sets, editable=entry is not None and not harbor_entry.not_editable(entry), std=std, std_jobs=jobs, versions=versions, views=views, deletable=os.path.isfile(os.path.join(paths.catalogue_dir(), catalog.BENCHMARKS, key, catalog.ENTRY)), restore_bundle=storage.can_restore("benchmarks", key, catalog.ROOT), @@ -116,6 +122,260 @@ def benchmark_page(key): providers=[(p, providers.label(p)) for p in providers.available(os.environ)]) +# --- a dataset's tasks: browsed, chosen and kept as a task set --------------------------------- + +# The listings being prepared, keyed by benchmark, resolved version, dataset and options. +_PREPARING: dict = {} +_PREPARING_LOCK = threading.Lock() + + +def _std_dataset(key: str, dataset: str, version: str = ""): + """(the standard's definition of ``key``, at ``version`` or its default, and its dataset) or a 404. The definition + goes to the listing as the command line gives it, so both read the same cached listing.""" + if version and not standard_definitions._VERSION.match(version): + abort(404) + bench = standard_definitions.get("benchmark", f"{key}@{version}" if version else key) + ds = next((d for d in (bench or {}).get("datasets") or [] if d["id"] == dataset), None) + if bench is None or ds is None: + abort(404) + return bench, ds + + +# a plan's options are a few names with short values; a longer text is refused before it is parsed +_OPTIONS_MAX = 4096 + + +def _listing_options() -> dict: + """The benchmark options of the plan the picker lists: a JSON object of strings, refused when it is not one, + when it is longer than ``_OPTIONS_MAX`` characters or nested past what the parser follows.""" + given = request.args.get("options", "{}") + if len(given) > _OPTIONS_MAX: + abort(400) + try: + options = json.loads(given) + except (ValueError, RecursionError): + abort(400) + if not isinstance(options, dict) or not all(isinstance(v, str) for v in options.values()): + abort(400) + return options + + +def _listing_key(bench: dict, dataset: str, options: dict): + return bench["key"], standard_definitions.version_of(bench), dataset, tuple(sorted(options.items())) + + +def _listing_state(bench: dict, dataset: str, options=None) -> dict: + """The state function's answer; whether a listing is being made here now, and why the last one failed; and + ``say``, the line the page shows while the listing is not there.""" + got = units.state(bench, dataset, options) + with _PREPARING_LOCK: + job = _PREPARING.get(_listing_key(bench, dataset, options or {})) or {} + alive = bool(job.get("thread") and job["thread"].is_alive()) + got = dict(got, preparing=alive and got["state"] != "cached", error="" if alive else job.get("error", "")) + nouns = (bench.get("units") or {}).get("nouns", "tasks") + fetched = ", then ".join(f["text"] for f in got["fetch"]) + if got["state"] == "cached": + say = "" + elif got["error"]: + say = f"The list of {nouns} could not be made: {got['error']}. Ids can still be pasted." + elif got["state"] == "refused": + say = f"The list of {nouns} cannot be made here: {got['reason']}. Ids can still be pasted." + elif got["state"] == "full": + say = (f"The list of {nouns} needs the benchmark's own environment on this machine" + + (f" ({', '.join(f['text'] for f in got['fetch'])})" if got["fetch"] else "") + + ": run the dataset once, or list it with the units command, then reload. Ids can still be pasted.") + else: + say = f"Preparing the list of {nouns}" + (f": fetching {fetched}." if fetched else ".") + " Ids can be pasted meanwhile." + return dict(got, say=say) + + +@app.route("/benchmarks//tasks/") +def benchmark_tasks(key, dataset): + """A dataset's tasks, at the benchmark's default version or ``?version=``: searched, counted by category, ticked + and kept as a task set; opened from a set (``?set=NAME``), its tasks ticked, at the version it was made at, and + saved as another set when they change. The page asks for the listing once loaded; this request reads none.""" + version = request.args.get("version", "") + entry, problem, broken = None, "", "" + if request.args.get("set"): + name = request.args["set"] + try: + entry = sets.load(key, name) + except sets.Refused as e: + # said without the file's path; a file there that cannot be read can still be deleted from the page + problem, broken = sets.plain(e, key, name), "" if isinstance(e, sets.NotFound) else name + if entry is not None and entry["dataset"] != dataset: + return redirect(url_for("benchmark_tasks", key=key, dataset=entry["dataset"], set=entry["name"])) + if entry is not None and entry.get("version") and not version and standard_definitions.get("benchmark", f"{key}@{entry['version']}"): + version = entry["version"] # its tasks as listed at the version it was made at + bench, ds = _std_dataset(key, dataset, version) + return render_template("catalogue/tasks.html", bench=bench, title=standard_definitions.title(bench), + ds=ds, entry=entry, rev=sets.latest(entry) if entry else None, problem=problem, + label=sets.label_of(entry) if entry else "", version=standard_definitions.version_of(bench) or "", + made_at=sets.version_label(bench, entry["version"]) if entry and entry.get("version") else "", + broken=broken, nouns=(bench.get("units") or {}).get("nouns", "units"), + noun=(bench.get("units") or {}).get("noun", "unit"), csrf=shared._csrf_token(), + writable=shared._local_client()) + + +@app.route("/benchmarks//tasks//listing") +def benchmark_tasks_listing(key, dataset): + """One page of the dataset's tasks for a search and category values, once the listing is in the cache; before + that, the state function's answer alone: this request never makes a listing.""" + bench, _ = _std_dataset(key, dataset, request.args.get("version", "")) + options = _listing_options() + st = _listing_state(bench, dataset, options) + if st["state"] != "cached": + return jsonify(ok=True, ready=False, **st) + cats: dict = {} + for word in request.args.getlist("cat"): + field_, eq, value = word.partition("=") + if eq and field_ and value: + cats.setdefault(field_, []).append(value) + page = request.args.get("page", "1") + limit = request.args.get("limit", "") + if limit and (not limit.isdigit() or int(limit) < 1): + return jsonify(ok=False, error="The task limit must be a whole number above zero."), 400 + limit = int(limit) if limit else None + # ``within=NAME``: the tasks of that set alone, as the run builder's start on specific tasks lists them + within = None + if request.args.get("within"): + try: + entry = sets.load(key, request.args["within"]) + except sets.Refused as e: + return jsonify(ok=False, error=sets.plain(e, key, request.args["within"])), 400 + within = sets.latest(entry)["units"] + try: + if request.args.get("ids"): # every match's id, for "select the N that match" + got = units.find(bench, dataset, options, search=request.args.get("q", ""), categories=cats, size=None, within=within, limit=limit) + return jsonify(ok=True, ready=True, total=got["total"], ids=[t["id"] for t in got["tasks"]]) + got = units.find(bench, dataset, options, search=request.args.get("q", ""), categories=cats, + page=int(page) if page.isdigit() and int(page) >= 1 else 1, within=within, limit=limit) + except units.Refused as e: + return jsonify(ok=False, error=str(e)), 400 + return jsonify(ok=True, ready=True, **got) + + +@app.route("/benchmarks//tasks//prepare", methods=["POST"]) +def benchmark_tasks_prepare(key, dataset): + """Make a listing the state function calls light, out of this request: it fetches what the state named and + starts the light listing command. A listing that needs the driver's full environment is never started here.""" + shared._require_csrf() + if not shared._local_client(): + abort(403, description="Listings are prepared from a browser on the application host only.") + bench, _ = _std_dataset(key, dataset, request.args.get("version", "")) + options = _listing_options() + identity = _listing_key(bench, dataset, options) + st = units.state(bench, dataset, options) + if st["state"] != "light": + return jsonify(ok=st["state"] == "cached", **_listing_state(bench, dataset, options)) + + def make(): + try: + units.listing(bench, dataset, options) + except (units.Refused, OSError) as e: + _PREPARING[identity]["error"] = str(e) + with _PREPARING_LOCK: + job = _PREPARING.get(identity) + if not (job and job["thread"].is_alive()): + job = _PREPARING[identity] = {"thread": threading.Thread(target=make, daemon=True), "error": ""} + job["thread"].start() + return jsonify(ok=True, **_listing_state(bench, dataset, options)) + + +@app.route("/benchmarks//tasks//rows", methods=["POST"]) +def benchmark_tasks_rows(key, dataset): + """The chosen ids as rows (show selected, ids pasted): each with its title and categories when the listing is in + the cache, and ``unknown``, the ids it does not list; without the listing, the ids alone.""" + bench, _ = _std_dataset(key, dataset, request.args.get("version", "")) + options = _listing_options() + ids = [str(u) for u in (request.get_json(silent=True) or {}).get("units") or [] if isinstance(u, str)] + if units.state(bench, dataset, options)["state"] != "cached": + return jsonify(ok=True, ready=False, tasks=[{"id": u, "title": "", "text": "", "categories": {}} for u in ids], unknown=[]) + have = {t["id"]: t for t in units.listing(bench, dataset, options)["tasks"]} + return jsonify(ok=True, ready=True, tasks=[have[u] for u in ids if u in have], unknown=[u for u in ids if u not in have]) + + +def _set_problem(key: str, name: str) -> str: + """Why ``name`` cannot name a task set, in a line for the page, or "". Any words do: the name commands take is + made from them.""" + if not name.strip(): + return "Give the task set a name." + try: + sets.check_label(name) + except sets.Refused as e: + return str(e)[0].upper() + str(e)[1:] + "." + return "" + + +@app.route("/benchmarks//tasks//save", methods=["POST"]) +def benchmark_tasks_save(key, dataset): + """Keep the ticked ids as a new task set ({name, description, units, version}), at the version the page listed: + the name typed is its label, and the name commands take is made from it. A set is never changed: the page of + one saves another.""" + shared._require_csrf() + if not shared._local_client(): + abort(403, description="Task sets are saved from a browser on the application host only.") + body = request.get_json(silent=True) or {} + bench, _ = _std_dataset(key, dataset, str(body.get("version") or "")) + ids = [u for u in body.get("units") or [] if isinstance(u, str)] + if not ids: + return jsonify(ok=False, error="Tick at least one task."), 400 + label = str(body.get("name") or "").strip() + problem = _set_problem(key, label) + if problem: + return jsonify(ok=False, error=problem), 400 + try: + entry = sets.create(bench, label, dataset=dataset, units=ids, description=str(body.get("description") or "").strip(), + note=str(body.get("note") or "")) + except sets.Refused as e: + return jsonify(ok=False, error=str(e)), 400 + return jsonify(ok=True, name=entry["name"], open=url_for("benchmark_tasks", key=key, dataset=dataset, set=entry["name"])) + + +def _set_guard(key: str, dataset: str) -> str: + """Every change to a set from its page: the form token and a browser on this machine; the set's name.""" + shared._require_csrf() + if not shared._local_client(): + abort(403, description="Task sets are changed from a browser on the application host only.") + _std_dataset(key, dataset) + return (request.form.get("set") or "").strip() + + +@app.route("/benchmarks//tasks//rename", methods=["POST"]) +def benchmark_tasks_rename(key, dataset): + """Give the set another name, its id and tasks kept (a job that ran it finds it by its id); the name commands + take is made from it again. Then its page under the new name. An empty name, one not allowed or its own is + refused.""" + name = _set_guard(key, dataset) + new = (request.form.get("name") or "").strip() + try: + was = sets.label_of(sets.load(key, name)) + problem = f"The task set is named {was} already." if new and new == was else _set_problem(key, new) + if problem: + flash(problem, "error") + return redirect(url_for("benchmark_tasks", key=key, dataset=dataset, set=name)) + entry = sets.rename(key, name, new) + except sets.Refused as e: + flash(sets.plain(e, key, name), "error") + return redirect(url_for("benchmark_tasks", key=key, dataset=dataset, set=name)) + flash(f"Renamed {was} to {entry['label']}. Runs made from it follow the new name.", "ok") + return redirect(url_for("benchmark_tasks", key=key, dataset=entry["dataset"], set=entry["name"])) + + +@app.route("/benchmarks//tasks//delete", methods=["POST"]) +def benchmark_tasks_delete(key, dataset): + """Remove the set from the catalogue; then the benchmark's task sets. A job that ran it keeps its record and names + it without a link.""" + name = _set_guard(key, dataset) + try: + gone = sets.delete(key, name) + except sets.Refused as e: + flash(sets.plain(e, key, name), "error") + return redirect(url_for("benchmark_tasks", key=key, dataset=dataset, set=name)) + flash(f"Deleted the task set {sets.label_of(gone) if gone else name}. Runs made from it stay.", "ok") + return redirect(url_for("benchmark_page", key=key, _anchor="task-sets")) + + @app.route("/catalogue///use-bundled", methods=["POST"]) def catalogue_use_bundled(group, key): shared._require_csrf() diff --git a/app/web/execute.py b/app/web/execute.py index 7cc557df..29f1897b 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -9,7 +9,9 @@ from nullius import execution, hosts, prerequisites, prices, providers, settings from nullius.harbor import source as harbor_source from nullius.standard.backends import boat +from nullius.standard.calls import ledger from nullius.standard.pages import recipe as standard_recipe +from nullius.standard.runner import rerun from .core import app from . import shared @@ -217,6 +219,125 @@ def _start(plan: execution.Plan): return jsonify(ok=True, open=destination, **summary) +REASON_MAX = 200 + + +def again_offer(job, ex) -> dict | None: + """What the job's page offers to run its tasks again: {"where": the machine it ran on} when the server can, + {"why": one line} when it cannot - no record of where it ran, still running, merged from its shards' jobs, its + host gone from Settings, a copy that is not its run's own - and None for a job that is not the standard's.""" + if not job.standard: + return None + if job.merged_from: + return {"why": "Merged from its shards' jobs: run a task again in its shard's job."} + if ex is None or ex.plan.runner != standard_recipe.HARNESS: + return {"why": "Not started from here: no record of where it ran."} + if ex.state in execution.ALIVE or job.is_running or job.is_preparing: + return {"why": "Still running: more tasks can be started once it has ended."} + if os.path.realpath(job.dir) != os.path.realpath(os.path.join(ex.jobs, job.job_id)): + return {"why": "This copy is not its run's own: open the job its run wrote."} + if ex.plan.host is not None and ex.plan.host.entry not in {h.entry for h in _hosts()}: + return {"why": f"Its host, {ex.plan.host.label}, is no longer in Settings."} + return {"where": ex.plan.host.label if ex.plan.host else "this machine"} + + +@app.route("/job//rerun", methods=["POST"]) +def job_rerun(job_id): + """Run the trials the job page ticked again, in the job, where its run ran: this machine, or the host the + run was sent to (``Execution.again``); a task it planned with no result runs there too. Same guards as Run. + Refused, and nothing started, for a job the page offers no button for (``again_offer``), a trial the job + does not hold, a host that no longer holds the job, or a provider whose key is not set here.""" + shared._require_csrf() + if not shared._local_client(): + abort(403, description="Runs are started from a browser on the application host only.") + j = shared._find_job(shared._jobs_for_request(), job_id) + if j is None: + abort(404) + ex = execution.for_job(job_id) + offer = again_offer(j, ex) + if offer is None or offer.get("why"): + return jsonify(ok=False, error=(offer or {}).get("why") or "Only a job of the Nullius standard is run again."), 409 + body = request.get_json(silent=True) or {} + from . import runs as runs_web + held = {t.trial_name for t in j.trials} | {t for w in runs_web.waiting_of(j) for t in w["trials"]} # and the tasks with no result + picked = list(dict.fromkeys(t for t in body.get("trials") or [] if isinstance(t, str))) if isinstance(body.get("trials"), list) else [] + if not picked: + return jsonify(ok=False, error="Tick the tasks to run again."), 400 + unknown = [t for t in picked if t not in held] + if unknown: + return jsonify(ok=False, error=f"{job_id} holds no trial {', '.join(unknown[:3])}"), 400 + reason = " ".join(str(body.get("reason") or "").split()) + if len(reason) > REASON_MAX: + return jsonify(ok=False, error=f"The reason is one line of at most {REASON_MAX} characters."), 400 + budget = job_cap(j, ex, settle=True) # one cap for the job: the part has what the parts before it left + if budget and budget["closed"]: + said = rerun.spent_out(budget, "change it to run more.") + return jsonify(ok=False, error=said[0].upper() + said[1:]), 409 + recipe = ex.plan.recipe or {} + missing = "" if ex.plan.keyless else provider_problem(recipe.get("provider") or "openai", recipe.get("endpoint")) + if missing: + return jsonify(ok=False, error=missing), 400 + gone = ex.holds(job_id) + if gone: + return jsonify(ok=False, error=gone), 409 + n = 1 + sum(1 for p in ex.plan.parts if p.get("again")) + try: + ex.again(standard_recipe.again(job_id, picked, reason=reason, max_usd=budget["max_usd"] if budget and budget["changed"] else None, n=n)) + except ValueError as e: + return jsonify(ok=False, error=str(e)), 409 + return jsonify(ok=True, **ex.summary()) + + +def job_cap(job, ex, settle: bool = False) -> dict | None: + """The job's one spending cap as its page shows it and its next part runs under it (``rerun.budget``): the cap + set on the page (``Plan.caps``) where it differs from the job's own, else the job's. ``settle``: a cap set on the + page that the job's record now holds is dropped from the run's record. None for a job with no cap.""" + if not job.standard: + return None + set_here = (ex.plan.caps or {}).get(job.job_id) if ex is not None else None + try: + got = rerun.budget(job.dir, cap=set_here) + except (OSError, ValueError, TypeError, KeyError): + return None + if settle and set_here is not None and got is not None and not got["changed"]: + with ex._turn: + ex.plan.caps = {k: v for k, v in ex.plan.caps.items() if k != job.job_id} + ex._save() + return got + + +@app.route("/job//cap", methods=["POST"]) +def job_cap_change(job_id): + """A new spending cap for the whole job, from its next part on: kept in its run's record (``Plan.caps``) and + handed to that part as ``rerun --max-usd``. Refused where the page offers no next part (``again_offer``: a part + running among them), and for a cap at or under what the job has spent.""" + shared._require_csrf() + if not shared._local_client(): + abort(403, description="Runs are started from a browser on the application host only.") + j = shared._find_job(shared._jobs_for_request(), job_id) + if j is None: + abort(404) + ex = execution.for_job(job_id) + offer = again_offer(j, ex) + if offer is None or offer.get("why"): + return jsonify(ok=False, error=(offer or {}).get("why") or "Only a job of the Nullius standard has a cap to change."), 409 + try: + cap = float((request.get_json(silent=True) or {}).get("max_usd")) + except (TypeError, ValueError): + cap = -1.0 + if not 0 < cap < float("inf"): + return jsonify(ok=False, error="The spending cap is an amount in USD above zero."), 400 + now = rerun.budget(j.dir, cap=cap) + # nothing left (float noise included), or a cap that reads as the spend the page shows + if now["left_usd"] <= 0 or ledger.usd(cap) == ledger.usd(now["spent_usd"]): + return jsonify(ok=False, error=f"The cap must be above what this run has spent, {ledger.usd(now['spent_usd'])} USD."), 400 + with ex._turn: + caps = {k: v for k, v in (ex.plan.caps or {}).items() if k != job_id} + ex.plan.caps = caps if not now["changed"] else dict(caps, **{job_id: cap}) + ex._save() + return jsonify(ok=True, max_usd=cap, left_usd=now["left_usd"]) + + @app.route("/run/") def run_status(run_id): """State and log lines from ``since`` on; the page polls this.""" diff --git a/app/web/filters.py b/app/web/filters.py index 5e579e0c..92ffc508 100644 --- a/app/web/filters.py +++ b/app/web/filters.py @@ -3,6 +3,7 @@ import json import re +from datetime import datetime from pathlib import Path from flask import g, render_template, url_for @@ -41,6 +42,34 @@ def _runtime(minutes): return f"{minutes * 60:.0f}s" if minutes < 1 else f"{minutes:.0f}m" +@app.template_filter("try_mark") +def _try_mark(t, job) -> str: + """How a try a person asked for after the run ended is named: "first run, in a later part" for a task of the plan + a later part began (the job's run of that time lists it as begun), "run again by hand" otherwise.""" + base = re.sub(r"\.try-\d+$", "", t.trial_name) + later = any(r["at"] == t.rerun.get("at") and base in {b["trial"] for b in r.get("begun") or []} for r in job.reruns) + return "first run, in a later part" if later else "run again by hand" + + +@app.template_filter("n_tasks") +def _n_tasks(trials) -> int: + """How many tasks a standard job's trial names hold: a task's attempts (``__uNNNNrK``) count once.""" + return len({re.sub(r"(__u\d+)r\d+$", r"\1", t) for t in trials}) + + +@app.template_filter("run_min") +def _run_min(job): + """The minutes a job ran: its first run's start to finish, and each later run's in it (``Job.reruns``) added; + None without the first run's times.""" + total = job.duration_min + for r in job.reruns if total is not None else (): + try: + total += (datetime.fromisoformat(r["finished_at"]) - datetime.fromisoformat(r["at"])).total_seconds() / 60.0 + except (TypeError, ValueError): + continue # a later run whose times are not both recorded + return total + + @app.template_filter("hitrate") def _hitrate(value): """Cache hit share. One decimal — two when rounding would claim 100%. diff --git a/app/web/runs.py b/app/web/runs.py index bd6d4867..de7be737 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -25,6 +25,7 @@ from nullius.runs import attempts, classify, failure_analysis, feasibility, launches, live, parse from nullius import workspace from nullius.standard.contract import definitions as standard_definitions +from nullius.standard.runner import sets as task_sets from .core import app from . import shared @@ -577,14 +578,20 @@ def job(job_id): return render_template("runs/preparing.html", job_id=job_id, ex=ex, csrf=shared._csrf_token(), own=own, deletable=_deletable(job_id, ex)) abort(404) from . import judge + from . import execute board = _live_board_state(j) + again = ex.again_of(job_id) if ex is not None else None + j, running_again = _until_again(j, (again or {}).get("trials") or []) + waiting = waiting_of(j, (again or {}).get("trials") or []) analysis, versions = _analysis_of(j) return render_template("runs/job.html", job=j, live_board=board, view=_view_of(board, j, ex), - execution=ex, csrf=shared._csrf_token(), + execution=ex, csrf=shared._csrf_token(), set_link=_set_link(j), set_saving=_set_saving(j), judgement=judge.job_summary(j) if j.trials else None, control=feasibility.summary_of(j), ended=shared.ended_for(job_id), own=own, deletable=_deletable(job_id, ex), trial_rows=attempts.grouped(j), pass_k=attempts.for_job(j), filtered=_filtered_of(j, analysis, versions), marks=_marks_of(analysis, versions), + again=execute.again_offer(j, ex), running_again=running_again, rerunning=again is not None, + waiting=waiting, plan_sets=plan_sets(j, waiting), job_cap=execute.job_cap(j, ex), names=_identity_names(j.identity)) @@ -648,6 +655,138 @@ def labels(d, given): "agent_options": labels(other, identity.get("agent_options") or {})} +def waiting_of(j, running=()) -> list: + """The tasks a standard job planned that have no result (``rerun.unfinished``), each {trial, trials, unit, folder, + running, outcome}: one row per unit, with its planned attempts in ``trials`` and its first in ``trial``. + Never begun, or begun and ended with none (``folder``); ``running``, one of the trials + ``running`` names, those a re-run under way runs. ``outcome``: ``not_run`` for a task never begun of a job + begun on a part of its plan (``start_with``), ``no_result`` otherwise. Its feed is read only for a job with + fewer trials than it planned: [] for every other job.""" + if not j.standard or len(j.trials) >= j.n_planned: + return [] + from nullius.standard.runner import rerun + waiting = {} + for name, x in rerun.unfinished(j.dir).items(): + row = waiting.setdefault(x["unit"], dict(x, trial=name, trials=[], running=False, + outcome="not_run" if j.start_with else "no_result")) + row["trials"].append(name) + row["running"] |= name in running + if x["folder"]: + row.update(folder=x["folder"], outcome="no_result") + return list(waiting.values()) + + +def plan_sets(j, waiting: list) -> list: + """The task sets of the job's benchmark and dataset that name planned tasks with no result: [{name, trials, + tasks}], ``name`` the set's label, ``trials`` those of ``waiting`` (:func:`waiting_of`) the set names and no + re-run is running. What the job page's "Run a set" offers; [] when no set names one.""" + if not waiting: + return [] + try: + with open(os.path.join(j.dir, "config.json"), encoding="utf-8") as f: + cfg = json.load(f) + bench = (cfg.get("standard") or {}).get("benchmark") + dataset = str(((cfg.get("datasets") or [{}])[0] or {}).get("name") or "").partition("/")[2] + except (OSError, ValueError, AttributeError): + return [] + if not isinstance(bench, str) or not bench: + return [] + try: + entries, _ = task_sets.entries(bench) + except task_sets.Refused: + return [] + out = [] + for e in entries: + if e.get("dataset") != dataset: + continue + last = task_sets.latest(e) + wanted = set(last["units"]) + trials = [w["trial"] for w in waiting if w["unit"] in wanted and not w["running"]] + if trials: + out.append({"name": task_sets.label_of(e), "trials": trials, + "tasks": len({w["unit"] for w in waiting if w["trial"] in trials})}) + return out + + +def _set_link(j) -> dict: + """The task set a job ran as its page names it: {name, link}, ``name`` its label. Found by its id, under the name + it has now (a set renamed since), its link the set's page; when the catalogue here holds no set of that id, the + label the job recorded and no link.""" + ts = j.task_set + if not ts: + return {} + entry = task_sets.by_id(ts["benchmark"], ts.get("id"), ts["name"]) if ts.get("benchmark") else None + if entry is None: + return {"name": ts.get("label") or ts["name"], "link": ""} + return {"name": task_sets.label_of(entry), "link": url_for("benchmark_tasks", key=ts["benchmark"], dataset=entry["dataset"], + set=entry["name"])} + + +def _set_saving(j) -> bool: + """Whether the job page offers "Save as task set": a standard job of a benchmark in the catalogue, whose trials + record their units, on a browser of this machine.""" + if not j.standard or not shared._local_client(): + return False + try: + with open(os.path.join(j.dir, "config.json"), encoding="utf-8") as f: + bench = (json.load(f).get("standard") or {}).get("benchmark") + except (OSError, ValueError, AttributeError): + return False + return bool(isinstance(bench, str) and standard_definitions.get("benchmark", bench)) + + +@app.route("/job//task-set", methods=["POST"]) +def job_task_set(job_id): + """Keep the units of the trials the outcome filter shows (every trial without one) as a new task set: each by + the full unit id its trial records (standard/runner/sets.py, ``from_job``); then the set's page.""" + shared._require_csrf() + if not shared._local_client(): + abort(403, description="Task sets are saved from a browser on the application host only.") + j = shared._find_job(shared._jobs_for_request(), job_id) + if j is None or not _set_saving(j): + abort(404) + with open(os.path.join(j.dir, "config.json"), encoding="utf-8") as f: + std = json.load(f)["standard"] + # the set is made at the version the job ran, when the catalogue still knows it + bench = standard_definitions.get("benchmark", str(std.get("benchmark_ref") or "")) or standard_definitions.get("benchmark", std["benchmark"]) + name, outcome = (request.form.get("name") or "").strip(), (request.form.get("outcome") or "").strip() + from . import catalogue + problem = catalogue._set_problem(bench["key"], name) + back = url_for("job", job_id=job_id, **({"outcome": outcome} if outcome else {})) + if problem: + flash(problem, "error") + return redirect(back) + try: + got = task_sets.from_job(bench, j.dir, outcomes=[outcome] if outcome else None) + entry = task_sets.create(bench, name, dataset=got["dataset"], units=got["units"], + description=(request.form.get("description") or "").strip(), note=got["note"]) + except task_sets.Refused as e: + flash(str(e), "error") + return redirect(back) + flash(f"Saved the task set {entry['label']}: {len(got['units'])} {'task' if len(got['units']) == 1 else 'tasks'}.", "ok") + return redirect(url_for("benchmark_tasks", key=bench["key"], dataset=entry["dataset"], set=entry["name"])) + + +def _until_again(j, names): + """The job as its page shows it while the trials ``names`` run again: a trial whose new try has not ended + has no result in its folder yet, and its last try kept in ``retried/`` stands in its place until it has. + (the job, the names of the trials shown by an earlier try).""" + have = {t.trial_name for t in j.trials} + earlier = [] + for name in names: + if name in have: + continue + kept = os.path.join(j.dir, "retried") + tries = [int(k.rpartition(".try-")[2]) for k in (os.listdir(kept) if os.path.isdir(kept) else ()) + if k.startswith(name + ".try-") and k.rpartition(".try-")[2].isdigit()] + t = parse.parse_trial(j.job_id, os.path.join(kept, f"{name}.try-{max(tries)}")) if tries else None + if t is not None: + earlier.append(replace(t, trial_name=name)) + if not earlier: + return j, set() + return replace(j, trials=sorted(j.trials + earlier, key=lambda t: t.trial_name)), {t.trial_name for t in earlier} + + def _runs_of(g, owner=None) -> list: """The runs Nullius made that hold every row of the launch *g*, and no job outside it; [] when a row is not one of theirs. ``owner``: a job's run.""" @@ -881,7 +1020,33 @@ def _live_board_state(j): # "running" here means "show the board and keep polling": the preparation # window and the starting state are on the board too, so it is every # state but finished — and unknown, an empty feed, which has nothing to show. - return {"running": snap["state"] in ("preparing", "starting", "running"), "initial": snap} + return {"running": snap["state"] in ("preparing", "starting", "running"), "initial": _with_part(j, snap)} + + +def _with_part(j, snap: dict) -> dict: + """The board's snapshot, with ``part`` while a standard job's run goes on over a part of its plan: the trials + of that part, the units its config began with or those the latest later start names, or the trial IDs chosen + for that later start where this application started it. The board counts the planned trials outside it as not + run, not queued. The snapshot as it was otherwise.""" + if not j.standard or snap.get("state") not in ("starting", "running"): + return snap + from nullius.standard.runner import rerun + try: + starts = [e.data for e in live.read_events(live.feed_path(j.dir)).events if e.event == "job.start"] + with open(os.path.join(j.dir, "config.json"), encoding="utf-8") as f: + began = ((json.load(f).get("standard") or {}).get("start_with") or {}).get("units") + except (OSError, ValueError, AttributeError): + return snap + units = starts[-1].get("tasks") if len(starts) > 1 else began + plan = rerun.planned(j.dir) if isinstance(units, list) else None + if not plan: + return snap + ex = execution.for_job(j.job_id) if len(starts) > 1 else None + chosen = ex.again_of(j.job_id) if ex is not None else None + if chosen is not None: # the attempts chosen, not every attempt of their tasks + return dict(snap, part=list(dict.fromkeys(chosen["trials"]))) + wanted = set(units) + return dict(snap, part=[name for name, unit in plan if unit in wanted]) @app.route("/job//live") @@ -911,6 +1076,6 @@ def job_live(job_id): response.status_code = 422 response.headers["Cache-Control"] = "no-store" return response - response = jsonify(snap) + response = jsonify(_with_part(j, snap)) response.headers["Cache-Control"] = "no-store" return response diff --git a/docs/benchmarks/add-manually.md b/docs/benchmarks/add-manually.md index 6ea08c99..a4cc1e3e 100644 --- a/docs/benchmarks/add-manually.md +++ b/docs/benchmarks/add-manually.md @@ -20,6 +20,7 @@ A standard benchmark from a scaffold, its driver calling the upstream's own code | `datasets[].path` | The file's path in that upstream | | `datasets[].sha256` | `sha256sum /path/to/dataset.jsonl` of that exact file | | `datasets[].units` | How many units | + | `datasets[].subset_of` | Optional: the id of the list this one is cut from, holding all its units | | `needs` | The ports really needed | | `score.says` | What a passing score means | diff --git a/docs/builder.md b/docs/builder.md index e4c9d867..268b4663 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -24,7 +24,7 @@ Then [read its results](results.md). | --- | --- | | Benchmark | A catalogue entry of either runner, and a version when it has several (`key@version`). | | Runner | **Nullius**, [the standard](standard.md#from-the-app), or **Harbor** with its pin ([Which Harbor](#which-harbor)). Only when both are supported. Default: Nullius | -| Dataset | One or more; each dataset with each agent is a job of its own. A benchmark option its datasets need is asked here, for the datasets it applies to. | +| Dataset | One or more; each dataset with each agent is a job of its own. Each runs all its tasks or one [task set](cli/task-sets.md), its benchmark's own lists (`subset_of`) included. **Start with**: all of it, or the tasks ticked, the rest left for the job's page ([`--start-with`](cli/run.md#plan-the-whole-begin-with-a-part)). A benchmark option its datasets need is asked here, for the datasets it applies to. | | Agent (*Memory* on a memory benchmark) | Reference agents first, or **No agent · Original** for a direct-model benchmark. A benchmark with [agents of its own](standard.md#a-benchmarks-own-agents) (OSWorld's) lists them first, in place of its Original tile; several may be chosen, a job each. Memory benchmarks offer **Original memory** alongside compatible memory capabilities. | | Model | **Like the paper** keeps what the paper fixed: the model picker shows only documented paper models when the benchmark lists them, and the user simulator and judge are their official models. A benchmark that lists no paper models but has an official simulator or judge leaves the model to you. **Like the leaderboard**, on a benchmark that declares its leaderboard's rules, leaves the model to you and fixes what the leaderboard does: its user simulator and judge, the options it sets and at least its attempts per unit. **Any of your choice** opens the provider's full list and lets the simulator and judge be changed. Nothing fixed by the paper: the paper choice is disabled. **Served by**, on OpenRouter, chooses the serving providers that may answer that model, tried in their order and no other ([Run a benchmark](cli/run.md#serving-providers)). Empty: any of them. | | Limits | Task limit (empty is every task), a task-name glob, concurrency, attempts per unit (each one scored), retries after an error (never after a failed task), timeouts in minutes. On the Nullius runner, a [spending cap](cli/run.md#a-spending-cap) for the run and one per unit, turns per conversation for a benchmark that holds conversations, a [cap on model calls](cli/run.md#a-cap-on-model-calls) per unit, what each trial keeps of its model calls ([`--exchanges`](cli/run.md#the-exchange-record)), [time limits](cli/run.md#time-limits) per phase in minutes, forced on every participant (empty: the benchmark's or agent's own value, else Nullius's default), then the benchmark's own bounds; a [list of units](cli/run.md#a-list-of-units) is set only on the command line | diff --git a/docs/cli/README.md b/docs/cli/README.md index 533fd34c..bdd85b15 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -19,6 +19,8 @@ From a source checkout, replace `nullius` with | [Conform an agent or a capability](conform.md) | `nullius standard conform` | | [Fidelity](fidelity.md) | `nullius standard fidelity` | | [Shard and merge](shard-and-merge.md) | `nullius standard run --shard`, `merge` | +| [Task sets](task-sets.md) | `nullius standard units`; `set create`, `list`, `show`, `rename`, `delete`, `import`; `run --set` | +| [Run tasks again](rerun.md) | `nullius standard rerun` | | [Storage](../settings/README.md#storage) | `nullius paths [--json]` | | [Model prices](../settings/model-prices.md) | `nullius prices [list\|update\|set\|remove]` | | [Migration](../getting-started.md#migrate-an-existing-checkout) | `nullius migrate --from CHECKOUT [--secrets PATH] [--apply]` | diff --git a/docs/cli/pages.md b/docs/cli/pages.md index 7caed9c2..1e25298f 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -17,9 +17,13 @@ Each page's command, or why there is none. | `/settings` | User `settings.json`, or the environment; `nullius paths` locates the file | | `/benchmarks` | `nullius standard list` for standard entries; Harbor entries on the page | | `/agents`, `/capabilities` | `nullius standard list` includes agents, capabilities and their proven ports | +| A benchmark's *Task sets* | `nullius standard set list KEY` ([Task sets](task-sets.md)) | +| `/benchmarks//tasks/` | `nullius standard units KEY --dataset D`; a set's, `set show KEY NAME` | +| Save, rename or delete a task set | `nullius standard set create`, `--from-job` for a job's; `set rename`, `set delete` | | A benchmark's *Prove it* | `nullius standard prove KEY` ([Prove](prove.md)) | | *Prove its ports* | `nullius standard conform KEY` ([Conform](conform.md)) | | `/run` | `nullius standard run` per dataset and choice, `--shard I/N` per machine ([Run](run.md)) | +| A job's *Run selected again*, *Run the rest*, *Run a set* | `nullius standard rerun JOB_DIR --unit ID`, `--unfinished`, `--set NAME` ([Run tasks again](rerun.md)) | ## While the app runs diff --git a/docs/cli/rerun.md b/docs/cli/rerun.md new file mode 100644 index 00000000..8d11863d --- /dev/null +++ b/docs/cli/rerun.md @@ -0,0 +1,33 @@ +# Run tasks again + +Chosen tasks of an ended job, or those an interruption left with no result, run again in that job. + +```bash title="Run tasks again" +nullius standard rerun JOB_DIR (--unit ID ... | --units FILE | --unfinished | --next N | --set NAME) [--reason TEXT] [-j N] [--retries N] [--max-usd USD] +``` + +| Flag | Does | +| --- | --- | +| `--unit ID` | A trial's name, or a unit's id for each of its attempts; repeatable | +| `--units FILE` | The ids a file lists, as [a run's list](run.md#a-list-of-units) | +| `--unfinished` | Planned trials with no result, cut off by the spending cap, or ended by a Stop | +| `--next N` | The next N planned tasks with no result, in the plan's order | +| `--set NAME` | The planned tasks with no result that a [task set](task-sets.md) names | +| `--reason TEXT` | Why, kept in the job's record | +| `-j N` | Units at once; the job's by default | +| `--retries N` | Automatic retries of each try, as [a run's](run.md#retries); 0 by default | +| `--max-usd USD` | The job's [spending cap](run.md#a-spending-cap) from this part on | +| `--from-run` | Started by Nullius: `OPENAI_API_KEY` and `OPENAI_BASE_URL` only, saved settings unread | + +| Rule | Detail | +| --- | --- | +| A try | The trial's folder is kept as `retried/.try-N`; the new result takes its place. | +| A task never begun | Runs as its first try, under the name the run gave it. | +| The settings | The job's own `config.json` and, on a host, the job's copy of the catalogue. | +| Refused | No task, an id never planned, a running job, another version, or no cap left. | +| A merged job | Runs again in place; `--unfinished` is refused, since it has no live feed. | +| The record | The trial's `standard.rerun` and the job's `reruns` keep each re-run, its reason and spend. | +| Score and cost | The new result is the task's on every page; the job's cost adds every try. | +| One cap | Each later part has the job's cap less what the parts before it spent. | +| A job begun on a part | `--next`, `--set` or `--unfinished` runs more of its plan in the same job. | +| The job's page | Runs chosen tasks again the same way, where the job ran ([Run tasks again](../results.md#run-tasks-again)). | diff --git a/docs/cli/run.md b/docs/cli/run.md index ffc40c4b..a878b431 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -3,7 +3,7 @@ One benchmark and one agent, capability, control or setup, into a job. ```bash title="Run" -nullius standard run [@version] [--model M] [--dataset D] [--units FILE] [--limit N] [-j N] \ +nullius standard run [@version] [--model M] [--dataset D] [--units FILE | --set NAME] [--limit N] [--start-with N|FILE|set:NAME|ids:ID,ID...] [-j N] \ [--unsandboxed | --backend container|boat] [--option NAME=VALUE]... [--bench-option NAME=VALUE]... \ [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]]... [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS]... [--max-turns N] [--max-calls N] \ [--constraint KEY=VALUE]... \ @@ -15,6 +15,8 @@ nullius standard run [@version] [--model M] [--dataset D] [-- nullius standard run humaneval reference --model gpt-5-mini --limit 2 --unsandboxed nullius standard run humaneval oracle --limit 6 nullius standard run humaneval oracle --units tasks.txt +nullius standard run humaneval oracle --set first-ten +nullius standard run humaneval oracle --start-with 10 nullius standard run locomo original --model gpt-3.5-turbo-4k nullius standard run locomo model --model gpt-4o-mini ``` @@ -27,6 +29,8 @@ nullius standard run locomo model --model gpt-4o-mini | `--provider` | `anthropic`, `custom`, `openai` or `openrouter` | | `--dataset`, `--limit`, `-j` | One dataset, the first N units, N at a time | | `--units FILE` | Only the units the file lists: [below](#a-list-of-units) | +| `--set NAME` | Only the units of a [task set](task-sets.md), in its dataset | +| `--start-with N\|FILE\|set:NAME\|ids:ID,ID...` | Plan the whole, begin with a part: [below](#plan-the-whole-begin-with-a-part) | | `--unsandboxed` | An agent runs as you; else `--backend container` | | `--backend` | `local` (default); `container`, each unit in a container with its relay; or [`boat`](../standard.md#the-boat-backend), a VM per unit | | `--boat-size` | Boat's VM size: `small` (default), `default`, `large`, `xlarge` | @@ -123,6 +127,7 @@ A benchmark that names a cut in `limits.scored_cuts` still scores an agent's uni | Cached input | Estimated as if not cached, so a unit can be cut off short of its cap | | The result | `result.json` carries `budget` | | From the builder | *Limits*: one cap shared in equal parts by the run's jobs, and one per unit | +| Later parts | The job's one cap: each part has what the parts before it left ([Run tasks again](rerun.md)) | | Shards | A shard's cap is its own: [Shard and merge](shard-and-merge.md) | ## Retries @@ -137,7 +142,7 @@ A benchmark that names a cut in `limits.scored_cuts` still scores an agent's uni | Wrong key, spent credit | No; three in a row stop the run | | A setup this machine lacks, a missing secret, a cap reached, Stop, a unit a guard asked to stop, a full context window, failed task | No | -`conform` and `prove` retry a rate limit once. +`conform` and `prove` retry a rate limit once. Chosen tasks of an ended job run again by hand: [Run tasks again](rerun.md). ## A list of units @@ -159,6 +164,25 @@ HumanEval/12 | The record | `config.json`: `standard.units_file`, the file's name, its sha256 and its units | | Where it is read | On the machine the command runs on, from the directory it starts in | | The builder | A recipe has no field for a list | +| A named list | A [task set](task-sets.md) keeps one, frozen: `--set NAME` | + +## Plan the whole, begin with a part + +`--start-with` plans the whole run and begins only a part of it; the rest stay planned, run later in the same job by [`rerun`](rerun.md). + +| The part | Begins | +| --- | --- | +| `N` | The plan's first N units, in its order | +| `FILE` | The units a file lists, as [a list of units](#a-list-of-units) | +| `set:NAME` | The units of a [task set](task-sets.md) of the run's dataset | +| `ids:ID,ID,...` | The units named, separated by commas with no space | + +| Rule | Detail | +| --- | --- | +| Refused | A unit outside the plan, more units than it holds, another dataset's set, or `--shard`. | +| Attempts | A unit begun gets all its `--attempts`; a unit not begun has none. | +| The record | `config.json` keeps the plan's size, `datasets[0].n_tasks`, and the part, `standard.start_with`. | +| The rates | Over the tasks run; the job's page and `runs show` say how many have run. | ## Serving providers diff --git a/docs/cli/shard-and-merge.md b/docs/cli/shard-and-merge.md index 9a6c785c..5851b99d 100644 --- a/docs/cli/shard-and-merge.md +++ b/docs/cli/shard-and-merge.md @@ -14,8 +14,9 @@ nullius standard merge jobs_standard/*__shard-* -o jobs_standard/humaneval-oracl | Shards by the unit's id | `sha256(unit id) mod N`: every unit in exactly one shard, new units leave the rest in place; changing N moves most. Order: `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6`: the first six of shard 1) | | A unit keeps its place | `u0042` is the 43rd unit of the dataset in every shard; shard jobs never share a trial name | | One launch | Each shard's `config.json` records `standard.shard` (`index`, `of`, `units_total`, `partition`, `planned`, `limit`) and `standard.launch`: `--launch`, or the day (UTC), benchmark, agent or capability and model. The runs page groups them until merged, then counts the merged job alone; source job files are kept | -| `merge JOB_DIR... -o OUT` | One job with its `result.json` recomputed. Different launches, versions, datasets, agents, models, backends or N refused unless `--force`; lists of different units and two trials of one unit always. Units no shard ran are named | +| `merge JOB_DIR... -o OUT` | One job with its `result.json` recomputed. Different launches, versions, datasets, agents, models, backends, N or task sets refused unless `--force`; lists of different units and two trials of one unit always. Units no shard ran are named | | A list of units | `--units FILE` on every machine: [Run a benchmark](run.md#a-list-of-units). A list's file name, comments and sha256 may differ from shard to shard; the merged job records the first shard's list | +| A task set | `--set NAME` on every machine, each with the entry; the merge keeps the first shard's set | | A spending cap | Each shard's own; the builder shares a recipe's cap over its shards. `merge` adds them into one `budget` when every shard had one | | `prove --shard I/N` | Controls and leak on that shard, units on all; recorded as `shard` | diff --git a/docs/cli/task-sets.md b/docs/cli/task-sets.md new file mode 100644 index 00000000..f9d9ff56 --- /dev/null +++ b/docs/cli/task-sets.md @@ -0,0 +1,40 @@ +# Task sets + +A named list of one dataset's units, frozen once made, that a run names and its job records. + +```bash title="Commands" +nullius standard units --dataset D [--bench-option NAME=VALUE]... [--search TEXT] [--category FIELD=VALUE]... [--json] +nullius standard set create [@version] "WORDS" [--dataset D] (--units FILE | --search TEXT | --category FIELD=VALUE... \ + | --from-job JOB_DIR [--outcome O,...]... [--unit ID]...) [--description TEXT] +nullius standard set list [] [--json] +nullius standard set show NAME [--json] +nullius standard set rename NAME "WORDS" +nullius standard set delete NAME +nullius standard set import PATH +nullius standard run --set NAME ... +``` + +```bash title="Examples" +nullius standard units osworld1 --dataset test_nogdrive --search tab --category domain=chrome +nullius standard set create humaneval "first ten" --dataset humaneval --units ten.txt +nullius standard set create humaneval misses --from-job jobs_standard/JOB --outcome failed,infra +nullius standard run humaneval reference --model gpt-5-mini --set first-ten --unsandboxed +``` + +| Rule | Detail | +| --- | --- | +| `units` | Each task's id, title, text and categories; ids alone when the driver has no `describe`. | +| A listing | Prepares the upstream, the dataset and, without `driver.list_command`, the driver's environment; starts no unit. | +| `--search`, `--category` | Every word in the id, title or text; one field's values widen, two fields narrow. | +| The entry | `sets//NAME.json` in the user catalogue, a plain file to copy or keep. | +| Frozen | No command changes a set's list; `rename` changes its label; jobs find it by id. | +| Its name | Up to 80 characters with a letter or a digit; commands take its slug. | +| `--from-job` | The units a standard job ran, or only those of `--outcome`'s outcomes and each `--unit`. | +| `import` | Adds an entry, or a job's set; another id under that name is refused. | +| A run | Takes the set's dataset and units; another `--dataset`, `--units` or an unlisted id is refused. | +| Another version | Refused before any unit when the run's dataset lacks one of the set's tasks. | +| The record | `config.json` keeps `standard.task_set`: the set's id, name, hash, units and version. | +| On a host | The app sends a recipe's sets with the runner; by hand, copy or `import` the entry. | +| The pages | Save, rename and delete a set only from a browser on the application host. | + +Exit codes: 0 done, 2 a usage error or a refusal, 3 no such benchmark, dataset, set, file or job ([Exit codes and output](exit-codes.md)). diff --git a/docs/concepts.md b/docs/concepts.md index c7281152..916786e5 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -12,6 +12,7 @@ The tasks and how each is scored; one folder in the catalogue, run on one or bot | Task, unit | One problem of a dataset; the standard says unit | | Task limit | How many tasks a run takes; empty means every task | | List of units | The tasks a standard run takes by their ids, from a file ([`--units FILE`](cli/run.md#a-list-of-units)) | +| Task set | A named, frozen list of a dataset's units that a run can take ([`--set NAME`](cli/task-sets.md)) | | Verifier | The benchmark's own scoring: tests, an exact answer, a judge model | | Setup | Who answers: `original` (the published pipeline and models), `model` (that pipeline, your model), or your agent or capability | | Control | A run with no agent: `nop` does nothing, `oracle` applies the reference solution | diff --git a/docs/field-guide.md b/docs/field-guide.md index f1755b8d..be3bfb68 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -32,7 +32,7 @@ Benchmarks measure performance. Kits check that an agent or capability implement ## Attempts and retries {#attempts} -An attempt is one run of a task, counted whatever its result. A retry reruns an attempt after an infrastructure or agent failure; its last try is the trial. +An attempt is one run of a task, counted whatever its result. A retry reruns an attempt after an infrastructure or agent failure; its last try is the trial. A task run again by hand ([`standard rerun`](cli/rerun.md)) is a further try of its attempt, or its first if never begun. A job [begun on a part of its plan](cli/run.md#plan-the-whole-begin-with-a-part) has its rates over the tasks run. Standard runs with repeated, scored attempts record both measures in `pass_hat_k`. They answer different questions. @@ -152,13 +152,14 @@ How the agent worked, not whether it won. Computed over layer 3. | `total_cache_tokens` | The part of those served from cache, as each trial's `result.json` records it. | derived | any | | `total_output_tokens` | Completion tokens. | derived | any | | `total_cost_usd` | The trials' recorded costs and their retried tries', summed: an estimate, not a bill. Shows — when none recorded one. | derived | any | -| `duration_min` | The whole run, start to finish. | derived | any | +| `duration_min` | The first run, start to finish; the job's page adds each later run. | derived | any | | `budget` | A standard run's spending cap, from `result.json`: `max_usd` and `spent_usd`, whether it `stopped` the run, the units `cut_off` and `not_run`, and with a cap per unit `unit_max_usd` and `over_unit`. Empty without a cap. | measured | any | | `agent_label` | The agent's name: the class of a `module:Class` path, or the trials' own name when the config gives none. | measured | any | | `agent_version` | The version the trial's `agent_info` reports. | measured | any | | `is_control` | An `oracle` or `nop` run: a check on the tasks, kept out of rankings and totals. Its row reads as a verdict, not a rate. A standard run is one only when its benchmark declares that control. On a benchmark that scores, a control's score of 1 reads as accepted and 0 as rejected. | measured | any | | `is_running` | The job records running or pending trials. Numbers are partial. | measured | any | | `n_planned / n_retries` | Planned trials from the run record or task count, and retries recorded by the harness. Repeated attempts are separate trials, not retries. | measured | any | +| `n_tasks_run · start_with` | Tasks with a trial, of `n_tasks` planned; `start_with`, the part a standard job began on. | measured | any | | `retries` | Retries a standard run allows each attempt (`--retries`); 0 elsewhere. | measured | any | | `identity` | A standard run's setup: benchmark, agent, model, provider, limits. Empty elsewhere. | measured | any | | `dataset` | The dataset folder, `name@version` for a registry fetch, or the task names' shared prefix. | measured | any | @@ -184,7 +185,7 @@ How the agent worked, not whether it won. Computed over layer 3. | `n_steps / n_tool_calls` | Trajectory steps and tool calls; empty placeholder calls are not counted. | measured | any | | `exception_type` | What ended the trial, if anything. It decides the infra / agent split. | measured | any | | `ended_by` | What ended the agent's work: `agent`, the benchmark's own end, or a limit (`time`, `calls`, `end`). | measured | standard | -| `n_retries` | Retries a standard run's attempt took. | measured | any | +| `n_retries` | Retries a standard run's attempt took, runs again by hand included. | measured | any | | `n_rate_limited_retries` | 429s counted in `agent/gateway.log`: on Harbor, the ones the agent's SDK retried and survived; on a standard run, every model call the relay saw refused with 429. No log: no count, never 0. | inferred | any | ## Standard run records @@ -194,6 +195,7 @@ These fields are stored in the standard's job and trial files ([Run a benchmark] | Field | What it is | Source | Works on | | --- | --- | --- | --- | | `standard.units_file` | In `config.json`: the units file's name, sha256 and ordered ids, before sharding and the limit. | measured | standard | +| `standard.task_set` | In the same config: the task set run, with its id, name, hash, ids and version. | measured | standard | | `standard.constraints` | In the same config: what the machine allowed the run, when set. Shards may have different machine constraints; merging keeps the first shard's config values. | measured | standard | | `standard.served_by` | In the same config: the allowed OpenRouter provider slugs by model, in the order tried. | measured | standard | | `served / standard.served` | In the job's `result.json` and each trial's `result.json`, respectively: answered calls by provider (`calls`), calls naming none (`unnamed`), and each pinned model's `held`. Counts cover every relay route; the job also includes the benchmark's own relay. Tokens and cost are the agent's own calls'. | measured | standard | diff --git a/docs/how-it-works.md b/docs/how-it-works.md index dd80515c..119317f7 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -79,7 +79,7 @@ workspace root. `nullius paths` shows the active location. | Page | Shows | | --- | --- | | `/runs` | Runs by launch; `?view=all` the flat table | -| `/job/` | Trials, or the live board while it runs | +| `/job/` | Trials, or the live board while it runs; chosen tasks run again | | `/trial//` | Conversation, trace, artifacts, judgement | | `/job//reconcile` | Outcome versus judged failure cause | | `/job//feasibility` | Oracle and nop brackets, broken tasks | diff --git a/docs/results.md b/docs/results.md index 20df63ab..db79dd27 100644 --- a/docs/results.md +++ b/docs/results.md @@ -30,6 +30,10 @@ Foreign results open the same way: [Open existing results](getting-started.md#op | 3 | Conversation and tool calls | Which actions led there? | | 4 | Trace and artifacts | Which calls failed or ran slowly? What files were produced? | +## Run tasks again + +On an ended standard job, the tasks ticked on its page run again in that job, where it ran, and the new result takes each task's place. A job [begun on a part of its plan](cli/run.md#plan-the-whole-begin-with-a-part) runs the rest the same way, its rates over the tasks run ([`nullius standard rerun`](cli/rerun.md)). + ## Check the task - **Controls:** the `nop` and `oracle` jobs beside the agent's ([Core concepts](concepts.md#benchmark)). diff --git a/docs/standard.md b/docs/standard.md index 012654a9..0d2eb768 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -146,6 +146,7 @@ record); verifier/reward.txt and score.json | Rate limits | After a `rate_limited` end no unit starts for 60 s, or the provider's `Retry-After`, doubling to 300 s while units keep ending so | | The relay | Headers pass through except the credentials, replaced by the relay's key; `agent/calls.jsonl` names them, never their values. A 429 reaches the agent as it came, never retried. Every call goes as the run's model, the one asked recorded as `model_asked`, except `model.side_models`, sent as asked and recorded `side`. Provider `anthropic` serves `messages` only ([protocols](settings/model-providers.md#protocols)) | | Constraints (`--constraint KEY=VALUE`) | What the machine allows Nullius, from Settings ([constraints](settings/run-hosts.md#constraints)): flags on every container the run starts on the machine, on either backend; a systemd scope for each process the run starts there (its drivers, and its agents and capabilities on the local backend); the most units at a time; the CPU affinity; the driver's `CUDA_VISIBLE_DEVICES`. The local backend refuses a cap that no scope holds. `config.json` records the values under `standard.constraints` | +| A task set (`--set NAME`) | A frozen, named list of a dataset's units, recorded in `config.json` as `standard.task_set` ([Task sets](cli/task-sets.md)) | | A cap on model calls (`--max-calls`) | Agents only. A unit's relay counts its agent route's answered calls and refuses the one past the cap: the agent's error, as a timeout is ([Run a benchmark](cli/run.md#a-cap-on-model-calls)) | | Who served a call | Each call's record keeps the routing field it was sent with (`request.routing`), the serving provider its reply names (`reply.served_by`), how the reply ended (`reply.end`: `finish_reason`, `stop_reason` or a Responses status) and an error the reply holds under a 200 (`reply.error`), cleaned of credentials. | | Serving providers (`--served-by`) | On OpenRouter, the providers that may answer a model, in order and no other: the caller's own routing is replaced, kept as `request.routing_asked`. `config.json` records `standard.served_by`; each trial's `result.json` and the job's say the calls of every route by serving provider and, for each pinned model, `held`, which reads the provider's name alone ([Run a benchmark](cli/run.md#serving-providers)) | @@ -365,7 +366,7 @@ N machines are N runs of the same command, each with `--shard I/N`, and one merg | Shards by the unit's id | `sha256(unit id) mod N`; changing N moves most units. Order: the driver's `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6` is the first six units of shard 1) | | A unit keeps its place | `u0042` is the 43rd unit of the whole dataset in every shard | | One launch | Each shard's `config.json` records `standard.shard` (`index`, `of`, `units_total`, `partition`, `planned`, `limit`) and `standard.launch` (`--launch`, else the UTC day, benchmark, agent or capability and model). With `--units`, `units_total` counts the listed units. The shards' lists hold the same units; a list's file name, comments and sha256 may differ from shard to shard | -| `cli merge JOB_DIR... -o OUT` | One job: trials hard-linked, `result.json` recomputed, `config.json` with `merged_from`. Shards that differ in launch, version, dataset, agent, model, serving providers, backend or N are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. | +| `cli merge JOB_DIR... -o OUT` | One job: trials hard-linked, `result.json` recomputed, `config.json` with `merged_from`. Shards that differ in launch, version, dataset, agent, model, serving providers, backend, N or task set are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. | | `cli prove --shard I/N` | The controls and the leak check on that shard's units; each record says `shard` | | Different options per shard | Shards of one launch may differ in `--bench-option` (a unit that needs a service its machine serves); the merged config keeps each shard's in `merged_from` | | `cli prove --job nop=MERGED` | Checks a merged launch of a control against its bound instead of running it. The job and each of its trials name that benchmark, version, control and job; each unit of the dataset has one trial, scored 0 to 1; the units check passes. `--dataset` named, no `--limit` or `--shard`. The record names the job and its options | @@ -414,7 +415,7 @@ local proof records; saved runs and credentials remain. ### A benchmark 1. **Scaffold it.** `cli new benchmark KEY` (`--family capability --port cap.memory/v1` for a capability benchmark) writes `benchmarks//standard.json` and `driver.py` under your user catalogue (`nullius paths`). -2. **Pin the data.** `upstream.repository` and `upstream.tested`, a full commit: the latest release tag's (`upstream.tag`; an annotated tag's commit is the `^{}` line of `git ls-remote --tags`), a default-branch commit only without a release. Each dataset: its `path` in the upstream or its `url` at a revision, its `sha256` and `units`. Installs and upstreams go under `STANDARD_DIR` (`~/.local/share/nullius/standard` on Linux by default), downloaded datasets under its `datasets/` or `STANDARD_DATA_DIR`. +2. **Pin the data.** `upstream.repository` and `upstream.tested`, a full commit: the latest release tag's (`upstream.tag`; an annotated tag's commit is the `^{}` line of `git ls-remote --tags`), a default-branch commit only without a release. Each dataset: its `path` in the upstream or its `url` at a revision, its `sha256` and `units`; optional `subset_of`, the id of a list cut from none that holds every unit of this one. Installs and upstreams go under `STANDARD_DIR` (`~/.local/share/nullius/standard` on Linux by default), downloaded datasets under its `datasets/` or `STANDARD_DATA_DIR`. 3. **Choose the needs.** The fewest ports: `agent.workspace/v1` for files, `agent.search/v1` for search and source retrieval, `agent.tools/v1` for MCP tools, `agent.conversation/v1` if a user speaks more than once; a skill the units cannot be done without goes in `needs_skills`. 4. **Write the driver.** It answers the [ops below](#driver-ops); the dataset file is `$NULLIUS_DATASET` (empty for a dataset with no `path` or `url`), the upstream `$NULLIUS_UPSTREAM`, the version `$NULLIUS_VERSION`. Keep the tests out of the workspace until `score`; prints go to stderr. 5. **Its own options**, when the upstream offers a choice a run should make ([below](#benchmark-options)). @@ -427,6 +428,7 @@ local proof records; saved runs and credentials remain. | Op | Sent | Replies | | --- | --- | --- | | `units` | `dataset`, `setup` | Every unit id | +| `describe` | `dataset`, with `driver.describe` | `{units: {ID: {title, text, categories: {FIELD: VALUE}}}}`, from the dataset's files alone, for [listings](cli/task-sets.md) | | `setup` | `unit`, `dir`; `attempt` with `limits.attempts`; `participant` (`agent`, `capability` or `control`) with `driver.participant` | `{prompt}`, any `mcp` servers, `environment`, an own image's `image`, `prepare`, `internet` and `verify`, and `agent_seconds`, the unit's own agent timeout (up to 6 hours, instead of `limits.turn_seconds`); `progress`, a file in the trial the driver rewrites: `{steps, steps_limit, ended}` | | `turn` | The transcript so far; `simulator: {model, base_url, key}` when there is one; `judge` for an upstream that grades as the conversation ends; `attempt` with `limits.attempts` | The next message, `{done: true}`, or `restart` | | `produce` | A capability benchmark's recall, `base_url` and `key` | The reading, through the relay | @@ -451,6 +453,8 @@ An `answer` or `score` error that begins `EnvironmentSetupError: `, `VerifierErr | `limits.call_seconds` | How long the relay waits for one model call's reply (default 900). A benchmark whose agent waits longer for a call sets it above that agent's own wait, so the agent's client, not the relay, ends a long call | | `driver.participant` | `true`: `setup` is also sent `participant`, the kind of what runs the unit, for a driver that starts something only an agent uses | | `driver.unit_end` | `true`: the driver is sent `end` (`unit`, `dir`) once each unit an agent ran has ended, scored or not, so that what its setup started for the agent ends with the unit. A control's or a setup's unit gets none | +| `driver.describe` | `true`: the driver answers `describe`; without it a listing gives ids alone | +| `driver.list_command` | A start of the driver for listings alone, needing only the standard library and the dataset's files; `{here}` its one slot | | `driver.task_given` | `true`: the driver is sent `task_given` before each agent is given its task, and the task waits for its answer: [the computer port](ports/agent-computer-v1.md#the-window-before-the-task) closes its window before the task there. A control's or a setup's unit gets none | | `limits.attempts` | How the upstream tells attempts apart; the driver is then sent `attempt` with `setup`, `turn` and `answer` | | `limits.scored_cuts` | The cuts after which an agent's unit is still scored: `time`, `calls`, `end` ([a unit cut at a limit](cli/run.md#a-unit-cut-at-a-limit)) | @@ -636,6 +640,7 @@ already accepts arbitrary models needs only the `original` method. | Recorded | `standard.setup` in the config and each trial: its name, the model `asked` and `sent`, `comparable_with_paper`, and the benchmark's own agent that ran (`agent`), whose key is also the job's agent (`agent_info.name`) | | Attempts | `cli run --attempts K` runs each unit K times; `result.json` carries [`pass_hat_k`](field-guide.md#attempts) | | Retries | `cli run --retries N` runs a failed attempt again: [which failures](cli/run.md#retries) | +| Run again by hand | `cli rerun JOB_DIR` runs chosen or unfinished tasks of an ended job again in it ([Run tasks again](cli/rerun.md)) | ### A benchmark's own agents