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
43 changes: 41 additions & 2 deletions app/nullius/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<home>/<name>/workspace.json name, label, roots, created, opened, closed
<home>/<name>/imported/ foreign run trees converted to job dirs
<home>/<name>/jobs/<id>.json a parsed Job, keyed by the job dir's signature
<home>/<name>/jobs/counts.json its runs and checks, while its jobs had all ended

``home`` is ``WORKSPACES_DIR`` or ``workspaces/`` in the persistent user data directory.
A name is a slug the user typed, or two words picked at random.
Expand Down Expand Up @@ -104,7 +105,7 @@ def jobs_dir(self) -> str:
def n_cached(self) -> int:
try:
return sum(1 for n in os.listdir(self.jobs_dir)
if n.endswith(".json") and n != "index.json")
if n.endswith(".json") and n not in _NOT_JOBS)
except OSError:
return 0

Expand Down Expand Up @@ -368,6 +369,9 @@ def _cache_file(ws: Workspace, job_dir: str) -> str:
return os.path.join(ws.jobs_dir, f"{key}.json")


_NOT_JOBS = ("index.json", "counts.json") # in jobs/ beside the job caches


def _index_path(ws: Workspace) -> str:
return os.path.join(ws.jobs_dir, "index.json")

Expand Down Expand Up @@ -403,6 +407,41 @@ def _write_index(ws: Workspace, index: dict) -> None:
ondisk.write_whole(_index_path(ws), lambda fh: json.dump(index, fh, ensure_ascii=False, indent=1))


COUNTS_VERSION = 1 # bump when what counts.json holds changes


def _key_digest(key) -> str:
return hashlib.sha256(json.dumps(key, default=str).encode()).hexdigest()


def stored_counts(ws: Workspace, key) -> dict | None:
"""The counts ``store_counts`` kept for *ws* under *key*, else None: no
trial is read. Plain JSON, job-level only: ``{"version", "key", "counts"}``."""
try:
with open(os.path.join(ws.jobs_dir, "counts.json"), encoding="utf-8") as fh:
data = json.load(fh)
except (OSError, ValueError):
return None
counts = data.get("counts") if isinstance(data, dict) else None
if (isinstance(counts, dict) and data.get("version") == COUNTS_VERSION and data.get("key") == _key_digest(key)
and all(isinstance(counts.get(k), int) for k in ("runs", "checks"))):
return counts
return None


def store_counts(ws: Workspace, key, counts: dict | None) -> None:
"""*counts* of *ws* kept beside its job caches under *key*; None removes them."""
path = os.path.join(ws.jobs_dir, "counts.json")
if counts is None:
try:
os.remove(path)
except OSError:
pass
return
os.makedirs(ws.jobs_dir, exist_ok=True)
ondisk.write_whole(path, json.dumps({"version": COUNTS_VERSION, "key": _key_digest(key), "counts": counts}))


# Jobs already decoded in this process, by cache file: (signature, Job, trial
# signatures, head). A page that loads the workspace then skips the JSON decode
# and the rebuild of every unchanged job. A Job is never changed once loaded
Expand Down Expand Up @@ -511,4 +550,4 @@ def clear_cache(ws: Workspace) -> int:
os.remove(os.path.join(ws.jobs_dir, n))
except OSError:
pass
return len([n for n in names if n != "index.json"])
return len([n for n in names if n not in _NOT_JOBS])
24 changes: 24 additions & 0 deletions app/tests/test_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,30 @@ def test_heads_move_with_a_job_added_removed_or_rewritten_not_with_a_trial(self)
gone = os.path.join(self.root, "gone")
self.assertEqual(workspace.heads([gone]), ((gone, None),))

def test_stored_counts_answer_their_own_key_alone(self):
key = ((self.root,), (), workspace.heads([self.root]), (("r1", "done"),), ())
self.assertIsNone(workspace.stored_counts(self.ws, key))
workspace.load_job(self.ws, self.job_dir)
workspace.store_counts(self.ws, key, {"runs": 3, "checks": 1})
self.assertEqual(workspace.stored_counts(self.ws, key), {"runs": 3, "checks": 1})
self.assertEqual(self.ws.n_cached, 1) # not a job's cache
self.assertIsNone(workspace.stored_counts(self.ws, key[:3] + ((("r1", "running"),), ())))
with patch.object(workspace, "COUNTS_VERSION", workspace.COUNTS_VERSION + 1):
self.assertIsNone(workspace.stored_counts(self.ws, key))
path = os.path.join(self.ws.jobs_dir, "counts.json")
for bad in ("[1]", "{", '{"version": 1, "key": "x"}',
json.dumps({"version": 1, "key": workspace._key_digest(key), "counts": {"runs": "3"}})):
with self.subTest(bad=bad):
with open(path, "w", encoding="utf-8") as fh:
fh.write(bad)
self.assertIsNone(workspace.stored_counts(self.ws, key))
workspace.store_counts(self.ws, key, {"runs": 3, "checks": 1})
workspace.store_counts(self.ws, key, None)
self.assertFalse(os.path.exists(path))
workspace.store_counts(self.ws, key, {"runs": 3, "checks": 1})
self.assertEqual(workspace.clear_cache(self.ws), 1) # Refresh drops them with the jobs
self.assertIsNone(workspace.stored_counts(self.ws, key))

