From 95b8cb612be4b82eac837b052c0fd710203959ef Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 3 Dec 2026 18:32:16 +0100 Subject: [PATCH] fix(judge): move judgements kept under a job's identity from before #793 when asked Closes #794 --- app/nullius/judge/store.py | 276 ++++++++++++++++++++- app/nullius/runs/uid.py | 18 +- app/nullius/workspace.py | 14 +- app/static/judgements-move.js | 7 +- app/templates/base.html | 2 +- app/templates/settings/settings.html | 2 +- app/tests/test_judge_adopt.py | 185 +++++++++++++- app/ui_tests/test_judgement_follows_job.py | 5 +- app/web/judge.py | 12 +- docs/judgement.md | 2 +- 10 files changed, 497 insertions(+), 26 deletions(-) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index dd0810cf3..eead47fc1 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -29,6 +29,7 @@ import os import re import shutil +from types import SimpleNamespace from typing import Optional from nullius import ondisk, paths @@ -42,6 +43,8 @@ TASKS = "task" # the lane of task-instruction judgements, by dataset (`task_dataset`) ADOPTED = "~adopted" # in a file: the digests of the older records copied in, so none is copied twice MOVED = ".moved" # in ``/judgements/``: a file per workspace whose older records are all in the user's store +CURRENT = ".current" # in ``/judgements/``: the folders this version wrote, ``/``, ``*`` after one holding files before +SETTLED = ".settled" # in ``/judgements/``: the folders a scan found a current job's or all copied; the first-load prompt's alone class Unreadable(client.JudgeError, ValueError): @@ -115,7 +118,8 @@ def _paths(base: str, job_id: str, trial_name: str, lane: str = "decision") -> l def _read(paths, strict: bool = False) -> dict: """The first judgement file of `paths` there is, read; {} when there is none. One that - cannot be read, or holds no JSON object: {}, or `Unreadable` when `strict` (a write).""" + cannot be read, or holds no JSON object: {}, or `Unreadable` when `strict` (a write), as for + one whose `ADOPTED` is no list of digests.""" for path in paths: try: with open(path, encoding="utf-8") as fh: @@ -130,6 +134,9 @@ def _read(paths, strict: bool = False) -> dict: if strict: raise Unreadable(path) return {} + adopted = data.get(ADOPTED, []) + if strict and not (isinstance(adopted, list) and all(isinstance(d, str) for d in adopted)): + raise Unreadable(path) # its digests are what keeps a copy from being made twice return data return {} @@ -243,6 +250,7 @@ def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "dec if "hygiene" in earlier or "hygiene" in record: merged["hygiene"] = {**(earlier.get("hygiene") or {}), **(record.get("hygiene") or {})} data[version] = merged + _written(os.path.dirname(path)) ondisk.write_whole(path, json.dumps(data, indent=1), mode=0o600) return merged @@ -388,6 +396,7 @@ def _merge_into(path: str, old, job_dir: Optional[str] = None) -> None: 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) @@ -599,9 +608,12 @@ def records_of(base: str, uids, olds=()) -> int: return len(found | {p for o in olds for p in o if os.path.dirname(p) in dirs}) -def old_stores(home_dir: str, into: Optional[str] = None) -> list: +def old_stores(home_dir: str, into: Optional[str] = None, exact: bool = False, hint: bool = False) -> list: """[(workspace, its count of older records)] for each workspace whose store from before holds - any, until it is `moved`; one whose folders cannot all be listed counts those it can.""" + any, until it is `moved`; one whose folders cannot all be listed counts those it can. Then, when + `exact` (the Move dialog), the records under an identity from before #793 (`earlier_entries`); + else one entry counting none while the user's store may hold some (`earlier_maybe`, by its + `hint` for the first-load prompt).""" from nullius import workspace out = [] for ws in workspace.list_all(home_dir): @@ -611,9 +623,229 @@ def old_stores(home_dir: str, into: Optional[str] = None) -> list: n = -1 if n and not moved(ws.dir, into): out.append((ws, max(n, 0))) + into = into or home() + if not earlier_maybe(into, hint and not exact): + return out + return out + (earlier_entries(home_dir, into) if exact else [_entry(EARLIER_LABEL, 0)]) + + +# Judgements a job's identity derived before #793 is kept under, when the job was opened from a +# root spelt `pair/`, `pair/.` or `pair/..` (`uid.earlier`): copied to the job's identity of now by +# `move` alone, and only where one job of the readable registered workspaces derives it. +EARLIER_LANES = (("decision", ""), ("llm", ""), (TASKS, "job:")) # a dataset-less job's task records: `task_dataset` +EARLIER_LABEL = "Earlier job identities" +UNLISTED = "a folder of judgements cannot be listed" +_UID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + + +def _entry(label: str, n: int) -> tuple: + return SimpleNamespace(label=label, dir=None), n + + +def _listed(path: str) -> list: + """The names in the folder `path`: [] when there is none, OSError when it cannot be listed.""" + try: + return sorted(os.listdir(path)) + except (FileNotFoundError, NotADirectoryError): + return [] + + +def _lane_list(into: str, which: str) -> Optional[set]: + """The entries of the list `which` (`CURRENT`, `SETTLED`): none when there is none, None when it cannot be read.""" + try: + with open(os.path.join(_root(into, "decision"), which), encoding="utf-8") as fh: + return set(fh.read().split()) + except FileNotFoundError: + return set() + except (OSError, ValueError): + 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.""" + 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")): + 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) + except OSError: + pass + + +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) + entry = os.path.relpath(folder, into) + have = _lane_list(into, CURRENT) or set() + if not _candidate(name) or entry in have or entry + "*" in have: + return + try: + held = any(n.endswith(".json") for n in _listed(folder)) + except OSError: + held = True + _note(into, CURRENT, {entry + "*" if held else entry}) + + +def _lane_entry(into: str, lane: str, name: str) -> str: + return os.path.relpath(os.path.join(_root(into, lane), name), into) + + +def _candidate(name: str) -> bool: + """Whether a folder of a lane is named by a job identity (`key`), as an earlier one would be.""" + return any(_UID.fullmatch(name.partition("~")[0].removeprefix(_SAFE.sub("_", prefix))) for _, prefix in EARLIER_LANES) + + +def earlier_maybe(into: str, hint: bool = False) -> bool: + """Whether the user's store may hold records under an earlier identity: a folder of it named by + an identity, or one that cannot be listed. With `hint` (the first-load prompt), none this version + wrote alone (`CURRENT`) or a scan settled (`SETTLED`). No workspace or job is read; which are + earlier is told when the dialog opens (`earlier_entries`).""" + known = (_lane_list(into, CURRENT) or set()) | (_lane_list(into, SETTLED) or set()) if hint else set() + for lane, _ in EARLIER_LANES: + try: + names = _listed(_root(into, lane)) + except OSError: + return True + if any(_candidate(n) and _lane_entry(into, lane, n) not in known for n in names): + return True + return False + + +def _walked(ws) -> list: + """`workspace.walked`, nothing of a manifest whose roots are no list of paths (`workspace.every` refuses it).""" + from nullius import workspace + try: + return [r for r in workspace.walked(ws) if isinstance(r, str)] + except TypeError: + return [] + + +def stray(home_dir: str, into: str) -> tuple: + """({an earlier identity some folder of the user's store is named by: {the identity of now of each + job of the registered workspaces that derived it: its folder}}, [why that may miss an owner or a + folder], {(lane, folder name) of the store}, {the folders this version wrote into that held files + already: never copied}, {(lane, folder name) whose owner may be unknown}). An identity a job holds + now is none, and so is a folder only this version wrote (`CURRENT`). Every root and job is read + afresh, strictly.""" + from nullius import workspace + from nullius.runs import parse, uid as job_uid + why, names = [], set() + for lane, prefix in EARLIER_LANES: + try: + names |= {(lane, n) for n in _listed(_root(into, lane))} + except OSError: + why.append(UNLISTED) + try: + spaces = workspace.every(home_dir) + except OSError as e: + why.append(str(e)) + spaces = workspace.list_all(home_dir) + cur = _lane_list(into, CURRENT) + if cur is None: + why.append("the list of judgements written cannot be read") + names = {(lane, n) for lane, n in names if _lane_entry(into, lane, n) not in (cur or ())} + written = {e[:-1] for e in cur or () if e.endswith("*")} + jobs = {} + for root in dict.fromkeys(r for ws in spaces for r in _walked(ws)): + try: + if not os.path.isdir(root): + raise OSError(f"{root} is not there") + for d in parse.find_job_dirs([root], strict=lambda _: True): + jobs[d] = (job_uid.strict(d), job_uid.earlier(d)) + except OSError: + why.append("a root or a job cannot be read") + now = {u for u, _ in jobs.values() if u} + uid_of = lambda lane, n: n.partition("~")[0][len("job_"):] if lane == TASKS else n # `key("job:" + uid)` + held = {uid_of(lane, n) for lane, n in names} + _note(into, SETTLED, {_lane_entry(into, lane, n) for lane, n in names if uid_of(lane, n) in now}) + unknown = {(lane, n) for lane, n in names if _candidate(n) and uid_of(lane, n) not in now} + out: dict = {} + for d, (u, olds) in jobs.items(): + for o in (olds & held) - now: + if any((lane, key(prefix + o)) in names for lane, prefix in EARLIER_LANES): + out.setdefault(o, {}).setdefault(u, d) + return out, list(dict.fromkeys(why)), names, written, unknown + + +WRITTEN = "written" # `_earlier_left`: a folder this version wrote into while it held files, never copied + + +def _copied(dest: str, data: dict) -> bool: + """Whether every record of `data` is in the file `dest` already, or was copied into it (`ADOPTED`). + `Unreadable` when that file cannot be read.""" + cur = _read([dest], strict=True) + have = set(cur.get(ADOPTED) or ()) | {_digest(r) for r in cur.values() if isinstance(r, dict)} + return all(_digest(r) in have for k, r in data.items() if k != ADOPTED and isinstance(r, dict)) + + +def _earlier_left(into: str, found: tuple) -> list: + """[(an earlier identity, a file under it, the file it belongs in or None while it has no single + owner, its job's folder, its records, None when it or the file it belongs in cannot be read, + False for a folder that cannot be listed, `WRITTEN` for one this version wrote into)] for each + not copied yet.""" + owned, why, names, written, _ = found + out, done = [], set() + for old, owners in owned.items(): + [(now, job_dir)] = owners.items() if len(owners) == 1 and not why else [(None, None)] + for lane, prefix in EARLIER_LANES: + if (lane, key(prefix + old)) not in names: + continue + src = os.path.join(_root(into, lane), key(prefix + old)) + dest = os.path.join(_root(into, lane), key(prefix + now)) if now else None + if _lane_entry(into, lane, key(prefix + old)) in written: + out.append((old, src, None, None, WRITTEN)) + continue + try: + files = [f for f in _listed(src) if f.endswith(".json")] + except OSError: + out.append((old, src, None, None, False)) + continue + n = len(out) + for f in files: + data, to = _old(os.path.join(src, f)), dest and os.path.join(dest, f) + try: + if to and data is not None and _copied(to, data): + continue + except Unreadable: + data = None + out.append((old, os.path.join(src, f), to, job_dir, data)) + if dest and len(out) == n: + done.add(_lane_entry(into, lane, key(prefix + old))) # every record of it copied + _note(into, SETTLED, done) return out +def earlier_entries(home_dir: str, into: str) -> list: + """`old_stores`' entries for the files under an earlier identity not copied yet: one for those + one job owns, one per identity several jobs may own, naming them, and one while some cannot be told.""" + owned, why, _, _, unknown = found = stray(home_dir, into) + left = _earlier_left(into, found) + mixed, left = [i[1] for i in left if i[4] == WRITTEN], [i for i in left if i[4] != WRITTEN] + out = [_entry(EARLIER_LABEL, n) for n in [sum(1 for i in left if i[2] and i[4])] if n] + for old, owners in owned.items(): + n = sum(1 for i in left if i[0] == old and not i[2] and i[4]) + if n and not why and len(owners) > 1: + out.append(_entry(_several(old, owners), n)) + n = sum(1 for i in left if why or not i[4]) + if n or UNLISTED in why or why and unknown: + out.append(_entry(f"{EARLIER_LABEL} ({', '.join(why) or 'a file cannot be read'})", n)) + return out + [_entry(_mixed(mixed), len(mixed))] if mixed else out + + +def _mixed(folders: list) -> str: + return f"{EARLIER_LABEL} saved to since, never copied: {', '.join(sorted(folders))}" + + +def _several(old: str, owners: dict) -> str: + return f"Earlier job identity {old}, which several jobs may own: {', '.join(sorted(owners.values()))}" + + def _plural(n: int, one: str, many: str) -> str: return f"{n} {one if n == 1 else many}" @@ -624,10 +856,13 @@ def move(home_dir: str, into: Optional[str] = None) -> list: A workspace is left for a later move, as one line in the list returned, while one of its roots or folders cannot be read, or one of its files cannot be read, belongs to no job its roots hold, or may belong to several (`owners`: a job id two jobs share, one still starting, or one that cannot be read): - such a file is copied nowhere, and still read as before. Safe to run again.""" + such a file is copied nowhere, and still read as before. Then the records under an identity + from before #793 (`_move_earlier`), whatever a page was shown. Safe to run again.""" into = into or home() left = [] for ws, _ in old_stores(home_dir, into): + if ws.dir is None: # an earlier identity's: `_move_earlier`, afresh + continue try: files = _old_files(ws.dir) # first: one added during the move leaves the workspace unmarked except OSError: @@ -667,4 +902,35 @@ def move(home_dir: str, into: Optional[str] = None) -> list: left.append(f"{ws.label} ({', '.join(why)})") else: _mark(ws.dir, into, files, raw) - return left + return left + _move_earlier(home_dir, into) + + +def _move_earlier(home_dir: str, into: str) -> list: + """`move`'s part for the files under an earlier identity, every job read afresh: each one job + owns copied into that job's file, the old file left as it is. Nothing is copied while a + workspace, a root, a job or a lane of the store cannot be read. The lines name what is left.""" + owned, why, _, _, unknown = found = stray(home_dir, into) + left = _earlier_left(into, found) + mixed, left = [i[1] for i in left if i[4] == WRITTEN], [i for i in left if i[4] != WRITTEN] + if why: + return [f"{EARLIER_LABEL} ({', '.join(why)})"] if left or mixed or UNLISTED in why or unknown else [] + lines, unwritten, unfinished = [], 0, set() + for old, src, dest, job_dir, data in left: + if dest and data: + try: + _merge_into(dest, [data], job_dir) + continue + except (OSError, client.JudgeError): # `Unreadable`, `Gone`: this one left for later + unwritten += 1 + if not (dest and data == {}): # an empty file has nothing to copy + unfinished.add(os.path.dirname(src)) + _note(into, SETTLED, {os.path.relpath(os.path.dirname(src), into) for _, src, dest, _, data in left + if dest and data is not False and os.path.dirname(src) not in unfinished}) + for old, owners in owned.items(): + n = sum(1 for i in left if i[0] == old and not i[2] and i[4]) + if n: + lines.append(f"{_several(old, owners)} ({_plural(n, 'record', 'records')})") + why = [_plural(n, *w) for n, w in ((sum(1 for i in left if i[4] is None), ("file cannot be read", "files cannot be read")), + (sum(1 for i in left if i[4] is False), ("folder cannot be listed", "folders cannot be listed")), + (unwritten, ("file cannot be written", "files cannot be written"))) if n] + return lines + ([f"{EARLIER_LABEL} ({', '.join(why)})"] if why else []) + ([_mixed(mixed)] if mixed else []) diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index 24304e4fe..811c26d5c 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -151,4 +151,20 @@ def of(job_dir: str, cfg: dict, res: dict) -> tuple: f = facts(job_dir, cfg, res) if f is None: return "", "pending" - return str(uuid.uuid5(NS_JOB, json.dumps(f, sort_keys=True, separators=(",", ":")))), "derived" + return _derived(f), "derived" + + +def _derived(f: dict) -> str: + return str(uuid.uuid5(NS_JOB, json.dumps(f, sort_keys=True, separators=(",", ":")))) + + +#: the folder a derived identity took, before #793, from a job folder spelt ``pair/``, ``pair/.`` or ``pair/..`` +EARLIER_FOLDERS = ("", ".", "..") + + +def earlier(job_dir: str) -> set: + """The identities the job's files derived before #793 under each spelling of `EARLIER_FOLDERS`, + read strictly (`strict`): none for a declared or pending one. Several jobs can share one.""" + cfg, res = _strict_json(os.path.join(job_dir, "config.json")), _strict_json(os.path.join(job_dir, "result.json")) + f = None if _declared(cfg) else facts(job_dir, cfg, res) + return set() if f is None else {_derived(dict(f, folder=n)) for n in EARLIER_FOLDERS} diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 693ac654b..440d7c880 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -315,7 +315,8 @@ def list_all(home_dir: str) -> list: def every(home_dir: str) -> list: """Every workspace under *home_dir*, for a reader that must miss none: OSError while one - there cannot be read (another version, damaged), since what it holds is unknown.""" + there cannot be read (another version, damaged, denied, roots that are no list of paths), + since what it holds is unknown.""" try: names = sorted(os.listdir(home_dir)) except FileNotFoundError: @@ -324,10 +325,15 @@ def every(home_dir: str) -> list: for name in names: try: ws = load(home_dir, name) - except (TypeError, ValueError) as error: + if ws is None and _NAME.fullmatch(name): + os.lstat(_path(home_dir, name)) # there, or not to be told: unread + raise ValueError("unread") + if ws and not all(isinstance(rs, list) and all(isinstance(r, str) for r in rs) for rs in (ws.roots, ws.job_roots)): + raise ValueError("invalid roots") + except (FileNotFoundError, NotADirectoryError): + continue + except (OSError, TypeError, ValueError) as error: raise OSError(f"workspace {name} cannot be read") from error - if ws is None and _NAME.fullmatch(name) and os.path.lexists(_path(home_dir, name)): - raise OSError(f"workspace {name} cannot be read") found += [ws] if ws else [] return found diff --git a/app/static/judgements-move.js b/app/static/judgements-move.js index 121eb7764..eb6148612 100644 --- a/app/static/judgements-move.js +++ b/app/static/judgements-move.js @@ -8,7 +8,7 @@ async function ask({later = false} = {}) { const got = await nulliusFetch(URL_, {headers: {Accept: 'application/json'}}).then(r => r.ok ? r.json() : {workspaces: []}).catch(() => ({workspaces: []})); - if (!got.workspaces.length) { if (later) remember(); return; } // nothing to move: not asked again here + if (!got.workspaces.length) { if (later) remember(); else notify('Nothing to move.'); return; } // not asked again here // a native modal, as the welcome: it keeps the focus, makes the page behind it inert and closes on Escape const d = document.createElement('dialog'); d.className = 'onb-dialog'; @@ -31,7 +31,8 @@ d.returnValue = 'move'; d.close(); if (j.ok) { notify('Judgements moved.'); - document.querySelectorAll('[data-move-judgements-row]').forEach(x => x.remove()); + // the count is gone; the button stays, as the page would show it now + document.querySelectorAll('[data-move-judgements-row] .st-value').forEach(x => { if (x.firstChild?.nodeType === Node.TEXT_NODE) x.firstChild.remove(); }); } else notify(j.error || 'The judgements could not be moved.', {error: true}); }); // Escape, like Not now @@ -44,7 +45,7 @@ document.addEventListener('click', e => { if (e.target.closest('[data-move-judgements]')) ask(); }); // shortcut: this first-load dialog is temporary migration UI, against "a notice is a toast"; remove it after a few versions. - if (window.parent !== window) return; + if (window.parent !== window || !me.hasAttribute('data-prompt')) return; let seen = true; try { seen = !!localStorage.getItem(KEY) || !(JSON.parse(localStorage.getItem('nullius-onboarding')) || {}).asked; } catch {} if (!seen && !document.querySelector('dialog[open]')) ask({later: true}); diff --git a/app/templates/base.html b/app/templates/base.html index d7ca39cfd..7fa076743 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -421,7 +421,7 @@ {% endif %} -{% if judgements_unmoved() %}{% endif %} +{% set judgements_prompt = judgements_unmoved() %}{% if judgements_prompt or old_judgements %}{% endif %} {% if not embedded %} {% include "workspaces/_create.html" %} diff --git a/app/templates/settings/settings.html b/app/templates/settings/settings.html index 6fbdde50a..40c967529 100644 --- a/app/templates/settings/settings.html +++ b/app/templates/settings/settings.html @@ -236,7 +236,7 @@

