diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 8e101f13d..505863eed 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}: it holds from the job's next run 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 [])] diff --git a/app/nullius/runs/cli.py b/app/nullius/runs/cli.py index 9c9770067..a0de4f575 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 started on some of its plan: how the start 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), } @@ -320,6 +326,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" started on some of its plan: {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 849eb5471..791120afc 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 6ceb2912a..04dfffc11 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -32,7 +32,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 = "24" +SCHEMA = "25" # 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 — @@ -68,6 +68,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.""" @@ -306,6 +342,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 @@ -481,6 +521,16 @@ class Job: # 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 started on some of it (config ``standard.start_with``): how the + # start 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 start'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) @@ -522,6 +572,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 started on + some 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.""" @@ -909,6 +966,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")), @@ -1255,8 +1313,16 @@ def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job: "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 6eb85de88..ba1fccd7d 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 runs of the job had from each model ([count, output tokens]), so that a later + run'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 7e9e2d01b..1ff24ef43 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -14,7 +14,9 @@ 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: @@ -46,7 +48,11 @@ ``--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``). ``set`` +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 +starts with some 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 @@ -96,7 +102,7 @@ from nullius.standard.calls import exchanges, relay 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, sets, 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() @@ -606,6 +612,11 @@ def cmd_run(a): price_list.update() except ValueError as e: unreachable = str(e) + try: + start = start_with(b, a.start_with, dataset) 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=dataset, limit=a.limit, @@ -619,6 +630,7 @@ def cmd_run(a): 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": start} if start else {}), **({"served_by": run.served_by(a.served_by, a.model or "")} if a.served_by else {}), **({"reasoning": run.reasoning(a.reasoning, a.model or "")} if a.reasoning else {}), **({"env": run_env(a.provider)} if a.from_run else {})) @@ -635,6 +647,47 @@ def cmd_run(a): return 3 if failed else 0 +def start_with(bench: dict, value: str, dataset: str | None = None) -> dict: + """``run --start-with``: the tasks a run starts with (``run.Run``'s ``start_with``). A whole number is a count, + ``set:NAME`` a task set of the benchmark (of a set of several datasets, its list of the run's ``dataset``), + ``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:"): + return set_units(bench["key"], value[4:], dataset, "--start-with set:") + try: + return {"units_file": run.units_file(value)} + except run.Refused as e: + raise run.Refused(str(e).replace("--units", "--start-with", 1)) + + +def set_units(benchmark: str, ref: str, dataset: str | None, flag: str) -> dict: + """The task set ``ref`` as the tasks of a run of ``dataset``: {"task_set": its record, "dataset": its dataset}. Of + a set of several datasets, its list of ``dataset``, refused when it holds none; of a set of one, that one, for + the run to check against its own.""" + name, rev = sets.split_ref(ref) + entry = sets.load(benchmark, name) + got = sets.latest(entry, rev) + if "datasets" not in entry: + return {"task_set": sets.record(entry, got), "dataset": entry["dataset"]} + if dataset not in entry["datasets"]: + raise sets.Refused(f"{flag}{ref}: the task set {name} mixes the datasets {', '.join(entry['datasets'])}" + + (f", not {dataset}" if dataset else "; give --dataset, one of them")) + return {"task_set": sets.record(entry, got, dataset), "dataset": dataset} + + def boat_credentials(a, bench, other, vals) -> dict: """Only the selected provider and declared benchmark licences cross SSH stdin.""" import base64 @@ -668,8 +721,8 @@ def boat_credentials(a, bench, other, vals) -> dict: def _boat_units(a, b, other) -> int: """A benchmark whose units boot VMs of their own, on Boat: each unit whole in a Boat VM (``boat_units``).""" from nullius.standard.runner import boat_units - if a.units or a.shard: - print("refused: whole-task Boat runs do not accept --units or --shard; choose a dataset and --limit") + if a.units or a.shard or a.start_with is not None: + print("refused: whole-task Boat runs do not accept --units, --shard or --start-with; choose a dataset and --limit") return 2 ds = a.dataset or b["datasets"][0]["id"] vals, bad = definitions.bench_options_of(b, ds, options(a.bench_option), @@ -1012,6 +1065,72 @@ def cmd_units(a): 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: + cfg = json.load(f) + std = cfg.get("standard") or {} + given = std.get("constraints") or {} + ran = str(((cfg.get("datasets") or [{}])[0] or {}).get("name") or "").partition("/")[2] + except run.Refused as e: + print("refused:", e, file=sys.stderr) + return 2 + except (OSError, ValueError, AttributeError): + std, given, ran = {}, {}, "" + 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: + chosen = None + if a.task_set is not None: + # a set of the job's benchmark: its tasks the job planned and has not run + chosen = set_units(str(std.get("benchmark") or "") if isinstance(std, dict) else "", a.task_set, ran or None, "--set ") + 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=chosen, **({"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: @@ -1120,6 +1239,10 @@ def main(argv=None): 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 start with some of it: " + "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; " "one with an experiment judge (LoCoMo's): run it, as this model") @@ -1250,6 +1373,28 @@ def main(argv=None): 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 run and every later one: each later run of the job has what the runs 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") @@ -1260,13 +1405,13 @@ def main(argv=None): 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, + "fidelity": cmd_fidelity, "prove": cmd_prove, "merge": cmd_merge, "rerun": cmd_rerun, "traces": cmd_traces, "set": cmd_set, "units": cmd_units}[a.cmd](a) diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 8cd5dd78e..7937b64b8 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -48,6 +48,7 @@ from nullius.standard.proofs import prove from nullius.standard.requirements import hostreq 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." @@ -540,6 +541,70 @@ def add(step, message, shown=False, field=None, unset=False): f"{', '.join(sets.datasets_of(entry))}, not {ds_id}.") continue set_of[ds_id] = {"name": set_name, "label": sets.label_of(entry), "units": len(part), "ids": set(part)} + # a chosen dataset's plan started on some of it (``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 + part = sets.parts(entry, got).get(ds_id) + if part is None: + add("dataset", f"Start with: the task set {sets.label_of(entry)} is cut from the dataset{'s' if len(sets.datasets_of(entry)) > 1 else ''} " + f"{', '.join(sets.datasets_of(entry))}, not {ds_id}.") + continue + outside = set(part) - 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(part), + "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. @@ -787,6 +852,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: @@ -794,6 +873,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 started on some 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: @@ -935,6 +1016,18 @@ def pinned(p: dict) -> Dict[str, List[str]]: 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 started on some of it: what it plans and what it starts with, 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] @@ -952,7 +1045,8 @@ def command_for(d: dict, p: dict, index: int) -> str: 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"], *(["--set", set_of[d["id"]]["name"]] if d["id"] in set_of else []), - *(["--limit", str(limit)] if isinstance(limit, int) else []), "-j", str(conc), + *(["--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 []), @@ -1032,6 +1126,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 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"]: @@ -1045,8 +1153,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" · task set {set_of[x['id']]['label']} · {set_of[x['id']]['units']} {bench_nouns}" - if x["id"] in set_of else f" · {x['units']} {bench_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']} {bench_nouns}") + if x["id"] in set_of else f" · {x['units']} {bench_nouns}" if x.get("units") and x["id"] not in start_of else "") + # started on some of the plan: 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)}")] @@ -1068,10 +1179,12 @@ def row(p: dict) -> list: + "".join(f" · {SERVED_LABEL[r_]} reasoning {', '.join(out['own_reasoning'][r_])} ({'the agent' if r_ == 'model' else 'the benchmark'}'s)" if r_ in out["own_reasoning"] else f" · {SERVED_LABEL[r_]} reasoning {levels[r_]}" for r_ in roles if r_ in levels or r_ in out["own_reasoning"])], - [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 "") @@ -1107,8 +1220,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.") - # Run asks first before every task of the datasets; a task set is a choice of tasks made already - if not isinstance(limit, int) and not set_of: + # Run asks first before every task of the datasets; a task set or a start on some tasks 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 @@ -1138,6 +1251,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 944e39015..56be076d0 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -612,7 +612,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, + 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, reasoning: Optional[Dict[str, str]] = None): @@ -625,7 +625,9 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str 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. ``repeat``: how + only for such a run. ``start_with``: a run started on some of its plan + (``run.Run.start_record``): how the start 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. @@ -658,6 +660,7 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str **({"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 67105df6a..74e4b6c15 100644 --- a/app/nullius/standard/runner/merge.py +++ b/app/nullius/standard/runner/merge.py @@ -276,9 +276,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 dd1b6ecc2..8f98c3baf 100644 --- a/app/nullius/standard/runner/payload.py +++ b/app/nullius/standard/runner/payload.py @@ -201,12 +201,15 @@ def _cached(destination: Path, marker: str, files: dict) -> bool: def recipe_sets(recipe: dict) -> list[tuple[str, str]]: - """The task sets a standard recipe runs (``task_sets``), as (benchmark, name): what its snapshot carries.""" + """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}) diff --git a/app/nullius/standard/runner/rerun.py b/app/nullius/standard/runner/rerun.py new file mode 100644 index 000000000..3aae5f1e4 --- /dev/null +++ b/app/nullius/standard/runner/rerun.py @@ -0,0 +1,623 @@ +"""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 started on some of its plan (``run --start-with``) has the rest planned +with no attempt: :func:`more` takes more 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 run is given (``max_usd``), which holds from then on. A later run's +ledger opens with the cap less what the job has spent; a run is refused +when nothing is left, or when the run before stopped at the cap and it has +not changed since. The job's ``budget`` keeps the cap, ``spent_total_usd`` +(every run) 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 stat +import time +from typing import Callable, Dict, List, Optional + +from nullius import ondisk +from nullius.harbor import feed as live_feed +from nullius.standard.backends import boat +from nullius.standard.calls import exchanges as exchange_store, 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 run of the job, 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 run 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 run'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 run has it: {"max_usd", "spent_usd" (every run), "left_usd", + "closed" (nothing left, or the last run 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 run 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]: + """More 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``, more 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") + if std.get("reasoning") and not isinstance(std["reasoning"], dict): + raise run.Refused(f"{os.path.basename(job_dir)} records its reasoning as {str(std['reasoning'])[:60]!r}, not a level " + "for each model: its config.json is not as its run wrote it") + 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 run has what the runs before it 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, reasoning=std.get("reasoning") or None, + exchanges=std.get("exchanges") or exchange_store.DEFAULT, exchanges_max_mb=std.get("exchanges_max_mb") or exchange_store.MAX_MB) + # 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 run 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 runs 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 {} + earlier = old["reruns"][k - 1] if k else {} + # Earlier shared-cap records already inherited replies and identified the run by its remaining budget. + if replies and (earlier.get("cumulative_replies") or "left_usd" in earlier): + 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 run") + r.known_models() + r.ready() # refused here, the job reads as it did: nothing has moved + p.emit("plan", stages="units") # a later run 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 + ondisk.write_whole(os.path.join(job_dir, name, NO_RESULT), json.dumps({"found_at": mark["at"], "result": None}), + mode=0o644) # readable as the trial's other files are + 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 run spent, each change of the cap, and whether this run 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 + result = os.path.join(job_dir, "result.json") + kept = os.lstat(result) if os.path.lexists(result) else None # its permissions, as the run left them + ondisk.write_whole(result, json.dumps(out, indent=1), + mode=stat.S_IMODE(kept.st_mode) if kept and stat.S_ISREG(kept.st_mode) else None) + + 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 76558ca85..b4b0bab7a 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -726,6 +726,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, @@ -738,7 +739,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, task_set: 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, @@ -767,6 +768,15 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas ``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 tasks of the plan the run starts 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 start'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 start 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 @@ -1014,6 +1024,17 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas 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 started on some 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 @@ -1210,6 +1231,9 @@ def _start(self, lck, mine) -> str: wanted = set(listed) mine = [(i, u) for i, u in mine if u in wanted] mine = mine[: self.limit] if self.limit else mine + start = None + if not why and self.start_with is not None: + start, why = self.start_of_plan([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 @@ -1231,12 +1255,14 @@ def _start(self, lck, mine) -> str: p.emit("refused", detail=why) raise Refused(why) units = [u for _, u in mine] - self.n_units = len(units) + begin = units if start is None else start + 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 start 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, @@ -1247,19 +1273,106 @@ def _start(self, lck, mine) -> str: # 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, task_set=self.task_set, + start_with=self.start_record(start) if start is not None else None, repeat=self.repeat, retries=self.retries, prices=self.prices_record(), constraints=self.constraints, served_by=self.serving, reasoning=self.reasoning, 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 + # started on some of the plan: the plan's every trial queued, the start's begun; the rest stand planned for a re-run + begun = set(start or ()) + first = work if start 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: + why = ("the agent's first call was longer than the model's context window in" if self.halted[0] == relay.CONTEXT_ERROR + else "the endpoint refused") + self.say(f"stopped: {why} {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 start 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 start_of_plan(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 start_record(self, start: List[str]) -> dict: + """What the job's config keeps of the tasks it started 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(start)) + + 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 @@ -1297,7 +1410,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 @@ -1332,44 +1445,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: - why = ("the agent's first call was longer than the model's context window in" if self.halted[0] == relay.CONTEXT_ERROR - else "the endpoint refused") - self.say(f"stopped: {why} {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 @@ -1446,7 +1525,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. @@ -1494,8 +1573,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 @@ -1719,6 +1816,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 @@ -1894,7 +1992,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), @@ -1916,7 +2014,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/units.py b/app/nullius/standard/runner/units.py index 33006a478..1ba9ca968 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -421,9 +421,10 @@ def fields(bench: dict, names: List[str]) -> Dict[str, dict]: 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, - licences=None) -> dict: + within: Optional[List[str]] = None, limit: Optional[int] = None, licences=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: + 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, name, count}, ...]}, fields: {FIELD: {label, names}}}. ``total`` counts every match, ``of`` the dataset's tasks; @@ -433,6 +434,11 @@ def find(bench: dict, dataset: str, options: Optional[dict] = None, search: str raise Refused(f"page {page}: 1, 2, ...") got = listing(bench, dataset, options, licences) 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] names = sorted({f for t in tasks for f in t["categories"]}) unknown = [f for f in chosen if f not in names] if unknown: diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index d170439c3..2bf279d9b 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -110,6 +110,7 @@ nav: - 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 8c7d02fd6..b657fbbbc 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -198,12 +198,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; delete r.reasoning; } - if (was !== b) delete r.task_sets; + 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); @@ -219,25 +220,29 @@ } // 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 dropped with it. + // 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 (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]; - return keepTaskSets(r); + 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 set of several datasets is chosen for each of them, those not chosen yet added: each runs // its part, a job of its own. A dataset no longer chosen keeps none. function setTaskSet(r, dataset, ref) { r.task_sets = {...(r.task_sets || {})}; - if (!ref) { delete r.task_sets[dataset]; return keepTaskSets(r); } + // tasks ticked to start with were ticked in the plan's list: another plan asks for them again + const unticked = ids => ids.forEach(id => { if (Array.isArray((r.start_with || {})[id])) setStartWith(r, id, ''); }); + if (!ref) { delete r.task_sets[dataset]; unticked([dataset]); return keepTaskSets(r); } const b = standardBench(r), name = ref.split('@')[0]; const set = b && b.datasets.flatMap(d => d.sets || []).find(s => s.name === name); const all = set && (set.datasets || []).length > 1 ? set.datasets.filter(id => b.datasets.some(d => d.id === id)) : [dataset]; + unticked(all); r.datasets = [...new Set([...datasetsOf(r), ...all])]; delete r.dataset; for (const id of all) r.task_sets[id] = ref; @@ -248,6 +253,21 @@ if (kept.length) r.task_sets = Object.fromEntries(kept); else delete r.task_sets; return r; } + // A chosen dataset's plan started on some of it (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 : ''); @@ -257,6 +277,7 @@ const b = standardBench(r), seen = new Set(); if (sets && sets.length) r.datasets = [...new Set(sets)].filter(id => { const w = wholeOf(b, id); return !seen.has(w) && seen.add(w); }); 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]; @@ -952,5 +973,5 @@ // A recipe nobody changed: Start over has nothing to ask about. A new one, or that one as a reloaded draft holds it // (fromJSON fills in what a new one leaves out). The page's own values are compared as they are: reading would drop the bad ones. const atDefaults = r => { const s = JSON.stringify(r); return s === JSON.stringify(prefill({})) || s === JSON.stringify(fromJSON(prefill({}))); }; - return {setTaskSet,keepTaskSets,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,reasoningRoles,setReasoning,LEVEL_NAMES,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,toggleParticipant,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,atDefaults,deleteAsk,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,reasoningRoles,setReasoning,LEVEL_NAMES,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,toggleParticipant,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,atDefaults,deleteAsk,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 6e9e5b4a0..4872d72c0 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -11,6 +11,10 @@ #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; } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 6dd2b46aa..19b57a7ff 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -819,7 +819,7 @@ return `

