Skip to content

Commit 32488c6

Browse files
authored
perf(web): keep the launches and each workspace's counts until their jobs or runs change (#232)
Closes #230 ## What - `workspace.heads(roots)` is a cheap change key. For each root and each folder in it, it takes `_head`, the key `load_job` already uses: the stat of the folder, of its `result.json` and of its `config.json`. These are what `find_job_dirs` and a finished job's own records change by. It costs about three stats per folder, with no listing per job, no realpath and no JSON. - `runs._every()` keeps its last result in `_EVERY`. The key is each record's id, state and jobs folder, plus the `heads` of those folders. It keeps the result only when every job it read is `finished`. - `workspaces._counts(ws, recs)` keeps each closed workspace's counts in `_COUNTS`. The key is the workspace's `roots`, its `job_roots`, the `heads` of its job roots and `recs`, the records' ids and states, built once per request. It keeps them only when all its jobs are `finished`. The open workspace is computed on each load. Both memos live in memory, so the first load after a start costs what it does today. Nothing is written to disk. ## Touches backend (`nullius/workspace.py`) · routes (`web/runs.py`, `web/workspaces.py`) · tests ## Verified A synthetic profile in a rootless Podman container: 100 workspaces, 2000 Harbor jobs, 200 run records. Warm is the median of requests 2 to 5; two runs each, a fresh process per page. | Page | main, warm | branch, warm | main, first | branch, first | | --- | --- | --- | --- | --- | | Workspaces | 0.67 / 0.63 s | 0.21 / 0.21 s | 6.5 / 5.4 s | 5.5 / 5.1 s | | Launches | 0.47 / 0.45 s | 0.33 / 0.33 s | 2.3 / 2.4 s | 2.2 / 2.4 s | - Same output: `/workspaces`, `/launches` and `/launches?ws=ws000` were saved from main and from the branch, each loaded twice so the second comes from the memo. After normalising the CSRF tokens, the asset digests and the interface digest, all six files are identical. - `python3 app/tests/parallel.py`: 3061 tests in 155 modules, OK. - `pip install -r app/requirements.txt`, then `python3 app/tests/parallel.py app/ui_tests`: 664 tests in 55 modules, OK. - New tests: - `test_workspace.py`: `heads` moves when a job is added, removed or has its records rewritten, and not for a change inside a trial. - `test_run_routes.py`, Workspaces: the memo is used, then the counts follow a job added, a job removed, a job's config rewritten in place, a launch added to the workspace and a run record removed. - `test_run_routes.py`, Launches: the list follows a run that ends, a job added, a job removed and a job rewritten in place. - With `heads` stubbed to return `()`, both route tests fail. Not checked: a profile with runs in progress, which takes the full path as today. ## Risk - A finished job whose only change is inside a trial folder keeps its old counts until its own records, its folder or a run record change, or the process restarts. The same holds for a root whose link is pointed elsewhere. A `shortcut:` comment on `heads` says when to key on each job's signature instead. The counts read no trial. - A job left with `n_running_trials` above 0 by a crash is never kept, so that page costs what it does today. - To undo, revert the commit.
1 parent 252a5b8 commit 32488c6

5 files changed

Lines changed: 103 additions & 6 deletions

File tree

‎app/nullius/workspace.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,24 @@ def _head(job_dir: str) -> str:
335335
return "\n".join(parts)
336336

337337

338+
def heads(roots) -> tuple:
339+
"""``_head`` of each of *roots* and of each entry in it: what
340+
``parse.find_job_dirs`` over them, and the parse of an ended job found
341+
there, can change by. A page's summary of ended jobs is kept while this is.
342+
shortcut: a change inside a trial folder alone (a trial's result.json, or
343+
the first one of a job without events.jsonl) or a link retargeted is not
344+
seen; key on ``signature`` of each job if those must show."""
345+
out = []
346+
for root in roots:
347+
try:
348+
names = sorted(os.listdir(root))
349+
except OSError:
350+
out.append((root, None))
351+
continue
352+
out.append((root, _head(root), tuple((n, _head(os.path.join(root, n))) for n in names)))
353+
return tuple(out)
354+
355+
338356
def _ended(job: parse.Job) -> bool:
339357
"""Its result records a finish and nothing running or pending: its trials are final."""
340358
return job.finished_at is not None and job.state == "finished"

‎app/tests/test_workspace.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,20 @@ def test_a_job_no_run_writes_is_read_by_its_head(self):
383383
again, from_cache = workspace.load_job(self.ws, self.job_dir, runs={"job-b": None})
384384
self.assertIs(again, first); self.assertTrue(from_cache)
385385

