From f393cb6e042ff6a954cb5e2f7623f16353b9db92 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 23 Nov 2026 14:15:18 +0100 Subject: [PATCH 01/37] feat(standard): list a dataset's tasks by search and category Nothing lists a dataset's tasks without running it: a user who wants a few tasks has to read the upstream's files to find their ids. A driver may now answer `describe` (each task's title, text and categories, read from the dataset's files alone) and name a light command for a listing (`driver.list_command`), which starts with Python's standard library and never prepares the driver's environment. `nullius standard units` lists a dataset's tasks from a cache under the user's cache folder, searched by text and counted by category. OSWorld1, LongMemEval and LoCoMo declare both. --- AGENTS.md | 2 +- .../catalogue/benchmarks/locomo/driver.py | 11 +- .../catalogue/benchmarks/locomo/standard.json | 1 + .../benchmarks/longmemeval/driver.py | 11 +- .../benchmarks/longmemeval/standard.json | 1 + .../catalogue/benchmarks/osworld1/driver.py | 18 +- .../benchmarks/osworld1/standard.json | 16 + app/nullius/standard/cli.py | 79 ++- app/nullius/standard/contract/definitions.py | 5 + app/nullius/standard/runner/units.py | 313 +++++++++++ app/site/mkdocs.yml | 1 + app/tests/test_cli_contract.py | 37 ++ app/tests/test_locomo_rag.py | 15 + app/tests/test_longmemeval_setups.py | 12 + app/tests/test_standard_units_listing.py | 512 ++++++++++++++++++ docs/cli/README.md | 1 + docs/cli/task-sets.md | 25 + docs/standard.md | 3 + 18 files changed, 1057 insertions(+), 6 deletions(-) create mode 100644 app/nullius/standard/runner/units.py create mode 100644 app/tests/test_standard_units_listing.py create mode 100644 docs/cli/task-sets.md diff --git a/AGENTS.md b/AGENTS.md index 2b17e07b5..a64aed1a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ and its resources. `protocols/`: `jsonl`, `acp`, `cancellation` (interruptible protocol waits), `computer_port` and `computer_pipe` (the computer port's MCP server, served by a desktop benchmark's runner over the benchmark's own loop, and the session's stdio pipe to it); `calls/`: `relay`, `ledger` (a run's spending cap); `backends/`: `container` (the container backend), `boat` (the boat backend: each unit's agent in a boat.dev VM), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `egress` (an own image's check's proxy to public addresses); - `runner/`: `run`, `job`, `retries` (what an attempt is tried again after, and how many times), `pace` (how soon the next unit starts after a rate limit), `shard` and `merge` (one run over many machines), `payload` (a snapshot of the running backend and effective catalogue for a remote host), `boat_units` (a benchmark whose units boot a VM of their own, each unit whole in a Boat VM); + `runner/`: `run`, `job`, `retries` (what an attempt is tried again after, and how many times), `pace` (how soon the next unit starts after a rate limit), `shard` and `merge` (one run over many machines), `payload` (a snapshot of the running backend and effective catalogue for a remote host), `boat_units` (a benchmark whose units boot a VM of their own, each unit whole in a Boat VM), `units` (a dataset's tasks listed, searched and counted by category, from the driver's `describe`); `proofs/`: `conform`, `fidelity` (ACP against the agent's own CLI), `prove` (a benchmark's controls and proofs), `pins` (image digests checked against registry tags); `pages/`: `recipe` (the builder's standard recipe), `howto` (the How to add steps); and the `cli` at its top; diff --git a/app/nullius/catalogue/benchmarks/locomo/driver.py b/app/nullius/catalogue/benchmarks/locomo/driver.py index c02ba3034..d924c0dd6 100644 --- a/app/nullius/catalogue/benchmarks/locomo/driver.py +++ b/app/nullius/catalogue/benchmarks/locomo/driver.py @@ -94,6 +94,15 @@ def units(dataset, setup=None): return {"units": out} +def describe(dataset, **_): + out = {} + for unit in units(dataset)["units"]: + q = question(unit)[1] + text = q["question"] + out[unit] = {"title": text, "text": text, "categories": {"category": str(q["category"])}} + return {"units": out} + + # What goes into the memory for each session: the run's ``rag_mode`` option, LoCoMo's --rag-mode - dialog # (the conversation), or the authors' own released extractions, observation (facts per speaker) and # summary (one per session). How a fact or a summary is put as a turn is ours: a fact is its speaker's @@ -259,7 +268,7 @@ def oracle(unit, dir): return {"answer": gold(q)} -HANDLERS = {"units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} +HANDLERS = {"describe": describe, "units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} for line in sys.stdin: try: req = json.loads(line) diff --git a/app/nullius/catalogue/benchmarks/locomo/standard.json b/app/nullius/catalogue/benchmarks/locomo/standard.json index 1eb810a29..c6e3d3cfd 100644 --- a/app/nullius/catalogue/benchmarks/locomo/standard.json +++ b/app/nullius/catalogue/benchmarks/locomo/standard.json @@ -14,6 +14,7 @@ "license": "CC-BY-NC-4.0" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" diff --git a/app/nullius/catalogue/benchmarks/longmemeval/driver.py b/app/nullius/catalogue/benchmarks/longmemeval/driver.py index 69e9320b6..f10b131ab 100644 --- a/app/nullius/catalogue/benchmarks/longmemeval/driver.py +++ b/app/nullius/catalogue/benchmarks/longmemeval/driver.py @@ -148,6 +148,15 @@ def units(dataset, setup=None): return {"units": [q for q in index() if kind == "all" or TYPES[q] == kind]} +def describe(dataset, **_): + out = {} + for unit in units(dataset)["units"]: + q = entry(unit) + text = q["question"] + out[unit] = {"title": text, "text": text, "categories": {"question_type": str(q["question_type"])}} + return {"units": out} + + def setup(unit, dir): q = entry(unit) dates = q.get("haystack_dates") or [""] * len(q["haystack_session_ids"]) @@ -373,7 +382,7 @@ def score_setup(unit, dir, judge): ("expansion_join", "separate"), ("gen_length", "upstream"))}}} -HANDLERS = {"units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} +HANDLERS = {"describe": describe, "units": units, "setup": setup, "produce": produce, "score": score, "oracle": oracle, "answer": answer} for line in sys.stdin: try: req = json.loads(line) diff --git a/app/nullius/catalogue/benchmarks/longmemeval/standard.json b/app/nullius/catalogue/benchmarks/longmemeval/standard.json index 7a2003fc8..8ebf24a00 100644 --- a/app/nullius/catalogue/benchmarks/longmemeval/standard.json +++ b/app/nullius/catalogue/benchmarks/longmemeval/standard.json @@ -14,6 +14,7 @@ "license": "MIT" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" diff --git a/app/nullius/catalogue/benchmarks/osworld1/driver.py b/app/nullius/catalogue/benchmarks/osworld1/driver.py index d8b897656..d193027cd 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/driver.py +++ b/app/nullius/catalogue/benchmarks/osworld1/driver.py @@ -9,6 +9,8 @@ units - every task of the dataset (one of the upstream's evaluation_examples/test_*.json), as domain__id, in the file's order +describe - each task's instruction (its title the first words) and its domain, + from the task's file alone setup - the task's instruction, for the null control. For an agent (participant "agent", which the definition's driver.participant asks Nullius to send): runner.py started in the trial's @@ -160,6 +162,19 @@ def units(dataset=None, setup=None): return {"units": [f"{d}__{e}" for d, ids in meta.items() for e in ids]} +def describe(dataset=None, **_): + """Each task of the dataset from its file alone: the instruction as its text (its title the first words), + its domain as a category.""" + out = {} + for unit in units()["units"]: + domain, _eid, example = _task(unit) + text = str(example.get("instruction") or "") + line = " ".join(text.split()) + title = line if len(line) <= 100 else line[:100].rsplit(" ", 1)[0] + " ..." + out[unit] = {"title": title, "text": text, "categories": {"domain": domain}} + return {"units": out} + + def setup(unit, dir, participant=None, **_): until = time.time() + SETUP_SECONDS - REAP_SECONDS - REMOVE_SECONDS - ANSWER_SECONDS # an agent's setup's own instruction = _task(unit)[2]["instruction"] @@ -845,7 +860,8 @@ def score(unit, dir, transcript=None, answer=None, setup=None, **_): return _scored(where, "nop.py, DesktopEnv.evaluate") -HANDLERS = {"units": units, "setup": setup, "task_given": task_given, "answer": answer, "score": score, "end": end} +HANDLERS = {"units": units, "describe": describe, "setup": setup, "task_given": task_given, "answer": answer, + "score": score, "end": end} def main(): diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 00096f8bc..182eaf264 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -28,6 +28,14 @@ }, "participant": true, "unit_end": true, + "describe": true, + "list_command": [ + "python3", + "{here}/driver.py", + "{here}/agents.json", + "{here}/nop.py", + "{here}/runner.py" + ], "task_given": true }, "mcp_servers": { @@ -303,6 +311,14 @@ }, "participant": true, "unit_end": true, + "describe": true, + "list_command": [ + "python3", + "{here}/driver.py", + "{here}/agents.json", + "{here}/nop.py", + "{here}/runner.py" + ], "task_given": true }, "setups": { diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 5c5bf2262..f4126f96c 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -12,6 +12,7 @@ PYTHONPATH=app python3 -m nullius.standard.cli prove BENCHMARK[@VERSION] [--dataset D] [--limit N] [--bench-option NAME=VALUE ...] [--job nop|oracle=JOB_DIR ...] PYTHONPATH=app python3 -m nullius.standard.cli run ... --shard I/N [--launch ID] PYTHONPATH=app python3 -m nullius.standard.cli merge JOB_DIR... -o OUT [--force] + PYTHONPATH=app python3 -m nullius.standard.cli units BENCHMARK --dataset D [--search TEXT] [--category FIELD=VALUE ...] [--json] PYTHONPATH=app python3 -m nullius.standard.cli fidelity AGENT --model M [--provider P] [--option NAME=VALUE ...] [--passes N] --unsandboxed An agent runs commands as you on the local backend, which is not a sandbox: @@ -43,7 +44,8 @@ ``--limit``), the job recording its shard and its launch (``--launch``); ``--units FILE`` runs only the units a file lists (``run.units_file``: one id a line), read on the machine the command runs on, ``--from-run`` or not; ``merge`` -puts a launch's shard jobs together into one job (``standard/runner/merge.py``). ``--option`` +puts a launch's shard jobs together into one job (``standard/runner/merge.py``). ``units`` lists a +dataset's tasks, searched and counted by category (``standard/runner/units.py``). ``--option`` sets one of the agent's or capability's options (``options`` in its definition); the rest keep the vendor's defaults, and the job's config records them all. ``--served-by [MODEL=]SLUG[,SLUG...]`` lets only those serving providers answer @@ -85,6 +87,7 @@ from nullius.standard.contract import definitions, match, ports, proofs from nullius.standard.proofs import conform, fidelity, pins, prove from nullius.standard.runner import job, merge, run, shard +from nullius.standard.runner import units as unit_list ENV_FILE = paths.settings_file() @@ -734,6 +737,66 @@ def cmd_merge(a): return 0 +def _refused(e: Exception) -> int: + print(f"refused: {e}", file=sys.stderr) + return 3 if isinstance(e, unit_list.NotFound) else 2 + + +def _find_bench(key): + """A benchmark of the catalogue, or a conformance kit, by its key; None when there is none.""" + return definitions.get("benchmark", key) or next((k for k in definitions.kits() if k["key"] == key), None) + + +UNITS_EPILOG = """\ +examples: + nullius standard units humaneval --dataset humaneval + nullius standard units osworld1 --dataset test_nogdrive --search "tab" --category domain=chrome --category domain=vlc + nullius standard units longmemeval --dataset longmemeval_oracle --bench-option question_type=multi-session --json + +exit codes: + 0 listed, a match of no task included + 1 unexpected error (a traceback: report it) + 2 usage, or refused: an option or a category not known, a program the listing needs not on this machine, + a driver that could not list the dataset + 3 not found: no such benchmark or dataset + +A first listing fetches what it needs first (the upstream, the dataset, the driver's environment unless the +benchmark names a light listing command), said in one line on stderr; later listings read the cache. +""" + + +def cmd_units(a): + try: + b = _find_bench(a.benchmark) + if b is None: + raise unit_list.NotFound(f"no benchmark {a.benchmark!r}") + try: + given = options(a.bench_option, "--bench-option") + except SystemExit as e: + raise unit_list.Refused(str(e)) + chosen = unit_list.categories_of(a.category) + before = unit_list.state(b, a.dataset, given) + if before["state"] == "refused": + raise unit_list.Refused(before["reason"]) + if before["fetch"]: + print(f"first listing of {a.dataset}: fetching " + ", then ".join(f["text"] for f in before["fetch"]), + file=sys.stderr, flush=True) + found = unit_list.find(b, a.dataset, given, search=a.search or "", categories=chosen, size=None) + except unit_list.Refused as e: + return _refused(e) + if a.json: + print(json.dumps(found, indent=2, ensure_ascii=False)) + return 0 + words = b["units"] + print(f"{found['total']} of {found['of']} {words['nouns']} of {a.dataset}" + + ("" if found["described"] else " (its driver gives ids alone: a search reads the ids)")) + for field, values in found["categories"].items(): + print(f"{field}: " + ", ".join(f"{v['value']} {v['count']}" for v in values)) + for t in found["tasks"]: + print(f" {t['id']}" + (f" {t['title']}" if t["title"] else "")) + return 0 + + def cmd_fidelity(a): o = definitions.get("agent", a.other) if not o: @@ -899,6 +962,17 @@ def main(argv=None): g.add_argument("jobs", nargs="+", metavar="JOB_DIR") g.add_argument("-o", "--out", required=True, help="the merged job's directory (its name is the job's)") g.add_argument("--force", action="store_true", help="merge shards of different launches, versions, models or agents") + un = sub.add_parser("units", help="a dataset's tasks: their ids, titles and categories, searched and counted", + epilog=UNITS_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + un.add_argument("benchmark", metavar="BENCH") + un.add_argument("--dataset", required=True, help="the dataset whose tasks are listed") + un.add_argument("--bench-option", action="append", metavar="NAME=VALUE", + help="a benchmark option the driver lists under (repeatable); the others at their defaults") + un.add_argument("--search", metavar="TEXT", help="the tasks whose id, title or text hold each word, whatever the case") + un.add_argument("--category", action="append", metavar="FIELD=VALUE", + help="the tasks of this category's value (repeatable: values of one field widen, fields narrow)") + un.add_argument("--json", action="store_true", + help="one JSON document: total, of, described, tasks and each category's values with their counts") 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") @@ -915,7 +989,8 @@ def main(argv=None): if not getattr(a, "from_run", False): settings.load(ENV_FILE) return {"list": cmd_list, "check": cmd_check, "fit": cmd_fit, "pins": cmd_pins, "new": cmd_new, "conform": cmd_conform, "run": cmd_run, - "fidelity": cmd_fidelity, "prove": cmd_prove, "merge": cmd_merge, "traces": cmd_traces}[a.cmd](a) + "fidelity": cmd_fidelity, "prove": cmd_prove, "merge": cmd_merge, "traces": cmd_traces, + "units": cmd_units}[a.cmd](a) if __name__ == "__main__": diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 5b890c7c3..28ff1a3fb 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1565,6 +1565,11 @@ def problems(d: dict, kind: str) -> List[str]: bad.append("driver.participant: true or false - whether setup is told the participant's kind") if "unit_end" in drv and not isinstance(drv["unit_end"], bool): bad.append("driver.unit_end: true or false - whether the driver is told each unit's end") + if "describe" in drv and not isinstance(drv["describe"], bool): + bad.append("driver.describe: true or false - whether the driver answers describe") + if "list_command" in drv: + # a listing's start: the standard library and the dataset's files, never the driver's install + bad += _command("driver.list_command", drv["list_command"], {"here"}) if "task_given" in drv and not isinstance(drv["task_given"], bool): bad.append("driver.task_given: true or false - whether the driver is told when the agent is given its task") bad += _mcp_servers(d.get("mcp_servers"), isinstance(drv, dict) and "install" in drv) diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py new file mode 100644 index 000000000..c2db7b0ff --- /dev/null +++ b/app/nullius/standard/runner/units.py @@ -0,0 +1,313 @@ +"""A benchmark's tasks listed with what each is about, searched and counted by category: what +``nullius standard units`` prints and what a page asks for, a page at a time (``find``). + +The driver is started as ``prove`` starts it, with the options given and the others at their defaults, after +the same preparation as a run's: the upstream at its tested commit, the dataset's file checked by its +sha256, the driver's own environment, each made once when it is not there. A definition whose +``driver.list_command`` names a lighter start (the standard library and the dataset's files alone) is +listed by it instead, after the upstream and the dataset alone: its driver's environment is never made for +a listing. A run checks its ids with the driver all the same. The driver is given no licence and no key, +and it starts no unit. Its ``units`` gives the ids; when its definition says ``driver.describe``, its +``describe`` gives each a title, a text and named categories, read from the dataset's files alone. A driver +without it gives ids, and a search reads the ids. ``state`` says, before a listing and with no side effect, +whether it is in the cache, what a first listing fetches, or why it cannot be made. + +The listing is kept in the user cache (``paths.cache_dir()``, ``standard-units//``) under a digest +of what makes it: the benchmark's definition, the files its driver (or its listing command) is started +with, the dataset and the option values. +The same listing again reads that file and starts nothing. + +A search is words: a task matches when each word is in its id, its title or its text, whatever the case. A +category filter is FIELD=VALUE: values of one field widen the match (either), fields narrow it (both). Each +field's values are counted over the tasks the search and the other fields' filters match, so a value chosen +leaves its field's other values counted. +""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import tempfile +from typing import Dict, List, Optional + +from nullius import ondisk, paths +from nullius.standard.contract import definitions +from nullius.standard.protocols import jsonl +from nullius.standard.requirements import install +from nullius.standard.runner import run + +PAGE = 100 # tasks a page +FOLDER = "standard-units" +SECONDS = 300 # a driver's time for each of its two answers + + +class Refused(Exception): + """The listing cannot be made as asked; the message says why.""" + + +class NotFound(Refused): + """No such benchmark or dataset.""" + + +def dataset_of(bench: dict, dataset: Optional[str]) -> dict: + ids = [d["id"] for d in bench.get("datasets") or []] + if not dataset: + raise Refused(f"--dataset: one of {', '.join(ids)}") + got = next((d for d in bench.get("datasets") or [] if d["id"] == dataset), None) + if got is None: + raise NotFound(f"{bench.get('label') or bench['key']} has no dataset {dataset!r}: {', '.join(ids)}") + return got + + +def option_values(bench: dict, dataset: str, given: Optional[dict] = None) -> Dict[str, str]: + """The options the driver lists under: those given, the others at their defaults.""" + values, bad = definitions.bench_options_of(bench, dataset, given) + if bad: + raise Refused("; ".join(bad)) + return {str(k): str(v) for k, v in sorted(values.items())} + + +def categories_of(given: Optional[List[str]]) -> Dict[str, List[str]]: + """``--category FIELD=VALUE`` (repeatable): the values asked of each field, in the order given.""" + out: Dict[str, List[str]] = {} + for word in given or []: + field, eq, value = str(word).partition("=") + if not eq or not field.strip() or not value.strip(): + raise Refused(f"--category {word}: FIELD=VALUE") + values = out.setdefault(field.strip(), []) + if value.strip() not in values: + values.append(value.strip()) + return out + + +def filter_text(search: str = "", categories: Optional[Dict[str, List[str]]] = None) -> str: + """The filter as the command line gives it, for a note.""" + words = ([f"--search {json.dumps(search, ensure_ascii=False)}"] if search else []) + words += [f"--category {f}={v}" for f, values in (categories or {}).items() for v in values] + return " ".join(words) + + +def _light(bench: dict) -> Optional[List[str]]: + """The definition's ``driver.list_command``: a start that answers ``units`` and ``describe`` with the + standard library and the dataset's files alone; None when it names none.""" + return (bench.get("driver") or {}).get("list_command") or None + + +def _digest(bench: dict, ds: dict, values: dict) -> str: + h = hashlib.sha256() + definition = {k: v for k, v in bench.items() if not k.startswith("_") or k == "_version"} + h.update(json.dumps([definition, ds, values], sort_keys=True, default=str).encode()) + here = bench.get("_here") + for word in _light(bench) or (bench.get("driver") or {}).get("command") or []: + # the files the driver is started with, beside its definition: a change to its code lists again + path = str(word).replace("{here}", here or "") if str(word).startswith("{here}/") else None + if path and os.path.isfile(path): + h.update(str(word).encode() + b"\0" + ondisk.sha256_of(path).encode()) + return h.hexdigest() + + +def _cache_contained(path: str) -> str: + root = os.path.realpath(paths.cache_dir()) + resolved = os.path.realpath(path) + if os.path.commonpath((resolved, root)) != root: + raise Refused(f"{path}: outside the cache root {root}") + return resolved + + +def cache_path(bench: dict, ds: dict, values: dict) -> str: + return _cache_contained(os.path.join(paths.cache_dir(), FOLDER, bench["key"], _digest(bench, ds, values) + ".json")) + + +def _start(bench: dict, ds: dict, values: dict, work: str) -> jsonl.Proc: + light = _light(bench) + try: + up = install.upstream(bench) + data = install.dataset(bench, ds, up) + cmd, extra = (install.words(light, {"here": bench["_here"]}), {}) if light else install.driver_argv(bench) + except (install.InstallFailed, OSError) as e: + raise Refused(f"cannot prepare {bench['key']}'s dataset {ds['id']} for its listing: {e}") + home, cwd = os.path.join(work, "driver-home"), os.path.join(work, "driver") + os.makedirs(home) + os.makedirs(cwd) + env = run.base_env(home, {**extra, "NULLIUS_UPSTREAM": up or "", "NULLIUS_DATASET": data or "", + "NULLIUS_DATASET_ID": ds["id"], "PYTHONPATH": run.driver_path(), + "PYTHONDONTWRITEBYTECODE": "1", "NULLIUS_VERSION": str(bench.get("_version") or ""), + **run.option_env(values)}) + try: + return jsonl.Proc(cmd, cwd, env, os.path.join(work, "driver.log")).start() + except OSError as e: + raise Refused(f"cannot start {bench['key']}'s driver for its listing: {e}") + + +def _described(got: object, ids: List[str]) -> Dict[str, dict]: + """``describe``'s reply checked: {"units": {ID: {"title", "text", "categories": {FIELD: VALUE}}}}.""" + units = got.get("units") if isinstance(got, dict) else None + if not isinstance(units, dict): + raise Refused("describe: the reply holds no units mapping") + out = {} + for u in ids: + d = units.get(u) or {} + cats = d.get("categories") if isinstance(d.get("categories"), dict) else {} + out[u] = {"title": str(d.get("title") or ""), "text": str(d.get("text") or ""), + "categories": {str(k): str(v) for k, v in cats.items() if v is not None and str(v) != ""}} + return out + + +def _list(bench: dict, ds: dict, values: dict) -> dict: + folder = _cache_contained(os.path.join(paths.cache_dir(), FOLDER)) + os.makedirs(folder, exist_ok=True) + work = tempfile.mkdtemp(prefix=".listing-", dir=folder) + try: + p = _start(bench, ds, values, work) + try: + ids = [str(u) for u in p.request("units", dataset=ds["id"], timeout=SECONDS).get("units") or []] + said = (_described(p.request("describe", dataset=ds["id"], timeout=SECONDS), ids) + if (bench.get("driver") or {}).get("describe") else {}) + except jsonl.Failed as e: + raise Refused(f"{bench['key']}'s driver could not list the dataset {ds['id']}: {e}") + finally: + p.close() + finally: + shutil.rmtree(work, ignore_errors=True) + tasks = [{"id": u, **said.get(u, {"title": "", "text": "", "categories": {}})} for u in ids] + return {"described": bool(said), "tasks": tasks} + + +def listing(bench: dict, dataset: str, options: Optional[dict] = None) -> dict: + """{described, tasks: [{id, title, text, categories}]}: every task of the dataset under the options, in + the driver's order, from the cache when it holds this listing.""" + ds = dataset_of(bench, dataset) + values = option_values(bench, ds["id"], options) + path = cache_path(bench, ds, values) + try: + with open(path, encoding="utf-8") as f: + got = json.load(f) + if isinstance(got, dict) and isinstance(got.get("tasks"), list): + return got + except (OSError, ValueError): + pass + got = _list(bench, ds, values) + path = _cache_contained(path) + os.makedirs(os.path.dirname(path), exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".units-", suffix=".json", dir=os.path.dirname(path)) + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(got, f, ensure_ascii=False) + os.replace(tmp, path) + return got + + +def _cached(path: str) -> bool: + try: + with open(path, encoding="utf-8") as f: + got = json.load(f) + return isinstance(got, dict) and isinstance(got.get("tasks"), list) + except (OSError, ValueError): + return False + + +def _program(word: str) -> Optional[str]: + """The program a command's first word names, when it is not on this machine.""" + there = os.access(word, os.X_OK) if os.sep in word else shutil.which(word) is not None + return None if there else word + + +def state(bench: dict, dataset: str, options: Optional[dict] = None) -> dict: + """What a listing of ``dataset`` under ``options`` needs before it is made, said without making, fetching or + starting anything: {state, fetch: [{what, text}], reason}. ``state`` is one of + + - ``cached``: the listing is in the cache; ``find`` reads it and starts nothing. + - ``light``: the definition's ``driver.list_command`` makes it with the standard library and the dataset's + files; ``fetch`` names what is fetched first (``upstream``, ``dataset``), empty when it is here. + - ``full``: the driver makes it from its own environment on this machine; ``fetch`` also names that + environment (``environment``) when it is not installed. + - ``refused``: it cannot be made; ``reason`` says why (an option, a program not on this machine, a + dataset's file not there). + + ``reason`` is empty but for ``refused``. Raises ``NotFound`` for a dataset the benchmark does not have.""" + ds = dataset_of(bench, dataset) + key = bench["key"] + + def refused(why: str) -> dict: + return {"state": "refused", "fetch": [], "reason": why} + + try: + values = option_values(bench, ds["id"], options) + path = cache_path(bench, ds, values) + except Refused as e: + return refused(str(e)) + if _cached(path): + return {"state": "cached", "fetch": [], "reason": ""} + prepare = f"cannot prepare {key}'s dataset {ds['id']} for its listing: " + fetch, needs = [], [] + up = bench.get("upstream") or {} + up_dir = install.upstream_dir(bench) + if up_dir and not install.ready(up_dir): + fetch.append({"what": "upstream", "text": f"the upstream {up['repository']} at {str(up['tested'])[:12]}"}) + needs.append("git") + if ds.get("url"): + if not os.path.isfile(install.download_path(ds["url"], ds["sha256"])): + fetch.append({"what": "dataset", "text": f"the dataset {ds['url']}"}) + elif ds.get("path") and (not up_dir or install.ready(up_dir)): + if not os.path.isfile(os.path.join(up_dir or bench["_here"], ds["path"])): + folder = "upstream" if up_dir else "definition folder" + return refused(prepare + f"dataset {ds['id']}: {ds['path']} is not in the {folder}") + light = _light(bench) + if not light: + inst = definitions.driver_install(bench)["install"] + where = install.driver_dir(bench) + if where and not install.ready(where): + tools = (["uv"] if any(inst.get(k) for k in ("pip", "project", "indexes", "wheels")) else []) \ + + (["npm"] if inst.get("npm") else []) + fetch.append({"what": "environment", + "text": "the driver's environment" + (f", installed with {' and '.join(tools)}" if tools else "")}) + needs += tools + first = (light or (bench.get("driver") or {}).get("command") or [""])[0] + if first and "{install}" not in first: # a program of the machine's, or a file beside the definition + needs.append(install.words([first], {"here": bench["_here"]})[0]) + missing = next((w for w in needs if _program(w)), None) + if missing: + return refused(prepare + f"{missing} is not on this machine") + return {"state": "light" if light else "full", "fetch": fetch, "reason": ""} + + +def _matches(task: dict, words: List[str]) -> bool: + hay = " ".join((task["id"], task["title"], task["text"])).lower() + return all(w in hay for w in words) + + +def find(bench: dict, dataset: str, options: Optional[dict] = None, search: str = "", + categories: Optional[Dict[str, List[str]]] = None, page: int = 1, size: Optional[int] = PAGE) -> 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: + {total, page, pages, of, described, tasks: [{id, title, text, categories}], + categories: {FIELD: [{value, count}, ...]}}. ``total`` counts every match, ``of`` the dataset's tasks; + each field's values are counted over the tasks the search and the other fields' filters match, the most + first. A field no task has is refused; a page past the last is empty.""" + if not isinstance(page, int) or page < 1: + raise Refused(f"page {page}: 1, 2, ...") + got = listing(bench, dataset, options) + tasks, chosen = got["tasks"], categories or {} + fields = sorted({f for t in tasks for f in t["categories"]}) + unknown = [f for f in chosen if f not in fields] + if unknown: + raise Refused(f"--category {unknown[0]}: no such category" + + (f"; the categories are {', '.join(fields)}" if fields else "; these tasks have none")) + words = [w for w in str(search or "").lower().split() if w] + searched = [t for t in tasks if _matches(t, words)] + + def kept(t: dict, but: Optional[str] = None) -> bool: + return all(t["categories"].get(f) in values for f, values in chosen.items() if f != but) + + matched = [t for t in searched if kept(t)] + counts = {} + for f in fields: + n: Dict[str, int] = {} + for t in searched: + if f in t["categories"] and kept(t, but=f): + n[t["categories"][f]] = n.get(t["categories"][f], 0) + 1 + counts[f] = [{"value": v, "count": c} for v, c in sorted(n.items(), key=lambda vc: (-vc[1], vc[0]))] + per = size if size else max(1, len(matched)) + start = (page - 1) * per + return {"total": len(matched), "page": page, "pages": max(1, -(-len(matched) // per)), "of": len(tasks), + "described": got["described"], "tasks": matched[start:start + per], "categories": counts} diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index 2e465487d..e05476dbe 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -108,6 +108,7 @@ nav: - Conform an agent or a capability: cli/conform.md - Fidelity: cli/fidelity.md - Shard and merge: cli/shard-and-merge.md + - Task sets: cli/task-sets.md - Pages from a shell: cli/pages.md - Exit codes and output: cli/exit-codes.md - Settings: diff --git a/app/tests/test_cli_contract.py b/app/tests/test_cli_contract.py index 06c25f587..3863043a9 100644 --- a/app/tests/test_cli_contract.py +++ b/app/tests/test_cli_contract.py @@ -289,6 +289,43 @@ def test_a_key_in_the_recorded_command_is_not_echoed_by_show_json(self): self.assertNotIn(KEY, out.stdout) +# ── task-sets.md ──────────────────────────────────────────────────────────── + +class TaskSetCommands(Scratch): + def test_help_and_refusals_of_the_task_set_commands(self): + """The units command has help with its examples and exit codes; a + refusal is one line on stderr with nothing on stdout, 2 for a usage + error or a refusal, 3 for what is not found, and writes nothing.""" + cat = os.path.join(self.tmp, "catalogue") + env = {"NULLIUS_CATALOGUE": cat, "NULLIUS_HOME": os.path.join(self.tmp, "profile")} + for sub in (("units",),): + with self.subTest(help=sub): + out = self.sh("standard.cli", *sub, "--help", env=env) + self.assertEqual(out.returncode, 0, out.stderr) + for line in ("usage:", "examples:", "exit codes:"): + self.assertIn(line, out.stdout) + self.assertEqual(out.stderr, "") + cases = [ + (["units", "humaneval"], 2, "usage:"), + (["units", "humaneval", "--dataset", "nope"], 3, "no dataset 'nope'"), + (["units", "no-such-bench", "--dataset", "x"], 3, "no benchmark"), + (["units", "humaneval", "--dataset", "humaneval", "--category", "kind"], 2, "FIELD=VALUE"), + ] + for args, code, said in cases: + with self.subTest(args=args): + out = self.sh("standard.cli", *args, env=env) + self.assertEqual(out.returncode, code, out.stderr) + self.assertIn(said, out.stderr) + self.assertEqual(out.stdout, "") + # a listing that needs a program this machine lacks is refused before it fetches anything + out = self.sh("standard.cli", "units", "humaneval", "--dataset", "humaneval", + env=dict(env, PATH=os.path.join(self.tmp, "no-programs"))) + self.assertEqual((out.returncode, out.stdout), (2, "")) + self.assertEqual(out.stderr, "refused: cannot prepare humaneval's dataset humaneval for its listing: " + "git is not on this machine\n") + self.assertFalse(os.path.exists(cat)) + + # ── import.md ─────────────────────────────────────────────────────────────── class ImportContract(Scratch): diff --git a/app/tests/test_locomo_rag.py b/app/tests/test_locomo_rag.py index beb6e227b..74ebadb1c 100644 --- a/app/tests/test_locomo_rag.py +++ b/app/tests/test_locomo_rag.py @@ -107,6 +107,21 @@ def close(self): self.p.stdout.close() +class Listing(unittest.TestCase): + def test_describe_gives_question_text_and_excludes_category_five(self): + with tempfile.TemporaryDirectory() as root: + driver = Driver(root, {}) + try: + ids = driver.ask(op="units", dataset="locomo10")["units"] + got = driver.ask(op="describe", dataset="locomo10") + finally: + driver.close() + self.assertEqual(got, {"units": {"conv-1:0": {"title": "What did A say?", "text": "What did A say?", + "categories": {"category": "4"}}}}) + self.assertEqual(list(got["units"]), ids) + self.assertIs(BENCH["driver"].get("describe"), True) + + class Retrieval(unittest.TestCase): def run_unit(self, **options): with tempfile.TemporaryDirectory() as root: diff --git a/app/tests/test_longmemeval_setups.py b/app/tests/test_longmemeval_setups.py index e3959b4c8..a1d6f7b5f 100644 --- a/app/tests/test_longmemeval_setups.py +++ b/app/tests/test_longmemeval_setups.py @@ -166,6 +166,18 @@ def run_driver(self, reqs, options, keep=None, questions=None, files=None): out = subprocess.run([sys.executable, DRIVER], input=lines, capture_output=True, text=True, env=env, timeout=60) return [json.loads(ln) for ln in out.stdout.splitlines()] + def test_describe_gives_question_text_and_respects_the_type_filter(self): + for kind in ("all", "knowledge-update"): + with self.subTest(kind=kind): + got = self.run_driver([{"op": "units", "dataset": "longmemeval_oracle"}, + {"op": "describe", "dataset": "longmemeval_oracle"}], + {"question_type": kind}, questions=self.QUESTIONS) + expected = {qid: {"title": "Q?", "text": "Q?", "categories": {"question_type": category}} + for qid, category in self.QUESTIONS if kind == "all" or category == kind} + self.assertEqual(got[1], {"units": expected}) + self.assertEqual(list(got[1]["units"]), got[0]["units"]) + self.assertIs(BENCH["driver"].get("describe"), True) + def test_the_original_runs_run_generation_as_the_script_does_and_scores_with_evaluate_qa(self): judge = {"model": "gpt-4o-2024-08-06", "base_url": "http://judge/v1", "key": "k"} got = self.run_driver([ diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py new file mode 100644 index 000000000..9ce9b6418 --- /dev/null +++ b/app/tests/test_standard_units_listing.py @@ -0,0 +1,512 @@ +"""The listing of a dataset's tasks (``standard/runner/units.py``, ``nullius standard units``): a search by the words +of an id, a title or a text; category values, either within a field and both across fields, each value +counted; 100 tasks a page with the total on every page; a driver without ``describe`` listed and searched by +its ids; the listing cached by its options; ``set create --search`` and ``--category`` storing the ids the +listing gives and the filter in its note; OSWorld1's ``describe`` from its task files. A definition's +``driver.list_command`` listing with no driver environment, OSWorld1's giving the driver's ids in its order; +``state`` giving each of its answers and starting nothing; the command's one line before a first listing that +fetches. No key, no network: each driver is a script of the test's own, the fake benchmark's or OSWorld1's on +task files of the test's own.""" +from __future__ import annotations + +import contextlib +import io +import json +import os +import shutil +import sys +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius import paths +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.runner import units + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +OSWORLD1 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "catalogue", + "benchmarks", "osworld1") +# 250 tasks: t000 ... t249; kind by i % 3, size by i % 2; under mode=short only the first 20 +DRIVER = r'''import json, os, sys +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "started"), "a") as f: + f.write("started\n") +KINDS = ("alpha", "beta", "gamma") +N = 20 if os.environ.get("NULLIUS_OPTION_MODE") == "short" else 250 +IDS = [f"t{i:03d}" for i in range(N)] +def about(i): + title = "Open the spreadsheet" if i == 7 else f"Task number {i}" + text = "Rename the folder called Quokka" if i == 11 else f"Do thing {i} on the desktop" + return {"title": title, "text": text, "categories": {"kind": KINDS[i % 3], "size": "small" if i % 2 else "large"}} +for line in sys.stdin: + req = json.loads(line) + op = req.pop("op") + if op == "units": + out = {"units": IDS} + elif op == "describe": + out = {"units": {u: about(i) for i, u in enumerate(IDS)}} + else: + out = {"error": "no such op"} + print(json.dumps(out), flush=True) +''' +MODE = {"mode": {"summary": "how many tasks the listing gives", "values": ["long", "short"], "default": "long"}} + + +class Scratch(unittest.TestCase): + """A profile and a catalogue of the test's own; ``self.b`` a benchmark whose driver describes 250 tasks.""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="nullius-units-") + self.addCleanup(shutil.rmtree, self.tmp, True) + self.cat = os.path.join(self.tmp, "catalogue") + here = os.path.join(self.tmp, "described") + os.makedirs(here) + with open(os.path.join(here, "driver.py"), "w") as f: + f.write(DRIVER) + self.started = os.path.join(here, "started") + fake = definitions.get("benchmark", "fakebench", ROOT) + self.b = dict(fake, key="described", label="Described bench", _here=here, options=MODE, + datasets=[{"id": "all", "units": 250}], + driver={"command": [sys.executable, "{here}/driver.py"], "describe": True}) + self.plain = dict(fake) + for patch in (mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": self.cat, + "NULLIUS_HOME": os.path.join(self.tmp, "profile")}), + mock.patch.object(cli, "_find_bench", side_effect=lambda key: {"described": self.b, + "fakebench": self.plain}.get(key)), + mock.patch.object(cli.settings, "load")): + patch.start() + self.addCleanup(patch.stop) + + def starts(self) -> int: + if not os.path.exists(self.started): + return 0 + with open(self.started) as f: + return len(f.read().splitlines()) + + def cli(self, *args): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + code = cli.main(list(args)) + return code, out.getvalue(), err.getvalue() + + def ids(self, got): + return [t["id"] for t in got["tasks"]] + + +class Search(Scratch): + def test_a_word_of_an_id_a_title_or_a_text_finds_its_tasks_whatever_the_case(self): + for search, want in (("t042", ["t042"]), ("SPREADSHEET", ["t007"]), ("quokka folder", ["t011"]), + ("number 24", ["t024", "t124", "t224"] + [f"t{i}" for i in range(240, 250)])): + with self.subTest(search=search): + got = units.find(self.b, "all", search=search) + self.assertEqual((self.ids(got), got["total"], got["of"]), (want, len(want), 250)) + t = units.find(self.b, "all", search="t011")["tasks"][0] + self.assertEqual(t, {"id": "t011", "title": "Task number 11", "text": "Rename the folder called Quokka", + "categories": {"kind": "gamma", "size": "small"}}) + + def test_no_match_gives_an_empty_page_and_a_total_of_0(self): + got = units.find(self.b, "all", search="wombat") + self.assertEqual((got["tasks"], got["total"], got["pages"], got["of"]), ([], 0, 1, 250)) + self.assertEqual(got["categories"], {"kind": [], "size": []}) + + +class Categories(Scratch): + def test_one_value_two_values_of_one_field_and_two_fields_together(self): + one = units.find(self.b, "all", categories={"kind": ["alpha"]}, size=None) + self.assertEqual(one["total"], 84) # 0, 3, ..., 249 + self.assertTrue(all(t["categories"]["kind"] == "alpha" for t in one["tasks"])) + either = units.find(self.b, "all", categories={"kind": ["alpha", "beta"]}, size=None) + self.assertEqual(either["total"], 84 + 83) + both = units.find(self.b, "all", categories={"kind": ["alpha"], "size": ["small"]}, size=None) + self.assertEqual(both["total"], 42) # the odd ones of 0, 3, ..., 249 + self.assertTrue(all(t["categories"] == {"kind": "alpha", "size": "small"} for t in both["tasks"])) + + def test_each_value_is_counted_over_the_search_and_the_other_fields_filters(self): + got = units.find(self.b, "all") + self.assertEqual(got["categories"], {"kind": [{"value": "alpha", "count": 84}, {"value": "beta", "count": 83}, + {"value": "gamma", "count": 83}], + "size": [{"value": "large", "count": 125}, {"value": "small", "count": 125}]}) + chosen = units.find(self.b, "all", categories={"kind": ["alpha"]}) + # the field chosen keeps its other values' counts; the other field is counted over the alpha tasks + self.assertEqual(chosen["categories"]["kind"], got["categories"]["kind"]) + self.assertEqual(chosen["categories"]["size"], [{"value": "large", "count": 42}, {"value": "small", "count": 42}]) + searched = units.find(self.b, "all", search="number 24", categories={"size": ["small"]}) + self.assertEqual(self.ids(searched), ["t241", "t243", "t245", "t247", "t249"]) + self.assertEqual(searched["categories"]["size"], [{"value": "large", "count": 8}, {"value": "small", "count": 5}]) + + def test_a_field_no_task_has_is_refused(self): + with self.assertRaisesRegex(units.Refused, "--category colour: no such category; the categories are kind, size"): + units.find(self.b, "all", categories={"colour": ["red"]}) + self.assertEqual(units.find(self.b, "all", categories={"kind": ["delta"]})["total"], 0) + + +class Pages(Scratch): + def test_250_tasks_come_as_three_pages_with_the_same_total(self): + pages = [units.find(self.b, "all", page=n) for n in (1, 2, 3, 4)] + self.assertEqual([len(p["tasks"]) for p in pages], [100, 100, 50, 0]) + self.assertEqual({(p["total"], p["pages"]) for p in pages}, {(250, 3)}) + self.assertEqual(sum((self.ids(p) for p in pages), []), [f"t{i:03d}" for i in range(250)]) + with self.assertRaisesRegex(units.Refused, "page 0"): + units.find(self.b, "all", page=0) + + +class WithoutDescribe(Scratch): + def test_the_listing_gives_ids_and_a_search_matches_ids(self): + got = units.find(self.plain, "all") + self.assertEqual((self.ids(got), got["described"], got["categories"]), (["good", "wrong", "slow", "model"], False, {})) + self.assertEqual(got["tasks"][0], {"id": "good", "title": "", "text": "", "categories": {}}) + self.assertEqual(self.ids(units.find(self.plain, "all", search="MOD")), ["model"]) + with self.assertRaisesRegex(units.Refused, "no such category; these tasks have none"): + units.find(self.plain, "all", categories={"kind": ["alpha"]}) + code, out, err = self.cli("units", "fakebench", "--dataset", "all", "--search", "od") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.splitlines(), ["2 of 4 tasks of all (its driver gives ids alone: a search reads the ids)", + " good", " model"]) + + +class Cache(Scratch): + def test_cache_links_cannot_read_or_write_outside_the_cache_root(self): + path = Path(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"})) + outside = Path(self.tmp, "outside-cache") + outside.mkdir() + cached = outside / "listing.json" + cached.write_text(json.dumps({"tasks": [], "described": False})) + for link, target in ((path.parent.parent, outside), (path.parent, outside), (path, cached)): + with self.subTest(link=link.name): + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(target, target_is_directory=target.is_dir()) + before = {p.name: p.read_bytes() for p in outside.iterdir()} + try: + with self.assertRaisesRegex(units.Refused, "outside the cache root"): + units.listing(self.b, "all") + self.assertEqual(units.state(self.b, "all")["state"], "refused") + self.assertEqual(self.starts(), 0) + self.assertEqual({p.name: p.read_bytes() for p in outside.iterdir()}, before) + finally: + link.unlink() + + def test_a_linked_cache_root_keeps_the_listing_under_its_resolved_root(self): + root = Path(paths.cache_dir()) + destination = Path(self.tmp, "cache-disk") + destination.mkdir() + root.parent.mkdir(parents=True, exist_ok=True) + root.symlink_to(destination, target_is_directory=True) + got = units.listing(self.b, "all") + path = Path(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"})) + self.assertTrue(path.resolve().is_relative_to(destination)) + self.assertEqual(json.loads(path.read_text()), got) + self.assertEqual(units.state(self.b, "all")["state"], "cached") + self.assertEqual(units.listing(self.b, "all"), got) + self.assertEqual(self.starts(), 1) + + def test_the_second_listing_starts_no_driver_and_another_option_lists_again(self): + units.find(self.b, "all") + units.find(self.b, "all", search="t1", page=2) + self.assertEqual(self.starts(), 1) + short = units.find(self.b, "all", {"mode": "short"}) + self.assertEqual((short["total"], self.starts()), (20, 2)) + units.find(self.b, "all", {"mode": "long"}) # the default, given: the same listing + self.assertEqual(self.starts(), 2) + self.assertTrue(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"}).startswith(paths.cache_dir())) + with self.assertRaisesRegex(units.Refused, "mode"): + units.find(self.b, "all", {"mode": "sideways"}) + with self.assertRaisesRegex(units.NotFound, "no dataset 'nope'"): + units.find(self.b, "nope") + + def test_a_driver_that_cannot_list_is_refused_with_its_words(self): + with open(os.path.join(self.b["_here"], "driver.py"), "w") as f: + f.write("import sys\nprint('the data is not there', file=sys.stderr)\nsys.exit(3)\n") + with self.assertRaisesRegex(units.Refused, "could not list the dataset all: .*the data is not there"): + units.find(self.b, "all") + self.assertEqual(os.listdir(os.path.join(paths.cache_dir(), units.FOLDER)), []) # nothing kept, no work left + + +class CommandLine(Scratch): + def test_the_command_prints_the_count_the_categories_and_the_tasks(self): + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "number 24", + "--category", "size=small") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.splitlines(), ["5 of 250 tasks of all", "kind: alpha 2, beta 2, gamma 1", "size: large 8, small 5", + " t241 Task number 241", " t243 Task number 243", " t245 Task number 245", + " t247 Task number 247", " t249 Task number 249"]) + code, out, err = self.cli("units", "described", "--dataset", "all", "--category", "kind=beta", "--json") + got = json.loads(out) + self.assertEqual((code, got["total"], got["pages"], len(got["tasks"])), (0, 83, 1, 83)) + + def test_the_longmemeval_help_example_names_a_known_dataset(self): + import shlex + example = next(line for line in cli.UNITS_EPILOG.splitlines() if "units longmemeval" in line) + args = shlex.split(example) + bench = definitions.get("benchmark", "longmemeval") + dataset = args[args.index("--dataset") + 1] + self.assertEqual(units.dataset_of(bench, dataset)["id"], "longmemeval_oracle") + self.assertEqual(units.option_values(bench, dataset, {"question_type": "multi-session"})["question_type"], + "multi-session") + + def test_refusals_are_one_line_on_stderr(self): + for args, code, said in ((["units", "nowhere", "--dataset", "all"], 3, "no benchmark 'nowhere'"), + (["units", "described", "--dataset", "nope"], 3, "no dataset 'nope'"), + (["units", "described", "--dataset", "all", "--category", "kind"], 2, "FIELD=VALUE"), + (["units", "described", "--dataset", "all", "--bench-option", "mode=x"], 2, "mode"), + (["units", "described", "--dataset", "all", "--bench-option", "broken"], 2, "NAME=VALUE")): + with self.subTest(args=args): + got, out, err = self.cli(*args) + self.assertEqual((got, out), (code, "")) + self.assertTrue(err.startswith("refused: ") and said in err and len(err.splitlines()) == 1, err) + + +ASKED = AssertionError("the listing asked for the driver's environment") +HEAVY = {"command": ["{install}/.venv/bin/python", "{here}/driver.py"], + "install": {"python": "3.12", "pip": ["nothing-installed==1.0"]}, "describe": True} + + +def no_environment(): + """Each way to the driver's environment fails the test.""" + stack = contextlib.ExitStack() + for name in ("driver_argv", "driver_packages", "packages"): + stack.enter_context(mock.patch.object(units.install, name, side_effect=ASKED)) + return stack + + +class LightCommand(Scratch): + def test_the_light_command_lists_and_the_drivers_environment_is_never_asked_for(self): + light = dict(self.b, driver=dict(HEAVY, list_command=[sys.executable, "{here}/driver.py"])) + with no_environment(): + got = units.find(light, "all", size=None) + self.assertEqual((got["total"], got["described"], self.starts()), (250, True, 1)) + self.assertEqual(got["tasks"], units.find(self.b, "all", size=None)["tasks"]) # as the driver's own start + with mock.patch.object(units.install, "upstream", return_value=None) as up, \ + mock.patch.object(units.install, "dataset", return_value=None) as data, no_environment(): + units.listing(dict(light, options={}), "all") # another definition: listed again + self.assertEqual((up.call_count, data.call_count), (1, 1)) # the upstream and the dataset, prepared + + def test_a_light_command_that_cannot_start_is_refused(self): + light = dict(self.b, driver=dict(HEAVY, list_command=["/nonexistent/python3", "{here}/driver.py"])) + with no_environment(), self.assertRaisesRegex(units.Refused, "cannot start described's driver for its listing"): + units.listing(light, "all") + + +class Definition(unittest.TestCase): + def test_a_list_command_is_checked_as_the_other_commands_are(self): + bench = {"schema": "nullius.benchmark/v1", "key": "fixture", "label": "Fixture", "summary": "A task.", + "family": "agent", "needs": ["agent.task/v1"], "driver": dict(HEAVY), + "datasets": [{"id": "all", "units": 1}], "units": {"noun": "task", "nouns": "tasks"}, + "score": {"kind": "pass", "says": "the answer is right"}} + ok = dict(bench, driver=dict(HEAVY, list_command=["python3", "{here}/driver.py"])) + self.assertEqual(definitions.problems(ok, "benchmark"), []) + for words, said in (([], "driver.list_command: a list of words"), + ("python3 {here}/driver.py", "driver.list_command: a list of words"), + (["python3", 3], "driver.list_command: a list of words"), + (["python3 -I", "{here}/driver.py"], "driver.list_command: 'python3 -I' is not a plain word"), + (["{install}/.venv/bin/python", "{here}/driver.py"], + "driver.list_command: {install} is not a slot (here)")): + with self.subTest(words=words): + self.assertIn(said, definitions.problems(dict(bench, driver=dict(HEAVY, list_command=words)), "benchmark")) + with open(os.path.join(OSWORLD1, "standard.json"), encoding="utf-8") as f: + osworld1 = json.load(f) + # its agent option is filled from its agents.json on loading: each version is checked as the loader reads it + for ref in ("osworld1", "osworld1@044bc33"): + with self.subTest(ref=ref): + self.assertEqual(definitions.problems(definitions.get("benchmark", ref, root=definitions.CATALOGUE), "benchmark"), []) + self.assertEqual(osworld1["driver"]["list_command"][1:], osworld1["driver"]["command"][1:]) + for v, block in osworld1["versions"].items(): # a version's driver replaces the shared one whole + driver = block.get("driver") or osworld1["driver"] + with self.subTest(version=v): + self.assertIs(driver.get("describe"), True) + self.assertEqual(driver.get("list_command"), osworld1["driver"]["list_command"]) + + +class State(Scratch): + """``units.state`` asked with every fetch and start failing the test, the files it could touch the same after.""" + + def tree(self) -> list: + got = [] + for top in (self.tmp, units.install.HOME): + for root, dirs, files in os.walk(top): + for name in dirs + files: + path = os.path.join(root, name) + got.append((path, Path(path).read_bytes() if name in files else None)) + return sorted(got) + + def asked(self, bench, dataset="all", options=None, programs=("git", "uv", "npm")): + before, started = self.tree(), self.starts() + with contextlib.ExitStack() as stack: + for name in ("upstream", "dataset", "download", "driver_argv", "driver_packages", "packages"): + stack.enter_context(mock.patch.object(units.install, name, side_effect=AssertionError(name))) + stack.enter_context(mock.patch.object(units.jsonl, "Proc", side_effect=AssertionError("a driver started"))) + stack.enter_context(mock.patch.object(units.shutil, "which", + side_effect=lambda w: f"/usr/bin/{w}" if w in programs else None)) + got = units.state(bench, dataset, options) + self.assertEqual((self.tree(), self.starts()), (before, started)) + return got + + def fetching(self, **driver) -> dict: + return dict(self.b, upstream={"repository": "https://example.org/upstream.git", "tested": "a" * 40}, + datasets=[{"id": "all", "url": "https://example.org/all.json", "sha256": "b" * 64, "units": 250}], + driver=dict(HEAVY, **driver)) + + def test_cached(self): + units.find(self.b, "all") + self.assertEqual(self.asked(self.b), {"state": "cached", "fetch": [], "reason": ""}) + self.assertEqual(self.asked(self.b, options={"mode": "short"})["state"], "full") # not listed under it + + def test_light_and_what_it_fetches(self): + light = [sys.executable, "{here}/driver.py"] + self.assertEqual(self.asked(dict(self.b, driver=dict(HEAVY, list_command=light))), + {"state": "light", "fetch": [], "reason": ""}) + got = self.asked(self.fetching(list_command=light)) + self.assertEqual((got["state"], got["reason"]), ("light", "")) + self.assertEqual(got["fetch"], [{"what": "upstream", "text": "the upstream https://example.org/upstream.git at aaaaaaaaaaaa"}, + {"what": "dataset", "text": "the dataset https://example.org/all.json"}]) + + def test_a_prepared_upstream_must_hold_the_datasets_file(self): + up = Path(self.tmp, "upstream") + up.mkdir() + bench = dict(self.fetching(list_command=[sys.executable, "{here}/driver.py"]), + datasets=[{"id": "all", "path": "absent.json", "sha256": "b" * 64, "units": 250}]) + with mock.patch.object(units.install, "upstream_dir", return_value=str(up)): + self.assertEqual(self.asked(bench)["state"], "light") + self.assertEqual([f["what"] for f in self.asked(bench)["fetch"]], ["upstream"]) + (up / units.install.MARK).touch() + got = self.asked(bench) + self.assertEqual((got["state"], got["fetch"]), ("refused", [])) + self.assertIn("absent.json is not in the upstream", got["reason"]) + + def test_a_present_dataset_is_not_checksummed_by_state(self): + data = Path(self.b["_here"], "data.json") + data.write_text("{}") + bench = dict(self.b, datasets=[{"id": "all", "path": "data.json", "sha256": "b" * 64, "units": 250}], + driver=dict(HEAVY, list_command=[sys.executable, "{here}/driver.py"])) + sha256 = units.ondisk.sha256_of + + def digest(path): + self.assertNotEqual(Path(path), data) + return sha256(path) + + with mock.patch.object(units.ondisk, "sha256_of", side_effect=digest): + self.assertEqual(self.asked(bench), {"state": "light", "fetch": [], "reason": ""}) + + def test_full_and_the_environment_it_installs(self): + self.assertEqual(self.asked(self.b), {"state": "full", "fetch": [], "reason": ""}) + got = self.asked(self.fetching()) + self.assertEqual((got["state"], [f["what"] for f in got["fetch"]]), ("full", ["upstream", "dataset", "environment"])) + self.assertEqual(got["fetch"][2]["text"], "the driver's environment, installed with uv") + + def test_refused_with_its_reason(self): + for bench, options, programs, said in ( + (self.b, {"mode": "sideways"}, ("git", "uv"), "mode"), + (self.fetching(), None, ("git",), "cannot prepare described's dataset all for its listing: " + "uv is not on this machine"), + (self.fetching(list_command=[sys.executable, "{here}/driver.py"]), None, ("uv",), "git is not on this machine"), + (dict(self.b, driver=dict(HEAVY, list_command=["python3", "{here}/driver.py"])), None, ("git",), + "python3 is not on this machine"), + (dict(self.b, datasets=[{"id": "all", "path": "absent.json", "sha256": "c" * 64, "units": 1}]), None, + ("git",), "dataset all: absent.json is not in the definition folder")): + with self.subTest(said=said): + got = self.asked(bench, options=options, programs=programs) + self.assertEqual((got["state"], got["fetch"]), ("refused", [])) + self.assertIn(said, got["reason"]) + with self.assertRaisesRegex(units.NotFound, "no dataset 'nope'"): + self.asked(self.b, "nope") + + +class FirstListing(Scratch): + def test_the_command_says_in_one_line_what_a_first_listing_fetches(self): + data = os.path.join(self.tmp, "fetched.json") + self.b = dict(self.b, datasets=[{"id": "all", "url": "https://example.org/all.json", "sha256": "b" * 64, + "units": 250}]) + + def fetched(url, sha256, progress=None): + open(data, "w").close() + return data + + with mock.patch.object(units.install, "download", side_effect=fetched) as download: + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") + self.assertEqual((code, out.splitlines()[0], err), (0, "1 of 250 tasks of all", + "first listing of all: fetching the dataset " + "https://example.org/all.json\n")) + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") + self.assertEqual((code, err, download.call_count, self.starts()), (0, "", 1, 1)) # the second from the cache + + def test_a_program_not_on_this_machine_is_refused_before_anything_is_fetched(self): + self.b = dict(self.b, driver=dict(HEAVY, list_command=["/nonexistent/python3", "{here}/driver.py"])) + with no_environment(): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual((code, out, self.starts()), (2, "", 0)) + self.assertEqual(err, "refused: cannot prepare described's dataset all for its listing: " + "/nonexistent/python3 is not on this machine\n") + + +def osworld1_upstream(tmp: str, tasks: dict) -> str: + """An upstream folder of OSWorld's shape holding ``tasks`` ({domain: {id: instruction}}); its dataset file's path.""" + for domain, ids in tasks.items(): + os.makedirs(os.path.join(tmp, "evaluation_examples", "examples", domain)) + for eid, instruction in ids.items(): + with open(os.path.join(tmp, "evaluation_examples", "examples", domain, eid + ".json"), "w") as f: + json.dump({"id": eid, "instruction": instruction}, f) + meta = os.path.join(tmp, "test_small.json") + with open(meta, "w") as f: + json.dump({d: list(ids) for d, ids in tasks.items()}, f) + return meta + + +class OSWorld1Light(Scratch): + def test_its_light_listing_gives_the_drivers_ids_in_its_order_with_no_environment(self): + up = os.path.join(self.tmp, "upstream") + meta = osworld1_upstream(up, {"vlc": {"v2": "Play the video.", "v1": "Mute it."}, "chrome": {"c1": "Open a tab."}}) + bench = definitions.get("benchmark", "osworld1") + with mock.patch.object(units.install, "upstream", return_value=up), \ + mock.patch.object(units.install, "dataset", return_value=meta), no_environment(): + got = units.listing(bench, "test_small") + earlier = units.listing(definitions.get("benchmark", "osworld1@044bc33"), "test_small") + self.assertEqual(earlier["tasks"], got["tasks"]) # each version lists by the same light start + import importlib.util + spec = importlib.util.spec_from_file_location("osworld1_driver_units", os.path.join(OSWORLD1, "driver.py")) + driver = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"NULLIUS_UPSTREAM": up, "NULLIUS_DATASET": meta}), \ + mock.patch.object(sys, "argv", ["driver.py"]): + spec.loader.exec_module(driver) + ids = driver.units(dataset="test_small")["units"] + self.assertEqual([t["id"] for t in got["tasks"]], ids) + self.assertEqual(ids, ["vlc__v2", "vlc__v1", "chrome__c1"]) + self.assertEqual(got["tasks"][0], {"id": "vlc__v2", "title": "Play the video.", "text": "Play the video.", + "categories": {"domain": "vlc"}}) + + +class OSWorld1(unittest.TestCase): + def test_describe_gives_each_tasks_instruction_and_domain_from_its_file(self): + tmp = tempfile.mkdtemp(prefix="nullius-osworld1-") + self.addCleanup(shutil.rmtree, tmp, True) + long = "Please " + "open the settings and change the theme " * 4 + "now." + tasks = {"chrome": {"c1": "Open a new tab."}, "vlc": {"v1": long}} + for domain, ids in tasks.items(): + os.makedirs(os.path.join(tmp, "evaluation_examples", "examples", domain)) + for eid, instruction in ids.items(): + with open(os.path.join(tmp, "evaluation_examples", "examples", domain, eid + ".json"), "w") as f: + json.dump({"id": eid, "instruction": instruction}, f) + meta = os.path.join(tmp, "test_small.json") + with open(meta, "w") as f: + json.dump({d: list(ids) for d, ids in tasks.items()}, f) + import importlib.util + spec = importlib.util.spec_from_file_location("osworld1_driver_describe", os.path.join(OSWORLD1, "driver.py")) + driver = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"NULLIUS_UPSTREAM": tmp, "NULLIUS_DATASET": meta}), \ + mock.patch.object(sys, "argv", ["driver.py"]): + spec.loader.exec_module(driver) + got = driver.describe(dataset="test_small")["units"] + self.assertIs(driver.HANDLERS["describe"], driver.describe) + self.assertEqual(list(got), ["chrome__c1", "vlc__v1"]) + self.assertEqual(got["chrome__c1"], {"title": "Open a new tab.", "text": "Open a new tab.", + "categories": {"domain": "chrome"}}) + self.assertEqual(got["vlc__v1"]["text"], long) + self.assertTrue(got["vlc__v1"]["title"].endswith(" ...") and len(got["vlc__v1"]["title"]) <= 104) + self.assertTrue(long.startswith(got["vlc__v1"]["title"][:-4])) + self.assertEqual(got["vlc__v1"]["categories"], {"domain": "vlc"}) + with open(os.path.join(OSWORLD1, "standard.json")) as f: + self.assertIs(json.load(f)["driver"]["describe"], True) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/cli/README.md b/docs/cli/README.md index 533fd34c2..de2aef933 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -19,6 +19,7 @@ From a source checkout, replace `nullius` with | [Conform an agent or a capability](conform.md) | `nullius standard conform` | | [Fidelity](fidelity.md) | `nullius standard fidelity` | | [Shard and merge](shard-and-merge.md) | `nullius standard run --shard`, `merge` | +| [Task sets](task-sets.md) | `nullius standard units` | | [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/task-sets.md b/docs/cli/task-sets.md new file mode 100644 index 000000000..5ed6765b5 --- /dev/null +++ b/docs/cli/task-sets.md @@ -0,0 +1,25 @@ +# Task sets + +```bash title="Commands" +nullius standard units --dataset D [--bench-option NAME=VALUE]... [--search TEXT] [--category FIELD=VALUE]... [--json] +``` + +```bash title="Examples" +nullius standard units osworld1 --dataset test_nogdrive --search tab --category domain=chrome +``` + +## Listing a dataset's tasks + +| Part | Detail | +| --- | --- | +| What it gives | Each task's id, title, text and categories, the number matched of the dataset's, and each category's values with their counts | +| Title, text, categories | From the driver's [`describe`](../standard.md#driver-ops), read from the dataset's files. A driver without it gives ids alone; a search then reads the ids | +| `--search TEXT` | The tasks whose id, title or text hold each word, whatever the case | +| `--category FIELD=VALUE` | Values of one field widen the match, fields narrow it. A field no task has is refused. Each field's values are counted over the tasks the search and the other fields match | +| `--bench-option` | The options the driver lists under; the others at their defaults | +| What it needs | The benchmark's upstream, its dataset file and its driver's environment, prepared as a run prepares them when missing; with [`driver.list_command`](../standard.md#driver-ops), the upstream and the dataset file alone. No unit, VM or container is started; no licence or key is given | +| A first listing | One line on stderr names what it fetches. A program it needs that this machine lacks (`git`, `uv`, the light command's) is refused before anything is fetched | +| Before a listing | `nullius.standard.runner.units.state(benchmark, dataset, options)` says, starting and fetching nothing: `cached`, `light` (what it fetches), `full` (the driver's environment, and what it fetches), or `refused` (the reason) | +| The cache | The user cache (`nullius paths`): the same benchmark, driver, dataset and options are listed once | + +Exit codes: 0 listed (no match included), 2 a usage error or a refusal (an option or a category not known, a program not on this machine, a driver that could not list), 3 no such benchmark or dataset. diff --git a/docs/standard.md b/docs/standard.md index ef1ce6b61..bcfb988d5 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -426,6 +426,7 @@ local proof records; saved runs and credentials remain. | Op | Sent | Replies | | --- | --- | --- | | `units` | `dataset`, `setup` | Every unit id | +| `describe` | `dataset`, with `driver.describe` | `{units: {ID: {title, text, categories: {FIELD: VALUE}}}}`, read from the dataset's files alone: what [`nullius standard units`](cli/task-sets.md#listing-a-datasets-tasks) and the pages search and count | | `setup` | `unit`, `dir`; `attempt` with `limits.attempts`; `participant` (`agent`, `capability` or `control`) with `driver.participant` | `{prompt}`, any `mcp` servers, `environment`, an own image's `image`, `prepare`, `internet` and `verify`, and `agent_seconds`, the unit's own agent timeout (up to 6 hours, instead of `limits.turn_seconds`) | | `turn` | The transcript so far; `simulator: {model, base_url, key}` when there is one; `judge` for an upstream that grades as the conversation ends; `attempt` with `limits.attempts` | The next message, `{done: true}`, or `restart` | | `produce` | A capability benchmark's recall, `base_url` and `key` | The reading, through the relay | @@ -450,6 +451,8 @@ An `answer` or `score` error that begins `EnvironmentSetupError: `, `VerifierErr | `limits.call_seconds` | How long the relay waits for one model call's reply (default 900). A benchmark whose agent waits longer for a call sets it above that agent's own wait, so the agent's client, not the relay, ends a long call | | `driver.participant` | `true`: `setup` is also sent `participant`, the kind of what runs the unit, for a driver that starts something only an agent uses | | `driver.unit_end` | `true`: the driver is sent `end` (`unit`, `dir`) once each unit an agent ran has ended, scored or not, so that what its setup started for the agent ends with the unit. A control's or a setup's unit gets none | +| `driver.describe` | `true`: the driver answers `describe`. Without it a listing gives ids alone | +| `driver.list_command` | A second start of the driver's code for a listing alone (`units`, and `describe` with `driver.describe`): Python's standard library and the dataset's files, `{here}` its one slot. The listing then prepares the upstream and the dataset and never the driver's environment; a run still checks its ids with `driver.command` | | `driver.task_given` | `true`: the driver is sent `task_given` before each agent is given its task, and the task waits for its answer: [the computer port](ports/agent-computer-v1.md#the-window-before-the-task) closes its window before the task there. A control's or a setup's unit gets none | | `limits.attempts` | How the upstream tells attempts apart; the driver is then sent `attempt` with `setup`, `turn` and `answer` | | `units.redistribute` | `false` when the data may not be redistributed: `cli prove` then records no unit id | From 8ac91750d39f39333bde7693aff886b95dd46a67 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 23 Nov 2026 14:15:28 +0100 Subject: [PATCH 02/37] feat(standard): save a named set of a dataset's tasks and run it with --set A user who runs the same few tasks again keeps their ids in a file of their own, and the job does not say which group of tasks it ran. A task set is a named, frozen list of one dataset's tasks in the user catalogue (`sets//NAME.json`), with the version of the benchmark it was made at. `set create` makes one from a file of ids or from what a listing matches (`--search`, `--category`); `list`, `show`, `rename`, `delete` and `import` manage them. `run --set NAME` runs a set's tasks: its dataset is the run's, a task the version lacks is refused before any unit, and `config.json` records the set. A host that runs a recipe receives the sets it names. The job parser reads the set; its cache shape is raised by one. --- AGENTS.md | 2 +- app/nullius/execution.py | 6 +- app/nullius/migrate.py | 2 +- app/nullius/runs/parse.py | 10 +- app/nullius/standard/cli.py | 220 +++++++- app/nullius/standard/runner/job.py | 7 +- app/nullius/standard/runner/merge.py | 26 +- app/nullius/standard/runner/payload.py | 31 +- app/nullius/standard/runner/run.py | 73 ++- app/nullius/standard/runner/sets.py | 588 ++++++++++++++++++++ app/tests/field_contract.json | 1 + app/tests/test_cli_contract.py | 33 +- app/tests/test_execution.py | 10 + app/tests/test_migrate.py | 21 + app/tests/test_standard_sets.py | 660 +++++++++++++++++++++++ app/tests/test_standard_shard.py | 29 +- app/tests/test_standard_units.py | 16 + app/tests/test_standard_units_listing.py | 28 +- app/tests/test_task_set_recipe.py | 91 ++++ docs/cli/README.md | 2 +- docs/cli/run.md | 5 +- docs/cli/shard-and-merge.md | 3 +- docs/cli/task-sets.md | 52 ++ docs/concepts.md | 1 + docs/field-guide.md | 1 + docs/standard.md | 3 +- 26 files changed, 1865 insertions(+), 56 deletions(-) create mode 100644 app/nullius/standard/runner/sets.py create mode 100644 app/tests/test_standard_sets.py create mode 100644 app/tests/test_task_set_recipe.py diff --git a/AGENTS.md b/AGENTS.md index a64aed1a9..43e65870f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ and its resources. `protocols/`: `jsonl`, `acp`, `cancellation` (interruptible protocol waits), `computer_port` and `computer_pipe` (the computer port's MCP server, served by a desktop benchmark's runner over the benchmark's own loop, and the session's stdio pipe to it); `calls/`: `relay`, `ledger` (a run's spending cap); `backends/`: `container` (the container backend), `boat` (the boat backend: each unit's agent in a boat.dev VM), `setup_container` (an Original setup's driver and its Linux dependencies in Docker), `forward` (a licence server's one door from it, or a benchmark's MCP server's), `web_services` (HTTP fixtures a driver's setup declares, each behind a unit-local Docker door), `mcp_machine` and `mcp_bridge` (a benchmark's MCP server run on the machine, in its driver's environment, and the agent's bridge to it), `egress` (an own image's check's proxy to public addresses); - `runner/`: `run`, `job`, `retries` (what an attempt is tried again after, and how many times), `pace` (how soon the next unit starts after a rate limit), `shard` and `merge` (one run over many machines), `payload` (a snapshot of the running backend and effective catalogue for a remote host), `boat_units` (a benchmark whose units boot a VM of their own, each unit whole in a Boat VM), `units` (a dataset's tasks listed, searched and counted by category, from the driver's `describe`); + `runner/`: `run`, `job`, `retries` (what an attempt is tried again after, and how many times), `pace` (how soon the next unit starts after a rate limit), `shard` and `merge` (one run over many machines), `payload` (a snapshot of the running backend and effective catalogue for a remote host), `boat_units` (a benchmark whose units boot a VM of their own, each unit whole in a Boat VM), `sets` (task sets: named lists of a benchmark's units in the user catalogue, frozen once made), `units` (a dataset's tasks listed, searched and counted by category, from the driver's `describe`); `proofs/`: `conform`, `fidelity` (ACP against the agent's own CLI), `prove` (a benchmark's controls and proofs), `pins` (image digests checked against registry tags); `pages/`: `recipe` (the builder's standard recipe), `howto` (the How to add steps); and the `cli` at its top; diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 2e0d91d58..5e7c779f8 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -1140,10 +1140,12 @@ def _app_here(self) -> Optional[tuple]: The exact code imported here travels, including source edits, so installed wheels and editable checkouts have the same behaviour. - Configuration and credential stores are not payload inputs. + Configuration and credential stores are not payload inputs; the + task sets the recipe runs are, from the user catalogue. """ try: - return standard_payload.build(app_root(self.root), catalogue=self._catalogue) + return standard_payload.build(app_root(self.root), catalogue=self._catalogue, + sets=standard_payload.recipe_sets(self.plan.recipe)) except (OSError, ValueError) as e: self._fail("app", "the standard runner could not be packed: " + str(e)[-300:]) return None diff --git a/app/nullius/migrate.py b/app/nullius/migrate.py index 5def150fa..41c580c4b 100644 --- a/app/nullius/migrate.py +++ b/app/nullius/migrate.py @@ -152,7 +152,7 @@ def add(dest, data, mode=0o600): bundled = Path(__file__).resolve().parent / "catalogue" source_catalogue = checkout / "app" / "nullius" / "catalogue" pending.catalogue_snapshot = source_catalogue.resolve() == bundled.resolve() - for kind in ("benchmarks", "agents", "features", "capabilities"): + for kind in ("benchmarks", "agents", "features", "capabilities", "sets"): parent = source_catalogue / kind _no_symlinks(parent) if not parent.exists(): diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index bd6e21c13..91810cb88 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -28,7 +28,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 = "17" +SCHEMA = "18" # 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 — @@ -306,6 +306,9 @@ class Job: launch_id: str = "" # Source job names explicitly recorded by standard merge. merged_from: list[str] = field(default_factory=list) + # The task set a Nullius standard job ran (config ``standard.task_set``): its name, its label (its name for a + # job from before labels) and id, its benchmark, and ``units``, its number of ids. {} for every other job. + task_set: dict = field(default_factory=dict) # 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) @@ -964,6 +967,11 @@ def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job: job.launch_id = str(std.get("launch") or "") merged = std.get("merged_from") job.merged_from = [s["job"] for s in merged if isinstance(s, dict) and isinstance(s.get("job"), str) and s["job"]] if isinstance(merged, list) else [] + ts = std.get("task_set") if isinstance(std.get("task_set"), dict) else {} + job.task_set = ({"name": str(ts["name"]), "label": str(ts.get("label") or ts["name"]), + "id": str(ts.get("id") or ""), "benchmark": str(std.get("benchmark") or ""), + "units": len(ts["units"]) if isinstance(ts.get("units"), list) else 0} + if isinstance(ts.get("name"), str) and ts["name"] else {}) job.budget = _budget(res.get("budget")) job.standard = bool(std) setup = std.get("setup") if isinstance(std.get("setup"), dict) else {} diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index f4126f96c..b4eedb59f 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -12,6 +12,8 @@ PYTHONPATH=app python3 -m nullius.standard.cli prove BENCHMARK[@VERSION] [--dataset D] [--limit N] [--bench-option NAME=VALUE ...] [--job nop|oracle=JOB_DIR ...] PYTHONPATH=app python3 -m nullius.standard.cli run ... --shard I/N [--launch ID] PYTHONPATH=app python3 -m nullius.standard.cli merge JOB_DIR... -o OUT [--force] + PYTHONPATH=app python3 -m nullius.standard.cli set create|list|show|rename|delete|import ... + PYTHONPATH=app python3 -m nullius.standard.cli run ... --set NAME PYTHONPATH=app python3 -m nullius.standard.cli units BENCHMARK --dataset D [--search TEXT] [--category FIELD=VALUE ...] [--json] PYTHONPATH=app python3 -m nullius.standard.cli fidelity AGENT --model M [--provider P] [--option NAME=VALUE ...] [--passes N] --unsandboxed @@ -44,7 +46,10 @@ ``--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``). ``units`` lists a +puts a launch's shard jobs together into one job (``standard/runner/merge.py``). ``set`` +keeps a named list of a benchmark's units in the user catalogue, frozen once +made (``standard/runner/sets.py``), and ``run --set NAME`` runs one: its dataset taken +from it, the job recording which set ran. ``units`` lists a dataset's tasks, searched and counted by category (``standard/runner/units.py``). ``--option`` sets one of the agent's or capability's options (``options`` in its definition); the rest keep the vendor's defaults, and the job's config records them all. @@ -86,7 +91,7 @@ from nullius.standard.backends import boat from nullius.standard.contract import definitions, match, ports, proofs from nullius.standard.proofs import conform, fidelity, pins, prove -from nullius.standard.runner import job, merge, run, shard +from nullius.standard.runner import job, merge, run, sets, shard from nullius.standard.runner import units as unit_list ENV_FILE = paths.settings_file() @@ -549,6 +554,14 @@ def _bench(key): def cmd_run(a): b = _bench(a.benchmark) + task_set, dataset, bench_options = None, a.dataset, options(a.bench_option) + if a.task_set is not None: + # the set's dataset over the run's, refused where it differs: before anything starts + try: + task_set, dataset = sets.for_run(b, a.task_set, dataset=a.dataset, units_given=a.units is not None) + except sets.Refused as e: + print("refused:", e) + return 2 if a.other in definitions.CONTROLS: other = definitions.control(b, a.other) if other is None: @@ -584,15 +597,16 @@ def cmd_run(a): unreachable = str(e) held, spill = licences(b, from_run=a.from_run) try: - job, failed = run.run_and_report(b, other, model=a.model or "", provider=a.provider, dataset=a.dataset, limit=a.limit, + job, failed = run.run_and_report(b, other, model=a.model or "", provider=a.provider, dataset=dataset, limit=a.limit, concurrency=a.concurrency, jobs_root=a.jobs, name=a.name, unsandboxed=a.unsandboxed, judge_model=a.judge_model, backend=a.backend, boat_size=a.boat_size, relay_container=a.relay_container, simulator_model=a.simulator_model, options=options(a.option), shard=_shard(a.shard), launch=a.launch, - shard_by=a.shard_by, licences=held, bench_options=options(a.bench_option), repeat=a.repeat, retries=a.retries, + shard_by=a.shard_by, licences=held, bench_options=bench_options, repeat=a.repeat, retries=a.retries, remove_images=a.remove_images, prices=prices(a.price), max_usd=a.max_usd, max_usd_per_unit=a.max_usd_per_unit, prices_unreachable=unreachable, constraints=given, timeouts=timeouts(a.timeout), max_turns=a.max_turns, max_calls=a.max_calls, **({"units_file": run.units_file(a.units)} if a.units is not None else {}), + **({"task_set": task_set} if task_set else {}), **({"served_by": run.served_by(a.served_by, a.model or "")} if a.served_by else {}), **({"env": run_env(a.provider)} if a.from_run else {})) except run.Refused as e: @@ -737,9 +751,49 @@ def cmd_merge(a): return 0 +SET_EPILOG = """\ +A set is frozen once made: another list of tasks is another set. Its name is +any words; the name commands take is made from them, in lower case with +hyphens ("first ten" makes first-ten), with -2 and on for a second equal one. + +examples: + nullius standard set create humaneval "first ten" --dataset humaneval --units ten.txt --description "a quick look" + nullius standard set create humaneval misses --from-job jobs_standard/JOB --outcome failed,infra + nullius standard set create osworld1@044bc33 "chrome tabs" --dataset test_nogdrive --search tab --category domain=chrome + nullius standard set show humaneval first-ten --json + nullius standard set rename humaneval misses "misses of June" + nullius standard set delete humaneval misses-of-june + nullius standard run humaneval reference --model M --set first-ten --unsandboxed + +exit codes: + 0 done + 1 unexpected error (a traceback: report it) + 2 usage, or refused: a name not allowed, a list the set cannot hold, an import that conflicts, + an entry of the earlier format + 3 not found: no such benchmark, set, file or job +""" + + def _refused(e: Exception) -> int: print(f"refused: {e}", file=sys.stderr) - return 3 if isinstance(e, unit_list.NotFound) else 2 + return 3 if isinstance(e, (sets.NotFound, unit_list.NotFound)) else 2 + + +def _listed_units(path: str) -> list: + """A ``--units`` file's ids, read by the rules ``run --units`` reads it by.""" + if not os.path.isfile(path): + raise sets.NotFound(f"--units {path}: no such file") + try: + return run.units_file(path)["units"] + except run.Refused as e: + raise sets.Refused(str(e)) + + +def _set_rows(entry: dict) -> dict: + last = sets.latest(entry) + return {"benchmark": entry["benchmark"], "name": entry["name"], "label": sets.label_of(entry), "id": entry["id"], + "units": len(last["units"]), "dataset": entry["dataset"], "version": entry.get("version") or "", + "description": entry.get("description") or ""} def _find_bench(key): @@ -747,6 +801,114 @@ def _find_bench(key): return definitions.get("benchmark", key) or next((k for k in definitions.kits() if k["key"] == key), None) +def cmd_set_create(a): + b = _find_bench(a.benchmark) + if b is None: + raise sets.NotFound(f"no benchmark {a.benchmark!r}") + filtered = a.search is not None or bool(a.category) + if sum((a.units is not None, a.from_job is not None, filtered)) != 1: + raise sets.Refused("set create: --units FILE, --from-job JOB_DIR, or --search and --category") + if a.from_job is None and (a.outcome or a.unit): + raise sets.Refused("--outcome and --unit choose a job's trials: give them with --from-job") + if a.units is not None: + dataset = sets._dataset(b, a.dataset) + got = {"dataset": dataset, "units": _listed_units(a.units), "note": f"from {os.path.basename(a.units)}"} + elif filtered: + # the ids the listing matches today, under the benchmark's default options; the note keeps the filter + dataset = sets._dataset(b, a.dataset) + chosen = unit_list.categories_of(a.category) + found = unit_list.find(b, dataset, search=a.search or "", categories=chosen, size=None) + if not found["total"]: + raise sets.Refused(f"no task of {dataset} matches {unit_list.filter_text(a.search or '', chosen)}") + got = {"dataset": dataset, "units": [t["id"] for t in found["tasks"]], + "note": f"matched by {unit_list.filter_text(a.search or '', chosen)}"} + else: + got = sets.from_job(b, a.from_job, a.outcome, a.unit) + if a.dataset and a.dataset != got["dataset"]: + raise sets.Refused(f"--dataset {a.dataset}: the job ran the dataset {got['dataset']}") + entry = sets.create(b, a.label, dataset=got["dataset"], units=got["units"], description=a.description, note=got["note"]) + print(f"wrote {sets.path_of(entry['benchmark'], entry['name'])}: {_named(entry)}, " + f"{len(got['units'])} {b['units']['nouns'] if len(got['units']) != 1 else b['units']['noun']} of {entry['dataset']}" + + (f" at {sets.version_label(b, entry['version'])}" if entry.get("version") else "")) + return 0 + + +def _named(entry: dict) -> str: + """A set as a line of output names it: its name, and its label when that is other words.""" + label = sets.label_of(entry) + return entry["name"] if label == entry["name"] else f"{entry['name']} ({label})" + + +def cmd_set_list(a): + got, bad = sets.entries(a.benchmark) + for problem in bad: + print("problem:", problem, file=sys.stderr) + rows = [_set_rows(e) for e in got] + if a.json: + print(json.dumps(rows, indent=2)) + return 0 + for r in rows: + print(f"{r['benchmark']:<16} {r['name']:<24} {r['units']:>6} units of {r['dataset']}" + + (f" at {r['version']}" if r["version"] else "") + + (f" {r['label']}" if r["label"] != r["name"] else "") + (f" {r['description']}" if r["description"] else "")) + return 0 + + +def cmd_set_show(a): + name, rev = sets.split_ref(a.ref) + entry = sets.load(a.benchmark, name) + got = sets.latest(entry, rev) + if a.json: + print(json.dumps({**{k: entry[k] for k in sets.HEADER if k in entry}, "label": sets.label_of(entry), + "date": got["date"], "note": got["note"], "hash": got["hash"], "units": got["units"]}, indent=2)) + return 0 + bench = _find_bench(a.benchmark) + print(f"{_named(entry)}: {len(got['units'])} units of {entry['benchmark']} {entry['dataset']}" + + (f", made at {sets.version_label(bench, entry['version'])}" if entry.get("version") else "")) + if entry.get("description"): + print(f" {entry['description']}") + print(f" id {entry['id']}") + print(f" {got['date']} {got['hash'][:12]}" + (f" {got['note']}" if got["note"] else "")) + print("units:") + for u in got["units"]: + print(f" {u}") + return 0 + + +def cmd_set_rename(a): + entry = sets.rename(a.benchmark, a.name, a.new) + print(f"renamed {a.name} to {_named(entry)} ({sets.path_of(entry['benchmark'], entry['name'])}): its id and its " + "tasks kept; jobs that ran it find it by its id") + return 0 + + +def cmd_set_delete(a): + path = sets._file_of(a.benchmark, a.name, None) + entry = sets.delete(a.benchmark, a.name) + if entry is None: + print(f"deleted {path}: an entry this version could not read") + return 0 + print(f"deleted {path}: {_named(entry)}, {len(sets.latest(entry)['units'])} units; jobs that ran it keep their record") + return 0 + + +def cmd_set_import(a): + entry, added = sets.import_path(a.path) + if added: + print(f"{_named(entry)} of {entry['benchmark']}: imported into {sets.path_of(entry['benchmark'], entry['name'])}") + else: + print(f"{_named(entry)} of {entry['benchmark']}: here already, with the same tasks") + return 0 + + +def cmd_set(a): + try: + return {"create": cmd_set_create, "list": cmd_set_list, "show": cmd_set_show, + "rename": cmd_set_rename, "delete": cmd_set_delete, "import": cmd_set_import}[a.set_cmd](a) + except (sets.Refused, unit_list.Refused) as e: + return _refused(e) + + UNITS_EPILOG = """\ examples: nullius standard units humaneval --dataset humaneval @@ -901,6 +1063,9 @@ def main(argv=None): p.add_argument("--units", metavar="FILE", help="only the units this file lists, one id a line (# starts a comment): in the dataset's order, " "before --shard and --limit; the job's config records the file's name, sha256 and units") + p.add_argument("--set", dest="task_set", metavar="NAME", + help="only the units of this task set (nullius standard set): its dataset is the run's, the " + "options the run's own; the job's config records the set") p.add_argument("--limit", type=int) p.add_argument("-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") @@ -962,6 +1127,47 @@ def main(argv=None): g.add_argument("jobs", nargs="+", metavar="JOB_DIR") g.add_argument("-o", "--out", required=True, help="the merged job's directory (its name is the job's)") g.add_argument("--force", action="store_true", help="merge shards of different launches, versions, models or agents") + st = sub.add_parser("set", help="task sets: named lists of a benchmark's units, frozen once made", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + ss = st.add_subparsers(dest="set_cmd", required=True, metavar="COMMAND") + sc = ss.add_parser("create", help="a new task set, from a units file or from a job's trials", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sc.add_argument("benchmark", metavar="BENCH") + sc.add_argument("label", metavar="NAME", + help="any words; the name commands take is made from them (lower case, hyphens, -2 for a second one)") + sc.add_argument("--dataset", help="the dataset the set is cut from (from a job: the job's)") + source = sc.add_mutually_exclusive_group() + source.add_argument("--units", metavar="FILE", help="the units a file lists, one id a line (# starts a comment)") + source.add_argument("--from-job", metavar="JOB_DIR", help="the units a standard job ran (each trial's full unit id)") + sc.add_argument("--outcome", action="append", metavar="O,...", + help="with --from-job: the trials of these outcomes (the pages' names, or passed, failed, infra)") + sc.add_argument("--unit", action="append", metavar="ID", help="with --from-job: this unit too (repeatable)") + sc.add_argument("--search", metavar="TEXT", + help="the tasks whose id, title or text hold each word (nullius standard units): those matched today") + sc.add_argument("--category", action="append", metavar="FIELD=VALUE", + help="the tasks of this category's value (repeatable: values of one field widen, fields narrow)") + sc.add_argument("--description", default="") + sl = ss.add_parser("list", help="the task sets, of one benchmark or all", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sl.add_argument("benchmark", metavar="BENCH", nargs="?") + sl.add_argument("--json", action="store_true", help="one JSON array of rows") + sw = ss.add_parser("show", help="one task set: what it holds", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sw.add_argument("benchmark", metavar="BENCH") + sw.add_argument("ref", metavar="NAME", help="the set's name") + sw.add_argument("--json", action="store_true", help="the set as one JSON document") + sr = ss.add_parser("rename", help="another name for a task set: its id and tasks kept", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sr.add_argument("benchmark", metavar="BENCH") + sr.add_argument("name", metavar="NAME") + sr.add_argument("new", metavar="NEW", help="any words; the name commands take is made from them again") + sd = ss.add_parser("delete", help="remove a task set from this catalogue: jobs that ran it keep their record", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sd.add_argument("benchmark", metavar="BENCH") + sd.add_argument("name", metavar="NAME") + si = ss.add_parser("import", help="a task set from its file, or from a job that ran one, into this catalogue", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + si.add_argument("path", metavar="PATH", help="an entry's .json file, or a job's directory") un = sub.add_parser("units", help="a dataset's tasks: their ids, titles and categories, searched and counted", epilog=UNITS_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) un.add_argument("benchmark", metavar="BENCH") @@ -980,7 +1186,7 @@ def main(argv=None): help="started by Nullius: the key is OPENAI_API_KEY (and OPENAI_BASE_URL), saved settings are not read") # Bootstrap decides whether settings may be read before these modules are # imported. Keep --from-run exact here too, so --from-r cannot bypass it. - for parser in (ap, *sub.choices.values()): + for parser in (ap, *sub.choices.values(), *ss.choices.values()): parser.allow_abbrev = False a = ap.parse_args(argv) if a.cmd in ("run", "prove", "conform", "fidelity"): @@ -990,7 +1196,7 @@ def main(argv=None): 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, - "units": cmd_units}[a.cmd](a) + "set": cmd_set, "units": cmd_units}[a.cmd](a) if __name__ == "__main__": diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index 2b8e4870c..efc08941a 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -573,6 +573,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, 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): """``unsandboxed`` is true for an agent on the local backend only: in a @@ -581,7 +582,10 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str say what differed. ``launch`` and ``shard``: a shard of a launch run over several machines (``shard``), which ``merge`` reads back. ``units_file``: the file a run's units were listed in (``run.units_file``), its name, its - sha256 and its units, said only for such a run. ``repeat``: how + sha256 and its units, said only for such a run. ``task_set``: the task + set a run's units came from (``sets.record``): its id, name, revision, + hash and units, and what ``set import`` rebuilds the entry from, said + only for such a run. ``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. @@ -606,6 +610,7 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str **({"simulator": simulator} if simulator else {}), **({"options": options} if options else {}), **({"benchmark_options": bench_options} if bench_options else {}), **_control(other), **_setup(other), **({"launch": launch} if launch else {}), **({"shard": shard} if shard else {}), **({"units_file": units_file} if units_file else {}), + **({"task_set": task_set} if task_set else {}), **({"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 1f4b49a9a..3c5c5fc74 100644 --- a/app/nullius/standard/runner/merge.py +++ b/app/nullius/standard/runner/merge.py @@ -17,7 +17,10 @@ different units, or a shard of a list and one of none: the merged job records one list. The units are compared in any order; a list's name, comments, line endings and sha256 may differ from shard to shard, and the -merged job records the first shard's list. Units no shard ran +merged job records the first shard's list. Shards of different task sets +(``sets``), of different revisions of one, or of a set and none, are refused +as the other differences are, unless ``force``; the merged job keeps the +first shard's set. Units no shard ran are not a refusal - a shard may be missing, or stopped early - and are said: the shards absent, and the units a shard planned and has no trial for. A trial whose record names another job, benchmark, version, control or agent @@ -45,7 +48,8 @@ ("benchmark version", ("standard", "benchmark_version")), ("dataset", ("datasets", 0, "name")), ("agent or capability", ("standard", "plugged")), ("model", ("agents", 0, "model_name")), ("backend", ("standard", "backend")), ("serving providers", ("standard", "served_by")), - ("number of shards", ("standard", "shard", "of")), ("retries per attempt", ("standard", "retries"))) + ("number of shards", ("standard", "shard", "of")), ("retries per attempt", ("standard", "retries")), + ("task set", ("standard", "task_set"))) LISTED = 1000 @@ -78,11 +82,23 @@ def _at(d, path): def _same(cfg: dict, path) -> object: - """What a shard's config says at ``path`` (``SAME``); ``retries`` absent reads as none.""" + """What a shard's config says at ``path`` (``SAME``); ``retries`` absent reads as none. + A task set is its name, revision, id and hash: the record's other fields follow from them.""" got = _at(cfg, path) + if path == ("standard", "task_set"): + return (tuple(got.get(k) for k in ("name", "revision", "id", "hash")) + if isinstance(got, dict) else None) return got or 0 if path == ("standard", "retries") else got +def _shown(cfg: dict, path) -> object: + got = _same(cfg, path) + if path == ("standard", "task_set") and got is not None: + name, revision, identity, digest = got + return f"{name}@{revision} ({str(identity)[:8]}, {str(digest)[:12]})" + return got + + def _listed(cfg: dict) -> Optional[tuple]: """The units a shard's list holds (``standard.units_file``), sorted; None for a shard of no list.""" units = _at(cfg, ("standard", "units_file", "units")) @@ -172,7 +188,7 @@ def check(job_dirs: List[str], force: bool = False) -> dict: for label, path in SAME: seen = {json.dumps(_same(s["config"], path), sort_keys=True) for s in shards} # a mapping by its content if len(seen) > 1: - differ.append(f"{label}: " + ", ".join(f"{s['name']} {_same(s['config'], path)!r}" for s in shards)) + differ.append(f"{label}: " + ", ".join(f"{s['name']} {_shown(s['config'], path)!r}" for s in shards)) if differ and not force: raise Refused("the shards are not of one launch - " + "; ".join(differ) + " (--force merges them anyway)") # every trial by its unit: two of one unit are never merged, force or not @@ -238,7 +254,7 @@ def check(job_dirs: List[str], force: bool = False) -> dict: short = total - len(by_unit) if short > 0: # a shard of a list of units counts the listed ones as its whole (run.units_file) - listed = any(_at(s["config"], ("standard", "units_file")) for s in shards) + listed = any(_at(s["config"], ("standard", "units_file")) or _at(s["config"], ("standard", "task_set")) for s in shards) whole = f"{total} listed units" if listed else f"dataset's {total} units" notes.append(f"{short} of the {whole} are not in the merge") return {"shards": shards, "by_unit": by_unit, "notes": notes, "missing": missing, "units_total": total, "differ": differ} diff --git a/app/nullius/standard/runner/payload.py b/app/nullius/standard/runner/payload.py index 1a86ad818..dd1b6ecc2 100644 --- a/app/nullius/standard/runner/payload.py +++ b/app/nullius/standard/runner/payload.py @@ -20,6 +20,7 @@ from nullius import paths from nullius.standard.contract import definitions +from nullius.standard.runner import sets as task_sets PACKAGE = Path(__file__).resolve().parents[2] FORMAT = 1 @@ -40,9 +41,9 @@ def _safe(relative: str) -> bool: and p.suffix.lower() not in {".pem", ".key", ".p12", ".pfx", ".pyc"}) -def _read(root: Path, relative: str) -> tuple[bytes, int]: +def _read(root: Path, relative: str, *, task_set: bool = False) -> tuple[bytes, int]: """Read a regular file below root, refusing symlinks at every segment.""" - if not _safe(relative): + if not (_safe(relative) or task_set and _safe(str(Path(relative).parent))): raise ValueError(f"not a runner resource: {relative}") p = root for segment in Path(relative).parts: @@ -191,7 +192,7 @@ def _cached(destination: Path, marker: str, files: dict) -> bool: valid = found == expected and manifest.read_text() == marker if valid: for name, value in files.items(): - if _read(destination / "app/nullius", name) != value: + if _read(destination / "app/nullius", name, task_set=name.startswith("catalogue/sets/")) != value: valid = False break if not valid: @@ -199,11 +200,24 @@ def _cached(destination: Path, marker: str, files: dict) -> bool: return True -def build(cache: str, *, package: Path | None = None, catalogue: str | None = None) -> tuple[str, str]: +def recipe_sets(recipe: dict) -> list[tuple[str, str]]: + """The task sets a standard recipe runs (``task_sets``), as (benchmark, name): what its snapshot carries.""" + asked = (recipe or {}).get("task_sets") + 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] + return sorted({(bench, ref.partition("@")[0]) for ref in refs if ref}) + + +def build(cache: str, *, package: Path | None = None, catalogue: str | None = None, + sets: list[tuple[str, str]] | None = None) -> tuple[str, str]: """Return (content ID, snapshot root), with ``app/nullius`` below it. A user entry replaces the whole bundled entry. Nothing is created in either input tree. The staged tree is replaced atomically, and the address covers the exact bytes being sent. + ``sets``: the task sets of the user catalogue the run reads, each + (benchmark, name), carried at ``catalogue/sets//.json``. """ package = Path(package) if package is not None else PACKAGE if package.is_symlink(): @@ -240,6 +254,15 @@ def build(cache: str, *, package: Path | None = None, catalogue: str | None = No except json.JSONDecodeError: continue # Unfinished JSON drafts are not runnable catalogue entries. files.update({f"catalogue/{kind}/{name}/{r}": value for r, value in contents.items()}) + for bench, name in sets or (): + try: + task_sets.check_name(name) + except task_sets.Refused as e: + raise ValueError(str(e)) from None + relative = f"sets/{bench}/{name}.json" + if not _KEY.fullmatch(bench) or "/" in name or not (user / relative).is_file(): + raise ValueError(f"the task set {name} of {bench} is not in the catalogue") + files[f"catalogue/{relative}"] = _read(user, relative, task_set=True) kits = package / "standard" / "kits" if kits.is_dir(): if kits.is_symlink(): diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 802433fca..2d7268bcd 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -80,7 +80,7 @@ from nullius.standard.contract import definitions, match from nullius.standard.protocols import acp, jsonl from nullius.standard.requirements import hostreq, install -from nullius.standard.runner import job, pace as pacing, shard as shards +from nullius.standard.runner import job, pace as pacing, sets, shard as shards from nullius.standard.runner.retries import RETRIES, retryable # the totals a unit's end carries onto the live board, from its trial's agent_result @@ -470,7 +470,7 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas licences: Optional[Licences] = None, bench_options: Optional[dict] = None, which=shutil.which, remove_images: bool = False, prices: Optional[dict] = None, max_usd: Optional[float] = None, max_usd_per_unit: Optional[float] = None, prices_unreachable: Optional[str] = None, - units_file: Optional[dict] = None, + units_file: Optional[dict] = None, task_set: Optional[dict] = None, 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): """``proving``: the run is a conformance kit's, the one run that may @@ -494,6 +494,9 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas an id the dataset does not hold refuses the run before any unit starts. The job's config records the file's name, its sha256 and its units. + ``task_set``: a task set's record (``sets.record``): its units run as + a file's would, and the job's config keeps the record. Refused beside + ``units_file``. ``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 @@ -717,7 +720,10 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas self.provider_env = env # where the provider's model list is asked (``known_models``) self.key_header = "authorization" if keyless else key_header(provider, other, env) self.limit, self.concurrency = limit, limits.concurrency(max(1, int(concurrency)), self.constraints) + if units_file and task_set: + raise Refused("a run takes its units from a file or from a task set, not both") self.units_file = units_file + self.task_set = task_set self.repeat = max(1, int(repeat or 1)) self.retries = max(0, int(retries or 0)) self.retry_if = retry_if or retryable @@ -877,39 +883,56 @@ def _start(self, lck, mine) -> str: container.sweep(self.name) raise everything = [str(u) for u in units] - listed = self.units_file["units"] if self.units_file else None + listed = self.units_file["units"] if self.units_file else self.task_set["units"] if self.task_set else None + why, unknown = "", [] if listed is not None: held = set(everything) unknown = [u for u in listed if u not in held] if unknown: - # what the run holds is let go as when its driver cannot list the units: on the container - # backend that includes the containers its driver or its doors started - for d in self.drivers: - d.close() - if self.bench_relay is not None: - self.bench_relay.stop() - if self.backend == "container" or self.relay_container: - container.sweep(self.name) - # the record a refusal in ready() leaves, which the runs list reads (execution's refused): - # the job's folder with its progress.jsonl, the driver's working folders and logs taken out - work = os.path.join(self.job_dir, ".work") - for name in os.listdir(work): - path = os.path.join(work, name) - if name in ("driver", "driver-home"): - shutil.rmtree(path, ignore_errors=True) - elif name.startswith("driver-") and name.endswith(".log"): - os.remove(path) words = self.bench["units"] - why = (f"{self.units_file['name']} lists {len(unknown)} {words['noun'] if len(unknown) == 1 else words['nouns']} " - f"that {self.bench['label']}'s dataset {self.ds['id']} does not hold: " + ", ".join(unknown)) - p.emit("refused", detail=why) - raise Refused(why) + if self.units_file: + why = (f"{self.units_file['name']} lists {len(unknown)} {words['noun'] if len(unknown) == 1 else words['nouns']} " + f"that {self.bench['label']}'s dataset {self.ds['id']} does not hold: " + ", ".join(unknown)) + elif self.task_set.get("version") and self.task_set["version"] != str(self.bench.get("_version") or ""): + # made at another version of the benchmark, whose list may hold other tasks + label = self.task_set.get("label") or self.task_set["name"] + ours, theirs = (sets.version_label(self.bench, v) for v in (str(self.bench.get("_version") or ""), self.task_set["version"])) + why = (f"the task set {label} was made at {self.bench['label']} {theirs}, and {unknown[0]} is not a task of " + f"{self.ds['id']} at {ours}, the version this run is at" + + (f" ({len(unknown) - 1} more are not either)" if len(unknown) > 1 else "") + + f": run it at {theirs}, or make a set at {ours}") + else: + # a set holds no option: its ids are checked against the listing under this run's own + given = ", ".join(f"{k}={v}" for k, v in sorted(self.bench_options.items())) or "none" + why = (f"{len(unknown)} of the {len(listed)} ids of the task set {self.task_set.get('label') or self.task_set['name']} " + f"are not listed by {self.bench['label']}'s dataset {self.ds['id']} " + f"under the run's options ({given}): " + ", ".join(unknown[:5]) + (", ..." if len(unknown) > 5 else "")) # the list and the shard, then the limit; each unit keeps its place in the whole dataset (its trial's tag) mine = shards.select(everything, *self.shard, by=self.shard_by) if self.shard else list(enumerate(everything)) if listed is not None: wanted = set(listed) mine = [(i, u) for i, u in mine if u in wanted] mine = mine[: self.limit] if self.limit else mine + if why: + # what the run holds is let go as when its driver cannot list the units: on the container + # backend that includes the containers its driver or its doors started + for d in self.drivers: + d.close() + if self.bench_relay is not None: + self.bench_relay.stop() + if self.backend == "container" or self.relay_container: + container.sweep(self.name) + # the record a refusal in ready() leaves, which the runs list reads (execution's refused): + # the job's folder with its progress.jsonl, the driver's working folders and logs taken out + work = os.path.join(self.job_dir, ".work") + for name in os.listdir(work): + path = os.path.join(work, name) + if name in ("driver", "driver-home"): + shutil.rmtree(path, ignore_errors=True) + elif name.startswith("driver-") and name.endswith(".log"): + os.remove(path) + p.emit("refused", detail=why) + raise Refused(why) units = [u for _, u in mine] self.n_units = len(units) if getattr(self, "boat", None) is not None: @@ -926,7 +949,7 @@ def _start(self, lck, mine) -> str: options=self.options, launch=self.launch or "", bench_options=self.bench_options, # a shard of a list splits the listed units: they are its whole shard=shards.record(*self.shard, len(everything) if listed is None else len(listed), units, self.limit, by=self.shard_by) - if self.shard else None, units_file=self.units_file, + if self.shard else None, units_file=self.units_file, task_set=self.task_set, repeat=self.repeat, retries=self.retries, prices=self.prices_record(), constraints=self.constraints, served_by=self.serving, timeouts=self.timeouts, max_turns=self.forced_turns, max_calls=self.max_calls, simulator=self.simulator_model if self.other["_kind"] in ("agent", "upstream") and self.simulator_model else "") diff --git a/app/nullius/standard/runner/sets.py b/app/nullius/standard/runner/sets.py new file mode 100644 index 000000000..083b11014 --- /dev/null +++ b/app/nullius/standard/runner/sets.py @@ -0,0 +1,588 @@ +"""Task sets: a named list of a benchmark's units, kept in the user catalogue. + +An entry is ``sets//.json`` under the user catalogue +(``paths.catalogue_dir``, ``NULLIUS_CATALOGUE``): a plain file to copy or keep +in git. A set is a group of tasks, run as a benchmark's own dataset is: it +holds an id minted when it is made, its label and the name made from it, its +description, the benchmark, the version of the benchmark it was made at, the +dataset it is cut from, and its list, and nothing that binds a run (no +benchmark option, no setup). The label is the text a person typed; the name +is what commands take: the label in lower case with hyphens, ``-2`` and on +for a second equal one (``name_for``). + +A set is frozen: nothing changes its list once made, and another list is +another set. The file keeps one entry in ``revisions``: its number, its date, +a note, the unit ids and a content hash over the benchmark, the dataset and +the sorted ids. A file made before sets were frozen may hold several; it reads +as its latest, and is never rewritten for it. Two runs ran the same set when +their jobs name the same id. Two entries with equal lists stay two sets. An +entry holding any other field is refused where it is read; one of the earlier +format, which kept a run's options, is refused as such (``Earlier``), and +``plain`` says it on a page without its path. ``rename`` gives a set another +label, and the name made from it, its id and list kept, so a job that ran it +finds it by its id (``by_id``); ``delete`` removes its file, and a job that +ran it keeps its record. + +``record`` is what a job's ``config.json`` keeps of the set it ran +(``standard.task_set``): its id, name, label, the number of its list, the +hash, the units and the version it was made at. With the job's benchmark and +dataset that is enough for ``import_path`` to rebuild the entry on another +machine, its description empty and its list dated by the import. The same id +with another list is refused there. +""" +from __future__ import annotations + +import hashlib +import json +import os +import re +import tempfile +import unicodedata +import uuid +from datetime import datetime, timezone +from typing import Iterable, List, Optional, Tuple + +from nullius import paths +from nullius.runs import classify +from nullius.standard.contract import definitions + +SCHEMA = "nullius.task-set/v1" +FOLDER = "sets" +# A name stays inside its benchmark's folder: no slash, no leading dot, no ``..`` +_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$") +NAME_MAX = 64 +LABEL_MAX = 80 +# the base of a name made from a label that holds no Latin letter or digit +FALLBACK = "task-set" +_TAG = re.compile(r"__u(\d+)(?:r\d+)?$") +# The outcome groups ``--outcome`` takes beside the pages' outcome names: a pass, a verdict against the +# agent (its failures and its own errors, as the attempts' pass count reads them), the infrastructure's +GROUPS = { + "passed": {classify.RESOLVED}, + "failed": {classify.PATCH_FAILED_TESTS, classify.FAILED_VERIFICATION, classify.PATCH_NOT_APPLIED, + classify.NO_PATCH, classify.AGENT_ERROR}, + "infra": set(classify.INFRA_OUTCOMES), +} +HEADER = ("id", "name", "label", "description", "benchmark", "version", "dataset") +# what an entry of the earlier format held beside its header: a run's options, bound to the set +EARLIER = ("benchmark_version", "benchmark_options", "setup") +REVISION = ("revision", "date", "note", "units", "hash") +RECORD = ("id", "name", "revision", "hash", "units") +# what the record of a newer job holds beside those: what its page shows, and what a run checks the set against +RECORD_MORE = ("label", "version") + + +class Refused(Exception): + """The set cannot be made, changed, read or run as asked; the message says why.""" + + +class NotFound(Refused): + """No such set, file or job.""" + + +class Earlier(Refused): + """An entry of the earlier format, which kept a run's options: refused where it is read.""" + + +def root_dir(root: Optional[str] = None) -> str: + return root if root is not None else paths.catalogue_dir() + + +def check_name(name: str) -> str: + if not isinstance(name, str) or not _NAME.match(name) or ".." in name: + raise Refused(f"{name!r} is not a task set's name: letters, digits, '.', '_' and '-', " + "starting with a letter or a digit, at most 64, no '..'") + return name + + +def check_label(label: str) -> str: + """The words a person names a set with, trimmed: any words with at least one letter or digit, at most 80 + characters, on one line.""" + text = label.strip() if isinstance(label, str) else "" + if not text: + raise Refused("a task set needs a name") + if len(text) > LABEL_MAX: + raise Refused(f"a task set's name is at most {LABEL_MAX} characters") + if any(unicodedata.category(c) == "Cc" for c in text): + raise Refused("a task set's name is one line") + if not any(c.isalnum() for c in text): + raise Refused("a task set's name needs a letter or a digit") + return text + + +def slug(label: str) -> str: + """The name a label makes: its Latin letters and digits in lower case, every other run of characters one + hyphen, at most 64; ``task-set`` when nothing is left. "Custom task set" makes ``custom-task-set``.""" + plain = unicodedata.normalize("NFKD", label or "").encode("ascii", "ignore").decode("ascii") + s = re.sub(r"[^a-z0-9]+", "-", plain.lower()).strip("-") + return s[:NAME_MAX].rstrip("-") or FALLBACK + + +def name_for(benchmark: str, label: str, root: Optional[str] = None, but: str = "") -> str: + """The name a set of ``benchmark`` labelled ``label`` takes: its ``slug``, or the first ``-`` from 2 + that no other set of the benchmark has (``but``, the set's own name when it is renamed, counts as free).""" + base = slug(check_label(label)) + folder = _folder(benchmark, root) + taken = {f[:-5] for f in os.listdir(folder) if f.endswith(".json")} if os.path.isdir(folder) else set() + taken.discard(but) + if base not in taken: + return base + for i in range(2, 10000): + name = f"{base[:NAME_MAX - len(str(i)) - 1].rstrip('-')}-{i}" + if name not in taken: + return name + raise Refused(f"every name made from {label!r} is taken") + + +def label_of(entry: dict) -> str: + """What a person reads a set by: its label, or the name of a set made before labels.""" + return entry.get("label") or entry["name"] + + +def version_label(bench: Optional[dict], version: str) -> str: + """A version a set was made at as a reader names it (``main (044bc33)``); the version's key itself when the + benchmark's definition no longer knows it.""" + return ((bench or {}).get("_labels") or {}).get(version) or version + + +def version_of(bench: dict) -> str: + """The version of the benchmark a set made from ``bench`` records: its resolved version, "" when it has none.""" + return str(bench.get("_version") or "") + + +def _bench_key(benchmark: str) -> str: + if not isinstance(benchmark, str) or not definitions._KEY.match(benchmark): + raise Refused(f"{benchmark!r} is not a benchmark's key") + return benchmark + + +def _contained(path: str, folder: str) -> str: + resolved = os.path.realpath(path) + if os.path.commonpath((resolved, folder)) != folder: + raise Refused(f"{path}: outside the task set folder {folder}") + return resolved + + +def _folder(benchmark: Optional[str], root: Optional[str]) -> str: + folder = os.path.join(os.path.realpath(root_dir(root)), FOLDER) + if benchmark is not None: + folder = os.path.join(folder, _bench_key(benchmark)) + return _contained(folder, folder) + + +def path_of(benchmark: str, name: str, root: Optional[str] = None) -> str: + folder = _folder(benchmark, root) + return _contained(os.path.join(folder, check_name(name) + ".json"), folder) + + +def split_ref(ref: str) -> Tuple[str, Optional[int]]: + """``NAME``, or ``NAME@N`` as recipes and commands made before sets were frozen name one: (name, N or None). + ``latest`` reads N.""" + name, at, rev = str(ref).partition("@") + if not at: + return check_name(name), None + if not rev.isdigit() or int(rev) < 1: + raise Refused(f"{ref!r}: a task set's name") + return check_name(name), int(rev) + + +def content_hash(benchmark: str, dataset: str, units: Iterable[str]) -> str: + """The sha256 over what makes the membership: the benchmark, the dataset and the ids sorted (an order, a + comment, a file's name say nothing).""" + doc = {"benchmark": benchmark, "dataset": dataset, "units": sorted(set(str(u) for u in units))} + return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest() + + +def _hash_of(entry: dict, units: Iterable[str]) -> str: + return content_hash(entry["benchmark"], entry["dataset"], units) + + +def _now() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _ids(units: Iterable[str], what: str) -> List[str]: + ids = [str(u) for u in units] + if any(not u or u.startswith("#") or u != u.strip() for u in ids): + raise Refused(f"{what}: an id is a word with no space around it, not empty and not starting with #") + twice = sorted({u for u in ids if ids.count(u) > 1}) + if twice: + raise Refused(f"{what} lists {', '.join(twice)} more than once") + if not ids: + raise Refused(f"{what} lists no unit") + return ids + + +def check(entry: dict, where: str) -> dict: + """``entry`` as read from ``where``, its shape and every list's hash checked.""" + if not isinstance(entry, dict) or entry.get("schema") != SCHEMA: + raise Refused(f"{where}: not a task set (schema {SCHEMA})") + other = sorted(set(entry) - {"schema", *HEADER, "revisions"}) + if other and set(other) & set(EARLIER): + raise Earlier(f"{where}: holds {', '.join(other)}, which a task set does not hold: an entry of the earlier " + "format, which kept a run's options. Delete it and make it again") + if other: + raise Refused(f"{where}: holds {', '.join(other)}, which a task set does not hold: a set is its dataset " + "and its ids, and a run gives its own options") + for k in ("id", "name", "benchmark", "dataset"): + if not isinstance(entry.get(k), str) or not entry[k]: + raise Refused(f"{where}: no {k}") + check_name(entry["name"]) + _bench_key(entry["benchmark"]) + if not isinstance(entry.get("description"), str): + raise Refused(f"{where}: description is text") + for k in ("label", "version"): + if k in entry and (not isinstance(entry[k], str) or not entry[k]): + raise Refused(f"{where}: {k} is text") + revs = entry.get("revisions") + if not isinstance(revs, list) or not revs: + raise Refused(f"{where}: no list of units") + seen = set() + for r in revs: + n = r.get("revision") if isinstance(r, dict) else None + if not isinstance(n, int) or isinstance(n, bool) or n < 1 or n in seen: + raise Refused(f"{where}: a list's number is a whole number, each once") + seen.add(n) + if not isinstance(r.get("date"), str) or not r["date"]: + raise Refused(f"{where}: list {n} has no date") + if not isinstance(r.get("note"), str): + raise Refused(f"{where}: list {n}'s note is text") + if not isinstance(r.get("units"), list) or any(not isinstance(u, str) for u in r["units"]): + raise Refused(f"{where}: list {n} lists no units") + _ids(r["units"], f"{where}: list {n}") + if r.get("hash") != _hash_of(entry, r["units"]): + raise Refused(f"{where}: list {n}'s hash is not that of its units and dataset: " + "the file was changed by hand") + return entry + + +def _read(path: str) -> dict: + try: + with open(path, encoding="utf-8") as f: + return json.load(f) + except FileNotFoundError: + raise NotFound(f"{path}: no such file") + except (OSError, ValueError) as e: + raise Refused(f"{path}: cannot read it as JSON: {e}") + + +def load(benchmark: str, name: str, root: Optional[str] = None) -> dict: + path = path_of(benchmark, name, root) + if not os.path.isfile(path): + raise NotFound(f"no task set {name!r} of {benchmark} (in {os.path.dirname(path)})") + entry = check(_read(path), path) + if entry["name"] != name or entry["benchmark"] != benchmark: + raise Refused(f"{path}: it names {entry['benchmark']}/{entry['name']}, not {benchmark}/{name}") + return entry + + +def latest(entry: dict, rev: Optional[int] = None) -> dict: + """The list ``entry`` holds: its latest, the only one of a set made since sets were frozen. ``rev``, the number a + recipe or a command from before named it by, is taken when it is that list's, and refused otherwise.""" + last = max(entry["revisions"], key=lambda r: r["revision"]) + if rev is not None and rev != last["revision"]: + raise NotFound(f"{entry['name']}@{rev} names an earlier list of the task set {label_of(entry)}: a set is " + f"read as its latest list now; name it {entry['name']}") + return last + + +# the name the modules that read a set by its list number knew it by +revision = latest + + +def entries(benchmark: Optional[str] = None, root: Optional[str] = None) -> Tuple[List[dict], List[str]]: + """Every entry (of ``benchmark``), by benchmark and name; and the files that could not be read.""" + base = _folder(None, root) + got, bad = [], [] + try: + benches = sorted(os.listdir(base)) if benchmark is None else [_bench_key(benchmark)] + except FileNotFoundError: + return [], [] + for b in benches: + if not definitions._KEY.match(b): + continue + try: + folder = _folder(b, root) + except Refused as e: + bad.append(str(e)) + continue + if not os.path.isdir(folder): + continue + for fname in sorted(os.listdir(folder)): + if not fname.endswith(".json") or fname.startswith("."): + continue + try: + got.append(load(b, fname[:-5], root)) + except Refused as e: + bad.append(str(e)) + return got, bad + + +def rows(benchmark: str, root: Optional[str] = None) -> List[dict]: + """The readable entries of ``benchmark`` as a page lists them, by name: {name, label, description, dataset, + version, units, date}, ``units`` the number of its ids, ``date`` the day its list was made, ``version`` "" + for a set made before sets recorded one.""" + out = [] + for e in entries(benchmark, root)[0]: + last = latest(e) + out.append({"name": e["name"], "label": label_of(e), "description": e.get("description") or "", "dataset": e["dataset"], + "version": e.get("version") or "", "units": len(last["units"]), "date": last["date"]}) + return out + + +def by_id(benchmark: str, set_id: str, name: str = "", root: Optional[str] = None) -> Optional[dict]: + """The readable entry of ``benchmark`` holding the id ``set_id``, whatever its name now; None when there is none. + ``name``, the name it was known by, is read first.""" + if not set_id: + return None + if name: + try: + entry = load(benchmark, name, root) + except Refused: + entry = None + if entry is not None and entry["id"] == set_id: + return entry + try: + return next((e for e in entries(benchmark, root)[0] if e["id"] == set_id), None) + except Refused: + return None + + +def plain(e: Refused, benchmark: str, name: str) -> str: + """Why the set ``name`` could not be read, in a line for a page: no file's path.""" + if isinstance(e, Earlier): + return f"The task set {name} is of an earlier format, which kept a run's options: delete it and make it again." + if isinstance(e, NotFound): + return f"There is no task set {name}." + return f"The task set {name} cannot be read: nullius standard set show {benchmark} {name} says why." + + +def write(entry: dict, root: Optional[str] = None) -> str: + """The entry written whole, in place of the old file at once.""" + path = path_of(entry["benchmark"], entry["name"], root) + os.makedirs(os.path.dirname(path), exist_ok=True) + ordered = {"schema": SCHEMA, **{k: entry[k] for k in HEADER if k in entry}, + "revisions": sorted(entry["revisions"], key=lambda r: r["revision"])} + fd, tmp = tempfile.mkstemp(prefix=".set-", suffix=".json", dir=os.path.dirname(path)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(ordered, f, indent=2, ensure_ascii=False) + f.write("\n") + os.replace(tmp, path) + except BaseException: + if os.path.exists(tmp): + os.unlink(tmp) + raise + return path + + +def _dataset(bench: dict, dataset: Optional[str]) -> str: + ids = [d["id"] for d in bench.get("datasets") or []] + if not dataset: + raise Refused(f"--dataset: the dataset the set is cut from, one of {', '.join(ids)}") + if dataset not in ids: + raise Refused(f"{bench['label']} has no dataset {dataset!r}: {', '.join(ids)}") + return dataset + + +def create(bench: dict, label: str, *, dataset: str, units: List[str], description: str = "", note: str = "", + root: Optional[str] = None) -> dict: + """A new entry labelled ``label``, its name made from it (``name_for``), at the version ``bench`` is; written. + A label another set has already gives the next free name.""" + label = check_label(label) + entry = {"id": uuid.uuid4().hex, "name": name_for(bench["key"], label, root), "label": label, + "description": description or "", "benchmark": bench["key"], + **({"version": version_of(bench)} if version_of(bench) else {}), "dataset": _dataset(bench, dataset)} + path = path_of(bench["key"], entry["name"], root) + if os.path.lexists(path): + raise Refused(f"a task set {entry['name']!r} of {bench['key']} exists already ({path})") + ids = _ids(units, f"the set {label}") + entry["revisions"] = [{"revision": 1, "date": _now(), "note": note or "", "units": ids, "hash": _hash_of(entry, ids)}] + write(entry, root) + return entry + + +def _file_of(benchmark: str, name: str, root: Optional[str]) -> str: + """The entry's file as named in its folder (a link stays a link), refused when it leads out of the folder.""" + path_of(benchmark, name, root) + path = os.path.join(_folder(benchmark, root), name + ".json") + if not os.path.isfile(path): + raise NotFound(f"no task set {name!r} of {benchmark} (in {os.path.dirname(path)})") + return path + + +def rename(benchmark: str, name: str, label: str, root: Optional[str] = None) -> dict: + """The entry labelled ``label`` and named by it (``name_for``, its own name free), its id, description and list + kept: written under the new name, then the old file removed. Refused: a label it has already or one not + allowed, and an entry that cannot be read.""" + old = _file_of(benchmark, name, root) + entry = load(benchmark, name, root) + label = check_label(label) + if label == label_of(entry): + raise Refused(f"the task set {name} is named {label!r} already") + new = name_for(benchmark, label, root, but=name) + if new != name and os.path.lexists(os.path.join(_folder(benchmark, root), new + ".json")): + raise Refused(f"a task set {new!r} of {benchmark} exists already") + entry = dict(entry, name=new, label=label) + write(entry, root) + if new != name: + os.unlink(old) + return entry + + +def delete(benchmark: str, name: str, root: Optional[str] = None) -> Optional[dict]: + """Remove the entry's file: the entry as it was, or None when it could not be read (an earlier format, a file + changed by hand). A job that ran it keeps its record.""" + path = _file_of(benchmark, name, root) + try: + entry = load(benchmark, name, root) + except NotFound: + raise + except Refused: + entry = None + os.unlink(path) + return entry + + +def _job_config(job_dir: str) -> dict: + cfg_path = os.path.join(job_dir, "config.json") + if not os.path.isfile(cfg_path): + raise NotFound(f"{job_dir}: no job (no config.json)") + cfg = _read(cfg_path) + if cfg.get("runner") != "standard" or not isinstance(cfg.get("standard"), dict): + raise Refused(f"{job_dir}: not a job of the Nullius standard") + return cfg + + +def _place(trial: str) -> int: + m = _TAG.search(trial) + return int(m.group(1)) if m else 1 << 30 + + +def outcome_names(given: Optional[List[str]]) -> set: + """``--outcome O,...`` (repeatable): the pages' outcome names, or passed, failed, infra.""" + out = set() + for word in (w.strip() for g in given or [] for w in g.split(",")): + if not word: + continue + if word in GROUPS: + out |= GROUPS[word] + elif word in classify.ORDER: + out.add(word) + else: + raise Refused(f"--outcome {word}: one of {', '.join(classify.ORDER)}, or {', '.join(GROUPS)}") + return out + + +def _job_dataset(cfg: dict) -> str: + return str(((cfg.get("datasets") or [{}])[0].get("name") or "")).rpartition("/")[2] + + +def from_job(bench: dict, job_dir: str, outcomes: Optional[List[str]] = None, named: Optional[List[str]] = None) -> dict: + """What a set made from a job holds: {dataset, units, note}. The trials of the + ``outcomes`` and the units ``named`` (each the full id a trial's ``standard.unit`` records), every unit + the job ran when neither is given; a unit of several attempts is taken when any of them is.""" + from nullius.runs import parse + from nullius.standard.runner import job + job_dir = os.path.abspath(job_dir.rstrip("/")) + cfg = _job_config(job_dir) + std = cfg["standard"] + if std.get("benchmark") != bench["key"]: + raise Refused(f"{job_dir} ran {std.get('benchmark')}, not {bench['key']}") + dataset = _job_dataset(cfg) + wanted = outcome_names(outcomes) + trials = [] + for trial_dir in job.trial_dirs(job_dir): + res = _read(os.path.join(trial_dir, "result.json")) + unit = (res.get("standard") or {}).get("unit") + if unit is None: + continue + t = parse.parse_trial(os.path.basename(job_dir), trial_dir) + trials.append((_place(os.path.basename(trial_dir)), str(unit), t.outcome if t else classify.UNKNOWN)) + trials.sort() + held = list(dict.fromkeys(u for _, u, _ in trials)) + if not held: + raise Refused(f"{job_dir}: no trial records its unit") + names = list(dict.fromkeys(named or [])) + unknown = [u for u in names if u not in held] + if unknown: + raise Refused(f"{job_dir} has no trial of {', '.join(unknown)}") + if wanted or names: + chosen = {u for _, u, o in trials if o in wanted} | set(names) + units = [u for u in held if u in chosen] + else: + units = held + if not units: + raise Refused(f"{job_dir} has no trial of the outcomes {', '.join(sorted(wanted))}") + said = ([f"outcomes {','.join(outcomes)}"] if outcomes else []) + ([f"{len(names)} named"] if names else []) + return {"dataset": dataset, "units": units, "note": f"from the job {cfg.get('job_name') or os.path.basename(job_dir)}" + + (f": {'; '.join(said)}" if said else "")} + + +def record(entry: dict, rev: Optional[dict] = None) -> dict: + """What a job's config keeps of the set it ran (``standard.task_set``): its id, name, label, the number and + hash of its list, its units, and the version it was made at when it recorded one.""" + rev = rev or latest(entry) + return {"id": entry["id"], "name": entry["name"], "label": label_of(entry), "revision": rev["revision"], + "hash": rev["hash"], "units": rev["units"], **({"version": entry["version"]} if entry.get("version") else {})} + + +def for_run(bench: dict, ref: str, *, dataset: Optional[str] = None, units_given: bool = False, + root: Optional[str] = None) -> Tuple[dict, str]: + """``run --set NAME``: (the record the job keeps, the dataset), the set's dataset taken over the run's. + A ``--units`` beside it, or another ``--dataset``, is refused. The run's benchmark options are its own, as + on the whole dataset: the run then refuses an id its driver does not list under them.""" + name, rev = split_ref(ref) + if units_given: + raise Refused(f"--set {ref} and --units: the set lists the units, give one or the other") + entry = load(bench["key"], name, root) + got = latest(entry, rev) + if dataset and dataset != entry["dataset"]: + raise Refused(f"--dataset {dataset}: the task set {name} is cut from the dataset {entry['dataset']}") + return record(entry, got), entry["dataset"] + + +def import_path(path: str, root: Optional[str] = None) -> Tuple[dict, bool]: + """(the entry, whether it was written): an entry's file, or a job that ran a set (its ``standard.task_set``), + written here when no set of that name is. When one is, with the same id and the same list, nothing is written. + Refused: the entry here has another id, another entry holds the id, or the same id holds another list here.""" + path = os.path.abspath(path.rstrip("/")) + if os.path.isdir(path): + cfg = _job_config(path) + rec = cfg["standard"].get("task_set") + if not isinstance(rec, dict): + raise NotFound(f"{path}: the job ran no task set") + missing = [k for k in RECORD if k not in rec] + if missing: + raise Refused(f"{path}: its task set's record has no {', '.join(missing)}") + incoming = {"schema": SCHEMA, "id": rec["id"], "name": rec["name"], + **{k: rec[k] for k in RECORD_MORE if k in rec}, "description": "", + "benchmark": cfg["standard"].get("benchmark"), "dataset": _job_dataset(cfg), + "revisions": [{"revision": rec["revision"], "date": _now(), + "note": f"from the job {cfg.get('job_name') or os.path.basename(path)}", + "units": rec["units"], "hash": rec["hash"]}]} + elif os.path.isfile(path): + incoming = _read(path) + else: + raise NotFound(f"{path}: no such file or job") + check(incoming, path) + bench, name = incoming["benchmark"], incoming["name"] + others, _ = entries(bench, root) + holder = next((e for e in others if e["id"] == incoming["id"] and e["name"] != name), None) + if holder: + raise Refused(f"the set {incoming['id']} is here already, named {holder['name']}") + target = path_of(bench, name, root) + if not os.path.exists(target): + incoming = {k: v for k, v in incoming.items() if k != "schema"} + write(incoming, root) + return incoming, True + here = load(bench, name, root) + if here["id"] != incoming["id"]: + raise Refused(f"a task set {name!r} of {bench} with another id is here already ({target})") + if here["dataset"] != incoming["dataset"]: + raise Refused(f"the set {name} here differs in its dataset: {here['dataset']!r}, not {incoming['dataset']!r}") + mine, theirs = latest(here), latest(incoming) + if mine["hash"] != theirs["hash"]: + raise Refused(f"the set {name} holds another list here (hash {mine['hash'][:12]}, not {theirs['hash'][:12]}): " + "the same id with another list") + return here, False diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index 04ef41646..ed9e81769 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -410,6 +410,7 @@ "standard", "started_at", "state", + "task_set", "total_cache_tokens", "total_cost_usd", "total_input_tokens", diff --git a/app/tests/test_cli_contract.py b/app/tests/test_cli_contract.py index 3863043a9..721d70fdf 100644 --- a/app/tests/test_cli_contract.py +++ b/app/tests/test_cli_contract.py @@ -15,6 +15,7 @@ import hashlib import json import os +import re import shutil import socket import subprocess @@ -293,19 +294,35 @@ def test_a_key_in_the_recorded_command_is_not_echoed_by_show_json(self): class TaskSetCommands(Scratch): def test_help_and_refusals_of_the_task_set_commands(self): - """The units command has help with its examples and exit codes; a + """Each set command, and units, has help with its examples and exit codes; a refusal is one line on stderr with nothing on stdout, 2 for a usage error or a refusal, 3 for what is not found, and writes nothing.""" cat = os.path.join(self.tmp, "catalogue") env = {"NULLIUS_CATALOGUE": cat, "NULLIUS_HOME": os.path.join(self.tmp, "profile")} - for sub in (("units",),): + for sub in (("set",), ("set", "create"), ("set", "list"), ("set", "show"), ("set", "rename"), + ("set", "delete"), ("set", "import"), ("units",)): with self.subTest(help=sub): out = self.sh("standard.cli", *sub, "--help", env=env) self.assertEqual(out.returncode, 0, out.stderr) for line in ("usage:", "examples:", "exit codes:"): self.assertIn(line, out.stdout) self.assertEqual(out.stderr, "") + listed = write_json(Path(self.tmp, "ten.txt"), "HumanEval/0\nHumanEval/1\n") cases = [ + (["set", "create", "humaneval"], 2, "usage:"), + (["set", "create", "humaneval", "..", "--dataset", "humaneval", "--units", listed], 2, "needs a letter or a digit"), + (["set", "show", "humaneval", "a/b"], 2, "not a task set's name"), + (["set", "create", "humaneval", "ok", "--dataset", "nope", "--units", listed], 2, "no dataset 'nope'"), + (["set", "create", "no-such-bench", "ok", "--dataset", "x", "--units", listed], 3, "no benchmark"), + (["set", "show", "humaneval", "nowhere"], 3, "no task set 'nowhere'"), + (["set", "update", "humaneval", "nowhere", "--add", "HumanEval/2"], 2, "invalid choice: 'update'"), # a set is frozen + (["set", "rename", "humaneval", "nowhere", "elsewhere"], 3, "no task set 'nowhere'"), + (["set", "rename", "humaneval", "nowhere"], 2, "usage:"), + (["set", "delete", "humaneval", "nowhere"], 3, "no task set 'nowhere'"), + (["set", "import", os.path.join(self.tmp, "absent.json")], 3, "no such file or job"), + (["set", "create", "humaneval", "ok", "--dataset", "humaneval", "--units", listed, "--bench-option", "a=b"], 2, + "unrecognized arguments: --bench-option"), + (["set", "create", "humaneval", "ok", "--dataset", "humaneval"], 2, "--units FILE, --from-job"), (["units", "humaneval"], 2, "usage:"), (["units", "humaneval", "--dataset", "nope"], 3, "no dataset 'nope'"), (["units", "no-such-bench", "--dataset", "x"], 3, "no benchmark"), @@ -324,6 +341,18 @@ def test_help_and_refusals_of_the_task_set_commands(self): self.assertEqual(out.stderr, "refused: cannot prepare humaneval's dataset humaneval for its listing: " "git is not on this machine\n") self.assertFalse(os.path.exists(cat)) + out = self.sh("standard.cli", "set", "list", "--json", env=env) + self.assertEqual((out.returncode, json.loads(out.stdout), out.stderr), (0, [], "")) + + def test_the_index_of_commands_names_each_set_command_there_is_and_no_other(self): + """The commands' index (docs/cli/README.md) names the set commands one by one: the ones ``set`` takes.""" + out = self.sh("standard.cli", "set", "--help", env={"NULLIUS_HOME": os.path.join(self.tmp, "profile")}) + self.assertEqual(out.returncode, 0, out.stderr) + taken = set(re.findall(r"^ ([a-z]+) ", out.stdout, re.M)) # the help's list of commands + row = next(line for line in (APP.parent / "docs" / "cli" / "README.md").read_text(encoding="utf-8").splitlines() + if line.startswith("| [Task sets]")) + listed = row[row.index("`set create`"):].split(";")[0] + self.assertEqual({name.removeprefix("set ") for name in re.findall(r"`([^`]+)`", listed)}, taken) # ── import.md ─────────────────────────────────────────────────────────────── diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index 71ee84ade..161934b49 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -814,6 +814,16 @@ def test_app_is_sent_at_its_content_address_and_the_part_runs_from_it(self): self.assertEqual(json.loads((self.tmp / "runs" / "std-shard-2of2" / "run.json").read_text())["catalogue_on_target"], "~/.nullius/runs/std-shard-2of2/catalogue") + def test_the_snapshot_a_host_is_sent_carries_the_recipes_task_sets(self): + self.plan.recipe = {"harness": "standard", "benchmark": "fakebench@1", "task_sets": {"all": "dev@2", "more": "other"}} + ex = self.run_it() + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + self.assertEqual(execution.standard_payload.build.call_args.kwargs["sets"], [("fakebench", "dev"), ("fakebench", "other")]) + self.plan.recipe = {} + self.plan.name = "std-plain" + self.run_it() + self.assertEqual(execution.standard_payload.build.call_args.kwargs["sets"], []) + def test_gaias_hugging_face_token_is_handed_from_data_providers_alone(self): # over the launcher's stdin as a licence is, read from Settings → Data providers; a value GAIA's own folder # holds under that name is never sent diff --git a/app/tests/test_migrate.py b/app/tests/test_migrate.py index 1de42710f..60ff0db5a 100644 --- a/app/tests/test_migrate.py +++ b/app/tests/test_migrate.py @@ -9,6 +9,7 @@ from unittest.mock import patch from nullius import migrate, paths, settings +from nullius.standard.runner import sets class Migration(unittest.TestCase): @@ -80,6 +81,26 @@ def test_workspaces_judgements_and_custom_entries_survive_without_moving_raw_run self.assertEqual(settings.in_file(paths.settings_file())["RUNS_DIR"], str(self.checkout / "runs")) self.assertTrue((workspace / "workspace.json").exists()) + def test_task_sets_and_the_lists_of_one_made_before_survive_migration(self): + source = self.checkout / "app/nullius/catalogue" + bench = {"key": "fakebench", "datasets": [{"id": "all"}]} + entry = sets.create(bench, "dev", dataset="all", units=["good"], root=str(source)) + # a set made before sets were frozen holds a second list + entry["revisions"].append({"revision": 2, "date": "2026-11-18T10:00:00Z", "note": "one more", "units": ["good", "model"], + "hash": sets.content_hash("fakebench", "all", ["good", "model"])}) + sets.write(entry, root=str(source)) + entry = sets.load("fakebench", "dev", str(source)) + original = Path(sets.path_of("fakebench", "dev", str(source))).read_bytes() + code, output = self.run_cli() + self.assertEqual(code, 0, output) + self.assertIn("catalogue_entries: 1", output) + self.assertFalse(self.profile.exists()) + self.assertEqual(self.run_cli("--apply")[0], 0) + self.assertEqual(sets.load("fakebench", "dev"), entry) + dest = Path(sets.path_of("fakebench", "dev")) + self.assertEqual(dest.read_bytes(), original) + self.assertEqual(Path(sets.path_of("fakebench", "dev", str(source))).read_bytes(), original) + def test_licences_are_opt_in_and_copied_privately(self): secret = self.root / "legacy-secrets/bench" secret.mkdir(parents=True) diff --git a/app/tests/test_standard_sets.py b/app/tests/test_standard_sets.py new file mode 100644 index 000000000..19d181e62 --- /dev/null +++ b/app/tests/test_standard_sets.py @@ -0,0 +1,660 @@ +"""Task sets (``standard/runner/sets.py``): a named list of a benchmark's units in the +user catalogue, with an id, a label and the name made from it, the version it +was made at, and no option. The content hash says the same for the same ids in +any order and changes with an id or the dataset; a set is frozen: nothing adds +to its list, and a file of several lists from before reads as its latest, +unchanged; a label makes a name in lower case with hyphens, a second equal one +``-2``; a name that would leave the benchmark's folder is refused; a set is +made from a file or from a job's trials by outcome or by name; an entry comes +in from its file or from a job that ran it. ``run --set`` takes the set's +dataset, refuses what contradicts it, runs under any options it is given, +refuses ids its driver does not list under them (naming both versions for a set +made at another), and records the set in the job's config. No key, no network: +the runs are a control's.""" +from __future__ import annotations + +import copy +import io +import json +import os +import shutil +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from unittest import mock + +from nullius import progress +from nullius.harbor import feed +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.requirements import install +from nullius.standard.runner import job, merge, run, sets, shard + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +NOP = {"nop": {"source": "nullius", "from": "nothing said"}} +MODE = {"mode": {"summary": "a mode the listing follows", "values": ["plain", "hard"], "default": "plain"}} +DATASET = ["good", "wrong", "slow", "model"] + + +def read(path): + with open(path) as f: + return json.load(f) + + +class Scratch(unittest.TestCase): + """A catalogue of its own (``NULLIUS_CATALOGUE``), the fake benchmark with a control and an option.""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="nullius-sets-") + self.addCleanup(shutil.rmtree, self.tmp, True) + self.cat = os.path.join(self.tmp, "catalogue") + self.jobs = os.path.join(self.tmp, "jobs") + self.b = dict(definitions.get("benchmark", "fakebench", ROOT), controls=NOP, options=MODE) + for patch in (mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": self.cat}), mock.patch.object(install, "HOME", os.path.join(self.tmp, "home")), + mock.patch.object(cli, "_bench", return_value=self.b), mock.patch.object(cli, "_find_bench", return_value=self.b), + mock.patch.object(cli, "_exit_on_term"), mock.patch.object(cli.settings, "load"), + mock.patch.object(progress, "ECHO", None)): + patch.start() + self.addCleanup(patch.stop) + + def file(self, text, name="units.txt"): + path = os.path.join(self.tmp, name) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return path + + def cli(self, *args): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + code = cli.main(list(args)) + return code, out.getvalue(), err.getvalue() + + def make(self, label, text, *extra): + name = sets.name_for("fakebench", label) + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file(text), *extra) + self.assertEqual(code, 0, err) + return sets.load("fakebench", name) + + def trials(self, job_dir): + return sorted(d for d in os.listdir(job_dir) if "__u" in d) + + +class Hash(Scratch): + def test_the_same_ids_in_another_order_or_from_a_file_with_comments_hash_the_same(self): + a = self.make("a", "good\nmodel\n") + b = self.make("b", "# the same two\n\n model \r\ngood\n") + self.assertEqual(sets.revision(a)["hash"], sets.revision(b)["hash"]) + self.assertNotEqual(a["id"], b["id"]) # two entries of equal lists stay two sets + self.assertEqual(sets.content_hash("fakebench", "all", ["good", "model"]), + sets.content_hash("fakebench", "all", ["model", "good"])) + + def test_it_changes_with_an_id_or_the_dataset(self): + base = sets.content_hash("fakebench", "all", ["good", "model"]) + for other in (sets.content_hash("fakebench", "all", ["good", "slow"]), + sets.content_hash("fakebench", "responding", ["good", "model"])): + self.assertNotEqual(base, other) + self.assertEqual(sets.revision(self.make("plain", "good\nmodel\n"))["hash"], base) + + def test_a_file_changed_by_hand_is_refused_where_it_is_read(self): + self.make("edited", "good\nmodel\n") + path = sets.path_of("fakebench", "edited") + entry = read(path) + entry["revisions"][0]["units"].append("slow") + with open(path, "w") as f: + json.dump(entry, f) + with self.assertRaisesRegex(sets.Refused, "changed by hand"): + sets.load("fakebench", "edited") + + +class NoOption(Scratch): + def test_set_create_takes_no_benchmark_option(self): + for source in (["--units", self.file("good\n")], ["--search", "good"]): + with self.subTest(source=source[0]): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err), self.assertRaises(SystemExit) as stop: + cli.main(["set", "create", "fakebench", "dev", "--dataset", "all", *source, "--bench-option", "mode=hard"]) + self.assertEqual((stop.exception.code, out.getvalue()), (2, "")) + self.assertIn("usage:", err.getvalue()) + self.assertIn("unrecognized arguments: --bench-option", err.getvalue()) + self.assertFalse(os.path.exists(self.cat)) + + def test_the_entry_holds_no_option_and_an_earlier_entry_that_does_is_refused_where_it_is_read(self): + entry = self.make("dev", "good\nmodel\n") + self.assertEqual(sorted(read(sets.path_of("fakebench", "dev"))), + ["benchmark", "dataset", "description", "id", "label", "name", "revisions", "schema"]) + self.assertEqual(sorted(sets.record(entry, sets.revision(entry))), ["hash", "id", "label", "name", "revision", "units"]) + for field, value in (("benchmark_options", {"mode": "hard"}), ("setup", "yours"), ("benchmark_version", "1")): + with self.subTest(field=field): + path = sets.path_of("fakebench", "dev") + with open(path, "w") as f: + json.dump(dict(entry, schema=sets.SCHEMA, **{field: value}), f) + with self.assertRaisesRegex(sets.Refused, f"holds {field}, which a task set does not hold"): + sets.load("fakebench", "dev") + code, out, err = self.cli("set", "show", "fakebench", "dev") + self.assertEqual((code, out), (2, "")) + self.assertIn(f"holds {field}", err) + + +class Frozen(Scratch): + def earlier(self, name="dev"): + """A set made before sets were frozen, as its file was written then: two lists, no label, no version.""" + folder = os.path.join(self.cat, "sets", "fakebench") + os.makedirs(folder, exist_ok=True) + lists = [["good", "model"], ["good", "model", "slow"]] + entry = {"schema": sets.SCHEMA, "id": "a" * 32, "name": name, "description": "from before", "benchmark": "fakebench", + "dataset": "all", "revisions": [{"revision": i, "date": f"2026-11-1{i}T10:00:00Z", "note": "", "units": u, + "hash": sets.content_hash("fakebench", "all", u)} for i, u in enumerate(lists, 1)]} + path = os.path.join(folder, name + ".json") + with open(path, "w") as f: + json.dump(entry, f, indent=2) + return path + + def test_a_set_of_several_lists_from_before_reads_as_its_latest_and_is_not_rewritten(self): + path = self.earlier() + with open(path, "rb") as f: + before = f.read() + entry = sets.load("fakebench", "dev") + self.assertEqual((sets.label_of(entry), sets.latest(entry)["units"]), ("dev", ["good", "model", "slow"])) + self.assertEqual(sets.rows("fakebench"), [{"name": "dev", "label": "dev", "description": "from before", "dataset": "all", + "version": "", "units": 3, "date": "2026-11-12T10:00:00Z"}]) + code, out, err = self.cli("set", "show", "fakebench", "dev") + self.assertEqual(code, 0, err) + self.assertTrue(out.startswith("dev: 3 units of fakebench all\n"), out) + self.assertNotIn("revision", out) + # a recipe or a command from before names its latest list as NAME@2: the same set; NAME@1 is refused + self.assertEqual(sets.for_run(self.b, "dev@2")[0]["units"], ["good", "model", "slow"]) + code, out, err = self.cli("set", "show", "fakebench", "dev@1") + self.assertEqual((code, out), (3, "")) + self.assertIn("dev@1 names an earlier list of the task set dev: a set is read as its latest list now; name it dev", err) + code, out, err = self.run_nop("--set", "dev", "--name", "from-before") + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(os.path.join(self.jobs, "from-before")), ["good__u0000", "model__u0003", "slow__u0002"]) + with open(path, "rb") as f: + self.assertEqual(f.read(), before) + + def run_nop(self, *args): + return self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "-j", "2", *args) + + +class Names(Scratch): + def test_a_label_makes_a_name_in_lower_case_with_hyphens_and_a_second_one_takes_two(self): + for label, name in (("Custom task set", "custom-task-set"), ("custom task set", "custom-task-set-2"), + (" Custom task set! ", "custom-task-set-3"), ("Café au lait", "cafe-au-lait"), + ("a/b", "a-b"), ("../up", "up"), ("x..y", "x-y"), ("ÉTÉ 2026", "ete-2026"), ("日本", "task-set"), + ("dev", "dev")): + with self.subTest(label=label): + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file("good\n")) + self.assertEqual(code, 0, err) + entry = sets.load("fakebench", name) + self.assertEqual(entry["label"], label.strip()) + self.assertTrue(out.startswith(f"wrote {sets.path_of('fakebench', name)}: "), out) + self.assertEqual(sets.slug("b" * 70), "b" * 64) + self.assertEqual(sets.name_for("fakebench", "b" * 70), "b" * 64) + sets.create(self.b, "b" * 70, dataset="all", units=["good"]) + self.assertEqual(sets.name_for("fakebench", "b" * 70), "b" * 62 + "-2") + + def test_a_label_with_no_letter_or_digit_on_two_lines_or_too_long_is_refused(self): + for label, said in (("", "needs a name"), (" ", "needs a name"), ("..", "needs a letter or a digit"), + ("a\nb", "one line"), ("x" * 81, "at most 80 characters")): + with self.subTest(label=label): + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file("good\n")) + self.assertEqual((code, out), (2, "")) + self.assertIn(said, err) + self.assertFalse(os.path.exists(os.path.join(self.cat, "sets", "fakebench"))) + + def test_a_name_that_would_leave_the_benchmarks_folder_is_refused(self): + for name in ("a/b", "..", "", ".hidden", "../up", "a\\b", "x..y"): + with self.subTest(name=name): + code, out, err = self.cli("set", "show", "fakebench", name) + self.assertEqual((code, out), (2, "")) + self.assertIn("not a task set's name", err) + + def test_links_cannot_escape_through_parent_folders_or_an_entry(self): + entry = self.make("dev", "good\n") + exported = self.file(json.dumps(read(sets.path_of("fakebench", "dev"))), "export.json") + for relative in ("sets", "sets/fakebench", "sets/fakebench/dev.json"): + with self.subTest(path=relative): + path = os.path.join(self.cat, relative) + outside = os.path.join(self.tmp, "outside") + os.rename(path, outside) + os.symlink(outside, path) + try: + for action in (lambda: sets.load("fakebench", "dev"), + lambda: sets.write(entry), + lambda: sets.rename("fakebench", "dev", "other"), + lambda: sets.import_path(exported)): + with self.assertRaisesRegex(sets.Refused, "outside"): + action() + if relative != "sets/fakebench/dev.json": + with self.assertRaisesRegex(sets.Refused, "outside"): + sets.create(self.b, "new", dataset="all", units=["good"]) + with mock.patch.object(sets.os, "listdir", wraps=os.listdir) as listed: + try: + found, bad = sets.entries() + except sets.Refused as e: + self.assertIn("outside", str(e)) + else: + self.assertEqual(found, []) + self.assertTrue(any("outside" in problem for problem in bad)) + self.assertNotIn(mock.call(path), listed.call_args_list) + finally: + os.unlink(path) + os.rename(outside, path) + self.assertEqual(sets.load("fakebench", "dev"), entry) + self.assertFalse(os.path.exists(sets.path_of("fakebench", "new"))) + + def test_a_label_that_exists_makes_another_set(self): + first = self.make("dev", "good\n") + code, out, err = self.cli("set", "create", "fakebench", "dev", "--dataset", "all", "--units", self.file("model\n")) + self.assertEqual(code, 0, err) + self.assertIn(": dev-2 (dev), 1 task of all", out) + self.assertEqual(sets.load("fakebench", "dev"), first) + self.assertEqual(sets.revision(sets.load("fakebench", "dev-2"))["units"], ["model"]) + + +class RenameAndDelete(Scratch): + def test_a_rename_keeps_the_id_and_the_list_makes_the_name_again_and_the_id_finds_it(self): + first = self.make("dev", "good\nmodel\n", "--description", "two of them") + code, out, err = self.cli("set", "rename", "fakebench", "dev", "Misses of June") + self.assertEqual((code, err), (0, "")) + self.assertTrue(out.startswith("renamed dev to misses-of-june (Misses of June) ("), out) + self.assertIn("its id and its tasks kept", out) + got = sets.load("fakebench", "misses-of-june") + self.assertEqual((got["id"], got["label"], got["description"], got["revisions"]), + (first["id"], "Misses of June", "two of them", first["revisions"])) + self.assertEqual(sorted(os.listdir(os.path.join(self.cat, "sets", "fakebench"))), ["misses-of-june.json"]) + self.assertEqual(sets.by_id("fakebench", first["id"], "dev")["name"], "misses-of-june") + # another set made under the old name is another set: the id still finds the renamed one + self.make("dev", "good\n") + self.assertEqual(sets.by_id("fakebench", first["id"], "dev")["name"], "misses-of-june") + self.assertIsNone(sets.by_id("fakebench", "0" * 32, "dev")) + # a label that makes the same name changes the label alone; one another set holds makes the next name + self.assertEqual(sets.rename("fakebench", "misses-of-june", "misses of june")["name"], "misses-of-june") + self.assertEqual(sets.rename("fakebench", "misses-of-june", "Dev")["name"], "dev-2") + + def test_its_own_label_an_empty_one_and_a_set_not_there_are_refused(self): + dev = self.make("dev", "good\n") + other = self.make("other", "model\n") + for new, code, said in (("dev", 2, "is named 'dev' already"), ("", 2, "needs a name"), ("..", 2, "letter or a digit")): + with self.subTest(new=new): + got = self.cli("set", "rename", "fakebench", "dev", new) + self.assertEqual(got[:2], (code, "")) + self.assertIn(said, got[2]) + got = self.cli("set", "rename", "fakebench", "nowhere", "x") + self.assertEqual(got[:2], (3, "")) + self.assertIn("no task set 'nowhere'", got[2]) + self.assertEqual((sets.load("fakebench", "dev"), sets.load("fakebench", "other")), (dev, other)) + self.assertEqual(sorted(os.listdir(os.path.join(self.cat, "sets", "fakebench"))), ["dev.json", "other.json"]) + self.assertEqual(sets.rename("fakebench", "dev", "other")["name"], "other-2") + + def test_a_delete_removes_the_file_and_says_what_it_held(self): + self.make("Dev set", "good\nmodel\n") + path = sets.path_of("fakebench", "dev-set") + code, out, err = self.cli("set", "delete", "fakebench", "dev-set") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.strip(), f"deleted {path}: dev-set (Dev set), 2 units; jobs that ran it keep their record") + self.assertFalse(os.path.exists(path)) + code, out, err = self.cli("set", "delete", "fakebench", "dev-set") + self.assertEqual((code, out), (3, "")) + self.assertIn("no task set 'dev-set'", err) + + def test_a_delete_of_a_link_removes_the_link_and_not_the_set_it_leads_to(self): + self.make("dev", "good\n") + folder = os.path.join(self.cat, "sets", "fakebench") + path = os.path.join(folder, "alias.json") + os.symlink(os.path.join(folder, "dev.json"), path) + code, out, err = self.cli("set", "delete", "fakebench", "alias") + self.assertEqual(code, 0, err) + self.assertEqual(out.strip(), f"deleted {path}: an entry this version could not read") + self.assertEqual(sorted(os.listdir(folder)), ["dev.json"]) + self.assertEqual(sets.revision(sets.load("fakebench", "dev"))["units"], ["good"]) + + def test_an_entry_of_the_earlier_format_is_refused_plainly_and_can_be_deleted(self): + entry = self.make("old", "good\n") + path = sets.path_of("fakebench", "old") + with open(path, "w") as f: + json.dump(dict(entry, schema=sets.SCHEMA, benchmark_options={"mode": "hard"}, setup="yours"), f) + with self.assertRaises(sets.Earlier) as refused: + sets.load("fakebench", "old") + self.assertIn(path, str(refused.exception)) + said = sets.plain(refused.exception, "fakebench", "old") + self.assertEqual(said, "The task set old is of an earlier format, which kept a run's options: delete it and make it again.") + self.assertNotIn(self.tmp, said) + code, out, err = self.cli("set", "rename", "fakebench", "old", "new") + self.assertEqual((code, out), (2, "")) + self.assertIn("earlier format", err) + code, out, err = self.cli("set", "delete", "fakebench", "old") + self.assertEqual((code, out.strip(), err), (0, f"deleted {path}: an entry this version could not read", "")) + self.assertFalse(os.path.exists(path)) + + +class FromAJob(Scratch): + def job(self, name="graded"): + """A job as a run writes it: good passed, wrong failed, slow rate limited, a unit whose id has a slash passed.""" + d = os.path.join(self.jobs, name) + os.makedirs(d) + other = dict(definitions.control(self.b, "nop"), _kind="control") + units = ["good", "wrong", "slow", "group/model"] + job.write_config(d, job=name, bench=self.b, other=other, model="", provider="openai", dataset="all", units=units, + concurrency=1, granted=False, bench_options={"mode": "hard"}) + ends = {"good": ({"reward": 1.0}, None), "wrong": ({"reward": 0.0}, None), "slow": (None, ("RateLimitError", "429")), + "group/model": ({"reward": 1.0}, None)} + results = [] + for place, u in enumerate(units): + score, exc = ends[u] + trial = os.path.join(d, f"{u.rpartition('/')[2]}__u{place:04d}") + os.makedirs(trial) + results.append(job.write_trial(trial, job=name, bench=self.b, other=other, model="", unit=u, t0=1.0, t1=2.0, + produce=(1.0, 2.0), score=score, exception=exc, calls=[], trajectory=None)) + job.write_result(d, name, 1.0, 3.0, results, len(units)) + return d + + def test_outcome_takes_the_trials_of_those_outcomes_by_their_full_unit_ids(self): + d = self.job() + for name, outcome, want in (("passed", "passed", ["good", "group/model"]), ("misses", "failed,infra", ["wrong", "slow"]), + ("limited", "rate_limited", ["slow"])): + with self.subTest(outcome=outcome): + code, out, err = self.cli("set", "create", "fakebench", name, "--from-job", d, "--outcome", outcome) + self.assertEqual(code, 0, err) + entry = sets.load("fakebench", name) + self.assertEqual(sets.revision(entry)["units"], want) + self.assertEqual(entry["dataset"], "all") + self.assertNotIn("benchmark_options", entry) # the job ran under mode=hard; the set holds none + self.assertEqual(sets.revision(entry)["hash"], sets.content_hash("fakebench", "all", want)) + self.assertIn(f"outcomes {outcome}", sets.revision(entry)["note"]) + + def test_unit_takes_the_ones_named(self): + d = self.job() + code, out, err = self.cli("set", "create", "fakebench", "two", "--from-job", d, "--unit", "group/model", "--unit", "wrong") + self.assertEqual(code, 0, err) + self.assertEqual(sets.revision(sets.load("fakebench", "two"))["units"], ["wrong", "group/model"]) + code, out, err = self.cli("set", "create", "fakebench", "none", "--from-job", d, "--unit", "model") + self.assertEqual((code, out), (2, "")) + self.assertIn("no trial of model", err) # the trial's name is not its unit's id + code, out, err = self.cli("set", "create", "fakebench", "bad", "--from-job", d, "--outcome", "sideways") + self.assertEqual(code, 2) + self.assertIn("--outcome sideways", err) + + +class Import(Scratch): + def test_an_entry_comes_in_from_its_file_and_another_list_under_its_id_is_refused(self): + entry = self.make("dev", "good\nmodel\n") + exported = os.path.join(self.tmp, "dev.json") + shutil.copy(sets.path_of("fakebench", "dev"), exported) + elsewhere = os.path.join(self.tmp, "elsewhere") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", exported) + self.assertEqual(code, 0, err) + self.assertEqual(read(sets.path_of("fakebench", "dev")), read(exported)) + code, out, err = self.cli("set", "import", exported) + self.assertEqual(code, 0, err) + self.assertIn("here already", out) + # here, the same id with another list + other = read(exported) + other["revisions"][0]["units"] = ["good", "wrong"] + other["revisions"][0]["hash"] = sets.content_hash("fakebench", "all", ["good", "wrong"]) + with open(exported, "w") as f: + json.dump(other, f) + code, out, err = self.cli("set", "import", exported) + self.assertEqual((code, out), (2, "")) + self.assertIn("the same id with another list", err) + self.assertEqual(sets.load("fakebench", "dev")["id"], entry["id"]) + self.assertEqual(sets.revision(sets.load("fakebench", "dev"))["units"], ["good", "model"]) + + def test_import_checks_every_consumed_field_before_storing_an_entry_or_job_record(self): + entry = dict(self.make("dev", "good\n"), schema=sets.SCHEMA) + cases = [("entry", k, None, True) for k in ("id", "name", "description", "benchmark", "dataset")] + cases += [("entry", k, v, False) for k, v in (("label", ""), ("label", 1), ("version", []), ("version", ""))] + cases += [("revision", k, None, True) for k in sets.REVISION] + cases += [("entry", k, v, False) for k, v in ( + ("id", 1), ("name", []), ("description", {}), ("benchmark", False), ("dataset", {}), + ("benchmark_options", {}), ("setup", "yours"))] + cases += [("revision", k, v, False) for k, v in ( + ("revision", True), ("date", None), ("date", []), ("date", ""), ("note", None), + ("note", {}), ("units", [1]), ("units", [{}]), ("units", "good"), ("hash", []))] + rec = sets.record(entry, sets.revision(entry)) + jobs = [(k, None, True) for k in sets.RECORD] + jobs += [(k, v, False) for k, v in (("id", 1), ("name", []), ("revision", True), ("revision", 0), + ("units", [1]), ("units", "good"), ("units", []), ("hash", []), + ("hash", "0" * 64))] + source_job = os.path.join(self.tmp, "source-job") + os.makedirs(source_job) + for index, (section, field, value, missing) in enumerate(cases + [("job",) + c for c in jobs]): + elsewhere = os.path.join(self.tmp, f"elsewhere-{index}") + with self.subTest(section=section, field=field, value=value, missing=missing): + if section == "job": + got = dict(rec) + target = got + else: + got = copy.deepcopy(entry) + target = got if section == "entry" else got["revisions"][0] + if missing: + del target[field] + else: + target[field] = value + if section == "job": + self.file(json.dumps({"runner": "standard", "datasets": [{"name": "fakebench/all"}], + "standard": {"benchmark": "fakebench", "task_set": got}}), + "source-job/config.json") + path = source_job + else: + path = self.file(json.dumps(got), "incoming.json") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", path) + self.assertEqual((code, out), (2, ""), err) + self.assertTrue(err.startswith("refused: "), err) + self.assertFalse(os.path.exists(elsewhere)) + + def test_an_entry_comes_in_from_a_job_that_ran_it(self): + entry = self.make("dev", "model\ngood\n", "--description", "two of them") + code, out, err = self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "--set", "dev", "--bench-option", "mode=hard", + "--name", "ran") + self.assertEqual(code, 0, out + err) + elsewhere = os.path.join(self.tmp, "elsewhere") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", os.path.join(self.jobs, "ran")) + self.assertEqual(code, 0, err) + got = sets.load("fakebench", "dev") + # the record holds the set's id, name, label, hash and units: the rest is the job's or the import's + self.assertEqual({k: got[k] for k in ("id", "name", "label", "benchmark", "dataset", "description")}, + {**{k: entry[k] for k in ("id", "name", "label", "benchmark", "dataset")}, "description": ""}) + self.assertEqual([{k: r[k] for k in ("revision", "units", "hash")} for r in got["revisions"]], + [{k: r[k] for k in ("revision", "units", "hash")} for r in entry["revisions"]]) + self.assertEqual(got["revisions"][0]["note"], "from the job ran") + # the entry exported from here then adds nothing there: the same id, revision and hash + code, out, err = self.cli("set", "import", sets.path_of("fakebench", "dev", self.cat)) + self.assertEqual(code, 0, err) + self.assertIn("here already", out) + code, out, err = self.cli("set", "import", self.jobs) + self.assertEqual((code, out), (3, "")) + self.assertIn("no job", err) + # another set under the name: refused, the entry here unchanged + shutil.rmtree(os.path.join(self.cat, "sets")) + self.make("dev", "model\ngood\n") + code, out, err = self.cli("set", "import", os.path.join(self.jobs, "ran")) + self.assertEqual(code, 2) + self.assertIn("another id", err) + + +class Running(Scratch): + def run_cli(self, *args): + return self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "-j", "2", *args) + + def test_an_empty_set_is_refused_before_any_unit(self): + code, out, err = self.run_cli("--set", "", "--name", "empty") + self.assertEqual(code, 2, out + err) + self.assertIn("not a task set's name", out) + self.assertFalse(os.path.exists(self.jobs)) + + def test_each_contradiction_is_refused_before_any_unit_with_a_plain_message(self): + self.make("dev", "good\nmodel\n") + for args, said in ((["--dataset", "responding"], "--dataset responding: the task set dev is cut from the dataset all"), + (["--units", self.file("good\n")], "the set lists the units, give one or the other"), + (["--set", "nowhere"], "no task set 'nowhere' of fakebench")): + with self.subTest(args=args): + code, out, err = self.run_cli(*(["--set", "dev"] if "--set" not in args else []), *args) + self.assertEqual(code, 2, out + err) + self.assertEqual(len(out.strip().splitlines()), 1, out) + self.assertTrue(out.startswith("refused: "), out) + self.assertIn(said, out) + self.assertFalse(os.path.exists(self.jobs)) # no job was begun + code, out, err = self.run_cli("--set", "dev", "--dataset", "all", "--bench-option", "mode=hard", "--name", "agrees") + self.assertEqual(code, 0, out + err) + + def test_two_runs_under_two_values_of_an_option_both_start_and_record_the_same_set(self): + entry = self.make("dev", "good\nwrong\n") + rev = sets.revision(entry) + records = [] + for value in ("plain", "hard"): + with self.subTest(value=value): + code, out, err = self.run_cli("--set", "dev", "--bench-option", f"mode={value}", "--name", value) + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(os.path.join(self.jobs, value)), ["good__u0000", "wrong__u0001"]) + cfg = read(os.path.join(self.jobs, value, "config.json")) + self.assertEqual(cfg["standard"]["benchmark_options"], {"mode": value}) + records.append(cfg["standard"]["task_set"]) + self.assertEqual(records[0], records[1]) + self.assertEqual({k: records[0][k] for k in ("id", "revision", "hash")}, + {"id": entry["id"], "revision": 1, "hash": rev["hash"]}) + self.assertEqual(rev["hash"], sets.content_hash("fakebench", "all", ["good", "wrong"])) # no option in it + + def listing_by_mode(self): + """The fake benchmark whose driver leaves slow and model out of its listing under mode=hard.""" + here = os.path.join(self.tmp, "fakebench") + shutil.copytree(self.b["_here"], here) + path = os.path.join(here, "driver.py") + with open(path) as f: + text = f.read() + text = text.replace(' units.remove("slow")\n', + ' units.remove("slow")\n' + ' if os.environ.get("NULLIUS_OPTION_MODE") == "hard":\n' + ' units = [u for u in units if u not in ("slow", "model")]\n') + with open(path, "w") as f: + f.write(text) + self.b["_here"] = here + + def test_ids_the_driver_does_not_list_under_the_runs_options_refuse_it_before_any_unit(self): + self.listing_by_mode() + self.make("dev", "good\nslow\nmodel\nwrong\n") + code, out, err = self.run_cli("--set", "dev", "--bench-option", "mode=hard", "--name", "hard") + self.assertEqual(code, 2, out + err) + self.assertIn("2 of the 4 ids of the task set dev are not listed by Fake bench's dataset all under the run's " + "options (mode=hard): slow, model", out) + job_dir = os.path.join(self.jobs, "hard") + self.assertEqual(self.trials(job_dir), []) + self.assertFalse(os.path.exists(os.path.join(job_dir, "config.json"))) + code, out, err = self.run_cli("--set", "dev", "--bench-option", "mode=plain", "--name", "plain") + self.assertEqual(code, 0, out + err) + + def test_the_message_names_the_first_five_ids_not_listed(self): + self.make("dev", "good\n" + "".join(f"gone{i}\n" for i in range(7))) + record = sets.record(sets.load("fakebench", "dev"), sets.revision(sets.load("fakebench", "dev"))) + r = run.Run(self.b, definitions.control(self.b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=record) + with self.assertRaises(run.Refused) as e: + r.start() + self.assertIn("7 of the 8 ids of the task set dev are not listed by Fake bench's dataset all under the run's " + "options (mode=plain): gone0, gone1, gone2, gone3, gone4, ...", str(e.exception)) + self.assertEqual(self.trials(r.job_dir), []) + self.assertFalse(os.path.exists(os.path.join(r.job_dir, "config.json"))) + + def test_the_units_run_are_the_sets_and_limit_and_shard_apply_after(self): + self.make("dev", "model\nwrong\nslow\n") + code, out, err = self.run_cli("--set", "dev", "--name", "whole") + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(out.strip().splitlines()[-1]), ["model__u0003", "slow__u0002", "wrong__u0001"]) + # the set, then the shard, then the limit: shard 1 of 2 holds wrong and model of the three, and the limit keeps wrong + self.assertEqual([shard.of(u, 2) for u in DATASET], [1, 1, 2, 1]) + code, out, err = self.run_cli("--set", "dev", "--shard", "1/2", "--limit", "1", "--name", "part-shard-1of2") + self.assertEqual(code, 0, out + err) + part = out.strip().splitlines()[-1] + self.assertEqual(self.trials(part), ["wrong__u0001"]) + rec = read(os.path.join(part, "config.json"))["standard"]["shard"] + self.assertEqual((rec["units_total"], rec["planned"], rec["limit"]), (3, ["wrong"], 1)) + with open(os.path.join(part, feed.FEED)) as f: + self.assertEqual(next(e for e in map(json.loads, f) if e["event"] == "job.start")["tasks"], ["wrong"]) + + def test_the_config_records_the_set_and_the_runs_options(self): + self.b["datasets"] = [*self.b["datasets"], {"id": "responding", "units": 3}] + self.make("Dev set", "good\nmodel\n", "--dataset", "responding") + code, out, err = self.run_cli("--set", "dev-set", "--bench-option", "mode=hard", "--name", "first") + self.assertEqual(code, 0, out + err) + cfg = read(os.path.join(self.jobs, "first", "config.json")) + entry = sets.load("fakebench", "dev-set") + self.assertEqual(cfg["standard"]["task_set"], sets.record(entry)) + self.assertEqual(cfg["standard"]["task_set"], + {"id": entry["id"], "name": "dev-set", "label": "Dev set", "revision": 1, "hash": entry["revisions"][0]["hash"], + "units": ["good", "model"]}) + self.assertEqual(cfg["standard"]["benchmark_options"], {"mode": "hard"}) + self.assertNotIn("units_file", cfg["standard"]) + self.assertEqual(cfg["datasets"], [{"name": "fakebench/responding", "n_tasks": 2}]) + + def versions(self): + """The fake benchmark at two versions, each its own copy of the entry: at "2", its driver no longer lists slow.""" + here = os.path.join(self.tmp, "fakebench-2") + shutil.copytree(self.b["_here"], here) + path = os.path.join(here, "driver.py") + with open(path) as f: + text = f.read() + with open(path, "w") as f: + f.write(text.replace(' units.remove("slow")\n', + ' units.remove("slow")\n' + ' units = [u for u in units if u != "slow"]\n')) + one = dict(self.b, _version="1", _versions=["1", "2"], _default="2", _ref="fakebench@1", _labels={"1": "v1 (one)", "2": "v2"}) + return one, dict(one, _version="2", _ref="fakebench@2", _here=here) + + def test_a_set_made_at_a_version_records_it_and_a_run_at_another_that_lacks_a_task_is_refused(self): + one, two = self.versions() + entry = sets.create(one, "From one", dataset="all", units=["good", "slow"]) + self.assertEqual((entry["version"], sets.record(entry)["version"]), ("1", "1")) + self.assertEqual(sets.rows("fakebench")[0]["version"], "1") + r = run.Run(two, definitions.control(two, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=sets.record(entry)) + with self.assertRaises(run.Refused) as e: + r.start() + self.assertIn("the task set From one was made at Fake bench v1 (one), and slow is not a task of all at v2, the " + "version this run is at: run it at v1 (one), or make a set at v2", str(e.exception)) + self.assertEqual(self.trials(r.job_dir), []) + # at the version it was made at, or at another that holds all its tasks, it runs + for b, label in ((one, ""), (two, "Only good")): + if label: + entry = sets.create(one, label, dataset="all", units=["good"]) + r = run.Run(b, definitions.control(b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=sets.record(entry), name=f"at-{b['_version']}-{entry['name']}") + r.start() + self.assertEqual(len(self.trials(r.job_dir)), len(sets.latest(entry)["units"])) + + def test_a_run_without_a_set_records_none(self): + code, out, err = self.run_cli("--name", "plain") + self.assertEqual(code, 0, out + err) + cfg = read(os.path.join(self.jobs, "plain", "config.json")) + self.assertEqual(sorted(cfg["standard"]), ["backend", "benchmark", "benchmark_options", "control", "kind", "needs", + "permissions_granted", "plugged", "provider", "retries", "unsandboxed"]) + + +class Listing(Scratch): + def test_list_and_show_say_each_set_with_its_name_and_label(self): + self.make("dev", "good\nmodel\n", "--description", "two of them") + self.make("All four", "\n".join(DATASET)) + code, out, err = self.cli("set", "list", "--json") + self.assertEqual(code, 0, err) + rows = json.loads(out) + self.assertEqual([(r["name"], r["label"], r["units"]) for r in rows], [("all-four", "All four", 4), ("dev", "dev", 2)]) + self.assertTrue(all("revision" not in r for r in rows)) + code, out, err = self.cli("set", "list", "fakebench") + self.assertEqual(code, 0, err) + self.assertIn("two of them", out) + self.assertIn("All four", out) + code, out, err = self.cli("set", "show", "fakebench", "dev") + self.assertEqual(code, 0, err) + self.assertTrue(out.startswith("dev: 2 units of fakebench all\n"), out) + self.assertNotIn("revision", out) + self.assertEqual(out.strip().splitlines()[-2:], [" good", " model"]) + code, out, err = self.cli("set", "show", "fakebench", "all-four", "--json") + self.assertEqual((code, json.loads(out)["label"], len(json.loads(out)["units"])), (0, "All four", 4)) + code, out, err = self.cli("set", "list", "otherbench", "--json") + self.assertEqual((code, json.loads(out)), (0, [])) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_standard_shard.py b/app/tests/test_standard_shard.py index 89bebcc9a..8d11fd527 100644 --- a/app/tests/test_standard_shard.py +++ b/app/tests/test_standard_shard.py @@ -66,7 +66,7 @@ def test_a_shard_is_i_of_n(self): def write_shard(root, name, units, index, of, *, total=10, launch="L1", model="gpt-5-mini", bench=BENCH, other=AGENT, planned=None, t0=1_760_000_000.0, failed=(), budget=None, backend="local", bench_options=None, - reward=lambda place: float(place % 2)): + reward=lambda place: float(place % 2), task_set=None): """A shard job as a run writes it: its config, a trial per unit (tagged by the unit's place in the whole dataset), its result.""" d = os.path.join(root, name) @@ -74,7 +74,7 @@ def write_shard(root, name, units, index, of, *, total=10, launch="L1", model="g planned = list(units) if planned is None else planned job.write_config(d, job=name, bench=bench, other=other, model=model, provider="openai", dataset="all", units=planned, concurrency=2, granted=True, launch=launch, shard=shard.record(index, of, total, planned), backend=backend, - bench_options=bench_options) + bench_options=bench_options, task_set=task_set) results = [] for k, u in enumerate(units): place = int(u.split("-")[1]) @@ -212,6 +212,31 @@ def test_shards_of_different_launches_models_or_versions_are_refused_unless_forc got = merge.merge([a, b], os.path.join(self.tmp, "forced"), force=True) self.assertIn("merged_despite", read((os.path.join(got["out"], "config.json")))["standard"]) + def test_shards_of_two_task_sets_or_revisions_are_refused_unless_forced_and_the_merge_keeps_the_set(self): + units = sorted(self.split[1] + self.split[2] + self.split[3]) + def of(name="dev", rev=1, id_="a" * 32, digest=None): + return {"id": id_, "name": name, "revision": rev, "hash": digest or f"{rev}" * 64, "units": units} + a = write_shard(self.tmp, "a", self.split[1], 1, 3, task_set=of()) + # the whole id and hash are compared: one changed in its last character is another set, never named whole + changed = ("a" * 31 + "b", "1" * 63 + "b") + for name, rec in (("b-rev", of(rev=2)), ("b-other", of(name="other", id_="b" * 32)), + ("b-id", of(id_=changed[0])), ("b-hash", of(digest=changed[1])), ("b-none", None)): + with self.subTest(other=name): + b = write_shard(self.tmp, name, self.split[2], 2, 3, task_set=rec) + with self.assertRaisesRegex(merge.Refused, "task set: a 'dev@1 ") as refused: + merge.merge([a, b], os.path.join(self.tmp, "never")) + self.assertFalse(os.path.exists(os.path.join(self.tmp, "never"))) + self.assertFalse([value for value in changed if value in str(refused.exception)]) + got = merge.merge([a, b], os.path.join(self.tmp, "forced-" + name), force=True) + cfg = read(os.path.join(got["out"], "config.json"))["standard"] + self.assertEqual(cfg["task_set"], of()) + self.assertTrue(any(d.startswith("task set: ") for d in cfg["merged_despite"])) + b = write_shard(self.tmp, "b", self.split[2], 2, 3, task_set=of()) + got = merge.merge([a, b], os.path.join(self.tmp, "out", "run")) + cfg = read(os.path.join(got["out"], "config.json"))["standard"] + self.assertEqual(cfg["task_set"], of()) + self.assertNotIn("merged_despite", cfg) + def test_a_shard_recorded_with_docker_is_of_one_launch_with_a_container_shard(self): a = write_shard(self.tmp, "a", self.split[1], 1, 3, backend="docker") # the container backend's earlier name b = write_shard(self.tmp, "b", self.split[2], 2, 3, backend="container") diff --git a/app/tests/test_standard_units.py b/app/tests/test_standard_units.py index c73267218..8e172f989 100644 --- a/app/tests/test_standard_units.py +++ b/app/tests/test_standard_units.py @@ -193,6 +193,22 @@ def test_lists_of_the_same_units_merge_whatever_their_files_names_comments_or_or got = merge.merge([left, right], os.path.join(self.jobs, "merged")) self.assertEqual(got["trials"], 2) + def test_a_list_and_a_task_set_together_are_refused_before_any_unit(self): + listed = run.units_file(self.file("good\n")) + record = {"id": "0" * 32, "name": "dev", "revision": 1, "hash": "0" * 64, "units": ["model"]} + with self.assertRaisesRegex(run.Refused, "from a file or from a task set, not both"): + run.Run(self.b, definitions.control(self.b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, units_file=listed, task_set=record) + self.assertFalse(os.path.exists(self.jobs)) + + def test_a_task_sets_units_run_as_a_lists_do_and_its_record_is_kept(self): + record = {"id": "0" * 32, "name": "dev", "revision": 2, "hash": "0" * 64, "units": ["model", "wrong"]} + job = self.go(task_set=record, limit=1) + self.assertEqual(self.trials(job), ["wrong__u0001"]) + cfg = read(os.path.join(job, "config.json"))["standard"] + self.assertEqual(cfg["task_set"], record) + self.assertNotIn("units_file", cfg) + class FromTheCommandLine(unittest.TestCase): """``nullius standard run ... --units FILE``: the file read where the command runs, with or diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 9ce9b6418..301289bfd 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -24,7 +24,7 @@ from nullius import paths from nullius.standard import cli from nullius.standard.contract import definitions -from nullius.standard.runner import units +from nullius.standard.runner import sets, units ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") OSWORLD1 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "catalogue", @@ -257,6 +257,32 @@ def test_refusals_are_one_line_on_stderr(self): self.assertTrue(err.startswith("refused: ") and said in err and len(err.splitlines()) == 1, err) +class SetFromAFilter(Scratch): + def test_the_ids_stored_are_the_ones_the_listing_gives_and_the_note_holds_the_filter(self): + code, out, err = self.cli("set", "create", "described", "picked", "--dataset", "all", "--search", "number 24", + "--category", "kind=alpha", "--category", "kind=beta") + self.assertEqual(code, 0, err) + entry = sets.load("described", "picked") + listed = units.find(self.b, "all", search="number 24", categories={"kind": ["alpha", "beta"]}, size=None) + self.assertEqual(sets.revision(entry)["units"], self.ids(listed)) + self.assertEqual(sets.revision(entry)["units"], ["t024", "t124", "t240", "t241", "t243", "t244", "t246", "t247", "t249"]) + self.assertEqual(sets.revision(entry)["note"], + 'matched by --search "number 24" --category kind=alpha --category kind=beta') + code, out, err = self.cli("set", "create", "described", "by-kind", "--dataset", "all", "--category", "kind=gamma") + self.assertEqual(code, 0, err) + self.assertEqual(len(sets.revision(sets.load("described", "by-kind"))["units"]), 83) + + def test_a_filter_that_matches_nothing_or_beside_another_source_is_refused(self): + for args, said in ((["--search", "wombat"], "no task of all matches --search \"wombat\""), + (["--search", "t1", "--units", os.path.join(self.tmp, "x.txt")], "--units FILE, --from-job"), + ([], "--units FILE, --from-job")): + with self.subTest(args=args): + code, out, err = self.cli("set", "create", "described", "none", "--dataset", "all", *args) + self.assertEqual((code, out), (2, "")) + self.assertIn(said, err) + self.assertFalse(os.path.exists(os.path.join(self.cat, "sets"))) + + ASKED = AssertionError("the listing asked for the driver's environment") HEAVY = {"command": ["{install}/.venv/bin/python", "{here}/driver.py"], "install": {"python": "3.12", "pip": ["nothing-installed==1.0"]}, "describe": True} diff --git a/app/tests/test_task_set_recipe.py b/app/tests/test_task_set_recipe.py new file mode 100644 index 000000000..234696319 --- /dev/null +++ b/app/tests/test_task_set_recipe.py @@ -0,0 +1,91 @@ +"""A task set in the builder's recipe and on a host: ``task_sets`` compiles to ``--set NAME`` beside the +dataset, its label and count in the Review step; a set of another benchmark or dataset is refused; the runner snapshot a +host receives carries the recipe's sets, and a run started from it there reads the set and records it. No key, +no network: the runs are the fake benchmark's control.""" +from __future__ import annotations + +import io +import json +import os +import shutil +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius import progress +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.requirements import install +from nullius.standard.runner import payload, sets + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +NOP = {"nop": {"source": "nullius", "from": "nothing said"}} + + +class Scratch(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-set-recipe-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.cat = self.tmp / "catalogue" + self.b = dict(definitions.get("benchmark", "fakebench", ROOT), controls=NOP, + datasets=[{"id": "all", "units": 4}, {"id": "more", "units": 4}]) + self.memo = definitions.get("benchmark", "fakememo", ROOT) + for patch in (mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(self.cat)}), + mock.patch.object(install, "HOME", str(self.tmp / "home")), mock.patch.object(progress, "ECHO", None)): + patch.start() + self.addCleanup(patch.stop) + self.defs = {"benchmark": [self.b, self.memo], "agent": [], "capability": []} + + def recipe(self, **kw): + r = {"version": 1, "harness": "standard", "name": "fake-sets", "title": "t", "benchmark": "fakebench", "datasets": ["all"], + "others": ["nop"], "provider": "openai", "model": "", "concurrency": 1, "where": "local"} + r.update(kw) + return r + + def compile(self, **kw): + return recipe.compile(self.recipe(**kw), self.defs) + + +class OnAHost(Scratch): + """What the app sends a host for a recipe with a set: the snapshot holds the set's entry; the run there, reading + the copy of the snapshot's catalogue a host run reads, runs the set and records it.""" + + def test_the_snapshot_carries_the_recipes_sets_and_the_run_there_records_the_set(self): + entry = sets.create(self.b, "settings", dataset="all", units=["good", "wrong"]) + r = self.recipe(task_sets={"all": "settings"}) + self.assertEqual(payload.recipe_sets(r), [("fakebench", "settings")]) + self.assertEqual(payload.recipe_sets(self.recipe()), []) + empty = self.tmp / "empty-package" + shutil.copytree(Path(payload.PACKAGE), empty, ignore=shutil.ignore_patterns("__pycache__", "catalogue", "kits")) + key0, _ = payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat)) + key, here = payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), sets=payload.recipe_sets(r)) + self.assertNotEqual(key, key0) + self.assertEqual(payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), + sets=payload.recipe_sets(r)), (key, here)) + carried = Path(here) / "app/nullius/catalogue/sets/fakebench/settings.json" + self.assertEqual(json.loads(carried.read_text())["id"], entry["id"]) + for name in ("gone", "../settings"): + with self.assertRaises(ValueError): + payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), sets=[("fakebench", name)]) + # on the host: the snapshot's catalogue copied for the run (execution: cp -R .../app/nullius/catalogue), read there + run_catalogue = self.tmp / "host" / "runs" / "fake-sets" / "catalogue" + shutil.copytree(Path(here) / "app/nullius/catalogue", run_catalogue) + shutil.rmtree(self.cat) # nothing of this machine's catalogue is left to read + jobs = self.tmp / "host" / "runs" / "fake-sets" / "jobs" + out, err = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(run_catalogue)}), \ + mock.patch.object(cli, "_bench", return_value=self.b), mock.patch.object(cli, "_exit_on_term"), \ + mock.patch.object(cli.settings, "load"), redirect_stdout(out), redirect_stderr(err): + code = cli.main(["run", "fakebench", "nop", "--dataset", "all", "--set", "settings", "-j", "1", "--name", "fake-sets", + "--jobs", str(jobs)]) + self.assertEqual(code, 0, out.getvalue() + err.getvalue()) + cfg = json.loads((jobs / "fake-sets" / "config.json").read_text()) + self.assertEqual(cfg["standard"]["task_set"], sets.record(entry)) + self.assertEqual(sorted(d for d in os.listdir(jobs / "fake-sets") if "__u" in d), ["good__u0000", "wrong__u0001"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/cli/README.md b/docs/cli/README.md index de2aef933..ea4ab836c 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -19,7 +19,7 @@ From a source checkout, replace `nullius` with | [Conform an agent or a capability](conform.md) | `nullius standard conform` | | [Fidelity](fidelity.md) | `nullius standard fidelity` | | [Shard and merge](shard-and-merge.md) | `nullius standard run --shard`, `merge` | -| [Task sets](task-sets.md) | `nullius standard units` | +| [Task sets](task-sets.md) | `nullius standard units`; `set create`, `list`, `show`, `rename`, `delete`, `import`; `run --set` | | [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/run.md b/docs/cli/run.md index ca998236a..e0bd9b442 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -3,7 +3,7 @@ One benchmark and one agent, capability, control or setup, into a job. ```bash title="Run" -nullius standard run [@version] [--model M] [--dataset D] [--units FILE] [--limit N] [-j N] \ +nullius standard run [@version] [--model M] [--dataset D] [--units FILE | --set NAME] [--limit N] [-j N] \ [--unsandboxed | --backend container|boat] [--option NAME=VALUE]... [--bench-option NAME=VALUE]... \ [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]]... [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS]... [--max-turns N] [--max-calls N] \ [--constraint KEY=VALUE]... \ @@ -15,6 +15,7 @@ nullius standard run [@version] [--model M] [--dataset D] [-- nullius standard run humaneval reference --model gpt-5-mini --limit 2 --unsandboxed nullius standard run humaneval oracle --limit 6 nullius standard run humaneval oracle --units tasks.txt +nullius standard run humaneval oracle --set first-ten nullius standard run locomo original --model gpt-3.5-turbo-4k nullius standard run locomo model --model gpt-4o-mini ``` @@ -27,6 +28,7 @@ nullius standard run locomo model --model gpt-4o-mini | `--provider` | `anthropic`, `custom`, `openai` or `openrouter` | | `--dataset`, `--limit`, `-j` | One dataset, the first N units, N at a time | | `--units FILE` | Only the units the file lists: [below](#a-list-of-units) | +| `--set NAME` | Only the units of a [task set](task-sets.md); its dataset is the run's, the options the run's own | | `--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` | @@ -136,6 +138,7 @@ HumanEval/12 | The record | `config.json`: `standard.units_file`, the file's name, its sha256 and its units | | Where it is read | On the machine the command runs on, from the directory it starts in | | The builder | A recipe has no field for a list | +| A named list | A [task set](task-sets.md) keeps one, frozen: `--set NAME` | ## Serving providers diff --git a/docs/cli/shard-and-merge.md b/docs/cli/shard-and-merge.md index 9a6c785cf..9d8c97bbc 100644 --- a/docs/cli/shard-and-merge.md +++ b/docs/cli/shard-and-merge.md @@ -14,8 +14,9 @@ nullius standard merge jobs_standard/*__shard-* -o jobs_standard/humaneval-oracl | Shards by the unit's id | `sha256(unit id) mod N`: every unit in exactly one shard, new units leave the rest in place; changing N moves most. Order: `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6`: the first six of shard 1) | | A unit keeps its place | `u0042` is the 43rd unit of the dataset in every shard; shard jobs never share a trial name | | One launch | Each shard's `config.json` records `standard.shard` (`index`, `of`, `units_total`, `partition`, `planned`, `limit`) and `standard.launch`: `--launch`, or the day (UTC), benchmark, agent or capability and model. The runs page groups them until merged, then counts the merged job alone; source job files are kept | -| `merge JOB_DIR... -o OUT` | One job with its `result.json` recomputed. Different launches, versions, datasets, agents, models, backends or N refused unless `--force`; lists of different units and two trials of one unit always. Units no shard ran are named | +| `merge JOB_DIR... -o OUT` | One job with its `result.json` recomputed. Different launches, versions, datasets, agents, models, backends, N or task sets refused unless `--force`; lists of different units and two trials of one unit always. Units no shard ran are named | | A list of units | `--units FILE` on every machine: [Run a benchmark](run.md#a-list-of-units). A list's file name, comments and sha256 may differ from shard to shard; the merged job records the first shard's list | +| A task set | `--set NAME` on every machine, each with the entry: shards of two sets, or a set and none, are refused unless `--force`; the merged job keeps the first shard's set ([Task sets](task-sets.md)) | | A spending cap | Each shard's own; the builder shares a recipe's cap over its shards. `merge` adds them into one `budget` when every shard had one | | `prove --shard I/N` | Controls and leak on that shard, units on all; recorded as `shard` | diff --git a/docs/cli/task-sets.md b/docs/cli/task-sets.md index 5ed6765b5..bdf5d7b52 100644 --- a/docs/cli/task-sets.md +++ b/docs/cli/task-sets.md @@ -1,11 +1,26 @@ # Task sets +A group of a benchmark's units, frozen once made and run as the benchmark's own dataset is: a run names the set, gives its own options, and its job records which set ran. A set holds no option and no setup. Another list of tasks is another set. + ```bash title="Commands" nullius standard units --dataset D [--bench-option NAME=VALUE]... [--search TEXT] [--category FIELD=VALUE]... [--json] +nullius standard set create [@version] "WORDS" [--dataset D] (--units FILE | --search TEXT | --category FIELD=VALUE... \ + | --from-job JOB_DIR [--outcome O,...]... [--unit ID]...) [--description TEXT] +nullius standard set list [] [--json] +nullius standard set show NAME [--json] +nullius standard set rename NAME "WORDS" +nullius standard set delete NAME +nullius standard set import PATH +nullius standard run --set NAME ... ``` ```bash title="Examples" nullius standard units osworld1 --dataset test_nogdrive --search tab --category domain=chrome +nullius standard set create humaneval "first ten" --dataset humaneval --units ten.txt +nullius standard set create osworld1@044bc33 "Chrome tabs" --dataset test_nogdrive --search tab --category domain=chrome +nullius standard set create humaneval misses --from-job jobs_standard/JOB --outcome failed,infra +nullius standard set rename humaneval misses "misses of June" +nullius standard run humaneval reference --model gpt-5-mini --set first-ten --unsandboxed ``` ## Listing a dataset's tasks @@ -23,3 +38,40 @@ nullius standard units osworld1 --dataset test_nogdrive --search tab --category | The cache | The user cache (`nullius paths`): the same benchmark, driver, dataset and options are listed once | Exit codes: 0 listed (no match included), 2 a usage error or a refusal (an option or a category not known, a program not on this machine, a driver that could not list), 3 no such benchmark or dataset. + +## The set + +| Part | Detail | +| --- | --- | +| The entry | `sets//NAME.json` in the user catalogue (`nullius paths`, `NULLIUS_CATALOGUE`): a plain file to copy or keep in git | +| What it holds | An id made at creation, the label and the name made from it, the description, the benchmark, the version of the benchmark it was made at, the dataset, and one list in `revisions`: its number, date, note, unit ids and a content hash over the benchmark, the dataset and the sorted ids. An entry holding any other field is refused where it is read. One of the earlier format, which kept a run's options: delete it and make it again | +| Frozen | Nothing changes a set's list once made. | +| Its name | Any words, at most 80 characters, with a letter or a digit: the label every page shows. The name commands take is made from it: its Latin letters and digits in lower case, every other run of characters one hyphen ("custom task set" gives `custom-task-set`), `-2` and on for a second equal one | +| Its version | The version of the benchmark it was made at: the one `create` names (`osworld1@044bc33`), the page listed, or the job ran. The same list may hold other tasks at another version | +| Identity | Two runs ran the same set when their jobs name the same id. Two sets of equal lists stay two sets | + +| Command | Rule | +| --- | --- | +| `create --units FILE` | The file's ids, read as [`run --units`](run.md#a-list-of-units) reads them; `--dataset` is needed | +| `create --search`, `--category` | The ids [the listing](#listing-a-datasets-tasks) matches that day, under the benchmark's default options; `--dataset` is needed. The list's note keeps the filter. No match is refused | +| `create --from-job JOB_DIR` | The units a standard job ran, by each trial's full unit id; the job's dataset. `--outcome` takes the trials of those outcomes ([outcome names](../field-guide.md#outcomes), or `passed`, `failed`, `infra`), `--unit` adds the units named; neither takes every unit. A unit is taken when any of its attempts is | +| `show NAME` | Its label, version, id, date and units | +| `rename NAME WORDS` | The same set under another label, its id and list kept, and the name made from it again: a job that ran it finds it by its id and names it by its new label | +| `delete NAME` | The entry removed. A job that ran it keeps its record | +| `import PATH` | An entry's file, or a job that ran a set (its description then empty, its list dated by the import), written when no set of that name is here; the same id with the same list adds nothing. Refused: another id under that name, or the same id with another list | +| Not checked | The ids, until a run: the driver lists the units then | + +## A run of a set + +| Rule | Detail | +| --- | --- | +| Its dataset | The set's. A `--dataset` of another is refused before any unit | +| Its options | The run's own, any `--bench-option` as on the whole dataset | +| `--units` | Refused beside `--set` | +| The units | The set's ids, as a [list of units](run.md#a-list-of-units): ids the driver does not list under the run's options refuse the run before any unit, the message giving how many and the first five; then `--shard`, then `--limit` | +| Another version | A run at another version than the set's, whose dataset lacks one of its tasks, is refused before any unit: the message names the task and both versions | +| The record | `config.json`: `standard.task_set`, the set's id, name, label, the number and hash of its list, its units and its version | +| Shards | `merge` refuses shards of two sets, or a set and none, unless `--force`; the merged job keeps the first shard's set ([Shard and merge](shard-and-merge.md)) | +| On a host | From the app: the runner snapshot sent to the host carries the recipe's sets, and the run there reads them from its copy of the catalogue. By hand: copy the entry, or `set import` a job that ran it | + +Exit codes: 0 done, 2 a usage error or a refusal, 3 no such benchmark, set, file or job ([Exit codes and output](exit-codes.md)). diff --git a/docs/concepts.md b/docs/concepts.md index c72811526..e1ff470c6 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -12,6 +12,7 @@ The tasks and how each is scored; one folder in the catalogue, run on one or bot | Task, unit | One problem of a dataset; the standard says unit | | Task limit | How many tasks a run takes; empty means every task | | List of units | The tasks a standard run takes by their ids, from a file ([`--units FILE`](cli/run.md#a-list-of-units)) | +| Task set | A named list of units, frozen once made, which a run names and its job records ([`--set NAME`](cli/task-sets.md)) | | Verifier | The benchmark's own scoring: tests, an exact answer, a judge model | | Setup | Who answers: `original` (the published pipeline and models), `model` (that pipeline, your model), or your agent or capability | | Control | A run with no agent: `nop` does nothing, `oracle` applies the reference solution | diff --git a/docs/field-guide.md b/docs/field-guide.md index b7c8dffc3..423324e2a 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -191,6 +191,7 @@ These fields are stored in the standard's job and trial files ([Run a benchmark] | Field | What it is | Source | Works on | | --- | --- | --- | --- | | `standard.units_file` | In `config.json`: the units file's name, sha256 and ordered ids, before sharding and the limit. | measured | standard | +| `standard.task_set` | In the same config: the task set the units came from, its id, name, label, the number and content hash of its list, its ids, and the version it was made at. Merging shards of two sets requires `--force`, and keeps the first shard's record. | measured | standard | | `standard.constraints` | In the same config: what the machine allowed the run, when set. Shards may have different machine constraints; merging keeps the first shard's config values. | measured | standard | | `standard.served_by` | In the same config: the allowed OpenRouter provider slugs by model, in the order tried. | measured | standard | | `served / standard.served` | In the job's `result.json` and each trial's `result.json`, respectively: answered calls by provider (`calls`), calls naming none (`unnamed`), and each pinned model's `held`. Counts cover every relay route; the job also includes the benchmark's own relay. Tokens and cost are the agent's own calls'. | measured | standard | diff --git a/docs/standard.md b/docs/standard.md index bcfb988d5..2b4e60b76 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -145,6 +145,7 @@ record); verifier/reward.txt and score.json | Rate limits | After a `rate_limited` end no unit starts for 60 s, or the provider's `Retry-After`, doubling to 300 s while units keep ending so | | The relay | Headers pass through except the credentials, replaced by the relay's key; `agent/calls.jsonl` names them, never their values. A 429 reaches the agent as it came, never retried. Every call goes as the run's model, the one asked recorded as `model_asked`, except `model.side_models`, sent as asked and recorded `side`. Provider `anthropic` serves `messages` only ([protocols](settings/model-providers.md#protocols)) | | Constraints (`--constraint KEY=VALUE`) | What the machine allows Nullius, from Settings ([constraints](settings/run-hosts.md#constraints)): flags on every container the run starts on the machine, on either backend; a systemd scope for each process the run starts there (its drivers, and its agents and capabilities on the local backend); the most units at a time; the CPU affinity; the driver's `CUDA_VISIBLE_DEVICES`. The local backend refuses a cap that no scope holds. `config.json` records the values under `standard.constraints` | +| A task set (`--set NAME`) | A named list of units in the user catalogue, `sets//NAME.json`, frozen once made: the run takes its dataset and refuses another, gives its own options, its ids go as a units file's, and `config.json` records `standard.task_set`, the set's id, name, hash and version ([Task sets](cli/task-sets.md)) | | A cap on model calls (`--max-calls`) | Agents only. A unit's relay counts its agent route's answered calls and refuses the one past the cap: the agent's error, as a timeout is ([Run a benchmark](cli/run.md#a-cap-on-model-calls)) | | Who served a call | Each call's record keeps the routing field it was sent with (`request.routing`), the serving provider its reply names (`reply.served_by`), how the reply ended (`reply.end`: `finish_reason`, `stop_reason` or a Responses status) and an error the reply holds under a 200 (`reply.error`), cleaned of credentials. | | Serving providers (`--served-by`) | On OpenRouter, the providers that may answer a model, in order and no other: the caller's own routing is replaced, kept as `request.routing_asked`. `config.json` records `standard.served_by`; each trial's `result.json` and the job's say the calls of every route by serving provider and, for each pinned model, `held`, which reads the provider's name alone ([Run a benchmark](cli/run.md#serving-providers)) | @@ -364,7 +365,7 @@ N machines are N runs of the same command, each with `--shard I/N`, and one merg | Shards by the unit's id | `sha256(unit id) mod N`; changing N moves most units. Order: the driver's `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6` is the first six units of shard 1) | | A unit keeps its place | `u0042` is the 43rd unit of the whole dataset in every shard | | One launch | Each shard's `config.json` records `standard.shard` (`index`, `of`, `units_total`, `partition`, `planned`, `limit`) and `standard.launch` (`--launch`, else the UTC day, benchmark, agent or capability and model). With `--units`, `units_total` counts the listed units. The shards' lists hold the same units; a list's file name, comments and sha256 may differ from shard to shard | -| `cli merge JOB_DIR... -o OUT` | One job: trials hard-linked, `result.json` recomputed, `config.json` with `merged_from`. Shards that differ in launch, version, dataset, agent, model, serving providers, backend or N are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. | +| `cli merge JOB_DIR... -o OUT` | One job: trials hard-linked, `result.json` recomputed, `config.json` with `merged_from`. Shards that differ in launch, version, dataset, agent, model, serving providers, backend, N or task set are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. | | `cli prove --shard I/N` | The controls and the leak check on that shard's units; each record says `shard` | | Different options per shard | Shards of one launch may differ in `--bench-option` (a unit that needs a service its machine serves); the merged config keeps each shard's in `merged_from` | | `cli prove --job nop=MERGED` | Checks a merged launch of a control against its bound instead of running it. The job and each of its trials name that benchmark, version, control and job; each unit of the dataset has one trial, scored 0 to 1; the units check passes. `--dataset` named, no `--limit` or `--shard`. The record names the job and its options | From f5df65c21b5d8fa0cb51f8b1e5098f0b58068fa9 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 23 Nov 2026 14:15:35 +0100 Subject: [PATCH 03/37] feat(standard): let a benchmark's list name the list it is cut from OSWorld1 declares four lists, three of them cut from the first. The pages count them as four datasets, though a run of a cut is a run of some tasks of the whole. A dataset may name the list it is cut from in `subset_of`: optional, one level, a list cut from none that holds every unit of this one. OSWorld1 declares its three cuts of All tasks at both versions. A run still names the list it runs. The benchmark's page data holds the field, for the pages to draw. --- .../benchmarks/osworld1/standard.json | 6 ++ app/nullius/standard/contract/definitions.py | 13 ++++ app/nullius/standard/pages/recipe.py | 2 + app/tests/test_dataset_subsets.py | 70 +++++++++++++++++++ docs/benchmarks/add-manually.md | 1 + docs/standard.md | 2 +- 6 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 app/tests/test_dataset_subsets.py diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 182eaf264..2c9cf1582 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -53,6 +53,7 @@ { "id": "test_nogdrive", "label": "Without Google Drive", + "subset_of": "test_all", "summary": "The upstream's test_nogdrive.json: every task but the 8 that need a Google account's credentials.", "path": "evaluation_examples/test_nogdrive.json", "sha256": "fcb9497e93a8986407345d3012c872c9c2fed253420730fbea64ccfcace67dbb", @@ -69,6 +70,7 @@ { "id": "test_small", "label": "Small", + "subset_of": "test_all", "summary": "The upstream's test_small.json: a few tasks of each domain.", "path": "evaluation_examples/test_small.json", "sha256": "bb29275171b78728d71825b125af311d74e66bb2a6d693c45c497d380b1fc640", @@ -77,6 +79,7 @@ { "id": "test_infeasible", "label": "Infeasible", + "subset_of": "test_all", "summary": "The upstream's test_infeasible.json: tasks that cannot be done, passed by answering FAIL.", "path": "evaluation_examples/test_infeasible.json", "sha256": "1b447d0462b1bdac4b660e0dd6e6add6d01c17a9e684702c701abcffda409abb", @@ -265,6 +268,7 @@ { "id": "test_nogdrive", "label": "Without Google Drive", + "subset_of": "test_all", "summary": "The upstream's test_nogdrive.json: every task but the 8 that need a Google account's credentials. The live MBTA booking task is retired at this release.", "path": "evaluation_examples/test_nogdrive.json", "sha256": "9270c11fe809eb4c4e35a78a47cdb50717ea76557c1b9164c183e8e8b8d9ce91", @@ -281,6 +285,7 @@ { "id": "test_small", "label": "Small", + "subset_of": "test_all", "summary": "The upstream's test_small.json: a few tasks of each domain.", "path": "evaluation_examples/test_small.json", "sha256": "bb29275171b78728d71825b125af311d74e66bb2a6d693c45c497d380b1fc640", @@ -289,6 +294,7 @@ { "id": "test_infeasible", "label": "Infeasible", + "subset_of": "test_all", "summary": "The upstream's test_infeasible.json: tasks that cannot be done, passed by answering FAIL.", "path": "evaluation_examples/test_infeasible.json", "sha256": "1b447d0462b1bdac4b660e0dd6e6add6d01c17a9e684702c701abcffda409abb", diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 28ff1a3fb..284ba11e4 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1597,6 +1597,19 @@ def problems(d: dict, kind: str) -> List[str]: bad.append(f"{w}.sha256: the file's digest") if not isinstance(x.get("units"), int) or x["units"] < 1: bad.append(f"{w}.units: how many units it holds") + # a list cut from another of the benchmark's lists, which holds every unit it holds: the pages draw it as + # that dataset's own task set. One level: the list it names is cut from none + by_id = {x.get("id"): x for x in ds if isinstance(x, dict)} + for i, x in enumerate(ds): + if not isinstance(x, dict) or "subset_of" not in x: + continue + whole = by_id.get(x["subset_of"]) if isinstance(x["subset_of"], str) else None + if whole is None or whole is x: + bad.append(f"datasets[{i}].subset_of: the id of another of its datasets, the list this one is cut from") + elif "subset_of" in whole: + bad.append(f"datasets[{i}].subset_of: {x['subset_of']} is cut from another list; name one cut from none") + elif isinstance(x.get("units"), int) and isinstance(whole.get("units"), int) and x["units"] > whole["units"]: + bad.append(f"datasets[{i}].subset_of: it holds more units than {x['subset_of']}") u = d.get("units") or {} if not (isinstance(u.get("noun"), str) and isinstance(u.get("nouns"), str)): bad.append("units: {noun, nouns}") diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 09a980e8c..89ae79560 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -191,6 +191,8 @@ def _bench_page(b: dict) -> dict: for n, r in hostreq.all_of(b).items()}, "datasets": [{"id": d["id"], "label": d.get("label") or d["id"], "summary": d.get("summary", ""), "units": d.get("units"), "environment": d.get("environment") or "", + # the list it is cut from, when the benchmark declares one: drawn as that dataset's own task set + "subset_of": d.get("subset_of") or "", "controls": [dict(c, **{k: status[d["id"]][c["key"]][k] for k in ("proven", "short", "failed")}) for c in controls], "proofs": {k: status[d["id"]][k]["proven"] for k in ("units", "leak")}, diff --git a/app/tests/test_dataset_subsets.py b/app/tests/test_dataset_subsets.py new file mode 100644 index 000000000..8d1018201 --- /dev/null +++ b/app/tests/test_dataset_subsets.py @@ -0,0 +1,70 @@ +"""A benchmark's list cut from another of its lists (``subset_of`` on a dataset of its definition): the field is +optional and names another list, one cut from none, that holds at least as many units; OSWorld1 declares its three +cuts of All tasks at each of its versions; a run still names the list it runs, so a recipe of a cut compiles as +before. No key, no network.""" +from __future__ import annotations + +import copy +import unittest + +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe + + +def clean(d: dict) -> dict: + return copy.deepcopy({k: v for k, v in d.items() if not k.startswith("_")}) + + +class TheField(unittest.TestCase): + def setUp(self): + self.osw = clean(definitions.get("benchmark", "osworld1")) + + def said(self, d): + return [p for p in definitions.problems(d, "benchmark") if "subset_of" in p] + + def test_it_is_optional_and_the_declared_lists_pass(self): + self.assertEqual(self.said(self.osw), []) + plain = copy.deepcopy(self.osw) + for x in plain["datasets"]: + x.pop("subset_of", None) + self.assertEqual(self.said(plain), []) + + def test_it_names_another_list_cut_from_none_holding_as_many_units(self): + ids = [x["id"] for x in self.osw["datasets"]] + nogdrive, whole, small = ids.index("test_nogdrive"), ids.index("test_all"), ids.index("test_small") + for change, said in (((nogdrive, "subset_of", "nowhere"), f"datasets[{nogdrive}].subset_of: the id of another of its datasets"), + ((whole, "subset_of", "test_all"), f"datasets[{whole}].subset_of: the id of another of its datasets"), + ((small, "subset_of", "test_nogdrive"), f"datasets[{small}].subset_of: test_nogdrive is cut from another list"), + ((nogdrive, "subset_of", 3), f"datasets[{nogdrive}].subset_of: the id of another of its datasets"), + ((whole, "units", 10), f"datasets[{nogdrive}].subset_of: it holds more units than test_all")): + with self.subTest(change=change): + d = copy.deepcopy(self.osw) + i, k, v = change + d["datasets"][i][k] = v + self.assertTrue(any(p.startswith(said) for p in self.said(d)), self.said(d)) + + +class Declared(unittest.TestCase): + def test_osworld1_declares_its_three_cuts_of_all_tasks_at_each_version(self): + for v in ("desktop-env-v1.0.3", "044bc33"): + with self.subTest(version=v): + b = definitions.get("benchmark", f"osworld1@{v}") + self.assertEqual({x["id"]: x.get("subset_of") for x in b["datasets"]}, + {"test_all": None, "test_nogdrive": "test_all", "test_small": "test_all", "test_infeasible": "test_all"}) + whole = next(x for x in b["datasets"] if x["id"] == "test_all") + self.assertTrue(all(x["units"] <= whole["units"] for x in b["datasets"])) + self.assertEqual([x["subset_of"] for x in recipe._bench_page(b)["datasets"]], + ["test_all" if x.get("subset_of") else "" for x in b["datasets"]]) + + def test_a_run_still_names_the_list_it_runs(self): + b = definitions.get("benchmark", "osworld1@044bc33") + out = recipe.compile({"version": 1, "harness": "standard", "name": "osw", "title": "t", "benchmark": "osworld1@044bc33", + "datasets": ["test_nogdrive"], "others": ["nop"], "provider": "openai", "model": "", "where": "local", + "concurrency": 1}, {"benchmark": [b], "agent": [], "capability": []}) + self.assertEqual(out["errors"], [], out["errors"]) + self.assertIn("--dataset test_nogdrive ", out["shards"][0]["command"]) + self.assertEqual(next(r for r in out["review"] if r[1] == "Dataset")[2], "Without Google Drive · 361 tasks") + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/benchmarks/add-manually.md b/docs/benchmarks/add-manually.md index 6ea08c991..fa7806303 100644 --- a/docs/benchmarks/add-manually.md +++ b/docs/benchmarks/add-manually.md @@ -20,6 +20,7 @@ A standard benchmark from a scaffold, its driver calling the upstream's own code | `datasets[].path` | The file's path in that upstream | | `datasets[].sha256` | `sha256sum /path/to/dataset.jsonl` of that exact file | | `datasets[].units` | How many units | + | `datasets[].subset_of` | Optional: the id of the list this one is cut from, when every unit of it is in that list at each version; the pages then draw it as that dataset's own task set | | `needs` | The ports really needed | | `score.says` | What a passing score means | diff --git a/docs/standard.md b/docs/standard.md index 2b4e60b76..021c74b89 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -414,7 +414,7 @@ local proof records; saved runs and credentials remain. ### A benchmark 1. **Scaffold it.** `cli new benchmark KEY` (`--family capability --port cap.memory/v1` for a capability benchmark) writes `benchmarks//standard.json` and `driver.py` under your user catalogue (`nullius paths`). -2. **Pin the data.** `upstream.repository` and `upstream.tested`, a full commit: the latest release tag's (`upstream.tag`; an annotated tag's commit is the `^{}` line of `git ls-remote --tags`), a default-branch commit only without a release. Each dataset: its `path` in the upstream or its `url` at a revision, its `sha256` and `units`. Installs and upstreams go under `STANDARD_DIR` (`~/.local/share/nullius/standard` on Linux by default), downloaded datasets under its `datasets/` or `STANDARD_DATA_DIR`. +2. **Pin the data.** `upstream.repository` and `upstream.tested`, a full commit: the latest release tag's (`upstream.tag`; an annotated tag's commit is the `^{}` line of `git ls-remote --tags`), a default-branch commit only without a release. Each dataset: its `path` in the upstream or its `url` at a revision, its `sha256` and `units`; a list the upstream cuts from another of its lists names it in `subset_of` (optional, one level: the list it names is cut from none, and holds every unit of this one, checked task by task at each version), and the pages then draw it as that dataset's own task set, while a run still names the list it runs. Installs and upstreams go under `STANDARD_DIR` (`~/.local/share/nullius/standard` on Linux by default), downloaded datasets under its `datasets/` or `STANDARD_DATA_DIR`. 3. **Choose the needs.** The fewest ports: `agent.workspace/v1` for files, `agent.search/v1` for search and source retrieval, `agent.tools/v1` for MCP tools, `agent.conversation/v1` if a user speaks more than once; a skill the units cannot be done without goes in `needs_skills`. 4. **Write the driver.** It answers the [ops below](#driver-ops); the dataset file is `$NULLIUS_DATASET` (empty for a dataset with no `path` or `url`), the upstream `$NULLIUS_UPSTREAM`, the version `$NULLIUS_VERSION`. Keep the tests out of the workspace until `score`; prints go to stderr. 5. **Its own options**, when the upstream offers a choice a run should make ([below](#benchmark-options)). From e2e42bca6cc2c66a9cf81c0afb2f5f781743ec7b Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Mon, 23 Nov 2026 14:15:46 +0100 Subject: [PATCH 04/37] feat(catalogue): browse a dataset's tasks, save task sets and choose one in the builder A task set can only be made and chosen on the command line, and a benchmark's lists cut from another show as datasets of their own. A dataset's tasks page lists its tasks with search and categories, ticks them and saves them as a task set under a free name; a set's page renames or deletes it. The benchmark's page lists its task sets, the benchmark's own cuts first. The builder's Dataset step asks Which tasks?: all of the dataset or one of its sets, the recipe's `task_sets` run as `--set NAME`, here or on a host. A benchmark whose lists name the one they are cut from shows one dataset and its cuts as its own sets. A job's page saves the tasks of a job as a set. The number of tasks says it runs all of them when empty and takes that many at most. --- app/nullius/standard/pages/recipe.py | 54 +- app/static/builder/command-builder-core.js | 38 +- app/static/builder/command-builder.css | 4 + app/static/builder/command-builder.js | 80 +- app/static/catalogue/catalogue.css | 80 ++ app/static/catalogue/tasks.js | 177 ++++ app/static/style.css | 8 + app/templates/catalogue/benchmark.html | 32 + app/templates/catalogue/tasks.html | 106 +++ app/templates/runs/job.html | 13 +- app/tests/test_task_set_recipe.py | 50 ++ app/ui_tests/test_builder_limits.py | 41 + app/ui_tests/test_task_set_pages.py | 921 +++++++++++++++++++++ app/web/catalogue.py | 226 +++++ app/web/runs.py | 62 +- docs/builder.md | 4 +- docs/cli/task-sets.md | 13 + 17 files changed, 1887 insertions(+), 22 deletions(-) create mode 100644 app/static/catalogue/tasks.js create mode 100644 app/templates/catalogue/tasks.html create mode 100644 app/ui_tests/test_builder_limits.py create mode 100644 app/ui_tests/test_task_set_pages.py diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 89ae79560..1ef981b63 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -35,6 +35,7 @@ from __future__ import annotations import math +import os import re import shlex from typing import Callable, Dict, List, Optional @@ -46,7 +47,7 @@ from nullius.standard.contract import definitions, match, ports from nullius.standard.proofs import prove from nullius.standard.requirements import hostreq -from nullius.standard.runner import run +from nullius.standard.runner import run, sets from nullius.standard.runner.retries import MAX_RETRIES CHOOSE_PROVIDER = "Choose a provider: OpenRouter, OpenAI, Anthropic or a custom provider." @@ -146,6 +147,7 @@ def _bench_page(b: dict) -> dict: controls = [{**{k: c[k] for k in ("key", "label", "source", "from", "expect")}, "must": prove.must_score(c["expect"])} for c in (definitions.control(b, w) for w in definitions.CONTROLS) if c] versioned = definitions.version_of(b) is not None + task_sets = sets.rows(b["key"]) return {"key": b["key"], "label": b["label"], "summary": b["summary"], "family": b["family"], "kind": _capability_kind(b), "ref": definitions.ref_of(b) if "_version" in b else b["key"], "version": b["_version"] if versioned else "", @@ -196,7 +198,10 @@ def _bench_page(b: dict) -> dict: "controls": [dict(c, **{k: status[d["id"]][c["key"]][k] for k in ("proven", "short", "failed")}) for c in controls], "proofs": {k: status[d["id"]][k]["proven"] for k in ("units", "leak")}, - "failed": {k: status[d["id"]][k]["failed"] for k in ("units", "leak") if status[d["id"]][k]["failed"]}} + "failed": {k: status[d["id"]][k]["failed"] for k in ("units", "leak") if status[d["id"]][k]["failed"]}, + # the user's task sets cut from it (standard/runner/sets.py), each with the version it was made at + "sets": [dict(s, version_label=sets.version_label(b, s["version"]) if s["version"] else "") + for s in task_sets if s["dataset"] == d["id"]]} for d in b["datasets"]]} @@ -451,6 +456,39 @@ def add(step, message, shown=False, field=None): unknown = [x for x in wanted if x not in {y["id"] for y in b["datasets"]}] if not dss or unknown: add("dataset", f"Choose one or more of {b['label']}'s datasets" + (f" ({', '.join(unknown)} is not one)" if unknown else "") + ".") + # a chosen dataset's task set (``task_sets``: {dataset: NAME}), run in place of all its tasks; a recipe from + # before sets were frozen may name one NAME@N + set_of = {} # {dataset: {name, label, units, ids}} + asked = recipe.get("task_sets") or {} + if not isinstance(asked, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in asked.items()): + add("dataset", "Task sets are a dataset with a set's name each.") + asked = {} + for ds_id, ref in asked.items(): + if ds_id not in {x["id"] for x in dss}: + add("dataset", f"The task set {ref} is for {ds_id}, a dataset not chosen.") + continue + try: + set_name, rev = sets.split_ref(ref) + except sets.Refused as e: + add("dataset", f"Task set {ref}: {e}.") + continue + try: + if not os.path.isfile(sets.path_of(b["key"], set_name)): + add("dataset", f"{b['label']} has no task set {set_name}: choose another, or all of {ds_id}'s tasks.") + continue + entry = sets.load(b["key"], set_name) + except sets.Refused as e: + add("dataset", sets.plain(e, b["key"], set_name)) + continue + try: + got = sets.latest(entry, rev) + except sets.Refused as e: + add("dataset", f"Task set {ref}: {e}.") + continue + if entry["dataset"] != ds_id: + add("dataset", f"The task set {sets.label_of(entry)} is cut from the dataset {entry['dataset']}, not {ds_id}.") + continue + set_of[ds_id] = {"name": set_name, "label": sets.label_of(entry), "units": len(got["units"]), "ids": set(got["units"])} 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. @@ -783,7 +821,8 @@ def pinned(p: dict) -> Dict[str, List[str]]: nouns = (b.get("units") or {}).get("nouns", "units") if picks and all(p.get("setup") for p in picks): # only setups: a unit is theirs (a conversation) nouns = picks[0]["o"]["units"]["nouns"] - each = [None if picks and all(p.get("setup") for p in picks) else x.get("units") for x in dss] # a setup's count is not the dataset's + each = [None if picks and all(p.get("setup") for p in picks) else (set_of[x["id"]]["units"] if x["id"] in set_of else x.get("units")) + for x in dss] # a setup's count is not the dataset's; a task set's is its own total = sum(each) if all(each) else None n = sum(min(limit, t) for t in each) if isinstance(limit, int) and total else (limit or total) of = len(targets) @@ -808,7 +847,8 @@ def command_for(d: dict, p: dict, index: int) -> str: o, control, given = p["o"], p["control"], p["given"] m = p["model"] if p.get("setup") else model words = ["nullius", "standard", "run", definitions.ref_of(b), o["_ref"], *(["--model", m] if m else []), "--provider", provider, - "--dataset", d["id"], *(["--limit", str(limit)] if isinstance(limit, int) else []), "-j", str(conc), + "--dataset", d["id"], *(["--set", set_of[d["id"]]["name"]] if d["id"] in set_of else []), + *(["--limit", str(limit)] if isinstance(limit, int) else []), "-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 []), @@ -900,7 +940,8 @@ def row(p: dict) -> list: out["review"] = [[STEP["benchmark"], "Benchmark", f"{b['label']} · needs {', '.join(b['needs'])}"], [STEP["runner"], "Runner", "Nullius"], [STEP["dataset"], "Datasets" if many else "Dataset", - ", ".join(f"{x.get('label') or x['id']}" + (f" · {x['units']} {nouns}" if x.get("units") else "") for x in dss)], + ", ".join(f"{x.get('label') or x['id']}" + (f" · task set {set_of[x['id']]['label']} · {set_of[x['id']]['units']} {nouns}" + if x["id"] in set_of else f" · {x['units']} {nouns}" if x.get("units") 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)}")] @@ -955,7 +996,8 @@ def row(p: dict) -> list: if any(p["control"] for p in picks) and any(definitions.own_image(e) for e in (b.get("environments") or {}).values()): notes.append(f"Each {(b.get('units') or {}).get('noun', 'unit')} of {b['label']} is its own image: the control " "runs in it, so docker is needed where it runs, whatever the backend.") - if not isinstance(limit, int): + # Run asks first before every task of the datasets; a task set is a choice of tasks made already + if not isinstance(limit, int) and not set_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 diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index dd54a9a8a..af635be31 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -170,10 +170,12 @@ if (!b) return r; const was = standardBench(r), same = !!was && was.key === b.key; // another version of it keeps the choices if (!same) { r.model_choice = 'any'; delete r.served_by; } + if (was !== b) delete r.task_sets; 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); const fitting = standardOthers(r).filter(o => !o.why.length); const keys = fitting.map(o => o.key), first = fitting.find(o => o.own) || fitting.find(o => o.setup && o.key === 'original') || fitting.find(o => !o.control && !o.setup); @@ -187,12 +189,37 @@ if (was !== b || r.name === 'standard-experiment') { r.name = b.key + '-experiment'; r.title = b.label + ' experiment'; } return r; } + // A benchmark whose lists name the list they are cut from (``subset_of``): the dataset a list is drawn under, its + // own id for one cut from none. A choice of another list of that dataset takes the place of the one chosen, its task + // set 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]; } + else if (r.task_sets) delete r.task_sets[now]; + return keepTaskSets(r); + } + // A chosen dataset's task set, NAME, run in place of all its tasks (recipe.py: task_sets, {dataset: NAME}); + // '' for all of them. A dataset no longer chosen keeps none. + function setTaskSet(r, dataset, ref) { + r.task_sets = {...(r.task_sets || {})}; + if (ref) r.task_sets[dataset] = ref; else delete r.task_sets[dataset]; + return keepTaskSets(r); + } + function keepTaskSets(r) { + const on = datasetsOf(r), kept = Object.entries(r.task_sets || {}).filter(([k, v]) => on.includes(k) && typeof v === 'string' && v); + if (kept.length) r.task_sets = Object.fromEntries(kept); else delete r.task_sets; + return r; + } // A saved standard recipe read back: known fields only, each of its type. function standardFromJSON(raw) { const r = createStandard(typeof raw.benchmark === 'string' ? raw.benchmark : ''); for (const key of ['name', 'title', 'model', 'where', 'model_choice']) if (typeof raw[key] === 'string') r[key] = raw[key]; const sets = Array.isArray(raw.datasets) ? raw.datasets.filter(k => typeof k === 'string') : typeof raw.dataset === 'string' && raw.dataset ? [raw.dataset] : null; if (sets && sets.length) r.datasets = [...new Set(sets)]; + if (raw.task_sets && typeof raw.task_sets === 'object' && !Array.isArray(raw.task_sets)) { r.task_sets = {...raw.task_sets}; keepTaskSets(r); } 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]; @@ -819,7 +846,14 @@ } function prefill(query) { // ?standard=[&other=]: the standard's recipe for that pair (the Agents and Capabilities pages link here). - if(query.standard)return createStandard(query.standard,query.other||''); + if(query.standard) { + const r = createStandard(query.standard, query.other || ''); + if ((standardBench(r)?.datasets || []).some(d => d.id === query.dataset)) { + r.datasets = [query.dataset]; + if (query.set) setTaskSet(r, query.dataset, query.set); + } + return r; + } // nothing asked for: the Nullius runner, chosen first; a Harbor recipe comes from its own card if(!query.agent&&!query.dataset&&!query.model&&!query.n_tasks&&standard().benchmarks.length)return createStandard(); const r=create(), known=schema.agents.find(a=>[a.id,a.arg,a.label].includes(query.agent))||(query.agent&&schema.agents.find(a=>String(a.arg||'').includes(':')&&String(a.arg).split(':').pop()===query.agent)); @@ -870,5 +904,5 @@ at: String(d.at || ''), saved: typeof d.saved === 'string' ? d.saved : ''}; } catch (e) { return e && e.message === RUNNER_GONE ? {recipe: null, gone: RUNNER_GONE} : null; } } - return {STANDARD_PHASES,STEPS,STEP,runners,RUNNER_GONE,isStandard,standard,standardBase,standardBench,standardOthers,ownAgentsOf,ownChosen,runsOf,standardKeyless,paperModels,paperListed,paperOffered,leaderboard,setModelChoice,servedRoles,servedList,setServed,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; + return {setTaskSet,keepTaskSets,nestedDatasets,wholeOf,swapDataset,STANDARD_PHASES,STEPS,STEP,runners,RUNNER_GONE,isStandard,standard,standardBase,standardBench,standardOthers,ownAgentsOf,ownChosen,runsOf,standardKeyless,paperModels,paperListed,paperOffered,leaderboard,setModelChoice,servedRoles,servedList,setServed,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; }); diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 98f86f052..d4b99a35e 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -12,6 +12,7 @@ #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 .std-yoursets { margin-top: 10px; } #nullius-builder .nb-dialoghead { display: flex; justify-content: space-between; align-items: center; gap: 12px; } #nullius-builder .nb-dialoghead h2 { margin: 0; } #nullius-builder .nb-dialogclose { flex: none; width: 32px; height: 32px; border: 0; border-radius: 8px; background: none; color: var(--nb-muted); font-size: 20px; line-height: 1; cursor: pointer; } @@ -257,6 +258,9 @@ /* a limit the benchmark or the agent declares: its placeholder reads as a value; Nullius's default stays grey */ #nullius-builder .nb-field input.nb-declared::placeholder { color: var(--nb-text); opacity: 1; } +/* A chosen dataset's tasks: all of them, or one of its task sets. */ +#nullius-builder .nb-pick-grid + .std-sethead, #nullius-builder .nb-field + .std-sethead { margin-top: 26px; } +#nullius-builder .std-sethead a.nb-inlinebutton { font-size: 13px; white-space: nowrap; } /* Where: machine kind, its machines, then isolation. Fixed values are not controls. */ #nullius-builder .std-machines { display: inline-flex; gap: 3px; padding: 3px; border: 1px solid var(--nb-line); border-radius: 999px; } #nullius-builder .std-machines button { padding: 6px 16px; border: 0; border-radius: 999px; background: transparent; color: var(--nb-text); font: 14px/1.4 var(--sans); } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 78c03bbd7..5d6e1d6f0 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -725,17 +725,67 @@ + (C.leaderboard(rec) ? tile({attr:'model-choice',key:'leaderboard',title:'Like the leaderboard',on:on==='leaderboard'}) : '') + `${tile({attr:'model-choice',key:'any',title:'Any of your choice',on:on==='any'})}`; } + // A chosen dataset's tasks: all of them, or one of its task sets (its name, its number of tasks), small cards, a + // select past five; and the page of its tasks, where a set is made. A recipe from before sets were frozen may name + // one NAME@N: it is that set. + function taskSetChoice(rec, b, x, u) { + const on = (rec.task_sets || {})[x.id] || '', sets = x.sets || [], ref = s => s.name; + const all = 'All ' + (x.units ? x.units + ' ' : '') + u.nouns; + const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(x.id)}`; + const picked = sets.find(s => on === s.name || on.split('@')[0] === s.name); + // a set made at another version of the benchmark says which: the run refuses a task that version lacks + const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; + const choice = sets.length + 1 > 5 + ? `' + : `
` + [tile({attr: 'std-taskset', key: '', data: ` data-of="${esc(x.id)}"`, on: !on, title: all}), + ...sets.map(s => tile({attr: 'std-taskset', key: ref(s), data: ` data-of="${esc(x.id)}"`, on: s === picked, title: s.label, tip: s.description || '', + meta: `${s.units} ${s.units === 1 ? u.noun : u.nouns}${made(s)}`})), + ...(on && !picked ? [tile({attr: 'std-taskset', key: on, data: ` data-of="${esc(x.id)}"`, on: true, title: on})] : [])].join('') + '
'; + // the dataset's name only where several are chosen: one chosen is the one above + const head = C.datasetsOf(rec).length > 1 ? esc(x.label) + ': which tasks?' : 'Which tasks?'; + return `` + choice; + } + // a dataset's proofs as its card shows them: its controls, then whether its ids are stable and nothing leaks + const datasetChecks = (b, x) => (x.controls || []).map(c => controlChip(c)).join('') + checkChip('stable', (x.proofs || {}).units, (x.failed || {}).units, 'the same ids twice, each unique') + + ((b.controls || []).some(c => c.key === 'oracle') ? checkChip('no leak', (x.proofs || {}).leak, (x.failed || {}).leak, 'nothing of the reference shows before the run') : ''); + // Which tasks? of a benchmark whose lists are cut from one (subset_of): all of it, the benchmark's own sets (its + // lists cut from it), then the user's sets of any of them. A choice names the list the run runs (data-was: the + // one chosen before) and, for a user's set, the set + function familyChoice(rec, b, x, u) { + const whole = b.datasets.find(d => d.id === C.wholeOf(b, x.id)) || x, cuts = b.datasets.filter(d => d.subset_of === whole.id); + const on = (rec.task_sets || {})[x.id] || '', many = n => n + ' ' + (n === 1 ? u.noun : u.nouns), was = ` data-was="${esc(x.id)}"`; + const mine = [whole, ...cuts].flatMap(d => (d.sets || []).map(s => ({...s, of: d}))); + const picked = mine.find(s => s.of.id === x.id && s.name === on.split('@')[0]); + const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; + const own = [tile({attr: 'std-family', key: whole.id, data: was, on: x.id === whole.id && !on, title: 'All of it', meta: whole.units ? many(whole.units) : ''}), + ...cuts.map(d => tile({attr: 'std-family', key: d.id, data: was, on: x.id === d.id && !on, title: d.label, tip: d.summary || '', + meta: d.units ? many(d.units) : '', foot: datasetChecks(b, d)}))]; + const yours = [...mine.map(s => tile({attr: 'std-family-set', key: s.name, data: was + ` data-in="${esc(s.of.id)}"`, on: s === picked, title: s.label, + tip: s.description || '', meta: many(s.units) + made(s)})), + ...(on && !picked ? [tile({attr: 'std-family-set', key: on, data: was + ` data-in="${esc(x.id)}"`, on: true, title: on})] : [])]; + const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(picked ? picked.of.id : whole.id)}`; + const head = C.datasetsOf(rec).length > 1 ? esc(whole.label) + ': which tasks?' : 'Which tasks?'; + return `` + + `
${own.join('')}
` + (yours.length ? `
${yours.join('')}
` : ''); + } function standardForm(rec) { const st = C.standard(), b = C.standardBench(rec); if (!b) return note('Choose a benchmark first', button('Benchmark step', `data-step="${S.benchmark}"`, 'nb-inlinebutton')); const u = unitsOf(rec); - if (step === S.dataset) + if (step === S.dataset) { + // a benchmark whose lists name the one they are cut from: one dataset each list cut from none, its cuts drawn + // under Which tasks? as its own task sets (familyChoice); the recipe still names the list a run runs + const nested = C.nestedDatasets(b), chosen = C.datasetsOf(rec); + const shown = nested ? b.datasets.filter(x => !x.subset_of) : b.datasets; + const on = x => nested ? chosen.some(id => C.wholeOf(b, id) === x.id) : chosen.includes(x.id); return `

Which datasets?

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

Scope

' - + field('Number of ' + u.nouns, 'limit', rec.limit, {type: 'number', min: 1, placeholder: all, hint: 'The first ones' + per + ', in its order.'}) + + field('Number of ' + u.nouns, 'limit', rec.limit, {type: 'number', min: 1, max: most, placeholder: all, + hint: 'Empty: all' + (most ? ' ' + most : '') + per + '. Else the first ones, in order.'}) + field('Concurrent ' + u.nouns, 'concurrency', rec.concurrency, {type: 'number', min: 1, max: 32, placeholder: rec.backend === 'boat' ? String((schema.standardHere || {}).boatSlots || 'Boat\'s limit') : '1'}) + '
' + '
' + field('Attempts per ' + u.noun, 'repeat', rec.repeat || '', {type: 'number', min: 1, max: 32, placeholder: '1'}) + field('Retries per attempt', 'retries', rec.retries ?? '', {type: 'number', min: 0, max: 9, placeholder: '0'}) + '
' @@ -873,6 +926,8 @@ refreshPlan(); }, 120); } + // the number of units a run takes, as typed: a number past the most the field takes is that most + const atMost = (el, value) => el.max !== '' && value !== '' && Number(value) > Number(el.max) ? Number(el.max) : value; const field = (label,key,value,{type='text',hint='',list='',min='',max='',placeholder='',declared=false}={}) => ``; const select = (label,key,value,options) => ``; const fixed = (label,value,whose='official') => ``; @@ -1135,7 +1190,10 @@ else if(d.runner){toRunner(d.runner,C.benchKey(r()));} else if(d.stdBench){C.setStandardBenchmark(r(),d.stdBench);} else if(d.stdOther){const rec=r(),c=C.chosenOf(rec);rec.others=c.includes(d.stdOther)?c.filter(k=>k!==d.stdOther):[...c,d.stdOther];delete rec.other;if(rec.options)delete rec.options[d.stdOther];} // a check - else if(d.stdDataset){const rec=r(),c=C.datasetsOf(rec);rec.datasets=c.includes(d.stdDataset)?(c.length>1?c.filter(k=>k!==d.stdDataset):c):[...c,d.stdDataset];delete rec.dataset;} + else if(d.stdDataset){const rec=r(),c=C.datasetsOf(rec),b=C.standardBench(rec),mine=c.filter(k=>C.wholeOf(b,k)===d.stdDataset);rec.datasets=mine.length?(c.length>mine.length?c.filter(k=>!mine.includes(k)):c):[...c,d.stdDataset];delete rec.dataset;C.keepTaskSets(rec);} + else if(d.stdFamily!==undefined){C.swapDataset(r(),d.was,d.stdFamily);} + else if(d.stdFamilySet!==undefined){C.swapDataset(r(),d.was,d.in);C.setTaskSet(r(),d.in,d.stdFamilySet);} + else if(d.stdTaskset!==undefined){C.setTaskSet(r(),d.of,d.stdTaskset);} // 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 @@ -1184,7 +1242,7 @@ if(d.servedBy!==undefined)return; // what is typed in a Served by filters its menu: a pick, or Enter, adds it (nb-pick) if(d.providerModel && rec.modelFormat !== 'provider-id'){for(const key of ['model','userModel','evalModel'])if(typeof rec[key]==='string')rec[key]=C.bareModel(rec[key]);rec.modelFormat='provider-id';} if(d.field){const p=d.field.startsWith('param:')?C.parameters().find(p=>p.key===d.field.slice(6)):null; - const value=el.type==='number'?(el.value===''?'':Number(el.value)):el.value; + const typed=el.type==='number'?(el.value===''?'':Number(el.value)):el.value,value=d.field==='limit'?atMost(el,typed):typed; if(p)rec.params[p.key]=p.type==='optional-boolean'?(value==='__default__'?null:value==='true'):value; else if(d.field==='timeoutMultiplier'){rec.timeoutMultiplier=value;rec.agentMinutes='';} else if(d.field.startsWith('adapterPath:')){const id=d.field.slice(12);if(String(value).trim())rec.adapterPaths[id]=String(value).trim();else delete rec.adapterPaths[id];} @@ -1209,6 +1267,7 @@ root.addEventListener('focusout',event=>{ const el=event.target; if(el.type==='number'&&(el.dataset.field||el.dataset.stdMinutes||el.dataset.benchOptSelect)&&el.validity&&el.validity.badInput){el.value='';window.nulliusNotify?.(`${el.getAttribute('aria-label')}: enter a number.`,{error:true,key:'bad-number'});} + else if(el.dataset.field==='limit'&&el.value!==''&&atMost(el,Number(el.value))!==Number(el.value)){el.value=el.max;window.nulliusNotify?.(`${el.getAttribute('aria-label')}: at most ${el.max}, all of them.`,{key:'at-most'});} }); // a provider picked in a Served by, or slugs typed there and Enter: they join its list, after the ones there root.addEventListener('nb-pick',event=>{const role=event.target.dataset.servedBy;if(!role)return;C.addServed(r(),role,event.detail);syncServed();refreshPlan();}); @@ -1218,6 +1277,7 @@ else if(d.stdUnsandboxed!==undefined){r().unsandboxed=el.checked;refreshPlan();} else if(d.stdVersion!==undefined){ // in place: only the card's count changes on this step, so nothing else is drawn again C.setStandardBenchmark(r(),el.value);benchTasks();render(false,false);} + else if(d.stdTasksetSelect!==undefined){C.setTaskSet(r(),d.stdTasksetSelect,el.value);renderForm();refreshPlan();} // an option at its default is left out: the recipe names only what was changed. A select's value can show or hide // the options that apply under it (`when`): the step is drawn again and the focus goes back to the select, or to the // menu button controls.js puts after it once this change is handled; a typed value is left as it is diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index fa87a01f0..c989e8ad4 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -429,3 +429,83 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .bench-main > .bench-section > h2, .bench-main > .bench-cols > .bench-section > h2 { margin-bottom: 18px; } .std-option-range { margin-top: 12px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: var(--text-dim); font-size: 14px; } @media (max-width: 640px) { .bench-main > .bench-section, .bench-main > .bench-cols > .bench-section { padding: 16px; } } + +/* A benchmark's task sets, and a dataset's tasks: browsed, ticked and kept as a set (catalogue/tasks.html). */ +.bench-sets td, .bench-sets th { vertical-align: top; } +.bench-sets small { display: block; color: var(--text-faint); font-size: 12px; } +.bench-setlinks { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; } +.bench-sets-group { margin: 14px 0 0; font-size: 13px; font-weight: 500; color: var(--text-dim); } +.bench-ownsets { margin-top: 8px; } +.bench-newset { position: relative; } +.bench-newset > summary { list-style: none; } +.bench-newset > summary::-webkit-details-marker { display: none; } +.bench-newset-menu { position: absolute; right: 0; top: calc(100% + 6px); z-index: 5; display: flex; flex-direction: column; min-width: 220px; max-width: calc(100vw - 32px); + padding: 6px; background: var(--surface); border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 12px 32px #0005; } +.bench-newset-menu a { display: flex; justify-content: space-between; gap: 14px; padding: 8px 10px; border-radius: 6px; color: var(--text); text-decoration: none; font-size: 14px; } +.bench-newset-menu a:hover, .bench-newset-menu a:focus-visible { background: var(--surface-2); color: var(--accent); } +.bench-newset-menu small { color: var(--text-faint); font-variant-numeric: tabular-nums; } +.tasks-page { display: flex; flex-direction: column; gap: 20px; } +.tasks-page .bench-blocked { margin: 0; } +.tasks-page .tasks-warn { border-color: color-mix(in srgb, var(--patch_failed_tests) 45%, var(--border)); } +.tasks-note { font-weight: 400; overflow-wrap: anywhere; } +.tasks-browse { padding: 22px; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); min-width: 0; } +.tasks-bar { display: flex; flex-direction: column; gap: 14px; } +.tasks-find { flex: none; max-width: 520px; } +.tasks-cats { display: flex; flex-direction: column; gap: 10px; } +.tasks-cats .filter-pills { align-items: center; } +.tasks-catname { font-size: 12px; color: var(--text-faint); min-width: 64px; } +.tasks-cats .filter-pill { min-height: 34px; padding: 6px 12px; } +.tasks-n { color: var(--text-faint); font-variant-numeric: tabular-nums; } +.filter-pill[aria-pressed="true"] .tasks-n { color: inherit; opacity: .8; } +.tasks-sel { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border-soft); } +.tasks-sel b { margin-right: 6px; font-weight: 500; font-variant-numeric: tabular-nums; } +.tasks-paste { position: relative; } +.tasks-paste > summary { list-style: none; } +.tasks-paste > summary::-webkit-details-marker { display: none; } +.tasks-paste-box { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; margin-top: 8px; width: min(420px, calc(100vw - 64px)); } +.tasks-paste-box textarea { width: 100%; box-sizing: border-box; font: 13px var(--mono); color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; } +.tasks-count { margin: 14px 0 6px; font-size: 13px; color: var(--text-dim); } +.tasks-scroll { overflow-x: auto; } +.tasks-table th, .tasks-table td { padding: .6rem .7rem; } +.tasks-table td:nth-child(2) { overflow-wrap: anywhere; } +.tasks-table td.tasks-text { width: 100%; max-width: 0; } +.tasks-row { display: flex; align-items: baseline; gap: 10px; width: 100%; min-width: 0; margin: 0; padding: 0; border: 0; background: none; color: inherit; + font: inherit; text-align: left; cursor: pointer; } +.tasks-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; } +.tasks-row .tasks-title { flex: 1 1 auto; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.tasks-row .tasks-whole { display: none; flex: 1 1 100%; white-space: pre-wrap; line-height: 1.45; } +.tasks-table .tasks-id { display: none; flex: none; margin: 0; } +.tasks-table tr:hover .tasks-id, .tasks-table tr:focus-within .tasks-id { display: inline; } +.tasks-open .tasks-row { flex-wrap: wrap; } +.tasks-open .tasks-row .tasks-title { display: none; } +.tasks-open .tasks-row .tasks-whole, .tasks-table .tasks-open .tasks-id { display: block; } +.tasks-tick { width: 1%; } +.tasks-tick input { width: 18px; height: 18px; margin: 0; } +.tasks-title { display: block; line-height: 1.45; } +.tasks-table tr[data-id] { cursor: pointer; } +.tasks-table small { display: block; margin-top: 2px; font-size: 12px; } +.tasks-tags { display: none; } +.tasks-pages { display: flex; align-items: center; gap: 12px; margin-top: 14px; font-size: 13px; color: var(--text-dim); } +.tasks-savebar { position: sticky; bottom: 12px; z-index: 2; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin-top: 14px; padding: 10px 16px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface-2); box-shadow: var(--shadow); } +.tasks-savebar b { font-weight: 500; font-variant-numeric: tabular-nums; } +.tasks-savebar.tasks-gone { visibility: hidden; } +.tasks-save { padding: 22px; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); } +.tasks-form { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 12px; } +.tasks-form + .tasks-form { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border-soft); } +.tasks-field { display: flex; flex-direction: column; gap: 6px; flex: 0 1 240px; font-size: 12px; color: var(--text-dim); } +.tasks-field.tasks-wide { flex: 1 1 320px; } +.tasks-field input { font: inherit; font-size: 14px; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 9px 11px; min-height: 40px; box-sizing: border-box; } +.tasks-field input:focus, .tasks-paste-box textarea:focus { outline: none; border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } +.tasks-msg { margin: 12px 0 0; min-height: 1.2em; font-size: 14px; } +.tasks-msg.bad { color: var(--bad); } +#task-sets { scroll-margin-top: calc(var(--topbar-height) + 24px); } +.tasks-rename[open] summary { border-color: var(--accent); } +.tasks-rename .bench-delete-ask { border-color: var(--border); } +.tasks-rename .tasks-field { flex: 1 1 100%; } +@media (max-width: 640px) { + .tasks-browse, .tasks-save { padding: 16px; } .tasks-field, .tasks-field.tasks-wide { flex: 1 1 100%; } .tasks-catname { min-width: 0; width: 100%; } + .tasks-table th:nth-child(3), .tasks-table td.tasks-catcol { display: none; } + .tasks-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; } + .tasks-table th, .tasks-table td { padding: .55rem .4rem; } + .tasks-page .bench-delete-ask { left: 0; right: auto; } +} diff --git a/app/static/catalogue/tasks.js b/app/static/catalogue/tasks.js new file mode 100644 index 000000000..cbbfba7c5 --- /dev/null +++ b/app/static/catalogue/tasks.js @@ -0,0 +1,177 @@ +// A dataset's tasks (templates/catalogue/tasks.html): the server gives a page of 100 tasks for a search and category +// values (web/catalogue.py, standard/runner/units.py); this page keeps the chosen ids alone. The listing is asked for once the +// page has loaded: in the cache, it shows at once; one that can be made lightly is started out of the request and +// the page asks again until it is ready; one that needs the benchmark's full environment is never started here. +(() => { + const page = document.getElementById('tasks-page'); + if (!page) return; + const $ = id => document.getElementById(id), d = page.dataset, nouns = d.nouns || 'tasks'; + const writable = d.writable === 'true'; + const chosen = new Set(JSON.parse(($('tasks-chosen-ids') || {}).textContent || '[]')); + // opened from a set: its members first; Show all browses the dataset + const st = {q: '', cats: {}, page: 1, showing: !!d.set && chosen.size > 0, ready: false, total: 0, pages: 1}; + const label = field => field.charAt(0).toUpperCase() + field.slice(1).replace(/_/g, ' '); + const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c])); + // the listing at the version the page shows (data-version, empty for the benchmark's default) + const at = url => d.version ? url + (url.includes('?') ? '&' : '?') + 'version=' + encodeURIComponent(d.version) : url; + const post = (url, body) => nulliusFetch(at(url), {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': d.csrf}, body: JSON.stringify(body)}); + const count = n => `${n.toLocaleString('en-US')} ${n === 1 ? nouns.replace(/s$/, '') : nouns}`; + + function say(text, warn) { + const el = $('tasks-state'); el.hidden = !text; el.textContent = text || ''; el.classList.toggle('tasks-warn', !!warn); + } + function chosenLine() { + $('tasks-chosen').textContent = `${chosen.size.toLocaleString('en-US')} chosen`; + if ($('tasks-bar-chosen')) $('tasks-bar-chosen').textContent = $('tasks-chosen').textContent; + $('tasks-show').disabled = !chosen.size && !st.showing; + } + // a task on one line: its title cut to the width, the whole text in its tooltip and, on a click of the row (or Enter + // on it), in place; its id beside it on hover or focus, and once open + function row(t) { + const tags = Object.values(t.categories || {}).map(v => `${esc(v)}`).join(' '); + const whole = t.text || t.title || t.id; + return `` + + `` + + `${t.unknown ? 'not in the listing' : ''}` + + (tags ? `${tags}` : '') + `${tags}`; + } + function draw(tasks) { + $('tasks-rows').innerHTML = tasks.map(row).join(''); + $('tasks-table').hidden = !tasks.length; + const fields = [...new Set(tasks.flatMap(t => Object.keys(t.categories || {})))]; + $('tasks-cat-head').hidden = !fields.length; + $('tasks-cat-head').textContent = fields.map(label).join(' · '); + document.querySelectorAll('#tasks-rows td.tasks-catcol').forEach(td => { td.hidden = !fields.length; }); + } + function facets(cats) { + $('tasks-cats').innerHTML = Object.entries(cats || {}).map(([field, values]) => + `
${esc(label(field))}` + + values.map(v => ``).join('') + + '
').join(''); + } + function pager() { + const nav = $('tasks-pages'); + nav.hidden = st.showing || st.pages <= 1; + $('tasks-page-of').textContent = `Page ${st.page} of ${st.pages}`; + nav.querySelector('[data-page=prev]').disabled = st.page <= 1; + nav.querySelector('[data-page=next]').disabled = st.page >= st.pages; + } + function query(extra) { + const u = new URLSearchParams(); + if (st.q) u.set('q', st.q); + Object.entries(st.cats).forEach(([f, vs]) => vs.forEach(v => u.append('cat', `${f}=${v}`))); + Object.entries(extra || {}).forEach(([k, v]) => u.set(k, v)); + if (d.version) u.set('version', d.version); + return d.listing + '?' + u; + } + let polling = null, asked = 0; + // not in the cache: the server's line for its state; a light listing started once, out of any request, then asked + // again every few seconds until it is ready + function notReady(got) { + if ($('tasks-match')) $('tasks-match').hidden = true; + const light = got.state === 'light' && !got.error; + say(got.say, !light); + if (!light) return; + clearTimeout(polling); + if (!got.preparing && d.local !== 'true') return say('The list is prepared from a browser on the application host. Ids can still be pasted.', true); + if (!got.preparing && !asked++) + return post(d.prepare, {}).then(r => r.json()).then(g => { say(g.say || got.say); polling = setTimeout(load, 2500); }) + .catch(() => say('The list could not be started. Reload the page.', true)); + polling = setTimeout(load, 2500); + } + async function load() { + let got; + try { got = await (await nulliusFetch(query({page: st.page}))).json(); } catch { return say('The list could not be read. Reload the page.', true); } + if (!got.ok) return say(got.error || 'The list could not be read.', true); + if (!got.ready) { $('tasks-count').textContent = ''; draw([...chosen].map(id => ({id}))); pager(); chosenLine(); return notReady(got); } + say(''); + st.ready = true; st.total = got.total; st.pages = got.pages; st.page = got.page; + facets(got.categories); + const m = $('tasks-match'); + if (m) { m.hidden = !writable || !got.total || st.showing; m.textContent = `Select the ${got.total.toLocaleString('en-US')} that match`; } + if (st.showing) return showSelected(); + draw(got.tasks); + $('tasks-count').textContent = `${count(got.total)}` + (got.total !== got.of ? ` of ${got.of.toLocaleString('en-US')}` : '') + + (got.described ? '' : ' · its driver gives ids alone'); + pager(); chosenLine(); + } + async function showSelected() { + const ids = [...chosen]; + let got = {tasks: ids.map(id => ({id})), unknown: []}; + try { got = await (await post(d.rows, {units: ids})).json(); } catch { /* the ids alone */ } + const unknown = new Set(got.unknown || []); + draw([...got.tasks, ...[...unknown].map(id => ({id, unknown: true}))]); + $('tasks-count').textContent = `${count(ids.length)} chosen` + (unknown.size ? ` · ${unknown.size} not in the listing` : ''); + pager(); chosenLine(); + } + + function setShowing(showing) { + st.showing = showing; + $('tasks-show').setAttribute('aria-pressed', String(showing)); + $('tasks-show').textContent = showing ? 'Show all' : 'Show selected'; + } + let typing = null; + $('tasks-q').addEventListener('input', e => { clearTimeout(typing); typing = setTimeout(() => { st.q = e.target.value.trim(); setShowing(false); st.page = 1; load(); }, 250); }); + $('tasks-cats').addEventListener('click', e => { + const b = e.target.closest('[data-field]'); if (!b) return; + const f = b.dataset.field, v = b.dataset.value, vs = st.cats[f] || []; + st.cats[f] = vs.includes(v) ? vs.filter(x => x !== v) : [...vs, v]; + if (!st.cats[f].length) delete st.cats[f]; + setShowing(false); st.page = 1; load(); + }); + $('tasks-rows').addEventListener('click', e => { + if (e.target.closest('input, a')) return; // a tick is a tick + const tr = e.target.closest('tr[data-id]'), b = tr && tr.querySelector('.tasks-row'); if (!b) return; + b.setAttribute('aria-expanded', String(tr.classList.toggle('tasks-open'))); + }); + $('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(); + }); + $('tasks-pages').addEventListener('click', e => { + const b = e.target.closest('[data-page]'); if (!b) return; + st.page += b.dataset.page === 'next' ? 1 : -1; load(); + }); + $('tasks-show').addEventListener('click', () => { + setShowing(!st.showing); load(); + }); + $('tasks-match')?.addEventListener('click', async () => { + const got = await (await nulliusFetch(query({ids: 1}))).json(); + if (got.ok && got.ready) { got.ids.forEach(id => chosen.add(id)); load(); } + }); + $('tasks-clear')?.addEventListener('click', () => { chosen.clear(); 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)); + $('tasks-paste').value = ''; $('tasks-paste').closest('details').open = false; + window.nulliusNotify?.(`${count(ids.length)} added.`); + load(); + }); + + const msg = (text, bad) => { const el = $('tasks-msg'); if (el) { el.textContent = text; el.classList.toggle('bad', !!bad); } }; + async function save(body) { + if (!chosen.size) return msg('Tick at least one task.', true); + let got; + try { got = await (await post(d.save, {...body, units: [...chosen]})).json(); } catch { return msg('Not saved: the server did not answer.', true); } + if (!got.ok) return msg(got.error, true); + location.href = got.open; + } + $('tasks-create')?.addEventListener('submit', e => { + e.preventDefault(); const f = e.target; + save({name: f.elements.namedItem('name').value.trim(), description: f.elements.namedItem('description').value.trim(), + ...(d.version ? {version: d.version} : {})}); + }); + // the count and the way to save stay in view under the rows; the bar steps aside once the form is in view + const bar = $('tasks-savebar'), form = document.querySelector('.tasks-save'); + if (bar && form && 'IntersectionObserver' in window) + new IntersectionObserver(([e]) => bar.classList.toggle('tasks-gone', e.isIntersecting)).observe(form); + $('tasks-to-save')?.addEventListener('click', e => { + const field = form?.querySelector('input'); if (!field) return; + e.preventDefault(); form.scrollIntoView({block: 'nearest'}); field.focus({preventScroll: true}); + }); + setShowing(st.showing); + chosenLine(); + load(); +})(); diff --git a/app/static/style.css b/app/static/style.css index 78accf262..2690f0925 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -359,6 +359,14 @@ tr.tone-good .jbar .fill { background: #4cc26a; } tr.tone-warn .jbar .fill { bac .run-meta > span + span::before { content: "·"; color: var(--text-faint); margin-right: 14px; } .run-meta > .mono { color: var(--text); } @media(max-width:640px){.run-meta > span + span::before{display:none}.run-meta{font-size:13px}} +.run-saveset { position: relative; } +.run-saveset > summary { list-style: none; } +.run-saveset > summary::-webkit-details-marker { display: none; } +.run-saveset-form { position: absolute; right: 0; top: calc(100% + 6px); z-index: 20; display: flex; flex-direction: column; gap: 10px; width: min(300px, calc(100vw - 32px)); padding: 14px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); box-shadow: 0 8px 24px rgba(0, 0, 0, .12); } +.run-saveset-form label { display: flex; flex-direction: column; gap: 5px; font-size: 12px; color: var(--text-dim); } +.run-saveset-form input:not([type=hidden]) { font: inherit; font-size: 14px; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; } +.run-saveset-form .btn { align-self: flex-start; } +@media (max-width: 640px) { .run-saveset-form { position: static; margin-top: 8px; box-shadow: none; } } .bar { display: flex; height: 8px; border-radius: 99px; overflow: hidden; diff --git a/app/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index 4a57c4fc6..1855efd08 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -206,6 +206,38 @@

{{ d.title }}

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

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

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

From {{ b.title }}

+ + {% if task_sets %}

Yours

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

{{ entry.description }}

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

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

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

{{ problem }}

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

+
+ + + + +
+ + {% if writable %} + + {% endif %} +
+ + {% if writable %} +
+

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

+
+ + + +
+ +
+ {% endif %} +
+ +{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index a4ad6ea6b..dfc8645df 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -22,6 +22,7 @@ {% if benchmark %}
Benchmark{{ benchmark }}
{% endif %}
Dataset{{ job.dataset|dsname }}
{% endif %} + {% if job.task_set %}task set {% if set_link.link %}{{ set_link.name }}{% else %}{{ set_link.name }}{% endif %}{% endif %} {% if job.agent_label or job.model_name %}
{% if job.agent_label %}{% endif %} @@ -45,7 +46,17 @@ title="Open the run builder with what this run recorded: its agents and their parameters, model, dataset and task filter, limits, timeouts and Harbor; anything a recipe cannot say is named there">New run like this{% endif %} {% set controls = feasibility_controls(job) %}{% if controls %}Feasibility · {{ controls|join(' + ') }}{% endif %} {% if job.harbor_command %}{% endif %}{% endset %} + title="{{ job.harbor_command }}">Copy command{% endif %} + {% if set_saving %}
+ Save as task set +
+ + + + +
+
{% endif %}{% endset %} {{ page_head(job.job_id, sub=meta, actions=actions) }} {% set board_ready = live_board and live_board.initial and live_board.initial.state != 'unknown' %} diff --git a/app/tests/test_task_set_recipe.py b/app/tests/test_task_set_recipe.py index 234696319..373ba5c62 100644 --- a/app/tests/test_task_set_recipe.py +++ b/app/tests/test_task_set_recipe.py @@ -49,6 +49,56 @@ def compile(self, **kw): return recipe.compile(self.recipe(**kw), self.defs) +class TheRecipe(Scratch): + def test_a_set_compiles_to_set_name_and_review_names_its_label_and_its_count(self): + sets.create(self.b, "Dev set", dataset="all", units=["good", "wrong", "slow"]) + # a recipe from before sets were frozen names it NAME@1: the same set + for ref, n in (("dev-set", 3), ("dev-set@1", 3)): + with self.subTest(ref=ref): + out = self.compile(task_sets={"all": ref}) + self.assertEqual(out["errors"], []) + self.assertIn("--dataset all --set dev-set -j 1", out["shards"][0]["command"]) + dataset_row = next(r for r in out["review"] if r[1] == "Dataset") + self.assertEqual(dataset_row[2], f"all · task set Dev set · {n} tasks") + self.assertNotIn("revision", json.dumps(out["review"])) + self.assertTrue(next(r for r in out["review"] if r[1] == "Scope")[2].startswith(f"all {n} tasks")) + 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")) + + def test_a_set_of_another_benchmark_or_dataset_or_a_dataset_not_chosen_is_refused(self): + sets.create(self.memo, "theirs", dataset=self.memo["datasets"][0]["id"], units=["x"]) + sets.create(self.b, "other-ds", dataset="more", units=["good"]) + sets.create(self.b, "dev", dataset="all", units=["good"]) + for kw, said in (({"task_sets": {"all": "theirs"}}, "Fake bench has no task set theirs: choose another, or all of all's tasks."), + ({"task_sets": {"all": "other-ds"}}, "The task set other-ds is cut from the dataset more, not all."), + ({"task_sets": {"more": "dev"}}, "The task set dev is for more, a dataset not chosen."), + ({"task_sets": {"all": "dev@4"}}, "Task set dev@4: dev@4 names an earlier list of the task set dev: " + "a set is read as its latest list now; name it dev."), + ({"task_sets": {"all": "a/b"}}, "Task set a/b: 'a/b' is not a task set's name"), + ({"task_sets": ["dev"]}, "Task sets are a dataset with a set's name each.")): + with self.subTest(kw=kw): + out = self.compile(**kw) + self.assertEqual([e["step"] for e in out["errors"]], [recipe.STEP["dataset"]]) + self.assertTrue(out["errors"][0]["message"].startswith(said), out["errors"][0]["message"]) + + def test_a_recipe_without_a_set_compiles_as_before(self): + sets.create(self.b, "dev", dataset="all", units=["good"]) + plain, empty = self.compile(), self.compile(task_sets={}) + self.assertEqual(plain, empty) + self.assertEqual(plain["shards"][0]["command"], + 'nullius standard run fakebench nop --provider openai --dataset all -j 1 ' + '--name fake-sets --from-run --jobs "${NULLIUS_JOBS:-jobs_standard}"') + self.assertEqual(next(r for r in plain["review"] if r[1] == "Dataset")[2], "all · 4 tasks") + + def test_the_builder_offers_each_datasets_sets(self): + sets.create(self.b, "dev", dataset="all", units=["good", "wrong"], description="two") + page = recipe._bench_page(self.b) + self.assertEqual([[(s["name"], s["label"], s["units"], s["description"]) for s in d["sets"]] for d in page["datasets"]], + [[("dev", "dev", 2, "two")], []]) + self.assertTrue(all("revision" not in s for d in page["datasets"] for s in d["sets"])) + + class OnAHost(Scratch): """What the app sends a host for a recipe with a set: the snapshot holds the set's entry; the run there, reading the copy of the snapshot's catalogue a host run reads, runs the set and records it.""" diff --git a/app/ui_tests/test_builder_limits.py b/app/ui_tests/test_builder_limits.py new file mode 100644 index 000000000..52e48cd8f --- /dev/null +++ b/app/ui_tests/test_builder_limits.py @@ -0,0 +1,41 @@ +"""The standard's Limits step as the page draws it: its fields, their hints and the defaults they show.""" +import json +import re +import subprocess + +from ui_tests.builder_support import APP, CompilerCase + + +class LimitsStep(CompilerCase): + def draw(self, key, edit=""): + """standardForm on the Limits step and what it calls, cut from the page script, run against the core: its html; + ``edit``, JavaScript changing the recipe ``r`` first.""" + page = (APP / "static/builder/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" + schema = dict(self.schema, hosts=[], standardHere={"docker": None, "licences": {}, "host": {}}) + program = ("const schema=" + json.dumps(schema) + ";const C=require(" + json.dumps(str(APP / "static/builder/command-builder-core.js")) + ")(schema);\n" + + "const S=C.STEP,REVIEW=S.review;let step=S.limits;\n" + + line("esc") + line("button") + cut(" const unitsOf = ", " // the first clause") + line("words") + + line("atMost") + line("field") + line("fixed") + line("note") + cut(" function standardForm(", " function compileRunner(") + + "const r=C.createStandard(" + json.dumps(key) + ");" + edit + + "process.stdout.write(JSON.stringify(standardForm(r)));") + return json.loads(subprocess.run([self.node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + + def test_the_number_of_tasks_says_all_of_them_and_takes_that_many_at_most(self): + field = lambda html: re.search(r'
{% 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 #} +
-
+ diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 301289bfd..d5032c23f 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -5,8 +5,9 @@ listing gives and the filter in its note; OSWorld1's ``describe`` from its task files. A definition's ``driver.list_command`` listing with no driver environment, OSWorld1's giving the driver's ids in its order; ``state`` giving each of its answers and starting nothing; the command's one line before a first listing that -fetches. No key, no network: each driver is a script of the test's own, the fake benchmark's or OSWorld1's on -task files of the test's own.""" +fetches; a licence the driver needs, given to it as a run gives it, and refused first when none is held. No +key, no network: each driver is a script of the test's own, the fake benchmark's or OSWorld1's on task files of +the test's own.""" from __future__ import annotations import contextlib @@ -33,6 +34,9 @@ DRIVER = r'''import json, os, sys with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "started"), "a") as f: f.write("started\n") +if os.environ.get("HF_TOKEN"): # a licence bound for the driver, as the listing gave it + with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "given"), "w") as f: + f.write(os.environ["HF_TOKEN"]) KINDS = ("alpha", "beta", "gamma") N = 20 if os.environ.get("NULLIUS_OPTION_MODE") == "short" else 250 IDS = [f"t{i:03d}" for i in range(N)] @@ -283,6 +287,36 @@ def test_a_filter_that_matches_nothing_or_beside_another_source_is_refused(self) self.assertFalse(os.path.exists(os.path.join(self.cat, "sets"))) +def gated(bench: dict) -> dict: + """``bench`` with its dataset in an environment that needs a data provider's token, bound for the driver.""" + return dict(bench, datasets=[dict(d, environment="data") for d in bench["datasets"]], + environments={"data": {"summary": "the data", "needs_secrets": [ + {"name": "HF_TOKEN", "to": "driver", "provider": "huggingface"}]}}) + + +class Licences(Scratch): + def given(self): + path = Path(self.b["_here"], "given") + return path.read_text() if path.exists() else None + + def test_the_driver_gets_its_licence_and_none_held_is_refused_before_it_starts(self): + self.b = gated(self.b) + env = {k: v for k, v in os.environ.items() if k != "HF_TOKEN"} + with mock.patch.dict(os.environ, env, clear=True): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual((code, out, self.starts()), (2, "", 0)) + self.assertEqual(err, "refused: cannot list described's dataset all: it needs a Hugging Face token, HF_TOKEN " + "(Settings → Data providers)\n") + with self.assertRaisesRegex(units.Refused, "needs a Hugging Face token"): + units.listing(self.b, "all") + # held, from the provider's variable as a headless run takes it, or from the store: the driver gets it + with mock.patch.dict(os.environ, dict(env, HF_TOKEN="from-the-environment"), clear=True): + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") + self.assertEqual((code, out.splitlines()[0], self.given()), (0, "1 of 250 tasks of all", "from-the-environment")) + units.listing(dict(self.b, options={}), "all", licences={"HF_TOKEN": {"kind": "value", "value": "from-the-store"}}) + self.assertEqual(self.given(), "from-the-store") + + ASKED = AssertionError("the listing asked for the driver's environment") HEAVY = {"command": ["{install}/.venv/bin/python", "{here}/driver.py"], "install": {"python": "3.12", "pip": ["nothing-installed==1.0"]}, "describe": True} @@ -375,13 +409,13 @@ def fetching(self, **driver) -> dict: def test_cached(self): units.find(self.b, "all") - self.assertEqual(self.asked(self.b), {"state": "cached", "fetch": [], "reason": ""}) + self.assertEqual(self.asked(self.b), {"state": "cached", "fetch": [], "reason": "", "needs": []}) self.assertEqual(self.asked(self.b, options={"mode": "short"})["state"], "full") # not listed under it def test_light_and_what_it_fetches(self): light = [sys.executable, "{here}/driver.py"] self.assertEqual(self.asked(dict(self.b, driver=dict(HEAVY, list_command=light))), - {"state": "light", "fetch": [], "reason": ""}) + {"state": "light", "fetch": [], "reason": "", "needs": []}) got = self.asked(self.fetching(list_command=light)) self.assertEqual((got["state"], got["reason"]), ("light", "")) self.assertEqual(got["fetch"], [{"what": "upstream", "text": "the upstream https://example.org/upstream.git at aaaaaaaaaaaa"}, @@ -412,10 +446,10 @@ def digest(path): return sha256(path) with mock.patch.object(units.ondisk, "sha256_of", side_effect=digest): - self.assertEqual(self.asked(bench), {"state": "light", "fetch": [], "reason": ""}) + self.assertEqual(self.asked(bench), {"state": "light", "fetch": [], "reason": "", "needs": []}) def test_full_and_the_environment_it_installs(self): - self.assertEqual(self.asked(self.b), {"state": "full", "fetch": [], "reason": ""}) + self.assertEqual(self.asked(self.b), {"state": "full", "fetch": [], "reason": "", "needs": []}) got = self.asked(self.fetching()) self.assertEqual((got["state"], [f["what"] for f in got["fetch"]]), ("full", ["upstream", "dataset", "environment"])) self.assertEqual(got["fetch"][2]["text"], "the driver's environment, installed with uv") @@ -437,6 +471,15 @@ def test_refused_with_its_reason(self): with self.assertRaisesRegex(units.NotFound, "no dataset 'nope'"): self.asked(self.b, "nope") + def test_a_licence_its_driver_needs_and_none_holds_is_refused_first(self): + bench = dict(gated(self.fetching())) + got = self.asked(bench, programs=()) # before the programs and the fetches are looked at + self.assertEqual((got["state"], got["fetch"], got["needs"]), ("refused", [], [{"name": "HF_TOKEN", "provider": "huggingface"}])) + self.assertEqual(got["reason"], "cannot list described's dataset all: it needs a Hugging Face token, HF_TOKEN " + "(Settings → Data providers)") + with mock.patch.object(units.run, "Licences", return_value={"HF_TOKEN": {"kind": "value", "value": "v"}}): + self.assertEqual(self.asked(bench)["state"], "full") + class FirstListing(Scratch): def test_the_command_says_in_one_line_what_a_first_listing_fetches(self): diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index 445d3273f..571ed47e6 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -356,21 +356,46 @@ def slow(bench, dataset, options=None): self.assertNotEqual(made[0], threading.current_thread().name) self.assertEqual(self.starts(), 0) - def test_a_listing_that_needs_the_full_environment_is_never_started_and_says_what_it_needs(self): + def test_a_listing_that_needs_the_full_environment_starts_on_a_click_and_says_what_it_installs(self): self.stack.enter_context(patch.object(units, "state", lambda b, d, o=None: { - "state": "full", "fetch": [{"what": "environment", "text": "the driver's environment, installed with uv"}], "reason": ""})) + "state": "full", "fetch": [{"what": "environment", "text": "the driver's environment, installed with uv"}], + "reason": "", "needs": []})) self.no_fetch_no_install() - called = [] - self.stack.enter_context(patch.object(units, "listing", lambda *a, **k: called.append(a))) + html = self.get("/benchmarks/described/tasks/all").get_data(as_text=True) + self.assertIn('', html) + self.assertIn('\s*', self.section("gaia"), re.S).group(1) - self.assertIn('New task set', head) - self.assertIn('
', head) # a menu: not a disclosure, no chevron - for d in gaia["datasets"]: # several datasets: a choice of them, each its tasks' page - self.assertIn(f'{d.get("label") or d["id"]}', head) + telco = _GET("benchmark", "open-telco") + part = self.section("open-telco") + self.assertNotIn("New task set", part) # several datasets: no menu, the button of each opens its tasks + for d in telco["datasets"]: + self.assertIn(f'', part) [only] = _GET("benchmark", "humaneval")["datasets"] one = self.section("humaneval") # one dataset: the button is its link self.assertIn(f'New task set', one) From 079cf3e7a556c9124e6dd17ab7a8d9c652c745ba Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:16:06 +0100 Subject: [PATCH 13/37] fix(catalogue): give the save form's fields the height of its button The shared text input grew to 48 px in the form's column of a label and its field, beside a 42 px button. The fields keep their natural size, 42 px high. --- app/static/catalogue/catalogue.css | 1 + 1 file changed, 1 insertion(+) diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index cb3dbc5e0..5a00ed13b 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -484,6 +484,7 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .tasks-form { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 12px; } .tasks-form + .tasks-form { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border-soft); } .tasks-field { display: flex; flex-direction: column; gap: 6px; flex: 0 1 240px; } +.tasks-field input { flex: none; height: 42px; box-sizing: border-box; } .tasks-field.tasks-wide { flex: 1 1 320px; } .tasks-paste-box textarea:focus { outline: none; border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } .tasks-msg { margin: 12px 0 0; min-height: 1.2em; } From c2f043471e3a5f2510129f6ebf1dc7170a694102 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:16:13 +0100 Subject: [PATCH 14/37] fix(catalogue): open the paste box below the row of chosen tasks Opened inside the row, the box made it as tall as itself, and the row centres its items: the count, Show selected and Clear moved to the middle of the box. The box now opens on its own line below the row. Show selected and Clear show once a task is chosen; with nothing chosen they had nothing to act on. --- app/static/catalogue/catalogue.css | 5 +++-- app/static/catalogue/tasks.js | 6 ++++-- app/templates/catalogue/tasks.html | 12 ++++++------ 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 5a00ed13b..b60044c79 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -450,10 +450,11 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .filter-pill[aria-pressed="true"] .tasks-n { color: inherit; opacity: .8; } .tasks-sel { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border-soft); } .tasks-sel b { margin-right: 6px; } -.tasks-paste { position: relative; } .tasks-paste > summary { list-style: none; } .tasks-paste > summary::-webkit-details-marker { display: none; } -.tasks-paste-box { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; margin-top: 8px; width: min(420px, calc(100vw - 64px)); } +/* the box opens on its own line below the row of the chosen tasks' controls */ +.tasks-paste-box { display: none; flex-direction: column; gap: 8px; align-items: flex-start; margin-top: 10px; width: min(420px, 100%); } +.tasks-sel:has(.tasks-paste[open]) + .tasks-paste-box { display: flex; } .tasks-paste-box textarea { width: 100%; box-sizing: border-box; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; } .tasks-list { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 10px; } .tasks-count { margin: 14px 0 6px; } diff --git a/app/static/catalogue/tasks.js b/app/static/catalogue/tasks.js index 4bc9fb136..60cffa9a0 100644 --- a/app/static/catalogue/tasks.js +++ b/app/static/catalogue/tasks.js @@ -30,7 +30,9 @@ function chosenLine() { $('tasks-chosen').textContent = `${chosen.size.toLocaleString('en-US')} chosen`; if ($('tasks-bar-chosen')) $('tasks-bar-chosen').textContent = $('tasks-chosen').textContent; - $('tasks-show').disabled = !chosen.size && !st.showing; + // Show selected and Clear once something is chosen; Show all while the chosen are shown + $('tasks-show').hidden = !chosen.size && !st.showing; + $('tasks-clear').hidden = !chosen.size; } // a task on one line: its title cut to the width, the whole text in the row's tooltip and, while its box (its text // where the box is disabled) has the keyboard's focus, in place; its id beside it on hover or focus. A click @@ -160,7 +162,7 @@ $('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)); - $('tasks-paste').value = ''; $('tasks-paste').closest('details').open = false; + $('tasks-paste').value = ''; $('tasks-paste-open').open = false; window.nulliusNotify?.(`${count(ids.length)} added.`); load(); }); diff --git a/app/templates/catalogue/tasks.html b/app/templates/catalogue/tasks.html index 4f7660f6c..e0f185bc2 100644 --- a/app/templates/catalogue/tasks.html +++ b/app/templates/catalogue/tasks.html @@ -71,13 +71,13 @@
0 chosen - -
Paste ids -
-
-
- + +
Paste ids
+
+ {#- the box Paste ids opens, on its own line below the row #} +
+

From b1eb3f6cfcda681cf5da3404d748e93f65d28cac Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:16:16 +0100 Subject: [PATCH 15/37] fix(catalogue): hide the tasks page's count and message lines while empty Empty, the count line and the save form's message still took their margins, and the message its line's height: a gap above the table and under the form. --- app/static/catalogue/catalogue.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index b60044c79..a11873624 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -458,6 +458,7 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .tasks-paste-box textarea { width: 100%; box-sizing: border-box; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; } .tasks-list { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 10px; } .tasks-count { margin: 14px 0 6px; } +.tasks-count:empty, .tasks-msg:empty { display: none; } .tasks-scroll { overflow-x: auto; } .tasks-table th, .tasks-table td { padding: .6rem .7rem; } .tasks-table td:nth-child(2) { overflow-wrap: anywhere; } @@ -488,7 +489,7 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .tasks-field input { flex: none; height: 42px; box-sizing: border-box; } .tasks-field.tasks-wide { flex: 1 1 320px; } .tasks-paste-box textarea:focus { outline: none; border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } -.tasks-msg { margin: 12px 0 0; min-height: 1.2em; } +.tasks-msg { margin: 12px 0 0; } .tasks-msg.bad { color: var(--bad); } #task-sets { scroll-margin-top: calc(var(--topbar-height) + 24px); } .tasks-rename[open] summary { border-color: var(--accent); } From 791fb83abbd87f0eb37324cfaaa58a3a76eab571 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:16:20 +0100 Subject: [PATCH 16/37] feat(catalogue): mark GAIA's three levels as cut from All levels All levels already holds the 165 questions of the three. Drawn as four datasets, the levels read as other data; as cuts of All levels they show as GAIA's own task sets, the builder offers them under All levels, and New task set opens All levels. --- app/nullius/catalogue/benchmarks/gaia/standard.json | 3 +++ app/tests/test_dataset_subsets.py | 13 +++++++++++-- app/ui_tests/test_task_set_pages.py | 4 ++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/app/nullius/catalogue/benchmarks/gaia/standard.json b/app/nullius/catalogue/benchmarks/gaia/standard.json index a2f1c5638..c357aa2a1 100644 --- a/app/nullius/catalogue/benchmarks/gaia/standard.json +++ b/app/nullius/catalogue/benchmarks/gaia/standard.json @@ -39,18 +39,21 @@ { "id": "gaia-validation-level1", "label": "Validation \u00b7 Level 1", + "subset_of": "gaia-validation", "units": 53, "environment": "data" }, { "id": "gaia-validation-level2", "label": "Validation \u00b7 Level 2", + "subset_of": "gaia-validation", "units": 86, "environment": "data" }, { "id": "gaia-validation-level3", "label": "Validation \u00b7 Level 3", + "subset_of": "gaia-validation", "units": 26, "environment": "data" } diff --git a/app/tests/test_dataset_subsets.py b/app/tests/test_dataset_subsets.py index 8d1018201..1a7fd99da 100644 --- a/app/tests/test_dataset_subsets.py +++ b/app/tests/test_dataset_subsets.py @@ -1,7 +1,7 @@ """A benchmark's list cut from another of its lists (``subset_of`` on a dataset of its definition): the field is optional and names another list, one cut from none, that holds at least as many units; OSWorld1 declares its three -cuts of All tasks at each of its versions; a run still names the list it runs, so a recipe of a cut compiles as -before. No key, no network.""" +cuts of All tasks at each of its versions, and GAIA its three levels of All levels; a run still names the list it +runs, so a recipe of a cut compiles as before. No key, no network.""" from __future__ import annotations import copy @@ -56,6 +56,15 @@ def test_osworld1_declares_its_three_cuts_of_all_tasks_at_each_version(self): self.assertEqual([x["subset_of"] for x in recipe._bench_page(b)["datasets"]], ["test_all" if x.get("subset_of") else "" for x in b["datasets"]]) + def test_gaias_three_levels_are_cut_from_all_levels(self): + b = definitions.get("benchmark", "gaia") + self.assertEqual({x["id"]: x.get("subset_of") for x in b["datasets"]}, + {"gaia-validation": None, "gaia-validation-level1": "gaia-validation", + "gaia-validation-level2": "gaia-validation", "gaia-validation-level3": "gaia-validation"}) + self.assertEqual(sum(x["units"] for x in b["datasets"] if x.get("subset_of")), + next(x["units"] for x in b["datasets"] if x["id"] == "gaia-validation")) + self.assertEqual([p for p in definitions.problems(clean(b), "benchmark") if "subset_of" in p], []) + def test_a_run_still_names_the_list_it_runs(self): b = definitions.get("benchmark", "osworld1@044bc33") out = recipe.compile({"version": 1, "harness": "standard", "name": "osw", "title": "t", "benchmark": "osworld1@044bc33", diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index cf6746abf..71edb8004 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -675,7 +675,7 @@ def test_the_page_lists_its_own_sets_then_the_users_and_one_dataset_to_cut_from( self.assertLess(text.index("From OSWorld1"), text.index("Yours")) self.assertLess(text.index("Yours"), text.index("Chrome tabs")) # a benchmark that declares nothing is drawn as before - self.assertNotIn("From ", visible(self.section("gaia"))) + self.assertNotIn("From ", visible(self.section("open-telco"))) def node_program(self, body): node = shutil.which("node") @@ -714,7 +714,7 @@ def test_the_builder_draws_all_of_it_the_benchmarks_own_sets_then_the_users(self self.assertEqual((got["whole"]["datasets"], got["whole"].get("task_sets")), (["test_all"], None)) def test_a_benchmark_that_declares_nothing_is_drawn_as_before(self): - got = self.node_program("const b=C.standardBench(C.createStandard('gaia'));" + got = self.node_program("const b=C.standardBench(C.createStandard('open-telco'));" "process.stdout.write(JSON.stringify({nested:C.nestedDatasets(b),n:b.datasets.length}));") self.assertEqual(got["nested"], False) self.assertGreater(got["n"], 1) From 000837ec0f37e1f101f3793d3be5aa014dc67fcf Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:16:24 +0100 Subject: [PATCH 17/37] feat(catalogue): describe GAIA's and Open Telco's questions for their listings Neither driver answered describe: their tasks pages listed ids alone, and a search read the ids. - GAIA: each question's text, and its level as its category, from the metadata its units come from. - Open Telco: each sample's question, and as its category the value of each filter its task takes (TeleQnA's subject, ORANBench's difficulty, 6G-Bench's task), from the sample's metadata. --- .../catalogue/benchmarks/gaia/driver.py | 12 +++++++++- .../catalogue/benchmarks/gaia/standard.json | 1 + .../catalogue/benchmarks/open-telco/driver.py | 23 ++++++++++++++++++- .../benchmarks/open-telco/standard.json | 1 + app/tests/test_gaia_driver.py | 10 +++++++- app/tests/test_open_telco_driver.py | 8 +++++++ 6 files changed, 52 insertions(+), 3 deletions(-) diff --git a/app/nullius/catalogue/benchmarks/gaia/driver.py b/app/nullius/catalogue/benchmarks/gaia/driver.py index ddc82fe68..c2b685ae9 100644 --- a/app/nullius/catalogue/benchmarks/gaia/driver.py +++ b/app/nullius/catalogue/benchmarks/gaia/driver.py @@ -95,6 +95,16 @@ def units(dataset, setup=None): return {"units": list(load())} +def describe(dataset, **_): + """Each question's text and its level, read from the metadata its unit comes from.""" + rows = load() + out = {} + for unit in units(dataset)["units"]: + text = rows[unit]["Question"] + out[unit] = {"title": text, "text": text, "categories": {"level": str(rows[unit]["Level"])}} + return {"units": out} + + def attachment(row): name = row.get("file_name") or "" path = row.get("file_path") or "" @@ -170,7 +180,7 @@ def answer(unit, dir, setup, model, base_url, key, **_): return {"answer": value, "model": model} -HANDLERS = {"units": units, "setup": setup, "score": score, "oracle": oracle, "answer": answer} +HANDLERS = {"units": units, "describe": describe, "setup": setup, "score": score, "oracle": oracle, "answer": answer} def main(): diff --git a/app/nullius/catalogue/benchmarks/gaia/standard.json b/app/nullius/catalogue/benchmarks/gaia/standard.json index c357aa2a1..a203e4df7 100644 --- a/app/nullius/catalogue/benchmarks/gaia/standard.json +++ b/app/nullius/catalogue/benchmarks/gaia/standard.json @@ -16,6 +16,7 @@ "tested_date": "2026-11-06" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" diff --git a/app/nullius/catalogue/benchmarks/open-telco/driver.py b/app/nullius/catalogue/benchmarks/open-telco/driver.py index 067804ead..c69da0c8b 100644 --- a/app/nullius/catalogue/benchmarks/open-telco/driver.py +++ b/app/nullius/catalogue/benchmarks/open-telco/driver.py @@ -10,6 +10,8 @@ else the sample's place in the file (1, 2, ...), zero-padded. A filter option (TeleQnA's subject, ORANBench's difficulty, 6G-Bench's task) runs the task with that argument; its samples keep their numbers +describe - each unit's question as the sample holds it, and the value of each + filter its task takes, from the sample's metadata, as its category setup - the task on the unit with a model that replies nothing: what the solver asks it (TeleMath's system prompt, then the question; the multiple-choice template with its lettered choices) is the prompt @@ -184,6 +186,25 @@ def units(dataset, setup=None): return {"units": out} +def text_of(s): + """A sample's question: its input, or the text of its input's messages.""" + if isinstance(s.input, str): + return s.input + return "\n\n".join(str(getattr(m, "text", "") or "") for m in s.input or []) + + +def describe(dataset, **_): + every = numbered() + out = {} + for unit in units(dataset)["units"]: + s = every[unit] + meta = s.metadata or {} + text = text_of(s) + out[unit] = {"title": text, "text": text, + "categories": {n: str(meta[n]) for n in FILTERS if n in PARAMS and meta.get(n) not in (None, "")}} + return {"units": out} + + def sample_id(unit): return unit if isinstance(numbered()[unit].id, str) else int(unit) @@ -238,7 +259,7 @@ def oracle(unit, dir): return {"answer": f"ANSWER: {s.target}" if s.choices else FORMATS[NAME] % s.target} -HANDLERS = {"units": units, "setup": setup, "answer": answer, "score": score, "oracle": oracle} +HANDLERS = {"units": units, "describe": describe, "setup": setup, "answer": answer, "score": score, "oracle": oracle} def main(): diff --git a/app/nullius/catalogue/benchmarks/open-telco/standard.json b/app/nullius/catalogue/benchmarks/open-telco/standard.json index 2b20bd626..b3f25fda3 100644 --- a/app/nullius/catalogue/benchmarks/open-telco/standard.json +++ b/app/nullius/catalogue/benchmarks/open-telco/standard.json @@ -15,6 +15,7 @@ "license": "MIT" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" diff --git a/app/tests/test_gaia_driver.py b/app/tests/test_gaia_driver.py index 3ec74fdf0..c0e451d27 100644 --- a/app/tests/test_gaia_driver.py +++ b/app/tests/test_gaia_driver.py @@ -158,10 +158,18 @@ def test_original_refuses_missing_or_nontext_model_output(self): return_value=io.BytesIO(json.dumps(reply).encode())), self.assertRaisesRegex(RuntimeError, "no textual answer"): self.driver.answer("fixture-task", str(self.workspace), "original", "model", "https://fixture.invalid", "key") - def test_units_names_only_selected_split_and_oracle_exposes_reference_for_leak_check(self): + def test_units_and_describe_name_only_selected_split_and_oracle_exposes_reference_for_leak_check(self): self.assertEqual(self.driver.units(DATASET), {"units": ["fixture-task"]}) with self.assertRaisesRegex(ValueError, "differs"): self.driver.units("gaia-validation") + self.driver.ROWS["second-task"] = dict(self.row, task_id="second-task", Question="How many?", Level="1") + self.assertEqual(self.driver.describe(DATASET), {"units": { + "fixture-task": {"title": self.row["Question"], "text": self.row["Question"], "categories": {"level": "1"}}, + "second-task": {"title": "How many?", "text": "How many?", "categories": {"level": "1"}}}}) + with self.assertRaisesRegex(ValueError, "differs"): + self.driver.describe("gaia-validation") + self.assertIs(json.loads((DRIVER.parent / "standard.json").read_text())["driver"]["describe"], True) + del self.driver.ROWS["second-task"] result = self.driver.oracle("fixture-task", str(self.workspace)) self.assertEqual(result["answer"], "FINAL ANSWER: synthetic-reference") self.assertEqual((self.workspace / ".gaia-oracle-answer.txt").read_text(), "synthetic-reference") diff --git a/app/tests/test_open_telco_driver.py b/app/tests/test_open_telco_driver.py index 4a11484bd..08563109b 100644 --- a/app/tests/test_open_telco_driver.py +++ b/app/tests/test_open_telco_driver.py @@ -159,6 +159,14 @@ def test_a_filter_runs_the_tasks_own_argument_and_keeps_each_questions_number(se self.assertIn(("teleqna", str(self.snap), {"subject": "Research overview"}), self.up.built) # as the data write it everything = self.load("teleqna-lite", subject="all") self.assertEqual(len(everything.units("teleqna-lite")["units"]), 12) + # describe: the units' questions and, for a task that filters by one, the sample's value as its category + said = driver.describe("teleqna-lite")["units"] + self.assertEqual(list(said), driver.units("teleqna-lite")["units"]) + self.assertEqual(said["04"], {"title": "q4", "text": "q4", "categories": {"subject": "Research overview"}}) + self.assertEqual(everything.describe("teleqna-lite")["units"]["01"]["categories"], {"subject": "Lexicon"}) + self.assertEqual(self.load("teletables-lite").describe("teletables-lite")["units"]["t_9_def456"], + {"title": "t2", "text": "t2", "categories": {}}) + self.assertIs(json.loads((FOLDER / "standard.json").read_text())["driver"]["describe"], True) def test_the_prompt_is_what_the_task_asks_its_model_and_nothing_is_written(self): driver = self.load("telemath-lite") From fbded304793d41b095072452a303280c8de8f985 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:17:48 +0100 Subject: [PATCH 18/37] feat(standard): draw N of a dataset's tasks at random for a task set A set of N tasks took the first N (--limit) or N ticked or pasted by hand. - set create --sample N draws N of the listed tasks, or of those --search and --category match, kept in the listing's order. The same --seed and listing give the same set; with no seed one is drawn and printed. The set's note keeps the draw's command. - A sample larger than the list, or a seed without a sample, is refused in one line. - The tasks page's Pick at random draws through the same code from the matches shown, ticks them, shows the seed, and saves the note with the set while the ticks are the ones drawn. --- app/nullius/standard/cli.py | 33 +++++++++++++++----- app/nullius/standard/runner/units.py | 30 ++++++++++++++++++- app/static/catalogue/catalogue.css | 2 ++ app/static/catalogue/tasks.js | 19 +++++++++++- app/templates/catalogue/tasks.html | 1 + app/tests/test_standard_units_listing.py | 38 ++++++++++++++++++++++-- app/ui_tests/test_task_set_pages.py | 14 +++++++++ app/web/catalogue.py | 16 +++++++++- docs/cli/pages.md | 1 + docs/cli/task-sets.md | 4 ++- 10 files changed, 143 insertions(+), 15 deletions(-) diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index e4acdeac0..b9a80e276 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -765,6 +765,7 @@ def cmd_merge(a): nullius standard set create humaneval "first ten" --dataset humaneval --units ten.txt --description "a quick look" nullius standard set create humaneval misses --from-job jobs_standard/JOB --outcome failed,infra nullius standard set create osworld1@044bc33 "chrome tabs" --dataset test_nogdrive --search tab --category domain=chrome + nullius standard set create gaia "twenty" --dataset gaia-validation --sample 20 --seed 7 nullius standard set show humaneval first-ten --json nullius standard set rename humaneval misses "misses of June" nullius standard set delete humaneval misses-of-june @@ -774,7 +775,7 @@ def cmd_merge(a): 0 done 1 unexpected error (a traceback: report it) 2 usage, or refused: a name not allowed, a list the set cannot hold, an import that conflicts, - an entry of the earlier format + an entry of the earlier format, a --sample larger than the list 3 not found: no such benchmark, set, file or job """ @@ -811,23 +812,33 @@ def cmd_set_create(a): if b is None: raise sets.NotFound(f"no benchmark {a.benchmark!r}") filtered = a.search is not None or bool(a.category) - if sum((a.units is not None, a.from_job is not None, filtered)) != 1: - raise sets.Refused("set create: --units FILE, --from-job JOB_DIR, or --search and --category") + listed = filtered or a.sample is not None + if a.seed is not None and a.sample is None: + raise sets.Refused("--seed draws --sample's tasks: give it with --sample") + if sum((a.units is not None, a.from_job is not None, listed)) != 1: + raise sets.Refused("set create: --units FILE, --from-job JOB_DIR, or --search, --category and --sample") if a.from_job is None and (a.outcome or a.unit): raise sets.Refused("--outcome and --unit choose a job's trials: give them with --from-job") + seed = None if a.units is not None: dataset = sets._dataset(b, a.dataset) got = {"dataset": dataset, "units": _listed_units(a.units), "note": f"from {os.path.basename(a.units)}"} - elif filtered: - # the ids the listing matches today, under the benchmark's default options; the note keeps the filter + elif listed: + # the ids the listing matches today, under the benchmark's default options, or --sample of them drawn at + # random; the note keeps the filter and the seed dataset = sets._dataset(b, a.dataset) chosen = unit_list.categories_of(a.category) found = unit_list.find(b, dataset, search=a.search or "", categories=chosen, size=None, licences=run.Licences(b, environ=os.environ)) if not found["total"]: raise sets.Refused(f"no task of {dataset} matches {unit_list.filter_text(a.search or '', chosen)}") - got = {"dataset": dataset, "units": [t["id"] for t in found["tasks"]], - "note": f"matched by {unit_list.filter_text(a.search or '', chosen)}"} + ids = [t["id"] for t in found["tasks"]] + if a.sample is not None: + ids, seed = unit_list.draw(ids, a.sample, a.seed) + note = unit_list.sample_note(a.sample, seed, a.search or "", chosen) + else: + note = f"matched by {unit_list.filter_text(a.search or '', chosen)}" + got = {"dataset": dataset, "units": ids, "note": note} else: got = sets.from_job(b, a.from_job, a.outcome, a.unit) if a.dataset and a.dataset != got["dataset"]: @@ -835,7 +846,8 @@ def cmd_set_create(a): entry = sets.create(b, a.label, dataset=got["dataset"], units=got["units"], description=a.description, note=got["note"]) print(f"wrote {sets.path_of(entry['benchmark'], entry['name'])}: {_named(entry)}, " f"{len(got['units'])} {b['units']['nouns'] if len(got['units']) != 1 else b['units']['noun']} of {entry['dataset']}" - + (f" at {sets.version_label(b, entry['version'])}" if entry.get("version") else "")) + + (f" at {sets.version_label(b, entry['version'])}" if entry.get("version") else "") + + (f", drawn with --seed {seed}" if seed is not None else "")) return 0 @@ -1160,6 +1172,11 @@ def main(argv=None): help="the tasks whose id, title or text hold each word (nullius standard units): those matched today") sc.add_argument("--category", action="append", metavar="FIELD=VALUE", help="the tasks of this category's value (repeatable: values of one field widen, fields narrow)") + sc.add_argument("--sample", type=int, metavar="N", + help="N of the listed tasks (of those --search and --category match) drawn at random") + sc.add_argument("--seed", type=int, metavar="S", + help="with --sample: the draw's seed; the same seed and listing give the same set " + "(default: one drawn, and shown)") sc.add_argument("--description", default="") sl = ss.add_parser("list", help="the task sets, of one benchmark or all", epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index fd54cf2b6..155e4cf06 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -23,15 +23,19 @@ category filter is FIELD=VALUE: values of one field widen the match (either), fields narrow it (both). Each field's values are counted over the tasks the search and the other fields' filters match, so a value chosen leaves its field's other values counted. + +A sample (``draw``) is N of the listed tasks, or of those a filter matches, at random: the same seed and the +same tasks give the same N, kept in the listing's order; without a seed one is drawn, and the set's note keeps it. """ from __future__ import annotations import hashlib import json import os +import random import shutil import tempfile -from typing import Dict, List, Optional +from typing import Dict, List, Optional, Tuple from nullius import ondisk, paths from nullius.standard.contract import definitions @@ -90,6 +94,30 @@ def filter_text(search: str = "", categories: Optional[Dict[str, List[str]]] = N return " ".join(words) +SEEDS = 1_000_000 # a seed drawn when none is given is below this + + +def draw(ids: List[str], n, seed=None) -> Tuple[List[str], int]: + """``n`` of ``ids`` at random, in their order, and the seed that drew them; one is drawn when ``seed`` is None. + More than ``ids`` holds, or a count or a seed that is not a whole number, is refused.""" + if isinstance(n, bool) or not isinstance(n, int) or n < 1: + raise Refused(f"--sample {n}: a whole number from 1") + if n > len(ids): + raise Refused(f"--sample {n}: the list holds {len(ids)}") + if seed is None: + seed = random.SystemRandom().randrange(SEEDS) + if isinstance(seed, bool) or not isinstance(seed, int) or seed < 0: + raise Refused(f"--seed {seed}: a whole number from 0") + picked = set(random.Random(seed).sample(range(len(ids)), n)) + return [u for i, u in enumerate(ids) if i in picked], seed + + +def sample_note(n: int, seed: int, search: str = "", categories: Optional[Dict[str, List[str]]] = None) -> str: + """A drawn set's note: ``drawn by --sample N --seed S``, after the filter it was drawn from.""" + words = filter_text(search, categories) + return (f"matched by {words}; " if words else "") + f"drawn by --sample {n} --seed {seed}" + + def _light(bench: dict) -> Optional[List[str]]: """The definition's ``driver.list_command``: a start that answers ``units`` and ``describe`` with the standard library and the dataset's files alone; None when it names none.""" diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index a11873624..253186771 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -457,6 +457,8 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .tasks-sel:has(.tasks-paste[open]) + .tasks-paste-box { display: flex; } .tasks-paste-box textarea { width: 100%; box-sizing: border-box; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; } .tasks-list { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 10px; } +.tasks-pick { display: inline-flex; align-items: center; gap: 6px; } +.tasks-pick input { flex: none; width: 4.5rem; height: 32px; padding: 0 .6rem; box-sizing: border-box; } .tasks-count { margin: 14px 0 6px; } .tasks-count:empty, .tasks-msg:empty { display: none; } .tasks-scroll { overflow-x: auto; } diff --git a/app/static/catalogue/tasks.js b/app/static/catalogue/tasks.js index 60cffa9a0..272104e8d 100644 --- a/app/static/catalogue/tasks.js +++ b/app/static/catalogue/tasks.js @@ -11,6 +11,9 @@ const chosen = new Set(JSON.parse(($('tasks-chosen-ids') || {}).textContent || '[]')); // opened from a set: its members first; Show all browses the dataset const st = {q: '', cats: {}, page: 1, showing: !!d.set && chosen.size > 0, ready: false, total: 0, pages: 1}; + // the last draw of Pick at random ({ids, seed, note}), while the chosen are the ones it drew + let drawn = null; + const picked = () => !!drawn && drawn.ids.size === chosen.size && [...chosen].every(id => drawn.ids.has(id)); const label = field => field.charAt(0).toUpperCase() + field.slice(1).replace(/_/g, ' '); const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c])); // the listing at the version the page shows (data-version, empty for the benchmark's default) @@ -106,6 +109,7 @@ facets(got.categories); const m = $('tasks-match'); if (m) { m.hidden = !writable || !got.total || st.showing; m.textContent = `Select the ${got.total.toLocaleString('en-US')} that match`; } + if ($('tasks-pick')) $('tasks-pick').hidden = !writable || !got.total || st.showing; if (st.showing) return showSelected(); draw(got.tasks); $('tasks-count').textContent = `${count(got.total)}` + (got.total !== got.of ? ` of ${got.of.toLocaleString('en-US')}` : '') @@ -118,7 +122,8 @@ try { got = await (await post(d.rows, {units: ids})).json(); } catch { /* the ids alone */ } 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` : ''); + $('tasks-count').textContent = `${count(ids.length)} chosen` + (unknown.size ? ` · ${unknown.size} not in the listing` : '') + + (picked() ? ` · picked at random with seed ${drawn.seed}` : ''); pager(); chosenLine(); } @@ -158,6 +163,17 @@ const got = await (await nulliusFetch(query({ids: 1}))).json(); if (got.ok && got.ready) { got.ids.forEach(id => chosen.add(id)); 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 + $('tasks-pick-go')?.addEventListener('click', async () => { + let got; + try { got = await (await nulliusFetch(query({ids: 1, sample: $('tasks-n').value.trim()}))).json(); } + catch { return window.nulliusNotify?.('The tasks could not be drawn. Reload the page.', {error: true}); } + if (!got.ok || !got.ready) return window.nulliusNotify?.(got.error || 'The list is not ready.', {error: true}); + chosen.clear(); got.ids.forEach(id => chosen.add(id)); + drawn = {ids: new Set(got.ids), seed: got.seed, note: got.note}; + setShowing(true); load(); + }); $('tasks-clear')?.addEventListener('click', () => { chosen.clear(); 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('#')))]; @@ -171,6 +187,7 @@ async function save(body) { if (!chosen.size) return msg('Tick at least one task.', true); let got; + if (picked()) body = {...body, note: drawn.note}; try { got = await (await post(d.save, {...body, units: [...chosen]})).json(); } catch { return msg('Not saved: the server did not answer.', true); } if (!got.ok) return msg(got.error, true); location.href = got.open; diff --git a/app/templates/catalogue/tasks.html b/app/templates/catalogue/tasks.html index e0f185bc2..208a85380 100644 --- a/app/templates/catalogue/tasks.html +++ b/app/templates/catalogue/tasks.html @@ -71,6 +71,7 @@
0 chosen + {% if writable %}{% endif %}
Paste ids
diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index d5032c23f..9510b60e7 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -5,9 +5,9 @@ listing gives and the filter in its note; OSWorld1's ``describe`` from its task files. A definition's ``driver.list_command`` listing with no driver environment, OSWorld1's giving the driver's ids in its order; ``state`` giving each of its answers and starting nothing; the command's one line before a first listing that -fetches; a licence the driver needs, given to it as a run gives it, and refused first when none is held. No -key, no network: each driver is a script of the test's own, the fake benchmark's or OSWorld1's on task files of -the test's own.""" +fetches; a licence the driver needs, given to it as a run gives it, and refused first when none is held; +``--sample`` drawing N of the listed tasks by a seed. No key, no network: each driver is a script of the test's +own, the fake benchmark's or OSWorld1's on task files of the test's own.""" from __future__ import annotations import contextlib @@ -276,6 +276,38 @@ def test_the_ids_stored_are_the_ones_the_listing_gives_and_the_note_holds_the_fi self.assertEqual(code, 0, err) self.assertEqual(len(sets.revision(sets.load("described", "by-kind"))["units"]), 83) + def test_a_sample_is_n_of_the_listed_tasks_the_same_for_the_same_seed_and_its_seed_in_the_note(self): + listed = self.ids(units.find(self.b, "all", size=None)) + for name in ("one", "two"): + code, out, err = self.cli("set", "create", "described", name, "--dataset", "all", "--sample", "5", "--seed", "7") + self.assertEqual(code, 0, err) + one, two = (sets.revision(sets.load("described", n)) for n in ("one", "two")) + self.assertEqual(one["units"], two["units"]) + self.assertEqual(len(one["units"]), 5) + self.assertEqual(one["units"], [u for u in listed if u in one["units"]]) # in the listing's order + self.assertEqual(one["note"], "drawn by --sample 5 --seed 7") + self.assertIn("drawn with --seed 7", out) + # of the tasks a filter matches; with no seed, one is drawn, shown and kept + code, out, err = self.cli("set", "create", "described", "gammas", "--dataset", "all", "--category", "kind=gamma", + "--sample", "3") + self.assertEqual(code, 0, err) + got = sets.revision(sets.load("described", "gammas")) + seed = int(out.rsplit("--seed ", 1)[1]) + self.assertEqual(got["note"], f"matched by --category kind=gamma; drawn by --sample 3 --seed {seed}") + gammas = self.ids(units.find(self.b, "all", categories={"kind": ["gamma"]}, size=None)) + self.assertEqual(got["units"], units.draw(gammas, 3, seed)[0]) + self.assertTrue(set(got["units"]) <= set(gammas)) + for args, said in ((["--sample", "251"], "refused: --sample 251: the list holds 250\n"), + (["--sample", "0"], "refused: --sample 0: a whole number from 1\n"), + (["--seed", "3"], "refused: --seed draws --sample's tasks: give it with --sample\n"), + (["--sample", "2", "--units", os.path.join(self.tmp, "x.txt")], None)): + with self.subTest(args=args): + code, out, err = self.cli("set", "create", "described", "too-many", "--dataset", "all", *args) + self.assertEqual((code, out), (2, "")) + self.assertEqual(err, said or "refused: set create: --units FILE, --from-job JOB_DIR, or --search, " + "--category and --sample\n") + self.assertEqual(sorted(e["name"] for e in sets.entries("described")[0]), ["gammas", "one", "two"]) + def test_a_filter_that_matches_nothing_or_beside_another_source_is_refused(self): for args, said in ((["--search", "wombat"], "no task of all matches --search \"wombat\""), (["--search", "t1", "--units", os.path.join(self.tmp, "x.txt")], "--units FILE, --from-job"), diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index 71edb8004..abc598575 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -194,6 +194,20 @@ 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_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"]] + got = self.listing(ids=1, sample=5, seed=7, cat=["kind=alpha"]) + self.assertEqual((got["ids"], got["seed"]), (units.draw(alpha, 5, 7)[0], 7)) + self.assertEqual(got["note"], "matched by --category kind=alpha; drawn by --sample 5 --seed 7") + drawn = self.listing(ids=1, sample=5) # no seed: one drawn, and given + self.assertEqual(drawn["ids"], units.draw([f"t{i:03d}" for i in range(250)], 5, drawn["seed"])[0]) + for sample, said in (("251", "--sample 251: the list holds 250"), ("x", "--sample x: a whole number from 1")): + r = self.client.get(f"/benchmarks/described/tasks/all/listing?ids=1&sample={sample}"); self.addCleanup(r.close) + self.assertEqual((r.status_code, r.get_json()["error"]), (400, said)) + self.post("/benchmarks/described/tasks/all/save", {"name": "five", "units": got["ids"], "note": got["note"]}) + self.assertEqual(sets.revision(sets.load("described", "five"))["note"], got["note"]) + def test_an_unknown_category_is_refused_plainly(self): units.listing(self.b, "all") r = self.client.get("/benchmarks/described/tasks/all/listing?cat=colour=red"); self.addCleanup(r.close) diff --git a/app/web/catalogue.py b/app/web/catalogue.py index c0dfb5b30..e953aab47 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -221,7 +221,14 @@ def benchmark_tasks_listing(key, dataset): 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) - return jsonify(ok=True, ready=True, total=got["total"], ids=[t["id"] for t in got["tasks"]]) + 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) + # Pick N at random: N of the matches, drawn as set create --sample draws them, its seed in the note + n, seed = (_whole(request.args.get(k)) for k in ("sample", "seed")) + ids, seed = units.draw(ids, n, seed) + return jsonify(ok=True, ready=True, total=got["total"], ids=ids, seed=seed, + note=units.sample_note(n, seed, request.args.get("q", ""), cats)) got = units.find(bench, dataset, search=request.args.get("q", ""), categories=cats, page=int(page) if page.isdigit() and int(page) >= 1 else 1) except units.Refused as e: @@ -229,6 +236,13 @@ def benchmark_tasks_listing(key, dataset): return jsonify(ok=True, ready=True, **got) +def _whole(word): + """A number the page sent as a whole number, else the text itself, for ``units.draw`` to refuse; None for none.""" + if word is None or word == "": + return None + return int(word) if word.isdigit() else word + + @app.route("/benchmarks//tasks//prepare", methods=["POST"]) def benchmark_tasks_prepare(key, dataset): """Make a listing, out of this request: it fetches what the state named, then starts the light listing diff --git a/docs/cli/pages.md b/docs/cli/pages.md index f0b77c015..47be55457 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -20,6 +20,7 @@ Each page's command, or why there is none. | A benchmark's *Task sets* | `nullius standard set list KEY` ([Task sets](task-sets.md)) | | `/benchmarks//tasks/` | `nullius standard units KEY --dataset D`; a set's, `set show KEY NAME` | | Its *List tasks* (*List questions*) | `nullius standard units KEY --dataset D`, which makes the listing | +| Its *Pick at random* | `nullius standard set create KEY NAME --dataset D --sample N [--seed S]` | | Save, rename or delete a task set | `nullius standard set create`, `--from-job` for a job's; `set rename`, `set delete` | | A benchmark's *Prove it* | `nullius standard prove KEY` ([Prove](prove.md)) | | *Prove its ports* | `nullius standard conform KEY` ([Conform](conform.md)) | diff --git a/docs/cli/task-sets.md b/docs/cli/task-sets.md index 2c8e9c2b0..62c85e730 100644 --- a/docs/cli/task-sets.md +++ b/docs/cli/task-sets.md @@ -5,7 +5,7 @@ A named list of one dataset's units, frozen once made, that a run names and its ```bash title="Commands" nullius standard units --dataset D [--bench-option NAME=VALUE]... [--search TEXT] [--category FIELD=VALUE]... [--json] nullius standard set create [@version] "WORDS" [--dataset D] (--units FILE | --search TEXT | --category FIELD=VALUE... \ - | --from-job JOB_DIR [--outcome O,...]... [--unit ID]...) [--description TEXT] + | --sample N [--seed S] | --from-job JOB_DIR [--outcome O,...]... [--unit ID]...) [--description TEXT] nullius standard set list [] [--json] nullius standard set show NAME [--json] nullius standard set rename NAME "WORDS" @@ -18,6 +18,7 @@ nullius standard run --set NAME ... nullius standard units osworld1 --dataset test_nogdrive --search tab --category domain=chrome nullius standard set create humaneval "first ten" --dataset humaneval --units ten.txt nullius standard set create humaneval misses --from-job jobs_standard/JOB --outcome failed,infra +nullius standard set create gaia twenty --dataset gaia-validation --sample 20 --seed 7 nullius standard run humaneval reference --model gpt-5-mini --set first-ten --unsandboxed ``` @@ -27,6 +28,7 @@ nullius standard run humaneval reference --model gpt-5-mini --set first-ten --un | A listing | Prepares the upstream, the dataset and, without `driver.list_command`, the driver's environment; starts no unit. | | Its licences | The driver gets its `to: driver` secrets, as a run's; one not set is refused first. | | `--search`, `--category` | Every word in the id, title or text; one field's values widen, two fields narrow. | +| `--sample N` | N of the listed or matched tasks at random; `--seed S` repeats a draw, and the note keeps it. | | The entry | `sets//NAME.json` in the user catalogue, a plain file to copy or keep. | | Frozen | No command changes a set's list; `rename` changes its label; jobs find it by id. | | Its name | Up to 80 characters with a letter or a digit; commands take its slug. | From f0a78a860f187313e0f92ae0beb53c4b85fc14c9 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:20:49 +0100 Subject: [PATCH 19/37] fix(catalogue): no rule above the chosen tasks while the search is hidden With no list yet the search is hidden, and the row of chosen tasks kept the rule and the space that part it from the search: an empty band at the top of the section. --- app/static/catalogue/catalogue.css | 1 + 1 file changed, 1 insertion(+) diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 253186771..ebdc187a6 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -450,6 +450,7 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .filter-pill[aria-pressed="true"] .tasks-n { color: inherit; opacity: .8; } .tasks-sel { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border-soft); } .tasks-sel b { margin-right: 6px; } +.tasks-bar[hidden] + .tasks-sel { margin-top: 0; padding-top: 0; border-top: 0; } .tasks-paste > summary { list-style: none; } .tasks-paste > summary::-webkit-details-marker { display: none; } /* the box opens on its own line below the row of the chosen tasks' controls */ From cb9ccc983fd86d71bedd0f56f3d554f23a1dbc56 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:22:13 +0100 Subject: [PATCH 20/37] test(standard): keep a listing test's token value out of the key pattern The judge's key-shaped pattern reads a token variable set to sixteen or more characters as a key: the test's made-up value is now shorter. --- app/tests/test_standard_units_listing.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 9510b60e7..358ecbd9b 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -342,9 +342,9 @@ def test_the_driver_gets_its_licence_and_none_held_is_refused_before_it_starts(s with self.assertRaisesRegex(units.Refused, "needs a Hugging Face token"): units.listing(self.b, "all") # held, from the provider's variable as a headless run takes it, or from the store: the driver gets it - with mock.patch.dict(os.environ, dict(env, HF_TOKEN="from-the-environment"), clear=True): + with mock.patch.dict(os.environ, dict(env, HF_TOKEN="from-env"), clear=True): code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") - self.assertEqual((code, out.splitlines()[0], self.given()), (0, "1 of 250 tasks of all", "from-the-environment")) + self.assertEqual((code, out.splitlines()[0], self.given()), (0, "1 of 250 tasks of all", "from-env")) units.listing(dict(self.b, options={}), "all", licences={"HF_TOKEN": {"kind": "value", "value": "from-the-store"}}) self.assertEqual(self.given(), "from-the-store") From 5f1201a00e18c2e87d6523f41838cf1cf71a3864 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:01:26 +0100 Subject: [PATCH 21/37] fix(standard): redact task listing driver secrets --- app/nullius/standard/runner/units.py | 61 +++++++++++++++++++++++- app/tests/test_standard_units_listing.py | 50 +++++++++++++++++++ app/ui_tests/test_task_set_pages.py | 26 +++++++++- docs/cli/task-sets.md | 1 + 4 files changed, 135 insertions(+), 3 deletions(-) diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index 155e4cf06..7c0248813 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -34,10 +34,13 @@ import os import random import shutil +import subprocess import tempfile +import threading from typing import Dict, List, Optional, Tuple from nullius import ondisk, paths +from nullius.redact import redact from nullius.standard.contract import definitions from nullius.standard.protocols import jsonl from nullius.standard.requirements import install @@ -182,6 +185,58 @@ def missing_text(needs: List[dict]) -> str: for n in needs) +class _ListingProc(jsonl.Proc): + """A listing's driver with its supplied secrets removed before output is kept.""" + + def __init__(self, cmd, cwd, env, log, credentials): + super().__init__(cmd, cwd, env, log) + self.secrets = sorted(set(credentials.values()) - {""}, key=len, reverse=True) + + def _clean(self, value): + if isinstance(value, dict): + return {self._clean(k): self._clean(v) for k, v in value.items()} + if isinstance(value, list): + return [self._clean(v) for v in value] + if isinstance(value, str): + for secret in self.secrets: + value = value.replace(secret, "[REDACTED]") + return redact(value) + return value + + def start(self): + self.err = open(self.log, "a") + try: + self.p = subprocess.Popen(self.cmd, cwd=self.cwd, env=self.env, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, + start_new_session=True) + except OSError: + self.err.close() + raise + self._stderr = threading.Thread(target=self._log, daemon=True) + self._stderr.start() + threading.Thread(target=self._read, daemon=True).start() + return self + + def _log(self): + with self.p.stderr, open(self.log, "a") as out: + for line in self.p.stderr: + out.write(self._clean(line)) + out.flush() + + def _read(self): + for line in self.p.stdout: + try: + line = json.dumps(self._clean(json.loads(line))) + except ValueError: + line = self._clean(line) + self.lines.put(line) + self.lines.put(None) + + def close(self): + super().close() + self._stderr.join() + + def _start(bench: dict, ds: dict, values: dict, work: str, licences=None) -> jsonl.Proc: light = _light(bench) try: @@ -193,13 +248,15 @@ def _start(bench: dict, ds: dict, values: dict, work: str, licences=None) -> jso home, cwd = os.path.join(work, "driver-home"), os.path.join(work, "driver") os.makedirs(home) os.makedirs(cwd) - env = run.base_env(home, {**extra, **run.driver_secrets(bench, _held(bench, licences)), + credentials = run.driver_secrets(bench, _held(bench, licences)) + env = run.base_env(home, {**extra, **credentials, "NULLIUS_UPSTREAM": up or "", "NULLIUS_DATASET": data or "", "NULLIUS_DATASET_ID": ds["id"], "PYTHONPATH": run.driver_path(), "PYTHONDONTWRITEBYTECODE": "1", "NULLIUS_VERSION": str(bench.get("_version") or ""), **run.option_env(values)}) try: - return jsonl.Proc(cmd, cwd, env, os.path.join(work, "driver.log")).start() + args = (cmd, cwd, env, os.path.join(work, "driver.log")) + return (_ListingProc(*args, credentials) if credentials else jsonl.Proc(*args)).start() except OSError as e: raise Refused(f"cannot start {bench['key']}'s driver for its listing: {e}") diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 358ecbd9b..63713c0c5 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -56,6 +56,12 @@ def about(i): print(json.dumps(out), flush=True) ''' MODE = {"mode": {"summary": "how many tasks the listing gives", "values": ["long", "short"], "default": "long"}} +REJECTING_DRIVER = r'''import json, os, sys +for line in sys.stdin: + message = 'Authentication failed for ' + os.environ['HF_TOKEN'] + os.environ.get('EXTRA_TOKEN', '') + print(message, file=sys.stderr, flush=True) + print(json.dumps({'error': message}), flush=True) +''' class Scratch(unittest.TestCase): @@ -327,6 +333,50 @@ def gated(bench: dict) -> dict: class Licences(Scratch): + def test_driver_secrets_are_absent_from_files_and_command_output(self): + self.b = gated(self.b) + self.b["environments"]["data"]["needs_secrets"].append({"name": "EXTRA_TOKEN", "to": "driver"}) + Path(self.b["_here"], "driver.py").write_text(REJECTING_DRIVER) + extra = "another-made-up-credential" + for token in ("made-up-listing-credential", "tiny"): + with self.subTest(token=token): + files = [] + remove = shutil.rmtree + + def capture(path, **kwargs): + files.extend(p.read_bytes() for p in Path(self.tmp).rglob("*") if p.is_file()) + remove(path, **kwargs) + + with mock.patch.object(units.run, "Licences", return_value={ + "HF_TOKEN": {"kind": "value", "value": token}, + "EXTRA_TOKEN": {"kind": "value", "value": extra}}), \ + mock.patch.object(units.shutil, "rmtree", capture): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual((code, out), (2, "")) + self.assertTrue(files) + for content in (out.encode(), err.encode(), *files): + with self.subTest(content=content): + self.assertNotIn(token.encode(), content) + self.assertNotIn(extra.encode(), content) + self.assertIn("Authentication failed for [REDACTED]", err) + self.assertIn(b"Authentication failed for [REDACTED][REDACTED]\n", files) + + def test_a_secret_in_a_successful_reply_is_redacted_before_caching(self): + self.b = gated(self.b) + self.b["driver"]["describe"] = False + Path(self.b["_here"], "driver.py").write_text( + REJECTING_DRIVER.replace("{'error': message}", "{'units': [message]}")) + token = 'made-up-quoted-"credential' + with mock.patch.dict(os.environ, {"HF_TOKEN": token}): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual(code, 0, err) + self.assertIn("Authentication failed for [REDACTED]", out) + cached = units.listing(self.b, "all") + self.assertEqual(cached["tasks"][0]["id"], "Authentication failed for [REDACTED]") + for content in (out, err, *(p.read_text() for p in Path(self.tmp).rglob("*") if p.is_file())): + self.assertNotIn(token, content) + self.assertNotIn(json.dumps(token)[1:-1], content) + def given(self): path = Path(self.b["_here"], "given") return path.read_text() if path.exists() else None diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index abc598575..a93e900ac 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -26,7 +26,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 +from tests.test_standard_units_listing import DRIVER, 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") @@ -294,6 +294,30 @@ class AFirstListing(Case): fetches said; full, never started, with what it needs said; refused, why. No request starts a fetch or an install inside itself.""" + def test_preparation_keeps_and_shows_no_driver_secret(self): + from web import catalogue + self.b = gated(self.b) + Path(self.b["_here"], "driver.py").write_text(REJECTING_DRIVER) + token = "made-up-page-credential" + self.stack.enter_context(patch.object(units.run, "Licences", return_value={ + "HF_TOKEN": {"kind": "value", "value": token}})) + self.stack.enter_context(patch.dict(catalogue._PREPARING, {}, clear=True)) + + def join(): + for job in catalogue._PREPARING.values(): + job["thread"].join(5) + self.assertFalse(job["thread"].is_alive()) + + self.addCleanup(join) + first = self.post("/benchmarks/described/tasks/all/prepare", {}) + join() + 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) + self.assertIn("Authentication failed for [REDACTED]", record["error"]) + self.assertEqual(shown["error"], record["error"]) + def test_preparation_errors_belong_to_the_resolved_version(self): from web import catalogue versions = {v: dict(self.b, _version=v, _ref=f"described@{v}") for v in ("1", "2")} diff --git a/docs/cli/task-sets.md b/docs/cli/task-sets.md index 62c85e730..6c2f8ef7f 100644 --- a/docs/cli/task-sets.md +++ b/docs/cli/task-sets.md @@ -27,6 +27,7 @@ nullius standard run humaneval reference --model gpt-5-mini --set first-ten --un | `units` | Each task's id, title, text and categories; ids alone when the driver has no `describe`. | | A listing | Prepares the upstream, the dataset and, without `driver.list_command`, the driver's environment; starts no unit. | | Its licences | The driver gets its `to: driver` secrets, as a run's; one not set is refused first. | +| Driver output | Supplied secrets are redacted before a listing is stored or its logs and errors are kept or shown. | | `--search`, `--category` | Every word in the id, title or text; one field's values widen, two fields narrow. | | `--sample N` | N of the listed or matched tasks at random; `--seed S` repeats a draw, and the note keeps it. | | The entry | `sets//NAME.json` in the user catalogue, a plain file to copy or keep. | From 87d66efff481ba9cbed752914c560608e085cc8b Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:01:26 +0100 Subject: [PATCH 22/37] test(standard): pin task samples for two seeds --- app/tests/test_standard_units_listing.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 63713c0c5..c1b5fc0c0 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -284,15 +284,18 @@ def test_the_ids_stored_are_the_ones_the_listing_gives_and_the_note_holds_the_fi def test_a_sample_is_n_of_the_listed_tasks_the_same_for_the_same_seed_and_its_seed_in_the_note(self): listed = self.ids(units.find(self.b, "all", size=None)) - for name in ("one", "two"): - code, out, err = self.cli("set", "create", "described", name, "--dataset", "all", "--sample", "5", "--seed", "7") + for name, seed in (("one", "7"), ("two", "7"), ("three", "8")): + code, out, err = self.cli("set", "create", "described", name, "--dataset", "all", "--sample", "5", "--seed", seed) self.assertEqual(code, 0, err) - one, two = (sets.revision(sets.load("described", n)) for n in ("one", "two")) + one, two, three = (sets.revision(sets.load("described", n)) for n in ("one", "two", "three")) self.assertEqual(one["units"], two["units"]) + self.assertEqual(one["units"], ["t038", "t082", "t101", "t166", "t242"]) + self.assertEqual(three["units"], ["t032", "t058", "t094", "t096", "t246"]) + self.assertNotEqual(one["units"], three["units"]) self.assertEqual(len(one["units"]), 5) self.assertEqual(one["units"], [u for u in listed if u in one["units"]]) # in the listing's order self.assertEqual(one["note"], "drawn by --sample 5 --seed 7") - self.assertIn("drawn with --seed 7", out) + self.assertIn("drawn with --seed 8", out) # of the tasks a filter matches; with no seed, one is drawn, shown and kept code, out, err = self.cli("set", "create", "described", "gammas", "--dataset", "all", "--category", "kind=gamma", "--sample", "3") @@ -312,7 +315,7 @@ def test_a_sample_is_n_of_the_listed_tasks_the_same_for_the_same_seed_and_its_se self.assertEqual((code, out), (2, "")) self.assertEqual(err, said or "refused: set create: --units FILE, --from-job JOB_DIR, or --search, " "--category and --sample\n") - self.assertEqual(sorted(e["name"] for e in sets.entries("described")[0]), ["gammas", "one", "two"]) + self.assertEqual(sorted(e["name"] for e in sets.entries("described")[0]), ["gammas", "one", "three", "two"]) def test_a_filter_that_matches_nothing_or_beside_another_source_is_refused(self): for args, said in ((["--search", "wombat"], "no task of all matches --search \"wombat\""), From 0d37e997e7f3e7a244fa553f1262f0825f978e7e Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:01:26 +0100 Subject: [PATCH 23/37] fix(web): refuse invalid task sample numbers --- app/ui_tests/test_task_set_pages.py | 12 ++++++++++++ app/web/catalogue.py | 5 ++++- docs/cli/task-sets.md | 1 + 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index a93e900ac..3a9a9625e 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -208,6 +208,18 @@ def test_pick_at_random_draws_as_set_create_sample_does_and_the_set_keeps_its_se self.post("/benchmarks/described/tasks/all/save", {"name": "five", "units": got["ids"], "note": got["note"]}) self.assertEqual(sets.revision(sets.load("described", "five"))["note"], got["note"]) + def test_invalid_sample_and_seed_numbers_are_refused(self): + units.listing(self.b, "all") + for field, minimum in (("sample", 1), ("seed", 0)): + for word in ("²", "9" * 4301): + with self.subTest(field=field, length=len(word)): + query = {"ids": "1", "sample": "2", "seed": "7", field: word} + r = self.client.get("/benchmarks/described/tasks/all/listing", query_string=query) + self.addCleanup(r.close) + self.assertEqual(r.status_code, 400) + self.assertEqual(r.get_json(), {"ok": False, + "error": f"--{field} {word}: a whole number from {minimum}"}) + def test_an_unknown_category_is_refused_plainly(self): units.listing(self.b, "all") r = self.client.get("/benchmarks/described/tasks/all/listing?cat=colour=red"); self.addCleanup(r.close) diff --git a/app/web/catalogue.py b/app/web/catalogue.py index e953aab47..b4f2f440d 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -240,7 +240,10 @@ def _whole(word): """A number the page sent as a whole number, else the text itself, for ``units.draw`` to refuse; None for none.""" if word is None or word == "": return None - return int(word) if word.isdigit() else word + try: + return int(word) if word.isdigit() else word + except ValueError: + return word @app.route("/benchmarks//tasks//prepare", methods=["POST"]) diff --git a/docs/cli/task-sets.md b/docs/cli/task-sets.md index 6c2f8ef7f..66638ee5a 100644 --- a/docs/cli/task-sets.md +++ b/docs/cli/task-sets.md @@ -30,6 +30,7 @@ nullius standard run humaneval reference --model gpt-5-mini --set first-ten --un | Driver output | Supplied secrets are redacted before a listing is stored or its logs and errors are kept or shown. | | `--search`, `--category` | Every word in the id, title or text; one field's values widen, two fields narrow. | | `--sample N` | N of the listed or matched tasks at random; `--seed S` repeats a draw, and the note keeps it. | +| Draw inputs | Invalid counts and seeds receive a refusal on the page and command. | | The entry | `sets//NAME.json` in the user catalogue, a plain file to copy or keep. | | Frozen | No command changes a set's list; `rename` changes its label; jobs find it by id. | | Its name | Up to 80 characters with a letter or a digit; commands take its slug. | From b6789d77948b957bfefb835a5751304b1e3cb8da Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:03:10 +0100 Subject: [PATCH 24/37] fix(standard): read a listing driver's stderr whatever its bytes The reader that redacts a listing driver's stderr decoded it strictly: one byte that is not UTF-8 ended the reader, and the log and the error lost every later line. Such a byte is now replaced. The error's last line is read once the reader has written it, and a child of the driver that keeps stderr open holds the listing for three seconds at most. --- app/nullius/standard/runner/units.py | 10 +++++++--- app/tests/test_standard_units_listing.py | 9 +++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index 7c0248813..c12358701 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -207,8 +207,8 @@ def start(self): self.err = open(self.log, "a") try: self.p = subprocess.Popen(self.cmd, cwd=self.cwd, env=self.env, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, - start_new_session=True) + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace", + bufsize=1, start_new_session=True) except OSError: self.err.close() raise @@ -232,9 +232,13 @@ def _read(self): self.lines.put(line) self.lines.put(None) + def _tail(self): + self._stderr.join(3) # the driver's last lines written to the log first + return super()._tail() + def close(self): super().close() - self._stderr.join() + self._stderr.join(3) # a child of the driver may still hold its stderr def _start(bench: dict, ds: dict, values: dict, work: str, licences=None) -> jsonl.Proc: diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index c1b5fc0c0..de4fd995b 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -380,6 +380,15 @@ def test_a_secret_in_a_successful_reply_is_redacted_before_caching(self): self.assertNotIn(token, content) self.assertNotIn(json.dumps(token)[1:-1], content) + def test_a_driver_that_ends_says_why_whatever_the_bytes_of_its_stderr(self): + self.b = gated(self.b) + Path(self.b["_here"], "driver.py").write_text("import os, sys\nsys.stdin.readline()\n" + "sys.stderr.buffer.write(b'\\xff failed for ' + os.environ['HF_TOKEN'].encode() + b'\\n')\n") + with mock.patch.dict(os.environ, {"HF_TOKEN": "made-up-bytes"}): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual((code, out), (2, "")) + self.assertIn("ended without replying (\ufffd failed for [REDACTED])\n", err) + def given(self): path = Path(self.b["_here"], "given") return path.read_text() if path.exists() else None From f459767174ce0b7f5464e896bfcb695e960952c2 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:03:28 +0100 Subject: [PATCH 25/37] fix(standard): redact a listing driver's secret as JSON or a URL holds it A secret with a quote, a backslash or a character outside ASCII is escaped inside a JSON string, and one with a slash, a plus or a space is encoded inside a URL. The listing replaced the value as given alone and missed both in the driver's log and its error. Those forms are now replaced too. --- app/nullius/standard/runner/units.py | 6 +++++- app/tests/test_standard_units_listing.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index c12358701..a39a4c315 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -38,6 +38,7 @@ import tempfile import threading from typing import Dict, List, Optional, Tuple +from urllib.parse import quote, quote_plus from nullius import ondisk, paths from nullius.redact import redact @@ -190,7 +191,10 @@ class _ListingProc(jsonl.Proc): def __init__(self, cmd, cwd, env, log, credentials): super().__init__(cmd, cwd, env, log) - self.secrets = sorted(set(credentials.values()) - {""}, key=len, reverse=True) + # each value as it is, as a JSON string holds it and as a URL holds it + forms = {f for v in credentials.values() if v for f in (v, json.dumps(v)[1:-1], + json.dumps(v, ensure_ascii=False)[1:-1], quote(v, safe=""), quote_plus(v))} + self.secrets = sorted(forms, key=len, reverse=True) def _clean(self, value): if isinstance(value, dict): diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index de4fd995b..05b7d0fe4 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -389,6 +389,16 @@ def test_a_driver_that_ends_says_why_whatever_the_bytes_of_its_stderr(self): self.assertEqual((code, out), (2, "")) self.assertIn("ended without replying (\ufffd failed for [REDACTED])\n", err) + def test_a_secret_is_redacted_as_a_json_string_or_a_url_holds_it(self): + self.b = gated(self.b) + Path(self.b["_here"], "driver.py").write_text("import json, os, sys, urllib.parse as u\nsys.stdin.readline()\n" + "t = os.environ['HF_TOKEN']\n" + "print(json.dumps([t]), json.dumps([t], ensure_ascii=False), u.quote(t, safe=''), u.quote_plus(t), file=sys.stderr)\n") + with mock.patch.dict(os.environ, {"HF_TOKEN": 'made/up "key" \u00e9+1'}): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual((code, out), (2, "")) + self.assertIn('(["[REDACTED]"] ["[REDACTED]"] [REDACTED] [REDACTED])\n', err) + def given(self): path = Path(self.b["_here"], "given") return path.read_text() if path.exists() else None From 138c814a4fed84fdb149189282985733397cb464 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:04:01 +0100 Subject: [PATCH 26/37] fix(standard): keep a listing's task texts whole beside its driver's secrets The listing passed every string of the driver's replies through the credential patterns as well as through its secrets' values: a question that names a torch bearer or a password lost words in its title and text. The patterns now read the driver's log and an error alone; tasks' ids, titles and texts lose only a secret's value. --- app/nullius/standard/runner/units.py | 10 ++++++---- app/tests/test_standard_units_listing.py | 7 +++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index a39a4c315..3f71f0204 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -204,7 +204,6 @@ def _clean(self, value): if isinstance(value, str): for secret in self.secrets: value = value.replace(secret, "[REDACTED]") - return redact(value) return value def start(self): @@ -224,15 +223,18 @@ def start(self): def _log(self): with self.p.stderr, open(self.log, "a") as out: for line in self.p.stderr: - out.write(self._clean(line)) + out.write(redact(self._clean(line))) out.flush() def _read(self): for line in self.p.stdout: try: - line = json.dumps(self._clean(json.loads(line))) + reply = self._clean(json.loads(line)) + if isinstance(reply, dict) and isinstance(reply.get("error"), str): + reply["error"] = redact(reply["error"]) # an error is shown; tasks' texts are kept whole + line = json.dumps(reply) except ValueError: - line = self._clean(line) + line = redact(self._clean(line)) self.lines.put(line) self.lines.put(None) diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 05b7d0fe4..73aa232e8 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -399,6 +399,13 @@ def test_a_secret_is_redacted_as_a_json_string_or_a_url_holds_it(self): self.assertEqual((code, out), (2, "")) self.assertIn('(["[REDACTED]"] ["[REDACTED]"] [REDACTED] [REDACTED])\n', err) + def test_a_listing_with_a_secret_keeps_its_tasks_texts_whole(self): + self.b = gated(self.b) + said = "Ask the bearer Kristiansen for the password: quokka-folder" + Path(self.b["_here"], "driver.py").write_text(DRIVER.replace("Rename the folder called Quokka", said)) + with mock.patch.object(units.run, "Licences", return_value={"HF_TOKEN": {"kind": "value", "value": "made-up"}}): + self.assertEqual(units.find(self.b, "all", search="t011")["tasks"][0]["text"], said) + def given(self): path = Path(self.b["_here"], "given") return path.read_text() if path.exists() else None From b87332a507e70efe866f3ffa97f90f5af16f6050 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:04:12 +0100 Subject: [PATCH 27/37] test(web): keep the page test's token value out of the key pattern The judge's key-shaped pattern reads a token variable set to sixteen or more characters as a key: the made-up value of the test of a listing's preparation is now shorter. --- app/ui_tests/test_task_set_pages.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index 3a9a9625e..9fcee8665 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -310,7 +310,7 @@ def test_preparation_keeps_and_shows_no_driver_secret(self): from web import catalogue self.b = gated(self.b) Path(self.b["_here"], "driver.py").write_text(REJECTING_DRIVER) - token = "made-up-page-credential" + token = "page-credential" self.stack.enter_context(patch.object(units.run, "Licences", return_value={ "HF_TOKEN": {"kind": "value", "value": token}})) self.stack.enter_context(patch.dict(catalogue._PREPARING, {}, clear=True)) From 71cdd910c28ff4244122c3a12e3b544c8b536ccc Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:04:17 +0100 Subject: [PATCH 28/37] docs(docs): drop the row on refused draw numbers The docs keep no validations: a count or a seed that is not a whole number is refused, and the refusal says so itself. --- docs/cli/task-sets.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/cli/task-sets.md b/docs/cli/task-sets.md index 66638ee5a..6c2f8ef7f 100644 --- a/docs/cli/task-sets.md +++ b/docs/cli/task-sets.md @@ -30,7 +30,6 @@ nullius standard run humaneval reference --model gpt-5-mini --set first-ten --un | Driver output | Supplied secrets are redacted before a listing is stored or its logs and errors are kept or shown. | | `--search`, `--category` | Every word in the id, title or text; one field's values widen, two fields narrow. | | `--sample N` | N of the listed or matched tasks at random; `--seed S` repeats a draw, and the note keeps it. | -| Draw inputs | Invalid counts and seeds receive a refusal on the page and command. | | The entry | `sets//NAME.json` in the user catalogue, a plain file to copy or keep. | | Frozen | No command changes a set's list; `rename` changes its label; jobs find it by id. | | Its name | Up to 80 characters with a letter or a digit; commands take its slug. | From a21647e20f48d806e09be5366260a9185d2ebf65 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:37:02 +0100 Subject: [PATCH 29/37] fix(runs): give Save as task set's fields the height of its button In the job page's Save as task set form, the shared text input grew to 48 px in its column of a label and a field, under a 34 px button. The fields now take the button's height, as the tasks page's save form does. --- app/static/style.css | 1 + 1 file changed, 1 insertion(+) diff --git a/app/static/style.css b/app/static/style.css index a0d8a442a..33414d886 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -366,6 +366,7 @@ tr.tone-good .jbar .fill { background: #4cc26a; } tr.tone-warn .jbar .fill { bac .run-saveset-form { position: absolute; right: 0; top: calc(100% + 6px); z-index: 20; display: flex; flex-direction: column; gap: 10px; width: min(300px, calc(100vw - 32px)); padding: 14px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); box-shadow: 0 8px 24px rgba(0, 0, 0, .12); } .run-saveset-form label { display: flex; flex-direction: column; gap: 5px; } .run-saveset-form .btn { align-self: flex-start; } +.run-saveset-form input[type=text] { flex: none; height: 34px; box-sizing: border-box; } @media (max-width: 640px) { .run-saveset-form { position: static; margin-top: 8px; box-shadow: none; } } .bar { From d791d1bf323886f4dbbfc0628c401b76ab798ecd Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 13:37:59 +0100 Subject: [PATCH 30/37] fix(catalogue): hide the tasks list's category block while it is empty A dataset whose driver gives ids alone has no category to filter by. Its empty block still took the search bar's 14 px gap, a band between the search and the chosen tasks' row. It is hidden while empty, as the count and message lines are. --- app/static/catalogue/catalogue.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index ebdc187a6..27b1e3be8 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -461,7 +461,7 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .tasks-pick { display: inline-flex; align-items: center; gap: 6px; } .tasks-pick input { flex: none; width: 4.5rem; height: 32px; padding: 0 .6rem; box-sizing: border-box; } .tasks-count { margin: 14px 0 6px; } -.tasks-count:empty, .tasks-msg:empty { display: none; } +.tasks-cats:empty, .tasks-count:empty, .tasks-msg:empty { display: none; } .tasks-scroll { overflow-x: auto; } .tasks-table th, .tasks-table td { padding: .6rem .7rem; } .tasks-table td:nth-child(2) { overflow-wrap: anywhere; } From 5e0e81c6726d10661f0df81add094ef045ef81cf Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 14:01:06 +0100 Subject: [PATCH 31/37] fix(catalogue): show the tasks page's save bar once a task is chosen With the save form in view, the save bar is made invisible but keeps its place. On a dataset with no list yet and nothing chosen, that left an empty band of about 60 px under the chosen tasks' row. The bar now shows once a task is chosen, as Show selected and Clear do. --- app/static/catalogue/tasks.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/static/catalogue/tasks.js b/app/static/catalogue/tasks.js index 272104e8d..efc42e87b 100644 --- a/app/static/catalogue/tasks.js +++ b/app/static/catalogue/tasks.js @@ -33,9 +33,10 @@ function chosenLine() { $('tasks-chosen').textContent = `${chosen.size.toLocaleString('en-US')} chosen`; if ($('tasks-bar-chosen')) $('tasks-bar-chosen').textContent = $('tasks-chosen').textContent; - // Show selected and Clear once something is chosen; Show all while the chosen are shown + // Show selected, Clear and the save bar once something is chosen; Show all while the chosen are shown $('tasks-show').hidden = !chosen.size && !st.showing; $('tasks-clear').hidden = !chosen.size; + if ($('tasks-savebar')) $('tasks-savebar').hidden = !chosen.size; } // a task on one line: its title cut to the width, the whole text in the row's tooltip and, while its box (its text // where the box is disabled) has the keyboard's focus, in place; its id beside it on hover or focus. A click From 029a9f599d8c8bdaec3489d5ad15b07cf2721edd Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 14:01:11 +0100 Subject: [PATCH 32/37] fix(catalogue): keep a task set's version and date on one line In the benchmark page's own task sets, a version such as desktop-env-v1.0.3 and the date broke onto two lines. Both cells now take the shared nowrap class. On a phone the version column is left out, as the tasks list leaves out its categories, and the cells take the tasks list's narrower padding: the table fits a 390 px screen without scrolling. --- app/static/catalogue/catalogue.css | 2 ++ app/templates/catalogue/benchmark.html | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 27b1e3be8..1876924ff 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -432,6 +432,8 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli /* A benchmark's task sets, and a dataset's tasks: browsed, ticked and kept as a set (catalogue/tasks.html). */ .bench-sets td, .bench-sets th { vertical-align: top; } .bench-sets small { display: block; } +/* on a phone the version a set was made at stays on its own page, and the others fit the width */ +@media (max-width: 640px) { .bench-sets .bench-made { display: none; } .bench-sets th, .bench-sets td { padding: .55rem .4rem; } } .bench-setlinks { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; } .bench-sets-group { margin: 14px 0 0; } .bench-ownsets { margin-top: 8px; } diff --git a/app/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index a99baa379..a6bbc3cc1 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -223,11 +223,11 @@

From {{ b.title }}

{% if task_sets %}
{% set made = task_sets|selectattr('version_label')|list %} - {% if made %}{% endif %} + {% if made %}{% endif %}{% for s in task_sets %} - {% if made %}{% endif %} + {% if made %}{% endif %} {% endfor %}
NameDataset{{ std.units.nouns|capitalize }}Made atDate
NameDataset{{ std.units.nouns|capitalize }}Made atDate
{{ s.label }}{% if s.description %}{{ s.description }}{% endif %} {{ (std.datasets|selectattr('id', 'equalto', s.dataset)|map(attribute='label')|first) or s.dataset }}{{ s.units }}{{ s.version_label }}{{ s.date[:10] }}
{{ s.units }}{{ s.version_label }}{{ s.date[:10] }}
{% endif %} From 207fc2046e6e3b599c5d7be68497ea396917163b Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 14:40:30 +0100 Subject: [PATCH 33/37] refactor(builder): draw Which tasks? from beside the Dataset step The Dataset step's drawing test cuts the page script from the standard form to the bounds section, and the step now calls the task set and nested list helpers. They move, unchanged, into that range, and the page tests that cut them end at the same place. --- app/static/builder/command-builder.js | 90 +++++++++++++-------------- app/ui_tests/test_task_set_pages.py | 4 +- 2 files changed, 47 insertions(+), 47 deletions(-) diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 23c7aa246..0f3361c39 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -731,51 +731,6 @@ + (C.leaderboard(rec) ? tile({attr:'model-choice',key:'leaderboard',title:'Like the leaderboard',on:on==='leaderboard'}) : '') + `${tile({attr:'model-choice',key:'any',title:'Any of your choice',on:on==='any'})}
`; } - // A chosen dataset's tasks: all of them, or one of its task sets (its name, its number of tasks), small cards, a - // select past five; and the page of its tasks, where a set is made. A recipe from before sets were frozen may name - // one NAME@N: it is that set. - function taskSetChoice(rec, b, x, u) { - const on = (rec.task_sets || {})[x.id] || '', sets = x.sets || [], ref = s => s.name; - const all = 'All ' + (x.units ? x.units + ' ' : '') + u.nouns; - const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(x.id)}`; - const picked = sets.find(s => on === s.name || on.split('@')[0] === s.name); - // a set made at another version of the benchmark says which: the run refuses a task that version lacks - const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; - const choice = sets.length + 1 > 5 - ? `' - : `
` + [tile({attr: 'std-taskset', key: '', data: ` data-of="${esc(x.id)}"`, on: !on, title: all}), - ...sets.map(s => tile({attr: 'std-taskset', key: ref(s), data: ` data-of="${esc(x.id)}"`, on: s === picked, title: s.label, tip: s.description || '', - meta: `${s.units} ${s.units === 1 ? u.noun : u.nouns}${made(s)}`})), - ...(on && !picked ? [tile({attr: 'std-taskset', key: on, data: ` data-of="${esc(x.id)}"`, on: true, title: on})] : [])].join('') + '
'; - // the dataset's name only where several are chosen: one chosen is the one above - const head = C.datasetsOf(rec).length > 1 ? esc(x.label) + ': which tasks?' : 'Which tasks?'; - return `` + choice; - } - // a dataset's proofs as its card shows them: its controls, then whether its ids are stable and nothing leaks - const datasetChecks = (b, x) => (x.controls || []).map(c => controlChip(c)).join('') + checkChip('stable', (x.proofs || {}).units, (x.failed || {}).units, 'the same ids twice, each unique') - + ((b.controls || []).some(c => c.key === 'oracle') ? checkChip('no leak', (x.proofs || {}).leak, (x.failed || {}).leak, 'nothing of the reference shows before the run') : ''); - // Which tasks? of a benchmark whose lists are cut from one (subset_of): all of it, the benchmark's own sets (its - // lists cut from it), then the user's sets of any of them. A choice names the list the run runs (data-was: the - // one chosen before) and, for a user's set, the set - function familyChoice(rec, b, x, u) { - const whole = b.datasets.find(d => d.id === C.wholeOf(b, x.id)) || x, cuts = b.datasets.filter(d => d.subset_of === whole.id); - const on = (rec.task_sets || {})[x.id] || '', many = n => n + ' ' + (n === 1 ? u.noun : u.nouns), was = ` data-was="${esc(x.id)}"`; - const mine = [whole, ...cuts].flatMap(d => (d.sets || []).map(s => ({...s, of: d}))); - const picked = mine.find(s => s.of.id === x.id && s.name === on.split('@')[0]); - const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; - const own = [tile({attr: 'std-family', key: whole.id, data: was, on: x.id === whole.id && !on, title: 'All of it', meta: whole.units ? many(whole.units) : ''}), - ...cuts.map(d => tile({attr: 'std-family', key: d.id, data: was, on: x.id === d.id && !on, title: d.label, tip: d.summary || '', - meta: d.units ? many(d.units) : '', foot: datasetChecks(b, d)}))]; - const yours = [...mine.map(s => tile({attr: 'std-family-set', key: s.name, data: was + ` data-in="${esc(s.of.id)}"`, on: s === picked, title: s.label, - tip: s.description || '', meta: many(s.units) + made(s)})), - ...(on && !picked ? [tile({attr: 'std-family-set', key: on, data: was + ` data-in="${esc(x.id)}"`, on: true, title: on})] : [])]; - const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(picked ? picked.of.id : whole.id)}`; - const head = C.datasetsOf(rec).length > 1 ? esc(whole.label) + ': which tasks?' : 'Which tasks?'; - return `` - + `
${own.join('')}
` + (yours.length ? `
${yours.join('')}
` : ''); - } function standardForm(rec) { const st = C.standard(), b = C.standardBench(rec); if (!b) return note('Choose a benchmark first', button('Benchmark step', `data-step="${S.benchmark}"`, 'nb-inlinebutton')); @@ -873,6 +828,51 @@ const KEEPS = [['whole', 'Pictures and text'], ['text', 'Text alone'], ['off', 'Nothing']]; const exchangesKept = rec => '
Model calls saved' + `
${KEEPS.map(([v, t]) => ``).join('')}
`; + // A chosen dataset's tasks: all of them, or one of its task sets (its name, its number of tasks), small cards, a + // select past five; and the page of its tasks, where a set is made. A recipe from before sets were frozen may name + // one NAME@N: it is that set. + function taskSetChoice(rec, b, x, u) { + const on = (rec.task_sets || {})[x.id] || '', sets = x.sets || [], ref = s => s.name; + const all = 'All ' + (x.units ? x.units + ' ' : '') + u.nouns; + const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(x.id)}`; + const picked = sets.find(s => on === s.name || on.split('@')[0] === s.name); + // a set made at another version of the benchmark says which: the run refuses a task that version lacks + const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; + const choice = sets.length + 1 > 5 + ? `' + : `
` + [tile({attr: 'std-taskset', key: '', data: ` data-of="${esc(x.id)}"`, on: !on, title: all}), + ...sets.map(s => tile({attr: 'std-taskset', key: ref(s), data: ` data-of="${esc(x.id)}"`, on: s === picked, title: s.label, tip: s.description || '', + meta: `${s.units} ${s.units === 1 ? u.noun : u.nouns}${made(s)}`})), + ...(on && !picked ? [tile({attr: 'std-taskset', key: on, data: ` data-of="${esc(x.id)}"`, on: true, title: on})] : [])].join('') + '
'; + // the dataset's name only where several are chosen: one chosen is the one above + const head = C.datasetsOf(rec).length > 1 ? esc(x.label) + ': which tasks?' : 'Which tasks?'; + return `` + choice; + } + // a dataset's proofs as its card shows them: its controls, then whether its ids are stable and nothing leaks + const datasetChecks = (b, x) => (x.controls || []).map(c => controlChip(c)).join('') + checkChip('stable', (x.proofs || {}).units, (x.failed || {}).units, 'the same ids twice, each unique') + + ((b.controls || []).some(c => c.key === 'oracle') ? checkChip('no leak', (x.proofs || {}).leak, (x.failed || {}).leak, 'nothing of the reference shows before the run') : ''); + // Which tasks? of a benchmark whose lists are cut from one (subset_of): all of it, the benchmark's own sets (its + // lists cut from it), then the user's sets of any of them. A choice names the list the run runs (data-was: the + // one chosen before) and, for a user's set, the set + function familyChoice(rec, b, x, u) { + const whole = b.datasets.find(d => d.id === C.wholeOf(b, x.id)) || x, cuts = b.datasets.filter(d => d.subset_of === whole.id); + const on = (rec.task_sets || {})[x.id] || '', many = n => n + ' ' + (n === 1 ? u.noun : u.nouns), was = ` data-was="${esc(x.id)}"`; + const mine = [whole, ...cuts].flatMap(d => (d.sets || []).map(s => ({...s, of: d}))); + const picked = mine.find(s => s.of.id === x.id && s.name === on.split('@')[0]); + const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; + const own = [tile({attr: 'std-family', key: whole.id, data: was, on: x.id === whole.id && !on, title: 'All of it', meta: whole.units ? many(whole.units) : ''}), + ...cuts.map(d => tile({attr: 'std-family', key: d.id, data: was, on: x.id === d.id && !on, title: d.label, tip: d.summary || '', + meta: d.units ? many(d.units) : '', foot: datasetChecks(b, d)}))]; + const yours = [...mine.map(s => tile({attr: 'std-family-set', key: s.name, data: was + ` data-in="${esc(s.of.id)}"`, on: s === picked, title: s.label, + tip: s.description || '', meta: many(s.units) + made(s)})), + ...(on && !picked ? [tile({attr: 'std-family-set', key: on, data: was + ` data-in="${esc(x.id)}"`, on: true, title: on})] : [])]; + const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(picked ? picked.of.id : whole.id)}`; + const head = C.datasetsOf(rec).length > 1 ? esc(whole.label) + ': which tasks?' : 'Which tasks?'; + return `` + + `
${own.join('')}
` + (yours.length ? `
${yours.join('')}
` : ''); + } // 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). diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index 9fcee8665..bfed0460e 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -739,7 +739,7 @@ def node_program(self, body): line = lambda name: re.search(r"^ const %s = .*$" % name, page, re.M).group(0) + "\n" program = (f"const schema={json.dumps(schema)};const C=require({json.dumps(str(folder / 'command-builder-core.js'))})(schema);\n" + line("esc") + cut(" const SOURCE_SAYS =", " // The yes to an agent") + cut(" const tile = t =>", " // The grids drawn by the server") - + cut(" // a dataset's proofs as its card shows them", " function standardForm(") + body) + + cut(" // a dataset's proofs as its card shows them", " function benchLimits(") + body) return json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True, timeout=10).stdout) def test_the_builder_draws_all_of_it_the_benchmarks_own_sets_then_the_users(self): @@ -812,7 +812,7 @@ def test_the_titles_name_the_dataset_only_when_several_are_chosen(self): cut = lambda start, end: page[page.index(start):page.index(end, page.index(start))] line = lambda name: re.search(r"^ const %s = .*$" % name, page, re.M).group(0) + "\n" program = (f"const schema={json.dumps(schema)};const C=require({json.dumps(str(folder / 'command-builder-core.js'))})(schema);\n" - + line("esc") + cut(" const tile = t =>", " // The grids drawn by the server") + cut(" function taskSetChoice(", " function standardForm(") + + 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);" From 5268a050a114ac4169dfef39523eb69bf7f834cd Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 14:41:59 +0100 Subject: [PATCH 34/37] fix(standard): write task sets and the tasks listing through the shared writer Main now writes every record whole through ondisk.write_whole. A task set's file and a dataset's cached listing were still written beside and renamed by hand; they take the shared writer too, owner-only as before. --- app/nullius/standard/runner/sets.py | 14 ++------------ app/nullius/standard/runner/units.py | 5 +---- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/app/nullius/standard/runner/sets.py b/app/nullius/standard/runner/sets.py index 083b11014..f7fa48b14 100644 --- a/app/nullius/standard/runner/sets.py +++ b/app/nullius/standard/runner/sets.py @@ -36,13 +36,12 @@ import json import os import re -import tempfile import unicodedata import uuid from datetime import datetime, timezone from typing import Iterable, List, Optional, Tuple -from nullius import paths +from nullius import ondisk, paths from nullius.runs import classify from nullius.standard.contract import definitions @@ -363,16 +362,7 @@ def write(entry: dict, root: Optional[str] = None) -> str: os.makedirs(os.path.dirname(path), exist_ok=True) ordered = {"schema": SCHEMA, **{k: entry[k] for k in HEADER if k in entry}, "revisions": sorted(entry["revisions"], key=lambda r: r["revision"])} - fd, tmp = tempfile.mkstemp(prefix=".set-", suffix=".json", dir=os.path.dirname(path)) - try: - with os.fdopen(fd, "w", encoding="utf-8") as f: - json.dump(ordered, f, indent=2, ensure_ascii=False) - f.write("\n") - os.replace(tmp, path) - except BaseException: - if os.path.exists(tmp): - os.unlink(tmp) - raise + ondisk.write_whole(path, json.dumps(ordered, indent=2, ensure_ascii=False) + "\n", mode=0o600) return path diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index 3f71f0204..ab970329e 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -325,10 +325,7 @@ def listing(bench: dict, dataset: str, options: Optional[dict] = None, licences= got = _list(bench, ds, values, licences) path = _cache_contained(path) os.makedirs(os.path.dirname(path), exist_ok=True) - fd, tmp = tempfile.mkstemp(prefix=".units-", suffix=".json", dir=os.path.dirname(path)) - with os.fdopen(fd, "w", encoding="utf-8") as f: - json.dump(got, f, ensure_ascii=False) - os.replace(tmp, path) + ondisk.write_whole(path, json.dumps(got, ensure_ascii=False), mode=0o600) return got From 6ff9dfeecc23aca2fe71fb5dfae08bd3ae39273a Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Thu, 26 Nov 2026 09:33:57 +0100 Subject: [PATCH 35/37] test(standard): name the job's uuid among a plain run's standard keys Main now writes standard.uuid into every job's config.json. The test that lists the keys a run without a task set records names it too. --- app/tests/test_standard_sets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/tests/test_standard_sets.py b/app/tests/test_standard_sets.py index ec5962cea..1bd19ee0f 100644 --- a/app/tests/test_standard_sets.py +++ b/app/tests/test_standard_sets.py @@ -630,7 +630,7 @@ def test_a_run_without_a_set_records_none(self): cfg = read(os.path.join(self.jobs, "plain", "config.json")) self.assertEqual(sorted(cfg["standard"]), ["backend", "benchmark", "benchmark_options", "control", "exchanges", "exchanges_max_mb", "kind", "needs", "permissions_granted", "plugged", - "provider", "retries", "unsandboxed"]) + "provider", "retries", "unsandboxed", "uuid"]) class Listing(Scratch): From f5cb9d535adb63021260e07edccb6dc304144e81 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Fri, 27 Nov 2026 00:45:26 +0100 Subject: [PATCH 36/37] feat(standard): task sets of several datasets, chosen on one page - New task set opens the tasks page; a Dataset select switches the list in place, ticks kept per dataset, saved as one set (parts per dataset, one hash); run --set NAME --dataset D runs a part, the builder runs each - Task sets section counts the user's sets alone; the dataset cuts stay datasets - Tasks page: save form on top, choosing row grouped, Show 10/25/100/All, an All pill, a spinner while listing, licences re-read when Settings closes, the header the same for every dataset - describe gives titles, texts and named categories for GSM8K, HumanEval, SWE-bench Verified, Terminal-Bench, tau3-bench, GAIA, LongMemEval, Open Telco and OSWorld1; units.categories names them on the page and in nullius standard units --- .../catalogue/benchmarks/gaia/driver.py | 11 +- .../catalogue/benchmarks/gaia/standard.json | 5 + .../catalogue/benchmarks/gsm8k/driver.py | 17 ++- .../catalogue/benchmarks/gsm8k/standard.json | 1 + .../catalogue/benchmarks/humaneval/driver.py | 20 ++- .../benchmarks/humaneval/standard.json | 1 + .../benchmarks/longmemeval/driver.py | 7 +- .../benchmarks/longmemeval/standard.json | 18 ++- .../catalogue/benchmarks/open-telco/driver.py | 29 +++- .../benchmarks/open-telco/standard.json | 53 +++++++- .../benchmarks/osworld1/standard.json | 19 ++- .../benchmarks/swe-bench-verified/driver.py | 13 +- .../swe-bench-verified/standard.json | 11 +- .../catalogue/benchmarks/tau3-bench/driver.py | 24 +++- .../benchmarks/tau3-bench/standard.json | 16 ++- .../benchmarks/terminal-bench/driver.py | 16 ++- .../benchmarks/terminal-bench/standard.json | 34 ++++- app/nullius/standard/cli.py | 59 +++++--- app/nullius/standard/contract/definitions.py | 6 + app/nullius/standard/pages/recipe.py | 16 ++- app/nullius/standard/runner/sets.py | 127 ++++++++++++++---- app/nullius/standard/runner/units.py | 33 +++-- app/static/builder/command-builder-core.js | 11 +- app/static/builder/command-builder.js | 4 +- app/static/catalogue/catalogue.css | 18 ++- app/static/catalogue/tasks.js | 103 +++++++++++--- app/templates/catalogue/benchmark.html | 21 +-- app/templates/catalogue/tasks.html | 93 ++++++++----- app/tests/test_longmemeval_setups.py | 3 +- app/tests/test_open_telco_driver.py | 12 +- app/tests/test_standard_sets.py | 74 +++++++++- app/tests/test_standard_units_listing.py | 21 ++- app/ui_tests/test_task_set_pages.py | 103 ++++++++------ app/web/catalogue.py | 35 +++-- app/web/runs.py | 4 +- docs/cli/task-sets.md | 9 +- docs/standard.md | 1 + 37 files changed, 823 insertions(+), 225 deletions(-) diff --git a/app/nullius/catalogue/benchmarks/gaia/driver.py b/app/nullius/catalogue/benchmarks/gaia/driver.py index c2b685ae9..7c214f8ba 100644 --- a/app/nullius/catalogue/benchmarks/gaia/driver.py +++ b/app/nullius/catalogue/benchmarks/gaia/driver.py @@ -13,6 +13,7 @@ import json import os from pathlib import Path, PurePosixPath +import re import shutil import sys import urllib.request @@ -23,6 +24,8 @@ CACHE = UPSTREAM / ".gaia-cache" ROWS = {} MARKER = "FINAL ANSWER:" +# a sentence ends at . ? ! before a space, not after an initial or a title (M. Last, St. Thomas), or at a line's end +SENTENCE_END = re.compile(r"(?'. FORMATS = {"telemath": "\\boxed{%s}", "telelogs": "\\boxed{%s}", "three_gpp": '{"WORKING GROUP": "%s"}'} @@ -193,15 +197,30 @@ def text_of(s): return "\n\n".join(str(getattr(m, "text", "") or "") for m in s.input or []) +def rows(): + """The dataset's rows as its file holds them, in the samples' order: read by the + task's own call (Inspect's hf_dataset, from the cache the task's load wrote).""" + with locked(os.path.join(WORK, "open-telco.lock")), quiet(): + from inspect_ai.dataset import Sample, hf_dataset + got = hf_dataset(ROOT, name=DATASET.rsplit("-", 1)[0], split=PARAMS["split"].default, + sample_fields=lambda r: Sample(input="", metadata=r)) + return [s.metadata for s in got] + + def describe(dataset, **_): every = numbered() + place = {u: i for i, u in enumerate(every)} + fields = ROW_FIELDS.get(NAME, ()) + row = rows() if fields else [] out = {} for unit in units(dataset)["units"]: s = every[unit] - meta = s.metadata or {} + meta = {**(s.metadata or {}), **{n: row[place[unit]].get(n) for n in fields}} text = text_of(s) - out[unit] = {"title": text, "text": text, - "categories": {n: str(meta[n]) for n in FILTERS if n in PARAMS and meta.get(n) not in (None, "")}} + title = text.split(DOCUMENT, 1)[1].strip().removeprefix("{").removesuffix("}") if DOCUMENT in text else text + out[unit] = {"title": title, "text": text, + "categories": {n: str(meta[n]) for n in (*FILTERS, *fields) + if (n in PARAMS or n in fields) and meta.get(n) not in (None, "")}} return {"units": out} diff --git a/app/nullius/catalogue/benchmarks/open-telco/standard.json b/app/nullius/catalogue/benchmarks/open-telco/standard.json index b3f25fda3..995c4a946 100644 --- a/app/nullius/catalogue/benchmarks/open-telco/standard.json +++ b/app/nullius/catalogue/benchmarks/open-telco/standard.json @@ -113,7 +113,58 @@ ], "units": { "noun": "question", - "nouns": "questions" + "nouns": "questions", + "categories": { + "subject": { + "label": "Subject" + }, + "difficulty": { + "label": "Difficulty", + "names": { + "easy": "Easy", + "medium": "Medium", + "hard": "Hard" + } + }, + "task_id": { + "label": "Task family", + "names": { + "T1": "Intent Feasibility Assessment", + "T2": "Intent Conflict Resolution", + "T3": "Intent Drift Detection", + "T4": "Slice Selection Reasoning", + "T5": "Slice Switching Decision", + "T6": "Slice Fairness vs Safety", + "T7": "Compute Placement Decision", + "T8": "Graceful Degradation under Edge Overload", + "T9": "Trust-Aware Offloading", + "T10": "SLA Violation Prediction", + "T11": "Preemptive Autonomy Downgrade", + "T12": "Conservative Continuation Decision", + "T13": "Swarm-Level Slice Negotiation", + "T14": "Scheduler Reconfiguration Adaptation", + "T15": "Decision Consistency under Replanning", + "T16": "Network-Exposed Compute Marketplace", + "T17": "Network-Knowledge RAG Augmentation", + "T18": "AI Agent Identity & Onboarding", + "T19": "AI Agent Interoperability & Federation", + "T20": "Agent-to-Agent Communication Management", + "T21": "Device-Network Task Offload Arbitration", + "T22": "Federated / Collaborative Learning Orchestration", + "T23": "Network-Assisted Digital Twin Control", + "T24": "Sensing-Enhanced Decisioning (ISAC)", + "T25": "AI-Agent-based Disaster / Public-Safety Coordination", + "T26": "Trust-Aware Third-Party Agent Exposure", + "T27": "Agent Lifecycle & Management", + "T28": "6G Model Training-as-a-Service Decision", + "T29": "Immersive/AR Resource Prioritization", + "T30": "Network Security Detection & Response Automation" + } + }, + "category": { + "label": "Category" + } + } }, "score": { "kind": "pass", diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index d669ffb53..612730a79 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -93,7 +93,24 @@ ], "units": { "noun": "task", - "nouns": "tasks" + "nouns": "tasks", + "categories": { + "domain": { + "label": "App", + "names": { + "chrome": "Chrome", + "gimp": "GIMP", + "libreoffice_calc": "LibreOffice Calc", + "libreoffice_impress": "LibreOffice Impress", + "libreoffice_writer": "LibreOffice Writer", + "multi_apps": "Several apps", + "os": "OS", + "thunderbird": "Thunderbird", + "vlc": "VLC", + "vs_code": "VS Code" + } + } + } }, "score": { "kind": "score", diff --git a/app/nullius/catalogue/benchmarks/swe-bench-verified/driver.py b/app/nullius/catalogue/benchmarks/swe-bench-verified/driver.py index 4748f9215..3ea800c14 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-verified/driver.py +++ b/app/nullius/catalogue/benchmarks/swe-bench-verified/driver.py @@ -6,6 +6,8 @@ script the harness runs and the name of the log parser that reads its output. units - the instance ids, in the dataset's order +describe - the problem statement as its text, its first line as its title; + its repository and the dataset's difficulty as categories setup - the problem statement as the prompt, verbatim; the instance's own image (``image``: the authors' prebuilt image, pulled by the digest its tag had when pinned here, ``images.json``), ``/testbed`` as the @@ -64,6 +66,15 @@ def units(dataset): return {"units": list(rows())} +def describe(dataset=None, **_): + out = {} + for unit, r in rows().items(): + text = r["problem_statement"] + title = next((line.strip() for line in text.splitlines() if line.strip()), "") + out[unit] = {"title": title, "text": text, "categories": {"repo": r["repo"], "difficulty": r["difficulty"]}} + return {"units": out} + + def setup(unit, dir): r = row(unit) capture = (f"cd {WORKDIR} && git add -A && " @@ -102,7 +113,7 @@ def oracle(unit, dir): "run": ["git", "-C", WORKDIR, "apply", "-v", "/tmp/gold.patch"], "seconds": SOLVE_SECONDS}} -HANDLERS = {"units": units, "setup": setup, "score": score, "oracle": oracle} +HANDLERS = {"units": units, "describe": describe, "setup": setup, "score": score, "oracle": oracle} for line in sys.stdin: try: req = json.loads(line) diff --git a/app/nullius/catalogue/benchmarks/swe-bench-verified/standard.json b/app/nullius/catalogue/benchmarks/swe-bench-verified/standard.json index dc40e22e9..4a2600ad8 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-verified/standard.json +++ b/app/nullius/catalogue/benchmarks/swe-bench-verified/standard.json @@ -15,6 +15,7 @@ "license": "MIT" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" @@ -38,7 +39,15 @@ ], "units": { "noun": "instance", - "nouns": "instances" + "nouns": "instances", + "categories": { + "repo": { + "label": "Repository" + }, + "difficulty": { + "label": "Difficulty" + } + } }, "environments": { "task": { diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/driver.py b/app/nullius/catalogue/benchmarks/tau3-bench/driver.py index f6656314f..a84b01670 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/driver.py +++ b/app/nullius/catalogue/benchmarks/tau3-bench/driver.py @@ -14,6 +14,10 @@ tasks than the upstream's task set runs. A dataset with no file (banking_knowledge, its tasks one file each) is the upstream's own task loader (``registry.get_tasks_loader``) +describe - each task's purpose (``description.purpose``, else the reason + for the call) and the user's reason for the call; a telecom task's + intent and persona, read from its id by the upstream's own + ``get_intent_from_task_id`` and ``get_persona_from_task_id`` setup - the agent's instructions and the domain's policy as the upstream's agent is given them (``LLMAgent.system_prompt``: its ``SYSTEM_PROMPT`` and ``AGENT_INSTRUCTION`` over @@ -110,6 +114,7 @@ from tau2.data_model.message import AssistantMessage, MultiToolMessage, ToolCall, ToolMessage, UserMessage from tau2.data_model.simulation import SimulationRun, TerminationReason, TextRunConfig from tau2.data_model.tasks import RewardType, Task +from tau2.domains.telecom.tasks.utils import get_intent_from_task_id, get_persona_from_task_id from tau2.evaluator.evaluator import EvaluationType, evaluate_simulation from tau2.orchestrator.orchestrator import DEFAULT_FIRST_AGENT_MESSAGE from tau2.registry import registry @@ -474,6 +479,23 @@ def units(dataset, setup=None): return {"units": [u for u, t in tasks().items() if keep is None or keep(t)]} +def describe(dataset, **_): + out = {} + for unit in units(dataset)["units"]: + t = task(unit) + said = t.user_scenario.instructions + reason = str(said if isinstance(said, str) else said.reason_for_call or "").strip() + purpose = (t.description.purpose if t.description else None) or "" + cats = ({"intent": get_intent_from_task_id(unit), "persona": get_persona_from_task_id(unit)} + if unit.startswith("[") else {}) # a telecom id: [intent]actions[PERSONA:persona] + # a telecom task's purpose and reason are its issue's, which the Issue category already says: the faults + # its id lists tell it from the others + faults = unit.split("]", 1)[1].rsplit("[", 1)[0] if cats else "" + title = " · ".join(f.replace("_", " ") for f in faults.split("|") if f).capitalize() or purpose.strip() or reason + out[unit] = {"title": title, "text": reason, "categories": cats} + return {"units": out} + + def setup(unit, dir, attempt=None): t = task(unit) _leave() # one unit at a time: an earlier one left unfinished is ended @@ -612,4 +634,4 @@ def oracle(unit, dir): if __name__ == "__main__": - serve({"units": units, "setup": setup, "turn": turn, "answer": answer, "score": score, "oracle": oracle}, out=PROTOCOL) + serve({"units": units, "describe": describe, "setup": setup, "turn": turn, "answer": answer, "score": score, "oracle": oracle}, out=PROTOCOL) diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/standard.json b/app/nullius/catalogue/benchmarks/tau3-bench/standard.json index c4f6ae5ec..133c5a693 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/standard.json +++ b/app/nullius/catalogue/benchmarks/tau3-bench/standard.json @@ -16,6 +16,7 @@ "license": "MIT" }, "driver": { + "describe": true, "command": [ "{install}/.venv/bin/python", "{here}/driver.py" @@ -80,7 +81,20 @@ ], "units": { "noun": "task", - "nouns": "tasks" + "nouns": "tasks", + "categories": { + "intent": { + "label": "Issue", + "names": { + "mms_issue": "MMS (picture/group messaging)", + "mobile_data_issue": "Mobile data/slow internet", + "service_issue": "No service/connection" + } + }, + "persona": { + "label": "Persona" + } + } }, "simulator": { "model": "gpt-4.1-2025-04-14", diff --git a/app/nullius/catalogue/benchmarks/terminal-bench/driver.py b/app/nullius/catalogue/benchmarks/terminal-bench/driver.py index 903461ffb..a6da1f8cc 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench/driver.py +++ b/app/nullius/catalogue/benchmarks/terminal-bench/driver.py @@ -8,6 +8,8 @@ units - the dataset's tasks: a few that build fast (``small``), or every task whose reference solution downloads nothing (``offline``), or all 89 (``full``) +describe - the task's id as its title, its instruction as its text, and its + task.toml's metadata difficulty and category as categories setup - the task's instruction as the prompt; its own image (``image``: by the run's image option, the prebuilt image its task.toml names, pulled by digest, or its environment folder built as published - a @@ -210,6 +212,18 @@ def units(dataset): return {"units": list(DATASETS[dataset])} +def describe(dataset, **_): + out = {} + for unit in DATASETS[dataset]: + here, t = task(unit) + with open(os.path.join(here, "instruction.md")) as f: + text = f.read().strip() + meta = t.get("metadata") or {} + out[unit] = {"title": unit, "text": text, + "categories": {"difficulty": meta.get("difficulty"), "category": meta.get("category")}} + return {"units": out} + + def setup(unit, dir): here, t = task(unit) with open(os.path.join(here, "instruction.md")) as f: @@ -256,7 +270,7 @@ def oracle(unit, dir): "seconds": (t.get("agent") or {}).get("timeout_sec") or 900}} -HANDLERS = {"units": units, "setup": setup, "score": score, "oracle": oracle} +HANDLERS = {"units": units, "describe": describe, "setup": setup, "score": score, "oracle": oracle} for line in sys.stdin: try: req = json.loads(line) diff --git a/app/nullius/catalogue/benchmarks/terminal-bench/standard.json b/app/nullius/catalogue/benchmarks/terminal-bench/standard.json index 994a2d982..33f5e9144 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench/standard.json +++ b/app/nullius/catalogue/benchmarks/terminal-bench/standard.json @@ -14,6 +14,7 @@ "license": "Apache-2.0" }, "driver": { + "describe": true, "command": [ "python3", "{here}/driver.py" @@ -41,7 +42,38 @@ ], "units": { "noun": "task", - "nouns": "tasks" + "nouns": "tasks", + "categories": { + "difficulty": { + "label": "Difficulty", + "names": { + "easy": "Easy", + "medium": "Medium", + "hard": "Hard" + } + }, + "category": { + "label": "Category", + "names": { + "software-engineering": "Software engineering", + "system-administration": "System administration", + "security": "Security", + "data-science": "Data science", + "scientific-computing": "Scientific computing", + "debugging": "Debugging", + "file-operations": "File operations", + "model-training": "Model training", + "data-processing": "Data processing", + "mathematics": "Mathematics", + "machine-learning": "Machine learning", + "personal-assistant": "Personal assistant", + "optimization": "Optimization", + "games": "Games", + "video-processing": "Video processing", + "data-querying": "Data querying" + } + } + } }, "environments": { "task": { diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 9ec552f37..e6974496d 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -801,12 +801,17 @@ def _listed_units(path: str) -> list: def _set_rows(entry: dict) -> dict: - last = sets.latest(entry) return {"benchmark": entry["benchmark"], "name": entry["name"], "label": sets.label_of(entry), "id": entry["id"], - "units": len(last["units"]), "dataset": entry["dataset"], "version": entry.get("version") or "", + "units": sets.size(entry), "dataset": sets.datasets_of(entry)[0], "datasets": sets.datasets_of(entry), + "parts": {d: len(ids) for d, ids in sets.parts(entry).items()}, "version": entry.get("version") or "", "description": entry.get("description") or ""} +def _parts_line(parts: dict) -> str: + """A set's datasets as a line says them: its one, or each with its number of ids.""" + return next(iter(parts)) if len(parts) == 1 else ", ".join(f"{d} {n}" for d, n in parts.items()) + + def _find_bench(key): """A benchmark of the catalogue, or a conformance kit, by its key; None when there is none.""" return definitions.get("benchmark", key) or next((k for k in definitions.kits() if k["key"] == key), None) @@ -825,9 +830,17 @@ def cmd_set_create(a): if a.from_job is None and (a.outcome or a.unit): raise sets.Refused("--outcome and --unit choose a job's trials: give them with --from-job") seed = None + given = a.dataset or [] + if a.units is None and len(given) > 1: + raise sets.Refused("--dataset once, but with --units: a set of several datasets is each --dataset D --units FILE") + a.dataset = given[0] if given else None if a.units is not None: - dataset = sets._dataset(b, a.dataset) - got = {"dataset": dataset, "units": _listed_units(a.units), "note": f"from {os.path.basename(a.units)}"} + # each --units FILE the ids of the --dataset beside it, in order: two or more pairs make a mixed set + if len(a.units) != max(1, len(given)) or (len(a.units) > 1 and len(set(given)) != len(given)): + raise sets.Refused("--dataset D --units FILE for each dataset of the set, each dataset once") + named = given or [None] + got = {"parts": {sets._dataset(b, d): _listed_units(f) for d, f in zip(named, a.units)}, + "note": "from " + ", ".join(os.path.basename(f) for f in a.units)} elif listed: # the ids the listing matches today, under the benchmark's default options, or --sample of them drawn at # random; the note keeps the filter and the seed @@ -848,9 +861,14 @@ def cmd_set_create(a): got = sets.from_job(b, a.from_job, a.outcome, a.unit) if a.dataset and a.dataset != got["dataset"]: raise sets.Refused(f"--dataset {a.dataset}: the job ran the dataset {got['dataset']}") - entry = sets.create(b, a.label, dataset=got["dataset"], units=got["units"], description=a.description, note=got["note"]) + if "parts" in got: + entry = sets.create(b, a.label, parts=got["parts"], description=a.description, note=got["note"]) + else: + entry = sets.create(b, a.label, dataset=got["dataset"], units=got["units"], description=a.description, note=got["note"]) + n = sets.size(entry) print(f"wrote {sets.path_of(entry['benchmark'], entry['name'])}: {_named(entry)}, " - f"{len(got['units'])} {b['units']['nouns'] if len(got['units']) != 1 else b['units']['noun']} of {entry['dataset']}" + f"{n} {b['units']['nouns'] if n != 1 else b['units']['noun']} of " + + _parts_line({d: len(ids) for d, ids in sets.parts(entry).items()}) + (f" at {sets.version_label(b, entry['version'])}" if entry.get("version") else "") + (f", drawn with --seed {seed}" if seed is not None else "")) return 0 @@ -871,7 +889,7 @@ def cmd_set_list(a): print(json.dumps(rows, indent=2)) return 0 for r in rows: - print(f"{r['benchmark']:<16} {r['name']:<24} {r['units']:>6} units of {r['dataset']}" + print(f"{r['benchmark']:<16} {r['name']:<24} {r['units']:>6} units of {_parts_line(r['parts'])}" + (f" at {r['version']}" if r["version"] else "") + (f" {r['label']}" if r["label"] != r["name"] else "") + (f" {r['description']}" if r["description"] else "")) return 0 @@ -882,19 +900,23 @@ def cmd_set_show(a): entry = sets.load(a.benchmark, name) got = sets.latest(entry, rev) if a.json: + listed = {"parts": got["parts"]} if "parts" in got else {"units": got["units"]} print(json.dumps({**{k: entry[k] for k in sets.HEADER if k in entry}, "label": sets.label_of(entry), - "date": got["date"], "note": got["note"], "hash": got["hash"], "units": got["units"]}, indent=2)) + "date": got["date"], "note": got["note"], "hash": got["hash"], **listed}, indent=2)) return 0 bench = _find_bench(a.benchmark) - print(f"{_named(entry)}: {len(got['units'])} units of {entry['benchmark']} {entry['dataset']}" + each = sets.parts(entry, got) + print(f"{_named(entry)}: {sets.size(entry, got)} units of {entry['benchmark']} " + + _parts_line({d: len(ids) for d, ids in each.items()}) + (f", made at {sets.version_label(bench, entry['version'])}" if entry.get("version") else "")) if entry.get("description"): print(f" {entry['description']}") print(f" id {entry['id']}") print(f" {got['date']} {got['hash'][:12]}" + (f" {got['note']}" if got["note"] else "")) - print("units:") - for u in got["units"]: - print(f" {u}") + for d, ids in each.items(): + print(f"units of {d}:" if len(each) > 1 else "units:") + for u in ids: + print(f" {u}") return 0 @@ -911,7 +933,7 @@ def cmd_set_delete(a): if entry is None: print(f"deleted {path}: an entry this version could not read") return 0 - print(f"deleted {path}: {_named(entry)}, {len(sets.latest(entry)['units'])} units; jobs that ran it keep their record") + print(f"deleted {path}: {_named(entry)}, {sets.size(entry)} units; jobs that ran it keep their record") return 0 @@ -978,7 +1000,9 @@ def cmd_units(a): print(f"{found['total']} of {found['of']} {words['nouns']} of {a.dataset}" + ("" if found["described"] else " (its driver gives ids alone: a search reads the ids)")) for field, values in found["categories"].items(): - print(f"{field}: " + ", ".join(f"{v['value']} {v['count']}" for v in values)) + said = found["fields"][field]["label"] # the field and the values as named, the key each takes + print((f"{said} ({field})" if said.lower() != field.replace("_", " ") else field) + ": " + + ", ".join(f"{v['name']}" + (f" ({v['value']})" if v["name"] != v["value"] else "") + f" {v['count']}" for v in values)) for t in found["tasks"]: print(f" {t['id']}" + (f" {t['title']}" if t["title"] else "")) return 0 @@ -1166,9 +1190,12 @@ def main(argv=None): sc.add_argument("benchmark", metavar="BENCH") sc.add_argument("label", metavar="NAME", help="any words; the name commands take is made from them (lower case, hyphens, -2 for a second one)") - sc.add_argument("--dataset", help="the dataset the set is cut from (from a job: the job's)") + sc.add_argument("--dataset", action="append", metavar="D", + help="the dataset the set is cut from (from a job: the job's); with --units, once per file, " + "for a set of several datasets") source = sc.add_mutually_exclusive_group() - source.add_argument("--units", metavar="FILE", help="the units a file lists, one id a line (# starts a comment)") + source.add_argument("--units", action="append", metavar="FILE", + help="the units a file lists, one id a line (# starts a comment): the ids of the --dataset beside it") source.add_argument("--from-job", metavar="JOB_DIR", help="the units a standard job ran (each trial's full unit id)") sc.add_argument("--outcome", action="append", metavar="O,...", help="with --from-job: the trials of these outcomes (the pages' names, or passed, failed, infra)") diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 79ed4c330..51143f853 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1649,6 +1649,12 @@ def problems(d: dict, kind: str) -> List[str]: bad.append("units: {noun, nouns}") if "redistribute" in u and not isinstance(u["redistribute"], bool): bad.append("units.redistribute: false when the data may not be redistributed") + cats = u.get("categories", {}) + if not isinstance(cats, dict) or not all( + isinstance(c, dict) and set(c) <= {"label", "names"} and isinstance(c.get("label", ""), str) + and isinstance(c.get("names", {}), dict) and all(isinstance(v, str) and v for v in c.get("names", {}).values()) + for c in cats.values()): + bad.append("units.categories: {FIELD: {label, names: {VALUE: name}}}, how a listing's categories read") lim = d.get("limits") if lim is not None: if not isinstance(lim, dict): diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 184c3ae2b..69029def4 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -209,9 +209,11 @@ def _bench_page(b: dict) -> dict: for c in controls], "proofs": {k: status[d["id"]][k]["proven"] for k in ("units", "leak")}, "failed": {k: status[d["id"]][k]["failed"] for k in ("units", "leak") if status[d["id"]][k]["failed"]}, - # the user's task sets cut from it (standard/runner/sets.py), each with the version it was made at - "sets": [dict(s, version_label=sets.version_label(b, s["version"]) if s["version"] else "") - for s in task_sets if s["dataset"] == d["id"]]} + # the user's task sets cut from it (standard/runner/sets.py), each with the version it was made at; + # a set of several datasets under each, its ``units`` its ids of this one + "sets": [dict(s, units=s["parts"][d["id"]], whole=s["units"], + version_label=sets.version_label(b, s["version"]) if s["version"] else "") + for s in task_sets if d["id"] in s["parts"]]} for d in b["datasets"]]} @@ -499,10 +501,12 @@ def add(step, message, shown=False, field=None, unset=False): except sets.Refused as e: add("dataset", f"Task set {ref}: {e}.") continue - if entry["dataset"] != ds_id: - add("dataset", f"The task set {sets.label_of(entry)} is cut from the dataset {entry['dataset']}, not {ds_id}.") + part = sets.parts(entry, got).get(ds_id) + if part is None: + add("dataset", f"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 - set_of[ds_id] = {"name": set_name, "label": sets.label_of(entry), "units": len(got["units"]), "ids": set(got["units"])} + set_of[ds_id] = {"name": set_name, "label": sets.label_of(entry), "units": len(part), "ids": set(part)} 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. diff --git a/app/nullius/standard/runner/sets.py b/app/nullius/standard/runner/sets.py index f7fa48b14..50432ea68 100644 --- a/app/nullius/standard/runner/sets.py +++ b/app/nullius/standard/runner/sets.py @@ -6,7 +6,10 @@ holds an id minted when it is made, its label and the name made from it, its description, the benchmark, the version of the benchmark it was made at, the dataset it is cut from, and its list, and nothing that binds a run (no -benchmark option, no setup). The label is the text a person typed; the name +benchmark option, no setup). A set may mix datasets: it then names them +(``datasets``) and its list holds the ids of each (``parts``: {dataset: ids}), +each dataset a job of its own when it runs; a set of one dataset is written as +before. The label is the text a person typed; the name is what commands take: the label in lower case with hyphens, ``-2`` and on for a second equal one (``name_for``). @@ -62,10 +65,10 @@ classify.NO_PATCH, classify.AGENT_ERROR}, "infra": set(classify.INFRA_OUTCOMES), } -HEADER = ("id", "name", "label", "description", "benchmark", "version", "dataset") +HEADER = ("id", "name", "label", "description", "benchmark", "version", "dataset", "datasets") # what an entry of the earlier format held beside its header: a run's options, bound to the set EARLIER = ("benchmark_version", "benchmark_options", "setup") -REVISION = ("revision", "date", "note", "units", "hash") +REVISION = ("revision", "date", "note", "units", "hash") # a mixed set's: "parts" in place of "units" RECORD = ("id", "name", "revision", "hash", "units") # what the record of a newer job holds beside those: what its page shows, and what a run checks the set against RECORD_MORE = ("label", "version") @@ -192,10 +195,35 @@ def content_hash(benchmark: str, dataset: str, units: Iterable[str]) -> str: return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest() -def _hash_of(entry: dict, units: Iterable[str]) -> str: +def parts_hash(benchmark: str, parts: dict) -> str: + """A mixed set's ``content_hash``: over the benchmark and each dataset's ids sorted.""" + doc = {"benchmark": benchmark, "parts": {d: sorted(set(str(u) for u in ids)) for d, ids in parts.items()}} + return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest() + + +def _hash_of(entry: dict, units) -> str: + """The hash of a list of ``entry``: its ids, or a mixed set's {dataset: ids}.""" + if "datasets" in entry: + return parts_hash(entry["benchmark"], units) return content_hash(entry["benchmark"], entry["dataset"], units) +def datasets_of(entry: dict) -> List[str]: + """The datasets a set is cut from: its one, or a mixed set's, in order.""" + return list(entry["datasets"]) if "datasets" in entry else [entry["dataset"]] + + +def parts(entry: dict, rev: Optional[dict] = None) -> dict: + """{dataset: ids} of the set's list (its latest when ``rev`` is not given).""" + rev = rev or latest(entry) + return {d: list(rev["parts"][d]) for d in entry["datasets"]} if "datasets" in entry else {entry["dataset"]: list(rev["units"])} + + +def size(entry: dict, rev: Optional[dict] = None) -> int: + """How many ids the set holds, every dataset's together.""" + return sum(len(ids) for ids in parts(entry, rev).values()) + + def _now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") @@ -223,9 +251,15 @@ def check(entry: dict, where: str) -> dict: if other: raise Refused(f"{where}: holds {', '.join(other)}, which a task set does not hold: a set is its dataset " "and its ids, and a run gives its own options") - for k in ("id", "name", "benchmark", "dataset"): + mixed = "datasets" in entry + for k in ("id", "name", "benchmark") + (() if mixed else ("dataset",)): if not isinstance(entry.get(k), str) or not entry[k]: raise Refused(f"{where}: no {k}") + if mixed: + ds = entry["datasets"] + if ("dataset" in entry or not isinstance(ds, list) or len(ds) < 2 or len(set(ds)) != len(ds) + or any(not isinstance(d, str) or not d for d in ds)): + raise Refused(f"{where}: datasets names two or more datasets, each once, in place of dataset") check_name(entry["name"]) _bench_key(entry["benchmark"]) if not isinstance(entry.get("description"), str): @@ -246,10 +280,21 @@ def check(entry: dict, where: str) -> dict: raise Refused(f"{where}: list {n} has no date") if not isinstance(r.get("note"), str): raise Refused(f"{where}: list {n}'s note is text") - if not isinstance(r.get("units"), list) or any(not isinstance(u, str) for u in r["units"]): - raise Refused(f"{where}: list {n} lists no units") - _ids(r["units"], f"{where}: list {n}") - if r.get("hash") != _hash_of(entry, r["units"]): + if mixed: + got = r.get("parts") + if not isinstance(got, dict) or sorted(got) != sorted(entry["datasets"]) or "units" in r: + raise Refused(f"{where}: list {n} holds the ids of each of its datasets (parts), and nothing else") + for d, ids in got.items(): + if not isinstance(ids, list) or any(not isinstance(u, str) for u in ids): + raise Refused(f"{where}: list {n} lists no units of {d}") + _ids(ids, f"{where}: list {n} of {d}") + listed = got + else: + if not isinstance(r.get("units"), list) or any(not isinstance(u, str) for u in r["units"]): + raise Refused(f"{where}: list {n} lists no units") + _ids(r["units"], f"{where}: list {n}") + listed = r["units"] + if r.get("hash") != _hash_of(entry, listed): raise Refused(f"{where}: list {n}'s hash is not that of its units and dataset: " "the file was changed by hand") return entry @@ -319,13 +364,14 @@ def entries(benchmark: Optional[str] = None, root: Optional[str] = None) -> Tupl def rows(benchmark: str, root: Optional[str] = None) -> List[dict]: """The readable entries of ``benchmark`` as a page lists them, by name: {name, label, description, dataset, - version, units, date}, ``units`` the number of its ids, ``date`` the day its list was made, ``version`` "" - for a set made before sets recorded one.""" + datasets, parts, version, units, date}, ``dataset`` its first, ``parts`` {dataset: number of its ids}, ``units`` + the number of its ids, ``date`` the day its list was made, ``version`` "" for a set made before sets recorded one.""" out = [] for e in entries(benchmark, root)[0]: - last = latest(e) - out.append({"name": e["name"], "label": label_of(e), "description": e.get("description") or "", "dataset": e["dataset"], - "version": e.get("version") or "", "units": len(last["units"]), "date": last["date"]}) + last, each = latest(e), parts(e) + out.append({"name": e["name"], "label": label_of(e), "description": e.get("description") or "", + "dataset": datasets_of(e)[0], "datasets": datasets_of(e), "parts": {d: len(ids) for d, ids in each.items()}, + "version": e.get("version") or "", "units": size(e), "date": last["date"]}) return out @@ -375,19 +421,29 @@ def _dataset(bench: dict, dataset: Optional[str]) -> str: return dataset -def create(bench: dict, label: str, *, dataset: str, units: List[str], description: str = "", note: str = "", - root: Optional[str] = None) -> dict: +def create(bench: dict, label: str, *, dataset: Optional[str] = None, units: Optional[List[str]] = None, + parts: Optional[dict] = None, description: str = "", note: str = "", root: Optional[str] = None) -> dict: """A new entry labelled ``label``, its name made from it (``name_for``), at the version ``bench`` is; written. - A label another set has already gives the next free name.""" + A label another set has already gives the next free name. Its list is ``units`` of ``dataset``, or ``parts``, + {dataset: units} in the order given: of one dataset, it is written as that dataset's list.""" label = check_label(label) + given = dict(parts) if parts is not None else {dataset: units} + if parts is not None and (dataset is not None or units is not None): + raise Refused("a set's list is its units of one dataset, or its parts: give one or the other") + given = {_dataset(bench, d): _ids(ids or [], f"the set {label}" + (f" of {d}" if len(given) > 1 else "")) + for d, ids in given.items()} + if not given: + raise Refused(f"the set {label} lists no unit") entry = {"id": uuid.uuid4().hex, "name": name_for(bench["key"], label, root), "label": label, "description": description or "", "benchmark": bench["key"], - **({"version": version_of(bench)} if version_of(bench) else {}), "dataset": _dataset(bench, dataset)} + **({"version": version_of(bench)} if version_of(bench) else {}), + **({"datasets": list(given)} if len(given) > 1 else {"dataset": next(iter(given))})} path = path_of(bench["key"], entry["name"], root) if os.path.lexists(path): raise Refused(f"a task set {entry['name']!r} of {bench['key']} exists already ({path})") - ids = _ids(units, f"the set {label}") - entry["revisions"] = [{"revision": 1, "date": _now(), "note": note or "", "units": ids, "hash": _hash_of(entry, ids)}] + listed = given if len(given) > 1 else next(iter(given.values())) + entry["revisions"] = [{"revision": 1, "date": _now(), "note": note or "", + "parts" if len(given) > 1 else "units": listed, "hash": _hash_of(entry, listed)}] write(entry, root) return entry @@ -509,24 +565,34 @@ def from_job(bench: dict, job_dir: str, outcomes: Optional[List[str]] = None, na + (f": {'; '.join(said)}" if said else "")} -def record(entry: dict, rev: Optional[dict] = None) -> dict: +def record(entry: dict, rev: Optional[dict] = None, dataset: Optional[str] = None) -> dict: """What a job's config keeps of the set it ran (``standard.task_set``): its id, name, label, the number and - hash of its list, its units, and the version it was made at when it recorded one.""" + hash of its list, its units, and the version it was made at when it recorded one. Of a mixed set, ``units`` + are those of the job's ``dataset``, and ``parts`` the whole list, for ``import_path`` to make it again.""" rev = rev or latest(entry) + each = parts(entry, rev) + mixed = "datasets" in entry return {"id": entry["id"], "name": entry["name"], "label": label_of(entry), "revision": rev["revision"], - "hash": rev["hash"], "units": rev["units"], **({"version": entry["version"]} if entry.get("version") else {})} + "hash": rev["hash"], "units": each[dataset] if mixed else rev["units"], + **({"parts": each} if mixed else {}), **({"version": entry["version"]} if entry.get("version") else {})} def for_run(bench: dict, ref: str, *, dataset: Optional[str] = None, units_given: bool = False, root: Optional[str] = None) -> Tuple[dict, str]: - """``run --set NAME``: (the record the job keeps, the dataset), the set's dataset taken over the run's. - A ``--units`` beside it, or another ``--dataset``, is refused. The run's benchmark options are its own, as + """``run --set NAME``: (the record the job keeps, the dataset), the set's dataset taken over the run's; of a + mixed set, the ``--dataset`` given, one of its, each a job of its own. A ``--units`` beside it, or another + ``--dataset``, is refused. The run's benchmark options are its own, as on the whole dataset: the run then refuses an id its driver does not list under them.""" name, rev = split_ref(ref) if units_given: raise Refused(f"--set {ref} and --units: the set lists the units, give one or the other") entry = load(bench["key"], name, root) got = latest(entry, rev) + if "datasets" in entry: + if dataset not in entry["datasets"]: + raise Refused(f"--dataset{' ' + dataset if dataset else ''}: the task set {name} mixes the datasets " + f"{', '.join(entry['datasets'])}; a run is one of them, each a job of its own") + return record(entry, got, dataset), dataset if dataset and dataset != entry["dataset"]: raise Refused(f"--dataset {dataset}: the task set {name} is cut from the dataset {entry['dataset']}") return record(entry, got), entry["dataset"] @@ -545,12 +611,14 @@ def import_path(path: str, root: Optional[str] = None) -> Tuple[dict, bool]: missing = [k for k in RECORD if k not in rec] if missing: raise Refused(f"{path}: its task set's record has no {', '.join(missing)}") + mixed = isinstance(rec.get("parts"), dict) # a mixed set: the job ran one of its datasets, and keeps all incoming = {"schema": SCHEMA, "id": rec["id"], "name": rec["name"], **{k: rec[k] for k in RECORD_MORE if k in rec}, "description": "", - "benchmark": cfg["standard"].get("benchmark"), "dataset": _job_dataset(cfg), + "benchmark": cfg["standard"].get("benchmark"), + **({"datasets": list(rec["parts"])} if mixed else {"dataset": _job_dataset(cfg)}), "revisions": [{"revision": rec["revision"], "date": _now(), "note": f"from the job {cfg.get('job_name') or os.path.basename(path)}", - "units": rec["units"], "hash": rec["hash"]}]} + **({"parts": rec["parts"]} if mixed else {"units": rec["units"]}), "hash": rec["hash"]}]} elif os.path.isfile(path): incoming = _read(path) else: @@ -569,8 +637,9 @@ def import_path(path: str, root: Optional[str] = None) -> Tuple[dict, bool]: here = load(bench, name, root) if here["id"] != incoming["id"]: raise Refused(f"a task set {name!r} of {bench} with another id is here already ({target})") - if here["dataset"] != incoming["dataset"]: - raise Refused(f"the set {name} here differs in its dataset: {here['dataset']!r}, not {incoming['dataset']!r}") + if datasets_of(here) != datasets_of(incoming): + raise Refused(f"the set {name} here differs in its datasets: {', '.join(datasets_of(here))}, " + f"not {', '.join(datasets_of(incoming))}") mine, theirs = latest(here), latest(incoming) if mine["hash"] != theirs["hash"]: raise Refused(f"the set {name} holds another list here (hash {mine['hash'][:12]}, not {theirs['hash'][:12]}): " diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index ab970329e..df4f95780 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -411,24 +411,33 @@ def _matches(task: dict, words: List[str]) -> bool: return all(w in hay for w in words) +def fields(bench: dict, names: List[str]) -> Dict[str, dict]: + """Each category field of ``names`` as it reads: {FIELD: {label, names: {VALUE: name}}}, from the definition's + ``units.categories``; a field it leaves out is its key, capitalised and spaced, and a value its own word.""" + said = (bench.get("units") or {}).get("categories") or {} + return {f: {"label": (said.get(f) or {}).get("label") or f[:1].upper() + f[1:].replace("_", " "), + "names": dict((said.get(f) or {}).get("names") or {})} for f in names} + + 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: """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: {total, page, pages, of, described, tasks: [{id, title, text, categories}], - categories: {FIELD: [{value, count}, ...]}}. ``total`` counts every match, ``of`` the dataset's tasks; - each field's values are counted over the tasks the search and the other fields' filters match, the most - first. A field no task has is refused; a page past the last is empty.""" + categories: {FIELD: [{value, name, count}, ...]}, fields: {FIELD: {label, names}}}. ``total`` counts + every match, ``of`` the dataset's tasks; + each field's values are counted over the tasks the search and the other fields' filters match, numbers + in their order, words the most first. A field no task has is refused; a page past the last is empty.""" if not isinstance(page, int) or page < 1: raise Refused(f"page {page}: 1, 2, ...") got = listing(bench, dataset, options, licences) tasks, chosen = got["tasks"], categories or {} - fields = sorted({f for t in tasks for f in t["categories"]}) - unknown = [f for f in chosen if f not in fields] + 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: raise Refused(f"--category {unknown[0]}: no such category" - + (f"; the categories are {', '.join(fields)}" if fields else "; these tasks have none")) + + (f"; the categories are {', '.join(names)}" if names else "; these tasks have none")) words = [w for w in str(search or "").lower().split() if w] searched = [t for t in tasks if _matches(t, words)] @@ -436,14 +445,18 @@ def kept(t: dict, but: Optional[str] = None) -> bool: return all(t["categories"].get(f) in values for f, values in chosen.items() if f != but) matched = [t for t in searched if kept(t)] - counts = {} - for f in fields: + counts, shown = {}, fields(bench, names) + for f in names: n: Dict[str, int] = {} for t in searched: if f in t["categories"] and kept(t, but=f): n[t["categories"][f]] = n.get(t["categories"][f], 0) + 1 - counts[f] = [{"value": v, "count": c} for v, c in sorted(n.items(), key=lambda vc: (-vc[1], vc[0]))] + # numbers (a level) in their order; words the most first + order = (lambda vc: int(vc[0])) if all(v.isdigit() for v in n) else (lambda vc: (-vc[1], vc[0])) + named = shown[f]["names"] + counts[f] = [{"value": v, "name": named.get(v, v), "count": c} for v, c in sorted(n.items(), key=order)] per = size if size else max(1, len(matched)) start = (page - 1) * per return {"total": len(matched), "page": page, "pages": max(1, -(-len(matched) // per)), "of": len(tasks), - "described": got["described"], "tasks": matched[start:start + per], "categories": counts} + "described": got["described"], "tasks": matched[start:start + per], "categories": counts, + "fields": shown} diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index e22193761..af37c23ce 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -202,10 +202,17 @@ return keepTaskSets(r); } // A chosen dataset's task set, NAME, run in place of all its tasks (recipe.py: task_sets, {dataset: NAME}); - // '' for all of them. A dataset no longer chosen keeps none. + // '' 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) r.task_sets[dataset] = ref; else delete r.task_sets[dataset]; + if (!ref) { delete r.task_sets[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]; + r.datasets = [...new Set([...datasetsOf(r), ...all])]; + delete r.dataset; + for (const id of all) r.task_sets[id] = ref; return keepTaskSets(r); } function keepTaskSets(r) { diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index b10237928..0b5f3a306 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -846,7 +846,9 @@ const page = `/benchmarks/${encodeURIComponent(b.key)}/tasks/${encodeURIComponent(x.id)}`; const picked = sets.find(s => on === s.name || on.split('@')[0] === s.name); // a set made at another version of the benchmark says which: the run refuses a task that version lacks - const made = s => s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : ''; + // a set of several datasets says so: its ids here, of all it holds + const made = s => (s.version && b.version && s.version !== b.version ? ' · made at ' + s.version_label : '') + + ((s.datasets || []).length > 1 ? ` · ${s.whole} in ${s.datasets.length} datasets` : ''); const choice = sets.length + 1 > 5 ? `
{% endif %} - {% if std %} - {#- The benchmark's own task sets, its lists cut from another (subset_of), as the builder draws them; then the user's - task sets of it (standard/runner/sets.py), each with the version it was made at; and each dataset's tasks to choose from. -#} - {% set cuts = std.datasets|selectattr('subset_of')|list %}{% set wholes = std.datasets|rejectattr('subset_of')|list %} + {% if std and (task_sets or local) %} + {#- The user's task sets (standard/runner/sets.py), each with the version it was made at; New task set opens the + first dataset's tasks, whose page chooses another. -#} + {% set wholes = std.datasets|rejectattr('subset_of')|list %}
-

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

- {#- a new set is made on the page of the tasks it is cut from: one dataset's here; of several, the buttons below #} - {% if local and wholes|length == 1 %}New task set{% endif %} +

Task sets{% if task_sets %} {{ task_sets|length }}{% endif %}

+ {% if local and wholes %}New task set{% endif %}
- {% if cuts %} -

From {{ b.title }}

- - {% if task_sets %}

Yours

{% endif %} - {% endif %} {% if task_sets %}
{% set made = task_sets|selectattr('version_label')|list %} {% if made %}{% endif %}{% for s in task_sets %} - + {% if made %}{% endif %} {% endfor %}
NameDataset{{ std.units.nouns|capitalize }}Made atDate
{{ s.label }}{% if s.description %}{{ s.description }}{% endif %}{{ (std.datasets|selectattr('id', 'equalto', s.dataset)|map(attribute='label')|first) or s.dataset }}{% for d, n in s.parts.items() %}{{ (std.datasets|selectattr('id', 'equalto', d)|map(attribute='label')|first) or d }}{% if s.parts|length > 1 %} {{ n }}{{ ', ' if not loop.last }}{% endif %}{% endfor %} {{ s.units }}{{ s.version_label }}{{ s.date[:10] }}
{% endif %} -
{% endif %} diff --git a/app/templates/catalogue/tasks.html b/app/templates/catalogue/tasks.html index 208a85380..b711bef50 100644 --- a/app/templates/catalogue/tasks.html +++ b/app/templates/catalogue/tasks.html @@ -1,23 +1,25 @@ {% extends "base.html" %} {% from '_page.html' import page_head %} -{% block title %}{{ label if entry else ds.label or ds.id }} · {{ title }} — Nullius{% endblock %} -{% block crumb %}/ benchmarks / {{ bench.key }} / {{ ds.id }}{% if entry %} / {{ label }}{% endif %}{% endblock %} +{#- 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 %} +{% block crumb %}/ benchmarks / {{ bench.key }} / {% if entry %}{{ label }}{% elif heading == 'New task set' %}new task set{% else %}{{ ds.id }}{% endif %}{% endblock %} {% block head %}{% endblock %} {% block body %} {#- One page for a dataset's tasks: the browser keeps the ids ticked, the server gives a page of 100 at a time (standard/runner/units.py). Opened from a set (?set=NAME), its tasks start ticked; a set does not change, and other ticks are saved as a new set. -#} +{#- a dataset's routes are this base, its id, then listing, prepare, rows or save: the page goes from one dataset to + another in place (tasks.js) #}
+ data-nouns="{{ nouns }}" data-set="{{ entry.name if entry else '' }}" data-version="{{ version }}" + data-bench="{{ bench.key }}" data-dataset="{{ ds.id }}"> {% set mark %}{% endset %} - {% set tags %}{{ 'Task set' if entry else 'Tasks' }}{{ title }} · {{ ds.label or ds.id }}{% endset %} + {% set tags %}{{ 'Tasks' if heading == (ds.label or ds.id) else 'Task set' }}{{ title }}{% endset %} {% set actions %} - Build a run + Build a run {#- renaming and deleting ask first, in place; one question open at a time #} {% if writable and entry %}
Rename @@ -28,7 +30,7 @@
{% endif %} - {% if writable and (entry or broken) %}{% set n = rev.units|length if entry else 0 %}
+ {% if writable and (entry or broken) %}{% set n = total %}
Delete
@@ -38,15 +40,16 @@
{% endif %} {% endset %} - {{ page_head(label if entry else ds.label or ds.id, sub=tags, actions=actions, mark=mark) }} + {{ page_head(heading, sub=tags, actions=actions, mark=mark) }} {% if entry and entry.description %}

{{ entry.description }}

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

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

{% endif %} {% if problem %}

{{ problem }}

{% endif %} {% if entry %}
-
{{ nouns|capitalize }}{{ rev.units|length }}
-
Dataset{{ ds.label or ds.id }}
+
{{ nouns|capitalize }}{{ total }}
+ {% if parts|length > 1 %}
Datasets{% for d, ids in parts.items() %}{{ pages[d].label if d in pages else d }} {{ ids|length }}{{ ', ' if not loop.last }}{% endfor %}
+ {% else %}
Dataset{{ ds.label or ds.id }}
{% endif %} {% if made_at %}
Made at{{ made_at }}
{% endif %}
Date{{ rev.date[:10] }}
In commands{{ entry.name }}
@@ -54,6 +57,28 @@
{% endif %} + {#- a new set's dataset, chosen here among the benchmark's whole lists (a cut is a filter of its own); a set keeps its own #} + {% set wholes = bench.datasets|rejectattr('subset_of')|list %} + {% if not entry and (wholes|length > 1 or ds not in wholes) %} + + {% endif %} + {#- what is chosen in each dataset, the one shown pressed: the others' pages a click away (tasks.js) #} + + {#- the set's name and the way to save it, above the list: no scroll to the bottom to save #} + {% if writable %} +
+

{{ '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 #} -
- 0 chosen - - {% if writable %}{% endif %} - -
Paste ids
- +
+ {#- 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 #}
@@ -86,8 +116,13 @@
-
- + + {% endblock %} {% block scripts %}{% endblock %} diff --git a/app/tests/test_longmemeval_setups.py b/app/tests/test_longmemeval_setups.py index a1d6f7b5f..50e8d75a4 100644 --- a/app/tests/test_longmemeval_setups.py +++ b/app/tests/test_longmemeval_setups.py @@ -172,7 +172,8 @@ def test_describe_gives_question_text_and_respects_the_type_filter(self): got = self.run_driver([{"op": "units", "dataset": "longmemeval_oracle"}, {"op": "describe", "dataset": "longmemeval_oracle"}], {"question_type": kind}, questions=self.QUESTIONS) - expected = {qid: {"title": "Q?", "text": "Q?", "categories": {"question_type": category}} + expected = {qid: {"title": "Q?", "text": "Q?", "categories": { + "question_type": category, "abstention": "yes" if qid.endswith("_abs") else "no"}} for qid, category in self.QUESTIONS if kind == "all" or category == kind} self.assertEqual(got[1], {"units": expected}) self.assertEqual(list(got[1]["units"]), got[0]["units"]) diff --git a/app/tests/test_open_telco_driver.py b/app/tests/test_open_telco_driver.py index 08563109b..51e8557df 100644 --- a/app/tests/test_open_telco_driver.py +++ b/app/tests/test_open_telco_driver.py @@ -33,8 +33,9 @@ def sample(text, target, choices=None, id=None, **metadata): "teletables": [sample("t1", "C", ["a", "b", "c"], id="t_7_abc123"), sample("t2", "A", ["a", "b", "c"], id="t_9_def456")], "telemath": [sample("m1", "0.5"), sample("m2", "12.0")], "telelogs": [sample("l1", "C3")], - "3gpp_tsg": [sample("d1", "SA5")], + "3gpp_tsg": [sample("Classify the text. ###TEXT:\n{d1}", "SA5")], } +ROWS = {"telemath": [{"question": "m1", "category": "Signal Processing"}, {"question": "m2", "category": ""}]} FILES = {"teleqna": "test_teleqna.json", "teletables": "test_teletables.json", "telemath": "test_telemath.json", "telelogs": "test_telelogs.json", "3gpp_tsg": "test_3gpp_tsg.json"} @@ -89,12 +90,15 @@ def modules(self, fetch=None): model = ModuleType("inspect_ai.model") model.get_model = self.get_model model.ModelOutput = SimpleNamespace(from_content=lambda model, content: SimpleNamespace(content=content)) + dataset = ModuleType("inspect_ai.dataset") + dataset.Sample = lambda input, metadata: SimpleNamespace(input=input, metadata=metadata) + dataset.hf_dataset = lambda path, name, split, sample_fields: [sample_fields(dict(r)) for r in ROWS[name]] scorer = ModuleType("inspect_ai.scorer") scorer.value_to_float = lambda: (lambda v: 1.0 if v == "C" else 0.0) registry = ModuleType("evals._registry") evals = ModuleType("evals") evals._registry = registry - mods = {"inspect_ai": inspect_ai, "inspect_ai.model": model, "inspect_ai.scorer": scorer, + mods = {"inspect_ai": inspect_ai, "inspect_ai.model": model, "inspect_ai.scorer": scorer, "inspect_ai.dataset": dataset, "evals": evals, "evals._registry": registry} registry.__all__ = [] for name, (fn, module) in self.tasks().items(): @@ -166,6 +170,10 @@ def test_a_filter_runs_the_tasks_own_argument_and_keeps_each_questions_number(se self.assertEqual(everything.describe("teleqna-lite")["units"]["01"]["categories"], {"subject": "Lexicon"}) self.assertEqual(self.load("teletables-lite").describe("teletables-lite")["units"]["t_9_def456"], {"title": "t2", "text": "t2", "categories": {}}) + # TeleMath's category from the row the task reads; 3GPP TSG's title the document past the prompt + self.assertEqual([u["categories"] for u in self.load("telemath-lite").describe("telemath-lite")["units"].values()], + [{"category": "Signal Processing"}, {}]) + self.assertEqual(self.load("3gpp_tsg-lite").describe("3gpp_tsg-lite")["units"]["1"]["title"], "d1") self.assertIs(json.loads((FOLDER / "standard.json").read_text())["driver"]["describe"], True) def test_the_prompt_is_what_the_task_asks_its_model_and_nothing_is_written(self): diff --git a/app/tests/test_standard_sets.py b/app/tests/test_standard_sets.py index 1bd19ee0f..5bc7baa5b 100644 --- a/app/tests/test_standard_sets.py +++ b/app/tests/test_standard_sets.py @@ -71,7 +71,8 @@ def cli(self, *args): def make(self, label, text, *extra): name = sets.name_for("fakebench", label) - code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file(text), *extra) + dataset = [] if "--dataset" in extra else ["--dataset", "all"] + code, out, err = self.cli("set", "create", "fakebench", label, *dataset, "--units", self.file(text), *extra) self.assertEqual(code, 0, err) return sets.load("fakebench", name) @@ -156,7 +157,8 @@ def test_a_set_of_several_lists_from_before_reads_as_its_latest_and_is_not_rewri entry = sets.load("fakebench", "dev") self.assertEqual((sets.label_of(entry), sets.latest(entry)["units"]), ("dev", ["good", "model", "slow"])) self.assertEqual(sets.rows("fakebench"), [{"name": "dev", "label": "dev", "description": "from before", "dataset": "all", - "version": "", "units": 3, "date": "2026-11-12T10:00:00Z"}]) + "datasets": ["all"], "parts": {"all": 3}, "version": "", "units": 3, + "date": "2026-11-12T10:00:00Z"}]) code, out, err = self.cli("set", "show", "fakebench", "dev") self.assertEqual(code, 0, err) self.assertTrue(out.startswith("dev: 3 units of fakebench all\n"), out) @@ -633,6 +635,74 @@ def test_a_run_without_a_set_records_none(self): "provider", "retries", "unsandboxed", "uuid"]) +class Mixed(Scratch): + """A set of several datasets: one list of ids each, made, shown, run one dataset a job, and imported whole.""" + + run_cli = Running.run_cli + + def setUp(self): + super().setUp() + self.b["datasets"] = [*self.b["datasets"], {"id": "responding", "units": 3}] + + def mix(self): + code, out, err = self.cli("set", "create", "fakebench", "Mix", "--dataset", "all", "--units", self.file("model\nslow\n", "a.txt"), + "--dataset", "responding", "--units", self.file("good\n", "b.txt")) + self.assertEqual(code, 0, err) + self.assertIn("3 tasks of all 2, responding 1", out) + return sets.load("fakebench", "mix") + + def test_it_holds_each_datasets_ids_under_one_hash(self): + entry = self.mix() + rev = entry["revisions"][0] + self.assertEqual((entry["datasets"], "dataset" in entry, "units" in rev), (["all", "responding"], False, False)) + self.assertEqual(sets.parts(entry), {"all": ["model", "slow"], "responding": ["good"]}) + self.assertEqual(rev["hash"], sets.parts_hash("fakebench", {"responding": ["good"], "all": ["slow", "model"]})) + self.assertEqual(sets.rows("fakebench")[0]["parts"], {"all": 2, "responding": 1}) + code, out, err = self.cli("set", "show", "fakebench", "mix") + self.assertEqual(code, 0, err) + self.assertIn("mix (Mix): 3 units of fakebench all 2, responding 1", out) + self.assertIn("units of all:\n model\n slow\nunits of responding:\n good", out) + # one dataset's list is written as before: no parts + code, out, err = self.cli("set", "create", "fakebench", "One", "--dataset", "all", "--units", self.file("good\n")) + self.assertEqual(code, 0, err) + self.assertEqual(sorted(read(sets.path_of("fakebench", "one"))), ["benchmark", "dataset", "description", "id", "label", + "name", "revisions", "schema"]) + + def test_a_list_short_of_a_dataset_or_a_pair_short_of_a_file_is_refused(self): + entry = self.mix() + path = sets.path_of("fakebench", "mix") + broken = read(path) + del broken["revisions"][0]["parts"]["responding"] + with open(path, "w") as f: + json.dump(broken, f) + with self.assertRaisesRegex(sets.Refused, "holds the ids of each of its datasets"): + sets.load("fakebench", "mix") + code, out, err = self.cli("set", "create", "fakebench", "Pair", "--dataset", "all", "--dataset", "responding", + "--units", self.file("good\n")) + self.assertEqual(code, 2) + self.assertIn("--dataset D --units FILE for each dataset of the set", err) + self.assertTrue(entry) + + def test_a_run_is_one_of_its_datasets_and_its_job_keeps_the_whole_set(self): + entry = self.mix() + code, out, err = self.run_cli("--set", "mix", "--name", "none") + self.assertEqual(code, 2, out + err) + self.assertIn("refused: --dataset: the task set mix mixes the datasets all, responding", out) + code, out, err = self.run_cli("--set", "mix", "--dataset", "responding", "--name", "second") + self.assertEqual(code, 0, out + err) + cfg = read(os.path.join(self.jobs, "second", "config.json")) + self.assertEqual(cfg["datasets"], [{"name": "fakebench/responding", "n_tasks": 1}]) + rec = cfg["standard"]["task_set"] + self.assertEqual((rec["units"], rec["parts"], rec["hash"]), + (["good"], {"all": ["model", "slow"], "responding": ["good"]}, entry["revisions"][0]["hash"])) + # elsewhere, the job brings the whole set + os.remove(sets.path_of("fakebench", "mix")) + code, out, err = self.cli("set", "import", os.path.join(self.jobs, "second")) + self.assertEqual(code, 0, err) + back = sets.load("fakebench", "mix") + self.assertEqual((back["id"], sets.parts(back)), (entry["id"], sets.parts(entry))) + + class Listing(Scratch): def test_list_and_show_say_each_set_with_its_name_and_label(self): self.make("dev", "good\nmodel\n", "--description", "two of them") diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 73aa232e8..9521aab04 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -134,17 +134,24 @@ def test_one_value_two_values_of_one_field_and_two_fields_together(self): self.assertTrue(all(t["categories"] == {"kind": "alpha", "size": "small"} for t in both["tasks"])) def test_each_value_is_counted_over_the_search_and_the_other_fields_filters(self): - got = units.find(self.b, "all") - self.assertEqual(got["categories"], {"kind": [{"value": "alpha", "count": 84}, {"value": "beta", "count": 83}, - {"value": "gamma", "count": 83}], - "size": [{"value": "large", "count": 125}, {"value": "small", "count": 125}]}) - chosen = units.find(self.b, "all", categories={"kind": ["alpha"]}) + named = dict(self.b, units=dict(self.b["units"], categories={"kind": {"label": "Kind of task", "names": {"alpha": "First"}}})) + got = units.find(named, "all") + self.assertEqual(got["categories"], {"kind": [{"value": "alpha", "name": "First", "count": 84}, + {"value": "beta", "name": "beta", "count": 83}, + {"value": "gamma", "name": "gamma", "count": 83}], + "size": [{"value": "large", "name": "large", "count": 125}, + {"value": "small", "name": "small", "count": 125}]}) + self.assertEqual(got["fields"], {"kind": {"label": "Kind of task", "names": {"alpha": "First"}}, + "size": {"label": "Size", "names": {}}}) # unnamed: the key, capitalised + chosen = units.find(named, "all", categories={"kind": ["alpha"]}) # the field chosen keeps its other values' counts; the other field is counted over the alpha tasks self.assertEqual(chosen["categories"]["kind"], got["categories"]["kind"]) - self.assertEqual(chosen["categories"]["size"], [{"value": "large", "count": 42}, {"value": "small", "count": 42}]) + self.assertEqual(chosen["categories"]["size"], [{"value": "large", "name": "large", "count": 42}, + {"value": "small", "name": "small", "count": 42}]) searched = units.find(self.b, "all", search="number 24", categories={"size": ["small"]}) self.assertEqual(self.ids(searched), ["t241", "t243", "t245", "t247", "t249"]) - self.assertEqual(searched["categories"]["size"], [{"value": "large", "count": 8}, {"value": "small", "count": 5}]) + self.assertEqual(searched["categories"]["size"], [{"value": "large", "name": "large", "count": 8}, + {"value": "small", "name": "small", "count": 5}]) def test_a_field_no_task_has_is_refused(self): with self.assertRaisesRegex(units.Refused, "--category colour: no such category; the categories are kind, size"): diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index bfed0460e..3a540629d 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -105,20 +105,20 @@ def filtered(self, action): }); return elements.get(id); } -element('tasks-page').dataset = {set: 'dev', writable: 'true', listing: '/listing', rows: '/rows'}; -element('tasks-chosen-ids').textContent = '["alpha","beta"]'; +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}})); const requests = []; async function request(url) { requests.push(url); const query = new URL(url, 'http://localhost').searchParams; const found = query.has('q') ? [] : query.has('cat') ? tasks.slice(1) : tasks; - return {json: async () => url === '/rows' ? {tasks, unknown: []} + return {json: async () => url === '/t/all/rows' ? {tasks, unknown: []} : {ok: true, ready: true, total: found.length, of: 2, pages: 1, page: 1, categories: {}, described: true, tasks: found}}; } require('node:vm').runInNewContext(require('node:fs').readFileSync(process.argv[1], 'utf8'), { - document: {getElementById: element, querySelectorAll: () => [], querySelector: () => null}, + document: {getElementById: element, querySelectorAll: () => [], querySelector: () => null, addEventListener() {}}, URLSearchParams, nulliusFetch: request, setTimeout: callback => { callback(); return 1; }, clearTimeout() {} }); async function flush() { for (let n = 0; n < 20; n++) await Promise.resolve(); } @@ -133,7 +133,7 @@ def filtered(self, action): element('tasks-cats').listeners.click({target: {closest: () => ({dataset: {field: 'kind', value: 'beta'}})}}); } await flush(); - assert.equal(requests.slice(before).some(url => url === '/rows'), false); + assert.equal(requests.slice(before).some(url => url === '/t/all/rows'), false); assert.equal(element('tasks-show').attributes['aria-pressed'], 'false'); assert.equal(element('tasks-show').textContent, 'Show selected'); assert.equal(element('tasks-chosen').textContent, '2 chosen'); @@ -254,13 +254,13 @@ 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').dataset = {writable: process.argv[2], listing: '/listing', rows: '/rows'}; +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: {}}]; const request = async () => ({json: async () => ({ok: true, ready: true, total: 2, of: 2, pages: 1, page: 1, categories: {}, described: true, tasks})}); let selected = ''; require('node:vm').runInNewContext(require('node:fs').readFileSync(process.argv[1], 'utf8'), { - document: {getElementById: element, querySelectorAll: () => [], querySelector: () => null}, + document: {getElementById: element, querySelectorAll: () => [], querySelector: () => null, addEventListener() {}}, URLSearchParams, nulliusFetch: request, setTimeout: callback => { callback(); return 1; }, clearTimeout() {}, getSelection: () => ({toString: () => selected}) }); @@ -480,10 +480,27 @@ def test_an_empty_name_and_one_with_no_letter_are_refused_with_a_plain_message(s self.assertEqual(sets.revision(sets.load("described", "dev"))["units"], ["t001"]) self.assertEqual(sorted(os.listdir(self.tmp / "catalogue" / "sets" / "described")), ["dev.json"]) + def test_ids_of_several_datasets_save_one_set_whose_page_opens_each(self): + self.b["datasets"] = [*self.b["datasets"], {"id": "more", "label": "More", "units": 250}] + got = self.save({"name": "Mix", "parts": {"all": ["t001", "t002"], "more": ["t003"]}}) + self.assertEqual(got["open"], "/benchmarks/described/tasks/all?set=mix") + self.assertEqual(sets.parts(sets.load("described", "mix")), {"all": ["t001", "t002"], "more": ["t003"]}) + html = self.get("/benchmarks/described/tasks/more?set=mix").get_data(as_text=True) + self.assertEqual(json.loads(re.search(r'', html).group(1)), + {"all": ["t001", "t002"], "more": ["t003"]}) + pages = json.loads(re.search(r'', html).group(1)) + self.assertEqual([(d, x["href"]) for d, x in pages], [("all", "/benchmarks/described/tasks/all?set=mix"), + ("more", "/benchmarks/described/tasks/more?set=mix")]) + self.assertIn("Datasets all 2, More 1", visible(html)) + # a dataset the set does not hold opens the set at its first + r = self.client.get("/benchmarks/described/tasks/nowhere?set=mix"); self.addCleanup(r.close) + self.assertEqual((r.status_code, r.headers["Location"]), (302, "/benchmarks/described/tasks/all?set=mix")) + self.assertEqual(self.save({"name": "x", "parts": {"all": [], "more": []}}, 400)["error"], "Tick at least one task.") + def test_a_set_opened_keeps_its_tasks_and_other_ticks_save_a_new_set(self): self.save({"name": "dev", "units": ["t001", "t002"]}) html = self.get("/benchmarks/described/tasks/all?set=dev").get_data(as_text=True) - self.assertEqual(json.loads(re.search(r'', html).group(1)), ["t001", "t002"]) + self.assertEqual(json.loads(re.search(r'', html).group(1)), {"all": ["t001", "t002"]}) self.assertIn('data-writable="true"', html) self.assertIn("Save as a new set", html) self.assertNotIn("revision", visible(html).lower()) @@ -505,7 +522,7 @@ def test_a_set_made_before_with_several_lists_opens_as_its_latest(self): (folder / "older.json").write_text(json.dumps(entry)) before = (folder / "older.json").read_bytes() html = self.get("/benchmarks/described/tasks/all?set=older").get_data(as_text=True) - self.assertEqual(json.loads(re.search(r'', html).group(1)), ["t001", "t002"]) + self.assertEqual(json.loads(re.search(r'', html).group(1)), {"all": ["t001", "t002"]}) self.assertNotIn("revision", visible(html).lower()) self.assertEqual((folder / "older.json").read_bytes(), before) @@ -527,7 +544,8 @@ def test_the_count_and_the_way_to_save_close_the_rows(self): def bar(html): rows = html.index('id="tasks-rows"') got = re.search(r'
(.*?)
', html, re.S) - return got and (got.start() > rows and got.start() < html.index('id="tasks-save-title"'), visible(got.group(1))) + # the form above the rows, the bar that leads back to it below them + return got and (html.index('id="tasks-save-title"') < rows < got.start(), visible(got.group(1))) self.assertEqual(bar(self.get("/benchmarks/described/tasks/all").get_data(as_text=True)), (True, "0 chosen Save as task set")) self.save({"name": "dev", "units": ["t001"]}) self.assertEqual(bar(self.get("/benchmarks/described/tasks/all?set=dev").get_data(as_text=True)), (True, "0 chosen Save as a new set")) @@ -661,25 +679,27 @@ def section(self, key): self.assertIsNotNone(got) return got.group(0) - def test_a_benchmark_with_no_set_shows_each_datasets_link(self): - osw = _GET("benchmark", "osworld1") + def test_a_benchmark_with_no_set_shows_new_task_set_alone(self): part = self.section("osworld1") - for d in osw["datasets"]: - self.assertIn(f'href="/benchmarks/osworld1/tasks/{d["id"]}"', part) + self.assertEqual(visible(part), "Task sets New task set") # no count, no table, no dataset's link self.assertNotIn("', part) + first = telco["datasets"][0]["id"] # several datasets: the first's tasks, whose page chooses another + self.assertIn(f'New task set', part) + page = self.get(f"/benchmarks/open-telco/tasks/{first}").get_data(as_text=True) + choice = re.search(r'', page, re.S).group(1) + self.assertEqual(re.findall(r'value="([^"]+)"', choice), [d["id"] for d in telco["datasets"]]) + self.assertIn(f'value="{first}" selected', choice) + self.assertNotIn('id="tasks-dataset"', self.get("/benchmarks/humaneval/tasks/humaneval").get_data(as_text=True)) [only] = _GET("benchmark", "humaneval")["datasets"] one = self.section("humaneval") # one dataset: the button is its link self.assertIn(f'New task set', one) self.assertNotIn("bench-newset", one) r = self.client.get("/benchmarks/humaneval", headers={"X-Forwarded-For": "192.0.2.4"}); self.addCleanup(r.close) - self.assertNotIn("New task set", r.get_data(as_text=True)) # saving is a browser's on the application host + self.assertNotIn('id="task-sets"', r.get_data(as_text=True)) # saving is a browser's on the application host def test_it_lists_the_benchmarks_sets_with_the_version_each_was_made_at(self): osw = _GET("benchmark", "osworld1") @@ -687,8 +707,7 @@ def test_it_lists_the_benchmarks_sets_with_the_version_each_was_made_at(self): earlier = _GET("benchmark", "osworld1@044bc33") sets.create(earlier, "Chrome tabs", dataset="test_nogdrive", units=["a"]) text = visible(self.section("osworld1")) - own = len([d for d in osw["datasets"] if d.get("subset_of")]) # the benchmark's own sets, counted too - self.assertIn(f"Task sets {2 + own}", text) + self.assertIn("Task sets 2 New task set", text) # the user's sets alone are counted self.assertNotIn("Revision", text) label = next(d.get("label") or d["id"] for d in osw["datasets"] if d["id"] == "test_nogdrive") self.assertRegex(text, re.escape(f"Chrome tabs four of them {label} 4 {osw['_version']} ") + r"\d{4}-\d\d-\d\d") @@ -698,34 +717,22 @@ def test_it_lists_the_benchmarks_sets_with_the_version_each_was_made_at(self): class TheBenchmarksOwnSets(Case): - """A benchmark whose lists name the one they are cut from: its page and the builder draw one dataset, and its cuts as - the benchmark's own task sets, before the user's.""" + """A benchmark whose lists name the one they are cut from: its page and the builder draw one dataset; its cuts + stay datasets, never task sets.""" def section(self, key): html = self.get(f"/benchmarks/{key}").get_data(as_text=True) return re.search(r'
', html, re.S).group(0) - def test_the_page_lists_its_own_sets_then_the_users_and_one_dataset_to_cut_from(self): + def test_its_cuts_are_datasets_and_new_task_set_opens_the_whole_list(self): osw = _GET("benchmark", "osworld1") cuts = [d for d in osw["datasets"] if d.get("subset_of")] part = self.section("osworld1") - text = visible(part) - self.assertIn(f"Task sets {len(cuts)}", text) - self.assertIn("From OSWorld1", text) - for d in cuts: - self.assertIn(f'href="/benchmarks/osworld1/tasks/{d["id"]}"', part) - self.assertIn(f"{d['label']} · {d['units']} tasks", text) - self.assertNotIn("Yours", text) - # New task set opens the whole list's tasks: one dataset, no menu + for d in cuts: # in the Dataset section above, not again as task sets + self.assertNotIn(f'href="/benchmarks/osworld1/tasks/{d["id"]}"', part) self.assertIn('New task set', part) - self.assertNotIn("bench-newset", part) sets.create(osw, "Chrome tabs", dataset="test_nogdrive", units=["a", "b"]) - text = visible(self.section("osworld1")) - self.assertIn(f"Task sets {len(cuts) + 1}", text) - self.assertLess(text.index("From OSWorld1"), text.index("Yours")) - self.assertLess(text.index("Yours"), text.index("Chrome tabs")) - # a benchmark that declares nothing is drawn as before - self.assertNotIn("From ", visible(self.section("open-telco"))) + self.assertIn("Task sets 1 New task set", visible(self.section("osworld1"))) def node_program(self, body): node = shutil.which("node") @@ -887,6 +894,26 @@ def test_build_a_run_carries_the_dataset_and_the_open_set(self): check=True, capture_output=True, text=True, timeout=10) self.assertEqual(json.loads(result.stdout), ["described", ["more"], task_sets]) + def test_a_set_of_several_datasets_is_chosen_for_each_of_them(self): + node = shutil.which("node") + if not node: + self.skipTest("Node is required for the recipe core") + import subprocess + self.b["datasets"].append({"id": "more", "units": 250}) + sets.create(self.b, "mix", parts={"all": ["t001", "t002"], "more": ["t003"]}) + html = self.get("/new-run").get_data(as_text=True) + schema = json.loads(re.search(r'', html, re.S).group(1)) + page = recipe._bench_page(self.b) + self.assertEqual([(s["units"], s["whole"]) for d in page["datasets"] for s in d["sets"]], [(2, 3), (1, 3)]) + schema["standard"]["benchmarks"].append(page) + 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.createStandard('described');r.datasets=['all'];C.setTaskSet(r,'all','mix');\n" + "const both=[r.datasets,r.task_sets];C.setTaskSet(r,'more','');\n" + "process.stdout.write(JSON.stringify({both,after:r.task_sets}));") + got = json.loads(subprocess.run([node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + self.assertEqual(got, {"both": [["all", "more"], {"all": "mix", "more": "mix"}], "after": {"all": "mix"}}) + def test_task_sets_follow_the_chosen_datasets(self): node = shutil.which("node") if not node: diff --git a/app/web/catalogue.py b/app/web/catalogue.py index ecd7034c6..71e086068 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -192,13 +192,19 @@ def benchmark_tasks(key, dataset): except sets.Refused as e: # said without the file's path; a file there that cannot be read can still be deleted from the page problem, broken = sets.plain(e, key, name), "" if isinstance(e, sets.NotFound) else name - if entry is not None and entry["dataset"] != dataset: - return redirect(url_for("benchmark_tasks", key=key, dataset=entry["dataset"], set=entry["name"])) + if entry is not None and dataset not in sets.datasets_of(entry): + return redirect(url_for("benchmark_tasks", key=key, dataset=sets.datasets_of(entry)[0], set=entry["name"])) if entry is not None and entry.get("version") and not version and standard_definitions.get("benchmark", f"{key}@{entry['version']}"): version = entry["version"] # its tasks as listed at the version it was made at bench, ds = _std_dataset(key, dataset, version) + rev = sets.latest(entry) if entry else None + # each dataset's page, for the chosen of each (a set's own, or a new one's): the set's at each of its datasets + pages = {d["id"]: {"label": d.get("label") or d["id"], + "href": url_for("benchmark_tasks", key=key, dataset=d["id"], set=entry["name"] if entry else None, + version=None if entry else (version or None))} for d in bench["datasets"]} return render_template("catalogue/tasks.html", bench=bench, title=standard_definitions.title(bench), - ds=ds, entry=entry, rev=sets.latest(entry) if entry else None, problem=problem, + ds=ds, entry=entry, rev=rev, problem=problem, parts=sets.parts(entry, rev) if entry else {}, + total=sets.size(entry, rev) if entry else 0, pages=pages, label=sets.label_of(entry) if entry else "", version=standard_definitions.version_of(bench) or "", made_at=sets.version_label(bench, entry["version"]) if entry and entry.get("version") else "", broken=broken, nouns=(bench.get("units") or {}).get("nouns", "units"), @@ -231,8 +237,10 @@ def benchmark_tasks_listing(key, dataset): ids, seed = units.draw(ids, n, seed) 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, - page=int(page) if page.isdigit() and int(page) >= 1 else 1) + 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) except units.Refused as e: return jsonify(ok=False, error=str(e)), 400 return jsonify(ok=True, ready=True, **got) @@ -301,27 +309,30 @@ def _set_problem(key: str, name: str) -> str: @app.route("/benchmarks//tasks//save", methods=["POST"]) def benchmark_tasks_save(key, dataset): - """Keep the ticked ids as a new task set ({name, description, units, version}), at the version the page listed: - the name typed is its label, and the name commands take is made from it. A set is never changed: the page of - one saves another.""" + """Keep the ticked ids as a new task set ({name, description, parts: {dataset: ids}, version}), at the version + the page listed: the name typed is its label, and the name commands take is made from it. Ids of several + datasets make a set of each, one of them its list. A set is never changed: the page of one saves another.""" shared._require_csrf() if not shared._local_client(): abort(403, description="Task sets are saved from a browser on the application host only.") body = request.get_json(silent=True) or {} bench, _ = _std_dataset(key, dataset, str(body.get("version") or "")) - ids = [u for u in body.get("units") or [] if isinstance(u, str)] - if not ids: + given = body.get("parts") if isinstance(body.get("parts"), dict) else {dataset: body.get("units")} + parts = {str(d): [u for u in ids if isinstance(u, str)] for d, ids in given.items() if isinstance(ids, list)} + parts = {d: ids for d, ids in parts.items() if ids} + if not parts: return jsonify(ok=False, error="Tick at least one task."), 400 label = str(body.get("name") or "").strip() problem = _set_problem(key, label) if problem: return jsonify(ok=False, error=problem), 400 try: - entry = sets.create(bench, label, dataset=dataset, units=ids, description=str(body.get("description") or "").strip(), + entry = sets.create(bench, label, parts=parts, description=str(body.get("description") or "").strip(), note=str(body.get("note") or "")) except sets.Refused as e: return jsonify(ok=False, error=str(e)), 400 - return jsonify(ok=True, name=entry["name"], open=url_for("benchmark_tasks", key=key, dataset=dataset, set=entry["name"])) + shown = dataset if dataset in parts else next(iter(parts)) + return jsonify(ok=True, name=entry["name"], open=url_for("benchmark_tasks", key=key, dataset=shown, set=entry["name"])) def _set_guard(key: str, dataset: str) -> str: @@ -351,7 +362,7 @@ def benchmark_tasks_rename(key, dataset): flash(sets.plain(e, key, name), "error") return redirect(url_for("benchmark_tasks", key=key, dataset=dataset, set=name)) flash(f"Renamed {was} to {entry['label']}. Runs made from it follow the new name.", "ok") - return redirect(url_for("benchmark_tasks", key=key, dataset=entry["dataset"], set=entry["name"])) + return redirect(url_for("benchmark_tasks", key=key, dataset=dataset, set=entry["name"])) @app.route("/benchmarks//tasks//delete", methods=["POST"]) diff --git a/app/web/runs.py b/app/web/runs.py index f55d6379e..4266453db 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -659,7 +659,9 @@ def _set_link(j) -> dict: entry = task_sets.by_id(ts["benchmark"], ts.get("id"), ts["name"]) if ts.get("benchmark") else None if entry is None: return {"name": ts.get("label") or ts["name"], "link": ""} - return {"name": task_sets.label_of(entry), "link": url_for("benchmark_tasks", key=ts["benchmark"], dataset=entry["dataset"], + held = task_sets.datasets_of(entry) # of a set of several datasets, the one the job ran + shown = j.dataset.rpartition("/")[2] if j.dataset.rpartition("/")[2] in held else held[0] + return {"name": task_sets.label_of(entry), "link": url_for("benchmark_tasks", key=ts["benchmark"], dataset=shown, set=entry["name"])} diff --git a/docs/cli/task-sets.md b/docs/cli/task-sets.md index 6c2f8ef7f..0ed952f87 100644 --- a/docs/cli/task-sets.md +++ b/docs/cli/task-sets.md @@ -1,17 +1,18 @@ # Task sets -A named list of one dataset's units, frozen once made, that a run names and its job records. +A named list of one or several datasets' units, frozen once made, that a run names and its job records. ```bash title="Commands" nullius standard units --dataset D [--bench-option NAME=VALUE]... [--search TEXT] [--category FIELD=VALUE]... [--json] nullius standard set create [@version] "WORDS" [--dataset D] (--units FILE | --search TEXT | --category FIELD=VALUE... \ | --sample N [--seed S] | --from-job JOB_DIR [--outcome O,...]... [--unit ID]...) [--description TEXT] +nullius standard set create [@version] "WORDS" (--dataset D --units FILE)... [--description TEXT] nullius standard set list [] [--json] nullius standard set show NAME [--json] nullius standard set rename NAME "WORDS" nullius standard set delete NAME nullius standard set import PATH -nullius standard run --set NAME ... +nullius standard run --set NAME [--dataset D] ... ``` ```bash title="Examples" @@ -19,6 +20,8 @@ nullius standard units osworld1 --dataset test_nogdrive --search tab --category nullius standard set create humaneval "first ten" --dataset humaneval --units ten.txt nullius standard set create humaneval misses --from-job jobs_standard/JOB --outcome failed,infra nullius standard set create gaia twenty --dataset gaia-validation --sample 20 --seed 7 +nullius standard set create open-telco mix --dataset teleqna-lite --units qna.txt --dataset telemath-lite --units math.txt +nullius standard run open-telco original --model M --set mix --dataset telemath-lite nullius standard run humaneval reference --model gpt-5-mini --set first-ten --unsandboxed ``` @@ -35,7 +38,9 @@ nullius standard run humaneval reference --model gpt-5-mini --set first-ten --un | Its name | Up to 80 characters with a letter or a digit; commands take its slug. | | `--from-job` | The units a standard job ran, or only those of `--outcome`'s outcomes and each `--unit`. | | `import` | Adds an entry, or a job's set; another id under that name is refused. | +| Several datasets | Each `--dataset D --units FILE` a part; one hash over all. The page keeps ticks per dataset until saved. | | A run | Takes the set's dataset and units; another `--dataset`, `--units` or an unlisted id is refused. | +| A run of several | `--dataset` picks one part, a job of its own; the builder runs each. The job records the whole set. | | Another version | Refused before any unit when the run's dataset lacks one of the set's tasks. | | The record | `config.json` keeps `standard.task_set`: the set's id, name, hash, units and version. | | On a host | The app sends a recipe's sets with the runner; by hand, copy or `import` the entry. | diff --git a/docs/standard.md b/docs/standard.md index 891f88e5a..7623a353c 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -459,6 +459,7 @@ An `answer` or `score` error that begins `EnvironmentSetupError: `, `VerifierErr | `limits.attempts` | How the upstream tells attempts apart; the driver is then sent `attempt` with `setup`, `turn` and `answer` | | `limits.scored_cuts` | The cuts after which an agent's unit is still scored: `time`, `calls`, `end` ([a unit cut at a limit](cli/run.md#a-unit-cut-at-a-limit)) | | `units.redistribute` | `false` when the data may not be redistributed: `cli prove` then records no unit id | +| `units.categories` | `{FIELD: {label, names: {VALUE: name}}}`: how `describe`'s categories read on a listing; `--category` still takes the value | !!! note "Call the upstream, never copy it" The driver imports the upstream from `$NULLIUS_UPSTREAM` and calls its loader, prompts, scorer, judge and loop. Never patch its bugs: say it in the limitations; a fix is a fork's, brought in as a [version](#versions). From 0212f59791b3086e704029e3b3c06b508a5cbddd Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Fri, 27 Nov 2026 01:08:23 +0100 Subject: [PATCH 37/37] fix(standard): listings use the Hugging Face mirror, and the review's other points - A listing's driver gets HF_ENDPOINT, as a run's does - Two lists cut from one list (GAIA's levels) in one recipe: the builder keeps the first, compile refuses them - The tasks page: a seed beside Pick at random, refusals in the page's words, no line on starting the driver - tau3-bench's persona None is named No persona - The background listing's error is written under its lock; an unused variable gone; the GAIA driver test restores its rows --- .../benchmarks/tau3-bench/standard.json | 3 ++- app/nullius/standard/pages/recipe.py | 5 ++++ app/nullius/standard/runner/units.py | 2 +- app/static/builder/command-builder-core.js | 4 ++- app/static/catalogue/tasks.js | 4 ++- app/templates/catalogue/tasks.html | 2 +- app/tests/test_dataset_subsets.py | 8 ++++++ app/tests/test_gaia_driver.py | 6 ++--- app/tests/test_standard_units_listing.py | 9 +++++++ app/ui_tests/test_task_set_pages.py | 13 +++++++--- app/web/catalogue.py | 25 +++++++++++++++---- 11 files changed, 65 insertions(+), 16 deletions(-) diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/standard.json b/app/nullius/catalogue/benchmarks/tau3-bench/standard.json index 133c5a693..f2266a2ae 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/standard.json +++ b/app/nullius/catalogue/benchmarks/tau3-bench/standard.json @@ -92,7 +92,8 @@ } }, "persona": { - "label": "Persona" + "label": "Persona", + "names": {"None": "No persona"} } } }, diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 69029def4..5c0cb317b 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -470,6 +470,11 @@ def add(step, message, shown=False, field=None, unset=False): dss = [x for x in b["datasets"] if x["id"] in wanted] dss.sort(key=lambda x: wanted.index(x["id"])) unknown = [x for x in wanted if x not in {y["id"] for y in b["datasets"]}] + # lists cut from one list (subset_of) overlap: one of them a run, as the builder draws one of each + whole = {x["id"]: x.get("subset_of") or x["id"] for x in dss} + twice = [x for x in dss if [whole[y["id"]] for y in dss].count(whole[x["id"]]) > 1] + if twice: + add("dataset", f"{' and '.join(x.get('label') or x['id'] for x in twice)} share their tasks: choose one of them.") if not dss or unknown: add("dataset", f"Choose one or more of {b['label']}'s datasets" + (f" ({', '.join(unknown)} is not one)" if unknown else "") + ".") # a chosen dataset's task set (``task_sets``: {dataset: NAME}), run in place of all its tasks; a recipe from diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py index df4f95780..33006a478 100644 --- a/app/nullius/standard/runner/units.py +++ b/app/nullius/standard/runner/units.py @@ -263,7 +263,7 @@ def _start(bench: dict, ds: dict, values: dict, work: str, licences=None) -> jso "NULLIUS_UPSTREAM": up or "", "NULLIUS_DATASET": data or "", "NULLIUS_DATASET_ID": ds["id"], "PYTHONPATH": run.driver_path(), "PYTHONDONTWRITEBYTECODE": "1", "NULLIUS_VERSION": str(bench.get("_version") or ""), - **run.option_env(values)}) + **run.option_env(values), **run.data_env()}) # the Hugging Face mirror, as a run's try: args = (cmd, cwd, env, os.path.join(work, "driver.log")) return (_ListingProc(*args, credentials) if credentials else jsonl.Proc(*args)).start() diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index af37c23ce..b446a373c 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -225,7 +225,9 @@ const r = createStandard(typeof raw.benchmark === 'string' ? raw.benchmark : ''); for (const key of ['name', 'title', 'model', 'where', 'model_choice']) if (typeof raw[key] === 'string') r[key] = raw[key]; const sets = Array.isArray(raw.datasets) ? raw.datasets.filter(k => typeof k === 'string') : typeof raw.dataset === 'string' && raw.dataset ? [raw.dataset] : null; - if (sets && sets.length) r.datasets = [...new Set(sets)]; + // lists cut from one list overlap: a recipe naming two keeps the first (the builder draws one of each) + 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); } 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)]; diff --git a/app/static/catalogue/tasks.js b/app/static/catalogue/tasks.js index a75dbf4e7..61c001741 100644 --- a/app/static/catalogue/tasks.js +++ b/app/static/catalogue/tasks.js @@ -227,11 +227,13 @@ // kept in the set's note while the chosen are the ones drawn $('tasks-pick-go')?.addEventListener('click', async () => { let got; - try { got = await (await nulliusFetch(query({ids: 1, sample: $('tasks-n').value.trim()}))).json(); } + const seed = ($('tasks-seed') || {}).value?.trim(); // set create --seed: the same seed, the same draw + try { got = await (await nulliusFetch(query({ids: 1, sample: $('tasks-n').value.trim(), ...(seed ? {seed} : {})}))).json(); } catch { return window.nulliusNotify?.('The tasks could not be drawn. Reload the page.', {error: true}); } if (!got.ok || !got.ready) return window.nulliusNotify?.(got.error || 'The list is not ready.', {error: true}); chosen.clear(); got.ids.forEach(id => chosen.add(id)); drawn = {ids: new Set(got.ids), seed: got.seed, note: got.note}; + 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(); }); diff --git a/app/templates/catalogue/tasks.html b/app/templates/catalogue/tasks.html index b711bef50..3f151a8ef 100644 --- a/app/templates/catalogue/tasks.html +++ b/app/templates/catalogue/tasks.html @@ -97,7 +97,7 @@

{{ 'Save as a new set' if entry else 'Save as task set {#- the ways to choose, then what is chosen #}
- {% if writable %}{% endif %} + {% if writable %}{% endif %}
Paste ids
diff --git a/app/tests/test_dataset_subsets.py b/app/tests/test_dataset_subsets.py index 1a7fd99da..2fabbbba7 100644 --- a/app/tests/test_dataset_subsets.py +++ b/app/tests/test_dataset_subsets.py @@ -73,6 +73,14 @@ def test_a_run_still_names_the_list_it_runs(self): self.assertEqual(out["errors"], [], out["errors"]) self.assertIn("--dataset test_nogdrive ", out["shards"][0]["command"]) self.assertEqual(next(r for r in out["review"] if r[1] == "Dataset")[2], "Without Google Drive · 361 tasks") + # two lists of one family share their tasks: refused, the builder drawing one of each + gaia = definitions.get("benchmark", "gaia") + out = recipe.compile({"version": 1, "harness": "standard", "name": "g", "title": "t", "benchmark": "gaia", + "datasets": ["gaia-validation-level1", "gaia-validation-level2"], "others": ["nop"], + "provider": "openai", "model": "", "where": "local", "concurrency": 1}, + {"benchmark": [gaia], "agent": [], "capability": []}) + self.assertIn("Validation · Level 1 and Validation · Level 2 share their tasks: choose one of them.", + [e["message"] for e in out["errors"]]) if __name__ == "__main__": diff --git a/app/tests/test_gaia_driver.py b/app/tests/test_gaia_driver.py index c0e451d27..fef555c0e 100644 --- a/app/tests/test_gaia_driver.py +++ b/app/tests/test_gaia_driver.py @@ -162,14 +162,14 @@ def test_units_and_describe_name_only_selected_split_and_oracle_exposes_referenc self.assertEqual(self.driver.units(DATASET), {"units": ["fixture-task"]}) with self.assertRaisesRegex(ValueError, "differs"): self.driver.units("gaia-validation") - self.driver.ROWS["second-task"] = dict(self.row, task_id="second-task", Question="How many?", Level="1") - self.assertEqual(self.driver.describe(DATASET), {"units": { + with patch.dict(self.driver.ROWS, {"second-task": dict(self.row, task_id="second-task", Question="How many?", Level="1")}): + described = self.driver.describe(DATASET) + self.assertEqual(described, {"units": { "fixture-task": {"title": self.row["Question"], "text": self.row["Question"], "categories": {"level": "1"}}, "second-task": {"title": "How many?", "text": "How many?", "categories": {"level": "1"}}}}) with self.assertRaisesRegex(ValueError, "differs"): self.driver.describe("gaia-validation") self.assertIs(json.loads((DRIVER.parent / "standard.json").read_text())["driver"]["describe"], True) - del self.driver.ROWS["second-task"] result = self.driver.oracle("fixture-task", str(self.workspace)) self.assertEqual(result["answer"], "FINAL ANSWER: synthetic-reference") self.assertEqual((self.workspace / ".gaia-oracle-answer.txt").read_text(), "synthetic-reference") diff --git a/app/tests/test_standard_units_listing.py b/app/tests/test_standard_units_listing.py index 9521aab04..f7f5d6d9d 100644 --- a/app/tests/test_standard_units_listing.py +++ b/app/tests/test_standard_units_listing.py @@ -37,6 +37,8 @@ if os.environ.get("HF_TOKEN"): # a licence bound for the driver, as the listing gave it with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "given"), "w") as f: f.write(os.environ["HF_TOKEN"]) +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "endpoint"), "w") as f: + f.write(os.environ.get("HF_ENDPOINT", "")) # where its downloads go KINDS = ("alpha", "beta", "gamma") N = 20 if os.environ.get("NULLIUS_OPTION_MODE") == "short" else 250 IDS = [f"t{i:03d}" for i in range(N)] @@ -417,6 +419,13 @@ def given(self): path = Path(self.b["_here"], "given") return path.read_text() if path.exists() else None + def test_the_driver_downloads_from_the_mirror_a_run_would(self): + with mock.patch.dict(os.environ, {"HF_ENDPOINT": "https://hf-mirror.example.org/"}): + units.listing(self.b, "all") + self.assertEqual(Path(self.b["_here"], "endpoint").read_text(), "https://hf-mirror.example.org") + units.listing(dict(self.b, options={}), "all") # the default: none set + self.assertEqual(Path(self.b["_here"], "endpoint").read_text(), "") + def test_the_driver_gets_its_licence_and_none_held_is_refused_before_it_starts(self): self.b = gated(self.b) env = {k: v for k, v in os.environ.items() if k != "HF_TOKEN"} diff --git a/app/ui_tests/test_task_set_pages.py b/app/ui_tests/test_task_set_pages.py index 3a540629d..65ff4059c 100644 --- a/app/ui_tests/test_task_set_pages.py +++ b/app/ui_tests/test_task_set_pages.py @@ -202,7 +202,7 @@ def test_pick_at_random_draws_as_set_create_sample_does_and_the_set_keeps_its_se self.assertEqual(got["note"], "matched by --category kind=alpha; drawn by --sample 5 --seed 7") drawn = self.listing(ids=1, sample=5) # no seed: one drawn, and given self.assertEqual(drawn["ids"], units.draw([f"t{i:03d}" for i in range(250)], 5, drawn["seed"])[0]) - for sample, said in (("251", "--sample 251: the list holds 250"), ("x", "--sample x: a whole number from 1")): + for sample, said in (("251", "251 at random: the list holds 250."), ("x", "x at random: a whole number from 1.")): r = self.client.get(f"/benchmarks/described/tasks/all/listing?ids=1&sample={sample}"); self.addCleanup(r.close) self.assertEqual((r.status_code, r.get_json()["error"]), (400, said)) self.post("/benchmarks/described/tasks/all/save", {"name": "five", "units": got["ids"], "note": got["note"]}) @@ -218,13 +218,13 @@ def test_invalid_sample_and_seed_numbers_are_refused(self): self.addCleanup(r.close) self.assertEqual(r.status_code, 400) self.assertEqual(r.get_json(), {"ok": False, - "error": f"--{field} {word}: a whole number from {minimum}"}) + "error": (f"{word} at random" if field == "sample" else f"Seed {word}") + f": a whole number from {minimum}."}) def test_an_unknown_category_is_refused_plainly(self): units.listing(self.b, "all") r = self.client.get("/benchmarks/described/tasks/all/listing?cat=colour=red"); self.addCleanup(r.close) self.assertEqual(r.status_code, 400) - self.assertIn("no such category", r.get_json()["error"]) + self.assertTrue(r.get_json()["error"].startswith("Category colour: no such category"), r.get_json()["error"]) def test_the_rows_of_chosen_ids_say_which_the_listing_does_not_hold(self): units.listing(self.b, "all") @@ -770,6 +770,13 @@ def test_the_builder_draws_all_of_it_the_benchmarks_own_sets_then_the_users(self self.assertEqual(re.findall(r'aria-pressed="true"[^>]*>.*?(.*?)', got["mine"]), ["Chrome tabs"]) self.assertEqual((got["whole"]["datasets"], got["whole"].get("task_sets")), (["test_all"], None)) + def test_a_saved_recipe_of_two_lists_of_one_family_keeps_the_first(self): + got = self.node_program( + "const r=C.fromJSON({version:1,harness:'standard',benchmark:'gaia',others:['original']," + "datasets:['gaia-validation-level1','gaia-validation-level2'],task_sets:{'gaia-validation-level2':'x'}});" + "process.stdout.write(JSON.stringify({datasets:r.datasets,sets:r.task_sets||null}));") + self.assertEqual(got, {"datasets": ["gaia-validation-level1"], "sets": None}) + def test_a_benchmark_that_declares_nothing_is_drawn_as_before(self): got = self.node_program("const b=C.standardBench(C.createStandard('open-telco'));" "process.stdout.write(JSON.stringify({nested:C.nestedDatasets(b),n:b.datasets.length}));") diff --git a/app/web/catalogue.py b/app/web/catalogue.py index 71e086068..50e4e96ec 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -109,7 +109,7 @@ def benchmark_page(key): data={d.key: sources.of(d, b.harness, std_def, only=len(vds) == 1) for d in vds}, current=(x["version"] == v) if v else x["default"], **(_proven(page) if page else {}))) shown = next(x for x in views if x["current"]) - std, ds, data = shown["std"], cat.datasets_of(b), shown["data"] + std, data = shown["std"], shown["data"] versions = views if len(views) > 1 else [] jobs = {j.job_id for j in shared._jobs_for_request()} if std else set() # the user's sets, each with the version it was made at as this benchmark's definition names it @@ -172,7 +172,7 @@ def _listing_state(bench: dict, dataset: str) -> dict: say = f"The list of {nouns} cannot be made here: {got['reason']}. Ids can still be pasted." elif got["state"] == "full" and not got["preparing"]: say = f"List the {nouns} to choose from, or paste their ids." - about = f"Listing fetches {fetched}." if fetched else "Listing starts the benchmark's driver on this machine." + about = f"Listing fetches {fetched}." if fetched else "" else: say = f"Preparing the list of {nouns}" + (f": fetching {fetched}." if fetched else ".") + " Ids can be pasted meanwhile." return dict(got, say=say, about=about, link=link) @@ -234,7 +234,10 @@ def benchmark_tasks_listing(key, dataset): return jsonify(ok=True, ready=True, total=got["total"], ids=ids) # Pick N at random: N of the matches, drawn as set create --sample draws them, its seed in the note n, seed = (_whole(request.args.get(k)) for k in ("sample", "seed")) - ids, seed = units.draw(ids, n, seed) + try: + ids, seed = units.draw(ids, n, seed) + except units.Refused as e: # said in the page's words, not the command's flags + return jsonify(ok=False, error=_page_words(e)), 400 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 @@ -242,10 +245,21 @@ def benchmark_tasks_listing(key, dataset): 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) except units.Refused as e: - return jsonify(ok=False, error=str(e)), 400 + return jsonify(ok=False, error=_page_words(e)), 400 return jsonify(ok=True, ready=True, **got) +def _page_words(e: Exception) -> str: + """A refusal of ``units`` as the page says it, its flag the page's word: ``--sample 900: the list holds 165`` as + ``900 at random: the list holds 165.``, ``--seed 7`` as ``Seed 7``, ``--category kind`` as ``Category kind``.""" + said = str(e) + for flag, word in (("--sample ", "{} at random"), ("--seed ", "Seed {}"), ("--category ", "Category {}")): + if said.startswith(flag): + value, _, rest = said[len(flag):].partition(":") + said = word.format(value) + ":" + rest + return said.rstrip(".") + "." + + def _whole(word): """A number the page sent as a whole number, else the text itself, for ``units.draw`` to refuse; None for none.""" if word is None or word == "": @@ -274,7 +288,8 @@ def make(): try: units.listing(bench, dataset) except (units.Refused, OSError) as e: - _PREPARING[identity]["error"] = str(e) + with _PREPARING_LOCK: + _PREPARING[identity]["error"] = str(e) with _PREPARING_LOCK: job = _PREPARING.get(identity) if not (job and job["thread"].is_alive()):