From ea47d96e919294142a02f20bd254ba1cdc8fc53a Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 1 Dec 2026 20:15:16 +0100 Subject: [PATCH] fix(catalogue): keep a bundled entry's proofs apart instead of copying the entry A proof of a bundled entry is written to proofs///proofs.json in the user data directory, its version alone, and read over the bundled evidence. The entry is still read from the bundle. A version the bundle does not declare stays in that file, unread. Use bundled entry keeps the proofs a user copy held, and keeps the copy when the bundled entry cannot take them or they cannot be written. An edit writes them into the copy; a host is sent them in the entry's one document, or not the entry when it is refused here. Proof save, copy and restore share one lock per entry. Closes #367 --- .agents/skills/import-standard/SKILL.md | 5 +- .claude/rules/running.md | 2 +- AGENTS.md | 2 +- app/nullius/catalogue/catalog.py | 3 +- app/nullius/catalogue/storage.py | 7 +- app/nullius/paths.py | 7 +- app/nullius/standard/contract/definitions.py | 152 ++++++++++++++++--- app/nullius/standard/contract/proofs.py | 81 +++++++++- app/nullius/standard/runner/payload.py | 6 + app/tests/test_catalogue_overlay.py | 133 +++++++++++++--- app/tests/test_standard_payload.py | 15 ++ app/ui_tests/test_use_bundled.py | 20 +++ app/web/catalogue.py | 5 +- docs/getting-started.md | 2 +- docs/settings/README.md | 3 +- docs/standard.md | 7 +- 16 files changed, 393 insertions(+), 57 deletions(-) diff --git a/.agents/skills/import-standard/SKILL.md b/.agents/skills/import-standard/SKILL.md index ee83c759f..e224aa264 100644 --- a/.agents/skills/import-standard/SKILL.md +++ b/.agents/skills/import-standard/SKILL.md @@ -74,8 +74,9 @@ interpreter: it copies a bundled entry's whole folder to the user catalogue and returns the writable path. For a new key, create the returned directory, or let `cli new` create it. A user folder replaces the bundled folder **in full**, even if incomplete: keep its JSON, drivers, wrappers, model templates -and other resources together. `new version`, `conform` and `prove` write user -copies too. Never edit `site-packages`. +and other resources together. `new version` writes a user copy too; `conform` +and `prove` copy nothing: a bundled entry's proofs go to `paths.proofs_dir()`. +Never edit `site-packages`. Default to a personal import in `paths.catalogue_dir()` (Linux default: `~/.local/share/nullius/catalogue/`), in `benchmarks/KEY`, `agents/KEY` or diff --git a/.claude/rules/running.md b/.claude/rules/running.md index a1c0187c4..d6422991d 100644 --- a/.claude/rules/running.md +++ b/.claude/rules/running.md @@ -35,7 +35,7 @@ automatically: `nullius migrate --from CHECKOUT` previews, `--apply` copies. A set `WORKSPACES_DIR` and raw runs stay where they are; default workspaces are copied. Migrated catalogue entries keep their versions across upgrades as user overrides; **Use bundled entry** on an entry's page removes -its user override, including local proof records, to resume bundled updates. +its user override, keeping its local proof records, to resume bundled updates. Existing destination entries must match exactly. Conflicts stop migration before copying. diff --git a/AGENTS.md b/AGENTS.md index 00d39be78..1f25d8b86 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -128,7 +128,7 @@ Add neither by default. another source or someone's fixes; never a change of our driver. Bring an official version first. - Definitions hold configuration. Proof runs write only `proofs.json`: a bundled - entry's in a user copy, which then hides the bundled one. Read both through + entry's under `paths.proofs_dir()`, copying nothing. Read both through `contract/definitions.py`; never infer proven ports from raw JSON. ## Issues and pull requests diff --git a/app/nullius/catalogue/catalog.py b/app/nullius/catalogue/catalog.py index 1da9eedec..3557d0c99 100644 --- a/app/nullius/catalogue/catalog.py +++ b/app/nullius/catalogue/catalog.py @@ -309,7 +309,8 @@ def entry_dir(key: str, root: str | None = None) -> str | None: def writable_dir(key: str, root: str | None = None) -> str: - return storage.writable_dir(BENCHMARKS, key, ROOT, root) + from nullius.standard.contract import definitions # it reads this module + return definitions.copied("benchmark", key, root, ROOT) def signature(root: str | None = None) -> tuple: diff --git a/app/nullius/catalogue/storage.py b/app/nullius/catalogue/storage.py index 43c48c3d8..908563718 100644 --- a/app/nullius/catalogue/storage.py +++ b/app/nullius/catalogue/storage.py @@ -65,11 +65,12 @@ def ensure_writable(target: str, bundled: str) -> None: raise ValueError("the bundled catalogue is read-only; use the user catalogue") -def writable_dir(group: str, key: str, bundled: str, root: str | None = None) -> str: +def writable_dir(group: str, key: str, bundled: str, root: str | None = None, prepare=None) -> str: """Copy a selected bundled folder in full before returning its user copy. An existing user folder is left intact. Staging keeps an interrupted copy - from shadowing a bundled entry with half of its files. + from shadowing a bundled entry with half of its files; ``prepare`` is given + the staged copy before it takes its place. """ if not key or key in (".", "..") or os.path.basename(key) != key: raise ValueError("an entry key is a folder name") @@ -94,6 +95,8 @@ def writable_dir(group: str, key: str, bundled: str, root: str | None = None) -> for name in files: path = os.path.join(folder, name) os.chmod(path, os.stat(path).st_mode | stat.S_IWUSR) + if prepare: + prepare(copied) os.rename(copied, target) return target diff --git a/app/nullius/paths.py b/app/nullius/paths.py index f24739850..4cd3d4890 100644 --- a/app/nullius/paths.py +++ b/app/nullius/paths.py @@ -62,6 +62,11 @@ def catalogue_dir(env=None) -> str: return env.get("NULLIUS_CATALOGUE") or os.path.join(data_dir(env), "catalogue") +def proofs_dir(env=None) -> str: + """The user's proofs of bundled catalogue entries.""" + return os.path.join(data_dir(env), "proofs") + + def workspaces_dir(env=None) -> str: env = os.environ if env is None else env return env.get("WORKSPACES_DIR") or os.path.join(data_dir(env), "workspaces") @@ -85,7 +90,7 @@ def main(argv=None) -> int: parser = argparse.ArgumentParser(prog="nullius paths", description="Show Nullius's persistent user directories (no secret values).") parser.add_argument("--json", action="store_true") args = parser.parse_args(argv) - values = {"settings": settings_file(), "secrets": secrets_dir(), "prices": prices_file(), "own prices": own_prices_file(), "catalogue": catalogue_dir(), + values = {"settings": settings_file(), "secrets": secrets_dir(), "prices": prices_file(), "own prices": own_prices_file(), "catalogue": catalogue_dir(), "proofs": proofs_dir(), "workspaces": workspaces_dir(), "runs": runs_dir(), "recipes": recipes_dir(), "cache": cache_dir()} if args.json: print(json.dumps(values, indent=2)) diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 434a3fa2a..900b95acb 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1874,14 +1874,115 @@ def writable_dir(kind: str, key: str, root: Optional[str] = None) -> str: """The user folder, copying all bundled files before an edit if needed.""" if not _KEY.fullmatch(key): raise ValueError("a key is lower case letters, digits and dashes") - return storage.writable_dir(KINDS[names.kind(kind)]["dir"], key, CATALOGUE, root) + return copied(kind, key, root) + + +def copied(kind: str, key: str, root: Optional[str] = None, bundled: Optional[str] = None) -> str: + """The user folder of an entry, first copied from ``bundled`` if it is + there alone. The user's proofs of the bundled entry are written into the + copy before it takes its place.""" + kind = names.kind(kind) + group = KINDS[kind]["dir"] + with _lock(f"{group}/{key}"): + source = storage.entry_dir(group, key, bundled or CATALOGUE, root) + evidence = with_own(source, kind) if source else None + return storage.writable_dir(group, key, bundled or CATALOGUE, root, + (lambda staged: proofs.write(staged, evidence)) if evidence else None) + + +def _own(folder: str, kind: str) -> Optional[str]: + """Where the user's proofs of a bundled entry are kept, apart from the + package and the user catalogue; None for a folder outside the bundle.""" + try: + storage.ensure_writable(folder, CATALOGUE) + except ValueError: + return os.path.join(paths.proofs_dir(), KINDS[names.kind(kind)]["dir"], os.path.basename(folder)) + return None + + +def with_own(folder: str, kind: str) -> Optional[dict]: + """A bundled entry's evidence with the user's proofs of it, as its copy + or a host is given it in one ``proofs.json``; None when the user has none.""" + kind = names.kind(kind) + user, path = _own(folder, kind), definition_path(folder, kind) + if not user or not os.path.lexists(os.path.join(user, proofs.FILE)) or not os.path.isfile(path): + return None + with open(path) as f: + return proofs.combined(names.definition(json.load(f)), kind, folder, user) + + +class Unfit(ValueError): + """A user copy's proofs that the bundled entry cannot take: the copy stays.""" + + +def _held(folder: str, d: Optional[dict], kind: str) -> dict: + """The version blocks a user copy holds as evidence of the bundled ``d``: + its ``proofs.json``, else what its definition embeds. A bundled entry + without a definition, ``d`` None, can take none.""" + file = os.path.join(folder, proofs.FILE) + try: + value = proofs.read(folder) + except ValueError: + value = [] # not a document: said below + if value is None: + file = definition_path(folder, kind) + try: + with open(file) as f: + value = proofs.document(names.definition(json.load(f)), kind) + except (FileNotFoundError, ValueError, TypeError, AttributeError, KeyError): + return {} # a definition that does not read embeds no evidence + value["versions"] = {v: b for v, b in value["versions"].items() if b} + if not value["versions"]: + return {} + if d is None: + vs = value.get("versions") if isinstance(value, dict) else None + bad = sorted(v for v, b in vs.items() if b and (not isinstance(b, dict) or any(b.values()))) \ + if isinstance(vs, dict) else [""] + value = {"versions": {}} + else: + bad = proofs.unfit(value, d, kind) + if bad: + of = ", ".join(v for v in bad if v) + raise Unfit(f"{said(kind).capitalize()} {os.path.basename(folder)}: the copy is kept. Its proofs" + f"{' of ' + of if of else ''} do not fit the bundled entry; remove them from {file} first.") + return value["versions"] + + +def use_bundled(group: str, key: str, bundled_root: Optional[str] = None) -> None: + """Remove the user's copy of a bundled entry, of ``bundled_root`` for a + catalogue-only benchmark. The proofs it holds that the bundle does not + are kept, as the user's proofs of the bundled entry, and replace the ones + kept before of the versions it holds; ``Unfit`` before anything is + removed when the bundled entry cannot take them.""" + kind = next((k for k, spec in KINDS.items() if spec["dir"] == group), None) + with _lock(f"{group}/{key}"): + bundled = kind and storage.can_restore(group, key, CATALOGUE) and entry_dir(kind, key, root=CATALOGUE) + if bundled: + path, d, held = definition_path(bundled, kind), None, {} + if os.path.isfile(path): + with open(path) as f: + d = names.definition(json.load(f)) + for directory in (storage.LEGACY if group == "modules" else (group,)): + folder = os.path.join(paths.catalogue_dir(), directory, key) + if os.path.isdir(folder): + held.update(_held(folder, d, kind)) + if held: + shipped = (proofs.read(bundled) or proofs.document(d, kind))["versions"] + user = _own(bundled, kind) + was = proofs.own(d, kind, user) or dict(proofs.document(d, kind), versions={}) + mine = {v: b for v, b in held.items() if b != shipped.get(v)} + 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) + storage.use_bundled(group, key, bundled_root or CATALOGUE) def read_document(path: str, kind: str) -> dict: """An authored definition with sibling evidence, before semantic checks.""" with open(path) as f: d = names.definition(json.load(f)) - return proofs.attach(d, names.kind(kind), os.path.dirname(path)) + folder = os.path.dirname(path) + return proofs.attach(d, names.kind(kind), folder, _own(folder, kind)) def _read(path: str, kind: str, key: str) -> Tuple[Optional[dict], List[str]]: @@ -2091,17 +2192,34 @@ def path_of(d: dict) -> str: return definition_path(d["_here"], d["_kind"]) +def _slot(folder: str) -> Optional[str]: + """``group/key`` for an entry folder of the bundled or the user catalogue.""" + parent, key = os.path.split(os.path.realpath(folder)) + base, group = os.path.split(parent) + group = "modules" if group in storage.LEGACY else group + if group in {spec["dir"] for spec in KINDS.values()} and base in {os.path.realpath(r) for r in storage.roots(CATALOGUE)}: + return f"{group}/{key}" + return None + + @contextlib.contextmanager -def _locked(path: str): - """One writer of a definition file at a time, across processes.""" +def _lock(name: str): where = os.path.join(paths.cache_dir(), "locks") os.makedirs(where, exist_ok=True) - with ondisk.locked(os.path.join(where, hashlib.sha256(os.path.realpath(path).encode()).hexdigest()[:24])): + with ondisk.locked(os.path.join(where, hashlib.sha256(name.encode()).hexdigest()[:24])): yield +def _locked(path: str): + """One writer of an entry at a time, across processes: of its definition, + its proofs, its copy and the copy's removal. A catalogue entry is one + whichever folder holds it; any other is its file.""" + return _lock(_slot(os.path.dirname(path)) or os.path.realpath(path)) + + def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None: - """Write only generated evidence to the entry's sibling ``proofs.json``. + """Write only generated evidence to the entry's sibling ``proofs.json``; + a bundled entry's to the user's proofs of it, its version alone. ``change``: what the run decided, applied to the definition as it is on disk now, under a lock - not to the copy loaded when a long run started, @@ -2111,18 +2229,13 @@ def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None: Without it, save the caller's evidence for its version. Authored fields are never written, including legacy embedded evidence; the sibling then supersedes that evidence. A deleted or replaced definition is refused.""" - # Explicit fixture roots remain local. Only a loaded bundled entry needs - # copying; helpers and model files beside its definition must follow it. - folder = d["_here"] - inside = os.path.realpath(folder).startswith(os.path.join(os.path.realpath(CATALOGUE), "")) # never scan the bundle for a user entry - bundled = inside and entry_dir(d["_kind"], d["key"], root=CATALOGUE) # under any of a Module's folder names - if bundled and os.path.realpath(folder) == os.path.realpath(bundled): - d["_here"] = writable_dir(d["_kind"], d["key"]) - storage.ensure_writable(d["_here"], CATALOGUE) + user = _own(d["_here"], d["_kind"]) # explicit fixture roots remain local path = path_of(d) with _locked(path): current = read_document(path, d["_kind"]) - if not isinstance(current, dict) or current.get("key") != d["key"] or current.get("schema") != KINDS[d["_kind"]]["schema"]: + 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"]))): 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) @@ -2134,10 +2247,15 @@ def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None: else: work = {"offers": d.get("offers") or [], "proven": d.get("proven") or {}} evidence = proofs.document(current, d["_kind"]) + if user: + evidence["versions"] = dict((proofs.own(current, d["_kind"], user) or {}).get("versions") or {}) fields = ("proven",) if d["_kind"] == "benchmark" or "versions" in current else proofs.FIELDS evidence["versions"][version] = {f: work[f] for f in fields} - proofs.validate(evidence, current, d["_kind"]) - proofs.write(d["_here"], evidence) + if user: + proofs.write_own(user, evidence, current, d["_kind"]) + else: + proofs.validate(evidence, current, d["_kind"]) + proofs.write(d["_here"], evidence) d["proven"] = work["proven"] if d["_kind"] != "benchmark": d["offers"] = ([p for p in ports.PORTS if p in d["proven"]] diff --git a/app/nullius/standard/contract/proofs.py b/app/nullius/standard/contract/proofs.py index 2021e95cb..b419cd670 100644 --- a/app/nullius/standard/contract/proofs.py +++ b/app/nullius/standard/contract/proofs.py @@ -6,7 +6,9 @@ Versioned participants derive offers from their own proven ports as before. An existing document replaces all embedded evidence; an absent document keeps -legacy definitions readable. Never combine evidence from different folders. +legacy definitions readable. Never combine evidence from different folders, +but for a bundled entry: the user's proofs of it are kept apart, in the same +document, and each version block there replaces the bundle's. Writers hold the definition's lock while reading, changing and replacing it. """ from __future__ import annotations @@ -98,16 +100,81 @@ def _unique(pairs): return out -def attach(d: dict, kind: str, folder: str) -> dict: - """Read sibling evidence, or keep embedded legacy evidence when absent.""" - if not isinstance(d, dict): - return d +def read(folder: str): + """A folder's evidence document as written, or None without one.""" try: with open(os.path.join(folder, FILE)) as f: - value = json.load(f, object_pairs_hook=_unique) + return json.load(f, object_pairs_hook=_unique) except FileNotFoundError: - return d + return None + + +def own(d: dict, kind: str, folder: str): + """The user's proofs of a bundled entry, kept in ``folder``, or None. + A version the bundle no longer declares is left out, never refused.""" + value = read(folder) + if value is None: + return None + if isinstance(value, dict) and isinstance(value.get("versions"), dict): + declared = blocks(d) + value = dict(value, versions={v: b for v, b in value["versions"].items() if v in declared}) validate(value, d, kind) + return value + + +def unfit(value, d: dict, kind: str) -> list: + """The versions of ``value`` that ``validate`` refuses for ``d``, each on + its own; all of them for another entry's document. A version ``d`` does + not declare is none of them.""" + vs = value.get("versions") if isinstance(value, dict) else None + if not isinstance(vs, dict): + return [""] + try: + validate(dict(value, versions={}), d, kind) + except ValueError: + return list(vs) or [""] + bad = [] + for v in set(vs) & set(blocks(d)): + try: + validate(dict(value, versions={v: vs[v]}), d, kind) + except ValueError: + bad.append(v) + return sorted(bad) + + +def write_own(folder: str, value: dict, d: dict, kind: str) -> None: + """Replace the user's proofs of a bundled entry, kept in ``folder``. The + blocks there of versions ``d`` does not declare stay, unread, for a bundle + that declares them again.""" + declared = blocks(d) + validate(dict(value, versions={v: b for v, b in value["versions"].items() if v in declared}), d, kind) + was = read(folder) + old = was.get("versions") if isinstance(was, dict) else None + extra = {v: b for v, b in old.items() if v not in declared} if isinstance(old, dict) else {} + os.makedirs(folder, exist_ok=True) + write(folder, dict(value, versions={**extra, **value["versions"]})) + + +def combined(d: dict, kind: str, folder: str, user: str | None = None): + """The evidence read with ``d``: its folder's document, with the version + blocks of a bundled entry's ``user`` proofs over it. None without either.""" + value = read(folder) + if value is not None: + validate(value, d, kind) + mine = own(d, kind, user) if user else None + if mine is None: + return value + value = value or document(d, kind) + return dict(value, versions={**value["versions"], **mine["versions"]}) + + +def attach(d: dict, kind: str, folder: str, user: str | None = None) -> dict: + """Read sibling evidence, or keep embedded legacy evidence when absent.""" + if not isinstance(d, dict): + return d + value = combined(d, kind, folder, user) + if value is None: + return d out = strip(d) for v, b in blocks(out).items(): evidence = names.definition(copy.deepcopy(value["versions"].get(v, {}))) diff --git a/app/nullius/standard/runner/payload.py b/app/nullius/standard/runner/payload.py index e99d5f56b..180bf42df 100644 --- a/app/nullius/standard/runner/payload.py +++ b/app/nullius/standard/runner/payload.py @@ -257,6 +257,12 @@ def build(cache: str, *, package: Path | None = None, catalogue: str | None = No contents = _entry(entry) except json.JSONDecodeError: continue # Unfinished JSON drafts are not runnable catalogue entries. + try: # the user's proofs of a bundled entry travel in its one document + own = definitions.with_own(str(entry), kind[:-1]) + except (OSError, ValueError, TypeError, AttributeError): + continue # refused here when read, so not sent as if it ran + if own: + contents["proofs.json"] = ((json.dumps(own, indent=2) + "\n").encode(), 0o644) files.update({f"catalogue/{kind}/{name}/{r}": value for r, value in contents.items()}) for bench, name in sets or (): try: diff --git a/app/tests/test_catalogue_overlay.py b/app/tests/test_catalogue_overlay.py index 842dde76a..949be2303 100644 --- a/app/tests/test_catalogue_overlay.py +++ b/app/tests/test_catalogue_overlay.py @@ -6,12 +6,13 @@ from pathlib import Path import shutil import tempfile +import threading import unittest from unittest.mock import patch from nullius import paths from nullius.catalogue import catalog, harbor_entry, storage -from nullius.standard.contract import definitions +from nullius.standard.contract import definitions, proofs from nullius.standard.requirements import install from .test_harbor_entry import form from .test_standard_definitions import AGENT, BENCH, MODULE @@ -231,34 +232,128 @@ def test_invalid_definition_override_is_reported_without_fallback(self): self.assertIsNone(definitions.get("agent", "bot")) self.assertEqual(definitions.load("agent"), ([], ["agent bot: missing agent.json"])) - def test_proof_save_copies_bundle_and_preserves_other_version_and_files(self): + def test_proof_save_on_a_bundled_entry_copies_nothing_and_is_read_with_it(self): folder = self.definition(self.bundle, "agent", VERSIONED) - (folder / "template.toml").write_text("template contents") before = self.tree(self.bundle) loaded = definitions.get("agent", "bot@2.0.0") loaded["proven"] = {"agent.task/v1": {"passed": "1/1", "on": "2026-10-27"}} definitions.save(loaded) - path = self.user / "agents" / "bot" / "agent.json" - self.assertEqual(json.loads(path.read_text()), VERSIONED) - raw = definitions.read_document(str(path), "agent") - self.assertEqual(raw["versions"]["1.0.0"], VERSIONED["versions"]["1.0.0"]) - self.assertEqual(raw["versions"]["2.0.0"]["proven"], loaded["proven"]) - self.assertEqual(raw["start"], VERSIONED["start"]) - self.assertEqual(loaded["_here"], str(path.parent)) - self.assertEqual((path.parent / "template.toml").read_text(), "template contents") + self.assertFalse(self.user.exists()) self.assertEqual(self.tree(self.bundle), before) - # a Module still in the package's earlier folder is copied the same way + self.assertEqual(loaded["_here"], str(folder)) + kept = Path(paths.proofs_dir(), "agents", "bot", "proofs.json") + self.assertEqual(list(json.loads(kept.read_text())["versions"]), ["2.0.0"]) + again = definitions.get("agent", "bot@2.0.0") + self.assertEqual((again["_here"], again["from"], again["proven"]), (str(folder), "bundled", loaded["proven"])) + # the other version, and a later bundle, are still the bundle's + self.assertEqual(definitions.get("agent", "bot@1.0.0")["proven"], VERSIONED["versions"]["1.0.0"]["proven"]) + later = json.loads(json.dumps(VERSIONED).replace("2.0.0", "3.0.0")) + self.definition(self.bundle, "agent", dict(later, label="Later")) + self.assertEqual([(d["label"], d["proven"]) for d in definitions.load("agent", every=True)[0] if d["_version"] == "3.0.0"], + [("Later", {})]) + # a Module still in the package's earlier folder keeps its proofs the same way self.write(self.bundle, "capabilities", "mem", "capability.json", MODULE) - before = self.tree(self.bundle) - definitions.save(definitions.get("module", "mem")) - self.assertTrue((self.user / "modules" / "mem" / "proofs.json").is_file()) - self.assertEqual(self.tree(self.bundle), before) + definitions.save(definitions.get("module", "mem"), lambda cur: cur["proven"]["cap.memory/v1"].update(passed="9/9")) + self.assertTrue(Path(paths.proofs_dir(), "modules", "mem", "proofs.json").is_file()) + self.assertEqual(definitions.get("module", "mem")["proven"]["cap.memory/v1"]["passed"], "9/9") + self.assertFalse(self.user.exists()) + + def test_use_bundled_keeps_the_proofs_a_copy_held(self): + folder = self.definition(self.bundle, "agent", VERSIONED) + (folder / "proofs.json").write_text(json.dumps(proofs.document(VERSIONED, "agent"))) + shipped = VERSIONED["versions"]["1.0.0"]["proven"] + mine = {"agent.task/v1": {"passed": "1/1", "version": "2.0.0"}} + copy = Path(storage.writable_dir("agents", "bot", str(self.bundle))) # as a proof alone left it before + evidence = json.loads((copy / "proofs.json").read_text()) + evidence["versions"]["2.0.0"] = {"proven": mine} + (copy / "proofs.json").write_text(json.dumps(evidence)) + self.assertEqual(definitions.get("agent", "bot@2.0.0")["proven"], mine) + self.assertEqual(definitions.get("agent", "bot@2.0.0")["_here"], str(copy)) + definitions.use_bundled("agents", "bot") + self.assertFalse(self.user.joinpath("agents", "bot").exists()) + self.assertEqual(definitions.get("agent", "bot@2.0.0")["proven"], mine) + kept = json.loads(Path(paths.proofs_dir(), "agents", "bot", "proofs.json").read_text()) + self.assertEqual(kept["versions"], {"2.0.0": {"proven": mine}}) # what the bundle ships still follows it + self.assertEqual(definitions.get("agent", "bot@1.0.0")["proven"], shipped) + # an edit copies the entry with the user's proofs of it; proofs of a version the bundle lacks stay on disk, unread + copy = Path(definitions.writable_dir("agent", "bot")) + self.assertEqual(definitions.get("agent", "bot@2.0.0")["proven"], mine) + (copy / "proofs.json").write_text(json.dumps(dict(evidence, versions={"9.9.9": {"proven": mine}}))) + definitions.use_bundled("agents", "bot") + self.assertEqual(definitions.get("agent", "bot@2.0.0")["proven"], mine) + definitions.save(definitions.get("agent", "bot@2.0.0")) + kept = Path(paths.proofs_dir(), "agents", "bot", "proofs.json") + self.assertEqual(set(json.loads(kept.read_text())["versions"]), {"2.0.0", "9.9.9"}) + # a copy back on what the bundle ships ends the user's earlier proof of that version, and no other + copy = Path(definitions.writable_dir("agent", "bot")) + (copy / "proofs.json").write_text((folder / "proofs.json").read_text()) + definitions.use_bundled("agents", "bot") + self.assertEqual(definitions.get("agent", "bot@2.0.0")["proven"], {}) + self.assertEqual(set(json.loads(kept.read_text())["versions"]), {"9.9.9"}) + + def test_use_bundled_keeps_the_copy_when_its_proofs_cannot_be_kept(self): + folder = self.definition(self.bundle, "agent", VERSIONED) + newer = {"proven": {"agent.task/v1": {"passed": "8/8", "version": "2.0.0"}}} + document = dict(proofs.document(VERSIONED, "agent"), versions={"2.0.0": newer}) + copy = Path(storage.writable_dir("agents", "bot", str(self.bundle))) + kept = Path(paths.proofs_dir(), "agents", "bot", "proofs.json") + (copy / "proofs.json").write_text(json.dumps(dict(document, key="other"))) # another agent's + with self.assertRaisesRegex(definitions.Unfit, r"^Agent bot: .* of 2\.0\.0 .*proofs\.json"): + definitions.use_bundled("agents", "bot") + (copy / "proofs.json").write_text(json.dumps(document)) + with patch.object(proofs, "write", side_effect=OSError(28, "No space left on device")), self.assertRaises(OSError): + definitions.use_bundled("agents", "bot") + self.assertTrue(copy.is_dir()) + self.assertFalse(kept.exists()) + # a proof that ends while the copy goes waits for it, and is refused: never written to a folder being removed + remove, running, ended, threads = storage.use_bundled, definitions.get("agent", "bot@2.0.0"), [], [] + + def removing(*args): + def save(): + try: + definitions.save(running) + except Exception as error: + ended.append(type(error)) + saving = threading.Thread(target=save) + saving.start() + saving.join(0.3) + ended.append(saving.is_alive()) + remove(*args) + threads.append(saving) + + with patch.object(storage, "use_bundled", removing): + definitions.use_bundled("agents", "bot") + threads.pop().join() + self.assertEqual(ended, [True, FileNotFoundError]) + self.assertEqual(json.loads(kept.read_text())["versions"], {"2.0.0": newer}) + # a copy from before proofs.json holds its evidence in its definition + self.definition(self.bundle, "module", MODULE) + (folder.parent.parent / "modules" / "mem" / "proofs.json").write_text(json.dumps(dict(proofs.document(MODULE, "module")))) + legacy = json.loads(json.dumps(MODULE).replace("1/1", "7/7")) + self.definition(self.user, "module", legacy) + definitions.use_bundled("modules", "mem") + self.assertEqual(definitions.get("module", "mem")["proven"], legacy["proven"]) + # a catalogue-only bundled benchmark has no definition to take the proofs of the copy's + self.benchmark(self.bundle) + copy = Path(catalog.writable_dir("toy")) + self.definition(self.user, "benchmark", dict(BENCH, proven={"all": {"units": {"passed": "3 ids"}}})) + with self.assertRaisesRegex(definitions.Unfit, r"^Benchmark toy: .*standard\.json"): + definitions.use_bundled("benchmarks", "toy") + self.assertTrue(copy.is_dir()) + + def test_a_benchmark_copied_for_an_edit_keeps_the_users_proofs_of_it(self): + self.definition(self.bundle, "benchmark", BENCH) + proven = {"all": {"units": {"passed": "3 ids"}}} + definitions.save(dict(definitions.get("benchmark", "toy"), proven=proven)) + self.assertEqual(definitions.get("benchmark", "toy")["proven"], proven) + self.assertEqual(catalog.writable_dir("toy"), str(self.user / "benchmarks" / "toy")) # as the logo editor asks + self.assertEqual(definitions.get("benchmark", "toy")["proven"], proven) def test_a_proof_that_ends_after_use_bundled_does_not_bring_the_users_entry_back(self): folder = self.definition(self.bundle, "agent", AGENT) (folder / "agent.py").write_text("the agent") - definitions.save(definitions.get("agent", "bot"), lambda cur: cur.update(summary="proven once")) - running = definitions.get("agent", "bot") # a second proof starts, on the user's copy + definitions.writable_dir("agent", "bot") + running = definitions.get("agent", "bot") # a proof starts, on the user's copy self.assertEqual(running["_here"], str(self.user / "agents" / "bot")) storage.use_bundled("agents", "bot", str(self.bundle)) with self.assertRaises(FileNotFoundError): @@ -273,7 +368,7 @@ def test_flat_proof_save_leaves_authored_fields_and_explicit_fixtures_unchanged( loaded["summary"] = "Updated" definitions.save(loaded) self.assertEqual(definitions.get("module", "mem")["summary"], MODULE["summary"]) - self.assertTrue((self.user / "modules" / "mem" / "proofs.json").is_file()) + self.assertTrue(Path(paths.proofs_dir(), "modules", "mem", "proofs.json").is_file()) self.assertEqual(self.tree(self.bundle), before) fixture = self.bundle.parent / "fixture" folder = self.definition(fixture, "module", MODULE) diff --git a/app/tests/test_standard_payload.py b/app/tests/test_standard_payload.py index afb10dfd5..6e993a80d 100644 --- a/app/tests/test_standard_payload.py +++ b/app/tests/test_standard_payload.py @@ -117,6 +117,21 @@ def test_effective_user_entry_replaces_the_whole_bundled_folder(self): self.assertFalse((entry / "proofs.json").exists(), "an override cannot borrow bundled evidence") self.assertEqual((entry / "driver.py").read_text(), "print('sample')\n") + def test_the_users_proofs_of_a_bundled_entry_travel_in_its_one_document(self): + self.bench(self.package / "catalogue") + mine = {"schema": "nullius.proofs/v1", "kind": "benchmark", "key": "sample", + "versions": {"": {"proven": {"main": {"units": {"passed": "1 id"}}}}}} + self.write(Path(paths.proofs_dir(), "benchmarks/sample/proofs.json"), mine) + with patch.object(definitions, "CATALOGUE", str(self.package / "catalogue")): + _, here = self.build() + self.assertEqual(json.loads((Path(here) / "app/nullius/catalogue/benchmarks/sample/proofs.json").read_text()), mine) + # proofs this machine refuses the entry for: the entry is not sent on the bundle's alone + self.write(Path(paths.proofs_dir(), "benchmarks/sample/proofs.json"), dict(mine, key="other")) + with patch.object(definitions, "CATALOGUE", str(self.package / "catalogue")): + self.assertIsNone(definitions.get("benchmark", "sample")) + _, here = self.build() + self.assertFalse((Path(here) / "app/nullius/catalogue/benchmarks/sample").exists()) + def test_definition_code_template_and_permissions_all_change_the_address(self): entry = self.bench(self.catalogue) self.write(entry / "standard.json", {"driver": {"command": ["python3", "{here}/driver.py"]}, diff --git a/app/ui_tests/test_use_bundled.py b/app/ui_tests/test_use_bundled.py index 94fcc9008..c8fa4a1ef 100644 --- a/app/ui_tests/test_use_bundled.py +++ b/app/ui_tests/test_use_bundled.py @@ -58,6 +58,26 @@ def test_all_entry_pages_restore_their_bundle_and_clear_the_action(self): self.assertNotIn(b"Customized entry", response.data) self.assertNotIn(b"Use bundled entry", response.data) + def test_a_proof_of_a_bundled_entry_shows_on_its_page_and_survives_a_copy_and_its_removal(self): + record = lambda cur: cur["proven"]["agent.task/v1"].update(passed="41/41") + definitions.save(definitions.get("agent", "goose"), record) + self.assertFalse((self.root / "catalogue").exists()) + page = self.client.get("/agents/goose").data + self.assertIn(b"41/41", page) + self.assertNotIn(b"Use bundled entry", page) + folder = self.override("agents", "goose", "agent.json") + definitions.save(definitions.get("agent", "goose"), record) # proven on the copy, as before + self.client.post("/catalogue/agents/goose/use-bundled", data={"csrf": "restore-test"}) + self.assertFalse(folder.exists()) + self.assertIn(b"41/41", self.client.get("/agents/goose").data) + # proofs the bundled entry cannot take: the copy stays, and the page says which + folder = self.override("agents", "goose", "agent.json") + document = json.loads((folder / "proofs.json").read_text()) + (folder / "proofs.json").write_text(json.dumps(dict(document, key="other"))) + response = self.client.post("/catalogue/agents/goose/use-bundled", data={"csrf": "restore-test"}, follow_redirects=True) + self.assertTrue(folder.exists()) + self.assertIn(b"Agent goose: the copy is kept.", response.data) + def test_a_reset_form_open_since_before_the_rename_still_resets(self): folder = self.override("modules", "keyword-memory", "capability.json") response = self.client.post("/catalogue/capabilities/keyword-memory/use-bundled", data={"csrf": "restore-test"}) diff --git a/app/web/catalogue.py b/app/web/catalogue.py index d48504c9b..87dcb70d6 100644 --- a/app/web/catalogue.py +++ b/app/web/catalogue.py @@ -458,7 +458,10 @@ def catalogue_use_bundled(group, key): abort(404) bundled = catalog.ROOT if group == "benchmarks" else standard_definitions.CATALOGUE try: - storage.use_bundled(group, key, bundled) + standard_definitions.use_bundled(group, key, bundled) + except standard_definitions.Unfit as error: + flash(str(error), "error") + return redirect(url_for(endpoints[group], key=key)) except (ValueError, OSError) as error: abort(409, description=str(error)) flash("Using the bundled entry. Saved runs and results are unchanged.", "ok") diff --git a/docs/getting-started.md b/docs/getting-started.md index 7a6d45b3c..c1792caa1 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -85,7 +85,7 @@ The backend commands also work without installation: ### Your settings and data Save provider credentials in **Settings**. -`nullius paths` lists settings, licences, user catalogue, workspaces, runs, saved +`nullius paths` lists settings, licences, user catalogue, proofs, workspaces, runs, saved recipes and cache paths without showing credentials. For the locations, see [Settings](settings/README.md#storage). diff --git a/docs/settings/README.md b/docs/settings/README.md index fcb844579..691a1fcad 100644 --- a/docs/settings/README.md +++ b/docs/settings/README.md @@ -81,6 +81,7 @@ credential values. Linux defaults: | Hugging Face token | `~/.config/nullius/secrets/data-provider-huggingface/` | | Model prices | `~/.config/nullius/prices.json`; your own, `prices-own.json` beside it | | User catalogue | `~/.local/share/nullius/catalogue/` | +| Your proofs of bundled entries | `~/.local/share/nullius/proofs/` | | Workspaces | `~/.local/share/nullius/workspaces/` | | Runs started from Review | `~/.local/share/nullius/runs/` | | Saved recipes | `~/.local/share/nullius/recipes/` | @@ -98,7 +99,7 @@ Personal settings and catalogue additions survive package upgrades. A user catalogue folder replaces the entire bundled folder of the same kind and key; files are never mixed between them. Standard commands that edit a bundled definition first copy that entry to the user catalogue. On a customized benchmark, -agent or Module page, **Use bundled entry** removes that copy and its local +agent or Module page, **Use bundled entry** removes that copy and keeps its local proof records. Saved runs, results and credentials stay unchanged. ## Migrate an existing checkout diff --git a/docs/standard.md b/docs/standard.md index c69f2e7fc..68f67b788 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -410,8 +410,8 @@ commands share the user storage shown by `nullius paths`. The user catalogue overlays bundled entries by whole folder: a key in `benchmarks/`, `agents/` or `modules/` replaces that complete entry, without -mixing files. Editing a bundled entry copies it into the user catalogue. **Use bundled entry** on its page removes the user copy and its -local proof records; saved runs and credentials remain. +mixing files. Editing a bundled entry copies it into the user catalogue. **Use bundled entry** on its page removes the user copy; +its local proof records, saved runs and credentials remain. Proofs the bundled entry cannot take keep the copy: the page names their versions and file. ### A benchmark @@ -748,7 +748,8 @@ What passed is recorded per dataset in the version's [proofs](#what-is-proven); ## What is proven Definitions describe what runs; their sibling `proofs.json` records what passed. -Proof runs update only that file. Each file names its `kind` and `key`, uses +Proof runs update only that file; for a bundled entry, a file of the same shape +in the user data directory's `proofs/`, whose versions replace the bundled ones; one the bundle does not declare stays there, unread. Each file names its `kind` and `key`, uses schema `nullius.proofs/v1`, and holds a `versions` map: the declared version, or `""` when the definition has no `upstream.version`. Each version holds its `proven`; a single-version agent or Module also keeps its generated `offers`