diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index b1b8055f9..978e85e0b 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -100,6 +100,7 @@ import json import os import re +import uuid from typing import Callable, Dict, List, Optional, Tuple from urllib.parse import urlsplit @@ -2083,9 +2084,26 @@ def use_bundled(group: str, key: str, bundled_root: Optional[str] = None) -> Non if mine or set(held) & set(was["versions"]): kept = {v: b for v, b in was["versions"].items() if v not in held} proofs.write_own(user, dict(was, versions={**kept, **mine}), d, kind) + mark = _removal(group, key) + os.makedirs(os.path.dirname(mark), exist_ok=True) + ondisk.write_whole(mark, uuid.uuid4().hex) storage.use_bundled(group, key, bundled_root or CATALOGUE) +def _removal(group: str, key: str) -> str: + return os.path.join(paths.cache_dir(), "removed", group, key) + + +def removed(group: str, key: str) -> str: + """The mark of the last ``use_bundled`` of an entry, "" before any: a copy made + since is another entry, though its path, key and schema are the same.""" + try: + with open(_removal(group, key), encoding="utf-8") as f: + return f.read() + except OSError: + return "" + + def read_document(path: str, kind: str) -> dict: """An authored definition with sibling evidence, before semantic checks.""" with open(path) as f: @@ -2095,6 +2113,7 @@ def read_document(path: str, kind: str) -> dict: def _read(path: str, kind: str, key: str) -> Tuple[Optional[dict], List[str]]: + mark = removed(KINDS[kind]["dir"], key) # before the definition: a copy made since is not taken for this one try: d = read_document(path, kind) if kind == "benchmark": @@ -2113,7 +2132,7 @@ def _read(path: str, kind: str, key: str) -> Tuple[Optional[dict], List[str]]: if bad: return None, bad notes = warnings(d, kind) - d = dict(d, _here=os.path.dirname(path), _kind=kind) + d = dict(d, _here=os.path.dirname(path), _kind=kind, _removed=mark) if notes: # carried by each of its versions: ``nullius standard check`` says them once d["_warnings"] = [f"{said(kind)} {key}: {p}" for p in notes] if kind == "benchmark": @@ -2357,7 +2376,8 @@ def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None: current = read_document(path, d["_kind"]) selected = user and entry_dir(d["_kind"], d["key"]) # a copy made since hides the bundled entry if (not isinstance(current, dict) or current.get("key") != d["key"] or current.get("schema") != KINDS[d["_kind"]]["schema"] - or (selected and os.path.realpath(selected) != os.path.realpath(d["_here"]))): + or (selected and os.path.realpath(selected) != os.path.realpath(d["_here"])) + or (not user and removed(KINDS[d["_kind"]]["dir"], d["key"]) != d.get("_removed", ""))): # a copy made since reuses path, key and schema raise ValueError("the definition changed identity while its proof ran") version = d.get("_version", str((d.get("upstream") or {}).get("version") or "")) resolved = resolve(current, version) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 258ec7dcf..d25e0f00b 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -727,7 +727,8 @@ 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.""" + it out, and its parse goes too. Nor without its parse file as this reader left it: a + Refresh meanwhile took it, and the job is read again.""" 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) @@ -737,6 +738,9 @@ def _merge_index(ws: Workspace, now: dict, before: dict, after: dict) -> 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}) + elif was is None and not _cached_as(_cache_file(ws, d), new.get("signature")): + with _DECODED_LOCK: + _DECODED.pop(_cache_file(ws, d), None) else: now[d] = new @@ -837,6 +841,17 @@ def _read_cache(path: str, job_dir: str) -> tuple | None: return None +def _cached_as(path: str, sig: str | None) -> bool: + """Whether the cache file *path* is there, and written with the signature *sig* when + one is given: by its first bytes, as ``_write_cache`` lays them.""" + want = json.dumps({"signature": sig}, ensure_ascii=False)[:-1] if sig else "{" + try: + with open(path, encoding="utf-8") as fh: + return fh.read(len(want)) == want + except (OSError, ValueError): + 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) body = {n: getattr(job, n) for n in _JOB_FIELDS if n != "trials"} diff --git a/app/tests/test_catalogue_overlay.py b/app/tests/test_catalogue_overlay.py index 949be2303..611f0fed3 100644 --- a/app/tests/test_catalogue_overlay.py +++ b/app/tests/test_catalogue_overlay.py @@ -361,6 +361,20 @@ def test_a_proof_that_ends_after_use_bundled_does_not_bring_the_users_entry_back self.assertFalse((self.user / "agents" / "bot").exists()) # not a folder holding the definition alone self.assertEqual(definitions.get("agent", "bot")["_here"], str(folder)) + def test_a_proof_started_on_a_copy_is_not_saved_onto_the_copy_that_replaced_it(self): + folder = self.definition(self.bundle, "agent", AGENT) + (folder / "agent.py").write_text("the agent") + copy = Path(definitions.writable_dir("agent", "bot")) + running = definitions.get("agent", "bot") # a proof starts, on the user's copy + definitions.use_bundled("agents", "bot") + self.assertEqual(Path(definitions.writable_dir("agent", "bot")), copy) # a new copy: same path, key and schema + (copy / "agent.py").write_text("another agent") + with self.assertRaisesRegex(ValueError, "changed identity"): + definitions.save(running, lambda cur: cur.update(proven={"agent.task/v1": {"passed": "7/7", "on": "2026-10-27"}})) + self.assertFalse((copy / "proofs.json").exists()) + definitions.save(definitions.get("agent", "bot")) # one started on the new copy saves + self.assertTrue((copy / "proofs.json").is_file()) + def test_flat_proof_save_leaves_authored_fields_and_explicit_fixtures_unchanged(self): self.definition(self.bundle, "module", MODULE) before = self.tree(self.bundle) diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index 825db5f78..f10269e51 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -795,6 +795,18 @@ def held_up(ws, index): go.set(); writer.join(); refresh.join() self.assertEqual(workspace.job_index(self.ws), {}) + 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) + workspace.clear_cache(ws) + with patch.object(workspace, "_write_cache", side_effect=refreshed): + workspace.load_job(self.ws, self.job_dir) + 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)) + def test_corrupt_cache_falls_back_to_parse(self): workspace.load_job(self.ws, self.job_dir) path = workspace._cache_file(self.ws, self.job_dir)