diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 5f2284f3c..484bc99e1 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -135,7 +135,7 @@ from datetime import datetime, timezone from typing import Callable, Dict, List, Optional -from nullius import hosts, ondisk, paths, prices as price_list, progress, providers, redact, secrets, settings, workspace +from nullius import hosts, identity, ondisk, paths, prices as price_list, progress, providers, redact, secrets, settings, trash, workspace from nullius.judge import store as judgements from nullius.runs import parse, uid as job_uid from nullius.harbor import source as harbor_source @@ -2746,3 +2746,95 @@ def _delete(names: List[str], home: str, root: Optional[str], copies, run: Optio judgements.remove(d) gone["kept"] += [f"Judgements kept because {why}" for why in dict.fromkeys(whys) if why] return gone + + +# --- cleaning a deleted run ---------------------------------------------------- +# Not called yet: Delete does not rename a run into the trash. + +def _run_payload(data: dict) -> bool: + """A run intent's payload. ``jobs``: per job folder, where it was in the run's own + folder, its ``uid`` and ``source``, or "" and ``pending``. ``workspaces``: per workspace + that held the run its ``identity`` and the ``roots`` and parsed ``jobs`` to forget, each + in the run's folder. ``host``: the label of the host that has a copy, or None. + ``kept``: what the steps report.""" + import uuid + payload, was = data["payload"], os.path.join(data["origin"]["runs_root"], data["name"]) + + def texts(value): + return isinstance(value, list) and all(isinstance(v, str) and v for v in value) + + def own(path): + return isinstance(path, str) and os.path.normpath(path) == path and path.startswith(was + os.sep) + + def identified(job): + if not isinstance(job, dict) or set(job) != {"uid", "source"} or job["uid"] == "": + return job == {"uid": "", "source": "pending"} + return job["source"] in ("declared", "derived") and isinstance(job["uid"], str) and str(uuid.UUID(job["uid"])) == job["uid"] + try: + return (set(payload) - {"kept"} == {"jobs", "workspaces", "host"} and isinstance(payload["jobs"], dict) + and all(own(d) and identified(j) for d, j in payload["jobs"].items()) + and isinstance(payload["workspaces"], list) + and all(set(w) == {"identity", "roots", "jobs"} and identity.valid_workspace(w["identity"]) + and texts(w["roots"]) and texts(w["jobs"]) and all(map(own, w["roots"])) and set(w["jobs"]) <= set(payload["jobs"]) + for w in payload["workspaces"]) + and (payload["host"] is None or isinstance(payload["host"], str) and bool(payload["host"])) + and texts(payload.get("kept", []))) + except (AttributeError, TypeError, ValueError): + return False + + +def _held_workspace(folder: str): + """The workspace in *folder*, read whole or not at all: Pending for one damaged in any + part, which is never written again from what could be read of it.""" + try: + ws = workspace.load(os.path.dirname(folder), os.path.basename(folder), strict=True) + except (TypeError, ValueError): + ws = None + if ws is None: + raise trash.Pending(f"workspace {os.path.basename(folder)} cannot be read") + return ws + + +def _detach(path: str, data: dict, env) -> None: + """Every workspace that held the run, found by its identity, without the run's roots + and parsed jobs, under the profile lock, then read back. One deleted since held them + no more. First, with nothing held, each job in the entry is a folder and the one the + intent names, by identity and source read once. Pending while that, a workspace or its index cannot be told + or read, or while a root is there again or cannot be told gone: a run made under the + name since is not this one.""" + was = os.path.join(data["origin"]["runs_root"], data["name"]) + for folder, job in data["payload"]["jobs"].items(): + there = os.path.join(path, os.path.relpath(folder, was)) + try: + found = stat.S_ISDIR(os.lstat(there).st_mode) and job_uid.strict_of(there) + except (AttributeError, TypeError, FileNotFoundError, NotADirectoryError): + found = None # not there, or of a shape nothing is told from + if found != (job["uid"], job["source"]): + raise trash.Pending(f"{there} is not the job its intent names") + with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): + for held in data["payload"]["workspaces"]: + for folder in workspace.located(held["identity"], env): + ws, back = _held_workspace(folder), [r for r in held["roots"] if trash.there(r)] + if back: + raise trash.Pending(f"{back[0]} is there again: workspace {ws.name} keeps its roots") + workspace.forget(ws, held["roots"], held["jobs"], held=True) + now = _held_workspace(folder) + if set(held["roots"]) & {*now.roots, *now.job_roots} or set(held["jobs"]) & set(workspace.job_index(now, strict=True)): + raise trash.Pending(f"workspace {ws.name} still holds it") + + +def _judgements(path: str, data: dict, env) -> list: + """The judgements of the run's jobs, in the user's store and in the workspaces that kept + some before, stay where they are, and that is reported: nothing here proves yet that + no copy of a job is left.""" + return [workspace.UNSUPPORTED] + + +def _host_copy(path: str, data: dict, env) -> None: + """A copy on a host is never removed from here: the entry keeps its intent until the user says it is handled.""" + if data["payload"]["host"]: + raise trash.Pending(f"The copy of {data['name']} on {data['payload']['host']} stays: remove it there.") + + +TRASHED = trash.Handler("run", RECORD, identity.run, identity.same_run, _run_payload, + (("detach", _detach), ("judgements", _judgements)), (("host", _host_copy),)) diff --git a/app/nullius/identity.py b/app/nullius/identity.py new file mode 100644 index 000000000..edc7ca7be --- /dev/null +++ b/app/nullius/identity.py @@ -0,0 +1,183 @@ +"""Who is who on disk: the profile an intent was written under, the profile a workspaces +folder belongs to, a workspace, a run. An unprovable match is no match. + +A profile is its data directory's path, device and inode, all three. One whose data +directory changed any of them (moved, copied, restored from a backup elsewhere or into a +folder made again) is another profile: it owns no workspaces folder marked before and +inherits no pending deletion. One restored in place, all three kept, is the same. The data +directory and the workspaces folder are made before the first claim; nothing here makes them. +""" +from __future__ import annotations + +import hashlib +import json +import math +import os +import uuid + +from nullius import ondisk, paths + +OWNER = "._owner.json" +OWNER_VERSION = 1 + + +class NotOwner(ValueError): + """A workspaces folder that another profile owns, or whose owner cannot be read.""" + + +def _int(value) -> bool: + return type(value) is int # never ``true`` for 1 + + +def _text(value) -> bool: + return isinstance(value, str) and bool(value) + + +def _finite(value) -> bool: + """A number a time can be: no infinity, no integer past what a float holds.""" + try: + return type(value) in (int, float) and math.isfinite(value) + except OverflowError: + return False + + +def _profile(value) -> bool: + return (isinstance(value, dict) and set(value) == {"path", "device", "inode"} and _text(value["path"]) + and _int(value["device"]) and _int(value["inode"])) + + +def origin(env=None) -> dict: + """The profile and roots this process writes under, as every intent records them.""" + data = os.path.realpath(paths.data_dir(env)) + found = os.stat(data) + return {"data_dir": {"path": data, "device": found.st_dev, "inode": found.st_ino}, + "workspaces_root": os.path.realpath(paths.workspaces_dir(env)), "runs_root": os.path.realpath(paths.runs_dir(env))} + + +def valid_origin(value) -> bool: + return (isinstance(value, dict) and set(value) == {"data_dir", "workspaces_root", "runs_root"} and _profile(value["data_dir"]) + and _text(value["workspaces_root"]) and _text(value["runs_root"])) + + +def same_origin(recorded, env=None) -> bool: + """*recorded* is this process's own profile and roots: else it was written under another profile.""" + try: + return valid_origin(recorded) and recorded == origin(env) + except OSError: + return False + + +def own(root, env=None) -> None: + """*root* is this profile's workspaces folder: from now on when no profile had it, since + of two taking it at once the link makes one the owner. ``NotOwner`` names another's.""" + mine, record = origin(env)["data_dir"], os.path.join(root, OWNER) + if not os.path.lexists(record): + part = os.path.join(root, f".{uuid.uuid4().hex}.part") + try: + with open(os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as f: + os.fchmod(f.fileno(), 0o600) # its owner reads it back whatever the umask + json.dump({"version": OWNER_VERSION, "data_dir": mine}, f) + os.link(part, record) # made whole or not at all; never over another's + except FileExistsError: + pass + finally: + if os.path.lexists(part): + os.unlink(part) + try: + data = ondisk.read_record(record) + if not (set(data) == {"version", "data_dir"} and _int(data["version"]) and data["version"] == OWNER_VERSION and _profile(data["data_dir"])): + raise ValueError("not an owner record this Nullius reads") + except (OSError, ValueError) as error: + raise NotOwner(f"The owner of this workspaces folder cannot be read: {record}") from error + if data["data_dir"] != mine: + raise NotOwner(f"This workspaces folder belongs to the profile at {data['data_dir']['path']}.") + + +def _held(folder, read): + """``read`` of *folder* through one descriptor, a path's opened here, itself no link + (its parents may be: a configured root is): None when it cannot be.""" + if isinstance(folder, int): + return read(folder) + folder = os.fspath(folder) + while folder.rstrip("/").endswith("/.") or len(folder) > 1 and folder.endswith("/"): + folder = folder.rstrip("/").removesuffix("/.") or "/" # the same folder, spelt so that a link is followed: ``..`` stays + try: + fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + except OSError: + return None + try: + return read(fd) + finally: + os.close(fd) + + +def _record(fd: int, name: str): + """The folder's own ``fstat`` and the object in its *name*, both through *fd*: a folder + swapped meanwhile cannot lend its record. None when either cannot be read.""" + try: + return os.fstat(fd), ondisk.read_record(name, dir_fd=fd) + except (OSError, ValueError): + return None + + +def workspace(folder) -> dict | None: + """The identity of the workspace in *folder*, a path or a directory descriptor its + caller holds and goes on reading through: ``uid`` (empty in one saved before it had + one), folder ``device`` and ``inode``, ``created``. None when it cannot be proved, or + its record is of a version ``workspace`` does not read.""" + from nullius import workspace as records # where it is imported from, in time + def read(fd): + found = _record(fd, "workspace.json") + if found is None or "version" in found[1] and not (_int(found[1]["version"]) and found[1]["version"] == records.RECORD_VERSION): + return None # one from before versions has none + value = {"uid": found[1].get("uid", ""), "device": found[0].st_dev, "inode": found[0].st_ino, "created": found[1].get("created", "")} + return value if valid_workspace(value) else None + return _held(folder, read) + + +def valid_workspace(value) -> bool: + """With no UID, a created time: one with neither has nothing to be matched by.""" + return (isinstance(value, dict) and set(value) == {"uid", "device", "inode", "created"} and isinstance(value["uid"], str) + and isinstance(value["created"], str) and bool(value["uid"] or value["created"]) and _int(value["device"]) and _int(value["inode"])) + + +def _proof(value: dict) -> list: + """What must match: with a UID, it and the folder; without, the folder and ``created``.""" + return [value["uid"], value["device"], value["inode"]] if value["uid"] else ["", value["device"], value["inode"], value["created"]] + + +def digest(value: dict) -> str: + """One opaque value for a workspace identity, equal exactly when two are the same workspace.""" + return hashlib.sha256(json.dumps(_proof(value)).encode()).hexdigest() + + +def same_workspace(a, b) -> bool: + return valid_workspace(a) and valid_workspace(b) and _proof(a) == _proof(b) + + +def run(folder) -> dict | None: + """What proves the run in *folder*, a path or a held directory descriptor: its + ``generation``; only for one saved without that field, ``id``, ``started`` and the + folder's ``device`` and ``inode`` together. None when it cannot be proved.""" + def read(fd): + found = _record(fd, "run.json") + if found is None: + return None + value = {"generation": found[1]["generation"]} if "generation" in found[1] else { + "id": found[1].get("id"), "started": found[1].get("started"), "device": found[0].st_dev, "inode": found[0].st_ino} + return value if valid_run(value) else None + return _held(folder, read) + + +def valid_run(value) -> bool: + if not isinstance(value, dict): + return False + if "generation" in value: + return set(value) == {"generation"} and _text(value["generation"]) + return (set(value) == {"id", "started", "device", "inode"} and _text(value["id"]) + and _finite(value["started"]) and _int(value["device"]) and _int(value["inode"])) + + +def same_run(a, b) -> bool: + """A run id alone proves nothing.""" + return valid_run(a) and valid_run(b) and a == b diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py index 26b15d07b..26ed748de 100644 --- a/app/nullius/ondisk.py +++ b/app/nullius/ondisk.py @@ -1,14 +1,17 @@ -"""A file written whole, a lock, a digest.""" +"""A file written whole, a record read, a lock, a digest.""" from __future__ import annotations import contextlib import errno import hashlib +import json import os import stat import time import uuid +WAIT = 1.0 # seconds one foreground sequence of locks waits, all of them together + # a handle that searches a folder without reading it: a folder its writer cannot list (0300) is written all the same _SEARCH = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0) or os.O_RDONLY @@ -58,16 +61,65 @@ def write_whole(path, data, mode=None) -> None: os.close(folder) +def _regular(path, dir_fd=None) -> int: + """*path* open to read, when it is a regular file: no link followed, and nothing waited + for, so a FIFO put there is refused instead of read.""" + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=dir_fd) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(errno.EINVAL, "not a regular file", os.fspath(path)) + return fd + + +def _once(pairs) -> dict: + found = dict(pairs) + if len(found) != len(pairs): + raise ValueError("a key given twice") + return found + + +def record(raw) -> dict: + """The JSON object *raw* spells; ``ValueError`` when it is not one object, names a + key twice or nests too deep to read.""" + try: + data = json.loads(raw, object_pairs_hook=_once) + except RecursionError as error: + raise ValueError("nested too deep") from error + if not isinstance(data, dict): + raise ValueError("not an object") + return data + + +def read_record(path, dir_fd=None) -> dict: + """``record`` of the regular file *path*, under *dir_fd* when given; ``OSError`` when + it cannot be opened or is not one.""" + with os.fdopen(_regular(path, dir_fd), "rb") as f: + return record(f.read()) + + +class Busy(TimeoutError): + """A lock still held by another at the deadline.""" + + +def deadline(seconds=WAIT) -> float: + """The monotonic time by which a sequence of locks is had, shared by all of them.""" + return time.monotonic() + seconds + + FIRST_WAIT = 1.0 # seconds an opener waits for a lock file made at this moment by another to get its mode -def _lock_file(path) -> int: +def _lock_file(path, deadline=None) -> int: """*path* open to write, as a lock wants it (NFS locks need a writable descriptor): a regular file, no link followed, never replaced nor removed. Made when missing, owner read and write whatever the umask; one of - this user's left without owner write (its maker stopped before setting its mode) gets it back, in place; - another refusal is tried again for a moment.""" + this user's left without owner write (its maker stopped before setting its mode) gets it back, in place, + once; another refusal is tried again for a moment, no later than *deadline*.""" until = time.monotonic() + FIRST_WAIT + until, repaired, again = until if deadline is None else min(until, deadline), False, False while True: + if again and deadline is not None and time.monotonic() >= deadline: # before each retry: never had late + raise Busy(path) + again = True try: fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) made = True @@ -78,12 +130,15 @@ def _lock_file(path) -> int: continue # gone since: made again except PermissionError: st = os.lstat(path) - if stat.S_ISREG(st.st_mode) and st.st_uid == os.geteuid() and not st.st_mode & 0o200: + if not repaired and stat.S_ISREG(st.st_mode) and st.st_uid == os.geteuid() and not st.st_mode & 0o200: os.chmod(path, stat.S_IMODE(st.st_mode) | 0o200, follow_symlinks=False) + repaired, again = True, False # no wait in it: a caller with one try has it too continue if time.monotonic() >= until: + if deadline is not None and until == deadline: + raise Busy(path) from None raise - time.sleep(0.005) + time.sleep(max(0, min(0.005, until - time.monotonic()))) continue made = False try: @@ -99,13 +154,29 @@ def _lock_file(path) -> int: @contextlib.contextmanager -def locked(path): +def locked(path, deadline=None): """One holder of ``path`` at a time, across processes and threads. The file holds - nothing and is never a link or a special file.""" + nothing and is never a link or a special file. + + Without ``deadline`` it waits. With one, a monotonic time, it raises ``Busy`` once + that passes; one already past tries once. Locks nested under one deadline share + its wait, and the one that fails releases those taken before it.""" import fcntl # POSIX only: imported where the lock is taken - fd = _lock_file(os.fspath(path)) + path = os.fspath(path) + fd = _lock_file(path, deadline) try: - fcntl.flock(fd, fcntl.LOCK_EX) + if deadline is None: + fcntl.flock(fd, fcntl.LOCK_EX) + else: + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + pass + time.sleep(max(0, min(deadline - time.monotonic(), 0.01))) + if time.monotonic() >= deadline: # checked before each retry: a late waiter never takes it + raise Busy(path) try: yield finally: diff --git a/app/nullius/paths.py b/app/nullius/paths.py index 4cd3d4890..a81c7d5af 100644 --- a/app/nullius/paths.py +++ b/app/nullius/paths.py @@ -57,6 +57,11 @@ def own_prices_file(env=None) -> str: return f"{root}-own{ext}" +def profile_lock(env=None) -> str: + """The profile's one lock, whatever ``WORKSPACES_DIR`` and ``RUNS_DIR`` say. Permanent: never removed.""" + return os.path.join(data_dir(env), "._home.lock") + + def catalogue_dir(env=None) -> str: env = os.environ if env is None else env return env.get("NULLIUS_CATALOGUE") or os.path.join(data_dir(env), "catalogue") diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index 811c26d5c..ffb5ee56e 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -117,10 +117,15 @@ def strict(job_dir: str) -> str: """The job's uid (`of`) from its files read strictly: OSError when one that is there cannot be read, so a caller that must know who owns a judgement (a delete) is told the owner is unknown, never another uid. The trials are listed strictly too.""" + return strict_of(job_dir)[0] + + +def strict_of(job_dir: str) -> tuple: + """``(uid, source)`` (`of`), both from the one strict read `strict` describes.""" cfg, res = _strict_json(os.path.join(job_dir, "config.json")), _strict_json(os.path.join(job_dir, "result.json")) if not _declared(cfg) and not res.get("started_at") and not isinstance(cfg.get("harness"), str): searched(job_dir) # the trials `_has_trial` looks for, each one strictly - return of(job_dir, cfg, res)[0] + return of(job_dir, cfg, res) def searched(folder: str) -> None: diff --git a/app/nullius/trash.py b/app/nullius/trash.py new file mode 100644 index 000000000..669331f68 --- /dev/null +++ b/app/nullius/trash.py @@ -0,0 +1,354 @@ +"""The trash of the configured runs and workspaces roots, ``/.trash//./``: +where an entry goes, what keeps it out of discovery, the intent it carries, one collector +per kind, and the loop that cleans its entries step by step (``collect``). Not called yet: +nothing is renamed into the trash. + +An intent is acted on only under the profile and roots it was written under +(``identity``): a profile whose data directory changed path, device or inode, moved, copied +or restored elsewhere, does not inherit pending deletions, which stay, reported as written +under another profile. +""" +from __future__ import annotations + +import json +import os +import re +import shutil +import stat +import time +import uuid +from dataclasses import dataclass +from datetime import datetime +from typing import Callable + +from nullius import identity, ondisk, paths + +KINDS = ("run", "workspace") +VERSION = 1 +INTENT = "intent.json" +STAMP = "%Y-%m-%dT%H:%M:%SZ" # UTC +_ENTRY = re.compile(r"(?P.+)\.(?P[0-9a-f]{32})", re.S) # the token follows the last dot: a dotted name parses +_FIELDS = {"version", "kind", "token", "name", "written", "origin", "subject", "steps", "pending", "payload"} + +# what ``read`` finds; only ``VALID`` may be acted on, only ``EMPTY`` removed +VALID, EMPTY, UNRECOGNISED, UNREADABLE, MISSING, DAMAGED, FUTURE, FOREIGN = ( + "valid", "empty", "unrecognised", "unreadable", "no intent", "damaged", "written by a later Nullius", "written under another profile") + + +class Refused(ValueError): + """A kind, name, trash folder or destination that is not safe to use. Nothing was touched.""" + + +class Invalid(ValueError): + """An intent that must not be acted on; its message is one of the states above.""" + + +def token() -> str: + return uuid.uuid4().hex + + +def _component(text) -> bool: + return isinstance(text, str) and text not in ("", ".", "..") and not any(c in text for c in ("/", os.sep, "\0")) + + +def parse(entry): + """``(name, token)`` of an entry's folder name, or None when it is not one: a single + path component, as its name is. The one check of a name and token, whoever asks.""" + found = _ENTRY.fullmatch(entry) if _component(entry) else None + return (found["name"], found["token"]) if found and _component(found["name"]) else None + + +def _named(name, token) -> bool: + return isinstance(name, str) and isinstance(token, str) and parse(f"{name}.{token}") == (name, token) + + +def root(kind: str, env=None) -> str: + """The configured root *kind* is trashed under, resolved: never a caller's own choice.""" + if kind not in KINDS: + raise Refused(f"{kind!r} is not a kind of trash") + return os.path.realpath(paths.runs_dir(env) if kind == "run" else paths.workspaces_dir(env)) + + +def folder(kind: str, make: bool = False, env=None) -> str: + """The folder of *kind*'s entries, once it and ``.trash`` are real directories (no + link) on their root's device, ours, mode 0700. ``FileNotFoundError`` when there is + none and *make* is not asked.""" + path = root(kind, env) + device = os.stat(path).st_dev + for part in (".trash", kind): + path = os.path.join(path, part) + if make: + try: + os.mkdir(path, 0o700) + os.chmod(path, 0o700) # the umask may have taken bits off + except FileExistsError: + pass + found = os.lstat(path) + wrong = ("is not a real folder" if not stat.S_ISDIR(found.st_mode) else "is on another device" if found.st_dev != device + else "belongs to another user" if found.st_uid != os.geteuid() else "is not mode 0700" if stat.S_IMODE(found.st_mode) != 0o700 else "") + if wrong: + raise Refused(f"{path} {wrong}") + return path + + +def destination(kind: str, name: str, token: str, env=None) -> str: + """Where *name* goes when trashed under *token*, its folders made. One that exists refuses.""" + if not _named(name, token): + raise Refused(f"{name!r} with {token!r} names no trash entry") + path = os.path.join(folder(kind, make=True, env=env), f"{name}.{token}") + if os.path.lexists(path): + raise Refused(f"{path} exists") + return path + + +def in_trash(path, env=None) -> bool: + """*path* leads to, or into, the trash of a configured root, however it is spelt: what + discovery leaves out. Links are resolved as they are met, never after ``..`` is + folded away; a linked ``.trash`` is left out with what it leads to. A ``.trash`` + anywhere else is read.""" + reached, trashes = os.path.realpath(path), set() + for kind in KINDS: + trash = os.path.join(root(kind, env), ".trash") + trashes |= {trash, os.path.realpath(trash)} + return any(os.path.commonpath([reached, trash]) == trash for trash in trashes) + + +def collector(kind: str, env=None): + """The one collector of *kind*, never waited for: ``ondisk.Busy`` when cleanup is + running elsewhere.""" + return ondisk.locked(os.path.join(folder(kind, env=env), LOCK), deadline=time.monotonic()) + + +def intent(kind: str, name: str, token: str, subject: dict, payload: dict | None = None, env=None) -> dict: + """The envelope written as ``intent.json`` in the live folder before its rename; + ``Invalid`` for one that would not be read back.""" + return validate({"version": VERSION, "kind": kind, "token": token, "name": name, "written": time.strftime(STAMP, time.gmtime()), + "origin": identity.origin(env), "subject": subject, "steps": {}, "pending": None, + "payload": {} if payload is None else payload}, kind, name, token, env) + + +def _stamp(value) -> bool: + """*value* is a time exactly as it is written here.""" + try: + return isinstance(value, str) and datetime.strptime(value, STAMP).strftime(STAMP) == value + except ValueError: + return False + + +def _written(data) -> bool: + """*data* is what reading it back from its file gives: no key that becomes another's, nothing JSON does not hold.""" + try: + return ondisk.record(json.dumps(data, allow_nan=False)) == data + except (TypeError, ValueError, RecursionError): + return False + + +def validate(data, kind: str, name: str, token: str, env=None) -> dict: + """*data* when it is the intent of this entry, written under this profile and roots; + else ``Invalid``. The subject is the kind handler's to check against the disk, as + are its own steps and payload.""" + if not isinstance(data, dict) or type(data.get("version")) is not int: + raise Invalid(DAMAGED) + if data["version"] > VERSION: + raise Invalid(FUTURE) + subject = identity.valid_workspace if kind == "workspace" else identity.valid_run + if not (data["version"] == VERSION and set(data) == _FIELDS and kind in KINDS and _named(name, token) + and (data["kind"], data["name"], data["token"]) == (kind, name, token) and _stamp(data["written"]) + and identity.valid_origin(data["origin"]) and subject(data["subject"]) + and isinstance(data["steps"], dict) and all(isinstance(k, str) and _stamp(v) for k, v in data["steps"].items()) + and (data["pending"] is None or isinstance(data["pending"], dict) and set(data["pending"]) == {"step", "reason", "at"} + and isinstance(data["pending"]["step"], str) and isinstance(data["pending"]["reason"], str) and _stamp(data["pending"]["at"])) + and isinstance(data["payload"], dict) and _written(data)): + raise Invalid(DAMAGED) + if not identity.same_origin(data["origin"], env): + raise Invalid(FOREIGN) + return data + + +def read(kind: str, entry: str, env=None) -> tuple: + """``(state, intent)`` of one entry of the configured root, its contents untouched; the + intent only when ``VALID``. ``EMPTY`` is a recognised entry seen to hold nothing; + one that cannot be listed, or whose intent is no regular file, is ``UNREADABLE``.""" + parsed = parse(entry) + if parsed is None: + return UNRECOGNISED, None + try: + fd = os.open(os.path.join(folder(kind, env=env), entry), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError: + return UNREADABLE, None + try: + names = os.listdir(fd) + if INTENT not in names: + return (MISSING if names else EMPTY), None + data = ondisk.read_record(INTENT, dir_fd=fd) + except OSError: + return UNREADABLE, None + except ValueError: + return DAMAGED, None + finally: + os.close(fd) + try: + return VALID, validate(data, kind, *parsed, env=env) + except Invalid as error: + return str(error), None + + +# --- cleaning entries ---------------------------------------------------------- + +LOCK = ".collector.lock" +BUSY = "Workspace storage is busy" +UNPROVED = "cannot be proved to be what its intent names" +_PART = re.compile(r"\.[0-9a-f]{32}\.part") # what a write of the intent leaves when it is killed (``ondisk.write_whole``) + + +class Pending(Exception): + """A step that cannot be done, or read back as done, now: why. Its entry stays as it is.""" + + +@dataclass(frozen=True) +class Handler: + """How entries of one kind are cleaned. Each of ``steps``, ``(name, step)`` in order, is + called with the entry's folder, its intent and the environment: it returns once what it + did is read back as done, with the lines to report about what it kept, or raises + ``Pending`` or ``OSError``. It may be run again after a kill, so does again only what is + not done. Then the entry's bytes go, ``record`` last, unless ``guard`` raises ``Pending`` + for what they still hold; ``after`` are steps left to the user.""" + kind: str + record: str # the file that proves the subject + subject: Callable # the identity read from an entry's folder + same: Callable + payload: Callable # whether an intent's payload is one its steps read, every path in it its subject's + steps: tuple + after: tuple = () + guard: Callable = lambda path, data, env: None + + +def _now() -> str: + return time.strftime(STAMP, time.gmtime()) + + +def there(path) -> bool: + """*path* is there; False only when it is seen not to be. OSError when that cannot be + told: one that cannot be reached is not one that is gone.""" + try: + os.lstat(path) + except (FileNotFoundError, NotADirectoryError): + return False + return True + + +def _write(kind: str, entry: str, data: dict, env) -> dict: + """*data* as the entry's intent, once it is read back as written.""" + ondisk.write_whole(os.path.join(folder(kind, env=env), entry, INTENT), json.dumps(data), mode=0o600) + if read(kind, entry, env) != (VALID, data): + raise Pending("its intent is not read back as written") + return data + + +def _rest(path: str) -> list: + return [n for n in os.listdir(path) if n != INTENT] + + +def _empty(path: str, last: str) -> None: + """Everything in the entry but its intent removed, *last* last: a removal stopped part + way leaves what proves whose bytes they are.""" + for name in sorted(_rest(path), key=lambda n: n == last): + item = os.path.join(path, name) + if os.path.isdir(item) and not os.path.islink(item): + shutil.rmtree(item) + else: + os.unlink(item) + if _rest(path): + raise Pending("some of its files are still there") + + +def _ordered(handler: Handler, data: dict) -> bool: + """The steps recorded are the handler's first ones, none skipped: a record of a later + step alone would let the earlier ones never run.""" + names = [name for name, _ in handler.steps] + ["bytes"] + [name for name, _ in handler.after] + return set(data["steps"]) == set(names[:len(data["steps"])]) + + +def _parts(path: str) -> bool: + """The entry holds nothing but its intent and the regular files a killed write of it left.""" + return all(_PART.fullmatch(n) and stat.S_ISREG(os.lstat(os.path.join(path, n)).st_mode) for n in _rest(path)) + + +def _proved(handler: Handler, path: str, data: dict) -> bool: + """The entry is the subject its intent names, its bytes not recorded as gone; or holds + nothing but that intent and what a killed write of it left, every step before the + bytes recorded: only a removal of its bytes, stopped or done, leaves that.""" + found = handler.subject(path) + if not there(os.path.join(path, handler.record)): + return found is None and all(name in data["steps"] for name, _ in handler.steps) and _parts(path) + return found is not None and handler.same(found, data["subject"]) and "bytes" not in data["steps"] + + +def _clean(handler: Handler, entry: str, data: dict, env) -> dict: + path, step, kept = os.path.join(folder(handler.kind, env=env), entry), "", list(data["payload"].get("kept") or ()) + try: + def remove(path, data, env): + handler.guard(path, data, env) + _empty(path, handler.record) + for step, act in (*handler.steps, ("bytes", remove), *handler.after): + if step in data["steps"]: + continue + kept += act(path, data, env) or () + data = _write(handler.kind, entry, {**data, "steps": {**data["steps"], step: _now()}, "pending": None, + "payload": {**data["payload"], **({"kept": kept} if kept else {})}}, env) + step = "bytes" + if not _parts(path): # its bytes recorded as gone: nothing else is this cleanup's to remove + raise Pending("it holds files again") + for name in _rest(path): # a killed write of the intent leaves a part + os.unlink(os.path.join(path, name)) + os.unlink(os.path.join(path, INTENT)) # last + os.rmdir(path) + return {"done": True, "step": None, "reason": "", "kept": kept} + except (Pending, OSError, ValueError) as error: + reason = (BUSY if isinstance(error, ondisk.Busy) else f"{error.filename}: {error.strerror}" + if isinstance(error, OSError) and error.filename and error.strerror else str(error)) + try: + _write(handler.kind, entry, {**data, "pending": {"step": step, "reason": reason, "at": _now()}}, env) + except (Pending, OSError, ValueError): + pass # reported all the same + return {"done": False, "step": step, "reason": reason, "kept": kept} + + +def collect(handler: Handler, only: str | None = None, env=None) -> list: + """Every entry of the handler's kind cleaned as far as it goes, or the one of token + *only*: per entry its ``entry`` folder name, ``done``, else the ``step`` that failed and + its ``reason``, and what was ``kept``. An entry whose intent is not ``VALID``, whose + payload or recorded steps its handler does not read or which is not proved to be its + subject is left whole, its ``reason`` saying which; one failing, or refused by the + filesystem, does not stop the next. ``Refused`` for an *only* that is no token; + ``ondisk.Busy`` when cleanup is running elsewhere.""" + if only is not None and not _named("a", only): + raise Refused(f"{only!r} is no token") + try: + held = collector(handler.kind, env) + except FileNotFoundError: + return [] # no trash yet + out = [] + with held: + kind_dir = folder(handler.kind, env=env) + for entry in sorted(n for n in os.listdir(kind_dir) if n != LOCK): + if only is not None and (parse(entry) or ("", ""))[1] != only: + continue + path, left = os.path.join(kind_dir, entry), {"done": False, "step": None, "kept": []} + try: + state, data = read(handler.kind, entry, env) + if state == EMPTY: + os.rmdir(path) + found = {**left, "done": True, "reason": ""} + elif state != VALID: + found = {**left, "reason": state} + elif not (_ordered(handler, data) and handler.payload(data)): + found = {**left, "reason": DAMAGED} + elif not _proved(handler, path, data): + found = {**left, "reason": UNPROVED} + else: + found = _clean(handler, entry, data, env) + except OSError as error: + found = {**left, "reason": f"{error.filename}: {error.strerror}" if error.filename and error.strerror else str(error)} + out.append({"entry": entry, **found}) + return out diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 0de3d31fd..3d22f10f7 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -52,7 +52,7 @@ from typing import Callable from nullius.runs import parse, verifier -from nullius import ondisk, paths +from nullius import identity, ondisk, paths, trash ADJECTIVES = """brisk quiet tidy sturdy curious gentle nimble patient plucky sunny wry keen mellow bold calm clever crisp eager fuzzy glossy humble jolly lucky merry neat proud quirky @@ -194,21 +194,22 @@ def _still(ws: Workspace, now: Workspace | None) -> Workspace | None: @contextlib.contextmanager -def _current(ws: Workspace): +def _current(ws: Workspace, held: bool = False): """*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.""" + deleted: nothing here makes its folder again, nor changes another made under its name. + *held*: by a caller that holds the profile lock, and nothing is locked here.""" if not os.path.isdir(ws.dir): yield None return - with _locked(ws): + with contextlib.nullcontext() if held else _locked(ws): yield _still(ws, load(os.path.dirname(ws.dir), ws.name)) -def _change(ws: Workspace, change: Callable) -> None: +def _change(ws: Workspace, change: Callable, held: bool = False) -> 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: + with _current(ws, held) as now: if now is None: return change(now) @@ -600,7 +601,7 @@ def _keep_judgements(ws: Workspace) -> None: _check_roots(ws, made) if old and not store.moved(ws.dir): store.adopt_owned(ws) # a record several jobs may own is not copied: it is kept below, whole - keep = os.path.join(store.home(), "judgements-of-deleted-workspaces", f"{ws.name}~{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}") + keep = os.path.join(store.home(), ARCHIVE, f"{ws.name}~{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}") os.makedirs(keep) for d in old: shutil.move(d, keep) @@ -610,6 +611,158 @@ def _keep_judgements(ws: Workspace) -> None: shutil.move(f, to) +# --- cleaning a deleted workspace ---------------------------------------------- +# Not called yet: Delete does not rename a workspace into the trash. + +ARCHIVE = "judgements-of-deleted-workspaces" # in the user data directory +KEPT_OF = "identity.json" # in a folder of it: the workspace it was kept from +SET_ASIDE = ".kept" # in a trash entry: what its archive is copied from, out of a writer's reach +UNSUPPORTED = "Judgements kept: removing them is not supported yet" + + +def located(wanted: dict, env=None) -> list: + """The folders of the workspaces folder that are the workspace of identity *wanted*, + under its name or another. ``trash.Pending`` while one that may be it cannot be told: + its record unreadable, or missing from the very folder that identity names; or the + workspaces folder itself not there, which put back would hold them all again.""" + home, found = paths.workspaces_dir(env), [] + try: + names = sorted(os.listdir(home)) + except FileNotFoundError: + raise trash.Pending(f"{home} is not there") + for folder in (os.path.join(home, n) for n in names if not n.startswith(".")): + got, at = identity.workspace(folder), os.stat(folder) + if got is None and (trash.there(os.path.join(folder, "workspace.json")) or (at.st_dev, at.st_ino) == (wanted["device"], wanted["inode"])): + raise trash.Pending(f"{folder} cannot be read") + found += [folder] if identity.same_workspace(got, wanted) else [] + return found + + +def _payload(data: dict) -> bool: + """A workspace intent's payload: ``prefix``, the folder it had, in the workspaces folder + under its name; ``roots``, the folders its jobs were read from (``walked``) as its Delete + found them; ``kept``, what the steps report. Its cleanup reads no root: it ends whether + or not they are still there.""" + payload = data["payload"] + return (set(payload) - {"kept"} == {"prefix", "roots"} and path_list(payload["roots"]) and path_list(payload.get("kept", [])) + and payload["prefix"] == os.path.join(data["origin"]["workspaces_root"], data["name"])) + + +def _evidence(path: str) -> list: + """Its judgement folders from before and the failure analyses of its imports, where a writer would put them.""" + from nullius.judge import store + from nullius.runs import failure_analysis + lanes, imports = [os.path.join(path, r) for r in store.ROOTS.values() if trash.there(os.path.join(path, r))], os.path.join(path, "imported") + return lanes + sorted(os.path.join(d, n) for d, _, names in (os.walk(imports, onerror=store._raise) if trash.there(imports) else ()) + for n in names if n.startswith(failure_analysis.FILE)) + + +def _new_evidence(path: str, data: dict, env) -> None: + """Before its bytes go: no judgement or failure analysis its archive was not made from, + its imports walked with nothing held; then, under the profile lock a save takes, the + entry still that workspace, none of that identity in the workspaces folder for a save + to find, and still no judgement folder. What was set aside is first read against its + archive again: one moved or changed since the archive step keeps them. Pending + otherwise. Nothing to tell once its record went: a removal stopped part way left + parts alone.""" + from nullius.judge import store + if not trash.there(os.path.join(path, "workspace.json")): + return + _archived(path, data, env) + late = _evidence(path) + with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): + late += [d for r in store.ROOTS.values() if trash.there(d := os.path.join(path, r))] + if late: + raise trash.Pending(f"{late[0]} was written after its archive: move it out, then retry") + if not identity.same_workspace(identity.workspace(path), data["subject"]) or located(data["subject"], env): + raise trash.Pending(f"{path} changed during cleanup") + + +def _set_aside(path: str) -> list: + """The files set aside in the entry, by their path in it; none when nothing was.""" + from nullius.judge import store + aside = os.path.join(path, SET_ASIDE) + if not trash.there(aside): + return [] + return sorted(os.path.relpath(os.path.join(d, n), aside) for d, _, names in os.walk(aside, onerror=store._raise) for n in names) + + +def _archived(path: str, data: dict, env) -> None: + """Pending unless the archive of the entry names this workspace and holds each file set aside as it is here.""" + from nullius.judge import store + files, keep = _set_aside(path), os.path.join(paths.data_dir(env), ARCHIVE, os.path.basename(path)) + if not files: + return + try: + whose = ondisk.read_record(os.path.join(keep, KEPT_OF)) + except (OSError, ValueError): + whose = None + if not identity.same_workspace(whose, data["subject"]): + raise trash.Pending(f"{keep} is not the archive of this workspace") + for rel in files: + raw = store._bytes(os.path.join(path, SET_ASIDE, rel)) + if raw is None or raw != store._bytes(os.path.join(keep, rel)): + raise trash.Pending(f"{os.path.join(keep, rel)} is not the file archived") + + +def _archive(path: str, data: dict, env) -> list: + """Its judgement folders from before, whole, and the failure analyses of its imports, + kept under ``ARCHIVE`` by the entry's own name with the identity they were kept from; + none is copied to its job or removed, here or in the user's store, which is reported. + First, under the profile lock a save takes and only for those renames, the entry + still that workspace, they are set aside + in the entry (``SET_ASIDE``), where no writer looks. Then, with nothing held, they are + copied to a folder of this step's own, read back, and given the archive's name by one + rename. An archive there already must name this workspace and hold each file as it + is here. One written since they were set aside holds the bytes (``_new_evidence``). + Pending while a rename of the workspace was not finished.""" + from nullius.judge import store + if trash.there(os.path.join(path, "rename.json")): + raise trash.Pending("its rename was not finished") + aside, found = os.path.join(path, SET_ASIDE), _evidence(path) # the walk of its imports holds nothing + with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): + if not identity.same_workspace(identity.workspace(path), data["subject"]): + raise trash.Pending(f"{path} changed during cleanup") + for item in found: + to = os.path.join(aside, os.path.relpath(item, path)) + if trash.there(to): + raise trash.Pending(f"{item} was written after its archive: move it out, then retry") + os.makedirs(os.path.dirname(to), exist_ok=True) + os.rename(item, to) + files = _set_aside(path) + home, name = os.path.join(paths.data_dir(env), ARCHIVE), os.path.basename(path) + keep, staged = os.path.join(home, name), os.path.join(home, f".{name}.staged") + if trash.there(staged): + shutil.rmtree(staged) # a copy a kill left: made again + if not files: + return [UNSUPPORTED] + if not trash.there(keep): + for rel in (*files, KEPT_OF): + raw = json.dumps(data["subject"]).encode() if rel == KEPT_OF else store._bytes(os.path.join(aside, rel)) + if raw is None: + raise trash.Pending(f"{os.path.join(aside, rel)} cannot be read") + os.makedirs(os.path.dirname(os.path.join(staged, rel)), exist_ok=True) + ondisk.write_whole(os.path.join(staged, rel), raw, mode=0o600) + os.rename(staged, keep) + _archived(path, data, env) + return [UNSUPPORTED] + + +def _unmark(path: str, data: dict, env) -> None: + """Its mark of a store all copied (``store.MOVED``), kept under its entry's name since its Delete, removed.""" + from nullius.judge import store + with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): + marker = store._marker(path, paths.data_dir(env)) + with contextlib.suppress(FileNotFoundError): + os.remove(marker) + if trash.there(marker): + raise trash.Pending(f"{marker} is still there") + + +TRASHED = trash.Handler("workspace", "workspace.json", identity.workspace, identity.same_workspace, _payload, + (("archive", _archive), ("marker", _unmark)), guard=_new_evidence) + + def holding(home_dir: str, folder: str) -> list: """Every workspace with a root in *folder*: [(workspace, those roots)].""" return holding_all(home_dir, [folder])[folder] @@ -630,22 +783,26 @@ def holding_all(home_dir: str, folders) -> dict: return found -def forget(ws: Workspace, roots, job_dirs) -> None: - """*ws* without *roots*, and without its parsed jobs of *job_dirs*.""" +def forget(ws: Workspace, roots, job_dirs, held: bool = False) -> None: + """*ws* without *roots*, and without its parsed jobs of *job_dirs*. *held*: its caller + holds the profile lock (``paths.profile_lock``), nothing is locked here, and a parse + that cannot be removed is an OSError, its entry left in the index.""" 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) + _change(ws, drop_roots, held) 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 for d in set(job_dirs) | {d for d in index if _under(d, roots)}: - _drop(ws, index, d) - _update_index(ws, drop) + _drop(ws, index, d, strict=held) + _update_index(ws, drop, held) + if held and any(trash.there(_cache_file(ws, d)) for d in job_dirs): + raise trash.Pending(f"workspace {ws.name} still holds a parse of it") def _under(job_dir: str, roots) -> bool: @@ -654,18 +811,21 @@ def _under(job_dir: str, roots) -> bool: return os.path.normpath(job_dir) in roots or os.path.dirname(os.path.normpath(job_dir)) in roots -def _drop(ws: Workspace, index: dict, job_dir: str, keep=()) -> None: - """*job_dir*'s entry in *index* and its parsed job, unless its cache file is one of *keep*.""" - index.pop(job_dir, None) +def _drop(ws: Workspace, index: dict, job_dir: str, keep=(), strict: bool = False) -> None: + """*job_dir*'s entry in *index* and its parsed job, unless its cache file is one of *keep*. + *strict*: OSError, the entry left, when the file is there and cannot be removed.""" path = _cache_file(ws, job_dir) - if path in keep: - return - with _DECODED_LOCK: - _DECODED.pop(path, None) - try: - os.remove(path) - except OSError: - pass + if path not in keep: + with _DECODED_LOCK: + _DECODED.pop(path, None) + try: + os.remove(path) + except FileNotFoundError: + pass + except OSError: + if strict: + raise + index.pop(job_dir, None) def _schema() -> str: @@ -811,20 +971,30 @@ def _index_path(ws: Workspace) -> str: _ENTRY = {"job_id": str, "n_trials": int, "dataset": str, "agent": str, "signature": str, "head": str} -def job_index(ws: Workspace) -> dict: +def job_index(ws: Workspace, strict: bool = False) -> dict: """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). The file is ``{"version", "jobs"}``; one written before it had a version is the bare map. A file that cannot be read is no index, and an entry that is not one is left out, as - is a field of the wrong type: no reader has to check one.""" + is a field of the wrong type: no reader has to check one. *strict*, for one that + changes it or must know a job is out of it: only a file seen not to be there is no + index; any other that is not one, of this version, every entry and field as written + here, is a ValueError.""" try: with open(_index_path(ws), encoding="utf-8") as fh: data = json.load(fh) - except (OSError, ValueError): # not JSON, not UTF-8 + except FileNotFoundError: + return {} + except (OSError, ValueError) as error: # not JSON, not UTF-8 + if strict: + raise ValueError(f"{_index_path(ws)} cannot be read") from error return {} if isinstance(data, dict) and "version" in data: - data = data.get("jobs") if data["version"] == INDEX_VERSION else None - if not isinstance(data, dict): + data = data.get("jobs") if data["version"] == INDEX_VERSION and (type(data["version"]) is int or not strict) else None + if not isinstance(data, dict) or strict and not all( + isinstance(e, dict) and all(v is None or type(v) is _ENTRY.get(k, type(v)) for k, v in e.items()) for e in data.values()): + if strict: + raise ValueError(f"{_index_path(ws)} cannot be read") return {} return {d: {k: v for k, v in e.items() if v is None or isinstance(v, _ENTRY.get(k, object))} for d, e in data.items() if isinstance(e, dict)} @@ -888,7 +1058,7 @@ def _holds(ws: Workspace) -> Callable | None: return lambda job_dir: _under(job_dir, kept) -def _update_index(ws: Workspace, change: Callable) -> None: +def _update_index(ws: Workspace, change: Callable, held: bool = False) -> None: """``change`` made in place to the index as the file holds it, under its lock: of two writers at once, each reads what the other wrote, so neither change is lost. Nothing once the workspace's folder is gone, renamed or deleted: no writer that began before @@ -896,8 +1066,8 @@ def _update_index(ws: Workspace, change: Callable) -> None: if not _jobs_folder(ws): return try: - with ondisk.locked(_index_path(ws) + ".lock"): - index = job_index(ws) + with contextlib.nullcontext() if held else ondisk.locked(_index_path(ws) + ".lock"): + index = job_index(ws, strict=held) before = dict(index) change(index) if index != before: diff --git a/app/tests/test_identity_on_disk.py b/app/tests/test_identity_on_disk.py new file mode 100644 index 000000000..873bd4fa8 --- /dev/null +++ b/app/tests/test_identity_on_disk.py @@ -0,0 +1,217 @@ +"""``nullius.identity``: the profile a root belongs to, the same workspace, the same run.""" +import json +import os +import shutil +import tempfile +import threading +import unittest +from unittest import mock + +from nullius import identity, paths + + +def put(folder, name, data): + os.makedirs(folder, exist_ok=True) + with open(os.path.join(folder, name), "w") as f: + json.dump(data, f) + + +class Case(unittest.TestCase): + def setUp(self): + self.tmp = os.path.realpath(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + + def profile(self, name, **roots): + env = {"NULLIUS_HOME": os.path.join(self.tmp, name), **roots} + os.makedirs(paths.data_dir(env)) + return env + + +class Profile(Case): + def test_an_origin_is_its_own_profile_and_roots_and_no_other(self): + a, b = self.profile("a"), self.profile("b") + recorded = json.loads(json.dumps(identity.origin(a))) + self.assertTrue(identity.same_origin(recorded, a)) + self.assertFalse(identity.same_origin(recorded, b)) + for moved in ("WORKSPACES_DIR", "RUNS_DIR"): # the same profile, a root relocated + self.assertFalse(identity.same_origin(recorded, {**a, moved: os.path.join(self.tmp, "elsewhere")})) + self.assertFalse(identity.same_origin({**recorded, "runs_root": 1}, a)) + self.assertFalse(identity.same_origin(recorded, {"NULLIUS_HOME": os.path.join(self.tmp, "none")})) + os.rename(a["NULLIUS_HOME"], a["NULLIUS_HOME"] + "-old") # another profile made at the same path + os.makedirs(paths.data_dir(a)) + self.assertFalse(identity.same_origin(recorded, a)) + + def test_of_two_profiles_taking_an_unmarked_root_at_once_one_owns_it(self): + root = os.path.join(self.tmp, "shared") + os.mkdir(root) + envs = [self.profile("a", WORKSPACES_DIR=root), self.profile("b", WORKSPACES_DIR=root)] + both, link, refused, owned = threading.Barrier(2, timeout=5), os.link, [], [] + def together(src, dst): + both.wait() # each has written its own record, neither has linked + return link(src, dst) + def take(env): + try: + identity.own(root, env) + owned.append(env) + except identity.NotOwner as error: + refused.append(str(error)) + with mock.patch.object(os, "link", together): + threads = [threading.Thread(target=take, args=(env,)) for env in envs] + for t in threads: t.start() + for t in threads: t.join(10) + self.assertEqual((len(owned), len(refused)), (1, 1)) + owner = paths.data_dir(owned[0]) + self.assertEqual(refused, [f"This workspaces folder belongs to the profile at {owner}."]) + self.assertEqual(os.listdir(root), [identity.OWNER]) # nothing left beside it + identity.own(root, owned[0]) # every later use compares + loser = next(env for env in envs if env is not owned[0]) + with self.assertRaisesRegex(identity.NotOwner, owner): + identity.own(root, loser) + record, mine = os.path.join(root, identity.OWNER), identity.origin(owned[0])["data_dir"] + kept = os.path.join(self.tmp, "kept") + os.rename(record, kept) + wrong = ["{", json.dumps({"version": True, "data_dir": mine}), json.dumps({"version": 2, "data_dir": mine}), + json.dumps({"version": 1, "data_dir": {**mine, "device": True}}), json.dumps({"version": 1, "data_dir": {**mine, "inode": str(mine["inode"])}}), + json.dumps({"version": 1, "data_dir": mine})[:-1] + ', "version": 1}', os.mkfifo, lambda path: os.symlink(kept, path)] + for made in wrong: + if callable(made): + made(record) + else: + with open(record, "w") as f: + f.write(made) + with self.assertRaisesRegex(identity.NotOwner, "cannot be read"): + identity.own(root, owned[0]) # never read as ours, never taken over, never waited for + os.unlink(record) + os.rename(kept, record) + identity.own(root, owned[0]) + + + def test_a_first_claim_under_a_closed_umask_is_read_back_by_its_owner(self): + root, env = os.path.join(self.tmp, "w"), self.profile("a") + os.mkdir(root) + old = os.umask(0o477) + try: + identity.own(root, env) + finally: + os.umask(old) + self.assertEqual(os.stat(os.path.join(root, identity.OWNER)).st_mode & 0o777, 0o600) + identity.own(root, env) + + +class Workspace(Case): + def make(self, name, **record): + folder = os.path.join(self.tmp, name) + put(folder, "workspace.json", {"name": name, **record}) + return folder + + def test_a_rename_keeps_it_and_a_copy_under_its_name_is_another(self): + folder = self.make("w", uid="u1", created="2026-01-01T00:00:00Z") + before = identity.workspace(folder) + self.assertEqual((before["uid"], before["created"], before["inode"]), ("u1", "2026-01-01T00:00:00Z", os.stat(folder).st_ino)) + os.rename(folder, folder + "-renamed") + renamed = identity.workspace(folder + "-renamed") + self.assertTrue(identity.same_workspace(before, renamed)) + self.assertEqual(identity.digest(before), identity.digest(renamed)) + shutil.copytree(folder + "-renamed", folder) # a replacement carrying the copied UID + copy = identity.workspace(folder) + self.assertEqual(copy["uid"], "u1") + self.assertFalse(identity.same_workspace(before, copy)) + self.assertNotEqual(identity.digest(before), identity.digest(copy)) + self.assertFalse(identity.same_workspace(before, identity.workspace(os.path.join(self.tmp, "gone")))) + self.assertFalse(identity.same_workspace(None, None)) + + def test_it_is_read_through_a_folder_its_caller_holds(self): + folder = self.make("w", uid="u1", created="2026-01-01T00:00:00Z") + fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, fd) + before = identity.workspace(fd) + self.assertEqual(before, identity.workspace(folder)) + os.rename(folder, folder + "-renamed") + self.make("w", uid="u2", created="2026-02-02T00:00:00Z") # another under its name: the held folder is still the first + self.assertEqual(identity.workspace(fd), before) + self.assertEqual(identity.workspace(folder)["uid"], "u2") + os.fstat(fd) # left open for its caller + run = os.path.join(self.tmp, "run") + put(run, "run.json", {"generation": "g1"}) + held = os.open(run, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, held) + self.assertEqual(identity.run(held), {"generation": "g1"}) + + def test_one_with_nothing_to_match_or_no_regular_record_is_no_one(self): + for record in ({}, {"created": ""}, {"uid": "", "created": ""}, {"uid": None, "created": "2026-01-01T00:00:00Z"}, {"uid": 1}): + folder = self.make("w", **record) + os.unlink(os.path.join(folder, "workspace.json")) + put(folder, "workspace.json", record) # not even a name + self.assertIsNone(identity.workspace(folder), record) + self.assertIsNotNone(identity.workspace(self.make("first", uid="u1"))) # from before versions + self.assertIsNotNone(identity.workspace(self.make("now", uid="u1", version=1))) + for version in (2, "1", True, None): # one ``workspace.load`` does not read + self.assertIsNone(identity.workspace(self.make(f"v{version}", uid="u1", version=version)), version) + parent, link = os.path.join(self.tmp, "parent"), os.path.join(self.tmp, "w-link") + os.symlink(self.tmp, parent) + os.symlink(os.path.join(self.tmp, "now"), link) + self.assertEqual(identity.workspace(os.path.join(parent, "now")), identity.workspace(os.path.join(self.tmp, "now"))) # an aliased root + for spelt in ("", "/", "/.", "/./", "//.//"): + self.assertIsNone(identity.workspace(link + spelt), spelt) # a link in its place lends nothing, however it is spelt + self.assertIsNotNone(identity.workspace(os.path.join(self.tmp, "now") + spelt), spelt) + self.assertIsNotNone(identity.workspace(link + "/../now/")) # ``..`` after a link is the system's to read + empty = {"uid": "", "device": 1, "inode": 2, "created": ""} + self.assertFalse(identity.valid_workspace(empty)) + self.assertFalse(identity.same_workspace(empty, empty)) + real = self.make("real", uid="u1") + for made in (os.mkfifo, lambda path: os.symlink(os.path.join(real, "workspace.json"), path)): + os.unlink(os.path.join(folder, "workspace.json")) + made(os.path.join(folder, "workspace.json")) + self.assertIsNone(identity.workspace(folder)) # a pipe is not waited for, a link not followed + + def test_one_without_a_uid_needs_its_folder_and_created_time_all_three(self): + folder = self.make("old", created="2025-01-01T00:00:00Z") + before = identity.workspace(folder) + self.assertEqual(before["uid"], "") + self.assertTrue(identity.same_workspace(before, identity.workspace(folder))) + self.assertTrue(identity.same_workspace(before, json.loads(json.dumps(before)))) # as an intent carries it + for field, other in (("created", "2025-01-02T00:00:00Z"), ("device", before["device"] + 1), ("inode", before["inode"] + 1), ("uid", "u1")): + self.assertFalse(identity.same_workspace(before, {**before, field: other}), field) + self.assertNotEqual(identity.digest(before), identity.digest({**before, field: other}), field) + self.make("old", created="2025-01-02T00:00:00Z") # rewritten in place: the same folder, another created + self.assertFalse(identity.same_workspace(before, identity.workspace(folder))) + self.assertFalse(identity.same_workspace(before, {k: v for k, v in before.items() if k != "created"})) + + +class Run(Case): + def test_two_runs_with_one_id_and_start_are_two_runs(self): + record = {"id": "bench-1700000000", "started": 1700000000.5} + first, second = os.path.join(self.tmp, "runs", "bench"), os.path.join(self.tmp, "other", "bench") + put(first, "run.json", record) + put(second, "run.json", record) + a, b = identity.run(first), identity.run(second) + self.assertEqual((a["id"], a["started"]), (b["id"], b["started"])) + self.assertTrue(identity.same_run(a, identity.run(first))) + self.assertFalse(identity.same_run(a, b)) + self.assertFalse(identity.same_run({"id": a["id"]}, {"id": a["id"]})) # an id alone proves nothing + self.assertFalse(identity.same_run(a, {**a, "started": a["started"] + 1})) + put(first, "run.json", {**record, "generation": "g1"}) + put(second, "run.json", {**record, "generation": "g2"}) + new = identity.run(first) + self.assertEqual(new, {"generation": "g1"}) + self.assertTrue(identity.same_run(new, {"generation": "g1"})) + self.assertFalse(identity.same_run(new, identity.run(second))) + self.assertFalse(identity.same_run(new, a)) # confirmed before it had one: confirm again + put(first, "run.json", {"id": "bench-1700000000"}) + self.assertIsNone(identity.run(first)) + for generation in (None, "", 1): # there and worthless: never the older proof instead + put(first, "run.json", {**record, "generation": generation}) + self.assertIsNone(identity.run(first), generation) + self.assertFalse(identity.same_run({**a, "generation": None}, {**a, "generation": None})) + self.assertFalse(identity.same_run({**a, "device": True}, {**a, "device": True})) + with open(os.path.join(first, "run.json"), "w") as f: + f.write('{"id": "bench-1700000000", "started": 1e400}') # read as infinity + self.assertIsNone(identity.run(first)) + for never in (float("inf"), float("nan")): + self.assertFalse(identity.valid_run({**a, "started": never})) + os.symlink(second, os.path.join(self.tmp, "linked")) + self.assertEqual(identity.run(second), {"generation": "g2"}) + for spelt in ("", "/", "/.", "/./"): + self.assertIsNone(identity.run(os.path.join(self.tmp, "linked") + spelt), spelt) # as ``execution.run_folder`` refuses it + self.assertEqual(identity.run(second + spelt), {"generation": "g2"}, spelt) + self.assertFalse(identity.valid_run({**a, "started": 10 ** 309})) diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index e92f0b8ef..5d8b0f324 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -8,10 +8,11 @@ import tempfile import textwrap import threading +import time import unittest from unittest import mock -from nullius import ondisk +from nullius import ondisk, paths class Whole(unittest.TestCase): @@ -328,6 +329,152 @@ def test_a_linked_lock_is_refused(self): with ondisk.locked(path): pass + +class Deadline(unittest.TestCase): + """The profile lock, waited for until a deadline.""" + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.profile = {"NULLIUS_HOME": self.tmp} + os.makedirs(paths.data_dir(self.profile)) + self.lock = paths.profile_lock(self.profile) + + def held(self, path, seconds=None): + """A thread holding *path* now: for *seconds*, or until the test ends or sets what is returned.""" + has, free = threading.Event(), threading.Event() + def hold(): + with ondisk.locked(path): + has.set() + free.wait(seconds) + t = threading.Thread(target=hold) + t.start() + self.addCleanup(t.join, 5) + self.addCleanup(free.set) + self.assertTrue(has.wait(5)) + return free + + def test_a_thread_holding_it_is_waited_for_until_the_deadline_only(self): + with ondisk.locked(self.lock, ondisk.deadline()): # free: had at once + pass + free, start = self.held(self.lock), time.monotonic() + with self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline()): # the one-second default + self.fail("two holders") + took = time.monotonic() - start + self.assertTrue(ondisk.WAIT <= took < ondisk.WAIT + 0.5, took) + start = time.monotonic() + with self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, time.monotonic()): # a deadline already past: one try + self.fail("two holders") + self.assertLess(time.monotonic() - start, 0.2) + threading.Timer(0.2, free.set).start() + start = time.monotonic() + with ondisk.locked(self.lock, ondisk.deadline()): + took = time.monotonic() - start + self.assertTrue(0.15 <= took < ondisk.WAIT, took) + + def test_another_process_with_its_roots_elsewhere_takes_the_same_lock(self): + moved = {**self.profile, "WORKSPACES_DIR": os.path.join(self.tmp, "w"), "RUNS_DIR": os.path.join(self.tmp, "r")} + self.assertEqual(paths.profile_lock(moved), os.path.join(self.tmp, "data", "._home.lock")) + script = textwrap.dedent(""" + import sys + from nullius import ondisk, paths + with ondisk.locked(paths.profile_lock()): + print("held", flush=True) + sys.stdin.read() + """) + app = os.path.dirname(os.path.dirname(os.path.abspath(ondisk.__file__))) + other = subprocess.Popen([sys.executable, "-c", script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + env={**os.environ, **moved, "PYTHONPATH": app}) + self.addCleanup(other.wait, 5) + self.addCleanup(other.stdin.close) + self.assertEqual(other.stdout.readline(), "held\n") + other.stdout.close() + start = time.monotonic() + with self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.3)): + self.fail("two holders") + took = time.monotonic() - start + self.assertTrue(0.3 <= took < 0.8, took) + other.stdin.close() + with ondisk.locked(self.lock, ondisk.deadline()): + pass + self.assertTrue(os.path.exists(self.lock)) # permanent + + def test_one_deadline_covers_every_lock_and_a_timeout_releases_those_already_had(self): + first, second = self.lock, os.path.join(self.tmp, "second.lock") + self.held(first, 0.25) + self.held(second) + start, until = time.monotonic(), ondisk.deadline(0.5) + with self.assertRaises(ondisk.Busy) as busy: + with ondisk.locked(first, until): + had = time.monotonic() - start + with ondisk.locked(second, until): + self.fail("two holders") + took = time.monotonic() - start + self.assertEqual(busy.exception.args, (second,)) + self.assertTrue(0.2 <= had < 0.5 <= took < 0.9, (had, took)) # not 250 ms and then 500 more + with ondisk.locked(first, time.monotonic()): # the first was given back + pass + + def test_a_waiter_that_wakes_after_its_deadline_does_not_take_a_lock_freed_meanwhile(self): + free, nap = self.held(self.lock), time.sleep + def overslept(seconds): + free.set() # the holder lets go while this waiter is late + nap(0.1) + with mock.patch.object(time, "sleep", overslept), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.025)): + self.fail("had after its deadline") + + def test_the_deadline_covers_a_lock_file_that_stays_refused(self): + with ondisk.locked(self.lock): + pass + real = os.open + def refused(path, flags, *a, **k): + if path == self.lock and not flags & os.O_CREAT: + raise PermissionError("made at this moment, its mode not yet set") + return real(path, flags, *a, **k) + start = time.monotonic() + with mock.patch.object(os, "open", refused), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.2)): + self.fail("held") + self.assertTrue(0.2 <= time.monotonic() - start < 0.7) + with mock.patch.object(os, "open", refused), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, time.monotonic()): # the collector's one try + self.fail("held") + nap, late = time.sleep, [] + def once(path, flags, *a, **k): + if path == self.lock and not flags & os.O_CREAT and not late: + raise PermissionError("refused this once") + return real(path, flags, *a, **k) + def overslept(seconds): + late.append(seconds) # allowed from now on, and this waiter is late + nap(0.1) + with mock.patch.object(os, "open", once), mock.patch.object(time, "sleep", overslept), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.015)): + self.fail("had after its deadline") + self.assertTrue(late and max(late) <= 0.005, late) + def gone(path, flags, *a, **k): + if path == self.lock and not flags & os.O_CREAT: + raise FileNotFoundError("removed at this moment") + return real(path, flags, *a, **k) + start = time.monotonic() + with mock.patch.object(os, "open", gone), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.05)): + self.fail("had after its deadline") + self.assertTrue(0.05 <= time.monotonic() - start < 0.5) + os.chmod(self.lock, 0o400) # left by a maker that stopped: put right within one try + with ondisk.locked(self.lock, time.monotonic()): + pass + + def test_a_caller_without_a_deadline_waits_past_the_default(self): + self.held(self.lock, ondisk.WAIT + 0.2) + start = time.monotonic() + with ondisk.locked(self.lock): + took = time.monotonic() - start + self.assertGreaterEqual(took, ondisk.WAIT + 0.1) + + class Digest(unittest.TestCase): def test_it_is_the_sha256_of_the_bytes(self): with tempfile.NamedTemporaryFile(delete=False) as f: diff --git a/app/tests/test_trash.py b/app/tests/test_trash.py new file mode 100644 index 000000000..c8355f006 --- /dev/null +++ b/app/tests/test_trash.py @@ -0,0 +1,517 @@ +"""``nullius.trash``: where an entry goes, what discovery leaves out, which intents may be acted on.""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +from unittest import mock + +from nullius import identity, ondisk, paths, trash + +T1, T2 = "0123456789abcdef" * 2, "f" * 32 +APP = os.path.dirname(os.path.dirname(os.path.abspath(trash.__file__))) + + +def _note(name, fail=False): + def step(path, data, env): + if fail and not os.path.exists(os.path.join(paths.data_dir(env), "let")): + raise trash.Pending("not yet") + with open(os.path.join(paths.data_dir(env), "did"), "a") as f: + f.write(name + "\n") + return [f"{name} kept"] if name == "one" else None + return name, step + + +# a kind whose steps only note that they ran; ``two`` waits for a file named ``let`` +TOY = trash.Handler("run", "run.json", identity.run, identity.same_run, lambda data: set(data["payload"]) <= {"kept"}, + (_note("one"), _note("two", fail=True))) + +KILLED = """ +import importlib, os, sys +from nullius import trash +module, _, name = sys.argv[1].rpartition(".") +at, when, real, calls = int(sys.argv[2]), sys.argv[3], trash._write, [] +def write(*args): + calls.append(1) + if len(calls) == at and when == "before": + os._exit(9) # the step done, its record not written + out = real(*args) + if len(calls) == at and when == "after": + os._exit(9) # recorded, the next not begun + return out +trash._write = write +if when == "last": + rmdir = os.rmdir + os.rmdir = lambda path, **kw: rmdir(path, **kw) if kw else os._exit(9) # the intent gone, its folder not +trash.collect(getattr(importlib.import_module(module), name)) +""" + + +def killed(env, handler, at, when) -> int: + """``collect`` in a process of its own that exits, as a kill does, at its *at*-th write of + an intent: before it, after it, or with ``last`` between the intent and its folder going.""" + return subprocess.run([sys.executable, "-c", KILLED, handler, str(at), when], env={**os.environ, **env, "PYTHONPATH": APP}, + timeout=60).returncode + + +def tree(path) -> dict: + """Every file under *path* with its bytes, every folder: what "left whole" compares.""" + out = {} + for folder, _, files in os.walk(path): + out[os.path.relpath(folder, path)] = None + for name in files: + with open(os.path.join(folder, name), "rb") as f: + out[os.path.relpath(os.path.join(folder, name), path)] = f.read() + return out + + +class Case(unittest.TestCase): + def setUp(self): + self.tmp = os.path.realpath(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.root = os.path.join(self.tmp, "root") # runs and workspaces in one folder + self.env = {"NULLIUS_HOME": os.path.join(self.tmp, "home"), "WORKSPACES_DIR": self.root, "RUNS_DIR": self.root} + os.makedirs(paths.data_dir(self.env)) + os.mkdir(self.root) + + def entry(self, kind, name, token, intent=None, env=None, **files): + """An entry as a producer leaves it: its intent and files, in place.""" + path = trash.destination(kind, name, token, env or self.env) + os.mkdir(path) + if intent is not None: + files[trash.INTENT] = intent if isinstance(intent, (str, bytes)) else json.dumps(intent) + for file, text in files.items(): + with open(os.path.join(path, file), "wb") as f: + f.write(text if isinstance(text, bytes) else text.encode()) + return path + + def intent(self, kind="run", name="bench", token=T1, env=None): + subject = {"generation": "g1"} if kind == "run" else {"uid": "u1", "device": 1, "inode": 2, "created": ""} + return trash.intent(kind, name, token, subject, env=env or self.env) + + def read(self, kind, entry, env=None): + return trash.read(kind, entry, env or self.env) + + +class Paths(Case): + def test_the_token_follows_the_last_dot_of_one_path_component(self): + self.assertEqual(trash.parse(f"a.{T1}"), ("a", T1)) + self.assertEqual(trash.parse(f"a.b.{T1}"), ("a.b", T1)) # never an entry of ``a`` + self.assertEqual(trash.parse(f"v1.2.{T1}.{T2}"), (f"v1.2.{T1}", T2)) + for other in ("a", T1, f".{T1}", f"a.{T1.upper()}", f"a.{T1[:-1]}", f"a.{T1}0", f"a-{T1}", ".collector.lock", + f"a/b.{T1}", f"../a.{T1}", f"/a.{T1}", f"...{T1}", f"..{T1}", f"a\0b.{T1}", "", None, 1): + self.assertIsNone(trash.parse(other), other) + self.assertRegex(trash.token(), r"\A[0-9a-f]{32}\Z") + path = trash.destination("run", "a.b", T1, self.env) + self.assertEqual(path, os.path.join(self.root, ".trash", "run", f"a.b.{T1}")) + self.assertEqual(os.stat(os.path.dirname(path)).st_mode & 0o777, 0o700) + good = self.intent() + for name, token in (("", T1), ("a/b", T1), ("..", T1), (".", T1), ("a\0", T1), (None, T1), ("a", "nope"), ("a", T1.upper()), ("a", None)): + with self.assertRaises(trash.Refused): # the builder, the reader and the validator, one check + trash.destination("run", name, token, self.env) + with self.assertRaises(trash.Invalid): + trash.validate({**good, "name": name, "token": token}, "run", name, token, self.env) + with self.assertRaises(trash.Invalid): + trash.intent("run", name, token, {"generation": "g1"}, env=self.env) + self.assertEqual(self.read("run", f"../run/a.b.{T1}"), (trash.UNRECOGNISED, None)) + for use in (lambda: trash.destination("job", "a", T1, self.env), lambda: self.read("job", f"a.{T1}"), lambda: trash.collector("job", self.env)): + with self.assertRaises(trash.Refused): + use() + + def test_a_run_and_a_workspace_of_one_name_neither_bar_nor_meet_each_other(self): + run = self.entry("run", "same", T1, self.intent("run", "same")) + workspace = self.entry("workspace", "same", T1, self.intent("workspace", "same")) + self.assertNotEqual(run, workspace) + self.assertEqual([self.read(kind, f"same.{T1}")[0] for kind in trash.KINDS], [trash.VALID] * 2) + os.rename(os.path.join(run, trash.INTENT), os.path.join(run, "moved")) + self.assertEqual(self.read("workspace", f"same.{T1}")[0], trash.VALID) + with trash.collector("run", self.env), trash.collector("workspace", self.env): # one collector per kind + pass + + def test_each_kind_is_read_under_its_own_configured_root_only(self): + runs = os.path.join(self.tmp, "runs") + os.mkdir(runs) + apart = {**self.env, "RUNS_DIR": runs} + self.assertEqual(os.path.dirname(trash.destination("run", "a", T1, apart)), os.path.join(runs, ".trash", "run")) + self.assertEqual(os.path.dirname(trash.destination("workspace", "a", T1, apart)), os.path.join(self.root, ".trash", "workspace")) + link = os.path.join(self.tmp, "link") # a configured root may be an alias + os.symlink(runs, link) + self.assertEqual(trash.destination("run", "a", T1, {**apart, "RUNS_DIR": link}), os.path.join(runs, ".trash", "run", f"a.{T1}")) + self.entry("run", "misplaced", T1, self.intent("run", "misplaced")) # in the workspaces root: no run trash of this configuration + self.entry("run", "hollow", T1) + self.assertEqual(self.read("run", f"misplaced.{T1}", apart), (trash.UNREADABLE, None)) + self.assertEqual(self.read("run", f"hollow.{T1}", apart), (trash.UNREADABLE, None)) # not EMPTY there + self.entry("run", "copied", T1, self.intent("run", "copied"), env=apart) # an intent of the other configuration, copied over + self.assertEqual(self.read("run", f"copied.{T1}", apart), (trash.FOREIGN, None)) + self.entry("run", "ours", T1, self.intent("run", "ours", env=apart), env=apart) + self.assertEqual(self.read("run", f"ours.{T1}", apart)[0], trash.VALID) + + def test_an_existing_destination_refuses(self): + path = self.entry("run", "a", T1, kept="x") + with self.assertRaisesRegex(trash.Refused, "exists"): + trash.destination("run", "a", T1, self.env) + self.assertEqual(os.listdir(path), ["kept"]) + trash.destination("run", "a", T2, self.env) # the same name under another token + os.symlink(os.path.join(self.tmp, "nowhere"), os.path.join(self.root, ".trash", "run", f"b.{T1}")) # a link to nothing counts + with self.assertRaisesRegex(trash.Refused, "exists"): + trash.destination("run", "b", T1, self.env) + + def test_trash_folders_that_are_not_ours_alone_refuse(self): + def refused(reason, kind="run"): + for use in (lambda: trash.destination(kind, "a", T1, self.env), lambda: self.read(kind, f"a.{T1}"), + lambda: trash.collector(kind, self.env)): + with self.assertRaisesRegex(trash.Refused, reason): + use() + trash.destination("run", "a", T1, self.env) + top, kind = os.path.join(self.root, ".trash"), os.path.join(self.root, ".trash", "run") + real = os.lstat + def elsewhere_mounted(path): + found = real(path) + return os.stat_result((*found[:2], found.st_dev + 1, *found[3:])) if path == kind else found + with mock.patch.object(os, "lstat", elsewhere_mounted): + refused("another device") + with mock.patch.object(os, "geteuid", lambda: os.stat(top).st_uid + 1): + refused("another user") + for folder in (kind, top): + os.chmod(folder, 0o750) + refused("not mode 0700") + os.chmod(folder, 0o700) + elsewhere = os.path.join(self.tmp, "elsewhere") + os.mkdir(elsewhere, 0o700) + os.symlink(elsewhere, os.path.join(top, "workspace")) + refused("not a real folder", "workspace") + os.rename(top, top + "-real") + os.symlink(top + "-real", top) + refused("not a real folder") + self.assertEqual(os.listdir(elsewhere), []) # nothing made through a link + + def test_only_the_trash_of_the_configured_roots_is_left_out_of_discovery(self): + runs = os.path.join(self.tmp, "runs") + env = {**self.env, "RUNS_DIR": runs} + entry = self.entry("workspace", "w", T1) + inner = os.path.join(runs, ".trash", "run", f"r.{T1}", "jobs") + os.makedirs(inner) + os.makedirs(os.path.join(self.root, "w", ".trash")) + unrelated = os.path.join(self.tmp, "imports", ".trash", "job") # a folder that merely has the name + os.makedirs(unrelated) + alias, into = os.path.join(self.tmp, "alias"), os.path.join(self.tmp, "into") + os.symlink(self.root, alias) + os.symlink(inner, into) # an alias into real trash + os.symlink(unrelated, os.path.join(entry, "out")) + for inside in (os.path.join(self.root, ".trash"), entry, os.path.join(entry, "jobs", "j"), os.path.join(alias, ".trash", "workspace"), + os.path.join(runs, ".trash"), inner, into, os.path.join(into, "j"), os.path.join(self.root, "w", "..", ".trash", "workspace"), + os.path.join(into, ".."), # the entry itself: ``..`` after the link, not of its name + os.path.join(entry, "out", "..", "..", "..", "root", ".trash")): + self.assertTrue(trash.in_trash(inside, env), inside) + for outside in (self.root, runs, os.path.join(self.root, "w"), os.path.join(self.root, "w", ".trash"), os.path.join(self.root, ".trashed"), + unrelated, os.path.dirname(unrelated), os.path.join(entry, "out"), os.path.join(entry, "out", ".."), + os.path.join(entry, "..", "..", "..", "w")): + self.assertFalse(trash.in_trash(outside, env), outside) + self.assertFalse(trash.in_trash(os.path.join(runs, ".trash"), self.env)) # no root of this configuration + os.symlink(unrelated, os.path.join(runs, "linked")) + self.assertFalse(trash.in_trash(os.path.join(runs, "linked"), env)) + os.rename(os.path.join(runs, ".trash"), os.path.join(runs, "real")) + os.symlink(os.path.join(runs, "real"), os.path.join(runs, ".trash")) + for inside in (os.path.join(runs, ".trash"), os.path.join(runs, ".trash", "run", f"r.{T1}"), into): # a linked one, and under it + self.assertTrue(trash.in_trash(inside, env), inside) + os.unlink(os.path.join(runs, ".trash")) + os.symlink("/", os.path.join(runs, ".trash")) # one that leads to the top: by component, not by prefix + for inside in ("/", os.path.join(runs, ".trash"), os.path.join(runs, ".trash", "usr"), os.path.join(runs, "real")): + self.assertTrue(trash.in_trash(inside, env), inside) + + +class Intents(Case): + def tree(self): + found = [] + for folder, _, files in os.walk(self.root): + for file in sorted(files): + with open(os.path.join(folder, file), "rb") as f: + found.append((folder, file, f.read())) + return sorted(found) + + def test_only_a_whole_intent_of_this_entry_and_profile_is_valid(self): + good = self.intent() + self.assertEqual(set(good), {"version", "kind", "token", "name", "written", "origin", "subject", "steps", "pending", "payload"}) + self.entry("run", "bench", T1, good, kept="x") + self.assertEqual(self.read("run", f"bench.{T1}"), (trash.VALID, good)) + done = {**good, "steps": {"detach": good["written"]}, "pending": {"step": "bytes", "reason": "busy", "at": good["written"]}} + self.assertEqual(trash.validate(done, "run", "bench", T1, self.env), done) + legacy = {"id": "bench-1", "started": 1.5, "device": 1, "inode": 2} + self.assertEqual(trash.intent("run", "bench", T1, legacy, {"host": "h"}, self.env)["payload"], {"host": "h"}) + for subject, payload in (({"id": "bench-1"}, None), ({"generation": ""}, None), (legacy, []), (legacy, ""), (legacy, 0), + (legacy, {1: "a", "1": "b"}), (legacy, {"deep": [{"raw": b"x"}]}), (legacy, {"pair": (1, 2)}), + (legacy, {"n": float("nan")}), ({**legacy, "started": float("inf")}, None)): + with self.assertRaises(trash.Invalid): # built as it is read: nothing put right in silence + trash.intent("run", "bench", T1, subject, payload, self.env) + other = {"NULLIUS_HOME": os.path.join(self.tmp, "other"), "WORKSPACES_DIR": self.root, "RUNS_DIR": self.root} + os.makedirs(paths.data_dir(other)) + def at(name, **changed): + return {**good, "name": name, "token": T2, **changed} + cases = { + "nothing": (None, trash.MISSING), "cut": (json.dumps(at("cut"))[:-9], trash.DAMAGED), "list": ("[]", trash.DAMAGED), + "bytes": (b"\xff", trash.DAMAGED), "deep": ('{"a":' * 100000, trash.DAMAGED), + "twice": (json.dumps(at("twice"))[:-1] + ', "version": 1}', trash.DAMAGED), + "later": ({"version": 2, "what": "unknown here"}, trash.FUTURE), "zero": (at("zero", version=0), trash.DAMAGED), + "true": (at("true", version=True), trash.DAMAGED), + "huge": (at("huge", subject={"id": "b", "started": 10 ** 309, "device": 1, "inode": 2}), trash.DAMAGED), + "kind": (at("kind", kind="workspace"), trash.DAMAGED), "token": (at("token", token=T1), trash.DAMAGED), + "name": (at("other"), trash.DAMAGED), "extra": (at("extra", more=1), trash.DAMAGED), + "short": ({k: v for k, v in at("short").items() if k != "payload"}, trash.DAMAGED), + "when": (at("when", written="yesterday"), trash.DAMAGED), "leap": (at("leap", written="2026-12-04T10:00:61Z"), trash.DAMAGED), + "sixty": (at("sixty", written="2026-12-04T10:00:60Z"), trash.DAMAGED), "loose": (at("loose", written="2026-12-4T10:00:00Z"), trash.DAMAGED), + "never": (json.dumps(at("never", subject={"id": "b", "started": 0, "device": 1, "inode": 2})).replace('"started": 0', '"started": 1e400'), trash.DAMAGED), "steps": (at("steps", steps={"detach": True}), trash.DAMAGED), + "pending": (at("pending", pending={"step": "bytes"}), trash.DAMAGED), "payload": (at("payload", payload=[]), trash.DAMAGED), + "origin": (at("origin", origin={"data_dir": "/x"}), trash.DAMAGED), + "subject": (at("subject", subject={"uid": "u1", "device": 1, "inode": 2, "created": ""}), trash.DAMAGED), + "id": (at("id", subject={"id": "bench-1"}), trash.DAMAGED), + "profile": (self.intent("run", "profile", T2, env=other), trash.FOREIGN), + "roots": (self.intent("run", "roots", T2, env={**self.env, "WORKSPACES_DIR": self.tmp}), trash.FOREIGN), + } + for name, (intent, _) in cases.items(): + self.entry("run", name, T2, intent, kept="x") + before = self.tree() + for name, (_, state) in cases.items(): + self.assertEqual(self.read("run", f"{name}.{T2}"), (state, None), name) + self.assertEqual(self.read("run", "stray"), (trash.UNRECOGNISED, None)) + self.assertEqual(self.read("run", f"bench.{T1}", other), (trash.FOREIGN, None)) # another profile's retry + self.assertEqual(self.tree(), before) # every one kept whole + + def test_an_empty_entry_is_told_from_one_that_cannot_be_read(self): + self.entry("run", "empty", T1) + self.entry("run", "full", T1, kept="x") + self.entry("run", "closed", T1, self.intent(name="closed")) + kind = os.path.join(self.root, ".trash", "run") + os.symlink(self.tmp, os.path.join(kind, f"link.{T1}")) + os.mkfifo(os.path.join(kind, f"pipe.{T1}")) + with open(os.path.join(kind, f"file.{T1}"), "w"): + pass + self.assertEqual(self.read("run", f"empty.{T1}"), (trash.EMPTY, None)) + self.assertEqual(self.read("run", f"full.{T1}"), (trash.MISSING, None)) + for name in ("link", "pipe", "file", "gone"): + self.assertEqual(self.read("run", f"{name}.{T1}"), (trash.UNREADABLE, None), name) + with mock.patch.object(os, "listdir", side_effect=PermissionError("no listing")): + self.assertEqual(self.read("run", f"empty.{T1}"), (trash.UNREADABLE, None)) + real = os.open + def no_intent(path, *a, **k): + if path == trash.INTENT: + raise PermissionError("no read") + return real(path, *a, **k) + with mock.patch.object(os, "open", no_intent): + self.assertEqual(self.read("run", f"closed.{T1}"), (trash.UNREADABLE, None)) + self.assertEqual(self.read("run", f"closed.{T1}")[0], trash.VALID) + + def test_an_intent_that_is_no_regular_file_is_neither_read_nor_waited_for(self): + real = self.entry("run", "real", T1, self.intent(name="real")) + made = {"pipe": lambda path: os.mkfifo(path), "link": lambda path: os.symlink(os.path.join(real, trash.INTENT), path), + "folder": lambda path: os.mkdir(path)} + start = time.monotonic() + for name, make in made.items(): + make(os.path.join(self.entry("run", name, T1), trash.INTENT)) + self.assertEqual(self.read("run", f"{name}.{T1}"), (trash.UNREADABLE, None), name) # a pipe with no writer would wait for ever + self.assertLess(time.monotonic() - start, 2) + + +class Collector(Case): + def test_of_two_processes_one_collects_and_the_other_does_not_wait(self): + with self.assertRaises(FileNotFoundError): # no trash, nothing to collect, nothing made + trash.collector("run", self.env) + self.assertEqual(os.listdir(self.root), []) + self.entry("run", "a", T1) + self.entry("workspace", "a", T1) + script = textwrap.dedent(""" + import sys + from nullius import trash + with trash.collector("run"): + print("collecting", flush=True) + sys.stdin.read() + """) + app = os.path.dirname(os.path.dirname(os.path.abspath(trash.__file__))) + other = subprocess.Popen([sys.executable, "-c", script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + env={**os.environ, **self.env, "PYTHONPATH": app}) + self.addCleanup(other.wait, 5) + self.addCleanup(other.stdin.close) + self.assertEqual(other.stdout.readline(), "collecting\n") + other.stdout.close() + start = time.monotonic() + with self.assertRaises(ondisk.Busy): + with trash.collector("run", self.env): + self.fail("two collectors") + self.assertLess(time.monotonic() - start, 0.5) + with trash.collector("workspace", self.env): # the other kind's is its own + pass + other.stdin.close() + other.wait(5) + with trash.collector("run", self.env): + pass + self.assertEqual(sorted(os.listdir(os.path.join(self.root, ".trash", "run"))), [".collector.lock", f"a.{T1}"]) + self.assertEqual(self.read("run", ".collector.lock"), (trash.UNRECOGNISED, None)) + + def test_a_collector_lock_that_is_a_link_or_a_pipe_is_refused_at_once(self): + self.entry("run", "a", T1) + lock, outside = os.path.join(self.root, ".trash", "run", ".collector.lock"), os.path.join(self.tmp, "outside") + start = time.monotonic() + for make in (lambda: os.symlink(outside, lock), lambda: os.symlink(self.tmp, lock), lambda: os.mkfifo(lock)): + make() + with self.assertRaises(OSError) as refused: + with trash.collector("run", self.env): + self.fail("held through it") + self.assertNotIsInstance(refused.exception, ondisk.Busy) + os.unlink(lock) + self.assertLess(time.monotonic() - start, 2) + self.assertFalse(os.path.lexists(outside)) # nothing made where the link led + + +class Collect(Case): + def setUp(self): + super().setUp() + self.did = os.path.join(paths.data_dir(self.env), "did") + + def run_entry(self, name="bench", token=T1, **files): + return self.entry("run", name, token, self.intent(name=name, token=token), **{"run.json": '{"generation": "g1"}', "log": "x", **files}) + + def let(self): + open(os.path.join(paths.data_dir(self.env), "let"), "w").close() + + def collect(self, **kw): + return trash.collect(TOY, env=self.env, **kw) + + def test_each_step_is_recorded_once_done_and_the_intent_goes_last(self): + self.assertEqual(self.collect(), []) # no trash: nothing made + self.assertEqual(os.listdir(self.root), []) + path, other = self.run_entry(), self.run_entry("other", T2) + os.mkdir(os.path.join(path, "jobs")) + [first, second] = self.collect() + self.assertEqual(first, {"entry": f"bench.{T1}", "done": False, "step": "two", "reason": "not yet", "kept": ["one kept"]}) + self.assertEqual(second["entry"], f"other.{T2}") # one failing does not stop the next + state, intent = self.read("run", f"bench.{T1}") + self.assertEqual((state, list(intent["steps"]), intent["pending"]["step"], intent["pending"]["reason"], intent["payload"]), + (trash.VALID, ["one"], "two", "not yet", {"kept": ["one kept"]})) + self.assertEqual(sorted(os.listdir(path)), ["intent.json", "jobs", "log", "run.json"]) # no byte goes before its steps + self.let() + self.assertEqual(self.collect(only=T2), [{"entry": f"other.{T2}", "done": True, "step": None, "reason": "", "kept": ["one kept"]}]) + self.assertTrue(os.path.isdir(path)) # retried by token: the other waits + self.assertEqual(self.collect(), [{"entry": f"bench.{T1}", "done": True, "step": None, "reason": "", "kept": ["one kept"]}]) + with open(self.did) as f: + self.assertEqual(f.read().split(), ["one", "one", "two", "two"]) # a step recorded is not run again + self.assertEqual(os.listdir(os.path.join(self.root, ".trash", "run")), [".collector.lock"]) + + def test_an_entry_that_cannot_be_trusted_is_left_whole_and_reported(self): + self.let() + far = {**self.env, "NULLIUS_HOME": os.path.join(self.tmp, "far")} + os.makedirs(paths.data_dir(far)) + made = {"none": (None, trash.MISSING), "damaged": ("{", trash.DAMAGED), "later": (None, trash.FUTURE), + "foreign": (None, trash.FOREIGN), "payload": (None, trash.DAMAGED), "another": (None, trash.UNPROVED), + "norecord": (None, trash.UNPROVED), "unread": (None, trash.UNREADABLE)} + if not os.geteuid(): + del made["unread"] # root lists a folder of mode 0 + for name, (intent, _) in made.items(): + files = {"run.json": '{"generation": "g1"}', "log": "x"} + if name == "foreign": + intent = trash.intent("run", name, T1, {"generation": "g1"}, env=far) # another profile, the same runs root + elif name == "payload": + intent = trash.intent("run", name, T1, {"generation": "g1"}, {"other": 1}, env=self.env) + elif name == "later": + intent = {**self.intent(name=name), "version": 2} + elif name not in ("none", "damaged"): + intent = self.intent(name=name) + if name == "another": + files["run.json"] = '{"generation": "g2"}' # a run of that name, not the one deleted + if name == "norecord": + del files["run.json"] + self.entry("run", name, T1, intent, **files) + folder = os.path.join(self.root, ".trash", "run") + with open(os.path.join(folder, "stray"), "w") as f: # no entry's name + f.write("x") + os.mkdir(os.path.join(folder, f"empty.{T1}")) + before = {n: tree(os.path.join(folder, n)) for n in os.listdir(folder)} + if "unread" in made: + os.chmod(os.path.join(folder, f"unread.{T1}"), 0) + self.addCleanup(os.chmod, os.path.join(folder, f"unread.{T1}"), 0o700) + found = {r["entry"]: r for r in self.collect()} + self.assertEqual({n: r["reason"] for n, r in found.items() if not r["done"]}, + {**{f"{name}.{T1}": why for name, (_, why) in made.items()}, "stray": trash.UNRECOGNISED}) + self.assertEqual([n for n, r in found.items() if r["done"]], [f"empty.{T1}"]) # recognised, seen to hold nothing + del before[f"empty.{T1}"] + if "unread" in made: + os.chmod(os.path.join(folder, f"unread.{T1}"), 0o700) + self.assertEqual({n: tree(os.path.join(folder, n)) for n in before}, before) + self.assertFalse(os.path.exists(self.did)) # no step ran + + def test_a_kill_between_any_two_writes_is_resumed(self): + self.let() + for at, when in (*((at, when) for at in (1, 2, 3) for when in ("before", "after")), (0, "last")): # one, two, bytes + with self.subTest(at=at, when=when): + path = self.run_entry(token=T2) + os.mkdir(os.path.join(path, "jobs")) + self.assertEqual(killed(self.env, "tests.test_trash.TOY", at, when), 9) + if when == "last": + self.assertEqual(os.listdir(path), []) # the intent went last + self.assertEqual([r["done"] for r in self.collect()], [True]) + self.assertFalse(os.path.lexists(path)) + with open(self.did) as f: + self.assertEqual(sorted(set(f.read().split())), ["one", "two"]) + os.unlink(self.did) + + def test_a_removal_of_bytes_stopped_part_way_is_finished(self): + self.let() + path = self.run_entry() + with mock.patch.object(os, "unlink", side_effect=PermissionError(13, "Permission denied", "log")): + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), (False, "bytes", "log: Permission denied")) + self.assertEqual(sorted(os.listdir(path)), ["intent.json", "log", "run.json"]) + os.unlink(os.path.join(path, "log")) + os.unlink(os.path.join(path, "run.json")) # as a kill after the record, removed last, leaves it + with open(os.path.join(path, "." + T2 + ".part"), "w") as f: # and one in a write of the intent + f.write("{") + self.assertEqual([r["done"] for r in self.collect()], [True]) + self.assertFalse(os.path.lexists(path)) + + def test_steps_recorded_out_of_order_or_a_folder_among_the_parts_are_not_acted_on(self): + self.let() + skipped = self.run_entry("skipped") + intent = self.intent(name="skipped") + with open(os.path.join(skipped, trash.INTENT), "w") as f: # ``two`` without ``one``: ``one`` would never run + json.dump({**intent, "steps": {"two": intent["written"]}}, f) + bare = self.entry("run", "bare", T2, {**self.intent(name="bare", token=T2), "steps": dict.fromkeys(("one", "two"), intent["written"])}) + os.mkdir(os.path.join(bare, "." + T1 + ".part")) # named as a killed write's file, and no file + with open(os.path.join(bare, "." + T1 + ".part", "verdict.json"), "w") as f: + f.write("{}") + whole = tree(skipped), tree(bare) + self.assertEqual({r["entry"]: r["reason"] for r in self.collect()}, {f"skipped.{T1}": trash.DAMAGED, f"bare.{T2}": trash.UNPROVED}) + self.assertEqual(((tree(skipped), tree(bare)), os.path.exists(self.did)), (whole, False)) + + def test_an_entry_the_filesystem_refuses_does_not_stop_the_next_and_a_token_is_one_or_none(self): + self.let() + folder = os.path.join(self.root, ".trash", "run") + self.run_entry() + os.mkdir(os.path.join(folder, f"a-empty.{T2}")) + rmdir = os.rmdir + with mock.patch.object(os, "rmdir", lambda path, **kw: rmdir(path, **kw) if kw or "a-empty" not in path else rmdir(os.path.join(path, "no"))): + first, second = self.collect() + self.assertEqual((first["done"], "No such file" in first["reason"], second["done"]), (False, True, True)) + for token in ("", "nope", T1.upper(), 0): + with self.assertRaises(trash.Refused): # never taken for "every entry" + self.collect(only=token) + self.assertTrue(os.path.isdir(os.path.join(folder, f"a-empty.{T2}"))) + + def test_a_second_process_does_not_collect_meanwhile(self): + self.let() + path = self.run_entry() + script = "import sys\nfrom nullius import trash\nwith trash.collector('run'):\n print('held', flush=True)\n sys.stdin.read()\n" + other = subprocess.Popen([sys.executable, "-c", script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + env={**os.environ, **self.env, "PYTHONPATH": APP}) + self.addCleanup(other.wait, 5) + self.addCleanup(other.stdout.close) + self.addCleanup(other.stdin.close) + self.assertEqual(other.stdout.readline(), "held\n") + before = tree(path) + with self.assertRaises(ondisk.Busy): # cleanup is running elsewhere + self.collect() + self.assertEqual(tree(path), before) + other.stdin.close() + other.wait(5) + self.assertEqual([r["done"] for r in self.collect()], [True]) diff --git a/app/tests/test_trash_collect.py b/app/tests/test_trash_collect.py new file mode 100644 index 000000000..298893b41 --- /dev/null +++ b/app/tests/test_trash_collect.py @@ -0,0 +1,518 @@ +"""Cleaning the trash entry of a deleted run (``execution.TRASHED``) or workspace +(``workspace.TRASHED``): on entries made by hand as a Delete will leave them, stopped at +every step and taken up again, and the form of ``forget`` a step uses under the profile lock.""" +from __future__ import annotations + +import json +import os +import shutil +import tempfile +import threading +import time +import uuid +import unittest +from unittest.mock import patch + +from nullius import execution, identity, ondisk, paths, trash, workspace +from nullius.judge import questions as Q, store +from nullius.runs import failure_analysis, parse, uid + +from tests.test_trash import T1, T2, killed, tree +from tests.test_workspace import _job_dir, _write_json + +TRIAL = "tau3-bench__t0__abc" + + +def rec(choice="x", asked_at="2026-01-01T00:00:00Z"): + return {"questions": Q.VERSION, "answers": {"q": {"choice": choice}}, "asked_at": asked_at} + + +class Case(unittest.TestCase): + def setUp(self): + self.world() + + def world(self): + """A profile of its own, runs and workspaces apart: made again by a test that needs a fresh one.""" + self.doCleanups() + self.tmp = os.path.realpath(tempfile.mkdtemp(prefix="nullius-collect-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.env = {"NULLIUS_HOME": os.path.join(self.tmp, "home"), "WORKSPACES_DIR": os.path.join(self.tmp, "ws"), + "RUNS_DIR": os.path.join(self.tmp, "runs")} + patcher = patch.dict(os.environ, self.env); patcher.start(); self.addCleanup(patcher.stop) + self.data, self.home, self.root = paths.data_dir(), paths.workspaces_dir(), paths.runs_dir() + for folder in (self.data, self.home, self.root): + os.makedirs(folder) + + def run_(self, name, job="job-a", state="done", **record): + """A run as it ended, live: its record and one job.""" + _write_json(os.path.join(self.root, name, execution.RECORD), {"state": state, **(record or {"generation": f"g-{name}"})}) + return os.path.join(self.root, name, "jobs"), _job_dir(os.path.join(self.root, name, "jobs"), job) + + def uid(self, job_dir): + return parse.parse_job(job_dir, trials=False).uid + + def trash_run(self, name, token=T1, host=None, spaces=()): + """The run *name* as its Delete leaves it: an intent naming what to clean, then one rename.""" + path, jobs = os.path.join(self.root, name), os.path.join(self.root, name, "jobs") + dirs = parse.find_job_dirs([jobs]) + payload = {"jobs": {d: {"uid": self.uid(d), "source": "derived"} for d in dirs}, "host": host, "workspaces": [ + {"identity": identity.workspace(ws.dir), "roots": [jobs], "jobs": dirs} for ws in spaces]} + _write_json(os.path.join(path, trash.INTENT), trash.intent("run", name, token, identity.run(path), payload)) + entry = trash.destination("run", name, token) + os.rename(path, entry) + return entry + + def trash_workspace(self, ws, token=T2): + """The workspace *ws* as its Delete leaves it: intent, its mark moved to the entry's name, one rename.""" + payload = {"prefix": ws.dir, "roots": workspace.walked(ws)} + _write_json(os.path.join(ws.dir, trash.INTENT), trash.intent("workspace", ws.name, token, identity.workspace(ws.dir), payload)) + entry = trash.destination("workspace", ws.name, token) + if os.path.exists(store._marker(ws.dir, self.data)): + os.replace(store._marker(ws.dir, self.data), store._marker(entry, self.data)) + os.rename(ws.dir, entry) + return entry + + def shown(self, uid, lane="decision"): + """The choices kept for the job *uid*'s trial in the user's store, every version.""" + return sorted(r["answers"]["q"]["choice"] for _, _, _, r in store.all_records(self.data, uid, lane)) + + +class Held(Case): + def test_forget_under_the_profile_lock_takes_no_lock_of_its_own(self): + jobs, job = self.run_("r1") + ws = workspace.create(self.home, [jobs], label="a") + workspace.load_jobs(ws, ws.roots) + done = threading.Thread(target=workspace.forget, args=(ws, [jobs], [job]), kwargs={"held": True}, daemon=True) + with ondisk.locked(os.path.join(ws.dir, "workspace.json.lock")), ondisk.locked(os.path.join(ws.jobs_dir, "index.json.lock")): + done.start() + done.join(5) + self.assertFalse(done.is_alive()) + now = workspace.load(self.home, ws.name) + self.assertEqual((now.roots, workspace.job_index(now)), ([], {})) + + +KEPT = [workspace.UNSUPPORTED] + + +def stopped(where, name, at, nth): + """*where.name* raising, as a kill would end it, at its *nth* call on a path holding *at*.""" + real, calls = getattr(where, name), [] + + def stop(path, *args, **kw): + calls.extend([path] if at in str(path) else []) + if at in str(path) and len(calls) == nth: + raise KeyboardInterrupt + return real(path, *args, **kw) + return patch.object(where, name, stop) + + +class Run(Case): + def world(self, host=None): + """r1, deleted, held by workspaces a (with r0) and b, each with an older record of its + job; c never held it. Its job is judged in the user's store.""" + super().world() + self.jobs, self.job = self.run_("r1") + self.others, _ = self.run_("r0", "job-b") + self.a = workspace.create(self.home, [self.jobs, self.others], label="a") + self.b = workspace.create(self.home, [self.jobs], label="b") + self.c = workspace.create(self.home, [self.others], label="c") + for ws in (self.a, self.b, self.c): + workspace.load_jobs(ws, ws.roots) # parsed, as a page leaves them + store.save(ws.dir, "job-a", TRIAL, rec(f"{ws.name} job-a")) + self.u = self.uid(self.job) + store.save(self.data, self.u, TRIAL, rec("mine", "2026-02-01T00:00:00Z")) + store.save(self.data, self.u, TRIAL, rec("mine"), lane="llm") + self.judged = tree(os.path.join(self.data, "judgements")), tree(os.path.join(self.data, "judgements-llm")) + self.entry = self.trash_run("r1", host=host, spaces=(self.a, self.b)) + + def collect(self, **kw): + return trash.collect(execution.TRASHED, **kw) + + def cleaned(self, entry=False): + """What a finished cleanup leaves, whatever stopped it on the way.""" + self.assertEqual(os.path.lexists(self.entry), entry) + a, b, c = (workspace.load(self.home, n) for n in "abc") + self.assertEqual((a.roots, b.roots, c.roots), ([self.others], [], [self.others])) + for ws in (a, b, c): + self.assertNotIn(self.job, workspace.job_index(ws)) + self.assertEqual(len(store.job_dirs(ws.dir, ["job-a"])), 1) # no judgement is removed or moved + self.assertEqual((tree(os.path.join(self.data, "judgements")), tree(os.path.join(self.data, "judgements-llm"))), self.judged) + + def test_it_detaches_keeps_the_judgements_and_says_so_then_frees_the_bytes(self): + self.assertEqual(self.collect(), [{"entry": f"r1.{T1}", "done": True, "step": None, "reason": "", "kept": KEPT}]) + self.cleaned() + self.assertEqual(sorted(os.listdir(self.root)), [".trash", "r0"]) + + def test_a_run_saved_before_generations_is_proved_by_its_folder(self): + self.run_("old", id="20260101-000000", started=1.5) + entry = self.trash_run("old", token=T2) + self.assertEqual(set(trash.read("run", f"old.{T2}")[1]["subject"]), {"id", "started", "device", "inode"}) + shutil.copytree(entry, entry + ".copy") # the same record in another folder is not it + os.rename(entry, entry + ".away"); os.rename(entry + ".copy", entry) + self.assertEqual(self.collect(only=T2), [{"entry": f"old.{T2}", "done": False, "step": None, "reason": trash.UNPROVED, "kept": []}]) + os.rename(entry, entry + ".copy"); os.rename(entry + ".away", entry) + self.assertTrue(self.collect(only=T2)[0]["done"]) + + def test_a_kill_at_any_write_of_the_intent_is_resumed(self): + for at, when in (*((at, when) for at in (1, 2, 3) for when in ("before", "after")), (0, "last")): # detach, judgements, bytes + with self.subTest(at=at, when=when): + self.world() + self.assertEqual(killed(self.env, "nullius.execution.TRASHED", at, when), 9) + self.assertEqual([(r["done"], r["kept"]) for r in self.collect()], [(True, KEPT if at else [])]) # said once + self.cleaned() + + def test_a_detach_stopped_between_two_workspaces_is_done_again(self): + with stopped(ondisk, "write_whole", os.path.join("ws", "b"), 1), self.assertRaises(KeyboardInterrupt): + self.collect() + self.assertEqual((workspace.load(self.home, "a").roots, workspace.load(self.home, "b").roots), ([self.others], [self.jobs])) + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) + self.collect() + self.cleaned() + + def test_no_folder_is_walked_or_parsed_under_the_profile_lock(self): + held, seen = [], [] + + def probed(real): + def call(*args, **kw): + seen.append(real.__name__) + try: + with ondisk.locked(paths.profile_lock(), time.monotonic()): + pass # had at once: nobody holds it + except ondisk.Busy: + held.append(real.__name__) + return real(*args, **kw) + return call + with patch.object(os, "walk", probed(os.walk)), patch.object(uid, "strict_of", probed(uid.strict_of)), \ + patch.object(parse, "find_job_dirs", probed(parse.find_job_dirs)): + self.assertTrue(self.collect()[0]["done"]) + self.assertEqual((held, "strict_of" in seen), ([], True)) + + def test_a_busy_profile_leaves_the_step_pending_and_nothing_changed(self): + whole = tree(self.home) + with ondisk.locked(paths.profile_lock()), patch.object(ondisk, "deadline", time.monotonic): + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"], found["kept"]), (False, "detach", trash.BUSY, [])) + intent = trash.read("run", f"r1.{T1}")[1] + self.assertEqual((intent["steps"], intent["pending"]["step"], intent["pending"]["reason"]), ({}, "detach", trash.BUSY)) + self.assertEqual(tree(self.home), whole) + self.collect() + self.cleaned() + + def test_a_run_made_under_the_name_since_keeps_its_roots(self): + self.run_("r1") # no barrier held the name: its roots read the same + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "detach")) + self.assertIn("is there again", found["reason"]) + self.assertEqual(workspace.load(self.home, "b").roots, [self.jobs]) + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) + + def test_a_job_that_is_not_the_one_its_intent_names_holds_the_detach(self): + intent = trash.read("run", f"r1.{T1}")[1] + named = {"another job": {"uid": str(uuid.uuid4()), "source": "derived"}, "another source": {"uid": self.u, "source": "declared"}} + for name, job in named.items(): + with self.subTest(name): + _write_json(os.path.join(self.entry, trash.INTENT), {**intent, "payload": {**intent["payload"], "jobs": {self.job: job}}}) + whole = tree(self.home) + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "detach")) + self.assertIn("is not the job its intent names", found["reason"]) + self.assertEqual(tree(self.home), whole) + _write_json(os.path.join(self.entry, trash.INTENT), intent) + self.collect() + self.cleaned() + + def test_a_job_that_is_gone_or_cannot_be_told_holds_its_entry_alone(self): + def gone(): + shutil.rmtree(os.path.join(self.entry, "jobs", "job-a")) + return {"uid": "", "source": "pending"} # claimed as never begun + + def shapeless(): + _write_json(os.path.join(self.entry, "jobs", "job-a", "config.json"), {"agents": [None], "datasets": 3}) + return None + for make in (gone, shapeless): + with self.subTest(make.__name__): + self.world() + self.run_("r2") + self.trash_run("r2", token=T2) # a sibling, whole + intent, claimed = trash.read("run", f"r1.{T1}")[1], make() + if claimed: + _write_json(os.path.join(self.entry, trash.INTENT), {**intent, "payload": {**intent["payload"], "jobs": {self.job: claimed}}}) + first, second = self.collect() + self.assertEqual((first["done"], first["step"], second["done"]), (False, "detach", True)) + self.assertEqual(workspace.load(self.home, "b").roots, [self.jobs]) + + def test_a_workspaces_folder_that_is_not_there_holds_the_detach(self): + os.rename(self.home, self.home + ".away") # put back, its workspaces would show the run again + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), (False, "detach", f"{self.home} is not there")) + os.rename(self.home + ".away", self.home) + self.collect() + self.cleaned() + + def test_a_payload_that_names_what_is_not_the_run_s_is_not_acted_on(self): + away = os.path.join(self.tmp, "offline", "jobs") # nobody's to detach + workspace.add_roots(self.c, [away]) + intent = trash.read("run", f"r1.{T1}")[1] + held, job = intent["payload"]["workspaces"][0], intent["payload"]["jobs"][self.job] + bad = {"a root elsewhere": {"workspaces": [{**held, "identity": identity.workspace(self.c.dir), "roots": [away]}]}, + "a job elsewhere": {"jobs": {os.path.join(away, "job-a"): job}, "workspaces": []}, + "no identity": {"jobs": {self.job: {"uid": "../../judgements", "source": "derived"}}}, + "a pending job with one": {"jobs": {self.job: {**job, "source": "pending"}}}, + "judgements to remove": {"workspaces": [{**held, "judged": ["judgements/job-a"]}]}, + "a job no run names": {"workspaces": [{**held, "jobs": [os.path.join(self.jobs, "job-z")]}]}} + for name, change in bad.items(): + with self.subTest(name): + _write_json(os.path.join(self.entry, trash.INTENT), {**intent, "payload": {**intent["payload"], **change}}) + whole = {k: v for k, v in tree(self.tmp).items() if not k.endswith(trash.LOCK)} + self.assertEqual(self.collect(), [{"entry": f"r1.{T1}", "done": False, "step": None, "reason": trash.DAMAGED, "kept": []}]) + self.assertEqual({k: v for k, v in tree(self.tmp).items() if not k.endswith(trash.LOCK)}, whole) + + def test_what_cannot_be_read_is_not_taken_for_gone(self): + def unsearchable_workspace(): + os.chmod(self.b.dir, 0); self.addCleanup(os.chmod, self.b.dir, 0o700) + return lambda: os.chmod(self.b.dir, 0o700) + + def unsearchable_run(): # one made under the name since + os.mkdir(os.path.join(self.root, "r1"), 0) + return lambda: os.rmdir(os.path.join(self.root, "r1")) + + def damaged_state(): + with open(os.path.join(self.b.dir, "state.json"), "w") as f: + f.write("{") + return lambda: workspace.save(self.b) + + def damaged_record(): # c may be one that held the run + path = os.path.join(self.c.dir, "workspace.json") + os.rename(path, path + ".whole") + with open(path, "w") as f: + f.write("{") + return lambda: os.replace(path + ".whole", path) + + def record_gone_from_its_folder(): # put back, it would show the run again + path = os.path.join(self.b.dir, "workspace.json") + os.rename(path, os.path.join(self.tmp, "kept.json")) + return lambda: os.rename(os.path.join(self.tmp, "kept.json"), path) + + def index(text): + path = os.path.join(self.a.jobs_dir, "index.json") + os.rename(path, path + ".whole") + with open(path, "w") as f: + f.write(text) + return lambda: os.replace(path + ".whole", path) + + def damaged_index(): + return index("{") + + def index_row_not_one(): # left out by a page, never by a removal + return index(json.dumps({"version": workspace.INDEX_VERSION, "jobs": {self.job: "x"}})) + + def index_version_not_a_number(): + return index(json.dumps({"version": True, "jobs": {self.job: {"job_id": "j1"}}})) + + def refused_parse(): + patcher = patch.object(workspace.os, "remove", side_effect=PermissionError(13, "Permission denied", "parse")); patcher.start() + return patcher.stop + for make in (unsearchable_workspace, unsearchable_run, damaged_state, damaged_record, record_gone_from_its_folder, damaged_index, + index_row_not_one, index_version_not_a_number, refused_parse): + with self.subTest(make.__name__): + self.world() + if os.geteuid() == 0 and make.__name__.startswith("unsearchable"): + continue # root searches a folder of mode 0 + repair = make() + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "detach"), found) + if make is damaged_state: # never written again from what could be read of it + self.assertEqual(os.path.getsize(os.path.join(self.b.dir, "state.json")), 1) + if make is damaged_index: + self.assertEqual(os.path.getsize(os.path.join(self.a.jobs_dir, "index.json")), 1) + repair() + if make is refused_parse or "index" in make.__name__: + self.assertIn(self.job, workspace.job_index(workspace.load(self.home, "a"))) + self.assertEqual(workspace.load(self.home, "b").roots, [self.jobs]) + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) + self.assertTrue(self.collect()[0]["done"]) + self.cleaned() + + def test_a_host_copy_is_never_removed_and_keeps_the_entry_pending(self): + self.world(host="gpu-1") + with patch.object(execution, "subprocess_run") as ran, patch.object(execution.subprocess, "run") as raw: + for _ in range(2): + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"], found["kept"]), + (False, "host", "The copy of r1 on gpu-1 stays: remove it there.", KEPT)) + self.assertFalse(ran.called or raw.called) # no command is sent to it + self.assertEqual(os.listdir(self.entry), [trash.INTENT]) # local cleanup is finished without it + self.assertEqual(list(trash.read("run", f"r1.{T1}")[1]["steps"]), ["detach", "judgements", "bytes"]) + self.cleaned(entry=True) + os.mkdir(os.path.join(self.entry, "jobs")) # its bytes are recorded as gone: these are not its own + self.assertEqual(self.collect(), [{"entry": f"r1.{T1}", "done": False, "step": None, "reason": trash.UNPROVED, "kept": []}]) + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs"))) + + def test_another_profile_on_the_same_roots_cleans_nothing(self): + far, whole = {**self.env, "NULLIUS_HOME": os.path.join(self.tmp, "far")}, tree(self.tmp) + os.makedirs(paths.data_dir(far)) + self.assertEqual(trash.collect(execution.TRASHED, env=far), + [{"entry": f"r1.{T1}", "done": False, "step": None, "reason": trash.FOREIGN, "kept": []}]) + self.assertEqual({k: v for k, v in tree(self.tmp).items() if not k.startswith("far") and not k.endswith(trash.LOCK)}, whole) + + +class Workspaces(Case): + def world(self): + """w, deleted: it read a run's jobs and a conversion kept in its ``imported/``, and kept + records from before for both, for a job it no longer reaches, and a failure analysis.""" + super().world() + self.jobs, self.job = self.run_("r0") + self.ws = workspace.create(self.home, [self.jobs], label="w") + self.kept = _job_dir(self.ws.imports_dir, "atif__x") + self.ws.job_roots = [self.ws.imports_dir]; workspace.save(self.ws) + failure_analysis.update(self.kept, lambda a: a.set_label("t0", "agent", by="me")) + for job in ("job-a", "atif__x", "job-gone"): + store.save(self.ws.dir, job, TRIAL, rec(job)) + os.makedirs(os.path.dirname(store._marker(self.ws.dir, self.data))) + open(store._marker(self.ws.dir, self.data), "w").close() + self.before, self.subject = tree(self.ws.dir), identity.workspace(self.ws.dir) + self.entry = self.trash_workspace(self.ws) + self.archive = os.path.join(self.data, workspace.ARCHIVE, f"w.{T2}") + self.gone = os.path.join("judgements", "job-gone", TRIAL + ".json") + + def collect(self, **kw): + return trash.collect(workspace.TRASHED, **kw) + + def cleaned(self): + self.assertFalse(os.path.lexists(self.entry)) + kept = {k: v for k, v in tree(self.archive).items() if v is not None} + self.assertEqual(json.loads(kept.pop(workspace.KEPT_OF)), self.subject) # whose they were + analysis = os.path.join("imported", "atif__x", failure_analysis.FILE) + self.assertEqual(kept, {k: v for k, v in self.before.items() if k.startswith(("judgements", analysis)) and v is not None}) + self.assertTrue({self.gone, analysis} <= set(kept)) + self.assertEqual(os.listdir(os.path.join(self.data, "judgements")), [store.MOVED]) # none copied to a job + self.assertEqual(os.listdir(os.path.join(self.data, "judgements", store.MOVED)), []) + self.assertFalse(os.path.exists(os.path.join(self.data, workspace.ARCHIVE, f".w.{T2}.staged"))) + + def test_it_archives_its_judgements_whole_and_says_so_then_frees_the_bytes(self): + self.assertEqual(self.collect(), [{"entry": f"w.{T2}", "done": True, "step": None, "reason": "", "kept": KEPT}]) + self.cleaned() + self.assertTrue(os.path.isdir(self.job)) # the roots it read are not its own + + def test_a_kill_at_any_write_of_the_intent_is_resumed(self): + for at, when in (*((at, when) for at in (1, 2, 3) for when in ("before", "after")), (0, "last")): # archive, marker, bytes + with self.subTest(at=at, when=when): + self.world() + self.assertEqual(killed(self.env, "nullius.workspace.TRASHED", at, when), 9) + self.assertEqual([(r["done"], r["kept"]) for r in self.collect()], [(True, KEPT if at else [])]) + self.cleaned() + + def test_a_step_stopped_part_way_is_done_again(self): + stops = ((os, "rename", os.path.join(".trash", "workspace"), 2), (ondisk, "write_whole", workspace.ARCHIVE, 2), + (os, "rename", workspace.ARCHIVE, 1), (os, "remove", store.MOVED, 1), (os, "unlink", os.path.join(".trash", "workspace"), 2)) + for where, name, at, nth in stops: + with self.subTest(name=name, at=at): + self.world() + with stopped(where, name, at, nth), self.assertRaises(KeyboardInterrupt): + self.collect() + found = [os.path.isfile(os.path.join(d, self.gone)) for d in (self.entry, os.path.join(self.entry, workspace.SET_ASIDE), self.archive)] + self.assertTrue(any(found), found) # where a writer put it, set aside, or in an archive that is whole + self.collect() + self.cleaned() + + def test_it_ends_whether_or_not_the_roots_it_read_are_still_there(self): + os.rename(os.path.join(self.root, "r0"), os.path.join(self.root, "away")) # deleted, or out of reach: it reads none + self.assertTrue(self.collect()[0]["done"]) + self.cleaned() + + def test_one_with_no_judgement_of_its_own_ends(self): + shutil.rmtree(os.path.join(self.entry, "judgements")) + for name in os.listdir(os.path.join(self.entry, "imported", "atif__x")): + if name.startswith(failure_analysis.FILE): + os.unlink(os.path.join(self.entry, "imported", "atif__x", name)) + self.assertEqual(self.collect(), [{"entry": f"w.{T2}", "done": True, "step": None, "reason": "", "kept": KEPT}]) + self.assertEqual((os.path.lexists(self.entry), os.path.exists(self.archive)), (False, False)) + + def test_an_archive_moved_since_it_was_made_keeps_what_was_set_aside(self): + with stopped(os, "remove", store.MOVED, 1), self.assertRaises(KeyboardInterrupt): + self.collect() # archived, recorded + os.rename(self.archive, self.archive + ".away") + for _ in range(2): + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), (False, "bytes", f"{self.archive} is not the archive of this workspace")) + self.assertTrue(os.path.isfile(os.path.join(self.entry, workspace.SET_ASIDE, self.gone))) + os.rename(self.archive + ".away", self.archive) + self.collect() + self.cleaned() + + def test_a_name_taken_again_is_another_workspace(self): + other = workspace.create(self.home, [], label="w") + self.assertEqual(other.dir, self.ws.dir) + store.save(other.dir, "job-a", TRIAL, rec("its own")) + whole = tree(other.dir) + self.collect() + self.assertEqual(tree(other.dir), whole) + self.cleaned() + + def test_a_rename_not_finished_leaves_it_whole(self): + _write_json(os.path.join(self.entry, "rename.json"), {"version": 1}) + whole = tree(self.entry) + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), (False, "archive", "its rename was not finished")) + self.assertEqual({k: v for k, v in tree(self.entry).items() if k != trash.INTENT}, {k: v for k, v in whole.items() if k != trash.INTENT}) + os.unlink(os.path.join(self.entry, "rename.json")) + self.collect() + self.cleaned() + + def test_a_verdict_saved_after_its_archive_was_begun_holds_the_bytes(self): + real, late = ondisk.write_whole, os.path.join(self.entry, "judgements", "job-late", TRIAL + ".json") + + def write(path, *args, **kw): # as the copy begins, nothing held: a save gets in + if workspace.ARCHIVE in path and not os.path.exists(late): + store.save(self.entry, "job-late", TRIAL, rec("late")) + return real(path, *args, **kw) + with patch.object(ondisk, "write_whole", write): + [found] = self.collect() + for _ in range(2): + self.assertEqual((found["done"], found["step"]), (False, "bytes")) + self.assertIn("was written after its archive", found["reason"]) + self.assertTrue(os.path.isfile(late) and os.path.isfile(os.path.join(self.entry, "workspace.json"))) + self.assertTrue(os.path.isfile(os.path.join(self.archive, self.gone))) + [found] = self.collect() # until it is moved out + shutil.move(os.path.join(self.entry, "judgements"), os.path.join(self.tmp, "late")) + self.assertTrue(self.collect()[0]["done"]) + self.cleaned() + + def test_an_archive_of_that_name_that_is_another_workspace_s_is_not_taken_for_its_own(self): + self.collect() + aside = tempfile.mkdtemp(prefix="nullius-collect-") + shutil.copytree(self.archive, os.path.join(aside, "kept")) + self.world() # the same bytes, kept from another folder + self.addCleanup(shutil.rmtree, aside, True) + shutil.copytree(os.path.join(aside, "kept"), self.archive) + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), (False, "archive", f"{self.archive} is not the archive of this workspace")) + self.assertTrue(os.path.isfile(os.path.join(self.entry, workspace.SET_ASIDE, self.gone))) + shutil.rmtree(self.archive) + self.collect() + self.cleaned() + + def test_bookkeeping_that_would_skip_a_step_or_name_another_folder_is_not_acted_on(self): + intent, path = trash.read("workspace", f"w.{T2}")[1], os.path.join(self.entry, trash.INTENT) + done = dict.fromkeys(("archive", "marker", "bytes"), intent["written"]) + bad = {"a later step alone": ({"steps": {"marker": intent["written"]}}, trash.DAMAGED), + "another folder": ({"payload": {**intent["payload"], "prefix": os.path.join(self.home, "other")}}, trash.DAMAGED), + "records to hand over": ({"payload": {**intent["payload"], "owners": {}}}, trash.DAMAGED), + "its bytes recorded as gone, all there": ({"steps": done}, trash.UNPROVED)} + for name, (change, reason) in bad.items(): + with self.subTest(name): + _write_json(path, {**intent, **change}) + whole = tree(self.entry) + self.assertEqual(self.collect(), [{"entry": f"w.{T2}", "done": False, "step": None, "reason": reason, "kept": []}]) + self.assertEqual((tree(self.entry), os.path.exists(self.archive)), (whole, False)) + + def test_a_copy_of_its_record_elsewhere_is_not_it(self): + shutil.copytree(self.entry, self.entry + ".copy") + os.rename(self.entry, os.path.join(self.tmp, "away")); os.rename(self.entry + ".copy", self.entry) + whole = tree(self.entry) + self.assertEqual(self.collect(), [{"entry": f"w.{T2}", "done": False, "step": None, "reason": trash.UNPROVED, "kept": []}]) + self.assertEqual(tree(self.entry), whole) + + +if __name__ == "__main__": + unittest.main()