diff --git a/app/nullius/catalogue/benchmarks/gaia/driver.py b/app/nullius/catalogue/benchmarks/gaia/driver.py index ddc82fe68..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"}'} @@ -184,6 +190,40 @@ 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 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 {}), **{n: row[place[unit]].get(n) for n in fields}} + text = text_of(s) + 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} + + def sample_id(unit): return unit if isinstance(numbered()[unit].id, str) else int(unit) @@ -238,7 +278,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 1f651f5bf..8787f78f8 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" @@ -112,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/driver.py b/app/nullius/catalogue/benchmarks/osworld1/driver.py index 709c1aead..67695c65c 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/driver.py +++ b/app/nullius/catalogue/benchmarks/osworld1/driver.py @@ -9,6 +9,8 @@ units - every task of the dataset (one of the upstream's evaluation_examples/test_*.json), as domain__id, in the file's order +describe - each task's instruction (its title the first words) and its domain, + from the task's file alone setup - the task's instruction, for the null control. For an agent (participant "agent", which the definition's driver.participant asks Nullius to send): runner.py started in the trial's @@ -164,6 +166,19 @@ def units(dataset=None, setup=None): return {"units": [f"{d}__{e}" for d, ids in meta.items() for e in ids]} +def describe(dataset=None, **_): + """Each task of the dataset from its file alone: the instruction as its text (its title the first words), + its domain as a category.""" + out = {} + for unit in units()["units"]: + domain, _eid, example = _task(unit) + text = str(example.get("instruction") or "") + line = " ".join(text.split()) + title = line if len(line) <= 100 else line[:100].rsplit(" ", 1)[0] + " ..." + out[unit] = {"title": title, "text": text, "categories": {"domain": domain}} + return {"units": out} + + def setup(unit, dir, participant=None, **_): until = time.time() + SETUP_SECONDS - REAP_SECONDS - REMOVE_SECONDS - ANSWER_SECONDS # an agent's setup's own instruction = _task(unit)[2]["instruction"] @@ -856,7 +871,8 @@ def score(unit, dir, transcript=None, answer=None, setup=None, **_): return _scored(where, "nop.py, DesktopEnv.evaluate") -HANDLERS = {"units": units, "setup": setup, "task_given": task_given, "answer": answer, "score": score, "end": end} +HANDLERS = {"units": units, "describe": describe, "setup": setup, "task_given": task_given, "answer": answer, + "score": score, "end": end} def main(): diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 684ffbc73..bb7ec514f 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -28,6 +28,14 @@ }, "participant": true, "unit_end": true, + "describe": true, + "list_command": [ + "python3", + "{here}/driver.py", + "{here}/agents.json", + "{here}/nop.py", + "{here}/runner.py" + ], "task_given": true }, "mcp_servers": { @@ -50,6 +58,7 @@ { "id": "test_nogdrive", "label": "Without Google Drive", + "subset_of": "test_all", "summary": "The upstream's test_nogdrive.json: every task but the 8 that need a Google account's credentials.", "path": "evaluation_examples/test_nogdrive.json", "sha256": "fcb9497e93a8986407345d3012c872c9c2fed253420730fbea64ccfcace67dbb", @@ -66,6 +75,7 @@ { "id": "test_small", "label": "Small", + "subset_of": "test_all", "summary": "The upstream's test_small.json: a few tasks of each domain.", "path": "evaluation_examples/test_small.json", "sha256": "bb29275171b78728d71825b125af311d74e66bb2a6d693c45c497d380b1fc640", @@ -74,6 +84,7 @@ { "id": "test_infeasible", "label": "Infeasible", + "subset_of": "test_all", "summary": "The upstream's test_infeasible.json: tasks that cannot be done, passed by answering FAIL.", "path": "evaluation_examples/test_infeasible.json", "sha256": "1b447d0462b1bdac4b660e0dd6e6add6d01c17a9e684702c701abcffda409abb", @@ -82,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", @@ -264,6 +292,7 @@ { "id": "test_nogdrive", "label": "Without Google Drive", + "subset_of": "test_all", "summary": "The upstream's test_nogdrive.json: every task but the 8 that need a Google account's credentials. The live MBTA booking task is retired at this release.", "path": "evaluation_examples/test_nogdrive.json", "sha256": "9270c11fe809eb4c4e35a78a47cdb50717ea76557c1b9164c183e8e8b8d9ce91", @@ -280,6 +309,7 @@ { "id": "test_small", "label": "Small", + "subset_of": "test_all", "summary": "The upstream's test_small.json: a few tasks of each domain.", "path": "evaluation_examples/test_small.json", "sha256": "bb29275171b78728d71825b125af311d74e66bb2a6d693c45c497d380b1fc640", @@ -288,6 +318,7 @@ { "id": "test_infeasible", "label": "Infeasible", + "subset_of": "test_all", "summary": "The upstream's test_infeasible.json: tasks that cannot be done, passed by answering FAIL.", "path": "evaluation_examples/test_infeasible.json", "sha256": "1b447d0462b1bdac4b660e0dd6e6add6d01c17a9e684702c701abcffda409abb", @@ -310,6 +341,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/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 7c842dae4..191acfdf3 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,21 @@ ], "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", + "names": {"None": "No 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/execution.py b/app/nullius/execution.py index ad22adcab..7690bb3c2 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 b96505976..a7a7ab6d7 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 139da6433..1a9f16b3e 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -32,7 +32,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "21" +SCHEMA = "22" # 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 — @@ -465,6 +465,9 @@ class Job: # "declared" by its producer, "derived" from its files or is "pending" ("" uid). uid: str = "" uid_source: str = "" + # 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) @@ -1221,6 +1224,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.identity = identity_of(cfg, res, job.agent_version) job.standard = bool(std) diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index efc3ae5ad..e6974496d 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -12,6 +12,9 @@ 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 An agent runs commands as you on the local backend, which is not a sandbox: @@ -43,7 +46,11 @@ ``--limit``), the job recording its shard and its launch (``--launch``); ``--units FILE`` runs only the units a file lists (``run.units_file``: one id a line), read on the machine the command runs on, ``--from-run`` or not; ``merge`` -puts a launch's shard jobs together into one job (``standard/runner/merge.py``). ``--option`` +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. ``--served-by [MODEL=]SLUG[,SLUG...]`` lets only those serving providers answer @@ -88,7 +95,8 @@ from nullius.standard.calls import exchanges from nullius.standard.contract import definitions, match, ports, proofs from nullius.standard.proofs import conform, fidelity, pins, prove -from nullius.standard.runner import job, merge, run, shard +from nullius.standard.runner import job, merge, run, sets, shard +from nullius.standard.runner import units as unit_list ENV_FILE = paths.settings_file() @@ -555,6 +563,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: @@ -590,16 +606,17 @@ 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, exchanges=a.exchanges, exchanges_max_mb=a.exchanges_max_mb, **({"units_file": run.units_file(a.units)} if a.units is not None else {}), + **({"task_set": task_set} if task_set else {}), **({"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: @@ -744,6 +761,253 @@ 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 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 + 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, a --sample larger than the list + 3 not found: no such benchmark, set, file or job +""" + + +def _refused(e: Exception) -> int: + print(f"refused: {e}", file=sys.stderr) + return 3 if isinstance(e, (sets.NotFound, unit_list.NotFound)) else 2 + + +def _listed_units(path: str) -> list: + """A ``--units`` file's ids, read by the rules ``run --units`` reads it by.""" + if not os.path.isfile(path): + raise sets.NotFound(f"--units {path}: no such file") + try: + return run.units_file(path)["units"] + except run.Refused as e: + raise sets.Refused(str(e)) + + +def _set_rows(entry: dict) -> dict: + return {"benchmark": entry["benchmark"], "name": entry["name"], "label": sets.label_of(entry), "id": entry["id"], + "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) + + +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) + 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 + 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: + # 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 + 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)}") + 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"]: + raise sets.Refused(f"--dataset {a.dataset}: the job ran the dataset {got['dataset']}") + 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"{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 + + +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 {_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 + + +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: + 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"], **listed}, indent=2)) + return 0 + bench = _find_bench(a.benchmark) + 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 "")) + 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 + + +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)}, {sets.size(entry)} units; jobs that ran it keep their record") + return 0 + + +def cmd_set_import(a): + entry, added = sets.import_path(a.path) + if added: + print(f"{_named(entry)} of {entry['benchmark']}: imported into {sets.path_of(entry['benchmark'], entry['name'])}") + else: + print(f"{_named(entry)} of {entry['benchmark']}: here already, with the same tasks") + return 0 + + +def cmd_set(a): + try: + return {"create": cmd_set_create, "list": cmd_set_list, "show": cmd_set_show, + "rename": cmd_set_rename, "delete": cmd_set_delete, "import": cmd_set_import}[a.set_cmd](a) + except (sets.Refused, unit_list.Refused) as e: + return _refused(e) + + +UNITS_EPILOG = """\ +examples: + nullius standard units humaneval --dataset humaneval + nullius standard units osworld1 --dataset test_nogdrive --search "tab" --category domain=chrome --category domain=vlc + nullius standard units longmemeval --dataset longmemeval_oracle --bench-option question_type=multi-session --json + +exit codes: + 0 listed, a match of no task included + 1 unexpected error (a traceback: report it) + 2 usage, or refused: an option or a category not known, a licence its driver needs not set, 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. The driver +gets the benchmark's saved licences marked to: driver, as a run's does (HF_TOKEN from the environment first). +""" + + +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) + held = run.Licences(b, environ=os.environ) # as a headless run holds them: a provider's variable first + before = unit_list.state(b, a.dataset, given, held) + 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, licences=held) + 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(): + 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 + + def cmd_fidelity(a): o = definitions.get("agent", a.other) if not o: @@ -848,6 +1112,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") @@ -915,6 +1182,66 @@ 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", 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", 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)") + 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("--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) + sl.add_argument("benchmark", metavar="BENCH", nargs="?") + sl.add_argument("--json", action="store_true", help="one JSON array of rows") + sw = ss.add_parser("show", help="one task set: what it holds", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sw.add_argument("benchmark", metavar="BENCH") + sw.add_argument("ref", metavar="NAME", help="the set's name") + sw.add_argument("--json", action="store_true", help="the set as one JSON document") + sr = ss.add_parser("rename", help="another name for a task set: its id and tasks kept", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sr.add_argument("benchmark", metavar="BENCH") + sr.add_argument("name", metavar="NAME") + sr.add_argument("new", metavar="NEW", help="any words; the name commands take is made from them again") + sd = ss.add_parser("delete", help="remove a task set from this catalogue: jobs that ran it keep their record", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + sd.add_argument("benchmark", metavar="BENCH") + sd.add_argument("name", metavar="NAME") + si = ss.add_parser("import", help="a task set from its file, or from a job that ran one, into this catalogue", + epilog=SET_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + si.add_argument("path", metavar="PATH", help="an entry's .json file, or a job's directory") + un = sub.add_parser("units", help="a dataset's tasks: their ids, titles and categories, searched and counted", + epilog=UNITS_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) + un.add_argument("benchmark", metavar="BENCH") + un.add_argument("--dataset", required=True, help="the dataset whose tasks are listed") + un.add_argument("--bench-option", action="append", metavar="NAME=VALUE", + help="a benchmark option the driver lists under (repeatable); the others at their defaults") + un.add_argument("--search", metavar="TEXT", help="the tasks whose id, title or text hold each word, whatever the case") + un.add_argument("--category", action="append", metavar="FIELD=VALUE", + help="the tasks of this category's value (repeatable: values of one field widen, fields narrow)") + un.add_argument("--json", action="store_true", + help="one JSON document: total, of, described, tasks and each category's values with their counts") 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") @@ -922,7 +1249,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"): @@ -931,7 +1258,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, + "set": cmd_set, "units": cmd_units}[a.cmd](a) if __name__ == "__main__": diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 82486ed18..a84a16fd2 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1613,6 +1613,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) @@ -1640,11 +1645,30 @@ 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}") 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 1ec716eea..644e31aa6 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." @@ -176,6 +177,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), "procedure": procedure_label(b), "origin": definitions.origin_of(b), @@ -224,10 +226,17 @@ def _bench_page(b: dict) -> dict: for n, r in hostreq.all_of(b).items()}, "datasets": [{"id": d["id"], "label": d.get("label") or d["id"], "summary": d.get("summary", ""), "units": d.get("units"), "environment": d.get("environment") or "", + # the list it is cut from, when the benchmark declares one: drawn as that dataset's own task set + "subset_of": d.get("subset_of") or "", "controls": [dict(c, **{k: status[d["id"]][c["key"]][k] for k in ("proven", "short", "failed")}) for c in controls], "proofs": {k: status[d["id"]][k]["proven"] for k in ("units", "leak")}, - "failed": {k: status[d["id"]][k]["failed"] for k in ("units", "leak") if status[d["id"]][k]["failed"]}} + "failed": {k: status[d["id"]][k]["failed"] for k in ("units", "leak") if status[d["id"]][k]["failed"]}, + # the user's task sets cut from it (standard/runner/sets.py), each with the version it was made at; + # 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"]]} @@ -484,8 +493,48 @@ 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 + # 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 + 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(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. @@ -831,7 +880,8 @@ def pinned(p: dict) -> Dict[str, List[str]]: nouns = bench_nouns = (b.get("units") or {}).get("nouns", "units") # a dataset's count is always the benchmark's 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) @@ -856,7 +906,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 []), @@ -948,7 +999,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']} {bench_nouns}" if x.get("units") else "") for x in dss)], + ", ".join(f"{x.get('label') or x['id']}" + (f" · task set {set_of[x['id']]['label']} · {set_of[x['id']]['units']} {bench_nouns}" + if x["id"] in set_of else f" · {x['units']} {bench_nouns}" if x.get("units") else "") for x in dss)], *[[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)}")] @@ -1005,7 +1057,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/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index ab4ad58f1..41d8d6886 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -606,6 +606,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, exchanges: str = "", exchanges_max_mb: Optional[int] = None): @@ -615,7 +616,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. @@ -646,6 +650,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 b6117862f..5e17e9056 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 @@ -47,7 +50,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 @@ -80,11 +84,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")) @@ -174,7 +190,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 @@ -240,7 +256,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 26a638de4..0d8bd1720 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -81,7 +81,7 @@ from nullius.standard.contract import definitions, match from nullius.standard.protocols import acp, jsonl from nullius.standard.requirements import hostreq, install -from nullius.standard.runner import job, pace as pacing, shard as shards +from nullius.standard.runner import job, pace as pacing, sets, shard as shards from nullius.standard.runner.retries import RETRIES, retryable # the totals a unit's end carries onto the live board, from its trial's agent_result @@ -728,7 +728,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, exchanges: str = exchange_store.DEFAULT, @@ -754,6 +754,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 @@ -982,7 +985,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 @@ -1149,39 +1155,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: @@ -1198,7 +1221,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, exchanges=self.exchanges, exchanges_max_mb=self.exchanges_max_mb, diff --git a/app/nullius/standard/runner/sets.py b/app/nullius/standard/runner/sets.py new file mode 100644 index 000000000..50432ea68 --- /dev/null +++ b/app/nullius/standard/runner/sets.py @@ -0,0 +1,647 @@ +"""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). 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``). + +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 unicodedata +import uuid +from datetime import datetime, timezone +from typing import Iterable, List, Optional, Tuple + +from nullius import ondisk, 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", "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") # 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") + + +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 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") + + +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") + 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): + 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 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 + + +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, + 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, 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 + + +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"])} + ondisk.write_whole(path, json.dumps(ordered, indent=2, ensure_ascii=False) + "\n", mode=0o600) + 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: 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. 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 {}), + **({"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})") + 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 + + +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, 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. 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": 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; 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"] + + +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)}") + 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"), + **({"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)}", + **({"parts": rec["parts"]} if mixed else {"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 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]}): " + "the same id with another list") + return here, False diff --git a/app/nullius/standard/runner/units.py b/app/nullius/standard/runner/units.py new file mode 100644 index 000000000..33006a478 --- /dev/null +++ b/app/nullius/standard/runner/units.py @@ -0,0 +1,462 @@ +"""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 its saved ``to: driver`` +licences, as a run's is, and no other key; one its dataset's environment needs and none holds refuses the +listing before anything is fetched. 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. + +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 subprocess +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 +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) + + +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.""" + 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 _held(bench: dict, licences=None): + """What the listing holds of the benchmark's licences: those given, else its store (``run.Licences``).""" + return licences if licences is not None else run.Licences(bench) + + +def missing_licences(bench: dict, ds: dict, licences=None) -> List[dict]: + """The licences bound for the driver (``to: driver``) that the dataset's environment needs and ``licences`` + does not hold: [{name, provider}], ``provider`` empty for a benchmark's own.""" + try: + _, env_def = definitions.environment_of(bench, None, ds) + except ValueError: + return [] + held = _held(bench, licences) + return [{"name": s["name"], "provider": s.get("provider") or ""} for s in (env_def or {}).get("needs_secrets") or [] + if s.get("to") == "driver" and not held.get(s["name"])] + + +TOKENS = {"huggingface": "a Hugging Face token"} # a data provider's token, as a line names it + + +def needed(n: dict) -> str: + """One licence ``missing_licences`` found, as a line names it: a data provider's token, else its name.""" + return TOKENS.get(n["provider"], n["name"]) if n["provider"] else n["name"] + + +def missing_text(needs: List[dict]) -> str: + """``needs a Hugging Face token, HF_TOKEN (Settings → Data providers)``: what ``missing_licences`` found, in + a line.""" + return "needs " + "; ".join( + f"{needed(n)}, {n['name']} (Settings → Data providers)" if n["provider"] else f"{n['name']} (Settings → Custom keys)" + 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) + # 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): + 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 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, errors="replace", + 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(redact(self._clean(line))) + out.flush() + + def _read(self): + for line in self.p.stdout: + try: + 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 = redact(self._clean(line)) + 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(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: + 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) + 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), **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() + 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, licences=None) -> dict: + unset = missing_licences(bench, ds, licences) + if unset: + raise Refused(f"cannot list {bench['key']}'s dataset {ds['id']}: it {missing_text(unset)}") + 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, licences) + 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, licences=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. ``licences`` are what its driver is given + (``run.Licences``), the benchmark's store by default.""" + 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, licences) + path = _cache_contained(path) + os.makedirs(os.path.dirname(path), exist_ok=True) + ondisk.write_whole(path, json.dumps(got, ensure_ascii=False), mode=0o600) + 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, licences=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, needs}. ``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 licence not set, a program not on + this machine, a dataset's file not there); ``needs`` names the licences not set (``missing_licences``). + + ``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, needs=()) -> dict: + return {"state": "refused", "fetch": [], "reason": why, "needs": list(needs)} + + 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": "", "needs": []} + prepare = f"cannot prepare {key}'s dataset {ds['id']} for its listing: " + unset = missing_licences(bench, ds, licences) + if unset: + return refused(f"cannot list {key}'s dataset {ds['id']}: it {missing_text(unset)}", unset) + 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": "", "needs": []} + + +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 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, 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 {} + 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(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)] + + 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, 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 + # 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, + "fields": shown} 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/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index 8e2579b2e..c6583822c 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -181,10 +181,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); @@ -198,12 +200,46 @@ 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 set of several datasets is chosen for each of them, those not chosen yet added: each runs + // its part, a job of its own. A dataset no longer chosen keeps none. + function setTaskSet(r, dataset, ref) { + r.task_sets = {...(r.task_sets || {})}; + if (!ref) { delete r.task_sets[dataset]; return keepTaskSets(r); } + 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) { + 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)]; + // 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)]; 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]; @@ -833,7 +869,14 @@ } function prefill(query) { // ?standard=[&other=]: the standard's recipe for that pair (the Agents and Capabilities pages link here). - if(query.standard)return createStandard(query.standard,query.other||''); + if(query.standard) { + const r = createStandard(query.standard, query.other || ''); + if ((standardBench(r)?.datasets || []).some(d => d.id === query.dataset)) { + r.datasets = [query.dataset]; + if (query.set) setTaskSet(r, query.dataset, query.set); + } + return r; + } // nothing asked for: the Nullius runner, chosen first; a Harbor recipe comes from its own card if(!query.agent&&!query.dataset&&!query.model&&!query.n_tasks&&standard().benchmarks.length)return createStandard(); const r=create(), known=schema.agents.find(a=>[a.id,a.arg,a.label].includes(query.agent))||(query.agent&&schema.agents.find(a=>String(a.arg||'').includes(':')&&String(a.arg).split(':').pop()===query.agent)); @@ -889,5 +932,5 @@ // A recipe nobody changed: Start over has nothing to ask about. A new one, or that one as a reloaded draft holds it // (fromJSON fills in what a new one leaves out). The page's own values are compared as they are: reading would drop the bad ones. const atDefaults = r => { const s = JSON.stringify(r); return s === JSON.stringify(prefill({})) || s === JSON.stringify(fromJSON(prefill({}))); }; - return {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,toggleParticipant,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,atDefaults,deleteAsk,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; + return {setTaskSet,keepTaskSets,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,toggleParticipant,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,atDefaults,deleteAsk,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; }); diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 19bd51547..91b453f89 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -11,6 +11,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; display: grid; place-items: center; padding: 0; width: 32px; height: 32px; border: 0; border-radius: 8px; background: none; color: var(--nb-muted); font-size: 20px; line-height: 1; cursor: pointer; } @@ -250,6 +251,8 @@ /* a limit the benchmark or the agent declares: its placeholder reads as a value; Nullius's default stays grey */ #nullius-builder .nb-field input.nb-declared::placeholder { color: var(--nb-text); opacity: 1; } +/* A chosen dataset's tasks: all of them, or one of its task sets. */ +#nullius-builder .nb-pick-grid + .std-sethead, #nullius-builder .nb-field + .std-sethead { margin-top: 26px; } /* Where: machine kind, its machines, then isolation. Fixed values are not controls. */ #nullius-builder .std-machines { display: inline-flex; gap: 3px; padding: 3px; border: 1px solid var(--nb-line); border-radius: 999px; } #nullius-builder .std-machines button { padding: 6px 16px; border: 0; border-radius: 999px; background: transparent; color: var(--nb-text); font: 14px/1.4 var(--sans); } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 0c3a37bc8..688319c5e 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -746,13 +746,19 @@ 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); + const du = b.units || {noun: 'unit', nouns: 'units'}; // a dataset's count, and a task set's, is the benchmark's, whoever runs it 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 + ' ' + (b.units || {nouns: 'units'}).nouns : '', // a dataset's count is the benchmark's, whoever runs it - 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 + ' ' + du.nouns : '', foot: datasetChecks(b, x)})).join('')}
` + + b.datasets.filter(x => chosen.includes(x.id)).map(x => nested ? familyChoice(rec, b, x, du) : taskSetChoice(rec, b, x, du)).join('') + + 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); @@ -801,9 +807,12 @@ if (step === S.limits) { const sets = b.datasets.filter(x => C.datasetsOf(rec).includes(x.id)), per = sets.length > 1 ? ' of each dataset' : ''; // empty is the default, shown as the placeholder: every unit, one at a time, one attempt - const ds = sets.length === 1 ? sets[0] : null, all = ds && ds.units ? String(ds.units) : 'all'; + const ds = sets.length === 1 ? sets[0] : null, mine = ds && (ds.sets || []).find(s => s.name === ((rec.task_sets || {})[ds.id] || '').split('@')[0]); + const all = mine ? String(mine.units) : ds && ds.units ? String(ds.units) : 'all', most = /^\d+$/.test(all) ? all : ''; + // the field takes that many at most: more would be all of them return '

Scope

' - + field('Number of ' + u.nouns, 'limit', rec.limit, {type: 'number', min: 1, placeholder: all, hint: 'The first ones' + per + ', in its order.'}) + + field('Number of ' + u.nouns, 'limit', rec.limit, {type: 'number', min: 1, max: most, placeholder: all, + hint: 'Empty: all' + (most ? ' ' + most : '') + per + '. Else the first ones, in order.'}) + field('Concurrent ' + u.nouns, 'concurrency', rec.concurrency, {type: 'number', min: 1, max: 32, placeholder: rec.backend === 'boat' ? String((schema.standardHere || {}).boatSlots || 'Boat\'s limit') : '1'}) + '
' + '
' + field('Attempts per ' + u.noun, 'repeat', rec.repeat || '', {type: 'number', min: 1, max: 32, placeholder: '1', hint: 'Each ' + esc(u.noun) + ' is run and scored this many times.'}) @@ -829,6 +838,53 @@ 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 + // 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 + ? `' + : `
` + [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). @@ -899,6 +955,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') => ``; @@ -1193,7 +1251,10 @@ else if(d.runner){toRunner(d.runner,C.benchKey(r()));} else if(d.stdBench){C.setStandardBenchmark(r(),d.stdBench);} else if(d.stdOther){C.toggleParticipant(r(),d.stdOther);} // a check - else if(d.stdDataset){const rec=r(),c=C.datasetsOf(rec);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 @@ -1245,7 +1306,7 @@ if(d.stdUnsandboxed!==undefined)return; // a box's value is no tick: its change sets the recipe if(d.providerModel){d.typing='true';syncServed();localErrors();return;} // what is typed in a model field filters its list: a pick, Enter or leaving the field sets it if(d.field){const p=d.field.startsWith('param:')?C.parameters().find(p=>p.key===d.field.slice(6)):null; - const value=el.type==='number'?(el.value===''?'':Number(el.value)):el.value; + const typed=el.type==='number'?(el.value===''?'':Number(el.value)):el.value,value=d.field==='limit'?atMost(el,typed):typed; if(p)rec.params[p.key]=p.type==='optional-boolean'?(value==='__default__'?null:value==='true'):value; else if(d.field==='timeoutMultiplier'){rec.timeoutMultiplier=value;rec.agentMinutes='';} else if(d.field.startsWith('adapterPath:')){const id=d.field.slice(12);if(String(value).trim())rec.adapterPaths[id]=String(value).trim();else delete rec.adapterPaths[id];} @@ -1270,6 +1331,7 @@ const el=event.target; if(el.dataset.providerModel)commitModel(el); // a change undone by hand since the focus fires no change event if(el.type==='number'&&(el.dataset.field||el.dataset.stdMinutes||el.dataset.benchOptSelect)&&el.validity&&el.validity.badInput){el.value='';window.nulliusNotify?.(`${el.getAttribute('aria-label')}: enter a number.`,{error:true,key:'bad-number'});} + else if(el.dataset.field==='limit'&&el.value!==''&&atMost(el,Number(el.value))!==Number(el.value)){el.value=el.max;window.nulliusNotify?.(`${el.getAttribute('aria-label')}: at most ${el.max}, all of them.`,{key:'at-most'});} }); // a provider picked in a Served by, or slugs typed there and Enter: they join its list, after the ones there root.addEventListener('nb-pick',event=>{const role=event.target.dataset.servedBy;if(!role)return;C.addServed(r(),role,event.detail);syncServed();refreshPlan();}); @@ -1280,6 +1342,7 @@ else if(d.stdUnsandboxed!==undefined){r().unsandboxed=el.checked;refreshPlan();} else if(d.stdVersion!==undefined){ // keep the grid's filters while refreshing the version's origin and settings C.setStandardBenchmark(r(),el.value);inPlace(()=>render());} + 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 5b37ad752..25c0e0ea4 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -414,3 +414,86 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli @media (max-width: 640px) { .bench-notes { display: flex; flex-direction: column; gap: 20px; } .bench-notes[hidden] { display: none; } .bench-main > .bench-section, .bench-main > .bench-cols > .bench-section, .bench-notes > .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; } +/* 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; } } +.tasks-page { display: flex; flex-direction: column; gap: 20px; } +.tasks-page .bench-blocked { margin: 0; } +/* the list being prepared: a spinner before its words */ +.tasks-busy { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } +.tasks-busy::before { content: ""; flex: none; width: 12px; height: 12px; border-radius: 50%; border: 2px solid var(--border); border-top-color: var(--accent); animation: tasks-spin .8s linear infinite; } +@keyframes tasks-spin { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { .tasks-busy::before { animation-duration: 2.4s; } } +.tasks-page .tasks-warn { border-color: color-mix(in srgb, var(--patch_failed_tests) 45%, var(--border)); } +.tasks-note { overflow-wrap: anywhere; } +.tasks-browse { padding: 22px; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); min-width: 0; } +.tasks-dataset { display: flex; flex-direction: column; gap: 6px; width: min(420px, 100%); } +.tasks-parts { align-items: center; } +.tasks-parts-all { margin-left: auto; } +.tasks-bar { display: flex; flex-direction: column; gap: 14px; } +.tasks-find { flex: none; max-width: 520px; } +.tasks-cats { display: flex; flex-direction: column; gap: 10px; } +.tasks-cats .filter-pills { align-items: center; } +.tasks-catname { min-width: 64px; } +.tasks-cats .filter-pill { min-height: 34px; padding: 6px 12px; } +.tasks-n { color: var(--text-faint); } +.filter-pill[aria-pressed="true"] .tasks-n { color: inherit; opacity: .8; } +.tasks-sel { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 16px; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border-soft); } +.tasks-add, .tasks-got { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } +.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 */ +.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-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-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; } +.tasks-table td.tasks-text { width: 100%; max-width: 0; } +.tasks-row { display: flex; align-items: baseline; gap: 10px; width: 100%; min-width: 0; } +.tasks-row .tasks-title { flex: 1 1 auto; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.tasks-row .tasks-whole { display: none; flex: 1 1 100%; white-space: pre-wrap; line-height: 1.45; } +.tasks-table .tasks-id { display: none; flex: none; margin: 0; } +.tasks-table tr:hover .tasks-id, .tasks-table tr:focus-within .tasks-id { display: inline; } +/* the row's tooltip shows on hover alone: while its box, or its text where the box is disabled, has the keyboard's + focus, the whole text is in place */ +.tasks-table tr:has(:focus-visible) .tasks-row { flex-wrap: wrap; } +.tasks-table tr:has(:focus-visible) .tasks-title { display: none; } +.tasks-table tr:has(:focus-visible) .tasks-whole { display: block; } +.tasks-tick { width: 1%; } +.tasks-tick input { width: 18px; height: 18px; margin: 0; } +.tasks-title { display: block; line-height: 1.45; } +.tasks-table tr[data-id]:has(input:enabled) { cursor: pointer; } +.tasks-table small { display: block; margin-top: 2px; } +.tasks-tags { display: none; } +.tasks-savebar { position: sticky; bottom: 12px; z-index: 2; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin-top: 14px; padding: 10px 16px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface-2); box-shadow: var(--shadow); } +.tasks-savebar.tasks-gone { visibility: hidden; } +.tasks-save { scroll-margin-top: calc(var(--topbar-height) + 24px); padding: 22px; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); } +.tasks-form { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 12px; } +.tasks-form + .tasks-form { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border-soft); } +.tasks-field { display: flex; flex-direction: column; gap: 6px; flex: 0 1 240px; } +.tasks-field 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; } +.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..61c001741 --- /dev/null +++ b/app/static/catalogue/tasks.js @@ -0,0 +1,277 @@ +// 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 started on a click +// (List questions), the same way. Until there is a list, the search is hidden. +(() => { + 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'; + // The chosen of each dataset ({dataset: ids}): a set's own, or what this tab ticked on the benchmark's other + // datasets, kept while it goes from one to another and saved together; this page's are ``chosen``. + const json = (id, empty) => { try { return JSON.parse(($(id) || {}).textContent || empty); } catch { return JSON.parse(empty); } }; + // each dataset's [id, {label, href}], in the benchmark's order + const pages = Object.fromEntries(json('tasks-dataset-pages', '[]')); + let here = d.dataset || ''; + // the dataset's own routes: listing, prepare, rows, save + const route = kind => `${d.base || ''}${encodeURIComponent(here)}/${kind}`; + const draftKey = `nullius-task-set:${d.bench}:${d.version || ''}:${d.set || ''}`; + let parts = json('tasks-chosen-parts', '{}'); + try { const kept = JSON.parse(globalThis.sessionStorage.getItem(draftKey) || 'null'); if (kept && typeof kept === 'object') parts = kept; } catch { /* none kept */ } + const chosen = new Set(parts[here] || []); + const keep = () => { + if (chosen.size) parts[here] = [...chosen]; else delete parts[here]; + try { globalThis.sessionStorage.setItem(draftKey, JSON.stringify(parts)); } catch { /* this page's alone */ } + }; + const total = () => Object.values(parts).reduce((n, ids) => n + ids.length, 0); + // opened from a set: its members first; Show all browses the dataset + const st = {q: '', cats: {}, page: 1, size: 25, showing: !!d.set && chosen.size > 0, ready: false, total: 0, pages: 1, fields: {}}; + // 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)); + // a category field and its values as the definition names them (the listing's `fields`), else their keys + const label = field => st.fields[field]?.label || field.charAt(0).toUpperCase() + field.slice(1).replace(/_/g, ' '); + const named = (field, value) => st.fields[field]?.names?.[value] || value; + const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c])); + // the listing at the version the page shows (data-version, empty for the benchmark's default) + const at = url => d.version ? url + (url.includes('?') ? '&' : '?') + 'version=' + encodeURIComponent(d.version) : url; + const post = (url, body) => nulliusFetch(at(url), {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': d.csrf}, body: JSON.stringify(body)}); + const count = n => `${n.toLocaleString('en-US')} ${n === 1 ? nouns.replace(/s$/, '') : nouns}`; + + // the notice: its line, and a link to where a licence is set or the button that starts a full listing + function say(text, warn, got) { + const el = $('tasks-state'), link = $('tasks-state-link'), list = $('tasks-list'); + el.hidden = !text; $('tasks-state-text').textContent = text || ''; el.classList.toggle('tasks-warn', !!warn); + el.classList.toggle('tasks-busy', !!text && !warn && !!got?.preparing); + link.hidden = !(got && got.link); + if (got && got.link) { link.href = got.link.href; link.textContent = got.link.text; } + const startable = !!got && got.state === 'full' && !got.preparing && d.local === 'true'; + if (list) { list.hidden = !startable; $('tasks-list-about').textContent = startable ? got.about || '' : ''; } + } + const inDatasets = n => `${n} dataset${n === 1 ? '' : 's'}`; + function chosenLine() { + keep(); + const others = Object.keys(parts).filter(k => k !== here), all = total().toLocaleString('en-US'); + $('tasks-chosen').textContent = `${chosen.size.toLocaleString('en-US')} chosen` + (others.length ? ' here' : ''); + if ($('tasks-bar-chosen')) $('tasks-bar-chosen').textContent = others.length + ? `${all} chosen in ${inDatasets(others.length + (chosen.size ? 1 : 0))}` : $('tasks-chosen').textContent; + // each dataset with something chosen, this one pressed: a click opens the other's page, its chosen kept + const strip = $('tasks-parts'); + if (strip) { + const shown = [...new Set([...Object.keys(pages), ...Object.keys(parts)])].filter(k => k === here ? chosen.size : parts[k]); // the benchmark's order + strip.hidden = !others.length; + strip.innerHTML = !others.length ? '' : 'Chosen' + + shown.map(k => ``).join('') + + `${all} chosen in ${inDatasets(shown.length)}`; + } + // 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 = !total(); + } + // a task on one line: its title cut to the width, the whole text in the row's tooltip and, while its box (its text + // where the box is disabled) has the keyboard's focus, in place; its id beside it on hover or focus. A click + // anywhere on the row ticks it. + function row(t) { + const tags = Object.entries(t.categories || {}).map(([f, v]) => `${esc(named(f, v))}`).join(' '); + const whole = t.text || t.title || t.id; + return `` + + `${esc(t.title || t.id)}` + + `${esc(whole)}${t.title ? `${esc(t.id)}` : ''}` + + `${t.unknown ? 'not in the listing' : ''}` + + (tags ? `${tags}` : '') + `${tags}`; + } + function draw(tasks) { + $('tasks-rows').innerHTML = tasks.map(row).join(''); + $('tasks-table').hidden = !tasks.length; + const fields = [...new Set(tasks.flatMap(t => Object.keys(t.categories || {})))]; + $('tasks-cat-head').hidden = !fields.length; + $('tasks-cat-head').textContent = fields.map(label).join(' · '); + 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.total <= 10; + const prev = nav.querySelector('[data-page=prev]'), next = nav.querySelector('[data-page=next]'); + prev.hidden = next.hidden = $('tasks-page-of').hidden = st.pages <= 1; // Show stays while one page holds all + $('tasks-page-of').textContent = `Page ${st.page} of ${st.pages}`; + prev.disabled = st.page <= 1; + 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 route('listing') + '?' + u; + } + let polling = null, asked = 0; + // not in the cache: the server's line for its state; a light listing started once, out of any request, then asked + // again every few seconds until it is ready + function prepare(got) { + return post(route('prepare'), {}).then(r => r.json()).then(g => { say(g.say || got.say, false, g); polling = setTimeout(load, 2500); }) + .catch(() => say('The list could not be started. Reload the page.', true)); + } + function notReady(got) { + if ($('tasks-match')) $('tasks-match').hidden = true; + $('tasks-bar').hidden = true; + const light = got.state === 'light' && !got.error, full = got.state === 'full'; + say(got.say, !light && !(full && !got.error), got); + clearTimeout(polling); + const elsewhere = () => say('The list is prepared from a browser on the application host. Ids can still be pasted.', true); + if (!light && !(full && got.preparing)) return full && !got.error && d.local !== 'true' ? elsewhere() : undefined; + if (!got.preparing && d.local !== 'true') return elsewhere(); + if (!got.preparing && !asked++) return prepare(got); + polling = setTimeout(load, 2500); + } + $('tasks-list-go')?.addEventListener('click', () => { $('tasks-list').hidden = true; asked++; prepare({say: ''}); }); + async function load() { + let got; + try { got = await (await nulliusFetch(query({page: st.page, size: st.size}))).json(); } catch { return say('The list could not be read. Reload the page.', true); } + if (!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(''); + $('tasks-bar').hidden = false; + st.ready = true; st.total = got.total; st.pages = got.pages; st.page = got.page; + st.fields = got.fields || {}; + facets(got.categories); + const m = $('tasks-match'); + if (m) { m.hidden = !writable || !got.total || st.showing; const n = got.total.toLocaleString('en-US'); m.textContent = got.total === got.of ? `Select all ${n}` : `Select the ${n} found`; } + 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')}` : '') + + (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(route('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` : '') + + (picked() ? ` · picked at random with seed ${drawn.seed}` : ''); + 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] = b.dataset.all !== undefined ? [] : vs.includes(v) ? vs.filter(x => x !== v) : [...vs, v]; + if (!st.cats[f].length) delete st.cats[f]; + setShowing(false); st.page = 1; load(); + }); + // a click anywhere on a row ticks it, as its box would; the box, a link or a button keeps its own action, and a + // drag that selects words is no click + $('tasks-rows').addEventListener('click', e => { + if (e.target.closest('input, a, button') || String(globalThis.getSelection?.() || '')) return; + e.target.closest('tr[data-id]')?.querySelector('input[type=checkbox]')?.click(); + }); + $('tasks-rows').addEventListener('change', e => { + const box = e.target.closest('input[type=checkbox]'); if (!box) return; + const id = box.closest('tr').dataset.id; + box.checked ? chosen.add(id) : chosen.delete(id); chosenLine(); + }); + // Another dataset in place: its tasks listed, its filters and its ticks; what this one ticked is kept for the set. + // The address follows (back returns), and Build a run takes it. + function switchTo(id, push = true) { + if (!id || id === here || !pages[id]) return; + keep(); + here = d.dataset = id; + chosen.clear(); (parts[id] || []).forEach(u => chosen.add(u)); + drawn = null; clearTimeout(polling); asked = 0; + Object.assign(st, {q: '', cats: {}, page: 1, ready: false, total: 0, pages: 1, fields: {}}); + setShowing(!!d.set && chosen.size > 0); + $('tasks-q').value = ''; $('tasks-cats').innerHTML = ''; $('tasks-bar').hidden = true; $('tasks-rows').innerHTML = ''; + const select = $('tasks-dataset'); + if (select && select.value !== id) { select.value = id; select.dispatchEvent(new Event('change', {bubbles: true})); } + const build = $('tasks-build'); + if (build) { const u = new URL(build.href, location.href); u.searchParams.set('dataset', id); build.href = u.pathname + u.search; } + if (push) history.pushState({dataset: id}, '', pages[id].href); + say(''); load(); + } + $('tasks-dataset')?.addEventListener('change', e => switchTo(e.target.value)); + $('tasks-parts')?.addEventListener('click', e => { const b = e.target.closest('[data-part]'); if (b) switchTo(b.dataset.part); }); + globalThis.addEventListener?.('popstate', () => switchTo(location.pathname.split('/').filter(Boolean).pop(), false)); + $('tasks-size').addEventListener('change', e => { st.size = +e.target.value; st.page = 1; load(); }); + $('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(); } + }); + // 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; + 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(); }); + $('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-open').open = false; + window.nulliusNotify?.(`${count(ids.length)} added.`); + load(); + }); + + const msg = (text, bad) => { const el = $('tasks-msg'); if (el) { el.textContent = text; el.classList.toggle('bad', !!bad); } }; + async function save(body) { + keep(); + if (!total()) return msg('Tick at least one task.', true); + let got; + if (picked() && Object.keys(parts).length === 1) body = {...body, note: drawn.note}; + try { got = await (await post(route('save'), {...body, parts})).json(); } catch { return msg('Not saved: the server did not answer.', true); } + if (!got.ok) return msg(got.error, true); + try { globalThis.sessionStorage.removeItem(draftKey); } catch { /* none kept */ } + 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}); + }); + // a licence added in Settings, opened from the warning, counts as soon as Settings closes + document.addEventListener('close', e => { if (e.target.id === 'settings-modal' && !st.ready) load(); }, true); + setShowing(st.showing); + chosenLine(); + load(); +})(); diff --git a/app/static/style.css b/app/static/style.css index 1c9fc3178..d1d6e9e1d 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -360,6 +360,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; } +.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 { display: flex; height: 8px; border-radius: 99px; overflow: hidden; diff --git a/app/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index ffbcbc0a5..1d73ca34a 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -204,6 +204,28 @@

{{ d.title }}

{% endif %} + {% 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 %} {{ task_sets|length }}{% endif %}

+ {% if local and wholes %}New task set{% 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 %}{% 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 %} + {% for y in views %}{% set sfx = '' if y.default else '-' ~ y.version %} {% if y.changes %} diff --git a/app/templates/catalogue/tasks.html b/app/templates/catalogue/tasks.html new file mode 100644 index 000000000..3f151a8ef --- /dev/null +++ b/app/templates/catalogue/tasks.html @@ -0,0 +1,139 @@ +{% extends "base.html" %} +{% from '_page.html' import page_head %} +{#- 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) #} +
+ {% set mark %}{% endset %} + {% set tags %}{{ 'Tasks' if heading == (ds.label or ds.id) else 'Task set' }}{{ title }}{% 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 = total %}
+ 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(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 }}{{ 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 }}
+ {% if rev.note %}
Note{{ rev.note }}
{% endif %} +
+ {% 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 #} + + +
+ +
+ {#- the ways to choose, then what is chosen #} +
+ + {% if writable %}{% endif %} +
Paste ids
+
+
+ 0 chosen + + +
+
+ {#- the box Paste ids opens, on its own line below the row #} +
+
+

+
+ + + + +
+ {#- the shared pager's look (_tables.html pager); its pages are the listing's, asked of the server #} + + {% if writable %} + + {% endif %} +
+ +
+ + +{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 2e3a173dd..e9f1eadf4 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -41,6 +41,7 @@ {% if job.dataset %}{% call identity_card(benchmark_rows) %} {% if benchmark %}
Benchmark{{ benchmark }}
{% endif %}
Dataset{{ job.dataset|dsname }}
+ {% if job.task_set %}
Task set{% if set_link.link %}{{ set_link.name }}{% else %}{{ set_link.name }}{% endif %}
{% endif %} {% endcall %}{% endif %} {% if job.agent_label or job.model_name %} {% call identity_card(agent_rows) %} @@ -65,7 +66,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/field_contract.json b/app/tests/field_contract.json index 3d6c86706..fb8595e0c 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -417,6 +417,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 1388f7ca0..7865a41b9 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 @@ -289,6 +290,71 @@ def test_a_key_in_the_recorded_command_is_not_echoed_by_show_json(self): self.assertNotIn(KEY, out.stdout) +# ── task-sets.md ──────────────────────────────────────────────────────────── + +class TaskSetCommands(Scratch): + def test_help_and_refusals_of_the_task_set_commands(self): + """Each set command, and units, has help with its examples and exit codes; a + refusal is one line on stderr with nothing on stdout, 2 for a usage + error or a refusal, 3 for what is not found, and writes nothing.""" + cat = os.path.join(self.tmp, "catalogue") + env = {"NULLIUS_CATALOGUE": cat, "NULLIUS_HOME": os.path.join(self.tmp, "profile")} + for sub in (("set",), ("set", "create"), ("set", "list"), ("set", "show"), ("set", "rename"), + ("set", "delete"), ("set", "import"), ("units",)): + with self.subTest(help=sub): + out = self.sh("standard.cli", *sub, "--help", env=env) + self.assertEqual(out.returncode, 0, out.stderr) + for line in ("usage:", "examples:", "exit codes:"): + self.assertIn(line, out.stdout) + self.assertEqual(out.stderr, "") + listed = write_json(Path(self.tmp, "ten.txt"), "HumanEval/0\nHumanEval/1\n") + cases = [ + (["set", "create", "humaneval"], 2, "usage:"), + (["set", "create", "humaneval", "..", "--dataset", "humaneval", "--units", listed], 2, "needs a letter or a digit"), + (["set", "show", "humaneval", "a/b"], 2, "not a task set's name"), + (["set", "create", "humaneval", "ok", "--dataset", "nope", "--units", listed], 2, "no dataset 'nope'"), + (["set", "create", "no-such-bench", "ok", "--dataset", "x", "--units", listed], 3, "no benchmark"), + (["set", "show", "humaneval", "nowhere"], 3, "no task set 'nowhere'"), + (["set", "update", "humaneval", "nowhere", "--add", "HumanEval/2"], 2, "invalid choice: 'update'"), # a set is frozen + (["set", "rename", "humaneval", "nowhere", "elsewhere"], 3, "no task set 'nowhere'"), + (["set", "rename", "humaneval", "nowhere"], 2, "usage:"), + (["set", "delete", "humaneval", "nowhere"], 3, "no task set 'nowhere'"), + (["set", "import", os.path.join(self.tmp, "absent.json")], 3, "no such file or job"), + (["set", "create", "humaneval", "ok", "--dataset", "humaneval", "--units", listed, "--bench-option", "a=b"], 2, + "unrecognized arguments: --bench-option"), + (["set", "create", "humaneval", "ok", "--dataset", "humaneval"], 2, "--units FILE, --from-job"), + (["units", "humaneval"], 2, "usage:"), + (["units", "humaneval", "--dataset", "nope"], 3, "no dataset 'nope'"), + (["units", "no-such-bench", "--dataset", "x"], 3, "no benchmark"), + (["units", "humaneval", "--dataset", "humaneval", "--category", "kind"], 2, "FIELD=VALUE"), + ] + for args, code, said in cases: + with self.subTest(args=args): + out = self.sh("standard.cli", *args, env=env) + self.assertEqual(out.returncode, code, out.stderr) + self.assertIn(said, out.stderr) + self.assertEqual(out.stdout, "") + # a listing that needs a program this machine lacks is refused before it fetches anything + out = self.sh("standard.cli", "units", "humaneval", "--dataset", "humaneval", + env=dict(env, PATH=os.path.join(self.tmp, "no-programs"))) + self.assertEqual((out.returncode, out.stdout), (2, "")) + self.assertEqual(out.stderr, "refused: cannot prepare humaneval's dataset humaneval for its listing: " + "git is not on this machine\n") + self.assertFalse(os.path.exists(cat)) + out = self.sh("standard.cli", "set", "list", "--json", env=env) + self.assertEqual((out.returncode, json.loads(out.stdout), out.stderr), (0, [], "")) + + def test_the_index_of_commands_names_each_set_command_there_is_and_no_other(self): + """The commands' index (docs/cli/README.md) names the set commands one by one: the ones ``set`` takes.""" + out = self.sh("standard.cli", "set", "--help", env={"NULLIUS_HOME": os.path.join(self.tmp, "profile")}) + self.assertEqual(out.returncode, 0, out.stderr) + taken = set(re.findall(r"^ ([a-z]+) ", out.stdout, re.M)) # the help's list of commands + row = next(line for line in (APP.parent / "docs" / "cli" / "README.md").read_text(encoding="utf-8").splitlines() + if line.startswith("| [Task sets]")) + listed = row[row.index("`set create`"):].split(";")[0] + self.assertEqual({name.removeprefix("set ") for name in re.findall(r"`([^`]+)`", listed)}, taken) + + # ── import.md ─────────────────────────────────────────────────────────────── class ImportContract(Scratch): diff --git a/app/tests/test_dataset_subsets.py b/app/tests/test_dataset_subsets.py new file mode 100644 index 000000000..2fabbbba7 --- /dev/null +++ b/app/tests/test_dataset_subsets.py @@ -0,0 +1,87 @@ +"""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, 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 +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_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", + "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") + # 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__": + unittest.main() diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index dad1c8538..bb3354165 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -828,6 +828,16 @@ def test_app_is_sent_at_its_content_address_and_the_part_runs_from_it(self): self.assertEqual(json.loads((self.tmp / "runs" / "std-shard-2of2" / "run.json").read_text())["catalogue_on_target"], "~/.nullius/runs/std-shard-2of2/catalogue") + def test_the_snapshot_a_host_is_sent_carries_the_recipes_task_sets(self): + self.plan.recipe = {"harness": "standard", "benchmark": "fakebench@1", "task_sets": {"all": "dev@2", "more": "other"}} + ex = self.run_it() + self.assertEqual((ex.state, ex.exit_code), ("done", 0), ex.lines) + self.assertEqual(execution.standard_payload.build.call_args.kwargs["sets"], [("fakebench", "dev"), ("fakebench", "other")]) + self.plan.recipe = {} + self.plan.name = "std-plain" + self.run_it() + self.assertEqual(execution.standard_payload.build.call_args.kwargs["sets"], []) + def test_gaias_hugging_face_token_is_handed_from_data_providers_alone(self): # over the launcher's stdin as a licence is, read from Settings → Data providers; a value GAIA's own folder # holds under that name is never sent diff --git a/app/tests/test_gaia_driver.py b/app/tests/test_gaia_driver.py index 3ec74fdf0..fef555c0e 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") + 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) 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_locomo_rag.py b/app/tests/test_locomo_rag.py index 533bf3616..13e289410 100644 --- a/app/tests/test_locomo_rag.py +++ b/app/tests/test_locomo_rag.py @@ -117,6 +117,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..50e8d75a4 100644 --- a/app/tests/test_longmemeval_setups.py +++ b/app/tests/test_longmemeval_setups.py @@ -166,6 +166,19 @@ 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, "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"]) + self.assertIs(BENCH["driver"].get("describe"), True) + def test_the_original_runs_run_generation_as_the_script_does_and_scores_with_evaluate_qa(self): judge = {"model": "gpt-4o-2024-08-06", "base_url": "http://judge/v1", "key": "k"} got = self.run_driver([ diff --git a/app/tests/test_migrate.py b/app/tests/test_migrate.py index 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_open_telco_driver.py b/app/tests/test_open_telco_driver.py index 4a11484bd..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(): @@ -159,6 +163,18 @@ 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": {}}) + # 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): driver = self.load("telemath-lite") diff --git a/app/tests/test_standard_sets.py b/app/tests/test_standard_sets.py new file mode 100644 index 000000000..5bc7baa5b --- /dev/null +++ b/app/tests/test_standard_sets.py @@ -0,0 +1,731 @@ +"""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) + 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) + + 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", + "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) + self.assertNotIn("revision", out) + # a recipe or a command from before names its latest list as NAME@2: the same set; NAME@1 is refused + self.assertEqual(sets.for_run(self.b, "dev@2")[0]["units"], ["good", "model", "slow"]) + code, out, err = self.cli("set", "show", "fakebench", "dev@1") + self.assertEqual((code, out), (3, "")) + self.assertIn("dev@1 names an earlier list of the task set dev: a set is read as its latest list now; name it dev", err) + code, out, err = self.run_nop("--set", "dev", "--name", "from-before") + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(os.path.join(self.jobs, "from-before")), ["good__u0000", "model__u0003", "slow__u0002"]) + with open(path, "rb") as f: + self.assertEqual(f.read(), before) + + def run_nop(self, *args): + return self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "-j", "2", *args) + + +class Names(Scratch): + def test_a_label_makes_a_name_in_lower_case_with_hyphens_and_a_second_one_takes_two(self): + for label, name in (("Custom task set", "custom-task-set"), ("custom task set", "custom-task-set-2"), + (" Custom task set! ", "custom-task-set-3"), ("Café au lait", "cafe-au-lait"), + ("a/b", "a-b"), ("../up", "up"), ("x..y", "x-y"), ("ÉTÉ 2026", "ete-2026"), ("日本", "task-set"), + ("dev", "dev")): + with self.subTest(label=label): + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file("good\n")) + self.assertEqual(code, 0, err) + entry = sets.load("fakebench", name) + self.assertEqual(entry["label"], label.strip()) + self.assertTrue(out.startswith(f"wrote {sets.path_of('fakebench', name)}: "), out) + self.assertEqual(sets.slug("b" * 70), "b" * 64) + self.assertEqual(sets.name_for("fakebench", "b" * 70), "b" * 64) + sets.create(self.b, "b" * 70, dataset="all", units=["good"]) + self.assertEqual(sets.name_for("fakebench", "b" * 70), "b" * 62 + "-2") + + def test_a_label_with_no_letter_or_digit_on_two_lines_or_too_long_is_refused(self): + for label, said in (("", "needs a name"), (" ", "needs a name"), ("..", "needs a letter or a digit"), + ("a\nb", "one line"), ("x" * 81, "at most 80 characters")): + with self.subTest(label=label): + code, out, err = self.cli("set", "create", "fakebench", label, "--dataset", "all", "--units", self.file("good\n")) + self.assertEqual((code, out), (2, "")) + self.assertIn(said, err) + self.assertFalse(os.path.exists(os.path.join(self.cat, "sets", "fakebench"))) + + def test_a_name_that_would_leave_the_benchmarks_folder_is_refused(self): + for name in ("a/b", "..", "", ".hidden", "../up", "a\\b", "x..y"): + with self.subTest(name=name): + code, out, err = self.cli("set", "show", "fakebench", name) + self.assertEqual((code, out), (2, "")) + self.assertIn("not a task set's name", err) + + def test_links_cannot_escape_through_parent_folders_or_an_entry(self): + entry = self.make("dev", "good\n") + exported = self.file(json.dumps(read(sets.path_of("fakebench", "dev"))), "export.json") + for relative in ("sets", "sets/fakebench", "sets/fakebench/dev.json"): + with self.subTest(path=relative): + path = os.path.join(self.cat, relative) + outside = os.path.join(self.tmp, "outside") + os.rename(path, outside) + os.symlink(outside, path) + try: + for action in (lambda: sets.load("fakebench", "dev"), + lambda: sets.write(entry), + lambda: sets.rename("fakebench", "dev", "other"), + lambda: sets.import_path(exported)): + with self.assertRaisesRegex(sets.Refused, "outside"): + action() + if relative != "sets/fakebench/dev.json": + with self.assertRaisesRegex(sets.Refused, "outside"): + sets.create(self.b, "new", dataset="all", units=["good"]) + with mock.patch.object(sets.os, "listdir", wraps=os.listdir) as listed: + try: + found, bad = sets.entries() + except sets.Refused as e: + self.assertIn("outside", str(e)) + else: + self.assertEqual(found, []) + self.assertTrue(any("outside" in problem for problem in bad)) + self.assertNotIn(mock.call(path), listed.call_args_list) + finally: + os.unlink(path) + os.rename(outside, path) + self.assertEqual(sets.load("fakebench", "dev"), entry) + self.assertFalse(os.path.exists(sets.path_of("fakebench", "new"))) + + def test_a_label_that_exists_makes_another_set(self): + first = self.make("dev", "good\n") + code, out, err = self.cli("set", "create", "fakebench", "dev", "--dataset", "all", "--units", self.file("model\n")) + self.assertEqual(code, 0, err) + self.assertIn(": dev-2 (dev), 1 task of all", out) + self.assertEqual(sets.load("fakebench", "dev"), first) + self.assertEqual(sets.revision(sets.load("fakebench", "dev-2"))["units"], ["model"]) + + +class RenameAndDelete(Scratch): + def test_a_rename_keeps_the_id_and_the_list_makes_the_name_again_and_the_id_finds_it(self): + first = self.make("dev", "good\nmodel\n", "--description", "two of them") + code, out, err = self.cli("set", "rename", "fakebench", "dev", "Misses of June") + self.assertEqual((code, err), (0, "")) + self.assertTrue(out.startswith("renamed dev to misses-of-june (Misses of June) ("), out) + self.assertIn("its id and its tasks kept", out) + got = sets.load("fakebench", "misses-of-june") + self.assertEqual((got["id"], got["label"], got["description"], got["revisions"]), + (first["id"], "Misses of June", "two of them", first["revisions"])) + self.assertEqual(sorted(os.listdir(os.path.join(self.cat, "sets", "fakebench"))), ["misses-of-june.json"]) + self.assertEqual(sets.by_id("fakebench", first["id"], "dev")["name"], "misses-of-june") + # another set made under the old name is another set: the id still finds the renamed one + self.make("dev", "good\n") + self.assertEqual(sets.by_id("fakebench", first["id"], "dev")["name"], "misses-of-june") + self.assertIsNone(sets.by_id("fakebench", "0" * 32, "dev")) + # a label that makes the same name changes the label alone; one another set holds makes the next name + self.assertEqual(sets.rename("fakebench", "misses-of-june", "misses of june")["name"], "misses-of-june") + self.assertEqual(sets.rename("fakebench", "misses-of-june", "Dev")["name"], "dev-2") + + def test_its_own_label_an_empty_one_and_a_set_not_there_are_refused(self): + dev = self.make("dev", "good\n") + other = self.make("other", "model\n") + for new, code, said in (("dev", 2, "is named 'dev' already"), ("", 2, "needs a name"), ("..", 2, "letter or a digit")): + with self.subTest(new=new): + got = self.cli("set", "rename", "fakebench", "dev", new) + self.assertEqual(got[:2], (code, "")) + self.assertIn(said, got[2]) + got = self.cli("set", "rename", "fakebench", "nowhere", "x") + self.assertEqual(got[:2], (3, "")) + self.assertIn("no task set 'nowhere'", got[2]) + self.assertEqual((sets.load("fakebench", "dev"), sets.load("fakebench", "other")), (dev, other)) + self.assertEqual(sorted(os.listdir(os.path.join(self.cat, "sets", "fakebench"))), ["dev.json", "other.json"]) + self.assertEqual(sets.rename("fakebench", "dev", "other")["name"], "other-2") + + def test_a_delete_removes_the_file_and_says_what_it_held(self): + self.make("Dev set", "good\nmodel\n") + path = sets.path_of("fakebench", "dev-set") + code, out, err = self.cli("set", "delete", "fakebench", "dev-set") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.strip(), f"deleted {path}: dev-set (Dev set), 2 units; jobs that ran it keep their record") + self.assertFalse(os.path.exists(path)) + code, out, err = self.cli("set", "delete", "fakebench", "dev-set") + self.assertEqual((code, out), (3, "")) + self.assertIn("no task set 'dev-set'", err) + + def test_a_delete_of_a_link_removes_the_link_and_not_the_set_it_leads_to(self): + self.make("dev", "good\n") + folder = os.path.join(self.cat, "sets", "fakebench") + path = os.path.join(folder, "alias.json") + os.symlink(os.path.join(folder, "dev.json"), path) + code, out, err = self.cli("set", "delete", "fakebench", "alias") + self.assertEqual(code, 0, err) + self.assertEqual(out.strip(), f"deleted {path}: an entry this version could not read") + self.assertEqual(sorted(os.listdir(folder)), ["dev.json"]) + self.assertEqual(sets.revision(sets.load("fakebench", "dev"))["units"], ["good"]) + + def test_an_entry_of_the_earlier_format_is_refused_plainly_and_can_be_deleted(self): + entry = self.make("old", "good\n") + path = sets.path_of("fakebench", "old") + with open(path, "w") as f: + json.dump(dict(entry, schema=sets.SCHEMA, benchmark_options={"mode": "hard"}, setup="yours"), f) + with self.assertRaises(sets.Earlier) as refused: + sets.load("fakebench", "old") + self.assertIn(path, str(refused.exception)) + said = sets.plain(refused.exception, "fakebench", "old") + self.assertEqual(said, "The task set old is of an earlier format, which kept a run's options: delete it and make it again.") + self.assertNotIn(self.tmp, said) + code, out, err = self.cli("set", "rename", "fakebench", "old", "new") + self.assertEqual((code, out), (2, "")) + self.assertIn("earlier format", err) + code, out, err = self.cli("set", "delete", "fakebench", "old") + self.assertEqual((code, out.strip(), err), (0, f"deleted {path}: an entry this version could not read", "")) + self.assertFalse(os.path.exists(path)) + + +class FromAJob(Scratch): + def job(self, name="graded"): + """A job as a run writes it: good passed, wrong failed, slow rate limited, a unit whose id has a slash passed.""" + d = os.path.join(self.jobs, name) + os.makedirs(d) + other = dict(definitions.control(self.b, "nop"), _kind="control") + units = ["good", "wrong", "slow", "group/model"] + job.write_config(d, job=name, bench=self.b, other=other, model="", provider="openai", dataset="all", units=units, + concurrency=1, granted=False, bench_options={"mode": "hard"}) + ends = {"good": ({"reward": 1.0}, None), "wrong": ({"reward": 0.0}, None), "slow": (None, ("RateLimitError", "429")), + "group/model": ({"reward": 1.0}, None)} + results = [] + for place, u in enumerate(units): + score, exc = ends[u] + trial = os.path.join(d, f"{u.rpartition('/')[2]}__u{place:04d}") + os.makedirs(trial) + results.append(job.write_trial(trial, job=name, bench=self.b, other=other, model="", unit=u, t0=1.0, t1=2.0, + produce=(1.0, 2.0), score=score, exception=exc, calls=[], trajectory=None)) + job.write_result(d, name, 1.0, 3.0, results, len(units)) + return d + + def test_outcome_takes_the_trials_of_those_outcomes_by_their_full_unit_ids(self): + d = self.job() + for name, outcome, want in (("passed", "passed", ["good", "group/model"]), ("misses", "failed,infra", ["wrong", "slow"]), + ("limited", "rate_limited", ["slow"])): + with self.subTest(outcome=outcome): + code, out, err = self.cli("set", "create", "fakebench", name, "--from-job", d, "--outcome", outcome) + self.assertEqual(code, 0, err) + entry = sets.load("fakebench", name) + self.assertEqual(sets.revision(entry)["units"], want) + self.assertEqual(entry["dataset"], "all") + self.assertNotIn("benchmark_options", entry) # the job ran under mode=hard; the set holds none + self.assertEqual(sets.revision(entry)["hash"], sets.content_hash("fakebench", "all", want)) + self.assertIn(f"outcomes {outcome}", sets.revision(entry)["note"]) + + def test_unit_takes_the_ones_named(self): + d = self.job() + code, out, err = self.cli("set", "create", "fakebench", "two", "--from-job", d, "--unit", "group/model", "--unit", "wrong") + self.assertEqual(code, 0, err) + self.assertEqual(sets.revision(sets.load("fakebench", "two"))["units"], ["wrong", "group/model"]) + code, out, err = self.cli("set", "create", "fakebench", "none", "--from-job", d, "--unit", "model") + self.assertEqual((code, out), (2, "")) + self.assertIn("no trial of model", err) # the trial's name is not its unit's id + code, out, err = self.cli("set", "create", "fakebench", "bad", "--from-job", d, "--outcome", "sideways") + self.assertEqual(code, 2) + self.assertIn("--outcome sideways", err) + + +class Import(Scratch): + def test_an_entry_comes_in_from_its_file_and_another_list_under_its_id_is_refused(self): + entry = self.make("dev", "good\nmodel\n") + exported = os.path.join(self.tmp, "dev.json") + shutil.copy(sets.path_of("fakebench", "dev"), exported) + elsewhere = os.path.join(self.tmp, "elsewhere") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", exported) + self.assertEqual(code, 0, err) + self.assertEqual(read(sets.path_of("fakebench", "dev")), read(exported)) + code, out, err = self.cli("set", "import", exported) + self.assertEqual(code, 0, err) + self.assertIn("here already", out) + # here, the same id with another list + other = read(exported) + other["revisions"][0]["units"] = ["good", "wrong"] + other["revisions"][0]["hash"] = sets.content_hash("fakebench", "all", ["good", "wrong"]) + with open(exported, "w") as f: + json.dump(other, f) + code, out, err = self.cli("set", "import", exported) + self.assertEqual((code, out), (2, "")) + self.assertIn("the same id with another list", err) + self.assertEqual(sets.load("fakebench", "dev")["id"], entry["id"]) + self.assertEqual(sets.revision(sets.load("fakebench", "dev"))["units"], ["good", "model"]) + + def test_import_checks_every_consumed_field_before_storing_an_entry_or_job_record(self): + entry = dict(self.make("dev", "good\n"), schema=sets.SCHEMA) + cases = [("entry", k, None, True) for k in ("id", "name", "description", "benchmark", "dataset")] + cases += [("entry", k, v, False) for k, v in (("label", ""), ("label", 1), ("version", []), ("version", ""))] + cases += [("revision", k, None, True) for k in sets.REVISION] + cases += [("entry", k, v, False) for k, v in ( + ("id", 1), ("name", []), ("description", {}), ("benchmark", False), ("dataset", {}), + ("benchmark_options", {}), ("setup", "yours"))] + cases += [("revision", k, v, False) for k, v in ( + ("revision", True), ("date", None), ("date", []), ("date", ""), ("note", None), + ("note", {}), ("units", [1]), ("units", [{}]), ("units", "good"), ("hash", []))] + rec = sets.record(entry, sets.revision(entry)) + jobs = [(k, None, True) for k in sets.RECORD] + jobs += [(k, v, False) for k, v in (("id", 1), ("name", []), ("revision", True), ("revision", 0), + ("units", [1]), ("units", "good"), ("units", []), ("hash", []), + ("hash", "0" * 64))] + source_job = os.path.join(self.tmp, "source-job") + os.makedirs(source_job) + for index, (section, field, value, missing) in enumerate(cases + [("job",) + c for c in jobs]): + elsewhere = os.path.join(self.tmp, f"elsewhere-{index}") + with self.subTest(section=section, field=field, value=value, missing=missing): + if section == "job": + got = dict(rec) + target = got + else: + got = copy.deepcopy(entry) + target = got if section == "entry" else got["revisions"][0] + if missing: + del target[field] + else: + target[field] = value + if section == "job": + self.file(json.dumps({"runner": "standard", "datasets": [{"name": "fakebench/all"}], + "standard": {"benchmark": "fakebench", "task_set": got}}), + "source-job/config.json") + path = source_job + else: + path = self.file(json.dumps(got), "incoming.json") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", path) + self.assertEqual((code, out), (2, ""), err) + self.assertTrue(err.startswith("refused: "), err) + self.assertFalse(os.path.exists(elsewhere)) + + def test_an_entry_comes_in_from_a_job_that_ran_it(self): + entry = self.make("dev", "model\ngood\n", "--description", "two of them") + code, out, err = self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "--set", "dev", "--bench-option", "mode=hard", + "--name", "ran") + self.assertEqual(code, 0, out + err) + elsewhere = os.path.join(self.tmp, "elsewhere") + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": elsewhere}): + code, out, err = self.cli("set", "import", os.path.join(self.jobs, "ran")) + self.assertEqual(code, 0, err) + got = sets.load("fakebench", "dev") + # the record holds the set's id, name, label, hash and units: the rest is the job's or the import's + self.assertEqual({k: got[k] for k in ("id", "name", "label", "benchmark", "dataset", "description")}, + {**{k: entry[k] for k in ("id", "name", "label", "benchmark", "dataset")}, "description": ""}) + self.assertEqual([{k: r[k] for k in ("revision", "units", "hash")} for r in got["revisions"]], + [{k: r[k] for k in ("revision", "units", "hash")} for r in entry["revisions"]]) + self.assertEqual(got["revisions"][0]["note"], "from the job ran") + # the entry exported from here then adds nothing there: the same id, revision and hash + code, out, err = self.cli("set", "import", sets.path_of("fakebench", "dev", self.cat)) + self.assertEqual(code, 0, err) + self.assertIn("here already", out) + code, out, err = self.cli("set", "import", self.jobs) + self.assertEqual((code, out), (3, "")) + self.assertIn("no job", err) + # another set under the name: refused, the entry here unchanged + shutil.rmtree(os.path.join(self.cat, "sets")) + self.make("dev", "model\ngood\n") + code, out, err = self.cli("set", "import", os.path.join(self.jobs, "ran")) + self.assertEqual(code, 2) + self.assertIn("another id", err) + + +class Running(Scratch): + def run_cli(self, *args): + return self.cli("run", "fakebench", "nop", "--jobs", self.jobs, "-j", "2", *args) + + def test_an_empty_set_is_refused_before_any_unit(self): + code, out, err = self.run_cli("--set", "", "--name", "empty") + self.assertEqual(code, 2, out + err) + self.assertIn("not a task set's name", out) + self.assertFalse(os.path.exists(self.jobs)) + + def test_each_contradiction_is_refused_before_any_unit_with_a_plain_message(self): + self.make("dev", "good\nmodel\n") + for args, said in ((["--dataset", "responding"], "--dataset responding: the task set dev is cut from the dataset all"), + (["--units", self.file("good\n")], "the set lists the units, give one or the other"), + (["--set", "nowhere"], "no task set 'nowhere' of fakebench")): + with self.subTest(args=args): + code, out, err = self.run_cli(*(["--set", "dev"] if "--set" not in args else []), *args) + self.assertEqual(code, 2, out + err) + self.assertEqual(len(out.strip().splitlines()), 1, out) + self.assertTrue(out.startswith("refused: "), out) + self.assertIn(said, out) + self.assertFalse(os.path.exists(self.jobs)) # no job was begun + code, out, err = self.run_cli("--set", "dev", "--dataset", "all", "--bench-option", "mode=hard", "--name", "agrees") + self.assertEqual(code, 0, out + err) + + def test_two_runs_under_two_values_of_an_option_both_start_and_record_the_same_set(self): + entry = self.make("dev", "good\nwrong\n") + rev = sets.revision(entry) + records = [] + for value in ("plain", "hard"): + with self.subTest(value=value): + code, out, err = self.run_cli("--set", "dev", "--bench-option", f"mode={value}", "--name", value) + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(os.path.join(self.jobs, value)), ["good__u0000", "wrong__u0001"]) + cfg = read(os.path.join(self.jobs, value, "config.json")) + self.assertEqual(cfg["standard"]["benchmark_options"], {"mode": value}) + records.append(cfg["standard"]["task_set"]) + self.assertEqual(records[0], records[1]) + self.assertEqual({k: records[0][k] for k in ("id", "revision", "hash")}, + {"id": entry["id"], "revision": 1, "hash": rev["hash"]}) + self.assertEqual(rev["hash"], sets.content_hash("fakebench", "all", ["good", "wrong"])) # no option in it + + def listing_by_mode(self): + """The fake benchmark whose driver leaves slow and model out of its listing under mode=hard.""" + here = os.path.join(self.tmp, "fakebench") + shutil.copytree(self.b["_here"], here) + path = os.path.join(here, "driver.py") + with open(path) as f: + text = f.read() + text = text.replace(' units.remove("slow")\n', + ' units.remove("slow")\n' + ' if os.environ.get("NULLIUS_OPTION_MODE") == "hard":\n' + ' units = [u for u in units if u not in ("slow", "model")]\n') + with open(path, "w") as f: + f.write(text) + self.b["_here"] = here + + def test_ids_the_driver_does_not_list_under_the_runs_options_refuse_it_before_any_unit(self): + self.listing_by_mode() + self.make("dev", "good\nslow\nmodel\nwrong\n") + code, out, err = self.run_cli("--set", "dev", "--bench-option", "mode=hard", "--name", "hard") + self.assertEqual(code, 2, out + err) + self.assertIn("2 of the 4 ids of the task set dev are not listed by Fake bench's dataset all under the run's " + "options (mode=hard): slow, model", out) + job_dir = os.path.join(self.jobs, "hard") + self.assertEqual(self.trials(job_dir), []) + self.assertFalse(os.path.exists(os.path.join(job_dir, "config.json"))) + code, out, err = self.run_cli("--set", "dev", "--bench-option", "mode=plain", "--name", "plain") + self.assertEqual(code, 0, out + err) + + def test_the_message_names_the_first_five_ids_not_listed(self): + self.make("dev", "good\n" + "".join(f"gone{i}\n" for i in range(7))) + record = sets.record(sets.load("fakebench", "dev"), sets.revision(sets.load("fakebench", "dev"))) + r = run.Run(self.b, definitions.control(self.b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=record) + with self.assertRaises(run.Refused) as e: + r.start() + self.assertIn("7 of the 8 ids of the task set dev are not listed by Fake bench's dataset all under the run's " + "options (mode=plain): gone0, gone1, gone2, gone3, gone4, ...", str(e.exception)) + self.assertEqual(self.trials(r.job_dir), []) + self.assertFalse(os.path.exists(os.path.join(r.job_dir, "config.json"))) + + def test_the_units_run_are_the_sets_and_limit_and_shard_apply_after(self): + self.make("dev", "model\nwrong\nslow\n") + code, out, err = self.run_cli("--set", "dev", "--name", "whole") + self.assertEqual(code, 0, out + err) + self.assertEqual(self.trials(out.strip().splitlines()[-1]), ["model__u0003", "slow__u0002", "wrong__u0001"]) + # the set, then the shard, then the limit: shard 1 of 2 holds wrong and model of the three, and the limit keeps wrong + self.assertEqual([shard.of(u, 2) for u in DATASET], [1, 1, 2, 1]) + code, out, err = self.run_cli("--set", "dev", "--shard", "1/2", "--limit", "1", "--name", "part-shard-1of2") + self.assertEqual(code, 0, out + err) + part = out.strip().splitlines()[-1] + self.assertEqual(self.trials(part), ["wrong__u0001"]) + rec = read(os.path.join(part, "config.json"))["standard"]["shard"] + self.assertEqual((rec["units_total"], rec["planned"], rec["limit"]), (3, ["wrong"], 1)) + with open(os.path.join(part, feed.FEED)) as f: + self.assertEqual(next(e for e in map(json.loads, f) if e["event"] == "job.start")["tasks"], ["wrong"]) + + def test_the_config_records_the_set_and_the_runs_options(self): + self.b["datasets"] = [*self.b["datasets"], {"id": "responding", "units": 3}] + self.make("Dev set", "good\nmodel\n", "--dataset", "responding") + code, out, err = self.run_cli("--set", "dev-set", "--bench-option", "mode=hard", "--name", "first") + self.assertEqual(code, 0, out + err) + cfg = read(os.path.join(self.jobs, "first", "config.json")) + entry = sets.load("fakebench", "dev-set") + self.assertEqual(cfg["standard"]["task_set"], sets.record(entry)) + self.assertEqual(cfg["standard"]["task_set"], + {"id": entry["id"], "name": "dev-set", "label": "Dev set", "revision": 1, "hash": entry["revisions"][0]["hash"], + "units": ["good", "model"]}) + self.assertEqual(cfg["standard"]["benchmark_options"], {"mode": "hard"}) + self.assertNotIn("units_file", cfg["standard"]) + self.assertEqual(cfg["datasets"], [{"name": "fakebench/responding", "n_tasks": 2}]) + + def versions(self): + """The fake benchmark at two versions, each its own copy of the entry: at "2", its driver no longer lists slow.""" + here = os.path.join(self.tmp, "fakebench-2") + shutil.copytree(self.b["_here"], here) + path = os.path.join(here, "driver.py") + with open(path) as f: + text = f.read() + with open(path, "w") as f: + f.write(text.replace(' units.remove("slow")\n', + ' units.remove("slow")\n' + ' units = [u for u in units if u != "slow"]\n')) + one = dict(self.b, _version="1", _versions=["1", "2"], _default="2", _ref="fakebench@1", _labels={"1": "v1 (one)", "2": "v2"}) + return one, dict(one, _version="2", _ref="fakebench@2", _here=here) + + def test_a_set_made_at_a_version_records_it_and_a_run_at_another_that_lacks_a_task_is_refused(self): + one, two = self.versions() + entry = sets.create(one, "From one", dataset="all", units=["good", "slow"]) + self.assertEqual((entry["version"], sets.record(entry)["version"]), ("1", "1")) + self.assertEqual(sets.rows("fakebench")[0]["version"], "1") + r = run.Run(two, definitions.control(two, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=sets.record(entry)) + with self.assertRaises(run.Refused) as e: + r.start() + self.assertIn("the task set From one was made at Fake bench v1 (one), and slow is not a task of all at v2, the " + "version this run is at: run it at v1 (one), or make a set at v2", str(e.exception)) + self.assertEqual(self.trials(r.job_dir), []) + # at the version it was made at, or at another that holds all its tasks, it runs + for b, label in ((one, ""), (two, "Only good")): + if label: + entry = sets.create(one, label, dataset="all", units=["good"]) + r = run.Run(b, definitions.control(b, "nop"), model="", provider="openai", jobs_root=self.jobs, env={}, + say=lambda s: None, task_set=sets.record(entry), name=f"at-{b['_version']}-{entry['name']}") + r.start() + self.assertEqual(len(self.trials(r.job_dir)), len(sets.latest(entry)["units"])) + + def test_a_run_without_a_set_records_none(self): + code, out, err = self.run_cli("--name", "plain") + self.assertEqual(code, 0, out + err) + cfg = read(os.path.join(self.jobs, "plain", "config.json")) + self.assertEqual(sorted(cfg["standard"]), ["backend", "benchmark", "benchmark_options", "control", "exchanges", + "exchanges_max_mb", "kind", "needs", "permissions_granted", "plugged", + "provider", "retries", "unsandboxed", "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") + 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 d2b8120b9..02454668c 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]) @@ -244,6 +244,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 new file mode 100644 index 000000000..f7f5d6d9d --- /dev/null +++ b/app/tests/test_standard_units_listing.py @@ -0,0 +1,708 @@ +"""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; 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 +import io +import json +import os +import shutil +import sys +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius import paths +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.runner import sets, units + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +OSWORLD1 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nullius", "catalogue", + "benchmarks", "osworld1") +# 250 tasks: t000 ... t249; kind by i % 3, size by i % 2; under mode=short only the first 20 +DRIVER = r'''import json, os, sys +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "started"), "a") as f: + f.write("started\n") +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)] +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"}} +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): + """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): + 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", "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", "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"): + units.find(self.b, "all", categories={"colour": ["red"]}) + self.assertEqual(units.find(self.b, "all", categories={"kind": ["delta"]})["total"], 0) + + +class Pages(Scratch): + def test_250_tasks_come_as_three_pages_with_the_same_total(self): + pages = [units.find(self.b, "all", page=n) for n in (1, 2, 3, 4)] + self.assertEqual([len(p["tasks"]) for p in pages], [100, 100, 50, 0]) + self.assertEqual({(p["total"], p["pages"]) for p in pages}, {(250, 3)}) + self.assertEqual(sum((self.ids(p) for p in pages), []), [f"t{i:03d}" for i in range(250)]) + with self.assertRaisesRegex(units.Refused, "page 0"): + units.find(self.b, "all", page=0) + + +class WithoutDescribe(Scratch): + def test_the_listing_gives_ids_and_a_search_matches_ids(self): + got = units.find(self.plain, "all") + self.assertEqual((self.ids(got), got["described"], got["categories"]), (["good", "wrong", "slow", "model"], False, {})) + self.assertEqual(got["tasks"][0], {"id": "good", "title": "", "text": "", "categories": {}}) + self.assertEqual(self.ids(units.find(self.plain, "all", search="MOD")), ["model"]) + with self.assertRaisesRegex(units.Refused, "no such category; these tasks have none"): + units.find(self.plain, "all", categories={"kind": ["alpha"]}) + code, out, err = self.cli("units", "fakebench", "--dataset", "all", "--search", "od") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.splitlines(), ["2 of 4 tasks of all (its driver gives ids alone: a search reads the ids)", + " good", " model"]) + + +class Cache(Scratch): + def test_cache_links_cannot_read_or_write_outside_the_cache_root(self): + path = Path(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"})) + outside = Path(self.tmp, "outside-cache") + outside.mkdir() + cached = outside / "listing.json" + cached.write_text(json.dumps({"tasks": [], "described": False})) + for link, target in ((path.parent.parent, outside), (path.parent, outside), (path, cached)): + with self.subTest(link=link.name): + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(target, target_is_directory=target.is_dir()) + before = {p.name: p.read_bytes() for p in outside.iterdir()} + try: + with self.assertRaisesRegex(units.Refused, "outside the cache root"): + units.listing(self.b, "all") + self.assertEqual(units.state(self.b, "all")["state"], "refused") + self.assertEqual(self.starts(), 0) + self.assertEqual({p.name: p.read_bytes() for p in outside.iterdir()}, before) + finally: + link.unlink() + + def test_a_linked_cache_root_keeps_the_listing_under_its_resolved_root(self): + root = Path(paths.cache_dir()) + destination = Path(self.tmp, "cache-disk") + destination.mkdir() + root.parent.mkdir(parents=True, exist_ok=True) + root.symlink_to(destination, target_is_directory=True) + got = units.listing(self.b, "all") + path = Path(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"})) + self.assertTrue(path.resolve().is_relative_to(destination)) + self.assertEqual(json.loads(path.read_text()), got) + self.assertEqual(units.state(self.b, "all")["state"], "cached") + self.assertEqual(units.listing(self.b, "all"), got) + self.assertEqual(self.starts(), 1) + + def test_the_second_listing_starts_no_driver_and_another_option_lists_again(self): + units.find(self.b, "all") + units.find(self.b, "all", search="t1", page=2) + self.assertEqual(self.starts(), 1) + short = units.find(self.b, "all", {"mode": "short"}) + self.assertEqual((short["total"], self.starts()), (20, 2)) + units.find(self.b, "all", {"mode": "long"}) # the default, given: the same listing + self.assertEqual(self.starts(), 2) + self.assertTrue(units.cache_path(self.b, self.b["datasets"][0], {"mode": "long"}).startswith(paths.cache_dir())) + with self.assertRaisesRegex(units.Refused, "mode"): + units.find(self.b, "all", {"mode": "sideways"}) + with self.assertRaisesRegex(units.NotFound, "no dataset 'nope'"): + units.find(self.b, "nope") + + def test_a_driver_that_cannot_list_is_refused_with_its_words(self): + with open(os.path.join(self.b["_here"], "driver.py"), "w") as f: + f.write("import sys\nprint('the data is not there', file=sys.stderr)\nsys.exit(3)\n") + with self.assertRaisesRegex(units.Refused, "could not list the dataset all: .*the data is not there"): + units.find(self.b, "all") + self.assertEqual(os.listdir(os.path.join(paths.cache_dir(), units.FOLDER)), []) # nothing kept, no work left + + +class CommandLine(Scratch): + def test_the_command_prints_the_count_the_categories_and_the_tasks(self): + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "number 24", + "--category", "size=small") + self.assertEqual((code, err), (0, "")) + self.assertEqual(out.splitlines(), ["5 of 250 tasks of all", "kind: alpha 2, beta 2, gamma 1", "size: large 8, small 5", + " t241 Task number 241", " t243 Task number 243", " t245 Task number 245", + " t247 Task number 247", " t249 Task number 249"]) + code, out, err = self.cli("units", "described", "--dataset", "all", "--category", "kind=beta", "--json") + got = json.loads(out) + self.assertEqual((code, got["total"], got["pages"], len(got["tasks"])), (0, 83, 1, 83)) + + def test_the_longmemeval_help_example_names_a_known_dataset(self): + import shlex + example = next(line for line in cli.UNITS_EPILOG.splitlines() if "units longmemeval" in line) + args = shlex.split(example) + bench = definitions.get("benchmark", "longmemeval") + dataset = args[args.index("--dataset") + 1] + self.assertEqual(units.dataset_of(bench, dataset)["id"], "longmemeval_oracle") + self.assertEqual(units.option_values(bench, dataset, {"question_type": "multi-session"})["question_type"], + "multi-session") + + def test_refusals_are_one_line_on_stderr(self): + for args, code, said in ((["units", "nowhere", "--dataset", "all"], 3, "no benchmark 'nowhere'"), + (["units", "described", "--dataset", "nope"], 3, "no dataset 'nope'"), + (["units", "described", "--dataset", "all", "--category", "kind"], 2, "FIELD=VALUE"), + (["units", "described", "--dataset", "all", "--bench-option", "mode=x"], 2, "mode"), + (["units", "described", "--dataset", "all", "--bench-option", "broken"], 2, "NAME=VALUE")): + with self.subTest(args=args): + got, out, err = self.cli(*args) + self.assertEqual((got, out), (code, "")) + self.assertTrue(err.startswith("refused: ") and said in err and len(err.splitlines()) == 1, err) + + +class SetFromAFilter(Scratch): + def test_the_ids_stored_are_the_ones_the_listing_gives_and_the_note_holds_the_filter(self): + code, out, err = self.cli("set", "create", "described", "picked", "--dataset", "all", "--search", "number 24", + "--category", "kind=alpha", "--category", "kind=beta") + self.assertEqual(code, 0, err) + entry = sets.load("described", "picked") + listed = units.find(self.b, "all", search="number 24", categories={"kind": ["alpha", "beta"]}, size=None) + self.assertEqual(sets.revision(entry)["units"], self.ids(listed)) + self.assertEqual(sets.revision(entry)["units"], ["t024", "t124", "t240", "t241", "t243", "t244", "t246", "t247", "t249"]) + self.assertEqual(sets.revision(entry)["note"], + 'matched by --search "number 24" --category kind=alpha --category kind=beta') + code, out, err = self.cli("set", "create", "described", "by-kind", "--dataset", "all", "--category", "kind=gamma") + self.assertEqual(code, 0, err) + self.assertEqual(len(sets.revision(sets.load("described", "by-kind"))["units"]), 83) + + def test_a_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, 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, 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 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") + 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", "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\""), + (["--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"))) + + +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 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 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 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 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 + + 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"} + 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-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-env")) + 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} + + +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": "", "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": "", "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"}, + {"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": "", "needs": []}) + + def test_full_and_the_environment_it_installs(self): + 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") + + 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") + + 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): + data = os.path.join(self.tmp, "fetched.json") + self.b = dict(self.b, datasets=[{"id": "all", "url": "https://example.org/all.json", "sha256": "b" * 64, + "units": 250}]) + + def fetched(url, sha256, progress=None): + open(data, "w").close() + return data + + with mock.patch.object(units.install, "download", side_effect=fetched) as download: + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") + self.assertEqual((code, out.splitlines()[0], err), (0, "1 of 250 tasks of all", + "first listing of all: fetching the dataset " + "https://example.org/all.json\n")) + code, out, err = self.cli("units", "described", "--dataset", "all", "--search", "t042") + self.assertEqual((code, err, download.call_count, self.starts()), (0, "", 1, 1)) # the second from the cache + + def test_a_program_not_on_this_machine_is_refused_before_anything_is_fetched(self): + self.b = dict(self.b, driver=dict(HEAVY, list_command=["/nonexistent/python3", "{here}/driver.py"])) + with no_environment(): + code, out, err = self.cli("units", "described", "--dataset", "all") + self.assertEqual((code, out, self.starts()), (2, "", 0)) + self.assertEqual(err, "refused: cannot prepare described's dataset all for its listing: " + "/nonexistent/python3 is not on this machine\n") + + +def osworld1_upstream(tmp: str, tasks: dict) -> str: + """An upstream folder of OSWorld's shape holding ``tasks`` ({domain: {id: instruction}}); its dataset file's path.""" + for domain, ids in tasks.items(): + os.makedirs(os.path.join(tmp, "evaluation_examples", "examples", domain)) + for eid, instruction in ids.items(): + with open(os.path.join(tmp, "evaluation_examples", "examples", domain, eid + ".json"), "w") as f: + json.dump({"id": eid, "instruction": instruction}, f) + meta = os.path.join(tmp, "test_small.json") + with open(meta, "w") as f: + json.dump({d: list(ids) for d, ids in tasks.items()}, f) + return meta + + +class OSWorld1Light(Scratch): + def test_its_light_listing_gives_the_drivers_ids_in_its_order_with_no_environment(self): + up = os.path.join(self.tmp, "upstream") + meta = osworld1_upstream(up, {"vlc": {"v2": "Play the video.", "v1": "Mute it."}, "chrome": {"c1": "Open a tab."}}) + bench = definitions.get("benchmark", "osworld1") + with mock.patch.object(units.install, "upstream", return_value=up), \ + mock.patch.object(units.install, "dataset", return_value=meta), no_environment(): + got = units.listing(bench, "test_small") + earlier = units.listing(definitions.get("benchmark", "osworld1@044bc33"), "test_small") + self.assertEqual(earlier["tasks"], got["tasks"]) # each version lists by the same light start + import importlib.util + spec = importlib.util.spec_from_file_location("osworld1_driver_units", os.path.join(OSWORLD1, "driver.py")) + driver = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"NULLIUS_UPSTREAM": up, "NULLIUS_DATASET": meta}), \ + mock.patch.object(sys, "argv", ["driver.py"]): + spec.loader.exec_module(driver) + ids = driver.units(dataset="test_small")["units"] + self.assertEqual([t["id"] for t in got["tasks"]], ids) + self.assertEqual(ids, ["vlc__v2", "vlc__v1", "chrome__c1"]) + self.assertEqual(got["tasks"][0], {"id": "vlc__v2", "title": "Play the video.", "text": "Play the video.", + "categories": {"domain": "vlc"}}) + + +class OSWorld1(unittest.TestCase): + def test_describe_gives_each_tasks_instruction_and_domain_from_its_file(self): + tmp = tempfile.mkdtemp(prefix="nullius-osworld1-") + self.addCleanup(shutil.rmtree, tmp, True) + long = "Please " + "open the settings and change the theme " * 4 + "now." + tasks = {"chrome": {"c1": "Open a new tab."}, "vlc": {"v1": long}} + for domain, ids in tasks.items(): + os.makedirs(os.path.join(tmp, "evaluation_examples", "examples", domain)) + for eid, instruction in ids.items(): + with open(os.path.join(tmp, "evaluation_examples", "examples", domain, eid + ".json"), "w") as f: + json.dump({"id": eid, "instruction": instruction}, f) + meta = os.path.join(tmp, "test_small.json") + with open(meta, "w") as f: + json.dump({d: list(ids) for d, ids in tasks.items()}, f) + import importlib.util + spec = importlib.util.spec_from_file_location("osworld1_driver_describe", os.path.join(OSWORLD1, "driver.py")) + driver = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"NULLIUS_UPSTREAM": tmp, "NULLIUS_DATASET": meta}), \ + mock.patch.object(sys, "argv", ["driver.py"]): + spec.loader.exec_module(driver) + got = driver.describe(dataset="test_small")["units"] + self.assertIs(driver.HANDLERS["describe"], driver.describe) + self.assertEqual(list(got), ["chrome__c1", "vlc__v1"]) + self.assertEqual(got["chrome__c1"], {"title": "Open a new tab.", "text": "Open a new tab.", + "categories": {"domain": "chrome"}}) + self.assertEqual(got["vlc__v1"]["text"], long) + self.assertTrue(got["vlc__v1"]["title"].endswith(" ...") and len(got["vlc__v1"]["title"]) <= 104) + self.assertTrue(long.startswith(got["vlc__v1"]["title"][:-4])) + self.assertEqual(got["vlc__v1"]["categories"], {"domain": "vlc"}) + with open(os.path.join(OSWORLD1, "standard.json")) as f: + self.assertIs(json.load(f)["driver"]["describe"], True) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_task_set_recipe.py b/app/tests/test_task_set_recipe.py new file mode 100644 index 000000000..373ba5c62 --- /dev/null +++ b/app/tests/test_task_set_recipe.py @@ -0,0 +1,141 @@ +"""A task set in the builder's recipe and on a host: ``task_sets`` compiles to ``--set NAME`` beside the +dataset, its label and count in the Review step; a set of another benchmark or dataset is refused; the runner snapshot a +host receives carries the recipe's sets, and a run started from it there reads the set and records it. No key, +no network: the runs are the fake benchmark's control.""" +from __future__ import annotations + +import io +import json +import os +import shutil +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius import progress +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.requirements import install +from nullius.standard.runner import payload, sets + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +NOP = {"nop": {"source": "nullius", "from": "nothing said"}} + + +class Scratch(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-set-recipe-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.cat = self.tmp / "catalogue" + self.b = dict(definitions.get("benchmark", "fakebench", ROOT), controls=NOP, + datasets=[{"id": "all", "units": 4}, {"id": "more", "units": 4}]) + self.memo = definitions.get("benchmark", "fakememo", ROOT) + for patch in (mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(self.cat)}), + mock.patch.object(install, "HOME", str(self.tmp / "home")), mock.patch.object(progress, "ECHO", None)): + patch.start() + self.addCleanup(patch.stop) + self.defs = {"benchmark": [self.b, self.memo], "agent": [], "capability": []} + + def recipe(self, **kw): + r = {"version": 1, "harness": "standard", "name": "fake-sets", "title": "t", "benchmark": "fakebench", "datasets": ["all"], + "others": ["nop"], "provider": "openai", "model": "", "concurrency": 1, "where": "local"} + r.update(kw) + return r + + def compile(self, **kw): + return recipe.compile(self.recipe(**kw), self.defs) + + +class TheRecipe(Scratch): + def test_a_set_compiles_to_set_name_and_review_names_its_label_and_its_count(self): + sets.create(self.b, "Dev set", dataset="all", units=["good", "wrong", "slow"]) + # a recipe from before sets were frozen names it NAME@1: the same set + for ref, n in (("dev-set", 3), ("dev-set@1", 3)): + with self.subTest(ref=ref): + out = self.compile(task_sets={"all": ref}) + self.assertEqual(out["errors"], []) + self.assertIn("--dataset all --set dev-set -j 1", out["shards"][0]["command"]) + dataset_row = next(r for r in out["review"] if r[1] == "Dataset") + self.assertEqual(dataset_row[2], f"all · task set Dev set · {n} tasks") + self.assertNotIn("revision", json.dumps(out["review"])) + self.assertTrue(next(r for r in out["review"] if r[1] == "Scope")[2].startswith(f"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.""" + + def test_the_snapshot_carries_the_recipes_sets_and_the_run_there_records_the_set(self): + entry = sets.create(self.b, "settings", dataset="all", units=["good", "wrong"]) + r = self.recipe(task_sets={"all": "settings"}) + self.assertEqual(payload.recipe_sets(r), [("fakebench", "settings")]) + self.assertEqual(payload.recipe_sets(self.recipe()), []) + empty = self.tmp / "empty-package" + shutil.copytree(Path(payload.PACKAGE), empty, ignore=shutil.ignore_patterns("__pycache__", "catalogue", "kits")) + key0, _ = payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat)) + key, here = payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), sets=payload.recipe_sets(r)) + self.assertNotEqual(key, key0) + self.assertEqual(payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), + sets=payload.recipe_sets(r)), (key, here)) + carried = Path(here) / "app/nullius/catalogue/sets/fakebench/settings.json" + self.assertEqual(json.loads(carried.read_text())["id"], entry["id"]) + for name in ("gone", "../settings"): + with self.assertRaises(ValueError): + payload.build(str(self.tmp / "cache"), package=empty, catalogue=str(self.cat), sets=[("fakebench", name)]) + # on the host: the snapshot's catalogue copied for the run (execution: cp -R .../app/nullius/catalogue), read there + run_catalogue = self.tmp / "host" / "runs" / "fake-sets" / "catalogue" + shutil.copytree(Path(here) / "app/nullius/catalogue", run_catalogue) + shutil.rmtree(self.cat) # nothing of this machine's catalogue is left to read + jobs = self.tmp / "host" / "runs" / "fake-sets" / "jobs" + out, err = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(run_catalogue)}), \ + mock.patch.object(cli, "_bench", return_value=self.b), mock.patch.object(cli, "_exit_on_term"), \ + mock.patch.object(cli.settings, "load"), redirect_stdout(out), redirect_stderr(err): + code = cli.main(["run", "fakebench", "nop", "--dataset", "all", "--set", "settings", "-j", "1", "--name", "fake-sets", + "--jobs", str(jobs)]) + self.assertEqual(code, 0, out.getvalue() + err.getvalue()) + cfg = json.loads((jobs / "fake-sets" / "config.json").read_text()) + self.assertEqual(cfg["standard"]["task_set"], sets.record(entry)) + self.assertEqual(sorted(d for d in os.listdir(jobs / "fake-sets") if "__u" in d), ["good__u0000", "wrong__u0001"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_builder_limits.py b/app/ui_tests/test_builder_limits.py index 5854667ee..8486e9972 100644 --- a/app/ui_tests/test_builder_limits.py +++ b/app/ui_tests/test_builder_limits.py @@ -69,3 +69,21 @@ def test_a_click_on_a_card_of_what_the_record_keeps_reaches_the_command_line(sel else: # the default: the run is told nothing self.assertNotIn("exchanges", kept) self.assertNotIn("--exchanges", out["script"]) + + def test_the_number_of_tasks_says_all_of_them_and_takes_that_many_at_most(self): + field = lambda html: re.search(r'