From 3b2fe23b7f34a834aec35d28be5663ead3c3e23a Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 3 Dec 2026 18:13:52 +0100 Subject: [PATCH] fix(runs): keep a parse during a rename from recreating the old workspace folder The parse cache and the stored counts make only jobs/ inside a workspace folder still there and skip writing once it is gone; the caller still gets the parsed job. Closes #758 --- app/nullius/workspace.py | 45 ++++++++++++++++++-------- app/tests/test_standard_scored_cuts.py | 1 + app/tests/test_standard_shard.py | 1 + app/tests/test_workspace.py | 27 +++++++++++++--- app/ui_tests/test_run_routes.py | 16 +++++++++ 5 files changed, 73 insertions(+), 17 deletions(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 5311b84d1..693ac654b 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -810,11 +810,7 @@ def _update_index(ws: Workspace, change: Callable) -> None: 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: + if not _jobs_folder(ws): return try: with ondisk.locked(_index_path(ws) + ".lock"): @@ -827,6 +823,18 @@ def _update_index(ws: Workspace, change: Callable) -> None: pass +def _jobs_folder(ws: Workspace) -> bool: + """*ws*'s ``jobs/`` there, made in its folder when need be. False once that folder is + gone, renamed or deleted: no writer that began before makes it again.""" + try: + os.mkdir(ws.jobs_dir) + except FileExistsError: + pass + except FileNotFoundError: + return False + return True + + def _write_index(ws: Workspace, index: dict) -> None: data = {"version": INDEX_VERSION, "jobs": index} ondisk.write_whole(_index_path(ws), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1)) @@ -855,7 +863,8 @@ def stored_counts(ws: Workspace, key) -> dict | None: def store_counts(ws: Workspace, key, counts: dict | None) -> None: - """*counts* of *ws* kept beside its job caches under *key*; None removes them.""" + """*counts* of *ws* kept beside its job caches under *key*; None removes them. Nothing + kept once *ws*'s folder is gone, renamed or deleted (``_write_cache``).""" path = os.path.join(ws.jobs_dir, "counts.json") if counts is None: try: @@ -863,8 +872,12 @@ def store_counts(ws: Workspace, key, counts: dict | None) -> None: except OSError: pass return - os.makedirs(ws.jobs_dir, exist_ok=True) - ondisk.write_whole(path, json.dumps({"version": COUNTS_VERSION, "key": _key_digest(key), "counts": counts})) + if not _jobs_folder(ws): + return + try: + ondisk.write_whole(path, json.dumps({"version": COUNTS_VERSION, "key": _key_digest(key), "counts": counts})) + except FileNotFoundError: # its folder moved away meanwhile + pass # Jobs already decoded in this process, by cache file: (signature, Job, trial @@ -899,8 +912,11 @@ def _cached_as(path: str, sig: str | None) -> bool: return False -def _write_cache(ws: Workspace, path: str, sig: str, head: str, job: parse.Job) -> None: - os.makedirs(ws.jobs_dir, exist_ok=True) +def _write_cache(ws: Workspace, path: str, sig: str, head: str, job: parse.Job) -> bool: + """*job*'s parse kept in *ws*'s ``jobs/``. False, nothing written, once *ws*'s folder is + gone, renamed or deleted: no parse that began before makes its old folder again.""" + if not _jobs_folder(ws): + return False body = {n: getattr(job, n) for n in _JOB_FIELDS if n != "trials"} dumps = lambda obj: json.dumps(obj, default=_encode, ensure_ascii=False) # the C encoder; json.dump's is Python @@ -911,7 +927,11 @@ def write(fh): for i, t in enumerate(job.trials): fh.write(("," if i else "") + dumps(_trial_to_dict(t))) fh.write("]}}") - ondisk.write_whole(path, write) + try: + ondisk.write_whole(path, write) + except FileNotFoundError: # its folder moved away meanwhile + return False + return True def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: Callable | None = None) -> tuple: @@ -971,8 +991,7 @@ def _load_job(ws: Workspace, job_dir: str, index: dict, runs: Callable | None) - # a trial whose own files are as they were parses the same: kept, not read again reuse = lambda sub: before.get(sub) if old_sigs.get(sub) and old_sigs.get(sub) == trial_sigs.get(sub) else None job = parse.parse_job(job_dir, reuse=reuse) - if sig: - _write_cache(ws, path, sig, head, job) + if sig and _write_cache(ws, path, sig, head, job): with _DECODED_LOCK: _DECODED[path] = (sig, job, trial_sigs, head) _note_in_index(job_dir, job, index, sig, head) diff --git a/app/tests/test_standard_scored_cuts.py b/app/tests/test_standard_scored_cuts.py index 2acd0a44c..9d2c30289 100644 --- a/app/tests/test_standard_scored_cuts.py +++ b/app/tests/test_standard_scored_cuts.py @@ -291,6 +291,7 @@ def test_an_unknown_end_is_redacted_before_it_is_cached(self): self.assertEqual(trial.ended_by, "[REDACTED]") job = parse.Job("j", trial.dir, "model", "example", 1, None, None, [trial]) ws = workspace.Workspace("test", "Test", [], "", "", os.path.join(trial.dir, "workspace")) + os.mkdir(ws.dir) path = os.path.join(ws.jobs_dir, "cached.json") workspace._write_cache(ws, path, "sig", "head", job) with open(path) as handle: diff --git a/app/tests/test_standard_shard.py b/app/tests/test_standard_shard.py index 809b00a7b..b58a815d8 100644 --- a/app/tests/test_standard_shard.py +++ b/app/tests/test_standard_shard.py @@ -491,6 +491,7 @@ def test_a_fold_reads_as_the_merged_job(self): def test_a_fold_is_read_again_only_when_the_workspace_parses_a_shard_again(self): dirs = [write_shard(self.tmp, f"c{i}", self.split[i], i, 3) for i in (1, 2)] ws = workspace.Workspace("w", "W", [self.tmp], "2026-01-01", "2026-01-01", os.path.join(self.tmp, "ws"), [self.tmp]) + os.mkdir(ws.dir) with patch.object(merge, "check", wraps=merge.check) as check: first = launches.fold([workspace.load_job(ws, d)[0] for d in dirs]) self.assertEqual(launches.fold([workspace.load_job(ws, d)[0] for d in dirs]), first) diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index 81ee73569..238357082 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -830,12 +830,28 @@ 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) + kept = write(ws, *rest) workspace.rename(self.home, workspace.load(self.home, self.ws.name), "moved") - with patch.object(workspace, "_write_cache", side_effect=renamed): + return kept + with patch.object(workspace, "_write_cache", side_effect=renamed), \ + patch.object(workspace, "_update_index", wraps=workspace._update_index) as index_write: workspace.load_job(self.ws, self.job_dir) + self.assertEqual(index_write.call_count, 1) self.assertFalse(os.path.exists(self.ws.dir)) + def test_a_parse_that_outlives_a_rename_makes_no_old_folder(self): + parse_job = parse.parse_job + + def renamed(*args, **kwargs): # the other request, before the cache write + job = parse_job(*args, **kwargs) + workspace.rename(self.home, workspace.load(self.home, self.ws.name), "moved") + return job + with patch.object(parse, "parse_job", side_effect=renamed): + job, from_cache = workspace.load_job(self.ws, self.job_dir) + self.assertEqual((len(job.trials), from_cache), (2, False)) + self.assertFalse(os.path.exists(self.ws.dir)) + self.assertIsNone(workspace.load(self.home, self.ws.name, strict=True)) # the old name is free for a launch + def test_a_refresh_waits_for_an_index_write_and_leaves_no_entry(self): inside, go = threading.Event(), threading.Event() write = workspace._write_index @@ -855,10 +871,13 @@ def test_a_refresh_between_a_parse_and_its_index_write_leaves_no_entry(self): write = workspace._write_cache def refreshed(ws, *rest): # the other request, before the index lock is taken - write(ws, *rest) + kept = write(ws, *rest) workspace.clear_cache(ws) - with patch.object(workspace, "_write_cache", side_effect=refreshed): + return kept + with patch.object(workspace, "_write_cache", side_effect=refreshed), \ + patch.object(workspace, "_update_index", wraps=workspace._update_index) as index_write: workspace.load_job(self.ws, self.job_dir) + self.assertEqual(index_write.call_count, 1) self.assertEqual((workspace.job_index(self.ws), self.ws.n_cached), ({}, 0)) self.assertFalse(workspace.load_job(self.ws, self.job_dir)[1]) # parsed again, and listed with its parse self.assertEqual((list(workspace.job_index(self.ws)), self.ws.n_cached), ([self.job_dir], 1)) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 9d58b8b96..65f26d52d 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -1687,6 +1687,22 @@ def counted_again(): # (the counts, whether its self.assertNotIn(self.other().name, web.workspaces._COUNTS) self.assertEqual(counted_again()[1], True) # counted each time + def test_a_count_whose_workspace_moves_meanwhile_makes_no_old_folder(self): + for how, change in (("rename", lambda ws: workspace.rename(self.home, ws, "moved")), ("delete", lambda ws: workspace.delete(self.home, ws.name))): + with self.subTest(how): + other = workspace.create(self.home, [str(self.run_dir / "jobs")], label=how, opened=False) + write, done = workspace._write_cache, [] + + def moved(ws, *rest): # another request, before the parse is kept + if ws.name == other.name and not done: + done.append(change(workspace.load(self.home, other.name))) + return write(ws, *rest) + with patch.object(workspace, "_write_cache", side_effect=moved): + self.assertEqual(self.get("/workspaces").status_code, 200) + self.assertTrue(done) + self.assertFalse(os.path.exists(other.dir), os.listdir(other.dir) if os.path.isdir(other.dir) else "") + self.assertIsNone(workspace.load(self.home, other.name, strict=True)) # the old name is free for a launch + def test_counts_from_the_disk_are_todays_for_every_workspace(self): from tests.test_feasibility import write_job live = str(self.tmp / "live"); write_job(live, "l-a", "my-agent", {"a": 1}); write_job(live, "l-nop", "nop", {"a": 0})