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
33 changes: 26 additions & 7 deletions app/nullius/runs/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,14 +261,15 @@ def _emit(doc) -> None:
sys.stdout.write("\n")


def _load(roots) -> list | None:
"""The jobs under *roots*, or None (said on stderr) when a root is missing."""
def _load(roots, newest_first=True) -> list | None:
"""The jobs under *roots*, or None (said on stderr) when a root is missing.
``newest_first``: ``parse.load_all``'s."""
missing = [r for r in roots if not os.path.isdir(r)]
if missing:
for r in missing:
print(f"no such directory: {r}", file=sys.stderr)
return None
return parse.load_all(roots)
return parse.load_all(roots, newest_first)


def _list(args) -> int:
Expand All @@ -287,12 +288,26 @@ def _list(args) -> int:


def _show(args) -> int:
jobs = _load([args.root])
jobs = _load([args.root], newest_first=False) # an id's job is the first found, as on the pages
if jobs is None:
return EXIT_NOT_FOUND
job = next((j for j in jobs if j.job_id == args.job_id), None)
views = parse.views_of(jobs, args.job_id) # a job folder of several agents, as its pages resolve it
if args.trial_name and views and not (job and any(t.trial_name == args.trial_name for t in job.trials)):
job = parse.view_of_trial(views, args.trial_name) or (job if args.call is not None or args.calls else None)
if job is None:
print(f"cannot resolve trial {args.trial_name!r} in job folder {args.job_id!r} under {args.root}",
file=sys.stderr)
return EXIT_NOT_FOUND
elif views and job is None:
if args.json:
_emit([dict(job_row(v), opens=opens) for v, opens in views])
else:
for v, opens in views:
print(v.job_id if opens else f"{v.job_id} (another job has this id)")
return EXIT_OK
if job is None:
known = ", ".join(j.job_id for j in jobs) or "none"
known = ", ".join(j.job_id for j in parse.newest(list(jobs))) or "none"
print(f"no job named {args.job_id!r} under {args.root} (jobs there: {known})",
file=sys.stderr)
return EXIT_NOT_FOUND
Expand All @@ -317,12 +332,16 @@ def _show(args) -> int:
else:
_print_trial(job, trial)
return EXIT_OK
# beside a job of its unassigned trials, its own folder's runs, as its page links them
agents = [v.job_id for v, opens in parse.views_of(jobs, job.job_id, within=job.dir) if opens]
if args.json:
_emit(job_detail(job))
_emit(dict(job_detail(job), views=agents) if agents else job_detail(job))
return EXIT_OK
row = job_row(job)
rate = lambda v: "—" if v is None else f"{100 * v:.0f}%"
print(f"{job.job_id}")
if agents:
print(f" runs of its agents: {', '.join(agents)}")
print(f" dataset {row['dataset'] or '—'} · model {row['model_label'] or '—'} · "
f"agent {row['agent'] or '—'} · {row['state']}")
print(f" {row['n_trials']} trial(s) of {row['n_planned']} planned: "
Expand Down Expand Up @@ -376,7 +395,7 @@ def main(argv=None) -> int:
sh = sub.add_parser("show", help="one job: its trials and their outcomes; or one trial",
epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
sh.add_argument("root", metavar="ROOT", help="the root the job is under")
sh.add_argument("job_id", metavar="JOB_ID", help="a job id, as `list` prints it")
sh.add_argument("job_id", metavar="JOB_ID", help="a job id, as `list` prints it; a job folder of several agents prints its ids")
sh.add_argument("trial_name", metavar="TRIAL", nargs="?", default="",
help="a trial name, as `show` on the job prints it: that trial's outcome, "
"checks, usage, exception and steps, as /trial/<job>/<trial> shows them")
Expand Down
31 changes: 29 additions & 2 deletions app/nullius/runs/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1525,9 +1525,36 @@ def split_agents(jobs: list) -> list:
return out


def load_all(roots) -> list[Job]:
def views_of(jobs, folder: str, within: str = "") -> list[tuple]:
"""The views ``split_agents`` made of each job folder named ``folder``, in
its config's order, as ``(view, opens)``: ``opens`` when the view's id
finds that view, the first of ``jobs`` (in the order the folders are found)
with it, and no other job. ``within``: that folder's alone."""
first = {}
for j in jobs:
first.setdefault(j.job_id, j)
real = os.path.realpath(within) if within else ""
return [(j, first[j.job_id] is j) for j in jobs if j.job_id.rpartition("~")[0] == folder
and os.path.basename(os.path.normpath(j.dir)) == folder and (not real or os.path.realpath(j.dir) == real)]


def view_of_trial(views, trial_name: str):
"""Of ``views_of``, the view that holds ``trial_name`` when exactly one
does and its id opens it; else None."""
held = [(v, opens) for v, opens in views if any(t.trial_name == trial_name for t in v.trials)]
return held[0][0] if len(held) == 1 and held[0][1] else None


def load_all(roots, newest_first: bool = True) -> list[Job]:
"""``newest_first`` False: in the order the folders are found, the order
in which, as on the pages, the first job of an id is the one it names."""
jobs = split_agents([parse_job(d) for d in find_job_dirs(roots)])
# Newest first. Compared as epoch numbers, not datetimes: a job whose
return newest(jobs) if newest_first else jobs


def newest(jobs: list) -> list:
"""``jobs`` sorted newest first, in place."""
# Compared as epoch numbers, not datetimes: a job whose
# result.json never got a started_at (a crashed run) yields None, and
# datetime.min is naive where parsed stamps are aware — mixing the two
# in one sort raises. -inf sorts the undated to the end instead.
Expand Down
19 changes: 19 additions & 0 deletions app/templates/runs/folder.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{% from '_tables.html' import table, cell %}
{% extends "base.html" %}
{% from '_page.html' import page_head %}
{#- A job folder of several agents (parse.views_of): one row per view, in its config's order; a link only where its id opens it. #}
{% block title %}{{ folder }} · Nullius{% endblock %}
{% block crumb %}/ {{ folder }}{% endblock %}
{% block head %}<script src="{{ url_for('static', filename='tables.js') }}"></script>{% endblock %}
{% macro view_tr(r) %}{% endmacro %}
{% block body %}
{{ page_head(folder, mono=true) }}
{% set cols = [dict(key='agent', label='Agent'), dict(key='model', label='Model'),
dict(key='trials', label='Trials', type='num'), dict(key='run', label='Run', width='expand')] %}
{% call(r, c) table('views', cols, views, view_tr, noun='runs', sort=false) %}{% set j, opens = r %}
{%- if c.key == 'agent' %}{% call cell(c) %}{% if opens %}<a href="{{ url_for('job', job_id=j.job_id) }}">{{ j.agent_label or j.job_id }}</a>{% else %}{{ j.agent_label or j.job_id }}{% endif %}{% endcall %}
{%- elif c.key == 'model' %}{% call cell(c, class='mono') %}{{ j.model_label }}{% endcall %}
{%- elif c.key == 'trials' %}{% call cell(c) %}{{ j.trials|length }}{% endcall %}
{%- else %}{% call cell(c, class='mono small') %}{{ j.job_id }}{% endcall %}{% endif %}
{%- endcall %}
{% endblock %}
2 changes: 2 additions & 0 deletions app/templates/runs/job.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@
{% endcall %}
</div>{% endset %}
{% set actions %}
{#- of a job folder of several agents, the runs of its agents (parse.views_of) beside its unassigned trials -#}
{% for v, opens in views or [] if opens %}<a class="btn sm ghost" href="{{ url_for('job', job_id=v.job_id) }}" title="{{ v.job_id }}">{{ v.agent_label or v.job_id }}</a>{% endfor %}
{% if execution and execution.plan.recipe %}<a class="btn sm ghost" href="{{ url_for('new_run', run=job.job_id, workspace=request.args.get('workspace') or none) }}"
title="Open the run builder with the recipe this run was started from, every setting as it was; Run gives it a new name">New run like this</a>
{% else %}<a class="btn sm ghost" href="{{ url_for('new_run', like=job.job_id, workspace=request.args.get('workspace') or none) }}"
Expand Down
47 changes: 47 additions & 0 deletions app/tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,53 @@ def test_a_standard_job_s_document_holds_what_identifies_it_and_both_means_and_t
self.assertIn(" mean score 0.50 over the trials scored · 0.38 over the 4 planned\n",
self.sh("runs.cli", "show", self.tmp, "scored").stdout)

def test_a_job_folder_of_several_agents_gives_its_views_as_its_page_does(self):
job = os.path.join(self.tmp, "pair")
for path, doc in [("config.json", {"agents": [{"name": "a", "model_name": "m/1"}, {"name": "b", "model_name": "m/2"}]}),
("result.json", {})] + [
(f"t__{x}/result.json", {"task_name": "t", "trial_name": f"t__{x}", "agent_info": {"name": x}}) for x in "ab"]:
os.makedirs(os.path.dirname(os.path.join(job, path)), exist_ok=True)
with open(os.path.join(job, path), "w", encoding="utf-8") as fh:
json.dump(doc, fh)
out = self.sh("runs.cli", "show", self.tmp, "pair")
self.assertEqual((out.returncode, out.stdout), (0, "pair~a-m-1\npair~b-m-2\n"), out.stderr)
out = self.sh("runs.cli", "show", self.tmp, "pair", "t__b")
self.assertEqual(out.returncode, 0, out.stderr)
self.assertTrue(out.stdout.startswith("pair~b-m-2/t__b\n"), out.stdout)
# a trial of an agent its config does not list: the folder's own job, beside its agents' runs
os.makedirs(os.path.join(job, "t__z"))
with open(os.path.join(job, "t__z", "result.json"), "w", encoding="utf-8") as fh:
json.dump({"task_name": "t", "trial_name": "t__z", "agent_info": {"name": "z"}}, fh)
out = self.sh("runs.cli", "show", self.tmp, "pair")
self.assertTrue(out.stdout.startswith("pair\n runs of its agents: pair~a-m-1, pair~b-m-2\n"), out.stdout)
self.assertTrue(self.sh("runs.cli", "show", self.tmp, "pair", "t__z").stdout.startswith("pair/t__z\n"))
self.assertTrue(self.sh("runs.cli", "show", self.tmp, "pair", "t__a").stdout.startswith("pair~a-m-1/t__a\n"))

def _harbor(self, name, agents, trials, started):
for path, doc in [("config.json", {"agents": [{"name": a, "model_name": m} for a, m in agents]}),
("result.json", {"started_at": started})] + [
(f"{t}/result.json", {"task_name": "t", "trial_name": t, "agent_info": {"name": a}}) for t, a in trials]:
os.makedirs(os.path.dirname(os.path.join(self.tmp, name, path)), exist_ok=True)
with open(os.path.join(self.tmp, name, path), "w", encoding="utf-8") as fh:
json.dump(doc, fh)

def test_a_view_id_a_newer_folder_also_holds_opens_what_the_page_opens(self):
# the page takes the first job of an id in the order the folders are found, not the newest
self._harbor("duo", [("a", "m/1"), ("b", "m/2")], [("a__t", "a"), ("b__t", "b")], "2026-01-01T00:00:00+00:00")
self._harbor("duo~a-m-1", [("x", "m/9")], [("x__t", "x")], "2026-02-01T00:00:00+00:00")
out = self.sh("runs.cli", "show", self.tmp, "duo")
self.assertEqual((out.returncode, out.stdout), (0, "duo~a-m-1\nduo~b-m-2\n"), out.stderr)
out = self.sh("runs.cli", "show", self.tmp, "duo", "a__t")
self.assertEqual(out.returncode, 0, out.stderr)
self.assertTrue(out.stdout.startswith("duo~a-m-1/a__t\n"), out.stdout)
self.assertEqual(self.sh("runs.cli", "list", self.tmp).stdout.split(), ["duo~a-m-1", "duo~a-m-1", "duo~b-m-2"])

def test_a_trial_no_run_of_the_folder_opens_is_named_with_the_folder(self):
self._harbor("duo", [("a", "m/1"), ("b", "m/2")], [("a__t", "a"), ("b__t", "b")], "2026-01-01T00:00:00+00:00")
out = self.sh("runs.cli", "show", self.tmp, "duo", "nope")
self.assertEqual(out.returncode, 3)
self.assertTrue(out.stderr.startswith("cannot resolve trial 'nope' in job folder 'duo' under "), out.stderr)


# -------------------------------------------------------
# The trial view, the comparison and the workspace list. Same table, same rules:
Expand Down
Loading
Loading