Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 37 additions & 12 deletions app/nullius/compare/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
PYTHONPATH=app python3 -m nullius.compare.cli <root> <job a> <job b> [<job c>...]
PYTHONPATH=app python3 -m nullius.compare.cli <root> <job a> <job b> --matched
PYTHONPATH=app python3 -m nullius.compare.cli <root> <job a> <job b> --json
PYTHONPATH=app python3 -m nullius.compare.cli <root> <job a> <job b> --exclude flawed

``<root>`` is what the other CLIs take: a Harbor job directory, a parent of
several, or an imported tree; ``parse.load_all`` walks it. The jobs are
resolved and the cohort built by ``nullius.compare.comparison`` so ``--matched`` keeps exactly the
trials the page keeps (the intersection of exact dataset/task identifiers,
every recorded attempt), and the totals printed per column are the ``Job``
properties the page's summary table reads over that cohort.
properties the page's summary table reads over that cohort. ``--exclude`` sets aside the tasks the page's
Exclude does (``flags.flag_filter``).

The task rows below the totals are the page's. A development build (source or unknown runtime) is
compared when named, with a note on stderr.
Expand All @@ -25,8 +27,8 @@
import sys
from datetime import datetime

from nullius.compare import comparison
from nullius.runs import parse
from nullius.compare import comparison, flags
from nullius.runs import failure_analysis, parse

EXIT_OK = 0
EXIT_NOT_FOUND = 3
Expand All @@ -37,6 +39,7 @@
nullius compare jobs 2026-09-12__22-53-55 2026-09-13__09-10-11
nullius compare jobs 2026-09-12__22-53-55 2026-09-13__09-10-11 --matched
nullius compare jobs 2026-09-12__22-53-55 2026-09-13__09-10-11 --json
nullius compare jobs 2026-09-12__22-53-55 2026-09-13__09-10-11 --exclude flawed

exit codes:
0 done
Expand Down Expand Up @@ -99,7 +102,8 @@ def totals_of(job: parse.Job, cohort: str) -> dict:
"total_cost_usd": job.total_cost_usd,
}
if cohort == "whole":
# No truthful wall-clock interval exists for a subset of parallel trials.
# A subset of parallel trials has no planned trial count, nor a truthful wall-clock interval.
doc["mean_score_planned"] = job.mean_score_planned
doc["duration_min"] = job.duration_min
return doc

Expand All @@ -113,10 +117,10 @@ def column(job: parse.Job, cohort: str) -> dict:
}