Which datasets?

` + `
${shown.map(x => tile({attr: 'std-dataset', key: x.id, on: on(x), title: x.label, tip: x.summary || '', meta: x.units ? x.units + ' ' + du.nouns : '', foot: datasetChecks(b, x)})).join('')}
` - + b.datasets.filter(x => chosen.includes(x.id)).map(x => nested ? familyChoice(rec, b, x, du) : taskSetChoice(rec, b, x, du)).join('') + + b.datasets.filter(x => chosen.includes(x.id)).map(x => (nested ? familyChoice(rec, b, x, du) : taskSetChoice(rec, b, x, du)) + startChoice(rec, b, x, du)).join('') + benchOptions(rec, b, 'dataset') + credentialWarnings(b, b.datasets.filter(x => chosen.includes(x.id))); } if (step === S.agent) { @@ -951,6 +951,63 @@ return `` + `
${own.join('')}
` + (yours.length ? `
${yours.join('')}
` : ''); } + // A chosen dataset's plan started on some of it: 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)) : ''; + // each tile names its dataset (data-of): the step drawn again finds the tile, not the Change button of the same pick + const tiles = [tile({attr: 'std-start', key: '', data, on: !on, title: 'All of it'}), + tile({attr: 'std-start-pick', key: x.id, data, 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 = b.units || {noun: 'unit', nouns: 'units'}, 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); + // the tasks page's routes: this base, the dataset, then listing, prepare or rows + Object.assign(page.dataset, {base: `/benchmarks/${encodeURIComponent(b.key)}/tasks/`, dataset: id, 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})}); + const go = page.querySelector('#tasks-list-go'); + if (go) go.textContent = 'List ' + u.nouns; + 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 = (C.standardBench(rec) || {}).units || {noun: 'unit', nouns: 'units'}; + 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; + } // The bounds the benchmark's upstream has of its own (its steps, its errors: options with ``limit``), in a section // of the benchmark's name after the run's scope and its time limits: those the chosen datasets and participants // take, each empty at its default, shown greyed - an agent's own under ``by`` (OSWorld's agents' steps). @@ -1005,6 +1062,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; @@ -1016,9 +1077,10 @@ runnerServed = accepted.served; if (step === S.model) syncServed(); if (!accepted.current) return; + const dropped = dropStartTasks(r(), out.errors); runnerOut = out; runnerOutKey = key; if (step === S.model) syncReasoning(); - if (step === REVIEW) renderForm(); + if (step === REVIEW || dropped && step === S.dataset) renderForm(); refreshPlan(); }, 120); } @@ -1225,7 +1287,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.

`:'')}
`; @@ -1320,11 +1382,13 @@ else if(d.runner){toRunner(d.runner,C.benchKey(r()));} else if(d.stdBench){C.setStandardBenchmark(r(),d.stdBench);} else if(d.stdOther){C.toggleParticipant(r(),d.stdOther);} // a check - 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);} + 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);} // the choice's group is drawn again as the chosen list's: so named (data-was), the redraw finds the choice in that group else if(d.stdFamily!==undefined){C.swapDataset(r(),d.was,d.stdFamily);d.was=d.stdFamily;} else if(d.stdFamilySet!==undefined){C.swapDataset(r(),d.was,d.in);C.setTaskSet(r(),d.in,d.stdFamilySet);d.was=d.in;} 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 diff --git a/app/static/catalogue/tasks.js b/app/static/catalogue/tasks.js index 61c001741..8bb7d385b 100644 --- a/app/static/catalogue/tasks.js +++ b/app/static/catalogue/tasks.js @@ -3,26 +3,30 @@ // 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 started on a click // (List questions), the same way. Until there is a list, the search is hidden. +// 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. (() => { - const page = document.getElementById('tasks-page'); - if (!page) return; - const $ = id => document.getElementById(id), d = page.dataset, nouns = d.nouns || 'tasks'; +function mount(page, opts = {}) { + const $ = id => page.querySelector('#' + id), d = page.dataset, nouns = d.nouns || 'tasks'; const writable = d.writable === 'true'; // The chosen of each dataset ({dataset: ids}): a set's own, or what this tab ticked on the benchmark's other // datasets, kept while it goes from one to another and saved together; this page's are ``chosen``. - const json = (id, empty) => { try { return JSON.parse(($(id) || {}).textContent || empty); } catch { return JSON.parse(empty); } }; + const json = (id, empty) => { try { return JSON.parse((document.getElementById(id) || {}).textContent || empty); } catch { return JSON.parse(empty); } }; // each dataset's [id, {label, href}], in the benchmark's order const pages = Object.fromEntries(json('tasks-dataset-pages', '[]')); let here = d.dataset || ''; // the dataset's own routes: listing, prepare, rows, save const route = kind => `${d.base || ''}${encodeURIComponent(here)}/${kind}`; const draftKey = `nullius-task-set:${d.bench}:${d.version || ''}:${d.set || ''}`; - let parts = json('tasks-chosen-parts', '{}'); - try { const kept = JSON.parse(globalThis.sessionStorage.getItem(draftKey) || 'null'); if (kept && typeof kept === 'object') parts = kept; } catch { /* none kept */ } - const chosen = new Set(parts[here] || []); + // the builder's dialog gives its ticks back (onChange) and keeps no draft of a set + const draft = !opts.onChange; + let parts = draft ? json('tasks-chosen-parts', '{}') : {}; + if (draft) try { const kept = JSON.parse(globalThis.sessionStorage.getItem(draftKey) || 'null'); if (kept && typeof kept === 'object') parts = kept; } catch { /* none kept */ } + const chosen = new Set(opts.chosen || parts[here] || []); + const changed = () => opts.onChange && opts.onChange([...chosen]); const keep = () => { if (chosen.size) parts[here] = [...chosen]; else delete parts[here]; - try { globalThis.sessionStorage.setItem(draftKey, JSON.stringify(parts)); } catch { /* this page's alone */ } + if (draft) try { globalThis.sessionStorage.setItem(draftKey, JSON.stringify(parts)); } catch { /* this page's alone */ } }; const total = () => Object.values(parts).reduce((n, ids) => n + ids.length, 0); // opened from a set: its members first; Show all browses the dataset @@ -35,12 +39,18 @@ const named = (field, value) => st.fields[field]?.names?.[value] || value; 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 => d.version ? url + (url.includes('?') ? '&' : '?') + 'version=' + encodeURIComponent(d.version) : url; + 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}`; // the notice: its line, and a link to where a licence is set or the button that starts a full listing function say(text, warn, got) { + if (page.isConnected === false) return; const el = $('tasks-state'), link = $('tasks-state-link'), list = $('tasks-list'); el.hidden = !text; $('tasks-state-text').textContent = text || ''; el.classList.toggle('tasks-warn', !!warn); el.classList.toggle('tasks-busy', !!text && !warn && !!got?.preparing); @@ -89,7 +99,7 @@ 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(' · '); - document.querySelectorAll('#tasks-rows td.tasks-catcol').forEach(td => { td.hidden = !fields.length; }); + 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]) => @@ -113,13 +123,19 @@ 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 route('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 prepare(got) { - return post(route('prepare'), {}).then(r => r.json()).then(g => { say(g.say || got.say, false, g); polling = setTimeout(load, 2500); }) + return post(route('prepare'), {}).then(r => r.json()).then(g => { + if (page.isConnected === false) return; + say(g.say || got.say, false, g); polling = setTimeout(load, 2500); + }) .catch(() => say('The list could not be started. Reload the page.', true)); } function notReady(got) { @@ -136,8 +152,10 @@ } $('tasks-list-go')?.addEventListener('click', () => { $('tasks-list').hidden = true; asked++; prepare({say: ''}); }); 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, size: st.size}))).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(''); @@ -158,6 +176,7 @@ const ids = [...chosen]; let got = {tasks: ids.map(id => ({id})), unknown: []}; try { got = await (await post(route('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` : '') @@ -188,7 +207,7 @@ $('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(); + box.checked ? chosen.add(id) : chosen.delete(id); chosenLine(); changed(); }); // Another dataset in place: its tasks listed, its filters and its ticks; what this one ticked is kept for the set. // The address follows (back returns), and Build a run takes it. @@ -221,7 +240,8 @@ }); $('tasks-match')?.addEventListener('click', async () => { const got = await (await nulliusFetch(query({ids: 1}))).json(); - if (got.ok && got.ready) { got.ids.forEach(id => chosen.add(id)); load(); } + if (page.isConnected === false) return; + if (got.ok && got.ready) { got.ids.forEach(id => chosen.add(id)); changed(); load(); } }); // Pick N at random: N of the matches, drawn on the server as set create --sample draws them; its seed is shown, and // kept in the set's note while the chosen are the ones drawn @@ -236,22 +256,23 @@ if ($('tasks-seed')) $('tasks-seed').value = got.seed; // the draw's seed, to draw it again setShowing(true); load(); }); - $('tasks-clear')?.addEventListener('click', () => { chosen.clear(); 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)); + ids.forEach(id => chosen.add(id)); changed(); $('tasks-paste').value = ''; $('tasks-paste-open').open = false; window.nulliusNotify?.(`${count(ids.length)} added.`); load(); }); - const msg = (text, bad) => { const el = $('tasks-msg'); if (el) { el.textContent = text; el.classList.toggle('bad', !!bad); } }; + 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) { keep(); if (!total()) return msg('Tick at least one task.', true); let got; if (picked() && Object.keys(parts).length === 1) body = {...body, note: drawn.note}; try { got = await (await post(route('save'), {...body, parts})).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); try { globalThis.sessionStorage.removeItem(draftKey); } catch { /* none kept */ } location.href = got.open; @@ -262,7 +283,7 @@ ...(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 = document.querySelector('.tasks-save'); + 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 => { @@ -274,4 +295,9 @@ setShowing(st.showing); chosenLine(); load(); + return {chosen}; +} +globalThis.nulliusTasks = mount; +const page = document.getElementById('tasks-page'); +if (page && !page.dataset.manual) mount(page); })(); diff --git a/app/static/runs/board.css b/app/static/runs/board.css index de7638735..2d92885dd 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 2872b5c31..ba0e8de71 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 job's next run 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 58fd7f6df..e5547da15 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 run of some of the plan under way: 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 478a64bb3..4a3d30cba 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 job started on some of its 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 run of the plan now under way (the snapshot's `this_run`): not run, not queued. + const outside = (s, t) => Array.isArray(s.this_run) && t.state === 'queued' && !s.this_run.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 '—'; @@ -117,7 +120,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 such a run goes on, its trials not begun, as its table lists them: a task run again counts as done and as running + const queued = Array.isArray(s.this_run) ? (s.trials || []).filter(t => t.state === 'queued' && s.this_run.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 @@ -130,7 +136,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; } @@ -173,13 +180,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(''); } @@ -201,11 +208,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 run under way that have not begun: a row each, under the running ones + const queued = Array.isArray(s.this_run) ? trials.filter(t => t.state === 'queued' && s.this_run.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 => { @@ -218,6 +228,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); @@ -231,8 +248,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 @@ -268,7 +286,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' : ''}
@@ -306,7 +324,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 10655df69..2525e8013 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -1106,6 +1106,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 59c763460..4109f0e64 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, tasks_state %} {% block title %}Run builder — Nullius{% endblock %} {% block crumb %}/ run builder{% endblock %} {% block head %}{# the Agent step's cards #} @@ -42,6 +43,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

+
+
+
+
@@ -61,4 +72,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 000000000..622359b58 --- /dev/null +++ b/app/templates/catalogue/_tasks_list.html @@ -0,0 +1,52 @@ +{#- 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). -#} + +{#- before a first listing: what to do, and the way to do it: the listing started on a click, or where a licence it + needs is set #} +{% macro tasks_state(nouns, writable) %} + +{% endmacro %} + +{#- ``pick``: Pick at random, on the tasks page that saves a set #} +{% macro tasks_list(nouns, pick=False) %} + +
+ {#- the ways to choose, then what is chosen #} +
+ + {% if pick %}{% endif %} +
Paste ids
+
+
+ 0 chosen + + +
+
+ {#- the box Paste ids opens, on its own line below the row #} +
+
+

+
+ + + + +
+ {#- the shared pager's look (_tables.html pager); its pages are the listing's, asked of the server #} + +{% endmacro %} diff --git a/app/templates/catalogue/tasks.html b/app/templates/catalogue/tasks.html index 3f151a8ef..e7e4db5f4 100644 --- a/app/templates/catalogue/tasks.html +++ b/app/templates/catalogue/tasks.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% from '_page.html' import page_head %} +{% from 'catalogue/_tasks_list.html' import tasks_list, tasks_state %} {#- what the page is for: a set's name; on the application host, a new set cut from the dataset; else the dataset #} {% set heading = label if entry else 'New task set' if writable and not broken else ds.label or ds.id %} {% block title %}{{ heading }} · {{ title }} — Nullius{% endblock %} @@ -79,51 +80,10 @@

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

{% endif %} - {#- before a first listing: what to do, and the way to do it: the listing started on a click, or where a licence it - needs is set #} - + {{ tasks_state(nouns, writable) }}
- -
- {#- the ways to choose, then what is chosen #} -
- - {% if writable %}{% endif %} -
Paste ids
-
-
- 0 chosen - - -
-
- {#- the box Paste ids opens, on its own line below the row #} -
-
-

-
- - - - -
- {#- the shared pager's look (_tables.html pager); its pages are the listing's, asked of the server #} - + {{ tasks_list(nouns, pick=writable) }} {% if writable %}
0 chosen diff --git a/app/templates/runs/index.html b/app/templates/runs/index.html index 51a2c7b1c..3c83e5d59 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 %} · started on some 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 259ac68ac..d024eaec0 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 %} @@ -54,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 }} 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 %} @@ -103,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 %} @@ -138,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. -#} @@ -192,6 +212,7 @@
raw rate
—
{% if job.mean_score_planned is not none %}
planned
{{ '%.2f'|format(job.mean_score_planned) }}
{% endif %} {% set also = job.complement %}{% if also %}
{{ also.label }}
{{ '%.2f'|format(also.score) }}
{% endif %} + {% if job.start_with %}
tasks run
{{ job.n_tasks_run }} of {{ job.n_tasks }}
{% endif %}
infra
{{ job.n_infra }} @@ -239,6 +260,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 %}
@@ -355,16 +377,21 @@
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.budget.not_run %}
{{ job.budget.not_run|length }} not run -
{% for u in job.budget.not_run %}{{ u }}{% endfor %}
{% endif %}{% endif %} + {% 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 run ends{% endif %}
{% endif %} + {#- the units the first run's cap left never begun; once a later run has run some, those still never begun #} + {%- set not_run = waiting|rejectattr('folder')|map(attribute='unit')|list if job.reruns and job.budget.not_run else job.budget.not_run %} + {% if not_run %}
{{ not_run|length }} not run +
{% for u in 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 %}
@@ -372,10 +399,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▾ @@ -389,7 +416,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 %} @@ -402,17 +444,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 %} @@ -423,7 +468,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 %} @@ -451,7 +496,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 %} @@ -469,15 +514,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) }} @@ -491,7 +537,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 }} @@ -511,17 +557,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; its last run 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 run #} + +
    +

    Spending cap for the whole run

    +

    {% if job_cap %}{{ job_cap.spent_usd|cap }} spent so far. {% endif %}The new cap applies from the job's next run.

    + + +
    +
    +
    +{% 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 87f4bacde..3b6d158cb 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 run 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 c267df47d..38f585e7d 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -404,6 +404,7 @@ "n_running_trials", "n_scored_parts", "n_tasks", + "n_tasks_run", "n_total_trials", "parts_by", "preparing", @@ -411,6 +412,7 @@ "raw_solve_rate", "reasoning_effort", "reports_regressions", + "reruns", "retries", "runner", "runner_commit", @@ -419,6 +421,7 @@ "score_by_group", "scored_only", "standard", + "start_with", "started_at", "state", "task_set", @@ -478,6 +481,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 000000000..95c7fb75e --- /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 7865a41b9..e26559ba8 100644 --- a/app/tests/test_cli_contract.py +++ b/app/tests/test_cli_contract.py @@ -237,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, diff --git a/app/tests/test_execution_again.py b/app/tests/test_execution_again.py new file mode 100644 index 000000000..bfc86f85f --- /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 b81e198c3..d05d94f67 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_parse.py b/app/tests/test_parse.py index b26018b0d..f193aab12 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_standard_boat_units.py b/app/tests/test_standard_boat_units.py index 96f0707ce..615320c16 100644 --- a/app/tests/test_standard_boat_units.py +++ b/app/tests/test_standard_boat_units.py @@ -123,14 +123,19 @@ def test_credentials_include_only_selected_provider_and_declared_licences(self): self.assertEqual(got["OPENAI_API_KEY"], "fake-model-key") self.assertEqual(secrets.unpack(got[secrets.HANDED]), {"HF_TOKEN": b"fake-hf-token"}) - def test_cli_forwards_models_options_and_divides_cap(self): + def test_cli_forwards_models_options_and_divides_cap_and_refuses_a_start(self): + command = ["run", "osworld1", "original", "--backend", "boat", "--boat-size", "default", + "--model", "gpt-4o", "--provider", "openrouter", "--dataset", "test_small", + "--limit", "2", "--max-usd", "1", "--max-calls", "5", "--served-by", "openai", + "--price", "openai/gpt-4o=1,2", "--timeout", "agent=90"] with patch.object(boat_units, "run", return_value=("/job", False)) as launch, \ patch.object(cli, "boat_credentials", return_value={"OPENAI_API_KEY": "fake-secret"}), \ - patch("sys.stdout", new_callable=io.StringIO): - result = cli.main(["run", "osworld1", "original", "--backend", "boat", "--boat-size", "default", - "--model", "gpt-4o", "--provider", "openrouter", "--dataset", "test_small", - "--limit", "2", "--max-usd", "1", "--max-calls", "5", "--served-by", "openai", - "--price", "openai/gpt-4o=1,2", "--timeout", "agent=90"]) + patch("sys.stdout", new_callable=io.StringIO) as out: + # each task runs whole in its VM: a start on some of them is refused, nothing launched + self.assertEqual(cli.main(command + ["--start-with", "1"]), 2) + self.assertIn("--start-with", out.getvalue()) + launch.assert_not_called() + result = cli.main(command) self.assertEqual(result, 0) words = launch.call_args.args[1] for flag, value in (("--model", "gpt-4o"), ("--max-usd", "0.5"), ("--max-calls", "5"), diff --git a/app/tests/test_standard_exchanges.py b/app/tests/test_standard_exchanges.py index d65a09383..4aa112fe8 100644 --- a/app/tests/test_standard_exchanges.py +++ b/app/tests/test_standard_exchanges.py @@ -29,8 +29,9 @@ from nullius.standard.calls import exchanges, relay from nullius.standard.contract import definitions from nullius.standard.pages import recipe +from nullius.standard.protocols import acp from nullius.standard.requirements import install -from nullius.standard.runner import pace as pacing, run +from nullius.standard.runner import pace as pacing, rerun, run ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -900,7 +901,12 @@ def show(self, job_id, trial, *more): return code, out.buffer.getvalue(), err.getvalue() def test_off_and_a_bad_value_and_the_command_line(self): - job_dir = self.go(exchanges="off", name="off") + job_dir = self.go(exchanges="off", exchanges_max_mb=1, name="off") + # a task that calls the model, run again in the job, keeps the job's choice + b = dict(definitions.get("benchmark", "fakebench", ROOT), datasets=[{"id": "responding", "units": 3}]) + with mock.patch.object(rerun, "resolve", return_value=(b, definitions.get("agent", "fake", ROOT))): + got = rerun.rerun(job_dir, ["model"], env=self.env, say=lambda s: None, root=ROOT) + self.assertEqual([x["unit"] for x in got["replaced"]], ["model"]) for root, dirs, _ in os.walk(job_dir): self.assertNotIn(exchanges.FOLDER, dirs, root) with open(os.path.join(job_dir, "config.json")) as f: @@ -919,6 +925,21 @@ def test_off_and_a_bad_value_and_the_command_line(self): standard_cli.main(["run", "fakebench", "fake", "--model", "m-1", "--from-run", "--exchanges", "text", "--exchanges-max-mb", "64"]) self.assertEqual((given["exchanges"], given["exchanges_max_mb"]), ("text", 64)) + def test_a_task_run_again_keeps_the_jobs_bound(self): + job_dir = self.go(exchanges_max_mb=1, name="bound") + b = dict(definitions.get("benchmark", "fakebench", ROOT), datasets=[{"id": "responding", "units": 3}]) + # the task run again asks one call past the bound of 1 MB, and its model answers short + real, big = acp.Client.prompt, "model " + "x" * 1_100_000 + short = lambda h: (h.rfile.read(int(h.headers["Content-Length"])), h.reply(200, json.dumps(CHAT).encode(), "application/json")) + with mock.patch.object(rerun, "resolve", return_value=(b, definitions.get("agent", "fake", ROOT))), \ + mock.patch.object(acp.Client, "prompt", lambda c, sid, given, timeout=600, **kw: real(c, sid, big, timeout=timeout, **kw)), \ + mock.patch.object(Upstream, "do_POST", short): + got = rerun.rerun(job_dir, ["model"], env=self.env, say=lambda s: None, root=ROOT) + self.assertEqual([x["now"] for x in got["replaced"]], [{"reward": 0.0}]) # the turn ended, with no error + name = got["replaced"][0]["trial"] + (line,) = exchanges.lines(os.path.join(job_dir, name, ".work", "relay", exchanges.FOLDER), name.rsplit("__", 1)[1]) + self.assertIn("bound of 1 MB", line.get("cut") or "") + class Recipe(unittest.TestCase): def test_a_recipe_takes_them_and_says_them_only_when_not_the_default(self): diff --git a/app/tests/test_standard_rerun.py b/app/tests/test_standard_rerun.py new file mode 100644 index 000000000..8208df646 --- /dev/null +++ b/app/tests/test_standard_rerun.py @@ -0,0 +1,897 @@ +"""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_and_the_job_result_replace_links_without_writing_their_target(self): + path = self.job() + outside = self.tmp / "evidence.bin" + outside.write_bytes(b"\x00original evidence\xff") + copy = self.tmp / "result-copy.json" # a hard-linked copy of the job's result keeps what it held + os.link(path / "result.json", copy) + kept_copy = copy.read_bytes() + (path / "result.json").chmod(0o600) # and the result keeps its permissions, whatever the umask + self.addCleanup(os.umask, os.umask(0o022)) + 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"]) + self.assertEqual(copy.read_bytes(), kept_copy) + self.assertEqual((path / "result.json").stat().st_mode & 0o777, 0o600) + + 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 recorded reasoning of the wrong shape"): + path = Path(job_dir, "config.json") + kept = path.read_bytes() + cfg = json.loads(kept) + path.write_text(json.dumps(dict(cfg, standard=dict(cfg["standard"], reasoning="high")))) + try: + whole = digest(job_dir) + with self.assertRaises(run.Refused) as e: + self.again(job_dir, ["model"]) + self.assertIn("job records its reasoning as 'high', not a level for each model", str(e.exception)) + self.assertEqual(digest(job_dir), whole) + finally: + path.write_bytes(kept) + 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 run of the job has what the runs before it left, a new cap holds from + then on, and a run 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_run_has_what_the_runs_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 run", 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 run 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_run_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 runs' 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_run_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 later_run(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_runs_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.later_run(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 run 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.later_run(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_run_inherits_cumulative_replies_once(self): + path = self.job(1.61, 1, 100) + row = {"input": 0.0, "output": 10000.0} + self.later_run(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.later_run(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_run_replies_are_combined_before_inheritance(self): + path = self.job(1.61, 1, 100) + self.later_run(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 n, amount, seen in ((2, 0.51, [3, 102]), (3, 0.34, [4, 103])): + _, admitted = self.later_run(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-{n}/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 run 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_run_is_queued_under_the_jobs_agent(self): + # the board names a queued trial by the job's agent, as the first run 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_served_by.py b/app/tests/test_standard_served_by.py index 9125884e9..30841aac7 100644 --- a/app/tests/test_standard_served_by.py +++ b/app/tests/test_standard_served_by.py @@ -32,7 +32,7 @@ from nullius.standard.calls import relay from nullius.standard.contract import definitions from nullius.standard.requirements import install -from nullius.standard.runner import job, merge, run +from nullius.standard.runner import job, merge, rerun, run ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -523,6 +523,24 @@ def test_a_pinned_run_records_its_pin_and_says_who_served_each_unit(self): with open(os.path.join(job_dir, "result.json")) as f: self.assertEqual(json.load(f)["served"], {"calls": {"Prov A": n}, "unnamed": 0, "held": {"m-1": True}}) + def test_a_task_run_again_in_its_job_keeps_the_jobs_pin_and_reasoning(self): + b = dict(self.b, datasets=[{"id": "responding", "units": 3}]) + with mock.patch.dict(run.providers.PRESETS, {"openrouter": dict(run.providers.PRESETS["openrouter"], base=self.base)}): + job_dir = run.run(b, self.a, model="m-1", provider="openrouter", env={"OPENROUTER_API_KEY": "or-test"}, unsandboxed=True, + jobs_root=os.path.join(self.tmp, "jobs"), say=lambda s: None, dataset="responding", + served_by={"m-1": ["prov-a"]}, reasoning={"m-1": "high"}) + with open(os.path.join(job_dir, "config.json")) as f: + self.assertEqual(json.load(f)["standard"]["reasoning"], {"m-1": "high"}) + first, Upstream.seen = Upstream.seen, [] + with mock.patch.object(rerun, "resolve", return_value=(b, self.a)): + got = rerun.rerun(job_dir, ["model"], env={"OPENROUTER_API_KEY": "or-test"}, say=lambda s: None, root=ROOT) + self.assertEqual([x["unit"] for x in got["replaced"]], ["model"]) + + def sent(seen): + return [(c.get("provider"), c.get("reasoning_effort")) for c in (json.loads(raw) for _, _, raw in seen)] + self.assertEqual(sent(first), [({"order": ["prov-a"], "allow_fallbacks": False}, "high")]) # a base that is not OpenRouter's: the field of its API + self.assertEqual(sent(Upstream.seen), sent(first)) + def test_a_run_without_the_option_sends_records_and_ends_as_before(self): """Every request as before, the record's earlier fields as they were read, and the same verdicts, even when the provider answers a 200 that holds an error: the relay reads that error beside the reply and the diff --git a/app/tests/test_standard_shard.py b/app/tests/test_standard_shard.py index 02454668c..5b10863bb 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"}} @@ -212,6 +212,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_runs_and_accepts_older_shards(self): + # Each shard spent 1 initially and 7 in a later run. + 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 diff --git a/app/tests/test_standard_start_with.py b/app/tests/test_standard_start_with.py new file mode 100644 index 000000000..986a2214f --- /dev/null +++ b/app/tests/test_standard_start_with.py @@ -0,0 +1,242 @@ +"""A run planned on a whole and started on some 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, their names and their identities alone +VOLATILE = {"started_at", "finished_at", "at", "found_at", "id", "job_name", "job", "date", "seconds", "ts", "uuid"} + + +def steady(doc): + """A record with what a clock, a job's name or its identity 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 StartWithTest(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") + start = ["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"], start) + 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(start))) + 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("started on some of its plan: 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): + started = self.plan(name="started", start_with={"count": 2}) + got = self.again(started, ["t3", "t2"], reason="two more") + self.assertEqual([x["unit"] for x in got["begun"]], ["t3", "t2"]) + self.assertEqual(parse.parse_job(started).n_tasks_run, 4) + got = self.again(started, [], every_unfinished=True) + self.assertEqual([x["unit"] for x in got["begun"]], ["t4", "t5"]) + whole = self.plan(name="whole") + j, w = parse.parse_job(started), 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(started, "result.json")["stats"]["n_cancelled_trials"], 0) + # the records, but for the start's and later runs' own (start_with, the re-runs and their summary, each later trial's mark) + cfg = self.read(started, "config.json") + del cfg["standard"]["start_with"] + self.assertEqual(steady(cfg), steady(self.read(whole, "config.json"))) + res = self.read(started, "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(started, 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(started)), 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_start_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") + # a set of several datasets: its list of the run's dataset; the rest of a job started on some of its plan, by its name + both = sets.create(b, "both", parts={"all": ["t4", "t2"], "other": ["t5"]}) + got = std_cli.start_with(b, "set:both", "all") + self.assertEqual((got["dataset"], got["task_set"]["units"], sorted(got["task_set"]["parts"])), ("all", ["t4", "t2"], ["all", "other"])) + for dataset, said in ((None, "set:both: the task set both mixes the datasets all, other; give --dataset"), + ("more", "set:both: the task set both mixes the datasets all, other, not more")): + with self.subTest(dataset=dataset), self.assertRaises(sets.Refused) as e: + std_cli.start_with(b, "set:both", dataset) + self.assertIn(said, str(e.exception)) + job_dir = self.plan(name="mixed", start_with={"count": 1}) + got = self.again(job_dir, [], task_set=std_cli.set_units(b["key"], "both", "all", "--set ")) + self.assertEqual([x["unit"] for x in got["begun"]], ["t2", "t4"]) + # a job that ran that set's list of one dataset, begun on its first task: the rest of that list next + job_dir = self.plan(name="mixed-set", task_set=sets.record(both, None, "all"), start_with={"count": 1}) + self.assertEqual(self.read(job_dir, "config.json")["standard"]["start_with"]["units"], ["t2"]) + got = self.again(job_dir, [], every_unfinished=True) + self.assertEqual([x["unit"] for x in got["begun"]], ["t4"]) + # 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_units_listing.py b/app/tests/test_standard_units_listing.py index f7f5d6d9d..33c9b6747 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -108,6 +108,14 @@ def ids(self, got): 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)])): diff --git a/app/tests/test_start_with_recipe.py b/app/tests/test_start_with_recipe.py new file mode 100644 index 000000000..8cf62456d --- /dev/null +++ b/app/tests/test_start_with_recipe.py @@ -0,0 +1,204 @@ +"""A recipe's plan started on some of it (``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_some_tasks_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"], "") + # of a set of several datasets, its list of the dataset begun with it + sets.create(self.b, "both", parts={"all": ["slow"], "more": ["good"]}) + out = self.compile(start_with={"all": "set:both"}) + self.assertEqual(out["errors"], []) + self.assertIn("--dataset all --start-with set:both -j 1", out["shards"][0]["command"]) + self.assertTrue(next(r[2] for r in out["review"] if r[1] == "Scope").startswith("1 first, 3 later")) + # 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 started on some 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, licences=None): + 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_task_set_recipe.py b/app/tests/test_task_set_recipe.py index 373ba5c62..a5395c1ac 100644 --- a/app/tests/test_task_set_recipe.py +++ b/app/tests/test_task_set_recipe.py @@ -61,10 +61,10 @@ def test_a_set_compiles_to_set_name_and_review_names_its_label_and_its_count(sel 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"all {n} tasks")) + 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("first 2 tasks of each shard")) + 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"]) diff --git a/app/ui_tests/test_attempt_routes.py b/app/ui_tests/test_attempt_routes.py index d8143cd45..24a8fd359 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_capped_job.py b/app/ui_tests/test_capped_job.py index 460b3d66d..bf286a887 100644 --- a/app/ui_tests/test_capped_job.py +++ b/app/ui_tests/test_capped_job.py @@ -84,8 +84,9 @@ def text(self, html, pattern): def test_a_run_the_cap_stopped_says_so_with_what_was_spent_and_the_units_left_out(self): html = self.page("stopped") self.assertEqual(self.text(html, r'
    .*?
    '), - "Stopped at its spending cap of $0.50, with $0.41 spent: 1 cut off, 4 not run.") # a neutral notice: nothing failed + "Stopped at its spending cap of $0.50, with $0.44 spent: 1 cut off, 4 not run.") # a neutral notice: nothing failed self.assertEqual(self.text(html, r'
    '), "Spending cap $0.50") + self.assertEqual(self.text(html, r'
    .*?
    ').split(" · ")[0], "$0.44 spent") # the same spend, the booked calls with it self.assertIn("$0.03", unescape(html)) # what stays booked for calls whose cost was never reported self.assertEqual(self.text(html, r'
    '), "t-6 t-7 t-8 t-9") self.assertIn("4 not run", html) diff --git a/app/ui_tests/test_live_board.py b/app/ui_tests/test_live_board.py index e50a1e40a..218fea846 100644 --- a/app/ui_tests/test_live_board.py +++ b/app/ui_tests/test_live_board.py @@ -72,6 +72,22 @@ def job_with_feed(root, job_id, *, feed=True, ended=False): return parse.parse_job(str(job_dir)) +class LiveBoardLayout(unittest.TestCase): + def test_seven_counts_use_one_row_only_on_wide_screens(self): + css = (APP_DIR / "static/runs/live-board.css").read_text() + selector = ".lb-stats:has(> .lb-stat:nth-child(7))" + wide = re.search(r"@media \(min-width: (\d+)px\)\s*\{\s*" + re.escape(selector) + + r"\s*\{([^}]+)\}\s*\}", css) + self.assertIsNotNone(wide) + self.assertGreater(int(wide[1]), 1000) + self.assertLessEqual(int(wide[1]), 1280) + self.assertIn("grid-template-columns: repeat(5, minmax(0, 1fr)) repeat(2, minmax(0, 1.2fr))", wide[2]) + self.assertNotIn(selector, css[:wide.start()] + css[wide.end():]) + for width, columns in ((1000, 3), (640, 6)): + self.assertRegex(css, rf"@media \(max-width: {width}px\)\s*\{{\s*\.lb-stats\s*\{{\s*" + rf"grid-template-columns: repeat\({columns}, minmax\(0, 1fr\)\)") + + class LiveBoard(unittest.TestCase): @classmethod def setUpClass(cls): diff --git a/app/ui_tests/test_rerun_page.py b/app/ui_tests/test_rerun_page.py new file mode 100644 index 000000000..490276a94 --- /dev/null +++ b/app/ui_tests/test_rerun_page.py @@ -0,0 +1,516 @@ +"""Tasks of an ended job run again from its page: a tick on each row, the rows +shown chosen at once, Run selected again with a reason and a cap; started where +the job ran (this machine or its host), refused with one line where the server +cannot; the earlier result while a task runs again; afterwards the list of +re-runs, the column of tries and the try's mark.""" +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import tempfile +import unittest +from contextlib import ExitStack +from html import unescape +from pathlib import Path +from unittest.mock import patch + +from nullius import execution, hosts, workspace +from nullius.harbor import feed +from nullius.standard.runner import job +from ui_tests.test_capped_job import AGENT, BENCH +from .test_routes import web + +UNITS = ["t-0", "t-1", "t-2"] + + +def trial_name(k): + return f"{UNITS[k]}__u{k:04d}" + + +def standard_job(d: Path, name: str, rewards=(1.0, 0.0, 1.0), **std): + """A standard job of three units, each ended with its reward; ``std`` more of its config's ``standard``.""" + d.mkdir(parents=True) + job.write_config(str(d), job=name, bench=BENCH, other=AGENT, model="m-1", provider="openai", dataset="all", units=UNITS, + concurrency=1, granted=True) + if std: + cfg = json.loads((d / "config.json").read_text()) + cfg["standard"].update(std) + (d / "config.json").write_text(json.dumps(cfg)) + results = [] + for k, u in enumerate(UNITS): + trial = d / trial_name(k) + trial.mkdir() + results.append(job.write_trial(str(trial), job=name, bench=BENCH, other=AGENT, model="m-1", 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": rewards[k]}, exception=None, calls=[], trajectory=None)) + job.write_result(str(d), name, 1_760_000_000.0, 1_760_000_060.0, results, len(UNITS)) + + +def text(html, pattern): + got = re.search(pattern, html, re.S) + assert got is not None, pattern + return re.sub(r"\s+", " ", unescape(re.sub(r"<[^>]+>", " ", got[0]))).strip() + + +class RerunPage(unittest.TestCase): + def setUp(self): + self.stack = ExitStack(); self.addCleanup(self.stack.close) + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-rerun-page-")); self.addCleanup(shutil.rmtree, self.tmp, True) + self.stack.enter_context(patch.dict(os.environ, {"RUNS_DIR": str(self.tmp / "runs"), "HOSTS": "bench", + "OPENAI_API_KEY": "sk-testkey-0123"})) + self.stack.enter_context(patch.dict(web.app.config, TESTING=True)) + self.stack.enter_context(patch.dict(execution.EXECUTIONS, clear=True)) + 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": []})) + self.asked = [] + self.stack.enter_context(patch.object(execution.Execution, "again", lambda ex, part, env=os.environ: self.asked.append((ex, part)) or ex)) + self.held = None + self.stack.enter_context(patch.object(execution.Execution, "holds", lambda ex, job_id: self.held)) + + def run_of(self, name="r1", host=None, state="done", **std): + d = self.tmp / "runs" / name + standard_job(d / "jobs" / name, name, **std) + plan = execution.Plan(name=name, script="", runner="standard", host=hosts.parse(host) if host else None, model="m-1", + key_var="OPENAI_API_KEY", url_var="", recipe={"provider": "openai"}, + parts=[{"id": "fake", "label": "Fake", "script": "true"}], jobs=[{"name": name, "agent": "fake"}]) + (d / "run.json").write_text(json.dumps({"id": f"{name}-1", "plan": plan.to_dict(), "state": state, "step": "run", + "ends": {"fake": {"rc": 0, "at": 1_760_000_060.0, "label": "Fake"}}})) + return d / "jobs" / name + + def open(self, *roots): + execution.restore() + web.shared.open_workspace(workspace.create(str(self.tmp / "ws"), [str(r) for r in roots], label="again")) + self.client = web.app.test_client() + r = self.client.get("/runs"); self.addCleanup(r.close) + with self.client.session_transaction() as s: + self.csrf = s["csrf"] + + def page(self, path): + r = self.client.get(path); self.addCleanup(r.close) + self.assertEqual(r.status_code, 200, path) + return r.get_data(as_text=True) + + def post(self, name, body, csrf=None, query=""): + r = self.client.post(f"/job/{name}/rerun{query}", json=body, headers={"X-CSRF-Token": self.csrf if csrf is None else csrf, + "Origin": "http://localhost"}) + self.addCleanup(r.close) + return r + + def test_each_row_has_a_tick_and_the_bar_the_rows_shown_the_count_and_the_button(self): + d = self.run_of() + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertEqual(re.findall(r'Select the rows shown', html) + self.assertIn('0 chosen', html) + self.assertIn('', html) + # the filter the bar's button reads: each row's outcome, the tick inside it + self.assertRegex(html, r']*data-trial="t-1__u0001"[^>]*>\s*') + self.assertEqual(ask, "Run 0 tasks again On this machine, in this job: each result replaces the task's, and the earlier tries stay. " + "Reason (optional) Cancel Run 0 tasks again") + self.assertIn('data-post="/job/r1/rerun"', html) + self.assertNotIn('id="rerun-why"', html) + + def test_run_selected_again_starts_it_where_the_job_ran_with_its_reason(self): + d = self.run_of() + self.open(d.parent) + r = self.post("r1", {"trials": [trial_name(1), trial_name(1), trial_name(2)], "reason": " the provider\nfailed ", "max_usd": "0.5"}) + self.assertEqual(r.status_code, 200, r.get_data(as_text=True)) + ((ex, part),) = self.asked + self.assertEqual((ex.plan.name, part["id"], part["again"], part["trials"]), ("r1", "again-1", "r1", [trial_name(1), trial_name(2)])) + self.assertIn(f"rerun \"${{NULLIUS_JOBS:-jobs_standard}}\"/r1 --unit {trial_name(1)} --unit {trial_name(2)} " + "--reason 'the provider failed' --from-run", part["script"]) # one cap for the job: none is posted + r = self.post("r1", {"trials": [trial_name(0)], "reason": ""}) + self.assertEqual(r.status_code, 200) + self.assertNotIn("--max-usd", self.asked[-1][1]["script"]); self.assertNotIn("--reason", self.asked[-1][1]["script"]) + + def test_what_the_route_refuses_starts_nothing(self): + d = self.run_of() + self.open(d.parent) + for body, code, said in [({"trials": []}, 400, "Tick the tasks to run again."), + ({"trials": ["nope"]}, 400, "r1 holds no trial nope"), + ({"trials": [trial_name(0)], "reason": "x" * 201}, 400, "The reason is one line of at most 200 characters.")]: + r = self.post("r1", body) + self.assertEqual((r.status_code, r.json["error"]), (code, said), body) + self.assertEqual(self.post("r1", {"trials": [trial_name(0)]}, csrf="wrong").status_code, 403) + with patch.dict(os.environ, {"OPENAI_API_KEY": ""}): + r = self.post("r1", {"trials": [trial_name(0)]}) + self.assertEqual(r.status_code, 400); self.assertIn("OPENAI_API_KEY", r.json["error"]) + self.assertEqual(self.asked, []) + + def test_a_job_on_a_host_goes_back_there_and_a_host_without_it_is_refused(self): + d = self.run_of(host="bench") + self.open(d.parent) + self.assertIn("On bench, in this job", self.page("/job/r1?view=results")) + self.held = "bench no longer holds r1: nothing was started" + r = self.post("r1", {"trials": [trial_name(1)]}) + self.assertEqual((r.status_code, r.json["error"]), (409, "bench no longer holds r1: nothing was started")) + self.assertEqual(self.asked, []) + self.held = None + self.assertEqual(self.post("r1", {"trials": [trial_name(1)]}).status_code, 200) + self.assertEqual(self.asked[0][0].plan.host.label, "bench") + + def test_each_job_the_server_cannot_run_again_shows_no_button_and_says_why(self): + here = self.run_of("r1") + gone = self.run_of("r2", host="ubuntu@10.0.0.9") # a host no longer in Settings + merged = self.run_of("r3", merged_from=[{"job": "a"}, {"job": "b"}]) + loose = self.tmp / "loose" + standard_job(loose / "cli-job", "cli-job") # started outside: no run record + ended = self.run_of("r4") + shutil.copytree(ended, self.tmp / "copy" / "r4") # its job copied: no run writes the copy + self.open(here.parent, gone.parent, merged.parent, loose, ended.parent) + copy = workspace.create(str(self.tmp / "ws"), [str(self.tmp / "copy")], label="copy").name + execution.EXECUTIONS["r1-1"].state = "running" + self.assertIn("Run selected again", self.page("/job/r4?view=results")) + for name, said, ws in [("r1", "Still running: more tasks can be started once it has ended.", ""), # "": the open one + ("r2", "Its host, ubuntu@10.0.0.9, is no longer in Settings.", ""), + ("r3", "Merged from its shards' jobs: run a task again in its shard's job.", ""), + ("cli-job", "Not started from here: no record of where it ran.", ""), + ("r4", "Not started from here: no record of where it ran.", copy)]: + html = self.page(f"/job/{name}?view=results&workspace={ws}") + self.assertNotIn('class="pick-row"', html, name); self.assertNotIn("Run selected again", html, name) + self.assertEqual(text(html, r'.*?'), "3") + row = re.search(rf']*data-trial="{name}".*?', html, re.S)[0] + self.assertIn('running', html) + self.assertNotIn("again-now", self.page("/job/r1?view=results").split(f'data-trial="{trial_name(0)}"')[1].split("")[0]) + + def test_the_waiting_page_refreshes_when_the_rerun_ends_before_its_first_poll(self): + node = shutil.which("node") + if not node: + self.skipTest("node not available") + d = self.run_of() + writer = feed.Writer(str(d / "events.jsonl"), "r1") + writer.emit("job.start", n_total=3) + writer.emit("job.end") + self.open(d.parent) + ex = execution.EXECUTIONS["r1-1"] + ex.plan.parts.append({"id": "again-1", "again": "r1", "trials": [trial_name(1)], "script": "true"}) + ex.part, ex.state = 1, "preparing" + html = self.page("/job/r1?view=results") + script = next(s for s in re.findall(r"", html, re.S) if "setInterval(tick, 2000)" in s) + program = """ +const [script, replies] = process.argv.slice(1).map(JSON.parse); +let tick, destination = null; +const location = {href: 'http://localhost/job/r1?view=results', assign: u => { destination = String(u); }}; +const fetch = async url => ({ok: true, json: async () => replies[url]}); +new Function('document', 'nulliusFetch', 'setInterval', 'URL', 'location', script)( + {hidden: false}, fetch, fn => { tick = fn; }, URL, location); +tick().then(() => process.stdout.write(JSON.stringify(destination))); +""" + for state in ("preparing", "running", "done", "failed", "stopped"): + with self.subTest(state=state): + ex.state = state + replies = {url: json.loads(self.page(url)) for url in ("/job/r1/live", "/run/r1-1")} + self.assertEqual(replies["/job/r1/live"]["state"], "finished") + result = subprocess.run([node, "-e", program, json.dumps(script), json.dumps(replies)], + capture_output=True, text=True, check=True, timeout=10) + self.assertEqual(json.loads(result.stdout), + "http://localhost/job/r1" if state in execution.ENDED else None) + + def rerun_record(self, d): + """The job as a re-run of t-1 leaves it: its earlier try kept, the trial marked, the job's list.""" + name = trial_name(1) + (d / "retried").mkdir() + shutil.copytree(d / name, d / "retried" / f"{name}.try-1") + res = json.loads((d / name / "result.json").read_text()) + res["verifier_result"] = {"rewards": {"reward": 1.0}} + res["standard"] = dict(res["standard"], retries=1, rerun={"by": "hand", "at": "2026-11-18T15:40:12+00:00", + "reason": "the provider failed", "replaced": {"reward": 0.0}}) + (d / name / "result.json").write_text(json.dumps(res)) + top = json.loads((d / "result.json").read_text()) + top["reruns"] = [{"at": "2026-11-18T15:40:12+00:00", "finished_at": "2026-11-18T15:42:00+00:00", "reason": "the provider failed", + "trials": [name], "replaced": [{"trial": name, "unit": "t-1", "try": 1, "was": {"reward": 0.0}, "now": {"reward": 1.0}}], + "max_usd": 0.5, "spent_usd": 0.0012}] + (d / "result.json").write_text(json.dumps(top)) + + def test_afterwards_the_list_of_re_runs_the_column_of_tries_and_the_try_s_mark(self): + d = self.run_of() + self.rerun_record(d) + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertEqual(text(html, r'
    .*?
    '), + "Run later 1 2026-11-18 15:40Z the provider failed t-1 reward 0.0 → reward 1.0 try 1 " + "1 task · $0.0012 spent") + self.assertIn('Retries', html) + cells = re.findall(r'(.*?)', html) + self.assertEqual(cells, ['0', "1", '0']) + trial = self.page(f"/trial/r1/{trial_name(1)}") + tabs = text(trial, r'
    '), "1 not run t-4") + self.assertEqual(text(html, r''), "No result 2") + + def test_a_cap_equal_to_the_spend_the_page_shows_is_refused(self): + d = self.run_of() + noisy = 0.0 + for _ in range(8): + noisy += 0.1 # 0.7999999999999999, as a ledger adds its calls + self.capped(d, {"max_usd": 0.5, "spent_usd": noisy, "stopped": True, "cut_off": [], "not_run": [], "spent_total_usd": noisy}) + self.open(d.parent) + self.assertEqual(text(self.page("/job/r1?view=results"), r'
    .*?
    '), "$0.80 spent · Change") + for typed in ("0.8", "0.80000000001"): + with self.subTest(typed=typed): + r = self.cap("r1", {"max_usd": typed}) + self.assertEqual((r.status_code, r.json["error"]), (400, "The cap must be above what this run has spent, 0.80 USD.")) + self.assertEqual(self.cap("r1", {"max_usd": "0.81"}).status_code, 200) + + def test_a_job_with_no_cap_has_none_until_one_is_set(self): + d = self.run_of() + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertEqual(text(html, r'
    '), "Spending cap none") + self.assertEqual(text(html, r'
    .*?
    '), "Set") + self.assertNotIn('id="rerun-budget"', html) + self.assertEqual(self.post("r1", {"trials": [trial_name(0)]}).status_code, 200) + self.assertNotIn("--max-usd", self.asked[-1][1]["script"]) + self.assertEqual(self.cap("r1", {"max_usd": "2"}).status_code, 200) + self.assertIn("Budget for the whole run: $2.00, $2.00 left.", self.page("/job/r1?view=results")) + + def test_a_job_never_run_again_shows_none_of_it(self): + d = self.run_of() + self.open(d.parent) + html = self.page("/job/r1?view=results") + for absent in ('id="reruns"', 'class="num">Retries<', "run-retries", "again-now", "running again", "no_result", "data-first"): + self.assertNotIn(absent, html) + trial = self.page(f"/trial/r1/{trial_name(1)}") + self.assertNotIn("try-tabs", trial); self.assertNotIn("try-why", trial) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_start_with_page.py b/app/ui_tests/test_start_with_page.py new file mode 100644 index 000000000..0836d3565 --- /dev/null +++ b/app/ui_tests/test_start_with_page.py @@ -0,0 +1,548 @@ +"""A job planned on a whole and started on some of it, on its page: how many of the plan have run, the tasks not +run as rows with no attempt under an outcome of their own, the rest and a set's tasks not run each one click from +the question Run selected asks, and the runs list's count over the trials run.""" +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +from nullius.harbor import feed +from nullius.standard.runner import sets +from ui_tests.test_capped_job import BENCH +from ui_tests import test_rerun_page as rerun_page, test_task_set_pages as task_set_pages +from ui_tests.test_rerun_page import text, trial_name + +PLAN = [f"t-{k}" for k in range(6)] + + +class StartWithPage(unittest.TestCase): + run_of, open, page, post, interrupted = (rerun_page.RerunPage.__dict__[k] for k in ("run_of", "open", "page", "post", "interrupted")) + + def setUp(self): + rerun_page.RerunPage.setUp(self) + self.stack.enter_context(patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(self.tmp / "catalogue")})) + + def started_on_some(self, d: Path): + """The job as ``run --start-with 3`` leaves it: six tasks planned, as its feed and its config say, the first + three run.""" + writer = feed.Writer(str(d / "events.jsonl"), "r1") + writer.emit("job.start", n_total=6, tasks=PLAN) + for k in range(6): + writer.emit("trial.queued", f"t-{k}__u{k:04d}", agent="fake", position=k) + writer.emit("job.end") + cfg = json.loads((d / "config.json").read_text()) + cfg["standard"]["start_with"] = {"count": 3, "units": PLAN[:3]} + cfg["datasets"][0]["n_tasks"] = 6 + (d / "config.json").write_text(json.dumps(cfg)) + top = json.loads((d / "result.json").read_text()) + top["n_total_trials"] = 6 + (d / "result.json").write_text(json.dumps(top)) + + def test_the_page_says_how_many_of_the_plan_ran_and_lists_the_rest_with_no_attempt(self): + d = self.run_of() + self.started_on_some(d) + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertEqual(text(html, r''), "3 of 6 tasks run") + self.assertEqual(text(html, r'Trials.*?
    '), "Trials 3 of 6 tasks run") # the head's Trials cell + self.assertEqual(text(html, r'
    tasks run
    '), "tasks run 3 of 6") + self.assertIn('id="tasks-run" class="warn"', html) + self.assertEqual(text(html, r'
    .*?
    '), "3 Trials of 6 planned") + self.assertEqual(text(html, r'
    '), "Not run 3") + self.assertIn('data-o="not_run" href="/job/r1?outcome=not_run"', html) # a link to the job's record, as the outcome links are + self.assertNotIn('data-o="no_result"', html) + rest = [f"t-{k}__u{k:04d}" for k in (3, 4, 5)] + rows = {n: text(html, rf']*data-trial="{n}".*?') for n in rest} + self.assertEqual(rows, {n: f"{n[:3]} — Not run" for n in rest}) + self.assertEqual(re.findall(r'.*?'), "6") + self.assertRegex(html, r'') + self.assertNotIn('id="plan-sets"', html) # no set names one + # the runs list: solved over the trials run, and how many of the plan + runs = self.page("/runs") + self.assertIn('title="Started on some of its plan: the rates and the mean are over the tasks run">3 of 6 tasks run', runs) + self.assertIn("3 on disk of 6 planned · started on some of its plan, 3 of 6 tasks run", self.page("/runs?view=all")) + + def test_a_set_s_tasks_not_run_and_the_rest_go_to_the_question_as_ticks(self): + d = self.run_of() + self.started_on_some(d) + both = dict(BENCH, datasets=[{"id": "all"}, {"id": "other"}], label="Fake bench") + sets.create(both, "late", dataset="all", units=["t-4", "t-0"]) + sets.create(both, "done", dataset="all", units=["t-1"]) # every task of it has run + sets.create(both, "elsewhere", dataset="other", units=["t-5"]) # another dataset + self.open(d.parent) + html = self.page("/job/r1?view=results") + menu = re.search(r'
    .*?
    ', html, re.S)[0] + self.assertEqual(re.findall(r'data-pick="([^"]*)">([^<]*)(\d+)', menu), [("t-4__u0004", "late", "1")]) + self.assertNotIn("revision", menu) + self.assertEqual(text(html, r'.*?'), "Run a set") + # what a set's or the rest's click ticks is posted as Run selected posts it: the path a re-run takes + r = self.post("r1", {"trials": ["t-4__u0004"]}) + self.assertEqual(r.status_code, 200, r.get_data(as_text=True)) + self.assertIn("--unit t-4__u0004 --from-run", self.asked[-1][1]["script"]) + r = self.post("r1", {"trials": ["t-3__u0003", "t-4__u0004", "t-5__u0005"]}) + self.assertEqual(r.status_code, 200, r.get_data(as_text=True)) + self.assertIn("--unit t-3__u0003 --unit t-4__u0004 --unit t-5__u0005 --from-run", self.asked[-1][1]["script"]) + + def test_on_a_host_the_later_runs_go_back_there(self): + d = self.run_of(host="bench") + self.started_on_some(d) + self.open(d.parent) + self.assertIn('data-first="On bench, in this job:', self.page("/job/r1?view=results")) + r = self.post("r1", {"trials": ["t-5__u0005"]}) + self.assertEqual(r.status_code, 200, r.get_data(as_text=True)) + ((ex, part),) = self.asked + self.assertEqual((ex.plan.host.label, part["trials"]), ("bench", ["t-5__u0005"])) + + def test_one_unrun_row_selects_every_planned_attempt_by_tick_set_or_rest(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the selection controls") + d = self.run_of(repeat=2) + self.started_on_some(d) + shutil.rmtree(d / trial_name(2)) + for k in range(2): + for attempt in (1, 2): + dest = d / f"{trial_name(k)}r{attempt}" + shutil.copytree(d / trial_name(k), dest) + result = json.loads((dest / "result.json").read_text()) + result["trial_name"] = dest.name + (dest / "result.json").write_text(json.dumps(result)) + shutil.rmtree(d / trial_name(k)) + cfg = json.loads((d / "config.json").read_text()) + cfg["standard"]["start_with"] = {"count": 2, "units": PLAN[:2]} + (d / "config.json").write_text(json.dumps(cfg)) + top = json.loads((d / "result.json").read_text()) + top["n_total_trials"] = 12 + (d / "result.json").write_text(json.dumps(top)) + (d / "events.jsonl").unlink() + writer = feed.Writer(str(d / "events.jsonl"), "r1") + writer.emit("job.start", n_total=12, tasks=PLAN) + for k in range(6): + for attempt in (1, 2): + writer.emit("trial.queued", f"t-{k}__u{k:04d}r{attempt}", agent="fake", position=k) + writer.emit("job.end") + sets.create(dict(BENCH, datasets=[{"id": "all"}]), "late", dataset="all", units=["t-4", "t-0"]) + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertEqual(text(html, r''), "2 of 6 tasks run") + rows = re.findall(r'', html, re.S) + self.assertEqual(len(rows), 4) + self.assertEqual([text(row, r".*") for row in rows], [f"t-{k} — Not run" for k in range(2, 6)]) + ticks = [dict(value=re.search(r'value="([^"]+)"', row)[1], + trials=re.search(r'data-trials="([^"]+)"', row)[1]) for row in rows] + picks = re.findall(r'data-pick="([^"]+)"', html) + board = Path(__file__).resolve().parents[1] / "static/runs/board.js" + program = r""" +const [file, values, picks] = process.argv.slice(1).map(JSON.parse), elements = new Map(); +function element(id) { + if (!elements.has(id)) elements.set(id, {dataset: {}, listeners: {}, textContent: '', + addEventListener(k, fn) { this.listeners[k] = fn; }, click() { this.listeners.click(); }, + replaceChildren() {}, showModal() {}, closest() { return null; }}); + return elements.get(id); +} +const ticks = values.map(x => Object.assign(element(x.value), {value: x.value, + dataset: {first: '', trials: x.trials}, getAttribute() { return 'Choose ' + x.value; }})); +const buttons = picks.map(pick => Object.assign(element('button:' + pick), {dataset: {pick}})), posted = []; +element('form').elements = {reason: {value: ''}, max_usd: {value: ''}}; +const source = require('node:fs').readFileSync(file, 'utf8'); +new Function('$', '$$', 'rows', 'document', 'nulliusFetch', 'URL', 'location', + source.slice(source.indexOf(' const ticks ='), source.lastIndexOf(' apply();')))( + element, s => s === '#trial-rows .pick-row' ? ticks : buttons, [], {createElement: () => ({})}, + async (url, options) => { posted.push(JSON.parse(options.body)); return {ok: true, json: async () => ({ok: true})}; }, + URL, {href: 'http://localhost/job/r1', assign() {}}); +(async () => { + ticks[0].checked = true; element('#rerun-open').click(); + const submit = () => element('form').listeners.submit({submitter: {value: 'run'}, preventDefault() {}}); + await submit(); + for (const button of buttons) { button.click(); await submit(); } + process.stdout.write(JSON.stringify(posted)); +})(); +""" + posted = json.loads(subprocess.run([node, "-e", program, json.dumps(str(board)), json.dumps(ticks), json.dumps(picks)], + capture_output=True, text=True, check=True, timeout=10).stdout) + expected = [[f"t-{k}__u{k:04d}r{attempt}" for k in units for attempt in (1, 2)] + for units in ([2], [4], range(2, 6))] + self.assertEqual([body["trials"] for body in posted], expected) + for body in posted: + response = self.post("r1", body) + self.assertEqual(response.status_code, 200, response.get_data(as_text=True)) + self.assertEqual(self.asked[-1][1]["trials"], body["trials"]) + + def test_tasks_never_run_get_one_short_question_and_a_reason_is_asked_only_beside_a_result(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the question") + d = self.run_of() + self.started_on_some(d) + top = json.loads((d / "result.json").read_text()) + top["budget"] = {"max_usd": 4.0, "spent_usd": 0.31, "stopped": False, "cut_off": [], "not_run": []} + (d / "result.json").write_text(json.dumps(top)) + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertIn('data-where="this machine"', html) + self.assertEqual(text(html, r'

    .*?

    '), "Budget for the whole run: $4.00, $3.69 left.") + self.assertNotIn('name="max_usd" min="0" step="any" inputmode="decimal">', html.split('id="cap-ask"')[0]) # no cap asked + ticks = [dict(value=v, first=f) for v, f in re.findall(r' Object.assign(element(x.value), {value: x.value, + dataset: x.first ? {first: ''} : {}, getAttribute() { return 'Choose ' + x.value; }})); +element('form').elements = {reason: {value: 'typed before'}}; +const source = require('node:fs').readFileSync(file, 'utf8'); +new Function('$', '$$', 'rows', 'document', 'nulliusFetch', 'URL', 'location', + source.slice(source.indexOf(' const ticks ='), source.lastIndexOf(' apply();')))( + element, s => s === '#trial-rows .pick-row' ? ticks : [], [], {createElement: () => ({})}, + async () => ({ok: true, json: async () => ({ok: true})}), URL, {href: 'http://localhost/job/r1', assign() {}}); +const out = []; +for (const pick of picks) { + ticks.forEach(x => { x.checked = pick.includes(x.value); }); + element('#rerun-open').click(); + out.push({head: element('#rerun-ask-h').textContent, go: element('[data-go]').textContent, reason: !element('[data-reason]').hidden, + names: (element('[data-names]').children || []).length, where: !element('p.muted').hidden, + typed: element('form').elements.reason.value}); +} +process.stdout.write(JSON.stringify(out)); +""" + rest = [t["value"] for t in ticks if t["first"]] + picks = [rest, rest[:1], [trial_name(0), rest[0]], [trial_name(0)]] + got = json.loads(subprocess.run([node, "-e", program, json.dumps(str(board)), json.dumps(ticks), json.dumps(picks)], + capture_output=True, text=True, check=True, timeout=10).stdout) + short = dict(go="Run", reason=False, names=0, where=False, typed="") + self.assertEqual(got[0], dict(short, head="Run the 3 tasks not yet run, on this machine?")) + self.assertEqual(got[1], dict(short, head="Run the 1 task not yet run, on this machine?")) + self.assertEqual(got[2], dict(head="Run 2 tasks, 1 again", go="Run 2 tasks, 1 again", reason=True, names=2, where=True, typed="")) + self.assertEqual(got[3], dict(head="Run 1 task again", go="Run 1 task again", reason=True, names=1, where=True, typed="")) + + def test_while_a_run_of_some_of_the_plan_goes_on_the_board_queues_its_tasks_and_says_not_run_for_the_rest(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the board") + d = self.tmp / "loose" / "r1" # no run record: the feed alone says it runs + rerun_page.standard_job(d, "r1") + self.started_on_some(d) + board = Path(__file__).resolve().parents[1] / "static/runs/live-board.js" + program = ("const L=require(" + json.dumps(str(board)) + ");const s=JSON.parse(process.argv[1]);" + "process.stdout.write(JSON.stringify(L.render(s,{selected:'t-5__u0005'})));") + name = lambda k: f"t-{k}__u{k:04d}" + first = [("job.start", None, dict(n_total=6, tasks=PLAN))] + [("trial.queued", name(k), dict(position=k)) for k in range(6)] + later = [("trial.end", name(k), dict(outcome="resolved", reward=1.0)) for k in range(3)] + later += [("job.end", None, {}), ("job.start", None, dict(n_total=6, tasks=["t-4"])), ("trial.queued", name(4), dict(position=0))] + for events, this_run, said in [(first + [("trial.phase", name(0), dict(task="t-0", phase="agent_run"))], [name(k) for k in range(3)], + "Done 0 /6 Running 1 Queued 2 Not run 3"), + (first + later, [name(4)], "Done 3 /6 Running 0 Queued 1 Not run 2")]: + (d / "events.jsonl").unlink() + writer = feed.Writer(str(d / "events.jsonl"), "r1") + for event, trial, data in events: + writer.emit(event, trial, **data) + self.open(d.parent) + snap = json.loads(self.page("/job/r1/live")) + self.assertEqual((snap["state"], snap["this_run"]), ("running", this_run)) + out = json.loads(subprocess.run([node, "-e", program, json.dumps(snap)], capture_output=True, text=True, + check=True, timeout=10).stdout) + self.assertEqual(text(out["stats"], r".*").split(" Rate")[0], said) + self.assertIn('u0005: not run"', out["tiles"]) + self.assertIn('u0002: queued"' if len(this_run) == 3 else 'u0002: Resolved"', out["tiles"]) + self.assertTrue(text(out["drawer"], r"

    .*?

    ").endswith("Not run"), out["drawer"]) + initial = re.search(r'', self.page("/job/r1?view=live"), re.S)[1] + self.assertEqual(json.loads(initial)["this_run"], this_run) # the page's first draw counts as its polls do + writer.emit("job.end") # ended: the board's own count, no run of the plan + self.assertNotIn("this_run", json.loads(self.page("/job/r1/live"))) + + def test_while_a_later_run_goes_on_each_of_its_tasks_not_begun_has_a_row_marked_queued(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the board") + d = self.tmp / "loose" / "r1" + rerun_page.standard_job(d, "r1") + self.started_on_some(d) + board = Path(__file__).resolve().parents[1] / "static/runs/live-board.js" + program = ("const L=require(" + json.dumps(str(board)) + ");const s=JSON.parse(process.argv[1]);" + "process.stdout.write(JSON.stringify(L.render(s,{})));") + name = lambda k: f"t-{k}__u{k:04d}" + events = [("job.start", None, dict(n_total=6, tasks=PLAN))] + [("trial.queued", name(k), dict(position=k)) for k in range(6)] + events += [("trial.end", name(k), dict(outcome="resolved", reward=1.0)) for k in range(3)] + events += [("job.end", None, {}), ("job.start", None, dict(n_total=6, tasks=["t-3", "t-4"])), + ("trial.queued", name(3), dict(position=0)), ("trial.phase", name(3), dict(task="t-3", phase="agent_run"))] + (d / "events.jsonl").unlink() + writer = feed.Writer(str(d / "events.jsonl"), "r1") + for event, trial, data in events: + writer.emit(event, trial, **data) + self.open(d.parent) + snap = json.loads(self.page("/job/r1/live")) + out = json.loads(subprocess.run([node, "-e", program, json.dumps(snap)], capture_output=True, text=True, + check=True, timeout=10).stdout) + rows = {re.search(r'data-trial="([^"]+)"', row)[1]: text(row, r".*") + for row in re.findall(r'') + self.assertRegex(tabs, r"^Try 1 first run, in a later run of the job \S+ Try 2 run again by hand"); self.assertNotIn("Try 1 run again", tabs) + self.assertRegex(trial, r'title="Try 1: [^"]*, first run, in a later run of the job: the rest of the plan"') + self.assertEqual(text(trial, r'

    '), "Run again by hand: the provider failed") + earlier = self.page(f"/trial/r1/{name}.try-1") + self.assertEqual(text(earlier, r'

    '), "First run, in a later run of the job: the rest of the plan") + + def test_first_run_label_strips_only_the_archive_suffix(self): + name = "case.try-1__u0000" + job = SimpleNamespace(reruns=[{"at": "later", "begun": [{"trial": name}]}]) + mark = rerun_page.web.app.jinja_env.filters["try_mark"] + for suffix in ("", ".try-1", ".try-12", ".try-note", ".try-1.more"): + with self.subTest(suffix=suffix): + trial = SimpleNamespace(trial_name=name + suffix, rerun={"at": "later"}) + expected = "run again by hand" if suffix in (".try-note", ".try-1.more") else "first run, in a later run of the job" + self.assertEqual(mark(trial, job), expected) + self.assertEqual(mark(SimpleNamespace(trial_name=name, rerun={"at": "again"}), job), "run again by hand") + + def test_a_later_run_contains_only_the_selected_attempt(self): + from nullius.runs import live, parse + from nullius.standard.runner import rerun, run + from tests import test_standard_rerun as fixtures + + fixture = fixtures.RerunRecords() + fixture.setUp() + self.addCleanup(fixture.doCleanups) + path = run.run(fixture.bench, fixture.other, model="", provider="custom", + jobs_root=str(fixture.tmp), name="selected-attempt", concurrency=1, + units_file=dict(fixtures.UNITS, units=["good", "wrong"]), + start_with={"count": 1}, repeat=2, env={}, say=lambda _: None) + selected = "wrong__u0001r1" + snapshots = [] + phase = run.Run.phase + + def observe(runner, name, unit, stage, timeout=None): + phase(runner, name, unit, stage, timeout) + if name == selected: + job, snap = parse.parse_job(path), live.snapshot(path) + snapshots.append(rerun_page.web.runs._with_this_run(job, snap)) + record = SimpleNamespace(again_of=lambda _: {"trials": [selected]}) + with patch.object(rerun_page.web.runs.shared, "run_for", return_value=record): + self.assertEqual(rerun_page.web.runs._with_this_run(job, snap)["this_run"], [selected]) + + with patch.object(run.Run, "phase", observe): + result = rerun.rerun(path, [selected], root=str(fixture.root), env={}, say=lambda _: None) + self.assertEqual(result["trials"], [selected]) + self.assertTrue(snapshots) + for snapshot in snapshots: # no record of the choice: every attempt of the task the start names + self.assertEqual(snapshot["this_run"], [selected, "wrong__u0001r2"]) + + def test_run_later_counts_the_tasks_of_a_later_run_not_their_attempts(self): + d = self.run_of() + top = json.loads((d / "result.json").read_text()) + top["reruns"] = [{"at": "2026-11-18T15:40:12+00:00", "finished_at": "2026-11-18T15:42:00+00:00", "reason": "the rest of the plan", + "trials": [f"t-{k}__u{k:04d}r{a}" for k in (3, 4) for a in (1, 2)], "replaced": [], + "begun": [{"trial": f"t-{k}__u{k:04d}r{a}", "unit": f"t-{k}", "now": {"reward": 1.0}} for k in (3, 4) for a in (1, 2)], + "max_usd": None, "spent_usd": 0.0012}] + (d / "result.json").write_text(json.dumps(top)) + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertTrue(text(html, r'

    .*?
    ').endswith("2 tasks · $0.0012 spent")) + + def test_the_duration_adds_each_later_run_s_time_to_the_first_s(self): + d = self.run_of() # its first run: one minute + top = json.loads((d / "result.json").read_text()) + top["reruns"] = [{"at": "2026-11-18T15:40:00+00:00", "finished_at": "2026-11-18T15:46:00+00:00", "trials": ["t-3__u0003"], + "replaced": [], "begun": [{"trial": "t-3__u0003", "unit": "t-3", "now": {"reward": 1.0}}]}, + {"at": "2026-11-18T16:00:00+00:00", "finished_at": "2026-11-18T16:02:00+00:00", "trials": ["t-0__u0000"], + "replaced": [{"trial": "t-0__u0000", "unit": "t-0", "try": 1, "was": {}, "now": {}}]}] + (d / "result.json").write_text(json.dumps(top)) + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertEqual(text(html, r'
    ]*>Duration.*?
    '), "Duration 9m") + self.assertIn('Duration9m', html) # the head says the same + top["reruns"] = [] + (d / "result.json").write_text(json.dumps(top)) + self.open(d.parent) + self.assertEqual(text(self.page("/job/r1?view=results"), r'
    ]*>Duration.*?
    '), "Duration 1m") + + def test_a_job_run_whole_shows_none_of_it(self): + d = self.run_of() + self.open(d.parent) + html = self.page("/job/r1?view=results") + for absent in ('id="plan-run"', 'id="tasks-run"', 'id="pick-rest"', 'id="plan-sets"', "not_run"): + self.assertNotIn(absent, html) + self.assertNotIn("tasks run
    ", self.page("/runs")) + + def test_an_interrupted_job_keeps_no_result_and_offers_the_rest(self): + d = self.run_of() + self.interrupted(d) + self.open(d.parent) + html = self.page("/job/r1?view=results") + self.assertEqual(text(html, r'
    '), "No result 3") + self.assertNotIn('data-o="not_run"', html) + self.assertIn(f'data-pick="{trial_name(2)} t-3__u0003 t-4__u0004">Run the rest · 3', html) + + +class TheBuilder(task_set_pages.BuilderCase): + """Start with in the builder: All of it or Specific tasks, ticked in a dialog holding the tasks page's list; Review, + compiled by the server, says what runs first and what stays for later; the core keeps the choice in the recipe, + drops it with its dataset, its plan and its benchmark, and reads it back from a saved recipe.""" + + def test_review_says_what_runs_first_and_what_stays_for_later(self): + 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", + "start_with": {"all": ["wrong", "good"]}} + out = self.post("/new-run/runner", {"recipe": recipe}) + self.assertEqual(out["errors"], []) + self.assertIn(["Dataset", "all · 2 tasks run first (the tasks ticked); the other 2 stay planned, to run later from the job's page"], + [r[1:] for r in out["review"]]) + self.assertEqual(out["confirm"], "") # no popup asks again + recipe["start_with"] = {"all": "set:dev"} # a recipe from before + out = self.post("/new-run/runner", {"recipe": recipe}) + self.assertIn(["Dataset", "all · 2 tasks run first (task set dev); the other 2 stay planned, to run later from the job's page"], + [r[1:] for r in out["review"]]) + out = self.post("/new-run/runner", {"recipe": dict(recipe, start_with={"all": "9"})}) + self.assertEqual([e["message"] for e in out["errors"]], ["Start with 9 tasks: all plans 4."]) + + def test_the_core_keeps_start_with_with_its_dataset(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the recipe core") + 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']," + "start_with:{all:'set:dev@1',gone:'2',bad:3}});\n" + "const read=JSON.parse(JSON.stringify(r.start_with));\n" + "C.setStartWith(r,'all','');const cleared=r.start_with===undefined;\n" + "C.setStartWith(r,'all','3');const count=r.start_with.all;r.datasets=[];C.keepStartWith(r);const dropped=r.start_with===undefined;\n" + "r.datasets=['all'];C.setStartWith(r,'all','3');C.setStandardBenchmark(r,'fakememo');\n" + "process.stdout.write(JSON.stringify({read,cleared,count,dropped,other:r.start_with===undefined}));") + got = json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + self.assertEqual(got, {"read": {"all": "set:dev@1"}, "cleared": True, "count": "3", "dropped": True, "other": True}) + 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']," + "start_with:{all:['good','wrong'],bad:[1]}});\n" + "const read=JSON.parse(JSON.stringify(r.start_with));\n" + "C.setStartWith(r,'all',['slow']);const ticked=r.start_with.all;\n" + "C.setTaskSet(r,'all','dev');const replanned=r.start_with===undefined;\n" + "process.stdout.write(JSON.stringify({read,ticked,replanned}));") + got = json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + self.assertEqual(got, {"read": {"all": ["good", "wrong"]}, "ticked": ["slow"], "replanned": True}) + + def test_the_step_offers_all_of_it_and_specific_tasks_alone(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the dataset step") + sets.create(self.fake, "other", dataset="all", units=["good"]) + 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 startChoice(", " // Specific tasks:") + + "const r=C.createStandard('fakebench'),b=C.standardBench(r),x=b.datasets[0],u={noun:'task',nouns:'tasks'};" + + "const all=startChoice(r,b,x,u);C.setStartWith(r,x.id,['good','slow']);const ticked=startChoice(r,b,x,u);" + + "C.setStartWith(r,x.id,'2');const older=startChoice(r,b,x,u);" + # the step drawn again by the page's keepFocus, its buttons as stand-ins that match its selectors and take the focus + + f"globalThis.CSS={{escape:s=>s}};const {{keepFocus}}=require({json.dumps(str(folder / 'command-builder.js'))});\n" + + r"""const draw=h=>[...h.matchAll(/]*)>([\s\S]*?)<\/button>/g)].map(([,a,t])=>({tagName:'BUTTON',id:'', + name:(t.match(/(.*?)<\/strong>/)||[0,t.replace(/<[^>]*>|→/g,'').trim()])[1],attributes:[...a.matchAll(/ ([\w-]+)="([^"]*)"/g)].map(([,name,value])=>({name,value})), + matches(s){return s.startsWith('BUTTON[')&&s.slice(7,-1).split('][').every(p=>this.attributes.some(a=>p===`${a.name}="${a.value}"`));},focus(){document.activeElement=this;}})); +// drawn again, the step takes the focus from the button it removes, as a page does +const body={name:'body'},step={els:[],contains(e){return this.els.includes(e);},querySelector(s){return this.els.find(e=>e.matches(s))||null;}, + set innerHTML(h){if(this.contains(document.activeElement))document.activeElement=body;this.els=draw(h);}}; +const back=(from,name,to)=>{step.els=draw(from);globalThis.document={activeElement:step.els.find(e=>e.name===name)};keepFocus(step,()=>{step.innerHTML=to;});return document.activeElement.name;}; +""" + # the dialog closed onto the tile with tasks ticked, or with none; Change the tasks, closed with none; All of it chosen + + "const focus=[back(all,'Specific tasks',ticked),back(ticked,'Specific tasks',ticked),back(ticked,'Change the tasks',all),back(ticked,'All of it',all)];" + + "process.stdout.write(JSON.stringify({all,ticked,older,focus}));") + got = json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True, timeout=10).stdout) + titles = lambda h: re.findall(r"(.*?)", h) + pressed = lambda h: re.findall(r'aria-pressed="true"[^>]*>.*?(.*?)', h) + self.assertEqual((titles(got["all"]), pressed(got["all"])), (["All of it", "Specific tasks"], ["All of it"])) + self.assertEqual((titles(got["ticked"]), pressed(got["ticked"])), (["All of it", "Specific tasks"], ["Specific tasks"])) + self.assertIn("2 chosen", got["ticked"]) + self.assertIn('data-std-start-pick="all"', got["ticked"]) + self.assertNotIn("other", task_set_pages.visible(got["all"])) # the other sets are not offered there + self.assertEqual(titles(got["older"]), ["All of it", "Specific tasks", "The first 2"]) # a recipe from before, shown chosen + # the keyboard stays on the choice, not on the Change button drawn before it + self.assertEqual(got["focus"], ["Specific tasks", "Specific tasks", "Specific tasks", "All of it"]) + + def test_the_page_holds_the_dialog_with_the_tasks_list(self): + html = self.get("/new-run").get_data(as_text=True) + dialog = re.search(r'', html, re.S).group(0) + self.assertIn('id="nb-tasks-done"', dialog) + template = re.search(r'', html, re.S).group(1) + for marker in ('data-manual="true"', 'id="tasks-q"', 'id="tasks-cats"', 'id="tasks-rows"', 'id="tasks-match"', 'id="tasks-show"', + 'id="tasks-bar"', 'id="tasks-state-text"', 'id="tasks-state-link"', 'id="tasks-list-go"', 'id="tasks-paste-open"'): + self.assertIn(marker, template) + self.assertIn("catalogue/tasks.js", html) + + def test_deselecting_a_dataset_removes_its_start_choice_before_review(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the dataset control") + load = task_set_pages.definitions.load + def with_more(kind, root=None, every=False): + entries, errors = load(kind, root, every=every) + if kind == "benchmark": + entries = [dict(b, datasets=[*b["datasets"], {"id": "more", "units": 4}]) + if b["key"] == "fakebench" else b for b in entries] + return entries, errors + self.stack.enter_context(patch.object(task_set_pages.definitions, "load", with_more)) + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S)[1]) + folder = Path(__file__).resolve().parents[1] / "static/builder" + handler = next(line.strip()[5:] for line in (folder / "command-builder.js").read_text().splitlines() + if "else if(d.stdDataset)" in line) + program = (f"const C=require({json.dumps(str(folder / 'command-builder-core.js'))})({json.dumps(schema)});" + "const rec=C.createStandard('fakebench','fake');rec.datasets=['all','more'];" + "rec.start_with={all:'1',more:'2'};rec.model='gpt-5-mini';rec.concurrency=1;rec.unsandboxed=true;" + f"new Function('C','r','d',{json.dumps(handler)})(C,()=>rec,{{stdDataset:'all'}});" + "process.stdout.write(JSON.stringify(rec));") + recipe = json.loads(subprocess.run([node, "-e", program], capture_output=True, text=True, check=True, timeout=10).stdout) + self.assertEqual(recipe["start_with"], {"more": "2"}) + self.assertEqual(self.post("/new-run/runner", {"recipe": recipe})["errors"], []) diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index 65ff4059c..31f5568b3 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -15,6 +15,7 @@ import threading import time import unittest +import urllib.parse from contextlib import ExitStack from html import unescape from pathlib import Path @@ -26,7 +27,7 @@ from nullius.standard.protocols import jsonl from nullius.standard.requirements import install from nullius.standard.runner import job, sets, units -from tests.test_standard_units_listing import DRIVER, REJECTING_DRIVER, gated +from tests.test_standard_units_listing import DRIVER, MODE, REJECTING_DRIVER, gated from .test_routes import web FIXTURES = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tests", "fixtures", "standard", "catalogue") @@ -88,6 +89,84 @@ def starts(self) -> int: class TheTaskFilters(unittest.TestCase): + def test_detached_responses_cannot_change_another_picker(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the task picker") + script = Path(__file__).resolve().parents[1] / "static/catalogue/tasks.js" + program = r""" +const assert = require('node:assert/strict'); +const source = require('node:fs').readFileSync(process.argv[1], 'utf8'); +async function check(rows, detached, failed) { + let active; + const requests = [], callbacks = {a: [], b: []}; + function picker(name) { + const elements = new Map(); + const element = id => { + if (['tasks-chosen-parts', 'tasks-savebar', 'tasks-create', 'tasks-to-save'].includes(id)) return null; + if (!elements.has(id)) elements.set(id, { + innerHTML: '', textContent: '', listeners: {}, attributes: {}, classList: {toggle() {}}, + addEventListener(type, callback) { this.listeners[type] = callback; }, + setAttribute(key, value) { this.attributes[key] = value; }, + querySelector() { return {disabled: false}; } + }); + return elements.get(id); + }; + return {isConnected: true, element, + dataset: {writable: 'true', base: '/', dataset: name}, + querySelector: selector => selector.startsWith('#') ? element(selector.slice(1)) : null, + querySelectorAll: () => []}; + } + const scope = { + document: {getElementById: id => id === 'tasks-page' ? null : active.element(id), + querySelector: () => null, querySelectorAll: () => [], addEventListener() {}}, + URLSearchParams, window: {}, setTimeout, clearTimeout, + nulliusFetch: url => new Promise((resolve, reject) => requests.push({url, resolve, reject})) + }; + require('node:vm').runInNewContext(source, scope); + async function flush() { for (let i = 0; i < 20; i++) await Promise.resolve(); } + function answer(request, id) { + request.resolve({json: async () => ({ok: true, ready: true, total: 1, of: 1, + page: 1, pages: 1, described: true, categories: {}, unknown: [], tasks: [{id}]})}); + return flush(); + } + const a = active = picker('a'); + scope.nulliusTasks(a, {chosen: ['task-a'], onChange: ids => callbacks.a.push(ids)}); + let pending = requests[0]; + if (rows) { + await answer(pending, 'task-a'); + a.element('tasks-show').listeners.click(); + await answer(requests[1], 'task-a'); + pending = requests[2]; + assert.equal(pending.url, '/a/rows'); + } + a.isConnected = !detached; + const before = a.element('tasks-rows').innerHTML; + const b = active = picker('b'); + scope.nulliusTasks(b, {onChange: ids => callbacks.b.push(ids)}); + await answer(requests.at(-1), 'task-b'); + if (failed) { pending.reject(Error('unavailable')); await flush(); } + else await answer(pending, 'late-a'); + assert.ok(b.element('tasks-rows').innerHTML.includes('data-id="task-b"')); + assert.equal(b.element('tasks-state-text').textContent, ''); + if (detached) { + assert.equal(a.element('tasks-rows').innerHTML, before); + assert.equal(a.element('tasks-state-text').textContent, ''); + } + const box = {checked: true, closest: () => ({dataset: {id: 'task-b'}})}; + b.element('tasks-rows').listeners.change({target: {closest: () => box}}); + assert.equal(JSON.stringify(callbacks.b), '[["task-b"]]'); + assert.equal(callbacks.a.length, 0); +} +(async () => { + for (const rows of [false, true]) for (const detached of [false, true]) + for (const failed of [false, true]) await check(rows, detached, failed); +})().catch(error => { console.error(error); process.exitCode = 1; }); +""" + got = subprocess.run([node, "-e", program, str(script)], stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=10) + self.assertEqual(got.returncode, 0, got.stderr) + def filtered(self, action): node = shutil.which("node") if not node: @@ -105,6 +184,8 @@ def filtered(self, action): }); return elements.get(id); } +element('tasks-page').querySelector = s => s.startsWith('#') ? element(s.slice(1)) : null; +element('tasks-page').querySelectorAll = () => []; element('tasks-page').dataset = {set: 'dev', writable: 'true', base: '/t/', dataset: 'all'}; element('tasks-chosen-parts').textContent = '{"all": ["alpha","beta"]}'; const tasks = ['alpha', 'beta'].map(id => ({id, title: id, categories: {kind: id}})); @@ -177,6 +258,37 @@ def test_task_pages_accept_the_definitions_version_syntax(self): self.assertIn(f'data-version="{version}"', response.get_data(as_text=True)) self.get("/benchmarks/fakebench/tasks/all?version=unknown", status=404) + def test_the_picker_lists_the_limited_plan_under_its_benchmark_options(self): + units.listing(self.fake, "all") + path = "/benchmarks/fakebench/tasks/all/listing?limit=1" + self.assertEqual([t["id"] for t in self.get(path).get_json()["tasks"]], ["good"]) + self.assertEqual(self.get(path + "&q=wrong&ids=1").get_json()["ids"], []) + self.b["options"] = MODE + units.listing(self.b, "all", {"mode": "short"}) + self.assertFalse(self.listing()["ready"]) + path = '/benchmarks/described/tasks/all/listing?options={"mode":"short"}&limit=10' + got = self.get(path).get_json() + self.assertEqual(([t["id"] for t in got["tasks"]], got["of"]), ([f"t{i:03}" for i in range(10)], 10)) + self.assertEqual(self.get(path + "&q=t019&ids=1").get_json()["ids"], []) + got = self.post('/benchmarks/described/tasks/all/rows?options={"mode":"short"}', {"units": ["t007", "t024"]}) + self.assertEqual(([t["id"] for t in got["tasks"]], got["unknown"]), (["t007"], ["t024"])) + + def test_options_too_deep_or_too_long_are_refused_as_a_wrong_value_is(self): + self.b["options"] = MODE + units.listing(self.b, "all", {"mode": "short"}) + before = self.starts() + path = "/benchmarks/described/tasks/all/" + for name, value in (("a list", "[1]"), ("a list nested 3,000 deep", "[" * 3000), + ("10,000 brackets", "[" * 10000), + ("an object of many options", "{" + ",".join(f'"k{i}": "v"' for i in range(500)) + "}")): + with self.subTest(name=name): + query = "options=" + urllib.parse.quote(value) + self.get(path + "listing?" + query, status=400) + self.post(path + "rows?" + query, {"units": ["t007"]}, status=400) + self.post(path + "prepare?" + query, {}, status=400) + self.assertTrue(self.get(path + 'listing?options={"mode":"short"}').get_json()["ready"]) + self.assertEqual(self.starts(), before) + def test_each_search_category_and_page_gives_what_the_listings_function_gives(self): units.listing(self.b, "all") # in the cache: the page reads it before = self.starts() @@ -194,6 +306,19 @@ def test_each_search_category_and_page_gives_what_the_listings_function_gives(se self.assertEqual(self.listing(ids=1, cat=["kind=alpha"])["ids"], [t["id"] for t in units.find(self.b, "all", categories={"kind": ["alpha"]}, size=None)["tasks"]]) self.assertEqual(self.starts(), before) # every answer from the cache: no driver started + def test_within_a_set_the_listing_holds_its_tasks_alone(self): + units.listing(self.b, "all") + sets.create(self.b, "Three", dataset="all", units=["t001", "t007", "t120"]) + got = self.listing(within="three") + self.assertEqual(([t["id"] for t in got["tasks"]], got["total"], got["of"]), (["t001", "t007", "t120"], 3, 3)) + self.assertEqual(got, dict(units.find(self.b, "all", within=["t001", "t007", "t120"]), ok=True, ready=True)) + self.assertEqual(self.listing(within="three", ids=1)["ids"], ["t001", "t007", "t120"]) + searched = self.listing(within="three", q="spreadsheet") + self.assertEqual([t["id"] for t in searched["tasks"]], [t["id"] for t in units.find(self.b, "all", search="spreadsheet")["tasks"] + if t["id"] in ("t001", "t007", "t120")]) + r = self.client.get("/benchmarks/described/tasks/all/listing?within=nowhere"); self.addCleanup(r.close) + self.assertEqual((r.status_code, r.get_json()["error"]), (400, "There is no task set nowhere.")) + def test_pick_at_random_draws_as_set_create_sample_does_and_the_set_keeps_its_seed(self): units.listing(self.b, "all") alpha = [t["id"] for t in units.find(self.b, "all", categories={"kind": ["alpha"]}, size=None)["tasks"]] @@ -254,6 +379,8 @@ def test_a_row_is_one_line_ticked_by_a_click_with_its_whole_text_on_hover_and_it return elements.get(id); } const writable = process.argv[2] === 'true'; +element('tasks-page').querySelector = s => s.startsWith('#') ? element(s.slice(1)) : null; +element('tasks-page').querySelectorAll = () => []; element('tasks-page').dataset = {writable: process.argv[2], base: '/t/', dataset: 'all'}; const long = 'Open the report and ' + 'make the second table match the first one, '.repeat(6); const tasks = [{id: 'os__a', title: long.slice(0, 99) + '…', text: long, categories: {}}, {id: 'b', title: '', text: '', categories: {}}]; @@ -323,7 +450,7 @@ def join(): self.addCleanup(join) first = self.post("/benchmarks/described/tasks/all/prepare", {}) join() - record = catalogue._PREPARING[catalogue._listing_key(self.b, "all")] + record = catalogue._PREPARING[catalogue._listing_key(self.b, "all", {})] shown = self.listing() for value in (json.dumps(first), record["error"], json.dumps(shown)): self.assertNotIn(token, value) @@ -340,7 +467,7 @@ def get(kind, ref, root=None): self.stack.enter_context(patch.dict(catalogue._PREPARING, {}, clear=True)) called = [] def make(bench, dataset, options=None): - called.append(bench["_version"]) + called.append((bench["_version"], options)) if bench["_version"] == "1": raise units.Refused("Version 1 is unavailable") self.stack.enter_context(patch.object(units, "listing", make)) @@ -350,18 +477,18 @@ def join(): self.assertFalse(job["thread"].is_alive()) self.addCleanup(join) path = '/benchmarks/described/tasks/all/' - self.post(path + 'prepare?version=1', {}) + self.post(path + 'prepare?version=1&options={"mode":"short"}', {}) join() - failed = self.get(path + 'listing?version=1').get_json() + failed = self.get(path + 'listing?version=1&options={"mode":"short"}').get_json() self.assertEqual(failed["error"], "Version 1 is unavailable") - for suffix in ('', '?version=2'): - got = self.get(path + 'listing' + suffix).get_json() + for suffix in ('', '&version=2'): + got = self.get(path + 'listing?options={"mode":"short"}' + suffix).get_json() self.assertEqual((got["state"], got["error"], got["preparing"]), ("light", "", False)) - self.post(path + 'prepare', {}) + self.post(path + 'prepare?options={"mode":"short"}', {}) join() - self.assertEqual(called, ["1", "2"]) - self.assertEqual(self.get(path + 'listing?version=2').get_json()["error"], "") - self.assertEqual(self.get(path + 'listing?version=1').get_json()["error"], failed["error"]) + self.assertEqual(called, [("1", {"mode": "short"}), ("2", {"mode": "short"})]) + self.assertEqual(self.get(path + 'listing?version=2&options={"mode":"short"}').get_json()["error"], "") + self.assertEqual(self.get(path + 'listing?version=1&options={"mode":"short"}').get_json()["error"], failed["error"]) def no_fetch_no_install(self): def refuse(*a, **k): @@ -791,6 +918,7 @@ 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") @@ -813,7 +941,99 @@ def test_the_schema_offers_the_sets_and_review_names_the_chosen_one(self): class TheDatasetStep(BuilderCase): - """Which tasks?, under the chosen datasets: the dataset's name in its title only when several are chosen.""" + """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 benchLimits(") + + 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: {}, querySelector: () => null}, 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") @@ -828,13 +1048,13 @@ def test_the_titles_name_the_dataset_only_when_several_are_chosen(self): 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 benchLimits(") + "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);" - + "r.datasets=[x.id,'more'];const two=taskSetChoice(r,b,x,u);" + + "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?"]) - self.assertEqual(heads(got["two"]), [f"{got['label']}: which tasks?"]) + 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): diff --git a/app/web/catalogue.py b/app/web/catalogue.py index 339e6ad7f..26754927d 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -133,7 +133,7 @@ def benchmark_page(key): # --- a dataset's tasks: browsed, chosen and kept as a task set --------------------------------- -# The listings being prepared, keyed by benchmark, resolved version and dataset. +# The listings being prepared, keyed by benchmark, resolved version, dataset and options. _PREPARING: dict = {} _PREPARING_LOCK = threading.Lock() @@ -150,17 +150,36 @@ def _std_dataset(key: str, dataset: str, version: str = ""): return bench, ds -def _listing_key(bench: dict, dataset: str): - return bench["key"], standard_definitions.version_of(bench), dataset +# 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_state(bench: dict, dataset: str) -> dict: +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; ``about``, what a listing the page starts on a click does first; ``link``, where a licence it needs is set.""" - got = units.state(bench, dataset) + got = units.state(bench, dataset, options) with _PREPARING_LOCK: - job = _PREPARING.get(_listing_key(bench, dataset)) or {} + 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") @@ -224,7 +243,8 @@ 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", "")) - st = _listing_state(bench, dataset) + options = _listing_options() + st = _listing_state(bench, dataset, options) if st["state"] != "cached": return jsonify(ok=True, ready=False, **st) cats: dict = {} @@ -233,9 +253,22 @@ def benchmark_tasks_listing(key, dataset): 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 (of a set of several datasets, its list of this one), 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.parts(entry).get(dataset) or [] try: if request.args.get("ids"): # every match's id, for "select the N that match" - got = units.find(bench, dataset, search=request.args.get("q", ""), categories=cats, size=None) + got = units.find(bench, dataset, options, search=request.args.get("q", ""), categories=cats, size=None, within=within, limit=limit) ids = [t["id"] for t in got["tasks"]] if "sample" not in request.args: return jsonify(ok=True, ready=True, total=got["total"], ids=ids) @@ -248,9 +281,10 @@ def benchmark_tasks_listing(key, dataset): return jsonify(ok=True, ready=True, total=got["total"], ids=ids, seed=seed, note=units.sample_note(n, seed, request.args.get("q", ""), cats)) size = request.args.get("size", "") # the page's Show: 10, 25 or 100 a page, or 0 for all - got = units.find(bench, dataset, search=request.args.get("q", ""), categories=cats, + 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, - size=(int(size) or None) if size in ("10", "25", "100", "0") else units.PAGE) + size=(int(size) or None) if size in ("10", "25", "100", "0") else units.PAGE, + within=within, limit=limit) except units.Refused as e: return jsonify(ok=False, error=_page_words(e)), 400 return jsonify(ok=True, ready=True, **got) @@ -286,14 +320,15 @@ def benchmark_tasks_prepare(key, dataset): 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", "")) - identity = _listing_key(bench, dataset) - st = units.state(bench, dataset) + options = _listing_options() + identity = _listing_key(bench, dataset, options) + st = units.state(bench, dataset, options) if st["state"] not in ("light", "full"): - return jsonify(ok=st["state"] == "cached", **_listing_state(bench, dataset)) + return jsonify(ok=st["state"] == "cached", **_listing_state(bench, dataset, options)) def make(): try: - units.listing(bench, dataset) + units.listing(bench, dataset, options) except (units.Refused, OSError) as e: with _PREPARING_LOCK: _PREPARING[identity]["error"] = str(e) @@ -302,7 +337,7 @@ def make(): 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)) + return jsonify(ok=True, **_listing_state(bench, dataset, options)) @app.route("/benchmarks//tasks//rows", methods=["POST"]) @@ -310,10 +345,11 @@ 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)["state"] != "cached": + 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)["tasks"]} + 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]) diff --git a/app/web/execute.py b/app/web/execute.py index 0ac77cb01..131fb8874 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 @@ -222,6 +224,124 @@ 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 (``ex``: the run that writes this very folder, + ``shared.run_for``), still running, merged from its shards' jobs, its host gone from Settings - 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 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 = shared.run_for(job_id, j) + 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: this run has what the runs 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 run has 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 run on: kept in its run's record (``Plan.caps``) and + handed to that run as ``rerun --max-usd``. Refused where the page offers no next run (``again_offer``: a run + of the job under way), 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 = shared.run_for(job_id, j) + 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 6fd67f134..894ec000f 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, jsonify, render_template, request, 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 run of the job" for a task of the plan + a later run 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 run of the job" 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 cb3d48480..e2132e81a 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -579,7 +579,11 @@ 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(), set_link=_set_link(j), set_saving=_set_saving(j), @@ -587,6 +591,8 @@ def job(job_id): control=feasibility.summary_of(j), ended=ended, 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)) @@ -650,6 +656,59 @@ 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 + started on some 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 (of a set of several, its list of that 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 dataset not in task_sets.datasets_of(e): + continue + wanted = set(task_sets.parts(e)[dataset]) + 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 @@ -711,6 +770,26 @@ def job_task_set(job_id): 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.""" @@ -944,7 +1023,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_this_run(j, snap)} + + +def _with_this_run(j, snap: dict) -> dict: + """The board's snapshot, with ``this_run`` while a standard job started on some of its plan runs: the trials + of that run, 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 = shared.run_for(j.job_id, j) 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, this_run=list(dict.fromkeys(chosen["trials"]))) + wanted = set(units) + return dict(snap, this_run=[name for name, unit in plan if unit in wanted]) @app.route("/job//live") @@ -974,6 +1079,6 @@ def job_live(job_id): response.status_code = 422 response.headers["Cache-Control"] = "no-store" return response - response = jsonify(snap) + response = jsonify(_with_this_run(j, snap)) response.headers["Cache-Control"] = "no-store" return response diff --git a/docs/builder.md b/docs/builder.md index 2ec29eb5b..10dd6ccb6 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`), labelled Official or Experiment. | | 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. Each runs all its tasks or one [task set](cli/task-sets.md), its benchmark's own lists (`subset_of`) included. 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-start-with-some-of-it)). A benchmark option its datasets need is asked here, for the datasets it applies to. | | Agent (*Memory* on a memory benchmark) | The selected version's procedure is the first card, on by default; agents, memory capabilities and checks run beside it, a job each, and it comes back when nothing is left. The procedure's own settings (LoCoMo's retrieval) are in its tab while it runs. A benchmark with [agents of its own](standard.md#a-benchmarks-own-agents) (OSWorld's) lists them first; several may be chosen, a job each. | | 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. **Reasoning**, beside each model, offers the levels that model offers; greyed when the agent or the benchmark sets its own ([Run a benchmark](cli/run.md#reasoning)). | | 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 94a73303c..b7823acfb 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -20,6 +20,7 @@ From a source checkout, replace `nullius` with | [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 ad10f66ec..c58cb0d08 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -28,6 +28,7 @@ Each page's command, or why there is none. | 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 000000000..61b1074de --- /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 run 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 run of the job has its cap less what the runs before it spent. | +| A job started on some of its plan | `--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 af192968e..20a90057c 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 | --set NAME] [--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]... \ @@ -16,6 +16,7 @@ nullius standard run humaneval reference --model gpt-5-mini --limit 2 --unsandbo 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 ``` @@ -29,6 +30,7 @@ nullius standard run locomo model --model gpt-4o-mini | `--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, start with some of it: [below](#plan-the-whole-start-with-some-of-it) | | `--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` | @@ -126,6 +128,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 runs | The job's one cap: each later run of the job has what the runs before it left ([Run tasks again](rerun.md)) | | Shards | A shard's cap is its own: [Shard and merge](shard-and-merge.md) | ## Retries @@ -140,7 +143,7 @@ A benchmark that names a cut in `limits.scored_cuts` still scores an agent's uni | Wrong key, spent credit, an agent's first call over the model's context window | 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 @@ -164,6 +167,24 @@ HumanEval/12 | 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, start with some of it + +`--start-with` plans the whole run and starts with some of it; the rest stay planned, run later in the same job by [`rerun`](rerun.md). + +| The start | Runs first | +| --- | --- | +| `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, `--shard`, or a [VM benchmark on Boat](../standard.md#the-boat-backend). | +| 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 start, `standard.start_with`. | +| The rates | Over the tasks run; the job's page and `runs show` say how many have run. | + ## Serving providers On OpenRouter one model is served by several providers. They may differ in precision, speed and price. `--served-by deepinfra` lets only DeepInfra answer the run's model; `--served-by m=deepinfra/fp8,together` lets DeepInfra's fp8 endpoint answer the model `m`, then Together when it cannot. diff --git a/docs/field-guide.md b/docs/field-guide.md index 1cf2b58dc..04213b894 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 [started on some of its plan](cli/run.md#plan-the-whole-start-with-some-of-it) has its rates over the tasks run. Standard runs with repeated, scored attempts record both measures in `pass_hat_k`. They answer different questions. @@ -153,13 +153,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 tasks a standard job started with. | measured | any | | `retries` | Retries a standard run allows each attempt (`--retries`); 0 elsewhere. | measured | any | | `identity` | A standard run's setup: benchmark, agent, backend, 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 | @@ -185,7 +186,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 diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 50de37da4..8757c953e 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -78,7 +78,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 20df63abf..3a8a12240 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 [started on some of its plan](cli/run.md#plan-the-whole-start-with-some-of-it) 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 a5fb05ea9..9a9d08f2a 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -643,6 +643,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