Skip to content

Commit 872e60a

Browse files
authored
perf(runs): leave an unchanged imported job as it is on each workspace open (#264)
Closes #259 ## What Each open of a workspace converts its ATIF and OpenTelemetry roots again (`shared._import_roots`). Both importers rewrote every file of the converted job, so the job got new mtimes and `workspace.load_job` parsed it again, even when the source had not changed. - `importers.write_if_changed` writes a file only when its bytes differ from the file on disk, and says whether it wrote. The ATIF importer uses it for the job's `result.json` and `config.json`, each trial's `result.json`, and the `trajectory.json` copy (still byte for byte). The OpenTelemetry importer's `_dump` uses it for the same files and `trace.json`. - `importers.mark_changed` moves the job's `result.json` mtime when any trial was written. An ended job's cache is checked by the job's own records and folder, and a change inside one trial can leave those identical, so without this an edited source would keep its old parse. Comparing the output bytes, rather than stamping the source, also covers a new importer version: any change in what it writes is written. A trial whose source is gone is removed as before. ## Touches backend (`nullius/importers/__init__.py`, `nullius/importers/atif.py`, `nullius/importers/otel.py`) · tests (`tests/test_import_unchanged_source.py`) ## Verified In a rootless Podman container (`python:3.12`): - `python3 app/tests/parallel.py`: 3106 tests in 158 modules, OK. - `pip install -r app/requirements.txt`, then `python3 app/tests/parallel.py app/ui_tests`: 555 tests in 56 modules, OK. - New `app/tests/test_import_unchanged_source.py`, one test per importer: convert, read, convert again over the unchanged source (no file in the job moves, and `load_job` returns the cached parse), then edit the source in a way that leaves the job's own records identical and convert again (files move, and the job is parsed again). - With the importers from main, both tests fail: `config.json`, `result.json` and each trial's files move, and the second read parses. - Without `mark_changed`, both fail on the edited source: the stale parse is returned. ## Risk - Each conversion now reads each existing output file once to compare it. These are the files it wrote before, and the source is read whole already. - A file in `imported/` edited by hand to the exact bytes the importer would write is left as it is. Any other edit is overwritten, as before.
1 parent d00c8e9 commit 872e60a

4 files changed

Lines changed: 123 additions & 30 deletions

File tree

‎app/nullius/importers/__init__.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from __future__ import annotations
5151

5252
import importlib
53+
import os
5354
import pkgutil
5455
import shutil
5556
import tempfile
@@ -136,5 +137,27 @@ def problem(path: str) -> str | None:
136137
return None
137138

138139

140+
def write_if_changed(path: str, data: bytes) -> bool:
141+
"""Write *data* to *path* unless the file already holds it; True when
142+
written. A conversion runs at each open of a workspace; an unchanged one
143+
keeps its mtimes, and with them the parse cache that keys on them."""
144+
try:
145+
with open(path, "rb") as fh:
146+
if fh.read() == data:
147+
return False
148+
except OSError:
149+
pass
150+
with open(path, "wb") as fh:
151+
fh.write(data)
152+
return True
153+
154+
155+
def mark_changed(job_dir: str, summaries: list) -> None:
156+
"""Move the job's own ``result.json`` when one of its trials was written:
157+
an ended job's cached parse is checked by that file, not trial by trial."""
158+
if any(s["changed"] for s in summaries):
159+
os.utime(os.path.join(job_dir, "result.json"))
160+
161+
139162
def labels() -> str:
140163
return ", ".join(getattr(m, "LABEL", name) for name, m in available().items())

‎app/nullius/importers/atif.py‎

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
import shutil
7171
from datetime import timezone
7272

73+
from nullius import importers
7374
from nullius.redact import redact
7475
from nullius.traces.trajectory import parse_ts
7576

@@ -273,6 +274,10 @@ def number(key):
273274
}
274275

275276

277+
def _dump(path: str, data) -> bool:
278+
return importers.write_if_changed(path, json.dumps(data, indent=2).encode())
279+
280+
276281
def _sha256(path: str) -> str:
277282
digest = hashlib.sha256()
278283
with open(path, "rb") as fh:
@@ -316,15 +321,15 @@ def convert_document(path: str, doc: dict, trial: str, job_dir: str) -> dict:
316321
"session_id": doc.get("session_id"),
317322
},
318323
}
319-
with open(os.path.join(trial_dir, "result.json"), "w", encoding="utf-8") as fh:
320-
json.dump(result, fh, indent=2)
324+
changed = _dump(os.path.join(trial_dir, "result.json"), result)
321325