def document(view: comparison.Comparison) -> dict:
def document(view: comparison.Comparison, filters: dict | None = None) -> dict:
"""The comparison as the page renders it: the columns with their totals
over the cohort, and the task rows."""
return {
over the cohort, and the task rows; with ``filters`` (``flags.flag_filter``), what they set aside."""
doc = {
"cohort": view.cohort,
"runs": [column(job, view.cohort) for job in view.jobs],
"shared_tasks": view.shared_tasks,
Expand All @@ -133,6 +137,12 @@ def document(view: comparison.Comparison) -> dict:
"scores": [t.score if t else None for t in row.trials],
} for row in view.tasks],
}
if filters:
doc["flags"] = {"exclude": filters["on"], "flagged": filters["flagged"],
"set_aside": sorted(key[1] for key in filters["set_aside"]),
"set_aside_trials": list(view.set_aside_trials),
"differ": filters["differ"], "unreadable": filters["unreadable"]}
return doc


def _cell(key: str, value) -> str:
Expand All @@ -151,8 +161,8 @@ def _cell(key: str, value) -> str:
return str(value)


def _print(view: comparison.Comparison) -> None:
doc = document(view)
def _print(view: comparison.Comparison, filters: dict | None = None) -> None:
doc = document(view, filters)
columns = doc["runs"]
width = max(12, *(len(c["job_id"]) for c in columns))
print(f"{view.cohort} runs: " + " vs ".join(c["job_id"] for c in columns))
Expand All @@ -161,6 +171,14 @@ def _print(view: comparison.Comparison) -> None:
+ ", ".join(str(n) for n in view.excluded_trials)
+ (" · repeated attempts " + ", ".join(str(n) for n in view.repeated_trials)
if any(view.repeated_trials) else ""))
if filters:
aside, differ = doc["flags"]["set_aside"], filters["differ"]
print(f" filtered ({', '.join(filters['on'])}): {len(aside)} task{'' if len(aside) == 1 else 's'} set aside "
"in every column · trials set aside " + ", ".join(str(n) for n in view.set_aside_trials))
if differ:
print(f" note: flags differ on {len(differ)} task{'' if len(differ) == 1 else 's'}: " + ", ".join(differ))
if filters["unreadable"]:
print(" note: flags unreadable: " + ", ".join(filters["unreadable"]))
if not view.datasets_match:
print(" note: the runs record different datasets; task rows are kept apart by dataset")
if not view.datasets_known:
Expand All @@ -173,6 +191,8 @@ def _print(view: comparison.Comparison) -> None:
if all(c["totals"]["mean_score"] is None for c in columns):
continue
rows.append((label, [_cell(key, c["totals"][key]) for c in columns]))
if any(c["totals"].get("mean_score_planned") is not None for c in columns):
rows.append(("Mean over planned", [_cell(key, c["totals"]["mean_score_planned"]) for c in columns]))
by = next((c["totals"]["parts_by"] for c in columns if c["totals"]["parts_by"]), "")
groups = dict.fromkeys(g["group"] for c in columns for g in c["totals"]["score_by_group"])
for g in groups:
Expand Down Expand Up @@ -220,6 +240,9 @@ def main(argv=None) -> int:
ap.add_argument("--matched", action="store_true",
help="the matched cohort: only the tasks every run attempted, by exact "
"dataset and task id (the page's cohort=matched); whole runs otherwise")
ap.add_argument("--exclude", action="append", default=[], choices=failure_analysis.KINDS, metavar="KIND",
help="set aside, in every column, the tasks a person flagged KIND (flawed or ambiguous) in any "
"of these runs, as the page's Exclude does; repeatable")
ap.add_argument("--json", action="store_true",
help="one JSON document: the columns with their totals and the task rows")
args = ap.parse_args(argv)
Expand All @@ -245,11 +268,13 @@ def main(argv=None) -> int:
return EXIT_FAILED
selected = comparison.resolve([comparison.RunRef("", job_id).value for job_id in ids],
{"": jobs}, {"": args.root})
view = comparison.build(selected, "matched" if args.matched else "whole")
filters = flags.flag_filter(selected, args.exclude) if args.exclude else None
view = comparison.build(selected, "matched" if args.matched else "whole",
filters["set_aside"] if filters else frozenset())
if args.json:
_emit(document(view))
_emit(document(view, filters))
else:
_print(view)
_print(view, filters)
return EXIT_OK


Expand Down
47 changes: 47 additions & 0 deletions app/nullius/compare/flags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""A comparison's flag filters, read from each run's failure analysis: what /compare's Exclude and ``nullius
compare --exclude`` set aside."""
from __future__ import annotations

from nullius.compare import comparison
from nullius.runs import failure_analysis


def flag_filter(selected, exclude=()) -> dict:
"""The flag filters of a comparison: one list of tasks set aside in every column, the union of the runs'
accepted flags of the kinds in ``exclude``, keyed as the comparison keys a task (`comparison.task_key`). A flag
counts only on the task version it names, and a task is set aside only when every column holding it ran the
same version; otherwise it stays, and is named in `differ` with the tasks the runs flag differently.
`flagged` counts each kind over all runs, for the switches; `unreadable` names runs whose file is broken."""
on = [k for k in failure_analysis.KINDS if k in exclude]
runs, unreadable = [], [] # per run: {task key: version}, {task key: kind}
for selection in selected:
job = selection.job
try:
analysis = failure_analysis.load(job.dir)
except failure_analysis.FailureAnalysisError:
analysis = failure_analysis.Analysis()
unreadable.append(job.job_id)
analysis = failure_analysis.for_job(job, analysis)
versions = failure_analysis.task_versions(job, analysis.flags) if analysis.flags else {}
tasks = {} # each task of the job to its comparison keys: one per identity it ran
for t in job.trials:
tasks.setdefault(failure_analysis.task_of(t), set()).add(comparison.task_key(selection, t))
kinds = {key: kind for kind in failure_analysis.KINDS
for task in analysis.set_aside([kind], versions) & set(tasks) for key in tasks[task]}
runs.append((selection, tasks, kinds, set().union(*tasks.values())))
flagged_keys = set().union(*(kinds for _, _, kinds, _ in runs))
# the versions every column holding a flagged task ran, read once per run for those tasks
ran = {}
for selection, tasks, _, _ in runs:
names = {task for task, keys in tasks.items() if keys & flagged_keys}
for task, version in failure_analysis.task_versions(selection.job, names).items():
for key in tasks[task]:
ran.setdefault(key, set()).add(version)
holders = {key: [r for r in runs if key in r[3]] for key in flagged_keys}
differ = sorted(key[1] for key in flagged_keys
if len(ran.get(key, set())) > 1 or len({kinds.get(key) for _, _, kinds, _ in holders[key]}) > 1)
set_aside = frozenset(key for key in flagged_keys if len(ran.get(key, set())) <= 1
and any(kinds.get(key) in on for _, _, kinds, _ in holders[key]))
return {"on": on, "flagged": {k: sum(1 for key in flagged_keys if any(kinds.get(key) == k for _, _, kinds, _ in runs))
for k in failure_analysis.KINDS},
"set_aside": set_aside, "differ": differ, "unreadable": unreadable}
15 changes: 9 additions & 6 deletions app/tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,10 +280,11 @@ def test_listing_opens_nothing_writes_nothing_and_prints_no_credential(self):

class CompareScoredRuns(unittest.TestCase):
"""A benchmark that scores (an F1) and gives no pass or fail: the CLI
carries the mean score, its breakdown and each task's score, as the
page's rows do, and counts nothing as solved."""
carries the mean score, over the planned trials too for whole runs, its
breakdown and each task's score, as the page's rows do, and counts
nothing as solved."""

def runs(self):
def runs(self, cohort="whole"):
from datetime import datetime, timedelta
from nullius.compare import comparison

Expand All @@ -302,12 +303,12 @@ def scored(task, groups):
def job(job_id, groups):
start = datetime(2026, 9, 1)
return parse.Job(job_id=job_id, dir="/unused", model_name="model", dataset="locomo10",
n_tasks=1, started_at=start, finished_at=start + timedelta(minutes=10),
n_tasks=2, started_at=start, finished_at=start + timedelta(minutes=10),
trials=[scored("conv-26", groups)], agent_name="reader")

a, b = job("a", {"1": (3.0, 4), "2": (1.0, 4)}), job("b", {"1": (2.0, 4), "2": (3.0, 4)})
return comparison.build(tuple(comparison.SelectedRun(comparison.RunRef("ws", j.job_id), j, "ws")
for j in (a, b)), "whole")
for j in (a, b)), cohort)

def test_the_document_carries_the_scores(self):
from nullius.compare import cli as compare_cli
Expand All @@ -318,14 +319,16 @@ def test_the_document_carries_the_scores(self):
[[("1", 0.75), ("2", 0.25)], [("1", 0.5), ("2", 0.75)]])
self.assertTrue(all(t["scored_only"] for t in totals))
self.assertEqual(doc["tasks"][0]["scores"], [0.5, 0.625])
self.assertEqual([t["mean_score_planned"] for t in totals], [0.25, 0.3125]) # two planned, one ran
self.assertNotIn("mean_score_planned", compare_cli.document(self.runs("matched"))["runs"][0]["totals"])

def test_the_table_prints_the_score_rows_and_nothing_solved(self):
from nullius.compare import cli as compare_cli
out = io.StringIO()
with redirect_stdout(out):
compare_cli._print(self.runs())
text = out.getvalue()
self.assertRegex(text, r"(?m)^ Mean score\s+0\.50\s+0\.62$")
self.assertRegex(text, r"(?m)^ Mean score\s+0\.50\s+0\.62\n Mean over planned\s+0\.25\s+0\.31\n Category 1\s")
self.assertRegex(text, r"(?m)^ Category 1\s+0\.75\s+0\.50$")
self.assertRegex(text, r"(?m)^ Category 2\s+0\.25\s+0\.75$")
self.assertRegex(text, r"(?m)^ Solved\s+—\s+—$")
Expand Down
17 changes: 17 additions & 0 deletions app/ui_tests/test_failure_analysis_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,23 @@ def test_a_task_flagged_in_any_run_is_set_aside_in_every_column(self):
self.assertEqual([sorted(t.task_base for t in j.trials) for j in view.jobs], [["t1", "t2", "t4"]] * 2)
self.assertEqual(view.set_aside_trials, (1, 1))
self.assertEqual(view.shared_tasks, 3) # the shared tasks left
# the command, for the same choice: the page's totals and rows; without it, none set aside
import io
from contextlib import redirect_stdout
from nullius.compare import cli as compare_cli

def run(*argv):
out = io.StringIO()
with redirect_stdout(out):
self.assertEqual(compare_cli.main([str(Path(self.temp.name) / "jobs"), "run-a", "run-b", *argv]), 0)
return out.getvalue()
doc = json.loads(run("--exclude", "ambiguous", "--json"))
self.assertEqual([(t["n_trials"], t["n_resolved"], t["adjusted_solve_rate"]) for t in (r["totals"] for r in doc["runs"])],
[(len(j.trials), j.n_resolved, j.adjusted_solve_rate) for j in view.jobs])
self.assertEqual([r["task"] for r in doc["tasks"]], [row.task for row in view.tasks])
self.assertEqual((doc["flags"]["set_aside"], doc["flags"]["set_aside_trials"], doc["flags"]["differ"]), (["t3"], [1, 1], ["t3"]))
self.assertIn("filtered (ambiguous): 1 task set aside in every column · trials set aside 1, 1", run("--exclude", "ambiguous"))
self.assertEqual([r["totals"]["n_trials"] for r in json.loads(run("--json"))["runs"]], [4, 4])

def test_the_sidebars_compare_link_does_not_carry_the_filters(self):
html = self.page(self.base + "&flawed=1")
Expand Down
42 changes: 3 additions & 39 deletions app/web/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,42 +738,6 @@ def _keep_flag_filters(endpoint, values):


def _flag_filter(selected) -> dict:
"""The flag filters of a comparison: one list of tasks set aside in every column, the union of the runs'
accepted flags of the kinds switched on, keyed as the comparison keys a task (`comparison.task_key`). A flag
counts only on the task version it names, and a task is set aside only when every column holding it ran the
same version; otherwise it stays, and is named in `differ` with the tasks the runs flag differently.
`flagged` counts each kind over all runs, for the switches; `unreadable` names runs whose file is broken."""
from nullius.compare import comparison
on = [k for k in failure_analysis.KINDS if request.args.get(k) == "1"]
runs, unreadable = [], [] # per run: {task key: version}, {task key: kind}
for selection in selected:
job = selection.job
try:
analysis = failure_analysis.load(job.dir)
except failure_analysis.FailureAnalysisError:
analysis = failure_analysis.Analysis()
unreadable.append(job.job_id)
analysis = failure_analysis.for_job(job, analysis)
versions = failure_analysis.task_versions(job, analysis.flags) if analysis.flags else {}
tasks = {} # each task of the job to its comparison keys: one per identity it ran
for t in job.trials:
tasks.setdefault(failure_analysis.task_of(t), set()).add(comparison.task_key(selection, t))
kinds = {key: kind for kind in failure_analysis.KINDS
for task in analysis.set_aside([kind], versions) & set(tasks) for key in tasks[task]}
runs.append((selection, tasks, kinds, set().union(*tasks.values())))
flagged_keys = set().union(*(kinds for _, _, kinds, _ in runs))
# the versions every column holding a flagged task ran, read once per run for those tasks
ran = {}
for selection, tasks, _, _ in runs:
names = {task for task, keys in tasks.items() if keys & flagged_keys}
for task, version in failure_analysis.task_versions(selection.job, names).items():
for key in tasks[task]:
ran.setdefault(key, set()).add(version)
holders = {key: [r for r in runs if key in r[3]] for key in flagged_keys}
differ = sorted(key[1] for key in flagged_keys
if len(ran.get(key, set())) > 1 or len({kinds.get(key) for _, _, kinds, _ in holders[key]}) > 1)
set_aside = frozenset(key for key in flagged_keys if len(ran.get(key, set())) <= 1
and any(kinds.get(key) in on for _, _, kinds, _ in holders[key]))
return {"on": on, "flagged": {k: sum(1 for key in flagged_keys if any(kinds.get(key) == k for _, _, kinds, _ in runs))
for k in failure_analysis.KINDS},
"set_aside": set_aside, "differ": differ, "unreadable": unreadable}
"""The flag filters of a comparison (``flags.flag_filter``), of the kinds this URL switches on."""
from nullius.compare import flags
return flags.flag_filter(selected, [k for k in failure_analysis.KINDS if request.args.get(k) == "1"])
2 changes: 1 addition & 1 deletion docs/cli/pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Each page's command, or why there is none.
| `/import`, `/use-path` | `nullius import <run tree> -o <job root> [--json]`; `--list` |
| `/leaderboard` | `nullius leaderboard <root>... [--json]`; `nullius remote leaderboard` against a served Nullius |
| `/scoring` | Profile `scoring.json` beside `settings.json`; `nullius paths` locates its configuration directory |
| `/compare` | `nullius compare <root> <id> <id>... [--matched] [--json]` |
| `/compare` | `nullius compare <root> <id> <id>... [--matched] [--exclude KIND]... [--json]` |
| `/workspaces/open/<name>` | `nullius serve <root>...`, `WORKSPACE=<name>` |
| `/workspaces` | `nullius workspace list [--home DIR] [--json]` |
| `/settings` | User `settings.json`, or the environment; `nullius paths` locates the file |
Expand Down
4 changes: 2 additions & 2 deletions docs/cli/read-jobs.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ nullius runs list <root>... [--json]
nullius runs show <root> <job id> [<trial>] [--json]
nullius runs show <root> <job id> <trial> --call N --request
nullius runs show <root> <job id> <trial> --calls
nullius compare <root> <job id> <job id>... [--matched] [--json]
nullius compare <root> <job id> <job id>... [--matched] [--exclude KIND]... [--json]
nullius workspace list [--home DIR] [--json]
nullius standard traces <dir> [--dry-run]
```
Expand Down Expand Up @@ -43,7 +43,7 @@ nullius standard traces <dir> [--dry-run]
| `nullius runs show <root> <job> <trial>` | A trial: outcome, checks, usage, exception, steps. Tool arguments and observations stay on the page |
| `nullius runs show <root> <job> <trial> --call N --request` | Call N's request as sent, rebuilt from the [exchange record](run.md#the-exchange-record); exit 4 when its hash differs |
| `nullius runs show <root> <job> <trial> --calls` | The trial's Conversation by model call, as JSON, redacted |
| `nullius compare <root> <id> <id>... [--matched]` | `/compare`'s cohort: whole, or matched on the tasks every job ran |
| `nullius compare <root> <id> <id>... [--matched] [--exclude KIND]...` | `/compare`'s cohort: whole, or matched on the tasks every job ran, without the tasks flagged KIND (`flawed`, `ambiguous`) |
| `nullius workspace list [--home DIR]` | The workspaces, as `/workspaces` lists them |

<div class="grid cards" markdown>
Expand Down