From d82146f3cf25d4c78040d57c5b1bec86c9ca9587 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 1 Dec 2026 19:19:00 +0100 Subject: [PATCH] fix(runs): version the workspace's job index and lock its writes --- app/nullius/workspace.py | 158 ++++++++++++++++++++++++++--------- app/nullius/workspace_cli.py | 2 +- app/tests/test_workspace.py | 75 ++++++++++++++++- 3 files changed, 191 insertions(+), 44 deletions(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 58e69b641..a66699646 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -349,11 +349,12 @@ def forget(ws: Workspace, roots, job_dirs) -> None: ws.roots = [r for r in ws.roots if r not in roots] ws.job_roots = [r for r in ws.job_roots if r not in roots] save(ws) - index = job_index(ws) - # a root already gone from disk finds no job dirs: its entries go by where they were - for d in set(job_dirs) | {d for d in index if _under(d, roots)}: - _drop(ws, index, d) - _write_index(ws, index) + + def drop(index): + # a root already gone from disk finds no job dirs: its entries go by where they were + for d in set(job_dirs) | {d for d in index if _under(d, roots)}: + _drop(ws, index, d) + _update_index(ws, drop) def _under(job_dir: str, roots) -> bool: @@ -515,31 +516,38 @@ def _index_path(ws: Workspace) -> str: return os.path.join(ws.jobs_dir, "index.json") +INDEX_VERSION = 1 # bump when what index.json holds changes +_ENTRY = {"job_id": str, "n_trials": int, "dataset": str, "agent": str, "signature": str, "head": str} + + def job_index(ws: Workspace) -> dict: """job dir → {job_id, n_trials, dataset, agent}: what the rail lists without parsing; - an ended job's also its signature and head (_note_in_index).""" + an ended job's also its signature and head (_note_in_index). The file is + ``{"version", "jobs"}``; one written before it had a version is the bare map. + A file that cannot be read is no index, and an entry that is not one is left out, as + is a field of the wrong type: no reader has to check one.""" try: with open(_index_path(ws), encoding="utf-8") as fh: data = json.load(fh) - except (OSError, json.JSONDecodeError): + except (OSError, ValueError): # not JSON, not UTF-8 return {} - return data if isinstance(data, dict) else {} + if isinstance(data, dict) and "version" in data: + data = data.get("jobs") if data["version"] == INDEX_VERSION else None + if not isinstance(data, dict): + return {} + return {d: {k: v for k, v in e.items() if v is None or isinstance(v, _ENTRY.get(k, object))} + for d, e in data.items() if isinstance(e, dict)} -def _noted_head(ws: Workspace, job_dir: str, sig, index: dict | None) -> str | None: - """The head the index noted for *job_dir* while its signature was *sig*.""" - entry = (job_index(ws) if index is None else index).get(job_dir) - return entry.get("head") if sig and isinstance(entry, dict) and entry.get("signature") == sig else None +def _noted_head(job_dir: str, sig, index: dict) -> str | None: + """The head *index* noted for *job_dir* while its signature was *sig*.""" + entry = index.get(job_dir) + return entry.get("head") if sig and entry and entry.get("signature") == sig else None -def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | None = None, - sig: str = "", head: str = "") -> bool: - """The job's entry in the rail's index, and an ended job's head with the - signature it was seen with. With ``index`` (load_jobs, which - reads the file once and writes it once) the dict is changed in place and - True returned when it changed; alone, the file is read and written here.""" - own = index is None - index = job_index(ws) if own else index +def _note_in_index(job_dir: str, job: parse.Job, index: dict, sig: str = "", head: str = "") -> bool: + """The job's entry in the rail's *index*, changed in place, and an ended job's head with + the signature it was seen with. True when it changed.""" entry = {"job_id": job.job_id, "n_trials": len(job.trials), "dataset": job.dataset, "agent": job.agent_label or job.agent_name} if sig and head and _ended(job): @@ -547,14 +555,67 @@ def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | No if index.get(job_dir) == entry: return False index[job_dir] = entry - if own: - _write_index(ws, index) return True +def _merge_index(ws: Workspace, now: dict, before: dict, after: dict) -> None: + """What a reader changed from *before* to *after*, made to *now*, the index as the file + holds it. An entry another writer changed or dropped meanwhile is left as theirs. A job + new here enters only while the workspace still holds its root: a forget meanwhile took + it out, and its parse goes too.""" + held = _holds(ws) if after.keys() - before.keys() else None + for d in before.keys() | after.keys(): + was, new = before.get(d), after.get(d) + if was == new or now.get(d) != was: + continue + if new is None: + del now[d] + elif was is None and held is not None and not held(d): + _drop(ws, now, d, {_cache_file(ws, k) for k in now}) + else: + now[d] = new + + +def _holds(ws: Workspace) -> Callable | None: + """Whether *ws*, as its record is now, holds a job folder: one under a root, or under a + job root it kept in ``imported/``, as ``open_workspace`` reads them. None when the record + cannot be read.""" + try: + now = load(os.path.dirname(ws.dir), ws.name) + except (TypeError, ValueError): + now = None + if now is None: + return None + kept = [*now.roots, *(r for r in now.job_roots + if os.path.commonpath([os.path.abspath(r), now.imports_dir]) == now.imports_dir)] + return lambda job_dir: _under(job_dir, kept) + + +def _update_index(ws: Workspace, change: Callable) -> None: + """``change`` made in place to the index as the file holds it, under its lock: of two + writers at once, each reads what the other wrote, so neither change is lost. Nothing + once the workspace's folder is gone, renamed or deleted: no writer that began before + makes its old folder again.""" + try: + os.mkdir(ws.jobs_dir) + except FileExistsError: + pass + except FileNotFoundError: + return + try: + with ondisk.locked(_index_path(ws) + ".lock"): + index = job_index(ws) + before = dict(index) + change(index) + if index != before: + _write_index(ws, index) + except FileNotFoundError: # its folder moved away meanwhile + pass + + def _write_index(ws: Workspace, index: dict) -> None: - os.makedirs(ws.jobs_dir, exist_ok=True) - ondisk.write_whole(_index_path(ws), lambda fh: json.dump(index, fh, ensure_ascii=False, indent=1)) + data = {"version": INDEX_VERSION, "jobs": index} + ondisk.write_whole(_index_path(ws), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1)) COUNTS_VERSION = 2 # bump when what counts.json holds changes @@ -631,9 +692,23 @@ def write(fh): def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: Callable | None = None) -> tuple: """(Job, from_cache). Parses only when the signature changed; an ended job whose head is unchanged is not stated trial by trial. ``index``: the - rail's index as load_jobs holds it, noted in place. ``runs``: job folder + rail's index as load_jobs holds it, noted in place; without it, the file's, + read before the parse, so that a load that ended meanwhile keeps its entry + (``_merge_index``). ``runs``: job folder -> the end of the run of this application that writes that very folder (``execution.run_ends``), None while that run goes on, "" when none does.""" + if index is not None: + return _load_job(ws, job_dir, index, runs) + index = job_index(ws) + entry = lambda: {job_dir: index[job_dir]} if job_dir in index else {} + before = entry() + found = _load_job(ws, job_dir, index, runs) + if entry() != before: + _update_index(ws, lambda now: _merge_index(ws, now, before, entry())) + return found + + +def _load_job(ws: Workspace, job_dir: str, index: dict, runs: Callable | None) -> tuple: run = runs(job_dir) if runs else "" short = run is not None # the head alone may answer head = _head(job_dir) + (f"\nrun={run}" if run else "") # before anything is read: a change after it is caught next time @@ -641,28 +716,28 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: Calla with _DECODED_LOCK: known = _DECODED.get(path) if short and known is not None and known[1].dir == job_dir and known[3] == head and _ended(known[1]): - _note_in_index(ws, job_dir, known[1], index, known[0], head) + _note_in_index(job_dir, known[1], index, known[0], head) return known[1], True cached = _read_cache(path, job_dir) if known is None else None if (short and cached is not None and _ended(cached[2]) - and head in (cached[1], _noted_head(ws, job_dir, cached[0], index))): + and head in (cached[1], _noted_head(job_dir, cached[0], index))): with _DECODED_LOCK: _DECODED[path] = (cached[0], cached[2], {}, head) - _note_in_index(ws, job_dir, cached[2], index, cached[0], head) + _note_in_index(job_dir, cached[2], index, cached[0], head) return cached[2], True sig, trial_sigs = _signatures(job_dir) if sig: if known is not None and known[0] == sig and known[1].dir == job_dir: with _DECODED_LOCK: _DECODED[path] = (sig, known[1], known[2], head) - _note_in_index(ws, job_dir, known[1], index, sig, head) + _note_in_index(job_dir, known[1], index, sig, head) return known[1], True if known is not None: cached = _read_cache(path, job_dir) if cached is not None and cached[0] == sig: with _DECODED_LOCK: _DECODED[path] = (sig, cached[2], trial_sigs, head) - _note_in_index(ws, job_dir, cached[2], index, sig, head) # read by its head from the next process on + _note_in_index(job_dir, cached[2], index, sig, head) # read by its head from the next process on return cached[2], True reuse = None if known is not None and known[1].dir == job_dir: @@ -675,7 +750,7 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: Calla _write_cache(ws, path, sig, head, job) with _DECODED_LOCK: _DECODED[path] = (sig, job, trial_sigs, head) - _note_in_index(ws, job_dir, job, index, sig, head) + _note_in_index(job_dir, job, index, sig, head) return job, False @@ -683,7 +758,8 @@ def load_jobs(ws: Workspace, roots, runs: Callable | None = None) -> list: """Every job under *roots*, each from the cache when its files are unchanged. Same order and de-duplication as ``parse.load_all``. ``runs``: as ``load_job``'s.""" - # the rail's index read once and written once, not once per job + # the rail's index read once and written once, not once per job: what changed in it here, + # applied to the file as it is then index = job_index(ws) before = dict(index) dirs = parse.find_job_dirs(roots) @@ -699,7 +775,7 @@ def load_jobs(ws: Workspace, roots, runs: Callable | None = None) -> list: _drop(ws, index, d, keep) store_counts(ws, None, None) if index != before: - _write_index(ws, index) + _update_index(ws, lambda now: _merge_index(ws, now, before, index)) return parse.split_agents(jobs) @@ -709,13 +785,13 @@ def clear_cache(ws: Workspace) -> int: with _DECODED_LOCK: for path in [p for p in _DECODED if os.path.dirname(p) == ws.jobs_dir]: del _DECODED[path] - try: - names = [n for n in os.listdir(ws.jobs_dir) if n.endswith(".json")] - except OSError: + if not os.path.isdir(ws.jobs_dir): return 0 - for n in names: - try: - os.remove(os.path.join(ws.jobs_dir, n)) - except OSError: - pass + with ondisk.locked(_index_path(ws) + ".lock"): # no index writer puts back what goes here + names = [n for n in os.listdir(ws.jobs_dir) if n.endswith(".json")] + for n in names: + try: + os.remove(os.path.join(ws.jobs_dir, n)) + except OSError: + pass return len([n for n in names if n not in _NOT_JOBS]) diff --git a/app/nullius/workspace_cli.py b/app/nullius/workspace_cli.py index 471970bfa..a690fde1f 100644 --- a/app/nullius/workspace_cli.py +++ b/app/nullius/workspace_cli.py @@ -57,7 +57,7 @@ def row(ws: workspace.Workspace) -> dict: "n_cached": ws.n_cached, "jobs": [{"dir": job_dir, "job_id": entry.get("job_id"), "n_trials": entry.get("n_trials"), "dataset": entry.get("dataset"), "agent": entry.get("agent")} - for job_dir, entry in index.items() if isinstance(entry, dict)], + for job_dir, entry in index.items()], "created": ws.created, "opened": ws.opened, } diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index f6de14a3a..c8b4fece2 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -626,10 +626,81 @@ def test_forget_drops_a_root_gone_from_disk(self): self.assertEqual(workspace.job_index(self.ws), {}) self.assertEqual(self.ws.n_cached, 0) + def test_the_index_carries_a_version_and_one_without_is_read(self): + workspace.load_job(self.ws, self.job_dir) + with open(workspace._index_path(self.ws), encoding="utf-8") as fh: + data = json.load(fh) + self.assertEqual((data["version"], list(data["jobs"])), (workspace.INDEX_VERSION, [self.job_dir])) + bare = {self.job_dir: {"job_id": "job-a", "n_trials": 2, "dataset": "tau3-bench", "agent": "MyAgent"}} + _write_json(workspace._index_path(self.ws), bare) # as written before the version + self.assertEqual(workspace.job_index(self.ws), bare) + for damaged in (b"\xff", json.dumps({"version": workspace.INDEX_VERSION, "jobs": {**bare, "/x": None}}).encode(), + json.dumps({**bare, "/x": None}).encode()): + with open(workspace._index_path(self.ws), "wb") as fh: + fh.write(damaged) + self.assertIn(workspace.job_index(self.ws), ({}, bare)) # unreadable is no index; a bad entry is left out + _write_json(workspace._index_path(self.ws), {"/x": {"job_id": "job-a", "agent": 13}}) + self.assertEqual(workspace.job_index(self.ws), {"/x": {"job_id": "job-a"}}) # nor a field of the wrong type + + def test_a_load_and_a_forget_at_once_lose_neither_change(self): + other = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, other, True) + gone = _job_dir(other, "job-b") + workspace.load_jobs(self.ws, [self.root, other]) + late = _job_dir(self.root, "job-c") + _job_dir(other, "job-d") # first parsed after its root was forgotten + made = [_job_dir(self.ws.imports_dir, n) for n in ("kept", "stray")] # converted before: one a job root + self.ws.job_roots = [self.root, other, made[0]]; workspace.save(self.ws) + load_job = workspace.load_job + + def forget_meanwhile(ws, job_dir, *rest): # the other request, between read and write + if job_dir == late: + workspace.forget(workspace.load(self.home, self.ws.name), [other], [gone]) + return load_job(ws, job_dir, *rest) + with patch.object(workspace, "load_job", side_effect=forget_meanwhile): + workspace.load_jobs(self.ws, [self.root, other, *made]) + self.assertEqual(sorted(workspace.job_index(self.ws)), sorted([self.job_dir, late, made[0]])) + + def test_a_slower_load_leaves_the_entry_a_newer_one_wrote(self): + parse_job = parse.parse_job + + def newer_meanwhile(*args, **kwargs): # the other request, after this parse + job = parse_job(*args, **kwargs) + _job_dir(self.root, n=3); os.utime(self.job_dir, None) + with patch.object(parse, "parse_job", parse_job): + workspace.load_job(replace(self.ws), self.job_dir) + return job + with patch.object(parse, "parse_job", side_effect=newer_meanwhile): + workspace.load_job(self.ws, self.job_dir) + self.assertEqual(workspace.job_index(self.ws)[self.job_dir]["n_trials"], 3) + + def test_a_load_that_outlives_a_rename_makes_no_old_folder(self): + write = workspace._write_cache + + def renamed(ws, *rest): # the other request, before the index write + write(ws, *rest) + workspace.rename(self.home, workspace.load(self.home, self.ws.name), "moved") + with patch.object(workspace, "_write_cache", side_effect=renamed): + workspace.load_job(self.ws, self.job_dir) + self.assertFalse(os.path.exists(self.ws.dir)) + + def test_a_refresh_waits_for_an_index_write_and_leaves_no_entry(self): + inside, go = threading.Event(), threading.Event() + write = workspace._write_index + + def held_up(ws, index): + inside.set(); go.wait(5) + write(ws, index) + with patch.object(workspace, "_write_index", side_effect=held_up): + writer = threading.Thread(target=workspace.load_job, args=(self.ws, self.job_dir)); writer.start() + inside.wait(5) + refresh = threading.Thread(target=workspace.clear_cache, args=(self.ws,)); refresh.start() + refresh.join(0.2) # held at the lock, or done before the write + go.set(); writer.join(); refresh.join() + self.assertEqual(workspace.job_index(self.ws), {}) + def test_corrupt_cache_falls_back_to_parse(self): workspace.load_job(self.ws, self.job_dir) - path = next(os.path.join(self.ws.jobs_dir, n) for n in os.listdir(self.ws.jobs_dir) - if n != "index.json") + path = workspace._cache_file(self.ws, self.job_dir) with open(path, "w", encoding="utf-8") as fh: fh.write("{not json") workspace._DECODED.clear() # a new process: only the file on disk