322326
# Byte for byte: the trial page reads what the producer wrote, and a
323327
# digest of the copy is a digest of the source.
324-
shutil.copyfile(path, os.path.join(agent_dir, "trajectory.json"))
328+
with open(path, "rb") as fh:
329+
changed |= importers.write_if_changed(os.path.join(agent_dir, "trajectory.json"), fh.read())
325330

326331
return {"trial_dir": trial, "started_at": started, "finished_at": finished,
327-
"agent_info": result["agent_info"]}
332+
"agent_info": result["agent_info"], "changed": changed}
328333

329334

330335

@@ -346,30 +351,29 @@ def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str
346351
# ordered as instants, not as text: one stamp with a zone and one without sort apart as strings
347352
starts = sorted((s["started_at"] for s in summaries if s["started_at"]), key=_instant)
348353
ends = sorted((s["finished_at"] for s in summaries if s["finished_at"]), key=_instant)
349-
with open(os.path.join(job_dir, "result.json"), "w", encoding="utf-8") as fh:
350-
json.dump({
351-
"started_at": starts[0] if starts else None,
352-
"finished_at": ends[-1] if ends else None,
353-
"n_total_trials": len(summaries),
354-
"stats": {"n_errored_trials": 0, "n_running_trials": 0,
355-
"n_pending_trials": 0, "n_retries": 0},
356-
}, fh, indent=2)
354+
_dump(os.path.join(job_dir, "result.json"), {
355+
"started_at": starts[0] if starts else None,
356+
"finished_at": ends[-1] if ends else None,
357+
"n_total_trials": len(summaries),
358+
"stats": {"n_errored_trials": 0, "n_running_trials": 0,
359+
"n_pending_trials": 0, "n_retries": 0},
360+
})
361+
importers.mark_changed(job_dir, summaries)
357362

358363
# The first document's producer names the job; a tree that mixes
359364
# producers still shows each trial's own under agent_info.
360365
agent = next((s["agent_info"] for s in summaries if s["agent_info"]["name"]),
361366
summaries[0]["agent_info"])
362-
with open(os.path.join(job_dir, "config.json"), "w", encoding="utf-8") as fh:
363-
json.dump({
364-
"job_name": job_name,
365-
"harness": NAME, # provenance; the walker ignores unknown keys
366-
"command": command or (
367-
f"PYTHONPATH=app python3 -m nullius.importers.cli {shlex.quote(root)} "
368-
f"-o {shlex.quote(out_root)} --job-name {shlex.quote(job_name)}"),
369-
"agents": [{"name": agent["name"],
370-
"model_name": agent["model_info"]["name"]}],
371-
"tasks": [{"name": f"{NAME}/{s['trial_dir']}"} for s in summaries],
372-
}, fh, indent=2)
367+
_dump(os.path.join(job_dir, "config.json"), {
368+
"job_name": job_name,
369+
"harness": NAME, # provenance; the walker ignores unknown keys
370+
"command": command or (
371+
f"PYTHONPATH=app python3 -m nullius.importers.cli {shlex.quote(root)} "
372+
f"-o {shlex.quote(out_root)} --job-name {shlex.quote(job_name)}"),
373+
"agents": [{"name": agent["name"],
374+
"model_name": agent["model_info"]["name"]}],
375+
"tasks": [{"name": f"{NAME}/{s['trial_dir']}"} for s in summaries],
376+
})
373377
return job_dir
374378

375379

‎app/nullius/importers/otel.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
import shutil
5555
from datetime import datetime, timezone
5656

57+
from nullius import importers
5758
from nullius.redact import redact
5859
from nullius.traces import otel as reader
5960
from nullius.traces import trace
@@ -139,10 +140,8 @@ def _iso(ns: int) -> str:
139140
return datetime.fromtimestamp(ns / 1e9, tz=timezone.utc).isoformat().replace("+00:00", "Z")
140141

141142

142-
def _dump(path: str, data) -> None:
143-
with open(path, "w", encoding="utf-8") as fh:
144-
json.dump(data, fh, ensure_ascii=False, indent=1)
145-
fh.write("\n")
143+
def _dump(path: str, data) -> bool:
144+
return importers.write_if_changed(path, (json.dumps(data, ensure_ascii=False, indent=1) + "\n").encode())
146145

147146