Judges

{% if old_judgements and writable %}
In workspaces - {{ old_judgements|sum(attribute=1) }} judgement{{ '' if old_judgements|sum(attribute=1) == 1 else 's' }}
+ {% set n = old_judgements|sum(attribute=1) %}{% if n %}{{ n }} judgement{{ '' if n == 1 else 's' }}{% endif %}
{% endif %} diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index 1207470fd..6d6688a05 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -9,12 +9,13 @@ import shutil import tempfile import unittest +import uuid from types import SimpleNamespace as NS from unittest.mock import patch from nullius import workspace from nullius.judge import questions as Q, store -from nullius.runs import parse +from nullius.runs import parse, uid as job_uid from tests.test_workspace import _job_dir @@ -157,7 +158,7 @@ def unlisted(p="."): # a root without permission: there, b self.assertTrue(os.path.isdir(ws.dir)) self.assertEqual(store.move(home_dir), []) self.assertTrue(store.moved(ws.dir)) - self.assertEqual(store.old_stores(home_dir), []) + self.assertEqual(store.old_stores(home_dir, exact=True), []) self.assertTrue(store.load(self.home, j.uid, j.trials[0].trial_name)) def test_a_workspace_is_moved_only_once_every_old_file_was_read_and_found_its_job(self): @@ -172,7 +173,7 @@ def test_a_workspace_is_moved_only_once_every_old_file_was_read_and_found_its_jo f.write('{"v2": {') # cut short self.assertEqual(store.move(home_dir), ["w (1 file cannot be read, 1 record of no job found)"]) self.assertFalse(store.moved(ws.dir)) - self.assertEqual(store.old_stores(home_dir), [(ws, 3)]) + self.assertEqual(store.old_stores(home_dir, exact=True), [(ws, 3)]) self.assertTrue(store.load(self.home, j.uid, t0)) # what could go, went _job_dir(root, "job-gone") [gone] = [g for g in workspace.load_jobs(ws, ws.roots) if g.job_id == "job-gone"] @@ -184,7 +185,7 @@ def test_a_workspace_is_moved_only_once_every_old_file_was_read_and_found_its_jo self.assertEqual(store.overlay(ws.dir, gone), {}) store.save(ws.dir, "job-a", "restored", rec("2026-01-01T00:00:00Z")) # a store brought back later self.assertFalse(store.moved(ws.dir)) - self.assertEqual([n for _, n in store.old_stores(home_dir)], [4]) + self.assertEqual([n for _, n in store.old_stores(home_dir, exact=True)], [4]) def test_a_moved_workspace_is_read_again_once_a_file_changes_or_a_folder_cannot_be_listed(self): root = os.path.join(self.tmp, "jobs"); _job_dir(root, "job-a") @@ -334,6 +335,182 @@ def test_a_save_or_a_copy_for_a_job_deleted_meanwhile_writes_nothing(self): write() self.assertFalse(os.path.exists(os.path.join(self.home, "judgements", "uid-1"))) + def _saved_before_793(self, root_is_job=True, lane="decision"): + """A workspace of the job `pair` (its root `pair/`, or the folder holding it), and a record saved + under the identity it derived before #793 from the folder "": a copy of it renamed derives it too.""" + root, home_dir = os.path.join(self.tmp, "jobs"), os.path.join(self.tmp, "ws") + pair = _job_dir(root, "pair") + ws = workspace.create(home_dir, [pair + os.sep if root_is_job else root], label="w") + [j] = workspace.load_jobs(ws, ws.roots) + files = [] + for n in ("config.json", "result.json"): + with open(os.path.join(pair, n), encoding="utf-8") as fh: + files.append(json.load(fh)) + f = dict(job_uid.facts(pair, *files), folder="") + old = str(uuid.uuid5(job_uid.NS_JOB, json.dumps(f, sort_keys=True, separators=(",", ":")))) + name = "job:" + old if lane == store.TASKS else old + store.save(self.home, name, j.trials[0].trial_name, rec("2026-01-01T00:00:00Z", "before"), lane=lane) + os.remove(os.path.join(self.home, "judgements", store.CURRENT)) # a store from before keeps no list + return home_dir, pair, j, old + + def _copy(self, pair, home_dir, folder="copy"): + shutil.copytree(pair, os.path.join(self.tmp, "other", folder)) + return workspace.create(home_dir, [os.path.join(self.tmp, "other")], label="v") + + def test_a_record_under_an_identity_from_before_793_moves_when_asked_to_its_one_owner(self): + for root_is_job, lane in ((True, "decision"), (False, "decision"), (True, store.TASKS)): + with self.subTest(root_is_job=root_is_job, lane=lane): + self.tmp = tempfile.mkdtemp(prefix="nullius-judge-adopt-"); self.addCleanup(shutil.rmtree, self.tmp, True) + self.home = os.path.join(self.tmp, "data") + patcher = patch.object(store, "home", return_value=self.home); patcher.start(); self.addCleanup(patcher.stop) + home_dir, _, j, old = self._saved_before_793(root_is_job, lane) + name, t0 = ("job:" if lane == store.TASKS else "") + j.uid, j.trials[0].trial_name + self.assertIsNone(store.load(self.home, name, t0, lane=lane)) # never merged on its own + self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, hint=True)], [("Earlier job identities", 0)]) + self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, exact=True)], [("Earlier job identities", 1)]) + self.assertEqual(store.move(home_dir), []) + self.assertEqual(store.load(self.home, name, t0, lane=lane)["answers"]["q"]["choice"], "before") + self.assertTrue(store.load(self.home, ("job:" if lane == store.TASKS else "") + old, t0, lane=lane)) # kept + self.assertEqual(store.old_stores(home_dir, exact=True), []) + self.assertEqual(store.old_stores(home_dir, hint=True), []) # the first-load prompt: settled + self.assertEqual(len(store.old_stores(home_dir)), 1) # Settings: Move still there + + def test_a_record_under_an_identity_from_before_793_two_jobs_derive_is_named_never_moved(self): + home_dir, pair, j, old = self._saved_before_793() + self._copy(pair, home_dir) + line = f"Earlier job identity {old}, which several jobs may own: {pair}, {os.path.join(self.tmp, 'other', 'copy')}" + for _ in range(2): + self.assertEqual(store.move(home_dir), [line + " (1 record)"]) + self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, exact=True)], [(line, 1)]) + self.assertIsNone(store.load(self.home, j.uid, j.trials[0].trial_name)) + + def test_a_record_under_an_identity_from_before_793_stays_while_another_owner_cannot_be_ruled_out(self): + home_dir, pair, j, old = self._saved_before_793() + t0 = j.trials[0].trial_name + real_open, real_lstat = open, os.lstat + for how in ("damaged", "roots that are no list", "denied"): + with self.subTest("a workspace cannot be read", how=how): # the copy in it would be a second owner + other = self._copy(pair, home_dir) + manifest = os.path.join(other.dir, "workspace.json") + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + with open(manifest, "w", encoding="utf-8") as fh: + fh.write("{" if how == "damaged" else json.dumps(dict(data, roots=None) if how != "denied" else data)) + def denied(f, *a, real=None, **k): # its folder cannot be searched + if how == "denied" and isinstance(f, str) and f.startswith(other.dir + os.sep): + raise PermissionError(13, "Permission denied", f) + return real(f, *a, **k) + with patch("builtins.open", lambda *a, **k: denied(*a, real=real_open, **k)), \ + patch("os.lstat", lambda *a, **k: denied(*a, real=real_lstat, **k)): + self.assertEqual(store.move(home_dir), [f"Earlier job identities (workspace {other.name} cannot be read)"]) + self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], + [f"Earlier job identities (workspace {other.name} cannot be read)"]) + self.assertIsNone(store.load(self.home, j.uid, t0)) + shutil.rmtree(other.dir); shutil.rmtree(os.path.join(self.tmp, "other")) + def denied_ws(f, real, d, *a, **k): + if isinstance(f, str) and f.startswith(d + os.sep): + raise PermissionError(13, "Permission denied", f) + return real(f, *a, **k) + with self.subTest("a root is away, then back"): + away = pair + ".away" + os.rename(pair, away) # its only owner unseen: unfinished + self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, exact=True)], + [("Earlier job identities (a root or a job cannot be read)", 0)]) + self.assertEqual(store.move(home_dir), ["Earlier job identities (a root or a job cannot be read)"]) + os.rename(away, pair) + [ws] = workspace.list_all(home_dir) + with patch("builtins.open", lambda f, *a, **k: denied_ws(f, real_open, ws.dir, *a, **k)), \ + patch("os.lstat", lambda f, *a, **k: denied_ws(f, real_lstat, ws.dir, *a, **k)): + self.assertEqual(store.move(home_dir), [f"Earlier job identities (workspace {ws.name} cannot be read)"]) + self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], ["Earlier job identities"]) + with self.subTest("a folder of judgements cannot be listed"): + real, lane = os.listdir, os.path.join(self.home, "judgements-llm") + def denied(p="."): + if isinstance(p, str) and os.path.realpath(p) == os.path.realpath(lane): + raise PermissionError(13, "Permission denied", p) + return real(p) + os.makedirs(lane, exist_ok=True) + with patch("os.listdir", denied): + self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], + ["Earlier job identities (a folder of judgements cannot be listed)"]) + self.assertEqual(store.move(home_dir), ["Earlier job identities (a folder of judgements cannot be listed)"]) + store.save(self.home, old, t0, rec("2026-01-01T00:00:00Z", "llm"), lane="llm") + os.remove(os.path.join(self.home, "judgements", store.CURRENT)) # saved before #793 + lane = os.path.join(self.home, "judgements-llm", old) # its own folder this time + with patch("os.listdir", denied): + self.assertEqual(store.move(home_dir), ["Earlier job identities (1 folder cannot be listed)"]) + self.assertTrue(store.load(self.home, j.uid, t0)) # the other lane's went + shutil.rmtree(lane) + os.remove(os.path.join(self.home, "judgements", j.uid, t0 + ".json")) + with self.subTest("a job holds that identity now"): + mine = self._copy(pair, home_dir, "declared") + cfg = os.path.join(self.tmp, "other", "declared", "config.json") + with open(cfg, encoding="utf-8") as fh: + data = json.load(fh) + with open(cfg, "w", encoding="utf-8") as fh: + json.dump(dict(data, nullius={"source": old}), fh) + self.assertEqual((store.old_stores(home_dir, exact=True), store.move(home_dir)), ([], [])) + self.assertIsNone(store.load(self.home, j.uid, t0)) + workspace.delete(home_dir, mine.name) + self.assertEqual(store.move(home_dir), []) + self.assertEqual(store.load(self.home, j.uid, t0)["answers"]["q"]["choice"], "before") + + def test_a_page_reads_no_workspace_for_them_and_offers_only_folders_no_save_wrote(self): + home_dir, folder = os.path.join(self.tmp, "ws"), str(uuid.uuid4()) + with patch.object(store, "stray", side_effect=AssertionError("a job was read")): + self.assertEqual(store.old_stores(home_dir), []) + store.save(self.home, str(uuid.uuid4()), "t0", rec("2026-01-01T00:00:00Z")) # a fresh save: never prompted + self.assertEqual(store.old_stores(home_dir, hint=True), []) + self.assertEqual(len(store.old_stores(home_dir)), 1) # Settings keeps Move + os.makedirs(os.path.join(self.home, "judgements-llm", folder)) # one from before + self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, hint=True)], [("Earlier job identities", 0)]) + with open(os.path.join(self.home, "judgements", store.SETTLED), "w") as fh: + fh.write(f"judgements/{folder}\n") # the same name in another lane + self.assertEqual(len(store.old_stores(home_dir, hint=True)), 1) + with open(os.path.join(self.home, "judgements", store.CURRENT), "wb") as fh: + fh.write(b"\xff\xfe") # damaged list: offered + self.assertEqual(len(store.old_stores(home_dir, hint=True)), 1) + self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], # read when the dialog opens + ["Earlier job identities (the list of judgements written cannot be read)"]) + + def test_a_record_under_an_identity_from_before_793_its_destination_refuses_stays_for_later(self): + home_dir, pair, j, old = self._saved_before_793() + t0 = j.trials[0].trial_name + dest = os.path.join(self.home, "judgements", j.uid, t0 + ".json") + os.makedirs(os.path.dirname(dest)) + with open(dest, "w") as fh: + fh.write('{"~adopted": 1}') # damaged: left as it is + self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, exact=True)], + [("Earlier job identities (a file cannot be read)", 1)]) + self.assertEqual(store.move(home_dir), ["Earlier job identities (1 file cannot be read)"]) + self.assertEqual(open(dest).read(), '{"~adopted": 1}') + os.remove(dest) + with patch("nullius.ondisk.locked", side_effect=PermissionError(13, "Permission denied")): + self.assertEqual(store.move(home_dir), ["Earlier job identities (1 file cannot be written)"]) + self.assertEqual(store.move(home_dir), []) + self.assertEqual(store.load(self.home, j.uid, t0)["answers"]["q"]["choice"], "before") + + def test_a_folder_this_version_saved_to_is_never_recovered_as_an_earlier_identity(self): + home_dir, pair, j, old = self._saved_before_793() + t0, folder = j.trials[0].trial_name, os.path.join(self.home, "judgements", old) + store.save(self.home, old, "t-new", rec("2026-06-01T00:00:00Z", "new")) # a job declaring it saved: mixed + line = f"Earlier job identities saved to since, never copied: {folder}" + self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], [line]) + self.assertEqual(store.move(home_dir), [line]) + shutil.rmtree(folder); os.remove(os.path.join(self.home, "judgements", store.CURRENT)) + store.save(self.home, old, t0, rec("2026-06-01T00:00:00Z", "new")) # only this version's + self.assertEqual((store.old_stores(home_dir, exact=True), store.move(home_dir)), ([], [])) + self.assertIsNone(store.load(self.home, j.uid, t0)) + + def test_an_unreadable_list_of_folders_written_is_left_as_it_is(self): + listed = os.path.join(self.home, "judgements", store.CURRENT) + os.makedirs(os.path.dirname(listed)) + with open(listed, "wb") as fh: + fh.write(b"\xff\xfe") + store.save(self.home, str(uuid.uuid4()), "t0", rec("2026-01-01T00:00:00Z")) + with open(listed, "rb") as fh: + self.assertEqual(fh.read(), b"\xff\xfe") + if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 01200668b..782979e42 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -67,6 +67,7 @@ def test_a_judgement_made_in_one_workspace_shows_in_another_and_outlives_it(self web.shared.open_workspace(a) self.judge("job-x") self.assertTrue(self.judged("job-x", b), "a judgement made in A does not show in B") + self.assertNotIn("judgements-move.js", web.app.test_client().get("/").get_data(as_text=True)) # nothing to move workspace.delete(web.shared.WS_HOME, a.name) self.assertTrue(self.judged("job-x", b), "deleting A deleted the judgement") c = workspace.create(web.shared.WS_HOME, [str(self.tmp / "runs")], "C") @@ -221,7 +222,9 @@ def test_the_move_copies_them_once_and_says_so_where_it_is_offered(self): self.assertEqual(tree(Path(self.ws.dir) / "judgements"), old) # the old files stay as they were self.assertTrue(self.shown()) self.assertEqual(self.get("/judgements/move").get_json(), {"workspaces": []}) - self.assertNotIn("data-move-judgements", self.get("/settings?embedded=1").get_data(as_text=True)) + settings = self.get("/settings?embedded=1").get_data(as_text=True) + self.assertIn("data-move-judgements", settings) # Move stays at hand; the dialog says what is left + self.assertNotIn("data-prompt", settings) self.assertNotIn("judgements-move.js", self.get("/").get_data(as_text=True)) def test_judging_a_job_checks_the_form_token_first(self): diff --git a/app/web/judge.py b/app/web/judge.py index bddffede4..e279dfc79 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -744,18 +744,20 @@ def judge_task(job, trial, api_key: str, post=None, calibration=None, column=Non @app.template_global() def judgements_unmoved() -> bool: - """Whether a workspace's judgements kept before still wait to be moved (`store.old_stores`).""" - return bool(store.old_stores(shared.WS_HOME)) + """Whether a workspace's judgements kept before may still wait to be moved, for the first-load + prompt (`store.old_stores`, by its hint).""" + return bool(store.old_stores(shared.WS_HOME, hint=True)) @app.route("/judgements/move", methods=["GET", "POST"]) def judgements_move(): """GET: the workspaces whose store from before holds judgements, and how - many each (`store.old_stores`). POST: every one of them copied into the - user's store (`store.move`), the old files kept; the error names the + many each, then the records under an earlier job identity, read afresh + (`store.old_stores`). POST: every one of them copied into the user's + store (`store.move`), the old files kept; the error names the workspaces left for a later move, and why.""" if request.method == "GET": - return jsonify(workspaces=[{"label": ws.label, "n": n} for ws, n in store.old_stores(shared.WS_HOME)]) + return jsonify(workspaces=[{"label": ws.label, "n": n} for ws, n in store.old_stores(shared.WS_HOME, exact=True)]) shared._require_csrf() if not shared._local_client(): abort(403) diff --git a/docs/judgement.md b/docs/judgement.md index fb3a9cdd4..27e9745a6 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -70,7 +70,7 @@ Follow the evidence: a recorded rate limit is a provider's failure whatever the | What | Detail | | --- | --- | | Where | `judgements//.json` below the user data directory, never in the job tree; task-instruction scores in `judgements-tasks//`. One record per trial and per try of a retried trial (a try that recorded no start is not judged), in every workspace that holds the job; a renamed Harbor or imported job folder is a new job | -| Before | Records under `workspaces//judgements/` are still shown; of two for one trial, the newer. *Move judgements* (first page, or Settings › Judges) copies them into the user data directory; the old files stay. A workspace is left for later while a root, a folder or a file cannot be read, or a record belongs to no job found, to two jobs, to one still starting or to one whose files cannot be read; such a record is still shown, never copied, even by a save | +| Before | Records under `workspaces//judgements/` are still shown; of two for one trial, the newer. *Move judgements* (first page, or Settings › Judges) copies them into the user data directory; the old files stay. A workspace is left for later while a root, a folder or a file cannot be read, or a record belongs to no job found, to two jobs, to one still starting or to one whose files cannot be read; such a record is still shown, never copied, even by a save. It also copies records an earlier version kept for a job opened from a root ending in `/`, `.` or `..`, when exactly one job of the readable registered workspaces derives them (register the folder holding a job to bring it in); one several jobs derive is listed with them, never copied | | Deleted | With the launch they judge (*Delete launch* in Runs, [Run](builder.md#run)), unless a copy of the job is found or a root cannot be read. Deleting a workspace keeps them, its old records and its imports' failure analyses in `judgements-of-deleted-workspaces/`; one with old records or failure analyses is refused while one of its roots, or a folder of its imports, cannot be read | | Version | `judgement.questions.v2`; v1 records marked *earlier* | | Cost | A batch button names its calls; each is checked against the token budget |