From 31a7a4b00fe7a5820b021a6eb6463c7f0caba83d Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 3 Dec 2026 14:43:22 +0100 Subject: [PATCH] fix(runs): open a job of several agents by its folder name Closes #275 --- app/nullius/runs/cli.py | 33 ++++- app/nullius/runs/parse.py | 31 ++++- app/templates/runs/folder.html | 19 +++ app/templates/runs/job.html | 2 + app/tests/test_cli.py | 47 +++++++ app/ui_tests/test_two_agent_job_folder.py | 150 ++++++++++++++++++++++ app/web/runs.py | 7 +- app/web/shared.py | 32 +++-- app/web/traces.py | 21 ++- docs/cli/read-jobs.md | 2 +- 10 files changed, 314 insertions(+), 30 deletions(-) create mode 100644 app/templates/runs/folder.html create mode 100644 app/ui_tests/test_two_agent_job_folder.py diff --git a/app/nullius/runs/cli.py b/app/nullius/runs/cli.py index 8be097845..f1ba50755 100644 --- a/app/nullius/runs/cli.py +++ b/app/nullius/runs/cli.py @@ -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: @@ -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 @@ -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: " @@ -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// shows them") diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index ba952ac08..7a1c9acfc 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -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. diff --git a/app/templates/runs/folder.html b/app/templates/runs/folder.html new file mode 100644 index 000000000..603c28ae4 --- /dev/null +++ b/app/templates/runs/folder.html @@ -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 %}{% 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 %}{{ j.agent_label or j.job_id }}{% 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 %} diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 84b208450..eff309c31 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -62,6 +62,8 @@ {% endcall %} {% 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 %}{{ v.agent_label or v.job_id }}{% endfor %} {% if execution and execution.plan.recipe %}New run like this {% else %} None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value), encoding="utf-8") + + +def _job(job: Path, agents, trials, started="2026-01-01T00:00:00+00:00") -> None: + """A Harbor job folder: ``agents`` (name, model) in its config, ``trials`` (trial name, agent, model).""" + _write(job / "config.json", {"job_name": job.name, "agents": [{"name": a, "model_name": m} for a, m in agents], + "datasets": [{"name": "terminal-bench", "version": "2.0"}]}) + _write(job / "result.json", {"started_at": started, "stats": {"n_completed_trials": len(trials)}}) + for t, agent, model in trials: + _write(job / t / "result.json", {"task_name": "hello", "trial_name": t, "source": "terminal-bench", + "agent_info": {"name": agent, "model_info": {"name": model}}, + "verifier_result": {"rewards": {"reward": 1.0}}}) + + +class Folders(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-pair-")) + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + + def open(self, roots): + stack = ExitStack() + self.addCleanup(stack.close) + stack.enter_context(patch.object(web.shared, "WS_HOME", str(self.tmp / "workspaces"))) + stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) + web.shared.open_workspace(workspace.create(web.shared.WS_HOME, [str(r) for r in roots], "W")) + self.client = web.app.test_client() + + def links(self, url): + return re.findall(r'href="/job/([^"/?#]+)"', self.client.get(url).get_data(as_text=True)) + + +class TwoAgentJobFolder(Folders): + def setUp(self): + super().setUp() + _job(self.tmp / "jobs" / FOLDER, AGENTS, [(f"hello__{a}", a, m) for a, m in AGENTS]) + _job(self.tmp / "jobs" / "solo", AGENTS[1:], [("hello__solo", *AGENTS[1])]) + self.open([self.tmp / "jobs"]) + self.views = sorted(set(re.findall(r'href="/job/(pair~[^"/?#]+)[?"]', self.client.get("/runs").get_data(as_text=True)))) + + def test_the_views_open(self): + self.assertEqual(self.views, ["pair~claude-code-anthropic-claude-sonnet-4-5", "pair~codex-openai-gpt-5"]) + for v in self.views: + self.assertEqual(self.client.get(f"/job/{v}").status_code, 200, v) + + def test_the_folder_name_lists_its_views(self): + self.assertEqual(self.client.get(f"/job/{FOLDER}").status_code, 200) + self.assertEqual(self.links(f"/job/{FOLDER}"), self.views) # config order + + def test_a_trial_under_the_folder_name_redirects_to_its_view(self): + got = self.client.get(f"/trial/{FOLDER}/hello__codex?hide=x") + self.assertEqual(got.status_code, 302) + self.assertEqual(got.headers["Location"], "/trial/pair~codex-openai-gpt-5/hello__codex?hide=x") + self.assertEqual(self.client.get(f"/trial/{FOLDER}/nope").status_code, 404) + + def test_the_redirect_keeps_the_query_as_it_was(self): + query = f"workspace={web.shared.STATE['workspace'].name}&hide=a&hide=b+c&hide_span=&job_id=x&trial_name=y&_external=1" + got = self.client.get(f"/trial/{FOLDER}/hello__codex?{query}") + self.assertEqual(got.headers["Location"], f"/trial/pair~codex-openai-gpt-5/hello__codex?{query}") + + def test_an_unknown_folder_is_not_found(self): + self.assertEqual(self.client.get("/job/nope").status_code, 404) + self.assertEqual(self.client.get("/trial/nope/hello__codex").status_code, 404) + + def test_a_job_of_one_agent_opens_as_before(self): + got = self.client.get("/job/solo") + self.assertEqual(got.status_code, 200) + self.assertNotIn('id="views"', got.get_data(as_text=True)) + self.assertEqual(self.client.get("/trial/solo/hello__solo").status_code, 200) + + def test_a_trial_missing_from_a_job_of_one_folder_reads_that_folder_alone(self): + with patch.object(web.shared.workspace, "load_jobs", side_effect=AssertionError("the whole workspace read")): + self.assertEqual(self.client.get("/trial/solo/missing").status_code, 404) + self.assertEqual(self.client.get(f"/trial/{FOLDER}/missing").status_code, 404) + + def test_a_launch_planning_the_same_name_does_not_hide_the_folder(self): + with patch.object(web.shared, "run_on_page", return_value=object()): + self.assertEqual(self.links(f"/job/{FOLDER}"), self.views) + + +class Collisions(Folders): + def test_a_view_whose_id_another_job_holds_is_listed_without_a_link(self): + # a one-agent folder named like a view of "duo", in a root read first + _job(self.tmp / "r1" / "duo~alpha-m-1", [("other", "m/9")], [("x__o", "other", "m/9")]) + _job(self.tmp / "r2" / "duo", [("alpha", "m/1"), ("beta", "m/2")], [("a__t", "alpha", "m/1"), ("b__t", "beta", "m/2")]) + self.open([self.tmp / "r1", self.tmp / "r2"]) + self.assertIn("x__o", self.client.get("/job/duo~alpha-m-1").get_data(as_text=True)) + self.assertEqual(self.links("/job/duo"), ["duo~beta-m-2"]) + self.assertIn("duo~alpha-m-1", self.client.get("/job/duo").get_data(as_text=True)) + self.assertEqual(self.client.get("/trial/duo/a__t").status_code, 404) + self.assertEqual(self.client.get("/trial/duo/b__t").headers["Location"], "/trial/duo~beta-m-2/b__t") + + def test_the_same_folder_in_two_roots_links_only_the_first(self): + for root, started in (("r1", "2026-02-01T00:00:00+00:00"), ("r2", "2026-01-01T00:00:00+00:00")): + _job(self.tmp / root / "twin", [("alpha", "m/1"), ("beta", "m/2")], + [(f"{root}__a", "alpha", "m/1"), (f"{root}__b", "beta", "m/2")], started=started) + self.open([self.tmp / "r1", self.tmp / "r2"]) + self.assertEqual(self.links("/job/twin"), ["twin~alpha-m-1", "twin~beta-m-2"]) + self.assertEqual(self.client.get("/trial/twin/r1__a").status_code, 302) + self.assertEqual(self.client.get("/trial/twin/r2__a").status_code, 404) # its view's id opens r1's + + def test_a_newer_folder_holding_a_view_id_does_not_take_it_from_the_view(self): + # found after the view's folder, as the CLI finds it (test_cli: ..._opens_what_the_page_opens) + _job(self.tmp / "jobs" / "duo", [("alpha", "m/1"), ("beta", "m/2")], [("a__t", "alpha", "m/1"), ("b__t", "beta", "m/2")]) + _job(self.tmp / "jobs" / "duo~alpha-m-1", [("other", "m/9")], [("x__o", "other", "m/9")], started="2026-02-01T00:00:00+00:00") + self.open([self.tmp / "jobs"]) + self.assertEqual(self.links("/job/duo"), ["duo~alpha-m-1", "duo~beta-m-2"]) + self.assertEqual(self.client.get("/trial/duo/a__t").headers["Location"], "/trial/duo~alpha-m-1/a__t") + + def test_unassigned_trials_link_only_the_runs_of_their_own_folder(self): + for root in ("r1", "r2"): + _job(self.tmp / root / "twins", [("alpha", "m/1"), ("beta", "m/2")], + [(f"{root}__a", "alpha", "m/1"), (f"{root}__b", "beta", "m/2")] + ([("z__t", "zeta", "m/3")] if root == "r2" else [])) + self.open([self.tmp / "r1", self.tmp / "r2"]) + self.assertIn("z__t", self.client.get("/job/twins").get_data(as_text=True)) + self.assertEqual([x for x in self.links("/job/twins") if x.startswith("twins~")], []) # their ids open r1's + + def test_unassigned_trials_stay_reachable_beside_the_views(self): + _job(self.tmp / "jobs" / "duo", [("alpha", "m/1"), ("beta", "m/2")], + [("a__t", "alpha", "m/1"), ("b__t", "beta", "m/2"), ("z__t", "zeta", "m/3")]) + self.open([self.tmp / "jobs"]) + self.assertIn("z__t", self.client.get("/job/duo").get_data(as_text=True)) # the job of the unassigned trial + self.assertEqual([x for x in self.links("/job/duo") if x.startswith("duo~")], ["duo~alpha-m-1", "duo~beta-m-2"]) + self.assertEqual(self.client.get("/trial/duo/z__t").status_code, 200) + self.assertEqual(self.client.get("/trial/duo/a__t").headers["Location"], "/trial/duo~alpha-m-1/a__t") + + +if __name__ == "__main__": + unittest.main() diff --git a/app/web/runs.py b/app/web/runs.py index 4b4f27a77..4311d4a0f 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -466,7 +466,10 @@ def change_source(): @app.route("/job/", methods=["GET", "HEAD"]) def job(job_id): # every job, not the one alone: its Delete (_deletable) walks the workspace anyway, and one folder first costs more - j = shared._find_job(shared._jobs_for_request(), job_id) + jobs = shared._jobs_for_request() + j, views = shared._find_job(jobs, job_id), parse.views_of(jobs, job_id) + if j is None and views: # a job folder of several agents: its views, before any run planning that name + return render_template("runs/folder.html", folder=job_id, views=views) ex = shared.run_on_page(job_id, j) if j is None and ex is None and request.args.get("workspace"): # not to be written under that workspace's roots: a run a written sibling brought there, as its Runs page @@ -492,7 +495,7 @@ def job(job_id): waiting = waiting_of(j, (again or {}).get("trials") or []) analysis, versions = _analysis_of(j) return render_template("runs/job.html", job=j, live_board=board, view=_view_of(board, j, ex), - execution=ex, csrf=shared._csrf_token(), set_link=_set_link(j), set_saving=_set_saving(j), + execution=ex, csrf=shared._csrf_token(), views=parse.views_of(jobs, job_id, within=j.dir), set_link=_set_link(j), set_saving=_set_saving(j), judgement=judge.job_summary(j) if j.trials else None, control=feasibility.summary_of(j), ended=ended, own=own, deletable=_deletable(job_id, ex), trial_rows=attempts.grouped(j), pass_k=attempts.for_job(j), diff --git a/app/web/shared.py b/app/web/shared.py index f86257367..2debe8fd3 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -322,20 +322,30 @@ def _find_job(jobs, job_id): return next((j for j in jobs if j.job_id == job_id), None) -def _job_for_request(job_id): - """``_find_job(_jobs_for_request(), job_id)``, reading only the job's own - folder when the open workspace has exactly one of that name (a view of one - of a job's agents is ``~``). The whole workspace on any - doubt: another workspace asked for, no such folder, or several.""" +def _one_folder(job_id): + """The jobs ``split_agents`` makes of the open workspace's one folder that + can hold ``job_id`` (of that name, or of the name before its ``~``), read + alone, once a request. None on any doubt: another workspace asked for, the + whole workspace read already, no such folder, or several.""" ws = STATE["workspace"] - if ws is not None and request.args.get("workspace", "") in ("", ws.name) and "" not in request_memo("jobs"): + if ws is None or request.args.get("workspace", "") not in ("", ws.name) or "" in request_memo("jobs"): + return None + memo = request_memo("one_folder") + if job_id not in memo: names = {job_id, job_id.rsplit("~", 1)[0]} dirs = [d for d in parse.find_job_dirs(STATE["job_roots"]) if os.path.basename(d) in names] - if len(dirs) == 1: - job = _find_job(parse.split_agents([workspace.load_job(ws, dirs[0], runs=run_ends())[0]]), job_id) - if job is not None: - return job - return _find_job(_jobs_for_request(), job_id) + memo[job_id] = parse.split_agents([workspace.load_job(ws, dirs[0], runs=run_ends())[0]]) if len(dirs) == 1 else None + return memo[job_id] + + +def _job_for_request(job_id): + """``_find_job(_jobs_for_request(), job_id)``, reading only the job's own + folder when the open workspace has exactly one of that name (a view of one + of a job's agents is ``~``, ``_one_folder``). The whole + workspace on any doubt.""" + one = _one_folder(job_id) + job = _find_job(one, job_id) if one else None + return job if job is not None else _find_job(_jobs_for_request(), job_id) def _safe_dest(base: str, rel: str) -> str | None: diff --git a/app/web/traces.py b/app/web/traces.py index efc135141..10625618f 100644 --- a/app/web/traces.py +++ b/app/web/traces.py @@ -110,14 +110,21 @@ def _attempt_of(job, trial): return (_find_trial(job, m["trial"]) if m else None) or trial -def _trial_evidence(job_id, trial_name, tries=False): +def _trial_evidence(job_id, trial_name, tries=False, views=False): """Resolve URL identifiers through parsed runs, never as filesystem paths. ``tries``: an attempt's earlier try too, ``.try-N``: evidence to - read, never a trial to judge.""" - job = shared._job_for_request(job_id) - if job is None: - abort(404) - trial = _find_trial(job, trial_name) or (_find_try(job, trial_name) if tries else None) + read, never a trial to judge. ``views``: a job folder of several agents + redirects to the view that holds the trial (``parse.views_of``).""" + one = shared._one_folder(job_id) if views else None + mine = parse.views_of(one, job_id) if one else [] # job_id names that one folder of several agents + job = shared._find_job(one, job_id) if mine else shared._job_for_request(job_id) + trial = job and (_find_trial(job, trial_name) or (_find_try(job, trial_name) if tries else None)) + # a redirect is possible, or folders compete: whose each id is, over the whole workspace + if views and trial is None and (one is None or any(_find_trial(v, trial_name) for v, _ in mine)): + view = parse.view_of_trial(parse.views_of(shared._jobs_for_request(), job_id), trial_name) + if view is not None: # the route's own path, the query as it came + target = url_for(request.endpoint, **dict(request.view_args, job_id=view.job_id), workspace=None) + abort(redirect(target + ("?" + request.query_string.decode() if request.query_string else ""))) if trial is None: abort(404) return job, trial @@ -295,7 +302,7 @@ def trace_span_data(job_id, trial_name): @app.route("/trial//") def trial(job_id, trial_name): - j, t = _trial_evidence(job_id, trial_name, tries=True) + j, t = _trial_evidence(job_id, trial_name, tries=True, views=True) attempt = _attempt_of(j, t) # t itself, or the attempt's last try when t is an earlier one traj = trajectory.load(t.trajectory_path) if t.has_trajectory else None ok = traj is not None and not traj.error diff --git a/docs/cli/read-jobs.md b/docs/cli/read-jobs.md index 220bd8fc9..5fd58b049 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -39,7 +39,7 @@ nullius standard traces [--dry-run] | Command | Gives | | --- | --- | | `nullius runs list ...` | The runs, as `/runs` lists them | -| `nullius runs show ` | A job: trials, outcomes, counts, solve rates, mean scores and [best of K scores](../field-guide.md#best-of-k-scores) | +| `nullius runs show ` | A job: trials, outcomes, counts, solve rates, mean scores and [best of K scores](../field-guide.md#best-of-k-scores); a Harbor job folder of several agents: one run id per agent | | `nullius runs show ` | A trial: outcome, checks, usage, exception, steps. Tool arguments and observations stay on the page | | `nullius runs show --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 --calls` | The trial's Conversation by model call, as JSON, redacted |