148147
def _window(document: dict) -> tuple:
@@ -206,10 +205,10 @@ def write_trial(document: dict, job_dir: str) -> dict:
206205
"n_cache_tokens": tokens.get("cache_read_tokens", 0),
207206
"cost_usd": None,
208207
}
209-
_dump(os.path.join(trial_dir, "result.json"), result)
210-
_dump(os.path.join(agent_dir, "trace.json"), document)
208+
changed = _dump(os.path.join(trial_dir, "result.json"), result)
209+
changed |= _dump(os.path.join(agent_dir, "trace.json"), document)
211210
return {"trial_dir": trial, "started_at": started, "finished_at": finished,
212-
"model": model, "agent": agent.get("name") or ""}
211+
"model": model, "agent": agent.get("name") or "", "changed": changed}
213212

214213

215214
def _write_job(documents: list, out_root: str, job_name: str, command: str,
@@ -235,6 +234,7 @@ def _write_job(documents: list, out_root: str, job_name: str, command: str,
235234
"stats": {"n_errored_trials": 0, "n_running_trials": 0,
236235
"n_pending_trials": 0, "n_retries": 0},
237236
})
237+
importers.mark_changed(job_dir, summaries)
238238
agents = sorted({s["agent"] for s in summaries if s["agent"]}) or [""]
239239
models = sorted({s["model"] for s in summaries if s["model"]})
240240
_dump(os.path.join(job_dir, "config.json"), {
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""Opening a workspace again over an unchanged ATIF or OpenTelemetry source
2+
leaves the converted job as it was, so its cached parse is used; a changed
3+
source is converted and parsed again."""
4+
from __future__ import annotations
5+
6+
import os
7+
import shutil
8+
import tempfile
9+
import time
10+
import unittest
11+
from pathlib import Path
12+
13+
from nullius import importers, workspace
14+
from tests.harnesses.test_atif import minimal, write_doc
15+
from tests.test_cli_contract import otlp_doc
16+
17+
18+
def open_again(root, imports):
19+
"""What shared._import_roots does for a root on each open_workspace."""
20+
module = importers.detect(root)
21+
return [d for tree in importers.trees(module, root) for d in module.convert(tree, imports)]
22+
23+
24+
def mtimes(job_dir):
25+
return {os.path.relpath(os.path.join(d, f), job_dir): os.stat(os.path.join(d, f)).st_mtime_ns
26+
for d, _, files in os.walk(job_dir) for f in files}
27+
28+
29+
class UnchangedSource(unittest.TestCase):
30+
def setUp(self):
31+
self.tmp = Path(tempfile.mkdtemp(prefix="nullius-import-"))
32+
self.addCleanup(shutil.rmtree, self.tmp, True)
33+
self.src = self.tmp / "src"
34+
35+
def check(self, change):
36+
"""Convert, read, open again unchanged, then again after *change*."""
37+
ws = workspace.create(str(self.tmp / "workspaces"), [str(self.src)], "w")
38+
[job_dir] = open_again(str(self.src), ws.imports_dir)
39+
before = mtimes(job_dir)
40+
self.assertFalse(workspace.load_job(ws, job_dir)[1]) # the first read parses
41+
time.sleep(0.05)
42+
open_again(str(self.src), ws.imports_dir) # opened again; the source unchanged
43+
moved = sorted(f for f, m in mtimes(job_dir).items() if before.get(f) != m)
44+
self.assertEqual((moved, workspace.load_job(ws, job_dir)[1]), ([], True))
45+
change()
46+
open_again(str(self.src), ws.imports_dir) # opened again; the source changed
47+
self.assertNotEqual(mtimes(job_dir), before)
48+
self.assertFalse(workspace.load_job(ws, job_dir)[1])
49+
50+
# Each change leaves the job's own result.json and config.json as they were.
51+
def test_atif(self):
52+
write_doc(self.src, "run-1.json", minimal())
53+
edited = minimal()
54+
edited["steps"][1]["message"] = "redone"
55+
self.check(lambda: write_doc(self.src, "run-1.json", edited))
56+
57+
def test_opentelemetry(self):
58+
write_doc(self.src, "export.json", otlp_doc())
59+
edited = otlp_doc()
60+
edited["resourceSpans"][0]["scopeSpans"][0]["spans"][0]["attributes"] = [
61+
{"key": "k", "value": {"stringValue": "v"}}]
62+
self.check(lambda: write_doc(self.src, "export.json", edited))
63+
64+
65+
if __name__ == "__main__":
66+
unittest.main()

0 commit comments

Comments
 (0)