diff --git a/app/nullius/client.py b/app/nullius/client.py index e6916f9b9..033bf0ba9 100644 --- a/app/nullius/client.py +++ b/app/nullius/client.py @@ -194,9 +194,9 @@ def start(self, recipe: Union[dict, str], where=None, name: Optional[str] = None def runs(self) -> list: return self.request("GET", "/runs") - def run(self, run_id: str, since: int = 0) -> dict: + def run(self, run_id: str, since: int = 0, job: Optional[str] = None) -> dict: """A run's state and stages, with its log lines from ``since`` on.""" - return self.request("GET", self._q("runs", run_id), since=since or None) + return self.request("GET", self._q("runs", run_id), since=since or None, job=job) def stop(self, run_id: str) -> dict: return self.request("POST", self._q("runs", run_id, "stop")) @@ -304,6 +304,7 @@ def main(argv=None) -> int: p = sub.add_parser("status", help="one run: its state, stages and log") p.add_argument("run_id") p.add_argument("--since", type=int, default=0) + p.add_argument("--job", help="show stages and counts for this job of the run") for name, text in (("stop", "stop a run"), ("continue", "answer a paused run: go on")): p = sub.add_parser(name, help=text) p.add_argument("run_id") @@ -337,7 +338,7 @@ def main(argv=None) -> int: "judge": lambda: (nx.judge(a.job_id, a.trial, a.lane, a.workspace) if a.trial else nx.judge_job(a.job_id, a.lane, confirm=a.yes, workspace=a.workspace)), "check": lambda: nx.check(_recipe_arg(a.recipe), a.where), - "status": lambda: nx.run(a.run_id, a.since), "stop": lambda: nx.stop(a.run_id), + "status": lambda: nx.run(a.run_id, a.since, job=a.job), "stop": lambda: nx.stop(a.run_id), "continue": lambda: nx.continue_(a.run_id)}[a.cmd]() except ApiError as e: print(e, file=sys.stderr) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 0c6c6c7b8..bc8a05888 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -667,21 +667,40 @@ def never_ran(self, job_id: str) -> bool: part = self.part_for(job_id) return self.state in ENDED and part in ids and part != self.launched and part not in self.ends and ids.index(part) >= self.part - def summary(self) -> dict: + def summary(self, job_id: Optional[str] = None) -> dict: return {"id": self.id, "name": self.plan.name, "state": self.state, "step": self.step, "host": self.plan.host.label if self.plan.host else "this machine", "exit_code": self.exit_code, "error": self.error, "started": self.started, "finished": self.finished, "jobs": self.jobs, "job_ids": [str(j.get("name")) for j in self.plan.jobs], "lines": len(self.lines), "question": self.question, - "progress": self.progress, "stages": self.stages()} + "progress": self.progress, "stages": self.stages(job_id)} - def stages(self) -> dict: + def stages(self, job_id: Optional[str] = None) -> dict: """The stages said so far, folded for the page (``progress.fold``). Once the run has ended, no stage is running or waiting any more. - Counts remain exactly what the progress events reported.""" + With a job, read its own progress (also mirrored from a host), beside + the shared host preparation. Never borrow another part's stages when + the job has not written progress yet. Counts are the events' own.""" with self._lock: events = list(self.events) + state = self.state + if job_id is not None: + if job_id not in {str(j.get("name")) for j in self.plan.jobs}: + return progress.fold([]) + own = progress.read(os.path.join(self.jobs, job_id)) + # Old single-job runners may say progress only on stderr. + if own or len(self.plan.jobs) != 1 or len(self.plan.steps()) != 1: + shared = {"connect", "uv", "tasks", "app", "harbor"} + events = [e for e in events if e.get("stage") in shared or + (e.get("stage") == "plan" and set(str(e.get("stages", "")).split(",")) <= shared)] + own + end = self.job_state(job_id) + state = end[0] if end else state got = progress.fold(events) - if self.state in ("done", "failed", "stopped"): - got["stages"] = [dict(r, state="done" if self.state == "done" else "failed") if r["state"] == "running" else r for r in got["stages"] if r["state"] != "waiting"] + if state in ("done", "failed", "stopped"): + def finish(rows): + return [dict(r, state="done" if state == "done" else "failed") if r["state"] == "running" else r + for r in rows if r["state"] != "waiting"] + got["stages"] = finish(got["stages"]) + if got["units"] and "environments" in got["units"]: + got["units"]["environments"] = finish(got["units"]["environments"]) got["current"] = None return got diff --git a/app/nullius/progress.py b/app/nullius/progress.py index 3337a471c..bbd9328cd 100644 --- a/app/nullius/progress.py +++ b/app/nullius/progress.py @@ -222,7 +222,8 @@ def fold(events: Iterable[dict]) -> dict: when it started), ``done`` or ``cached`` with its ``seconds``, or ``failed`` with its detail. A planned stage still waiting when a later one has started was not needed (a benchmark with nothing to download), - and is left out. + and is left out. Environments first built during units belong to + ``units.environments``, not to later steps in the strip. - ``units``: ``n`` to run, the ``noun``, how many ended and how: passed, failed, scored, errors; ``running`` the ones started and not ended. A run of several parts counts every part's: ``n`` grows as each begins. @@ -239,6 +240,7 @@ def fold(events: Iterable[dict]) -> dict: parts, part = {}, None ended, detail = None, None started_units = 0 + environments = set() earlier: dict = {} # by stage, the seconds a later run of the same job adds to for ev in events: st = ev.get("stage") @@ -277,6 +279,8 @@ def fold(events: Iterable[dict]) -> dict: ended, detail = st, ev.get("detail") continue key = _key(ev) + if st == "environment" and units is not None and stages.get(key, {}).get("state", "waiting") == "waiting": + environments.add(key) if key not in stages: # a planned stage, now said with what it is of: the plan's entry becomes it if key != st and st in stages and stages[st]["state"] == "waiting": @@ -321,6 +325,9 @@ def fold(events: Iterable[dict]) -> dict: if ended: # a run that ended has nothing running, nor anything still to come rows = [dict(r, state="failed" if ended == "refused" else "done") if r["state"] == "running" else r for r in rows if r["state"] != "waiting"] + if environments and units is not None: + units["environments"] = [r for r in rows if r["key"] in environments] + rows = [r for r in rows if r["key"] not in environments] current = next((r for r in rows if r["state"] == "running"), None) if parts: parts[part] = units diff --git a/app/templates/runs/_execution.html b/app/templates/runs/_execution.html index c4a424bd8..4a3f6d664 100644 --- a/app/templates/runs/_execution.html +++ b/app/templates/runs/_execution.html @@ -5,9 +5,9 @@ {# `own`: this job's own (state, finished) when the run is of several agents - an arm that answered everything is done though a later arm failed; the run's state is said beside it. #} {# `deletable`: the key of this job's launch when the Runs page offers its Delete (web/runs._deletable). #} -{% macro execution_strip(ex, csrf, waiting=false, own=none, deletable=false) %} +{% macro execution_strip(ex, csrf, waiting=false, own=none, deletable=false, job_id=none) %} {% set shown = own[0] if own else ex.state %} -
{{ shown }}{% if not own and ex.step and ex.state in ('preparing', 'running') %} · {{ ex.step }}{% endif %} @@ -24,7 +24,7 @@
{# what the run is doing: a stepper of the stages before its first unit (a check when done, its number until then), then its units (nullius/progress.py) #} - {% set sp = ex.stages() %} + {% set sp = ex.stages(job_id) %}
    {% for st in sp.stages %}
  1. {{ st.label }} @@ -32,6 +32,10 @@ {%- if st.state in ('running', 'failed') and st.detail and st.detail != sp.detail %}{{ st.detail }}{% endif %}
  2. {% endfor %}
{% if sp.units %}{% set u = sp.units %}{{ u.done }} / {{ u.n if u.n is not none else '?' }} {{ u.noun }}{% for k in ('passed', 'failed', 'scored', 'errors') if u[k] %} · {{ u[k] }} {{ 'error' + ('' if u[k] == 1 else 's') if k == 'errors' else k }}{% endfor %}{% if u.running %} · {{ u.running }} running{% endif %}{% endif %}
+
+ Environments within Units +
    {% if sp.units %}{% for st in sp.units.environments %}
  • {{ st.label }} · {{ st.state }}{% if st.get('seconds') is not none %} · {{ st.seconds|secs }}{% endif %}{% if st.detail %} · {{ st.detail }}{% endif %}
  • {% endfor %}{% endif %}
+
{% if sp.ended == 'refused' %}Refused before its first unit: {{ sp.detail }}{% endif %}
{# a part downloading: its file, how much of it, as a bar #} @@ -72,6 +76,13 @@ refused.hidden = sp.ended !== 'refused'; refused.textContent = sp.ended === 'refused' ? 'Refused before its first unit: ' + sp.detail : ''; const u = sp.units; units.hidden = !u; + const environments = document.getElementById('execution-environments'), builds = u?.environments || []; + environments.hidden = !builds.length; + environments.querySelector('ul').replaceChildren(...builds.map(st => { + const li = el('li', '', st.label + ' · ' + st.state + (st.seconds != null ? ' · ' + secs(st.seconds) : '') + (st.detail ? ' · ' + st.detail : '')); + li.title = st.full || st.label; + return li; + })); if (u) { const bar = el('progress'); if (u.n != null) { bar.max = u.n || 1; bar.value = u.done; } const txt = el('span', 'small'); txt.append(el('b', '', u.done + ' / ' + (u.n != null ? u.n : '?')), ' ' + u.noun); @@ -83,7 +94,7 @@ const tick = async () => { let retry = true; try { - const r = await nulliusFetch(box.dataset.run + '?since=' + since, {cache: 'no-store'}); if (!r.ok) return; + const r = await nulliusFetch(box.dataset.run + '?since=' + since + (box.dataset.job ? '&job=' + encodeURIComponent(box.dataset.job) : ''), {cache: 'no-store'}); if (!r.ok) return; const j = await r.json(); if (j.log.length) { pre.textContent += j.log.join('\n') + '\n'; pre.scrollTop = pre.scrollHeight; since = j.lines; } const bar = document.getElementById('execution-progress'), p = j.progress; diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 019e89a7b..a96f24769 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -128,7 +128,7 @@ {% if execution %}
-{{ execution_strip(execution, csrf, own=own if execution.plan.steps()|length > 1 else none, deletable=deletable) }} +{{ execution_strip(execution, csrf, job_id=job.job_id, own=own if execution.plan.steps()|length > 1 else none, deletable=deletable) }}
{% endif %}
diff --git a/app/templates/runs/preparing.html b/app/templates/runs/preparing.html index 60e5016cc..8bae66ff9 100644 --- a/app/templates/runs/preparing.html +++ b/app/templates/runs/preparing.html @@ -13,7 +13,7 @@
-{{ execution_strip(ex, csrf, waiting=true, own=own, deletable=deletable) }} +{{ execution_strip(ex, csrf, job_id=job_id, waiting=true, own=own, deletable=deletable) }}
diff --git a/app/tests/test_client.py b/app/tests/test_client.py index ead6bf525..aac633165 100644 --- a/app/tests/test_client.py +++ b/app/tests/test_client.py @@ -115,6 +115,7 @@ def test_every_call_carries_the_token_and_asks_its_route(self): (lambda: self.nx.runs(), "GET", "/runs", "", None), (lambda: self.nx.run("r1"), "GET", "/runs/r1", "", None), (lambda: self.nx.run("r1", since=40), "GET", "/runs/r1", "since=40", None), + (lambda: self.nx.run("r1", job="r1-nop"), "GET", "/runs/r1", "job=r1-nop", None), (lambda: self.nx.stop("r1"), "POST", "/runs/r1/stop", "", None), (lambda: self.nx.continue_("r1"), "POST", "/runs/r1/continue", "", None)): self.answer(method, path, {"ok": path}) @@ -261,6 +262,10 @@ def test_a_read_prints_the_server_s_document(self): self.assertEqual(json.loads(self.remote("job", "a", "t")[1]), {"trial": {"trial_name": "t"}}) self.assertEqual(self.remote("compare", "a", "b", "--matched")[0], 0) self.assertEqual(self.last()["query"], "job=a&job=b&matched=1") + self.answer("GET", "/runs/r1", {"stages": {"units": {"n": 8}}}) + code, out, err = self.remote("status", "r1", "--job", "r1-nop") + self.assertEqual((code, json.loads(out)["stages"]["units"]["n"], err), (0, 8, "")) + self.assertEqual(self.last()["query"], "job=r1-nop") self.answer("GET", "/leaderboard", {"rows": []}) self.assertEqual((json.loads(self.remote("leaderboard")[1]), self.last()["query"]), ({"rows": []}, "")) self.remote("leaderboard", "--workspace", "nightly") diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index 353118c2f..8498b6f71 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -265,6 +265,43 @@ def test_a_last_part_failing_is_a_failed_run_with_no_question(self): ex = self.wait(execution.Execution(execution.Plan(name="r", script="", parts=parts), root=str(self.tmp)).start()) self.assertEqual((ex.state, ex.exit_code, ex.question), ("failed", 4, None)) + def test_job_stages_count_only_its_units_and_install_after_restart(self): + from nullius import progress + names = ["nop", "oracle", "codex", "goose"] + plan = execution.Plan(name="four", script="", runner="standard", + parts=[{"id": n, "label": n, "script": "true"} for n in names], + jobs=[{"name": "four-" + n, "agent": n} for n in names]) + ex = execution.Execution(plan, root=str(self.tmp)) + ex.log(progress.line("plan", stages="connect,app")) + ex.log(progress.line("connect", "done", seconds=1)) + ex.log(progress.line("app", "cached")) + # A queued job has only shared preparation, not the current part's units. + for name in names: + with self.subTest(name=name): + self.assertIsNone(ex.stages("four-" + name)["units"]) + reporter = progress.Reporter(os.path.join(ex.jobs, "four-" + name)) + events = [("plan", None, {"stages": "image,install,units"}), ("image", "cached", {})] + if name in ("codex", "goose"): + events.append(("install", "cached", {"agent": name})) + events += [("units", "start", {"n": 8, "noun": "tasks"})] + events += [("unit", "done", {"outcome": "passed"}) for _ in range(8)] + for stage, state, fields in events: + reporter.emit(stage, state, **fields) + ex.log(progress.line(stage, state, **fields)) + ex.ends[name] = {"rc": 0, "at": time.time(), "label": name} + ex.state, ex.part, ex.launched = "failed", 4, "goose" + ex._save() + back = execution.Execution(plan, root=str(self.tmp), record=json.loads(Path(ex.dir, "run.json").read_text())) + self.assertEqual(back.stages()["units"]["n"], 32) + for name in names: + got = back.stages("four-" + name) + self.assertEqual((got["units"]["n"], got["units"]["done"]), (8, 8)) + self.assertEqual([s["label"] for s in got["stages"] if s["stage"] == "install"], + ["Install " + name] if name in ("codex", "goose") else []) + self.assertEqual(got["stages"][-1]["state"], "done") # another part's failure does not fail this job + self.assertEqual([s["key"] for s in got["stages"]][:2], ["connect", "app"]) + self.assertIsNone(back.stages("../outside")["units"]) + def test_each_agent_s_job_ends_as_its_own_part_did(self): """An agent that finished is done though a later one failed: its page and its row say its own result, and the run's error names the part.""" diff --git a/app/tests/test_progress.py b/app/tests/test_progress.py index 222733865..1b90dc112 100644 --- a/app/tests/test_progress.py +++ b/app/tests/test_progress.py @@ -167,6 +167,26 @@ def test_a_later_run_of_a_job_counts_each_task_once(self): u, row = got["units"], next(s for s in got["stages"] if s["key"] == "units") self.assertEqual((u["n"], u["done"], u["passed"], u["failed"], u["errors"], u["running"], row["seconds"]), (3, 3, 2, 1, 0, 0, 2.0)) + def test_environments_built_during_units_belong_to_units(self): + events = [ev("plan", stages="image,units"), ev("image", "cached"), + ev("environment", "cached", name="prepared"), ev("units", "start", n=8), + ev("unit", "start", unit="a"), ev("environment", "start", name="task-a"), + ev("environment", "progress", name="task-a", bytes=10, total=20)] + got = progress.fold(events) + self.assertEqual([s["key"] for s in got["stages"]], ["image", "units", "environment:prepared"]) + self.assertEqual(got["current"], "units") + reused = progress.fold(events + [ev("environment", "cached", name="prepared")]) + self.assertIn("environment:prepared", [s["key"] for s in reused["stages"]]) + self.assertNotIn("environment:prepared", [s["key"] for s in reused["units"]["environments"]]) + build = got["units"]["environments"][0] + self.assertEqual((build["key"], build["state"], build["bytes"]), ("environment:task-a", "running", 10)) + got = progress.fold(events + [ev("environment", "failed", name="task-a", seconds=2, detail="build failed"), + ev("environment", "cached", name="task-b"), ev("units", "done"), ev("done")]) + self.assertEqual([(s["key"], s["state"]) for s in got["units"]["environments"]], + [("environment:task-a", "failed"), ("environment:task-b", "cached")]) + self.assertEqual(got["units"]["environments"][0]["detail"], "build failed") + self.assertEqual(got["units"]["n"], 8) + def test_a_download_shows_its_bytes(self): got = progress.fold([ev("dataset", "start", 1.0), ev("dataset", "progress", bytes=5_000_000, total=9_000_000)]) self.assertEqual((got["stages"][0]["bytes"], got["stages"][0]["total"]), (5_000_000, 9_000_000)) diff --git a/app/ui_tests/test_api.py b/app/ui_tests/test_api.py index 123a74d98..f729c0566 100644 --- a/app/ui_tests/test_api.py +++ b/app/ui_tests/test_api.py @@ -663,6 +663,15 @@ def test_a_run_is_followed_listed_and_stopped_by_its_id(self): self.assertIn("key=21", "\n".join(got["log"])) # the run had its provider's key self.assertNotIn("sk-testkey-0123456789", json.dumps(got)) # and its log does not self.assertEqual(self.get(f"/runs/{run_id}?since={got['lines']}").json["log"], []) + from nullius import progress + ex = execution.EXECUTIONS[run_id] + reporter = progress.Reporter(os.path.join(ex.jobs, got["job_ids"][0])) + reporter.emit("units", "start", n=8, noun="tasks") + ex.events = [progress.parse(progress.line("units", "start", n=32))] + scoped = self.get(f"/runs/{run_id}?job={got['job_ids'][0]}") + self.assertEqual(scoped.json["stages"]["units"]["n"], 8) + self.assertEqual(self.get(f"/runs/{run_id}").json["stages"]["units"]["n"], 32) + self.assertEqual(self.get(f"/runs/{run_id}?job=unknown").status_code, 404) self.assertEqual([x["id"] for x in self.get("/runs").json], [run_id]) self.assertEqual(self.get("/runs/nope").status_code, 404) for verb in ("stop", "continue"): diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 760907897..c1ecd10dd 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -255,6 +255,46 @@ def test_the_run_s_page_shows_its_stages_and_its_units(self): self.assertIn('aria-current="step">