diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py index cf981855..57194e3e 100644 --- a/app/nullius/importers/__init__.py +++ b/app/nullius/importers/__init__.py @@ -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 @@ -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 @@ -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 ``-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()) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py index 9414702c..bc04b45f 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} @@ -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. @@ -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} @@ -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 @@ -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) diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py index b6ded5a5..9ceb077f 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) @@ -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 @@ -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: @@ -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 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 — diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index 8bee809c..f85e23fb 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -7,11 +7,15 @@ - **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 - 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. + resumed into the same folder and new for a merge; an import carries its + 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 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). @@ -28,15 +32,20 @@ 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") 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,9 +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: its folder names its source - # shortcut: two imports of one source basename share an identity; a per-source id replaces this. - 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 32052b03..c4507b25 100644 --- a/app/tests/test_import_unchanged_source.py +++ b/app/tests/test_import_unchanged_source.py @@ -1,16 +1,21 @@ """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 +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 @@ -62,5 +67,237 @@ 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))) + + +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.""" + + 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_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): + a, b, out = self.sources(fmt) + [ja] = open_again(a, out) + cfg_path = os.path.join(ja, "config.json") + 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 + 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) + + 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()) + [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, 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 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): + 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_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_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 + + 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_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): + 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 + 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__": unittest.main()