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
7 changes: 4 additions & 3 deletions app/nullius/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down
31 changes: 25 additions & 6 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 8 additions & 1 deletion app/nullius/progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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")
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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
Expand Down
19 changes: 15 additions & 4 deletions app/templates/runs/_execution.html
Original file line number Diff line number Diff line change
Expand Up @@ -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 %}
<section class="execution" id="execution" data-run="{{ url_for('run_status', run_id=ex.id) }}" data-stop="{{ url_for('run_stop', run_id=ex.id) }}" data-continue="{{ url_for('run_continue', run_id=ex.id) }}"
<section class="execution" id="execution" data-run="{{ url_for('run_status', run_id=ex.id) }}" data-job="{{ job_id or '' }}" data-stop="{{ url_for('run_stop', run_id=ex.id) }}" data-continue="{{ url_for('run_continue', run_id=ex.id) }}"
data-live="{{ 'yes' if ex.state in ('preparing', 'running') else 'no' }}" data-waiting="{{ 'yes' if waiting else 'no' }}" data-csrf="{{ csrf }}" data-own="{{ own[0] if own else '' }}">
<div class="execution-line">
<span class="chip {{ 'st-runs' if shown == 'done' else 'st-blocked' if shown == 'failed' else 'st-lane' }}" id="execution-state">{{ shown }}{% if not own and ex.step and ex.state in ('preparing', 'running') %} · {{ ex.step }}{% endif %}</span>
Expand All @@ -24,14 +24,18 @@
<button type="button" class="btn sm" id="execution-continue">Continue</button>
</div>
{# 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) %}
<div class="execution-stages" id="execution-stages"{% if not sp.stages and not sp.units %} hidden{% endif %}>
<ol class="xs-list" id="execution-stage-list">{% for st in sp.stages %}
<li class="xs {{ st.state }}"{% if st.detail %} title="{{ st.detail }}"{% endif %}{% if st.state == 'running' %} aria-current="step"{% endif %}><i aria-hidden="true">{{ '' if st.state in ('done', 'cached') else '✕' if st.state == 'failed' else loop.index }}</i><span class="xs-label"{% if st.full %} title="{{ st.full }}"{% endif %}>{{ st.label }}</span>
{%- if st.state == 'cached' %}<span class="xs-time">cached</span>{% elif st.get('seconds') is not none and st.state in ('done', 'failed') %}<span class="xs-time">{{ st.seconds|secs }}</span>{% endif %}
{%- if st.state in ('running', 'failed') and st.detail and st.detail != sp.detail %}<span class="xs-detail">{{ st.detail }}</span>{% endif %}</li>{% endfor %}
</ol>
<div class="xs-units" id="execution-units"{% if not sp.units %} hidden{% endif %}>{% if sp.units %}{% set u = sp.units %}<progress{% if u.n is not none %} max="{{ u.n or 1 }}" value="{{ u.done }}"{% endif %}></progress><span class="small"><b>{{ u.done }} / {{ u.n if u.n is not none else '?' }}</b> {{ 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 %}</span>{% endif %}</div>
<details id="execution-environments"{% if not sp.units or not sp.units.environments %} hidden{% endif %}>
<summary class="small">Environments within Units</summary>
<ul>{% if sp.units %}{% for st in sp.units.environments %}<li title="{{ st.full or st.label }}">{{ st.label }} · {{ st.state }}{% if st.get('seconds') is not none %} · {{ st.seconds|secs }}{% endif %}{% if st.detail %} · {{ st.detail }}{% endif %}</li>{% endfor %}{% endif %}</ul>
</details>
<div class="small bad" id="execution-refused"{% if sp.ended != 'refused' %} hidden{% endif %}>{% if sp.ended == 'refused' %}Refused before its first unit: {{ sp.detail }}{% endif %}</div>
</div>
{# a part downloading: its file, how much of it, as a bar #}
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion app/templates/runs/job.html
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
</div>
{% if execution %}
<div role="tabpanel" id="view-logs" aria-labelledby="tab-logs"{% if view != 'logs' %} hidden{% endif %}>
{{ 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) }}
</div>
{% endif %}
<div role="tabpanel" id="view-live" aria-labelledby="tab-live"{% if view != 'live' %} hidden{% endif %}>
Expand Down
2 changes: 1 addition & 1 deletion app/templates/runs/preparing.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<button type="button" role="tab" id="tab-logs" data-view-tab="logs" aria-controls="view-logs" aria-selected="true">Logs</button>
</div>
<div role="tabpanel" id="view-logs" aria-labelledby="tab-logs">
{{ execution_strip(ex, csrf, waiting=true, own=own, deletable=deletable) }}
{{ execution_strip(ex, csrf, job_id=job_id, waiting=true, own=own, deletable=deletable) }}
</div>
<div role="tabpanel" id="view-live" aria-labelledby="tab-live" hidden>{{ live_panel(job_id, trial_base=url_for('job', job_id=job_id)) }}</div>
<div role="tabpanel" id="view-results" aria-labelledby="tab-results" hidden></div>
Expand Down
5 changes: 5 additions & 0 deletions app/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down Expand Up @@ -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")
Expand Down
37 changes: 37 additions & 0 deletions app/tests/test_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
Loading