diff --git a/app/nullius/execution.py b/app/nullius/execution.py index bc8a05888..831043d94 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -2037,8 +2037,8 @@ def _judged_elsewhere(home: str, paths: list, uids: set) -> set: """Which of the jobs *uids* of the run folders *paths*, deleted together, keep their judgements: those with another folder of the same identity outside them - a copy - under a root of any workspace or another run, read - afresh, never from a cache; all of them when one of those roots cannot be - read, since who owns them is then unknown.""" + afresh, never from a cache; all of them when one of those roots, or a + workspace, cannot be read, since who owns them is then unknown.""" try: return _copies(home, paths, uids) except OSError: @@ -2048,10 +2048,10 @@ def _judged_elsewhere(home: str, paths: list, uids: set) -> set: def _copies(home: str, paths: list, uids: set) -> set: outside = lambda d: all(os.path.commonpath([os.path.realpath(d), p]) != p for p in paths) roots = [] - for ws in workspace.list_all(home): - if not all(os.path.isdir(r) for r in ws.job_roots or ws.roots): + for ws in workspace.every(home): + if not all(os.path.isdir(r) for r in workspace.walked(ws)): return set(uids) - roots += ws.job_roots or ws.roots + roots += workspace.walked(ws) roots += [j for parent in {os.path.dirname(p) for p in paths} for e in os.scandir(parent) if e.is_dir(follow_symlinks=False) and e.path not in paths and os.path.isdir(j := os.path.join(e.path, "jobs"))] return {job_uid.strict(d) for d in parse.find_job_dirs(roots, strict=lambda name: True) if outside(d)} & uids diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 13bb08714..dd0810cf3 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -498,9 +498,10 @@ def owners(ws, into: Optional[str] = None, names=None) -> Optional[dict]: of its roots, or a folder in one that may be a job, cannot be read: its jobs, and so the owners, are unknown.""" from dataclasses import replace + from nullius import workspace from nullius.runs import parse, uid as job_uid into = into or home() - roots = ws.job_roots or ws.roots + roots = workspace.walked(ws) spelt = None if names is None else {s for n in names for s in _names(n)} mine = lambda name: spelt is None or not spelt.isdisjoint(_names(name)) if not all(os.path.isdir(r) for r in roots): diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index a66699646..258ec7dcf 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -2,11 +2,13 @@ A workspace gives the app's roots, and what it made from them, a name and a directory, so they survive a restart, so two sets of runs can be kept apart, -and so the expensive part — parsing a 375-trial job, converting a foreign -run tree — happens once per change rather than once per page. +and so the expensive part, parsing a 375-trial job, happens once per change +rather than once per page. - //workspace.json name, label, roots, created, opened, closed - //imported/ previously converted job directories + //workspace.json version, uid, name, label, roots, created, job_roots + //state.json opened, closed: an open rewrites this alone + //imported/ job directories converted before: ``job_roots`` + names those read still (``walked``) //jobs/.json a parsed Job, keyed by the job dir's signature //jobs/counts.json its runs and checks, while its jobs had all ended @@ -36,6 +38,7 @@ """ from __future__ import annotations +import contextlib import hashlib import json import os @@ -43,7 +46,8 @@ import random import re import threading -from dataclasses import asdict, dataclass, field, fields +import uuid +from dataclasses import dataclass, field, fields from datetime import datetime, timezone from typing import Callable @@ -97,8 +101,10 @@ class Workspace: created: str opened: str dir: str - job_roots: list = field(default_factory=list) # job directories the parser walks + job_roots: list = field(default_factory=list) # those of its imported/ it reads too (walked) + folder: tuple = () # its folder's device and inode when read; never stored closed: bool = False # closed by the user: a restart leaves it closed + uid: str = "" # made with it, never changed; none in one saved before @property def imports_dir(self) -> str: @@ -121,14 +127,110 @@ def _path(home_dir: str, name: str) -> str: return os.path.join(home_dir, name, "workspace.json") +RECORD_VERSION = 1 # bump when what workspace.json holds changes +_RECORD = ("uid", "name", "label", "roots", "created", "job_roots") +_STATE = ("opened", "closed") + + def save(ws: Workspace) -> None: + """*ws* written whole as it is held here, its state before its record: a record is + never there without the state that goes with it.""" + _write(ws, _STATE) + _write(ws, _RECORD) + + +def _write(ws: Workspace, keys) -> None: os.makedirs(ws.dir, exist_ok=True) - data = {k: v for k, v in asdict(ws).items() if k != "dir"} - ondisk.write_whole(os.path.join(ws.dir, "workspace.json"), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1)) + data = {k: getattr(ws, k) for k in keys} + if keys is _RECORD: + data = {"version": RECORD_VERSION, **data} + path = os.path.join(ws.dir, "workspace.json" if keys is _RECORD else "state.json") + ondisk.write_whole(path, lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1)) + + +def _locked(ws: Workspace): + return ondisk.locked(os.path.join(ws.dir, "workspace.json.lock")) + + +def _folder(ws_dir: str) -> tuple: + """A folder's device and inode: its own through a rename, no other folder's while it is there.""" + try: + found = os.stat(ws_dir) + except OSError: + return () + return found.st_dev, found.st_ino + + +def _still(ws: Workspace, now: Workspace | None) -> Workspace | None: + """*now*, read under *ws*'s name, when it is the workspace *ws* was read from: not one + made under that name since *ws* was renamed or deleted. By its uid; when neither was + saved with one, by its folder and created time.""" + if now is None: + return None + if ws.uid or now.uid: + return now if ws.uid == now.uid else None + return now if not ws.folder or (ws.folder, ws.created) == (now.folder, now.created) else None + + +@contextlib.contextmanager +def _current(ws: Workspace): + """*ws* as it is on disk now, under its lock, to change and write: of two writers at + once, each reads what the other wrote. None once the workspace is gone, renamed or + deleted: nothing here makes its folder again, nor changes another made under its name.""" + if not os.path.isdir(ws.dir): + yield None + return + with _locked(ws): + yield _still(ws, load(os.path.dirname(ws.dir), ws.name)) + + +def _change(ws: Workspace, change: Callable) -> None: + """``change`` made to *ws*'s record and saved, with its state: a record from before + ``state.json`` leaves its opened and closed there. *ws* takes the roots and label saved.""" + with _current(ws) as now: + if now is None: + return + change(now) + save(now) + ws.roots, ws.label = now.roots, now.label + + +def _set_state(ws: Workspace, **state) -> None: + """*state* written over *ws*'s own, the rest of it as it is on disk; *ws* takes both.""" + with _current(ws) as now: + if now is None: + return + for key, value in state.items(): + setattr(now, key, value) + _write(now, _STATE) + ws.opened, ws.closed = now.opened, now.closed + + +def add_roots(ws: Workspace, roots) -> None: + """*ws* with *roots* it does not hold yet.""" + def add(now): + now.roots = list(now.roots) + [r for r in roots if r not in now.roots] + _change(ws, add) + + +def _state(ws_dir: str) -> dict | None: + """``state.json``'s opened and closed; None when there is no file (a workspace saved + before it), ValueError when the file is not a state.""" + try: + with open(os.path.join(ws_dir, "state.json"), encoding="utf-8") as fh: + data = json.load(fh) + except FileNotFoundError: + return None + except OSError as error: + raise ValueError(str(error)) from error + if not isinstance(data, dict) or not isinstance(data.get("opened"), str) or not isinstance(data.get("closed"), bool): + raise ValueError("invalid workspace state") + return {k: data[k] for k in _STATE} def load(home_dir: str, name: str, *, strict: bool = False) -> Workspace | None: - """Read a workspace. Strict launch reads refuse a damaged existing destination.""" + """Read a workspace. Strict launch reads refuse a damaged existing destination. + A record of another version is not read, so never written over: only a launch says so.""" if not name or not _NAME.fullmatch(name): return None try: @@ -142,14 +244,31 @@ def load(home_dir: str, name: str, *, strict: bool = False) -> Workspace | None: if strict: raise ValueError("The launch workspace cannot be read. Repair it or choose another workspace.") from error return None - known = {f.name for f in fields(Workspace)} - {"dir"} + legacy = not isinstance(data, dict) or "version" not in data # from before state.json: opened and closed are in the record + if not legacy and data["version"] != RECORD_VERSION: + if strict: + raise ValueError(f"The launch workspace was saved as version {data['version']!r} and this Nullius reads version " + f"{RECORD_VERSION}. Upgrade Nullius or choose another workspace.") + return None + known = {f.name for f in fields(Workspace)} - {"dir", "folder"} + if not legacy: + known -= set(_STATE) + ws_dir = os.path.join(home_dir, name) + try: + state, lacks = _state(ws_dir), "" if legacy else "no" + except ValueError: + state, lacks = None, "an invalid" + if state is None and lacks: + if strict: + raise ValueError(f"The launch workspace has {lacks} state.json. Repair it or choose another workspace.") + state = {"opened": "", "closed": True} # unknown: never taken for the one left open try: if not isinstance(data, dict) or not data.get("name"): raise ValueError("missing workspace name") - ws = Workspace(dir=os.path.join(home_dir, name), - **{k: v for k, v in data.items() if k in known}) + record = {"opened": "", **{k: v for k, v in data.items() if k in known}, **(state or {})} + ws = Workspace(dir=ws_dir, folder=_folder(ws_dir), **record) if strict and (ws.name != name - or any(not isinstance(getattr(ws, k), str) for k in ("name", "label", "created", "opened")) + or any(not isinstance(getattr(ws, k), str) for k in ("uid", "name", "label", "created", "opened")) or not isinstance(ws.closed, bool) or any(not isinstance(roots, list) or any(not isinstance(r, str) for r in roots) for roots in (ws.roots, ws.job_roots))): @@ -173,6 +292,32 @@ def list_all(home_dir: str) -> list: return sorted(found, key=lambda w: w.opened, reverse=True) +def every(home_dir: str) -> list: + """Every workspace under *home_dir*, for a reader that must miss none: OSError while one + there cannot be read (another version, damaged), since what it holds is unknown.""" + try: + names = sorted(os.listdir(home_dir)) + except FileNotFoundError: + return [] + found = [] + for name in names: + try: + ws = load(home_dir, name) + except (TypeError, ValueError) as error: + raise OSError(f"workspace {name} cannot be read") from error + if ws is None and _NAME.fullmatch(name) and os.path.lexists(_path(home_dir, name)): + raise OSError(f"workspace {name} cannot be read") + found += [ws] if ws else [] + return found + + +def walked(ws: Workspace) -> list: + """The folders *ws*'s jobs are read from, open or closed: its roots, then the job roots + it kept in its own ``imported/``, converted before.""" + kept = [r for r in ws.job_roots if os.path.commonpath([os.path.abspath(r), ws.imports_dir]) == ws.imports_dir] + return list(dict.fromkeys([*ws.roots, *kept])) + + def last_open(home_dir: str) -> Workspace | None: """The workspace opened last, unless the user closed it.""" last = next(iter(list_all(home_dir)), None) @@ -201,15 +346,24 @@ def _free(name: str, taken) -> str: def create(home_dir: str, roots, label: str = "", *, opened: bool = True, exact: bool = False) -> Workspace: - name = label - if not exact: - taken = {ws.name for ws in list_all(home_dir)} - name = slug(label) - name = _free(name, taken) if name else random_name(taken) + name, taken = label, set() if exact else {ws.name for ws in list_all(home_dir)} + os.makedirs(home_dir, exist_ok=True) + while True: + if not exact: + name = slug(label) + name = _free(name, taken) if name else random_name(taken) + try: + os.mkdir(os.path.join(home_dir, name)) # the name is this workspace's from here: another create moves on + break + except FileExistsError: + if exact: + raise + taken.add(name) now = _now() - ws = Workspace(name=name, label=label.strip() or name, roots=list(roots), - created=now, opened=now if opened else "", closed=not opened, dir=os.path.join(home_dir, name)) + ws = Workspace(name=name, label=label.strip() or name, roots=list(roots), created=now, opened=now if opened else "", + closed=not opened, dir=os.path.join(home_dir, name), uid=uuid.uuid4().hex) save(ws) + ws.folder = _folder(ws.dir) # as load reads it return ws @@ -221,27 +375,36 @@ def rename(home_dir: str, ws: Workspace, label: str) -> Workspace: label with nothing to slug keeps the name it has. The roots it reads stay where they are.""" label = (label or "").strip() - if not label: + if not label or not os.path.isdir(ws.dir): return ws name = slug(label) - if name and name != ws.name: - # a directory there that holds no workspace - left behind, half made - is taken too - taken = {w.name for w in list_all(home_dir)} | set(os.listdir(home_dir)) - name = _free(name, taken - {ws.name}) - new_dir = os.path.join(home_dir, name) - os.rename(ws.dir, new_dir) - from nullius.judge import store - store.unmark(ws.dir, to=new_dir) - ws.name, ws.dir = name, new_dir - ws.label = label - save(ws) + with _locked(ws): # the lock moves with the folder + now = _still(ws, load(home_dir, ws.name)) + if now is None: + return ws + if name and name != ws.name: + # a directory there that holds no workspace - left behind, half made - is taken too + taken = {w.name for w in list_all(home_dir)} | set(os.listdir(home_dir)) + name = _free(name, taken - {ws.name}) + new_dir = os.path.join(home_dir, name) + os.rename(ws.dir, new_dir) + from nullius.judge import store + store.unmark(ws.dir, to=new_dir) + now.name, now.dir = name, new_dir + now.label = label + save(now) + ws.name, ws.dir, ws.label, ws.roots = now.name, now.dir, now.label, now.roots return ws def touch(ws: Workspace) -> None: - ws.opened = _now() - ws.closed = False - save(ws) + """*ws* opened now: its state alone is written, its record is left as it is.""" + _set_state(ws, opened=_now(), closed=False) + + +def close(ws: Workspace) -> None: + """*ws* closed by the user: a restart leaves it closed.""" + _set_state(ws, closed=True) def delete(home_dir: str, name: str) -> bool: @@ -346,9 +509,11 @@ def holding_all(home_dir: str, folders) -> dict: def forget(ws: Workspace, roots, job_dirs) -> None: """*ws* without *roots*, and without its parsed jobs of *job_dirs*.""" - ws.roots = [r for r in ws.roots if r not in roots] + def drop_roots(now): + now.roots = [r for r in now.roots if r not in roots] + now.job_roots = [r for r in now.job_roots if r not in roots] + _change(ws, drop_roots) ws.job_roots = [r for r in ws.job_roots if r not in roots] - save(ws) def drop(index): # a root already gone from disk finds no job dirs: its entries go by where they were @@ -577,17 +742,15 @@ def _merge_index(ws: Workspace, now: dict, before: dict, after: dict) -> None: def _holds(ws: Workspace) -> Callable | None: - """Whether *ws*, as its record is now, holds a job folder: one under a root, or under a - job root it kept in ``imported/``, as ``open_workspace`` reads them. None when the record - cannot be read.""" + """Whether *ws*, as its record is now, holds a job folder: one under a folder it reads + (``walked``). None when the record cannot be read.""" try: now = load(os.path.dirname(ws.dir), ws.name) except (TypeError, ValueError): now = None if now is None: return None - kept = [*now.roots, *(r for r in now.job_roots - if os.path.commonpath([os.path.abspath(r), now.imports_dir]) == now.imports_dir)] + kept = walked(now) return lambda job_dir: _under(job_dir, kept) diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index 84c1892f8..e5152794c 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -641,6 +641,7 @@ "closed", "created", "dir", + "folder", "imports_dir", "job_roots", "jobs_dir", @@ -648,7 +649,8 @@ "n_cached", "name", "opened", - "roots" + "roots", + "uid" ] } } diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index dfe30de8b..95a33cc75 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -96,6 +96,15 @@ def test_a_copy_elsewhere_or_a_root_that_cannot_be_read_keeps_the_judgements(sel execution.delete(["r3"], self.home, self.root) self.assertEqual(store.job_dirs(self.data, [uid]), []) + def test_a_workspace_this_nullius_cannot_read_keeps_the_judgements(self): + uid = self.judged(self.jobs, "job-a") + twin = os.path.join(self.tmp, "twin"); shutil.copytree(os.path.join(self.jobs, "job-a"), os.path.join(twin, "job-a")) + d = workspace.create(self.home, [twin], label="d") + path = os.path.join(d.dir, "workspace.json") + _write_json(path, dict(json.load(open(path)), version=workspace.RECORD_VERSION + 1)) # its roots unknown here + execution.delete(["r1"], self.home, self.root) + self.assertTrue(store.job_dirs(self.data, [uid])) + def test_a_copy_whose_config_cannot_be_read_keeps_the_judgements(self): cfg = os.path.join(self.jobs, "job-a", "config.json") _write_json(cfg, dict(json.load(open(cfg)), standard={"uuid": "11111111-2222-3333-4444-555555555555"})) diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index c8b4fece2..825db5f78 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -200,6 +200,104 @@ def test_an_unopened_workspace_is_remembered_only_after_it_is_opened(self): self.assertFalse(a.closed) self.assertEqual(workspace.last_open(self.home).name, a.name) + def test_the_record_holds_the_definition_and_an_open_leaves_it_alone(self): + a = workspace.create(self.home, ["/r/a"], label="a") + path = os.path.join(a.dir, "workspace.json") + with open(path, encoding="utf-8") as fh: + self.assertEqual(json.load(fh), {"version": workspace.RECORD_VERSION, "uid": a.uid, "name": "a", "label": "a", + "roots": ["/r/a"], "created": a.created, "job_roots": []}) + before = os.stat(path) + with patch.object(workspace, "_now", return_value="2999-01-01T00:00:00+00:00"): + workspace.touch(a) + workspace.close(a) + after = os.stat(path) + self.assertEqual((after.st_ino, after.st_mtime_ns), (before.st_ino, before.st_mtime_ns)) + again = workspace.load(self.home, "a") + self.assertEqual((again.opened, again.closed), ("2999-01-01T00:00:00+00:00", True)) + with open(os.path.join(a.dir, "state.json"), "w", encoding="utf-8") as fh: + fh.write("{broken") + self.assertTrue(workspace.load(self.home, "a").closed) # unknown is not open + self.assertRaisesRegex(ValueError, "invalid state.json", workspace.load, self.home, "a", strict=True) + os.remove(os.path.join(a.dir, "state.json")) + self.assertRaisesRegex(ValueError, "no state.json", workspace.load, self.home, "a", strict=True) + + def test_a_handle_read_earlier_changes_only_what_it_was_asked_to(self): + a = workspace.create(self.home, [], label="a") + old, other = workspace.load(self.home, "a"), workspace.load(self.home, "a") + with patch.object(workspace, "_now", return_value="2999-01-01T00:00:00+00:00"): + workspace.touch(a) + workspace.close(old) + self.assertEqual(workspace.load(self.home, "a").opened, "2999-01-01T00:00:00+00:00") + workspace.rename(self.home, a, "b") + workspace.close(old); workspace.touch(other) # the folder it knew is gone: not made again + self.assertEqual(os.listdir(self.home), ["b"]) + workspace.create(self.home, ["/r/new"], label="a") # another, under the name it knew + workspace.close(old); workspace.add_roots(other, ["/r/old"]); workspace.rename(self.home, old, "c") + new = workspace.load(self.home, "a") + self.assertEqual((new.closed, new.roots, sorted(os.listdir(self.home))), (False, ["/r/new"], ["a", "b"])) + workspace.delete(self.home, "a") + with patch.object(workspace, "_folder", return_value=new.folder), patch.object(workspace, "_now", return_value=new.created): + workspace.create(self.home, [], label="a") # made again in the same second, on the same inode + workspace.close(new) + new.uid = "" # one saved before it had a uid + workspace.close(new) + self.assertFalse(workspace.load(self.home, "a").closed) + + def test_two_creates_at_once_of_one_label_make_two_workspaces(self): + list_all = workspace.list_all + + def create_meanwhile(home_dir): # the other request, once this one read the names + taken = list_all(home_dir) + if raced.is_set(): + return taken + raced.set() + workspace.create(self.home, ["/r/b"], label="Experiment") + return taken + raced = threading.Event() + with patch.object(workspace, "list_all", side_effect=create_meanwhile): + a = workspace.create(self.home, ["/r/a"], label="Experiment") + self.assertEqual(sorted((w.name, w.roots) for w in workspace.list_all(self.home)), + [("experiment", ["/r/b"]), ("experiment-2", ["/r/a"])]) + self.assertEqual(a.name, "experiment-2") + + def test_a_record_of_another_version_is_not_read_nor_written_over(self): + a = workspace.create(self.home, ["/r/a"], label="a") + path = os.path.join(a.dir, "workspace.json") + later = {"version": workspace.RECORD_VERSION + 1, "name": "a", "label": "a", "roots": ["/r/a"], "created": "", "more": 1} + _write_json(path, later) + self.assertIsNone(workspace.load(self.home, "a")) + with self.assertRaisesRegex(ValueError, "version 2"): + workspace.load(self.home, "a", strict=True) + workspace.add_roots(a, ["/r/b"]); workspace.rename(self.home, a, "b") + with open(path, encoding="utf-8") as fh: + self.assertEqual(json.load(fh), later) + + def test_a_record_saved_before_its_version_opens_as_it_did(self): + converted = os.path.join(self.home, "old", "imported", "atif") + _write_json(os.path.join(self.home, "old", "workspace.json"), { + "name": "old", "label": "Old runs", "roots": ["/r/old"], "created": "2026-01-01T00:00:00+00:00", + "opened": "2026-02-01T00:00:00+00:00", "closed": False, "job_roots": ["/r/old", converted]}) + ws = workspace.load(self.home, "old", strict=True) + self.assertEqual((ws.label, ws.roots, ws.opened, ws.closed), ("Old runs", ["/r/old"], "2026-02-01T00:00:00+00:00", False)) + workspace.add_roots(ws, ["/r/more"]) # the first versioned record: its state goes to state.json + with open(os.path.join(ws.dir, "workspace.json"), encoding="utf-8") as fh: + record = json.load(fh) + self.assertNotIn("opened", record) + self.assertEqual(record["job_roots"], ["/r/old", converted]) # what was converted before stays read + self.assertEqual(workspace.walked(workspace.load(self.home, "old")), ["/r/old", "/r/more", converted]) + self.assertEqual(workspace.load(self.home, "old").opened, "2026-02-01T00:00:00+00:00") + self.assertEqual(workspace.last_open(self.home).name, "old") + workspace.touch(ws) + self.assertEqual(workspace.load(self.home, "old").opened, ws.opened) + + def test_a_root_added_and_another_removed_at_once_keep_both(self): + a = workspace.create(self.home, ["/r/a", "/r/b"], label="a") + one, two = workspace.load(self.home, "a"), workspace.load(self.home, "a") # two requests, each its own copy + workspace.add_roots(one, ["/r/c"]) + workspace.forget(two, ["/r/a"], []) + self.assertEqual(workspace.load(self.home, a.name).roots, ["/r/b", "/r/c"]) + self.assertEqual(two.roots, ["/r/b", "/r/c"]) + class Holding(unittest.TestCase): def test_each_folder_lists_the_workspaces_with_a_root_in_it(self): @@ -313,8 +411,7 @@ def test_the_cache_of_every_fixture_reads_back_equal(self): 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) + workspace._write_cache(self.ws, path, "sig", "head", job) # the module no longer has asdict to call 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): diff --git a/app/ui_tests/test_routes.py b/app/ui_tests/test_routes.py index 1c16d4d62..87bafa269 100644 --- a/app/ui_tests/test_routes.py +++ b/app/ui_tests/test_routes.py @@ -398,7 +398,7 @@ def test_foreign_workspace_evidence_does_not_change_active_workspace(self): self.assertIs(web.shared.STATE["workspace"], self.active) self.assertEqual(self.client.get("/trial/foreign-run/task-001/conversation").status_code, 404) self.assertEqual(self.client.get("/trial/active-run/task-001/conversation?workspace=missing").status_code, 404) - self.assertTrue(any(call.args[0] is self.foreign and call.args[1] == self.foreign.job_roots + self.assertTrue(any(call.args[0] is self.foreign and call.args[1] == workspace.walked(self.foreign) for call in self.load_jobs.call_args_list)) def test_job_score_mode_work_is_bounded_and_fresh_on_each_render(self): diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index b42809162..2a43be811 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -508,7 +508,7 @@ def test_a_failed_workspace_save_does_not_add_roots_in_memory(self): with patch.dict(execution.EXECUTIONS, clear=True), \ patch.object(execution.Plan, "check", return_value=""), \ patch.object(execution.Execution, "start") as start, \ - patch.object(workspace, "save", side_effect=OSError("disk failure")): + patch.object(workspace, "_write", side_effect=OSError("disk failure")): runs, problem, status = web.execute.begin([execution.Plan(name="launch", script="true")], "trials") self.assertEqual((runs, status), ([], 503), problem) start.assert_not_called() diff --git a/app/web/runs.py b/app/web/runs.py index f95452af5..4b4f27a77 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -95,14 +95,14 @@ def _grouped(ws=None): in its launch, and the jobs whose run is not known: two of those records name it, or two folders here have its id (the first is the one read). ``ws``: another workspace's, read from its cache without opening it.""" - jobs = shared._load_jobs() if ws is None else workspace.load_jobs(ws, ws.job_roots or ws.roots, shared.run_ends()) + jobs = shared._load_jobs() if ws is None else workspace.load_jobs(ws, workspace.walked(ws), shared.run_ends()) have, twice = {}, set() for j in jobs: if have.setdefault(j.job_id, j.dir) != j.dir and os.path.realpath(have[j.job_id]) != os.path.realpath(j.dir): twice.add(j.job_id) # The run records are the app's, not the workspace's: only those launched # into this workspace's roots, or with a job already written here, belong. - real = _real_roots(None if ws is None else list(ws.roots) + list(ws.job_roots)) + real = _real_roots(None if ws is None else workspace.walked(ws)) mine = [e for e in execution.EXECUTIONS.values() if _launched_here(e, have, real)] merged = launches.merged_sources(jobs) jobs = [j for j in jobs if j.job_id not in merged] diff --git a/app/web/shared.py b/app/web/shared.py index 4f402adb7..f86257367 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -4,7 +4,6 @@ import glob import hashlib import ipaddress -from dataclasses import replace import secrets import os from urllib.parse import urlsplit @@ -104,9 +103,8 @@ def dataset_title(name): # startup from CLI args / env; roots may be empty, in which case the UI asks. # `label` is what the header shows — roots can be an internal detail. # The open workspace, and what it resolved to. `roots` and `label` are what -# the user pointed at; `job_roots` is after the foreign trees among them were -# converted — the directories parse actually walks. Conversion happens when -# the workspace is opened or refreshed, not on every request. +# the user pointed at; `job_roots` the directories parse walks: those roots and +# the conversions the workspace kept (`workspace.walked`), set when it is opened. STATE: dict = {"roots": [], "label": "", "workspace": None, "job_roots": []} WS_HOME = workspace.home() @@ -165,18 +163,14 @@ def open_workspace(ws, refresh=False): set_source(ws.roots, ws.label) if refresh: workspace.clear_cache(ws) - # Previously converted jobs remain readable; no foreign roots are converted. - saved = [r for r in ws.job_roots if os.path.commonpath([os.path.abspath(r), ws.imports_dir]) == ws.imports_dir] - STATE["job_roots"] = list(dict.fromkeys([*ws.roots, *saved])) - ws.job_roots = list(STATE["job_roots"]) + STATE["job_roots"] = workspace.walked(ws) workspace.touch(ws) def close_workspace(save=True): ws = STATE["workspace"] if ws is not None and save: - ws.closed = True - workspace.save(ws) + workspace.close(ws) STATE.update({"workspace": None, "roots": [], "label": "", "job_roots": []}) @@ -192,9 +186,7 @@ def adopt_roots(roots, label="", new=False, into=""): if into and not (ws and ws.name == into): ws = workspace.load(WS_HOME, into) if ws and not new: - added = list(ws.roots) + [r for r in roots if r not in ws.roots] - workspace.save(replace(ws, roots=added)) - ws.roots = added + workspace.add_roots(ws, roots) if STATE["workspace"] is ws: open_workspace(ws) return ws @@ -263,7 +255,7 @@ def run_on_page(job_id, job, here=False): return runs[0] if len(runs) == 1 else None if ws is None: return run_for(job_id) - return run_for(job_id, roots={os.path.realpath(r) for r in ws.job_roots or ws.roots}) + return run_for(job_id, roots={os.path.realpath(r) for r in workspace.walked(ws)}) def ended_for(job_id, job=None): @@ -294,7 +286,7 @@ def _jobs_for_workspace(name=None): ws = workspace.load(WS_HOME, name) if ws is None: abort(404) - jobs = workspace.load_jobs(ws, ws.job_roots or ws.roots, run_ends()) + jobs = workspace.load_jobs(ws, workspace.walked(ws), run_ends()) memo[key] = jobs return jobs diff --git a/app/web/workspaces.py b/app/web/workspaces.py index ab5c3856f..91735cacb 100644 --- a/app/web/workspaces.py +++ b/app/web/workspaces.py @@ -68,7 +68,7 @@ def _counts(ws, recs, cat) -> dict: 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, cat) + key = None if is_open else (tuple(ws.roots), tuple(ws.job_roots), workspace.heads(workspace.walked(ws)), recs, cat) last = _COUNTS.get(ws.name) if key is not None and last and last[0] == key: return last[1] diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 26a6d5906..57c71869d 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -65,7 +65,8 @@ workspace root. `nullius paths` shows the active location. | Path | Holds | | --- | --- | -| `workspaces//workspace.json` | Roots, label, opened time | +| `workspaces//workspace.json` | Label and roots | +| `workspaces//state.json` | Opened time, closed | | `workspaces//jobs/.json` | Parse cache | | `workspaces//jobs/counts.json` | Runs and checks of a closed workspace whose jobs ended |