From 5873e40dbaff2d30455e980ee584c3aacb9e6eeb Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 00:29:47 +0100 Subject: [PATCH 1/8] feat(execution): add the shared profile lock, identity and trash primitives --- app/nullius/identity.py | 183 +++++++++++++++++ app/nullius/ondisk.py | 91 ++++++++- app/nullius/paths.py | 5 + app/nullius/trash.py | 189 ++++++++++++++++++ app/tests/test_identity_on_disk.py | 217 ++++++++++++++++++++ app/tests/test_ondisk.py | 149 +++++++++++++- app/tests/test_trash.py | 311 +++++++++++++++++++++++++++++ 7 files changed, 1134 insertions(+), 11 deletions(-) create mode 100644 app/nullius/identity.py create mode 100644 app/nullius/trash.py create mode 100644 app/tests/test_identity_on_disk.py create mode 100644 app/tests/test_trash.py 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/trash.py b/app/nullius/trash.py new file mode 100644 index 000000000..fbc09e8ae --- /dev/null +++ b/app/nullius/trash.py @@ -0,0 +1,189 @@ +"""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. Nothing here removes anything. + +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 stat +import time +import uuid +from datetime import datetime + +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), ".collector.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 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..3d8a1d498 --- /dev/null +++ b/app/tests/test_trash.py @@ -0,0 +1,311 @@ +"""``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 ondisk, paths, trash + +T1, T2 = "0123456789abcdef" * 2, "f" * 32 + + +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 From 75d49d44dfc9b382eaf27d0fef051d647050b7f9 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 09:36:18 +0100 Subject: [PATCH 2/8] feat(execution): add the collector loop for trash entries --- app/nullius/trash.py | 132 ++++++++++++++++++++++++++++- app/tests/test_trash.py | 180 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 309 insertions(+), 3 deletions(-) diff --git a/app/nullius/trash.py b/app/nullius/trash.py index fbc09e8ae..f8da961a0 100644 --- a/app/nullius/trash.py +++ b/app/nullius/trash.py @@ -1,6 +1,7 @@ """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. Nothing here removes anything. +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 @@ -12,10 +13,13 @@ 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 @@ -112,7 +116,7 @@ def in_trash(path, env=None) -> bool: 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), ".collector.lock"), deadline=time.monotonic()) + 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: @@ -187,3 +191,127 @@ def read(kind: str, entry: str, env=None) -> tuple: 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; ``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 a payload is one its steps read + steps: tuple + after: tuple = () + + +def _now() -> str: + return time.strftime(STAMP, time.gmtime()) + + +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 _proved(handler: Handler, path: str, data: dict) -> bool: + """The entry is the subject its intent names; or holds nothing but that intent, every + step before the bytes recorded: only a removal of its bytes, stopped, leaves that.""" + found = handler.subject(path) + if found is not None or os.path.lexists(os.path.join(path, handler.record)): + return found is not None and handler.same(found, data["subject"]) + return all(_PART.fullmatch(n) for n in _rest(path)) and all(name in data["steps"] for name, _ in handler.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: + for step, act in (*handler.steps, ("bytes", lambda path, data, env: _empty(path, handler.record)), *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" + _empty(path, handler.record) # a killed write of the intent leaves a part + 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 its handler does not read or which is not proved to be its subject is left + whole, its ``reason`` saying which; one failing does not stop the next. ``ondisk.Busy`` + when cleanup is running elsewhere.""" + 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 and (parse(entry) or ("", ""))[1] != only: + continue + state, data = read(handler.kind, entry, env) + path, left = os.path.join(kind_dir, entry), {"done": False, "step": None, "kept": []} + if state == EMPTY: + os.rmdir(path) + found = {**left, "done": True, "reason": ""} + elif state != VALID: + found = {**left, "reason": state} + elif not handler.payload(data["payload"]): + found = {**left, "reason": DAMAGED} + elif not _proved(handler, path, data): + found = {**left, "reason": UNPROVED} + else: + found = _clean(handler, entry, data, env) + out.append({"entry": entry, **found}) + return out diff --git a/app/tests/test_trash.py b/app/tests/test_trash.py index 3d8a1d498..2fc14be6d 100644 --- a/app/tests/test_trash.py +++ b/app/tests/test_trash.py @@ -10,9 +10,63 @@ import unittest from unittest import mock -from nullius import ondisk, paths, trash +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 payload: set(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): @@ -309,3 +363,127 @@ def test_a_collector_lock_that_is_a_link_or_a_pipe_is_refused_at_once(self): 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_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]) From c5d4ccdd80436511c90b9ae2482ac3c8794cfdb5 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 09:45:25 +0100 Subject: [PATCH 3/8] feat(execution): add forget and judgement merge and remove for a holder of the profile lock --- app/nullius/judge/store.py | 26 ++++++++ app/nullius/workspace.py | 24 ++++--- app/tests/test_trash_collect.py | 114 ++++++++++++++++++++++++++++++++ 3 files changed, 153 insertions(+), 11 deletions(-) create mode 100644 app/tests/test_trash_collect.py diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index eead47fc1..814e3df63 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -24,6 +24,7 @@ (``questions.EARLIER``), newest first, so an earlier judgement is still shown, and a write always lands under the version the record names.""" from __future__ import annotations +import errno import hashlib import json import os @@ -97,6 +98,16 @@ def remove(folder: str) -> None: shutil.rmtree(folder, ignore_errors=True) +def remove_held(folder: str, deadline=None) -> None: + """`remove` for a caller that holds the profile lock (`paths.profile_lock`), the folder's own + taken under it: OSError when the folder, or anything of it, is still there.""" + if os.path.isdir(folder): + with ondisk.locked(os.path.join(folder, ".lock"), deadline): + shutil.rmtree(folder) + if os.path.lexists(folder): + raise OSError(errno.ENOTEMPTY, "still there", folder) + + def key(name: str) -> str: """A job id's or trial name's file name: the name itself when every character is safe, else its safe spelling and a digest of the name, so @@ -400,6 +411,21 @@ def _merge_into(path: str, old, job_dir: Optional[str] = None) -> None: ondisk.write_whole(path, json.dumps(got, indent=1), mode=0o600) +def merge_held(path: str, old, deadline=None) -> None: + """`_merge_into` for a caller that holds the profile lock (`paths.profile_lock`), the file's + own taken under it: the file read again, `old` merged in, never written over, then read back. + `Unreadable` when it cannot be read, OSError when what is read back is not what was merged.""" + os.makedirs(os.path.dirname(path), exist_ok=True) + with ondisk.locked(os.path.join(os.path.dirname(path), ".lock"), deadline): + cur = _read([path], strict=True) + got = _with(cur, old) + if got != cur: + _written(os.path.dirname(path)) + ondisk.write_whole(path, json.dumps(got, indent=1), mode=0o600) + if _read([path], strict=True) != got: + raise OSError(errno.EIO, "not read back as merged", path) + + def _raise(e: OSError): raise e diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 0de3d31fd..70187cd67 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -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) @@ -630,14 +631,15 @@ 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``), and nothing is locked here.""" 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] @@ -645,7 +647,7 @@ 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) + _update_index(ws, drop, held) def _under(job_dir: str, roots) -> bool: @@ -888,7 +890,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,7 +898,7 @@ def _update_index(ws: Workspace, change: Callable) -> None: if not _jobs_folder(ws): return try: - with ondisk.locked(_index_path(ws) + ".lock"): + with contextlib.nullcontext() if held else ondisk.locked(_index_path(ws) + ".lock"): index = job_index(ws) before = dict(index) change(index) diff --git a/app/tests/test_trash_collect.py b/app/tests/test_trash_collect.py new file mode 100644 index 000000000..4802986ce --- /dev/null +++ b/app/tests/test_trash_collect.py @@ -0,0 +1,114 @@ +"""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 forms of ``forget``, merge and remove their steps +use under the profile lock.""" +from __future__ import annotations + +import json +import os +import shutil +import tempfile +import threading +import time +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 + +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, + "judged": [os.path.relpath(d, ws.dir) for d in store.job_dirs(ws.dir, [os.path.basename(d) for d in 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)), ([], {})) + + def test_a_merge_reads_the_file_again_and_a_removal_says_what_stays(self): + path = os.path.join(self.data, "judgements", "u1", "t0.json") + store.save(self.data, "u1", "t0", rec("saved")) + store.merge_held(path, [{Q.VERSION: rec("older", "2025-01-01T00:00:00Z")}]) + self.assertEqual(self.shown("u1"), ["older", "saved"]) # merged, never written over + with patch.object(store.ondisk, "write_whole"), self.assertRaisesRegex(OSError, "not read back"): + store.merge_held(path, [{Q.VERSION: rec("lost", "2025-01-02T00:00:00Z")}]) + with patch.object(store.shutil, "rmtree"), self.assertRaisesRegex(OSError, "still there"): + store.remove_held(os.path.dirname(path)) + store.remove_held(os.path.dirname(path)) + store.remove_held(os.path.dirname(path)) # gone already: done + self.assertFalse(os.path.exists(os.path.dirname(path))) + with ondisk.locked(os.path.join(self.data, "judgements", "u2.lock")): + pass + os.makedirs(os.path.join(self.data, "judgements", "u2")) + with ondisk.locked(os.path.join(self.data, "judgements", "u2", ".lock")), self.assertRaises(ondisk.Busy): + store.remove_held(os.path.join(self.data, "judgements", "u2"), time.monotonic()) # its saves' lock, under the deadline + + +if __name__ == "__main__": + unittest.main() From c873fa055ef07d573626918d56c2388a116f9d3e Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 09:45:27 +0100 Subject: [PATCH 4/8] feat(execution): add the cleanup of a workspace's trash entry --- app/nullius/workspace.py | 119 +++++++++++++++++++++++++++++++- app/tests/test_trash_collect.py | 97 ++++++++++++++++++++++++++ 2 files changed, 214 insertions(+), 2 deletions(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 70187cd67..b419f6f69 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 @@ -601,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) @@ -611,6 +611,121 @@ 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 + + +def located(wanted: dict, env=None, live: bool = False) -> list: + """Every folder that is the workspace of identity *wanted* (wherever it is: under its + name, renamed, in the trash) or keeps its judgements once deleted; *live*: those still + in the workspaces folder only. ``trash.Pending`` while a folder that may be it cannot + be told.""" + def told(folder, record, read): + try: + found = read(folder) + except (OSError, ValueError): + found = None + if found is None and os.path.lexists(os.path.join(folder, record)): + raise trash.Pending(f"{folder} cannot be read") + return identity.same_workspace(found, wanted) + + def under(parent): + try: + return [os.path.join(parent(), n) for n in sorted(os.listdir(parent()))] + except FileNotFoundError: + return [] + except trash.Refused as error: + raise trash.Pending(str(error)) from error + found = [f for f in under(lambda: paths.workspaces_dir(env)) if told(f, "workspace.json", identity.workspace)] + if not live: + found += [f for f in under(lambda: trash.folder("workspace", env=env)) if told(f, "workspace.json", identity.workspace)] + found += [f for f in under(lambda: os.path.join(paths.data_dir(env), ARCHIVE)) + if told(f, KEPT_OF, lambda f: ondisk.read_record(os.path.join(f, KEPT_OF)))] + return found + + +def _payload(payload) -> bool: + """A workspace intent's payload: ``prefix``, the folder it had; ``roots``, the folders + its jobs were read from (``walked``) as its Delete found them; ``kept``, what the steps report.""" + return (isinstance(payload, dict) and set(payload) - {"kept"} == {"prefix", "roots"} and _is_path(payload["prefix"]) + and path_list(payload["roots"]) and path_list(payload.get("kept", []))) + + +def _trashed(path: str, data: dict) -> Workspace: + """The deleted workspace as its entry holds it: the roots that were in its own + ``imported/`` named where they are now, the others as they are.""" + was = os.path.join(data["payload"]["prefix"], "imported") + roots = [os.path.join(path, "imported", os.path.relpath(os.path.abspath(r), os.path.abspath(was))) if _inside(r, was) else r + for r in data["payload"]["roots"]] + return Workspace(name=data["name"], label=data["name"], roots=roots, created="", opened="", dir=path) + + +def _own_judgements(path: str, data: dict, env) -> None: + """The records it kept before they were kept by job, merged into the user's store under + the one job its roots hold that owns each: found with nothing held, merged and read + back under the profile lock. Pending while a root cannot be read, or while it holds a + rename that was not finished.""" + from nullius.judge import store + if os.path.lexists(os.path.join(path, "rename.json")): + raise trash.Pending("its rename was not finished") + if not any(os.path.isdir(os.path.join(path, r)) for r in store.ROOTS.values()): + return + ws, into = _trashed(path, data), paths.data_dir(env) + owned = store.owners(ws, into) if all(map(_listable, ws.roots)) else None + if owned is None: + raise trash.Pending(f"a root of {data['name']} cannot be read, so its judgements cannot be kept") + merged: dict = {} + for src, (dest, _) in store.single(owned).items(): + records = store._old(src) + if records: + merged.setdefault(dest, []).append(records) + with ondisk.locked(paths.profile_lock(env), until := ondisk.deadline()): + for dest, old in merged.items(): + store.merge_held(dest, old, until) + + +def _archive(path: str, data: dict, env) -> None: + """Its judgement folders from before, whole, and the failure analyses of its imports, + copied under ``ARCHIVE`` by the entry's own name with the identity they were kept from, + each file read back: a copy stopped part way is taken up again.""" + from nullius.judge import store + from nullius.runs import failure_analysis + files = [os.path.join(d, n) for top in (*store.ROOTS.values(), "imported") if os.path.isdir(os.path.join(path, top)) + for d, _, names in os.walk(os.path.join(path, top), onerror=store._raise) + for n in names if top != "imported" or n.startswith(failure_analysis.FILE)] + if not files: + return + keep = os.path.join(paths.data_dir(env), ARCHIVE, os.path.basename(path)) + kept = {os.path.join(keep, KEPT_OF): json.dumps(data["subject"]).encode()} + for file in files: + with open(file, "rb") as fh: + kept[os.path.join(keep, os.path.relpath(file, path))] = fh.read() + for to, raw in kept.items(): + os.makedirs(os.path.dirname(to), exist_ok=True) + if store._bytes(to) != raw: + ondisk.write_whole(to, raw, mode=0o600) + if store._bytes(to) != raw: + raise trash.Pending(f"{to} is not read back as copied") + + +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 os.path.lexists(marker): + raise trash.Pending(f"{marker} is still there") + + +TRASHED = trash.Handler("workspace", "workspace.json", identity.workspace, identity.same_workspace, _payload, + (("evidence", _own_judgements), ("archive", _archive), ("marker", _unmark))) + + 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] diff --git a/app/tests/test_trash_collect.py b/app/tests/test_trash_collect.py index 4802986ce..0d1038f73 100644 --- a/app/tests/test_trash_collect.py +++ b/app/tests/test_trash_collect.py @@ -110,5 +110,102 @@ def test_a_merge_reads_the_file_again_and_a_removal_says_what_stays(self): store.remove_held(os.path.join(self.data, "judgements", "u2"), time.monotonic()) # its saves' lock, under the deadline +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)) + self.uids = self.uid(self.job), self.uid(self.kept) + 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}") + + def collect(self, **kw): + return trash.collect(workspace.TRASHED, **kw) + + def cleaned(self): + self.assertFalse(os.path.lexists(self.entry)) + self.assertEqual([self.shown(u) for u in self.uids], [["job-a"], ["atif__x"]]) # each under the one job that owns it + kept = tree(self.archive) + 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)) or k in (".", "imported", "imported/atif__x")}) + self.assertEqual(os.listdir(os.path.join(self.data, "judgements", store.MOVED)), []) + self.assertTrue(os.path.isdir(self.job)) # the roots it read are not its own + + def test_it_keeps_its_judgements_archives_them_whole_then_frees_the_bytes(self): + self.assertEqual(self.collect(), [{"entry": f"w.{T2}", "done": True, "step": None, "reason": "", "kept": []}]) + self.cleaned() + + 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, 4) for when in ("before", "after")), (0, "last")): # evidence, 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"] for r in self.collect()], [True]) + self.cleaned() + + def test_a_step_stopped_part_way_is_done_again(self): + stops = ((store, "merge_held", "judgements", 2), (ondisk, "write_whole", workspace.ARCHIVE, 2), (os, "remove", store.MOVED, 1)) + for where, name, at, nth in stops: # the *nth* call on a path holding *at* + with self.subTest(name): + self.world() + real, calls = getattr(where, name), [] + + def stop(path, *args, **kw): # as a kill: nothing after it runs, nothing is recorded + calls.extend([path] if at in path else []) + if at in path and len(calls) == nth: + raise KeyboardInterrupt + return real(path, *args, **kw) + with patch.object(where, name, stop), self.assertRaises(KeyboardInterrupt): + self.collect() + self.assertTrue(os.path.isfile(os.path.join(self.entry, "judgements", "job-gone", TRIAL + ".json"))) # no byte went + self.collect() + self.cleaned() + + def test_its_imports_are_read_where_they_are_now_never_under_its_old_name(self): + other = workspace.create(self.home, [], label="w") # the name is taken again at once + self.assertEqual(other.dir, self.ws.dir) + again = _job_dir(other.imports_dir, "atif__x") + _write_json(os.path.join(again, "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) + self.assertNotEqual(self.uid(again), self.uids[1]) + whole = tree(other.dir) + self.collect() + self.assertEqual((self.shown(self.uids[1]), self.shown(self.uid(again))), (["atif__x"], [])) + self.assertEqual(tree(other.dir), whole) + + def test_a_root_that_cannot_be_read_or_a_rename_not_finished_leaves_it_whole(self): + os.rename(os.path.join(self.root, "r0"), os.path.join(self.root, "away")) + whole = tree(self.entry) + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), + (False, "evidence", "a root of w cannot be read, so its judgements cannot be kept")) + os.rename(os.path.join(self.root, "away"), os.path.join(self.root, "r0")) + _write_json(os.path.join(self.entry, "rename.json"), {"version": 1}) + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), (False, "evidence", "its rename was not finished")) + os.unlink(os.path.join(self.entry, "rename.json")) + 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}) + self.assertFalse(os.path.exists(self.archive)) + self.collect() + self.cleaned() + + 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() From 8a6936fbad150eeabe26575c0691baeafbbc1005 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 09:45:34 +0100 Subject: [PATCH 5/8] feat(execution): add the cleanup of a run's trash entry --- app/nullius/execution.py | 169 +++++++++++++++++- app/nullius/judge/store.py | 39 ++++- app/tests/test_trash_collect.py | 292 ++++++++++++++++++++++++++++++++ 3 files changed, 497 insertions(+), 3 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 5f2284f3c..f9b3a78c5 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -131,11 +131,11 @@ import sys import threading import time -from dataclasses import asdict, dataclass, field +from dataclasses import asdict, dataclass, field, replace 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,168 @@ 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(payload) -> bool: + """A run intent's payload. ``jobs``: per job folder, where it was, its ``uid`` ("" while + pending) and ``source``. ``workspaces``: per workspace that held the run its ``identity``, + the ``roots`` and parsed ``jobs`` to forget, and ``judged``, the folders of its store from + before that those jobs alone own, relative to it. ``host``: the label of the host that has + a copy, or None. ``kept``: what the steps report.""" + def texts(value): + return isinstance(value, list) and all(isinstance(v, str) and v for v in value) + + def older(rel): + lane, _, name = rel.partition("/") + return lane in judgements.ROOTS.values() and name not in ("", ".", "..") and "/" not in name + try: + return (set(payload) - {"kept"} == {"jobs", "workspaces", "host"} and isinstance(payload["jobs"], dict) + and all(os.path.isabs(d) and set(j) == {"uid", "source"} and all(isinstance(v, str) for v in j.values()) + for d, j in payload["jobs"].items()) + and isinstance(payload["workspaces"], list) + and all(set(w) == {"identity", "roots", "jobs", "judged"} and identity.valid_workspace(w["identity"]) + and all(map(texts, (w["roots"], w["jobs"], w["judged"]))) and all(map(older, w["judged"])) + 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): + return False + + +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. Pending while one cannot be told or read, or while a root is there again: a + run made under the name since is not this one.""" + home = paths.workspaces_dir(env) + with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): + for held in data["payload"]["workspaces"]: + for folder in workspace.located(held["identity"], env, live=True): + name = os.path.basename(folder) + + def read(): + try: + ws = workspace.load(home, name) + except (TypeError, ValueError): + ws = None + if ws is None or not workspace.readable(ws): + raise trash.Pending(f"workspace {name} cannot be read") + return ws + ws, back = read(), [r for r in held["roots"] if os.path.exists(r)] + if back: + raise trash.Pending(f"{back[0]} is there again: workspace {name} keeps its roots") + workspace.forget(ws, held["roots"], held["jobs"], held=True) + now = read() + if set(held["roots"]) & {*now.roots, *now.job_roots} or set(held["jobs"]) & set(workspace.job_index(now)): + raise trash.Pending(f"workspace {name} still holds it") + + +def _older_judgements(path: str, data: dict, env) -> None: + """The records a workspace kept for the run's jobs before they were kept by job, handed + over to the user's store (``judgements.hand_over``) from where that workspace is now: + live, renamed, in the trash, or its archive once deleted. Nothing of one that left none. + Pending, the records left whole, while they are in several places.""" + was, jobs = os.path.join(data["origin"]["runs_root"], data["name"]), None + for held in data["payload"]["workspaces"]: + found = workspace.located(held["identity"], env) if held["judged"] else [] + if len(found) > 1: + raise trash.Pending(f"the judgements of one workspace are in several places: {', '.join(found)}") + for base in found: + if jobs is None: # the trashed folders say who owns what + inside = {d: os.path.relpath(d, was) for d in data["payload"]["jobs"]} + if any(rel.split(os.sep)[0] == os.pardir for rel in inside.values()): + raise trash.Pending(trash.DAMAGED) + jobs = [replace(job, uid=j["uid"]) for d, j in data["payload"]["jobs"].items() if j["uid"] + for job in parse.split_agents([parse.parse_job(os.path.join(path, inside[d]))])] + judgements.hand_over(base, jobs, held["judged"], paths.data_dir(env), paths.profile_lock(env), + lambda: workspace.located(held["identity"], env) == [base]) + + +def _seen(home: str, root: str) -> tuple: + """What tells whether a job has a copy, read with nothing held: every workspace's roots + and the runs root *root* as listed, to compare under the locks; the identities of the + jobs found there, "" for one that has none yet; and why a copy may come unseen, or "". + OSError when a workspace or a root cannot be read.""" + held, why = [(ws.dir, workspace.walked(ws)) for ws in workspace.every(home)], "" + for folder, roots in held: + for r in roots: + if not os.path.isdir(r): + raise OSError(f"{r}, a root of workspace {os.path.basename(folder)}, cannot be found") + if all(os.path.commonpath([os.path.realpath(r), os.path.realpath(own)]) != os.path.realpath(own) for own in (root, home)): + why = why or f"{r}, a root of workspace {os.path.basename(folder)}, is written outside this Nullius" + roots = [r for _, roots in held for r in roots] + roots += [j for e in os.scandir(root) if e.is_dir(follow_symlinks=False) and os.path.isdir(j := os.path.join(e.path, "jobs"))] + listed = {r: sorted(os.listdir(r)) for r in dict.fromkeys([root, *roots])} + return (held, listed), {job_uid.strict(d) for d in parse.find_job_dirs(roots, strict=lambda name: True)}, why + + +def _changed(home: str, root: str, seen: tuple) -> str: + """Under the locks: why what ``_seen`` read no longer tells, or "". A workspace or a + listing that changed; a run reserved, alive or unread, that may still write a job.""" + held, listed = seen + try: + if held != [(ws.dir, workspace.walked(ws)) for ws in workspace.every(home)]: + return "a workspace changed during cleanup" + for folder, names in listed.items(): + if sorted(os.listdir(folder)) != names: + return f"{folder} changed during cleanup" + for name in listed[root]: + folder = os.path.join(root, name) + try: + alive = ondisk.read_record(os.path.join(folder, RECORD)).get("state", "preparing") in ALIVE + except (FileNotFoundError, NotADirectoryError): + alive = False + if alive or os.path.lexists(os.path.join(folder, RESERVED)): + return f"{name} may still write its jobs" + except (OSError, ValueError) as error: + return str(error) + return "" + + +def _judgements(path: str, data: dict, env) -> list: + """The judgements of the run's jobs in the user's store removed, read back: those of a + job no copy of which is found. The scan holds nothing and only finds candidates; then, + under the runs root's lock and the profile lock, both held through the removal, what it + read is compared by one listing each, no folder walked. Whenever that does not prove + the jobs are the run's alone before the deadline, they are kept, and why is reported.""" + home, root, into = paths.workspaces_dir(env), data["origin"]["runs_root"], paths.data_dir(env) + uids = {j["uid"] for j in data["payload"]["jobs"].values() if j["uid"]} + if not judgements.job_dirs(into, sorted(uids)): + return [] + try: + seen, found, why = _seen(home, root) + except OSError as e: + return [f"Judgements kept because {e.filename} cannot be read: {e.strerror}" if e.filename else f"Judgements kept because {e}"] + why = why or ("a job has no identity yet" if "" in found else "") + folders = judgements.job_dirs(into, sorted(uids - found)) + if not why and folders: + until, lock = ondisk.deadline(), os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + while True: # the lock a reservation takes (``reserve``), not waited for past the deadline + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= until: + raise ondisk.Busy(root) from None + time.sleep(0.01) + with ondisk.locked(paths.profile_lock(env), until): + why = _changed(home, root, seen) or ("it could not be checked in time" if time.monotonic() >= until else "") + for folder in () if why else folders: + judgements.remove_held(folder, until) + finally: + os.close(lock) + return [f"Judgements kept because {why}"] if why else [] + + +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), ("evidence", _older_judgements), ("judgements", _judgements)), (("host", _host_copy),)) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 814e3df63..45481b807 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -24,6 +24,7 @@ (``questions.EARLIER``), newest first, so an earlier judgement is still shown, and a write always lands under the version the record names.""" from __future__ import annotations +import contextlib import errno import hashlib import json @@ -33,7 +34,7 @@ from types import SimpleNamespace from typing import Optional -from nullius import ondisk, paths +from nullius import ondisk, paths, trash from . import client, questions as Q @@ -626,6 +627,42 @@ def adopt_owned(ws, into: Optional[str] = None, dirs=None) -> Optional[set]: return done +def hand_over(base: str, jobs, folders, into: str, lock: str, still) -> None: + """The older records the deleted `jobs` own in `folders`, relative to `base` (a workspace's + store from before, wherever it is now), merged into the user's store `into`, then those + folders removed. One holding a file that cannot be read, or that not one file of `jobs` + alone owns, stays whole. Read with nothing held; then, under the profile lock `lock`, each + file's own under it: merged and read back (`merge_held`), the folder found as it was read, + and only then removed. `trash.Pending`, that folder left whole, when `still()` no longer + holds under the lock or the folder changed since it was read.""" + read: dict = {} # folder: {older file: (its bytes, its records, the files they belong in)} + for job in jobs: + for src, dest in _places(base, job, into): + if os.path.relpath(os.path.dirname(src), base) in folders: + raw = _bytes(src) + read.setdefault(os.path.dirname(src), {}).setdefault(src, (raw, _old(src, raw), set()))[2].add(dest) + named = lambda folder: [os.path.join(folder, n) for n in _listed(folder) if n.endswith(".json")] + whole = {folder: files for folder, files in read.items() if named(folder) == sorted(files) + and all(records is not None and len(dests) == 1 and None not in dests for _, records, dests in files.values())} + if not whole: + return + with ondisk.locked(lock, until := ondisk.deadline()): + if not still(): + raise trash.Pending(f"{base} changed during cleanup") + for folder, files in whole.items(): + merged: dict = {} + for _, records, dests in files.values(): + if records: + merged.setdefault(*dests, []).append(records) + for dest, old in merged.items(): + merge_held(dest, old, until) + if named(folder) != sorted(files) or any(_bytes(src) != raw for src, (raw, _, _) in files.items()): + raise trash.Pending(f"{folder} changed during cleanup") + shutil.rmtree(folder) + with contextlib.suppress(FileNotFoundError): # read again until a later `move`, as after `forget` + os.remove(_marker(base, into)) + + def records_of(base: str, uids, olds=()) -> int: """How many trial records the jobs `uids` have in the user's store, their older records `olds` (`overlay`s) counted with them, nothing copied.""" diff --git a/app/tests/test_trash_collect.py b/app/tests/test_trash_collect.py index 0d1038f73..d4dece857 100644 --- a/app/tests/test_trash_collect.py +++ b/app/tests/test_trash_collect.py @@ -110,6 +110,298 @@ def test_a_merge_reads_the_file_again_and_a_removal_says_what_stays(self): store.remove_held(os.path.join(self.data, "judgements", "u2"), time.monotonic()) # its saves' lock, under the deadline +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 + for job in ("job-a", "job-b"): + store.save(ws.dir, job, TRIAL, rec(f"{ws.name} {job}", f"2026-01-0{'abc'.index(ws.name) + 1}T00:00:00Z")) + 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 = store.job_dirs(self.data, [self.u]) + self.entry = self.trash_run("r1", host=host, spaces=(self.a, self.b)) + + def collect(self, **kw): + return trash.collect(execution.TRASHED, **kw) + + def twin(self, name="r2"): + """Another run holding a copy of the job: its judgements are not the deleted run's alone.""" + jobs, job = self.run_(name) + self.assertEqual(self.uid(job), self.u) + return jobs + + def cleaned(self, kept=False, 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): + self.assertNotIn(self.job, workspace.job_index(ws)) + self.assertEqual(store.job_dirs(ws.dir, ["job-a"]), []) # handed over + self.assertEqual(len(store.job_dirs(ws.dir, ["job-b"])), 1) # another run's stay + self.assertEqual(len(store.job_dirs(c.dir, ["job-a"])), 1) # c never held the run + self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged if kept else []) + if kept: + self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) # no record lost on the way + + def test_it_detaches_hands_over_removes_then_frees_the_bytes(self): + self.assertEqual(self.collect(), [{"entry": f"r1.{T1}", "done": True, "step": None, "reason": "", "kept": []}]) + self.cleaned() + self.assertEqual(sorted(os.listdir(self.root)), [".trash", "r0"]) + + def test_a_copy_of_a_job_keeps_its_judgements_with_the_older_ones(self): + self.twin() + self.assertEqual(self.collect()[0]["kept"], []) # a copy is found: nothing to explain + self.cleaned(kept=True) + + 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, 4) for when in ("before", "after")), (0, "last")): # detach, evidence, judgements, bytes + for kept in (False, True): + with self.subTest(at=at, when=when, kept=kept): + self.world() + if kept: + self.twin() + self.assertEqual(killed(self.env, "nullius.execution.TRASHED", at, when), 9) + self.assertEqual([r["done"] for r in self.collect()], [True]) + self.cleaned(kept) + + def test_a_step_stopped_part_way_is_done_again(self): + stops = {"detach": (workspace, "_update_index"), "evidence": (store.shutil, "rmtree"), + "judgements": (store, "remove_held"), "judgements, one gone": (store, "remove_held")} + for step, (where, name) in stops.items(): + for kept in (False, True): + with self.subTest(step=step, kept=kept): + self.world() + if kept: + self.twin() + real, calls = getattr(where, name), [] + + def stop(*args, **kw): # as a kill: nothing after it runs, nothing is recorded + calls.append(args) + if step.endswith("one gone") and len(calls) == 1: + return real(*args, **kw) + raise KeyboardInterrupt + with patch.object(where, name, stop): + if kept and step.startswith("judgements"): + self.collect() # nothing of them to remove: not reached + else: + with self.assertRaises(KeyboardInterrupt): + self.collect() + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) + if step == "evidence": # merged, its source not yet removed: no last copy went + self.assertEqual(self.shown(self.u), ["a job-a", "mine"]) + self.assertEqual(len(store.job_dirs(self.a.dir, ["job-a"])), 1) + self.collect() + self.cleaned(kept) + + def test_a_copy_that_appears_after_the_scan_keeps_the_judgements(self): + seen = execution._seen + + def then_a_copy_lands(*args): + try: + return seen(*args) + finally: + self.twin() + with patch.object(execution, "_seen", then_a_copy_lands): + [found] = self.collect() + self.assertEqual((found["done"], found["kept"]), (True, [f"Judgements kept because {self.root} changed during cleanup"])) + self.cleaned(kept=True) + + def test_judgements_are_kept_whenever_the_jobs_are_not_proved_the_runs_alone(self): + def outside(): + away = os.path.join(self.tmp, "elsewhere"); _job_dir(away, "job-z") + workspace.add_roots(self.c, [away]) + return f"{away}, a root of workspace c, is written outside this Nullius" + + def alive(): + self.run_("r5", "job-z", state="running") + return "r5 may still write its jobs" + + def reserved(): + self.run_("r5", "job-z") + open(os.path.join(self.root, "r5", execution.RESERVED), "w").close() + return "r5 may still write its jobs" + + def pending(): + _write_json(os.path.join(self.root, "r5", "jobs", "job-z", "config.json"), {"job_name": "job-z", "agents": []}) # preparing: whose it will be is unknown + return "a job has no identity yet" + + def unread(): + self.c.roots = [self.others, 1]; workspace.save(self.c) # what it holds is unknown + return "workspace c cannot be read" + + def missing(): + shutil.rmtree(os.path.join(self.root, "r0")) + return f"{self.others}, a root of workspace a, cannot be found" + + def late(): + patcher = patch.object(execution, "_changed", lambda *args: time.sleep(0.01) or ""); patcher.start(); self.addCleanup(patcher.stop) + patcher = patch.object(ondisk, "deadline", lambda: time.monotonic() + 0.005); patcher.start(); self.addCleanup(patcher.stop) + return "it could not be checked in time" + for make in (outside, alive, reserved, pending, unread, missing, late): + with self.subTest(make.__name__): + self.world() + why = make() + if make is missing: + self.c.roots = []; workspace.save(self.c) # a alone names it + [found] = self.collect() + self.assertEqual((found["done"], found["kept"]), (True, [f"Judgements kept because {why}"])) + self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) + self.assertFalse(os.path.lexists(self.entry)) # its bytes go all the same + + def test_no_folder_is_walked_or_parsed_under_the_profile_lock(self): + self.twin() + 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(parse, "parse_job", probed(parse.parse_job)), \ + patch.object(parse, "find_job_dirs", probed(parse.find_job_dirs)): + self.assertTrue(self.collect()[0]["done"]) + self.assertEqual((held, {"parse_job", "find_job_dirs"} <= set(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"]), (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), store.job_dirs(self.data, [self.u])), (whole, self.judged)) + 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.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) + + def test_a_workspace_that_cannot_be_told_leaves_the_detach_pending(self): + path = os.path.join(self.c.dir, "workspace.json") + with open(path) as f: + raw = f.read() + with open(path, "w") as f: + f.write("{") # may be one that held the run + [found] = self.collect() + self.assertEqual((found["done"], found["step"], found["reason"]), (False, "detach", f"{self.c.dir} cannot be read")) + self.assertEqual(workspace.load(self.home, "b").roots, [self.jobs]) + with open(path, "w") as f: + f.write(raw) + self.collect() + self.cleaned() + + def test_a_record_saved_or_a_source_changed_meanwhile_is_never_lost(self): + self.twin() + merge, older = store.merge_held, os.path.join(self.a.dir, "judgements", "job-a", TRIAL + ".json") + + def meanwhile(path, old, deadline=None): + if not os.path.exists(os.path.join(self.tmp, "once")): + open(os.path.join(self.tmp, "once"), "w").close() + store.save(self.data, self.u, TRIAL, rec("saved meanwhile", "2026-03-01T00:00:00Z")) # after the copy was read + merge(path, old, deadline) + store.save(self.a.dir, "job-a", TRIAL, rec("changed meanwhile", "2026-03-02T00:00:00Z")) + else: + merge(path, old, deadline) + with patch.object(store, "merge_held", meanwhile): + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "evidence")) + self.assertIn("changed during cleanup", found["reason"]) + with open(older) as f: + self.assertIn("changed meanwhile", f.read()) # left whole + self.assertEqual(self.shown(self.u), ["a job-a", "saved meanwhile"]) + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs"))) # no byte before its evidence + self.collect() + self.assertFalse(os.path.lexists(self.entry)) + self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "changed meanwhile", "saved meanwhile"]) + + def test_a_folder_holding_a_file_that_cannot_be_read_stays_whole(self): + self.twin() + damaged = os.path.join(self.a.dir, "judgements", "job-a", "another-trial.json") + with open(damaged, "w") as f: + f.write("{") + self.assertTrue(self.collect()[0]["done"]) + self.assertEqual(sorted(os.listdir(os.path.dirname(damaged))), [".lock", "another-trial.json", TRIAL + ".json"]) + self.assertEqual(self.shown(self.u), ["b job-a", "mine"]) + + def test_the_older_records_are_found_where_their_workspace_is_now(self): + for where in ("renamed", "trash", "archive", "both"): + with self.subTest(where): + self.world() + self.twin() + with patch.object(store, "hand_over", side_effect=trash.Pending("later")): + self.assertEqual(self.collect()[0]["step"], "evidence") # detached; then its workspace is renamed or deleted + a = workspace.load(self.home, "a") + held = workspace.rename(self.home, a, "elsewhere").dir if where == "renamed" else self.trash_workspace(a) + if where in ("archive", "both"): + with patch.object(trash, "_empty", side_effect=KeyboardInterrupt if where == "both" else trash._empty): + try: + trash.collect(workspace.TRASHED) + except KeyboardInterrupt: # archived, its bytes not yet gone + pass + self.assertEqual(os.path.isdir(held), where == "both") + if where == "both": # in its entry and its archive at once: neither is touched + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "evidence")) + self.assertIn("several places", found["reason"]) + self.assertEqual(self.shown(self.u), ["mine"]) + trash.collect(workspace.TRASHED) + self.assertTrue(self.collect()[0]["done"]) + self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) + if where in ("archive", "both"): + self.assertFalse(os.path.lexists(held)) + held = os.path.join(self.data, workspace.ARCHIVE, os.path.basename(held)) + self.assertEqual(os.listdir(os.path.join(held, "judgements")), ["job-b"]) # removed where they were, the others whole + + 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"]), (False, "host", "The copy of r1 on gpu-1 stays: remove it there.")) + 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", "evidence", "judgements", "bytes"]) + self.cleaned(entry=True) + + 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 From 34486ceba17ac075c7dc1b7a6dd6d34aca91b6b4 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 10:24:21 +0100 Subject: [PATCH 6/8] feat(execution): clean a trash entry only on facts read again under the removal locks --- app/nullius/execution.py | 265 +++++++++++++++++--------- app/nullius/judge/store.py | 63 ++++--- app/nullius/trash.py | 71 ++++--- app/nullius/workspace.py | 184 +++++++++++------- app/tests/test_trash.py | 30 ++- app/tests/test_trash_collect.py | 322 ++++++++++++++++++++++++++------ 6 files changed, 662 insertions(+), 273 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index f9b3a78c5..2702a4ae4 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -2751,116 +2751,193 @@ def _delete(names: List[str], home: str, root: Optional[str], copies, run: Optio # --- cleaning a deleted run ---------------------------------------------------- # Not called yet: Delete does not rename a run into the trash. -def _run_payload(payload) -> bool: - """A run intent's payload. ``jobs``: per job folder, where it was, its ``uid`` ("" while - pending) and ``source``. ``workspaces``: per workspace that held the run its ``identity``, - the ``roots`` and parsed ``jobs`` to forget, and ``judged``, the folders of its store from - before that those jobs alone own, relative to it. ``host``: the label of the host that has - a copy, or None. ``kept``: what the steps report.""" +PUBLISHERS = "._runs.json" # in the user data directory: {"version": 1, "roots": [every runs folder a Nullius of this profile writes under]} + + +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``, the ``roots`` and parsed ``jobs`` to forget, each in + the run's folder, and ``judged``, the folders of its store from before that those jobs + alone own, relative to it. ``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 older(rel): lane, _, name = rel.partition("/") - return lane in judgements.ROOTS.values() and name not in ("", ".", "..") and "/" not in name + return lane in judgements.ROOTS.values() and name not in ("", ".", "..") and "/" not in name and "\0" not in name + + 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(os.path.isabs(d) and set(j) == {"uid", "source"} and all(isinstance(v, str) for v in j.values()) - for d, j in payload["jobs"].items()) + 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", "judged"} and identity.valid_workspace(w["identity"]) and all(map(texts, (w["roots"], w["jobs"], w["judged"]))) and all(map(older, w["judged"])) + 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): + 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: + return workspace.load(os.path.dirname(folder), os.path.basename(folder), strict=True) + except (TypeError, ValueError) as error: + raise trash.Pending(f"workspace {os.path.basename(folder)} cannot be read") from error + + 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. Pending while one cannot be told or read, or while a root is there again: a - run made under the name since is not this one.""" - home = paths.workspaces_dir(env) + no more. Pending while one 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.""" with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): for held in data["payload"]["workspaces"]: - for folder in workspace.located(held["identity"], env, live=True): - name = os.path.basename(folder) - - def read(): - try: - ws = workspace.load(home, name) - except (TypeError, ValueError): - ws = None - if ws is None or not workspace.readable(ws): - raise trash.Pending(f"workspace {name} cannot be read") - return ws - ws, back = read(), [r for r in held["roots"] if os.path.exists(r)] + for folder in workspace.located(held["identity"], env)["live"]: + ws, back = _held_workspace(folder), [r for r in held["roots"] if trash.there(r)] + if ws is None: + raise trash.Pending(f"workspace {os.path.basename(folder)} cannot be read") if back: - raise trash.Pending(f"{back[0]} is there again: workspace {name} keeps its roots") + 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 = read() - if set(held["roots"]) & {*now.roots, *now.job_roots} or set(held["jobs"]) & set(workspace.job_index(now)): - raise trash.Pending(f"workspace {name} still holds it") - - -def _older_judgements(path: str, data: dict, env) -> None: - """The records a workspace kept for the run's jobs before they were kept by job, handed - over to the user's store (``judgements.hand_over``) from where that workspace is now: - live, renamed, in the trash, or its archive once deleted. Nothing of one that left none. - Pending, the records left whole, while they are in several places.""" - was, jobs = os.path.join(data["origin"]["runs_root"], data["name"]), None + now = _held_workspace(folder) + if now is None or set(held["roots"]) & {*now.roots, *now.job_roots} or set(held["jobs"]) & set(workspace.job_index(now)): + raise trash.Pending(f"workspace {ws.name} still holds it") + + +def _older_judgements(path: str, data: dict, env) -> list: + """The records a live workspace kept for the run's jobs before they were kept by job, + handed over to the user's store (``judgements.hand_over``), once no job the workspace + holds now claims them too, which is checked again under the profile lock. Pending, + the records left whole, while such a job is there, or while the workspace is in the + trash: its own cleanup reads that. Once it is deleted its archive keeps them whole, + and they stay there, reported.""" + was, into, jobs, kept = os.path.join(data["origin"]["runs_root"], data["name"]), paths.data_dir(env), None, [] for held in data["payload"]["workspaces"]: - found = workspace.located(held["identity"], env) if held["judged"] else [] - if len(found) > 1: - raise trash.Pending(f"the judgements of one workspace are in several places: {', '.join(found)}") - for base in found: + if not held["judged"]: + continue + found = workspace.located(held["identity"], env) + if found["trash"] or len(found["live"]) > 1: + raise trash.Pending(f"{(found['trash'] or found['live'])[0]} is being cleaned: its judgements are handed over after") + kept += [f"Older judgements of the jobs of {data['name']} stay in {folder}" for folder in found["archive"]] + for base in found["live"]: if jobs is None: # the trashed folders say who owns what - inside = {d: os.path.relpath(d, was) for d in data["payload"]["jobs"]} - if any(rel.split(os.sep)[0] == os.pardir for rel in inside.values()): - raise trash.Pending(trash.DAMAGED) jobs = [replace(job, uid=j["uid"]) for d, j in data["payload"]["jobs"].items() if j["uid"] - for job in parse.split_agents([parse.parse_job(os.path.join(path, inside[d]))])] - judgements.hand_over(base, jobs, held["judged"], paths.data_dir(env), paths.profile_lock(env), - lambda: workspace.located(held["identity"], env) == [base]) + for job in parse.split_agents([parse.parse_job(os.path.join(path, os.path.relpath(d, was)))])] + + def members(): + ws = _held_workspace(base) + return None if ws is None else (ws, [(r, sorted(os.listdir(r))) for r in workspace.walked(ws)]) + seen = members() + owned = None if seen is None else judgements.owners(seen[0], into, names={os.path.basename(d) for d in data["payload"]["jobs"]}) + if owned is None: + raise trash.Pending(f"workspace {os.path.basename(base)} cannot be read") + if any(os.path.relpath(os.path.dirname(src), base) in held["judged"] for src in owned): + raise trash.Pending(f"A job of workspace {os.path.basename(base)} has the name of one of {data['name']}: whose its older judgements are is unknown") + + def still(): + now = workspace.located(held["identity"], env) + return now["live"] == [base] and not now["trash"] and (members() or (None, None))[1] == seen[1] + judgements.hand_over(base, jobs, held["judged"], into, paths.profile_lock(env), still) + return kept + + +def _names(folder: str): + """The names in *folder*, None when it is seen not to be one. OSError when that cannot be told.""" + try: + return sorted(os.listdir(folder)) + except (FileNotFoundError, NotADirectoryError): + return None + + +def _job_facts(folder: str) -> tuple: + """What a job's identity is read from, by inode, size and time: its ``config.json`` and + ``result.json``, None for one seen not to be there.""" + def fact(name): + try: + found = os.stat(os.path.join(folder, name)) + except (FileNotFoundError, NotADirectoryError): + return None + return found.st_ino, found.st_size, found.st_mtime_ns + return fact("config.json"), fact("result.json") def _seen(home: str, root: str) -> tuple: - """What tells whether a job has a copy, read with nothing held: every workspace's roots - and the runs root *root* as listed, to compare under the locks; the identities of the - jobs found there, "" for one that has none yet; and why a copy may come unseen, or "". - OSError when a workspace or a root cannot be read.""" - held, why = [(ws.dir, workspace.walked(ws)) for ws in workspace.every(home)], "" + """What tells whether a job has a copy, read with nothing held, from one listing of + the runs root *root* and of each workspace's roots: all of it, to read again under the + locks (every folder that is or may become a job's, a run's ``jobs`` that is not there + yet included, with ``_job_facts``); the identities of the jobs found, "" for one that + has none yet; and why a copy may come unseen, or "". OSError when a workspace or a + root cannot be read.""" + held, runs, why = [(ws.dir, workspace.walked(ws)) for ws in workspace.every(home)], sorted(os.listdir(root)), "" for folder, roots in held: for r in roots: if not os.path.isdir(r): raise OSError(f"{r}, a root of workspace {os.path.basename(folder)}, cannot be found") if all(os.path.commonpath([os.path.realpath(r), os.path.realpath(own)]) != os.path.realpath(own) for own in (root, home)): why = why or f"{r}, a root of workspace {os.path.basename(folder)}, is written outside this Nullius" - roots = [r for _, roots in held for r in roots] - roots += [j for e in os.scandir(root) if e.is_dir(follow_symlinks=False) and os.path.isdir(j := os.path.join(e.path, "jobs"))] - listed = {r: sorted(os.listdir(r)) for r in dict.fromkeys([root, *roots])} - return (held, listed), {job_uid.strict(d) for d in parse.find_job_dirs(roots, strict=lambda name: True)}, why - - -def _changed(home: str, root: str, seen: tuple) -> str: - """Under the locks: why what ``_seen`` read no longer tells, or "". A workspace or a - listing that changed; a run reserved, alive or unread, that may still write a job.""" - held, listed = seen + listed, jobs, uids = {}, {}, set() + for r in dict.fromkeys([*(r for _, roots in held for r in roots), *(os.path.join(root, n, "jobs") for n in runs)]): + listed[r] = _names(r) + for d in [r, *(os.path.join(r, n) for n in listed[r])] if listed[r] is not None else (): + jobs[d] = _job_facts(d) + job_uid.searched(d) + if parse.looks_like_job_dir(d): + uids.add(job_uid.strict(d)) + return (held, runs, listed, jobs), uids, why + + +def _only_publisher(root: str, env) -> str: + """Why a copy may be written where this cleanup does not look, or "": the profile + records the runs folders its Nullius write under (``PUBLISHERS``), and *root* is the + only one. Not recorded, it cannot be told.""" + try: + said = ondisk.read_record(os.path.join(paths.data_dir(env), PUBLISHERS)) + except (OSError, ValueError): + said = {} + if said.get("version") != 1 or not isinstance(said.get("roots"), list) or root not in said["roots"]: + return "the runs folders of this profile are not recorded, and one may hold a copy" + return "" if said["roots"] == [root] else "another runs folder of this profile may hold a copy" + + +def _changed(home: str, root: str, seen: tuple, env=None) -> str: + """Under the locks: why what ``_seen`` read no longer tells, or "". Another runs folder + of the profile; a workspace, a listing or a job's files that changed; a run reserved, + alive or unread, that may still write a job. Named folders only, none walked.""" + held, runs, listed, jobs = seen try: + if other := _only_publisher(root, env): + return other if held != [(ws.dir, workspace.walked(ws)) for ws in workspace.every(home)]: return "a workspace changed during cleanup" - for folder, names in listed.items(): - if sorted(os.listdir(folder)) != names: + for folder, names in ((root, runs), *listed.items()): + if _names(folder) != names: return f"{folder} changed during cleanup" - for name in listed[root]: + for folder, facts in jobs.items(): + if _job_facts(folder) != facts: + return f"{folder} changed during cleanup" + for name in runs: folder = os.path.join(root, name) try: alive = ondisk.read_record(os.path.join(folder, RECORD)).get("state", "preparing") in ALIVE except (FileNotFoundError, NotADirectoryError): alive = False - if alive or os.path.lexists(os.path.join(folder, RESERVED)): + if alive or trash.there(os.path.join(folder, RESERVED)): return f"{name} may still write its jobs" except (OSError, ValueError) as error: return str(error) @@ -2871,36 +2948,42 @@ def _judgements(path: str, data: dict, env) -> list: """The judgements of the run's jobs in the user's store removed, read back: those of a job no copy of which is found. The scan holds nothing and only finds candidates; then, under the runs root's lock and the profile lock, both held through the removal, what it - read is compared by one listing each, no folder walked. Whenever that does not prove - the jobs are the run's alone before the deadline, they are kept, and why is reported.""" + read is read again, no folder walked, and the folders to remove are listed there. + Whenever that does not prove the jobs are the run's alone before the deadline, they + are kept, and why is reported.""" home, root, into = paths.workspaces_dir(env), data["origin"]["runs_root"], paths.data_dir(env) uids = {j["uid"] for j in data["payload"]["jobs"].values() if j["uid"]} - if not judgements.job_dirs(into, sorted(uids)): + if not uids: return [] + why, found = _only_publisher(root, env), set() try: - seen, found, why = _seen(home, root) + seen, found, more = (None, found, "") if why else _seen(home, root) except OSError as e: - return [f"Judgements kept because {e.filename} cannot be read: {e.strerror}" if e.filename else f"Judgements kept because {e}"] - why = why or ("a job has no identity yet" if "" in found else "") - folders = judgements.job_dirs(into, sorted(uids - found)) - if not why and folders: - until, lock = ondisk.deadline(), os.open(root, os.O_RDONLY | os.O_DIRECTORY) - try: - while True: # the lock a reservation takes (``reserve``), not waited for past the deadline - try: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except BlockingIOError: - if time.monotonic() >= until: - raise ondisk.Busy(root) from None - time.sleep(0.01) - with ondisk.locked(paths.profile_lock(env), until): - why = _changed(home, root, seen) or ("it could not be checked in time" if time.monotonic() >= until else "") - for folder in () if why else folders: - judgements.remove_held(folder, until) - finally: - os.close(lock) - return [f"Judgements kept because {why}"] if why else [] + more = f"{e.filename} cannot be read: {e.strerror}" if e.filename and e.strerror else str(e) + why = why or more or ("a job has no identity yet" if "" in found else "") + if why: # said only of judgements there are + return [f"Judgements kept because {why}"] if judgements.job_dirs(into, sorted(uids)) else [] + until, lock = ondisk.deadline(), os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + while True: # the lock a reservation takes (``reserve``), not waited for past the deadline + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= until: + raise ondisk.Busy(root) from None + time.sleep(0.01) + with ondisk.locked(paths.profile_lock(env), until): + why = _changed(home, root, seen, env) or ("it could not be checked in time" if time.monotonic() >= until else "") + if why: + return [f"Judgements kept because {why}"] if judgements.job_dirs(into, sorted(uids)) else [] + for folder in judgements.job_dirs(into, sorted(uids - found)): + judgements.remove_held(folder, until) + if judgements.job_dirs(into, sorted(uids - found)): + raise trash.Pending("a folder of its judgements is still there") + finally: + os.close(lock) + return [] def _host_copy(path: str, data: dict, env) -> None: diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 45481b807..153c2dc22 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -421,7 +421,7 @@ def merge_held(path: str, old, deadline=None) -> None: cur = _read([path], strict=True) got = _with(cur, old) if got != cur: - _written(os.path.dirname(path)) + _written(os.path.dirname(path), deadline) ondisk.write_whole(path, json.dumps(got, indent=1), mode=0o600) if _read([path], strict=True) != got: raise OSError(errno.EIO, "not read back as merged", path) @@ -629,36 +629,38 @@ def adopt_owned(ws, into: Optional[str] = None, dirs=None) -> Optional[set]: def hand_over(base: str, jobs, folders, into: str, lock: str, still) -> None: """The older records the deleted `jobs` own in `folders`, relative to `base` (a workspace's - store from before, wherever it is now), merged into the user's store `into`, then those - folders removed. One holding a file that cannot be read, or that not one file of `jobs` - alone owns, stays whole. Read with nothing held; then, under the profile lock `lock`, each - file's own under it: merged and read back (`merge_held`), the folder found as it was read, - and only then removed. `trash.Pending`, that folder left whole, when `still()` no longer - holds under the lock or the folder changed since it was read.""" - read: dict = {} # folder: {older file: (its bytes, its records, the files they belong in)} + store from before), merged into the user's store `into`, then removed where they were. + Read with nothing held. Then, under the profile lock `lock`, whatever was read: `still()` + holds, and per folder, its own lock under it, every file in it is one that was read, as it + was read, of one place in the user's store; they are merged and read back (`merge_held`), + those files alone removed, then the folder. `trash.Pending`, the folder left whole, when + `still()` does not hold or the folder holds anything else: a file changed, added, nested, + unreadable or of no single place. A folder gone already was handed over before.""" + read: dict = {} # older file: (its bytes, its records, the files they belong in) for job in jobs: for src, dest in _places(base, job, into): if os.path.relpath(os.path.dirname(src), base) in folders: raw = _bytes(src) - read.setdefault(os.path.dirname(src), {}).setdefault(src, (raw, _old(src, raw), set()))[2].add(dest) - named = lambda folder: [os.path.join(folder, n) for n in _listed(folder) if n.endswith(".json")] - whole = {folder: files for folder, files in read.items() if named(folder) == sorted(files) - and all(records is not None and len(dests) == 1 and None not in dests for _, records, dests in files.values())} - if not whole: - return + read.setdefault(src, (raw, _old(src, raw), set()))[2].add(dest) with ondisk.locked(lock, until := ondisk.deadline()): if not still(): raise trash.Pending(f"{base} changed during cleanup") - for folder, files in whole.items(): - merged: dict = {} - for _, records, dests in files.values(): - if records: - merged.setdefault(*dests, []).append(records) - for dest, old in merged.items(): - merge_held(dest, old, until) - if named(folder) != sorted(files) or any(_bytes(src) != raw for src, (raw, _, _) in files.items()): - raise trash.Pending(f"{folder} changed during cleanup") - shutil.rmtree(folder) + for folder in (os.path.join(base, rel) for rel in folders): + if not trash.there(folder): + continue + with ondisk.locked(os.path.join(folder, ".lock"), until): + files, merged = [os.path.join(folder, n) for n in sorted(os.listdir(folder)) if n != ".lock"], {} + for src in files: + raw, records, dests = read.get(src, (None, None, ())) + if raw is None or records is None or len(dests) != 1 or None in dests or os.path.islink(src) or _bytes(src) != raw: + raise trash.Pending(f"{src} is not a record of the deleted jobs alone, as it was read") + if records: + merged.setdefault(*dests, []).append(records) + for dest, old in merged.items(): + merge_held(dest, old, until) + for src in (*files, os.path.join(folder, ".lock")): + os.unlink(src) + os.rmdir(folder) with contextlib.suppress(FileNotFoundError): # read again until a later `move`, as after `forget` os.remove(_marker(base, into)) @@ -724,15 +726,16 @@ def _lane_list(into: str, which: str) -> Optional[set]: return None -def _note(into: str, which: str, entries: set) -> None: - """`entries` added to the list `which`, under its lock. Best effort: a list that cannot be - read or written is left as it is, and the move stays offered.""" +def _note(into: str, which: str, entries: set, deadline=None) -> None: + """`entries` added to the list `which`, under its lock, not waited for past `deadline`. Best + effort: a list that cannot be read, written or locked in time is left as it is, and the move + stays offered.""" if not entries or entries <= (_lane_list(into, which) or set()): return root = _root(into, "decision") try: os.makedirs(root, exist_ok=True) - with ondisk.locked(os.path.join(root, which + ".lock")): + with ondisk.locked(os.path.join(root, which + ".lock"), deadline): have = _lane_list(into, which) if have is not None: ondisk.write_whole(os.path.join(root, which), "".join(n + "\n" for n in sorted(have | entries)), mode=0o600) @@ -740,7 +743,7 @@ def _note(into: str, which: str, entries: set) -> None: pass -def _written(folder: str) -> None: +def _written(folder: str, deadline=None) -> None: """Before a write into the lane folder `folder`: it noted in `CURRENT` as this version's, with a ``*`` when it held files already, records an earlier identity's may be among.""" into, name = os.path.dirname(os.path.dirname(folder)), os.path.basename(folder) @@ -752,7 +755,7 @@ def _written(folder: str) -> None: held = any(n.endswith(".json") for n in _listed(folder)) except OSError: held = True - _note(into, CURRENT, {entry + "*" if held else entry}) + _note(into, CURRENT, {entry + "*" if held else entry}, deadline) def _lane_entry(into: str, lane: str, name: str) -> str: diff --git a/app/nullius/trash.py b/app/nullius/trash.py index f8da961a0..695d58474 100644 --- a/app/nullius/trash.py +++ b/app/nullius/trash.py @@ -216,7 +216,7 @@ class Handler: record: str # the file that proves the subject subject: Callable # the identity read from an entry's folder same: Callable - payload: Callable # whether a payload is one its steps read + payload: Callable # whether an intent's payload is one its steps read, every path in it its subject's steps: tuple after: tuple = () @@ -225,6 +225,16 @@ 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) @@ -250,13 +260,24 @@ def _empty(path: str, last: str) -> None: 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 _proved(handler: Handler, path: str, data: dict) -> bool: - """The entry is the subject its intent names; or holds nothing but that intent, every - step before the bytes recorded: only a removal of its bytes, stopped, leaves that.""" + """The entry is the subject its intent names; or holds nothing but that intent and + the files a killed write of it left, every step before the bytes recorded: only a + removal of its bytes, stopped, leaves that.""" found = handler.subject(path) - if found is not None or os.path.lexists(os.path.join(path, handler.record)): - return found is not None and handler.same(found, data["subject"]) - return all(_PART.fullmatch(n) for n in _rest(path)) and all(name in data["steps"] for name, _ in handler.steps) + try: + os.lstat(os.path.join(path, handler.record)) + except FileNotFoundError: + return (found is None and all(name in data["steps"] for name, _ in handler.steps) + and all(_PART.fullmatch(n) and stat.S_ISREG(os.lstat(os.path.join(path, n)).st_mode) for n in _rest(path))) + return found is not None and handler.same(found, data["subject"]) def _clean(handler: Handler, entry: str, data: dict, env) -> dict: @@ -287,9 +308,12 @@ 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 its handler does not read or which is not proved to be its subject is left - whole, its ``reason`` saying which; one failing does not stop the next. ``ondisk.Busy`` - when cleanup is running elsewhere.""" + 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: @@ -298,20 +322,23 @@ def collect(handler: Handler, only: str | None = None, env=None) -> list: 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 and (parse(entry) or ("", ""))[1] != only: + if only is not None and (parse(entry) or ("", ""))[1] != only: continue - state, data = read(handler.kind, entry, env) path, left = os.path.join(kind_dir, entry), {"done": False, "step": None, "kept": []} - if state == EMPTY: - os.rmdir(path) - found = {**left, "done": True, "reason": ""} - elif state != VALID: - found = {**left, "reason": state} - elif not handler.payload(data["payload"]): - found = {**left, "reason": DAMAGED} - elif not _proved(handler, path, data): - found = {**left, "reason": UNPROVED} - else: - found = _clean(handler, entry, data, env) + 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 b419f6f69..0cfa1352e 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -618,97 +618,135 @@ def _keep_judgements(ws: Workspace) -> None: KEPT_OF = "identity.json" # in a folder of it: the workspace it was kept from -def located(wanted: dict, env=None, live: bool = False) -> list: - """Every folder that is the workspace of identity *wanted* (wherever it is: under its - name, renamed, in the trash) or keeps its judgements once deleted; *live*: those still - in the workspaces folder only. ``trash.Pending`` while a folder that may be it cannot - be told.""" +def located(wanted: dict, env=None) -> dict: + """Where the workspace of identity *wanted* is: ``live``, its folders in the workspaces + folder, under its name or another; ``trash``, its entries there, each a valid intent of + this profile naming it; ``archive``, the folders that keep its judgements once deleted. + ``trash.Pending`` while a folder that may be it cannot be told, or its trash entry is + not one to act on: only its own cleanup reads that.""" def told(folder, record, read): try: found = read(folder) except (OSError, ValueError): found = None - if found is None and os.path.lexists(os.path.join(folder, record)): + if found is None and trash.there(os.path.join(folder, record)): raise trash.Pending(f"{folder} cannot be read") return identity.same_workspace(found, wanted) def under(parent): try: - return [os.path.join(parent(), n) for n in sorted(os.listdir(parent()))] + return [os.path.join(parent(), n) for n in sorted(os.listdir(parent())) if not n.startswith(".")] except FileNotFoundError: return [] except trash.Refused as error: raise trash.Pending(str(error)) from error - found = [f for f in under(lambda: paths.workspaces_dir(env)) if told(f, "workspace.json", identity.workspace)] - if not live: - found += [f for f in under(lambda: trash.folder("workspace", env=env)) if told(f, "workspace.json", identity.workspace)] - found += [f for f in under(lambda: os.path.join(paths.data_dir(env), ARCHIVE)) - if told(f, KEPT_OF, lambda f: ondisk.read_record(os.path.join(f, KEPT_OF)))] + found = {"live": [f for f in under(lambda: paths.workspaces_dir(env)) if told(f, "workspace.json", identity.workspace)], + "trash": [f for f in under(lambda: trash.folder("workspace", env=env)) if told(f, "workspace.json", identity.workspace)], + "archive": [f for f in under(lambda: os.path.join(paths.data_dir(env), ARCHIVE)) + if told(f, KEPT_OF, lambda f: ondisk.read_record(os.path.join(f, KEPT_OF)))]} + for folder in found["trash"]: + state, data = trash.read("workspace", os.path.basename(folder), env) + if state != trash.VALID or not _payload(data) or not identity.same_workspace(data["subject"], wanted): + raise trash.Pending(f"{folder} is not a trash entry to act on") return found -def _payload(payload) -> bool: - """A workspace intent's payload: ``prefix``, the folder it had; ``roots``, the folders - its jobs were read from (``walked``) as its Delete found them; ``kept``, what the steps report.""" - return (isinstance(payload, dict) and set(payload) - {"kept"} == {"prefix", "roots"} and _is_path(payload["prefix"]) - and path_list(payload["roots"]) and path_list(payload.get("kept", []))) - +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; ``owners``, per file of its store from before, by its path in it, the files + of the user's store its jobs claimed it for then (``store.owners``), by their path there, + None for a job with no identity; ``kept``, what the steps report.""" + from nullius.judge import store + payload = data["payload"] -def _trashed(path: str, data: dict) -> Workspace: - """The deleted workspace as its entry holds it: the roots that were in its own - ``imported/`` named where they are now, the others as they are.""" - was = os.path.join(data["payload"]["prefix"], "imported") - roots = [os.path.join(path, "imported", os.path.relpath(os.path.abspath(r), os.path.abspath(was))) if _inside(r, was) else r - for r in data["payload"]["roots"]] - return Workspace(name=data["name"], label=data["name"], roots=roots, created="", opened="", dir=path) + def within(rel, tops): + parts = rel.split("/") if isinstance(rel, str) else [] + return len(parts) == 3 and parts[0] in tops and parts[2].endswith(".json") and all(p not in ("", ".", "..") and "\0" not in p for p in parts) + try: + return (set(payload) - {"kept"} == {"prefix", "roots", "owners"} + and payload["prefix"] == os.path.join(data["origin"]["workspaces_root"], data["name"]) + and path_list(payload["roots"]) and path_list(payload.get("kept", [])) and isinstance(payload["owners"], dict) + and all(within(src, store.ROOTS.values()) and isinstance(dests, list) and bool(dests) + and all(d is None or within(d, (*store.ROOTS.values(), "judgements-tasks")) for d in dests) + for src, dests in payload["owners"].items())) + except (AttributeError, TypeError): + return False def _own_judgements(path: str, data: dict, env) -> None: - """The records it kept before they were kept by job, merged into the user's store under - the one job its roots hold that owns each: found with nothing held, merged and read - back under the profile lock. Pending while a root cannot be read, or while it holds a - rename that was not finished.""" + """The records it kept before they were kept by job, merged into the user's store where + one job alone claimed each when it was deleted: no folder is read by its name now, a + job made under one since owns none. Read with nothing held, merged and read back under + the profile lock. Pending while a root cannot be read, or while it holds a rename + that was not finished.""" from nullius.judge import store - if os.path.lexists(os.path.join(path, "rename.json")): + if trash.there(os.path.join(path, "rename.json")): raise trash.Pending("its rename was not finished") - if not any(os.path.isdir(os.path.join(path, r)) for r in store.ROOTS.values()): - return - ws, into = _trashed(path, data), paths.data_dir(env) - owned = store.owners(ws, into) if all(map(_listable, ws.roots)) else None - if owned is None: - raise trash.Pending(f"a root of {data['name']} cannot be read, so its judgements cannot be kept") + was, payload = os.path.join(data["payload"]["prefix"], "imported"), data["payload"] + for root in payload["roots"]: # one that was in its own ``imported/`` is read where it is now + if not _listable(os.path.join(path, "imported", os.path.relpath(os.path.abspath(root), os.path.abspath(was))) if _inside(root, was) else root): + raise trash.Pending(f"{root}, a root of {data['name']}, cannot be read, so its judgements cannot be kept") merged: dict = {} - for src, (dest, _) in store.single(owned).items(): - records = store._old(src) + for src, dests in payload["owners"].items(): + records = store._old(os.path.join(path, src)) if len(dests) == 1 and dests[0] else None if records: - merged.setdefault(dest, []).append(records) + merged.setdefault(os.path.join(paths.data_dir(env), dests[0]), []).append(records) with ondisk.locked(paths.profile_lock(env), until := ondisk.deadline()): for dest, old in merged.items(): store.merge_held(dest, old, until) +def _to_keep(path: str) -> list: + """Every file of its judgement folders from before, and the failure analyses of its imports, by their path in it.""" + from nullius.judge import store + from nullius.runs import failure_analysis + return sorted(os.path.relpath(os.path.join(d, n), path) for top in (*store.ROOTS.values(), "imported") if os.path.isdir(os.path.join(path, top)) + for d, _, names in os.walk(os.path.join(path, top), onerror=store._raise) + for n in names if top != "imported" or n.startswith(failure_analysis.FILE)) + + def _archive(path: str, data: dict, env) -> None: """Its judgement folders from before, whole, and the failure analyses of its imports, - copied under ``ARCHIVE`` by the entry's own name with the identity they were kept from, - each file read back: a copy stopped part way is taken up again.""" + kept under ``ARCHIVE`` by the entry's own name, with the identity they were kept from. + Copied with nothing held into a folder of this step's own; then, under the profile + lock a save takes: the entry still that workspace, its files those copied, none more, + the copy given its name by one rename, and those files removed from the entry. A file + changed or added since leaves everything where it is, pending. After a kill, the files + left in the entry go once each is the one archived.""" from nullius.judge import store - from nullius.runs import failure_analysis - files = [os.path.join(d, n) for top in (*store.ROOTS.values(), "imported") if os.path.isdir(os.path.join(path, top)) - for d, _, names in os.walk(os.path.join(path, top), onerror=store._raise) - for n in names if top != "imported" or n.startswith(failure_analysis.FILE)] + 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") + made = trash.there(keep) + if trash.there(staged): + shutil.rmtree(staged) # a copy a kill left: made again + files = _to_keep(path) if not files: return - keep = os.path.join(paths.data_dir(env), ARCHIVE, os.path.basename(path)) - kept = {os.path.join(keep, KEPT_OF): json.dumps(data["subject"]).encode()} - for file in files: - with open(file, "rb") as fh: - kept[os.path.join(keep, os.path.relpath(file, path))] = fh.read() - for to, raw in kept.items(): - os.makedirs(os.path.dirname(to), exist_ok=True) - if store._bytes(to) != raw: - ondisk.write_whole(to, raw, mode=0o600) - if store._bytes(to) != raw: - raise trash.Pending(f"{to} is not read back as copied") + for rel in () if made else (*files, KEPT_OF): + os.makedirs(os.path.dirname(os.path.join(staged, rel)), exist_ok=True) + raw = json.dumps(data["subject"]).encode() if rel == KEPT_OF else store._bytes(os.path.join(path, rel)) + if raw is None: + raise trash.Pending(f"{os.path.join(path, rel)} cannot be read") + ondisk.write_whole(os.path.join(staged, rel), raw, mode=0o600) + copy = keep if made else staged + with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): + now = _to_keep(path) # its own few folders, no root + if not identity.same_workspace(identity.workspace(path), data["subject"]) or (not made and now != files): + raise trash.Pending(f"{path} changed during cleanup") + for rel in now: + raw = store._bytes(os.path.join(path, rel)) + if raw is None or raw != store._bytes(os.path.join(copy, rel)): + raise trash.Pending(f"{os.path.join(path, rel)} changed during cleanup") + if not made: + os.rename(staged, keep) + for rel in now: + os.unlink(os.path.join(path, rel)) + for top in store.ROOTS.values(): # emptied: a folder that is not stays, and the step with it + for folder, _, _ in os.walk(os.path.join(path, top), topdown=False): + os.rmdir(folder) + if _to_keep(path): + raise trash.Pending(f"{path} still holds judgements") def _unmark(path: str, data: dict, env) -> None: @@ -718,7 +756,7 @@ def _unmark(path: str, data: dict, env) -> None: marker = store._marker(path, paths.data_dir(env)) with contextlib.suppress(FileNotFoundError): os.remove(marker) - if os.path.lexists(marker): + if trash.there(marker): raise trash.Pending(f"{marker} is still there") @@ -748,7 +786,8 @@ def holding_all(home_dir: str, folders) -> dict: 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``), and nothing is locked here.""" + 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] @@ -761,8 +800,10 @@ def drop_roots(now): # a field that is no list of p 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) + _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: @@ -771,18 +812,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: diff --git a/app/tests/test_trash.py b/app/tests/test_trash.py index 2fc14be6d..c8355f006 100644 --- a/app/tests/test_trash.py +++ b/app/tests/test_trash.py @@ -27,7 +27,7 @@ def step(path, data, env): # 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 payload: set(payload) <= {"kept"}, +TOY = trash.Handler("run", "run.json", identity.run, identity.same_run, lambda data: set(data["payload"]) <= {"kept"}, (_note("one"), _note("two", fail=True))) KILLED = """ @@ -470,6 +470,34 @@ def test_a_removal_of_bytes_stopped_part_way_is_finished(self): 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() diff --git a/app/tests/test_trash_collect.py b/app/tests/test_trash_collect.py index d4dece857..b2e6f8363 100644 --- a/app/tests/test_trash_collect.py +++ b/app/tests/test_trash_collect.py @@ -42,6 +42,7 @@ def world(self): 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) + _write_json(os.path.join(self.data, execution.PUBLISHERS), {"version": 1, "roots": [self.root]}) # the one runs folder of the profile def run_(self, name, job="job-a", state="done", **record): """A run as it ended, live: its record and one job.""" @@ -65,7 +66,9 @@ def trash_run(self, name, token=T1, host=None, spaces=()): 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)} + owners = {os.path.relpath(src, ws.dir): [os.path.relpath(d, self.data) if isinstance(d, str) else None for d in dests] + for src, dests in store.owners(ws).items()} # who claimed each older file, as its Delete found them + payload = {"prefix": ws.dir, "roots": workspace.walked(ws), "owners": owners} _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)): @@ -109,6 +112,17 @@ def test_a_merge_reads_the_file_again_and_a_removal_says_what_stays(self): with ondisk.locked(os.path.join(self.data, "judgements", "u2", ".lock")), self.assertRaises(ondisk.Busy): store.remove_held(os.path.join(self.data, "judgements", "u2"), time.monotonic()) # its saves' lock, under the deadline + def test_a_merge_does_not_wait_past_its_deadline_for_the_list_of_folders(self): + uid = "6f0f3a52-5c1e-4d39-9a2b-6a4c1f0e7d21" # a folder the list would note + path, start = os.path.join(self.data, "judgements", uid, "t0.json"), time.monotonic() + os.makedirs(os.path.join(self.data, "judgements")) + waited = threading.Thread(target=store.merge_held, args=(path, [{Q.VERSION: rec("older")}], start + 0.1), daemon=True) + with ondisk.locked(os.path.join(self.data, "judgements", store.CURRENT + ".lock")): + waited.start() + waited.join(3) + self.assertFalse(waited.is_alive()) # the note is skipped, the merge made + self.assertEqual((self.shown(uid), time.monotonic() - start < 3), (["older"], True)) + class Run(Case): def world(self, host=None): @@ -185,9 +199,9 @@ def test_a_kill_at_any_write_of_the_intent_is_resumed(self): self.cleaned(kept) def test_a_step_stopped_part_way_is_done_again(self): - stops = {"detach": (workspace, "_update_index"), "evidence": (store.shutil, "rmtree"), - "judgements": (store, "remove_held"), "judgements, one gone": (store, "remove_held")} - for step, (where, name) in stops.items(): + stops = {"detach": (workspace, "_update_index", ""), "evidence": (os, "unlink", os.path.join("ws", "a", "judgements")), + "judgements": (store, "remove_held", ""), "judgements, one gone": (store, "remove_held", "")} + for step, (where, name, at) in stops.items(): for kept in (False, True): with self.subTest(step=step, kept=kept): self.world() @@ -196,8 +210,8 @@ def test_a_step_stopped_part_way_is_done_again(self): real, calls = getattr(where, name), [] def stop(*args, **kw): # as a kill: nothing after it runs, nothing is recorded - calls.append(args) - if step.endswith("one gone") and len(calls) == 1: + calls.extend([args] if at in str(args[0]) else []) + if not calls or step.endswith("one gone") and len(calls) == 1: return real(*args, **kw) raise KeyboardInterrupt with patch.object(where, name, stop): @@ -250,19 +264,26 @@ def unread(): return "workspace c cannot be read" def missing(): - shutil.rmtree(os.path.join(self.root, "r0")) - return f"{self.others}, a root of workspace a, cannot be found" + gone = os.path.join(self.root, "r7", "jobs") + workspace.create(self.home, [gone], label="d") + return f"{gone}, a root of workspace d, cannot be found" + + def unrecorded(): + os.unlink(os.path.join(self.data, execution.PUBLISHERS)) + return "the runs folders of this profile are not recorded, and one may hold a copy" + + def another_ui(): # a second web UI of the profile, on a runs folder of its own + _write_json(os.path.join(self.data, execution.PUBLISHERS), {"version": 1, "roots": [self.root, os.path.join(self.tmp, "runs2")]}) + return "another runs folder of this profile may hold a copy" def late(): patcher = patch.object(execution, "_changed", lambda *args: time.sleep(0.01) or ""); patcher.start(); self.addCleanup(patcher.stop) patcher = patch.object(ondisk, "deadline", lambda: time.monotonic() + 0.005); patcher.start(); self.addCleanup(patcher.stop) return "it could not be checked in time" - for make in (outside, alive, reserved, pending, unread, missing, late): + for make in (outside, alive, reserved, pending, unread, missing, unrecorded, another_ui, late): with self.subTest(make.__name__): self.world() why = make() - if make is missing: - self.c.roots = []; workspace.save(self.c) # a alone names it [found] = self.collect() self.assertEqual((found["done"], found["kept"]), (True, [f"Judgements kept because {why}"])) self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) @@ -323,65 +344,196 @@ def test_a_workspace_that_cannot_be_told_leaves_the_detach_pending(self): def test_a_record_saved_or_a_source_changed_meanwhile_is_never_lost(self): self.twin() - merge, older = store.merge_held, os.path.join(self.a.dir, "judgements", "job-a", TRIAL + ".json") - - def meanwhile(path, old, deadline=None): - if not os.path.exists(os.path.join(self.tmp, "once")): - open(os.path.join(self.tmp, "once"), "w").close() - store.save(self.data, self.u, TRIAL, rec("saved meanwhile", "2026-03-01T00:00:00Z")) # after the copy was read - merge(path, old, deadline) - store.save(self.a.dir, "job-a", TRIAL, rec("changed meanwhile", "2026-03-02T00:00:00Z")) - else: - merge(path, old, deadline) - with patch.object(store, "merge_held", meanwhile): + hand_over, older = store.hand_over, os.path.join(self.a.dir, "judgements", "job-a", TRIAL + ".json") + + def meanwhile(base, jobs, folders, into, lock, still): + def then(): # after the copy was read, before it is merged + if base == self.a.dir and not os.path.exists(os.path.join(self.tmp, "once")): + open(os.path.join(self.tmp, "once"), "w").close() + store.save(self.data, self.u, TRIAL, rec("saved meanwhile", "2026-03-01T00:00:00Z")) + _write_json(older, {Q.VERSION: rec("changed meanwhile", "2026-03-02T00:00:00Z")}) + return still() + return hand_over(base, jobs, folders, into, lock, then) + with patch.object(store, "hand_over", meanwhile): [found] = self.collect() self.assertEqual((found["done"], found["step"]), (False, "evidence")) - self.assertIn("changed during cleanup", found["reason"]) + self.assertIn("as it was read", found["reason"]) with open(older) as f: - self.assertIn("changed meanwhile", f.read()) # left whole - self.assertEqual(self.shown(self.u), ["a job-a", "saved meanwhile"]) + self.assertIn("changed meanwhile", f.read()) # left whole, nothing of it merged + self.assertEqual(self.shown(self.u), ["saved meanwhile"]) self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs"))) # no byte before its evidence self.collect() self.assertFalse(os.path.lexists(self.entry)) - self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "changed meanwhile", "saved meanwhile"]) + self.assertEqual(self.shown(self.u), ["b job-a", "changed meanwhile", "saved meanwhile"]) + + def test_a_folder_holding_more_than_was_read_is_left_whole_and_pending(self): + self.twin() + folder = os.path.join(self.a.dir, "judgements", "job-a") + def text(path, what="{"): + with open(path, "w") as f: + f.write(what) + made = {"damaged.json": text, "note.txt": text, "nested": lambda p: _write_json(os.path.join(p, TRIAL + ".json"), {Q.VERSION: rec("nested")})} + for name, make in made.items(): + with self.subTest(name): + make(os.path.join(folder, name)) + whole = tree(folder) + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "evidence")) + self.assertIn(os.path.join(folder, name), found["reason"]) + self.assertEqual((tree(folder), "a job-a" in self.shown(self.u)), (whole, False)) + shutil.rmtree(os.path.join(folder, name)) if name == "nested" else os.unlink(os.path.join(folder, name)) + self.assertTrue(self.collect()[0]["done"]) + self.cleaned(kept=True) + + def detached(self): + """Its roots gone from the workspaces, its older judgements not yet handed over.""" + with patch.object(store, "hand_over", side_effect=trash.Pending("later")): + self.assertEqual(self.collect()[0]["step"], "evidence") + return workspace.load(self.home, "a") - def test_a_folder_holding_a_file_that_cannot_be_read_stays_whole(self): + def test_a_renamed_workspace_hands_its_older_records_over(self): self.twin() - damaged = os.path.join(self.a.dir, "judgements", "job-a", "another-trial.json") - with open(damaged, "w") as f: - f.write("{") + workspace.rename(self.home, self.detached(), "elsewhere") self.assertTrue(self.collect()[0]["done"]) - self.assertEqual(sorted(os.listdir(os.path.dirname(damaged))), [".lock", "another-trial.json", TRIAL + ".json"]) - self.assertEqual(self.shown(self.u), ["b job-a", "mine"]) + self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) - def test_the_older_records_are_found_where_their_workspace_is_now(self): - for where in ("renamed", "trash", "archive", "both"): - with self.subTest(where): + def test_a_workspace_in_the_trash_is_read_by_its_own_cleanup_alone(self): + for valid in (True, False): + with self.subTest(valid=valid): self.world() self.twin() - with patch.object(store, "hand_over", side_effect=trash.Pending("later")): - self.assertEqual(self.collect()[0]["step"], "evidence") # detached; then its workspace is renamed or deleted - a = workspace.load(self.home, "a") - held = workspace.rename(self.home, a, "elsewhere").dir if where == "renamed" else self.trash_workspace(a) - if where in ("archive", "both"): - with patch.object(trash, "_empty", side_effect=KeyboardInterrupt if where == "both" else trash._empty): - try: - trash.collect(workspace.TRASHED) - except KeyboardInterrupt: # archived, its bytes not yet gone - pass - self.assertEqual(os.path.isdir(held), where == "both") - if where == "both": # in its entry and its archive at once: neither is touched + held = self.trash_workspace(self.detached()) + if not valid: # written by a later Nullius: nobody here acts on it + _write_json(os.path.join(held, trash.INTENT), {**ondisk.read_record(os.path.join(held, trash.INTENT)), "version": 2}) + whole = tree(held) + [found] = self.collect() + self.assertEqual((found["done"], found["step"], tree(held)), (False, "evidence", whole)) + self.assertEqual((self.shown(self.u), trash.collect(workspace.TRASHED)[0]["done"]), (["mine"], valid)) + [found] = self.collect() + self.assertEqual(found["done"], valid) + if valid: # deleted: its archive keeps them whole, unattributed + archive = os.path.join(self.data, workspace.ARCHIVE, os.path.basename(held)) + self.assertEqual(found["kept"], [f"Older judgements of the jobs of r1 stay in {archive}"]) + self.assertEqual(sorted(os.listdir(os.path.join(archive, "judgements"))), ["job-a", "job-b"]) + self.assertEqual(self.shown(self.u), ["b job-a", "mine"]) + + def test_a_job_of_the_same_name_that_joined_since_leaves_the_older_records_where_they_are(self): + self.twin() + a = self.detached() + again = _job_dir(os.path.join(self.root, "r3", "jobs"), "job-a") # the name, another job + _write_json(os.path.join(again, "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) + self.assertNotEqual(self.uid(again), self.u) + workspace.add_roots(a, [os.path.dirname(again)]) + whole = tree(os.path.join(a.dir, "judgements")) + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "evidence")) + self.assertIn("has the name of one of r1", found["reason"]) + self.assertEqual((tree(os.path.join(a.dir, "judgements")), self.shown(self.uid(again))), (whole, [])) + + def test_a_workspace_that_moves_as_it_is_read_is_checked_all_the_same(self): + self.twin() + a, places = self.detached(), store._places + + def moved(base, *args): + if os.path.isdir(self.a.dir): + workspace.rename(self.home, a, "elsewhere") # between its lookup and its read: nothing is found there + return places(base, *args) + with patch.object(store, "_places", moved): + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "evidence")) + self.assertTrue(self.collect()[0]["done"]) + self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) + + def test_what_tells_a_copy_is_read_once_and_read_again_under_the_locks(self): + def first_jobs(): # a run listed without jobs gets its first + shutil.copytree(os.path.join(self.entry, "jobs", "job-a"), os.path.join(self.root, "r3", "jobs", "job-a")) + return f"{os.path.join(self.root, 'r3', 'jobs')} changed during cleanup" + + def in_place(): # a job there becomes another, its folder's name the same + _write_json(os.path.join(self.others, "job-b", "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) + return f"{os.path.join(self.others, 'job-b')} changed during cleanup" + for make in (first_jobs, in_place): + with self.subTest(make.__name__): + self.world() + _write_json(os.path.join(self.root, "r3", execution.RECORD), {"state": "done", "generation": "g3"}) + seen, why = execution._seen, [] + + def then(*args): + try: + return seen(*args) + finally: + why.append(make()) + with patch.object(execution, "_seen", then): [found] = self.collect() - self.assertEqual((found["done"], found["step"]), (False, "evidence")) - self.assertIn("several places", found["reason"]) - self.assertEqual(self.shown(self.u), ["mine"]) - trash.collect(workspace.TRASHED) + self.assertEqual((found["done"], found["kept"]), (True, [f"Judgements kept because {why[0]}"])) + self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) + listed, real = [], os.listdir + with patch.object(os, "listdir", lambda path=".": listed.append(path) or real(path)): + execution._seen(self.home, self.root) + self.assertEqual(listed.count(self.root), 1) # one listing names the runs scanned and those read again + + def test_a_lane_that_appears_under_the_locks_goes_with_the_others(self): + shutil.rmtree(os.path.join(self.data, "judgements-llm")) + changed = execution._changed + + def then(*args): + store.save(self.data, self.u, TRIAL, rec("late"), lane="llm") + return changed(*args) + with patch.object(execution, "_changed", then): + self.assertTrue(self.collect()[0]["done"]) + self.assertEqual(store.job_dirs(self.data, [self.u]), []) + + 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"}}}, + "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 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, 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 refused_parse: + self.assertIn(self.job, workspace.job_index(workspace.load(self.home, "a"))) + repair() + self.assertEqual(workspace.load(self.home, "b").roots, [self.jobs]) + self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) self.assertTrue(self.collect()[0]["done"]) - self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) - if where in ("archive", "both"): - self.assertFalse(os.path.lexists(held)) - held = os.path.join(self.data, workspace.ARCHIVE, os.path.basename(held)) - self.assertEqual(os.listdir(os.path.join(held, "judgements")), ["job-b"]) # removed where they were, the others whole + self.cleaned() def test_a_host_copy_is_never_removed_and_keeps_the_entry_pending(self): self.world(host="gpu-1") @@ -447,7 +599,8 @@ def test_a_kill_at_any_write_of_the_intent_is_resumed(self): self.cleaned() def test_a_step_stopped_part_way_is_done_again(self): - stops = ((store, "merge_held", "judgements", 2), (ondisk, "write_whole", workspace.ARCHIVE, 2), (os, "remove", store.MOVED, 1)) + stops = ((store, "merge_held", "judgements", 2), (ondisk, "write_whole", workspace.ARCHIVE, 2), + (os, "unlink", os.path.join(".trash", "workspace"), 2), (os, "remove", store.MOVED, 1)) for where, name, at, nth in stops: # the *nth* call on a path holding *at* with self.subTest(name): self.world() @@ -460,7 +613,11 @@ def stop(path, *args, **kw): # as a kill: nothing after it return real(path, *args, **kw) with patch.object(where, name, stop), self.assertRaises(KeyboardInterrupt): self.collect() - self.assertTrue(os.path.isfile(os.path.join(self.entry, "judgements", "job-gone", TRIAL + ".json"))) # no byte went + gone = os.path.join("judgements", "job-gone", TRIAL + ".json") + if name != "unlink": # stopped among the removals: some are left + self.assertEqual(os.path.isfile(os.path.join(self.entry, gone)), name in ("merge_held", "write_whole")) + self.assertEqual(os.path.isfile(os.path.join(self.archive, gone)), name in ("unlink", "remove")) # in one or the other, the archive whole or not there + self.assertEqual(workspace.located(self.subject)["archive"], [self.archive] if name in ("unlink", "remove") else []) self.collect() self.cleaned() @@ -480,7 +637,7 @@ def test_a_root_that_cannot_be_read_or_a_rename_not_finished_leaves_it_whole(sel whole = tree(self.entry) [found] = self.collect() self.assertEqual((found["done"], found["step"], found["reason"]), - (False, "evidence", "a root of w cannot be read, so its judgements cannot be kept")) + (False, "evidence", f"{self.jobs}, a root of w, cannot be read, so its judgements cannot be kept")) os.rename(os.path.join(self.root, "away"), os.path.join(self.root, "r0")) _write_json(os.path.join(self.entry, "rename.json"), {"version": 1}) [found] = self.collect() @@ -491,6 +648,53 @@ def test_a_root_that_cannot_be_read_or_a_rename_not_finished_leaves_it_whole(sel self.collect() self.cleaned() + def test_a_verdict_saved_after_the_copy_was_read_is_not_lost(self): + kept, source = workspace._to_keep, os.path.join(self.entry, "judgements", "job-gone", TRIAL + ".json") + added = os.path.join(self.entry, "judgements", "job-late", TRIAL + ".json") + for late in (lambda: _write_json(source, {Q.VERSION: rec("newer")}), lambda: _write_json(added, {Q.VERSION: rec("added")})): + calls = [] + + def then(path): # read with nothing held, then again under the profile lock + calls.append(path) + if len(calls) == 2: + late() + return kept(path) + with patch.object(workspace, "_to_keep", then): + [found] = self.collect() + self.assertEqual((found["done"], found["step"]), (False, "archive")) + self.assertIn("changed during cleanup", found["reason"]) + self.assertEqual((os.path.exists(self.archive), os.path.isfile(source)), (False, True)) # nothing published, nothing removed + self.assertTrue(self.collect()[0]["done"]) + with open(os.path.join(self.archive, "judgements", "job-gone", TRIAL + ".json")) as f: + self.assertIn("newer", f.read()) + self.assertTrue(os.path.isfile(os.path.join(self.archive, "judgements", "job-late", TRIAL + ".json"))) + + def test_a_job_made_since_under_a_name_it_read_owns_none_of_its_records(self): + _write_json(os.path.join(self.job, "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) + self.assertNotEqual(self.uid(self.job), self.uids[0]) # the root it read, the job's name, another job + self.collect() + self.assertEqual((self.shown(self.uids[0]), self.shown(self.uid(self.job))), (["job-a"], [])) + + 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) + bad = {"a later step alone": {"steps": {"archive": intent["written"]}}, + "another folder": {"payload": {**intent["payload"], "prefix": os.path.join(self.home, "other")}}, + "a file outside its store": {"payload": {**intent["payload"], "owners": {"../x/y.json": ["judgements/u/t.json"]}}}, + "a place outside the store": {"payload": {**intent["payload"], "owners": {"judgements/job-a/t.json": ["../u/t.json"]}}}} + for name, change 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": trash.DAMAGED, "kept": []}]) + self.assertEqual((tree(self.entry), os.path.exists(self.archive)), (whole, False)) + + def test_a_root_that_cannot_be_read_holds_it_even_with_no_judgement_folder(self): + for lane in store.ROOTS.values(): + shutil.rmtree(os.path.join(self.entry, lane), True) # only the failure analysis of an import + os.rename(os.path.join(self.root, "r0"), os.path.join(self.root, "away")) + [found] = self.collect() + self.assertEqual((found["done"], found["step"], os.path.exists(self.archive)), (False, "evidence", 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) From c5c5e8ac41722fea8add332c23739b3b3159cb78 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 10:48:39 +0100 Subject: [PATCH 7/8] feat(execution): keep judgements in trash cleanup, archive and detach on verified facts Cleanup never removes judgements nor copies older ones to their jobs: both handlers keep them and report it. The copy scan, the runs registry and the handover are removed. The archive is copied from files set aside under a short profile hold, its identity checked on reuse; a verdict written since holds the bytes. Detach checks each job against its intent, reads the index strictly and holds on a record gone from its folder. --- app/nullius/execution.py | 214 ++---------- app/nullius/judge/store.py | 80 +---- app/nullius/trash.py | 34 +- app/nullius/workspace.py | 211 ++++++------ app/tests/test_trash_collect.py | 556 +++++++++----------------------- 5 files changed, 309 insertions(+), 786 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 2702a4ae4..c80539e96 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -131,7 +131,7 @@ import sys import threading import time -from dataclasses import asdict, dataclass, field, replace +from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from typing import Callable, Dict, List, Optional @@ -2751,15 +2751,11 @@ def _delete(names: List[str], home: str, root: Optional[str], copies, run: Optio # --- cleaning a deleted run ---------------------------------------------------- # Not called yet: Delete does not rename a run into the trash. -PUBLISHERS = "._runs.json" # in the user data directory: {"version": 1, "roots": [every runs folder a Nullius of this profile writes under]} - - 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``, the ``roots`` and parsed ``jobs`` to forget, each in - the run's folder, and ``judged``, the folders of its store from before that those jobs - alone own, relative to it. ``host``: the label of the host that has a copy, or None. + 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"]) @@ -2770,10 +2766,6 @@ def texts(value): def own(path): return isinstance(path, str) and os.path.normpath(path) == path and path.startswith(was + os.sep) - def older(rel): - lane, _, name = rel.partition("/") - return lane in judgements.ROOTS.values() and name not in ("", ".", "..") and "/" not in name and "\0" not in name - def identified(job): if not isinstance(job, dict) or set(job) != {"uid", "source"} or job["uid"] == "": return job == {"uid": "", "source": "pending"} @@ -2782,9 +2774,8 @@ def identified(job): 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", "judged"} and identity.valid_workspace(w["identity"]) - and all(map(texts, (w["roots"], w["jobs"], w["judged"]))) and all(map(older, w["judged"])) - and all(map(own, w["roots"])) and set(w["jobs"]) <= set(payload["jobs"]) + 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", []))) @@ -2796,194 +2787,43 @@ 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: - return workspace.load(os.path.dirname(folder), os.path.basename(folder), strict=True) - except (TypeError, ValueError) as error: - raise trash.Pending(f"workspace {os.path.basename(folder)} cannot be read") from error + 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. Pending while one 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.""" + no more. First, with nothing held, each job in the entry is the one the intent names, + by identity and source. 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)) + if (job_uid.strict(there), parse.parse_job(there, trials=False).uid_source) != (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)["live"]: + for folder in workspace.located(held["identity"], env): ws, back = _held_workspace(folder), [r for r in held["roots"] if trash.there(r)] - if ws is None: - raise trash.Pending(f"workspace {os.path.basename(folder)} cannot be read") 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 now is None or set(held["roots"]) & {*now.roots, *now.job_roots} or set(held["jobs"]) & set(workspace.job_index(now)): + 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 _older_judgements(path: str, data: dict, env) -> list: - """The records a live workspace kept for the run's jobs before they were kept by job, - handed over to the user's store (``judgements.hand_over``), once no job the workspace - holds now claims them too, which is checked again under the profile lock. Pending, - the records left whole, while such a job is there, or while the workspace is in the - trash: its own cleanup reads that. Once it is deleted its archive keeps them whole, - and they stay there, reported.""" - was, into, jobs, kept = os.path.join(data["origin"]["runs_root"], data["name"]), paths.data_dir(env), None, [] - for held in data["payload"]["workspaces"]: - if not held["judged"]: - continue - found = workspace.located(held["identity"], env) - if found["trash"] or len(found["live"]) > 1: - raise trash.Pending(f"{(found['trash'] or found['live'])[0]} is being cleaned: its judgements are handed over after") - kept += [f"Older judgements of the jobs of {data['name']} stay in {folder}" for folder in found["archive"]] - for base in found["live"]: - if jobs is None: # the trashed folders say who owns what - jobs = [replace(job, uid=j["uid"]) for d, j in data["payload"]["jobs"].items() if j["uid"] - for job in parse.split_agents([parse.parse_job(os.path.join(path, os.path.relpath(d, was)))])] - - def members(): - ws = _held_workspace(base) - return None if ws is None else (ws, [(r, sorted(os.listdir(r))) for r in workspace.walked(ws)]) - seen = members() - owned = None if seen is None else judgements.owners(seen[0], into, names={os.path.basename(d) for d in data["payload"]["jobs"]}) - if owned is None: - raise trash.Pending(f"workspace {os.path.basename(base)} cannot be read") - if any(os.path.relpath(os.path.dirname(src), base) in held["judged"] for src in owned): - raise trash.Pending(f"A job of workspace {os.path.basename(base)} has the name of one of {data['name']}: whose its older judgements are is unknown") - - def still(): - now = workspace.located(held["identity"], env) - return now["live"] == [base] and not now["trash"] and (members() or (None, None))[1] == seen[1] - judgements.hand_over(base, jobs, held["judged"], into, paths.profile_lock(env), still) - return kept - - -def _names(folder: str): - """The names in *folder*, None when it is seen not to be one. OSError when that cannot be told.""" - try: - return sorted(os.listdir(folder)) - except (FileNotFoundError, NotADirectoryError): - return None - - -def _job_facts(folder: str) -> tuple: - """What a job's identity is read from, by inode, size and time: its ``config.json`` and - ``result.json``, None for one seen not to be there.""" - def fact(name): - try: - found = os.stat(os.path.join(folder, name)) - except (FileNotFoundError, NotADirectoryError): - return None - return found.st_ino, found.st_size, found.st_mtime_ns - return fact("config.json"), fact("result.json") - - -def _seen(home: str, root: str) -> tuple: - """What tells whether a job has a copy, read with nothing held, from one listing of - the runs root *root* and of each workspace's roots: all of it, to read again under the - locks (every folder that is or may become a job's, a run's ``jobs`` that is not there - yet included, with ``_job_facts``); the identities of the jobs found, "" for one that - has none yet; and why a copy may come unseen, or "". OSError when a workspace or a - root cannot be read.""" - held, runs, why = [(ws.dir, workspace.walked(ws)) for ws in workspace.every(home)], sorted(os.listdir(root)), "" - for folder, roots in held: - for r in roots: - if not os.path.isdir(r): - raise OSError(f"{r}, a root of workspace {os.path.basename(folder)}, cannot be found") - if all(os.path.commonpath([os.path.realpath(r), os.path.realpath(own)]) != os.path.realpath(own) for own in (root, home)): - why = why or f"{r}, a root of workspace {os.path.basename(folder)}, is written outside this Nullius" - listed, jobs, uids = {}, {}, set() - for r in dict.fromkeys([*(r for _, roots in held for r in roots), *(os.path.join(root, n, "jobs") for n in runs)]): - listed[r] = _names(r) - for d in [r, *(os.path.join(r, n) for n in listed[r])] if listed[r] is not None else (): - jobs[d] = _job_facts(d) - job_uid.searched(d) - if parse.looks_like_job_dir(d): - uids.add(job_uid.strict(d)) - return (held, runs, listed, jobs), uids, why - - -def _only_publisher(root: str, env) -> str: - """Why a copy may be written where this cleanup does not look, or "": the profile - records the runs folders its Nullius write under (``PUBLISHERS``), and *root* is the - only one. Not recorded, it cannot be told.""" - try: - said = ondisk.read_record(os.path.join(paths.data_dir(env), PUBLISHERS)) - except (OSError, ValueError): - said = {} - if said.get("version") != 1 or not isinstance(said.get("roots"), list) or root not in said["roots"]: - return "the runs folders of this profile are not recorded, and one may hold a copy" - return "" if said["roots"] == [root] else "another runs folder of this profile may hold a copy" - - -def _changed(home: str, root: str, seen: tuple, env=None) -> str: - """Under the locks: why what ``_seen`` read no longer tells, or "". Another runs folder - of the profile; a workspace, a listing or a job's files that changed; a run reserved, - alive or unread, that may still write a job. Named folders only, none walked.""" - held, runs, listed, jobs = seen - try: - if other := _only_publisher(root, env): - return other - if held != [(ws.dir, workspace.walked(ws)) for ws in workspace.every(home)]: - return "a workspace changed during cleanup" - for folder, names in ((root, runs), *listed.items()): - if _names(folder) != names: - return f"{folder} changed during cleanup" - for folder, facts in jobs.items(): - if _job_facts(folder) != facts: - return f"{folder} changed during cleanup" - for name in runs: - folder = os.path.join(root, name) - try: - alive = ondisk.read_record(os.path.join(folder, RECORD)).get("state", "preparing") in ALIVE - except (FileNotFoundError, NotADirectoryError): - alive = False - if alive or trash.there(os.path.join(folder, RESERVED)): - return f"{name} may still write its jobs" - except (OSError, ValueError) as error: - return str(error) - return "" - - def _judgements(path: str, data: dict, env) -> list: - """The judgements of the run's jobs in the user's store removed, read back: those of a - job no copy of which is found. The scan holds nothing and only finds candidates; then, - under the runs root's lock and the profile lock, both held through the removal, what it - read is read again, no folder walked, and the folders to remove are listed there. - Whenever that does not prove the jobs are the run's alone before the deadline, they - are kept, and why is reported.""" - home, root, into = paths.workspaces_dir(env), data["origin"]["runs_root"], paths.data_dir(env) - uids = {j["uid"] for j in data["payload"]["jobs"].values() if j["uid"]} - if not uids: - return [] - why, found = _only_publisher(root, env), set() - try: - seen, found, more = (None, found, "") if why else _seen(home, root) - except OSError as e: - more = f"{e.filename} cannot be read: {e.strerror}" if e.filename and e.strerror else str(e) - why = why or more or ("a job has no identity yet" if "" in found else "") - if why: # said only of judgements there are - return [f"Judgements kept because {why}"] if judgements.job_dirs(into, sorted(uids)) else [] - until, lock = ondisk.deadline(), os.open(root, os.O_RDONLY | os.O_DIRECTORY) - try: - while True: # the lock a reservation takes (``reserve``), not waited for past the deadline - try: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except BlockingIOError: - if time.monotonic() >= until: - raise ondisk.Busy(root) from None - time.sleep(0.01) - with ondisk.locked(paths.profile_lock(env), until): - why = _changed(home, root, seen, env) or ("it could not be checked in time" if time.monotonic() >= until else "") - if why: - return [f"Judgements kept because {why}"] if judgements.job_dirs(into, sorted(uids)) else [] - for folder in judgements.job_dirs(into, sorted(uids - found)): - judgements.remove_held(folder, until) - if judgements.job_dirs(into, sorted(uids - found)): - raise trash.Pending("a folder of its judgements is still there") - finally: - os.close(lock) - return [] + """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: @@ -2993,4 +2833,4 @@ def _host_copy(path: str, data: dict, env) -> None: TRASHED = trash.Handler("run", RECORD, identity.run, identity.same_run, _run_payload, - (("detach", _detach), ("evidence", _older_judgements), ("judgements", _judgements)), (("host", _host_copy),)) + (("detach", _detach), ("judgements", _judgements)), (("host", _host_copy),)) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 153c2dc22..eead47fc1 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -24,8 +24,6 @@ (``questions.EARLIER``), newest first, so an earlier judgement is still shown, and a write always lands under the version the record names.""" from __future__ import annotations -import contextlib -import errno import hashlib import json import os @@ -34,7 +32,7 @@ from types import SimpleNamespace from typing import Optional -from nullius import ondisk, paths, trash +from nullius import ondisk, paths from . import client, questions as Q @@ -99,16 +97,6 @@ def remove(folder: str) -> None: shutil.rmtree(folder, ignore_errors=True) -def remove_held(folder: str, deadline=None) -> None: - """`remove` for a caller that holds the profile lock (`paths.profile_lock`), the folder's own - taken under it: OSError when the folder, or anything of it, is still there.""" - if os.path.isdir(folder): - with ondisk.locked(os.path.join(folder, ".lock"), deadline): - shutil.rmtree(folder) - if os.path.lexists(folder): - raise OSError(errno.ENOTEMPTY, "still there", folder) - - def key(name: str) -> str: """A job id's or trial name's file name: the name itself when every character is safe, else its safe spelling and a digest of the name, so @@ -412,21 +400,6 @@ def _merge_into(path: str, old, job_dir: Optional[str] = None) -> None: ondisk.write_whole(path, json.dumps(got, indent=1), mode=0o600) -def merge_held(path: str, old, deadline=None) -> None: - """`_merge_into` for a caller that holds the profile lock (`paths.profile_lock`), the file's - own taken under it: the file read again, `old` merged in, never written over, then read back. - `Unreadable` when it cannot be read, OSError when what is read back is not what was merged.""" - os.makedirs(os.path.dirname(path), exist_ok=True) - with ondisk.locked(os.path.join(os.path.dirname(path), ".lock"), deadline): - cur = _read([path], strict=True) - got = _with(cur, old) - if got != cur: - _written(os.path.dirname(path), deadline) - ondisk.write_whole(path, json.dumps(got, indent=1), mode=0o600) - if _read([path], strict=True) != got: - raise OSError(errno.EIO, "not read back as merged", path) - - def _raise(e: OSError): raise e @@ -627,44 +600,6 @@ def adopt_owned(ws, into: Optional[str] = None, dirs=None) -> Optional[set]: return done -def hand_over(base: str, jobs, folders, into: str, lock: str, still) -> None: - """The older records the deleted `jobs` own in `folders`, relative to `base` (a workspace's - store from before), merged into the user's store `into`, then removed where they were. - Read with nothing held. Then, under the profile lock `lock`, whatever was read: `still()` - holds, and per folder, its own lock under it, every file in it is one that was read, as it - was read, of one place in the user's store; they are merged and read back (`merge_held`), - those files alone removed, then the folder. `trash.Pending`, the folder left whole, when - `still()` does not hold or the folder holds anything else: a file changed, added, nested, - unreadable or of no single place. A folder gone already was handed over before.""" - read: dict = {} # older file: (its bytes, its records, the files they belong in) - for job in jobs: - for src, dest in _places(base, job, into): - if os.path.relpath(os.path.dirname(src), base) in folders: - raw = _bytes(src) - read.setdefault(src, (raw, _old(src, raw), set()))[2].add(dest) - with ondisk.locked(lock, until := ondisk.deadline()): - if not still(): - raise trash.Pending(f"{base} changed during cleanup") - for folder in (os.path.join(base, rel) for rel in folders): - if not trash.there(folder): - continue - with ondisk.locked(os.path.join(folder, ".lock"), until): - files, merged = [os.path.join(folder, n) for n in sorted(os.listdir(folder)) if n != ".lock"], {} - for src in files: - raw, records, dests = read.get(src, (None, None, ())) - if raw is None or records is None or len(dests) != 1 or None in dests or os.path.islink(src) or _bytes(src) != raw: - raise trash.Pending(f"{src} is not a record of the deleted jobs alone, as it was read") - if records: - merged.setdefault(*dests, []).append(records) - for dest, old in merged.items(): - merge_held(dest, old, until) - for src in (*files, os.path.join(folder, ".lock")): - os.unlink(src) - os.rmdir(folder) - with contextlib.suppress(FileNotFoundError): # read again until a later `move`, as after `forget` - os.remove(_marker(base, into)) - - def records_of(base: str, uids, olds=()) -> int: """How many trial records the jobs `uids` have in the user's store, their older records `olds` (`overlay`s) counted with them, nothing copied.""" @@ -726,16 +661,15 @@ def _lane_list(into: str, which: str) -> Optional[set]: return None -def _note(into: str, which: str, entries: set, deadline=None) -> None: - """`entries` added to the list `which`, under its lock, not waited for past `deadline`. Best - effort: a list that cannot be read, written or locked in time is left as it is, and the move - stays offered.""" +def _note(into: str, which: str, entries: set) -> None: + """`entries` added to the list `which`, under its lock. Best effort: a list that cannot be + read or written is left as it is, and the move stays offered.""" if not entries or entries <= (_lane_list(into, which) or set()): return root = _root(into, "decision") try: os.makedirs(root, exist_ok=True) - with ondisk.locked(os.path.join(root, which + ".lock"), deadline): + with ondisk.locked(os.path.join(root, which + ".lock")): have = _lane_list(into, which) if have is not None: ondisk.write_whole(os.path.join(root, which), "".join(n + "\n" for n in sorted(have | entries)), mode=0o600) @@ -743,7 +677,7 @@ def _note(into: str, which: str, entries: set, deadline=None) -> None: pass -def _written(folder: str, deadline=None) -> None: +def _written(folder: str) -> None: """Before a write into the lane folder `folder`: it noted in `CURRENT` as this version's, with a ``*`` when it held files already, records an earlier identity's may be among.""" into, name = os.path.dirname(os.path.dirname(folder)), os.path.basename(folder) @@ -755,7 +689,7 @@ def _written(folder: str, deadline=None) -> None: held = any(n.endswith(".json") for n in _listed(folder)) except OSError: held = True - _note(into, CURRENT, {entry + "*" if held else entry}, deadline) + _note(into, CURRENT, {entry + "*" if held else entry}) def _lane_entry(into: str, lane: str, name: str) -> str: diff --git a/app/nullius/trash.py b/app/nullius/trash.py index 695d58474..669331f68 100644 --- a/app/nullius/trash.py +++ b/app/nullius/trash.py @@ -211,7 +211,8 @@ class Handler: 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; ``after`` are steps left to the user.""" + 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 @@ -219,6 +220,7 @@ class Handler: 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: @@ -267,30 +269,38 @@ def _ordered(handler: Handler, data: dict) -> bool: 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; or holds nothing but that intent and - the files a killed write of it left, every step before the bytes recorded: only a - removal of its bytes, stopped, leaves that.""" + """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) - try: - os.lstat(os.path.join(path, handler.record)) - except FileNotFoundError: - return (found is None and all(name in data["steps"] for name, _ in handler.steps) - and all(_PART.fullmatch(n) and stat.S_ISREG(os.lstat(os.path.join(path, n)).st_mode) for n in _rest(path))) - return found is not None and handler.same(found, data["subject"]) + 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: - for step, act in (*handler.steps, ("bytes", lambda path, data, env: _empty(path, handler.record)), *handler.after): + 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" - _empty(path, handler.record) # a killed write of the intent leaves a part + 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} diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 0cfa1352e..410d4c7aa 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -616,137 +616,114 @@ def _keep_judgements(ws: Workspace) -> None: 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) -> dict: - """Where the workspace of identity *wanted* is: ``live``, its folders in the workspaces - folder, under its name or another; ``trash``, its entries there, each a valid intent of - this profile naming it; ``archive``, the folders that keep its judgements once deleted. - ``trash.Pending`` while a folder that may be it cannot be told, or its trash entry is - not one to act on: only its own cleanup reads that.""" - def told(folder, record, read): - try: - found = read(folder) - except (OSError, ValueError): - found = None - if found is None and trash.there(os.path.join(folder, record)): +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.""" + home, found = paths.workspaces_dir(env), [] + try: + names = sorted(os.listdir(home)) + except FileNotFoundError: + return [] + 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") - return identity.same_workspace(found, wanted) - - def under(parent): - try: - return [os.path.join(parent(), n) for n in sorted(os.listdir(parent())) if not n.startswith(".")] - except FileNotFoundError: - return [] - except trash.Refused as error: - raise trash.Pending(str(error)) from error - found = {"live": [f for f in under(lambda: paths.workspaces_dir(env)) if told(f, "workspace.json", identity.workspace)], - "trash": [f for f in under(lambda: trash.folder("workspace", env=env)) if told(f, "workspace.json", identity.workspace)], - "archive": [f for f in under(lambda: os.path.join(paths.data_dir(env), ARCHIVE)) - if told(f, KEPT_OF, lambda f: ondisk.read_record(os.path.join(f, KEPT_OF)))]} - for folder in found["trash"]: - state, data = trash.read("workspace", os.path.basename(folder), env) - if state != trash.VALID or not _payload(data) or not identity.same_workspace(data["subject"], wanted): - raise trash.Pending(f"{folder} is not a trash entry to act on") + 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; ``owners``, per file of its store from before, by its path in it, the files - of the user's store its jobs claimed it for then (``store.owners``), by their path there, - None for a job with no identity; ``kept``, what the steps report.""" - from nullius.judge import store + found them; ``kept``, what the steps report. Its cleanup reads no root: it ends whether + or not they are still there.""" payload = data["payload"] - - def within(rel, tops): - parts = rel.split("/") if isinstance(rel, str) else [] - return len(parts) == 3 and parts[0] in tops and parts[2].endswith(".json") and all(p not in ("", ".", "..") and "\0" not in p for p in parts) - try: - return (set(payload) - {"kept"} == {"prefix", "roots", "owners"} - and payload["prefix"] == os.path.join(data["origin"]["workspaces_root"], data["name"]) - and path_list(payload["roots"]) and path_list(payload.get("kept", [])) and isinstance(payload["owners"], dict) - and all(within(src, store.ROOTS.values()) and isinstance(dests, list) and bool(dests) - and all(d is None or within(d, (*store.ROOTS.values(), "judgements-tasks")) for d in dests) - for src, dests in payload["owners"].items())) - except (AttributeError, TypeError): - return False + 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 _own_judgements(path: str, data: dict, env) -> None: - """The records it kept before they were kept by job, merged into the user's store where - one job alone claimed each when it was deleted: no folder is read by its name now, a - job made under one since owns none. Read with nothing held, merged and read back under - the profile lock. Pending while a root cannot be read, or while it holds a rename - that 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") - was, payload = os.path.join(data["payload"]["prefix"], "imported"), data["payload"] - for root in payload["roots"]: # one that was in its own ``imported/`` is read where it is now - if not _listable(os.path.join(path, "imported", os.path.relpath(os.path.abspath(root), os.path.abspath(was))) if _inside(root, was) else root): - raise trash.Pending(f"{root}, a root of {data['name']}, cannot be read, so its judgements cannot be kept") - merged: dict = {} - for src, dests in payload["owners"].items(): - records = store._old(os.path.join(path, src)) if len(dests) == 1 and dests[0] else None - if records: - merged.setdefault(os.path.join(paths.data_dir(env), dests[0]), []).append(records) - with ondisk.locked(paths.profile_lock(env), until := ondisk.deadline()): - for dest, old in merged.items(): - store.merge_held(dest, old, until) - - -def _to_keep(path: str) -> list: - """Every file of its judgement folders from before, and the failure analyses of its imports, by their path in it.""" +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 - return sorted(os.path.relpath(os.path.join(d, n), path) for top in (*store.ROOTS.values(), "imported") if os.path.isdir(os.path.join(path, top)) - for d, _, names in os.walk(os.path.join(path, top), onerror=store._raise) - for n in names if top != "imported" or n.startswith(failure_analysis.FILE)) + 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 _archive(path: str, data: dict, env) -> None: +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. 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 + 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 _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. - Copied with nothing held into a folder of this step's own; then, under the profile - lock a save takes: the entry still that workspace, its files those copied, none more, - the copy given its name by one rename, and those files removed from the entry. A file - changed or added since leaves everything where it is, pending. After a kill, the files - left in the entry go once each is the one archived.""" + 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 = sorted(os.path.relpath(os.path.join(d, n), aside) for d, _, names in os.walk(aside, onerror=store._raise) for n in names) 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") - made = trash.there(keep) if trash.there(staged): shutil.rmtree(staged) # a copy a kill left: made again - files = _to_keep(path) if not files: - return - for rel in () if made else (*files, KEPT_OF): - os.makedirs(os.path.dirname(os.path.join(staged, rel)), exist_ok=True) - raw = json.dumps(data["subject"]).encode() if rel == KEPT_OF else store._bytes(os.path.join(path, rel)) - if raw is None: - raise trash.Pending(f"{os.path.join(path, rel)} cannot be read") - ondisk.write_whole(os.path.join(staged, rel), raw, mode=0o600) - copy = keep if made else staged - with ondisk.locked(paths.profile_lock(env), ondisk.deadline()): - now = _to_keep(path) # its own few folders, no root - if not identity.same_workspace(identity.workspace(path), data["subject"]) or (not made and now != files): - raise trash.Pending(f"{path} changed during cleanup") - for rel in now: - raw = store._bytes(os.path.join(path, rel)) - if raw is None or raw != store._bytes(os.path.join(copy, rel)): - raise trash.Pending(f"{os.path.join(path, rel)} changed during cleanup") - if not made: - os.rename(staged, keep) - for rel in now: - os.unlink(os.path.join(path, rel)) - for top in store.ROOTS.values(): # emptied: a folder that is not stays, and the step with it - for folder, _, _ in os.walk(os.path.join(path, top), topdown=False): - os.rmdir(folder) - if _to_keep(path): - raise trash.Pending(f"{path} still holds judgements") + 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) + 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(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") + return [UNSUPPORTED] def _unmark(path: str, data: dict, env) -> None: @@ -761,7 +738,7 @@ def _unmark(path: str, data: dict, env) -> None: TRASHED = trash.Handler("workspace", "workspace.json", identity.workspace, identity.same_workspace, _payload, - (("evidence", _own_judgements), ("archive", _archive), ("marker", _unmark))) + (("archive", _archive), ("marker", _unmark)), guard=_new_evidence) def holding(home_dir: str, folder: str) -> list: @@ -972,20 +949,28 @@ 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 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): + 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)} @@ -1058,7 +1043,7 @@ def _update_index(ws: Workspace, change: Callable, held: bool = False) -> None: return try: with contextlib.nullcontext() if held else ondisk.locked(_index_path(ws) + ".lock"): - index = job_index(ws) + index = job_index(ws, strict=held) before = dict(index) change(index) if index != before: diff --git a/app/tests/test_trash_collect.py b/app/tests/test_trash_collect.py index b2e6f8363..51b31844a 100644 --- a/app/tests/test_trash_collect.py +++ b/app/tests/test_trash_collect.py @@ -1,7 +1,6 @@ """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 forms of ``forget``, merge and remove their steps -use under the profile lock.""" +every step and taken up again, and the form of ``forget`` a step uses under the profile lock.""" from __future__ import annotations import json @@ -10,6 +9,7 @@ import tempfile import threading import time +import uuid import unittest from unittest.mock import patch @@ -42,7 +42,6 @@ def world(self): 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) - _write_json(os.path.join(self.data, execution.PUBLISHERS), {"version": 1, "roots": [self.root]}) # the one runs folder of the profile def run_(self, name, job="job-a", state="done", **record): """A run as it ended, live: its record and one job.""" @@ -57,8 +56,7 @@ def trash_run(self, name, token=T1, host=None, spaces=()): 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, - "judged": [os.path.relpath(d, ws.dir) for d in store.job_dirs(ws.dir, [os.path.basename(d) for d in dirs])]} for ws in spaces]} + {"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) @@ -66,9 +64,7 @@ def trash_run(self, name, token=T1, host=None, spaces=()): 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.""" - owners = {os.path.relpath(src, ws.dir): [os.path.relpath(d, self.data) if isinstance(d, str) else None for d in dests] - for src, dests in store.owners(ws).items()} # who claimed each older file, as its Delete found them - payload = {"prefix": ws.dir, "roots": workspace.walked(ws), "owners": owners} + 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)): @@ -94,34 +90,20 @@ def test_forget_under_the_profile_lock_takes_no_lock_of_its_own(self): now = workspace.load(self.home, ws.name) self.assertEqual((now.roots, workspace.job_index(now)), ([], {})) - def test_a_merge_reads_the_file_again_and_a_removal_says_what_stays(self): - path = os.path.join(self.data, "judgements", "u1", "t0.json") - store.save(self.data, "u1", "t0", rec("saved")) - store.merge_held(path, [{Q.VERSION: rec("older", "2025-01-01T00:00:00Z")}]) - self.assertEqual(self.shown("u1"), ["older", "saved"]) # merged, never written over - with patch.object(store.ondisk, "write_whole"), self.assertRaisesRegex(OSError, "not read back"): - store.merge_held(path, [{Q.VERSION: rec("lost", "2025-01-02T00:00:00Z")}]) - with patch.object(store.shutil, "rmtree"), self.assertRaisesRegex(OSError, "still there"): - store.remove_held(os.path.dirname(path)) - store.remove_held(os.path.dirname(path)) - store.remove_held(os.path.dirname(path)) # gone already: done - self.assertFalse(os.path.exists(os.path.dirname(path))) - with ondisk.locked(os.path.join(self.data, "judgements", "u2.lock")): - pass - os.makedirs(os.path.join(self.data, "judgements", "u2")) - with ondisk.locked(os.path.join(self.data, "judgements", "u2", ".lock")), self.assertRaises(ondisk.Busy): - store.remove_held(os.path.join(self.data, "judgements", "u2"), time.monotonic()) # its saves' lock, under the deadline - - def test_a_merge_does_not_wait_past_its_deadline_for_the_list_of_folders(self): - uid = "6f0f3a52-5c1e-4d39-9a2b-6a4c1f0e7d21" # a folder the list would note - path, start = os.path.join(self.data, "judgements", uid, "t0.json"), time.monotonic() - os.makedirs(os.path.join(self.data, "judgements")) - waited = threading.Thread(target=store.merge_held, args=(path, [{Q.VERSION: rec("older")}], start + 0.1), daemon=True) - with ondisk.locked(os.path.join(self.data, "judgements", store.CURRENT + ".lock")): - waited.start() - waited.join(3) - self.assertFalse(waited.is_alive()) # the note is skipped, the merge made - self.assertEqual((self.shown(uid), time.monotonic() - start < 3), (["older"], True)) + +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): @@ -136,47 +118,31 @@ def world(self, host=None): 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 - for job in ("job-a", "job-b"): - store.save(ws.dir, job, TRIAL, rec(f"{ws.name} {job}", f"2026-01-0{'abc'.index(ws.name) + 1}T00:00:00Z")) + 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 = store.job_dirs(self.data, [self.u]) + 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 twin(self, name="r2"): - """Another run holding a copy of the job: its judgements are not the deleted run's alone.""" - jobs, job = self.run_(name) - self.assertEqual(self.uid(job), self.u) - return jobs - - def cleaned(self, kept=False, entry=False): + 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): + for ws in (a, b, c): self.assertNotIn(self.job, workspace.job_index(ws)) - self.assertEqual(store.job_dirs(ws.dir, ["job-a"]), []) # handed over - self.assertEqual(len(store.job_dirs(ws.dir, ["job-b"])), 1) # another run's stay - self.assertEqual(len(store.job_dirs(c.dir, ["job-a"])), 1) # c never held the run - self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged if kept else []) - if kept: - self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) # no record lost on the way - - def test_it_detaches_hands_over_removes_then_frees_the_bytes(self): - self.assertEqual(self.collect(), [{"entry": f"r1.{T1}", "done": True, "step": None, "reason": "", "kept": []}]) + 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_copy_of_a_job_keeps_its_judgements_with_the_older_ones(self): - self.twin() - self.assertEqual(self.collect()[0]["kept"], []) # a copy is found: nothing to explain - self.cleaned(kept=True) - 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) @@ -188,109 +154,22 @@ def test_a_run_saved_before_generations_is_proved_by_its_folder(self): 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, 4) for when in ("before", "after")), (0, "last")): # detach, evidence, judgements, bytes - for kept in (False, True): - with self.subTest(at=at, when=when, kept=kept): - self.world() - if kept: - self.twin() - self.assertEqual(killed(self.env, "nullius.execution.TRASHED", at, when), 9) - self.assertEqual([r["done"] for r in self.collect()], [True]) - self.cleaned(kept) - - def test_a_step_stopped_part_way_is_done_again(self): - stops = {"detach": (workspace, "_update_index", ""), "evidence": (os, "unlink", os.path.join("ws", "a", "judgements")), - "judgements": (store, "remove_held", ""), "judgements, one gone": (store, "remove_held", "")} - for step, (where, name, at) in stops.items(): - for kept in (False, True): - with self.subTest(step=step, kept=kept): - self.world() - if kept: - self.twin() - real, calls = getattr(where, name), [] - - def stop(*args, **kw): # as a kill: nothing after it runs, nothing is recorded - calls.extend([args] if at in str(args[0]) else []) - if not calls or step.endswith("one gone") and len(calls) == 1: - return real(*args, **kw) - raise KeyboardInterrupt - with patch.object(where, name, stop): - if kept and step.startswith("judgements"): - self.collect() # nothing of them to remove: not reached - else: - with self.assertRaises(KeyboardInterrupt): - self.collect() - self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) - if step == "evidence": # merged, its source not yet removed: no last copy went - self.assertEqual(self.shown(self.u), ["a job-a", "mine"]) - self.assertEqual(len(store.job_dirs(self.a.dir, ["job-a"])), 1) - self.collect() - self.cleaned(kept) - - def test_a_copy_that_appears_after_the_scan_keeps_the_judgements(self): - seen = execution._seen - - def then_a_copy_lands(*args): - try: - return seen(*args) - finally: - self.twin() - with patch.object(execution, "_seen", then_a_copy_lands): - [found] = self.collect() - self.assertEqual((found["done"], found["kept"]), (True, [f"Judgements kept because {self.root} changed during cleanup"])) - self.cleaned(kept=True) - - def test_judgements_are_kept_whenever_the_jobs_are_not_proved_the_runs_alone(self): - def outside(): - away = os.path.join(self.tmp, "elsewhere"); _job_dir(away, "job-z") - workspace.add_roots(self.c, [away]) - return f"{away}, a root of workspace c, is written outside this Nullius" - - def alive(): - self.run_("r5", "job-z", state="running") - return "r5 may still write its jobs" - - def reserved(): - self.run_("r5", "job-z") - open(os.path.join(self.root, "r5", execution.RESERVED), "w").close() - return "r5 may still write its jobs" - - def pending(): - _write_json(os.path.join(self.root, "r5", "jobs", "job-z", "config.json"), {"job_name": "job-z", "agents": []}) # preparing: whose it will be is unknown - return "a job has no identity yet" - - def unread(): - self.c.roots = [self.others, 1]; workspace.save(self.c) # what it holds is unknown - return "workspace c cannot be read" - - def missing(): - gone = os.path.join(self.root, "r7", "jobs") - workspace.create(self.home, [gone], label="d") - return f"{gone}, a root of workspace d, cannot be found" - - def unrecorded(): - os.unlink(os.path.join(self.data, execution.PUBLISHERS)) - return "the runs folders of this profile are not recorded, and one may hold a copy" - - def another_ui(): # a second web UI of the profile, on a runs folder of its own - _write_json(os.path.join(self.data, execution.PUBLISHERS), {"version": 1, "roots": [self.root, os.path.join(self.tmp, "runs2")]}) - return "another runs folder of this profile may hold a copy" - - def late(): - patcher = patch.object(execution, "_changed", lambda *args: time.sleep(0.01) or ""); patcher.start(); self.addCleanup(patcher.stop) - patcher = patch.object(ondisk, "deadline", lambda: time.monotonic() + 0.005); patcher.start(); self.addCleanup(patcher.stop) - return "it could not be checked in time" - for make in (outside, alive, reserved, pending, unread, missing, unrecorded, another_ui, late): - with self.subTest(make.__name__): + 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() - why = make() - [found] = self.collect() - self.assertEqual((found["done"], found["kept"]), (True, [f"Judgements kept because {why}"])) - self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) - self.assertFalse(os.path.lexists(self.entry)) # its bytes go all the same + 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): - self.twin() held, seen = [], [] def probed(real): @@ -306,16 +185,16 @@ def call(*args, **kw): with patch.object(os, "walk", probed(os.walk)), patch.object(parse, "parse_job", probed(parse.parse_job)), \ patch.object(parse, "find_job_dirs", probed(parse.find_job_dirs)): self.assertTrue(self.collect()[0]["done"]) - self.assertEqual((held, {"parse_job", "find_job_dirs"} <= set(seen)), ([], True)) + self.assertEqual((held, "parse_job" 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"]), (False, "detach", trash.BUSY)) + 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), store.job_dirs(self.data, [self.u])), (whole, self.judged)) + self.assertEqual(tree(self.home), whole) self.collect() self.cleaned() @@ -325,163 +204,22 @@ def test_a_run_made_under_the_name_since_keeps_its_roots(self): 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.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) - def test_a_workspace_that_cannot_be_told_leaves_the_detach_pending(self): - path = os.path.join(self.c.dir, "workspace.json") - with open(path) as f: - raw = f.read() - with open(path, "w") as f: - f.write("{") # may be one that held the run - [found] = self.collect() - self.assertEqual((found["done"], found["step"], found["reason"]), (False, "detach", f"{self.c.dir} cannot be read")) - self.assertEqual(workspace.load(self.home, "b").roots, [self.jobs]) - with open(path, "w") as f: - f.write(raw) - self.collect() - self.cleaned() - - def test_a_record_saved_or_a_source_changed_meanwhile_is_never_lost(self): - self.twin() - hand_over, older = store.hand_over, os.path.join(self.a.dir, "judgements", "job-a", TRIAL + ".json") - - def meanwhile(base, jobs, folders, into, lock, still): - def then(): # after the copy was read, before it is merged - if base == self.a.dir and not os.path.exists(os.path.join(self.tmp, "once")): - open(os.path.join(self.tmp, "once"), "w").close() - store.save(self.data, self.u, TRIAL, rec("saved meanwhile", "2026-03-01T00:00:00Z")) - _write_json(older, {Q.VERSION: rec("changed meanwhile", "2026-03-02T00:00:00Z")}) - return still() - return hand_over(base, jobs, folders, into, lock, then) - with patch.object(store, "hand_over", meanwhile): - [found] = self.collect() - self.assertEqual((found["done"], found["step"]), (False, "evidence")) - self.assertIn("as it was read", found["reason"]) - with open(older) as f: - self.assertIn("changed meanwhile", f.read()) # left whole, nothing of it merged - self.assertEqual(self.shown(self.u), ["saved meanwhile"]) - self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs"))) # no byte before its evidence - self.collect() - self.assertFalse(os.path.lexists(self.entry)) - self.assertEqual(self.shown(self.u), ["b job-a", "changed meanwhile", "saved meanwhile"]) - - def test_a_folder_holding_more_than_was_read_is_left_whole_and_pending(self): - self.twin() - folder = os.path.join(self.a.dir, "judgements", "job-a") - def text(path, what="{"): - with open(path, "w") as f: - f.write(what) - made = {"damaged.json": text, "note.txt": text, "nested": lambda p: _write_json(os.path.join(p, TRIAL + ".json"), {Q.VERSION: rec("nested")})} - for name, make in made.items(): + 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): - make(os.path.join(folder, name)) - whole = tree(folder) - [found] = self.collect() - self.assertEqual((found["done"], found["step"]), (False, "evidence")) - self.assertIn(os.path.join(folder, name), found["reason"]) - self.assertEqual((tree(folder), "a job-a" in self.shown(self.u)), (whole, False)) - shutil.rmtree(os.path.join(folder, name)) if name == "nested" else os.unlink(os.path.join(folder, name)) - self.assertTrue(self.collect()[0]["done"]) - self.cleaned(kept=True) - - def detached(self): - """Its roots gone from the workspaces, its older judgements not yet handed over.""" - with patch.object(store, "hand_over", side_effect=trash.Pending("later")): - self.assertEqual(self.collect()[0]["step"], "evidence") - return workspace.load(self.home, "a") - - def test_a_renamed_workspace_hands_its_older_records_over(self): - self.twin() - workspace.rename(self.home, self.detached(), "elsewhere") - self.assertTrue(self.collect()[0]["done"]) - self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) - - def test_a_workspace_in_the_trash_is_read_by_its_own_cleanup_alone(self): - for valid in (True, False): - with self.subTest(valid=valid): - self.world() - self.twin() - held = self.trash_workspace(self.detached()) - if not valid: # written by a later Nullius: nobody here acts on it - _write_json(os.path.join(held, trash.INTENT), {**ondisk.read_record(os.path.join(held, trash.INTENT)), "version": 2}) - whole = tree(held) - [found] = self.collect() - self.assertEqual((found["done"], found["step"], tree(held)), (False, "evidence", whole)) - self.assertEqual((self.shown(self.u), trash.collect(workspace.TRASHED)[0]["done"]), (["mine"], valid)) + _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"], valid) - if valid: # deleted: its archive keeps them whole, unattributed - archive = os.path.join(self.data, workspace.ARCHIVE, os.path.basename(held)) - self.assertEqual(found["kept"], [f"Older judgements of the jobs of r1 stay in {archive}"]) - self.assertEqual(sorted(os.listdir(os.path.join(archive, "judgements"))), ["job-a", "job-b"]) - self.assertEqual(self.shown(self.u), ["b job-a", "mine"]) - - def test_a_job_of_the_same_name_that_joined_since_leaves_the_older_records_where_they_are(self): - self.twin() - a = self.detached() - again = _job_dir(os.path.join(self.root, "r3", "jobs"), "job-a") # the name, another job - _write_json(os.path.join(again, "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) - self.assertNotEqual(self.uid(again), self.u) - workspace.add_roots(a, [os.path.dirname(again)]) - whole = tree(os.path.join(a.dir, "judgements")) - [found] = self.collect() - self.assertEqual((found["done"], found["step"]), (False, "evidence")) - self.assertIn("has the name of one of r1", found["reason"]) - self.assertEqual((tree(os.path.join(a.dir, "judgements")), self.shown(self.uid(again))), (whole, [])) - - def test_a_workspace_that_moves_as_it_is_read_is_checked_all_the_same(self): - self.twin() - a, places = self.detached(), store._places - - def moved(base, *args): - if os.path.isdir(self.a.dir): - workspace.rename(self.home, a, "elsewhere") # between its lookup and its read: nothing is found there - return places(base, *args) - with patch.object(store, "_places", moved): - [found] = self.collect() - self.assertEqual((found["done"], found["step"]), (False, "evidence")) - self.assertTrue(self.collect()[0]["done"]) - self.assertEqual(self.shown(self.u), ["a job-a", "b job-a", "mine"]) - - def test_what_tells_a_copy_is_read_once_and_read_again_under_the_locks(self): - def first_jobs(): # a run listed without jobs gets its first - shutil.copytree(os.path.join(self.entry, "jobs", "job-a"), os.path.join(self.root, "r3", "jobs", "job-a")) - return f"{os.path.join(self.root, 'r3', 'jobs')} changed during cleanup" - - def in_place(): # a job there becomes another, its folder's name the same - _write_json(os.path.join(self.others, "job-b", "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) - return f"{os.path.join(self.others, 'job-b')} changed during cleanup" - for make in (first_jobs, in_place): - with self.subTest(make.__name__): - self.world() - _write_json(os.path.join(self.root, "r3", execution.RECORD), {"state": "done", "generation": "g3"}) - seen, why = execution._seen, [] - - def then(*args): - try: - return seen(*args) - finally: - why.append(make()) - with patch.object(execution, "_seen", then): - [found] = self.collect() - self.assertEqual((found["done"], found["kept"]), (True, [f"Judgements kept because {why[0]}"])) - self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) - listed, real = [], os.listdir - with patch.object(os, "listdir", lambda path=".": listed.append(path) or real(path)): - execution._seen(self.home, self.root) - self.assertEqual(listed.count(self.root), 1) # one listing names the runs scanned and those read again - - def test_a_lane_that_appears_under_the_locks_goes_with_the_others(self): - shutil.rmtree(os.path.join(self.data, "judgements-llm")) - changed = execution._changed - - def then(*args): - store.save(self.data, self.u, TRIAL, rec("late"), lane="llm") - return changed(*args) - with patch.object(execution, "_changed", then): - self.assertTrue(self.collect()[0]["done"]) - self.assertEqual(store.job_dirs(self.data, [self.u]), []) + 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_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 @@ -492,6 +230,7 @@ def test_a_payload_that_names_what_is_not_the_run_s_is_not_acted_on(self): "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): @@ -514,10 +253,29 @@ def damaged_state(): 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 damaged_index(): + path = os.path.join(self.a.jobs_dir, "index.json") + os.rename(path, path + ".whole") + with open(path, "w") as f: + f.write("{") + return lambda: os.replace(path + ".whole", path) + 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, refused_parse): + for make in (unsearchable_workspace, unsearchable_run, damaged_state, damaged_record, record_gone_from_its_folder, damaged_index, refused_parse): with self.subTest(make.__name__): self.world() if os.geteuid() == 0 and make.__name__.startswith("unsearchable"): @@ -527,11 +285,13 @@ def refused_parse(): 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 refused_parse: - self.assertIn(self.job, workspace.job_index(workspace.load(self.home, "a"))) + if make is damaged_index: + self.assertEqual(os.path.getsize(os.path.join(self.a.jobs_dir, "index.json")), 1) repair() + if make in (refused_parse, damaged_index): + self.assertIn(self.job, workspace.job_index(workspace.load(self.home, "a"))) self.assertEqual(workspace.load(self.home, "b").roots, [self.jobs]) - self.assertEqual(store.job_dirs(self.data, [self.u]), self.judged) + self.assertTrue(os.path.isdir(os.path.join(self.entry, "jobs", "job-a"))) self.assertTrue(self.collect()[0]["done"]) self.cleaned() @@ -540,11 +300,15 @@ def test_a_host_copy_is_never_removed_and_keeps_the_entry_pending(self): 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"]), (False, "host", "The copy of r1 on gpu-1 stays: remove it there.")) + 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", "evidence", "judgements", "bytes"]) + 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) @@ -566,135 +330,125 @@ def world(self): 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)) - self.uids = self.uid(self.job), self.uid(self.kept) 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)) - self.assertEqual([self.shown(u) for u in self.uids], [["job-a"], ["atif__x"]]) # each under the one job that owns it - kept = tree(self.archive) + kept = {k: v for k, v in tree(self.archive).items() if os.path.isfile(os.path.join(self.archive, k))} 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)) or k in (".", "imported", "imported/atif__x")}) + self.assertEqual(kept, {k: v for k, v in self.before.items() + if k.startswith(("judgements", analysis)) and os.path.isfile(os.path.join(self.archive, k))}) + self.assertIn(self.gone, 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.assertTrue(os.path.isdir(self.job)) # the roots it read are not its own + self.assertFalse(os.path.exists(os.path.join(self.data, workspace.ARCHIVE, f".w.{T2}.staged"))) - def test_it_keeps_its_judgements_archives_them_whole_then_frees_the_bytes(self): - self.assertEqual(self.collect(), [{"entry": f"w.{T2}", "done": True, "step": None, "reason": "", "kept": []}]) + 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, 4) for when in ("before", "after")), (0, "last")): # evidence, archive, marker, bytes + 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"] for r in self.collect()], [True]) + 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 = ((store, "merge_held", "judgements", 2), (ondisk, "write_whole", workspace.ARCHIVE, 2), - (os, "unlink", os.path.join(".trash", "workspace"), 2), (os, "remove", store.MOVED, 1)) - for where, name, at, nth in stops: # the *nth* call on a path holding *at* - with self.subTest(name): + 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() - real, calls = getattr(where, name), [] - - def stop(path, *args, **kw): # as a kill: nothing after it runs, nothing is recorded - calls.extend([path] if at in path else []) - if at in path and len(calls) == nth: - raise KeyboardInterrupt - return real(path, *args, **kw) - with patch.object(where, name, stop), self.assertRaises(KeyboardInterrupt): + with stopped(where, name, at, nth), self.assertRaises(KeyboardInterrupt): self.collect() - gone = os.path.join("judgements", "job-gone", TRIAL + ".json") - if name != "unlink": # stopped among the removals: some are left - self.assertEqual(os.path.isfile(os.path.join(self.entry, gone)), name in ("merge_held", "write_whole")) - self.assertEqual(os.path.isfile(os.path.join(self.archive, gone)), name in ("unlink", "remove")) # in one or the other, the archive whole or not there - self.assertEqual(workspace.located(self.subject)["archive"], [self.archive] if name in ("unlink", "remove") else []) + 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_its_imports_are_read_where_they_are_now_never_under_its_old_name(self): - other = workspace.create(self.home, [], label="w") # the name is taken again at once + 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_a_name_taken_again_is_another_workspace(self): + other = workspace.create(self.home, [], label="w") self.assertEqual(other.dir, self.ws.dir) - again = _job_dir(other.imports_dir, "atif__x") - _write_json(os.path.join(again, "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) - self.assertNotEqual(self.uid(again), self.uids[1]) + store.save(other.dir, "job-a", TRIAL, rec("its own")) whole = tree(other.dir) self.collect() - self.assertEqual((self.shown(self.uids[1]), self.shown(self.uid(again))), (["atif__x"], [])) self.assertEqual(tree(other.dir), whole) + self.cleaned() - def test_a_root_that_cannot_be_read_or_a_rename_not_finished_leaves_it_whole(self): - os.rename(os.path.join(self.root, "r0"), os.path.join(self.root, "away")) - whole = tree(self.entry) - [found] = self.collect() - self.assertEqual((found["done"], found["step"], found["reason"]), - (False, "evidence", f"{self.jobs}, a root of w, cannot be read, so its judgements cannot be kept")) - os.rename(os.path.join(self.root, "away"), os.path.join(self.root, "r0")) + 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, "evidence", "its rename was not finished")) - os.unlink(os.path.join(self.entry, "rename.json")) + 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}) - self.assertFalse(os.path.exists(self.archive)) + os.unlink(os.path.join(self.entry, "rename.json")) self.collect() self.cleaned() - def test_a_verdict_saved_after_the_copy_was_read_is_not_lost(self): - kept, source = workspace._to_keep, os.path.join(self.entry, "judgements", "job-gone", TRIAL + ".json") - added = os.path.join(self.entry, "judgements", "job-late", TRIAL + ".json") - for late in (lambda: _write_json(source, {Q.VERSION: rec("newer")}), lambda: _write_json(added, {Q.VERSION: rec("added")})): - calls = [] - - def then(path): # read with nothing held, then again under the profile lock - calls.append(path) - if len(calls) == 2: - late() - return kept(path) - with patch.object(workspace, "_to_keep", then): - [found] = self.collect() - self.assertEqual((found["done"], found["step"]), (False, "archive")) - self.assertIn("changed during cleanup", found["reason"]) - self.assertEqual((os.path.exists(self.archive), os.path.isfile(source)), (False, True)) # nothing published, nothing removed + 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"]) - with open(os.path.join(self.archive, "judgements", "job-gone", TRIAL + ".json")) as f: - self.assertIn("newer", f.read()) - self.assertTrue(os.path.isfile(os.path.join(self.archive, "judgements", "job-late", TRIAL + ".json"))) + self.cleaned() - def test_a_job_made_since_under_a_name_it_read_owns_none_of_its_records(self): - _write_json(os.path.join(self.job, "config.json"), {"job_name": "another", "agents": [{"name": "b", "model_name": "m"}]}) - self.assertNotEqual(self.uid(self.job), self.uids[0]) # the root it read, the job's name, another job + 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.assertEqual((self.shown(self.uids[0]), self.shown(self.uid(self.job))), (["job-a"], [])) + 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) - bad = {"a later step alone": {"steps": {"archive": intent["written"]}}, - "another folder": {"payload": {**intent["payload"], "prefix": os.path.join(self.home, "other")}}, - "a file outside its store": {"payload": {**intent["payload"], "owners": {"../x/y.json": ["judgements/u/t.json"]}}}, - "a place outside the store": {"payload": {**intent["payload"], "owners": {"judgements/job-a/t.json": ["../u/t.json"]}}}} - for name, change in bad.items(): + 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": trash.DAMAGED, "kept": []}]) + 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_root_that_cannot_be_read_holds_it_even_with_no_judgement_folder(self): - for lane in store.ROOTS.values(): - shutil.rmtree(os.path.join(self.entry, lane), True) # only the failure analysis of an import - os.rename(os.path.join(self.root, "r0"), os.path.join(self.root, "away")) - [found] = self.collect() - self.assertEqual((found["done"], found["step"], os.path.exists(self.archive)), (False, "evidence", 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) From c3fe4aeb2df893695380b98b465bf92193991f50 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Fri, 4 Dec 2026 11:21:19 +0100 Subject: [PATCH 8/8] feat(execution): hold trash cleanup on a job, index or archive that cannot be told A workspace with nothing set aside ends. Its archive is read again before the bytes go. Detach requires each job folder, reads its identity and source once, rejects malformed index rows and versions, and waits for a workspaces folder that is not there. --- app/nullius/execution.py | 10 +++-- app/nullius/runs/uid.py | 7 ++- app/nullius/workspace.py | 60 +++++++++++++++++-------- app/tests/test_trash_collect.py | 79 ++++++++++++++++++++++++++++----- 4 files changed, 123 insertions(+), 33 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index c80539e96..484bc99e1 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -2798,14 +2798,18 @@ def _held_workspace(folder: str): 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 the one the intent names, - by identity and source. Pending while that, a workspace or its index cannot be told + 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)) - if (job_uid.strict(there), parse.parse_job(there, trials=False).uid_source) != (job["uid"], job["source"]): + 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"]: 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/workspace.py b/app/nullius/workspace.py index 410d4c7aa..3d22f10f7 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -623,12 +623,13 @@ def _keep_judgements(ws: Workspace) -> None: 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.""" + 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: - return [] + 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"])): @@ -660,11 +661,14 @@ 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. Pending otherwise. Nothing to tell once its - record went: a removal stopped part way left parts alone.""" + 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))] @@ -674,6 +678,33 @@ def _new_evidence(path: str, data: dict, env) -> None: 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; @@ -698,7 +729,7 @@ def _archive(path: str, data: dict, env) -> list: 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 = sorted(os.path.relpath(os.path.join(d, n), aside) for d, _, names in os.walk(aside, onerror=store._raise) for n in names) + 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): @@ -713,16 +744,7 @@ def _archive(path: str, data: dict, env) -> list: 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) - 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(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") + _archived(path, data, env) return [UNSUPPORTED] @@ -956,7 +978,8 @@ def job_index(ws: Workspace, strict: bool = False) -> dict: 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. *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 is a ValueError.""" + 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) @@ -967,8 +990,9 @@ def job_index(ws: Workspace, strict: bool = False) -> dict: 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 {} diff --git a/app/tests/test_trash_collect.py b/app/tests/test_trash_collect.py index 51b31844a..298893b41 100644 --- a/app/tests/test_trash_collect.py +++ b/app/tests/test_trash_collect.py @@ -15,7 +15,7 @@ from nullius import execution, identity, ondisk, paths, trash, workspace from nullius.judge import questions as Q, store -from nullius.runs import failure_analysis, parse +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 @@ -182,10 +182,10 @@ def call(*args, **kw): held.append(real.__name__) return real(*args, **kw) return call - with patch.object(os, "walk", probed(os.walk)), patch.object(parse, "parse_job", probed(parse.parse_job)), \ + 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, "parse_job" in seen), ([], True)) + 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) @@ -221,6 +221,34 @@ def test_a_job_that_is_not_the_one_its_intent_names_holds_the_detach(self): 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]) @@ -265,17 +293,27 @@ def record_gone_from_its_folder(): # put back, it would os.rename(path, os.path.join(self.tmp, "kept.json")) return lambda: os.rename(os.path.join(self.tmp, "kept.json"), path) - def damaged_index(): + 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("{") + 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, refused_parse): + 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"): @@ -288,7 +326,7 @@ def refused_parse(): if make is damaged_index: self.assertEqual(os.path.getsize(os.path.join(self.a.jobs_dir, "index.json")), 1) repair() - if make in (refused_parse, damaged_index): + 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"))) @@ -342,12 +380,11 @@ def collect(self, **kw): def cleaned(self): self.assertFalse(os.path.lexists(self.entry)) - kept = {k: v for k, v in tree(self.archive).items() if os.path.isfile(os.path.join(self.archive, k))} + 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 os.path.isfile(os.path.join(self.archive, k))}) - self.assertIn(self.gone, kept) + 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"))) @@ -383,6 +420,26 @@ def test_it_ends_whether_or_not_the_roots_it_read_are_still_there(self): 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)