def test_index_lists_runs_without_a_parse(self):
self.assertEqual(workspace.job_index(self.ws), {})
workspace.load_job(self.ws, self.job_dir)
Expand Down
58 changes: 58 additions & 0 deletions app/ui_tests/test_run_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,6 +1259,64 @@ def test_counts_kept_between_loads_follow_the_disk(self):
del execution.EXECUTIONS["r9"] # the run records change
self.assertEqual(counts(), ("2", "1", "1"))

def test_counts_after_a_restart_come_from_the_disk(self):
from tests.test_feasibility import write_job
jobs, stored = str(self.run_dir / "jobs"), os.path.join(self.other().jobs_dir, "counts.json")
counts = lambda: (self.cell(self.other(), 2), self.cell(self.other(), 3))

def restart(): # what a new process has: no counts, no decoded job of it
web.workspaces._COUNTS.clear()
with workspace._DECODED_LOCK:
for p in [p for p in workspace._DECODED if os.path.dirname(p) == self.other().jobs_dir]:
del workspace._DECODED[p]

def counted_again(): # (the counts, whether its jobs were read for them)
restart()
with patch.object(web.runs, "_grouped", wraps=web.runs._grouped) as grouped:
got = counts()
return got, any(c.args and c.args[0] is not None and c.args[0].name == self.other().name for c in grouped.call_args_list)

self.assertEqual(counts(), ("2", "0"))
self.assertEqual(json.loads(Path(stored).read_text())["counts"], {"runs": 2, "checks": 0})
self.assertFalse(os.path.exists(os.path.join(self.ws.jobs_dir, "counts.json"))) # the open one: never stored
restart()
with patch.object(workspace, "job_from_dict", side_effect=AssertionError("decoded")), \
patch.object(parse, "parse_job", side_effect=AssertionError("parsed")):
self.assertEqual(counts(), ("2", "0")) # no trial read
self.assertEqual(counted_again(), (("2", "0"), False))
write_job(jobs, "r1-c", "nop", {"a": 0}) # a moved head
self.assertEqual(counted_again(), (("2", "1"), True))
rec = LaunchesPage.record(self, "r9") # a changed root
other = self.other(); other.roots.append(rec.jobs); workspace.save(other)
self.assertEqual(counted_again(), (("3", "2"), True))
del execution.EXECUTIONS["r9"] # a changed run record
self.assertEqual(counted_again(), (("3", "1"), True))
with patch.object(workspace, "COUNTS_VERSION", workspace.COUNTS_VERSION + 1): # another shape on disk
self.assertEqual(counted_again(), (("3", "1"), True))
with patch.object(web.workspaces.catalog, "signature", return_value=(("elsewhere", None),)): # a changed catalogue
self.assertEqual(counted_again(), (("3", "1"), True))
self.assertEqual(counted_again(), (("3", "1"), True)) # and back
self.assertEqual(counted_again(), (("3", "1"), False))
self._write_json(os.path.join(jobs, "r1-c", "result.json"), {"stats": {"n_running_trials": 1}}) # a job still running
self.assertEqual(counted_again(), (("3", "1"), True))
self.assertFalse(os.path.exists(stored))
self.assertNotIn(self.other().name, web.workspaces._COUNTS)
self.assertEqual(counted_again()[1], True) # counted each time

def test_counts_from_the_disk_are_todays_for_every_workspace(self):
from tests.test_feasibility import write_job
live = str(self.tmp / "live"); write_job(live, "l-a", "my-agent", {"a": 1}); write_job(live, "l-nop", "nop", {"a": 0})
self._write_json(os.path.join(live, "l-a", "result.json"), {"stats": {"n_running_trials": 1}})
running = workspace.create(self.home, [live], label="running")
table = lambda: {ws.name: (self.cell(ws, 2), self.cell(ws, 3)) for ws in (self.ws, self.other(), running)}
first = table()
web.workspaces._COUNTS.clear() # a restart
self.assertEqual(table(), first)
web.workspaces._COUNTS.clear()
with patch.object(workspace, "stored_counts", return_value=None): # as today: counted from the jobs
self.assertEqual(table(), first)
self.assertEqual(first[running.name], ("1", "1"))

