From 70c946103f94194c5ca2714e085dbbaa207c01ff Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 16:31:10 +0100 Subject: [PATCH 1/7] fix(runs): give each imported document a trial of its own when names collide OpenTelemetry traces sharing a root span name and the first 7 hex of their trace id, and ATIF paths that flatten to one name (a/b.json, a__b.json), were written into one trial folder while the job counted both. Names are now decided before writing: an unshared name is kept as it is, a shared one takes the full trace id (OpenTelemetry) or a digest of its path (ATIF), and a name still shared is refused. The OpenTelemetry trial records its full trace id. --- app/nullius/importers/__init__.py | 16 ++++++++++++++++ app/nullius/importers/atif.py | 11 +++++++++-- app/nullius/importers/otel.py | 17 ++++++++++------- app/tests/harnesses/test_atif.py | 14 ++++++++++++++ app/tests/harnesses/test_otel_import.py | 15 +++++++++++++++ 5 files changed, 64 insertions(+), 9 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index 998471030..76f7ce2bc 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -44,6 +44,7 @@ import pkgutil import shutil import tempfile +from collections import Counter from types import ModuleType from nullius.redact import redact @@ -140,6 +141,21 @@ def write_if_changed(path: str, data: bytes) -> bool: return True +def unique_names(names: list[tuple[str, str]]) -> list[str]: + """One trial directory per document, decided before anything is written. + + Each entry is (name, longer name): the name where no other document + shares it, so existing trials keep theirs; the longer one where it is + shared. Two documents still left with one name are refused. + """ + counts = Counter(name for name, _ in names) + out = [name if counts[name] == 1 else longer for name, longer in names] + shared = sorted(name for name, n in Counter(out).items() if n > 1) + if shared: + raise SystemExit(redact(f"two documents would share the trial {shared[0]!r}")) + return out + + def mark_changed(job_dir: str, summaries: list) -> None: """Move the job's own ``result.json`` when one of its trials was written: an ended job's cached parse is checked by that file, not trial by trial.""" diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 2a9129fe1..4c3cde2b2 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -58,6 +58,7 @@ """ from __future__ import annotations +import hashlib import json import os import re @@ -321,11 +322,17 @@ def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict: def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str) -> 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. + names = importers.unique_names([ + (_trial_name(path, root), _trial_name(path, root) + "__" + + hashlib.sha256(_shown(path, root).encode()).hexdigest()[:8]) + for path, _doc in docs]) job_dir = os.path.join(out_root, job_name) os.makedirs(job_dir, exist_ok=True) - summaries = [convert_document(path, doc, _trial_name(path, root), job_dir) - for path, doc in docs] + summaries = [convert_document(path, doc, name, job_dir) + for (path, doc), 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} diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index 0ad31e8da..bdbb07a44 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -147,17 +147,17 @@ def _window(document: dict) -> tuple: return (min(starts) if starts else None, max(ends) if ends else None) -def trial_name_of(document: dict) -> str: - """``__<7 hex of the trace id>`` — readable, and unique - per trace.""" +def trial_name_of(document: dict, full: bool = False) -> str: + """``__<7 hex of the trace id>``, readable; with *full*, + the whole trace id, for traces whose short names collide.""" tid = str(document.get("session_id") or "") stem = _UNSAFE.sub("_", str(document.get("trial_name") or "")).strip("._-") or "trace" - return f"{stem[:80]}__{tid[:7] or 'unknown'}" + return f"{stem[:80]}__{(tid if full else tid[:7]) or 'unknown'}" -def write_trial(document: dict, job_dir: str) -> dict: +def write_trial(document: dict, job_dir: str, trial: str = "") -> dict: """One trace document as a trial directory. Returns a summary.""" - trial = trial_name_of(document) + trial = trial or trial_name_of(document) trial_dir = os.path.join(job_dir, trial) agent_dir = os.path.join(trial_dir, "agent") os.makedirs(agent_dir, exist_ok=True) @@ -190,6 +190,7 @@ def write_trial(document: dict, job_dir: str) -> dict: {"started_at": started, "finished_at": finished} if started and finished else None), "verifier": None, "config": {"environment": {"type": ""}}, + "source_document": {"trace_id": document.get("session_id")}, } if tokens: result["agent_result"] = { @@ -206,9 +207,11 @@ def write_trial(document: dict, job_dir: str) -> dict: def _write_job(documents: list, out_root: str, job_name: str, command: str, root: str, skipped: list) -> str: + names = importers.unique_names( + [(trial_name_of(doc), trial_name_of(doc, full=True)) for doc in documents]) job_dir = os.path.join(out_root, job_name) os.makedirs(job_dir, exist_ok=True) - summaries = [write_trial(doc, job_dir) for doc in documents] + summaries = [write_trial(doc, job_dir, name) for doc, name in zip(documents, names)] # Derived output this importer wholly owns: a trial the export no longer # produces is stale and would keep being counted. diff --git a/app/tests/harnesses/test_atif.py b/app/tests/harnesses/test_atif.py index 3ee3f1ba2..0e4d5761d 100644 --- a/app/tests/harnesses/test_atif.py +++ b/app/tests/harnesses/test_atif.py @@ -101,6 +101,20 @@ def test_trial_names_follow_the_tree_and_a_bare_trajectory_takes_its_directory(s self.assertEqual(sorted(t.trial_name for t in job.trials), ["a", "runs__b", "runs__c", "trajectory"]) + def test_paths_that_flatten_to_one_name_stay_two_trials(self): + src = tempfile.mkdtemp() + write_doc(src, "a/b.json", minimal(session_id="s-nested")) + write_doc(src, "a__b.json", minimal(session_id="s-flat")) + write_doc(src, "c.json", minimal()) + job_dir, job = self.convert(src) + names = sorted(t.trial_name for t in job.trials) + self.assertEqual(len(names), 3) + self.assertIn("c", names) # an unshared name is kept as it was + sessions = {json.loads(Path(t.dir, "result.json").read_text())["source_document"]["session_id"] + for t in job.trials} + self.assertEqual(sessions, {"s-nested", "s-flat", "s-1"}) + self.assertEqual(json.loads(Path(job_dir, "result.json").read_text())["n_total_trials"], 3) + def test_re_converting_updates_in_place_and_drops_a_stale_trial(self): src = tempfile.mkdtemp() write_doc(src, "a.json", minimal()) diff --git a/app/tests/harnesses/test_otel_import.py b/app/tests/harnesses/test_otel_import.py index 9c082b53b..462e6c7f0 100644 --- a/app/tests/harnesses/test_otel_import.py +++ b/app/tests/harnesses/test_otel_import.py @@ -49,6 +49,21 @@ def test_nothing_readable_is_an_error_naming_the_refusals(self): self.assertNotIn("hunter2", message) self.assertEqual(os.listdir(self.out), []) # nothing half-written + def test_traces_whose_short_names_collide_stay_two_trials(self): + src = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, src, True) + ids = ["abcdef1" + "0" * 25, "abcdef1" + "f" * 25, "1234567" + "0" * 25] + spans = [{"traceId": tid, "spanId": "01", "name": "agent run", + "startTimeUnixNano": "1", "endTimeUnixNano": "9"} for tid in ids] + with open(os.path.join(src, "export.json"), "w") as fh: + json.dump({"resourceSpans": [{"resource": {}, "scopeSpans": [{"spans": spans}]}]}, fh) + job_dir = importer.convert(src, self.out)[0] + trials = sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) + self.assertEqual(trials, ["agent_run__1234567", "agent_run__" + ids[0], "agent_run__" + ids[1]]) + recorded = {json.load(open(os.path.join(job_dir, t, "result.json")))["source_document"]["trace_id"] + for t in trials} + self.assertEqual(recorded, set(ids)) + def test_a_refused_file_deeper_down_is_named_by_its_path_under_the_root_once(self): src = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, src, True) From f4dcfa88f5206d5a56ded2896cf6efc6781219a9 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 16:39:32 +0100 Subject: [PATCH 2/7] fix(runs): keep an imported trial's name when a later document collides with it Judgements are keyed by a trial's name, so a later conversion must not rename a trial already in the output job. Each importer now reads which document each existing trial folder holds (the recorded trace id or source path, or the trace a folder carries) and keeps that name for it; only a newcomer that collides takes the longer name. A folder an older conversion wrote two documents into is split, and a folder whose document cannot be told keeps its name for the first document that would take it. --- app/nullius/importers/__init__.py | 49 ++++++++++++++++++++++--- app/nullius/importers/atif.py | 15 ++++++-- app/nullius/importers/otel.py | 22 ++++++++++- app/tests/harnesses/test_atif.py | 28 ++++++++++++++ app/tests/harnesses/test_otel_import.py | 24 ++++++++++++ 5 files changed, 127 insertions(+), 11 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index 76f7ce2bc..03748ebab 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -40,6 +40,7 @@ from __future__ import annotations import importlib +import json import os import pkgutil import shutil @@ -141,15 +142,51 @@ def write_if_changed(path: str, data: bytes) -> bool: return True -def unique_names(names: list[tuple[str, str]]) -> list[str]: +def existing_trials(job_dir: str, identity_of) -> tuple[dict, bool]: + """The trials a previous conversion left in *job_dir*: name -> the + document each holds, by ``identity_of(trial_dir)`` (None when the files + cannot tell), and whether the job counted more trials than it has folders, + which is how two documents once written into one folder show.""" + trials = {} + if os.path.isdir(job_dir): + for name in sorted(os.listdir(job_dir)): + if os.path.isdir(os.path.join(job_dir, name)): + trials[name] = identity_of(os.path.join(job_dir, name)) + try: + with open(os.path.join(job_dir, "result.json"), encoding="utf-8") as fh: + counted = json.load(fh)["n_total_trials"] + except (OSError, ValueError, KeyError, TypeError): + counted = len(trials) + return trials, isinstance(counted, int) and counted > len(trials) + + +def unique_names(documents: list[tuple], existing: dict | None = None, + merged: bool = False) -> list[str]: """One trial directory per document, decided before anything is written. - Each entry is (name, longer name): the name where no other document - shares it, so existing trials keep theirs; the longer one where it is - shared. Two documents still left with one name are refused. + Each document is (identity, name, longer name). A document whose trial + already exists keeps that trial's name: judgements are keyed by it. A + folder whose document cannot be told keeps its name for the first + document that would take it. Any other document takes its name unless + another holds it, else the longer one. A *merged* job (two documents + written into one folder by an older conversion) splits that folder: each + of its documents takes the longer name. Two documents still left with + one name are refused. """ - counts = Counter(name for name, _ in names) - out = [name if counts[name] == 1 else longer for name, longer in names] + existing = existing or {} + identities = {identity for identity, _, _ in documents} + held = {identity: name for name, identity in existing.items() if identity in identities} + unknown = {name for name, identity in existing.items() if identity not in identities} + shorts = Counter(name for _, name, _ in documents) + split = {name for name, n in shorts.items() if merged and n > 1 and name in existing} + out = [held.get(identity) if held.get(identity) not in split else None + for identity, _, _ in documents] + taken = {name for name in out if name} + for i, (_, name, longer) in enumerate(documents): + if out[i] is None: + free = name not in taken and name not in split + out[i] = name if free and (shorts[name] == 1 or name in unknown) else longer + taken.add(out[i]) shared = sorted(name for name, n in Counter(out).items() if n > 1) if shared: raise SystemExit(redact(f"two documents would share the trial {shared[0]!r}")) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 4c3cde2b2..c62a7bd77 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -320,15 +320,24 @@ def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict: +def _source_in(trial_dir: str): + """The source document a trial folder was made from, as recorded.""" + try: + with open(os.path.join(trial_dir, "result.json"), encoding="utf-8") as fh: + return str(json.load(fh)["source_document"]["path"]) + except (OSError, ValueError, KeyError, TypeError): + return None + + def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str) -> 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. + job_dir = os.path.join(out_root, job_name) names = importers.unique_names([ - (_trial_name(path, root), _trial_name(path, root) + "__" + (os.path.abspath(path), _trial_name(path, root), _trial_name(path, root) + "__" + hashlib.sha256(_shown(path, root).encode()).hexdigest()[:8]) - for path, _doc in docs]) - job_dir = os.path.join(out_root, job_name) + for path, _doc in docs], *importers.existing_trials(job_dir, _source_in)) os.makedirs(job_dir, exist_ok=True) summaries = [convert_document(path, doc, name, job_dir) diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index bdbb07a44..502bcce83 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -205,11 +205,29 @@ def write_trial(document: dict, job_dir: str, trial: str = "") -> dict: "model": model, "agent": agent.get("name") or "", "changed": changed} +def _trace_id_in(trial_dir: str): + """The trace a trial folder holds: its recorded id, or its trace's own.""" + for path, keys in ((("result.json"), ("source_document", "trace_id")), + (os.path.join("agent", "trace.json"), ("session_id",))): + try: + with open(os.path.join(trial_dir, path), encoding="utf-8") as fh: + value = json.load(fh) + for key in keys: + value = value[key] + except (OSError, ValueError, KeyError, TypeError): + continue + if value is not None: + return str(value) + return None + + def _write_job(documents: list, out_root: str, job_name: str, command: str, root: str, skipped: list) -> str: - names = importers.unique_names( - [(trial_name_of(doc), trial_name_of(doc, full=True)) for doc in documents]) job_dir = os.path.join(out_root, job_name) + names = importers.unique_names( + [(str(doc.get("session_id") or ""), trial_name_of(doc), trial_name_of(doc, full=True)) + for doc in documents], + *importers.existing_trials(job_dir, _trace_id_in)) os.makedirs(job_dir, exist_ok=True) summaries = [write_trial(doc, job_dir, name) for doc, name in zip(documents, names)] diff --git a/app/tests/harnesses/test_atif.py b/app/tests/harnesses/test_atif.py index 0e4d5761d..d8a3a8495 100644 --- a/app/tests/harnesses/test_atif.py +++ b/app/tests/harnesses/test_atif.py @@ -115,6 +115,34 @@ def test_paths_that_flatten_to_one_name_stay_two_trials(self): self.assertEqual(sessions, {"s-nested", "s-flat", "s-1"}) self.assertEqual(json.loads(Path(job_dir, "result.json").read_text())["n_total_trials"], 3) + def test_a_later_colliding_document_never_renames_the_trial_already_there(self): + src = tempfile.mkdtemp() + write_doc(src, "a__b.json", minimal(session_id="s-first")) + job_dir, _ = self.convert(src) + before = {p.relative_to(job_dir): p.read_bytes() for p in Path(job_dir, "a__b").rglob("*") if p.is_file()} + write_doc(src, "a/b.json", minimal(session_id="s-later")) + _, job = self.convert(src) + names = sorted(t.trial_name for t in job.trials) + self.assertEqual(names[0], "a__b") + self.assertRegex(names[1], r"^a__b__[0-9a-f]{8}$") + after = {p.relative_to(job_dir): p.read_bytes() for p in Path(job_dir, "a__b").rglob("*") if p.is_file()} + self.assertEqual(after, before) + + def test_a_folder_an_older_conversion_wrote_two_documents_into_is_split(self): + src = tempfile.mkdtemp() + write_doc(src, "a__b.json", minimal(session_id="s-flat")) + write_doc(src, "a/b.json", minimal(session_id="s-nested")) + job_dir = os.path.join(self.out, "atif__old") + os.makedirs(os.path.join(job_dir, "a__b")) + Path(job_dir, "a__b", "result.json").write_text(json.dumps( + {"source_document": {"path": os.path.join(src, "a", "b.json")}})) + Path(job_dir, "result.json").write_text(json.dumps({"n_total_trials": 2})) + _, job = self.convert(src, job_name="atif__old") + names = sorted(t.trial_name for t in job.trials) + self.assertEqual(len(names), 2) + for name in names: + self.assertRegex(name, r"^a__b__[0-9a-f]{8}$") + def test_re_converting_updates_in_place_and_drops_a_stale_trial(self): src = tempfile.mkdtemp() write_doc(src, "a.json", minimal()) diff --git a/app/tests/harnesses/test_otel_import.py b/app/tests/harnesses/test_otel_import.py index 462e6c7f0..4d093e6a4 100644 --- a/app/tests/harnesses/test_otel_import.py +++ b/app/tests/harnesses/test_otel_import.py @@ -64,6 +64,30 @@ def test_traces_whose_short_names_collide_stay_two_trials(self): for t in trials} self.assertEqual(recorded, set(ids)) + def test_a_later_colliding_trace_never_renames_the_trial_already_there(self): + src = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, src, True) + first, later = "abcdef1" + "f" * 25, "abcdef1" + "0" * 25 + + def export(name, tid): + with open(os.path.join(src, name), "w") as fh: + json.dump({"resourceSpans": [{"resource": {}, "scopeSpans": [{"spans": [ + {"traceId": tid, "spanId": "01", "name": "agent run", + "startTimeUnixNano": "1", "endTimeUnixNano": "9"}]}]}]}, fh) + + def files(trial): + root = Path(job_dir, trial) + return {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()} + + export("one.json", first) + job_dir = importer.convert(src, self.out)[0] + before = files("agent_run__abcdef1") + export("two.json", later) + importer.convert(src, self.out) + trials = sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) + self.assertEqual(trials, ["agent_run__abcdef1", "agent_run__" + later]) + self.assertEqual(files("agent_run__abcdef1"), before) + def test_a_refused_file_deeper_down_is_named_by_its_path_under_the_root_once(self): src = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, src, True) From 251c49e3c6d4f5f5d025a545a870ebb1898049fc Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 17:27:10 +0100 Subject: [PATCH 3/7] fix(runs): keep a gone document's trial name from a newcomer, match documents by real path and split only a folder listed twice A trial whose recorded document is known but no longer in the source keeps its name reserved: a newcomer with the same short name takes the longer one. ATIF documents are compared by real path, so one tree reached through a link keeps its trials. A folder counts as written by two documents when its job's config lists it twice; only a job without that list falls back to the trial count. --- app/nullius/importers/__init__.py | 36 ++++++++++++++-------- app/nullius/importers/atif.py | 7 +++-- app/tests/harnesses/test_atif.py | 41 +++++++++++++++++++------ app/tests/harnesses/test_otel_import.py | 6 ++++ 4 files changed, 65 insertions(+), 25 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index 03748ebab..3675a71b5 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -142,46 +142,56 @@ def write_if_changed(path: str, data: bytes) -> bool: return True -def existing_trials(job_dir: str, identity_of) -> tuple[dict, bool]: +def existing_trials(job_dir: str, identity_of) -> tuple[dict, set]: """The trials a previous conversion left in *job_dir*: name -> the document each holds, by ``identity_of(trial_dir)`` (None when the files - cannot tell), and whether the job counted more trials than it has folders, - which is how two documents once written into one folder show.""" + cannot tell), and the names of folders two documents were once written + into: a name its ``config.json`` lists twice among its tasks, or, without + that list, any name when the job counted more trials than it has folders.""" trials = {} if os.path.isdir(job_dir): for name in sorted(os.listdir(job_dir)): if os.path.isdir(os.path.join(job_dir, name)): trials[name] = identity_of(os.path.join(job_dir, name)) + try: + with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as fh: + tasks = json.load(fh)["tasks"] + listed = Counter(str(t["name"]).split("/", 1)[-1] for t in tasks) + return trials, {name for name, n in listed.items() if n > 1} + except (OSError, ValueError, KeyError, TypeError): + pass try: with open(os.path.join(job_dir, "result.json"), encoding="utf-8") as fh: counted = json.load(fh)["n_total_trials"] except (OSError, ValueError, KeyError, TypeError): counted = len(trials) - return trials, isinstance(counted, int) and counted > len(trials) + # shortcut: a folder deleted by hand also counts, so any collision splits; only jobs without a tasks list + return trials, set(trials) if isinstance(counted, int) and counted > len(trials) else set() def unique_names(documents: list[tuple], existing: dict | None = None, - merged: bool = False) -> list[str]: + merged: set = frozenset()) -> list[str]: """One trial directory per document, decided before anything is written. Each document is (identity, name, longer name). A document whose trial already exists keeps that trial's name: judgements are keyed by it. A - folder whose document cannot be told keeps its name for the first + folder whose document is known stays that document's, even when it is + gone. A folder whose document cannot be told keeps its name for the first document that would take it. Any other document takes its name unless - another holds it, else the longer one. A *merged* job (two documents - written into one folder by an older conversion) splits that folder: each - of its documents takes the longer name. Two documents still left with - one name are refused. + another holds it, else the longer one. A *merged* folder (two documents + written into one by an older conversion) is split: each of its documents + takes the longer name. Two documents still left with one name are refused. """ existing = existing or {} identities = {identity for identity, _, _ in documents} held = {identity: name for name, identity in existing.items() if identity in identities} - unknown = {name for name, identity in existing.items() if identity not in identities} + unknown = {name for name, identity in existing.items() if identity is None} + gone = {name for name, identity in existing.items() if identity is not None and identity not in identities} shorts = Counter(name for _, name, _ in documents) - split = {name for name, n in shorts.items() if merged and n > 1 and name in existing} + split = {name for name, n in shorts.items() if n > 1 and name in existing and name in merged} out = [held.get(identity) if held.get(identity) not in split else None for identity, _, _ in documents] - taken = {name for name in out if name} + taken = {name for name in out if name} | gone for i, (_, name, longer) in enumerate(documents): if out[i] is None: free = name not in taken and name not in split diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index c62a7bd77..5062f9c8d 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -321,10 +321,11 @@ def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict: def _source_in(trial_dir: str): - """The source document a trial folder was made from, as recorded.""" + """The source document a trial folder was made from, as recorded, by its real path: one tree + reached through a link is the same tree.""" try: with open(os.path.join(trial_dir, "result.json"), encoding="utf-8") as fh: - return str(json.load(fh)["source_document"]["path"]) + return os.path.realpath(str(json.load(fh)["source_document"]["path"])) except (OSError, ValueError, KeyError, TypeError): return None @@ -335,7 +336,7 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str # a digest of their path, so each document keeps a trial of its own. job_dir = os.path.join(out_root, job_name) names = importers.unique_names([ - (os.path.abspath(path), _trial_name(path, root), _trial_name(path, root) + "__" + (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], *importers.existing_trials(job_dir, _source_in)) os.makedirs(job_dir, exist_ok=True) diff --git a/app/tests/harnesses/test_atif.py b/app/tests/harnesses/test_atif.py index d8a3a8495..0f4ebeea6 100644 --- a/app/tests/harnesses/test_atif.py +++ b/app/tests/harnesses/test_atif.py @@ -128,20 +128,43 @@ def test_a_later_colliding_document_never_renames_the_trial_already_there(self): after = {p.relative_to(job_dir): p.read_bytes() for p in Path(job_dir, "a__b").rglob("*") if p.is_file()} self.assertEqual(after, before) + def test_one_tree_through_a_link_or_with_a_folder_deleted_by_hand_keeps_its_trial(self): + for case in ("link", "deleted"): + with self.subTest(case): + real = tempfile.mkdtemp() + src = os.path.join(real, "run") + write_doc(src, "a/b.json", minimal(session_id="s-first")) + write_doc(src, "c.json", minimal()) + if case == "link": + os.symlink(src, os.path.join(real, "link")) + job_dir, _ = self.convert(os.path.join(real, "link"), job_name=case) + else: + job_dir, _ = self.convert(src, job_name=case) + shutil.rmtree(os.path.join(job_dir, "c")) + write_doc(src, "a__b.json", minimal(session_id="s-later")) + _, job = self.convert(src, job_name=case) + held = {t.trial_name: json.loads(Path(t.dir, "result.json").read_text())["source_document"]["session_id"] + for t in job.trials} + self.assertEqual(held["a__b"], "s-first") + def test_a_folder_an_older_conversion_wrote_two_documents_into_is_split(self): src = tempfile.mkdtemp() write_doc(src, "a__b.json", minimal(session_id="s-flat")) write_doc(src, "a/b.json", minimal(session_id="s-nested")) job_dir = os.path.join(self.out, "atif__old") - os.makedirs(os.path.join(job_dir, "a__b")) - Path(job_dir, "a__b", "result.json").write_text(json.dumps( - {"source_document": {"path": os.path.join(src, "a", "b.json")}})) - Path(job_dir, "result.json").write_text(json.dumps({"n_total_trials": 2})) - _, job = self.convert(src, job_name="atif__old") - names = sorted(t.trial_name for t in job.trials) - self.assertEqual(len(names), 2) - for name in names: - self.assertRegex(name, r"^a__b__[0-9a-f]{8}$") + for name, data in (("result.json", {"n_total_trials": 2}), # counted, or listed twice + ("config.json", {"tasks": [{"name": "atif/a__b"}, {"name": "atif/a__b"}]})): + with self.subTest(name): + os.makedirs(os.path.join(job_dir, "a__b")) + Path(job_dir, "a__b", "result.json").write_text(json.dumps( + {"source_document": {"path": os.path.join(src, "a", "b.json")}})) + Path(job_dir, name).write_text(json.dumps(data)) + _, job = self.convert(src, job_name="atif__old") + names = sorted(t.trial_name for t in job.trials) + self.assertEqual(len(names), 2) + for trial in names: + self.assertRegex(trial, r"^a__b__[0-9a-f]{8}$") + shutil.rmtree(job_dir) def test_re_converting_updates_in_place_and_drops_a_stale_trial(self): src = tempfile.mkdtemp() diff --git a/app/tests/harnesses/test_otel_import.py b/app/tests/harnesses/test_otel_import.py index 4d093e6a4..df2df7147 100644 --- a/app/tests/harnesses/test_otel_import.py +++ b/app/tests/harnesses/test_otel_import.py @@ -87,6 +87,12 @@ def files(trial): trials = sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) self.assertEqual(trials, ["agent_run__abcdef1", "agent_run__" + later]) self.assertEqual(files("agent_run__abcdef1"), before) + os.remove(os.path.join(src, "one.json")) # gone: its name is still not another trace's + os.remove(os.path.join(src, "two.json")) + export("three.json", "abcdef1" + "1" * 25) + importer.convert(src, self.out) + trials = sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) + self.assertEqual(trials, ["agent_run__abcdef1" + "1" * 25]) def test_a_refused_file_deeper_down_is_named_by_its_path_under_the_root_once(self): src = tempfile.mkdtemp() From d8da9623491a456f77c2272fdc0d83170b299069 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:45:10 +0100 Subject: [PATCH 4/7] fix(runs): keep an imported trial's name its document's after its folder is pruned The job's config.json keeps each trial name with the document it was given to, across conversions. A later document never takes a name another document once held, even after a conversion without that document pruned its folder; the document itself gets its name back when it returns. --- app/nullius/importers/__init__.py | 32 ++++++++++++++++++++++++- app/nullius/importers/atif.py | 5 +++- app/nullius/importers/otel.py | 5 ++-- app/tests/harnesses/test_otel_import.py | 27 +++++++++++++++++++++ 4 files changed, 65 insertions(+), 4 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index 3675a71b5..094a0eebb 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -142,12 +142,42 @@ def write_if_changed(path: str, data: bytes) -> bool: return True +def _reserved(job_dir: str) -> dict: + """Trial name -> the document it was given to, as the job's ``config.json`` + keeps it across conversions: a name stays its document's after its folder + is pruned.""" + try: + with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as fh: + reserved = json.load(fh)["trial_documents"] + return {str(k): str(v) for k, v in reserved.items() if v} + except (OSError, ValueError, KeyError, TypeError, AttributeError): + return {} + + +def reservations(job_dir: str, written) -> dict: + """The ``trial_documents`` to keep in *job_dir*'s ``config.json``: what + it kept, with *written* ((name, document) pairs) on top.""" + reserved = _reserved(job_dir) + reserved.update((name, identity) for name, identity in written if identity) + return dict(sorted(reserved.items())) + + def existing_trials(job_dir: str, identity_of) -> tuple[dict, set]: """The trials a previous conversion left in *job_dir*: name -> the document each holds, by ``identity_of(trial_dir)`` (None when the files - cannot tell), and the names of folders two documents were once written + cannot tell), with the names reserved for documents whose folders are + gone, and the names of folders two documents were once written into: a name its ``config.json`` lists twice among its tasks, or, without that list, any name when the job counted more trials than it has folders.""" + trials, merged = _folders(job_dir, identity_of) + held = set(trials.values()) + for name, identity in _reserved(job_dir).items(): + if name not in trials and identity not in held: + trials[name] = identity + return trials, merged + + +def _folders(job_dir: str, identity_of) -> tuple[dict, set]: trials = {} if os.path.isdir(job_dir): for name in sorted(os.listdir(job_dir)): diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 5062f9c8d..1dd505c78 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -54,7 +54,8 @@ Re-converting is idempotent: trial names are deterministic (the document's path relative to the tree, a bare ``trajectory.json`` named after its directory), every file is rewritten in -place, and a trial the tree no longer holds is removed. +place, and a trial the tree no longer holds is removed; its name stays +its document's, kept in the job's ``config.json`` under ``trial_documents``. """ from __future__ import annotations @@ -376,6 +377,8 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str "agents": [{"name": agent["name"], "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))), }) return job_dir diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index 502bcce83..ea247e870 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -224,9 +224,9 @@ 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: job_dir = os.path.join(out_root, job_name) + ids = [str(doc.get("session_id") or "") for doc in documents] names = importers.unique_names( - [(str(doc.get("session_id") or ""), trial_name_of(doc), trial_name_of(doc, full=True)) - for doc in documents], + [(tid, trial_name_of(doc), trial_name_of(doc, full=True)) for tid, doc in zip(ids, documents)], *importers.existing_trials(job_dir, _trace_id_in)) os.makedirs(job_dir, exist_ok=True) summaries = [write_trial(doc, job_dir, name) for doc, name in zip(documents, names)] @@ -260,6 +260,7 @@ def _write_job(documents: list, out_root: str, job_name: str, command: str, "datasets": [{"name": NAME, "path": root, "n_tasks": len(summaries)}], "import": {"format": reader.FORMAT, "conventions": reader.CONVENTIONS, "skipped": skipped}, + "trial_documents": importers.reservations(job_dir, zip(names, ids)), }) return job_dir diff --git a/app/tests/harnesses/test_otel_import.py b/app/tests/harnesses/test_otel_import.py index df2df7147..1f68d4679 100644 --- a/app/tests/harnesses/test_otel_import.py +++ b/app/tests/harnesses/test_otel_import.py @@ -94,6 +94,33 @@ def files(trial): trials = sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) self.assertEqual(trials, ["agent_run__abcdef1" + "1" * 25]) + def test_a_name_once_given_to_a_trace_stays_its_after_a_conversion_without_it(self): + src = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, src, True) + gone, other, newcomer = "abcdef1" + "f" * 25, "1234567" + "0" * 25, "abcdef1" + "0" * 25 + + def export(name, tid, span="agent run"): + with open(os.path.join(src, name), "w") as fh: + json.dump({"resourceSpans": [{"resource": {}, "scopeSpans": [{"spans": [ + {"traceId": tid, "spanId": "01", "name": span, + "startTimeUnixNano": "1", "endTimeUnixNano": "9"}]}]}]}, fh) + + def trials(): + return sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))) + + export("a.json", gone) + export("x.json", other, "other") + job_dir = importer.convert(src, self.out)[0] + os.remove(os.path.join(src, "a.json")) + importer.convert(src, self.out) # its folder is pruned, its name kept + self.assertEqual(trials(), ["other__1234567"]) + export("b.json", newcomer) + importer.convert(src, self.out) + self.assertEqual(trials(), ["agent_run__" + newcomer, "other__1234567"]) + export("a.json", gone) # back: its own name again + importer.convert(src, self.out) + self.assertEqual(trials(), ["agent_run__abcdef1", "agent_run__" + newcomer, "other__1234567"]) + def test_a_refused_file_deeper_down_is_named_by_its_path_under_the_root_once(self): src = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, src, True) From 019d2421126c1b0213210496738dd19b9cc1a734 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:52:53 +0100 Subject: [PATCH 5/7] test(runs): give the older conversion of the split-folder test the config every conversion wrote --- app/tests/harnesses/test_atif.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/tests/harnesses/test_atif.py b/app/tests/harnesses/test_atif.py index 0f4ebeea6..ef18b8e4c 100644 --- a/app/tests/harnesses/test_atif.py +++ b/app/tests/harnesses/test_atif.py @@ -153,9 +153,10 @@ def test_a_folder_an_older_conversion_wrote_two_documents_into_is_split(self): write_doc(src, "a/b.json", minimal(session_id="s-nested")) job_dir = os.path.join(self.out, "atif__old") for name, data in (("result.json", {"n_total_trials": 2}), # counted, or listed twice - ("config.json", {"tasks": [{"name": "atif/a__b"}, {"name": "atif/a__b"}]})): + ("config.json", {"harness": "atif", "tasks": [{"name": "atif/a__b"}, {"name": "atif/a__b"}]})): with self.subTest(name): os.makedirs(os.path.join(job_dir, "a__b")) + Path(job_dir, "config.json").write_text(json.dumps({"harness": "atif"})) # as every conversion wrote it Path(job_dir, "a__b", "result.json").write_text(json.dumps( {"source_document": {"path": os.path.join(src, "a", "b.json")}})) Path(job_dir, name).write_text(json.dumps(data)) From 569851a61d89321998ab9033ac028191dbb7cb9e Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:23:43 +0100 Subject: [PATCH 6/7] fix(runs): write an imported job's files whole, so a refresh cut short keeps its trial names A conversion rewrote config.json in place: a refresh stopped mid-write left it truncated, and with it the trial names kept for documents whose folders are gone. Each file is now written beside the old one and renamed over it. --- app/nullius/importers/__init__.py | 7 ++++--- app/tests/harnesses/test_atif.py | 12 ++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index 094a0eebb..f7642ad01 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -48,6 +48,7 @@ from collections import Counter from types import ModuleType +from nullius import ondisk from nullius.redact import redact # A module must expose all three to count. A half-written one is skipped @@ -129,7 +130,8 @@ def problem(path: str) -> str | None: def write_if_changed(path: str, data: bytes) -> bool: """Write *data* to *path* unless the file already holds it; True when - written. A conversion runs at each open of a workspace; an unchanged one + written, whole, renamed over the old file: a refresh cut short leaves the + old one. A conversion runs at each open of a workspace; an unchanged one keeps its mtimes, and with them the parse cache that keys on them.""" try: with open(path, "rb") as fh: @@ -137,8 +139,7 @@ def write_if_changed(path: str, data: bytes) -> bool: return False except OSError: pass - with open(path, "wb") as fh: - fh.write(data) + ondisk.write_whole(path, data) return True diff --git a/app/tests/harnesses/test_atif.py b/app/tests/harnesses/test_atif.py index ef18b8e4c..4cd1f230c 100644 --- a/app/tests/harnesses/test_atif.py +++ b/app/tests/harnesses/test_atif.py @@ -147,6 +147,18 @@ def test_one_tree_through_a_link_or_with_a_folder_deleted_by_hand_keeps_its_tria for t in job.trials} self.assertEqual(held["a__b"], "s-first") + def test_a_refresh_replaces_the_config_whole(self): + src = tempfile.mkdtemp() + write_doc(src, "a.json", minimal()) + job_dir, _ = self.convert(src) + with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as held: # a reader mid-refresh + before = held.read() + write_doc(src, "b.json", minimal()) + self.convert(src) + held.seek(0) + self.assertEqual(held.read(), before) + self.assertIn("atif/b", Path(job_dir, "config.json").read_text()) + def test_a_folder_an_older_conversion_wrote_two_documents_into_is_split(self): src = tempfile.mkdtemp() write_doc(src, "a__b.json", minimal(session_id="s-flat")) From d062c100c9e0f504ed4648238ac587f0a3541210 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:23:49 +0100 Subject: [PATCH 7/7] fix(runs): keep a pruned trial's name from a job made before names were kept, and from a longer name A job converted before trial_documents lost a gone document's name on its first refresh: the folder was pruned before its name was recorded. The names of every folder whose document is known are now recorded before pruning. A document whose short name was taken fell back to its longer name even when that name was kept for a gone document. Such a conversion is now refused before anything is written. --- app/nullius/importers/__init__.py | 12 ++++++++---- app/nullius/importers/atif.py | 5 +++-- app/nullius/importers/otel.py | 5 +++-- app/tests/harnesses/test_atif.py | 28 ++++++++++++++++++++++++++++ 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index f7642ad01..cf981855b 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -155,10 +155,13 @@ def _reserved(job_dir: str) -> dict: return {} -def reservations(job_dir: str, written) -> dict: +def reservations(job_dir: str, written, existing: dict = None, merged: set = frozenset()) -> dict: """The ``trial_documents`` to keep in *job_dir*'s ``config.json``: what - it kept, with *written* ((name, document) pairs) on top.""" + it kept, and the folders *existing* held before pruning (but a *merged* one or one whose document + could not be told), with *written* ((name, document) pairs) on top.""" reserved = _reserved(job_dir) + reserved.update((name, identity) for name, identity in (existing or {}).items() + if identity and name not in merged and name not in reserved) reserved.update((name, identity) for name, identity in written if identity) return dict(sorted(reserved.items())) @@ -211,7 +214,8 @@ def unique_names(documents: list[tuple], existing: dict | None = None, document that would take it. Any other document takes its name unless another holds it, else the longer one. A *merged* folder (two documents written into one by an older conversion) is split: each of its documents - takes the longer name. Two documents still left with one name are refused. + takes the longer name. Two documents still left with one name, or a + document left with a gone document's, are refused. """ existing = existing or {} identities = {identity for identity, _, _ in documents} @@ -228,7 +232,7 @@ def unique_names(documents: list[tuple], existing: dict | None = None, free = name not in taken and name not in split out[i] = name if free and (shorts[name] == 1 or name in unknown) else longer taken.add(out[i]) - shared = sorted(name for name, n in Counter(out).items() if n > 1) + shared = sorted({name for name, n in Counter(out).items() if n > 1} | (set(out) & gone)) if shared: raise SystemExit(redact(f"two documents would share the trial {shared[0]!r}")) return out diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 1dd505c78..9414702cc 100644 --- a/app/nullius/importers/atif.py +++ b/app/nullius/importers/atif.py @@ -336,10 +336,11 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str # 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. job_dir = os.path.join(out_root, job_name) + existing = importers.existing_trials(job_dir, _source_in) 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], *importers.existing_trials(job_dir, _source_in)) + for path, _doc in docs], *existing) os.makedirs(job_dir, exist_ok=True) summaries = [convert_document(path, doc, name, job_dir) @@ -378,7 +379,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))), + job_dir, ((name, os.path.realpath(path)) for (path, _doc), name in zip(docs, names)), *existing), }) return job_dir diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index ea247e870..b6ded5a5d 100644 --- a/app/nullius/importers/otel.py +++ b/app/nullius/importers/otel.py @@ -225,9 +225,10 @@ def _write_job(documents: list, out_root: str, job_name: str, command: str, root: str, skipped: list) -> 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) names = importers.unique_names( [(tid, trial_name_of(doc), trial_name_of(doc, full=True)) for tid, doc in zip(ids, documents)], - *importers.existing_trials(job_dir, _trace_id_in)) + *existing) os.makedirs(job_dir, exist_ok=True) summaries = [write_trial(doc, job_dir, name) for doc, name in zip(documents, names)] @@ -260,7 +261,7 @@ def _write_job(documents: list, out_root: str, job_name: str, command: str, "datasets": [{"name": NAME, "path": root, "n_tasks": len(summaries)}], "import": {"format": reader.FORMAT, "conventions": reader.CONVENTIONS, "skipped": skipped}, - "trial_documents": importers.reservations(job_dir, zip(names, ids)), + "trial_documents": importers.reservations(job_dir, zip(names, ids), *existing), }) return job_dir diff --git a/app/tests/harnesses/test_atif.py b/app/tests/harnesses/test_atif.py index 4cd1f230c..1ef8f1cb0 100644 --- a/app/tests/harnesses/test_atif.py +++ b/app/tests/harnesses/test_atif.py @@ -8,6 +8,7 @@ the same trajectories came from are not claimed. """ +import hashlib import json import os import shutil @@ -147,6 +148,33 @@ def test_one_tree_through_a_link_or_with_a_folder_deleted_by_hand_keeps_its_tria for t in job.trials} self.assertEqual(held["a__b"], "s-first") + def test_a_gone_document_keeps_its_name_from_a_job_without_reservations_and_from_a_longer_name(self): + src = tempfile.mkdtemp() + write_doc(src, "a/b.json", minimal(session_id="s-gone")) + write_doc(src, "c.json", minimal()) + job_dir, _ = self.convert(src) + config = json.loads(Path(job_dir, "config.json").read_text()) + del config["trial_documents"] # as a conversion before them wrote it + Path(job_dir, "config.json").write_text(json.dumps(config)) + os.remove(os.path.join(src, "a", "b.json")) + self.convert(src) # its folder is pruned, its name kept + write_doc(src, "a__b.json", minimal(session_id="s-new")) + _, job = self.convert(src) + self.assertNotIn("a__b", {t.trial_name for t in job.trials}) + + src = tempfile.mkdtemp() # a gone file named like another's longer name + longer = "a__b__" + hashlib.sha256(b"a/b.json").hexdigest()[:8] + write_doc(src, longer + ".json", minimal(session_id="s-gone")) + write_doc(src, "c.json", minimal()) + job_dir, _ = self.convert(src, job_name="longer") + os.remove(os.path.join(src, longer + ".json")) + self.convert(src, job_name="longer") + write_doc(src, "a/b.json", minimal(session_id="s-nested")) + write_doc(src, "a__b.json", minimal(session_id="s-flat")) + with self.assertRaisesRegex(SystemExit, "share the trial"): + self.convert(src, job_name="longer") + self.assertEqual(sorted(n for n in os.listdir(job_dir) if os.path.isdir(os.path.join(job_dir, n))), ["c"]) + def test_a_refresh_replaces_the_config_whole(self): src = tempfile.mkdtemp() write_doc(src, "a.json", minimal())