From 39658f0d8d4af429553266738d7b54792406fc93 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 17:26:36 +0100 Subject: [PATCH 1/3] feat(catalogue): add suites, a fixed selection of tasks from several benchmarks --- app/nullius/standard/cli.py | 9 +- app/nullius/standard/pages/recipe.py | 28 ++- app/nullius/standard/runner/sets.py | 29 +++ app/nullius/standard/runner/suites.py | 211 +++++++++++++++++++ app/templates/catalogue/benchmarks.html | 5 +- app/templates/catalogue/suite.html | 25 +++ app/tests/fixtures/suites/smoke/2026-12.json | 11 + app/tests/fixtures/suites/smoke/suite.json | 16 ++ app/tests/test_suites.py | 149 +++++++++++++ app/ui_tests/test_every_route.py | 2 + app/ui_tests/test_suite_routes.py | 85 ++++++++ app/web/catalogue.py | 34 ++- docs/concepts.md | 1 + pyproject.toml | 2 +- 14 files changed, 601 insertions(+), 6 deletions(-) create mode 100644 app/nullius/standard/runner/suites.py create mode 100644 app/templates/catalogue/suite.html create mode 100644 app/tests/fixtures/suites/smoke/2026-12.json create mode 100644 app/tests/fixtures/suites/smoke/suite.json create mode 100644 app/tests/test_suites.py create mode 100644 app/ui_tests/test_suite_routes.py diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 7fcc6092b..9a7e69800 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -111,7 +111,7 @@ from nullius.standard.calls import exchanges, relay from nullius.standard.contract import definitions, match, ports, proofs from nullius.standard.proofs import conform, fidelity, pins, prove -from nullius.standard.runner import job, merge, rerun, run, sets, shard +from nullius.standard.runner import job, merge, rerun, run, sets, shard, suites from nullius.standard.runner import units as unit_list ENV_FILE = paths.settings_file() @@ -245,6 +245,13 @@ def cmd_list(a): print(f" {'':<18} and the skills " + "; ".join(f"{', '.join(s)} of {p}" for p, s in d["needs_skills"].items())) for note in ([] if kind == "benchmark" else older(d) + skills(d)): print(f" {'':<18} {note}") + found, bad_suites = suites.load() + bad += bad_suites + if found: + print("suites:") + for s in found: + print(f" {s['ref']:<18} {suites.tasks(s)} tasks of {len({m['benchmark'] for m in s['members']})} benchmarks" + + (f" · {s['left_out']} without an id left out" if s["left_out"] else "")) t = match.table(got["benchmark"], got["agent"], got["module"]) print("pairs:") for b, row in t.items(): diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 548d81a69..2685874cc 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -47,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, sets +from nullius.standard.runner import run, sets, suites from nullius.standard.runner import units as listing from nullius.standard.runner.retries import MAX_RETRIES @@ -249,6 +249,32 @@ def _bench_page(b: dict) -> dict: for d in b["datasets"]]} +def suite_page(s: dict, benches: List[dict]) -> dict: + """A suite as the builder reads a benchmark (``_bench_page``'s fields): its members are its datasets, each named + by its benchmark, with no task set, option or proof of its own to choose - those are each member's. It takes + agents; the checks are the ones a member declares. ``members``: its rows by benchmark, as its page lists them + (``setup``: the procedure a member that takes no agent runs).""" + rows = suites.groups(s, benches) + retired = [(g["bench"].get("score") or {}).get("judge") for g in rows if ((g["bench"].get("score") or {}).get("judge") or {}).get("retired")] + blank = _bench_page({"key": s["key"], "label": s["label"], "summary": s["summary"], "family": "agent", "datasets": []}) + several = lambda g: len(g["bench"]["datasets"]) > 1 + label_of = lambda g, m: next(x.get("label") or x["id"] for x in g["bench"]["datasets"] if x["id"] == m["dataset"]) + return dict(blank, suite=True, ref=s["ref"], version=s["version"], procedure="", units={"noun": "task", "nouns": "tasks"}, + versions=[{"ref": s["key"] if v == s["default"] else f"{s['key']}@{v}", "version": v, "default": v == s["default"], + "choice_label": v, "label": v, "origin": "official"} for v in s["versions"]], + controls=[{"key": c, "label": definitions.CONTROL_LABEL[c], "source": "nullius", "from": "Each member's own check.", + "expect": {}, "must": ""} for c in definitions.CONTROLS if any(definitions.control(g["bench"], c) for g in rows)], + judged=any((g["bench"].get("score") or {}).get("judge") for g in rows), judge=", ".join(j["model"] for j in retired), + judge_retired=bool(retired), simulator="each member's own" if any(g["bench"].get("simulator") for g in rows) else "", + datasets=[{"id": m["id"], "label": g["bench"]["label"] + (f" · {label_of(g, m)}" if several(g) else ""), "summary": "", + "units": len(m["units"]), "judge": "", "environment": "", "subset_of": "", "controls": [], "selections": [], + "proofs": {}, "failed": {}, "sets": []} for g in rows for m in g["members"]], + members=[{"key": g["bench"]["key"], "label": g["bench"]["label"], "setup": g["settings"].get("setup", ""), + "backend": g["settings"].get("backend", ""), "pin": g["members"][0]["version"], "version": g["bench"].get("_version") or "", + "datasets": [{"id": m["dataset"], "label": label_of(g, m), "tasks": len(m["units"])} for m in g["members"]], + "tasks": suites.tasks(s, g["members"])} for g in rows]) + + def protocol(o: dict) -> str: """How Nullius talks to it, in a word or two for a page, in sentence case as its filter names it.""" if o["_kind"] == "control": diff --git a/app/nullius/standard/runner/sets.py b/app/nullius/standard/runner/sets.py index 32ab6ea06..78cb9568c 100644 --- a/app/nullius/standard/runner/sets.py +++ b/app/nullius/standard/runner/sets.py @@ -509,6 +509,35 @@ def create(bench: dict, label: str, *, dataset: Optional[str] = None, units: Opt return entry +def frozen(bench: dict, name: str, label: str, parts: dict, *, set_id: str, description: str = "", root: Optional[str] = None, + save: bool = True) -> dict: + """The set ``name`` of ``bench`` holding ``parts`` ({dataset: units}) under the id ``set_id``: what a suite makes of + its tasks (``suites.freeze``). Made when no set has the name, under the benchmark's lock (``_changing``), or reused + when the one there has this id and list. Refused where the name holds another id or list. ``save=False``: the + entry as it would be made, nothing written and no lock taken (a preview).""" + given = {_dataset(bench, d): _ids(ids, f"the set {name} of {d}") for d, ids in parts.items()} + entry = {"id": set_id, "name": check_name(name), "label": check_label(label), "description": description, "benchmark": bench["key"], + **({"version": version_of(bench)} if version_of(bench) else {}), + **({"datasets": list(given)} if len(given) > 1 else {"dataset": next(iter(given))})} + listed = given if len(given) > 1 else next(iter(given.values())) + path = path_of(bench["key"], name, root) + + def there(): + have = load(bench["key"], name, root) + if have["id"] != set_id or latest(have)["hash"] != _hash_of(entry, listed): + raise Refused(f"a task set {name!r} of {bench['key']} holds another list ({path}): rename or delete it") + return have + entry["revisions"] = [{"revision": 1, "date": _now(), "note": "", "parts" if len(given) > 1 else "units": listed, + "hash": _hash_of(entry, listed)}] + if not save: + return there() if os.path.lexists(path) else entry + with _changing(bench["key"], root): + if os.path.lexists(path): + return there() + 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) diff --git a/app/nullius/standard/runner/suites.py b/app/nullius/standard/runner/suites.py new file mode 100644 index 000000000..94491b8f7 --- /dev/null +++ b/app/nullius/standard/runner/suites.py @@ -0,0 +1,211 @@ +"""Suites: a fixed selection of tasks from several benchmarks, run as ordinary runs, one after the other. + +An entry is ``suites//suite.json`` in the catalogue, the user's folder +over the bundled one of the same name (``catalogue.storage``). It is a +catalogue kind of its own: it has no driver, no upstream and no proofs. It +names its versions, each dated (``2026-12``) and frozen: a version is one +list of tasks, kept in a file of its own beside the entry (``tasks``), and +what the suite fixes for a member benchmark (``settings``). + +The task file holds ``{"tasks": [{benchmark, version, dataset, task}, ...]}``; +any other field is ignored. ``version`` is the member benchmark's pin: its +catalogue version, or the commit its definition was tested at. A task without +an id (a place drawn later) is left out and counted (``left_out``). + +A member is one dataset of one benchmark at its pin, with its unit ids. What +runs is the member benchmark's own definition and driver: ``freeze`` makes of +each benchmark's tasks an ordinary task set (``sets.frozen``), and ``plan`` +says, for the participants chosen, what runs each member, for the recipe's +compile and the command alike. An agent runs the suite only when it fits +every chosen member that takes an agent, on the backend each run gets +(``backend_for``): ``plan`` keeps why not, by member. + +A suite's key is no benchmark's: one that is, is left out and said (``load``). + +``settings``, by benchmark: ``setup`` (``model`` or ``original``) for a member +that takes no agent, which then runs its own procedure with the run's model, once; +``backend`` and ``bench_options``, the member's own over the run's. +""" +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import uuid +from typing import Dict, List, Optional, Tuple + +from nullius.catalogue import storage +from nullius.standard.contract import definitions, match +from nullius.standard.runner import sets + +SCHEMA = "nullius.suite/v1" +GROUP = "suites" +FILE = "suite.json" +SETTINGS = ("setup", "backend", "bench_options") +_VERSION = re.compile(r"^\d{4}-\d{2}(?:-\d{2})?(?:\.\d+)?$") +_FILE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\.json$") +_NAMESPACE = uuid.UUID("6f1c2d3e-5b7a-4c8d-9e0f-1a2b3c4d5e6f") + + +class Refused(Exception): + """The suite cannot be read or run as asked; the message says why.""" + + +def _members(path: str) -> Tuple[List[dict], int]: + """(members, tasks left out) of a task file: a member per benchmark and dataset, in the file's order.""" + with open(path, encoding="utf-8") as f: + doc = json.load(f) + tasks = doc.get("tasks") if isinstance(doc, dict) else None + if not isinstance(tasks, list) or not tasks: + raise ValueError("no tasks") + found: Dict[tuple, dict] = {} + left_out = 0 + for t in tasks: + if not isinstance(t, dict) or not all(isinstance(t.get(k), str) and t[k] for k in ("benchmark", "version", "dataset")): + raise ValueError("a task names its benchmark, version and dataset") + if t.get("task") is None: + left_out += 1 + continue + if not isinstance(t["task"], str) or not t["task"]: + raise ValueError("a task's id is text") + m = found.setdefault((t["benchmark"], t["dataset"]), {"id": f"{t['benchmark']}.{t['dataset']}", "benchmark": t["benchmark"], + "version": t["version"], "dataset": t["dataset"], "units": []}) + if m["version"] != t["version"]: + raise ValueError(f"{t['benchmark']} is pinned twice") + if t["task"] in m["units"]: + raise ValueError(f"{m['id']} lists {t['task']} twice") + m["units"].append(t["task"]) + pins = {} + for m in found.values(): + if pins.setdefault(m["benchmark"], m["version"]) != m["version"]: + raise ValueError(f"{m['benchmark']} is pinned twice") + return list(found.values()), left_out + + +def content_hash(members: List[dict], settings: Optional[dict] = None) -> str: + """The sha256 over what a version runs: each member's benchmark, pin, dataset and ids, sorted, and what it + fixes for a benchmark (``settings``).""" + doc = [sorted((m["benchmark"], m["version"], m["dataset"], sorted(m["units"])) for m in members), + {k: v for k, v in sorted((settings or {}).items()) if v}] + # keys sorted at every depth: the same settings written in another order are the same version + return hashlib.sha256(json.dumps(doc, separators=(",", ":"), ensure_ascii=False, sort_keys=True).encode()).hexdigest() + + +def _read(folder: str, key: str) -> List[dict]: + """Every version of the entry in ``folder``, resolved; ValueError says what is wrong with it.""" + with open(os.path.join(folder, FILE), encoding="utf-8") as f: + d = json.load(f) + if not isinstance(d, dict) or d.get("schema") != SCHEMA: + raise ValueError(f"schema {SCHEMA}") + if d.get("key") != key or not definitions._KEY.match(key): + raise ValueError("its key is its folder's name") + for k in ("label", "summary"): + if not isinstance(d.get(k), str) or not d[k]: + raise ValueError(f"no {k}") + versions = d.get("versions") + if not isinstance(versions, dict) or not versions or d.get("default") not in versions: + raise ValueError("versions, and the default among them") + out = [] + for v, block in versions.items(): + if not _VERSION.match(v): + raise ValueError(f"version {v}: a date, YYYY-MM") + if not isinstance(block, dict) or set(block) - {"tasks", "settings"} or not _FILE.match(str(block.get("tasks") or "")): + raise ValueError(f"version {v}: tasks, a file beside {FILE}, and settings") + settings = block.get("settings") or {} + if not isinstance(settings, dict) or any(not isinstance(s, dict) or set(s) - set(SETTINGS) for s in settings.values()): + raise ValueError(f"version {v}: settings are {', '.join(SETTINGS)}, by benchmark") + try: + members, left_out = _members(os.path.join(folder, block["tasks"])) + except (OSError, ValueError) as e: + raise ValueError(f"version {v}: {block['tasks']}: {e}") + for b, s in settings.items(): + if b not in {m["benchmark"] for m in members}: + raise ValueError(f"version {v}: settings of {b}, which is no member") + if s.get("setup", "model") not in definitions.SETUPS or s.get("backend", "local") not in definitions.names.BACKENDS \ + or not isinstance(s.get("bench_options", {}), dict): + raise ValueError(f"version {v}: settings of {b}") + out.append({"key": key, "label": d["label"], "summary": d["summary"], "version": v, "versions": list(versions), + "default": d["default"], "ref": key if v == d["default"] else f"{key}@{v}", "members": members, + "settings": settings, "left_out": left_out, "hash": content_hash(members, settings), "_here": folder}) + return out + + +def load(root: Optional[str] = None) -> Tuple[List[dict], List[str]]: + """Every version of every suite, in folder order, and what is wrong with the entries left out.""" + out, bad = [], [] + benchmarks = storage.folders(definitions.KINDS["benchmark"]["dir"], definitions.CATALOGUE, root) + for key, folder in storage.folders(GROUP, definitions.CATALOGUE, root).items(): + if key in benchmarks: # else a recipe or a command naming the benchmark would run the suite + bad.append(f"suite {key}: a benchmark has this key: give the suite another") + continue + try: + out += _read(folder, key) + except (OSError, ValueError) as e: + bad.append(f"suite {key}: {e}") + return out, bad + + +def find(ref: str, root: Optional[str] = None) -> Optional[dict]: + """The suite ``ref`` names: ``key`` for its default version, or ``key@version``.""" + return next((s for s in load(root)[0] if ref in (s["ref"], f"{s['key']}@{s['version']}")), None) + + +def tasks(s: dict, members: Optional[List[dict]] = None) -> int: + return sum(len(m["units"]) for m in (s["members"] if members is None else members)) + + +def set_name(s: dict) -> str: + """The name of the task set each member benchmark runs: the suite's key and version.""" + return f"{s['key']}-{s['version']}" + + +def workspace(s: dict) -> str: + """The workspace a suite's jobs go into: its own, so a run of some of a benchmark's tasks sets no other aside.""" + return "suite-" + re.sub(r"[^a-z0-9]+", "-", set_name(s)) + + +def bench_of(benches: List[dict], member: dict) -> Optional[dict]: + """The member's benchmark at its pin among the resolved definitions (every version), or None.""" + return next((b for b in benches if b["key"] == member["benchmark"] + and member["version"] in (b.get("_version"), (b.get("upstream") or {}).get("tested"))), None) + + +def groups(s: dict, benches: List[dict], chosen: Optional[List[str]] = None) -> List[dict]: + """The suite's members by benchmark, in order: [{bench, members, settings}], ``chosen`` the member ids taken + (all when None). Refused: a member no definition of the standard has at its pin.""" + out: Dict[str, dict] = {} + for m in s["members"]: + if chosen is not None and m["id"] not in chosen: + continue + b = bench_of(benches, m) + if b is None: + has = any(x["key"] == m["benchmark"] for x in benches) + raise Refused(f"{s['label']} pins {m['benchmark']} at {m['version'][:12]}, " + ( + "which its definition no longer has: a moved pin is another version of the suite" if has + else "which has no definition of the standard: a suite's members run through the Nullius standard")) + if m["dataset"] not in {d["id"] for d in b["datasets"]}: + raise Refused(f"{b['label']} has no dataset {m['dataset']} at {m['version'][:12]}") + out.setdefault(m["benchmark"], {"bench": b, "members": [], "settings": s["settings"].get(m["benchmark"]) or {}})["members"].append(m) + return list(out.values()) + + +def freeze(s: dict, benches: List[dict], chosen: Optional[List[str]] = None, *, save: bool = True, + root: Optional[str] = None) -> Dict[str, dict]: + """By benchmark with a member taken, its tasks in the suite as its task set ``set_name`` (the entry): made or + reused under the benchmark's sets lock, its id from the suite's hash, so the same version makes the same set + anywhere. ``save=False``: as it would be, nothing written (a preview). Refused where the name holds another list.""" + taken = {g["bench"]["key"] for g in groups(s, benches, chosen)} + out = {} + # the set is the benchmark's whole selection, whichever of its members are taken; a benchmark with none taken is not resolved + for g in groups(s, benches, [m["id"] for m in s["members"] if m["benchmark"] in taken]): + b = g["bench"] + try: + out[b["key"]] = sets.frozen(b, set_name(s), f"{s['label']} {s['version']}", {m["dataset"]: m["units"] for m in g["members"]}, + set_id=uuid.uuid5(_NAMESPACE, f"{s['hash']}:{b['key']}").hex, + description=f"{b['label']}'s tasks in the suite {s['label']}, version {s['version']}.", + root=root, save=save) + except sets.Refused as e: + raise Refused(str(e)) + return out diff --git a/app/templates/catalogue/benchmarks.html b/app/templates/catalogue/benchmarks.html index a42576555..804c46323 100644 --- a/app/templates/catalogue/benchmarks.html +++ b/app/templates/catalogue/benchmarks.html @@ -35,7 +35,10 @@ dict(key='blocker', label='Blocker', card='alert')] %} {% set sort = ['title', 'tasks', 'datasets'] %} {% call cards('benchmarks', cols, items, search='Name, category, dataset', choices=choices, sort=sort, empty='No benchmark matches.', noun='benchmarks', layout='table' if request.args.get('view') == 'table' else 'cards', default='cards') %} - {{ grid(cols, items, every=items, choices=choices, sort=sort) }} + {%- set suites = items|selectattr('suite', 'defined')|list %} + {% if suites %}

Suites

{{ grid(cols, suites, every=items, choices=choices, sort=sort) }}
+

Benchmarks

{{ grid(cols, items|rejectattr('suite', 'defined')|list, every=items, choices=choices, sort=sort) }}
+ {% else %}{{ grid(cols, items, every=items, choices=choices, sort=sort) }}{% endif %} {% endcall %} {% endblock %} diff --git a/app/templates/catalogue/suite.html b/app/templates/catalogue/suite.html new file mode 100644 index 000000000..077da729b --- /dev/null +++ b/app/templates/catalogue/suite.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% from '_page.html' import page_head %} +{% from '_cards.html' import cards %} +{% block title %}{{ s.label }} · Nullius{% endblock %} +{% block crumb %}/ benchmarks / {{ s.key }}{% endblock %} +{% block head %} +{% endblock %} +{% block body %} +{#- A suite's page (web/catalogue.py, suite_page): its members by benchmark, each at its pin. -#} +
+ {% set tags %}Suite {{ s.members|map(attribute='benchmark')|unique|list|length }} benchmarks · {{ s.members|map(attribute='units')|map('length')|sum }} tasks{% endset %} + {{ page_head(s.label, sub=tags) }} +

{{ s.summary }}

+ {% if s.versions|length > 1 %} + {% endif %} + {% if problem %}

{{ problem }}

{% endif %} +

Members {{ s.version }}

+ {% set cols = [dict(key='title', label='Benchmark', card='title'), dict(key='pin', label='Pinned at', card='text', class='mono'), + dict(key='datasets', label='Datasets', card='text'), dict(key='tasks', label='Tasks', card='stat', type='num'), + dict(key='runs', label='Run by', card='text'), dict(key='backend', label='Backend', card='text')] %} + {{ cards('suite-members', cols, items, search='Benchmark, dataset', sort=['title', 'tasks'], empty='No member matches.', noun='benchmarks', layout='table', default='table') }} +
+{% endblock %} diff --git a/app/tests/fixtures/suites/smoke/2026-12.json b/app/tests/fixtures/suites/smoke/2026-12.json new file mode 100644 index 000000000..522f6decf --- /dev/null +++ b/app/tests/fixtures/suites/smoke/2026-12.json @@ -0,0 +1,11 @@ +{ + "tasks": [ + {"benchmark": "gsm8k", "version": "3101c7d5072418e28b9008a6636bde82a006892c", "dataset": "test", "task": "0012"}, + {"benchmark": "gsm8k", "version": "3101c7d5072418e28b9008a6636bde82a006892c", "dataset": "test", "task": "0110"}, + {"benchmark": "humaneval", "version": "6d43fb980f9fee3c892a914eda09951f772ad10d", "dataset": "humaneval", "task": "HumanEval/17"}, + {"benchmark": "simpleqa", "version": "652c89d0ca9df547706735883097e9537d40dc47", "dataset": "simpleqa", "task": "0173"}, + {"benchmark": "longmemeval", "version": "9e0b455f4ef0e2ab8f2e582289761153549043fc", "dataset": "longmemeval_oracle", "task": "4c36ccef"}, + {"benchmark": "osworld1", "version": "desktop-env-v1.0.3", "dataset": "test_all", "task": "os__4783cc41-c03c-4e1b-89b4-50658f642bd5"}, + {"benchmark": "tau3-bench", "version": "fc0055dc4e0a316c3f83133267fbd6faaa770992", "dataset": "banking_knowledge", "task": "task_024"} + ] +} diff --git a/app/tests/fixtures/suites/smoke/suite.json b/app/tests/fixtures/suites/smoke/suite.json new file mode 100644 index 000000000..000b80aa9 --- /dev/null +++ b/app/tests/fixtures/suites/smoke/suite.json @@ -0,0 +1,16 @@ +{ + "schema": "nullius.suite/v1", + "key": "smoke", + "label": "Suite smoke test", + "summary": "7 tasks of 6 benchmarks, one for each thing a suite does: two plain members, a judged one, one that takes no agent, one for a desktop agent, and one that needs the sandbox runtime on the machine.", + "default": "2026-12", + "versions": { + "2026-12": { + "tasks": "2026-12.json", + "settings": { + "longmemeval": {"setup": "model"}, + "tau3-bench": {"bench_options": {"retrieval": "terminal_use"}} + } + } + } +} diff --git a/app/tests/test_suites.py b/app/tests/test_suites.py new file mode 100644 index 000000000..8cfdf48b1 --- /dev/null +++ b/app/tests/test_suites.py @@ -0,0 +1,149 @@ +"""Suites: the entry and its frozen task list, the members' task sets, the recipe compiled into an ordinary run per +member and participant, and the command. No key, no network, no run: the fake benchmarks, pinned by hand.""" +from __future__ import annotations + +import argparse +import io +import json +import os +import shutil +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest import mock + +from nullius.standard import cli +from nullius.standard.contract import definitions +from nullius.standard.pages import recipe +from nullius.standard.runner import sets, suites + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "standard", "catalogue") +PIN, OTHER_PIN = "a" * 40, "b" * 40 +TASKS = [{"benchmark": "fakebench", "version": PIN, "dataset": "all", "task": "good", "axes": ["ignored"]}, + {"benchmark": "fakebench", "version": PIN, "dataset": "all", "task": "wrong"}, + {"benchmark": "fakebench", "version": PIN, "dataset": "more", "task": "slow"}, + {"benchmark": "fakememo", "version": OTHER_PIN, "dataset": "all", "task": "m1"}, + {"benchmark": "fakememo", "version": OTHER_PIN, "dataset": "all", "task": None, "draw": "1 of 1"}] + + +class Scratch(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-suites-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + patch = mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(self.tmp / "catalogue")}) + patch.start(); self.addCleanup(patch.stop) + bench = dict(definitions.get("benchmark", "fakebench", ROOT), upstream={"tested": PIN}, + controls={"nop": {"source": "nullius", "from": "nothing said"}}, + datasets=[{"id": "all", "units": 4}, {"id": "more", "units": 4}]) + memo = dict(definitions.get("benchmark", "fakememo", ROOT), upstream={"tested": OTHER_PIN}) + # a member whose answers a judge model grades: its check pays, and it needs one more port than Lesser proved + judged = dict(bench, key="fakejudged", _ref="fakejudged", label="Fake judged", datasets=[{"id": "all", "units": 4}], + score=dict(bench["score"], judge={"model": "gpt-4.1", "says": "a model grades the answer"})) + fake = definitions.get("agent", "fake", ROOT) + other = dict(fake, key="lesser", _ref="lesser", label="Lesser", offers=[], proven={}) + boxed = dict(fake, key="boxed", _ref="boxed", label="Boxed", backends=["container"]) # an agent of the container backend alone + self.defs = {"benchmark": [bench, memo, judged], "agent": [fake, other, boxed], "module": []} + + def suite(self, tasks=TASKS, settings=None, key="demo"): + folder = self.tmp / "catalogue" / "suites" / key + folder.mkdir(parents=True, exist_ok=True) + (folder / "2026-12.json").write_text(json.dumps({"tasks": tasks})) + (folder / "suite.json").write_text(json.dumps({ + "schema": suites.SCHEMA, "key": key, "label": "Demo", "summary": "Two fakes.", "default": "2026-12", + "versions": {"2026-12": {"tasks": "2026-12.json", **({"settings": settings} if settings else {})}}})) + return suites.find(key) + + def recipe(self, **kw): + s = suites.find(kw.get("benchmark", "demo")) # every member, said: a launch names what it takes + return dict({"version": 1, "harness": "standard", "name": "demo-run", "benchmark": "demo", "others": ["fake"], "provider": "openai", + "model": "gpt-5-mini", "unsandboxed": True, "where": "local", "datasets": [m["id"] for m in s["members"]] if s else []}, **kw) + + +class TheEntry(Scratch): + def test_a_selection_file_is_its_members_and_a_task_without_an_id_is_left_out(self): + s = self.suite() + self.assertEqual([(m["id"], m["version"], m["units"]) for m in s["members"]], + [("fakebench.all", PIN, ["good", "wrong"]), ("fakebench.more", PIN, ["slow"]), ("fakememo.all", OTHER_PIN, ["m1"])]) + self.assertEqual((s["left_out"], suites.tasks(s), s["ref"], suites.workspace(s)), (1, 4, "demo", "suite-demo-2026-12")) + + def test_another_list_is_another_hash_and_an_order_is_not(self): + first = self.suite()["hash"] + self.assertEqual(self.suite(list(reversed(TASKS)))["hash"], first) + self.assertNotEqual(self.suite(TASKS[1:])["hash"], first) + + def test_a_bad_entry_is_left_out_and_said(self): + self.suite([dict(TASKS[0]), dict(TASKS[1], version=OTHER_PIN)]) + self.assertEqual(suites.load(str(self.tmp / "catalogue")), ([], ["suite demo: version 2026-12: 2026-12.json: fakebench is pinned twice"])) + + def test_a_task_file_that_is_no_object_is_left_out_and_said(self): + self.suite() + for text in ("[]", '"tasks"', "3"): + (self.tmp / "catalogue" / "suites" / "demo" / "2026-12.json").write_text(text) + self.assertEqual(suites.load(str(self.tmp / "catalogue")), ([], ["suite demo: version 2026-12: 2026-12.json: no tasks"]), text) + + def test_a_moved_pin_or_a_benchmark_outside_the_standard_is_refused(self): + s = self.suite() + moved = [dict(self.defs["benchmark"][0], upstream={"tested": "c" * 40}), self.defs["benchmark"][1]] + with self.assertRaisesRegex(suites.Refused, "a moved pin is another version of the suite"): + suites.groups(s, moved) + with self.assertRaisesRegex(suites.Refused, "has no definition of the standard"): # a benchmark only Harbor runs + suites.groups(s, self.defs["benchmark"][:1]) + + def test_what_a_version_fixes_for_a_benchmark_is_part_of_its_hash(self): + self.assertNotEqual(self.suite()["hash"], self.suite(settings={"fakebench": {"backend": "container"}})["hash"]) + + def test_a_suite_named_as_a_benchmark_is_left_out_and_said(self): + (self.tmp / "catalogue" / "benchmarks" / "demo").mkdir(parents=True) + self.assertIsNone(self.suite()) + self.assertEqual(suites.load(), ([], ["suite demo: a benchmark has this key: give the suite another"])) + self.suite(key="gsm8k") # a bundled benchmark's key + self.assertIn("suite gsm8k: a benchmark has this key: give the suite another", suites.load()[1]) + self.assertIsNone(suites.find("gsm8k")) + + def test_the_fixture_suite_finds_every_member_at_its_pin(self): + shutil.copytree(os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "suites"), self.tmp / "catalogue" / "suites") + found, bad = suites.load() + self.assertEqual(([s["ref"] for s in found], bad), (["smoke"], [])) + suites.groups(found[0], definitions.load("benchmark", every=True)[0]) + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": str(self.tmp / "none")}): + self.assertEqual(suites.load(), ([], [])) # none is bundled + + +class TheSets(Scratch): + def test_each_benchmark_taken_gets_one_set_made_once_with_the_same_id(self): + s = self.suite() + made = suites.freeze(s, self.defs["benchmark"], ["fakebench.more"]) + self.assertEqual(list(made), ["fakebench"]) # no member of fakememo taken: no set of it + first = sets.load("fakebench", "demo-2026-12") + self.assertEqual((sets.parts(first), first["label"]), ({"all": ["good", "wrong"], "more": ["slow"]}, "Demo 2026-12")) + self.assertFalse(os.path.exists(sets.path_of("fakememo", "demo-2026-12"))) + os.remove(sets.path_of("fakebench", "demo-2026-12")) + again = suites.freeze(s, self.defs["benchmark"]) # made again, anywhere: the same set + self.assertEqual((again["fakebench"]["id"], sets.latest(again["fakebench"])["hash"]), (first["id"], sets.latest(first)["hash"])) + self.assertEqual(sets.parts(sets.load("fakememo", "demo-2026-12")), {"all": ["m1"]}) + + def test_the_same_settings_in_another_order_are_the_same_version_and_freeze_again(self): + one = self.suite(settings={"fakebench": {"backend": "container", "setup": "model"}, "fakememo": {"backend": "container"}}) + first = suites.freeze(one, self.defs["benchmark"]) + two = self.suite(settings={"fakememo": {"backend": "container"}, "fakebench": {"setup": "model", "backend": "container"}}) + self.assertEqual(one["hash"], two["hash"]) + again = suites.freeze(two, self.defs["benchmark"]) + self.assertEqual({k: sets.latest(e)["hash"] for k, e in first.items()}, {k: sets.latest(e)["hash"] for k, e in again.items()}) + + def test_a_preview_writes_nothing_and_says_the_same_list(self): + s = self.suite() + seen = suites.freeze(s, self.defs["benchmark"], save=False) + self.assertFalse((self.tmp / "catalogue" / "sets").exists()) + made = suites.freeze(s, self.defs["benchmark"]) + self.assertEqual({k: (e["id"], sets.latest(e)["hash"]) for k, e in seen.items()}, {k: (e["id"], sets.latest(e)["hash"]) for k, e in made.items()}) + + def test_a_name_that_holds_another_list_is_refused_previewed_or_not(self): + sets.create(self.defs["benchmark"][0], "demo 2026-12", dataset="all", units=["good"]) + for save in (False, True): + with self.assertRaisesRegex(suites.Refused, "holds another list"): + suites.freeze(self.suite(), self.defs["benchmark"], save=save) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_every_route.py b/app/ui_tests/test_every_route.py index a4e6ffbd0..904ecb8b0 100644 --- a/app/ui_tests/test_every_route.py +++ b/app/ui_tests/test_every_route.py @@ -172,6 +172,8 @@ def test_every_get_rule_answers(self): # `/benchmarks/` shares it with the artifact route but means a benchmark if raw == "/benchmarks/": local["key"] = catalog.load().listed_benchmarks[0].key + if raw == "/suites/": # none is bundled: the fixture's, a user entry (test_suite_routes covers its page) + self.skipTest("no suite is bundled") # an agent's or a Module's page is the standard's definition of that key if raw in ("/agents/", "/modules/", "/features/"): from nullius.standard.contract import definitions diff --git a/app/ui_tests/test_suite_routes.py b/app/ui_tests/test_suite_routes.py new file mode 100644 index 000000000..e5d0d64b1 --- /dev/null +++ b/app/ui_tests/test_suite_routes.py @@ -0,0 +1,85 @@ +"""A suite on its pages and from the builder: a group of the Benchmarks page, its own page, the Agent step's grid by the +members chosen, and a Run that starts an ordinary run per member and participant, queued, in the suite's own workspace. +The suite is the fixture's (tests/fixtures/suites), a user entry here: none is bundled.""" +from __future__ import annotations + +import json +import os +import shutil +import tempfile +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +from nullius import execution, prerequisites +from .test_routes import web + + +FIXTURE = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "suites" +CHECKS = {"version": 1, "harness": "standard", "name": "smoke-checks", "benchmark": "smoke", "others": ["nop"], "provider": "openai", + "model": "", "where": "local", "datasets": ["gsm8k.test", "simpleqa.simpleqa"]} + + +class SuiteRoutes(unittest.TestCase): + def setUp(self): + self.stack = ExitStack(); self.addCleanup(self.stack.close) + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-suite-")); self.addCleanup(shutil.rmtree, self.tmp, True) + shutil.copytree(FIXTURE, self.tmp / "catalogue" / "suites") + self.stack.enter_context(patch.dict(os.environ, {"HOSTS": "", "RUNS_DIR": str(self.tmp / "runs"), "OPENAI_API_KEY": "sk-0123456789abcdef", + "NULLIUS_CATALOGUE": str(self.tmp / "catalogue")})) + self.stack.enter_context(patch.dict(web.app.config, TESTING=True)) + self.stack.enter_context(patch.dict(execution.EXECUTIONS, clear=True)) + self.stack.enter_context(patch.object(prerequisites, "docker_here", lambda fresh=False: None)) + self.stack.enter_context(patch.object(web.shared, "WS_HOME", str(self.tmp / "workspaces"))) + self.stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "job_roots": []})) + self.started = [] + # started, and left waiting: no thread runs anything + self.stack.enter_context(patch.object(execution.Execution, "start", lambda ex: self.started.append(ex) or ex)) + self.client = web.app.test_client() + r = self.client.get("/new-run"); self.addCleanup(r.close) + with self.client.session_transaction() as s: + self.headers = {"Origin": "http://localhost", "X-CSRF-Token": s["csrf"]} + + def get(self, url): + r = self.client.get(url); self.addCleanup(r.close) + return r + + def post(self, url, body): + r = self.client.post(url, data=json.dumps(body), content_type="application/json", headers=self.headers) + self.addCleanup(r.close); return r + + def run_it(self, recipe=CHECKS): + """Review, then Run with what Review showed.""" + digest = self.post("/new-run/runner", {"recipe": recipe}).get_json()["suite"]["digest"] + return self.post("/run", {"recipe": recipe, "reviewed": digest}) + + def test_the_pages_list_the_suite_apart_and_its_members(self): + page = self.get("/benchmarks").get_data(as_text=True) + self.assertLess(page.index("

