Skip to content
104 changes: 101 additions & 3 deletions app/nullius/importers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,15 @@
from __future__ import annotations

import importlib
import json
import os
import pkgutil
import shutil
import tempfile
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
Expand Down Expand Up @@ -127,19 +130,114 @@ 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:
if fh.read() == data:
return False
except OSError:
pass
with open(path, "wb") as fh:
fh.write(data)
ondisk.write_whole(path, data)
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, existing: dict = None, merged: set = frozenset()) -> dict:
"""The ``trial_documents`` to keep in *job_dir*'s ``config.json``: what
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()))


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), 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)):
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)
# 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: 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 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* 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, or a
document left with a gone document's, 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 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 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} | gone
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} | (set(out) & gone))
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."""
Expand Down
27 changes: 24 additions & 3 deletions app/nullius/importers/atif.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,12 @@
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

import hashlib
import json
import os
import re
Expand Down Expand Up @@ -319,13 +321,30 @@ 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, 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 os.path.realpath(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)
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], *existing)
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}
Expand Down Expand Up @@ -359,6 +378,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)), *existing),
})
return job_dir

Expand Down
37 changes: 30 additions & 7 deletions app/nullius/importers/otel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""``<root span name>__<7 hex of the trace id>`` — readable, and unique
per trace."""
def trial_name_of(document: dict, full: bool = False) -> str:
"""``<root span name>__<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)
Expand Down Expand Up @@ -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"] = {
Expand All @@ -204,11 +205,32 @@ def write_trial(document: dict, job_dir: 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:
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)],
*existing)
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.
Expand Down Expand Up @@ -239,6 +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), *existing),
})
return job_dir

Expand Down
106 changes: 106 additions & 0 deletions app/tests/harnesses/test_atif.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
the same trajectories came from are not claimed.
"""

import hashlib
import json
import os
import shutil
Expand Down Expand Up @@ -101,6 +102,111 @@ 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_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_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_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())
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"))
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", {"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))
_, 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()
write_doc(src, "a.json", minimal())
Expand Down
Loading
Loading