def test_launches_count_as_the_filtered_launches_page(self):
bare = workspace.create(self.home, [str(self.tmp / "none")], label="bare")
rows = re.findall(r'<tr data-launch="[^"]+".*?data-f-ws="([^"]*)"', self.get("/launches").get_data(as_text=True))
Expand Down
23 changes: 16 additions & 7 deletions app/web/workspaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from markupsafe import Markup, escape
from nullius.runs import parse
from nullius import execution, workspace
from nullius.catalogue import catalog
from nullius.judge import store

from .core import app
Expand Down Expand Up @@ -59,26 +60,34 @@ def _root(path, launched, memo) -> dict:
return {**memo[real], "path": path}


def _counts(ws, recs) -> dict:
def _counts(ws, recs, cat) -> dict:
"""The runs and the checks (nop, oracle) of *ws*, summed over the launches
its Runs page shows, each counted as there and on the Launches page
(``runs._tally``). Its roots are walked, each unchanged job read from its
cache. A closed workspace whose jobs had all ended keeps its counts while
its roots, their heads (``workspace.heads``) and ``recs``, the run records'
ids and states, are unchanged."""
cache. A closed workspace whose jobs had all ended keeps its counts, in
memory and on disk beside its job caches (``workspace.store_counts``), while
its roots, their heads (``workspace.heads``), ``recs``, the run records' ids
and states, and ``cat``, the catalogue's signature, are unchanged."""
is_open = shared.STATE["workspace"] is not None and shared.STATE["workspace"].name == ws.name
key = None if is_open else (tuple(ws.roots), tuple(ws.job_roots), workspace.heads(ws.job_roots or ws.roots), recs)
key = None if is_open else (tuple(ws.roots), tuple(ws.job_roots), workspace.heads(ws.job_roots or ws.roots), recs, cat)
last = _COUNTS.get(ws.name)
if key is not None and last and last[0] == key:
return last[1]
stored = None if key is None else workspace.stored_counts(ws, key) # a restart: no trial read
if stored is not None:
_COUNTS[ws.name] = (key, stored)
return stored
jobs, _, _, groups = runs_web._grouped(None if is_open else ws)
by_id = {j.job_id: j for j in jobs}
tallies = [runs_web._tally(g, by_id) for g in groups]
counts = {"runs": sum(t["n_runs"] for t in tallies), "checks": sum(t["n_checks"] for t in tallies)}
if key is not None and all(j.state == "finished" for j in jobs):
_COUNTS[ws.name] = (key, counts)
workspace.store_counts(ws, key, counts)
else:
_COUNTS.pop(ws.name, None)
if key is not None:
workspace.store_counts(ws, key, None)
return counts


Expand All @@ -89,9 +98,9 @@ def _counts(ws, recs) -> dict:
def workspaces_page():
wss, launched = workspace.list_all(shared.WS_HOME), runs_web._held_launches()
held = [w.name for _, _, holders in launched[0] for w in holders]
recs = tuple((e.id, e.state) for e in execution.EXECUTIONS.values())
recs, cat = tuple((e.id, e.state) for e in execution.EXECUTIONS.values()), catalog.signature()
return render_template("workspaces/workspaces.html", workspaces=wss, csrf=shared._csrf_token(),
counts={ws.name: _counts(ws, recs) for ws in wss}, n_judged={ws.name: store.count(ws.dir) for ws in wss}, n_launches={ws.name: held.count(ws.name) for ws in wss})
counts={ws.name: _counts(ws, recs, cat) for ws in wss}, n_judged={ws.name: store.count(ws.dir) for ws in wss}, n_launches={ws.name: held.count(ws.name) for ws in wss})


@app.route("/workspaces/open/<name>", methods=["POST"])
Expand Down
1 change: 1 addition & 0 deletions docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ workspace root. `nullius paths` shows the active location.
| --- | --- |
| `workspaces/<name>/workspace.json` | Roots, label, opened time |
| `workspaces/<name>/jobs/<hash>.json` | Parse cache |
| `workspaces/<name>/jobs/counts.json` | Runs and checks of a closed workspace whose jobs ended |
| `workspaces/<name>/imported/` | Converted foreign roots |
| `workspaces/<name>/judgements/<job>/<trial>.json` | Judge records |

Expand Down
Loading