386+
def test_heads_move_with_a_job_added_removed_or_rewritten_not_with_a_trial(self):
387+
before = workspace.heads([self.root])
388+
_write_json(os.path.join(self.job_dir, "tau3-bench__t0__abc", "result.json"), {"rewritten": True})
389+
self.assertEqual(workspace.heads([self.root]), before) # the shortcut's limit
390+
_write_json(os.path.join(self.job_dir, "result.json"), {"id": "j1", "stats": {"n_running_trials": 1}})
391+
rewritten = workspace.heads([self.root])
392+
self.assertNotEqual(rewritten, before)
393+
_job_dir(self.root, "job-b")
394+
self.assertNotEqual(workspace.heads([self.root]), rewritten)
395+
shutil.rmtree(os.path.join(self.root, "job-b"))
396+
self.assertNotEqual(workspace.heads([self.root]), rewritten) # the root's own mtime moved
397+
gone = os.path.join(self.root, "gone")
398+
self.assertEqual(workspace.heads([gone]), ((gone, None),))
399+
386400
def test_index_lists_runs_without_a_parse(self):
387401
self.assertEqual(workspace.job_index(self.ws), {})
388402
workspace.load_job(self.ws, self.job_dir)

‎app/ui_tests/test_run_routes.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -975,6 +975,22 @@ def test_runs_and_checks_are_counted_alike_on_both_pages(self):
975975
self.assertEqual([self.cells(rows[key])[c] for c in ("runs", "checks")], ["1", "0"]) # the merge stands for its two shards
976976
self.assertEqual([self.cells(rows[f"run:{refused.id}"])[c] for c in ("runs", "checks", "state")], ["1", "1", "refused"])
977977

978+
def test_launches_kept_between_loads_follow_the_disk(self):
979+
from tests.test_feasibility import write_job
980+
rec = self.record("r3", "running")
981+
said = lambda: [self.cells(self.rows()[f"run:{rec.id}"])[c] for c in ("runs", "checks", "state")]
982+
self.assertEqual(said(), ["1", "1", "running"])
983+
rec.state = "done" # a run ending
984+
self.assertEqual(said(), ["1", "1", "finished"])
985+
self.assertIn("last", web.runs._EVERY) # kept: every job has ended
986+
write_job(rec.jobs, "r3-nop", "my-agent", {"a": 1}) # a job added: no check after all
987+
self.assertEqual(said(), ["2", "0", "finished"])
988+
shutil.rmtree(os.path.join(rec.jobs, "r3-nop")) # and removed: named, not written
989+
self.assertEqual(said(), ["1", "1", "finished"])
990+
cfg = os.path.join(rec.jobs, "r3-a", "config.json") # a job rewritten in place
991+
self._write_json(cfg, {**json.loads(Path(cfg).read_text()), "agents": [{"name": "oracle"}]})
992+
self.assertEqual(said(), ["0", "2", "finished"])
993+
978994
def test_no_launch_is_one_line(self):
979995
execution.EXECUTIONS.clear()
980996
self.assertIn('<div class="alert">No launch yet.</div>', self.get("/launches").get_data(as_text=True))
@@ -1140,6 +1156,26 @@ def test_runs_and_checks_count_as_the_runs_and_launches_pages_count_them(self):
11401156
ask = self.get(f"/workspaces/{self.ws.name}/roots/ask?root={d / 'jobs'}").get_data(as_text=True)
11411157
self.assertIn("<p>1 run · 2 checks · ", ask) # the folder's Delete counts its run alike
11421158

1159+
def test_counts_kept_between_loads_follow_the_disk(self):
1160+
from tests.test_feasibility import write_job
1161+
other, jobs = self.other(), str(self.run_dir / "jobs")
1162+
counts = lambda: (self.cell(other, 2), self.cell(other, 3), self.cell(other, 5))
1163+
self.assertEqual(counts(), ("2", "0", "1"))
1164+
self.assertIn(other.name, web.workspaces._COUNTS) # kept: its jobs have ended
1165+
self.assertEqual(counts(), ("2", "0", "1"))
1166+
write_job(jobs, "r1-c", "nop", {"a": 0}) # a job added
1167+
self.assertEqual(counts(), ("2", "1", "1"))
1168+
shutil.rmtree(os.path.join(jobs, "r1-c")) # and removed
1169+
self.assertEqual(counts(), ("2", "0", "1"))
1170+
cfg = os.path.join(jobs, "r1-b", "config.json") # a job rewritten in place
1171+
self._write_json(cfg, {**json.loads(Path(cfg).read_text()), "agents": [{"name": "oracle"}]})
1172+
self.assertEqual(counts(), ("1", "1", "1"))
1173+
rec = LaunchesPage.record(self, "r9") # a launch added to it: its roots change
1174+
other.roots.append(rec.jobs); workspace.save(other)
1175+
self.assertEqual(counts(), ("2", "2", "2"))
1176+
del execution.EXECUTIONS["r9"] # the run records change
1177+
self.assertEqual(counts(), ("2", "1", "1"))
1178+
11431179
def test_launches_count_as_the_filtered_launches_page(self):
11441180
bare = workspace.create(self.home, [str(self.tmp / "none")], label="bare")
11451181
rows = re.findall(r'<tr data-launch="[^"]+".*?data-f-ws="([^"]*)"', self.get("/launches").get_data(as_text=True))

‎app/web/runs.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,12 +132,26 @@ def _record(ex, merged=()) -> tuple:
132132
def _every() -> tuple:
133133
"""Every launch Nullius made, newest first: every run record, grouped as
134134
the Runs page groups them, each record's jobs read without their trials,
135-
and a merge of them written beside them. Returns (job id -> job, launches)."""
135+
and a merge of them written beside them. Returns (job id -> job, launches).
136+
Kept while the records' states and their folders' heads are unchanged and
137+
every job had ended (``workspace.heads``)."""
136138
recs = list(execution.EXECUTIONS.values())
139+
key = (tuple((e.id, e.state, e.jobs) for e in recs), workspace.heads(dict.fromkeys(e.jobs for e in recs)))
140+
last = _EVERY.get("last")
141+
if last and last[0] == key:
142+
return last[1]
137143
named = {str(x.get("name")) for e in recs for x in e.plan.jobs}
138144
jobs = [parse.parse_job(d, trials=False) for d in parse.find_job_dirs([e.jobs for e in recs if os.path.isdir(e.jobs)])]
139145
jobs = [j for j in jobs if j.job_id in named or named & set(getattr(j, "merged_from", []))]
140-
return {j.job_id: j for j in jobs}, launches.group(jobs, {e.id: _record(e) for e in recs})
146+
every = {j.job_id: j for j in jobs}, launches.group(jobs, {e.id: _record(e) for e in recs})
147+
if all(j.state == "finished" for j in jobs):
148+
_EVERY["last"] = (key, every)
149+
else:
150+
_EVERY.pop("last", None)
151+
return every
152+
153+
154+
_EVERY: dict = {} # "last": (key, _every()) of the last call that found every job ended
141155

142156

143157
def _tally(g, by_id) -> dict:

‎app/web/workspaces.py‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,24 +61,39 @@ def _root(path, launched, memo) -> dict:
6161
return {**memo[real], "path": path}
6262

6363

64-
def _counts(ws) -> dict:
64+
def _counts(ws, recs) -> dict:
6565
"""The runs and the checks (nop, oracle) of *ws*, summed over the launches
6666
its Runs page shows, each counted as there and on the Launches page
6767
(``runs._tally``). Its roots are walked, each unchanged job read from its
68-
cache."""
68+
cache. A closed workspace whose jobs had all ended keeps its counts while
69+
its roots, their heads (``workspace.heads``) and ``recs``, the run records'
70+
ids and states, are unchanged."""
6971
is_open = shared.STATE["workspace"] is not None and shared.STATE["workspace"].name == ws.name
72+
key = None if is_open else (tuple(ws.roots), tuple(ws.job_roots), workspace.heads(ws.job_roots or ws.roots), recs)
73+
last = _COUNTS.get(ws.name)
74+
if key is not None and last and last[0] == key:
75+
return last[1]
7076
jobs, _, _, groups = runs_web._grouped(None if is_open else ws)
7177
by_id = {j.job_id: j for j in jobs}
7278
tallies = [runs_web._tally(g, by_id) for g in groups]
73-
return {"runs": sum(t["n_runs"] for t in tallies), "checks": sum(t["n_checks"] for t in tallies)}
79+
counts = {"runs": sum(t["n_runs"] for t in tallies), "checks": sum(t["n_checks"] for t in tallies)}
80+
if key is not None and all(j.state == "finished" for j in jobs):
81+
_COUNTS[ws.name] = (key, counts)
82+
else:
83+
_COUNTS.pop(ws.name, None)
84+
return counts
85+
86+
87+
_COUNTS: dict = {} # workspace name -> (key, _counts) of a workspace whose jobs had all ended
7488

7589

7690
@app.route("/workspaces")
7791
def workspaces_page():
7892
wss, launched = workspace.list_all(shared.WS_HOME), runs_web._held_launches()
7993
held = [w.name for _, _, holders in launched[0] for w in holders]
94+
recs = tuple((e.id, e.state) for e in execution.EXECUTIONS.values())
8095
return render_template("workspaces/workspaces.html", workspaces=wss, csrf=shared._csrf_token(),
81-
counts={ws.name: _counts(ws) for ws in wss}, n_judged={ws.name: store.count(ws.dir) for ws in wss}, n_launches={ws.name: held.count(ws.name) for ws in wss})
96+
counts={ws.name: _counts(ws, recs) for ws in wss}, n_judged={ws.name: store.count(ws.dir) for ws in wss}, n_launches={ws.name: held.count(ws.name) for ws in wss})
8297

8398

8499
@app.route("/workspaces/open/<name>", methods=["POST"])

0 commit comments

Comments
 (0)