From d1a392e3e9cd282046e51e53012068c4eefd1246 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 16:33:06 +0100 Subject: [PATCH 01/10] feat(runs): give each import source a folder and an identity of its own Two ATIF or OpenTelemetry sources of one basename were converted into one imported/__ folder, each conversion pruning the other's trials, and shared one derived identity. A source's first conversion now gives it an id, written in the job's config.json as nullius.source with its absolute path, and kept on every reconversion. Its folder is the one recording it; a new source takes the default name, or -2, -3... when that belongs to another source. The job's identity is declared from the id. A folder converted before ids is reused for its own source, never rewritten to gain one, and keeps its derived identity. Refs #400 --- app/nullius/importers/__init__.py | 63 +++++++++++++++++++++++ app/nullius/importers/atif.py | 23 ++++++--- app/nullius/importers/otel.py | 15 ++++-- app/nullius/runs/uid.py | 22 ++++---- app/tests/test_import_unchanged_source.py | 63 ++++++++++++++++++++++- 5 files changed, 166 insertions(+), 20 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index cf981855..69e0217f 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -28,6 +28,13 @@ Without it a claimed root is one tree, which is how the CLI reads it. The picker uses the same boundaries so both surfaces produce the same jobs. +**One source, one job folder.** A tree is a source, known by its absolute +path. Its first conversion gives it an id of its own (:func:`place`), written +in the job's ``config.json`` as ``nullius.source`` and read back on every +reconversion, so the folder and the identity stay its own: a second source of +one basename gets a folder of its own. A folder converted before the id is +kept as it is, without one. + **Refusing a tree** is `convert` raising ``SystemExit`` with a message that names the file and what is wrong with it — never a job with no trials or a traceback. The message is what a person sees, on the picker or from the CLI, so it is redacted at construction: a tree is arbitrary bytes from @@ -45,6 +52,7 @@ import pkgutil import shutil import tempfile +import uuid from collections import Counter from types import ModuleType @@ -245,5 +253,60 @@ def mark_changed(job_dir: str, summaries: list) -> None: os.utime(os.path.join(job_dir, "result.json")) +def _config(job_dir: str) -> dict: + try: + with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as fh: + cfg = json.load(fh) + except (OSError, ValueError): + return {} + return cfg if isinstance(cfg, dict) else {} + + +def _source(cfg: dict) -> tuple: + """``(id, path)`` a conversion recorded in ``nullius``, or ``(None, None)``.""" + own = cfg.get("nullius") if isinstance(cfg.get("nullius"), dict) else {} + try: + return str(uuid.UUID(str(own["source"]))), own.get("source_path") + except (KeyError, ValueError, TypeError): + return None, None + + +def place(out_root: str, root: str, default: str, job_name: str = "", recorded=None) -> tuple: + """``(job_name, source id)``: the folder under *out_root* the tree at *root* + is converted into, and its id, None for a folder converted before ids. + + The folder that already records this source is its own. Otherwise *default*, + then ``-2``, ``-3``…, skipping a folder that belongs to another + source: one recording another path, or an older one whose + ``recorded(config)`` names another path. A named *job_name* is used as it is. + """ + src = os.path.abspath(root) + names = sorted(os.listdir(out_root)) if not job_name and os.path.isdir(out_root) else [] + for name in names: + sid, path = _source(_config(os.path.join(out_root, name))) + if sid and path == src: + return name, sid + n = 1 + while True: + name = job_name or (default if n == 1 else f"{default}-{n}") + job_dir = os.path.join(out_root, name) + if not os.path.isdir(job_dir): + return name, str(uuid.uuid4()) + cfg = _config(job_dir) + sid, path = _source(cfg) + if job_name: # named: written there as asked; an older folder keeps having no id + return name, (sid if path == src else str(uuid.uuid4())) if sid else None + if not sid: + old = recorded(cfg) if recorded and cfg else None + if not old or os.path.abspath(old) == src or os.path.normpath(old) == os.path.normpath(root): + return name, None + n += 1 + + +def recorded_as(sid, root: str) -> dict: + """What a job's ``config.json`` carries of its source: nothing for a folder converted before ids.""" + return {"nullius": {"source": sid, "source_path": os.path.abspath(root)}} if sid else {} + + def labels() -> str: return ", ".join(getattr(m, "LABEL", name) for name, m in available().items()) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 9414702c..2a93ee6a 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -331,7 +331,7 @@ def _source_in(trial_dir: str): return None -def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str) -> str: +def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str, sid=None) -> str: """The read documents, as one job directory of one trial each.""" # Flattening can give two paths one name (a/b.json, a__b.json): those take # a digest of their path, so each document keeps a trial of its own. @@ -380,6 +380,7 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str "tasks": [{"name": f"{NAME}/{s['trial_dir']}"} for s in summaries], "trial_documents": importers.reservations( job_dir, ((name, os.path.realpath(path)) for (path, _doc), name in zip(docs, names)), *existing), + **importers.recorded_as(sid, root), }) return job_dir @@ -390,9 +391,17 @@ def convert(root: str, out_root: str, job_name: str = "", into one job. Every document is read before anything is written, so a refused tree leaves no half-written job behind.""" docs = _read_all(root) - if not job_name: - base = os.path.basename(os.path.normpath(root)) - if os.path.isfile(root): - base = _trial_name(root, root) - job_name = f"{NAME}__{base}" - return [_write_job(docs, root, out_root, job_name, command)] + base = os.path.basename(os.path.normpath(root)) + if os.path.isfile(root): + base = _trial_name(root, root) + job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, _recorded) + return [_write_job(docs, root, out_root, job_name, command, sid)] + + +def _recorded(cfg: dict): + """The tree a conversion from before ids was made from: the one its default command names.""" + try: + words = shlex.split(str(cfg.get("command") or "")) + return words[words.index("nullius.importers.cli") + 1] + except (ValueError, IndexError): + return None diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index b6ded5a5..dc19f334 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -222,7 +222,7 @@ def _trace_id_in(trial_dir: str): def _write_job(documents: list, out_root: str, job_name: str, command: str, - root: str, skipped: list) -> str: + root: str, skipped: list, sid=None) -> str: job_dir = os.path.join(out_root, job_name) ids = [str(doc.get("session_id") or "") for doc in documents] existing = importers.existing_trials(job_dir, _trace_id_in) @@ -262,6 +262,7 @@ def _write_job(documents: list, out_root: str, job_name: str, command: str, "import": {"format": reader.FORMAT, "conventions": reader.CONVENTIONS, "skipped": skipped}, "trial_documents": importers.reservations(job_dir, zip(names, ids), *existing), + **importers.recorded_as(sid, root), }) return job_dir @@ -286,5 +287,13 @@ def convert(root: str, out_root: str, job_name: str = "", raise SystemExit(str(exc)) from None if not documents: raise SystemExit(redact(f"the OTLP/JSON exports in {root} carry no spans")) - name = job_name or f"{NAME}__{os.path.basename(os.path.abspath(root)) or 'export'}" - return [_write_job(documents, out_root, name, command, root, skipped)] + name, sid = importers.place(out_root, root, f"{NAME}__{os.path.basename(os.path.abspath(root)) or 'export'}", + job_name, _recorded) + return [_write_job(documents, out_root, name, command, root, skipped, sid)] + + +def _recorded(cfg: dict): + """The export a conversion from before ids was made from.""" + datasets = cfg.get("datasets") + first = datasets[0] if isinstance(datasets, list) and datasets and isinstance(datasets[0], dict) else {} + return first.get("path") if isinstance(first.get("path"), str) else None diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index 8bee809c..51ae213a 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -7,9 +7,11 @@ - **declared**: the producer wrote one. A Nullius standard job carries ``standard.uuid`` in its ``config.json``, made at creation, kept by a run - resumed into the same folder and new for a merge. -- **derived**: none was written (Harbor, imports, standard jobs from before - ``standard.uuid``). A ``uuid5`` over fixed facts read from the files: the + resumed into the same folder and new for a merge; an import carries its + source's ``nullius.source``, made at the source's first conversion and kept + by every reconversion. +- **derived**: none was written (Harbor, imports and standard jobs from before + their ids). A ``uuid5`` over fixed facts read from the files: the format, the folder name, what ran and when it started. No path is a fact, so a copy or a move keeps it; a renamed folder is a new job. - **pending**: nothing fixed to derive from yet: a job with no trial and no @@ -33,10 +35,13 @@ def _declared(cfg: dict): std = cfg.get("standard") if isinstance(cfg.get("standard"), dict) else {} - try: - return str(uuid.UUID(str(std["uuid"]))) - except (KeyError, ValueError, TypeError, AttributeError): - return None + own = cfg.get("nullius") if isinstance(cfg.get("nullius"), dict) else {} + for got in (std.get("uuid"), own.get("source")): + try: + return str(uuid.UUID(str(got))) + except (ValueError, TypeError, AttributeError): + continue + return None def _has_trial(job_dir: str) -> bool: @@ -52,8 +57,7 @@ def facts(job_dir: str, cfg: dict, res: dict): pending. The start is ``result.json``'s only, which nothing later rewrites.""" std = cfg.get("standard") if isinstance(cfg.get("standard"), dict) else {} agents = [a for a in cfg.get("agents") or [] if isinstance(a, dict)] - if isinstance(cfg.get("harness"), str): # an import: its folder names its source - # shortcut: two imports of one source basename share an identity; a per-source id replaces this. + if isinstance(cfg.get("harness"), str): # an import from before nullius.source: its folder names its source return {"v": 1, "format": cfg["harness"], "folder": os.path.basename(job_dir)} start = str(res["started_at"]) if res.get("started_at") else None if std and not res: diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index 32052b03..4767987c 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -1,8 +1,10 @@ """Opening a workspace again over an unchanged ATIF or OpenTelemetry source leaves the converted job as it was, so its cached parse is used; a changed -source is converted and parsed again.""" +source is converted and parsed again. Each source has a folder and an +identity of its own, whatever its basename.""" from __future__ import annotations +import json import os import shutil import tempfile @@ -11,6 +13,7 @@ from pathlib import Path from nullius import importers, workspace +from nullius.runs import parse from tests.harnesses.test_atif import minimal, write_doc from tests.test_cli_contract import otlp_doc @@ -62,5 +65,63 @@ def test_opentelemetry(self): self.check(lambda: write_doc(self.src, "export.json", edited)) + +def trials(job_dir): + return sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) + + +class OneFolderPerSource(unittest.TestCase): + """Two sources of one basename, ``a/run`` and ``b/run``, in one imports folder.""" + + SOURCES = {"atif": lambda d, n: write_doc(d, f"{n}.json", minimal()), + "otel": lambda d, n: write_doc(d, f"{n}.json", otlp_doc())} + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-import-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + + def sources(self, fmt): + a, b, out = (str(self.tmp / fmt / p) for p in ("a/run", "b/run", "imported")) + self.SOURCES[fmt](a, "one") + self.SOURCES[fmt](b, "two") + return a, b, out + + def test_two_sources_of_one_basename_get_two_folders_and_two_identities(self): + for fmt in self.SOURCES: + with self.subTest(fmt): + a, b, out = self.sources(fmt) + [ja], [jb] = open_again(a, out), open_again(b, out) + self.assertNotEqual(ja, jb) + ua, ub = parse.parse_job(ja), parse.parse_job(jb) + self.assertEqual((ua.uid_source, ub.uid_source), ("declared", "declared")) + self.assertNotEqual(ua.uid, ub.uid) + kept, before = trials(ja), mtimes(jb) + time.sleep(0.05) + self.assertEqual(open_again(a, out), [ja]) # reconverted: its own folder + self.assertEqual((parse.parse_job(ja).uid, trials(ja)), (ua.uid, kept)) + self.assertEqual(mtimes(jb), before) # the other's untouched + + def test_a_conversion_from_before_ids_keeps_its_folder_and_identity(self): + for fmt in self.SOURCES: + with self.subTest(fmt): + a, b, out = self.sources(fmt) + [ja] = open_again(a, out) + cfg_path = os.path.join(ja, "config.json") + with open(cfg_path) as fh: + cfg = json.load(fh) + del cfg["nullius"] + with open(cfg_path, "w") as fh: + json.dump(cfg, fh, indent=2) + old = parse.parse_job(ja) + self.assertEqual(old.uid_source, "derived") + self.assertEqual(open_again(a, out), [ja]) # reconverted where it was, no id gained + with open(cfg_path) as fh: + self.assertNotIn("nullius", json.load(fh)) + self.assertEqual(parse.parse_job(ja).uid, old.uid) + [jb] = open_again(b, out) # another source: not that folder + self.assertNotEqual(jb, ja) + self.assertEqual(parse.parse_job(ja).uid, old.uid) + + if __name__ == "__main__": unittest.main() From 08ae3a2d4ccb73926492de56ec762e8a93cfaeb2 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 16:38:27 +0100 Subject: [PATCH 02/10] feat(runs): derive an import source's id from its format and real path A random id gave one tree a new identity in each workspace that imported it, so its judgements stayed behind. nullius.source is now a uuid5 over the format and the tree's real path ("v": 1), still written at the first conversion and read back on reconversion, so a copied job keeps it. A tree moved or renamed on disk is a new source. Refs #400 --- app/nullius/importers/__init__.py | 27 ++++++++++++++++------- app/nullius/importers/atif.py | 2 +- app/nullius/importers/otel.py | 2 +- app/nullius/runs/uid.py | 5 +++-- app/tests/test_import_unchanged_source.py | 10 +++++++++ 5 files changed, 34 insertions(+), 12 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index 69e0217f..d6d969bd 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -28,8 +28,9 @@ Without it a claimed root is one tree, which is how the CLI reads it. The picker uses the same boundaries so both surfaces produce the same jobs. -**One source, one job folder.** A tree is a source, known by its absolute -path. Its first conversion gives it an id of its own (:func:`place`), written +**One source, one job folder.** A tree is a source, known by its real +path. Its first conversion gives it an id of its own (:func:`place`), derived +from the format and that path so every workspace importing it agrees, written in the job's ``config.json`` as ``nullius.source`` and read back on every reconversion, so the folder and the identity stay its own: a second source of one basename gets a folder of its own. A folder converted before the id is @@ -271,7 +272,17 @@ def _source(cfg: dict) -> tuple: return None, None -def place(out_root: str, root: str, default: str, job_name: str = "", recorded=None) -> tuple: +#: fixed for good: changing it changes every import's identity +NS_SOURCE = uuid.UUID("3b1d7e44-9a0c-4f62-8e15-2c7a9f4d6b08") + + +def source_id(fmt: str, root: str) -> str: + """A source's id: a ``uuid5`` over its format and real path, ``"v": 1``; a moved tree is a new source.""" + facts = {"v": 1, "format": fmt, "path": os.path.realpath(root)} + return str(uuid.uuid5(NS_SOURCE, json.dumps(facts, sort_keys=True, separators=(",", ":")))) + + +def place(out_root: str, root: str, default: str, job_name: str = "", recorded=None, fmt: str = "") -> tuple: """``(job_name, source id)``: the folder under *out_root* the tree at *root* is converted into, and its id, None for a folder converted before ids. @@ -280,7 +291,7 @@ def place(out_root: str, root: str, default: str, job_name: str = "", recorded=N source: one recording another path, or an older one whose ``recorded(config)`` names another path. A named *job_name* is used as it is. """ - src = os.path.abspath(root) + src, new = os.path.realpath(root), source_id(fmt, root) names = sorted(os.listdir(out_root)) if not job_name and os.path.isdir(out_root) else [] for name in names: sid, path = _source(_config(os.path.join(out_root, name))) @@ -291,21 +302,21 @@ def place(out_root: str, root: str, default: str, job_name: str = "", recorded=N name = job_name or (default if n == 1 else f"{default}-{n}") job_dir = os.path.join(out_root, name) if not os.path.isdir(job_dir): - return name, str(uuid.uuid4()) + return name, new cfg = _config(job_dir) sid, path = _source(cfg) if job_name: # named: written there as asked; an older folder keeps having no id - return name, (sid if path == src else str(uuid.uuid4())) if sid else None + return name, (sid if path == src else new) if sid else None if not sid: old = recorded(cfg) if recorded and cfg else None - if not old or os.path.abspath(old) == src or os.path.normpath(old) == os.path.normpath(root): + if not old or os.path.realpath(old) == src or os.path.normpath(old) == os.path.normpath(root): return name, None n += 1 def recorded_as(sid, root: str) -> dict: """What a job's ``config.json`` carries of its source: nothing for a folder converted before ids.""" - return {"nullius": {"source": sid, "source_path": os.path.abspath(root)}} if sid else {} + return {"nullius": {"source": sid, "source_path": os.path.realpath(root)}} if sid else {} def labels() -> str: diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 2a93ee6a..0c3e7d7f 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -394,7 +394,7 @@ def convert(root: str, out_root: str, job_name: str = "", base = os.path.basename(os.path.normpath(root)) if os.path.isfile(root): base = _trial_name(root, root) - job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, _recorded) + job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, _recorded, NAME) return [_write_job(docs, root, out_root, job_name, command, sid)] diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index dc19f334..a1130a8f 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -288,7 +288,7 @@ def convert(root: str, out_root: str, job_name: str = "", if not documents: raise SystemExit(redact(f"the OTLP/JSON exports in {root} carry no spans")) name, sid = importers.place(out_root, root, f"{NAME}__{os.path.basename(os.path.abspath(root)) or 'export'}", - job_name, _recorded) + job_name, _recorded, NAME) return [_write_job(documents, out_root, name, command, root, skipped, sid)] diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index 51ae213a..0daf3738 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -8,8 +8,9 @@ - **declared**: the producer wrote one. A Nullius standard job carries ``standard.uuid`` in its ``config.json``, made at creation, kept by a run resumed into the same folder and new for a merge; an import carries its - source's ``nullius.source``, made at the source's first conversion and kept - by every reconversion. + source's ``nullius.source``, derived from its format and real path at its + first conversion, so every workspace importing it agrees, and kept by every + reconversion and copy. - **derived**: none was written (Harbor, imports and standard jobs from before their ids). A ``uuid5`` over fixed facts read from the files: the format, the folder name, what ran and when it started. No path is a fact, diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index 4767987c..8beb3e0e 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -101,6 +101,16 @@ def test_two_sources_of_one_basename_get_two_folders_and_two_identities(self): self.assertEqual((parse.parse_job(ja).uid, trials(ja)), (ua.uid, kept)) self.assertEqual(mtimes(jb), before) # the other's untouched + def test_one_source_in_two_workspaces_has_one_identity(self): + for fmt in self.SOURCES: + with self.subTest(fmt): + a, _, out = self.sources(fmt) + [one], [two] = open_again(a, out), open_again(a, out + "-elsewhere") + self.assertEqual(parse.parse_job(one).uid, parse.parse_job(two).uid) + copy = str(self.tmp / fmt / "copied") # a copied job keeps it + shutil.copytree(one, copy) + self.assertEqual(parse.parse_job(copy).uid, parse.parse_job(one).uid) + def test_a_conversion_from_before_ids_keeps_its_folder_and_identity(self): for fmt in self.SOURCES: with self.subTest(fmt): From 030295792097acf6c056624538e8e4cbd94f5b38 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 17:24:04 +0100 Subject: [PATCH 03/10] fix(runs): match an import source by its id, refuse another source's named folder and convert one at a time A path converted in another format no longer takes over the first format's folder and id. A --job-name that names another source's folder, recorded or from before ids, is refused before anything is written. Conversions into one folder hold a lock from choosing the folder through the write. The source is resolved to its real path once, so a relative root or a link records one spelling. An import from before ids derives its identity from its recorded source path as well as its folder. --- app/nullius/importers/__init__.py | 50 +++++++++---- app/nullius/importers/atif.py | 8 ++- app/nullius/importers/otel.py | 8 ++- app/nullius/runs/uid.py | 12 ++-- app/tests/test_import_unchanged_source.py | 86 +++++++++++++++++++++-- 5 files changed, 134 insertions(+), 30 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index d6d969bd..e056ce34 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -33,8 +33,9 @@ from the format and that path so every workspace importing it agrees, written in the job's ``config.json`` as ``nullius.source`` and read back on every reconversion, so the folder and the identity stay its own: a second source of -one basename gets a folder of its own. A folder converted before the id is -kept as it is, without one. +one basename gets a folder of its own, and a job name that names another +source's folder is refused. A folder converted before the id is kept as it +is, without one. **Refusing a tree** is `convert` raising ``SystemExit`` with a message that names the file and what is wrong with it — never a job with no trials or a traceback. The message is what a person sees, on the picker or from @@ -47,6 +48,7 @@ """ from __future__ import annotations +import contextlib import importlib import json import os @@ -286,17 +288,18 @@ def place(out_root: str, root: str, default: str, job_name: str = "", recorded=N """``(job_name, source id)``: the folder under *out_root* the tree at *root* is converted into, and its id, None for a folder converted before ids. - The folder that already records this source is its own. Otherwise *default*, + The folder that already records this source's id is its own. Otherwise *default*, then ``-2``, ``-3``…, skipping a folder that belongs to another - source: one recording another path, or an older one whose - ``recorded(config)`` names another path. A named *job_name* is used as it is. + source: one recording another id, or an older one whose + ``recorded(config)`` names another absolute path. A named *job_name* is used + as it is, and refused when it belongs to another source. Call it under + :func:`locked`, through the write, so two conversions never pick one folder. """ src, new = os.path.realpath(root), source_id(fmt, root) names = sorted(os.listdir(out_root)) if not job_name and os.path.isdir(out_root) else [] for name in names: - sid, path = _source(_config(os.path.join(out_root, name))) - if sid and path == src: - return name, sid + if _source(_config(os.path.join(out_root, name)))[0] == new: + return name, new n = 1 while True: name = job_name or (default if n == 1 else f"{default}-{n}") @@ -304,16 +307,33 @@ def place(out_root: str, root: str, default: str, job_name: str = "", recorded=N if not os.path.isdir(job_dir): return name, new cfg = _config(job_dir) - sid, path = _source(cfg) - if job_name: # named: written there as asked; an older folder keeps having no id - return name, (sid if path == src else new) if sid else None - if not sid: - old = recorded(cfg) if recorded and cfg else None - if not old or os.path.realpath(old) == src or os.path.normpath(old) == os.path.normpath(root): - return name, None + if not cfg: # no conversion finished there + return name, new + sid = _source(cfg)[0] + old = recorded(cfg) if recorded and not sid else None + # a relative path was the cwd's of a conversion long gone: it names nothing + mine = sid == new if sid else not old or not os.path.isabs(old) or os.path.realpath(old) == src + if mine: + return name, sid + if job_name: + raise SystemExit(redact(f"{job_dir} holds the import of another source; choose another job name")) n += 1 +@contextlib.contextmanager +def locked(out_root: str): + """One conversion at a time into *out_root*, from :func:`place` through the write.""" + os.makedirs(out_root, exist_ok=True) + with ondisk.locked(os.path.join(out_root, ".nullius-import.lock")): + yield + + +def recorded(cfg: dict): + """The source path an import from before ids recorded in its ``config.json``, or None.""" + module = get(str(cfg.get("harness") or "")) + return module._recorded(cfg) if module and hasattr(module, "_recorded") else None + + def recorded_as(sid, root: str) -> dict: """What a job's ``config.json`` carries of its source: nothing for a folder converted before ids.""" return {"nullius": {"source": sid, "source_path": os.path.realpath(root)}} if sid else {} diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 0c3e7d7f..477c503c 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -390,12 +390,14 @@ def convert(root: str, out_root: str, job_name: str = "", """Convert the documents at *root* — a directory of them or one file — into one job. Every document is read before anything is written, so a refused tree leaves no half-written job behind.""" - docs = _read_all(root) base = os.path.basename(os.path.normpath(root)) if os.path.isfile(root): base = _trial_name(root, root) - job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, _recorded, NAME) - return [_write_job(docs, root, out_root, job_name, command, sid)] + root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links + docs = _read_all(root) + with importers.locked(out_root): + job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, _recorded, NAME) + return [_write_job(docs, root, out_root, job_name, command, sid)] def _recorded(cfg: dict): diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index a1130a8f..6c9058a6 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -275,6 +275,8 @@ def convert(root: str, out_root: str, job_name: str = "", are listed in the job's ``config.json`` under ``import.skipped`` with their redacted reasons; when nothing reads, that list is the error. """ + default = f"{NAME}__{os.path.basename(os.path.abspath(root)) or 'export'}" + root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links paths = find_exports(root) skipped = refused(root) if not paths: @@ -287,9 +289,9 @@ def convert(root: str, out_root: str, job_name: str = "", raise SystemExit(str(exc)) from None if not documents: raise SystemExit(redact(f"the OTLP/JSON exports in {root} carry no spans")) - name, sid = importers.place(out_root, root, f"{NAME}__{os.path.basename(os.path.abspath(root)) or 'export'}", - job_name, _recorded, NAME) - return [_write_job(documents, out_root, name, command, root, skipped, sid)] + with importers.locked(out_root): + name, sid = importers.place(out_root, root, default, job_name, _recorded, NAME) + return [_write_job(documents, out_root, name, command, root, skipped, sid)] def _recorded(cfg: dict): diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index 0daf3738..f85e23fb 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -13,8 +13,9 @@ reconversion and copy. - **derived**: none was written (Harbor, imports and standard jobs from before their ids). A ``uuid5`` over fixed facts read from the files: the - format, the folder name, what ran and when it started. No path is a fact, - so a copy or a move keeps it; a renamed folder is a new job. + format, the folder name, what ran and when it started. No path of the job is a + fact (an import's recorded source path is), so a copy or a move keeps it; a + renamed folder is a new job. - **pending**: nothing fixed to derive from yet: a job with no trial and no start (a Harbor job preparing), or a standard job from before ``standard.uuid`` without its ``result.json`` (still running, or killed). @@ -31,6 +32,8 @@ import os import uuid +from nullius import importers + #: fixed for good: changing one changes every derived identity NS_JOB = uuid.UUID("6f0f3a52-5c1e-4d39-9a2b-6a4c1f0e7d21") @@ -58,8 +61,9 @@ def facts(job_dir: str, cfg: dict, res: dict): pending. The start is ``result.json``'s only, which nothing later rewrites.""" std = cfg.get("standard") if isinstance(cfg.get("standard"), dict) else {} agents = [a for a in cfg.get("agents") or [] if isinstance(a, dict)] - if isinstance(cfg.get("harness"), str): # an import from before nullius.source: its folder names its source - return {"v": 1, "format": cfg["harness"], "folder": os.path.basename(job_dir)} + if isinstance(cfg.get("harness"), str): # an import from before nullius.source: its folder and recorded source + return {"v": 1, "format": cfg["harness"], "folder": os.path.basename(job_dir), + "source": str(importers.recorded(cfg) or "")} start = str(res["started_at"]) if res.get("started_at") else None if std and not res: return None diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index 8beb3e0e..312c7818 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -8,11 +8,13 @@ import os import shutil import tempfile +import threading import time import unittest from pathlib import Path from nullius import importers, workspace +from nullius.importers import atif, otel from nullius.runs import parse from tests.harnesses.test_atif import minimal, write_doc from tests.test_cli_contract import otlp_doc @@ -70,6 +72,17 @@ def trials(job_dir): return sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) +def forget_id(job_dir, **changes): + """The job as a conversion from before ids wrote it, with *changes* to its config.""" + path = os.path.join(job_dir, "config.json") + with open(path) as fh: + cfg = json.load(fh) + del cfg["nullius"] + cfg.update(changes) + with open(path, "w") as fh: + json.dump(cfg, fh, indent=2) + + class OneFolderPerSource(unittest.TestCase): """Two sources of one basename, ``a/run`` and ``b/run``, in one imports folder.""" @@ -117,11 +130,7 @@ def test_a_conversion_from_before_ids_keeps_its_folder_and_identity(self): a, b, out = self.sources(fmt) [ja] = open_again(a, out) cfg_path = os.path.join(ja, "config.json") - with open(cfg_path) as fh: - cfg = json.load(fh) - del cfg["nullius"] - with open(cfg_path, "w") as fh: - json.dump(cfg, fh, indent=2) + forget_id(ja) old = parse.parse_job(ja) self.assertEqual(old.uid_source, "derived") self.assertEqual(open_again(a, out), [ja]) # reconverted where it was, no id gained @@ -132,6 +141,73 @@ def test_a_conversion_from_before_ids_keeps_its_folder_and_identity(self): self.assertNotEqual(jb, ja) self.assertEqual(parse.parse_job(ja).uid, old.uid) + def test_one_path_in_two_formats_is_two_sources(self): + src, out = str(self.tmp / "both"), str(self.tmp / "imported") + write_doc(src, "export.json", otlp_doc()) + [jo] = otel.convert(src, out) + kept, uo = trials(jo), parse.parse_job(jo).uid + write_doc(src, "atif.json", minimal()) + [ja] = atif.convert(src, out) + self.assertNotEqual(ja, jo) + self.assertNotEqual(parse.parse_job(ja).uid, uo) + self.assertEqual((trials(jo), parse.parse_job(jo).uid), (kept, uo)) + + def test_a_named_folder_of_another_source_is_refused(self): + for legacy in (False, True): + with self.subTest(legacy=legacy): + a, b, out = self.sources("atif") + [ja] = atif.convert(a, out, job_name="mine") + if legacy: + forget_id(ja) + before = mtimes(ja) + with self.assertRaises(SystemExit): + atif.convert(b, out, job_name="mine") + self.assertEqual(mtimes(ja), before) + self.assertEqual(atif.convert(a, out, job_name="mine"), [ja]) # its own source still may + shutil.rmtree(self.tmp / "atif") + + def test_two_first_conversions_at_once_take_two_folders(self): + a, b, out = self.sources("otel") + real = importers.place + + def slow(*args, **kwargs): + got = real(*args, **kwargs) + time.sleep(0.2) # the other conversion's turn + return got + importers.place = slow + self.addCleanup(setattr, importers, "place", real) + done = {} + threads = [threading.Thread(target=lambda r: done.update({r: otel.convert(r, out)[0]}), args=(r,)) + for r in (a, b)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertNotEqual(done[a], done[b]) + self.assertTrue(trials(done[a]) and trials(done[b])) + + def test_conversions_from_before_ids_of_two_sources_of_one_basename_differ(self): + for fmt in self.SOURCES: + with self.subTest(fmt): + a, b, out = self.sources(fmt) + [ja], [jb] = open_again(a, out), open_again(b, out + "-elsewhere") + self.assertEqual(os.path.basename(ja), os.path.basename(jb)) + forget_id(ja) + forget_id(jb) + self.assertNotEqual(parse.parse_job(ja).uid, parse.parse_job(jb).uid) + + def test_a_relative_root_is_its_real_path_from_any_directory(self): + a, _, out = self.sources("atif") + here = os.getcwd() + self.addCleanup(os.chdir, here) + os.chdir(self.tmp / "atif") + [ja] = atif.convert("a/run", out) + with open(os.path.join(ja, "config.json")) as fh: + self.assertIn(os.path.realpath(a), json.load(fh)["command"]) + forget_id(ja, command="python3 -m nullius.importers.cli a/run") # an older one, recorded as typed + os.chdir(self.tmp) + self.assertEqual(atif.convert(a, out), [ja]) + if __name__ == "__main__": unittest.main() From 207091e3fb89517c628c7d26e1cd92ff432ba492 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:49:49 +0100 Subject: [PATCH 04/10] fix(runs): reuse an import folder from before ids only when its format and source are shown A folder converted before source ids is reused only when it stored the same format and names this source: by the absolute path it recorded, or else by where each of its trials says its document was read. A folder that cannot be tied to the source (another format, no recorded path, a relative one, an unreadable config) is never written into: a named job is refused and an automatic name takes a folder of its own. --- app/nullius/importers/__init__.py | 46 ++++++++++++++--------- app/nullius/importers/atif.py | 18 ++++++++- app/nullius/importers/otel.py | 2 +- app/tests/test_import_unchanged_source.py | 26 +++++++++++++ 4 files changed, 73 insertions(+), 19 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index e056ce34..4369b348 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -33,9 +33,9 @@ from the format and that path so every workspace importing it agrees, written in the job's ``config.json`` as ``nullius.source`` and read back on every reconversion, so the folder and the identity stay its own: a second source of -one basename gets a folder of its own, and a job name that names another -source's folder is refused. A folder converted before the id is kept as it -is, without one. +one basename gets a folder of its own, and a job name that names a folder not +shown to be this source's is refused. A folder converted before the id is +kept as it is, without one, when its format and recorded source are this one's. **Refusing a tree** is `convert` raising ``SystemExit`` with a message that names the file and what is wrong with it — never a job with no trials or a traceback. The message is what a person sees, on the picker or from @@ -284,16 +284,16 @@ def source_id(fmt: str, root: str) -> str: return str(uuid.uuid5(NS_SOURCE, json.dumps(facts, sort_keys=True, separators=(",", ":")))) -def place(out_root: str, root: str, default: str, job_name: str = "", recorded=None, fmt: str = "") -> tuple: +def place(out_root: str, root: str, default: str, job_name: str = "", fmt: str = "") -> tuple: """``(job_name, source id)``: the folder under *out_root* the tree at *root* is converted into, and its id, None for a folder converted before ids. The folder that already records this source's id is its own. Otherwise *default*, - then ``-2``, ``-3``…, skipping a folder that belongs to another - source: one recording another id, or an older one whose - ``recorded(config)`` names another absolute path. A named *job_name* is used - as it is, and refused when it belongs to another source. Call it under - :func:`locked`, through the write, so two conversions never pick one folder. + then ``-2``, ``-3``…, skipping a folder that holds anything not + shown to be this source's: another id, or an older conversion :func:`_verified` + does not tie to it. A named *job_name* is used as it is, and refused when + it is not shown to be this source's. Call it under :func:`locked`, through + the write, so two conversions never pick one folder. """ src, new = os.path.realpath(root), source_id(fmt, root) names = sorted(os.listdir(out_root)) if not job_name and os.path.isdir(out_root) else [] @@ -304,22 +304,34 @@ def place(out_root: str, root: str, default: str, job_name: str = "", recorded=N while True: name = job_name or (default if n == 1 else f"{default}-{n}") job_dir = os.path.join(out_root, name) - if not os.path.isdir(job_dir): + if not os.path.isdir(job_dir) or not os.listdir(job_dir): return name, new cfg = _config(job_dir) - if not cfg: # no conversion finished there - return name, new sid = _source(cfg)[0] - old = recorded(cfg) if recorded and not sid else None - # a relative path was the cwd's of a conversion long gone: it names nothing - mine = sid == new if sid else not old or not os.path.isabs(old) or os.path.realpath(old) == src - if mine: + if sid == new: return name, sid + if not sid and _verified(job_dir, cfg, fmt, src): + return name, None if job_name: - raise SystemExit(redact(f"{job_dir} holds the import of another source; choose another job name")) + raise SystemExit(redact(f"{job_dir} holds an import not shown to be this source's; " + "choose another job name")) n += 1 +def _verified(job_dir: str, cfg: dict, fmt: str, src: str) -> bool: + """A folder converted before ids is the source at real path *src* only when it + stored the format *fmt* and names *src*: by the absolute path it recorded, + else by where each of its trials says its document was read.""" + if not cfg or cfg.get("harness") != fmt: + return False + old = recorded(cfg) + if isinstance(old, str) and os.path.isabs(old): + return os.path.realpath(old) == src + module = get(fmt) + read = module._trial_sources(job_dir) if hasattr(module, "_trial_sources") else [] + return bool(read) and all(p == src or p.startswith(os.path.join(src, "")) for p in read) + + @contextlib.contextmanager def locked(out_root: str): """One conversion at a time into *out_root*, from :func:`place` through the write.""" diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 477c503c..37b34b6d 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -396,7 +396,7 @@ def convert(root: str, out_root: str, job_name: str = "", root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links docs = _read_all(root) with importers.locked(out_root): - job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, _recorded, NAME) + job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, NAME) return [_write_job(docs, root, out_root, job_name, command, sid)] @@ -407,3 +407,19 @@ def _recorded(cfg: dict): return words[words.index("nullius.importers.cli") + 1] except (ValueError, IndexError): return None + + +def _trial_sources(job_dir: str) -> list: + """The real path each trial of *job_dir* records its document was read from; + empty when one cannot tell.""" + found = [] + for name in sorted(os.listdir(job_dir)): + trial = os.path.join(job_dir, name) + if not os.path.isdir(trial): + continue + try: + with open(os.path.join(trial, "result.json"), encoding="utf-8") as fh: + found.append(os.path.realpath(str(json.load(fh)["source_document"]["path"]))) + except (OSError, ValueError, KeyError, TypeError): + return [] + return found diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index 6c9058a6..f38301b1 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -290,7 +290,7 @@ def convert(root: str, out_root: str, job_name: str = "", if not documents: raise SystemExit(redact(f"the OTLP/JSON exports in {root} carry no spans")) with importers.locked(out_root): - name, sid = importers.place(out_root, root, default, job_name, _recorded, NAME) + name, sid = importers.place(out_root, root, default, job_name, NAME) return [_write_job(documents, out_root, name, command, root, skipped, sid)] diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index 312c7818..8be85cb3 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -166,6 +166,32 @@ def test_a_named_folder_of_another_source_is_refused(self): self.assertEqual(atif.convert(a, out, job_name="mine"), [ja]) # its own source still may shutil.rmtree(self.tmp / "atif") + def test_a_folder_from_before_ids_not_shown_to_be_the_source_is_never_reused(self): + def unreadable(job_dir): + with open(os.path.join(job_dir, "config.json"), "w") as fh: + fh.write("{") + cases = {"another format": (atif, forget_id), + "no recorded path": (otel, lambda j: forget_id(j, datasets=[])), + "a relative path": (otel, lambda j: forget_id(j, datasets=[{"name": "otel", "path": "a/run"}])), + "an unreadable config": (otel, unreadable)} + for case, (module, change) in cases.items(): + with self.subTest(case): + shutil.rmtree(self.tmp / "otel", True) + a, b, out = self.sources("otel") + if module is atif: + b = str(self.tmp / "atif-src") + write_doc(b, "one.json", minimal()) + name = f"{module.NAME}__{os.path.basename(b)}" # the name b would take + [jo] = otel.convert(a, out, job_name=name) + change(jo) + before = mtimes(jo) + with self.assertRaises(SystemExit): + module.convert(b, out, job_name=name) + self.assertEqual(mtimes(jo), before) # its trials untouched + [jb] = module.convert(b, out) # an automatic name: a folder of its own + self.assertNotEqual(jb, jo) + self.assertEqual(mtimes(jo), before) + def test_two_first_conversions_at_once_take_two_folders(self): a, b, out = self.sources("otel") real = importers.place From 25ec8b829ce22323ee3043e4864b70205aad52b4 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:50:24 +0100 Subject: [PATCH 05/10] fix(runs): keep the recorded source of an import from before ids through reconversion A reconversion into a folder converted before source ids keeps the command (ATIF) or export path (OpenTelemetry) it recorded, as typed: that string is what the folder's derived uid was made from, so rewriting it as a real path would give the job another identity. --- app/nullius/importers/atif.py | 3 ++- app/nullius/importers/otel.py | 4 +++- app/tests/test_import_unchanged_source.py | 7 ++++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 37b34b6d..f16943d8 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -372,7 +372,8 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str _dump(os.path.join(job_dir, "config.json"), { "job_name": job_name, "harness": NAME, # provenance; the walker ignores unknown keys - "command": command or ( + # a folder converted before ids keeps the command its identity was derived from + "command": importers._config(job_dir).get("command") if sid is None else command or ( f"PYTHONPATH=app python3 -m nullius.importers.cli {shlex.quote(root)} " f"-o {shlex.quote(out_root)} --job-name {shlex.quote(job_name)}"), "agents": [{"name": agent["name"], diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index f38301b1..ef72f36e 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -258,7 +258,9 @@ def _write_job(documents: list, out_root: str, job_name: str, command: str, "command": command, "agents": [{"name": agents[0], "model_name": models[0] if len(models) == 1 else "", "kwargs": {}}], - "datasets": [{"name": NAME, "path": root, "n_tasks": len(summaries)}], + # a folder converted before ids keeps the path its identity was derived from + "datasets": [{"name": NAME, "path": _recorded(importers._config(job_dir)) if sid is None else root, + "n_tasks": len(summaries)}], "import": {"format": reader.FORMAT, "conventions": reader.CONVENTIONS, "skipped": skipped}, "trial_documents": importers.reservations(job_dir, zip(names, ids), *existing), diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index 8be85cb3..d5e84363 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -130,7 +130,10 @@ def test_a_conversion_from_before_ids_keeps_its_folder_and_identity(self): a, b, out = self.sources(fmt) [ja] = open_again(a, out) cfg_path = os.path.join(ja, "config.json") - forget_id(ja) + link = str(self.tmp / fmt / "link") # recorded as typed, through a link + os.symlink(a, link) + forget_id(ja, **{"atif": {"command": f"python3 -m nullius.importers.cli {link}"}, + "otel": {"datasets": [{"name": "otel", "path": link, "n_tasks": 1}]}}[fmt]) old = parse.parse_job(ja) self.assertEqual(old.uid_source, "derived") self.assertEqual(open_again(a, out), [ja]) # reconverted where it was, no id gained @@ -231,8 +234,10 @@ def test_a_relative_root_is_its_real_path_from_any_directory(self): with open(os.path.join(ja, "config.json")) as fh: self.assertIn(os.path.realpath(a), json.load(fh)["command"]) forget_id(ja, command="python3 -m nullius.importers.cli a/run") # an older one, recorded as typed + uid = parse.parse_job(ja).uid os.chdir(self.tmp) self.assertEqual(atif.convert(a, out), [ja]) + self.assertEqual(parse.parse_job(ja).uid, uid) # its identity's inputs kept if __name__ == "__main__": From 01ea5f37c206f0a3121b63a868fadb3d81eee3be Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:51:28 +0100 Subject: [PATCH 06/10] fix(runs): read an import's source under the conversion lock and copy the bytes parsed A conversion reads its source again once it holds the lock, so one that read an older source never publishes it over trials a later conversion published meanwhile; a refused tree is still refused before anything is written. An ATIF document is read once: its trial's copy and digest are the bytes parsed. --- app/nullius/importers/atif.py | 41 ++++++++++++----------- app/nullius/importers/otel.py | 13 +++++-- app/tests/test_import_unchanged_source.py | 31 +++++++++++++++++ 3 files changed, 62 insertions(+), 23 deletions(-) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index f16943d8..f9069278 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -67,7 +67,7 @@ import shutil from datetime import timezone -from nullius import importers, ondisk +from nullius import importers from nullius.redact import redact from nullius.traces.trajectory import parse_ts @@ -107,14 +107,15 @@ def _mentions_atif(path: str) -> bool: return False -def _read(path: str, shown: str) -> dict: - """The document at *path*, or a SystemExit naming what is wrong with it. +def _read(path: str, shown: str) -> tuple: + """``(document, bytes)`` at *path*, or a SystemExit naming what is wrong with it. The message is redacted here. """ try: - with open(path, encoding="utf-8") as fh: - doc = json.load(fh) + with open(path, "rb") as fh: + data = fh.read() + doc = json.loads(data.decode("utf-8")) except OSError as e: raise SystemExit(redact(f"{shown}: cannot be read ({e.strerror})")) from None except ValueError as e: @@ -130,7 +131,7 @@ def _read(path: str, shown: str) -> dict: raise SystemExit(redact(f"{shown}: no steps (a partial document)")) if not isinstance(doc["steps"], list): raise SystemExit(redact(f"{shown}: steps is not a list")) - return doc + return doc, data def _claims(path: str) -> bool: @@ -190,13 +191,13 @@ def _shown(path: str, root: str) -> str: return os.path.relpath(path, root) -def _read_all(root: str) -> list[tuple[str, dict]]: +def _read_all(root: str) -> list[tuple[str, dict, bytes]]: paths = find_documents(root) if not paths: raise SystemExit(redact( f"no ATIF trajectories (schema_version {SUPPORTED_VERSIONS[0]} through " f"{SUPPORTED_VERSIONS[-1]}) found in {root}")) - return [(path, _read(path, _shown(path, root))) for path in paths] + return [(path, *_read(path, _shown(path, root))) for path in paths] @@ -276,8 +277,8 @@ def _dump(path: str, data) -> bool: # ── one document = one trial ──────────────────────────────────────────────── -def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict: - """Write one document as a Harbor-shaped trial directory. Returns a summary.""" +def convert_document(path: str, doc: dict, data: bytes, trial: str, job_dir: str) -> dict: + """Write one document, parsed from *data*, as a Harbor-shaped trial directory. Returns a summary.""" trial_dir = os.path.join(job_dir, trial) agent_dir = os.path.join(trial_dir, "agent") os.makedirs(agent_dir, exist_ok=True) @@ -304,17 +305,16 @@ def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict: "agent_result": _usage(doc), "source_document": { "path": os.path.abspath(path), - "sha256": ondisk.sha256_of(path), + "sha256": hashlib.sha256(data).hexdigest(), "schema_version": doc["schema_version"], "session_id": doc.get("session_id"), }, } changed = _dump(os.path.join(trial_dir, "result.json"), result) - # Byte for byte: the trial page reads what the producer wrote, and a - # digest of the copy is a digest of the source. - with open(path, "rb") as fh: - changed |= importers.write_if_changed(os.path.join(agent_dir, "trajectory.json"), fh.read()) + # Byte for byte the bytes parsed: the trial page reads what the producer + # wrote, and a digest of the copy is a digest of the source. + changed |= importers.write_if_changed(os.path.join(agent_dir, "trajectory.json"), data) return {"trial_dir": trial, "started_at": started, "finished_at": finished, "agent_info": result["agent_info"], "changed": changed} @@ -340,11 +340,11 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str names = importers.unique_names([ (os.path.realpath(path), _trial_name(path, root), _trial_name(path, root) + "__" + hashlib.sha256(_shown(path, root).encode()).hexdigest()[:8]) - for path, _doc in docs], *existing) + for path, _doc, _data in docs], *existing) os.makedirs(job_dir, exist_ok=True) - summaries = [convert_document(path, doc, name, job_dir) - for (path, doc), name in zip(docs, names)] + summaries = [convert_document(path, doc, data, name, job_dir) + for (path, doc, data), name in zip(docs, names)] # Derived output this importer wholly owns: a trial the tree no longer # holds is stale and would keep being counted. produced = {s["trial_dir"] for s in summaries} @@ -380,7 +380,7 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str "model_name": agent["model_info"]["name"]}], "tasks": [{"name": f"{NAME}/{s['trial_dir']}"} for s in summaries], "trial_documents": importers.reservations( - job_dir, ((name, os.path.realpath(path)) for (path, _doc), name in zip(docs, names)), *existing), + job_dir, ((name, os.path.realpath(path)) for (path, _doc, _data), name in zip(docs, names)), *existing), **importers.recorded_as(sid, root), }) return job_dir @@ -395,8 +395,9 @@ def convert(root: str, out_root: str, job_name: str = "", if os.path.isfile(root): base = _trial_name(root, root) root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links - docs = _read_all(root) + _read_all(root) # a refused tree is refused before even the lock is written with importers.locked(out_root): + docs = _read_all(root) # read under the lock: a newer conversion is never undone job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, NAME) return [_write_job(docs, root, out_root, job_name, command, sid)] diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index ef72f36e..9ceb077f 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -279,6 +279,15 @@ def convert(root: str, out_root: str, job_name: str = "", """ default = f"{NAME}__{os.path.basename(os.path.abspath(root)) or 'export'}" root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links + _read(root) # a refused tree is refused before even the lock is written + with importers.locked(out_root): + documents, skipped = _read(root) # read under the lock: a newer conversion is never undone + name, sid = importers.place(out_root, root, default, job_name, NAME) + return [_write_job(documents, out_root, name, command, root, skipped, sid)] + + +def _read(root: str) -> tuple: + """``(documents, refused files)`` of the exports under *root*, or a SystemExit.""" paths = find_exports(root) skipped = refused(root) if not paths: @@ -291,9 +300,7 @@ def convert(root: str, out_root: str, job_name: str = "", raise SystemExit(str(exc)) from None if not documents: raise SystemExit(redact(f"the OTLP/JSON exports in {root} carry no spans")) - with importers.locked(out_root): - name, sid = importers.place(out_root, root, default, job_name, NAME) - return [_write_job(documents, out_root, name, command, root, skipped, sid)] + return documents, skipped def _recorded(cfg: dict): diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index d5e84363..2e926fad 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -215,6 +215,37 @@ def slow(*args, **kwargs): self.assertNotEqual(done[a], done[b]) self.assertTrue(trials(done[a]) and trials(done[b])) + def test_a_conversion_never_publishes_a_source_older_than_one_published_meanwhile(self): + def another_trace(): + doc = otlp_doc() + doc["resourceSpans"][0]["scopeSpans"][0]["spans"][0]["traceId"] = "1" * 32 + return doc + later = {"atif": minimal, "otel": another_trace} + for fmt, module, read in (("atif", atif, "_read_all"), ("otel", otel, "_read")): + with self.subTest(fmt): + a, _, out = self.sources(fmt) + real, paused, resume = getattr(module, read), threading.Event(), threading.Event() + + def pausing(root): + got = real(root) + if threading.current_thread().name == "first" and not paused.is_set(): + paused.set() # the first has read the source + resume.wait(10) + return got + setattr(module, read, pausing) + self.addCleanup(setattr, module, read, real) + first = threading.Thread(target=module.convert, args=(a, out), name="first") + first.start() + self.assertTrue(paused.wait(10)) + write_doc(a, "later.json", later[fmt]()) # the source grows, and is converted + [job] = module.convert(a, out) + published = trials(job) + resume.set() + first.join(10) + self.assertEqual(len(published), 2) + self.assertEqual(trials(job), published) # the first's older read is not published + setattr(module, read, real) + def test_conversions_from_before_ids_of_two_sources_of_one_basename_differ(self): for fmt in self.SOURCES: with self.subTest(fmt): From d9e9852cf6eef72c41a857b511be48abe21f4bf5 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:24:38 +0100 Subject: [PATCH 07/10] fix(runs): parse cached jobs again now an import's id counts its recorded source A job cached before an import's id took in its recorded source path kept its older id once read back, while a fresh parse of the same folder gave another. --- app/nullius/runs/parse.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index 1ead121f..dcc53bf5 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -32,7 +32,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "20" +SCHEMA = "21" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — From 78d046afc7d539b123e2e5d8152d66079f276fec Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:26:11 +0100 Subject: [PATCH 08/10] fix(runs): reuse an ATIF folder from before ids only for the one tree its trials are named from A folder converted from a relative path was reused for any tree holding every document its trials were read from: converting a parent into it added the parent's documents under the child's identity. The folder is now the source's only when the source is the one tree that names its trials as they are and ends with the path recorded. Otherwise a named conversion is refused and an automatic one takes a folder of its own. --- app/nullius/importers/__init__.py | 9 ++++++--- app/nullius/importers/atif.py | 17 +++++++++++++---- app/tests/test_import_unchanged_source.py | 9 ++++++--- 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index 4369b348..57194e3e 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -321,15 +321,18 @@ def place(out_root: str, root: str, default: str, job_name: str = "", fmt: str = def _verified(job_dir: str, cfg: dict, fmt: str, src: str) -> bool: """A folder converted before ids is the source at real path *src* only when it stored the format *fmt* and names *src*: by the absolute path it recorded, - else by where each of its trials says its document was read.""" + else as the one tree its trials are named from (where each says its document + was read) that ends with the relative path it recorded.""" if not cfg or cfg.get("harness") != fmt: return False old = recorded(cfg) if isinstance(old, str) and os.path.isabs(old): return os.path.realpath(old) == src module = get(fmt) - read = module._trial_sources(job_dir) if hasattr(module, "_trial_sources") else [] - return bool(read) and all(p == src or p.startswith(os.path.join(src, "")) for p in read) + roots = module._trial_roots(job_dir) if hasattr(module, "_trial_roots") else [] + if isinstance(old, str): + roots = [r for r in roots if os.path.normpath(old) == "." or r.endswith(os.sep + os.path.normpath(old))] + return roots == [src] @contextlib.contextmanager diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index f9069278..2b01843e 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -411,8 +411,9 @@ def _recorded(cfg: dict): return None -def _trial_sources(job_dir: str) -> list: - """The real path each trial of *job_dir* records its document was read from; +def _trial_roots(job_dir: str) -> list: + """Every tree whose documents, named from there, give *job_dir*'s trials the + names they have, by where each trial records its document was read; empty when one cannot tell.""" found = [] for name in sorted(os.listdir(job_dir)): @@ -421,7 +422,15 @@ def _trial_sources(job_dir: str) -> list: continue try: with open(os.path.join(trial, "result.json"), encoding="utf-8") as fh: - found.append(os.path.realpath(str(json.load(fh)["source_document"]["path"]))) + found.append((name, os.path.realpath(str(json.load(fh)["source_document"]["path"])))) except (OSError, ValueError, KeyError, TypeError): return [] - return found + if not found: + return [] + roots, root = [], os.path.commonpath([path for _, path in found]) + while True: + if all(_trial_name(path, root) == name for name, path in found): + roots.append(root) + if os.path.dirname(root) == root: + return roots + root = os.path.dirname(root) diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index 2e926fad..c697ad74 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -156,11 +156,14 @@ def test_one_path_in_two_formats_is_two_sources(self): self.assertEqual((trials(jo), parse.parse_job(jo).uid), (kept, uo)) def test_a_named_folder_of_another_source_is_refused(self): - for legacy in (False, True): - with self.subTest(legacy=legacy): + for legacy, parent in ((False, False), (True, False), (True, True)): + with self.subTest(legacy=legacy, parent=parent): a, b, out = self.sources("atif") [ja] = atif.convert(a, out, job_name="mine") - if legacy: + if parent: # every old trial is under it too + b = os.path.dirname(a) + forget_id(ja, command="python3 -m nullius.importers.cli a/run") + elif legacy: forget_id(ja) before = mtimes(ja) with self.assertRaises(SystemExit): From b987351b5f90e522506da398eab34ae0eb2b863a Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:27:09 +0100 Subject: [PATCH 09/10] fix(runs): write an imported job's files whole, so a refresh cut short keeps its source A conversion rewrote config.json in place: a refresh stopped mid-write left it truncated, and with it the source the job was converted from. Each file is now written beside the old one and renamed over it. --- app/tests/test_import_unchanged_source.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index c697ad74..719d6cb7 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -198,6 +198,20 @@ def unreadable(job_dir): self.assertNotEqual(jb, jo) self.assertEqual(mtimes(jo), before) + def test_a_refresh_replaces_the_config_whole(self): + for fmt, module in (("atif", atif), ("otel", otel)): + with self.subTest(fmt): + a, _, out = self.sources(fmt) + [job] = module.convert(a, out) + path = os.path.join(job, "config.json") + Path(path).write_text(json.dumps(json.loads(Path(path).read_text()))) # to be written again + with open(path, encoding="utf-8") as held: # a reader mid-refresh + before = held.read() + module.convert(a, out) + held.seek(0) + self.assertEqual(held.read(), before) + self.assertNotEqual(Path(job, "config.json").read_text(), before) + def test_two_first_conversions_at_once_take_two_folders(self): a, b, out = self.sources("otel") real = importers.place From 4d2ebfba7fcd2c819870569765180c77890505fb Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 15:26:23 +0100 Subject: [PATCH 10/10] fix(runs): reuse an ATIF folder from before ids whose trials took the longer name of colliding paths Two paths that flatten to one name (a/b.json, a__b.json) each take that name with a digest of their path. A folder converted before ids with such trials was never shown to be its own tree's, so its source got a new folder and identity. Those names now count as named from the tree too. --- app/nullius/importers/atif.py | 4 +++- app/tests/test_import_unchanged_source.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 2b01843e..bc04b45f 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -429,7 +429,9 @@ def _trial_roots(job_dir: str) -> list: return [] roots, root = [], os.path.commonpath([path for _, path in found]) while True: - if all(_trial_name(path, root) == name for name, path in found): + # a name another document's took is its own name with a digest of its path + if all(name in (_trial_name(path, root), _trial_name(path, root) + "__" + + hashlib.sha256(_shown(path, root).encode()).hexdigest()[:8]) for name, path in found): roots.append(root) if os.path.dirname(root) == root: return roots diff --git a/app/tests/test_import_unchanged_source.py b/app/tests/test_import_unchanged_source.py index 719d6cb7..c4507b25 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -144,6 +144,17 @@ def test_a_conversion_from_before_ids_keeps_its_folder_and_identity(self): self.assertNotEqual(jb, ja) self.assertEqual(parse.parse_job(ja).uid, old.uid) + def test_a_conversion_from_before_ids_with_names_of_colliding_paths_keeps_its_folder(self): + src, out = self.tmp / "x" / "run", str(self.tmp / "imported") + write_doc(str(src / "a"), "b.json", minimal()) + write_doc(str(src), "a__b.json", minimal()) + [job] = atif.convert(str(src), out) + self.assertEqual(len([t for t in trials(job) if t.startswith("a__b__")]), 2) + forget_id(job, command="python3 -m nullius.importers.cli run") + uid = parse.parse_job(job).uid + self.assertEqual(atif.convert(str(src), out), [job]) + self.assertEqual(parse.parse_job(job).uid, uid) + def test_one_path_in_two_formats_is_two_sources(self): src, out = str(self.tmp / "both"), str(self.tmp / "imported") write_doc(src, "export.json", otlp_doc())