Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions app/nullius/importers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@
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 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, 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
the CLI, so it is redacted at construction: a tree is arbitrary bytes from
Expand All @@ -39,12 +48,14 @@
"""
from __future__ import annotations

import contextlib
import importlib
import json
import os
import pkgutil
import shutil
import tempfile
import uuid
from collections import Counter
from types import ModuleType

Expand Down Expand Up @@ -245,5 +256,103 @@ 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


#: 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 = "", 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 ``<default>-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 []
for name in names:
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}")
job_dir = os.path.join(out_root, name)
if not os.path.isdir(job_dir) or not os.listdir(job_dir):
return name, new
cfg = _config(job_dir)
sid = _source(cfg)[0]
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 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 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)
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
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 {}


def labels() -> str:
return ", ".join(getattr(m, "LABEL", name) for name, m in available().items())
96 changes: 68 additions & 28 deletions app/nullius/importers/atif.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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]



Expand Down Expand Up @@ -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)
Expand All @@ -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}
Expand All @@ -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.
Expand All @@ -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}
Expand Down Expand Up @@ -372,14 +372,16 @@ 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"],
"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

Expand All @@ -389,10 +391,48 @@ 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)
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)
root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links
_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)]


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


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)):
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((name, os.path.realpath(str(json.load(fh)["source_document"]["path"]))))
except (OSError, ValueError, KeyError, TypeError):
return []
if not found:
return []
roots, root = [], os.path.commonpath([path for _, path in found])
while True:
# 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
root = os.path.dirname(root)
28 changes: 24 additions & 4 deletions app/nullius/importers/otel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -258,10 +258,13 @@ 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),
**importers.recorded_as(sid, root),
})
return job_dir

Expand All @@ -274,6 +277,17 @@ 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
_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:
Expand All @@ -286,5 +300,11 @@ 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)]
return documents, skipped


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
2 changes: 1 addition & 1 deletion app/nullius/runs/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 —
Expand Down
Loading
Loading