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
62 changes: 48 additions & 14 deletions app/nullius/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
application writes is checked trial by trial while that run goes on (a host
run's copy can bring a trial's files after the job's own), and its head
carries the run's end, so the last copy is checked trial by trial once more.
An ended job's head is noted in ``jobs/index.json`` beside the signature it was
seen with: a head that moves while the signature holds rewrites that index, not
the job's cache.
"""
from __future__ import annotations

Expand Down Expand Up @@ -346,8 +349,20 @@ def _decode(d):
return d


_JOB_FIELDS = tuple(f.name for f in fields(parse.Job))
_TRIAL_FIELDS = tuple(f.name for f in fields(parse.Trial))


def job_to_dict(job: parse.Job) -> dict:
return asdict(job)
"""*job* as plain values, its containers shared, not copied: read it, never change it.
No field holds a dataclass, so ``asdict``'s deep copy of every trial is not needed."""
out = {n: getattr(job, n) for n in _JOB_FIELDS}
out["trials"] = [_trial_to_dict(t) for t in job.trials]
return out


def _trial_to_dict(trial: parse.Trial) -> dict:
return {n: getattr(trial, n) for n in _TRIAL_FIELDS}


def job_from_dict(data: dict) -> parse.Job:
Expand Down Expand Up @@ -377,7 +392,8 @@ def _index_path(ws: Workspace) -> str:


def job_index(ws: Workspace) -> dict:
"""job dir → {job_id, n_trials}: what the rail lists without parsing."""
"""job dir → {job_id, n_trials, dataset, agent}: what the rail lists without parsing;
an ended job's also its signature and head (_note_in_index)."""
try:
with open(_index_path(ws), encoding="utf-8") as fh:
data = json.load(fh)
Expand All @@ -386,14 +402,24 @@ def job_index(ws: Workspace) -> dict:
return data if isinstance(data, dict) else {}


def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | None = None) -> bool:
"""The job's entry in the rail's index. With ``index`` (load_jobs, which
def _noted_head(ws: Workspace, job_dir: str, sig, index: dict | None) -> str | None:
"""The head the index noted for *job_dir* while its signature was *sig*."""
entry = (job_index(ws) if index is None else index).get(job_dir)
return entry.get("head") if sig and isinstance(entry, dict) and entry.get("signature") == sig else None


def _note_in_index(ws: Workspace, job_dir: str, job: parse.Job, index: dict | None = None,
sig: str = "", head: str = "") -> bool:
"""The job's entry in the rail's index, and an ended job's head with the
signature it was seen with. With ``index`` (load_jobs, which
reads the file once and writes it once) the dict is changed in place and
True returned when it changed; alone, the file is read and written here."""
own = index is None
index = job_index(ws) if own else index
entry = {"job_id": job.job_id, "n_trials": len(job.trials), "dataset": job.dataset,
"agent": job.agent_label or job.agent_name}
if sig and head and _ended(job):
entry.update(signature=sig, head=head)
if index.get(job_dir) == entry:
return False
index[job_dir] = entry
Expand Down Expand Up @@ -465,8 +491,17 @@ def _read_cache(path: str, job_dir: str) -> tuple | None:

def _write_cache(ws: Workspace, path: str, sig: str, head: str, job: parse.Job) -> None:
os.makedirs(ws.jobs_dir, exist_ok=True)
ondisk.write_whole(path, lambda fh: json.dump({"signature": sig, "head": head, "dir": job.dir, "cached": _now(),
"job": job_to_dict(job)}, fh, default=_encode, ensure_ascii=False))
body = {n: getattr(job, n) for n in _JOB_FIELDS if n != "trials"}
dumps = lambda obj: json.dumps(obj, default=_encode, ensure_ascii=False) # the C encoder; json.dump's is Python

def write(fh):
# one trial's text in memory at a time: each dict's closing brace cut and written last
fh.write(dumps({"signature": sig, "head": head, "dir": job.dir, "cached": _now()})[:-1])
fh.write(', "job": ' + dumps(body)[:-1] + ', "trials": [')
for i, t in enumerate(job.trials):
fh.write(("," if i else "") + dumps(_trial_to_dict(t)))
fh.write("]}}")
ondisk.write_whole(path, write)


def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict | None = None) -> tuple:
Expand All @@ -482,29 +517,28 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict
with _DECODED_LOCK:
known = _DECODED.get(path)
if short and known is not None and known[1].dir == job_dir and known[3] == head and _ended(known[1]):
_note_in_index(ws, job_dir, known[1], index)
_note_in_index(ws, job_dir, known[1], index, known[0], head)
return known[1], True
cached = _read_cache(path, job_dir) if known is None else None
if short and cached is not None and cached[1] == head and _ended(cached[2]):
if (short and cached is not None and _ended(cached[2])
and head in (cached[1], _noted_head(ws, job_dir, cached[0], index))):
with _DECODED_LOCK:
_DECODED[path] = (cached[0], cached[2], {}, head)
_note_in_index(ws, job_dir, cached[2], index)
_note_in_index(ws, job_dir, cached[2], index, cached[0], head)
return cached[2], True
sig, trial_sigs = _signatures(job_dir)
if sig:
if known is not None and known[0] == sig and known[1].dir == job_dir:
with _DECODED_LOCK:
_DECODED[path] = (sig, known[1], known[2], head)
_note_in_index(ws, job_dir, known[1], index)
_note_in_index(ws, job_dir, known[1], index, sig, head)
return known[1], True
if known is not None:
cached = _read_cache(path, job_dir)
if cached is not None and cached[0] == sig:
if cached[1] != head and _ended(cached[2]):
_write_cache(ws, path, sig, head, cached[2]) # read by its head from the next process on
with _DECODED_LOCK:
_DECODED[path] = (sig, cached[2], trial_sigs, head)
_note_in_index(ws, job_dir, cached[2], index)
_note_in_index(ws, job_dir, cached[2], index, sig, head) # read by its head from the next process on
return cached[2], True
reuse = None
if known is not None and known[1].dir == job_dir:
Expand All @@ -517,7 +551,7 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None, runs: dict
_write_cache(ws, path, sig, head, job)
with _DECODED_LOCK:
_DECODED[path] = (sig, job, trial_sigs, head)
_note_in_index(ws, job_dir, job, index)
_note_in_index(ws, job_dir, job, index, sig, head)
return job, False


Expand Down
93 changes: 85 additions & 8 deletions app/tests/test_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,17 +266,44 @@ def load():
self.assertEqual([n for n in os.listdir(self.ws.jobs_dir) if n.endswith(".part")], [])

def test_the_cache_is_written_a_piece_at_a_time(self):
job, rows = parse.parse_job(self.job_dir), {"rows": ["x" * 100] * 20000} # about 2 MB as JSON
job = parse.parse_job(self.job_dir)
job.trials = [replace(job.trials[0], exception_message="x" * 1000) for _ in range(2000)] # about 3 MB as JSON
path = os.path.join(self.ws.jobs_dir, "large.json")
with patch.object(workspace, "job_to_dict", lambda job: rows):
tracemalloc.start()
try:
workspace._write_cache(self.ws, path, "sig", "head", job)
peak = tracemalloc.get_traced_memory()[1]
finally:
tracemalloc.stop()
tracemalloc.start()
try:
workspace._write_cache(self.ws, path, "sig", "head", job)
peak = tracemalloc.get_traced_memory()[1]
finally:
tracemalloc.stop()
self.assertGreater(os.path.getsize(path), 2_000_000)
self.assertLess(peak, os.path.getsize(path) / 2) # never the whole text in memory
self.assertEqual(workspace._read_cache(path, job.dir)[2], job)

def test_the_cache_of_every_fixture_reads_back_equal(self):
fixtures = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")
jobs = [parse.parse_job(d) for d in parse.find_job_dirs(
[os.path.join(fixtures, n) for n in sorted(os.listdir(fixtures)) if os.path.isdir(os.path.join(fixtures, n))])]
self.assertGreater(sum(len(j.trials) for j in jobs), 0)
for job in jobs:
self.assertEqual(workspace.job_from_dict(workspace.job_to_dict(job)), job)
path = workspace._cache_file(self.ws, job.dir)
with patch.object(workspace, "asdict", side_effect=AssertionError("asdict")):
workspace._write_cache(self.ws, path, "sig", "head", job)
self.assertEqual(workspace._read_cache(path, job.dir), ("sig", "head", job))

def test_a_cache_written_whole_by_asdict_is_read_by_its_head(self):
from dataclasses import asdict
self._end()
first, _ = workspace.load_job(self.ws, self.job_dir)
path = workspace._cache_file(self.ws, self.job_dir)
with open(path, encoding="utf-8") as fh:
old = json.load(fh)
with open(path, "w", encoding="utf-8") as fh: # as the writer before this one left it
json.dump({**old, "job": asdict(first)}, fh, default=workspace._encode, ensure_ascii=False)
workspace._DECODED.clear()
with patch.object(workspace, "_signatures", side_effect=AssertionError("trials stated")):
again, from_cache = workspace.load_job(self.ws, self.job_dir)
self.assertTrue(from_cache); self.assertEqual(again, first)

def test_load_jobs_matches_load_all(self):
_job_dir(self.root, "job-b", n=1)
Expand Down Expand Up @@ -358,6 +385,56 @@ def test_an_ended_job_is_not_stated_trial_by_trial(self):
again, from_cache = workspace.load_job(self.ws, self.job_dir)
self.assertTrue(from_cache); self.assertEqual(again, first)

def _cache_bytes(self):
path = workspace._cache_file(self.ws, self.job_dir)
with open(path, "rb") as fh:
return fh.read(), os.stat(path).st_mtime_ns

def test_a_moved_head_writes_no_job_cache_and_is_read_by_it_next(self):
self._end()
first = workspace.load_jobs(self.ws, [self.root])
before = self._cache_bytes()
st = os.stat(self.job_dir)
os.utime(self.job_dir, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9)) # an entry added or removed beside the trials
for process in ("next", "fresh"):
workspace._DECODED.clear()
with patch.object(workspace, "_write_cache", side_effect=AssertionError("cache written")):
self.assertEqual(workspace.load_jobs(self.ws, [self.root]), first)
self.assertEqual(self._cache_bytes(), before)
workspace._DECODED.clear() # the process after: the head in the index answers
with patch.object(workspace, "_signatures", side_effect=AssertionError("trials stated")):
self.assertEqual(workspace.load_jobs(self.ws, [self.root]), first)
self.assertEqual(self._cache_bytes(), before)
noted = workspace.job_index(self.ws)[self.job_dir]
self.assertEqual((noted["signature"], noted["head"]), (workspace.signature(self.job_dir), workspace._head(self.job_dir)))

def test_a_head_noted_with_another_signature_answers_nothing(self):
self._end()
workspace.load_job(self.ws, self.job_dir)
st = os.stat(self.job_dir)
os.utime(self.job_dir, ns=(st.st_atime_ns, st.st_mtime_ns + 10**9))
workspace._DECODED.clear()
workspace.load_job(self.ws, self.job_dir) # the head noted in the index
index = workspace.job_index(self.ws)
index[self.job_dir]["signature"] = "another"
workspace._write_index(self.ws, index)
workspace._DECODED.clear()
with patch.object(workspace, "_signatures", wraps=workspace._signatures) as stated:
_, from_cache = workspace.load_job(self.ws, self.job_dir)
self.assertTrue(from_cache); self.assertEqual(stated.call_count, 1)

def test_an_ended_job_that_changed_writes_its_cache_again(self):
self._end()
workspace.load_job(self.ws, self.job_dir)
time.sleep(0.01)
shutil.copytree(os.path.join(self.job_dir, "tau3-bench__t1__abc"), os.path.join(self.job_dir, "tau3-bench__t9__abc"))
workspace._DECODED.clear()
with patch.object(workspace, "_write_cache", wraps=workspace._write_cache) as written:
job, from_cache = workspace.load_job(self.ws, self.job_dir)
self.assertFalse(from_cache); self.assertEqual(written.call_count, 1)
workspace._DECODED.clear()
self.assertEqual(workspace.load_job(self.ws, self.job_dir), (job, True))

def test_a_cache_from_before_the_head_learns_it_once(self):
self._end()
workspace.load_job(self.ws, self.job_dir)
Expand Down
Loading