diff --git a/app/nullius/execution.py b/app/nullius/execution.py index eac5769b6..a0a6d557b 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -2384,13 +2384,15 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, dirs = parse.find_job_dirs(roots) jobs = workspace.load_jobs(ws, roots, ends) judged = [] - if final: # the workspace's records from before: those of its jobs alone copied in + # the workspace's records from before: those of its jobs alone copied in; one that cannot be read keeps its own + if final and workspace.readable(ws): done = judgements.adopt_owned(ws, dirs=set(dirs)) or set() judged = [d for d in judgements.job_dirs(ws.dir, [j.job_id for j in jobs]) if all(os.path.join(d, n) in done for n in os.listdir(d) if n.endswith(".json"))] - else: # else counted as they are + elif not final: # else counted as they are olds += [judgements.overlay(ws.dir, j) for j in jobs] - held.append({"ws": ws, "roots": roots, "jobs": dirs, "judged": judged}) + unread = final and not workspace.readable(ws) and bool(judgements.job_dirs(ws.dir, [j.job_id for j in jobs])) + held.append({"ws": ws, "roots": roots, "jobs": dirs, "judged": judged, "unread": unread}) uids = {j.uid: j.uid_source for j in (parse.parse_job(d, trials=False) for d in parse.find_job_dirs([os.path.join(path, "jobs")])) if j.uid} return {"name": name, "dir": path, "bytes": size_of(path), "host": host, "workspaces": held, "uids": uids, @@ -2398,24 +2400,26 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, "judgements": judgements.records_of(judgements.home(), uids, olds)} -def _judged_elsewhere(home: str, paths: list, uids: set) -> set: +def _judged_elsewhere(home: str, paths: list, uids: set) -> tuple: """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, or a - workspace, cannot be read, since who owns them is then unknown.""" + keep their judgements, and why when it is not a copy: 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, or a workspace, cannot be read, since who owns them is + then unknown, with what could not be read.""" try: - return _copies(home, paths, uids) - except OSError: - return set(uids) + return _copies(home, paths, uids), "" + except OSError as e: + return set(uids), f"{e.filename} cannot be read: {e.strerror}" if e.filename else str(e) 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.every(home): - if not all(os.path.isdir(r) for r in workspace.walked(ws)): - return set(uids) + for r in workspace.walked(ws): + if not os.path.isdir(r): + raise OSError(f"{r}, a root of workspace {ws.name}, cannot be found") 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"))] @@ -2427,14 +2431,23 @@ def deletion(names: List[str], home: str, root: Optional[str] = None, holding: O """What deleting the runs *names* of one launch removes: per run (``runs``) its folder and size, the host copy that is its own, and per workspace that holds it its roots, parsed jobs and judgement folders; the totals, and the - number of copies per host. ValueError when any of them is alive or is not - a run: nothing goes then. ``holding``: a run folder's ``workspace.holding``, + number of copies per host. ValueError when any of them is alive, is not + a run or is among a workspace's roots that are not all paths: nothing goes then. ``holding``: a run folder's ``workspace.holding``, when the caller has it already. Its judgement folders in the user's store (``judged``) are those of every job of the runs; ``delete`` decides which go once the runs went.""" - holding = holding or (lambda path: workspace.holding(home, path)) + holding, memo = holding or (lambda path: workspace.holding(home, path)), {} + + def held(path): + if path not in memo: + memo[path] = holding(path) + return memo[path] + for n in dict.fromkeys(names): # every run first: a refusal writes nothing + for ws, _ in held(run_folder(n, root)): + if not workspace.path_list(ws.roots): # its roots could not be written without the run's: nothing goes + raise ValueError(f"{n} is in workspace {ws.name}, whose roots are not all paths: repair its workspace.json") ends = run_ends() - runs = [_run_deletion(n, home, root, holding, ends, final) for n in dict.fromkeys(names)] + runs = [_run_deletion(n, home, root, held, ends, final) for n in dict.fromkeys(names)] copies: Dict[str, int] = {} for r in runs: if r["host"]: @@ -2547,8 +2560,13 @@ def _delete(names: List[str], home: str, root: Optional[str], copies, run: Optio gone["kept"].append(f"the copy of {r['name']} on {host.label} stays: " + redact.redact(out.strip()[-200:])) # a run that stayed, even in part, keeps its jobs' identities as they were read before the delete uids = {u for r in went for u in r["uids"]} - {u for r in gone["runs"] if r not in went for u in r["uids"]} + # a workspace that cannot be read keeps its records from before, as the user's store does its own then + whys = [f"workspace {w['ws'].name} cannot be read" for r in went for w in r["workspaces"] if w["unread"]] if uids and judgements.job_dirs(judgements.home(), sorted(uids)): - uids -= _judged_elsewhere(home, [r["dir"] for r in went], uids) + kept, why = _judged_elsewhere(home, [r["dir"] for r in went], uids) + uids -= kept + whys.append(why) for d in judgements.job_dirs(judgements.home(), sorted(uids)): judgements.remove(d) + gone["kept"] += [f"Judgements kept because {why}" for why in dict.fromkeys(whys) if why] return gone diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 440d7c880..9f7ea589a 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -291,8 +291,7 @@ def load(home_dir: str, name: str, *, strict: bool = False) -> Workspace | None: if strict and (ws.name != name 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))): + or not readable(ws)): raise ValueError("invalid workspace fields") return ws except (TypeError, ValueError) as error: @@ -313,6 +312,23 @@ def list_all(home_dir: str) -> list: return sorted(found, key=lambda w: w.opened, reverse=True) +UNREADABLE = "Unreadable: repair its workspace.json" + + +def _is_path(r) -> bool: + return isinstance(r, str) and r != "" and "\0" not in r + + +def path_list(rs) -> bool: + """Whether *rs*, a workspace's roots or job roots, is a list of paths.""" + return isinstance(rs, list) and all(map(_is_path, rs)) + + +def readable(ws: Workspace) -> bool: + """Whether *ws*'s roots and job roots are lists of paths: else what it holds is unknown.""" + return path_list(ws.roots) and path_list(ws.job_roots) + + 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, denied, roots that are no list of paths), @@ -328,7 +344,7 @@ def every(home_dir: str) -> list: if ws is None and _NAME.fullmatch(name): os.lstat(_path(home_dir, name)) # there, or not to be told: unread raise ValueError("unread") - if ws and not all(isinstance(rs, list) and all(isinstance(r, str) for r in rs) for rs in (ws.roots, ws.job_roots)): + if ws and not readable(ws): raise ValueError("invalid roots") except (FileNotFoundError, NotADirectoryError): continue @@ -345,9 +361,9 @@ def walked(ws: Workspace) -> list: def last_open(home_dir: str) -> Workspace | None: - """The workspace opened last, unless the user closed it.""" + """The workspace opened last, unless the user closed it or it cannot be read.""" last = next(iter(list_all(home_dir)), None) - return None if last is None or last.closed else last + return None if last is None or last.closed or not readable(last) else last def find_by_roots(home_dir: str, roots, besides: str = "") -> Workspace | None: @@ -410,6 +426,8 @@ def rename(home_dir: str, ws: Workspace, label: str) -> Workspace: now = _still(ws, load(home_dir, ws.name)) if now is None: return ws + if not readable(now): + raise ValueError(UNREADABLE) 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)) @@ -552,7 +570,9 @@ def holding_all(home_dir: str, folders) -> dict: inside = {f: os.path.join(os.path.realpath(f), "") for f in folders} found = {f: [] for f in folders} for ws in list_all(home_dir): - real = [(r, os.path.join(os.path.realpath(r), "")) for r in ws.roots] + # the paths of roots it cannot all read too: a holder known, whose Delete is refused (``execution``) + listed = [r for r in ws.roots if _is_path(r)] if isinstance(ws.roots, list) else [] + real = [(r, os.path.join(os.path.realpath(r), "")) for r in listed] for f, prefix in inside.items(): roots = [r for r, rr in real if rr.startswith(prefix)] if roots: @@ -562,11 +582,14 @@ 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*.""" - 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] + def drop_roots(now): # a field that is no list of paths stays as it is, to be repaired + if path_list(now.roots): + now.roots = [r for r in now.roots if r not in roots] + if path_list(now.job_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] + if path_list(ws.job_roots): + ws.job_roots = [r for r in ws.job_roots if r not in roots] def drop(index): # a root already gone from disk finds no job dirs: its entries go by where they were @@ -807,7 +830,11 @@ def _holds(ws: Workspace) -> Callable | None: now = None if now is None: return None - kept = walked(now) + if readable(now): + kept = walked(now) + else: # one that cannot all be read holds only what its paths name + listed = lambda rs: [r for r in rs if _is_path(r)] if isinstance(rs, list) else [] + kept = listed(now.roots) + [r for r in listed(now.job_roots) if _inside(r, now.imports_dir)] return lambda job_dir: _under(job_dir, kept) diff --git a/app/nullius/workspace_cli.py b/app/nullius/workspace_cli.py index 7b4b36b90..1bf75d5c5 100644 --- a/app/nullius/workspace_cli.py +++ b/app/nullius/workspace_cli.py @@ -47,13 +47,14 @@ def row(ws: workspace.Workspace) -> dict: """One workspace as the page's table shows it, plus the job ids its cache index names.""" - index = workspace.job_index(ws) + index, readable = workspace.job_index(ws), workspace.readable(ws) return { "name": ws.name, "label": ws.label, "dir": ws.dir, - "roots": list(ws.roots), - "job_roots": list(ws.job_roots), + "readable": readable, # else its roots are as its manifest holds them + "roots": list(ws.roots) if readable else ws.roots, + "job_roots": list(ws.job_roots) if readable else ws.job_roots, "n_cached": ws.n_cached, "jobs": [{"dir": job_dir, "job_id": entry.get("job_id"), "n_trials": entry.get("n_trials"), "dataset": entry.get("dataset"), "agent": entry.get("agent")} @@ -86,7 +87,9 @@ def _list(args) -> int: opened = (ws.opened or "")[:16].replace("T", " ") print(f"{ws.name:<{width}} {ws.label}") print(f"{'':<{width}} cached runs {r['n_cached']} · opened {opened or '—'}") - for root in workspace.walked(ws): + if not r["readable"]: + print(f"{'':<{width}} {workspace.UNREADABLE}") + for root in workspace.walked(ws) if r["readable"] else (): print(f"{'':<{width}} root {root}") for job in r["jobs"]: print(f"{'':<{width}} job {job['job_id']} ({job['n_trials']} trial(s))") diff --git a/app/templates/runs/start.html b/app/templates/runs/start.html index 405fbfa70..bae60d136 100644 --- a/app/templates/runs/start.html +++ b/app/templates/runs/start.html @@ -25,7 +25,7 @@
{{ unreadable }}
{% endif %}