Suites

"), page.index('href="/suites/smoke"')) + self.assertLess(page.index('href="/suites/smoke"'), page.index("

Benchmarks

")) + own = self.get("/suites/smoke") + self.assertEqual(own.status_code, 200) + self.assertIn('href="/benchmarks/longmemeval"', own.get_data(as_text=True)) + self.assertIn("Its own procedure", own.get_data(as_text=True)) + self.assertEqual(self.get("/suites/nope").status_code, 404) + # a member is found by its name + text = own.get_data(as_text=True) + self.assertRegex(text, r'data-search="[^"]*gsm8k') + self.assertIn('href="/benchmarks/gsm8k"', text) # no version of its own: its page + + def test_a_task_file_that_is_no_object_leaves_the_benchmarks_reachable(self): + (self.tmp / "catalogue" / "suites" / "smoke" / "2026-12.json").write_text("[]") + page = self.get("/benchmarks") + self.assertEqual(page.status_code, 200) + self.assertIn('href="/benchmarks/gsm8k"', page.get_data(as_text=True)) + self.assertEqual(self.get("/benchmarks/gsm8k").status_code, 200) + + def test_a_suite_named_as_a_benchmark_never_takes_its_place(self): + shutil.copytree(self.tmp / "catalogue" / "suites" / "smoke", self.tmp / "catalogue" / "suites" / "gsm8k") + out = self.post("/new-run/runner", {"recipe": dict(CHECKS, benchmark="gsm8k", datasets=["test"])}).get_json() + self.assertEqual((out["errors"], "suite" in out, out["review"][0][1]), ([], False, "Benchmark")) + self.assertNotIn('href="/suites/gsm8k"', self.get("/benchmarks").get_data(as_text=True)) + +if __name__ == "__main__": + unittest.main() diff --git a/app/web/catalogue.py b/app/web/catalogue.py index 0db0f8438..f955ee6bf 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -17,7 +17,7 @@ from nullius.standard.pages import howto from nullius.standard.proofs import prove from nullius.standard.pages import recipe as standard_recipe -from nullius.standard.runner import sets, units +from nullius.standard.runner import sets, suites, units from .core import app from . import execute @@ -28,7 +28,7 @@ @app.route("/benchmarks") def benchmarks_page(): cat = shared._catalog_cached() - return render_template("catalogue/benchmarks.html", cat=cat, items=benchmark_cards(cat), choices=benchmark_choices(cat), + return render_template("catalogue/benchmarks.html", cat=cat, items=suite_cards() + benchmark_cards(cat), choices=benchmark_choices(cat), prompts=howto.prompts(), catalogue_dir=paths.catalogue_dir()) @@ -48,6 +48,36 @@ def benchmark_cards(cat) -> list: for row in standard_recipe.benchmarks(cat)] +def suite_cards() -> list: + """The suites as cards beside the benchmarks', a group of their own (``suite``): each suite's default version.""" + return [{"key": s["key"], "suite": True, "href": url_for("suite_page", key=s["key"]), "keys": s["key"], + "search": " ".join([s["label"], s["key"], "suite", *{m["benchmark"] for m in s["members"]}]), + "category": "Suite", "origin": [], "icon": None, "title": s["label"], "domain": s["summary"], + "runs": [{"text": RUNS_WITH["standard"][0], "class": "rt-standard", "title": "Runs with " + RUNS_WITH["standard"][1], "value": "standard"}], + "needs": [], "tasks": {"text": f"{suites.tasks(s):,}", "label": "Tasks", "value": suites.tasks(s)}, "versions": {}, + "datasets": {"text": len({m["benchmark"] for m in s["members"]}), "label": "Benchmarks"}, + "evaluates": {"text": FAMILIES["agent"], "value": standard_definitions.names.wire("agent")}, "scoring": "", "blocker": ""} + for s in suites.load()[0] if s["version"] == s["default"]] + + +@app.route("/suites/") +def suite_page(key): + """One suite: its versions, and the members of the one shown (``?v=``, the default without it), by benchmark.""" + s = suites.find(f"{key}@{request.args['v']}" if request.args.get("v") else key) + if s is None or s["key"] != key: + abort(404) + try: + page, problem = standard_recipe.suite_page(s, standard_definitions.load("benchmark", every=True)[0]), "" + except suites.Refused as e: + page, problem = None, str(e) + items = [{"title": m["label"], "href": url_for("benchmark_page", key=m["key"], v=m["version"] or None), "pin": m["pin"][:12], + "search": " ".join([m["label"], m["key"], *(d["label"] for d in m["datasets"])]), + "datasets": ", ".join(d["label"] for d in m["datasets"]), "tasks": {"text": m["tasks"], "value": m["tasks"]}, + "runs": "Its own procedure" if m["setup"] else "The agent", + "backend": m["backend"].capitalize()} for m in (page or {}).get("members") or []] + return render_template("catalogue/suite.html", s=s, items=items, problem=problem) + + NEEDS_NOTHING = ("none", "Nothing") # the Needs filter's value for a benchmark that needs nothing of a machine diff --git a/docs/concepts.md b/docs/concepts.md index fc77dae38..9efbfb989 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -14,6 +14,7 @@ The tasks and how each is scored; one folder in the catalogue, run on one or bot | List of units | The tasks a standard run takes by their ids, from a file ([`--units FILE`](cli/run.md#a-list-of-units)) | | Task set | A named, frozen list of a dataset's units that a run can take ([`--set NAME`](cli/task-sets.md)) | | Verifier | The benchmark's own scoring: tests, an exact answer, a judge model | +| Suite | A fixed, dated selection of tasks from several benchmarks, each at its pin | | Setup | Who answers: `original` (the published pipeline and models), `model` (that pipeline, your model), or your agent or Module | | Control | A run with no agent: `nop` does nothing, `oracle` applies the reference solution | diff --git a/pyproject.toml b/pyproject.toml index 3d7c6b176..b29ed49da 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,7 +53,7 @@ _nullius_app = "app" dependencies = {file = ["app/requirements.txt"]} [tool.setuptools.package-data] -"nullius.catalogue" = ["agents/*/*.json", "agents/*/*.py", "agents/*/*.toml", "agents/*/*.yaml", "agents/*/*.txt", "benchmarks/*/env/*", "benchmarks/*/*.json", "benchmarks/*/*.py", "benchmarks/*/*.txt", "benchmarks/*/*.yml", "benchmarks/*/startup/*.py", "modules/*/*.json", "modules/*/*.py"] +"nullius.catalogue" = ["agents/*/*.json", "agents/*/*.py", "agents/*/*.toml", "agents/*/*.yaml", "agents/*/*.txt", "benchmarks/*/env/*", "benchmarks/*/*.json", "benchmarks/*/*.py", "benchmarks/*/*.txt", "benchmarks/*/*.yml", "benchmarks/*/startup/*.py", "suites/*/*.json", "modules/*/*.json", "modules/*/*.py"] "nullius.standard" = ["kits/*/*.json", "kits/*/*.py", "kits/*/*.Dockerfile", "kits/*/*.txt"] "nullius.judge" = ["floors.json"] "nullius.leaderboard" = ["definitions.json"] From 56c2e11c951a188290ea22089ee7b59bd62d6690 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 18:09:34 +0100 Subject: [PATCH 2/3] feat(execution): run the runs of one launch one after the other --- app/nullius/execution.py | 326 +++++++++++++++++++++++++- app/tests/test_execution_queue.py | 366 ++++++++++++++++++++++++++++++ app/ui_tests/test_api.py | 3 + app/ui_tests/test_run_routes.py | 4 + app/web/api.py | 3 +- app/web/execute.py | 3 +- 6 files changed, 697 insertions(+), 8 deletions(-) create mode 100644 app/tests/test_execution_queue.py diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 6de8c8569..ad2facd47 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -108,6 +108,25 @@ store itself, and nothing is sent. Log lines pass through ``redact`` before they are kept. +Runs of one queue (``Plan.queue``, the id of one submission of a suite, in +every run's plan and record) are started by one launch and +run one after the other: each names the run before it (``Plan.after``) in the +plan saved before the launch's decision. A run waits, ``preparing``, until the +record of that run on disk says it ended, whatever its outcome; a record +missing or unreadable holds the queue. Its turn is saved (``promoted``) before +anything of it starts, so a restart waits again or goes on, never both. One +Stop is the queue's (``stop``): saved as a flag in its first run's folder +(``QUEUE_STOP``, naming the queue) before any run is told, it ends the run +under way and every run still waiting. While a run of the queue has not ended +none of them runs a part again nor is deleted (``queue_open``); once all have, +a run that runs tasks again is no longer the queue's: its Stop is its own and +the queue's flag does not reach it. A queue's records are of ``QUEUE_VERSION``, +so a Nullius from before queues leaves them alone. What a queue's run is to +its queue is in its record too (``member``): a run whose plan cannot be read +back at ``restore`` is held as that (``Execution.lost``), on the pages and +under the queue's Stop, and holds the runs after it until no process of it is +left on this machine; then it ends ``failed`` and the queue goes on. + What the run is doing is said in stages (``nullius/progress.py``): the steps here that get a host ready - connect, uv, the tasks, app/, a pinned Harbor - each a ``[nullius] stage=...`` line in the run's log, and the run's own (the @@ -127,6 +146,7 @@ import re import shlex import shutil +import signal import stat import subprocess import sys @@ -157,6 +177,9 @@ STOP_WAIT = 20.0 # seconds a Stop's own commands on the target take at most: the kill and the last copy back, together LAUNCH_GRACE = 5.0 # seconds a restart waits for a part a launcher claimed to start (_settle) UV_INSTALL = "curl -LsSf https://astral.sh/uv/install.sh | sh" +QUEUE_STOP = "queue.stop" # in a queue's first run's folder: its Stop, saved before any of its runs is told (``stop``) +QUEUE_VERSION = 2 # of a queue's run's record: a Nullius that knows no queue reads it as a later one's and leaves it +QUEUE_POLL = 1.0 # seconds between a waiting run's looks at the record of the run before it RECORD = "run.json" # the run as it is now (``Execution._save``) PLAN = "plan.json" # its plan, recipe included, without the scripts: they are run.sh and each part's file VERSION = 1 # of the record; one without it holds its plan and every trial it said (``recorded``) @@ -289,6 +312,10 @@ class Plan: keyless: bool = False # nothing in it calls a model (the standard's controls): handed no key and no endpoint at all licences: dict = field(default_factory=dict) # the standard's on a host: {"benchmark", "names", "providers"} - what it is sent of that benchmark's licences roles: dict = field(default_factory=dict) # by role, its own provider's {key_var, url_var, base_url}: the standard's judge or user simulator + queue: str = "" # the queue it is a run of, the id of one submission: a suite's runs, one after the other (``Execution._turn_comes``) + queue_runs: list = field(default_factory=list) # every run of that queue, by name, in order: the first holds its Stop (``QUEUE_STOP``) + queue_recipe: dict = field(default_factory=dict) # the suite's own recipe the queue was compiled from: what "Run the rest" compiles again + after: str = "" # the run of its queue it waits for: it starts once that run's saved record says it ended def steps(self) -> List[dict]: return [p for p in self.parts if p.get("script")] or [{"id": "run", "label": "the run", "script": self.script, "whole": True}] @@ -425,6 +452,7 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl self._run_plain = run or subprocess_run self._run = run or (lambda argv, timeout=600.0, stdin=None: subprocess_run(argv, timeout, stdin, stop=self._stop)) self._credentials(key, url, env, agent_keys) + self._given = (key, url, env, agent_keys) # read again when its turn in a queue comes (``_turn_comes``) # the benchmark's licences a standard run on a host is sent: read from its store at each launch, unless given self._licences_given = licences self._redact: List[str] = [] # the licences' values sent, as text: never in a log line @@ -455,6 +483,10 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl self.launched: str = rec.get("launched") or "" # the fresh checks passed, the run's name on a host its own (``_checked``): None for a record from before the field self.checked: Optional[bool] = rec.get("checked") if record else False + # its turn in its queue came, saved before anything of it starts (``_turn_comes``); a run of no queue has no turn to wait for + self.promoted: bool = bool(rec.get("promoted")) or not plan.after + # why its plan could not be read back (``_lost``): held as its record says it, nothing of it run from here + self.lost: str = "" if self.state == "stopping": # a Stop that a restart interrupted: finish it, do not run on self._stop.set() self.log_offset = int(rec.get("log_offset", 0)) @@ -558,14 +590,18 @@ def _save(self, strict: bool = False, inline: bool = False) -> bool: ``plan.json`` saved as one, its plan in it, no other file written. Nothing once ``deleted``: False.""" with self._turn: - if self.deleted: + if self.deleted or self.lost: # a run held without its plan is saved by ``_keep_lost`` alone return False - data = {"version": VERSION, "id": self.id, "state": self.state, "step": self.step, "part": self.part, "pid": self.pid, + data = {"version": QUEUE_VERSION if self.plan.queue else VERSION, **({"queue": self.plan.queue} if self.plan.queue else {}), "id": self.id, "state": self.state, "step": self.step, "part": self.part, "pid": self.pid, "log_offset": self.log_offset, "exit_code": self.exit_code, "error": self.error, "question": self.question, "ends": self.ends, "started": self.started, "finished": self.finished, "harbor": self.harbor, "tasks_on_target": self.tasks_on_target, "app_on_target": self.app_on_target, "catalogue_on_target": self.catalogue_on_target, "workspace": self.workspace, - "launched": self.launched, "checked": self.checked, "feeds": self._feeds, "caps": self.caps, + "launched": self.launched, "checked": self.checked, **({"promoted": self.promoted} if self.plan.after else {}), "feeds": self._feeds, "caps": self.caps, "again": [{k: v for k, v in p.items() if k != "script"} for p in self.plan.parts if p.get("again")]} + if self.plan.queue: # what it is to its queue, should its plan not be read back (``_lost``) + data["member"] = {"runs": self.plan.queue_runs, "jobs": self.plan.jobs, "runner": self.plan.runner, "remote": bool(self.plan.host), + "recipe": {k: v for k, v in (self.plan.recipe or {}).items() if k in ("suite", "max_usd")}, + "rest_of": (self.plan.queue_recipe or {}).get("rest_of")} if self._pending: data["pending"] = self._pending if self._seen_trials: @@ -758,12 +794,15 @@ def refused(self, job_id: str) -> Optional[str]: def live_state(self, job_id: str) -> Optional[str]: """What one job of this run is doing while the run lives: the run's state for the part running now, ``queued`` for a part still to come - (the parts run one after another), and the run's own while it + (the parts run one after another) and for a run waiting for its turn + in its queue, and the run's own while it prepares or stops, which is every part's. ``not run`` for one held back by a pause: nothing starts it unless the page says continue. None once the run ended.""" if self.state not in ALIVE: return None + if self.state == "preparing" and not self.promoted: # a run waiting for its turn in its queue + return "queued" part = self.part_for(job_id) if self.state in ("preparing", "stopping") or part is None or part == self.launched or self.again_of(job_id) is not None: return self.state @@ -828,10 +867,65 @@ def file_under(self, workspace: str, *, persist: bool = True) -> None: def resume(self) -> "Execution": """Pick a recorded run up where it was: the part that was running is followed again, a pause waits again, the rest runs on.""" + if self.plan.queue and not self.rerunning() and _queue_stopped(self.root, self.plan): + self.state = "stopping" # its queue's Stop was saved, and Nullius went before this run was told + self._stop.set() self.thread = threading.Thread(target=self._main_resumed, name=f"run-{self.plan.name}", daemon=True) self.thread.start() return self + def _keep_lost(self, rec: dict, remote: bool, kw: dict) -> None: + """A run whose plan could not be read back (``_lost``), looked at until it ends or can be picked up: its + record stays as it was, so the runs after it wait. Each look reads the plan again: readable, the run is + picked up as any other. Else, once no process of it is left on this machine (``_in_folder``) and its + turn has come - the run before it ended - it is recorded ``failed`` with the reason, and the queue goes + on. Under the queue's Stop its processes are ended, by their groups, and it is recorded ``stopped``. + One on a host, or where processes cannot be listed, is never known to be gone: it is held until a + Stop, which records it ``stopped`` and says its processes were not reached.""" + runs = self.plan.queue_runs + before = runs[runs.index(self.plan.name) - 1] if self.plan.name in runs[1:] else "" + while True: + try: + again, plan = recorded(self.dir) + new = Execution(Plan.from_dict(plan), root=self.root, record=again, **kw) + except (OSError, ValueError, KeyError, TypeError): + pass + else: + with _QUEUES: + EXECUTIONS[self.id] = new + if new.state in ALIVE: + new.resume() + return + stopping = self._stop.is_set() or (not self.rerunning() and _queue_stopped(self.root, self.plan)) + left = None if remote else _in_folder(self.dir) + for pid in (left or ()) if stopping else (): + try: + group = os.getpgid(pid) + os.killpg(group, signal.SIGTERM) if group != os.getpgid(0) else os.kill(pid, signal.SIGTERM) + except OSError: + pass + turn = self.promoted or not before + if not turn: + try: + with open(os.path.join(self.root, before, RECORD), encoding="utf-8") as fh: + turn = json.load(fh).get("state") in ENDED + except (OSError, ValueError, AttributeError): + pass + if (stopping and not left) or (left == [] and turn): + state = "stopped" if stopping else "failed" + said = self.lost + ("; its processes could not be reached" if stopping and left is None else "") + try: + with _QUEUES: # as a turn is saved: a Stop of the queue is before or after, never during + ondisk.write_whole(os.path.join(self.dir, RECORD), json.dumps(dict(rec, state=state, error=said, finished=time.time()), indent=1)) + except OSError: + pass # held, and written at the next look + else: + self.log(f"✕ {said}" + ("" if stopping else "; the runs after it go on")) + with self._turn: + self.state, self.error, self.finished = state, said, time.time() + return + time.sleep(QUEUE_POLL) + def continue_(self) -> None: """Answer a pause: go on with the next agent.""" self.question = None @@ -920,8 +1014,78 @@ def _kill_part(self) -> Optional[int]: self.pid, self._live = None, None return int(code) + def rerunning(self) -> bool: + """Whether the run is running tasks again (``again``, a part only a run of a closed queue is given): it is + then no longer its queue's, from that part's start until the run's end is recorded.""" + return self.state in ALIVE and any(p.get("again") for p in self.plan.parts) + + def _turn_comes(self) -> bool: + """Wait, ``preparing``, for this run's turn in its queue: until the + record on disk of the run before it (``Plan.after``) says that run + ended, whatever its outcome. True once the turn is saved + (``promoted``, a strict save: nothing of the run starts before); + False when the run ended here instead - the queue's Stop, saved + (``QUEUE_STOP``) or said to this run, or the run before it recorded + ``stopped``. A record missing, unreadable, of another queue, of another run + (its id), of another version or of a later attempt, or not yet ended holds the + queue, and a turn that cannot be saved is tried again: the log says + why once. A run before it that ended in this process but whose record + does not say so is asked to save it again.""" + said = None + while not self.promoted: + why = None + with _QUEUES: # a Stop of the queue is saved before or after this turn, never during + state = None + try: + with open(os.path.join(self.root, self.plan.after, RECORD), encoding="utf-8") as fh: + before = json.load(fh) + state = before.get("state") + if before.get("queue") != self.plan.queue: # a folder of that name another launch made: never this run's turn + state, why = None, f"the record of {self.plan.after} is not this launch's" + elif (not re.fullmatch(re.escape(self.plan.after) + r"-\d+", str(before.get("id"))) or before.get("version") != QUEUE_VERSION + or before.get("again")): # another run's record, or one of a later attempt: not the end waited for + state, why = None, f"the record of {self.plan.after} is not that run's first attempt" + except (OSError, ValueError, AttributeError): + why = f"the record of {self.plan.after} cannot be read" + if self._stop.is_set() or state == "stopped" or _queue_stopped(self.root, self.plan): + self._stop.set() + elif state in ENDED: + self.promoted, was = True, self.started + self.started = time.time() + try: + self._credentials(*self._given) # the keys as Settings holds them now, not as the launch read them + + if not self._save(strict=True): + return False # deleted + except OSError as e: + self.promoted, self.started = False, was + why = str(e) if isinstance(e, Unreadable) else f"its turn could not be saved ({e.strerror or e})" + else: + self.log(f"— {self.plan.after} ended ({state}): starting") + return True + elif why is None: + before = next((e for e in list(EXECUTIONS.values()) if e.plan.name == self.plan.after and e.root == self.root), None) + if before is not None and before.state in ENDED: + before._save() # its end was not saved: tried again, read at the next look + why = f"the end of {self.plan.after} is not saved yet" + if self._stop.is_set(): + self._done(130) + return False + now = why or f"waiting for {self.plan.after} to end" + if now != said: + said = now + self.log(f"— {now}" + ("; the queue is held until it can" if why else "")) + with self._turn: + if self.state == "preparing": + self.step = "queued" + self._save() + self._stop.wait(QUEUE_POLL) + return True + def _main(self) -> None: try: + if not self._turn_comes(): + return os.makedirs(self.jobs, exist_ok=True) problem = self.plan.check() if problem: @@ -1022,6 +1186,8 @@ def again(self, part: dict, env=os.environ, settle: Optional[tuple] = None) -> " with self._turn: if self.state in ALIVE: raise ValueError(f"{self.plan.name} is {self.state}: a run takes one more part once it has ended") + if queue_open(self): + raise ValueError(f"{self.plan.name} is one of a suite's runs, and some have not ended: nothing was started") if self._deleting(): raise ValueError(f"{self.plan.name} is being deleted: nothing was started") name = _base(part) + ".sh" @@ -1111,6 +1277,8 @@ def holds(self, job_id: str) -> Optional[str]: def _main_resumed(self) -> None: try: self.log(f"— Nullius is back; picking the run up at {self.plan.steps()[min(self.part, len(self.plan.steps()) - 1)]['label']}") + if not self._turn_comes(): + return unbegun = self._unbegun() if unbegun is None: return @@ -2104,6 +2272,99 @@ def start(plan: Plan, **kw) -> Execution: return start_all([Execution(plan, **kw)])[0] +_QUEUES = threading.Lock() # a queue's Stop and each of its runs' turn, one at a time (``stop``, ``Execution._turn_comes``) + + +def _queue_stop(root: str, plan: Plan) -> str: + return os.path.join(root, (plan.queue_runs or [plan.name])[0], QUEUE_STOP) + + +def _queue_stopped(root: str, plan: Plan) -> bool: + """Whether the Stop of *plan*'s queue is saved: its flag, naming that queue. One that cannot be read counts, + one another launch left in a folder of that name does not.""" + try: + with open(_queue_stop(root, plan), encoding="utf-8") as fh: + return json.load(fh).get("queue") == plan.queue + except FileNotFoundError: + return False + except (OSError, ValueError, AttributeError): + return True + + +def queue_of(ex: Execution) -> List[Execution]: + """The runs of *ex*'s queue this process holds, *ex* alone when it is of none.""" + if not ex.plan.queue: + return [ex] + return [e for e in list(EXECUTIONS.values()) if e.plan.queue == ex.plan.queue and e.root == ex.root] or [ex] + + +def _unended(ex: Execution) -> List[str]: + """The runs of *ex*'s queue whose saved record does not say they ended: one waiting or under way, one whose + end was not saved, one whose record cannot be read, one this process does not hold included. Its members are + the plan's (``Plan.queue_runs``), not what this process holds; one whose folder is gone, or holds the readable + record of another queue's run, is left out.""" + out = [] + for name in ex.plan.queue_runs or [e.plan.name for e in queue_of(ex)]: + if not os.path.isdir(os.path.join(ex.root, name)): + continue # deleted, once the queue had closed + try: + with open(os.path.join(ex.root, name, RECORD), encoding="utf-8") as fh: + rec = json.load(fh) + if rec.get("queue") != ex.plan.queue or rec.get("state") in ENDED: + continue # ended, or another launch's run in a folder of that name: its own was deleted + except (OSError, ValueError, AttributeError): + pass + out.append(name) + return out + + +def queue_open(ex: Execution) -> bool: + """Whether a run of *ex*'s queue has not ended: one running, one still waiting for its turn, or one whose + saved record does not say it ended (``_unended``), held by this process or not. A run that runs tasks again + once all had ended does not open it again.""" + if not ex.plan.queue: + return False + held = {e.plan.name: e for e in queue_of(ex)} + return (any(e.state in ALIVE and not e.rerunning() for e in held.values()) + or any(not (name in held and held[name].rerunning()) for name in _unended(ex))) + + +def _first_is_ours(ex: Execution) -> bool: + """Whether the folder that holds the queue's Stop is known to be its first run's: its record there names + the queue, or, that not readable, its plan does, or this process holds that run. False otherwise - the first + run was deleted once the queue had closed and its name taken by another launch, which may have no record + yet (``reserve``): nothing of this queue is written into a folder that is not shown to be its own.""" + folder = os.path.dirname(_queue_stop(ex.root, ex.plan)) + for name in (RECORD, PLAN): + try: + with open(os.path.join(folder, name), encoding="utf-8") as fh: + return json.load(fh).get("queue") == ex.plan.queue + except (OSError, ValueError, AttributeError): + pass + return any(e.dir == folder and not e.deleted for e in queue_of(ex)) + + +def stop(ex: Execution) -> bool: + """Stop *ex*; of an open queue, the queue: its Stop saved first (``QUEUE_STOP``), then the run under way and + every run waiting told, each ending ``stopped`` by itself. Saved too while a record of the queue does not say + its run ended, though every run this process holds has: a Stop asked again after one that could not be saved. + False when the Stop could not be saved: no run is told, since one ending without the flag would let the run + after it start. A run running tasks again is stopped alone.""" + if not ex.plan.queue or ex.rerunning(): + ex.stop() + return True + with _QUEUES: + runs = [e for e in queue_of(ex) if not e.rerunning()] + if (any(e.state in ALIVE for e in runs) or _unended(ex)) and _first_is_ours(ex): + try: + ondisk.write_whole(_queue_stop(ex.root, ex.plan), json.dumps({"queue": ex.plan.queue, "at": time.time()})) + except OSError: + return False + for e in runs: + e.stop() + return True + + class Unreadable(OSError): """A key Settings holds for a run, or a file in its folder, could not be read: its message names it.""" @@ -2480,10 +2741,12 @@ def recorded(path: str, scripts: bool = True) -> tuple: plan = rec["plan"] rec.setdefault("caps", plan.pop("caps", None) or {}) return rec, plan - if rec.get("version", 0) > VERSION: + if rec.get("version", 0) > QUEUE_VERSION: raise ValueError(f"{path} was recorded by a later Nullius") with open(os.path.join(path, PLAN), encoding="utf-8") as fh: plan = json.load(fh) + if plan.get("go_on"): + raise ValueError(f"{path} is a suite's joined plan, of a design that was dropped: it is not picked up; run the suite again") rec.setdefault("caps", plan.pop("caps", None) or {}) ids = {p.get("id") for p in plan.get("parts") or ()} plan["parts"] = (plan.get("parts") or []) + [dict(p) for p in rec.get("again") or () if p.get("id") not in ids] @@ -2513,7 +2776,8 @@ def restore(root: Optional[str] = None, **kw) -> List[Execution]: try: rec, plan = recorded(os.path.join(root, name)) plan = Plan.from_dict(plan) - except (OSError, ValueError, KeyError, TypeError): + except (OSError, ValueError, KeyError, TypeError) as e: + _lost(root, name, e, kw) continue ex = Execution(plan, root=root, record=rec, **kw) EXECUTIONS[ex.id] = ex @@ -2522,6 +2786,52 @@ def restore(root: Optional[str] = None, **kw) -> List[Execution]: return back +def _lost(root: str, name: str, why: Exception, kw: dict) -> Optional[Execution]: + """A run of a queue whose plan ``restore`` cannot read back, held as its record says it (``member``): on the + pages, in its queue (``queue_of``) and under its Stop, with a plan of what the record kept and nothing to + run. While the record says it is alive it is looked at again (``Execution._keep_lost``). None, and nothing held, + for a run of no queue, and for a record that cannot be read or is a later Nullius's: the queue is held by + that record.""" + try: + with open(os.path.join(root, name, RECORD), encoding="utf-8") as fh: + rec = json.load(fh) + if not rec.get("queue") or rec.get("version", 0) > QUEUE_VERSION: + return None + member = rec.get("member") if isinstance(rec.get("member"), dict) else {} + # the parts it ran again stay its plan's: a run running tasks again is not its queue's, held or not (``rerunning``) + plan = Plan(name=name, script="", queue=str(rec["queue"]), queue_runs=[str(n) for n in member.get("runs") or [name]], + parts=[dict(p) for p in rec.get("again") or () if isinstance(p, dict)], + jobs=[dict(j) for j in member.get("jobs") or ()], runner=str(member.get("runner") or "harbor"), + recipe=dict(member.get("recipe") or {}), queue_recipe={"rest_of": member["rest_of"]} if member.get("rest_of") else {}) + ex = Execution(plan, root=root, record=rec, **kw) + except (OSError, ValueError, AttributeError, TypeError, KeyError): + return None + ex.lost = f"could not be picked up again: {getattr(why, 'strerror', None) or why}" + ex.promoted = bool(rec.get("promoted", True)) + EXECUTIONS[ex.id] = ex + if ex.state in ALIVE: + ex.thread = threading.Thread(target=ex._keep_lost, args=(rec, bool(member.get("remote")), kw), name=f"run-{name}", daemon=True) + ex.thread.start() + return ex + + +def _in_folder(path: str) -> Optional[List[int]]: + """The processes of this machine whose working directory is the run folder *path* or under it: a part's + detached shell stays there until its script ends. None where that cannot be told (no ``PROC``).""" + if not os.path.isdir(PROC): + return None + real, out = os.path.realpath(path), [] + for p in os.listdir(PROC): + if p.isdigit() and int(p) != os.getpid(): + try: + cwd = os.readlink(os.path.join(PROC, p, "cwd")) + except OSError: + continue + if cwd == real or cwd.startswith(real + os.sep): + out.append(int(p)) + return out + + # --- deleting a launch --------------------------------------------------------- def run_folder(name: str, root: Optional[str] = None) -> str: @@ -2602,6 +2912,8 @@ def _deletable(name: str, root: Optional[str]) -> tuple: state = ex.state if ex is not None else rec.get("state") if state in ALIVE: raise ValueError(f"{name} is {state}: stop it before you delete it") + if ex is not None and queue_open(ex): + raise ValueError(f"{name} is one of a suite's runs, and some have not ended: stop the suite before you delete it") return path, rec @@ -2767,6 +3079,8 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r with ex._turn: if ex.state in ALIVE: raise ValueError(f"{n} is {ex.state}: stop it before you delete it") + if queue_open(ex): + raise ValueError(f"{n} is one of a suite's runs, and some have not ended: stop the suite before you delete it") return _delete(names, home, root, copies, run) finally: with _CLAIMS: diff --git a/app/tests/test_execution_queue.py b/app/tests/test_execution_queue.py new file mode 100644 index 000000000..e082f1f46 --- /dev/null +++ b/app/tests/test_execution_queue.py @@ -0,0 +1,366 @@ +"""A queue: runs of one launch, one after the other, across a Stop, a Delete and a restart at each of its boundaries.""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import time +from pathlib import Path +from unittest.mock import patch + +from nullius import execution + +from tests.execution_support import Base + + +class Queue(Base): + def setUp(self): + super().setUp() + self.addCleanup(setattr, execution, "QUEUE_POLL", execution.QUEUE_POLL); execution.QUEUE_POLL = 0.02 + self.root, self.order = self.tmp / "runs", self.tmp / "order" + + def plans(self, scripts): + """A plan per script, named q1, q2...: each says its name in ``order`` first, and waits for the run before it.""" + names = [f"q{i}" for i in range(1, len(scripts) + 1)] + return [execution.Plan(name=n, script=f"echo {n} >> {self.order}; {s}", queue="one-launch", queue_runs=names, after=names[i - 1] if i else "") + for i, (n, s) in enumerate(zip(names, scripts))] + + def launch(self, *scripts): + return execution.start_all([execution.Execution(p, root=str(self.root)) for p in self.plans(scripts)]) + + def ran(self): + return self.order.read_text().split() if self.order.exists() else [] + + def test_each_run_starts_once_the_one_before_it_ended_and_a_failed_one_does_not_stop_the_next(self): + gate = self.tmp / "gate" + q1, q2, q3 = self.launch(f"while [ ! -e {gate} ]; do sleep 0.02; done", "exit 3", "true") + self.until_recorded(q1, "running") + time.sleep(0.3) + self.assertEqual((self.ran(), q2.state, q2.step, q3.state), (["q1"], "preparing", "queued", "preparing")) + self.assertIn("— waiting for q1 to end", q2.lines) + self.assertEqual((q1.live_state("q1"), q2.live_state("q2")), ("running", "queued")) # as the Runs page says it + gate.write_text("") + for ex in (q1, q2, q3): + self.wait(ex) + self.assertEqual((self.ran(), [e.state for e in (q1, q2, q3)]), (["q1", "q2", "q3"], ["done", "failed", "done"])) + self.assertGreaterEqual(q3.started, q2.finished) # its start is its turn, not the launch + self.assertEqual(execution.recorded(q3.dir)[1]["after"], "q2") # the link is in the plan the launch saved + + def test_a_record_that_cannot_be_read_holds_the_queue_until_it_can(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + q3 = execution.Execution(execution.Plan(name="q3", script="true", queue="one-launch", queue_runs=["q1", "q2", "q3"], after="gone"), root=str(self.root)).start() + time.sleep(0.3) + self.assertEqual(q3.state, "preparing") + self.assertIn("— the record of gone cannot be read; the queue is held until it can", q3.lines) + (self.root / "gone").mkdir(); (self.root / "gone" / "run.json").write_text('{"state": "running", "queue": "one-launch"}') + time.sleep(0.2) + self.assertEqual(q3.state, "preparing") # a run not ended, as far as its record says + (self.root / "gone" / "run.json").write_text('{"state": "failed", "queue": "another-launch"}') + time.sleep(0.2) + self.assertEqual(q3.state, "preparing") # a run of that name another launch made + self.assertIn("— the record of gone is not this launch's; the queue is held until it can", q3.lines) + mine = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "gone" / "run.json").write_text(json.dumps(mine)) # a sibling's record copied over it: ended, of this queue + time.sleep(0.2) + self.assertEqual(q3.state, "preparing") + self.assertIn("— the record of gone is not that run's first attempt; the queue is held until it can", q3.lines) + for other in ({"version": execution.VERSION}, {"again": [{"id": "again-1"}]}): + (self.root / "gone" / "run.json").write_text(json.dumps({**mine, "id": "gone-1", **other})) + time.sleep(0.2) + self.assertEqual(q3.state, "preparing", other) + (self.root / "gone" / "run.json").write_text(json.dumps(dict(mine, id="gone-1", state="failed"))) + self.assertEqual(self.wait(q3).state, "done") + + def test_an_end_that_was_not_saved_holds_the_next_run_until_it_is(self): + real, refuse = execution.Execution._save, [True] + def save(ex, *a, **kw): + if ex.plan.name == "q1" and ex.state == "done" and refuse[0]: + return False # the disk was full as it ended + return real(ex, *a, **kw) + with patch.object(execution.Execution, "_save", save): + q1, q2 = self.launch("true", "true") + self.wait(q1); time.sleep(0.3) + self.assertEqual((q2.state, self.ran()), ("preparing", ["q1"])) + self.assertIn("— the end of q1 is not saved yet; the queue is held until it can", q2.lines) + refuse[0] = False + self.assertEqual(self.wait(q2).state, "done") + + def test_stop_ends_the_run_under_way_and_every_run_waiting_and_none_starts_after_a_restart(self): + q1, q2, q3 = runs = self.launch("sleep 30", "true", "true") + self.until_recorded(q1, "running") + self.assertTrue(execution.stop(q3)) # any of its runs: the Stop is the queue's + for ex in runs: + self.wait(ex) + self.assertEqual(([e.state for e in runs], self.ran()), (["stopped"] * 3, ["q1"])) + self.assertTrue((self.root / "q1" / execution.QUEUE_STOP).exists()) + self.assertIn("✕ stopped before the run: exit 130", q2.lines) + execution.EXECUTIONS.clear() + self.assertEqual(execution.restore(str(self.root)), []) + + def test_no_run_of_an_open_queue_is_deleted_or_run_again(self): + gate = self.tmp / "gate" + q1, q2, q3 = self.launch("true", f"while [ ! -e {gate} ]; do sleep 0.02; done", "true") + self.wait(q1); self.until_recorded(q2, "running") + for names in (["q1"], ["q1", "q2", "q3"]): + with self.assertRaisesRegex(ValueError, "stop"): + execution.delete(names, str(self.tmp / "ws"), str(self.root)) + self.assertRaisesRegex(ValueError, "q1 is one of a suite's runs", execution.deletable, ["q1"], str(self.root)) + with self.assertRaisesRegex(ValueError, "one of a suite's runs, and some have not ended"): + q1.again({"id": "again-1", "label": "again", "script": "true", "again": "job"}) + gate.write_text("") + self.wait(q2); self.wait(q3) + gone = execution.delete(["q1", "q2", "q3"], str(self.tmp / "ws"), str(self.root)) + self.assertEqual((gone["stays"], sorted(os.listdir(self.root))), ([], [".lock"] if (self.root / ".lock").exists() else [])) + + KILLED = ("import json, os, re, signal, sys\n" + "sys.path.insert(0, sys.argv[1]); from nullius import execution\n" + "root, plans, end, mark, stop = json.loads(sys.argv[2])\n" + "execution.QUEUE_POLL = execution.SYNC_EVERY = 0.02\n" + "real = execution.ondisk.write_whole\n" + "def call(path, data, *a, **k):\n" + " out = real(path, data, *a, **k)\n" + " if end in str(path) and (re.search(mark[3:], data) if mark.startswith('re:') else mark in data): os.kill(os.getpid(), signal.SIGKILL)\n" + " return out\n" + "execution.ondisk.write_whole = call\n" + "execution.docker_here = lambda *a, **k: None\n" + "exs = execution.start_all([execution.Execution(execution.Plan(**p), root=root) for p in plans])\n" + "if stop:\n" + " while not os.path.exists(stop): pass\n" + " execution.stop(exs[-1])\n" + "for ex in exs: ex.thread.join(60)\n") + + def killed(self, scripts, end, mark, stop=False): + """The queue of *scripts* launched in a process of its own, killed just after it wrote *mark* to a file whose path holds *end*; *stop*: it stops the queue once q1 runs.""" + app = str(Path(execution.__file__).resolve().parents[1]) + plans = [{"name": p.name, "script": p.script, "queue": p.queue, "queue_runs": p.queue_runs, "after": p.after} for p in self.plans(scripts)] + return subprocess.run([sys.executable, "-c", self.KILLED, app, json.dumps([str(self.root), plans, end, mark, str(self.order) if stop else ""])], timeout=60).returncode + + def test_a_queue_killed_at_any_of_its_boundaries_runs_each_of_its_runs_once_in_order_after_a_restart(self): + for case, end, mark in (("the launch decided, none started", ".launch-", '"committed"'), + ("q1 ended, q2 not yet promoted", "q1/run.json", '"state": "done"'), + ("q2 promoted, nothing of it started", "q2/run.json", '"promoted": true'), + ("q2 ended failed, q3 not yet promoted", "q2/run.json", '"state": "failed"'), + ("q3 promoted", "q3/run.json", '"promoted": true'), + ("q1 under way", "q1/run.json", '"state": "running"'), # between two boundaries + ("q2 under way", "q2/run.json", '"state": "running"')): + with self.subTest(case=case): + slug = case.replace(" ", "-").replace(",", "") + self.root, self.order = self.tmp / slug, self.tmp / (slug + ".order") + self.assertEqual(self.killed(["true", "exit 3", "true"], end, mark), -9) + back = execution.restore(str(self.root)) + for ex in back: + self.wait(ex, 20) + states = {e.plan.name: e.state for e in execution.EXECUTIONS.values()} + self.assertEqual((self.ran(), states), (["q1", "q2", "q3"], {"q1": "done", "q2": "failed", "q3": "done"}), case) + execution.EXECUTIONS.clear() + + def test_a_queue_killed_as_its_stop_was_saved_starts_nothing_more_after_a_restart(self): + self.assertEqual(self.killed(["sleep 30", "true", "true"], execution.QUEUE_STOP, '"at"', stop=True), -9) + for ex in execution.restore(str(self.root)): + self.wait(ex, 30) + self.assertEqual(({e.plan.name: e.state for e in execution.EXECUTIONS.values()}, self.ran()), + ({"q1": "stopped", "q2": "stopped", "q3": "stopped"}, ["q1"])) + + AGAIN = {"id": "again-1", "label": "again", "script": "sleep 30", "again": "job"} + + def test_a_run_again_after_a_stop_is_its_own_and_one_does_not_hold_the_others(self): + q1, q2 = runs = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + execution.stop(q1) + for ex in runs: + self.wait(ex) + q1.again(dict(self.AGAIN)) # the queue closed: its Stop is past + self.until_recorded(q1, "running") + self.assertFalse(execution.queue_open(q2)) # one run again does not hold the launch + execution.deletable(["q2"], str(self.root)) + execution.EXECUTIONS.clear() # Nullius restarted: the old flag is not this attempt's + back, = execution.restore(str(self.root)) + time.sleep(0.3) + self.assertEqual((back.plan.name, back.state), ("q1", "running")) + flag = self.root / "q1" / execution.QUEUE_STOP + flag.unlink() + self.assertTrue(execution.stop(back)) # its own Stop, not the queue's + self.assertEqual((self.wait(back).state, flag.exists()), ("stopped", False)) + + def test_a_flag_another_launch_left_stops_nothing(self): + gate = self.tmp / "gate" + q1, q2 = self.launch(f"while [ ! -e {gate} ]; do sleep 0.02; done", "true") + self.until_recorded(q1, "running") + (self.tmp / "flag").write_text('{"queue": "another-launch"}') # put there whole: one half written cannot be read, and stops + os.replace(self.tmp / "flag", self.root / "q1" / execution.QUEUE_STOP) + gate.write_text("") + self.assertEqual([self.wait(e).state for e in (q1, q2)], ["done", "done"]) + + def test_a_stop_asked_again_is_saved_while_a_record_does_not_say_its_run_ended(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="preparing", promoted=False))) # its end never reached the disk + self.assertTrue(execution.stop(q1)) + self.assertEqual(json.loads((self.root / "q1" / execution.QUEUE_STOP).read_text())["queue"], "one-launch") + execution.EXECUTIONS.clear() + for ex in execution.restore(str(self.root)): + self.wait(ex) + self.assertEqual(self.ran(), ["q1", "q2"]) # q2 is not started a second time + + def test_a_queue_s_records_are_of_a_version_an_older_nullius_leaves_alone(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + self.assertEqual((rec["version"], rec["queue"]), (execution.QUEUE_VERSION, "one-launch")) + self.assertGreater(rec["version"], execution.VERSION) + with patch.object(execution, "QUEUE_VERSION", execution.VERSION): # as a Nullius from before queues reads it + self.assertRaisesRegex(ValueError, "a later Nullius", execution.recorded, str(self.root / "q2")) + plan = json.loads((self.root / "q1" / "plan.json").read_text()) + (self.root / "q1" / "plan.json").write_text(json.dumps(dict(plan, go_on=True))) + self.assertRaisesRegex(ValueError, "a suite's joined plan, of a design that was dropped", execution.recorded, str(self.root / "q1")) + + def lost(self, script="sleep 3", then=("true",)): + """q1 under way, its process alive, Nullius killed, and its plan not to be read back at the restart.""" + self.assertEqual(self.killed([script, *then], "q1/run.json", r're:"pid": \d'), -9) + self.plan = (self.root / "q1" / "plan.json").read_text() + (self.root / "q1" / "plan.json").write_text("{") + execution.restore(str(self.root)) + return [next(e for e in execution.EXECUTIONS.values() if e.plan.name == n) for n in ("q1", "q2")] + + def test_a_run_whose_plan_cannot_be_read_back_holds_the_next_one_until_its_process_is_gone(self): + q1, q2 = self.lost() + time.sleep(1) + self.assertEqual((self.ran(), q1.state, q2.state), (["q1"], "running", "preparing")) # q1's part runs on: q2 does not start + self.assertTrue(q1.lost and execution.queue_open(q2)) + self.assertEqual([e.plan.name for e in execution.queue_of(q2)], ["q1", "q2"]) # on the launch, under its Stop + self.assertRaisesRegex(ValueError, "stop", execution.delete, ["q1", "q2"], str(self.tmp / "ws"), str(self.root)) + self.wait(q1, 20) + self.assertEqual(self.wait(q2, 20).state, "done") + rec = json.loads((self.root / "q1" / "run.json").read_text()) + self.assertEqual((rec["state"], q1.state, self.ran()), ("failed", "failed", ["q1", "q2"])) + self.assertGreaterEqual(json.loads((self.root / "q2" / "run.json").read_text())["started"], rec["finished"]) + self.assertIn("could not be picked up again", rec["error"]) + self.assertIn("the runs after it go on", (self.root / "q1" / "nullius.log").read_text()) + execution.EXECUTIONS.clear() # the restart after: still one of its launch + self.assertEqual(execution.restore(str(self.root)), []) + self.assertEqual({e.plan.name: (e.state, bool(e.lost)) for e in execution.EXECUTIONS.values()}, {"q1": ("failed", True), "q2": ("done", False)}) + self.assertEqual(execution.delete(["q1", "q2"], str(self.tmp / "ws"), str(self.root))["stays"], []) + + def test_a_plan_that_can_be_read_again_is_picked_up_not_failed(self): + q1, q2 = self.lost() + time.sleep(0.3) + (self.root / "q1" / "plan.json").write_text(self.plan) # unreadable once + for _ in range(100): + q1 = next(e for e in execution.EXECUTIONS.values() if e.plan.name == "q1") + if not q1.lost: + break + time.sleep(0.05) + self.assertEqual((self.wait(q1, 20).state, self.wait(q2, 20).state, self.ran()), ("done", "done", ["q1", "q2"])) + + def test_the_stop_of_a_queue_ends_a_run_held_without_its_plan(self): + q1, q2 = self.lost("sleep 30") + self.assertTrue(execution.stop(q2)) + self.wait(q1, 20); self.wait(q2, 20) + self.assertEqual((json.loads((self.root / "q1" / "run.json").read_text())["state"], q2.state, self.ran()), ("stopped", "stopped", ["q1"])) + self.assertEqual(execution._in_folder(q1.dir), []) + self.assertFalse(execution.queue_open(q2)) + + def test_a_stop_that_cannot_be_saved_tells_no_run(self): + q1, q2 = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + real = execution.ondisk.write_whole + def full(path, *a, **kw): + if str(path).endswith(execution.QUEUE_STOP): + raise OSError(28, "No space left on device") + return real(path, *a, **kw) + with patch.object(execution.ondisk, "write_whole", full): + self.assertFalse(execution.stop(q1)) + time.sleep(0.2) + self.assertEqual((q1.state, q2.state), ("running", "preparing")) # none was told: none ends without the flag + self.assertTrue(execution.stop(q1)) + self.assertEqual([self.wait(e).state for e in (q1, q2)], ["stopped", "stopped"]) + + def test_a_run_again_that_finished_is_not_stopped_by_the_old_flag_at_a_restart(self): + q1, q2 = runs = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + execution.stop(q1) + for ex in runs: + self.wait(ex) + q1.again(dict(self.AGAIN, script="true")) + self.assertEqual(self.wait(q1).state, "done") + rec = json.loads((self.root / "q1" / "run.json").read_text()) + (self.root / "q1" / "run.json").write_text(json.dumps(dict(rec, state="running", finished=None))) # killed between its part's end and its own + self.assertTrue((self.root / "q1" / execution.QUEUE_STOP).exists()) + execution.EXECUTIONS.clear() + back, = execution.restore(str(self.root)) + self.assertEqual((back.plan.name, self.wait(back).state), ("q1", "done")) + + def test_a_name_another_launch_took_neither_holds_the_queue_nor_gets_its_stop(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + execution.delete(["q1"], str(self.tmp / "ws"), str(self.root)) # the queue closed: each run is its own + other = execution.Execution(execution.Plan(name="q1", script="true", queue="another-launch", queue_runs=["q1"]), root=str(self.root)) + self.wait(execution.start_all([other])[0]) + self.assertFalse(execution.queue_open(q2)) + execution.deletable(["q2"], str(self.root)) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="running"))) # its end unsaved: a Stop would be saved + self.assertTrue(execution.stop(q2)) + self.assertFalse((self.root / "q1" / execution.QUEUE_STOP).exists()) # not in the other launch's folder + + def test_a_name_reserved_by_another_launch_with_no_record_yet_does_not_get_the_stop(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + execution.delete(["q1"], str(self.tmp / "ws"), str(self.root)) + other = [execution.Execution(execution.Plan(name="q1", script="true", queue="another-launch", queue_runs=["q1"]), root=str(self.root))] + execution.reserve(other) # its folder is there, its first record is not + self.assertFalse((self.root / "q1" / "run.json").exists()) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="running"))) # a Stop would be saved + self.assertTrue(execution.stop(q2)) + self.assertFalse((self.root / "q1" / execution.QUEUE_STOP).exists()) + self.assertEqual(self.wait(execution.start_all(other, reserved=True)[0]).state, "done") # and it starts as reserved + + def test_a_run_again_held_without_its_plan_does_not_take_the_old_stop(self): + q1, q2 = runs = self.launch("sleep 30", "true") + self.until_recorded(q1, "running") + execution.stop(q1) + for ex in runs: + self.wait(ex) + q1.again(dict(self.AGAIN)) + self.until_recorded(q1, "running") + for _ in range(200): + if execution._in_folder(q1.dir): break + time.sleep(0.02) + (self.root / "q1" / "plan.json").write_text("{") + execution.EXECUTIONS.clear() # Nullius restarted: the flag of the Stop before is still there + execution.restore(str(self.root)) + held = next(e for e in execution.EXECUTIONS.values() if e.plan.name == "q1") + time.sleep(0.5) + self.assertEqual((bool(held.lost), held.rerunning(), held.state, json.loads((self.root / "q1" / "run.json").read_text())["state"]), + (True, True, "running", "running")) + self.assertTrue(execution.stop(held)) # its own Stop ends it + self.wait(held, 20); q1.stop(); self.wait(q1, 20) + self.assertEqual(held.state, "stopped") + + def test_a_queue_is_open_by_its_records_not_by_what_this_process_holds(self): + q1, q2 = self.launch("true", "true") + self.wait(q1); self.wait(q2) + rec = json.loads((self.root / "q2" / "run.json").read_text()) + (self.root / "q2" / "run.json").write_text(json.dumps(dict(rec, state="running"))) + execution.EXECUTIONS.pop(q2.id) # not held here + self.assertTrue(execution.queue_open(q1)) + self.assertRaisesRegex(ValueError, "stop", execution.deletable, ["q1"], str(self.root)) + (self.root / "q2" / "run.json").write_text(json.dumps(rec)) + self.assertFalse(execution.queue_open(q1)) + + def test_a_waiting_run_reads_its_key_as_its_turn_comes(self): + gate, env = self.tmp / "gate", dict(os.environ, MY_KEY="at-launch") + plans = self.plans([f"while [ ! -e {gate} ]; do sleep 0.02; done", "true"]) + for p in plans: + p.key_var = "MY_KEY" + q1, q2 = execution.start_all([execution.Execution(p, root=str(self.root), env=env) for p in plans]) + self.until_recorded(q1, "running") + env["MY_KEY"] = "set-since" # changed in Settings while q2 waited + gate.write_text("") + self.wait(q2) + self.assertEqual((q1._key, q2._key), ("at-launch", "set-since")) diff --git a/app/ui_tests/test_api.py b/app/ui_tests/test_api.py index 9b9f83e82..6231ea688 100644 --- a/app/ui_tests/test_api.py +++ b/app/ui_tests/test_api.py @@ -683,6 +683,9 @@ def test_a_running_run_is_stopped_from_another_machine(self): for _ in range(400): if "started" in "\n".join(self.get(f"/runs/{run_id}").json["log"]): break time.sleep(0.02) + with patch.object(execution, "stop", lambda ex: False): # a queue's Stop that could not be saved + s = self.post(f"/runs/{run_id}/stop", environ_base={"REMOTE_ADDR": "10.0.0.7"}) + self.assertEqual((s.status_code, "no run was told" in s.json["error"]), (503, True)) s = self.post(f"/runs/{run_id}/stop", environ_base={"REMOTE_ADDR": "10.0.0.7"}) self.assertEqual((s.status_code, s.json["id"]), (200, run_id)) self.assertIn(s.json["state"], ("stopping", "stopped")) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 4fffd8837..83d95622e 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -549,6 +549,10 @@ def test_the_page_carries_the_token_the_stop_button_sends(self): for _ in range(200): if ex.pid: break time.sleep(0.02) + with patch.object(execution, "stop", lambda ex: False): # a queue's Stop that could not be saved: said, none told + s = self.client.post(f"/run/{r.json['id']}/stop", headers={"Origin": "http://localhost", "X-CSRF-Token": self.csrf}); self.addCleanup(s.close) + self.assertEqual((s.status_code, s.json["ok"], ex.state), (503, False, "running")) + self.assertIn("no run was told", s.json["error"]) s = self.client.post(f"/run/{r.json['id']}/stop", headers={"Origin": "http://localhost", "X-CSRF-Token": self.csrf}); self.addCleanup(s.close) self.assertEqual(s.status_code, 200); self.assertEqual(s.json["state"], "stopping") # said at once ex.thread.join(10); self.assertEqual((ex.state, ex.exit_code), ("stopped", 130)) diff --git a/app/web/api.py b/app/web/api.py index 34bd93f90..0cbd7fc21 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -532,7 +532,8 @@ def api_run(run_id): @api("run") def api_run_stop(run_id): ex = _run(run_id) - ex.stop() + if not execution.stop(ex): # a suite's Stop is its whole queue's, saved before its runs are told + raise _Refused(503, "the Stop could not be saved, so no run was told: stop it again") return _json(ex.summary()) diff --git a/app/web/execute.py b/app/web/execute.py index 3cce0e6b3..95f7841a6 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -484,7 +484,8 @@ def run_stop(run_id): ex = execution.EXECUTIONS.get(run_id) if ex is None: abort(404) - ex.stop() + if not execution.stop(ex): # a suite's Stop is its whole queue's, saved before its runs are told + return jsonify({**ex.summary(), "ok": False, "error": "The Stop could not be saved, so no run was told: stop it again."}), 503 return jsonify(ok=True, **ex.summary()) From 0c7ff3b4f689e37f89bd538c9ca3df915b1ae7a2 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 18:29:23 +0100 Subject: [PATCH 3/3] feat(builder): run a suite as one launch of ordinary runs --- .../catalogue/agents/digitalmate/agent.json | 1 + app/nullius/client.py | 12 +- app/nullius/mcp_server.py | 5 +- app/nullius/standard/cli.py | 75 ++++- app/nullius/standard/contract/definitions.py | 4 + app/nullius/standard/pages/recipe.py | 265 +++++++++++++++++- app/nullius/standard/runner/job.py | 8 +- app/nullius/standard/runner/rerun.py | 13 + app/nullius/standard/runner/run.py | 13 +- app/nullius/standard/runner/suites.py | 79 ++++++ app/static/builder/command-builder-core.js | 2 +- app/static/builder/command-builder.js | 14 +- app/static/runs/launches.css | 2 +- app/templates/builder/benchmarks.html | 10 +- app/templates/catalogue/suite.html | 3 +- app/templates/runs/_execution.html | 3 +- app/templates/runs/index.html | 8 +- app/tests/test_standard_run.py | 4 + app/tests/test_suites.py | 241 ++++++++++++++++ app/ui_tests/test_builder_benchmarks.py | 2 +- app/ui_tests/test_builder_check_chips.py | 2 +- app/ui_tests/test_builder_limit_error.py | 2 +- app/ui_tests/test_suite_routes.py | 188 +++++++++++++ app/web/api.py | 9 +- app/web/builder.py | 49 +++- app/web/execute.py | 229 ++++++++++++++- app/web/runs.py | 73 ++++- docs/agents/add-manually.md | 3 + docs/api.md | 4 +- docs/builder.md | 1 + docs/cli/pages.md | 4 +- docs/cli/run.md | 26 ++ docs/concepts.md | 3 +- 33 files changed, 1295 insertions(+), 62 deletions(-) diff --git a/app/nullius/catalogue/agents/digitalmate/agent.json b/app/nullius/catalogue/agents/digitalmate/agent.json index 0338f0bd8..d1b1e4f57 100644 --- a/app/nullius/catalogue/agents/digitalmate/agent.json +++ b/app/nullius/catalogue/agents/digitalmate/agent.json @@ -4,6 +4,7 @@ "label": "DigitalMate", "company": "ThinkFlowLab", "summary": "DigitalMate's Personal Agent service, run as Hive Home with its owned WorkSwarm runtimes.", + "backends": ["container"], "model": { "apis": [ "chat" diff --git a/app/nullius/client.py b/app/nullius/client.py index 033bf0ba9..50d037c05 100644 --- a/app/nullius/client.py +++ b/app/nullius/client.py @@ -186,10 +186,11 @@ def check(self, recipe: Union[dict, str], where=None) -> dict: return self.request("POST", "/runs/check", self._run_body(recipe, where)) def start(self, recipe: Union[dict, str], where=None, name: Optional[str] = None, confirm: bool = False, - workspace: Optional[str] = None) -> dict: - """Start a recipe; ``runs`` holds one run per machine. ``confirm``: the yes to the question ``check`` returns. - ``workspace``: the one its jobs go into, made when there is none; the open one stays open.""" - return self.request("POST", "/runs", self._run_body(recipe, where, name=name, confirm=confirm, workspace=workspace)) + workspace: Optional[str] = None, reviewed: Optional[str] = None) -> dict: + """Start a recipe; ``runs`` holds one run per machine, or of a suite one per member and participant. ``confirm``: the yes to the question ``check`` returns. + ``workspace``: the one its jobs go into, made when there is none; the open one stays open. + ``reviewed``: of a suite, the digest ``check`` returned, without which it is refused.""" + return self.request("POST", "/runs", self._run_body(recipe, where, name=name, confirm=confirm, workspace=workspace, reviewed=reviewed)) def runs(self) -> list: return self.request("GET", "/runs") @@ -299,6 +300,7 @@ def main(argv=None) -> int: p.add_argument("--name", help="the run's name (default: the recipe's name and the second)") p.add_argument("--workspace", help="the workspace its jobs go into, made when there is none (default: the open one)") p.add_argument("--yes", action="store_true", help="answer yes to the question the check returns") + p.add_argument("--reviewed", metavar="DIGEST", help="of a suite: the digest its check returned") p.add_argument("--follow", action="store_true", help="print the log until the run ends; exit 4 unless it ends done") sub.add_parser("runs", help="the runs the server follows") p = sub.add_parser("status", help="one run: its state, stages and log") @@ -316,7 +318,7 @@ def main(argv=None) -> int: return EXIT_USAGE try: if a.cmd == "run": - out = nx.start(_recipe_arg(a.recipe), where=a.where, name=a.name, confirm=a.yes, workspace=a.workspace) + out = nx.start(_recipe_arg(a.recipe), where=a.where, name=a.name, confirm=a.yes, workspace=a.workspace, reviewed=a.reviewed) if a.follow: ok = True for r in out["runs"]: diff --git a/app/nullius/mcp_server.py b/app/nullius/mcp_server.py index ce05ea4da..5866f9e78 100644 --- a/app/nullius/mcp_server.py +++ b/app/nullius/mcp_server.py @@ -64,8 +64,9 @@ "and the question to confirm.", {**_RECIPE, "where": _S}, ["recipe"], lambda nx, a: nx.check(a["recipe"], a.get("where"))), "start_run": ("Start a recipe. It spends model tokens and machine time: call check_run first, and set confirm only " - "when the person has agreed to the question it returned.", {**_RECIPE, "where": _S, "confirm": _B, **_WORKSPACE}, ["recipe"], - lambda nx, a: nx.start(a["recipe"], a.get("where"), confirm=a.get("confirm") is True, workspace=a.get("workspace"))), + "when the person has agreed to the question it returned.", {**_RECIPE, "where": _S, "confirm": _B, "reviewed": _S, **_WORKSPACE}, ["recipe"], + lambda nx, a: nx.start(a["recipe"], a.get("where"), confirm=a.get("confirm") is True, workspace=a.get("workspace"), + reviewed=a.get("reviewed"))), "list_runs": ("The runs the server follows: state, stages, job ids.", {}, [], lambda nx, a: nx.runs()), "get_run": ("One run: state, stages, and its log lines from `since` on.", {**_RUN, "since": _I}, ["run_id"], lambda nx, a: nx.run(a["run_id"], a.get("since") or 0)), diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 9a7e69800..88529c45c 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -316,6 +316,27 @@ def cmd_check(a): @definitions.reading() def cmd_fit(a): + s = suites.find(a.benchmark) + if s: # a suite: each agent runs every member that takes one, or none (suites.plan) + got = _all()[0] + ids = [m["id"] for m in s["members"]] + wrong = [x for x in a.dataset or () if x not in ids] + if wrong: + print(f"refused: {', '.join(wrong)} is no member of {s['ref']}: {', '.join(ids)}") + return 2 + try: + for o in got["agent"]: + p = suites.plan(s, got, [o["_ref"]], chosen=a.dataset or None, backend=definitions.names.backend(a.backend or "local")) + own = [r for r in p["rows"] if not r["setup"]] + no = p["unfit"].get(o["_ref"]) or [] + on = sorted({b for r in own for b in r["backend"].values() if b != "local"}) + print(f" {'✗' if no else '✓'} {o['_ref']}: " + (f"{len(own) - len(no)} of {len(own)} benchmarks" if no else + "every member" + (f", on the {' and '.join(on)} backend" if on else "")) + + "".join(f"\n {label}: {why}" for label, why in no)) + except suites.Refused as e: + print("refused:", e) + return 2 + return 0 b = definitions.get("benchmark", a.benchmark) if not b: sys.exit(f"no benchmark {a.benchmark!r}") @@ -610,6 +631,10 @@ def _bench(key): def cmd_run(a): + if suites.find(a.benchmark): # until the command launches through the builder's queue (docs/cli/run.md) + print(f"refused: {a.benchmark} is a suite: run it from the builder (New run), which starts its runs one after the other; " + f"nullius standard fit {a.benchmark} says which agents run it") + return 2 b = _bench(a.benchmark) task_set, dataset, bench_options = None, a.dataset, options(a.bench_option) if a.task_set is not None: @@ -619,6 +644,33 @@ def cmd_run(a): except sets.Refused as e: print("refused:", e) return 2 + if a.set_hash and (task_set or {}).get("hash") != a.set_hash: + print(f"refused: --set-hash: the task set {a.task_set} is not the list this run was reviewed with: launch the suite again") + return 2 + suite = suites.marked(a.suite) if a.suite else None + if a.suite: + # the mark is true of this run, or the run is refused: the suite as reviewed, its list, the launch that carries it + s = suite and suites.find(f"{suite['key']}@{suite['version']}") + try: + with open(os.path.join(os.path.dirname(os.path.abspath(a.jobs)), "plan.json"), encoding="utf-8") as fh: + launched = json.load(fh) + said = (launched.get("recipe") or {}).get("suite") or {} + launched = bool(launched.get("queue")) and said.get("mark") == a.suite + # the member, the participant and the options Review showed for this run, against what this command was given + bound = said.get("set_hash") == a.set_hash and said.get("bound") == {"benchmark": a.benchmark, "other": a.other, "model": a.model or "", "dataset": a.dataset, + "limit": a.limit, "backend": a.backend, "max_usd": a.max_usd} + except (OSError, ValueError, AttributeError): + launched = bound = False + why = ("KEY@VERSION:DIGEST:HASH:PIN, as a suite's launch writes it" if not suite else + f"no suite {suite['key']}@{suite['version']} here" if not s else + "the suite changed since Review: review it again" if s["hash"] != suite["hash"] else + f"a suite's run takes its suite's list, --set {suites.set_name(s)} --set-hash" if a.task_set != suites.set_name(s) or not a.set_hash else + "only a suite's own launch marks a run: run the suite from the builder (New run)" if not launched else + "the run is not the one reviewed (its list, member, participant, model, limit, cap or backend differs): review the suite again" if not bound else "") + if why: + print("refused: --suite:", why) + return 2 + suite = dict(suite, members=[m["id"] for m in s["members"] if m["benchmark"] == b["key"] and m["dataset"] == dataset]) if a.other in definitions.CONTROLS: other = definitions.control(b, a.other) if other is None: @@ -642,7 +694,13 @@ def cmd_run(a): if why: print("refused: constraints:", why) return 2 + if suite and suites.pin(b, None if a.other in definitions.CONTROLS + definitions.SETUPS else other) != suite["pin"]: + print(f"refused: --suite: {b['label']} or {a.other} is no longer what was reviewed (a version, a pin or a setting changed): review the suite again") + return 2 if a.backend == "boat" and definitions.boots_vms(b): + if suite: # that path plans from the dataset's count, not the list reviewed + print(f"refused: --suite: {b['label']} on Boat runs each task whole in a VM, which takes no selection of tasks yet") + return 2 return _boat_units(a, b, other) # a cap counts each call at its model's price: the public list fetched first (Settings, Model prices); a machine # that cannot reach it runs uncapped where a model has no price, and says so (run.Run) @@ -661,7 +719,7 @@ def cmd_run(a): try: 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, + 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, suite=suite, 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, @@ -1562,6 +1620,8 @@ def main(argv=None): c.add_argument("path", nargs="?") f = sub.add_parser("fit", help="what can run a benchmark, and why the rest cannot") f.add_argument("benchmark") + f.add_argument("--dataset", action="append", metavar="MEMBER", help="of a suite: the members taken, as the Dataset step ticks them (default: every member)") + f.add_argument("--backend", help="of a suite: the backend its runs are asked on (default: local)") p = sub.add_parser("pins", help="compare image pins with registry tags without changing them") p.add_argument("benchmark") p.add_argument("--tag", help="tag to compare (default: embedded tag, or latest)") @@ -1578,8 +1638,11 @@ def main(argv=None): p = sub.add_parser(name, help=helps[name]) if name == "run": p.add_argument("benchmark") - p.add_argument("other", help="an agent or a Module: KEY (its default version) or KEY@VERSION" + # of run, optional to the parser alone: a suite named with nothing after it is told the way to the builder (main) + p.add_argument("other", **({"nargs": "?"} if name == "run" else {}), help="an agent or a Module: KEY (its default version) or KEY@VERSION" + ("; or nop, oracle: a control the benchmark declares; or original, model: one of its setups" if name == "run" else "")) + if name == "run": + run_parser = p p.add_argument("--model", required=name == "conform", help="the model (a control needs none; original takes one of the paper's, its first by default)" if name == "run" else None) p.add_argument("--provider", default="openai", choices=sorted(providers.PROVIDERS)) @@ -1616,6 +1679,12 @@ def main(argv=None): 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") + if name == "run": + p.add_argument("--set-hash", metavar="SHA256", + help="with --set: refused unless the set's list has this hash (a suite's run is bound to the list reviewed)") + p.add_argument("--suite", metavar="KEY@VERSION:DIGEST:HASH:PIN", + help="the suite launch this run is one of, written by that launch alone: refused unless the suite, its list, " + "the benchmark and the participant are what was reviewed; the job's config records it") p.add_argument("--limit", type=int) p.add_argument("--start-with", metavar="N|FILE|set:NAME|ids:ID,ID...", help="plan the whole (the dataset, or what --units, --set, --limit name) and start with some of it: " @@ -1868,6 +1937,8 @@ def main(argv=None): for parser in (ap, *sub.choices.values(), *ss.choices.values()): parser.allow_abbrev = False a = ap.parse_args(argv) + if a.cmd == "run" and a.other is None and not suites.find(a.benchmark): + run_parser.error("the following arguments are required: other") if a.cmd == "replay" and not a.list and (a.call is None or a.times is None or a.max_usd is None): rp.error("--call N, --times K and --max-usd USD go together (or --list)") if a.cmd == "replay" and a.list and (a.call is not None or a.dry_run): diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 978e85e0b..67af40652 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1943,6 +1943,10 @@ def problems(d: dict, kind: str) -> List[str]: if only is not None and (not isinstance(only, list) or not only or len(set(map(str, only))) != len(only) or not all(isinstance(k, str) and _KEY.match(k) for k in only)): bad.append("only_for: the keys of the benchmarks it is the reference agent of, each once") + only_on = d.get("backends") + if only_on is not None and (not isinstance(only_on, list) or not only_on or len(set(map(str, only_on))) != len(only_on) + or not all(k in names.BACKENDS for k in only_on)): + bad.append(f"backends: the backends it runs on alone, each once, of {', '.join(names.BACKENDS)}") bad += _proven(d) bad += _install(d) bad += _env(d.get("env")) diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 2685874cc..e53e4241e 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -38,7 +38,7 @@ import os import re import shlex -from typing import Callable, Dict, List, Optional +from typing import Callable, Dict, List, Optional, Tuple from nullius import constraints as limits, hosts, providers from nullius.providers import PROVIDERS, STEP @@ -275,6 +275,29 @@ def suite_page(s: dict, benches: List[dict]) -> dict: "tasks": suites.tasks(s, g["members"])} for g in rows]) +def suite_pages(d: Dict[str, List[dict]]) -> Tuple[List[dict], Dict[str, dict]]: + """(pages, fits) of the suites the builder offers: each suite's default version, another version's own ``page`` + under it as a benchmark's; and by suite ref, each agent, none refused here (``suites.plan`` decides by the members chosen).""" + found, _ = suites.load() + pages, fits = [], {} + for s in found: + try: + page = suite_page(s, d["benchmark"]) + except suites.Refused: + continue # a pin the catalogue no longer has: its page says so + # an agent runs the suite when it fits every member chosen that takes one: the Agent step's grid and Review say which do + fits[s["ref"]] = {o["_ref"]: [] for o in d["agent"]} + fits[s["ref"]].update({c["key"]: [] for c in page["controls"]}) + if s["version"] == s["default"]: + pages.append(page) + for s in found: + base = next((x for x in pages if x["key"] == s["key"]), None) + for v in base["versions"] if base and s["version"] != s["default"] else (): + if v["version"] == s["version"] and s["ref"] in fits: + v["page"] = dict(suite_page(s, d["benchmark"]), versions=[]) + return pages, fits + + def protocol(o: dict) -> str: """How Nullius talks to it, in a word or two for a page, in sentence case as its filter names it.""" if o["_kind"] == "control": @@ -399,17 +422,19 @@ def choices(*, benchmark_keys=None) -> dict: keys.add(defaults[0]["key"]) defaults = [b for b in defaults if b["key"] in keys] benches = [b for b in benches if b["key"] in keys] - return {"benchmarks": [_with_versions(b) for b in defaults], + suite_list, suite_fits = suite_pages(_all()) if benchmark_keys is None else ([], {}) + return {"benchmarks": [_with_versions(b) for b in defaults] + suite_list, # Entries marked as examples are not offered for runs. "agents": [_other_page(o) for o in d["agent"] + definitions.benchmark_agents(d["benchmark"]) if not o.get("example")], "modules": [_other_page(o) for o in d["module"] if not o.get("example")], - "fits": match.table(benches, d["agent"], d["module"]), + "fits": {**match.table(benches, d["agent"], d["module"]), **suite_fits}, "ports": {p: s["summary"] for p, s in ports.PORTS.items()}, "providers": list(PROVIDERS)} -def licences_of(key: str) -> List[dict]: - """The credentials a benchmark's environments need, every version's, as its +def licences_of(key: str, version: Optional[str] = None) -> List[dict]: + """The credentials a benchmark's environments need, every version's - or + *version*'s alone, what one run of it may ask for - as its Settings lists them: [{environment, summary, needs: [{name, kind, to, summary, path?, env?, provider?, status}]}], ``status`` the store's (``secrets.status``: dates, never a value; a data provider's token, its @@ -418,7 +443,7 @@ def licences_of(key: str) -> List[dict]: have = secrets.status(key) out: Dict[str, dict] = {} for b in _all()["benchmark"]: - if b["key"] != key: + if b["key"] != key or (version is not None and (b.get("_version") or "") != version): continue for n, e in (b.get("environments") or {}).items(): env = out.setdefault(n, {"environment": n, "summary": e.get("summary", ""), "needs": []}) @@ -479,7 +504,8 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, docker_unusable: Optional[Callable[[], Optional[str]]] = None, boat_unusable: Optional[Callable[[], Optional[str]]] = None, boat_size_problem: Optional[Callable[[str], Optional[str]]] = None, - unpriced: Optional[Callable[[List[str]], List[str]]] = None) -> dict: + unpriced: Optional[Callable[[List[str]], List[str]]] = None, + set_entries: Optional[Dict[str, dict]] = None, suite_mark: Optional[dict] = None) -> dict: """{errors, notes, review, jobs, confirm, script, parts, model} for one recipe; errors name the step that edits what is wrong. And ``shards``: one per machine of *Where*, each @@ -524,8 +550,18 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, the run sends it as. ``reasoning``: each model field's level (``{model|simulator|judge: level}``), compiled into ``--reasoning`` the same way, for each job whose agent or benchmark sets none of its own; - ``own_reasoning`` says, by field, what does when every job's does.""" + ``own_reasoning`` says, by field, what does when every job's does. + + A suite's recipe (``runner.suites``) is compiled into its runs (``_suite``). + ``set_entries``: by name, a task set as it will be made (a suite's, at + Run), read in place of its file. ``suite``, in a suite's run's recipe: + {key, version, label, tasks, digest, set_hash}, compiled into ``--suite`` and, beside + ``--set``, ``--set-hash``.""" d = defs or _all() + suite = suites.find(str(recipe.get("benchmark") or "")) + if suite: + return _suite(recipe, suite, d, docker_unusable=docker_unusable, boat_unusable=boat_unusable, + boat_size_problem=boat_size_problem, unpriced=unpriced) errors, notes = [], [] # each problem once; shown: the step already says it elsewhere, so only Review lists it; field: the input it is about; unset: nothing is # chosen yet, which the Model step does not say before its field is used @@ -575,10 +611,13 @@ def add(step, message, shown=False, field=None, unset=False): add("dataset", f"Task set {ref}: {e}.") continue try: - if not os.path.isfile(sets.path_of(b["key"], set_name)): + if set_name in (set_entries or {}): + entry = set_entries[set_name] + elif 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) + else: + entry = sets.load(b["key"], set_name) except sets.Refused as e: add("dataset", sets.plain(e, b["key"], set_name)) continue @@ -773,6 +812,9 @@ def add(step, message, shown=False, field=None, unset=False): why = providers.embedding_problem(m, recipe.get("provider") or "openai") if why: add("model", why) + for p in picks: + if p["o"].get("backends") and backend not in p["o"]["backends"]: + add("where", f"{p['o']['label']} runs on the {' or '.join(p['o']['backends'])} backend alone: choose it.") agents_local = [p["o"]["label"] for p in picks if side == "agent" and not p["control"] and not p.get("setup") and backend == "local"] if agents_local and recipe.get("unsandboxed") is not True: add("where", f"{', '.join(agents_local)} would run as you, not sandboxed: tick Run it as me" @@ -1133,11 +1175,15 @@ def launch_of(d: dict, p: dict) -> str: def job_of(d: dict, p: dict, index: int) -> str: return f"{launch_of(d, p)}-shard-{index}of{of}" if of > 1 else launch_of(d, p) + in_suite = suite_mark or {} # a suite's own compile alone marks a run (``_suite``): a recipe's ``suite`` field is never read + 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"], *(["--set", set_of[d["id"]]["name"]] if d["id"] in set_of else []), + *(["--set-hash", str(in_suite["set_hash"])] if d["id"] in set_of and in_suite.get("set_hash") else []), + *(["--suite", in_suite["mark"]] if in_suite.get("mark") else []), *(["--limit", str(limit)] if isinstance(limit, int) else []), *(["--start-with", start_of[d["id"]]["value"]] if d["id"] in start_of else []), "-j", str(conc), *[w for k, v in options_for_pick(d, p).items() for w in ("--bench-option", f"{k}={v}")], @@ -1162,6 +1208,10 @@ def command_for(d: dict, p: dict, index: int) -> str: *limits.cli_words(limits.of(targets[index - 1])), *[w for m_, slugs in pinned(d, p).items() for w in ("--served-by", f"{m_}={','.join(slugs)}")], *[w for m_, v in reasoned(d, p).items() for w in ("--reasoning", f"{m_}={v}")], "--from-run"] + if in_suite: # what the run is given, as Review showed it: its command is held to it (cli, --suite) + out["bound"] = {"benchmark": definitions.ref_of(b), "other": o["_ref"], "model": m or "", "dataset": d["id"], + "limit": limit if isinstance(limit, int) else None, "backend": backend, + "max_usd": float(f"{share:.6f}") if share and spends(p) else None} return " ".join(shlex.quote(w) for w in words) + ' --jobs "${NULLIUS_JOBS:-jobs_standard}"' def script_for(d: dict, p: dict, command: str, index: int) -> str: @@ -1339,6 +1389,201 @@ def row(p: dict) -> list: return out +# what a suite's recipe leaves to each member: its datasets and tasks are the suite's, its options its own +_MEMBERS_OWN = ("dataset", "datasets", "task_sets", "start_with", "bench_options", "limit", "other", "others", "model_choice", + "judge_model", "simulator_model", "max_usd", "backend", "suite", "only", "rest_of") + + +def _suite(recipe: dict, s: dict, d: Dict[str, List[dict]], **asks) -> dict: + """``compile`` for a suite (``runner.suites``): its members are its datasets (``datasets``: the member ids, all + when none is named). Nothing is joined: ``runs`` lists an ordinary recipe per member and participant - each + check a member declares, then each agent, or once the procedure of a member that takes none - compiled as any + recipe of that benchmark at its pin, on the suite's task set, with its own keys, backend and job + (``runs[i]["out"]``). They run on this machine one after the other, a failed one never stopping the next + (``execution.Plan.after``). Nothing is written: the task sets are read as they will be made at Run + (``suites.freeze``), each run bound to its list's hash. + + An agent runs when it fits every member chosen that takes one (``suites.plan``); else an error names the + members it fails, to untick. ``max_usd`` is the suite's one ceiling, shared by task count between the runs + that pay (``suites.shares``), 0 or empty for none; a model without a price is said once. ``suite``: its key, + version, label, tasks chosen, workspace and the digest of what was compiled (``suites.digest``). + ``hosts``: what each member needs of the machine.""" + errors, notes, review = [], [], [] + out = {"errors": errors, "notes": notes, "review": review, "jobs": [], "confirm": "", "script": "", "parts": [], "model": "", + "served_models": {}, "own_reasoning": {}, "roles": {}, "provider": "", "runs": []} + + def add(step, message, **more): + if not any(e["step"] == STEP[step] and e["message"] == message for e in errors): + errors.append({"step": STEP[step], "message": message, **more}) + name, refs = str(recipe.get("name") or ""), [r for r in chosen_of(recipe)] + ids = [m["id"] for m in s["members"]] + wanted = recipe.get("datasets") if isinstance(recipe.get("datasets"), list) else [] + if not wanted or recipe.get("dataset"): # never every member by default: a launch names what it takes + add("dataset", f"Choose the members of {s['label']} to run.") + if any(x not in ids for x in wanted): + add("dataset", f"Choose members of {s['label']}" + f" ({', '.join(str(x) for x in wanted if x not in ids)} is not one).") + if any(r in definitions.SETUPS for r in refs): + add("agent", f"Choose an agent for {s['label']}: a member that takes none runs its own procedure.") + if not refs: + add("agent", f"Choose an agent for {s['label']}, or a check.") + if recipe.get("simulator_model"): + add("model", "Each member keeps its own user simulator: leave its model empty.") + if where_of(recipe.get("where", "local"))[0] != ["local"]: + add("where", "A suite runs on this machine.") + cap = recipe.get("max_usd") + if cap in ("", None, 0): # zero: no ceiling + cap = None + elif isinstance(cap, bool) or not isinstance(cap, (int, float)) or not 0 < cap < float("inf"): + add("limits", "The spending cap is an amount in USD, or empty or 0 for none.") + cap = None + asked_backend = definitions.names.backend(recipe.get("backend") or "local") + chosen = [x for x in wanted if x in ids] + try: + p = suites.plan(s, d, [r for r in refs if r not in definitions.SETUPS], chosen=chosen, + model=str(recipe.get("model") or "").strip(), provider=str(recipe.get("provider") or ""), backend=asked_backend) + entries = suites.freeze(s, d["benchmark"], chosen, save=False) + except suites.Refused as e: + add("benchmark", f"{e}.") + p, entries = {"rows": [], "agents": [], "unfit": {}}, {} + rows = p["rows"] + labels = {x: definitions.title(o) for x in refs if (o := definitions.find(d["agent"] + d["module"], x))} + kinds = {f: [r["bench"]["label"] for r in rows if not r["setup"] and r["bench"]["family"] == f] for f in ("agent", "module")} + mixed = bool(kinds["agent"] and kinds["module"]) + if mixed: # no participant is both: said once, not as every agent's misfit + add("dataset", f"{', '.join(kinds['agent'])} take{'s' if len(kinds['agent']) == 1 else ''} an agent and {', '.join(kinds['module'])} " + f"take{'s' if len(kinds['module']) == 1 else ''} a Module: untick one kind, they run in launches of their own.") + for r, failed in ({} if mixed else p["unfit"]).items(): + add("agent", f"{labels.get(r, r)} cannot run {'; '.join(f'{label} ({why})' for label, why in failed)}: " + f"untick {'it' if len(failed) == 1 else 'them'} on the Dataset step, or choose another agent.") + for r in rows: + if r["why"]: + add("dataset", f"{r['bench']['label']} cannot run its own procedure: {r['why']}: untick it.") + base = {k: v for k, v in recipe.items() if k not in _MEMBERS_OWN} + several = {b for b in {m["benchmark"] for m in s["members"]} if sum(1 for m in s["members"] if m["benchmark"] == b) > 1} + runs = [] + for r in rows: + b = r["bench"] + who = r["controls"] + ([r["setup"]] if r["setup"] and p["agents"] and not r["why"] else [] if r["setup"] else p["agents"]) + # one backend for every agent of a member, so they work its tasks alike: the one an agent needs, when one does + needed = list(dict.fromkeys(x for x in (r["backend"].get(a) for a in p["agents"]) if x and x != (r["settings"].get("backend") or asked_backend))) + if len(needed) > 1 and not r["setup"]: + add("agent", f"The agents chosen need different backends for {b['label']} ({', '.join(needed)}): choose agents of one.") + for m in r["members"]: + for x in who: + o = definitions.find(d["agent"] + d["module"], x) if x not in definitions.CONTROLS + definitions.SETUPS else None + backend = (needed[0] if needed and o else suites.backend_for(r["settings"], o, asked_backend)[0]) if x not in definitions.SETUPS \ + else r["settings"].get("backend") or asked_backend + if backend == "boat" and definitions.boots_vms(b): + add("where", f"{b['label']} on Boat runs each task whole in a VM, which takes no selection of tasks yet: untick it, or choose another backend.") + sub = dict(base, benchmark=b["_ref"], datasets=[m["dataset"]], task_sets={m["dataset"]: suites.set_name(s)}, + name="-".join([name, b["key"]] + ([m["dataset"]] if b["key"] in several else []) + [definitions.job_word(o) if o else x]), + others=["original" if x == r["setup"] else x], backend=backend, + model_choice="paper" if x == "original" == r["setup"] and "model" in (b.get("setups") or {}) else "any", + **({"bench_options": r["settings"]["bench_options"]} if r["settings"].get("bench_options") else {}), + # each member keeps its official judge; one whose judge is retired takes the recipe's + **({"judge_model": recipe.get("judge_model")} if ((b.get("score") or {}).get("judge") or {}).get("retired") else {})) + runs.append({"member": m["id"], "benchmark": b["key"], "who": x, "tasks": len(m["units"]), "units": m["units"], + "control": x in definitions.CONTROLS, "recipe": sub, "backend": backend, "pin": suites.pin(b, o), + "pins": {"benchmark": f"{b['key']}@{b.get('_version') or ''}", **({"participant": o["_ref"]} if o else {})}}) + # "Run the rest" of a launch: these runs alone, the cap - what is left of the launch's - shared between them + only = recipe.get("only") + kept = (lambda run: True) if not isinstance(only, list) else (lambda run: [run["member"], run["who"]] in only) + runs = [run for run in runs if kept(run)] + mark = suites.digest(s, [dict(run, recipe=dict(run["recipe"], max_usd=cap)) for run in runs]) + selected = suites.tasks(s, [m for r in rows for m in r["members"]]) + info = {"key": s["key"], "version": s["version"], "label": s["label"], "hash": s["hash"], "selected": selected, + "tasks": suites.tasks(s, [m for r in rows for m in r["members"] if any(run["member"] == m["id"] and kept(run) for run in runs)]), + "workspace": suites.workspace(s), "digest": mark} + # a model without a price is one problem of the suite's, not one of each run's + missing = [] + + ask_prices = asks.get("unpriced") + + def unpriced_once(models): + missing.extend(m for m in ask_prices(models) if m not in missing) + return [] + asks = dict(asks, unpriced=unpriced_once if ask_prices else None) + + def one(run, share=None): + b = run["benchmark"] + said = dict({k: info[k] for k in ("key", "version", "label", "tasks", "digest", "hash")}, member=run["member"], who=run["who"], + set_hash=sets.latest(entries[b])["hash"], pins=run["pins"], mark=suites.mark(s, mark, run["pin"])) + sub = dict(run["recipe"], suite=said, **({"max_usd": share} if share else {})) + run.update(recipe=sub, out=compile(sub, d, set_entries={suites.set_name(s): entries[b]}, suite_mark=said, **asks), name=sub["name"], max_usd=share) + said["bound"] = run["out"].get("bound") # kept with the run's plan, in its recipe + # a check pays when its member's judge does: known once compiled; an agent or a procedure always pays + for run in runs: + if run["control"] or cap is None: + one(run) + if cap is not None: + pays = [not run["control"] or not run["out"].get("keyless", True) for run in runs] + for run, share in zip(runs, suites.shares(cap, [(run["tasks"], pay) for run, pay in zip(runs, pays)])): + if share == 0: + add("limits", f"The spending cap is too small to share: {run['recipe']['name']} would get nothing of it.") + elif share: + one(run, share) + for run in runs: + for e in run.get("out", {}).get("errors", ()): + add(next(k for k, v in STEP.items() if v == e["step"]), e["message"], **{k: v for k, v in e.items() if k not in ("step", "message")}) + if missing: + add("limits", f"A spending cap needs a price for {', '.join(missing)}: update the price list in Settings, or set a price there.") + # a licence a member's environments may need and the store does not hold: asked for as its tasks start, not before + for key in dict.fromkeys(run["benchmark"] for run in runs): + version = next(r["bench"].get("_version") or "" for r in rows if r["bench"]["key"] == key) + lacking = sorted({n["name"] for e in licences_of(key, version) for n in e["needs"] if not (n.get("status") or {}).get("set")}) + if lacking: + notes.append(f"{next(r['bench']['label'] for r in rows if r['bench']['key'] == key)} may need {', '.join(lacking)}, not set: " + "it is asked for as its tasks start, after the runs before it.") + count = lambda n: f"{n} task{'' if n == 1 else 's'}" + review += [[STEP["benchmark"], "Suite", f"{s['label']} {s['version']} · {len({r['bench']['key'] for r in rows})} benchmarks · {count(info['tasks'])}"], + [STEP["runner"], "Runner", "Nullius"]] + for r in rows: + b = r["bench"] + mine = [run for run in runs if run["benchmark"] == b["key"]] + # the member's own judge and user simulator, as its recipe's Model row says them + roles = list(dict.fromkeys(x for run in mine for row in run.get("out", {}).get("review", ()) if row[1] == "Model" + for x in row[2].split(" · ") if x.startswith(("judge ", "user simulator ")))) + said = lambda run: "its own procedure" if run["who"] == r["setup"] else definitions.CONTROL_LABEL[run["who"]] if run["control"] else labels.get(run["who"], run["who"]) + # a backend not every run of the member gets is said with whose it is (an agent's own, ``backends``) + on = [x + " backend" + ("" if all(run["backend"] == x for run in mine) else " for " + ", ".join(dict.fromkeys(said(run) for run in mine if run["backend"] == x))) + for x in dict.fromkeys(run["backend"] for run in mine if run["backend"] != "local")] + share = sum(run.get("max_usd") or 0 for run in mine) + review.append([STEP["dataset"], b["label"], " · ".join(filter(None, [ + sets.version_label(b, b.get("_version") or "") or r["members"][0]["version"][:7], + ", ".join(m["dataset"] for m in r["members"]) if len(b["datasets"]) > 1 else "", + count(r["tasks"]), ", ".join(dict.fromkeys(said(run) for run in mine)) or ("not run: it declares none of the checks chosen" if runs else ""), *roles, + *on, f"cap ${ledger.usd(share)}" if share else ""]))]) + model_row = next((row for run in runs for row in run.get("out", {}).get("review", ()) if row[1] == "Model" and not run["control"]), None) + review += [[STEP["model"], "Model", " · ".join(model_row[2].split(" · ")[:2])]] if model_row else [] + if rows and not runs and not errors: + add("agent", f"Nothing chosen runs a member of {s['label']}.") + if runs: + review.append([STEP["limits"], "Scope", (f"{info['tasks']} of {count(selected)}" if info["tasks"] != selected else count(selected)) + + f" · {len(runs)} run{'' if len(runs) == 1 else 's'}, one after the other"]) + if cap is not None: + review.append([STEP["limits"], "Spending cap", f"${ledger.usd(cap)} in all, shared by task count"]) + review.append([STEP["where"], "Where", "this machine"]) + out["suite"] = info + if errors or not runs: + return out + compiled = [run["out"] for run in runs] + for run in runs: + for j in run["out"]["jobs"]: + j["launch"] = name # its runs' records join one launch on the Runs page (runs.launches) + notes += [n for n in run["out"]["notes"] if n not in notes] + out["roles"].update(run["out"]["roles"]) + for role, m in run["out"]["served_models"].items(): + out["served_models"].setdefault(role, m) if m else None + out.update(runs=runs, jobs=[j for one_ in compiled for j in one_["jobs"]], + script="\n".join(sh["command"] for one_ in compiled for sh in one_["shards"]), + docker=any(one_["docker"] for one_ in compiled), keyless=all(one_["keyless"] for one_ in compiled), + model=next((one_["model"] for one_ in compiled if one_["model"]), ""), + provider=next((one_["provider"] for one_ in compiled if not one_["keyless"]), compiled[0]["provider"]), + hosts=[one_["host"] for one_ in compiled if one_["host"]["needs"]], host={"benchmark": "", "needs": [], "check": [], "install": []}, + licences={}, shards=[{"where": "local", "index": 1, "of": 1, "name": name}]) + return out + + def where_of(where) -> tuple: """*Where* as a list of machines - ``local`` or a host's entry - and why it cannot be, or "": a word or a list, each machine once. Whether a host diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index f256a6208..3440ed8d4 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -606,7 +606,7 @@ def job_uuid(job_dir: str, *, benchmark: str, plugged: str, model: str, dataset: def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str, provider: str, dataset: str, units: List[str], concurrency: int, granted: bool, judge: str = "", backend: str = "local", image: str = "", boat_size: str = "", - options: Optional[dict] = None, launch: str = "", shard: Optional[dict] = None, repeat: int = 1, + options: Optional[dict] = None, launch: str = "", suite: Optional[dict] = None, shard: Optional[dict] = None, repeat: int = 1, retries: int = 0, bench_options: Optional[dict] = None, simulator: str = "", prices: Optional[dict] = None, units_file: Optional[dict] = None, task_set: Optional[dict] = None, start_with: Optional[dict] = None, @@ -618,7 +618,9 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str container (``backend``, ``image``) it is not. ``standard.options`` holds every option's value, the defaults included, so two runs read side by side say what differed. ``launch`` and ``shard``: a shard of a launch run over - several machines (``shard``), which ``merge`` reads back. ``units_file``: + several machines (``shard``), which ``merge`` reads back. ``suite``: the + suite launch the run is one of: its key, version, manifest digest, hash, pin and members + (``run --suite``), said only for such a run. ``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. ``task_set``: the task set a run's units came from (``sets.record``): its id, name, revision, @@ -658,7 +660,7 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str **({"judge": judge} if judge else {}), **{f"{r}_provider": p for r, p in sorted((role_providers or {}).items())}, **({"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 {}), + **({"launch": launch} if launch else {}), **({"suite": suite} if suite else {}), **({"shard": shard} if shard else {}), **({"units_file": units_file} if units_file else {}), **({"task_set": task_set} if task_set else {}), **({"start_with": start_with} if start_with else {}), diff --git a/app/nullius/standard/runner/rerun.py b/app/nullius/standard/runner/rerun.py index 6822f87b1..182f5b163 100644 --- a/app/nullius/standard/runner/rerun.py +++ b/app/nullius/standard/runner/rerun.py @@ -230,6 +230,19 @@ def _spent(job_dir: str, res: dict, unknown: Optional[List[str]] = None) -> floa return sum(c for c in (_cost(merge._read(os.path.join(t, "result.json"))) for t in tries) if c is not None) + extra +def spent(job_dir: str) -> Optional[float]: + """What the job has spent, every run counted (:func:`_spent`); for one with no result yet, what its first + run's ledger holds, 0 when it began no unit. None when that cannot be told.""" + res, unknown = merge._read(os.path.join(job_dir, "result.json")), [] + if res: + got = _spent(job_dir, res, unknown) + else: + got = _ledger_spent(_ledger_path(job_dir, 0), None, unknown) + if got is None and not merge._trials(job_dir): + got = 0.0 + return None if unknown else got + + def budget(job_dir: str, res: Optional[dict] = None, cap: Optional[float] = None) -> Optional[dict]: """The job's one spending cap as its next run has it: {"max_usd", "spent_usd" (every run), "left_usd", "closed" (nothing left, or the last run stopped at the cap and it has not changed since, or what an earlier run diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index e83da3d2b..ad028426c 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -795,7 +795,7 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas turn_seconds: Optional[int] = None, say: Callable[[str], None] = print, env=os.environ, proving: bool = False, unsandboxed: bool = False, judge_model: Optional[str] = None, backend: str = "local", options: Optional[dict] = None, shard: Optional[tuple] = None, shard_by: str = "id", - launch: Optional[str] = None, repeat: int = 1, retries: Optional[int] = None, + launch: Optional[str] = None, suite: Optional[dict] = None, repeat: int = 1, retries: Optional[int] = None, retry_if: Optional[Callable[[dict], bool]] = None, simulator_model: Optional[str] = None, 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, @@ -823,6 +823,8 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas ``shard``: (I, N), only the units of shard I of N (``shard``), before ``limit``, ``shard_by`` its units' id (by hash) or place (``shard.BY``); ``launch``: the id every shard of one launch records. + ``suite``: the suite launch this run is one of, {key, version, digest} + (``runner.suites``), kept in the job's config. ``units_file``: the units a file lists (:func:`units_file`): only those of the dataset run, in the dataset's order, before ``limit``; an id the dataset does not hold refuses the run before any unit @@ -915,6 +917,8 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas why = boat.unusable(env=env, which=which) if why: raise Refused(f"the Boat backend cannot run here: {why}") + if other.get("backends") and backend not in other["backends"]: + raise Refused(f"{other['label']} runs on the {' or '.join(other['backends'])} backend alone (--backend {other['backends'][0]})") if backend == "local" and other.get("_kind") == "agent" and not unsandboxed: raise Refused(f"{other['label']} would run commands as you: the local backend is not a sandbox. " "Say so explicitly to go on (--unsandboxed), or run it in a container (--backend container).") @@ -1042,6 +1046,10 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas self.cap_dropped = None # why the spending cap asked for is not applied if self.max_usd is not None or self.unit_max_usd is not None: unpriced = [m for m in self.models_called() if m not in self.prices] + if unpriced and prices_unreachable and suite: + # a suite's run holds a share of one ceiling: without it nothing bounds the launch + raise Refused("its share of the suite's spending cap cannot be applied: the price list could not be fetched, and " + + ", ".join(unpriced) + f" {'has' if len(unpriced) == 1 else 'have'} no price. Nothing was called") if unpriced and prices_unreachable: # the price list could not be fetched before the run (``cli run``): no price, no cap, and the user told self.cap_dropped = (f"no spending cap: the price list could not be fetched, and " @@ -1177,6 +1185,7 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas if shard_by not in shards.BY: raise Refused(f"--shard-by {shard_by!r}: one of {', '.join(shards.BY)}") self.shard_by = shard_by + self.suite = suite self.launch = launch or (shards.launch_id(definitions.job_word(bench), definitions.job_word(other), model) if self.shard else None) self.name = name or (f"{stamp}__{definitions.job_word(bench)}__{definitions.job_word(other)}" @@ -1420,7 +1429,7 @@ def _start(self, lck, mine) -> str: granted=self.other["_kind"] == "agent", judge=self.judge_model or "", backend=self.backend, boat_size=self.boat.size if getattr(self, "boat", None) is not None else "", image=self.setup_driver.image if self.setup_driver else self.image, - options=self.options, launch=self.launch or "", bench_options=self.bench_options, + options=self.options, launch=self.launch or "", suite=self.suite, 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, task_set=self.task_set, diff --git a/app/nullius/standard/runner/suites.py b/app/nullius/standard/runner/suites.py index 94491b8f7..d2041904f 100644 --- a/app/nullius/standard/runner/suites.py +++ b/app/nullius/standard/runner/suites.py @@ -209,3 +209,82 @@ def freeze(s: dict, benches: List[dict], chosen: Optional[List[str]] = None, *, except sets.Refused as e: raise Refused(str(e)) return out + + +def backend_for(settings: dict, other: Optional[dict], asked: str = "local") -> Tuple[str, str]: + """(backend, why not) of one run: the suite's for the member's benchmark (``settings``), else the one its agent + needs (``backends``, the first of them when ``asked`` is not one), else ``asked``.""" + fixed, needs = settings.get("backend") or "", list((other or {}).get("backends") or []) + if fixed and needs and fixed not in needs: + return fixed, f"{other['label']} runs on the {' or '.join(needs)} backend alone, and the suite runs this member on {fixed}" + return fixed or (asked if not needs or asked in needs else needs[0]), "" + + +def plan(s: dict, defs: Dict[str, List[dict]], refs: List[str], *, chosen: Optional[List[str]] = None, + model: str = "", provider: str = "", backend: str = "local") -> dict: + """What a run of the suite with the participants ``refs`` (agents, ``nop``, ``oracle``) does: + {rows, agents, unfit}. ``rows``, by benchmark: {bench, members, settings, tasks, setup, why, controls, fit, + backend}. ``setup``: the procedure a member that takes no agent runs with ``model``, once, when an agent is + chosen, and ``why`` it cannot (""); ``controls``: the checks chosen that it declares; ``fit``: by agent, why it + cannot run this member (empty: it can), the backend its run gets (``backend``, by agent) included. + ``agents``: those that fit every member taking one, the only ones that run; ``unfit``: by any other, the + members it fails, [(benchmark label, why)].""" + rows = [] + asked = [r for r in refs if r not in definitions.CONTROLS] + for g in groups(s, defs["benchmark"], chosen): + b, setup, why = g["bench"], g["settings"].get("setup") or "", "" + fit, backends = {}, {} + if setup and asked and model: # no model yet: the recipe's own error + orig = (b.get("setups") or {}).get("original") or {} + o, why_not = definitions.setup(b, setup, definitions.upstream_name(orig, model, provider) if setup == "original" else model, provider) + why = "" if o is not None else why_not + for r in asked if not setup else (): + o = definitions.find(defs["agent" if b["family"] == "agent" else "module"], r) + backends[r], wrong = backend_for(g["settings"], o, backend) + fit[r] = ([f"takes {'an agent' if b['family'] == 'agent' else 'a Module'}"] if o is None else match.fit(b, o)) + ([wrong] if wrong else []) + rows.append(dict(g, tasks=tasks(s, g["members"]), setup=setup, why=why, fit=fit, backend=backends, + controls=[r for r in refs if r in definitions.CONTROLS and definitions.control(b, r)])) + unfit = {r: [(row["bench"]["label"], "; ".join(row["fit"][r])) for row in rows if row["fit"].get(r)] for r in asked} + return {"rows": rows, "agents": [r for r in asked if not unfit[r]], "unfit": {r: w for r, w in unfit.items() if w}} + + +def shares(cap: float, runs: List[Tuple[int, bool]]) -> List[Optional[float]]: + """One ceiling shared between a suite's runs, ``runs`` each (its tasks, whether it pays - a model, or a paid + judge): by task count, rounded down to a millionth so the shares never pass ``cap``; None for a run that pays + nothing, 0.0 for a share too small to hold.""" + total = sum(n for n, pays in runs if pays) + return [math.floor(cap * n / total * 1e6) / 1e6 if pays else None for n, pays in runs] + + +def pin(bench: dict, other: Optional[dict] = None) -> str: + """The sha256 of what a run resolves its benchmark and its participant to: each definition whole at its + version - commit, judge, user simulator, options and limits included - so a run that would resolve another + is told from the one reviewed (``run --suite``). ``other``: the agent or Module, None for a check or the + benchmark's own procedure, which are the benchmark's.""" + whole = lambda d: {k: v for k, v in d.items() if not k.startswith("_") or k == "_version"} if d else None + doc = {"benchmark": whole(bench), "other": whole(other)} + return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode()).hexdigest() + + +def mark(s: dict, digest_: str, pinned: str) -> str: + """A run's suite mark, as its command carries it (``run --suite``): KEY@VERSION:DIGEST:HASH:PIN.""" + return f"{s['key']}@{s['version']}:{digest_}:{s['hash']}:{pinned}" + + +def marked(text: str) -> Optional[dict]: + """``mark`` read back: {key, version, digest, hash, pin}, None when it is not one.""" + ref, *rest = str(text or "").split(":") + key, _, version = ref.partition("@") + if not (key and version and len(rest) == 3 and all(len(x) == 64 and not set(x) - set("0123456789abcdef") for x in rest)): + return None + return {"key": key, "version": version, "digest": rest[0], "hash": rest[1], "pin": rest[2]} + + +def digest(s: dict, runs: List[dict]) -> str: + """The sha256 of what one launch of the suite was reviewed to run (its manifest): the suite's key, version and + hash, and each run - its member, its units, its recipe (the name left out) and what its benchmark and + participant resolve to (``pin``).""" + doc = {"key": s["key"], "version": s["version"], "hash": s["hash"], + "runs": [{"member": r["member"], "units": r["units"], "pin": r["pin"], + "recipe": {k: v for k, v in r["recipe"].items() if k not in ("name", "suite")}} for r in runs]} + return hashlib.sha256(json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest() diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index 98e366898..4d2620b41 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -206,7 +206,7 @@ if (was !== b) { delete r.task_sets; delete r.start_with; } r.benchmark = key; const kept = same ? datasetsOf(r).filter(id => b.datasets.some(d => d.id === id)) : []; - r.datasets = kept.length ? kept : [b.datasets[0].id]; + r.datasets = kept.length ? kept : b.suite ? b.datasets.map(d => d.id) : [b.datasets[0].id]; // a suite: every member delete r.dataset; keepTaskSets(r); keepStartWith(r); diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index df9afffb8..ba719fb8e 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -552,7 +552,7 @@ // A check's chips on the Agent step: its proof on each chosen dataset (the first when none is), never a sum, // since a proof is a dataset's own and datasets can share tasks (GSM8K-Platinum is GSM8K test, cleaned). // Several: one row each, named by its dataset. - const controlChips = (o, b, ids) => { const chosen = b.datasets.filter(x => ids.includes(x.id)), ds = chosen.length ? chosen : b.datasets.slice(0, 1); + const controlChips = (o, b, ids) => { if (b.suite) return ''; const chosen = b.datasets.filter(x => ids.includes(x.id)), ds = chosen.length ? chosen : b.datasets.slice(0, 1); const chip = x => controlChip(((x || {}).controls || []).find(c => c.key === o.key) || {...o, from: o.summary}, true, ds.length > 1 ? x.label : ''); return ds.length > 1 ? `${ds.map(chip).join('')}` : chip(ds[0]); }; const checkChip = (name, proven, failed, says) => { const p = proofOf(proven, failed); if (p.state === 'ok') { p.title = [says, proven.passed, p.title].filter(Boolean).join(' · '); p.text = ''; } @@ -775,7 +775,7 @@ // pressed as the recipe chooses (nullius-pick changes the recipe). const grids = [ {slot: 'nb-bench-grid', store: 'nb-bench-view', url: () => '/new-run/benchmarks?', chosen: rec => [C.benchKey(rec)], after: benchTasks}, - {slot: 'nb-agent-grid', store: 'nb-agent-view', url: rec => '/new-run/agents?' + new URLSearchParams({benchmark: rec.benchmark}) + '&', chosen: rec => C.chosenOf(rec)}, + {slot: 'nb-agent-grid', store: 'nb-agent-view', url: rec => '/new-run/agents?' + new URLSearchParams({benchmark: rec.benchmark, ...((C.standardBench(rec) || {}).suite ? {members: (rec.datasets || []).join(',')} : {})}) + '&', chosen: rec => C.chosenOf(rec)}, ]; grids.forEach(g => { g.view = 'cards'; g.ref = ''; g.node = null; try { g.view = localStorage.getItem(g.store) === 'table' ? 'table' : 'cards'; } catch {} }); const placeGrids = () => grids.forEach(placeGrid); @@ -835,6 +835,7 @@ placeGrid(g); } function modelChoiceCards(rec) { + if ((C.standardBench(rec) || {}).suite) return ''; // each member keeps its own judge and user simulator const hasPaper = C.paperOffered(rec), on = rec.model_choice || 'any'; return `
${tile({attr:'model-choice',key:'paper',title:'Like the paper',on:on==='paper',disabled:!hasPaper,why:'Paper models unavailable',note:hasPaper?'':'Paper models unavailable'})}` + (C.leaderboard(rec) ? tile({attr:'model-choice',key:'leaderboard',title:'Like the leaderboard',on:on==='leaderboard'}) : '') @@ -851,6 +852,9 @@ 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 + // a suite: its members are its datasets, each with the tasks the suite fixed, its options and proofs its benchmark's own + if (b.suite) return `

Which members?

` + + `
${shown.map(x => tile({attr: 'std-dataset', key: x.id, on: on(x), title: x.label, meta: x.units + ' ' + (x.units === 1 ? du.noun : du.nouns)})).join('')}
`; return `

Which datasets?

` + `
${shown.map(x => tile({attr: 'std-dataset', key: x.id, on: on(x), title: x.label, tip: x.summary || '', meta: x.units ? x.units + ' ' + du.nouns : '', foot: datasetChecks(b, x)})).join('')}
` @@ -915,8 +919,8 @@ 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, max: most, placeholder: all, - hint: 'Empty: all' + (most ? ' ' + most : '') + per + '. Else the first ones, in order.'}) + + (b.suite ? '' : 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.'}) @@ -1377,7 +1381,7 @@ if(C.providerBlocker(rec))return; // the button is disabled then; /run refuses the same if(!(prereq.out&&prereq.out.ready))return; // Run waits for the prerequisites // A runner of its own sends its choices only: /run compiles them again from the definition file. - if(C.isStandard(rec)){body={name:rec.name,where:rec.where,recipe:rec};ask=runnerOut&&runnerOut.confirm;} + if(C.isStandard(rec)){body={name:rec.name,where:rec.where,recipe:rec,...(runnerOut&&runnerOut.suite?{reviewed:runnerOut.suite.digest}:{})};ask=runnerOut&&runnerOut.confirm;} // a suite: what Review showed, by its digest else{const plan=C.runnable(rec); if(plan.errors.length)return; body={name:rec.name,script:plan.script,where:rec.where,tasks:plan.tasks,model:plan.model,jobs:plan.jobs,parts:plan.parts,recipe:rec}; ask=plan.confirm;} // the recipe travels with the run if(ask&&!window.confirm(ask)){say('Not started.');return;} const b=$('#nb-run'); b.disabled=true; say('starting…'); diff --git a/app/static/runs/launches.css b/app/static/runs/launches.css index 9091f1774..ea7be0644 100644 --- a/app/static/runs/launches.css +++ b/app/static/runs/launches.css @@ -46,7 +46,7 @@ .la-state.finished i { background: var(--resolved); } .la-state.running i, .la-state.preparing i { background: var(--resolved); animation: la-beat 2s infinite; } .la-state.paused i, .la-state.stopping i { background: var(--patch_failed_tests); } -.la-state.stopped i, .la-state.failed i, .la-state.refused i, .la-state.not-run i { background: var(--bad); } +.la-state.stopped i, .la-state.failed i, .la-state.refused i, .la-state.not-run i, .la-state.cancelled i { background: var(--bad); } .la-state.not-run, .launch-paused { color: var(--bad); } @keyframes la-beat { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--resolved) 55%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } } .la-rate { display: grid; grid-template-columns: 3.2em minmax(90px, 1fr); gap: 10px; align-items: center; min-width: 160px; } diff --git a/app/templates/builder/benchmarks.html b/app/templates/builder/benchmarks.html index 7e84a600e..cb278fb26 100644 --- a/app/templates/builder/benchmarks.html +++ b/app/templates/builder/benchmarks.html @@ -1,11 +1,17 @@ {#- The builder's Benchmark step grid (web/builder.py, new_run_benchmarks): the Benchmarks page's cards (web/catalogue.py, benchmark_cards) as single-choice pick cards of the card toolkit (_cards.html), or its rows (`layout` 'table'), loaded by command-builder.js. -#} -{% from '_cards.html' import cards %} +{% from '_cards.html' import cards, grid %} {#- Category, what it evaluates and origin use the catalogue's filter menus. -#} {% set cols = [dict(key='icon', label='Mark', card='icon', table=false, class='bench-mark'), dict(key='title', label='Name', card='title', width='expand'), dict(key='evaluates', label='Evaluates', card='badge', class='std-tag', filter='dropdown', filter_icon='target'), dict(key='tasks', label='Tasks', card='stat', type='num'), dict(key='category', label='Category', card='tag', class='cat-tag', filter='dropdown'), dict(key='origin', label='Origin', class='origin-tag', filter='dropdown', filter_icon='origin'), dict(key='runs', label='Runner', class='run-tag'), dict(key='domain', label='Domain', off=true)] %} -{{ cards('nb-benchmarks', cols, items, search='Search benchmarks', choices=choices, sort=['title', 'tasks'], empty='No benchmark matches.', noun='benchmarks', layout=layout, default='cards') }} +{% set sort = ['title', 'tasks'] %} +{% call cards('nb-benchmarks', cols, items, search='Search benchmarks', choices=choices, sort=sort, empty='No benchmark matches.', noun='benchmarks', layout=layout, default='cards') %} +{%- set suites = items|selectattr('suite', 'defined')|list %} +{% if suites %}

Suites

{{ grid(cols, suites, every=items, choices=choices, sort=sort) }}
+

Benchmarks

{{ grid(cols, items|rejectattr('suite', 'defined')|list, every=items, choices=choices, sort=sort) }}
+{% else %}{{ grid(cols, items, every=items, choices=choices, sort=sort) }}{% endif %} +{% endcall %} diff --git a/app/templates/catalogue/suite.html b/app/templates/catalogue/suite.html index 077da729b..6b9100972 100644 --- a/app/templates/catalogue/suite.html +++ b/app/templates/catalogue/suite.html @@ -9,7 +9,8 @@ {#- A suite's page (web/catalogue.py, suite_page): its members by benchmark, each at its pin. -#}
{% set tags %}Suite {{ s.members|map(attribute='benchmark')|unique|list|length }} benchmarks · {{ s.members|map(attribute='units')|map('length')|sum }} tasks{% endset %} - {{ page_head(s.label, sub=tags) }} + {% set actions %}Build a run {% endset %} + {{ page_head(s.label, sub=tags, actions=actions) }}

{{ s.summary }}

{% if s.versions|length > 1 %}
@@ -125,6 +125,7 @@ // The answer names the state (`stopping`) at once; the run's own thread // finishes the stop. A refused stop puts the button back and says why. document.getElementById('execution-stop')?.addEventListener('click', async e => { + if (e.target.dataset.ask && !confirm(e.target.dataset.ask)) return; e.target.disabled = true; try { const r = await nulliusFetch(box.dataset.stop, {method: 'POST', headers: {'X-CSRF-Token': box.dataset.csrf}}); diff --git a/app/templates/runs/index.html b/app/templates/runs/index.html index 7de894acd..a96bdffbf 100644 --- a/app/templates/runs/index.html +++ b/app/templates/runs/index.html @@ -56,7 +56,7 @@ {%- if kind == 'control' %} — {%- else %} - {% if j and j.scored_only %}—{% elif j and part == 'fold' %}{{ j.n_resolved }}/{{ j.trials|length }}{% if r.not_run %}{{ r.not_run }} of {{ r.total }} not run{% endif %}{% elif j and j.start_with %}{{ j.n_resolved }}/{{ j.trials|length }}{% elif j %}{{ j.n_resolved }}/{{ j.n_planned or j.trials|length }}{% else %}0{% if g.n_tasks %}/{{ g.n_tasks }}{% endif %}{% endif %} + {% if j and j.scored_only %}—{% elif j and part == 'fold' %}{{ j.n_resolved }}/{{ j.trials|length }}{% if r.not_run %}{{ r.not_run }} of {{ r.total }} not run{% endif %}{% elif j and j.start_with %}{{ j.n_resolved }}/{{ j.trials|length }}{% elif j %}{{ j.n_resolved }}/{{ j.n_planned or j.trials|length }}{% else %}0{% if g.n_tasks and not g.suite %}/{{ g.n_tasks }}{% endif %}{% endif %} {%- if j and j.start_with and part != 'fold' and j.n_tasks_run < j.n_tasks %}{{ j.n_tasks_run }} of {{ j.n_tasks }} tasks run{% endif %} {%- endif %} {% if j and (j.total_input_tokens or j.total_output_tokens) %}{{ (j.total_input_tokens + j.total_output_tokens)|tokens(j.kind) }}{% else %}—{% endif %} @@ -112,8 +112,8 @@ {% set by_runner = g.agents|map(attribute='job')|select|map(attribute='runner')|select|first %} {% set words = g.agents|map(attribute='job')|select|map(attribute='runner_items')|select|first %}
-

{{ g.dataset_title if L.dataset else (L.name or g.dataset_title) }}{% if g.n_tasks %} · {{ g.n_tasks }} {% if words %}{{ words[0] if g.n_tasks == 1 else words[1] }}{% else %}task{{ '' if g.n_tasks == 1 else 's' }}{% endif %}{% endif %}

- {{ L.title }} +

{{ g.suite or (g.dataset_title if L.dataset else (L.name or g.dataset_title)) }}{% if g.n_tasks %} · {{ g.n_tasks }} {% if words and not g.suite %}{{ words[0] if g.n_tasks == 1 else words[1] }}{% else %}task{{ '' if g.n_tasks == 1 else 's' }}{% endif %}{% endif %}

+ {{ L.title }} {% if L.started %}{{ L.started|dt }} · {% endif %}{{ g.n_runs }} run{{ '' if g.n_runs == 1 else 's' }}{% if g.n_checks %} · {{ g.n_checks }} check{{ '' if g.n_checks == 1 else 's' }}{% endif %}
{# a runner's launch without controls is checked by its own floor and ceiling, which are arms in its table #} @@ -140,6 +140,8 @@

{{ g.dataset_title if L.dataset else (L.name or g.dataset_title) }}{% if g.n {{ g.summary or 'checks only' }} {% if g.paused %}Paused after a failure: continue or stop{% endif %} + {% if g.queue and g.queue.open %}
+ {%- elif g.queue and g.queue.rest %}
{% endif %} {% if g.recipe %}Recipe{% endif %} {% if g.compare|length >= 2 %}Compare {{ g.compare|length }} {% elif g.agents %}Compare needs two finished agents{% endif %} diff --git a/app/tests/test_standard_run.py b/app/tests/test_standard_run.py index 8a58e2a6c..8f91610f3 100644 --- a/app/tests/test_standard_run.py +++ b/app/tests/test_standard_run.py @@ -1070,6 +1070,10 @@ def test_a_capped_run_whose_price_list_could_not_be_fetched_runs_uncapped_and_sa with open(os.path.join(job_dir, "progress.jsonl")) as f: units = [e for e in map(json.loads, f) if e.get("stage") == "units" and e.get("state") == "start"] self.assertEqual(units[0]["detail"], "no spending cap: the price list could not be fetched, and m-1 has no price") + # a suite's run holds a share of one ceiling: refused before any call, never run without it + with self.assertRaisesRegex(run.Refused, "its share of the suite's spending cap cannot be applied.*m-1 has no price. Nothing was called"): + run.run(b, o, name="suite-run", prices_unreachable="could not fetch the price list: offline", suite={"key": "demo"}, **kw) + self.assertFalse([n for n in os.listdir(os.path.join(self.tmp, "suite-run")) if "__u" in n] if os.path.isdir(os.path.join(self.tmp, "suite-run")) else []) with self.assertRaises(run.Refused) as e: # the list reached, the model not in it run.run(b, o, name="capped", say=lambda s: None, **kw) self.assertIn("a spending cap needs a price for every model the run calls, and there is none for m-1", str(e.exception)) diff --git a/app/tests/test_suites.py b/app/tests/test_suites.py index 8cfdf48b1..0a2abc8f0 100644 --- a/app/tests/test_suites.py +++ b/app/tests/test_suites.py @@ -145,5 +145,246 @@ def test_a_name_that_holds_another_list_is_refused_previewed_or_not(self): suites.freeze(self.suite(), self.defs["benchmark"], save=save) +class TheFit(Scratch): + def test_an_agent_runs_when_it_fits_every_member_chosen_and_the_others_keep_why_by_member(self): + s = self.suite(TASKS[:4] + [{"benchmark": "fakejudged", "version": PIN, "dataset": "all", "task": "good"}]) + p = suites.plan(s, self.defs, ["fake", "lesser", "nop"]) + self.assertEqual(p["agents"], []) # fakememo takes a Module: no agent fits every member + self.assertEqual([label for label, _ in p["unfit"]["fake"]], ["Fake memory bench"]) + self.assertEqual([label for label, _ in p["unfit"]["lesser"]], ["Fake bench", "Fake memory bench", "Fake judged"]) + p = suites.plan(s, self.defs, ["fake", "lesser", "nop"], chosen=["fakebench.all", "fakejudged.all"]) # the member unticked + self.assertEqual((p["agents"], list(p["unfit"])), (["fake"], ["lesser"])) + self.assertEqual([r["fit"]["fake"] for r in p["rows"]], [[], []]) + self.assertIn("needs agent.task/v1", p["rows"][0]["fit"]["lesser"][0]) + self.assertEqual([r["controls"] for r in p["rows"]], [["nop"], ["nop"]]) + + def test_the_backend_an_agent_needs_is_the_one_its_runs_get(self): + s = self.suite(TASKS[:3]) + row, = suites.plan(s, self.defs, ["fake", "boxed"])["rows"] + self.assertEqual((row["backend"], row["fit"]), ({"fake": "local", "boxed": "container"}, {"fake": [], "boxed": []})) + s = self.suite(TASKS[:3], settings={"fakebench": {"backend": "local"}}) # the suite fixes another for the member + p = suites.plan(s, self.defs, ["boxed"]) + self.assertEqual(p["unfit"]["boxed"], [("Fake bench", "Boxed runs on the container backend alone, and the suite runs this member on local")]) + + def test_a_ceiling_is_shared_by_task_count_between_the_runs_that_pay(self): + self.assertEqual(suites.shares(3, [(2, True), (1, True), (5, False)]), [2.0, 1.0, None]) + self.assertEqual(suites.shares(1, [(1, True), (2, True)]), [0.333333, 0.666666]) # never more than the ceiling in all + self.assertEqual(suites.shares(0.000001, [(1, True), (9, True)])[0], 0.0) # too small to hold + + +class TheRecipe(Scratch): + MEMBERS = TASKS[:3] + [{"benchmark": "fakejudged", "version": PIN, "dataset": "all", "task": "good"}] + + def compile(self, **kw): + asks = {k: kw.pop(k) for k in ("unpriced",) if k in kw} + return recipe.compile(self.recipe(**kw), self.defs, **asks) + + def test_each_member_with_each_participant_is_an_ordinary_run_bound_to_its_list(self): + s = self.suite(self.MEMBERS) + out = self.compile(others=["nop", "fake"]) + self.assertEqual(out["errors"], []) + self.assertEqual([r["name"] for r in out["runs"]], + ["demo-run-fakebench-all-nop", "demo-run-fakebench-all-fake", "demo-run-fakebench-more-nop", "demo-run-fakebench-more-fake", + "demo-run-fakejudged-nop", "demo-run-fakejudged-fake"]) + one = out["runs"][3] + mark, set_hash = out["suite"]["digest"], sets.latest(suites.freeze(s, self.defs["benchmark"], save=False)["fakebench"])["hash"] + self.assertEqual(one["out"]["shards"][0]["command"], + f'nullius standard run fakebench fake --model gpt-5-mini --provider openai --dataset more --set demo-2026-12 --set-hash {set_hash} ' + f'--suite demo@2026-12:{mark}:{s["hash"]}:{suites.pin(self.defs["benchmark"][0], self.defs["agent"][0])} -j 1 --name demo-run-fakebench-more-fake --unsandboxed --from-run --jobs "${{NULLIUS_JOBS:-jobs_standard}}"') + self.assertEqual(one["recipe"]["suite"]["bound"], # what its command is held to + {"benchmark": "fakebench", "other": "fake", "model": "gpt-5-mini", "dataset": "more", "limit": None, "backend": "local", "max_usd": None}) + self.assertEqual([len(r["out"]["parts"]) for r in out["runs"]], [1] * 6) # one part each: none ever pauses + self.assertEqual({j["launch"] for j in out["jobs"]}, {"demo-run"}) # one launch on the Runs page + self.assertEqual((out["suite"]["workspace"], out["suite"]["tasks"], out["confirm"]), ("suite-demo-2026-12", 4, "")) + self.assertFalse((self.tmp / "catalogue" / "sets").exists()) # compiled, nothing written + self.assertEqual(self.compile(others=["nop", "fake"], name="another")["suite"]["digest"], mark) # the name is no part of what was reviewed + self.assertNotEqual(self.compile(others=["fake"])["suite"]["digest"], mark) + + def test_a_check_alone_gets_no_key_and_a_judged_member_s_check_its_judge_s(self): + self.suite(self.MEMBERS) + out = self.compile(others=["nop"], model="") + self.assertEqual(out["errors"], []) + self.assertEqual([(r["benchmark"], r["out"]["keyless"]) for r in out["runs"]], [("fakebench", True), ("fakebench", True), ("fakejudged", False)]) + + def test_an_agent_that_fails_a_member_is_refused_with_the_members_to_untick(self): + self.suite() + said, = [e["message"] for e in self.compile(others=["fake"])["errors"]] + self.assertEqual(said, "Fake bench takes an agent and Fake memory bench takes a Module: untick one kind, they run in launches of their own.") + self.assertIn("Choose the members of Demo to run.", [e["message"] for e in self.compile(datasets=[])["errors"]]) # never all by default + self.assertIn("Choose the members of Demo to run.", [e["message"] for e in self.compile(dataset="all")["errors"]]) + out = self.compile(others=["fake", "lesser"], datasets=["fakebench.all", "fakebench.more"]) + self.assertEqual([e["step"] for e in out["errors"]], [recipe.STEP["agent"]]) + self.assertIn("Lesser cannot run Fake bench (needs agent.task/v1", out["errors"][0]["message"]) + self.assertEqual(out["runs"], []) # nothing runs for one agent alone + + def test_an_agent_of_one_backend_alone_gets_it_and_review_says_so(self): + self.suite(TASKS[:3]) + out = self.compile(others=["boxed", "fake"]) + self.assertEqual(out["errors"], []) + self.assertEqual([(r["who"], r["backend"], "--backend container" in r["out"]["shards"][0]["command"]) for r in out["runs"][:2]], + [("boxed", "container", True), ("fake", "container", True)]) # one backend for a member's agents + self.assertTrue(next(r[2] for r in out["review"] if r[1] == "Fake bench").endswith("Boxed, Fake agent · container backend")) + self.assertTrue(out["docker"]) + with mock.patch.object(definitions, "boots_vms", lambda b: True): # Boat would plan such a member by its dataset's count + said = [e["message"] for e in self.compile(others=["fake"], backend="boat")["errors"]] + self.assertIn("Fake bench on Boat runs each task whole in a VM, which takes no selection of tasks yet: untick it, or choose another backend.", said) + ordinary = recipe.compile(self.recipe(benchmark="fakebench", datasets=["all"], others=["boxed"]), self.defs) # and outside a suite + self.assertIn("Boxed runs on the container backend alone: choose it.", [e["message"] for e in ordinary["errors"]]) + + def test_one_ceiling_is_shared_by_task_count_paid_judges_included_and_a_price_is_asked_for_once(self): + self.suite(self.MEMBERS) + asked = [] + out = self.compile(others=["nop", "fake"], max_usd=4, unpriced=lambda models: asked.append(models) or ["gpt-5-mini"]) + self.assertEqual([e["message"] for e in out["errors"]], + ["A spending cap needs a price for gpt-5-mini: update the price list in Settings, or set a price there."]) + self.assertGreater(len(asked), 1) + out = self.compile(others=["nop", "fake"], max_usd=4) + self.assertEqual(out["errors"], []) + # 2 + 1 + 1 tasks of the agent and 1 of the judged member's check: five paying tasks + self.assertEqual([r["max_usd"] for r in out["runs"]], [None, 1.6, None, 0.8, 0.8, 0.8]) + self.assertIn("--max-usd 1.6 ", out["runs"][1]["out"]["shards"][0]["command"]) + self.assertEqual(out["runs"][1]["recipe"]["suite"]["bound"]["max_usd"], 1.6) + # the rest of a launch: what is left of its ceiling, between the runs asked for alone + rest = self.compile(others=["nop", "fake"], max_usd=1.5, only=[["fakebench.more", "fake"], ["fakejudged.all", "fake"]]) + self.assertEqual(([r["name"] for r in rest["runs"]], [r["max_usd"] for r in rest["runs"]]), + (["demo-run-fakebench-more-fake", "demo-run-fakejudged-fake"], [0.75, 0.75])) + self.assertNotIn("--max-usd", out["runs"][0]["out"]["shards"][0]["command"]) + rows = {r[1]: r[2] for r in out["review"]} + self.assertEqual(rows["Spending cap"], "$4.00 in all, shared by task count") + self.assertTrue(rows["Fake bench"].endswith("cap $2.40") and rows["Fake judged"].endswith("cap $1.60"), rows) + + def test_no_ceiling_at_zero_and_one_too_small_to_share_is_refused(self): + self.suite(self.MEMBERS) + out = self.compile(max_usd=0) + self.assertEqual((out["errors"], [r["max_usd"] for r in out["runs"]]), ([], [None] * 3)) + self.assertNotIn("Spending cap", [r[1] for r in out["review"]]) + said = [e["message"] for e in self.compile(max_usd=0.000003)["errors"]] + self.assertEqual(said, ["The spending cap is too small to share: demo-run-fakebench-more-fake would get nothing of it.", + "The spending cap is too small to share: demo-run-fakejudged-fake would get nothing of it."]) + + def test_a_host_a_setup_and_an_unknown_member_are_refused(self): + self.suite() + for kw, step, said in (({"where": "me@bench"}, "where", "A suite runs on this machine."), + ({"others": ["original"]}, "agent", "Choose an agent for Demo: a member that takes none runs its own procedure."), + ({"datasets": ["nope.all"]}, "dataset", "Choose members of Demo (nope.all is not one).")): + with self.subTest(kw=kw): + self.assertIn({"step": recipe.STEP[step], "message": said}, self.compile(**kw)["errors"]) + + def test_the_builder_reads_a_suite_as_a_benchmark_whose_datasets_are_its_members(self): + page = recipe.suite_page(self.suite(), self.defs["benchmark"]) + self.assertEqual([(d["id"], d["label"], d["units"]) for d in page["datasets"]], + [("fakebench.all", "Fake bench · all", 2), ("fakebench.more", "Fake bench · more", 1), ("fakememo.all", "Fake memory bench", 1)]) + self.assertEqual(set(recipe._bench_page(self.defs["benchmark"][0])) - set(page), set()) # every field the builder reads + + +class TheCommand(Scratch): + def said(self, command, **kw): + out = io.StringIO() + with mock.patch.object(cli, "_all", lambda: (self.defs, [])), redirect_stdout(out): + code = command(argparse.Namespace(**{"benchmark": "demo", "dataset": None, "backend": None, **kw})) + return code, out.getvalue().splitlines() + + def test_run_is_refused_with_the_way_to_the_builder_and_nothing_is_written(self): + self.suite() + code, said = self.said(cli.cmd_run, other="fake", model="gpt-5-mini") + self.assertEqual((code, said), (2, ["refused: demo is a suite: run it from the builder (New run), which starts its runs one after the " + "other; nullius standard fit demo says which agents run it"])) + self.assertFalse((self.tmp / "catalogue" / "sets").exists()) + + def test_the_command_as_typed_names_the_builder_and_a_benchmark_still_asks_for_its_participant(self): + self.suite() + out = io.StringIO() + with redirect_stdout(out), mock.patch("sys.stderr", out), mock.patch.object(cli.settings, "load"): + self.assertEqual(cli.main(["run", "demo"]), 2) + self.assertIn("refused: demo is a suite: run it from the builder (New run)", out.getvalue()) + with self.assertRaises(SystemExit) as stopped: + cli.main(["run", "fakebench"]) + self.assertEqual(stopped.exception.code, 2) + self.assertIn("the following arguments are required: other", out.getvalue()) + + def test_fit_says_who_runs_every_member_and_which_members_fail_the_others(self): + self.suite(TASKS[:3]) + code, said = self.said(cli.cmd_fit) + self.assertEqual((code, said[0], said[1], said[-1]), + (0, " ✓ fake: every member", " ✗ lesser: 0 of 1 benchmarks", " ✓ boxed: every member, on the container backend")) + self.assertTrue(said[2].startswith(" Fake bench: needs agent.task/v1"), said) + self.suite() # with a member that takes a Module: none runs every member + self.assertEqual(self.said(cli.cmd_fit)[1][0], " ✗ fake: 1 of 2 benchmarks") + self.assertEqual(self.said(cli.cmd_fit, dataset=["fakebench.all"])[1][0], " ✓ fake: every member") # as the page, by the members taken + self.assertEqual(self.said(cli.cmd_fit, dataset=["nope"]), (2, ["refused: nope is no member of demo: fakebench.all, fakebench.more, fakememo.all"])) + + +class TheMark(Scratch): + """``run --suite``: the mark a suite's launch writes is true of the run, or the run is refused.""" + + def setUp(self): + super().setUp() + self.bench = self.defs["benchmark"][0] + self.s = self.suite(TASKS[:3]) + self.set_hash = sets.latest(suites.freeze(self.s, self.defs["benchmark"])["fakebench"])["hash"] + self.mark = suites.mark(self.s, "d" * 64, suites.pin(self.bench)) + for p in (mock.patch.object(cli, "_bench", lambda key: self.bench), mock.patch.object(cli, "_exit_on_term"), mock.patch.object(cli.settings, "load")): + p.start(); self.addCleanup(p.stop) + self.jobs = self.tmp / "runs" / "demo-run-fakebench-all-nop" / "jobs" + self.jobs.mkdir(parents=True) + self.launched() + + BOUND = {"benchmark": "fakebench", "other": "nop", "model": "", "dataset": "all", "limit": None, "backend": "local", "max_usd": None} + + def launched(self, **plan): + (self.jobs.parent / "plan.json").write_text(json.dumps(dict({"queue": "one-launch", "recipe": {"suite": self.said()}}, **plan))) + + def said(self, **more): + return dict({"mark": self.mark, "bound": self.BOUND, "set_hash": self.set_hash}, **more) + + def go(self, *more, mark=None, hashed=True): + out = io.StringIO() + words = ["run", "fakebench", "nop", "--dataset", "all", "--set", "demo-2026-12", *(["--set-hash", self.set_hash] if hashed else []), + "--suite", mark or self.mark, "--name", "one", "--jobs", str(self.jobs), "--from-run", *more] + with redirect_stdout(out), mock.patch("sys.stderr", out): + code = cli.main(words) + return code, out.getvalue() + + def test_a_run_of_a_suite_s_launch_records_the_suite_its_hash_and_its_member(self): + code, said = self.go() + self.assertEqual(code, 0, said) + with open(self.jobs / "one" / "config.json") as fh: + got = json.load(fh)["standard"]["suite"] + self.assertEqual((got["key"], got["version"], got["hash"], got["digest"], got["members"]), ("demo", "2026-12", self.s["hash"], "d" * 64, ["fakebench.all"])) + + def test_a_mark_no_launch_wrote_or_not_true_of_the_run_is_refused_before_anything_runs(self): + cases = [] + self.launched(queue="") + cases.append((self.go(), "only a suite's own launch marks a run")) + self.launched(recipe={"suite": {"mark": self.mark.replace("d" * 64, "e" * 64)}}) + cases.append((self.go(), "only a suite's own launch marks a run")) + self.launched() + cases.append((self.go(hashed=False), "a suite's run takes its suite's list, --set demo-2026-12 --set-hash")) + cases.append((self.go(mark="demo@2026-12:" + "d" * 64), "KEY@VERSION:DIGEST:HASH:PIN")) + other = suites.mark(dict(self.s, hash="f" * 64), "d" * 64, suites.pin(self.bench)) + self.launched(recipe={"suite": {"mark": other}}) + cases.append((self.go(mark=other), "the suite changed since Review")) + self.launched() + # the plan, the mark and the list's hash kept, the command changed: another member, model, limit, cap + for words in (["--dataset", "more"], ["--model", "gpt-5"], ["--limit", "1"], ["--max-usd", "5"]): + cases.append((self.go(*words), "the run is not the one reviewed")) + self.launched(recipe={"suite": self.said(set_hash="0" * 64)}) # the list changed and its new hash given: not the one reviewed + cases.append((self.go(), "the run is not the one reviewed")) + self.launched(recipe={"suite": {"mark": self.mark}}) # a plan from before runs were bound + cases.append((self.go(), "the run is not the one reviewed")) + self.launched() + self.bench = dict(self.bench, limits={"turn_seconds": 7}) # the default moved while the run waited + cases.append((self.go(), "Fake bench or nop is no longer what was reviewed")) + self.bench = self.defs["benchmark"][0] + self.launched(recipe={"suite": self.said(bound=dict(self.BOUND, backend="boat"))}) + with mock.patch.object(definitions, "boots_vms", lambda b: True): # the path that plans by the dataset's count + cases.append((self.go("--backend", "boat"), "on Boat runs each task whole in a VM, which takes no selection of tasks yet")) + for (code, said), why in cases: + self.assertEqual(code, 2, said) + self.assertIn("refused: --suite: ", said) + self.assertIn(why, said) + self.assertFalse((self.jobs / "one").exists()) + + if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_builder_benchmarks.py b/app/ui_tests/test_builder_benchmarks.py index fe403803a..2a8e003e4 100644 --- a/app/ui_tests/test_builder_benchmarks.py +++ b/app/ui_tests/test_builder_benchmarks.py @@ -29,7 +29,7 @@ def get(self, url): def test_it_lists_the_benchmarks_pages_benchmarks_each_a_single_choice(self): html = self.get("/new-run/benchmarks") cards = {m.group(1): m.group(0) for m in re.finditer(r'
', html, re.S)} - listed = re.findall(r'b.datasets.length>1)){out[b.key]={};" + + "const out={};for(const b of C.standard().benchmarks.filter(b=>b.datasets.length>1&&!b.suite)){out[b.key]={};" + "for(const o of b.controls||[])out[b.key][o.key]=[...controlChips(o,b," + pick + ").matchAll(/title=\"([^\"]*)\">[^<]*<\\/b>(?:([^<]*)<\\/em>)?]*>(?:]*>]*\\/><\\/svg>)? *([^<]*)[m[1],m[3],m[2]||null]);" + "out[b.key].$rows=controlChips((b.controls||[])[0]||{key:'nop'},b," + pick + ").startsWith('');}" + "process.stdout.write(JSON.stringify({out,data:Object.fromEntries(C.standard().benchmarks.map(b=>[b.key,b.datasets]))}));") diff --git a/app/ui_tests/test_builder_limit_error.py b/app/ui_tests/test_builder_limit_error.py index a8d3373b0..dc022d4e8 100644 --- a/app/ui_tests/test_builder_limit_error.py +++ b/app/ui_tests/test_builder_limit_error.py @@ -33,7 +33,7 @@ def test_the_message_names_the_fields_noun(self): page = PAGE.read_text(encoding="utf-8") unitsof = page[page.index(" const unitsOf = "):page.index(" // the first clause", page.index(" const unitsOf = "))] program = ("const C=require(" + json.dumps(str(APP / "static/builder/command-builder-core.js")) + ")(" + json.dumps(self.schema) + ");\n" + unitsof - + "const out=[];for(const b of C.standard().benchmarks)for(const runs of [b.setups.length?['original']:[],(b.controls||[]).slice(0,1).map(c=>c.key)]){" + + "const out=[];for(const b of C.standard().benchmarks.filter(b=>!b.suite))for(const runs of [b.setups.length?['original']:[],(b.controls||[]).slice(0,1).map(c=>c.key)]){" + "if(!runs.length)continue;const r=C.createStandard(b.key);r.others=runs;r.limit=-3;out.push([b.key,runs,'Number of '+unitsOf(r).nouns,r]);}" + "process.stdout.write(JSON.stringify(out));") cases = json.loads(subprocess.run([self.node, "-"], input=program, check=True, capture_output=True, text=True).stdout) diff --git a/app/ui_tests/test_suite_routes.py b/app/ui_tests/test_suite_routes.py index e5d0d64b1..e2329d4e7 100644 --- a/app/ui_tests/test_suite_routes.py +++ b/app/ui_tests/test_suite_routes.py @@ -67,6 +67,7 @@ def test_the_pages_list_the_suite_apart_and_its_members(self): text = own.get_data(as_text=True) self.assertRegex(text, r'data-search="[^"]*gsm8k') self.assertIn('href="/benchmarks/gsm8k"', text) # no version of its own: its page + self.assertIn("

Suites

", self.get("/new-run/benchmarks").get_data(as_text=True)) def test_a_task_file_that_is_no_object_leaves_the_benchmarks_reachable(self): (self.tmp / "catalogue" / "suites" / "smoke" / "2026-12.json").write_text("[]") @@ -75,11 +76,198 @@ def test_a_task_file_that_is_no_object_leaves_the_benchmarks_reachable(self): self.assertIn('href="/benchmarks/gsm8k"', page.get_data(as_text=True)) self.assertEqual(self.get("/benchmarks/gsm8k").status_code, 200) + def test_the_agent_grid_greys_an_agent_by_the_members_chosen_and_says_its_backend(self): + every = self.get("/new-run/agents?benchmark=smoke").get_data(as_text=True) + self.assertIn("Cannot run", every) # no agent runs a desktop and a conversation member alike + some = self.get("/new-run/agents?benchmark=smoke&members=gsm8k.test,simpleqa.simpleqa").get_data(as_text=True) + card = some[some.index('id="pick-digitalmate-0.1.13"') - 2000:some.index('id="pick-digitalmate-0.1.13"') + 3000] + self.assertIn("container backend", card) + at = some.index('id="pick-opencode"') + self.assertNotIn("Cannot run", some[at:some.index("
", at)]) + + def test_review_reads_only_and_run_queues_ordinary_runs_in_the_suite_s_workspace(self): + out = self.post("/new-run/runner", {"recipe": CHECKS}).get_json() + self.assertEqual((out["errors"], len(out["jobs"]), out["suite"]["workspace"]), ([], 2, "suite-smoke-2026-12")) + self.assertFalse((self.tmp / "catalogue" / "sets").exists()) # Review wrote no task set + for more, status, said in (({"workspace": "mine"}, 400, "A suite's runs go into its own workspace, suite-smoke-2026-12."), + ({}, 400, 'A suite starts from its Review: send the digest it showed as "reviewed".'), + ({"reviewed": "0" * 64}, 409, "The suite's runs changed since Review: review them again.")): + r = self.post("/run", {"recipe": CHECKS, **more}) + self.assertEqual((r.status_code, r.get_json()["error"], self.started), (status, said, [])) + r = self.post("/run", {"recipe": CHECKS, "reviewed": out["suite"]["digest"]}) + self.assertEqual(r.status_code, 200, r.get_data(as_text=True)) + plans = [ex.plan for ex in self.started] + queue = plans[0].queue # the launch's own id, in every run of it + self.assertRegex(queue, r"^smoke-checks-[0-9a-f]{8}$") + self.assertEqual([(p.name, p.queue, p.queue_runs, p.after, p.keyless, len(p.steps())) for p in plans], + [("smoke-checks-gsm8k-nop", queue, ["smoke-checks-gsm8k-nop", "smoke-checks-simpleqa-nop"], "", True, 1), + ("smoke-checks-simpleqa-nop", queue, ["smoke-checks-gsm8k-nop", "smoke-checks-simpleqa-nop"], "smoke-checks-gsm8k-nop", False, 1)]) + self.assertEqual(({j["launch"] for p in plans for j in p.jobs}, plans[1].queue_recipe), ({queue}, CHECKS)) + self.assertEqual([p.key_var for p in plans], ["OPENAI_API_KEY"] * 2) + self.assertIn("--set smoke-2026-12 --set-hash ", plans[0].script) + self.assertIn(f"--suite smoke@2026-12:{out['suite']['digest']}", plans[1].script) + self.assertEqual(sorted(os.listdir(self.tmp / "catalogue" / "sets")), ["gsm8k", "gsm8k.lock", "simpleqa", "simpleqa.lock"]) + self.assertEqual(execution.recorded(self.started[1].dir)[1]["after"], "smoke-checks-gsm8k-nop") # saved with the launch + # the suite's workspace is the open one, and the Runs page shows the launch by the suite's name + self.assertEqual((web.shared.STATE["workspace"].name, {ex.workspace for ex in self.started}), ("suite-smoke-2026-12", {"suite-smoke-2026-12"})) + page = self.get("/runs?view=launch").get_data(as_text=True) + self.assertIn("

Suite smoke test 2026-12 · 3 tasks

", page) + self.assertIn("0 runs · 2 checks", page) + self.assertIn(f'action="/launch/{queue}/stop"', page) # Stop suite, while a run of it has not ended + # a name a suite's launch has had is not taken twice, whichever members: their runs would join one launch + again = self.post("/new-run/runner", {"recipe": dict(CHECKS, datasets=["humaneval.humaneval"])}).get_json()["suite"]["digest"] + r = self.post("/run", {"recipe": dict(CHECKS, datasets=["humaneval.humaneval"]), "reviewed": again}) + self.assertEqual((r.status_code, r.get_json()["error"], len(self.started)), (409, "smoke-checks is a launch already: give this one another name.", 2)) + # a run's suite mark is its launch's to write: an ordinary recipe that carries one is refused + r = self.post("/run", {"recipe": dict(plans[0].recipe, name="copied")}) + self.assertEqual((r.status_code, len(self.started)), (400, 2)) + self.assertIn("one run of a suite", r.get_json()["error"]) + + def test_a_stopped_suite_shows_its_cancelled_runs_and_runs_the_rest_as_reviewed(self): + self.assertEqual(self.run_it().status_code, 200) + first, second = self.started + first.state = "done"; first._save() + second.state = "stopped"; second._save() # it never had its turn + page = self.get("/runs?view=launch").get_data(as_text=True) + self.assertIn("cancelled", page) + self.assertIn(f'action="/launch/{first.plan.queue}/rest"', page) + r = self.client.post(f"/launch/{first.plan.queue}/rest", data={"csrf": self.headers["X-CSRF-Token"]}, headers={"Origin": "http://localhost"}) + self.addCleanup(r.close) + self.assertEqual(r.status_code, 302) + rest, = self.started[2:] # the one that did not finish, alone + self.assertEqual((rest.plan.name, rest.plan.after, rest.plan.queue_recipe["only"]), ("smoke-checks-rest-simpleqa-nop", "", [["simpleqa.simpleqa", "nop"]])) + self.assertNotEqual(rest.plan.queue, first.plan.queue) + self.assertEqual(rest.plan.recipe["suite"]["hash"], second.plan.recipe["suite"]["hash"]) + # once: not offered, nor started again, while that rest has not ended + self.assertNotIn("/rest\"", self.get("/runs?view=launch").get_data(as_text=True)) + r = self.client.post(f"/launch/{first.plan.queue}/rest", data={"csrf": self.headers["X-CSRF-Token"]}, headers={"Origin": "http://localhost"}) + self.addCleanup(r.close) + self.assertEqual(len(self.started), 3) + # nor when a restart could not read that rest's record: its plan still says whose rest it is + record = Path(rest.dir) / "run.json" + kept = record.read_text(); record.write_text("{") + del execution.EXECUTIONS[rest.id] + self.assertTrue(web.execute.rest(first.plan.queue)["open"]) + r = self.client.post(f"/launch/{first.plan.queue}/rest", data={"csrf": self.headers["X-CSRF-Token"]}, headers={"Origin": "http://localhost"}) + self.addCleanup(r.close) + self.assertEqual(len(self.started), 3) + record.write_text(kept); execution.EXECUTIONS[rest.id] = rest + # a member whose definition moved since is not run as if reviewed + rest.state = "failed"; rest._save() + from nullius.standard.runner import suites + with patch.object(suites, "pin", lambda b, o=None: "0" * 64): + r = self.client.post(f"/launch/{rest.plan.queue}/rest", data={"csrf": self.headers["X-CSRF-Token"]}, headers={"Origin": "http://localhost"}) + self.addCleanup(r.close) + self.assertEqual(len(self.started), 3) + + def test_the_rest_of_a_launch_gets_what_is_left_of_its_ceiling(self): + self.assertEqual(self.run_it().status_code, 200) + first, second = self.started + first.plan.queue_recipe["max_usd"] = 10 # the suite's ceiling, as the launch kept it + first.state = "done"; first._save() + second.state = "stopped"; second._save() + sent = [] + def start(recipe, into, reviewed): + sent.append(recipe) + return web.execute.jsonify(ok=True) + ask = lambda: self.addCleanup(self.client.post(f"/launch/{first.plan.queue}/rest", data={"csrf": self.headers["X-CSRF-Token"]}, + headers={"Origin": "http://localhost"}).close) + with patch.object(web.execute, "_start_suite", start), patch.object(web.execute, "unpriced", lambda models: []): + with patch.object(web.execute, "_spent", lambda ex: 4.9 if ex is second else 0.0): + ask() + self.assertEqual((sent[0]["max_usd"], sent[0]["rest_of"], sent[0]["only"]), + (5.1, {"queue": first.plan.queue, "max_usd": 10.0}, [["simpleqa.simpleqa", "nop"]])) + with patch.object(web.execute, "_spent", lambda ex: 5.0): # the ceiling is spent: nothing starts + ask() + self.assertEqual(len(sent), 1) + # a run stopped before its result: what its first ledger holds; a unit begun and no ledger: its whole share + from nullius.standard.calls import ledger + second.plan.recipe["max_usd"] = 5 + job = Path(second.dir) / "jobs" / second.plan.jobs[0]["name"] + (job / ".work" / "ledger").mkdir(parents=True) + book = ledger.Ledger.create(str(job / ".work" / "ledger" / "ledger.json"), max_usd=5) + book.settle(book.reserve(4.9)[0], 4.9) + self.assertEqual(web.execute._spent(second), 4.9) + shutil.rmtree(job / ".work"); (job / "0001__u0000").mkdir(); (job / "0001__u0000" / "result.json").write_text("{}") + self.assertEqual(web.execute._spent(second), 5.0) + # a rest's own rest counts from the first launch's ceiling, and what every launch of it spent + second.plan.queue_recipe = dict(sent[0]) + self.assertEqual(web.execute.rest(second.plan.queue)["ceiling"], 10.0) + + def test_deleting_an_ended_launch_gives_none_of_its_spending_back(self): + self.assertEqual(self.run_it().status_code, 200) + first, second = self.started + first.plan.queue_recipe["max_usd"] = 10 + first.state = "done"; first._save() + second.state = "failed"; second._save() + cost = {second.plan.name: 4.0} + ask = lambda queue: self.addCleanup(self.client.post(f"/launch/{queue}/rest", data={"csrf": self.headers["X-CSRF-Token"]}, + headers={"Origin": "http://localhost"}).close) + with patch.object(web.execute, "unpriced", lambda models: []), patch.object(web.execute, "_spent", lambda ex: cost.get(ex.plan.name, 0.0)): + ask(first.plan.queue) + one = self.started[2] + self.assertEqual(one.plan.queue_recipe["max_usd"], 6.0) + one.state = "failed"; one._save(); cost[one.plan.name] = 1.0 + execution.delete([first.plan.name, second.plan.name], web.shared.WS_HOME) # the first launch, ended, deleted as any + self.assertNotIn(second.id, execution.EXECUTIONS) + ask(one.plan.queue) + two = self.started[3] + self.assertEqual(two.plan.queue_recipe["max_usd"], 5.0) # 10 less the 4 and the 1, not 9 + two.state = "failed"; two._save() + execution.delete([two.plan.name], web.shared.WS_HOME) # the last rest gone: what it spent is not known + ask(one.plan.queue) + self.assertEqual(len(self.started), 4) + + def test_a_run_deleted_alone_before_the_first_rest_leaves_no_cap_to_give(self): + self.assertEqual(self.run_it().status_code, 200) + first, second = self.started + first.plan.queue_recipe["max_usd"] = 10 + first.state = "done"; first._save() # it spent 4 of the 10 + second.state = "failed"; second._save() + execution.delete([first.plan.name], web.shared.WS_HOME) # deleted alone, as the Roots dialog does + with patch.object(web.execute, "unpriced", lambda models: []), patch.object(web.execute, "_spent", lambda ex: 0.0): + r = self.client.post(f"/launch/{second.plan.queue}/rest", data={"csrf": self.headers["X-CSRF-Token"]}, headers={"Origin": "http://localhost"}) + self.addCleanup(r.close) + self.assertEqual(len(self.started), 2) # not 10 again for the one that is left + + def test_a_run_held_without_its_plan_is_on_its_launch_and_in_its_rest(self): + self.assertEqual(self.run_it().status_code, 200) + first, second = self.started + first.state = "done"; first._save() + second.state = "failed"; second._save() + os.remove(os.path.join(second.dir, "plan.json")) + execution.EXECUTIONS.clear() # Nullius restarted + self.assertEqual(execution.restore(), []) + held = next(e for e in execution.EXECUTIONS.values() if e.lost) + self.assertEqual((held.plan.name, held.plan.queue, held.state), (second.plan.name, first.plan.queue, "failed")) + page = self.get("/runs?view=launch").get_data(as_text=True) + self.assertIn(second.plan.name, page) + self.assertEqual(list(web.execute.rest(first.plan.queue)["marks"]), [("simpleqa.simpleqa", "nop")]) + + def test_stop_is_the_queue_s_and_its_runs_are_not_deleted_while_one_waits(self): + self.assertEqual(self.run_it().status_code, 200) + first, second = self.started + self.assertIn("Stop suite", self.get(f"/job/{second.plan.name}").get_data(as_text=True)) + first.state = "done" # the first ended, the second waits its turn + with self.assertRaisesRegex(ValueError, "one of a suite's runs, and some have not ended"): + execution.deletable([first.plan.name]) + r = self.post(f"/run/{first.id}/stop", {}) + self.assertEqual((r.status_code, second.state), (200, "stopping")) + self.assertTrue(os.path.exists(os.path.join(first.dir, execution.QUEUE_STOP))) + + def test_a_run_whose_key_is_not_set_starts_nothing(self): + with patch.dict(os.environ, {"OPENAI_API_KEY": ""}): + r = self.run_it() # the judged member's check needs its judge's key + self.assertEqual((r.status_code, self.started), (400, [])) + self.assertIn("OPENAI_API_KEY is not set in Settings", r.get_json()["error"]) + self.assertFalse((self.tmp / "catalogue" / "sets").exists()) + def test_a_suite_named_as_a_benchmark_never_takes_its_place(self): shutil.copytree(self.tmp / "catalogue" / "suites" / "smoke", self.tmp / "catalogue" / "suites" / "gsm8k") out = self.post("/new-run/runner", {"recipe": dict(CHECKS, benchmark="gsm8k", datasets=["test"])}).get_json() self.assertEqual((out["errors"], "suite" in out, out["review"][0][1]), ([], False, "Benchmark")) self.assertNotIn('href="/suites/gsm8k"', self.get("/benchmarks").get_data(as_text=True)) + if __name__ == "__main__": unittest.main() diff --git a/app/web/api.py b/app/web/api.py index 0cbd7fc21..59766a687 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -447,7 +447,9 @@ def _compiled(recipe: dict) -> tuple: out = builder._standard_compile(recipe) post = {"name": recipe.get("name"), "where": recipe.get("where"), "recipe": recipe} return post, {"errors": [e["message"] for e in out["errors"]], "notes": out["notes"], "review": out["review"], - "jobs": out["jobs"], "confirm": out["confirm"] or ""} + "jobs": out["jobs"], "confirm": out["confirm"] or "", + # a suite: the digest of what this check reviewed, which its start takes back + **({"reviewed": out["suite"]["digest"]} if out.get("suite") else {})} def _checked(recipe: dict) -> tuple: @@ -478,7 +480,8 @@ def api_run_check(): @app.route(PREFIX + "/runs", methods=["POST"]) @api("run") def api_run_start(): - """Start a recipe: ``{"recipe": {...} | "", "where"?, "name"?, "confirm"?, "workspace"?}``. A new run each + """Start a recipe: ``{"recipe": {...} | "", "where"?, "name"?, "confirm"?, "workspace"?, "reviewed"?}`` + (``reviewed``: for a suite, the digest its check returned, required). A new run each time, named by the recipe's name and the second unless ``name`` says; refused with what Review would show when the recipe does not compile, a machine lacks a prerequisite, or its question is not answered. ``workspace``: the one its jobs go into, made when there is none, in place of the open one.""" @@ -492,6 +495,8 @@ def api_run_start(): return _error(409, doc["confirm"] + " Send \"confirm\": true to start it.", **doc) if "workspace" in body: post["workspace"] = body["workspace"] + if "reviewed" in body: + post["reviewed"] = body["reviewed"] started = execute.start(post) out = started[0].get_json() if isinstance(started, tuple) else started.get_json() status = started[1] if isinstance(started, tuple) else 200 diff --git a/app/web/builder.py b/app/web/builder.py index baae50a24..df9f7d8ec 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -19,6 +19,7 @@ from nullius.standard.contract import definitions from nullius.standard.requirements import hostreq from nullius.standard.pages import recipe as standard_recipe +from nullius.standard.runner import suites from .core import app from .filters import agent_mark_url, module_mark_url @@ -51,7 +52,7 @@ def new_run(): if request.args.get("run") or (ex and ex.plan.recipe): if ex is None or not ex.plan.recipe: abort(404) - data["loadRecipe"] = ex.plan.recipe + data["loadRecipe"] = ex.plan.queue_recipe or ex.plan.recipe # a suite's run opens its suite data["loadRun"] = run elif like: job = shared._job_for_request(like) @@ -76,7 +77,7 @@ def new_run_benchmarks(): # a benchmark with versions carries each one's Tasks (the default's under ""), for the builder to show the chosen one's items = [dict(i, pick={"value": i["key"], "one": True}, id="pick-bench-" + i["key"], title={"text": i["title"], "title": i["domain"]}, data={"tasks": json.dumps({"": i["tasks"], **i["versions"]})} if i["versions"] else None) - for i in catalogue.benchmark_cards(cat)] + for i in catalogue.suite_cards() + catalogue.benchmark_cards(cat)] every = catalogue.benchmark_choices(cat) choices = {k: [(v, t) for v, t in every[k] if any(v in _values(i[k]) for i in items)] for k in ("category", "evaluates", "runs", "origin")} return render_template("builder/benchmarks.html", items=items, choices={k: v for k, v in choices.items() if len(v) > 1}, @@ -94,6 +95,9 @@ def new_run_agents(): builder puts in its page: its agents or Modules as pick cards (templates/builder/agents.html), or rows with ?view=table, from the entries the Agents page lists (``recipe.entries``), each greyed with the reasons it does not fit.""" benches = definitions.load("benchmark", every=True)[0] + suite = suites.find(request.args.get("benchmark", "")) + if suite: + return _suite_agents(suite, benches) b = definitions.find(benches, request.args.get("benchmark", "")) if b is None: abort(404) @@ -117,6 +121,36 @@ def new_run_agents(): layout="table" if request.args.get("view") == "table" else "cards") +def _suite_agents(s: dict, benches: list): + """The Agent step's grid for a suite: an agent is offered when it fits every member chosen that takes one + (``?members=``, ids with commas; all without it), on the backend its runs get (``suites.plan``); greyed, the + members it fails.""" + ids = [m["id"] for m in s["members"]] + chosen = [x for x in request.args.get("members", "").split(",") if x in ids] or None + defs = standard_recipe._all() + try: + own = [g["bench"] for g in suites.groups(s, benches, chosen) if not g["settings"].get("setup") and g["bench"]["family"] == "agent"] + entries = [e for e in standard_recipe.entries("agent", benches=own, every=True)["entries"] if not e["d"].get("example")] + plan = suites.plan(s, defs, [e["d"]["_ref"] for e in entries], chosen=chosen) + except suites.Refused: + abort(404) + b = {"key": s["key"], "label": s["label"], "family": "agent", "needs": sorted({p for m in own for p in m.get("needs") or []})} + items = [] + for e in entries: + ref = e["d"]["_ref"] + failed = plan["unfit"].get(ref) or [] + card = _pick_card(b, dict(e, fits=[{"why": [f"{label}: {why}" for label, why in failed]}])) + if failed: + card["alert"] = {"text": "Cannot run " + ", ".join(label for label, _ in failed), "title": card["alert"]["title"]} + on = sorted({r["backend"][ref] for r in plan["rows"] if r["backend"].get(ref, "local") != "local" and not r["settings"].get("backend")}) + if on and not failed: + card["ticks"] = card["ticks"] + [{"text": f"{' and '.join(on)} backend", "title": "Its runs use this backend, whatever the Where step says."}] + items.append(card) + choices = {"fit": [(v, t) for v, t in (("fit", "Can run it"), ("unfit", "Cannot")) if any(i["fit"]["value"] == v for i in items)]} + return render_template("builder/agents.html", items=items, kind="agent", choices={k: v for k, v in choices.items() if len(v) > 1}, + layout="table" if request.args.get("view") == "table" else "cards") + + def _setup_card(b: dict, key: str, procedure: str) -> dict: """The selected version's own procedure, run by its own code: a pick card beside the agents or Modules, named as its settings tab is.""" @@ -233,7 +267,8 @@ def _standard_compile(recipe: dict) -> dict: boat_size_problem=execute.boat_size_problem, unpriced=execute.unpriced) # served_models: each model field's model as the run sends it, which Served by lists the providers of; # own_reasoning: by field, what sets its reasoning in every job, which greys its select - return {k: out[k] for k in ("errors", "notes", "review", "jobs", "confirm", "served_models", "own_reasoning")} + # suite: a suite's key, version and the digest of what Review shows, which Run sends back + return {k: out[k] for k in ("errors", "notes", "review", "jobs", "confirm", "served_models", "own_reasoning", "suite") if k in out} @app.route("/new-run/prerequisites", methods=["POST"]) @@ -261,10 +296,10 @@ def prerequisites_of(body: dict): return jsonify(machines=[], ready=False, errors=[]) wheres = [sh["where"] for sh in out["shards"]] needs = (["engine"] if out["docker"] else []) + (list(boat.PROGRAMS) if recipe.get("backend") == "boat" else []) - h = out.get("host") or {} - b = definitions.get("benchmark", h.get("benchmark", "")) if h.get("needs") else None - setups = {n["name"]: {**n, "install": hostreq.install_lines(b, [n["name"]])} - for n in h.get("needs") or []} if b else {} + for h in out.get("hosts") or [out.get("host") or {}]: # a suite: what each member needs + b = definitions.get("benchmark", h.get("benchmark", "")) if h.get("needs") else None + setups.update({n["name"]: {**n, "install": hostreq.install_lines(b, [n["name"]])} + for n in h.get("needs") or []} if b else {}) host_needs = needs + ["python3", "git"] elif recipe.get("harness", "harbor") != "harbor": return jsonify(machines=[], ready=False, errors=[providers.GONE]) diff --git a/app/web/execute.py b/app/web/execute.py index 95f7841a6..08fbea34d 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -4,6 +4,8 @@ import json import os import re +import secrets +import threading import time from flask import abort, jsonify, request, url_for from nullius import execution, hosts, prerequisites, prices, providers, settings, workspace @@ -11,7 +13,7 @@ from nullius.standard.backends import boat from nullius.standard.calls import ledger from nullius.standard.pages import recipe as standard_recipe -from nullius.standard.runner import rerun +from nullius.standard.runner import rerun, sets, suites from .core import app from . import shared @@ -40,6 +42,10 @@ def start(body: dict): return jsonify(ok=False, error="A workspace's name is lowercase letters, digits and dashes."), 400 into = into or "" if recipe.get("harness") == standard_recipe.HARNESS: + if suites.find(str(recipe.get("benchmark") or "")): + return _start_suite({k: v for k, v in recipe.items() if k not in ("only", "rest_of")}, into, str(body.get("reviewed") or "")) + if "suite" in recipe: # the mark of a suite's run: its launch alone writes it + return jsonify(ok=False, error="This recipe is one run of a suite: run the suite, or remove its suite field."), 400 return _start_standard(recipe, into) where = str(body.get("where") or "local") host = None @@ -182,6 +188,225 @@ def _start_standard(recipe: dict, into: str = ""): **started[0].summary()) +def _start_suite(recipe: dict, into: str = "", reviewed: str = ""): + """A suite: each member with each participant an ordinary run of its own (``recipe.compile``'s ``runs``), every + one checked - its own providers' keys, its plan - before any starts; then one launch of them all, a queue: each + run waits for the one before it (``execution.Plan.after``). The members' task sets are made or reused here, + under each benchmark's sets lock, and each run is bound to its list's hash. The runs go into the suite's own + workspace, opened so the Runs page shows them; another ``into`` is refused. ``reviewed``: the digest + Review showed (the page's, or the API's check), required, refused when the suite compiles to another now. + The launch is one queue (``execution.Plan.queue``): an id of its own in every run, which the Runs page + groups by; a name a suite's launch has had is refused.""" + if len(json.dumps(recipe)) > 200_000: + return jsonify(ok=False, error="the recipe is too large to keep with the run"), 400 + out = standard_recipe.compile(recipe, docker_unusable=docker_problem, boat_unusable=boat.unusable, + boat_size_problem=boat_size_problem, unpriced=unpriced) + if out["errors"]: + return jsonify(ok=False, error=" ".join(e["message"] for e in out["errors"])), 400 + info = out["suite"] + if into and into != info["workspace"]: + return jsonify(ok=False, error=f"A suite's runs go into its own workspace, {info['workspace']}."), 400 + if not reviewed: + return jsonify(ok=False, error="A suite starts from its Review: send the digest it showed as \"reviewed\"."), 400 + if reviewed != info["digest"]: + return jsonify(ok=False, error="The suite's runs changed since Review: review them again."), 409 + for run in out["runs"]: + missing = providers_problem(run["recipe"], run["out"]) + if missing: + return jsonify(ok=False, error=missing), 400 + s = suites.find(recipe["benchmark"]) + try: + entries = suites.freeze(s, standard_recipe._all()["benchmark"], [run["member"] for run in out["runs"]]) + except suites.Refused as e: + return jsonify(ok=False, error=f"{e}."), 409 + except OSError as e: + return jsonify(ok=False, error=f"The suite's task sets could not be saved ({e.strerror or e})."), 503 + plans = [] + for run in out["runs"]: + if sets.latest(entries[run["benchmark"]])["hash"] != run["recipe"]["suite"]["set_hash"]: + return jsonify(ok=False, error="The suite's task sets changed since Review: review them again."), 409 + made, problem = standard_plans(run["recipe"], run["out"], set()) + if problem: + return jsonify(ok=False, error=problem), 400 + plans += made + name = str(recipe.get("name") or "") + queue = f"{name}-{secrets.token_hex(4)}" + for before, plan in zip([None] + plans, plans): + plan.queue, plan.queue_runs, plan.after, plan.queue_recipe = queue, [p.name for p in plans], before.name if before else "", recipe + for j in plan.jobs: + j["launch"] = queue + with _SUITES: # one launch at a time takes a suite's name + if any((e.plan.queue_recipe or {}).get("name") == name or e.plan.name == name for e in list(execution.EXECUTIONS.values())): + return jsonify(ok=False, error=f"{name} is a launch already: give this one another name."), 409 + started, problem, status = begin(plans, info["workspace"]) + if problem: + return jsonify(ok=False, error=problem), status + ws = workspace.load(shared.WS_HOME, info["workspace"]) + if ws is not None and workspace.readable(ws): + shared.open_workspace(ws) # the Runs page shows the launch at once + return jsonify(ok=True, open=url_for("index", view="launch"), runs=[ex.summary() for ex in started], **started[0].summary()) + + +_SUITES = threading.Lock() + + +_RESTS = threading.Lock() +RESTS = ".suite-rests.json" # in the runs folder: by first launch, each rest's runs and what the suite had spent before it + + +def _rests(root: str) -> dict: + """The rests started under the runs folder *root*: {first launch's queue: [{"before": USD, "runs": [names]}]}. + {} when none was; OSError or ValueError when the file is there and cannot be read.""" + try: + with open(os.path.join(root, RESTS), encoding="utf-8") as fh: + got = json.load(fh) + except FileNotFoundError: + return {} + if not isinstance(got, dict): + raise ValueError("not a rests file") + return got + + +def _spent(ex) -> float: + """What the run *ex* spent of its cap, by its jobs' own account (``rerun.budget``); its whole share where a + job cannot say.""" + share = (ex.plan.recipe or {}).get("max_usd") + share = float(share) if isinstance(share, (int, float)) and not isinstance(share, bool) else 0.0 + spent = 0.0 + for j in ex.plan.jobs: + folder = os.path.join(ex.dir, "jobs", str(j.get("name"))) + if not os.path.isdir(folder): + continue # never started: nothing spent + try: + got = rerun.spent(folder) # a run stopped before its result: its first ledger + except (OSError, ValueError, TypeError, KeyError): + got = None + if got is None: + return share + spent += got + return spent + + +def _unheld(root: str, queue: str, name: str) -> bool: + """Whether the runs folder *root* holds a run this process does not - its record could not be read at the + restart - that is of a rest of the launch *queue*, by its plan, or, that unreadable too, by its name.""" + held = {e.plan.name for e in execution.EXECUTIONS.values() if e.root == root} + try: + names = [n for n in os.listdir(root) if n not in held and os.path.isdir(os.path.join(root, n))] + except OSError: + return False + for n in names: + try: + with open(os.path.join(root, n, execution.PLAN), encoding="utf-8") as fh: + of = (json.load(fh).get("queue_recipe") or {}).get("rest_of") or {} + if of.get("queue") == queue: + return True + except (OSError, ValueError, AttributeError): + if name and n.startswith(f"{name}-rest"): + return True + return False + + +def rest(queue: str) -> dict: + """What "Run the rest" of the suite's launch *queue* has to go on: {"root": the first launch's queue, + "recipe": the suite's own as this launch kept it, or None, "marks": {(member, participant): what its run was + marked with} for each whose last run - in that launch or a rest of it - did not finish, "open": whether one + of those launches has a run that has not ended, "ceiling": the first launch's spending cap, or None, + "family": the runs of those launches}. Its members are the records' (a run held + without its plan included, ``execution._lost``); a rest whose record + could not be read at the restart keeps it open (``_unheld``).""" + of = lambda e: (e.plan.queue_recipe or {}).get("rest_of") if isinstance((e.plan.queue_recipe or {}).get("rest_of"), dict) else {} + mine = [e for e in execution.EXECUTIONS.values() if e.plan.queue == queue] + root = next((of(e)["queue"] for e in mine if of(e).get("queue")), queue) + family = sorted((e for e in execution.EXECUTIONS.values() if e.plan.queue and root in (e.plan.queue, of(e).get("queue"))), key=lambda e: e.started or 0) + recipe = next((e.plan.queue_recipe for e in mine if (e.plan.queue_recipe or {}).get("benchmark")), None) + last = {} + for e in family: + m = (e.plan.recipe or {}).get("suite") or {} + if m.get("member"): + last[(m["member"], m.get("who"))] = (e.state, m) + ceiling = next((of(e)["max_usd"] for e in mine if of(e).get("queue")), (recipe or {}).get("max_usd")) + ceiling = float(ceiling) if isinstance(ceiling, (int, float)) and not isinstance(ceiling, bool) and ceiling > 0 else None + return {"root": root, "recipe": recipe, "marks": {k: m for k, (state, m) in last.items() if state != "done"}, + "open": any(execution.queue_open(e) for e in {e.plan.queue: e for e in family}.values()) + or bool(mine) and _unheld(mine[0].root, root, str((recipe or {}).get("name") or "").split("-rest")[0]), + "ceiling": ceiling, "family": family} + + +def rest_of(queue: str): + """"Run the rest" of a suite's launch that ended: a new launch of the runs whose last run did not finish - + cancelled, stopped or failed - from the suite's own recipe as that launch kept it. Its cap is what is left + of the first launch's ceiling, shared between its runs: the launch and its rests never spend more than + that ceiling in all. What the suite had spent is kept with each rest (``RESTS``), so + deleting an ended launch gives nothing back; a rest whose runs were deleted leaves it unknown, and the next is refused. + One at a time: refused while the launch or a rest of it is open, when all finished, + when nothing is left of the ceiling, and when a run's benchmark or participant is no longer what was + reviewed.""" + with _RESTS: + try: + return _rest_of(queue) + except (OSError, ValueError) as e: # the rests file: what earlier rests spent cannot be told + return jsonify(ok=False, error=f"What the suite has spent could not be read ({getattr(e, 'strerror', None) or e}): the rest was not started."), 503 + + +def _rest_of(queue: str): + runs = [e for e in execution.EXECUTIONS.values() if e.plan.queue == queue] + r = rest(queue) + if not runs or not r["recipe"]: + abort(404) + if r["open"]: + return jsonify(ok=False, error="The launch has runs that have not ended: stop the suite first." if execution.queue_open(runs[0]) else + "The rest of this launch is running already.", ), 409 + marks = r["marks"] + if not marks: + return jsonify(ok=False, error="Every run of the launch finished."), 409 + left, book, spent = None, _rests(runs[0].root), 0.0 + chain = book.get(r["root"]) or [] + if r["ceiling"] is not None: + spent = sum(_spent(e) for e in r["family"]) + if chain: # the launches before the last rest may be deleted: it kept what they had spent + last, held = chain[-1], {e.plan.name: e for e in r["family"]} + if not set(last["runs"]) <= set(held): + return jsonify(ok=False, error="A run of this launch's last rest was deleted, so what the suite spent cannot be told: " + "launch the suite again from the builder."), 409 + spent = max(spent, last["before"] + sum(_spent(held[n]) for n in last["runs"])) + elif not set(runs[0].plan.queue_runs) <= {e.plan.name for e in r["family"]}: + # before the first rest nothing kept what the launch's runs spent: one deleted alone took its spending with it + return jsonify(ok=False, error="A run of this launch was deleted, so what the suite spent cannot be told: " + "launch the suite again from the builder."), 409 + left = round(r["ceiling"] - spent, 6) + if left is not None and left <= 0: + return jsonify(ok=False, error="The suite's spending cap is spent: nothing is left for the rest."), 409 + base = str(r["recipe"].get("name") or "") + taken = {(e.plan.queue_recipe or {}).get("name") for e in execution.EXECUTIONS.values()} + name = next(n for n in (f"{base}-rest" + (f"-{i}" if i > 1 else "") for i in range(1, 1000)) if n not in taken) + recipe = dict(r["recipe"], name=name, only=[list(k) for k in marks], rest_of={"queue": r["root"], "max_usd": r["ceiling"]}, + **({"max_usd": left} if left is not None else {})) + out = standard_recipe.compile(recipe, docker_unusable=docker_problem, boat_unusable=boat.unusable, + boat_size_problem=boat_size_problem, unpriced=unpriced) + if out["errors"]: + return jsonify(ok=False, error=" ".join(e["message"] for e in out["errors"])), 400 + for run in out["runs"]: + was = suites.marked(marks[(run["member"], run["who"])].get("mark")) or {} + if was.get("pin") != run["pin"] or was.get("hash") != out["suite"]["hash"]: + return jsonify(ok=False, error=f"{run['name']} is no longer what was reviewed: review the suite again in the builder."), 409 + # what the suite had spent before this rest, kept beside the runs: it outlives the launches it counted + path = os.path.join(runs[0].root, RESTS) + if left is None: # no ceiling: nothing to keep + return _start_suite(recipe, "", out["suite"]["digest"]) + try: + execution.ondisk.write_whole(path, json.dumps({**book, r["root"]: chain + [{"before": spent, "runs": [run["name"] for run in out["runs"]]}]})) + except OSError as e: + return jsonify(ok=False, error=f"What the suite has spent could not be saved ({e.strerror or e}): the rest was not started."), 503 + started = _start_suite(recipe, "", out["suite"]["digest"]) + if not (started[0] if isinstance(started, tuple) else started).get_json().get("ok"): + try: + execution.ondisk.write_whole(path, json.dumps(book)) + except OSError: + pass # an entry of runs that never were: the next rest is refused, not overspent + return started + + _PRICED = {"at": float("-inf"), "rows": {}} @@ -339,6 +564,8 @@ def again_offer(job, ex) -> dict | None: return {"why": "Not started from here: no record of where it ran."} if ex.state in execution.ALIVE or job.is_running or job.is_preparing: return {"why": "Still running: more tasks can be started once it has ended."} + if execution.queue_open(ex): + return {"why": "One of a suite's runs: more tasks can be started once every run of its launch has ended."} if ex.plan.host is not None and ex.plan.host.entry not in {h.entry for h in _hosts()}: return {"why": f"Its host, {ex.plan.host.label}, is no longer in Settings."} return {"where": ex.plan.host.label if ex.plan.host else "this machine"} diff --git a/app/web/runs.py b/app/web/runs.py index 75c417f19..607e6ea9e 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -220,10 +220,15 @@ def _launched_here(ex, have, real) -> bool: # A launch's runs, in the order the block lists them: finished first, best # adjusted rate on top; then those still going; then the ones that stopped. -_STATE_ORDER = {"finished": 0, "running": 1, "preparing": 2, "queued": 3, "stopping": 4, "paused": 5, "failed": 6, "refused": 7, "stopped": 8, execution.NOT_RUN: 8.5, +_STATE_ORDER = {"finished": 0, "running": 1, "preparing": 2, "queued": 3, "stopping": 4, "paused": 5, "failed": 6, "refused": 7, "stopped": 8, "cancelled": 8.4, execution.NOT_RUN: 8.5, "not in this workspace": 9} +def _cancelled(ex) -> bool: + """Whether the run was one of a suite's still waiting when the suite was stopped: it never had its turn.""" + return ex is not None and bool(getattr(ex.plan, "queue", "")) and not ex.promoted and ex.state == "stopped" + + def _said(state) -> str: """A run record's state in the words the pages show.""" return "finished" if state == "done" else state @@ -242,7 +247,7 @@ def _state_of(job_id, j, ended, owner): # named by a run record and not under this workspace's roots: still to be written while the run lives, refused # before it started (its folder says so, or no part was launched), else elsewhere if ex is not None and ex.state not in execution.ALIVE: - return "refused" if ex.refused(job_id) else execution.NOT_RUN if ex.never_ran(job_id) else "not in this workspace" + return "refused" if ex.refused(job_id) else "cancelled" if _cancelled(ex) else execution.NOT_RUN if ex.never_ran(job_id) else "not in this workspace" return ex.state if ex is not None else "preparing" if j.is_preparing: return "preparing" @@ -266,7 +271,7 @@ def _control_of(job: dict) -> str: # A control in one of these states ended before it checked every task. -_ENDED_SHORT = ("failed", "refused", "stopped", execution.NOT_RUN, "not in this workspace") +_ENDED_SHORT = ("failed", "refused", "stopped", "cancelled", execution.NOT_RUN, "not in this workspace") def _cut_short(r) -> str: @@ -283,7 +288,7 @@ def _cut_short(r) -> str: # A shard's job as a recipe names it (standard/pages/recipe.py): ``-shard-of``. _SHARD = re.compile(r"-shard-(\d+)of\d+$") # A participant's state is its shards' most telling: one still working, else the one that ended worst. -_TELLING = ("running", "preparing", "stopping", "paused", "queued", "failed", "refused", "stopped", execution.NOT_RUN, +_TELLING = ("running", "preparing", "stopping", "paused", "queued", "failed", "refused", "stopped", "cancelled", execution.NOT_RUN, "not in this workspace", "finished") @@ -405,9 +410,24 @@ def _launch_view(g, by_id, verdicts, ended, owner, twice=()) -> dict: for r in leaves(controls + rows): counts[r["state"]] = counts.get(r["state"], 0) + 1 ex = owner((g.job_ids + g.pending)[0]) + # a suite's launch: named by the suite, its tasks those of the members chosen, not one member's + suite = (ex.plan.recipe or {}).get("suite") if ex is not None else None + if isinstance(suite, dict) and suite.get("label"): + n_tasks = suite.get("tasks") or None + else: + suite = None known = not set(twice) & set(g.job_ids + g.pending) # else the links that open a run would open another - return {"gone": _deletion(_runs_of(g, owner, twice)), - "launch": g, "checks": checks, "verdict": verdict, + # a suite's launch, one queue: stopped as one while a run of it has not ended; then the runs that did not finish can be run + queued = [e for e in _runs_of(g, owner, twice) if getattr(e.plan, "queue", "")] + queue = None + if queued and len({e.plan.queue for e in queued}) == 1: + from . import execute + rest = execute.rest(queued[0].plan.queue) + # offered once: not while a rest of this launch runs, nor once each of its runs finished there + queue = {"key": queued[0].plan.queue, "open": execution.queue_open(queued[0]), + "rest": len(rest["marks"]) if rest["recipe"] and not rest["open"] else 0} + return {"gone": _deletion(_runs_of(g, owner, twice)), "suite": f"{suite['label']} {suite['version']}" if suite else "", + "launch": g, "checks": checks, "verdict": verdict, "queue": queue, "controls": controls, "checked": checked, "agents": rows, "n_tasks": n_tasks, "compare": finished, **_tally(g, by_id, owner), @@ -480,7 +500,7 @@ def job(job_id): ex = None if job_id in twice else runs.get(job_id) ended = ex.job_state(job_id) if ex is not None else None # this job's own state beside the run's: ended, or a part still to come while another runs - own = ((execution.NOT_RUN, None) if ex is not None and ex.state not in execution.ALIVE and ex.never_ran(job_id) + own = (("cancelled" if _cancelled(ex) else execution.NOT_RUN, None) if ex is not None and ex.state not in execution.ALIVE and ex.never_ran(job_id) else ended or ((ex.live_state(job_id), None) if ex is not None and ex.live_state(job_id) in ("queued", execution.NOT_RUN) else None)) if not j: @@ -818,6 +838,11 @@ def launches_page(): std = standard_definitions.load("benchmark")[0] for r in rows: r["bench"], r["datasets"] = _catalogued(r["runs"][0].plan.recipe if r["runs"] else {}, r["launch"].dataset, std) + suite = (r["runs"][0].plan.recipe or {}).get("suite") if r["runs"] else None + if isinstance(suite, dict) and suite.get("label"): # a suite's launch: the suite, and every member's dataset + r["bench"] = (f"{suite['label']} {suite['version']}", url_for("suite_page", key=suite["key"], v=suite["version"]) if suite.get("key") else None) + r["datasets"] = list(dict.fromkeys(d for e in r["runs"] for d in _catalogued(e.plan.recipe or {}, None, std)[1])) + r["shards"] = 1 # its runs follow one another: none is a shard choices = {"bench": [("", "none")] + sorted({(r["bench"][0], r["bench"][0]) for r in rows if r["bench"]}), "dataset": [("", "none")] + sorted({(d, d) for r in rows for d, _ in r["datasets"]}), "state": [(s, s) for s in _TELLING if any(r["state"] == s for r in rows)], @@ -827,6 +852,40 @@ def launches_page(): return render_template("runs/launches.html", rows=rows, workspaces=wss, choices=choices, telling=_TELLING, only=only) +def _queue_here(key) -> list: + """The runs of the suite's launch (its queue) *key*; 404 for none.""" + runs = [e for e in execution.EXECUTIONS.values() if e.plan.queue == key] + if not runs: + abort(404) + return runs + + +@app.route("/launch//stop", methods=["POST"]) +def launch_stop(key): + """Stop suite: the run under way and every run of the launch still waiting (``execution.stop``).""" + shared._require_csrf() + if not shared._local_client(): + abort(403) + if not execution.stop(_queue_here(key)[0]): + flash("The Stop could not be saved, so no run was told: stop it again.", "error") + return redirect(url_for("index", view="launch", _anchor=key.replace(":", "-"))) + + +@app.route("/launch//rest", methods=["POST"]) +def launch_rest(key): + """Run the rest: a new launch of the runs of this one that did not finish (``execute.rest_of``).""" + from . import execute + shared._require_csrf() + if not shared._local_client(): + abort(403) + _queue_here(key) + out = execute.rest_of(key) + doc, status = (out[0].get_json(), out[1]) if isinstance(out, tuple) else (out.get_json(), 200) + if not doc.get("ok"): + flash(doc.get("error") or "The rest did not start.", "error") + return redirect(url_for("index", view="launch")) + + @app.route("/launch//ask") def launch_ask(key): """What the Launches page's Delete asks of a launch, in the dialog: the diff --git a/docs/agents/add-manually.md b/docs/agents/add-manually.md index 88c0df015..45bd59995 100644 --- a/docs/agents/add-manually.md +++ b/docs/agents/add-manually.md @@ -134,6 +134,9 @@ A benchmark's own reference agent, made for that benchmark rather than for any task, names it in `only_for` (`"only_for": ["terminal-bench"]` for Terminus 2): it is offered for those benchmarks alone, whatever ports it has proven. +An agent that runs on some backends alone names them in `backends` +(`"backends": ["container"]` for DigitalMate): a recipe on another is refused. + A benchmark whose upstream ships its own agent scripts keeps them in its folder's `agents.json` instead, each started by the benchmark's driver (`start.driver`): see [A benchmark's own agents](../standard.md#a-benchmarks-own-agents). diff --git a/docs/api.md b/docs/api.md index 452176aba..69f08dbd6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -78,8 +78,8 @@ job["adjusted_solve_rate"], job["counts"] | `judgements(job)`, `judgement(job, trial)` | A judge's stored answers; `lane="llm"` for the LLM judge | | `judge(job, trial)`, `judge_job(job, confirm=False)` | Ask a judge: [below](#asking-a-judge) | | `recipes()`, `recipe(id_or_name)`, `save_recipe(recipe)` | The builder's saved recipes | -| `check(recipe, where=None)` | What Review shows: `ready`, `errors`, `confirm`, `machines` | -| `start(recipe, where=None, name=None, confirm=False, workspace=None)` | `runs`: one per machine | +| `check(recipe, where=None)` | What Review shows: `ready`, `errors`, `confirm`, `machines`; of a suite, `reviewed` | +| `start(recipe, where=None, name=None, confirm=False, workspace=None, reviewed=None)` | `runs`: one per machine; of a suite, one per member and participant. A suite needs `reviewed`, the digest its check returned | | `runs()`, `run(id, since=0, job=None)`, `follow(id)`, `wait(id)` | State, stages, log | | `stop(id)`, `continue_(id)` | Stop; answer a paused run | diff --git a/docs/builder.md b/docs/builder.md index 5228bd82d..af8a70c43 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -23,6 +23,7 @@ Then [read its results](results.md). | Stage | Decides | | --- | --- | | Benchmark | A catalogue entry of either runner, and a version when it has several (`key@version`), labelled Official or Experiment. | +| Benchmark, a suite | A fixed selection of tasks from several benchmarks ([A suite](cli/run.md#a-suite)): its members are the Dataset step's choices, the Agent step offers the agents that fit every member chosen, and Review lists each member with who runs it, its backend and its share of the cap. | | Runner | **Nullius**, [the standard](standard.md#from-the-app), or **Harbor** with its pin ([Which Harbor](#which-harbor)). Only when both are supported. Default: Nullius | | Dataset | One or more; each dataset with each agent is a job of its own. Each runs all its tasks or one [task set](cli/task-sets.md), its benchmark's own lists (`subset_of`) included. **Start with**: all of it, or the tasks ticked, the rest left for the job's page ([`--start-with`](cli/run.md#plan-the-whole-start-with-some-of-it)). A benchmark option its datasets need is asked here, for the datasets it applies to. | | Agent (*Memory* on a memory benchmark) | The selected version's procedure is the first card, on by default; agents, memory Modules and checks run beside it, a job each, and it comes back when nothing is left. The procedure's own settings (LoCoMo's retrieval) are in its tab while it runs. A benchmark with [agents of its own](standard.md#a-benchmarks-own-agents) (OSWorld's) lists them first; several may be chosen, a job each. | diff --git a/docs/cli/pages.md b/docs/cli/pages.md index 3b7c12264..4eb861b72 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -16,7 +16,8 @@ Each page's command, or why there is none. | `/workspaces` | `nullius workspace list [--home DIR] [--json]` | | Settings popup (`/settings` opens it) | User `settings.json`, or the environment; `nullius paths` locates the file | | Settings, API access | `nullius access create`, `list`, `revoke` | -| `/benchmarks` | `nullius standard list` for standard entries; Harbor entries on the page | +| `/benchmarks` | `nullius standard list` for standard entries and suites; Harbor entries on the page | +| `/suites/` | `nullius standard list`; which agents run which members, `nullius standard fit KEY` | | `/agents`, `/modules` | `nullius standard list` includes agents, Modules and their proven ports | | A benchmark's *Task sets* | `nullius standard set list KEY` ([Task sets](task-sets.md)) | | `/benchmarks//tasks/` | `nullius standard units KEY --dataset D`; a set's, `set show KEY NAME` | @@ -26,6 +27,7 @@ Each page's command, or why there is none. | A benchmark's *Prove it* | `nullius standard prove KEY [--units FILE]` ([Prove](prove.md)) | | *Prove its ports* | `nullius standard conform KEY` ([Conform](conform.md)) | | `/run` | `nullius standard run` per dataset and choice, `--shard I/N` per machine ([Run](run.md)) | +| `/run`, a suite; a launch's *Stop suite*, *Run the rest* | None: `nullius standard run SUITE` is refused until it launches through the same queue ([A suite](run.md#a-suite)). The API starts one with the `reviewed` digest its check returns ([API](../api.md)) | | A job's *Run selected again*, *Run the rest*, *Run a set* | `nullius standard rerun JOB_DIR --unit ID`, `--unfinished`, `--set NAME` ([Run tasks again](rerun.md)) | ## While the app runs diff --git a/docs/cli/run.md b/docs/cli/run.md index b576d636b..f0df65271 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -175,6 +175,32 @@ HumanEval/12 | The builder | A recipe has no field for a list | | A named list | A [task set](task-sets.md) keeps one, frozen: `--set NAME` | +## A suite + +A suite is a fixed selection of tasks from several benchmarks, each at its pin (`nullius standard list` names them). +It runs from the builder: an ordinary run per member and participant, one after the other. `nullius standard run SUITE` is refused. + +| Rule | Detail | +| --- | --- | +| Members | One per benchmark dataset, the Dataset step's choices. A launch names the ones it takes. Members that take an agent and members that take a Module run in launches of their own | +| Tasks | The suite's, as the task set `-` of each benchmark, made at Run. Each run is bound to that list (`--set-hash`) and records the suite, its hash and its member (`--suite`) | +| As reviewed | Run takes the digest Review showed and refuses another. A run whose suite, list, benchmark or participant changed while it waited, or whose command is not the member, participant, model, limit, cap and backend reviewed, is refused at its turn: review the suite again | +| Agents | An agent runs when it fits every chosen member that takes one: `nullius standard fit SUITE [--dataset MEMBER ...] [--backend B]`. Untick the members it fails, or choose another | +| Checks | `nop` and `oracle` run on each member that declares them | +| A member that takes no agent | Runs its own procedure once, with the model | +| Backend | The suite's for a member, else the one an agent chosen needs, for every agent of that member, else the Where step's. Boat is refused for a member whose tasks boot VMs | +| Judge | Each member's own; the recipe's reaches only a member whose official judge is retired | +| Spending cap | One for the suite, shared by task count between the runs that pay, a paid judge's check included. Empty or 0: none. A run that cannot apply its share (no price for a model) is refused before it calls one | +| A run that fails | The next still starts | +| Stop suite | Stops the run under way; the runs waiting end `cancelled`. A Stop that cannot be saved stops nothing: stop it again | +| After a restart | A run whose plan cannot be read back holds the runs after it until none of its processes is left on this machine, then ends `failed`. One on a host is held until Stop suite | +| Run the rest | On the launch once it ended: a new launch of the runs that did not finish, each as reviewed. One at a time. Its cap is what the launch and its earlier rests left of the suite's, so they never spend more than it in all | +| Rerun, Delete | Refused until every run of the launch has ended; then each run is its own | +| Licences | One a member may need and Settings does not hold is named at Review; it is asked for as that member's tasks start | +| An older Nullius | Leaves a suite's runs alone | +| Where | This machine. The runs go into the suite's own workspace, `suite--` | +| Key | A suite named as a benchmark is left out, and `nullius standard list` says so | + ## Plan the whole, start with some of it `--start-with` plans the whole run and starts with some of it; the rest stay planned, run later in the same job by [`rerun`](rerun.md). diff --git a/docs/concepts.md b/docs/concepts.md index 9efbfb989..5bacfb6fc 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -14,7 +14,7 @@ The tasks and how each is scored; one folder in the catalogue, run on one or bot | List of units | The tasks a standard run takes by their ids, from a file ([`--units FILE`](cli/run.md#a-list-of-units)) | | Task set | A named, frozen list of a dataset's units that a run can take ([`--set NAME`](cli/task-sets.md)) | | Verifier | The benchmark's own scoring: tests, an exact answer, a judge model | -| Suite | A fixed, dated selection of tasks from several benchmarks, each at its pin | +| Suite | A fixed, dated selection of tasks from several benchmarks, each at its pin, run from the builder as one launch of ordinary runs, one after the other ([A suite](cli/run.md#a-suite)) | | Setup | Who answers: `original` (the published pipeline and models), `model` (that pipeline, your model), or your agent or Module | | Control | A run with no agent: `nop` does nothing, `oracle` applies the reference solution | @@ -82,6 +82,7 @@ Several web UIs and commands may use one profile (`NULLIUS_HOME`) at once, withi - Each runs folder (`RUNS_DIR`) is followed by one web UI; a second on the same folder refuses to start. Stopping a run goes through the web UI that follows it. - A job folder has one writer at a time: `standard run`, `standard rerun` or the run itself. +- A suite's runs start one after the other: each once the saved record of the run before it says it ended. A record that cannot be read holds the next run until it can. - Settings, Leaderboard weights, access tokens, proofs, task flags and task sets change under their own lock. Files are replaced whole, never half written. Supported: