Skip to content

Commit 38235bd

Browse files
authored
perf(runs): note a moved head in the job index, and write a job's cache trial by trial (#317)
Closes #311 ## What An ended job is answered by its head. When only its folder's time moved (an entry added or removed beside the trials), `load_job` decoded the cache, found the signature current and wrote the whole job again to store the new head. The head is now noted in the workspace's `jobs/index.json`, beside the signature it was seen with: the entry of an ended job gains `signature` and `head`. `load_jobs` already reads that file once and writes it once, so a moved head costs one small write for the workspace and none for the job. The next process answers the job by the head in the index when the cache's signature is the one noted there, without stating its trials. The cache file keeps the head it was written with, and either answers. A cache write no longer goes through `dataclasses.asdict`, which deep-copied every trial, nor through `json.dump`, whose encoder is pure Python. Each trial is encoded by `json.dumps` (the C encoder) and written in turn, so one trial's text is in memory at a time, as before. `job_to_dict` reads the fields without copying them: no field of a `Job` or `Trial` holds a dataclass. The cache file's shape is unchanged (its keys are the same; `trials` now comes last in `job`), so `workspace.SCHEMA` stays as it is and caches written before are read as they are. ## Touches backend: `app/nullius/workspace.py` (`job_to_dict`, `_write_cache`, `_note_in_index`, `_noted_head`, `load_job`). Tests: `app/tests/test_workspace.py`. ## Verified - Backend suite: 3220 tests in 169 modules, OK. Route suite: 719 tests in 61 modules, OK. Both in a rootless `python:3.12` container, on main with #314. - New tests: - an ended job whose folder's mtime moved writes no job cache (the writer patched to fail), its file left byte for byte and mtime as it was, and the process after answers it with `workspace._signatures` patched to fail; the index holds the job's signature and head; - a head noted with another signature answers nothing: the trials are stated; - an ended job that gained a trial writes its cache again, once; - every job of the test fixtures equals `job_from_dict(job_to_dict(job))`, and its cache read back, written with `asdict` patched to fail; - a cache written by the previous writer (`asdict` and `json.dump`) is read by its head and equals the job; - the existing test that the cache is written a piece at a time now writes a job of 2000 trials (about 3 MB) and checks the peak stays under half the file. - The first `/workspaces` after a start, on profiles from the generator in #309 (W workspaces of 20 ended Harbor jobs of 50 trials), main and this branch alternated on the same profile, 3 fresh server processes each in one rootless `python:3.12` container, timed with curl inside it, median and range: | Before the start | main: first | this branch: first | Next, both | | --- | --- | --- | --- | | 20x20x50, caches current | 0.88 s (0.87-0.97) | 0.88 s (0.87-0.95) | 0.02 s | | 20x20x50, each job folder's mtime moved | 5.15 s (5.05-5.24) | 1.30 s (1.24-1.33) | 0.02 s | | 20x20x50, no job caches | 6.04 s (5.85-6.08) | 2.99 s (2.95-3.14) | 0.02 s | | 20x20x50, caches from before a `parse.SCHEMA` change | 7.00 s (6.49-7.03) | 3.84 s (3.83-3.95) | 0.02 s | | 100x20x50, caches current | 4.47 s (4.13-4.60) | 4.48 s (4.30-4.50) | 0.06-0.07 s | | 100x20x50, each job folder's mtime moved | 26.7 s (25.3-34.4) | 6.07 s (6.06-6.73) | 0.06-0.07 s | | 100x20x50, no job caches | 29.8 s (29.2-31.7) | 14.9 s (14.7-14.9) | 0.06 s | A moved head now takes 1.48 times the start with current caches at 20x20x50 (1.35 at 100x20x50). What it still spends beyond that is stating each job's trials once to confirm its signature, as the head alone cannot. The start with no caches is about twice as fast. The issue's 15.0 s for that start was measured before #313. - cProfile of the first request at 20x20x50 (werkzeug `ProfilerMiddleware`, which slows it down), measured before #314 merged, so line numbers are those of that build: ``` each job folder's mtime moved, main ncalls cumtime function 400 22.513 nullius/workspace.py:433(load_job) 400 17.261 nullius/workspace.py:427(_write_cache) 420 9.773 json/__init__.py:120(dump) 400 7.327 dataclasses.py:1308(asdict) this branch 400 1.695 nullius/workspace.py:467(load_job) 400 0.859 nullius/workspace.py:439(_read_cache) 400 0.801 nullius/workspace.py:269(_signatures) no _write_cache no job caches, main 400 22.780 nullius/workspace.py:433(load_job) 400 18.068 nullius/workspace.py:427(_write_cache) this branch 400 6.018 nullius/workspace.py:467(load_job) 400 4.068 nullius/runs/parse.py:888(parse_job) 400 1.048 nullius/workspace.py:452(_write_cache) ``` ## Risk The head in the index is trusted only with the signature it was noted with, and the head is taken before the signature, as the cache's own head is: a job changed after its head was taken moves its head again. It shares the head's existing limit: a file changed inside a trial folder of an ended job and nothing else is not seen; Refresh reads every job again. A lost or older index (an older version rewriting it without the new keys) costs one statement of the trials per job, never a wrong answer. The cache's format is unchanged, so an upgrade costs nothing and a downgrade reads the caches as written. The index's new keys are ignored by its other readers. Undone by a revert; the extra keys in `index.json` are harmless and Refresh removes the file.
1 parent aa3f41b commit 38235bd

2 files changed

Lines changed: 133 additions & 22 deletions

File tree

‎app/nullius/workspace.py‎

Lines changed: 48 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@
2727
application writes is checked trial by trial while that run goes on (a host
2828
run's copy can bring a trial's files after the job's own), and its head
2929
carries the run's end, so the last copy is checked trial by trial once more.
30+
An ended job's head is noted in ``jobs/index.json`` beside the signature it was
31+
seen with: a head that moves while the signature holds rewrites that index, not
32+
the job's cache.
3033
"""
3134
from __future__ import annotations
3235

@@ -346,8 +349,20 @@ def _decode(d):
346349
return d
347350

348351

352+
_JOB_FIELDS = tuple(f.name for f in fields(parse.Job))
353+
_TRIAL_FIELDS = tuple(f.name for f in fields(parse.Trial))
354+
355+
349356
def job_to_dict(job: parse.Job) -> dict:
350-
return asdict(job)
357+
"""*job* as plain values, its containers shared, not copied: read it, never change it.
358+
No field holds a dataclass, so ``asdict``'s deep copy of every trial is not needed."""
359+
out = {n: getattr(job, n) for n in _JOB_FIELDS}
360+
out["trials"] = [_trial_to_dict(t) for t in job.trials]
361+
return out
362+
363+
364+
def _trial_to_dict(trial: parse.Trial) -> dict:
365+
return {n: getattr(trial, n) for n in _TRIAL_FIELDS}
351366

352367

353368
def job_from_dict(data: dict) -> parse.Job:
@@ -377,7 +392,8 @@ def _index_path(ws: Workspace) -> str:
377392

378393

379394
def job_index(ws: Workspace) -> dict:
380-
"""job dir → {job_id, n_trials}: what the rail lists without parsing."""
395+
"""job dir → {job_id, n_trials, dataset, agent}: what the rail lists without parsing;
396+
an ended job's also its signature and head (_note_in_index)."""
381397
try:
382398
with open(_index_path(ws), encoding="utf-8") as fh:
383399
data = json.load(fh)
@@ -386,14 +402,24 @@ def job_index(ws: Workspace) -> dict:
386402
return data if isinstance(data, dict) else {}
387403

388404

389-
def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | None = None) -> bool:
390-
"""The job's entry in the rail's index. With ``index`` (load_jobs, which
405+
def _noted_head(ws: Workspace, job_dir: str, sig, index: dict | None) -> str | None:
406+
"""The head the index noted for *job_dir* while its signature was *sig*."""
407+
entry = (job_index(ws) if index is None else index).get(job_dir)
408+
return entry.get("head") if sig and isinstance(entry, dict) and entry.get("signature") == sig else None
409+
410+
411+
def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | None = None,
412+
sig: str = "", head: str = "") -> bool:
413+
"""The job's entry in the rail's index, and an ended job's head with the
414+
signature it was seen with. With ``index`` (load_jobs, which
391415
reads the file once and writes it once) the dict is changed in place and
392416
True returned when it changed; alone, the file is read and written here."""
393417
own = index is None
394418
index = job_index(ws) if own else index
395419
entry = {"job_id": job.job_id, "n_trials": len(job.trials), "dataset": job.dataset,
396420
"agent": job.agent_label or job.agent_name}
421+
if sig and head and _ended(job):
422+
entry.update(signature=sig, head=head)
397423
if index.get(job_dir) == entry:
398424
return False
399425
index[job_dir] = entry
@@ -465,8 +491,17 @@ def _read_cache(path: str, job_dir: str) -> tuple | None:
465491

466492
def _write_cache(ws: Workspace, path: str, sig: str, head: str, job: parse.Job) -> None:
467493
os.makedirs(ws.jobs_dir, exist_ok=True)
468-
ondisk.write_whole(path, lambda fh: json.dump({"signature": sig, "head": head, "dir": job.dir, "cached": _now(),
469-
"job": job_to_dict(job)}, fh, default=_encode, ensure_ascii=False))
494+
body = {n: getattr(job, n) for n in _JOB_FIELDS if n != "trials"}
495+
dumps = lambda obj: json.dumps(obj, default=_encode, ensure_ascii=False) # the C encoder; json.dump's is Python
496+
497+
def write(fh):
498+
# one trial's text in memory at a time: each dict's closing brace cut and written last
499+
fh.write(dumps({"signature": sig, "head": head, "dir": job.dir, "cached": _now()})[:-1])
500+
fh.write(', "job": ' + dumps(body)[:-1] + ', "trials": [')
501+
for i, t in enumerate(job.trials):
502+
fh.write(("," if i else "") + dumps(_trial_to_dict(t)))
503+
fh.write("]}}")
504+
ondisk.write_whole(path, write)
470505

471506

472507
def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict | None = None) -> tuple:
@@ -482,29 +517,28 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict
482517
with _DECODED_LOCK:
483518
known = _DECODED.get(path)
484519
if short and known is not None and known[1].dir == job_dir and known[3] == head and _ended(known[1]):
485-
_note_in_index(ws, job_dir, known[1], index)
520+
_note_in_index(ws, job_dir, known[1], index, known[0], head)
486521
return known[1], True
487522
cached = _read_cache(path, job_dir) if known is None else None
488-
if short and cached is not None and cached[1] == head and _ended(cached[2]):
523+
if (short and cached is not None and _ended(cached[2])
524+
and head in (cached[1], _noted_head(ws, job_dir, cached[0], index))):
489525
with _DECODED_LOCK:
490526
_DECODED[path] = (cached[0], cached[2], {}, head)
491-
_note_in_index(ws, job_dir, cached[2], index)
527+
_note_in_index(ws, job_dir, cached[2], index, cached[0], head)
492528
return cached[2], True
493529
sig, trial_sigs = _signatures(job_dir)
494530
if sig:
495531
if known is not None and known[0] == sig and known[1].dir == job_dir:
496532
with _DECODED_LOCK:
497533
_DECODED[path] = (sig, known[1], known[2], head)
498-
_note_in_index(ws, job_dir, known[1], index)
534+
_note_in_index(ws, job_dir, known[1], index, sig, head)
499535
return known[1], True
500536
if known is not None:
501537
cached = _read_cache(path, job_dir)
502538
if cached is not None and cached[0] == sig:
503-
if cached[1] != head and _ended(cached[2]):
504-
_write_cache(ws, path, sig, head, cached[2]) # read by its head from the next process on
505539
with _DECODED_LOCK:
506540
_DECODED[path] = (sig, cached[2], trial_sigs, head)
507-
_note_in_index(ws, job_dir, cached[2], index)
541+
_note_in_index(ws, job_dir, cached[2], index, sig, head) # read by its head from the next process on
508542
return cached[2], True
509543
reuse = None
510544
if known is not None and known[1].dir == job_dir:
@@ -517,7 +551,7 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict
517551
_write_cache(ws, path, sig, head, job)
518552
with _DECODED_LOCK:
519553
_DECODED[path] = (sig, job, trial_sigs, head)
520-
_note_in_index(ws, job_dir, job, index)
554+
_note_in_index(ws, job_dir, job, index, sig, head)
521555
return job, False
522556

523557

‎app/tests/test_workspace.py‎

Lines changed: 85 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -266,17 +266,44 @@ def load():
266266
self.assertEqual([n for n in os.listdir(self.ws.jobs_dir) if n.endswith(".part")], [])
267267

268268
def test_the_cache_is_written_a_piece_at_a_time(self):
269-
job, rows = parse.parse_job(self.job_dir), {"rows": ["x" * 100] * 20000} # about 2 MB as JSON
269+
job = parse.parse_job(self.job_dir)
270+
job.trials = [replace(job.trials[0], exception_message="x" * 1000) for _ in range(2000)] # about 3 MB as JSON
270271
path = os.path.join(self.ws.jobs_dir, "large.json")
271-
with patch.object(workspace, "job_to_dict", lambda job: rows):
272-
tracemalloc.start()
273-
try:
274-
workspace._write_cache(self.ws, path, "sig", "head", job)
275-
peak = tracemalloc.get_traced_memory()[1]
276-
finally:
277-
tracemalloc.stop()
272+
tracemalloc.start()
273+
try:
274+
workspace._write_cache(self.ws, path, "sig", "head", job)
275+
peak = tracemalloc.get_traced_memory()[1]
276+
finally:
277+
tracemalloc.stop()
278278
self.assertGreater(os.path.getsize(path), 2_000_000)
279279
self.assertLess(peak, os.path.getsize(path) / 2) # never the whole text in memory
280+
self.assertEqual(workspace._read_cache(path, job.dir)[2], job)
281+
282+
def test_the_cache_of_every_fixture_reads_back_equal(self):
283+
fixtures = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")
284+
jobs = [parse.parse_job(d) for d in parse.find_job_dirs(
285+
[os.path.join(fixtures, n) for n in sorted(os.listdir(fixtures)) if os.path.isdir(os.path.join(fixtures, n))])]
286+
self.assertGreater(sum(len(j.trials) for j in jobs), 0)
287+
for job in jobs:
288+
self.assertEqual(workspace.job_from_dict(workspace.job_to_dict(job)), job)
289+
path = workspace._cache_file(self.ws, job.dir)
290+
with patch.object(workspace, "asdict", side_effect=AssertionError("asdict")):
291+
workspace._write_cache(self.ws, path, "sig", "head", job)
292+
self.assertEqual(workspace._read_cache(path, job.dir), ("sig", "head", job))
293+
294+
def test_a_cache_written_whole_by_asdict_is_read_by_its_head(self):
295+
from dataclasses import asdict
296+
self._end()
297+
first, _ = workspace.load_job(self.ws, self.job_dir)
298+
path = workspace._cache_file(self.ws, self.job_dir)
299+
with open(path, encoding="utf-8") as fh:
300+
old = json.load(fh)
301+
with open(path, "w", encoding="utf-8") as fh: # as the writer before this one left it
302+
json.dump({**old, "job": asdict(first)}, fh, default=workspace._encode, ensure_ascii=False)
303+
workspace._DECODED.clear()
304+
with patch.object(workspace, "_signatures", side_effect=AssertionError("trials stated")):
305+
again, from_cache = workspace.load_job(self.ws, self.job_dir)
306+
self.assertTrue(from_cache); self.assertEqual(again, first)
280307

281308
def test_load_jobs_matches_load_all(self):
282309
_job_dir(self.root, "job-b", n=1)
@@ -358,6 +385,56 @@ def test_an_ended_job_is_not_stated_trial_by_trial(self):
358385
again, from_cache = workspace.load_job(self.ws, self.job_dir)
359386
self.assertTrue(from_cache); self.assertEqual(again, first)
360387

388+
def _cache_bytes(self):
389+
path = workspace._cache_file(self.ws, self.job_dir)
390+
with open(path, "rb") as fh:
391+
return fh.read(), os.stat(path).st_mtime_ns
392+
393+
def test_a_moved_head_writes_no_job_cache_and_is_read_by_it_next(self):
394+
self._end()
395+
first = workspace.load_jobs(self.ws, [self.root])
396+
before = self._cache_bytes()
397+
st = os.stat(self.job_dir)
398+
os.utime(self.job_dir, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) # an entry added or removed beside the trials
399+
for process in ("next", "fresh"):
400+
workspace._DECODED.clear()
401+
with patch.object(workspace, "_write_cache", side_effect=AssertionError("cache written")):
402+
self.assertEqual(workspace.load_jobs(self.ws, [self.root]), first)
403+
self.assertEqual(self._cache_bytes(), before)
404+
workspace._DECODED.clear() # the process after: the head in the index answers
405+
with patch.object(workspace, "_signatures", side_effect=AssertionError("trials stated")):
406+
self.assertEqual(workspace.load_jobs(self.ws, [self.root]), first)
407+
self.assertEqual(self._cache_bytes(), before)
408+
noted = workspace.job_index(self.ws)[self.job_dir]
409+
self.assertEqual((noted["signature"], noted["head"]), (workspace.signature(self.job_dir), workspace._head(self.job_dir)))
410+
411+
def test_a_head_noted_with_another_signature_answers_nothing(self):
412+
self._end()
413+
workspace.load_job(self.ws, self.job_dir)
414+
st = os.stat(self.job_dir)
415+
os.utime(self.job_dir, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9))
416+
workspace._DECODED.clear()
417+
workspace.load_job(self.ws, self.job_dir) # the head noted in the index
418+
index = workspace.job_index(self.ws)
419+
index[self.job_dir]["signature"] = "another"
420+
workspace._write_index(self.ws, index)
421+
workspace._DECODED.clear()
422+
with patch.object(workspace, "_signatures", wraps=workspace._signatures) as stated:
423+
_, from_cache = workspace.load_job(self.ws, self.job_dir)
424+
self.assertTrue(from_cache); self.assertEqual(stated.call_count, 1)
425+
426+
def test_an_ended_job_that_changed_writes_its_cache_again(self):
427+
self._end()
428+
workspace.load_job(self.ws, self.job_dir)
429+
time.sleep(0.01)
430+
shutil.copytree(os.path.join(self.job_dir, "tau3-bench__t1__abc"), os.path.join(self.job_dir, "tau3-bench__t9__abc"))
431+
workspace._DECODED.clear()
432+
with patch.object(workspace, "_write_cache", wraps=workspace._write_cache) as written:
433+
job, from_cache = workspace.load_job(self.ws, self.job_dir)
434+
self.assertFalse(from_cache); self.assertEqual(written.call_count, 1)
435+
workspace._DECODED.clear()
436+
self.assertEqual(workspace.load_job(self.ws, self.job_dir), (job, True))
437+
361438
def test_a_cache_from_before_the_head_learns_it_once(self):
362439
self._end()
363440
workspace.load_job(self.ws, self.job_dir)

0 commit comments

Comments
 (0)