From e64b5480a7dc688408150c56fd709ce060e2368d Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 14:42:49 +0100 Subject: [PATCH 01/24] fix(judge): keep judgements by the job they judge, not by the workspace A judgement was kept in the workspace's own folder under the bare job id: deleting the workspace deleted it, a second workspace holding the job did not see it, and two jobs of one name shared one record. Judgements are now Nullius's own record in the user data directory, under the job's identity (Job.uid) and the trial's key, never in a job folder, which belongs to whatever produced it. - The same judgement shows in every workspace that holds the job. - Records kept in a workspace before are copied in when its job is read, the old files left in place; of two records for one trial the newer is shown and the other kept beside it. Two jobs of one id in that workspace each get its record, as each showed it before. - Deleting a workspace keeps its jobs' judgements and moves its old store into the user data directory whole. - Deleting a launch removes its jobs' judgements, unless another folder of the same identity is found or a root cannot be read. - Task-instruction scores are kept by dataset in judgements-tasks/, no longer as a job named task:. - A save holds a file lock, across processes. --- app/nullius/execution.py | 36 +++- app/nullius/judge/batch.py | 20 ++- app/nullius/judge/store.py | 169 +++++++++++++----- app/nullius/onboarding.py | 11 +- app/nullius/workspace.py | 21 ++- app/templates/workspaces/workspaces.html | 7 +- .../judgements-llm/job-x/t0.json | 8 + .../workspace-store/judgements/job-x/t0.json | 8 + app/tests/test_judge.py | 6 +- app/tests/test_judge_adopt.py | 85 +++++++++ app/tests/test_judge_store_race.py | 14 ++ app/tests/test_run_delete.py | 46 ++++- app/ui_tests/test_failure_analysis_routes.py | 1 + app/ui_tests/test_judge_calibration_reads.py | 7 +- app/ui_tests/test_judge_other_workspace.py | 35 ++-- app/ui_tests/test_judgement_follows_job.py | 86 +++++++++ app/ui_tests/test_reconcile_routes.py | 1 + app/ui_tests/test_run_routes.py | 11 +- app/ui_tests/test_task_judgement_slot.py | 16 +- app/ui_tests/test_trial_head.py | 1 + app/web/judge.py | 112 ++++++------ app/web/judge_tasks.py | 4 +- app/web/reconcile.py | 3 +- app/web/workspaces.py | 3 +- docs/builder.md | 2 +- docs/concepts.md | 2 +- docs/how-it-works.md | 1 - docs/judgement.md | 5 +- docs/settings/llm-judge.md | 2 +- 29 files changed, 558 insertions(+), 165 deletions(-) create mode 100644 app/tests/fixtures/judge/workspace-store/judgements-llm/job-x/t0.json create mode 100644 app/tests/fixtures/judge/workspace-store/judgements/job-x/t0.json create mode 100644 app/tests/test_judge_adopt.py create mode 100644 app/ui_tests/test_judgement_follows_job.py diff --git a/app/nullius/execution.py b/app/nullius/execution.py index bcb809a12..5d010df28 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -1838,14 +1838,38 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, held = [] for ws, roots in holding(path): dirs = parse.find_job_dirs(roots) - ids = [j.job_id for j in workspace.load_jobs(ws, roots, ends)] + jobs = workspace.load_jobs(ws, roots, ends) + for j in jobs: # the workspace's records from before, in the user's store first: they are counted there + judgements.adopt(ws.dir, j) + ids = [j.job_id for j in jobs] # a job of the same id from another root shares these judgements: they stay others = {e.get("job_id") for d, e in workspace.job_index(ws).items() if d not in dirs} judged = judgements.job_dirs(ws.dir, [i for i in ids if i.split("~")[0] not in others]) - held.append({"ws": ws, "roots": roots, "jobs": dirs, - "judged": judged, "judgements": sum(len(os.listdir(d)) for d in judged)}) - return {"name": name, "dir": path, "bytes": size_of(path), "host": host, "workspaces": held, - "judgements": sum(w["judgements"] for w in held)} + held.append({"ws": ws, "roots": roots, "jobs": dirs, "judged": judged}) + uids = {parse.parse_job(d, trials=False).uid for d in parse.find_job_dirs([os.path.join(path, "jobs")])} - {""} + judged = judgements.job_dirs(judgements.home(), sorted(uids)) + if judged: + judged = judgements.job_dirs(judgements.home(), sorted(uids - _judged_elsewhere(home, path, uids))) + return {"name": name, "dir": path, "bytes": size_of(path), "host": host, "workspaces": held, "judged": judged, + "judgements": judgements.count_in(judged)} + + +def _judged_elsewhere(home: str, path: str, uids: set) -> set: + """Which of the jobs *uids* of the run folder *path* keep their + judgements when it goes: those with another folder of the same identity + outside it - a copy - under a root of any workspace or another run, and + all of them when one of those roots cannot be read, since who owns them + is then unknown.""" + outside = lambda d: os.path.commonpath([os.path.realpath(d), path]) != path + kept = set() + for ws in workspace.list_all(home): + roots = ws.job_roots or ws.roots + if not all(os.path.isdir(r) for r in roots): + return set(uids) + kept |= {j.uid for j in workspace.load_jobs(ws, roots) if outside(j.dir)} & uids + others = [j for e in os.scandir(os.path.dirname(path)) + if e.is_dir(follow_symlinks=False) and e.path != path and os.path.isdir(j := os.path.join(e.path, "jobs"))] + return kept | ({parse.parse_job(d, trials=False).uid for d in parse.find_job_dirs(others)} & uids) def deletion(names: List[str], home: str, root: Optional[str] = None, holding: Optional[Callable] = None) -> dict: @@ -1884,6 +1908,8 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r continue for key in [k for k, e in EXECUTIONS.items() if os.path.realpath(e.dir) == r["dir"]]: del EXECUTIONS[key] + for d in r["judged"]: + shutil.rmtree(d, ignore_errors=True) for w in r["workspaces"]: for d in w["judged"]: shutil.rmtree(d, ignore_errors=True) diff --git a/app/nullius/judge/batch.py b/app/nullius/judge/batch.py index 80b11a549..c49725e20 100644 --- a/app/nullius/judge/batch.py +++ b/app/nullius/judge/batch.py @@ -96,20 +96,22 @@ def ask_states(states: dict, key: str, post: Optional[Callable] = None, calibrat return merged -def ask_and_store(ws_dir: str, job_id: str, trial_name: str, states: dict, key, post: Optional[Callable] = None, - calibration: Optional[dict] = None, started: Optional[str] = None) -> Optional[dict]: +def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, post: Optional[Callable] = None, + calibration: Optional[dict] = None, started: Optional[str] = None, + lane: Optional[str] = None) -> Optional[dict]: """`ask_states`, then the merged record saved under the trial's key - - its answers over the version's earlier ones. Returns the record as - stored. The pre-flight reads the workspace's own calibration unless one - is given. `started`: the trial's own - start, which the record keeps (`store.save`).""" + its answers over the version's earlier ones - in the store at `base` + (`store.home`). Returns the record as stored. The pre-flight reads the + store's own calibration unless one is given. `started`: the trial's own + start, which the record keeps (`store.save`). `lane`: where it is kept, + the judge's own lane unless named (`store.TASKS`).""" if calibration is None: - calibration = store.calibration(ws_dir) + calibration = store.calibration(base) rec = ask_states(states, key, post=post, calibration=calibration) if rec is not None: # the LLM judge's records apart from Decision's; a call over some of the kinds keeps the # earlier readings for the others, as the answers are kept (`store.save`), and returns them - lane = getattr(key, "lane", "decision") + lane = lane or getattr(key, "lane", "decision") rec.setdefault("hygiene", {}) - rec["hygiene"] = store.save(ws_dir, job_id, trial_name, rec, lane=lane, started=started)["hygiene"] + rec["hygiene"] = store.save(base, job_id, trial_name, rec, lane=lane, started=started)["hygiene"] return rec diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index c80c5c42e..d0fb844ca 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -1,9 +1,18 @@ -"""Where a judgement lives: the workspace's own store, beside the parsed -jobs - ``/judgements//.json`` (each name -spelled by `key`) for System -One's, ``/judgements-llm/...`` for the LLM judge's (a trial has -both, apart, ``lane``) - keyed by question version inside. Never under the job's ``agent/`` directory: the -run tree is Harbor's, and a re-parse of the job does not touch this. +"""Where a judgement lives: the user's own store, by the job it judges - +``/judgements//.json`` (each name spelled by +`key`; ``Job.uid``, ``Trial.key``) for System One's, +``/judgements-llm/...`` for the LLM judge's (a trial has both, +apart, ``lane``), ``/judgements-tasks//...`` for task +instructions - keyed by question version inside. ```` is +``home()``, the user data directory. Never in a job folder: it is its +producer's, and can be rewritten, pruned or read-only. So one judgement +shows in every workspace that holds the job, and deleting a workspace +leaves it. + +Every function takes the store's base first: ``home()``, or a workspace's +folder for the store judgements were kept in before (``/ +judgements{,-llm}//``), which is still read: `adopt` copies a job's +records from it, never deleting them. Every version is kept, and under each every try of a retried trial: the try judged last under the version, each earlier one under @@ -16,30 +25,31 @@ import json import os import re -import threading from typing import Optional -from nullius import ondisk +from nullius import ondisk, paths from . import client, questions as Q _SAFE = re.compile(r"[^A-Za-z0-9._@+-]") -_LOCKS: dict = {} # one per judgement file: a save reads, merges and writes it whole -_LOCKS_GUARD = threading.Lock() +ROOTS = {"decision": "judgements", "llm": "judgements-llm"} # one directory per judge +TASKS = "task" # the lane of task-instruction judgements, by dataset (`task_dataset`) -def _lock(path: str) -> threading.Lock: - with _LOCKS_GUARD: - return _LOCKS.setdefault(path, threading.Lock()) +def home() -> str: + """The base of the user's own store: the user data directory.""" + return paths.data_dir() -ROOTS = {"decision": "judgements", "llm": "judgements-llm"} # one directory per judgement +def _root(base: str, lane: str) -> str: + return os.path.join(base, "judgements-tasks" if lane == TASKS else ROOTS.get(lane, "judgements")) -def _root(ws_dir: str, lane: str) -> str: - return os.path.join(ws_dir, ROOTS.get(lane, "judgements")) +def _locked(path: str): + """One save at a time to a judgement file, across threads and processes: a save reads, merges and writes it whole.""" + return ondisk.locked(os.path.join(os.path.dirname(path), ".lock")) def key(name: str) -> str: @@ -55,9 +65,9 @@ def _names(name: str) -> tuple: return tuple(dict.fromkeys((key(name), _SAFE.sub("_", name)))) -def _paths(ws_dir: str, job_id: str, trial_name: str, lane: str = "decision") -> list: +def _paths(base: str, job_id: str, trial_name: str, lane: str = "decision") -> list: """Where a judgement is written, then where an older store may hold it.""" - root = _root(ws_dir, lane) + root = _root(base, lane) return [os.path.join(root, j, t + ".json") for j in _names(job_id) for t in _names(trial_name)] @@ -99,12 +109,14 @@ def _pick(data: dict, version: Optional[str], started: Optional[str] = None) -> return None -def load(ws_dir: str, job_id: str, trial_name: str, version: Optional[str] = None, lane: str = "decision", +def load(base: str, job_id: str, trial_name: str, version: Optional[str] = None, lane: str = "decision", started: Optional[str] = None) -> Optional[dict]: """The record under `version`; with none named, the current version or the newest earlier one that has a record. `started`: the trial's own start, so a record of an earlier try under its name is none of its.""" - return _pick(_read(_paths(ws_dir, job_id, trial_name, lane)), version, started) + if not job_id: # a job with no identity yet (Job.uid_source "pending") has no judgement + return None + return _pick(_read(_paths(base, job_id, trial_name, lane)), version, started) def is_current(record: Optional[dict]) -> bool: @@ -112,17 +124,19 @@ def is_current(record: Optional[dict]) -> bool: return bool(record) and record.get("questions") == Q.VERSION -def save(ws_dir: str, job_id: str, trial_name: str, record: dict, lane: str = "decision", +def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "decision", started: Optional[str] = None) -> dict: """The record under its question version, returned as stored; other versions kept. A record's answers and hygiene readings merge over the version's earlier ones, so judging one question later does not drop the others. Saves to - one file take turns; each writes through a temporary file of its own.""" - paths = _paths(ws_dir, job_id, trial_name, lane) - path = paths[0] + one file take turns, across processes; each writes through a temporary file of its own.""" + if not job_id: + raise ValueError("a judgement needs the job's identity") + found = _paths(base, job_id, trial_name, lane) + path = found[0] os.makedirs(os.path.dirname(path), exist_ok=True) - with _lock(path): - data = _read(paths) + with _locked(path): + data = _read(found) version = record.get("questions", Q.VERSION) earlier = data.get(version) or {} if not _of(earlier, started): # another try's: kept beside, and none of its answers are this one's @@ -137,33 +151,32 @@ def save(ws_dir: str, job_id: str, trial_name: str, record: dict, lane: str = "d return merged -def for_job(ws_dir: str, job_id: str, started: dict, version: Optional[str] = None, lane: str = "decision") -> dict: +def for_job(base: str, job_id: str, started: dict, version: Optional[str] = None, lane: str = "decision") -> dict: """The judged trials of a job: {trial_name: record} for each trial of `started` - {trial_name: its start}, every trial of the job - that has one, as `load` picks it.""" out = {} for name, start in started.items(): - rec = load(ws_dir, job_id, name, version, lane, start) + rec = load(base, job_id, name, version, lane, start) if rec: out[name] = rec return out -def job_dirs(ws_dir: str, job_ids) -> list: +def job_dirs(base: str, job_ids) -> list: """The folders that hold these jobs' judgements, in every lane.""" - return [d for lane in ROOTS for j in job_ids for n in _names(j) if os.path.isdir(d := os.path.join(_root(ws_dir, lane), n))] + return [d for lane in ROOTS for j in job_ids if j for n in _names(j) if os.path.isdir(d := os.path.join(_root(base, lane), n))] -def count(ws_dir: str) -> int: - """The stored judgements of a workspace, every lane: one per trial and - lane, its versions inside.""" - return sum(n.endswith(".json") for lane in ROOTS for _, _, names in os.walk(_root(ws_dir, lane)) for n in names) +def count_in(dirs) -> int: + """The judgements stored in these folders: one per trial and lane, its versions inside.""" + return sum(n.endswith(".json") for d in dirs for _, _, names in os.walk(d) for n in names) -def all_records(ws_dir: str, job_id: Optional[str] = None, lane: str = "decision"): +def all_records(base: str, job_id: Optional[str] = None, lane: str = "decision"): """Every stored record, every version: yields (job_id, trial_name, version, record). One job's when `job_id` is given.""" - root = _root(ws_dir, lane) + root = _root(base, lane) try: jobs = list(_names(job_id)) if job_id else sorted(os.listdir(root)) except OSError: @@ -187,15 +200,15 @@ def all_records(ws_dir: str, job_id: Optional[str] = None, lane: str = "decision yield j, n[:-5], version, rec -def calibration(ws_dir: Optional[str]) -> Optional[dict]: - """The judge's observed characters per token over this workspace's - stored calls (`client.calibrate`); None with no workspace or no sample.""" - if not ws_dir: +def calibration(base: Optional[str]) -> Optional[dict]: + """The judge's observed characters per token over the stored calls + (`client.calibrate`); None with no store or no sample.""" + if not base: return None - return client.calibrate(rec for _, _, _, rec in all_records(ws_dir)) + return client.calibrate(rec for _, _, _, rec in all_records(base)) -def truncation_report(ws_dir: str, job_id: str, limit: Optional[int] = None) -> dict: +def truncation_report(base: str, job_id: str, limit: Optional[int] = None) -> dict: """Which state kinds were cut to the limit over a job's stored calls, and how often - counted here. `kinds[kind]` is {calls, truncated, max_chars}, most-truncated first; `untyped` counts records that say @@ -204,7 +217,7 @@ def truncation_report(ws_dir: str, job_id: str, limit: Optional[int] = None) -> limit = judge_state.LIMIT if limit is None else limit kinds: dict = {} records = truncated = untyped = 0 - for _, _, _, rec in all_records(ws_dir, job_id): + for _, _, _, rec in all_records(base, job_id): records += 1 if rec.get("truncated"): truncated += 1 @@ -222,3 +235,73 @@ def truncation_report(ws_dir: str, job_id: str, limit: Optional[int] = None) -> def pair_key(a_trial: str, b_trial: str) -> str: return "pair:" + _SAFE.sub("_", a_trial) + "__vs__" + _SAFE.sub("_", b_trial) + + +def task_dataset(job) -> str: + """Where a dataset's task-instruction judgements are kept (lane `TASKS`), + so an instruction is judged once for every run of that dataset: its + recorded path, or its registry name, so two datasets of one folder name + keep apart; a job that names none, its own identity.""" + return job.dataset_path or job.dataset or "job:" + job.uid + + +def _digest(rec) -> str: + return hashlib.sha256(json.dumps(rec, sort_keys=True).encode("utf-8")).hexdigest()[:10] + + +def _merge_into(path: str, data: dict) -> None: + """Records of an older store into the file at `path`: each one not there + yet is added. Where the file has another under its key, the one shown + stays there and the other is kept beside: of two tries, the later try's + shown and the earlier under its own start (`_try`); of one try, the + newer by `asked_at` shown and the other under ``~``. + Nothing is dropped, and adding the same record again changes nothing.""" + os.makedirs(os.path.dirname(path), exist_ok=True) + with _locked(path): + cur = _read([path]) + have = {_digest(r) for r in cur.values()} + changed = False + for k, rec in data.items(): + if not isinstance(rec, dict) or _digest(rec) in have: + continue + now = cur.get(k) + if now is None: + cur[k] = rec + else: + a, b = now.get("trial_started_at"), rec.get("trial_started_at") + tries = bool(a and b and a != b) + newer = str(b) > str(a) if tries else str(rec.get("asked_at") or "") > str(now.get("asked_at") or "") + shown, other = (rec, now) if newer else (now, rec) + slot = _try(k, other["trial_started_at"]) if tries else f"{k}~{_digest(other)}" + if slot in cur: + slot = f"{slot}~{_digest(other)}" + cur[k], cur[slot] = shown, other + have |= {_digest(r) for r in cur.values()} + changed = True + if changed: + ondisk.write_whole(path, json.dumps(cur, indent=1), mode=0o600) + + +def adopt(ws_dir: str, job, into: Optional[str] = None) -> None: + """Copy what the workspace's store from before (`ws_dir`) holds for `job` + - under its job id, its trials' and its dataset's task records - into + the user's store (`into`, `home()` by default) under the job's identity. + Two jobs of one id in that workspace each get the same records, as each + showed them before. The workspace's files are left as they are.""" + if not job.uid: + return + into = into or home() + names = {n: key(t.trial_name) for t in job.trials for n in _names(t.trial_name)} + places = [(lane, j, job.uid, names) for lane in ROOTS for j in _names(job.job_id)] + # before, a dataset's task records were a job of their own, named `task:`, and a job naming none its id + places += [(TASKS, j, task_dataset(job), {}) for j in _names("task:" + (job.dataset_path or job.dataset or "job:" + job.job_id))] + for lane, old, new, rename in places: + src = os.path.join(_root(ws_dir, "decision" if lane == TASKS else lane), old) + try: + files = sorted(f for f in os.listdir(src) if f.endswith(".json")) + except OSError: + continue + for f in files: + data = _read([os.path.join(src, f)]) + if data: + _merge_into(os.path.join(_root(into, lane), key(new), rename.get(f[:-5], f[:-5]) + ".json"), data) diff --git a/app/nullius/onboarding.py b/app/nullius/onboarding.py index b256325c5..f0fc820fd 100644 --- a/app/nullius/onboarding.py +++ b/app/nullius/onboarding.py @@ -94,12 +94,13 @@ def facts(env, jobs: Iterable[dict] = (), judged: bool = False, docker: Optional def any_judged(ws_dir: Optional[str]) -> bool: - """Whether a workspace holds a judgement from either judge.""" + """Whether the user's store, or the store a workspace kept before, holds a judgement from either judge.""" from nullius.judge import store - for lane in store.ROOTS.values(): - root = os.path.join(ws_dir or "", lane) - if ws_dir and os.path.isdir(root) and any(files for _, _, files in os.walk(root)): - return True + for base in filter(None, (store.home(), ws_dir)): + for lane in store.ROOTS.values(): + root = os.path.join(base, lane) + if os.path.isdir(root) and any(n.endswith(".json") for _, _, files in os.walk(root) for n in files): + return True return False diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 5479fd3a1..bc8a96d88 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -219,14 +219,33 @@ def touch(ws: Workspace) -> None: def delete(home_dir: str, name: str) -> bool: """Remove a workspace: its record, its parse cache and its converted - imports. The job roots it pointed at are not touched. True when something was removed.""" + imports. The job roots it pointed at are not touched, nor the + judgements of their jobs (`_keep_judgements`). True when something was removed.""" ws = load(home_dir, name) if ws is None: return False + _keep_judgements(ws) shutil.rmtree(ws.dir, ignore_errors=True) return True +def _keep_judgements(ws: Workspace) -> None: + """The judgements a workspace kept before they were kept by job + (``/judgements{,-llm}/``): copied into the user's store under + each job its roots hold, then its files moved there whole, so none is + lost with it - a job its roots no longer reach included.""" + from nullius.judge import store + old = [d for r in store.ROOTS.values() if os.path.isdir(d := os.path.join(ws.dir, r))] + if not old: + return + for job in load_jobs(ws, ws.job_roots or ws.roots): + store.adopt(ws.dir, job) + keep = os.path.join(store.home(), "judgements-of-deleted-workspaces", 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) + + 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/templates/workspaces/workspaces.html b/app/templates/workspaces/workspaces.html index 0e226d33c..1f1108b79 100644 --- a/app/templates/workspaces/workspaces.html +++ b/app/templates/workspaces/workspaces.html @@ -44,7 +44,7 @@ {%- set _ = items.append(dict(open=open, name=dict(text=ws.label, class='ws-name', after=pencil(ws) ~ rename(ws, 'cards')), disk=ws.name if labels.count(ws.label) > 1 else '', runs=counts[ws.name].runs, checks=counts[ws.name].checks, opened=dict(text=ws.opened[:16]|replace('T', ' '), value=opened(ws)), launches=dict(text=launches(ws), value=n_launches[ws.name]), roots=dict(text=roots(ws), value=ws.roots|length), - actions=dict(title='Delete workspace', attrs={'data-ask': 'ws-ask-delete', 'data-label': ws.label, 'data-action': url_for('workspace_delete', name=ws.name), 'data-judged': n_judged[ws.name], 'aria-haspopup': 'dialog', 'aria-label': 'Delete workspace ' ~ ws.label}), + actions=dict(title='Delete workspace', attrs={'data-ask': 'ws-ask-delete', 'data-label': ws.label, 'data-action': url_for('workspace_delete', name=ws.name), 'aria-haspopup': 'dialog', 'aria-label': 'Delete workspace ' ~ ws.label}), search=ws.label ~ ' ' ~ ws.name)) %} {%- endfor %} {{ cards('workspaces', cols, items, search='Search by name', empty='No workspace matches.', noun='workspaces', sort=true, layout='cards') }} @@ -65,7 +65,7 @@ {%- elif c.key == 'launches' %}{% call cell(c) %}{{ launches(ws) }}{% endcall %} {%- elif c.key == 'roots' %}{% call cell(c, sort=ws.roots|length) %}{{ roots(ws) }}{% endcall %} {%- elif c.key == 'actions' %}{% call cell(c, class='acts-col') %} - + {% endcall %} {%- endif %} {% endcall %} @@ -90,10 +90,9 @@ // a template of the page, or, for an address, the server's answer: what a Delete takes is worked out only now const content = async b => { if (b.dataset.ask === 'ws-ask-delete') { - const c = document.getElementById('ws-ask-delete').content.cloneNode(true), n = +b.dataset.judged; + const c = document.getElementById('ws-ask-delete').content.cloneNode(true); c.querySelector('h2').append(b.dataset.label); c.querySelector('form').action = b.dataset.action; - if (n) c.querySelector('p').prepend(`Its judgements (${n}) are deleted. `); return c; } if (!b.dataset.ask.startsWith('/')) return b.closest('[data-holder]').querySelector('template.' + b.dataset.ask).content.cloneNode(true); diff --git a/app/tests/fixtures/judge/workspace-store/judgements-llm/job-x/t0.json b/app/tests/fixtures/judge/workspace-store/judgements-llm/job-x/t0.json new file mode 100644 index 000000000..323e23195 --- /dev/null +++ b/app/tests/fixtures/judge/workspace-store/judgements-llm/job-x/t0.json @@ -0,0 +1,8 @@ +{ + "judgement.questions.v2": { + "questions": "judgement.questions.v2", + "judge": {"model": "llm-judge"}, + "asked_at": "2026-11-01T10:05:00Z", + "answers": {"failure_cause": {"choice": "environment_error"}} + } +} diff --git a/app/tests/fixtures/judge/workspace-store/judgements/job-x/t0.json b/app/tests/fixtures/judge/workspace-store/judgements/job-x/t0.json new file mode 100644 index 000000000..40443ec8e --- /dev/null +++ b/app/tests/fixtures/judge/workspace-store/judgements/job-x/t0.json @@ -0,0 +1,8 @@ +{ + "judgement.questions.v2": { + "questions": "judgement.questions.v2", + "judge": {"model": "decision-model"}, + "asked_at": "2026-11-01T10:00:00Z", + "answers": {"failure_cause": {"choice": "agent_error", "confidence": 0.8}} + } +} diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index 543ff55c7..e531aca1d 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -192,13 +192,13 @@ def test_save_load_merge_and_survive_a_reparse(self): self.assertEqual(store.load(self.ws.dir, "job-1", "task__abc/def")["answers"]["task_completed"], {"noul": 0.9}) def test_count_is_one_per_trial_and_lane_every_version_inside(self): - self.assertEqual(store.count(self.ws.dir), 0) + count = lambda: store.count_in(store.job_dirs(self.ws.dir, ["job-1", "job-2"])) + self.assertEqual(count(), 0) for version in ("judgement.questions.v1", questions.VERSION): store.save(self.ws.dir, "job-1", "t0", {"questions": version, "answers": {}}) # two versions: one judgement store.save(self.ws.dir, "job-1", "t1", {"questions": "v", "answers": {}}) store.save(self.ws.dir, "job-2", "t0", {"questions": "v", "answers": {}}, lane="llm") - (Path(self.ws.jobs_dir)).mkdir(parents=True, exist_ok=True); (Path(self.ws.jobs_dir) / "x.json").write_text("{}") # the cache: not one - self.assertEqual(store.count(self.ws.dir), 3) + self.assertEqual(count(), 3) # the lock beside them: not one class Versions(unittest.TestCase): diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py new file mode 100644 index 000000000..c6c209a06 --- /dev/null +++ b/app/tests/test_judge_adopt.py @@ -0,0 +1,85 @@ +"""Judgements kept in a workspace before they were kept by job +(``/judgements{,-llm}//``) are still read: copied into the +user's store under the job's identity, the old files left as they are; a +trial judged in two workspaces keeps both records, the newer shown.""" +from __future__ import annotations + +import json +import os +import shutil +import tempfile +import unittest +from types import SimpleNamespace as NS +from unittest.mock import patch + +from nullius import workspace +from nullius.judge import questions as Q, store + +from tests.test_workspace import _job_dir + +FIXTURE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "judge", "workspace-store") + + +def rec(asked_at, choice="x"): + return {"questions": Q.VERSION, "answers": {"q": {"choice": choice}}, "asked_at": asked_at} + + +def job(job_id, uid, trials=("t0",)): + return NS(job_id=job_id, uid=uid, dataset="", dataset_path="", trials=[NS(trial_name=t) for t in trials]) + + +class Adopt(unittest.TestCase): + def setUp(self): + 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) + self.a, self.b = (os.path.join(self.tmp, n) for n in "ab") + + def test_a_record_kept_in_a_workspace_is_read_under_the_job_and_its_file_stays(self): + shutil.copytree(FIXTURE, self.a) # a workspace's store as it was kept before + before = open(os.path.join(self.a, "judgements", "job-x", "t0.json")).read() + for _ in range(2): # twice: nothing added the second time + store.adopt(self.a, job("job-x", "uid-1")) + self.assertEqual(store.load(self.home, "uid-1", "t0")["answers"]["failure_cause"]["choice"], "agent_error") + self.assertEqual(store.load(self.home, "uid-1", "t0", lane="llm")["answers"]["failure_cause"]["choice"], "environment_error") + with open(os.path.join(self.home, "judgements", "uid-1", "t0.json")) as f: + self.assertEqual(list(json.load(f)), [Q.VERSION]) + self.assertEqual(open(os.path.join(self.a, "judgements", "job-x", "t0.json")).read(), before) + + def test_a_trial_judged_in_two_workspaces_shows_the_newer_and_keeps_the_other(self): + store.save(self.a, "job-x", "t0", rec("2026-01-02T00:00:00Z", "newer")) + store.save(self.b, "job-x", "t0", rec("2026-01-01T00:00:00Z", "older")) + for ws in (self.b, self.a, self.b): + store.adopt(ws, job("job-x", "uid-1")) + self.assertEqual(store.load(self.home, "uid-1", "t0")["answers"]["q"]["choice"], "newer") + kept = [r["answers"]["q"]["choice"] for _, _, _, r in store.all_records(self.home, "uid-1")] + self.assertEqual(sorted(kept), ["newer", "older"]) + + def test_two_jobs_of_one_id_in_a_workspace_each_get_its_record(self): + store.save(self.a, "job-x", "t0", rec("2026-01-01T00:00:00Z")) + for uid in ("uid-1", "uid-2"): + store.adopt(self.a, job("job-x", uid)) + self.assertEqual([bool(store.load(self.home, u, "t0")) for u in ("uid-1", "uid-2")], [True, True]) + + def test_a_task_score_kept_as_a_job_is_read_by_its_dataset(self): + store.save(self.a, "task:/ds/bench", "fix@abc", rec("2026-01-01T00:00:00Z")) + run = job("run-1", "uid-1"); run.dataset, run.dataset_path = "bench", "/ds/bench" + store.adopt(self.a, run) + self.assertTrue(store.load(self.home, "/ds/bench", "fix@abc", lane=store.TASKS)) + + def test_deleting_a_workspace_keeps_its_judgements(self): + root = os.path.join(self.tmp, "jobs"); _job_dir(root, "job-a") + ws = workspace.create(os.path.join(self.tmp, "ws"), [root], label="w") + [j] = workspace.load_jobs(ws, ws.roots) + store.save(ws.dir, "job-a", j.trials[0].trial_name, rec("2026-01-01T00:00:00Z")) + store.save(ws.dir, "job-gone", "t0", rec("2026-01-01T00:00:00Z")) # a job its roots no longer reach + workspace.delete(os.path.dirname(ws.dir), ws.name) + self.assertFalse(os.path.exists(ws.dir)) + self.assertTrue(store.load(self.home, j.uid, j.trials[0].trial_name)) + [kept] = os.listdir(os.path.join(self.home, "judgements-of-deleted-workspaces")) + self.assertTrue(os.path.isfile(os.path.join(self.home, "judgements-of-deleted-workspaces", kept, "judgements", "job-gone", "t0.json"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_judge_store_race.py b/app/tests/test_judge_store_race.py index 7d0b1c2e9..82b9a25f0 100644 --- a/app/tests/test_judge_store_race.py +++ b/app/tests/test_judge_store_race.py @@ -2,12 +2,14 @@ from __future__ import annotations import json +import os import shutil import tempfile import threading import unittest from unittest import mock +from nullius import ondisk from nullius.judge import store @@ -44,6 +46,18 @@ def save(question): answers = store.load(ws, "job", "t1", "v1")["answers"] self.assertEqual((errors, sorted(answers)), ([], ["q1", "q2"])) + def test_a_save_waits_for_the_file_lock_another_process_would_hold(self): + base = tempfile.mkdtemp(prefix="nullius-judge-lock-") + self.addCleanup(shutil.rmtree, base, True) + store.save(base, "job", "t1", {"questions": "v1", "answers": {}}) + done = threading.Event() + save = threading.Thread(target=lambda: (store.save(base, "job", "t1", {"questions": "v1", "answers": {"q": 1}}), done.set())) + with ondisk.locked(os.path.join(base, "judgements", "job", ".lock")): # not this process's thread lock: a file's + save.start() + self.assertFalse(done.wait(0.3), "the save did not wait for the lock") + save.join(2) + self.assertEqual(store.load(base, "job", "t1", "v1")["answers"], {"q": 1}) + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index 99f0bee9e..83ded6e09 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -1,7 +1,8 @@ """Deleting a launch Nullius made, one run or a shard per machine: per run its folder, its roots and parsed jobs in every workspace, the judgements of its -trials there, and its host copy when asked; never a launch with a run still -going, nor a folder that is not a run's.""" +jobs - unless a copy of a job is still found, or a root cannot be read - and +its host copy when asked; never a launch with a run still going, nor a folder +that is not a run's.""" from __future__ import annotations import json @@ -13,6 +14,7 @@ from nullius import execution, hosts, workspace from nullius.judge import store +from nullius.runs import parse from tests.test_workspace import _job_dir, _write_json @@ -23,6 +25,8 @@ def setUp(self): self.addCleanup(shutil.rmtree, self.tmp, True) self.root, self.home = os.path.join(self.tmp, "runs"), os.path.join(self.tmp, "ws") patcher = patch.dict(execution.EXECUTIONS, clear=True); patcher.start(); self.addCleanup(patcher.stop) + self.data = os.path.join(self.tmp, "data") + patcher = patch.object(store, "home", return_value=self.data); patcher.start(); self.addCleanup(patcher.stop) self.jobs = self.run_("r1") other = os.path.join(self.tmp, "elsewhere"); _job_dir(other, "job-b") self.a = workspace.create(self.home, [self.jobs, other], label="a") @@ -42,15 +46,16 @@ def run_(self, name, state="done", host=None, step="run", job="job-a"): def test_it_asks_what_goes(self): gone = execution.deletion(["r1"], self.home, self.root) - self.assertEqual((gone["bytes"], gone["judgements"], gone["workspaces"], gone["hosts"]), (gone["runs"][0]["bytes"], 4, ["a", "b"], {})) + self.assertEqual((gone["bytes"], gone["judgements"], gone["workspaces"], gone["hosts"]), (gone["runs"][0]["bytes"], 2, ["a", "b"], {})) gone = gone["runs"][0] self.assertEqual(gone["dir"], os.path.realpath(os.path.join(self.root, "r1"))) self.assertGreater(gone["bytes"], 0) self.assertEqual(sorted(w["ws"].name for w in gone["workspaces"]), ["a", "b"]) - self.assertEqual(gone["judgements"], 4) # job-a's, in both lanes, in a and b + self.assertEqual(gone["judgements"], 2) # job-a's, in both lanes, once however many workspaces held it self.assertIsNone(gone["host"]) def test_it_deletes_the_folder_its_roots_and_its_judgements_only(self): + uid = self.uid("job-a") execution.delete(["r1"], self.home, self.root) self.assertFalse(os.path.exists(os.path.join(self.root, "r1"))) a, b, c = (workspace.load(self.home, n) for n in "abc") @@ -63,6 +68,37 @@ def test_it_deletes_the_folder_its_roots_and_its_judgements_only(self): for ws in (a, c): self.assertEqual(len(store.job_dirs(ws.dir, ["job-b"])), 2) # another root's judgements stay self.assertEqual(len(store.job_dirs(c.dir, ["job-a"])), 2) # c never held the run + self.assertEqual(store.job_dirs(self.data, [uid]), []) + + def uid(self, name, root=None): + return parse.parse_job(os.path.join(root or self.jobs, name), trials=False).uid + + def judged(self, root, name): + """A judgement of the job *name* under *root* in the user's store, as the pages make it.""" + job = parse.parse_job(os.path.join(root, name)) + store.save(self.data, job.uid, "t0", {"questions": "v", "answers": {"q": 1}}) + return job.uid + + def test_a_copy_elsewhere_or_a_root_that_cannot_be_read_keeps_the_judgements(self): + uid = self.judged(self.jobs, "job-a") + twin = os.path.join(self.tmp, "twin"); shutil.copytree(os.path.join(self.jobs, "job-a"), os.path.join(twin, "job-a")) + d = workspace.create(self.home, [twin], label="d") + self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 0) + shutil.rmtree(twin) # d's root is gone: who owns them is unknown + self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 0) + workspace.delete(self.home, d.name) + self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 2) + execution.delete(["r1"], self.home, self.root) + self.assertEqual(store.job_dirs(self.data, [uid]), []) + + def test_another_job_of_the_same_name_does_not_keep_them(self): + uid = self.judged(self.jobs, "job-a") + other = os.path.join(self.tmp, "other"); _job_dir(other, "job-a") + _write_json(os.path.join(other, "job-a", "result.json"), {"id": "j2", "started_at": "2026-09-05T00:00:00Z", "stats": {}}) + workspace.create(self.home, [other], label="d") + self.assertNotEqual(self.uid("job-a", other), uid) + execution.delete(["r1"], self.home, self.root) + self.assertEqual(store.job_dirs(self.data, [uid]), []) def test_a_job_of_the_same_id_in_another_root_keeps_its_judgements(self): twin = os.path.join(self.tmp, "twin"); _job_dir(twin, "job-a") @@ -75,7 +111,7 @@ def test_a_job_of_the_same_id_deleted_from_another_root_keeps_none(self): twin = os.path.join(self.tmp, "twin"); _job_dir(twin, "job-a") self.a.roots.append(twin); workspace.save(self.a); workspace.load_jobs(self.a, self.a.roots) shutil.rmtree(os.path.join(twin, "job-a")) # the older copy deleted by hand - self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 4) + self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 2) execution.delete(["r1"], self.home, self.root) self.assertEqual(store.job_dirs(self.a.dir, ["job-a"]), []) diff --git a/app/ui_tests/test_failure_analysis_routes.py b/app/ui_tests/test_failure_analysis_routes.py index 2d5fe5cb1..f4728f725 100644 --- a/app/ui_tests/test_failure_analysis_routes.py +++ b/app/ui_tests/test_failure_analysis_routes.py @@ -173,6 +173,7 @@ def setUp(self): stack = ExitStack() self.addCleanup(stack.close) stack.enter_context(patch.object(web.shared, "WS_HOME", str(tmp / "ws"))) + stack.enter_context(patch.object(store, "home", return_value=str(tmp / "data"))) stack.enter_context(patch.dict(web.app.config, TESTING=True)) stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []})) stack.enter_context(patch.object(fa, "who", lambda: "Ann")) diff --git a/app/ui_tests/test_judge_calibration_reads.py b/app/ui_tests/test_judge_calibration_reads.py index 91b49d920..6a7938349 100644 --- a/app/ui_tests/test_judge_calibration_reads.py +++ b/app/ui_tests/test_judge_calibration_reads.py @@ -28,6 +28,7 @@ def setUp(self): self.addCleanup(stack.close) tmp = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="nullius-judge-calib-"))) stack.enter_context(patch.object(web.shared, "WS_HOME", str(tmp / "workspaces"))) + stack.enter_context(patch.object(web.judge.store, "home", return_value=str(tmp / "data"))) stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) stack.enter_context(patch.dict(os.environ, TYPESAFE_API_KEY="ts-fake")) stack.enter_context(patch.object(web.judge.batch, "ask_states", side_effect=rec)) @@ -40,8 +41,8 @@ def setUp(self): def reads_to_judge_all(self, n): web.shared.open_workspace(workspace.create(web.shared.WS_HOME, [], f"w{n}")) job_id = "job" - trials = [NS(trial_name=f"t{i}", has_trajectory=True, trajectory_path="-", started_at=None, outcome="resolved") for i in range(n)] - job = NS(job_id=job_id, trials=trials) + trials = [NS(trial_name=f"t{i}", key=f"t{i}", has_trajectory=True, trajectory_path="-", started_at=None, outcome="resolved") for i in range(n)] + job = NS(job_id=job_id, uid=f"uid-{n}", dir=f"/jobs/{n}", dataset="", dataset_path="", trials=trials) real_open, reads = builtins.open, [0] def counting_open(path, mode="r", *a, **k): @@ -51,7 +52,7 @@ def counting_open(path, mode="r", *a, **k): with patch.object(web.shared, "_job_for_request", lambda j: job), patch("builtins.open", counting_open): self.assertEqual(self.client.post(f"/judge/job/{job_id}", data={"csrf": "t"}).status_code, 302) - self.assertEqual(len(web.judge.store.for_job(web.judge.ws_dir(), job_id, {t.trial_name: None for t in trials})), n) + self.assertEqual(len(web.judge.store.for_job(web.judge.store.home(), job.uid, {t.trial_name: None for t in trials})), n) return reads[0] def test_store_reads_grow_linearly_with_the_trials_judged(self): diff --git a/app/ui_tests/test_judge_other_workspace.py b/app/ui_tests/test_judge_other_workspace.py index 4915f9cb2..82b77c5f0 100644 --- a/app/ui_tests/test_judge_other_workspace.py +++ b/app/ui_tests/test_judge_other_workspace.py @@ -1,5 +1,6 @@ -"""A job of another workspace, opened with ``?workspace=``, shows and keeps its -judgements in that workspace's store, not the open one's.""" +"""A job of another workspace, opened with ``?workspace=``, shows the +judgements that workspace kept for it before, and its new ones go to the +user's store under the job's identity, into neither workspace.""" from __future__ import annotations import os @@ -9,7 +10,7 @@ from contextlib import ExitStack from dataclasses import replace from pathlib import Path -from types import SimpleNamespace as NS +from types import SimpleNamespace from unittest.mock import patch from flask import url_for @@ -31,6 +32,7 @@ def setUp(self): shutil.copytree(JOB, tmp / "a" / "job-x") shutil.copytree(JOB, tmp / "b" / "job-y") (tmp / "b" / "job-y" / TRIAL / "agent" / "trajectory.json").write_text("{}") + stack.enter_context(patch.object(store, "home", return_value=str(tmp / "data"))) stack.enter_context(patch.object(web.shared, "WS_HOME", str(tmp / "workspaces"))) stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) self.a = workspace.create(web.shared.WS_HOME, [str(tmp / "a")], "A") @@ -47,28 +49,33 @@ def test_the_trial_page_reads_the_judgement_kept_in_its_own_workspace(self): self.assertEqual(web.app.test_client().get(self.url).status_code, 200) self.assertTrue(seen[0]["judged"], "B's judgement of B's trial is not shown") - def test_judging_that_trial_writes_into_its_own_workspace(self): + def test_judging_that_trial_writes_into_neither_workspace(self): rec = {"questions": Q.VERSION, "answers": {"q": {"choice": "x"}}, "judge": {"model": "m"}} with web.app.test_request_context(self.url): job, trial = web.traces._trial_evidence("job-y", TRIAL) - with patch.object(web.judge.batch, "ask_states", return_value=dict(rec)): - web.judge.batch.ask_and_store(web.judge.ws_dir(), job.job_id, trial.trial_name, {}, None) - self.assertNotIn("judgements", os.listdir(self.a.dir), "a judgement of B's trial was written into A") - self.assertIsNotNone(store.load(self.b.dir, "job-y", TRIAL)) - - def test_judge_all_and_task_judging_write_into_its_own_workspace(self): + with patch.object(web.judge.trajectory, "load", return_value=SimpleNamespace(error=None)), \ + patch.object(web.judge, "_trial_ids_and_states", return_value={}), \ + patch.object(web.judge.batch, "ask_states", return_value=dict(rec)), \ + patch.object(trial, "has_trajectory", True): + web.judge.judge_trial(job, trial, None) + for ws in (self.a, self.b): + self.assertNotIn("judgements", os.listdir(ws.dir), f"a judgement was written into {ws.label}") + self.assertIsNotNone(store.load(store.home(), job.uid, TRIAL)) + + def test_judge_all_and_task_judging_write_into_neither_workspace(self): rec = {"questions": Q.VERSION, "answers": {"q": {"choice": "x"}}, "judge": {"model": "m"}} client = web.app.test_client() with client.session_transaction() as sess: sess["csrf"] = "t" with patch.dict(os.environ, TYPESAFE_API_KEY="ts-fake"), patch.object(web.judge.batch, "ask_states", side_effect=lambda *a, **k: dict(rec)), \ - patch.object(web.judge.trajectory, "load", lambda path: NS(error=None)), patch.object(web.judge, "_trial_ids_and_states", lambda trial, traj: {}), \ + patch.object(web.judge.trajectory, "load", lambda path: SimpleNamespace(error=None)), patch.object(web.judge, "_trial_ids_and_states", lambda trial, traj: {}), \ patch.object(web.judge, "_task_instruction", lambda trial: "Say hello."): for route in ("job", "tasks"): self.assertEqual(client.post(f"/judge/{route}/job-y?workspace={self.b.name}", data={"csrf": "t"}).status_code, 302) - self.assertNotIn("judgements", os.listdir(self.a.dir), "Judge all on B's job wrote into A") - self.assertIsNotNone(store.load(self.b.dir, "job-y", TRIAL)) - self.assertTrue(any(k.startswith("task_") for k in os.listdir(Path(self.b.dir) / "judgements")), os.listdir(Path(self.b.dir) / "judgements")) + for ws in (self.a, self.b): + self.assertNotIn("judgements", os.listdir(ws.dir), f"Judge all on B's job wrote into {ws.label}") + for lane in ("judgements", "judgements-tasks"): + self.assertTrue(any((Path(store.home()) / lane).rglob("*.json")), f"nothing kept in the profile's {lane}") def test_the_judge_forms_post_back_to_that_workspace(self): with web.app.test_request_context(self.url): diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py new file mode 100644 index 000000000..894c67233 --- /dev/null +++ b/app/ui_tests/test_judgement_follows_job.py @@ -0,0 +1,86 @@ +"""A judgement belongs to the job it judges, not to the workspace it was +made in: it shows in every workspace that holds the job, outlives the +workspace, and stays apart from another job of the same name.""" +from __future__ import annotations + +import json +import shutil +import tempfile +import unittest +from contextlib import ExitStack +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +from nullius import workspace +from nullius.judge import questions as Q + +from .test_routes import web + +JOB = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "harbor-jobs" / "liveboard-oracle-x4" +TRIAL = "hello-world__mAXMKXR" + + +def copy_job(dest: Path, started: str = "") -> Path: + shutil.copytree(JOB, dest) + (dest / TRIAL / "agent" / "trajectory.json").write_text("{}") + if started: + res = json.loads((dest / "result.json").read_text()) + (dest / "result.json").write_text(json.dumps(dict(res, started_at=started))) + (dest / "events.jsonl").unlink(missing_ok=True) + return dest + + +class JudgementFollowsTheJob(unittest.TestCase): + def setUp(self): + stack = ExitStack() + self.addCleanup(stack.close) + self.tmp = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="nullius-judge-job-"))) + stack.enter_context(patch.object(web.shared, "WS_HOME", str(self.tmp / "workspaces"))) + stack.enter_context(patch.object(web.judge.store, "home", return_value=str(self.tmp / "data"))) + stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) + rec = {"questions": Q.VERSION, "answers": {"failure_cause": {"choice": "agent_error"}}, "judge": {"model": "m"}, + "asked_at": "2026-11-01T00:00:00Z"} + stack.enter_context(patch.object(web.judge, "_trial_ids_and_states", return_value={})) + stack.enter_context(patch.object(web.judge.trajectory, "load", return_value=SimpleNamespace(error=None))) + stack.enter_context(patch.object(web.judge.batch, "ask_states", side_effect=lambda *a, **k: dict(rec))) + + def judge(self, job_id, ws=None): + q = f"?workspace={ws.name}" if ws else "" + with web.app.test_request_context(f"/trial/{job_id}/{TRIAL}{q}"): + job, trial = web.traces._trial_evidence(job_id, TRIAL) + web.judge.judge_trial(job, trial, None) + + def judged(self, job_id, ws=None) -> bool: + q = f"?workspace={ws.name}" if ws else "" + with web.app.test_request_context(f"/trial/{job_id}/{TRIAL}{q}"): + job, trial = web.traces._trial_evidence(job_id, TRIAL) + return bool(web.judge.judgement_of(job, trial)) + + def test_a_judgement_made_in_one_workspace_shows_in_another_and_outlives_it(self): + copy_job(self.tmp / "runs" / "job-x") + a = workspace.create(web.shared.WS_HOME, [str(self.tmp / "runs")], "A") + b = workspace.create(web.shared.WS_HOME, [str(self.tmp / "runs")], "B") + 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") + 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") + self.assertTrue(self.judged("job-x", c)) + + def test_two_jobs_of_one_name_in_two_roots_keep_their_own_judgements(self): + copy_job(self.tmp / "one" / "job-x", "2026-01-01T00:00:00Z") + copy_job(self.tmp / "two" / "job-x", "2026-02-02T00:00:00Z") + both = workspace.create(web.shared.WS_HOME, [str(self.tmp / "one"), str(self.tmp / "two")], "Both") + web.shared.open_workspace(both) + jobs = {Path(j.dir).parent.name: j for j in workspace.load_jobs(both, both.roots)} + trial = lambda j: next(t for t in j.trials if t.trial_name == TRIAL) + with web.app.test_request_context(f"/trial/job-x/{TRIAL}"): + web.judge.judge_trial(jobs["one"], trial(jobs["one"]), None) + seen = {k: bool(web.judge.judgement_of(j, trial(j))) for k, j in jobs.items()} + self.assertEqual(seen, {"one": True, "two": False}) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_reconcile_routes.py b/app/ui_tests/test_reconcile_routes.py index 59be52b1b..6edfef040 100644 --- a/app/ui_tests/test_reconcile_routes.py +++ b/app/ui_tests/test_reconcile_routes.py @@ -30,6 +30,7 @@ def setUp(self): self.stack = ExitStack(); self.addCleanup(self.stack.close) self.stack.enter_context(patch.dict(web.app.config, TESTING=True)) self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup) + self.stack.enter_context(patch.object(store, "home", return_value=self.tmp.name + "/data")) self.job = write_job(self.tmp.name, "r-agent", "my-agent", { "solved": 1, "failed": 0, "setup": "EnvironmentSetupError", "limited": "ApiRateLimitError", "odd": "SomethingNobodyKnowsError", "weak": 0}) self.nop = write_job(self.tmp.name, "r-nop", "nop", {"a": 0}) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index cd25e91f1..c88dbb0f3 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -543,6 +543,7 @@ def setUp(self): self.stack = ExitStack(); self.addCleanup(self.stack.close) self.tmp = Path(tempfile.mkdtemp(prefix="nullius-wsdel-")); self.addCleanup(shutil.rmtree, self.tmp, True) self.stack.enter_context(patch.object(web.shared, "WS_HOME", str(self.tmp / "ws"))) + self.stack.enter_context(patch.object(web.judge.store, "home", return_value=str(self.tmp / "data"))) self.stack.enter_context(patch.dict(web.app.config, TESTING=True)) self.stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []})) root = self.tmp / "jobs"; root.mkdir() @@ -574,7 +575,7 @@ def test_the_page_is_a_table_or_cards_and_renders_only_the_one_chosen(self): self.assertRegex(card, r'
Launches
.*?
Roots
`; + const back = document.activeElement; + document.body.append(d); + d.showModal(); + d.querySelector('[data-a=move]').focus(); + d.addEventListener('click', async e => { + const a = e.target.closest('[data-a]')?.dataset.a; + if (a === 'later') return d.close(); + if (a !== 'move') return; + e.target.disabled = true; + const r = await nulliusFetch(URL_, {method: 'POST', headers: {'X-CSRF-Token': CSRF, Accept: 'application/json'}}).catch(() => null); + const j = r ? await r.json().catch(() => ({})) : {}; + d.returnValue = 'move'; d.close(); + if (j.ok) { + notify('Judgements moved.'); + document.querySelectorAll('[data-move-judgements-row]').forEach(x => x.remove()); + } else notify(j.error || 'The judgements could not be moved.', {error: true}); + }); + // Escape, like Not now + d.addEventListener('close', () => { + remember(); d.remove(); back?.focus(); + if (d.returnValue !== 'move' && later) notify('Move them later in Settings › Judges.'); + }); + } + + 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; + 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 fd439811c..063b355fc 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -418,6 +418,7 @@ {% endif %} +{% if judgements_unmoved() %}{% endif %} {% if not embedded %}
diff --git a/app/templates/runs/_launch_ask.html b/app/templates/runs/_launch_ask.html index ca2a3a58d..4e909a3d9 100644 --- a/app/templates/runs/_launch_ask.html +++ b/app/templates/runs/_launch_ask.html @@ -4,7 +4,7 @@
{% if back %}{% endif %}
    {{ caller() }}
-

{{ k }} folder{{ '' if k == 1 else 's' }} · {{ gone.bytes|filesizeformat }}{% if n %} · {{ n }} judgement{{ '' if n == 1 else 's' }}{% endif %}{% if wss %} · workspace{{ '' if wss|length == 1 else 's' }} {{ wss|join(', ') }}{% endif %}

+

{{ k }} folder{{ '' if k == 1 else 's' }} · {{ gone.bytes|filesizeformat }}{% if n %} · up to {{ n }} judgement{{ '' if n == 1 else 's' }}{% endif %}{% if wss %} · workspace{{ '' if wss|length == 1 else 's' }} {{ wss|join(', ') }}{% endif %}

{% for h, c in gone.hosts.items() %}{% endfor %}
diff --git a/app/templates/settings/settings.html b/app/templates/settings/settings.html index 92fd92570..cda4b2647 100644 --- a/app/templates/settings/settings.html +++ b/app/templates/settings/settings.html @@ -234,6 +234,12 @@

Judges

{{ field(by['LLM_JUDGE_MODEL'], 'Model', writable, picker='[data-picker]') }} {% endif %} + {% if old_judgements and writable %} +
+
In workspaces + {{ old_judgements|sum(attribute=1) }} judgement{{ '' if old_judgements|sum(attribute=1) == 1 else 's' }}
+
+ {% endif %} {% include "settings/custom_keys.html" %} diff --git a/app/templates/workspaces/_root_ask.html b/app/templates/workspaces/_root_ask.html index 6b6331ce8..980133b29 100644 --- a/app/templates/workspaces/_root_ask.html +++ b/app/templates/workspaces/_root_ask.html @@ -4,7 +4,7 @@

{{ run.dir }}

-

{{ n_runs }} run{{ '' if n_runs == 1 else 's' }}{% if n_checks %} · {{ n_checks }} check{{ '' if n_checks == 1 else 's' }}{% endif %} · {{ gone.bytes|filesizeformat }}{% if gone.judgements %} · {{ gone.judgements }} judgement{{ '' if gone.judgements == 1 else 's' }}{% endif %}

+

{{ n_runs }} run{{ '' if n_runs == 1 else 's' }}{% if n_checks %} · {{ n_checks }} check{{ '' if n_checks == 1 else 's' }}{% endif %} · {{ gone.bytes|filesizeformat }}{% if gone.judgements %} · up to {{ gone.judgements }} judgement{{ '' if gone.judgements == 1 else 's' }}{% endif %}

{% if others %}

Also removed from {{ others|join(', ') }}.

{% endif %} {% for h, c in gone.hosts.items() %}{% endfor %}
diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index c6c209a06..e401375fd 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -25,7 +25,7 @@ def rec(asked_at, choice="x"): def job(job_id, uid, trials=("t0",)): - return NS(job_id=job_id, uid=uid, dataset="", dataset_path="", trials=[NS(trial_name=t) for t in trials]) + return NS(job_id=job_id, uid=uid, dataset="", dataset_path="", trials=[NS(trial_name=t, key=t, n_retries=0) for t in trials]) class Adopt(unittest.TestCase): @@ -44,7 +44,7 @@ def test_a_record_kept_in_a_workspace_is_read_under_the_job_and_its_file_stays(s self.assertEqual(store.load(self.home, "uid-1", "t0")["answers"]["failure_cause"]["choice"], "agent_error") self.assertEqual(store.load(self.home, "uid-1", "t0", lane="llm")["answers"]["failure_cause"]["choice"], "environment_error") with open(os.path.join(self.home, "judgements", "uid-1", "t0.json")) as f: - self.assertEqual(list(json.load(f)), [Q.VERSION]) + self.assertEqual(list(json.load(f)), [Q.VERSION, store.ADOPTED]) self.assertEqual(open(os.path.join(self.a, "judgements", "job-x", "t0.json")).read(), before) def test_a_trial_judged_in_two_workspaces_shows_the_newer_and_keeps_the_other(self): @@ -80,6 +80,70 @@ def test_deleting_a_workspace_keeps_its_judgements(self): [kept] = os.listdir(os.path.join(self.home, "judgements-of-deleted-workspaces")) self.assertTrue(os.path.isfile(os.path.join(self.home, "judgements-of-deleted-workspaces", kept, "judgements", "job-gone", "t0.json"))) + def test_an_earlier_try_is_read_under_its_trial_filed_under_its_try(self): + first, last = "2026-01-01T00:00:00Z", "2026-01-01T01:00:00Z" + store.save(self.a, "job-x", "t0.try-1", rec("2026-01-01T00:30:00Z", "first try"), started=first) + store.save(self.a, "job-x", "t0", rec("2026-01-01T01:30:00Z", "last try"), started=last) + run = job("job-x", "uid-1"); run.trials[0].n_retries = 1 + old = store.overlay(self.a, run) + for name, read in (("read", lambda **k: store.load(self.home, "uid-1", "t0", old=old, **k)), + ("copied", lambda **k: store.load(self.home, "uid-1", "t0", **k))): + with self.subTest(name): + if name == "copied": + store.adopt(self.a, run) + self.assertEqual(read(started=first)["answers"]["q"]["choice"], "first try") + self.assertEqual(read(started=last)["answers"]["q"]["choice"], "last try") + + def test_a_record_copied_once_is_not_copied_again_after_a_save_changed_it(self): + store.save(self.a, "job-x", "t0", rec("2026-01-01T00:00:00Z")) + run = job("job-x", "uid-1") + store.adopt(self.a, run) + store.save(self.home, "uid-1", "t0", dict(rec("2026-01-02T00:00:00Z"), answers={"other": {"choice": "y"}})) + store.adopt(self.a, run) + shown = store.load(self.home, "uid-1", "t0", old=store.overlay(self.a, run)) + self.assertEqual(set(shown["answers"]), {"q", "other"}) + with open(os.path.join(self.home, "judgements", "uid-1", "t0.json")) as f: + self.assertEqual(sorted(json.load(f)), [Q.VERSION, store.ADOPTED]) # no second slot of the same record + + def test_an_old_file_that_holds_no_object_is_skipped(self): + d = os.path.join(self.a, "judgements", "job-x"); os.makedirs(d) + for name, body in (("t0", [1, 2]), ("t1", {Q.VERSION: [1]})): + with open(os.path.join(d, name + ".json"), "w") as f: + json.dump(body, f) + run = job("job-x", "uid-1", trials=("t0", "t1")) + self.assertIsNone(store.load(self.home, "uid-1", "t0", old=store.overlay(self.a, run))) + store.adopt(self.a, run) + self.assertEqual(list(store.all_records(self.home, "uid-1")), []) + + def test_a_store_file_that_cannot_be_read_is_never_written_over(self): + store.save(self.a, "job-x", "t0", rec("2026-01-01T00:00:00Z")) + path = os.path.join(self.home, "judgements", "uid-1", "t0.json"); os.makedirs(os.path.dirname(path)) + with open(path, "w") as f: + f.write('{"judgement.questions.v2": {"questi') # cut short + for name, write in (("a save", lambda: store.save(self.home, "uid-1", "t0", rec("2026-01-02T00:00:00Z"))), + ("a copy", lambda: store.adopt(self.a, job("job-x", "uid-1")))): + with self.subTest(name), self.assertRaises(store.Unreadable): + write() + self.assertEqual(open(path).read(), '{"judgement.questions.v2": {"questi') + + def test_the_move_waits_for_a_root_that_cannot_be_read(self): + root = os.path.join(self.tmp, "jobs"); _job_dir(root, "job-a") + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [root], label="w") + [j] = workspace.load_jobs(ws, ws.roots) + store.save(ws.dir, "job-a", j.trials[0].trial_name, rec("2026-01-01T00:00:00Z")) + os.rename(root, root + ".away") + self.assertEqual(store.move(home_dir), ["w"]) + self.assertFalse(store.moved()) + with self.assertRaisesRegex(ValueError, "cannot be read"): + workspace.delete(home_dir, ws.name) + self.assertTrue(os.path.isdir(ws.dir)) + os.rename(root + ".away", root) + self.assertEqual(store.move(home_dir), []) + self.assertTrue(store.moved()) + self.assertEqual(store.old_stores(home_dir), []) + self.assertTrue(store.load(self.home, j.uid, j.trials[0].trial_name)) + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_judge_cost.py b/app/tests/test_judge_cost.py index 8582b14f5..b6f32c5bd 100644 --- a/app/tests/test_judge_cost.py +++ b/app/tests/test_judge_cost.py @@ -92,7 +92,8 @@ def test_the_store_walks_every_record_and_every_version_and_calibrates(self): seen = sorted((j, t, v) for j, t, v, _ in store.all_records(self.d)) self.assertEqual(seen, [("job-a", "t1", "judgement.questions.v1"), ("job-a", "t1", "judgement.questions.v2"), ("job-b", store.key("t/2"), "judgement.questions.v2")]) self.assertEqual([t for _, t, _, _ in store.all_records(self.d, "job-b")], [store.key("t/2")]) - self.assertEqual(store.calibration(self.d), {"chars_per_token": 3.25, "n": 2, "low": 2.5, "high": 3.5, "n_large": 0}) # small samples only: the band widened to the default + self.assertEqual(store.calibration(self.d, ["job-a", "job-b"]), {"chars_per_token": 3.25, "n": 2, "low": 2.5, "high": 3.5, "n_large": 0}) # small samples only: the band widened to the default + self.assertEqual(store.calibration(self.d, ["job-a"])["n"], 1) # the jobs asked for, never every record def test_truncation_is_counted_per_state_kind_so_the_cut_state_can_be_named(self): limit = state.LIMIT @@ -122,7 +123,7 @@ def post(url, body, key): self.assertTrue(all(v["request_chars"] > v["chars"] and v["input_tokens"] == v["request_chars"] // 4 for v in rec["states"].values())) rep = store.truncation_report(self.d, "job") self.assertEqual((rep["kinds"]["final"]["truncated"], rep["kinds"]["trial"]["truncated"], rep["untyped"]), (1, 0, 0)) - cal = store.calibration(self.d) + cal = store.calibration(self.d, ["job"]) self.assertEqual((round(cal["chars_per_token"]), cal["n"], cal["n_large"]), (4, 2, 0)) # read over the request, not the state alone self.assertEqual((cal["low"], cal["high"]), (2.5, round(cal["chars_per_token"], 3))) # small samples: the pooled ratio widened to the default band self.assertNotIn(KEY, json.dumps(rec)) diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index 83ded6e09..eaddd4c2b 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -83,12 +83,17 @@ def test_a_copy_elsewhere_or_a_root_that_cannot_be_read_keeps_the_judgements(sel uid = self.judged(self.jobs, "job-a") twin = os.path.join(self.tmp, "twin"); shutil.copytree(os.path.join(self.jobs, "job-a"), os.path.join(twin, "job-a")) d = workspace.create(self.home, [twin], label="d") - self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 0) + self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 2) # asked: its jobs' all, nothing checked + execution.delete(["r1"], self.home, self.root) + self.assertTrue(store.job_dirs(self.data, [uid])) # a copy is in d shutil.rmtree(twin) # d's root is gone: who owns them is unknown - self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 0) + self.run_("r2") + self.assertEqual(self.uid("job-a", os.path.join(self.root, "r2", "jobs")), uid) + execution.delete(["r2"], self.home, self.root) + self.assertTrue(store.job_dirs(self.data, [uid])) workspace.delete(self.home, d.name) - self.assertEqual(execution.deletion(["r1"], self.home, self.root)["judgements"], 2) - execution.delete(["r1"], self.home, self.root) + self.run_("r3") + execution.delete(["r3"], self.home, self.root) self.assertEqual(store.job_dirs(self.data, [uid]), []) def test_another_job_of_the_same_name_does_not_keep_them(self): diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 894c67233..c9eab0601 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -82,5 +82,84 @@ def test_two_jobs_of_one_name_in_two_roots_keep_their_own_judgements(self): self.assertEqual(seen, {"one": True, "two": False}) +def tree(root: Path) -> dict: + """Every file under *root* and its bytes, and every folder.""" + return {str(p.relative_to(root)): p.read_bytes() if p.is_file() else None for p in sorted(root.rglob("*"))} if root.exists() else {} + + +class JudgementsKeptBefore(unittest.TestCase): + """Records a workspace kept before are shown by a read that writes + nothing, and copied into the user's store only by the move.""" + def setUp(self): + stack = ExitStack() + self.addCleanup(stack.close) + self.tmp = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="nullius-judge-move-"))) + stack.enter_context(patch.object(web.shared, "WS_HOME", str(self.tmp / "workspaces"))) + stack.enter_context(patch.object(web.judge.store, "home", return_value=str(self.tmp / "data"))) + stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) + copy_job(self.tmp / "runs" / "job-x") + self.ws = workspace.create(web.shared.WS_HOME, [str(self.tmp / "runs")], "A") + old = Path(self.ws.dir) / "judgements" / "job-x" + old.mkdir(parents=True) + (old / f"{TRIAL}.json").write_text(json.dumps({Q.VERSION: { + "questions": Q.VERSION, "answers": {"failure_cause": {"choice": "agent_error"}}, "judge": {"model": "m"}, + "asked_at": "2026-11-01T00:00:00Z"}})) + web.shared.open_workspace(self.ws) + self.client = web.app.test_client() + + def get(self, url): + r = self.client.get(url, follow_redirects=True); self.addCleanup(r.close) + self.assertEqual(r.status_code, 200, url) + return r + + def token(self): + self.get("/settings") + with self.client.session_transaction() as s: + return s["csrf"] + + def shown(self) -> bool: + with web.app.test_request_context(f"/trial/job-x/{TRIAL}"): + job, trial = web.traces._trial_evidence("job-x", TRIAL) + return bool(web.judge.judgement_of(job, trial)) + + def test_a_job_page_shows_them_and_writes_nothing(self): + self.get("/") # the workspace parsed, as any page leaves it + before = tree(self.tmp / "data"), tree(Path(self.ws.dir) / "judgements") + page = self.get("/job/job-x").get_data(as_text=True) + self.get(f"/trial/job-x/{TRIAL}") + self.assertEqual((tree(self.tmp / "data"), tree(Path(self.ws.dir) / "judgements")), before) + self.assertTrue(self.shown()) + self.assertIn("judgements-move.js", page) + + def test_the_move_copies_them_once_and_says_so_where_it_is_offered(self): + self.assertEqual(self.get("/judgements/move").get_json(), {"workspaces": [{"label": "A", "n": 1}]}) + self.assertIn("data-move-judgements", self.get("/settings").get_data(as_text=True)) + self.assertEqual(self.client.post("/judgements/move", data={"csrf": "stale"}).status_code, 403) + self.assertFalse((self.tmp / "data").exists()) + old = tree(Path(self.ws.dir) / "judgements") + for _ in range(2): # twice: the second changes nothing + r = self.client.post("/judgements/move", headers={"X-CSRF-Token": self.token()}); self.addCleanup(r.close) + self.assertEqual(r.get_json(), {"ok": True}) + if not _: + moved = tree(self.tmp / "data") + self.assertEqual(tree(self.tmp / "data"), moved) + 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").get_data(as_text=True)) + self.assertNotIn("judgements-move.js", self.get("/").get_data(as_text=True)) + + def test_judging_a_job_checks_the_form_token_first(self): + r = self.client.post("/judge/job/no-such-job", data={"csrf": "stale"}); self.addCleanup(r.close) + self.assertEqual(r.status_code, 403) + + def test_a_workspace_with_a_root_that_cannot_be_read_is_not_deleted(self): + shutil.rmtree(self.tmp / "runs") + r = self.client.post(f"/workspaces/delete/{self.ws.name}", data={"csrf": self.token()}); self.addCleanup(r.close) + self.assertTrue(Path(self.ws.dir, "judgements", "job-x", f"{TRIAL}.json").is_file()) + self.assertIsNotNone(web.shared.STATE["workspace"]) # left open, as it was + self.assertIn("cannot be read", self.get("/workspaces").get_data(as_text=True)) + + if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index c88dbb0f3..e8c1b0f12 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -716,7 +716,7 @@ def test_the_launch_asks_what_goes(self): self.assertIn('', html) self.assertEqual(html.count(''), 1) said = re.sub(r"<[^>]+>", " ", re.search(r'', html, re.S).group(1)) - self.assertRegex(" ".join(said.split()), r"^Delete launch r1-\* \S+ \S+ 1 folder · \d+(\.\d)? (Bytes|kB) · 1 judgement · " + self.assertRegex(" ".join(said.split()), r"^Delete launch r1-\* \S+ \S+ 1 folder · \d+(\.\d)? (Bytes|kB) · up to 1 judgement · " r"workspaces (witty pelican, sharp lemur|sharp lemur, witty pelican) Keep it Delete launch$") self.assertIn('', html) self.assertNotIn('name="host"', html) # ran here: no host copy diff --git a/app/ui_tests/test_task_judgement_slot.py b/app/ui_tests/test_task_judgement_slot.py index de04aaaea..e77c30c36 100644 --- a/app/ui_tests/test_task_judgement_slot.py +++ b/app/ui_tests/test_task_judgement_slot.py @@ -35,7 +35,7 @@ def setUp(self): stack.enter_context(patch.object(web.judge.batch, "ask_states", return_value=dict(SCORED))) def job(self, job_id, dataset, path=""): - trial = NS(task_base="fix-bug", trial_name="fix-bug__1", has_trajectory=True) + trial = NS(task_base="fix-bug", trial_name="fix-bug__1", key="fix-bug__1", has_trajectory=True) return NS(job_id=job_id, uid="uid-" + job_id, dir="/jobs/" + job_id, dataset=dataset, dataset_path=path, trials=[trial]), trial def test_a_changed_instruction_is_judged_again(self): diff --git a/app/web/judge.py b/app/web/judge.py index 2babf4e11..0f361d0a7 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -68,20 +68,25 @@ def ws_dir(name=None): def job_key(job, name=None) -> str: - """The job's key in the user's store: its identity (``Job.uid``). The - records the workspace that holds it on screen (`ws_dir`) kept for it - before are copied in first, once per request (`store.adopt`).""" - d = ws_dir(name) - memo = shared.request_memo("judgements_adopted") - if d and (d, job.dir, job.job_id) not in memo: - memo[(d, job.dir, job.job_id)] = store.adopt(d, job) + """The job's key in the user's store: its identity (``Job.uid``).""" return job.uid +def old_of(job, name=None) -> dict: + """The records the workspace that holds the job on screen (`ws_dir`) kept + for it before, read with the user's store (`store.overlay`) and never + written by a read; once per request.""" + d = ws_dir(name) + memo = shared.request_memo("judgements_old") + if (d, job.dir, job.job_id) not in memo: + memo[(d, job.dir, job.job_id)] = store.overlay(d, job) + return memo[(d, job.dir, job.job_id)] + + def batch_calibration() -> dict: - """The store's calibration, read once for a batch and passed to each + """The calibration over the open workspace's jobs, read once for a batch and passed to each call; {} when there is no sample, so no call reads the store again.""" - return store.calibration(store.home()) or {} + return store.calibration(store.home(), [j.uid for j in shared._jobs_for_request()]) or {} def started_of(trial) -> str | None: @@ -96,7 +101,7 @@ def started_by_name(job) -> dict: def judgement_of(job, trial, lane: str = "decision") -> dict | None: - return store.load(store.home(), job_key(job), trial.key, lane=lane, started=started_of(trial)) + return store.load(store.home(), job_key(job), trial.key, lane=lane, started=started_of(trial), old=old_of(job)) def panel(job, trial, lane: str = "decision") -> dict: @@ -275,7 +280,7 @@ def judge_trial(job, trial, api_key: str, post=None, calibration=None) -> dict: if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) return batch.ask_and_store(store.home(), job_key(job), trial.key, _trial_ids_and_states(trial, traj), api_key, post=post, - calibration=calibration, started=started_of(trial)) + calibration=calibration, started=started_of(trial), old=old_of(job)) def _guard(): @@ -310,13 +315,13 @@ def judge_trial_route(job_id, trial_name): def judge_job_route(job_id): """Judge the job's unjudged trials with one judge, the form's ``lane`` (Decision unless it names the LLM judge): the click is the request.""" + _guard() job = shared._job_for_request(job_id) if job is None: abort(404) lane = request.form.get("lane") if request.form.get("lane") in client.LANES else "decision" - judged = store.for_job(store.home(), job_key(job), started_by_name(job), lane=lane) + judged = store.for_job(store.home(), job_key(job), started_by_name(job), lane=lane, old=old_of(job)) todo = [t for t in job.trials if t.has_trajectory and t.key not in judged] - _guard() k, cal = key(lane), batch_calibration() done, failed = run_batch(todo, lambda t: judge_trial(job, t, k, calibration=cal), lambda t: t.trial_name) from flask import flash @@ -333,8 +338,8 @@ def job_summary(job) -> dict: number on the page is its place here, raised or not - and `lanes` is the board's record -> judge lanes (`nullius.judge.lanes`), whose status for each trial is also in `by_trial`.""" - d, uid = store.home(), job_key(job) - judged = store.for_job(d, uid, started_by_name(job)) + d, uid, old = store.home(), job_key(job), old_of(job) + judged = store.for_job(d, uid, started_by_name(job), old=old) flag_ids = [q for q in Q.group_ids("trial") if Q.QUESTIONS[q].get("flag")] board = lanes.board(job, judged) by_trial = {} @@ -359,7 +364,7 @@ def job_summary(job) -> dict: return {"judged": len(judged), "trials": len(job.trials), "unjudged": len([t for t in job.trials if t.trial_name not in judged]), "causes": sorted(causes.items(), key=lambda kv: -kv[1]), "n_cause": sum(causes.values()), "keyed": bool(key()), "flags": sorted(raised.items(), key=lambda kv: (-kv[1], kv[0])), "by_trial": by_trial, - "truncation": store.truncation_report(d, uid) if judged else None, + "truncation": store.truncation_report(d, uid, old=old) if judged else None, "unresolved": sum(1 for t in job.trials if t.outcome != "resolved"), "flag_ids": flag_ids, "lanes": board, "llm": _llm_count(d, job)} @@ -367,7 +372,7 @@ def job_summary(job) -> dict: def _llm_count(d, job) -> dict: """The LLM judge's own count for the job's button: it judges apart from Decision, so a trial judged by one is still unjudged by the other.""" - judged = store.for_job(d, job_key(job), started_by_name(job), lane="llm") + judged = store.for_job(d, job_key(job), started_by_name(job), lane="llm", old=old_of(job)) return {"unjudged": len([t for t in job.trials if t.trial_name not in judged]), "keyed": bool(key("llm"))} @@ -401,7 +406,7 @@ def side_of(job, trial, column) -> dict | None: """One side's score as the compare page shows it, from the trial's own current record, the job opened from its column's workspace `column`: the expectation, the level it rounds to, the judge's confidence, the provenance. None until scored under the current vocabulary.""" - rec = store.load(store.home(), job_key(job, column), trial.key, started=started_of(trial)) + rec = store.load(store.home(), job_key(job, column), trial.key, started=started_of(trial), old=old_of(job, column)) if not rec or not store.is_current(rec): return None a = (rec.get("answers") or {}).get(SIDE_QUESTION) @@ -418,9 +423,9 @@ def pair_records(view) -> dict: model's own pick - under job A. Read, never written.""" if not view.selected or len(view.jobs) != 2: return {} - out, uid = {}, job_key(view.jobs[0], view.selected[0].workspace) + out, uid, old = {}, job_key(view.jobs[0]), old_of(view.jobs[0], view.selected[0].workspace) for task, a, b in pairs_of(view): - rec = store.load(store.home(), uid, store.pair_key(a.trial_name, b.trial_name)) + rec = store.load(store.home(), uid, store.pair_key(a.trial_name, b.trial_name), old=old) if rec and (rec.get("answers") or {}).get(LEGACY_QUESTION): out[task] = rec return out @@ -460,7 +465,7 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> when it has them all.""" if not trial.has_trajectory: raise client.JudgeError(0, "this trial has no trajectory to judge") - rec = store.load(store.home(), job_key(job, column), trial.key, started=started_of(trial)) + rec = store.load(store.home(), job_key(job, column), trial.key, started=started_of(trial), old=old_of(job, column)) have = (rec.get("answers") or {}) if store.is_current(rec) else {} ids = [q for q in side_ids(trial) if q not in have] if not ids: @@ -469,7 +474,7 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) return batch.ask_and_store(store.home(), job_key(job, column), trial.key, _states_for(trial, traj, ids), api_key, post=post, - calibration=calibration, started=started_of(trial)) + calibration=calibration, started=started_of(trial), old=old_of(job, column)) def _sides_todo(view) -> list: @@ -555,7 +560,7 @@ def judge_control(side, jobs, api_key: str, post=None, calibration=None) -> dict if trial is None: raise client.JudgeError(0, f"{side.control} trial {side.trial_name} is not in this workspace") return batch.ask_and_store(store.home(), job_key(job), trial.key, control_states(side, trial), api_key, post=post, - calibration=calibration, started=started_of(trial)) + calibration=calibration, started=started_of(trial), old=old_of(job)) def triage_summary(report, jobs) -> dict: @@ -565,7 +570,7 @@ def triage_summary(report, jobs) -> dict: rows, judged, todo = {}, 0, [] for row, s in sides: job, _ = _control_trial(s, jobs) - rec = store.load(store.home(), job_key(job), s.trial_name) if job else None + rec = store.load(store.home(), job_key(job), s.trial_name, old=old_of(job)) if job else None a = ((rec.get("answers") or {}).get("control_failure_cause")) if store.is_current(rec) else None if a: rows.setdefault(row.task_base, {})[s.control] = _choice_row("control_failure_cause", a) @@ -579,9 +584,7 @@ def triage_summary(report, jobs) -> dict: # -- task-instruction quality: once per dataset, task and instruction text --------------- def task_key(job) -> str: - """The dataset a job's task judgements are kept under (`store.task_dataset`), - its earlier records copied in first (`job_key`).""" - job_key(job) + """The dataset a job's task judgements are kept under (`store.task_dataset`).""" return store.task_dataset(job) @@ -592,7 +595,7 @@ def task_slot(trial) -> str: def task_record(job, trial) -> dict | None: - rec = store.load(store.home(), task_key(job), task_slot(trial), lane=store.TASKS) + rec = store.load(store.home(), task_key(job), task_slot(trial), lane=store.TASKS, old=old_of(job)) return rec if store.is_current(rec) else None @@ -667,4 +670,33 @@ def judge_task(job, trial, api_key: str, post=None, calibration=None) -> dict | raise client.JudgeError(0, f"no instruction can be read for {trial.task_base}") states = batch.states_for(Q.group_ids("task"), lambda kind: judge_state.build(kind, None, instruction=instruction)) return batch.ask_and_store(store.home(), task_key(job), task_slot(trial), states, api_key, post=post, calibration=calibration, - lane=store.TASKS) + lane=store.TASKS, old=old_of(job)) + + +# -- the move of the judgements workspaces kept before into the user's store --------------- + +@app.template_global() +def judgements_unmoved() -> bool: + """Whether the judgements workspaces kept before may still wait to be moved (`store.moved`).""" + return not store.moved() + + +@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; ``unread``, the + workspaces left for a later move.""" + if request.method == "GET": + return jsonify(workspaces=[{"label": ws.label, "n": n} for ws, n in store.old_stores(shared.WS_HOME)]) + shared._require_csrf() + if not shared._local_client(): + abort(403) + try: + unread = store.move(shared.WS_HOME) + except store.Unreadable as e: + return jsonify(ok=False, error=str(e)), 409 + if unread: + return jsonify(ok=False, error="Not moved: " + ", ".join(unread) + (" has" if len(unread) == 1 else " have") + + " a root that cannot be read."), 409 + return jsonify(ok=True) diff --git a/app/web/reconcile.py b/app/web/reconcile.py index 385d6cc64..977a7b157 100644 --- a/app/web/reconcile.py +++ b/app/web/reconcile.py @@ -25,7 +25,7 @@ def threshold_requested() -> float: def view_of(job, threshold: float) -> dict: - records = store.for_job(store.home(), judge.job_key(job), judge.started_by_name(job)) + records = store.for_job(store.home(), judge.job_key(job), judge.started_by_name(job), old=judge.old_of(job)) return reconcile.reconcile(job, records, threshold) diff --git a/app/web/settings.py b/app/web/settings.py index 656df7ce6..3108ae991 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -9,7 +9,7 @@ from nullius import constraints, execution, hosts, paths, prerequisites, prices, providers, sandbox, secrets, settings from nullius.standard.backends import boat, container from nullius.standard.pages import recipe as standard_recipe -from nullius.judge import client +from nullius.judge import client, store as judge_store from .core import app from . import shared @@ -49,7 +49,8 @@ def settings_page(): provider_cards=provider_cards({r["name"]: r for r in rows}), ssh_hosts=hosts.scan_ssh_config(), judges=(client.decision_judge(os.environ), client.llm_judge(os.environ)), llm_providers=client.llm_providers(os.environ), decision_providers=client.decision_judge_providers(os.environ), judge_protocols={"DECISION": client.DECISION_PROTOCOLS, "LLM_JUDGE": client.LLM_PROTOCOLS}, protocols=providers.PROTOCOLS, agent_keys=settings.agent_key_names(), reserved_agent_keys=settings.reserved_agent_keys(), - tested={k: _shown(v) for k, v in providers.tests().items() if isinstance(v, dict)}) + tested={k: _shown(v) for k, v in providers.tests().items() if isinstance(v, dict)}, + old_judgements=judge_store.old_stores(shared.WS_HOME)) def _shown(result: dict) -> dict: diff --git a/app/web/workspaces.py b/app/web/workspaces.py index eb694301c..c2d609380 100644 --- a/app/web/workspaces.py +++ b/app/web/workspaces.py @@ -166,6 +166,11 @@ def workspace_delete(name): read. The open one closes first. Takes the form token.""" shared._require_csrf() ws = shared.STATE["workspace"] + try: + workspace.check_deletable(shared.WS_HOME, name) + except ValueError as e: + flash(str(e), "error") + return redirect(url_for("workspaces_page")) if ws is not None and ws.name == name: shared.close_workspace() if workspace.delete(shared.WS_HOME, name): From 579279001b717f948f576cdfbc17bc6d5a759b29 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 15:43:36 +0100 Subject: [PATCH 03/24] docs(judge): name the job identity, the task and deleted-workspace stores and the move --- docs/builder.md | 2 +- docs/judgement.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/builder.md b/docs/builder.md index 4f54fadc0..a3f9052ec 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -104,7 +104,7 @@ and Delete work only from a browser on the application host. | Proofs | Local runs save to the user catalogue. A host's proofs come back beside `jobs/`; the user catalogue is unchanged | | Docker or Podman | Must answer `ps`, or the run stops before it starts | | Stop | Ends the current part (exit 130), records `stopped`; the next part never starts | -| Delete launch | Once every run of the launch has ended. Deletes each run's `//` (a shard per machine included), every job of the launch, their judgements unless a copy of a job is found or a root cannot be read, and each run's copy on its host when ticked. A run still going is refused: stop it first. A launch with jobs from elsewhere has no Delete | +| Delete launch | Once every run of the launch has ended. Deletes each run's `//` (a shard per machine included), every job of the launch, their judgements unless a copy of a job is found under another run or a workspace's root, or one of those roots cannot be read, and each run's copy on its host when ticked. A run still going is refused: stop it first. A launch with jobs from elsewhere has no Delete | | Restart of Nullius | Reattaches; the job goes back into the workspace it started in, under the name a rename gave it, while that workspace exists, without opening it. The workspace open before the restart opens again. One process follows a runs folder: a second `nullius serve` on it stops with a message | | Cannot run from the page | Generated tasks and custom agents are not supported by Run | | Refused | Reads *refused* on the runs page, with why; the job was never written | diff --git a/docs/judgement.md b/docs/judgement.md index e64f6222c..c95507048 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -69,9 +69,9 @@ Follow the evidence: a recorded rate limit is a provider's failure whatever the | What | Detail | | --- | --- | -| Where | `judgements//.json` below the user data directory, by the job's identity, never in the job tree. One record per trial, 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 read; of two for one trial, the newer is shown | -| 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 | +| Where | `judgements//.json` below the user data directory, never in the job tree; task-instruction scores in `judgements-tasks//`. One record per trial, 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 | +| 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 in `judgements-of-deleted-workspaces/`; one with old records not yet moved is refused while one of its roots 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 | | Noise floors | Each yes/no's run-to-run spread | From 86ffc3c7afd5ddc52b4ef708f67a266995783fcc Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 15:50:39 +0100 Subject: [PATCH 04/24] fix(settings): lay the move judgements row out on one line --- app/static/settings/settings.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/static/settings/settings.css b/app/static/settings/settings.css index f1d5793bd..5b6eaeace 100644 --- a/app/static/settings/settings.css +++ b/app/static/settings/settings.css @@ -314,7 +314,7 @@ .st-sandbox-rows { display: grid; gap: 14px; } .st-sandbox-rows > .st-row + .st-row { padding-top: 14px; border-top: 1px solid var(--border-soft); } .settings-page .st-sandbox-rows .st-input { height: 34px; min-height: 34px; padding-block: 0; } -.settings-page #sandbox .st-row-value.st-value, .settings-page #prices .st-row-value.st-value, .settings-page #data-providers .st-row-value.st-value { flex-direction: row; justify-content: flex-start; align-items: center; } +.settings-page #sandbox .st-row-value.st-value, .settings-page #prices .st-row-value.st-value, .settings-page #data-providers .st-row-value.st-value, .settings-page #judge .st-row-value.st-value { flex-direction: row; justify-content: flex-start; align-items: center; } #prices [data-prices-update].busy .ic { animation: st-prices-spin .9s linear infinite; } @keyframes st-prices-spin { to { transform: rotate(360deg); } } @media (prefers-reduced-motion: reduce) { #prices [data-prices-update].busy .ic { animation: none; } } From 0e709f8ba5cbfbe393d9ffd466a94a5987241eec Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 24 Nov 2026 17:31:03 +0100 Subject: [PATCH 05/24] fix(judge): move a workspace's judgements only when each has one job, and keep each try's own A workspace is marked moved only once every old file was read and found one job with an identity; otherwise it stays read in memory and the move names it as left for later. A record two jobs of one id share is copied to neither. A try is judged under its own folder name. A read merges older records under every spelling. A save for a deleted job writes nothing. Deleting a workspace keeps its imports' failure analyses. --- app/nullius/judge/batch.py | 7 +- app/nullius/judge/store.py | 229 ++++++++++++++----- app/nullius/workspace.py | 18 +- app/templates/workspaces/workspaces.html | 2 +- app/tests/test_judge_adopt.py | 91 +++++++- app/ui_tests/test_judge_calibration_reads.py | 4 +- app/ui_tests/test_judgement_follows_job.py | 27 +++ app/ui_tests/test_run_routes.py | 2 +- app/web/judge.py | 37 ++- docs/judgement.md | 6 +- 10 files changed, 318 insertions(+), 105 deletions(-) diff --git a/app/nullius/judge/batch.py b/app/nullius/judge/batch.py index cf91aa7bf..13a0751c0 100644 --- a/app/nullius/judge/batch.py +++ b/app/nullius/judge/batch.py @@ -98,14 +98,15 @@ def ask_states(states: dict, key: str, post: Optional[Callable] = None, calibrat def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, post: Optional[Callable] = None, calibration: Optional[dict] = None, started: Optional[str] = None, - lane: Optional[str] = None, old: Optional[dict] = None) -> Optional[dict]: + lane: Optional[str] = None, old: Optional[dict] = None, job_dir: Optional[str] = None) -> Optional[dict]: """`ask_states`, then the merged record saved under the trial's key - its answers over the version's earlier ones - in the store at `base` (`store.home`). Returns the record as stored. The pre-flight reads the job's own calibration unless one is given. `started`: the trial's own start, which the record keeps (`store.save`). `lane`: where it is kept, the judge's own lane unless named (`store.TASKS`). `old`: the job's - older records (`store.overlay`), the file's copied in by the save.""" + older records (`store.overlay`), the file's copied in by the save. `job_dir`: the + job's folder, nothing saved once it is deleted (`store.Gone`).""" if calibration is None: calibration = store.calibration(base, [job_id]) rec = ask_states(states, key, post=post, calibration=calibration) @@ -114,5 +115,5 @@ def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, po # earlier readings for the others, as the answers are kept (`store.save`), and returns them lane = lane or getattr(key, "lane", "decision") rec.setdefault("hygiene", {}) - rec["hygiene"] = store.save(base, job_id, trial_name, rec, lane=lane, started=started, old=old)["hygiene"] + rec["hygiene"] = store.save(base, job_id, trial_name, rec, lane=lane, started=started, old=old, job_dir=job_dir)["hygiene"] return rec diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 13203dfb9..88a9e7138 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -1,6 +1,6 @@ """Where a judgement lives: the user's own store, by the job it judges - ``/judgements//.json`` (each name spelled by -`key`; ``Job.uid``, ``Trial.key``) for System One's, +`key`; ``Job.uid``, ``Trial.trial_name``) for System One's, ``/judgements-llm/...`` for the LLM judge's (a trial has both, apart, ``lane``), ``/judgements-tasks//...`` for task instructions - keyed by question version inside. ```` is @@ -11,14 +11,15 @@ Every function takes the store's base first: ``home()``, or a workspace's folder for the store judgements were kept in before (``/ -judgements{,-llm}//``). Until `move` has copied every workspace's -into the user's store, a read merges a job's older records in memory +judgements{,-llm}//``). Until `move` has copied a workspace's into +the user's store, a read merges a job's older records from it in memory (`overlay`, passed as ``old``) and writes nothing; a save copies in those of the file it writes (`adopt`). The older files are never deleted or rewritten. -Every version is kept, and under each every try of a retried trial: the -try judged last under the version, each earlier one under -``@``. A read without a version asks for the current one +A try of a retried trial is a trial of its own, by its folder's name +(``.try-N``). Every version is kept, and under each every run of +one trial name: the one judged last under the version, each earlier one +under ``@``. A read without a version asks for the current one and falls back to the earlier ones the vocabulary still names (``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 @@ -27,6 +28,7 @@ import json import os import re +import shutil from typing import Optional from nullius import ondisk, paths @@ -39,7 +41,7 @@ ROOTS = {"decision": "judgements", "llm": "judgements-llm"} # one directory per judge 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/``: every workspace's older records are in the user's store +MOVED = ".moved" # in ``/judgements/``: a file per workspace whose older records are all in the user's store class Unreadable(client.JudgeError, ValueError): @@ -58,10 +60,40 @@ def _root(base: str, lane: str) -> str: def _locked(path: str): - """One save at a time to a judgement file, across threads and processes: a save reads, merges and writes it whole.""" + """One save at a time to a judgement file, across threads and processes: a save reads, merges and writes it whole. + A delete of the folder takes it too (`remove`).""" return ondisk.locked(os.path.join(os.path.dirname(path), ".lock")) +class Gone(client.JudgeError, ValueError): + """The job a judgement was being written for was deleted meanwhile: nothing is written.""" + def __init__(self, job_dir: str): + super().__init__(0, f"{job_dir} was deleted; its judgement is not kept.") + + +def _open_for(path: str, job_dir: Optional[str]): + """The folder of `path` made, unless the job `job_dir` is gone already (`Gone`).""" + if job_dir and not os.path.isdir(job_dir): + raise Gone(job_dir) + os.makedirs(os.path.dirname(path), exist_ok=True) + + +def _still(path: str, job_dir: Optional[str]) -> None: + """Under the lock: `Gone` when the job was deleted since `_open_for`, the folder it made removed again.""" + if job_dir and not os.path.isdir(job_dir): + d = os.path.dirname(path) + if not any(n.endswith(".json") for n in (os.listdir(d) if os.path.isdir(d) else ())): + shutil.rmtree(d, ignore_errors=True) + raise Gone(job_dir) + + +def remove(folder: str) -> None: + """A job's judgement folder deleted, under the lock its saves take, so none writes into it meanwhile.""" + if os.path.isdir(folder): + with ondisk.locked(os.path.join(folder, ".lock")): + shutil.rmtree(folder, ignore_errors=True) + + 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 @@ -143,7 +175,12 @@ def load(base: str, job_id: str, trial_name: str, version: Optional[str] = None, if not job_id: # a job with no identity yet (Job.uid_source "pending") has no judgement return None found = _paths(base, job_id, trial_name, lane) - return _pick(_with(_read(found), (old or {}).get(found[0])), version, started) + return _pick(_with(_read(found), _olds(old, found)), version, started) + + +def _olds(old: Optional[dict], found) -> list: + """The older records `old` holds for any of the spellings `found` of one file.""" + return [d for p in found for d in (old or {}).get(p) or ()] def is_current(record: Optional[dict]) -> bool: @@ -152,20 +189,22 @@ def is_current(record: Optional[dict]) -> bool: def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "decision", - started: Optional[str] = None, old: Optional[dict] = None) -> dict: + started: Optional[str] = None, old: Optional[dict] = None, job_dir: Optional[str] = None) -> dict: """The record under its question version, returned as stored; other versions kept. A record's answers and hygiene readings merge over the version's earlier ones, so judging one question later does not drop the others. Saves to one file take turns, across processes; each writes through a temporary file of its own. `old`: the job's older records (`overlay`), those of this file copied in first. - `Unreadable` when the file is there and cannot be read: nothing is written.""" + `Unreadable` when the file is there and cannot be read, `Gone` when the + job's folder `job_dir` is no longer there: nothing is written.""" if not job_id: raise ValueError("a judgement needs the job's identity") found = _paths(base, job_id, trial_name, lane) path = found[0] - os.makedirs(os.path.dirname(path), exist_ok=True) + _open_for(path, job_dir) with _locked(path): - data = _with(_read(found, strict=True), (old or {}).get(path)) + _still(path, job_dir) + data = _with(_read(found, strict=True), _olds(old, found)) version = record.get("questions", Q.VERSION) earlier = data.get(version) or {} if not _of(earlier, started): # another try's: kept beside, and none of its answers are this one's @@ -311,48 +350,71 @@ def _merged(cur: dict, data: dict) -> dict: return cur -def _merge_into(path: str, old) -> None: +def _merge_into(path: str, old, job_dir: Optional[str] = None) -> None: """The older records `old` (a list of files' contents) into the file at `path` (`_merged`), - under its lock; nothing written when nothing is new. `Unreadable` when the file cannot be read.""" - os.makedirs(os.path.dirname(path), exist_ok=True) + under its lock; nothing written when nothing is new. `Unreadable` when the file cannot be read, + `Gone` when the job `job_dir` was deleted.""" + _open_for(path, job_dir) with _locked(path): + _still(path, job_dir) cur = _read([path], strict=True) got = _with(cur, old) if got != cur: ondisk.write_whole(path, json.dumps(got, indent=1), mode=0o600) -def moved(into: Optional[str] = None) -> bool: - """Whether `move` has copied every workspace's older records into the user's store.""" - return os.path.exists(os.path.join(_root(into or home(), "decision"), MOVED)) +def _old_files(ws_dir: str) -> list: + """The files of a workspace's store from before, by their path in it.""" + return sorted(os.path.relpath(os.path.join(d, f), ws_dir) for r in ROOTS.values() + for d, _, fs in os.walk(os.path.join(ws_dir, r)) for f in fs if f.endswith(".json")) -def _try_file(data: dict, n: int) -> dict: - """An older store's record of try `n` of a trial (``.try-N.json``), filed under its try: - each version's under ``@``, as `save` keeps an earlier try.""" - return {k if "@" in k or not isinstance(rec, dict) else _try(k, rec.get("trial_started_at") or f"try-{n}"): rec - for k, rec in data.items()} +def _marker(ws_dir: str, into: str) -> str: + return os.path.join(_root(into, "decision"), MOVED, os.path.basename(ws_dir)) -def overlay(ws_dir: Optional[str], job, into: Optional[str] = None) -> dict: - """What the workspace's store from before (`ws_dir`) holds for `job` - - under its job id, its trials' (a try's ``.try-N`` under its trial, - filed under its try) and its dataset's task records - as {the file of the - user's store (`into`, `home()` by default) it belongs in: [its contents]}. - Read only. Two jobs of one id in that workspace each get the same - records, as each showed them before. {} once `move` is done.""" - into = into or home() - if not ws_dir or not job.uid or moved(into): - return {} +def _signature(files) -> str: + # shortcut: names only, so a file rewritten in place under the same name is not seen; stat each if that matters + return hashlib.sha256("\n".join(files).encode("utf-8")).hexdigest() + + +def moved(ws_dir: Optional[str], into: Optional[str] = None) -> bool: + """Whether `move` copied every record of the workspace's store from before into the user's + store, and it holds no file since: one added, by a restore or an older Nullius, is read again.""" + if not ws_dir: + return False + try: + with open(_marker(ws_dir, into or home()), encoding="utf-8") as fh: + return fh.read() == _signature(_old_files(ws_dir)) + except OSError: + return False + + +def _mark(ws_dir: str, into: str, files) -> None: + os.makedirs(os.path.dirname(_marker(ws_dir, into)), exist_ok=True) + ondisk.write_whole(_marker(ws_dir, into), _signature(files)) + + +def forget(ws_dir: str, folders) -> None: + """A workspace's older folders of a deleted job removed, the workspace still `moved` if it was.""" + was = moved(ws_dir) + for d in folders: + shutil.rmtree(d, ignore_errors=True) + if was: + _mark(ws_dir, home(), _old_files(ws_dir)) + + +def _places(ws_dir: str, job, into: str): + """(an older file, the file of the user's store it belongs in) for each the workspace's store + from before holds for `job`: under its job id its trials' and tries' (each by its own name), and + its dataset's task records.""" names = {} for t in job.trials: - names.update((n, (key(t.key), 0)) for n in _names(t.trial_name)) - for i in range(1, min(getattr(t, "n_retries", 0) or 0, 99) + 1): - names.update((n, (key(t.key), i)) for n in _names(f"{t.trial_name}.try-{i}")) + for name in (t.trial_name, *(f"{t.trial_name}.try-{i}" for i in range(1, min(getattr(t, "n_retries", 0) or 0, 99) + 1))): + names.update((n, key(name)) for n in _names(name)) places = [(lane, j, job.uid, names) for lane in ROOTS for j in _names(job.job_id)] # before, a dataset's task records were a job of their own, named `task:`, and a job naming none its id places += [(TASKS, j, task_dataset(job), {}) for j in _names("task:" + (job.dataset_path or job.dataset or "job:" + job.job_id))] - out: dict = {} for lane, old, new, rename in places: src = os.path.join(_root(ws_dir, "decision" if lane == TASKS else lane), old) try: @@ -360,10 +422,32 @@ def overlay(ws_dir: Optional[str], job, into: Optional[str] = None) -> dict: except OSError: continue for f in files: - data = _read([os.path.join(src, f)]) - name, n = rename.get(f[:-5], (f[:-5], 0)) - if data: - out.setdefault(os.path.join(_root(into, lane), key(new), name + ".json"), []).append(_try_file(data, n) if n else data) + yield os.path.join(src, f), os.path.join(_root(into, lane), key(new), rename.get(f[:-5], f[:-5]) + ".json") + + +def _old(path: str) -> Optional[dict]: + """An older file's records; None when it cannot be read or holds no JSON object.""" + try: + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + except (OSError, ValueError): + return None + return {} if data is None else data if isinstance(data, dict) else None + + +def overlay(ws_dir: Optional[str], job, into: Optional[str] = None) -> dict: + """What the workspace's store from before (`ws_dir`) holds for `job` (`_places`), as {the file + of the user's store (`into`, `home()` by default) it belongs in: [its contents]}. Read only; a + file that cannot be read is left out. Two jobs of one id in that workspace each get the same + records, as each showed them before. {} once the workspace is `moved`.""" + into = into or home() + if not ws_dir or not job.uid or moved(ws_dir, into): + return {} + out: dict = {} + for src, dest in _places(ws_dir, job, into): + data = _old(src) + if data: + out.setdefault(dest, []).append(data) return out @@ -371,7 +455,7 @@ def adopt(ws_dir: str, job, into: Optional[str] = None) -> None: """Copy `overlay` into the user's store, file by file under each file's lock. The workspace's files are left as they are.""" for path, old in overlay(ws_dir, job, into).items(): - _merge_into(path, old) + _merge_into(path, old, getattr(job, "dir", None)) def records_of(base: str, uids, olds=()) -> int: @@ -383,35 +467,60 @@ def records_of(base: str, uids, olds=()) -> int: def old_stores(home_dir: str, into: Optional[str] = None) -> list: - """[(workspace, its count of older records)] for each workspace whose store from before holds any, - until `move` is done.""" + """[(workspace, its count of older records)] for each workspace whose store from before holds + any, until it is `moved`.""" from nullius import workspace - if moved(into): - return [] out = [] for ws in workspace.list_all(home_dir): - n = sum(f.endswith(".json") for r in ROOTS.values() for _, _, fs in os.walk(os.path.join(ws.dir, r)) for f in fs) - if n: + n = len(_old_files(ws.dir)) + if n and not moved(ws.dir, into): out.append((ws, n)) return out +def _plural(n: int, one: str, many: str) -> str: + return f"{n} {one if n == 1 else many}" + + def move(home_dir: str, into: Optional[str] = None) -> list: - """Copy every workspace's older records into the user's store (`adopt`, for every job its - roots hold) and record that it is done (`moved`), so reads stop consulting the older stores. - The older files stay as they are. A workspace with a root that cannot be read is left for a - later move, which is then not done: its labels are returned. Safe to run again.""" + """Copy every workspace's older records into the user's store, the older files left as they + are, and mark each workspace whose every file went (`moved`), so reads stop consulting it. + A workspace is left for a later move, as one line in the list returned, while one of its roots + cannot be read, or one of its files cannot be read, belongs to no job its roots hold, or belongs + to several (a job id two jobs share): such a file is copied nowhere, and still read as before. + Safe to run again.""" from nullius import workspace into = into or home() - unread = [] + left = [] for ws, _ in old_stores(home_dir, into): + files = _old_files(ws.dir) # first: one added during the move leaves the workspace unmarked roots = ws.job_roots or ws.roots if not all(os.path.isdir(r) for r in roots): - unread.append(ws.label) + left.append(f"{ws.label} (a root cannot be read)") continue + owners: dict = {} for job in workspace.load_jobs(ws, roots): - adopt(ws.dir, job, into) - if not unread: - os.makedirs(_root(into, "decision"), exist_ok=True) - ondisk.write_whole(os.path.join(_root(into, "decision"), MOVED), "") - return unread + if job.uid: + for src, dest in _places(ws.dir, job, into): + owners.setdefault(src, {}).setdefault(dest, job.dir) + unread, shared, by_dest = 0, 0, {} + for src, dests in owners.items(): + data = _old(src) + if data is None: + unread += 1 + elif len(dests) > 1: # unresolved: whose it is cannot be told + shared += 1 + elif data: + [(dest, job_dir)] = dests.items() + by_dest.setdefault(dest, (job_dir, []))[1].append(data) + for dest, (job_dir, old) in by_dest.items(): + _merge_into(dest, old, job_dir) + orphans = len({os.path.join(ws.dir, f) for f in files} - set(owners)) + why = [_plural(n, *w) for n, w in ((unread, ("file cannot be read", "files cannot be read")), + (orphans, ("record of no job found", "records of no job found")), + (shared, ("record two jobs share", "records several jobs share"))) if n] + if why: + left.append(f"{ws.label} ({', '.join(why)})") + else: + _mark(ws.dir, into, files) + return left diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index bc03e98d9..4698d742e 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -242,7 +242,7 @@ def _check_roots(ws: Workspace) -> None: """ValueError while *ws* holds judgements kept before by job id, not yet copied into the user's store, and one of its roots cannot be read: its jobs, and so their records, are unknown.""" from nullius.judge import store - if store.moved() or not any(os.path.isdir(os.path.join(ws.dir, r)) for r in store.ROOTS.values()): + if store.moved(ws.dir) or not any(os.path.isdir(os.path.join(ws.dir, r)) for r in store.ROOTS.values()): return unread = [r for r in ws.job_roots or ws.roots if not os.path.isdir(r)] if unread: @@ -253,20 +253,28 @@ def _keep_judgements(ws: Workspace) -> None: """The judgements a workspace kept before they were kept by job (``/judgements{,-llm}/``): copied into the user's store under each job its roots hold, then its files moved there whole, so none is - lost with it - a job its roots no longer reach included. Refused while a - root cannot be read, since its jobs' records could not be copied.""" + lost with it - a job its roots no longer reach included - and the User + judge's failure analyses of its converted imports beside them, under + ``imported/`` by their job folder's path. Refused while a root cannot be + read, since its jobs' records could not be copied.""" from nullius.judge import store + from nullius.runs import failure_analysis old = [d for r in store.ROOTS.values() if os.path.isdir(d := os.path.join(ws.dir, r))] - if not old: + made = [os.path.join(d, n) for d, _, names in os.walk(ws.imports_dir) for n in names if n.startswith(failure_analysis.FILE)] + if not old and not made: return _check_roots(ws) - if not store.moved(): + if old and not store.moved(ws.dir): for job in load_jobs(ws, ws.job_roots or ws.roots): store.adopt(ws.dir, job) keep = os.path.join(store.home(), "judgements-of-deleted-workspaces", 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) + for f in made: + to = os.path.join(keep, os.path.relpath(f, ws.dir)) + os.makedirs(os.path.dirname(to), exist_ok=True) + shutil.move(f, to) def holding(home_dir: str, folder: str) -> list: diff --git a/app/templates/workspaces/workspaces.html b/app/templates/workspaces/workspaces.html index 1f1108b79..07e69047a 100644 --- a/app/templates/workspaces/workspaces.html +++ b/app/templates/workspaces/workspaces.html @@ -75,7 +75,7 @@

Delete workspace

-

Its run folders stay on disk.

+

Its roots and judgements stay; its converted imports go.

diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index e401375fd..b8a3c3655 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -80,19 +80,26 @@ def test_deleting_a_workspace_keeps_its_judgements(self): [kept] = os.listdir(os.path.join(self.home, "judgements-of-deleted-workspaces")) self.assertTrue(os.path.isfile(os.path.join(self.home, "judgements-of-deleted-workspaces", kept, "judgements", "job-gone", "t0.json"))) - def test_an_earlier_try_is_read_under_its_trial_filed_under_its_try(self): - first, last = "2026-01-01T00:00:00Z", "2026-01-01T01:00:00Z" - store.save(self.a, "job-x", "t0.try-1", rec("2026-01-01T00:30:00Z", "first try"), started=first) - store.save(self.a, "job-x", "t0", rec("2026-01-01T01:30:00Z", "last try"), started=last) + def test_an_earlier_try_is_read_under_its_own_name(self): + store.save(self.a, "job-x", "t0.try-1", rec("2026-01-01T00:30:00Z", "first try")) # judged before starts were kept + store.save(self.a, "job-x", "t0", rec("2026-01-01T01:30:00Z", "last try")) run = job("job-x", "uid-1"); run.trials[0].n_retries = 1 old = store.overlay(self.a, run) - for name, read in (("read", lambda **k: store.load(self.home, "uid-1", "t0", old=old, **k)), - ("copied", lambda **k: store.load(self.home, "uid-1", "t0", **k))): + for name, read in (("read", lambda t, **k: store.load(self.home, "uid-1", t, old=old, **k)), + ("copied", lambda t, **k: store.load(self.home, "uid-1", t, **k))): with self.subTest(name): if name == "copied": store.adopt(self.a, run) - self.assertEqual(read(started=first)["answers"]["q"]["choice"], "first try") - self.assertEqual(read(started=last)["answers"]["q"]["choice"], "last try") + self.assertEqual(read("t0.try-1", started="S1")["answers"]["q"]["choice"], "first try") + self.assertEqual(read("t0", started="S2")["answers"]["q"]["choice"], "last try") + + def test_a_pair_kept_under_the_older_spelling_is_read_before_the_move(self): + name = store.pair_key("t0", "t1") + d = os.path.join(self.a, "judgements", "job-x"); os.makedirs(d) + with open(os.path.join(d, store._SAFE.sub("_", name) + ".json"), "w") as f: + json.dump({Q.VERSION: rec("2026-01-01T00:00:00Z", "pair")}, f) + run = job("job-x", "uid-1") + self.assertEqual(store.load(self.home, "uid-1", name, old=store.overlay(self.a, run))["answers"]["q"]["choice"], "pair") def test_a_record_copied_once_is_not_copied_again_after_a_save_changed_it(self): store.save(self.a, "job-x", "t0", rec("2026-01-01T00:00:00Z")) @@ -133,17 +140,79 @@ def test_the_move_waits_for_a_root_that_cannot_be_read(self): [j] = workspace.load_jobs(ws, ws.roots) store.save(ws.dir, "job-a", j.trials[0].trial_name, rec("2026-01-01T00:00:00Z")) os.rename(root, root + ".away") - self.assertEqual(store.move(home_dir), ["w"]) - self.assertFalse(store.moved()) + self.assertEqual(store.move(home_dir), ["w (a root cannot be read)"]) + self.assertFalse(store.moved(ws.dir)) with self.assertRaisesRegex(ValueError, "cannot be read"): workspace.delete(home_dir, ws.name) self.assertTrue(os.path.isdir(ws.dir)) os.rename(root + ".away", root) self.assertEqual(store.move(home_dir), []) - self.assertTrue(store.moved()) + self.assertTrue(store.moved(ws.dir)) self.assertEqual(store.old_stores(home_dir), []) 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): + root = os.path.join(self.tmp, "jobs"); _job_dir(root, "job-a") + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [root], label="w") + [j] = workspace.load_jobs(ws, ws.roots) + t0, t1 = (t.trial_name for t in j.trials) + store.save(ws.dir, "job-a", t0, rec("2026-01-01T00:00:00Z", "here")) + store.save(ws.dir, "job-gone", "t0", rec("2026-01-01T00:00:00Z", "gone")) # its folder away for now + with open(os.path.join(ws.dir, "judgements", "job-a", t1 + ".json"), "w") as f: + 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.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"] + self.assertEqual(store.load(self.home, gone.uid, "t0", old=store.overlay(ws.dir, gone))["answers"]["q"]["choice"], "gone") + os.remove(os.path.join(ws.dir, "judgements", "job-a", t1 + ".json")) # repaired by hand + store.save(ws.dir, "job-a", t1, rec("2026-01-01T00:00:00Z", "repaired")) + self.assertEqual(store.move(home_dir), []) + self.assertTrue(store.moved(ws.dir)) + 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]) + + def test_a_record_two_jobs_of_one_id_share_is_moved_to_neither_and_still_shown_on_both(self): + r1, r2 = (os.path.join(self.tmp, r) for r in ("r1", "r2")) + _job_dir(r1, "job-x"); _job_dir(r2, "job-x") + with open(os.path.join(r2, "job-x", "result.json"), "w") as f: + json.dump({"id": "j2", "started_at": "2026-09-05T00:00:00Z", "stats": {}}, f) + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [r1, r2], label="w") + jobs = workspace.load_jobs(ws, ws.roots) + self.assertEqual(len({j.uid for j in jobs}), 2) + t0 = jobs[0].trials[0].trial_name + store.save(ws.dir, "job-x", t0, rec("2026-01-01T00:00:00Z")) + self.assertEqual(store.move(home_dir), ["w (1 record two jobs share)"]) + self.assertFalse(os.path.isdir(os.path.join(self.home, "judgements")) and + [d for d in os.listdir(os.path.join(self.home, "judgements")) if not d.startswith(".")]) + self.assertEqual([bool(store.load(self.home, j.uid, t0, old=store.overlay(ws.dir, j))) for j in jobs], [True, True]) + + def test_deleting_a_workspace_keeps_the_failure_analyses_of_its_imports(self): + from nullius.runs import failure_analysis as fa + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [], label="w") + j = _job_dir(ws.imports_dir, "atif__x") + fa.update(j, lambda a: a.set_label("t0", "agent", by="me")) + workspace.delete(home_dir, ws.name) + [kept] = os.listdir(os.path.join(self.home, "judgements-of-deleted-workspaces")) + self.assertTrue(os.path.isfile(os.path.join(self.home, "judgements-of-deleted-workspaces", kept, "imported", "atif__x", fa.FILE))) + + def test_a_save_or_a_copy_for_a_job_deleted_meanwhile_writes_nothing(self): + gone = os.path.join(self.tmp, "deleted-job") + store.save(self.a, "job-x", "t0", rec("2026-01-01T00:00:00Z")) + run = job("job-x", "uid-1"); run.dir = gone + for name, write in (("a save", lambda: store.save(self.home, "uid-1", "t0", rec("2026-01-02T00:00:00Z"), job_dir=gone)), + ("a copy", lambda: store.adopt(self.a, run))): + with self.subTest(name), self.assertRaises(store.Gone): + write() + self.assertFalse(os.path.exists(os.path.join(self.home, "judgements", "uid-1"))) + if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_judge_calibration_reads.py b/app/ui_tests/test_judge_calibration_reads.py index 6a7938349..d0f6e8e00 100644 --- a/app/ui_tests/test_judge_calibration_reads.py +++ b/app/ui_tests/test_judge_calibration_reads.py @@ -26,7 +26,7 @@ class CalibrationReads(unittest.TestCase): def setUp(self): stack = ExitStack() self.addCleanup(stack.close) - tmp = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="nullius-judge-calib-"))) + self.tmp = tmp = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="nullius-judge-calib-"))) stack.enter_context(patch.object(web.shared, "WS_HOME", str(tmp / "workspaces"))) stack.enter_context(patch.object(web.judge.store, "home", return_value=str(tmp / "data"))) stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) @@ -42,7 +42,7 @@ def reads_to_judge_all(self, n): web.shared.open_workspace(workspace.create(web.shared.WS_HOME, [], f"w{n}")) job_id = "job" trials = [NS(trial_name=f"t{i}", key=f"t{i}", has_trajectory=True, trajectory_path="-", started_at=None, outcome="resolved") for i in range(n)] - job = NS(job_id=job_id, uid=f"uid-{n}", dir=f"/jobs/{n}", dataset="", dataset_path="", trials=trials) + job = NS(job_id=job_id, uid=f"uid-{n}", dir=str(self.tmp), dataset="", dataset_path="", trials=trials) real_open, reads = builtins.open, [0] def counting_open(path, mode="r", *a, **k): diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index c9eab0601..9bd6ddfc0 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -161,5 +161,32 @@ def test_a_workspace_with_a_root_that_cannot_be_read_is_not_deleted(self): self.assertIn("cannot be read", self.get("/workspaces").get_data(as_text=True)) +class EachTryItsOwn(unittest.TestCase): + """A retried trial's earlier try is judged, and shown, apart from its last + try, even when the try recorded no start.""" + def test_two_tries_each_show_and_keep_their_own_record(self): + from nullius.runs import parse + tmp = Path(tempfile.mkdtemp(prefix="nullius-judge-tries-")); self.addCleanup(shutil.rmtree, tmp, True) + d = copy_job(tmp / "runs" / "job-x") + res = json.loads((d / TRIAL / "result.json").read_text()) + (d / TRIAL / "result.json").write_text(json.dumps(dict(res, standard={"retries": 1}))) + shutil.copytree(d / TRIAL, d / "retried" / f"{TRIAL}.try-1") + (d / "retried" / f"{TRIAL}.try-1" / "result.json").write_text(json.dumps({k: v for k, v in res.items() if k != "started_at"})) + job = parse.parse_job(str(d)) + (n1, first), (n2, last) = parse.tries(next(t for t in job.trials if t.trial_name == TRIAL)) + self.assertEqual((n1, n2), (1, 2)) + self.assertIsNone(first.started_at) + asked = lambda choice: lambda *a, **k: {"questions": Q.VERSION, "answers": {"failure_cause": {"choice": choice}}} + with patch.object(web.judge.store, "home", return_value=str(tmp / "data")), \ + patch.object(web.judge.trajectory, "load", return_value=SimpleNamespace(error=None)), \ + patch.object(web.judge, "_trial_ids_and_states", return_value={}), \ + web.app.test_request_context("/"): + for trial, choice in ((last, "last"), (first, "first"), (last, "last")): + with patch.object(web.judge.batch, "ask_states", asked(choice)): + web.judge.judge_trial(job, trial, "k", calibration={}) + shown = [web.judge.judgement_of(job, t)["answers"]["failure_cause"]["choice"] for t in (first, last)] + self.assertEqual(shown, ["first", "last"]) + + if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index e8c1b0f12..a456c9b4e 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -1267,7 +1267,7 @@ def test_delete_workspace_says_what_is_lost(self): self.assertEqual(html.count("Delete workspace ', ask) self.assertIn(f'', ask) - self.assertIn("

Its run folders stay on disk.

", ask) + self.assertIn("

Its roots and judgements stay; its converted imports go.

", ask) self.assertNotIn("Its judgements", html) # its jobs keep theirs for ws in (self.ws, self.other()): self.assertIn(f'data-ask="ws-ask-delete" data-label="{ws.label}" data-action="/workspaces/delete/{ws.name}" aria-haspopup="dialog"', self.row(ws, html)) diff --git a/app/web/judge.py b/app/web/judge.py index 0f361d0a7..0af98f7f9 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -97,11 +97,11 @@ def started_of(trial) -> str | None: def started_by_name(job) -> dict: """{trial name: start} for every trial of a job: what `store.for_job` reads its records for.""" - return {t.key: started_of(t) for t in job.trials} + return {t.trial_name: started_of(t) for t in job.trials} def judgement_of(job, trial, lane: str = "decision") -> dict | None: - return store.load(store.home(), job_key(job), trial.key, lane=lane, started=started_of(trial), old=old_of(job)) + return store.load(store.home(), job_key(job), trial.trial_name, lane=lane, started=started_of(trial), old=old_of(job)) def panel(job, trial, lane: str = "decision") -> dict: @@ -279,8 +279,8 @@ def judge_trial(job, trial, api_key: str, post=None, calibration=None) -> dict: traj = trajectory.load(trial.trajectory_path) if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) - return batch.ask_and_store(store.home(), job_key(job), trial.key, _trial_ids_and_states(trial, traj), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job)) + return batch.ask_and_store(store.home(), job_key(job), trial.trial_name, _trial_ids_and_states(trial, traj), api_key, post=post, + calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir) def _guard(): @@ -321,7 +321,7 @@ def judge_job_route(job_id): abort(404) lane = request.form.get("lane") if request.form.get("lane") in client.LANES else "decision" judged = store.for_job(store.home(), job_key(job), started_by_name(job), lane=lane, old=old_of(job)) - todo = [t for t in job.trials if t.has_trajectory and t.key not in judged] + todo = [t for t in job.trials if t.has_trajectory and t.trial_name not in judged] k, cal = key(lane), batch_calibration() done, failed = run_batch(todo, lambda t: judge_trial(job, t, k, calibration=cal), lambda t: t.trial_name) from flask import flash @@ -406,7 +406,7 @@ def side_of(job, trial, column) -> dict | None: """One side's score as the compare page shows it, from the trial's own current record, the job opened from its column's workspace `column`: the expectation, the level it rounds to, the judge's confidence, the provenance. None until scored under the current vocabulary.""" - rec = store.load(store.home(), job_key(job, column), trial.key, started=started_of(trial), old=old_of(job, column)) + rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column)) if not rec or not store.is_current(rec): return None a = (rec.get("answers") or {}).get(SIDE_QUESTION) @@ -465,7 +465,7 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> when it has them all.""" if not trial.has_trajectory: raise client.JudgeError(0, "this trial has no trajectory to judge") - rec = store.load(store.home(), job_key(job, column), trial.key, started=started_of(trial), old=old_of(job, column)) + rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column)) have = (rec.get("answers") or {}) if store.is_current(rec) else {} ids = [q for q in side_ids(trial) if q not in have] if not ids: @@ -473,8 +473,8 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> traj = trajectory.load(trial.trajectory_path) if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) - return batch.ask_and_store(store.home(), job_key(job, column), trial.key, _states_for(trial, traj, ids), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job, column)) + return batch.ask_and_store(store.home(), job_key(job, column), trial.trial_name, _states_for(trial, traj, ids), api_key, post=post, + calibration=calibration, started=started_of(trial), old=old_of(job, column), job_dir=job.dir) def _sides_todo(view) -> list: @@ -559,8 +559,8 @@ def judge_control(side, jobs, api_key: str, post=None, calibration=None) -> dict job, trial = _control_trial(side, jobs) if trial is None: raise client.JudgeError(0, f"{side.control} trial {side.trial_name} is not in this workspace") - return batch.ask_and_store(store.home(), job_key(job), trial.key, control_states(side, trial), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job)) + return batch.ask_and_store(store.home(), job_key(job), trial.trial_name, control_states(side, trial), api_key, post=post, + calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir) def triage_summary(report, jobs) -> dict: @@ -677,26 +677,25 @@ def judge_task(job, trial, api_key: str, post=None, calibration=None) -> dict | @app.template_global() def judgements_unmoved() -> bool: - """Whether the judgements workspaces kept before may still wait to be moved (`store.moved`).""" - return not store.moved() + """Whether a workspace's judgements kept before still wait to be moved (`store.old_stores`).""" + return bool(store.old_stores(shared.WS_HOME)) @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; ``unread``, the - workspaces left for a later move.""" + 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)]) shared._require_csrf() if not shared._local_client(): abort(403) try: - unread = store.move(shared.WS_HOME) + left = store.move(shared.WS_HOME) except store.Unreadable as e: return jsonify(ok=False, error=str(e)), 409 - if unread: - return jsonify(ok=False, error="Not moved: " + ", ".join(unread) + (" has" if len(unread) == 1 else " have") - + " a root that cannot be read."), 409 + if left: + return jsonify(ok=False, error="Left for later: " + "; ".join(left) + "."), 409 return jsonify(ok=True) diff --git a/docs/judgement.md b/docs/judgement.md index c95507048..1db7a6d6c 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -69,9 +69,9 @@ 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, 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 | -| 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 in `judgements-of-deleted-workspaces/`; one with old records not yet moved is refused while one of its roots cannot be read | +| 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, 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 or a file cannot be read, or a record belongs to no job found or to two jobs; such a record is still shown, 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 not yet moved is refused while one of its roots 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 | | Noise floors | Each yes/no's run-to-run spread | From 2df7abdfbee442c5f5657385b569f4c9436d1f5b Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 26 Nov 2026 11:45:00 +0100 Subject: [PATCH 06/24] fix(runs): decide a deleted launch's judgements from fresh files and keep those an unread root may need A copy elsewhere is read from the job folders, never a cached parse, and runs of the launch deleted together are no copy of each other. A judgement folder is removed under the lock saves take. The workspace's job list keeps a job whose root cannot be read. --- app/nullius/execution.py | 44 ++++++++++++++++++------------------ app/nullius/workspace.py | 3 ++- app/tests/test_run_delete.py | 29 ++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 23 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 1ee182e6c..d18b859df 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -1833,8 +1833,8 @@ def deletable(names: List[str], root: Optional[str] = None) -> None: def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, ends: dict, final: bool = False) -> dict: """What deleting the run *name* removes. Its judgements are counted, the older records its workspaces kept included, nothing written; *final* (the - delete itself) copies those older records in first and keeps the - judgements of a job a copy of which is found elsewhere (`_judged_elsewhere`).""" + delete itself) copies those older records in first. ``uids``: its jobs' + identities, whose judgements ``deletion`` keeps when a copy is found elsewhere.""" path, rec = _deletable(name, root) plan = rec.get("plan") or {} # a run refused at the name check never made the host folder: one of that name there is not its own @@ -1854,29 +1854,26 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, judged = judgements.job_dirs(ws.dir, [i for i in ids if i.split("~")[0] not in others]) held.append({"ws": ws, "roots": roots, "jobs": dirs, "judged": judged}) uids = {parse.parse_job(d, trials=False).uid for d in parse.find_job_dirs([os.path.join(path, "jobs")])} - {""} - if final and judgements.job_dirs(judgements.home(), sorted(uids)): - uids -= _judged_elsewhere(home, path, uids) - return {"name": name, "dir": path, "bytes": size_of(path), "host": host, "workspaces": held, + return {"name": name, "dir": path, "bytes": size_of(path), "host": host, "workspaces": held, "uids": uids, "judged": judgements.job_dirs(judgements.home(), sorted(uids)), "judgements": judgements.records_of(judgements.home(), uids, olds)} -def _judged_elsewhere(home: str, path: str, uids: set) -> set: - """Which of the jobs *uids* of the run folder *path* keep their - judgements when it goes: those with another folder of the same identity - outside it - a copy - under a root of any workspace or another run, and - all of them when one of those roots cannot be read, since who owns them - is then unknown.""" - outside = lambda d: os.path.commonpath([os.path.realpath(d), path]) != path - kept = set() +def _judged_elsewhere(home: str, paths: list, uids: set) -> set: + """Which of the jobs *uids* of the run folders *paths*, deleted together, + keep their judgements: those with another folder of the same identity + outside them - a copy - under a root of any workspace or another run, read + afresh, never from a cache; all of them when one of those roots cannot be + read, since who owns them is then unknown.""" + outside = lambda d: all(os.path.commonpath([os.path.realpath(d), p]) != p for p in paths) + roots = [] for ws in workspace.list_all(home): - roots = ws.job_roots or ws.roots - if not all(os.path.isdir(r) for r in roots): + if not all(os.path.isdir(r) for r in ws.job_roots or ws.roots): return set(uids) - kept |= {j.uid for j in workspace.load_jobs(ws, roots) if outside(j.dir)} & uids - others = [j for e in os.scandir(os.path.dirname(path)) - if e.is_dir(follow_symlinks=False) and e.path != path and os.path.isdir(j := os.path.join(e.path, "jobs"))] - return kept | ({parse.parse_job(d, trials=False).uid for d in parse.find_job_dirs(others)} & uids) + roots += ws.job_roots or ws.roots + roots += [j for parent in {os.path.dirname(p) for p in paths} for e in os.scandir(parent) + if e.is_dir(follow_symlinks=False) and e.path not in paths and os.path.isdir(j := os.path.join(e.path, "jobs"))] + return {parse.parse_job(d, trials=False).uid for d in parse.find_job_dirs(roots) if outside(d)} & uids def deletion(names: List[str], home: str, root: Optional[str] = None, holding: Optional[Callable] = None, @@ -1891,6 +1888,10 @@ def deletion(names: List[str], home: str, root: Optional[str] = None, holding: O holding = holding or (lambda path: workspace.holding(home, path)) ends = run_ends() runs = [_run_deletion(n, home, root, holding, ends, final) for n in dict.fromkeys(names)] + if final and any(r["judged"] for r in runs): + kept = _judged_elsewhere(home, [r["dir"] for r in runs], set().union(*(r["uids"] for r in runs))) + for r in runs: + r["judged"] = judgements.job_dirs(judgements.home(), sorted(r["uids"] - kept)) copies: Dict[str, int] = {} for r in runs: if r["host"]: @@ -1918,10 +1919,9 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r for key in [k for k, e in EXECUTIONS.items() if os.path.realpath(e.dir) == r["dir"]]: del EXECUTIONS[key] for d in r["judged"]: - shutil.rmtree(d, ignore_errors=True) + judgements.remove(d) for w in r["workspaces"]: - for d in w["judged"]: - shutil.rmtree(d, ignore_errors=True) + judgements.forget(w["ws"].dir, w["judged"]) # read again: another run of the launch may have left this workspace already ws = workspace.load(home, w["ws"].name) if ws is not None: diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 4698d742e..6bf62d1e8 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -640,7 +640,8 @@ def load_jobs(ws: Workspace, roots, runs: dict | None = None) -> list: jobs = [load_job(ws, d, index, runs)[0] for d in dirs] # a job folder gone from disk, or no longer found under these roots, leaves the index found = set(dirs) - gone = [d for d in index if d not in found and (_under(d, roots) or not os.path.isdir(d))] + # one under a root that cannot be read (unmounted) stays: whether it is gone is unknown + gone = [d for d in index if d not in found and (_under(d, roots) or not os.path.isdir(d) and os.path.isdir(os.path.dirname(d)))] if gone: keep = {_cache_file(ws, d) for d in dirs} # the same folder found by another path for d in gone: diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index eaddd4c2b..a40148380 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -105,6 +105,35 @@ def test_another_job_of_the_same_name_does_not_keep_them(self): execution.delete(["r1"], self.home, self.root) self.assertEqual(store.job_dirs(self.data, [uid]), []) + def test_runs_of_one_launch_deleted_together_are_no_copy_of_each_other(self): + uid = self.judged(self.jobs, "job-a") + self.run_("r2") + execution.delete(["r1", "r2"], self.home, self.root) + self.assertEqual(store.job_dirs(self.data, [uid]), []) + + def test_a_copy_is_told_from_its_files_not_from_a_cached_parse(self): + start = lambda d, at: _write_json(os.path.join(d, "result.json"), {"id": "j1", "started_at": at, "stats": {}}) + start(os.path.join(self.jobs, "job-a"), "2026-09-04T00:00:00Z") + uid = self.judged(self.jobs, "job-a") + twin = os.path.join(self.tmp, "twin"); _job_dir(twin, "job-a"); start(os.path.join(twin, "job-a"), "2026-09-05T00:00:00Z") + d = workspace.create(self.home, [twin], label="d") + workspace.load_jobs(d, d.roots) # cached as another job + res = os.path.join(twin, "job-a", "result.json"); st = os.stat(res) + start(os.path.join(twin, "job-a"), "2026-09-04T00:00:00Z") # now a copy: same size, same time + os.utime(res, ns=(st.st_atime_ns, st.st_mtime_ns)) + self.assertEqual(self.uid("job-a", twin), uid) + execution.delete(["r1"], self.home, self.root) + self.assertTrue(store.job_dirs(self.data, [uid])) + + def test_a_job_of_the_same_id_under_a_root_that_cannot_be_read_keeps_the_old_records(self): + twin = os.path.join(self.tmp, "twin"); _job_dir(twin, "job-a") + self.a.roots.append(twin); workspace.save(self.a); workspace.load_jobs(self.a, self.a.roots) + os.rename(twin, twin + ".unmounted") + workspace.load_jobs(self.a, [self.jobs]) # a page of the run's root alone + self.assertEqual(sorted(e.get("job_id") for e in workspace.job_index(self.a).values()), ["job-a", "job-a", "job-b"]) + execution.delete(["r1"], self.home, self.root) + self.assertEqual(len(store.job_dirs(self.a.dir, ["job-a"])), 2) + def test_a_job_of_the_same_id_in_another_root_keeps_its_judgements(self): twin = os.path.join(self.tmp, "twin"); _job_dir(twin, "job-a") self.a.roots.append(twin); workspace.save(self.a); workspace.load_jobs(self.a, self.a.roots) From ce06dfe5c28ffd73dbbbcabf29bfe0547aa14733 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:58:28 +0100 Subject: [PATCH 07/24] fix(judge): keep a try's judgement under its attempt's name, told apart by its start A verdict saved while a trial was the last try missed once the runner moved that try aside as .try-N, and a record that names no start matched the try that replaced it. A try with a start is now kept and read under its attempt's name by that start, so it is found before and after it is moved; one kept under the try's own name is still read. Of an attempt with several tries, a record that names no start is no try's: shown on none, and set aside, not merged, by a save. --- app/nullius/judge/batch.py | 9 ++-- app/nullius/judge/store.py | 34 +++++++++------ app/ui_tests/test_judge_calibration_reads.py | 2 +- app/ui_tests/test_judgement_follows_job.py | 23 ++++++++++ app/web/judge.py | 45 +++++++++++++++----- app/web/reconcile.py | 3 +- 6 files changed, 87 insertions(+), 29 deletions(-) diff --git a/app/nullius/judge/batch.py b/app/nullius/judge/batch.py index 13a0751c0..bd4da21f6 100644 --- a/app/nullius/judge/batch.py +++ b/app/nullius/judge/batch.py @@ -98,7 +98,8 @@ def ask_states(states: dict, key: str, post: Optional[Callable] = None, calibrat def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, post: Optional[Callable] = None, calibration: Optional[dict] = None, started: Optional[str] = None, - lane: Optional[str] = None, old: Optional[dict] = None, job_dir: Optional[str] = None) -> Optional[dict]: + lane: Optional[str] = None, old: Optional[dict] = None, job_dir: Optional[str] = None, + strict: bool = False) -> Optional[dict]: """`ask_states`, then the merged record saved under the trial's key - its answers over the version's earlier ones - in the store at `base` (`store.home`). Returns the record as stored. The pre-flight reads the @@ -106,7 +107,8 @@ def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, po start, which the record keeps (`store.save`). `lane`: where it is kept, the judge's own lane unless named (`store.TASKS`). `old`: the job's older records (`store.overlay`), the file's copied in by the save. `job_dir`: the - job's folder, nothing saved once it is deleted (`store.Gone`).""" + job's folder, nothing saved once it is deleted (`store.Gone`). `strict`: an + attempt with several tries (`store.save`).""" if calibration is None: calibration = store.calibration(base, [job_id]) rec = ask_states(states, key, post=post, calibration=calibration) @@ -115,5 +117,6 @@ def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, po # earlier readings for the others, as the answers are kept (`store.save`), and returns them lane = lane or getattr(key, "lane", "decision") rec.setdefault("hygiene", {}) - rec["hygiene"] = store.save(base, job_id, trial_name, rec, lane=lane, started=started, old=old, job_dir=job_dir)["hygiene"] + rec["hygiene"] = store.save(base, job_id, trial_name, rec, lane=lane, started=started, old=old, job_dir=job_dir, + strict=strict)["hygiene"] return rec diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 88a9e7138..f1cc5f163 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -145,12 +145,15 @@ def _versions(version: Optional[str]) -> tuple: return (version,) if version else (Q.VERSION, *Q.EARLIER) -def _of(rec: Optional[dict], started: Optional[str]) -> bool: +def _of(rec: Optional[dict], started: Optional[str], strict: bool = False) -> bool: """Whether a record judged the try that started at ``started``: a retry runs an attempt again under its trial's name, and what was asked of the try before is not this one's. A record from before tries were told - apart, or a check that names no start, takes it as it is.""" - return not started or not rec or rec.get("trial_started_at") in (None, started) + apart, or a check that names no start, takes it as it is, unless + `strict` (an attempt with several tries): which try it judged is unknown.""" + if not started or not rec: + return True + return rec.get("trial_started_at") == started or (not strict and rec.get("trial_started_at") is None) def _try(version: str, started: str) -> str: @@ -158,24 +161,25 @@ def _try(version: str, started: str) -> str: return f"{version}@{started}" -def _pick(data: dict, version: Optional[str], started: Optional[str] = None) -> Optional[dict]: +def _pick(data: dict, version: Optional[str], started: Optional[str] = None, strict: bool = False) -> Optional[dict]: for v in _versions(version): for rec in (data.get(v), started and data.get(_try(v, started))): - if rec and _of(rec, started): + if rec and _of(rec, started, strict): return rec return None def load(base: str, job_id: str, trial_name: str, version: Optional[str] = None, lane: str = "decision", - started: Optional[str] = None, old: Optional[dict] = None) -> Optional[dict]: + started: Optional[str] = None, old: Optional[dict] = None, strict: bool = False) -> Optional[dict]: """The record under `version`; with none named, the current version or the newest earlier one that has a record. `started`: the trial's own - start, so a record of an earlier try under its name is none of its. + start, so a record of an earlier try under its name is none of its + (`strict`: an attempt with several tries, `_of`). `old`: the job's older records (`overlay`), read with it.""" if not job_id: # a job with no identity yet (Job.uid_source "pending") has no judgement return None found = _paths(base, job_id, trial_name, lane) - return _pick(_with(_read(found), _olds(old, found)), version, started) + return _pick(_with(_read(found), _olds(old, found)), version, started, strict) def _olds(old: Optional[dict], found) -> list: @@ -189,7 +193,8 @@ def is_current(record: Optional[dict]) -> bool: def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "decision", - started: Optional[str] = None, old: Optional[dict] = None, job_dir: Optional[str] = None) -> dict: + started: Optional[str] = None, old: Optional[dict] = None, job_dir: Optional[str] = None, + strict: bool = False) -> dict: """The record under its question version, returned as stored; other versions kept. A record's answers and hygiene readings merge over the version's earlier ones, so judging one question later does not drop the others. Saves to @@ -207,8 +212,9 @@ def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "dec data = _with(_read(found, strict=True), _olds(old, found)) version = record.get("questions", Q.VERSION) earlier = data.get(version) or {} - if not _of(earlier, started): # another try's: kept beside, and none of its answers are this one's - data[_try(version, earlier["trial_started_at"])] = earlier + if not _of(earlier, started, strict): # another try's: kept beside, and none of its answers are this one's + at = earlier.get("trial_started_at") + data[_try(version, at) if at else f"{version}~{_digest(earlier)}"] = earlier # unstamped: whose is unknown earlier = data.pop(_try(version, started), None) or {} merged = dict(record, **({"trial_started_at": started} if started else {})) merged["answers"] = {**(earlier.get("answers") or {}), **(record.get("answers") or {})} @@ -220,13 +226,13 @@ def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "dec def for_job(base: str, job_id: str, started: dict, version: Optional[str] = None, lane: str = "decision", - old: Optional[dict] = None) -> dict: + old: Optional[dict] = None, strict=()) -> dict: """The judged trials of a job: {trial_name: record} for each trial of `started` - {trial_name: its start}, every trial of the job - that has - one, as `load` picks it.""" + one, as `load` picks it; `strict`: the names of those with several tries.""" out = {} for name, start in started.items(): - rec = load(base, job_id, name, version, lane, start, old) + rec = load(base, job_id, name, version, lane, start, old, strict=name in strict) if rec: out[name] = rec return out diff --git a/app/ui_tests/test_judge_calibration_reads.py b/app/ui_tests/test_judge_calibration_reads.py index d0f6e8e00..045702f86 100644 --- a/app/ui_tests/test_judge_calibration_reads.py +++ b/app/ui_tests/test_judge_calibration_reads.py @@ -41,7 +41,7 @@ def setUp(self): def reads_to_judge_all(self, n): web.shared.open_workspace(workspace.create(web.shared.WS_HOME, [], f"w{n}")) job_id = "job" - trials = [NS(trial_name=f"t{i}", key=f"t{i}", has_trajectory=True, trajectory_path="-", started_at=None, outcome="resolved") for i in range(n)] + trials = [NS(trial_name=f"t{i}", key=f"t{i}", has_trajectory=True, trajectory_path="-", started_at=None, outcome="resolved", n_retries=0) for i in range(n)] job = NS(job_id=job_id, uid=f"uid-{n}", dir=str(self.tmp), dataset="", dataset_path="", trials=trials) real_open, reads = builtins.open, [0] diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 9bd6ddfc0..b3b497bec 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -187,6 +187,29 @@ def test_two_tries_each_show_and_keep_their_own_record(self): shown = [web.judge.judgement_of(job, t)["answers"]["failure_cause"]["choice"] for t in (first, last)] self.assertEqual(shown, ["first", "last"]) + def test_a_try_judged_while_it_was_the_last_keeps_its_record_once_moved_aside(self): + from nullius.runs import parse + tmp = Path(tempfile.mkdtemp(prefix="nullius-judge-tries-")); self.addCleanup(shutil.rmtree, tmp, True) + d = copy_job(tmp / "runs" / "job-x") + asked = lambda *a, **k: {"questions": Q.VERSION, "answers": {"failure_cause": {"choice": "first"}}} + with patch.object(web.judge.store, "home", return_value=str(tmp / "data")), \ + patch.object(web.judge.trajectory, "load", return_value=SimpleNamespace(error=None)), \ + patch.object(web.judge, "_trial_ids_and_states", return_value={}), \ + patch.object(web.judge.batch, "ask_states", asked), web.app.test_request_context("/"): + job = parse.parse_job(str(d)) + web.judge.judge_trial(job, next(t for t in job.trials if t.trial_name == TRIAL), "k", calibration={}) + (d / "retried").mkdir() + shutil.move(d / TRIAL, d / "retried" / f"{TRIAL}.try-1") # the runner tries the attempt again + shutil.copytree(d / "retried" / f"{TRIAL}.try-1", d / TRIAL) + res = json.loads((d / TRIAL / "result.json").read_text()) + (d / TRIAL / "result.json").write_text(json.dumps(dict(res, started_at="2026-12-01T00:00:00Z", standard={"retries": 1}))) + job = parse.parse_job(str(d)) + (_, first), (_, last) = parse.tries(next(t for t in job.trials if t.trial_name == TRIAL)) + web.judge.store.save(str(tmp / "data"), job.uid, TRIAL, {"questions": Q.VERSION, "answers": {"q": 1}}, lane="llm") + self.assertEqual(web.judge.judgement_of(job, first)["answers"]["failure_cause"]["choice"], "first") + self.assertIsNone(web.judge.judgement_of(job, last)) + self.assertEqual([web.judge.judgement_of(job, t, lane="llm") for t in (first, last)], [None, None]) # no start: whose is unknown + if __name__ == "__main__": unittest.main() diff --git a/app/web/judge.py b/app/web/judge.py index 0af98f7f9..dcfc8dc0f 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -100,8 +100,28 @@ def started_by_name(job) -> dict: return {t.trial_name: started_of(t) for t in job.trials} +def strict(trial) -> bool: + """Whether the trial is one try of an attempt with several: a record that names no start is then no try's.""" + return bool(trial.n_retries) or trial.key != trial.trial_name + + +def retried(job) -> set: + """The names of a job's trials with several tries (`strict`), for `store.for_job`.""" + return {t.trial_name for t in job.trials if strict(t)} + + +def slot(trial) -> str: + """The name a try's record is kept under: its attempt's (``Trial.key``), told apart by its + start, so it is found before and after the try is moved aside; a try with no start, its own.""" + return trial.key if started_of(trial) else trial.trial_name + + def judgement_of(job, trial, lane: str = "decision") -> dict | None: - return store.load(store.home(), job_key(job), trial.trial_name, lane=lane, started=started_of(trial), old=old_of(job)) + """A try's record (`slot`); else one kept under the try's own name, as before.""" + uid, start, old = job_key(job), started_of(trial), old_of(job) + return (store.load(store.home(), uid, slot(trial), lane=lane, started=start, old=old, strict=strict(trial)) + or (store.load(store.home(), uid, trial.trial_name, lane=lane, started=start, old=old) + if slot(trial) != trial.trial_name else None)) def panel(job, trial, lane: str = "decision") -> dict: @@ -279,8 +299,9 @@ def judge_trial(job, trial, api_key: str, post=None, calibration=None) -> dict: traj = trajectory.load(trial.trajectory_path) if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) - return batch.ask_and_store(store.home(), job_key(job), trial.trial_name, _trial_ids_and_states(trial, traj), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir) + return batch.ask_and_store(store.home(), job_key(job), slot(trial), _trial_ids_and_states(trial, traj), api_key, post=post, + calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir, + strict=strict(trial)) def _guard(): @@ -320,7 +341,7 @@ def judge_job_route(job_id): if job is None: abort(404) lane = request.form.get("lane") if request.form.get("lane") in client.LANES else "decision" - judged = store.for_job(store.home(), job_key(job), started_by_name(job), lane=lane, old=old_of(job)) + judged = store.for_job(store.home(), job_key(job), started_by_name(job), lane=lane, old=old_of(job), strict=retried(job)) todo = [t for t in job.trials if t.has_trajectory and t.trial_name not in judged] k, cal = key(lane), batch_calibration() done, failed = run_batch(todo, lambda t: judge_trial(job, t, k, calibration=cal), lambda t: t.trial_name) @@ -339,7 +360,7 @@ def job_summary(job) -> dict: the board's record -> judge lanes (`nullius.judge.lanes`), whose status for each trial is also in `by_trial`.""" d, uid, old = store.home(), job_key(job), old_of(job) - judged = store.for_job(d, uid, started_by_name(job), old=old) + judged = store.for_job(d, uid, started_by_name(job), old=old, strict=retried(job)) flag_ids = [q for q in Q.group_ids("trial") if Q.QUESTIONS[q].get("flag")] board = lanes.board(job, judged) by_trial = {} @@ -372,7 +393,7 @@ def job_summary(job) -> dict: def _llm_count(d, job) -> dict: """The LLM judge's own count for the job's button: it judges apart from Decision, so a trial judged by one is still unjudged by the other.""" - judged = store.for_job(d, job_key(job), started_by_name(job), lane="llm", old=old_of(job)) + judged = store.for_job(d, job_key(job), started_by_name(job), lane="llm", old=old_of(job), strict=retried(job)) return {"unjudged": len([t for t in job.trials if t.trial_name not in judged]), "keyed": bool(key("llm"))} @@ -406,7 +427,8 @@ def side_of(job, trial, column) -> dict | None: """One side's score as the compare page shows it, from the trial's own current record, the job opened from its column's workspace `column`: the expectation, the level it rounds to, the judge's confidence, the provenance. None until scored under the current vocabulary.""" - rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column)) + rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column), + strict=strict(trial)) if not rec or not store.is_current(rec): return None a = (rec.get("answers") or {}).get(SIDE_QUESTION) @@ -465,7 +487,8 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> when it has them all.""" if not trial.has_trajectory: raise client.JudgeError(0, "this trial has no trajectory to judge") - rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column)) + rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column), + strict=strict(trial)) have = (rec.get("answers") or {}) if store.is_current(rec) else {} ids = [q for q in side_ids(trial) if q not in have] if not ids: @@ -474,7 +497,8 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) return batch.ask_and_store(store.home(), job_key(job, column), trial.trial_name, _states_for(trial, traj, ids), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job, column), job_dir=job.dir) + calibration=calibration, started=started_of(trial), old=old_of(job, column), job_dir=job.dir, + strict=strict(trial)) def _sides_todo(view) -> list: @@ -560,7 +584,8 @@ def judge_control(side, jobs, api_key: str, post=None, calibration=None) -> dict if trial is None: raise client.JudgeError(0, f"{side.control} trial {side.trial_name} is not in this workspace") return batch.ask_and_store(store.home(), job_key(job), trial.trial_name, control_states(side, trial), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir) + calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir, + strict=strict(trial)) def triage_summary(report, jobs) -> dict: diff --git a/app/web/reconcile.py b/app/web/reconcile.py index 977a7b157..1c7df2769 100644 --- a/app/web/reconcile.py +++ b/app/web/reconcile.py @@ -25,7 +25,8 @@ def threshold_requested() -> float: def view_of(job, threshold: float) -> dict: - records = store.for_job(store.home(), judge.job_key(job), judge.started_by_name(job), old=judge.old_of(job)) + records = store.for_job(store.home(), judge.job_key(job), judge.started_by_name(job), old=judge.old_of(job), + strict=judge.retried(job)) return reconcile.reconcile(job, records, threshold) From 44902eaab2e8cf7ccf3a10859676f5d2c0455836 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:58:48 +0100 Subject: [PATCH 08/24] fix(execution): remove a deleted launch's judgements only once its runs are gone Two runs of one launch that hold copies of one job each excluded the other as a copy, and the first one removed took the job's judgements while the second could still fail to go. The judgements of the user's store are now decided once every run went or stayed: a run that stayed, even in part, keeps the identities its jobs had before the delete, the copies are read afresh against what is left, and a folder that cannot be listed then keeps them all. Each identity keeps where it came from. --- app/nullius/execution.py | 37 ++++++++++++++++++++++++------------ app/tests/test_run_delete.py | 20 +++++++++++++++++++ 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index d18b859df..b322aca83 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -1833,8 +1833,9 @@ def deletable(names: List[str], root: Optional[str] = None) -> None: def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, ends: dict, final: bool = False) -> dict: """What deleting the run *name* removes. Its judgements are counted, the older records its workspaces kept included, nothing written; *final* (the - delete itself) copies those older records in first. ``uids``: its jobs' - identities, whose judgements ``deletion`` keeps when a copy is found elsewhere.""" + delete itself) copies those older records in first. + ``uids``: its jobs' identities and where each came from (``Job.uid_source``), + whose judgements ``delete`` keeps when a copy is found elsewhere.""" path, rec = _deletable(name, root) plan = rec.get("plan") or {} # a run refused at the name check never made the host folder: one of that name there is not its own @@ -1853,7 +1854,8 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, others = {e.get("job_id") for d, e in workspace.job_index(ws).items() if d not in dirs} judged = judgements.job_dirs(ws.dir, [i for i in ids if i.split("~")[0] not in others]) held.append({"ws": ws, "roots": roots, "jobs": dirs, "judged": judged}) - uids = {parse.parse_job(d, trials=False).uid for d in parse.find_job_dirs([os.path.join(path, "jobs")])} - {""} + uids = {j.uid: j.uid_source for j in (parse.parse_job(d, trials=False) for d in parse.find_job_dirs([os.path.join(path, "jobs")])) + if j.uid} return {"name": name, "dir": path, "bytes": size_of(path), "host": host, "workspaces": held, "uids": uids, "judged": judgements.job_dirs(judgements.home(), sorted(uids)), "judgements": judgements.records_of(judgements.home(), uids, olds)} @@ -1865,6 +1867,13 @@ def _judged_elsewhere(home: str, paths: list, uids: set) -> set: outside them - a copy - under a root of any workspace or another run, read afresh, never from a cache; all of them when one of those roots cannot be read, since who owns them is then unknown.""" + try: + return _copies(home, paths, uids) + except OSError: + return set(uids) + + +def _copies(home: str, paths: list, uids: set) -> set: outside = lambda d: all(os.path.commonpath([os.path.realpath(d), p]) != p for p in paths) roots = [] for ws in workspace.list_all(home): @@ -1883,15 +1892,12 @@ def deletion(names: List[str], home: str, root: Optional[str] = None, holding: O holds it its roots, parsed jobs and judgement folders; the totals, and the number of copies per host. ValueError when any of them is alive or is not a run: nothing goes then. ``holding``: a run folder's ``workspace.holding``, - when the caller has it already. The judgements are those of every job of - the runs until *final*, the delete's own (`_run_deletion`).""" + when the caller has it already. Its judgement folders in the user's store + (``judged``) are those of every job of the runs; ``delete`` decides which + go once the runs went.""" holding = holding or (lambda path: workspace.holding(home, path)) ends = run_ends() runs = [_run_deletion(n, home, root, holding, ends, final) for n in dict.fromkeys(names)] - if final and any(r["judged"] for r in runs): - kept = _judged_elsewhere(home, [r["dir"] for r in runs], set().union(*(r["uids"] for r in runs))) - for r in runs: - r["judged"] = judgements.job_dirs(judgements.home(), sorted(r["uids"] - kept)) copies: Dict[str, int] = {} for r in runs: if r["host"]: @@ -1906,9 +1912,11 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r in every workspace, and its copy on its host when that host's label is in *copies*. Returns ``deletion``'s answer, with ``stays``: the runs whose folder could not go (they keep everything else), and ``kept``: one line - per thing that stays.""" + per thing that stays. The judgements of the user's store go last, once + every folder went or stayed: those of a job no folder of which is left.""" gone = deletion(names, home, root, final=True) gone["stays"], gone["kept"] = [], [] + went = [] for r in gone["runs"]: try: shutil.rmtree(r["dir"]) @@ -1916,10 +1924,9 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r gone["stays"].append(r["name"]) gone["kept"].append(f"{r['name']} stays in {r['dir']}: {e.strerror or e}") continue + went.append(r) for key in [k for k, e in EXECUTIONS.items() if os.path.realpath(e.dir) == r["dir"]]: del EXECUTIONS[key] - for d in r["judged"]: - judgements.remove(d) for w in r["workspaces"]: judgements.forget(w["ws"].dir, w["judged"]) # read again: another run of the launch may have left this workspace already @@ -1931,4 +1938,10 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r rc, out = (run or subprocess_run)(host.argv(f"rm -rf {_rq(REMOTE_HOME + '/runs/' + r['name'])}", timeout=15), 60) if rc != 0: gone["kept"].append(f"the copy of {r['name']} on {host.label} stays: " + redact.redact(out.strip()[-200:])) + # a run that stayed, even in part, keeps its jobs' identities as they were read before the delete + uids = {u for r in went for u in r["uids"]} - {u for r in gone["runs"] if r not in went for u in r["uids"]} + if uids and judgements.job_dirs(judgements.home(), sorted(uids)): + uids -= _judged_elsewhere(home, [r["dir"] for r in went], uids) + for d in judgements.job_dirs(judgements.home(), sorted(uids)): + judgements.remove(d) return gone diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index a40148380..120e081ab 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -111,6 +111,26 @@ def test_runs_of_one_launch_deleted_together_are_no_copy_of_each_other(self): execution.delete(["r1", "r2"], self.home, self.root) self.assertEqual(store.job_dirs(self.data, [uid]), []) + def test_a_run_that_stays_keeps_the_judgements_of_its_jobs(self): + uid = self.judged(self.jobs, "job-a") + r2 = os.path.dirname(self.run_("r2")) # a copy of job-a, deleted with r1 + real = shutil.rmtree + + def fails(path, *a, **k): + if os.path.realpath(path) == os.path.realpath(r2): + os.remove(os.path.join(r2, "jobs", "job-a", "config.json")) # in part: its identity read now is another + raise PermissionError(13, "Permission denied", path) + return real(path, *a, **k) + with patch.object(execution.shutil, "rmtree", fails): + got = execution.delete(["r1", "r2"], self.home, self.root) + self.assertEqual(got["stays"], ["r2"]) + self.assertTrue(store.job_dirs(self.data, [uid])) + with self.subTest("a root that cannot be listed when they are decided"), \ + patch.object(execution, "_copies", side_effect=PermissionError(13, "Permission denied")): + _job_dir(os.path.join(r2, "jobs"), "job-a") # whole again: job-a's last folder + execution.delete(["r2"], self.home, self.root) + self.assertTrue(store.job_dirs(self.data, [uid])) + def test_a_copy_is_told_from_its_files_not_from_a_cached_parse(self): start = lambda d, at: _write_json(os.path.join(d, "result.json"), {"id": "j1", "started_at": at, "stats": {}}) start(os.path.join(self.jobs, "job-a"), "2026-09-04T00:00:00Z") From 34d594836ad603bfa3bee18fd071994f2ec040c0 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:59:28 +0100 Subject: [PATCH 09/24] fix(judge): copy a workspace's older judgements only to the one job that owns each A save copied in every older record of the file it wrote, so a record that two jobs of one name may own went into both. Move, a save, a workspace's delete and a launch's delete now share one owner check, read afresh from the roots: a job still starting counts as a possible owner, a root that cannot be read leaves every owner unknown, and only a record one job alone owns is ever copied. The others stay where they are, still shown, and a deleted workspace keeps them whole beside its other files. Move also marks a workspace by the paths and contents of the files it copied, so one rewritten in place since is read again, and leaves for later a workspace whose folders cannot all be listed. --- app/nullius/execution.py | 19 +-- app/nullius/judge/store.py | 188 +++++++++++++++------ app/nullius/workspace.py | 5 +- app/tests/test_judge_adopt.py | 41 +++++ app/tests/test_run_delete.py | 2 +- app/ui_tests/test_judgement_follows_job.py | 17 ++ app/web/judge.py | 21 ++- docs/judgement.md | 2 +- 8 files changed, 226 insertions(+), 69 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index b322aca83..98752283f 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -1833,7 +1833,8 @@ def deletable(names: List[str], root: Optional[str] = None) -> None: def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, ends: dict, final: bool = False) -> dict: """What deleting the run *name* removes. Its judgements are counted, the older records its workspaces kept included, nothing written; *final* (the - delete itself) copies those older records in first. + delete itself) copies in first those older records one of its jobs alone + owns (`judgements.adopt_owned`), and names their folders (``judged``) to remove with it. ``uids``: its jobs' identities and where each came from (``Job.uid_source``), whose judgements ``delete`` keeps when a copy is found elsewhere.""" path, rec = _deletable(name, root) @@ -1844,15 +1845,13 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, for ws, roots in holding(path): dirs = parse.find_job_dirs(roots) jobs = workspace.load_jobs(ws, roots, ends) - for j in jobs: # the workspace's records from before: copied in when it goes, else counted as they are - if final: - judgements.adopt(ws.dir, j) - else: - olds.append(judgements.overlay(ws.dir, j)) - ids = [j.job_id for j in jobs] - # a job of the same id from another root shares these judgements: they stay - others = {e.get("job_id") for d, e in workspace.job_index(ws).items() if d not in dirs} - judged = judgements.job_dirs(ws.dir, [i for i in ids if i.split("~")[0] not in others]) + judged = [] + if final: # the workspace's records from before: those of its jobs alone copied in + done = judgements.adopt_owned(ws, dirs=set(dirs)) or set() + judged = [d for d in judgements.job_dirs(ws.dir, [j.job_id for j in jobs]) + if all(os.path.join(d, n) in done for n in os.listdir(d) if n.endswith(".json"))] + else: # else counted as they are + olds += [judgements.overlay(ws.dir, j) for j in jobs] held.append({"ws": ws, "roots": roots, "jobs": dirs, "judged": judged}) uids = {j.uid: j.uid_source for j in (parse.parse_job(d, trials=False) for d in parse.find_job_dirs([os.path.join(path, "jobs")])) if j.uid} diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index f1cc5f163..4a323f755 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -369,36 +369,56 @@ def _merge_into(path: str, old, job_dir: Optional[str] = None) -> None: ondisk.write_whole(path, json.dumps(got, indent=1), mode=0o600) +def _raise(e: OSError): + raise e + + def _old_files(ws_dir: str) -> list: - """The files of a workspace's store from before, by their path in it.""" - return sorted(os.path.relpath(os.path.join(d, f), ws_dir) for r in ROOTS.values() - for d, _, fs in os.walk(os.path.join(ws_dir, r)) for f in fs if f.endswith(".json")) + """The files of a workspace's store from before, by their path in it. OSError when a folder + of it cannot be listed: what it holds is unknown.""" + return sorted(os.path.relpath(os.path.join(d, f), ws_dir) for r in ROOTS.values() if os.path.isdir(os.path.join(ws_dir, r)) + for d, _, fs in os.walk(os.path.join(ws_dir, r), onerror=_raise) for f in fs if f.endswith(".json")) def _marker(ws_dir: str, into: str) -> str: return os.path.join(_root(into, "decision"), MOVED, os.path.basename(ws_dir)) -def _signature(files) -> str: - # shortcut: names only, so a file rewritten in place under the same name is not seen; stat each if that matters - return hashlib.sha256("\n".join(files).encode("utf-8")).hexdigest() +def _bytes(path: str) -> Optional[bytes]: + try: + with open(path, "rb") as fh: + return fh.read() + except OSError: + return None + + +def _signature(ws_dir: str, files, raw: Optional[dict] = None) -> str: + """The digest of the files `files` of a workspace's store from before, by path and contents: + those in `raw` ({path: bytes}) as they were read, the others as they are now.""" + h = hashlib.sha256() + for f in files: + data = (raw or {}).get(f) + data = _bytes(os.path.join(ws_dir, f)) if data is None else data + h.update(f"{f}\0{hashlib.sha256(data).hexdigest() if data is not None else '-'}\n".encode("utf-8")) + return h.hexdigest() def moved(ws_dir: Optional[str], into: Optional[str] = None) -> bool: """Whether `move` copied every record of the workspace's store from before into the user's - store, and it holds no file since: one added, by a restore or an older Nullius, is read again.""" + store, and its files are as `move` read them: one added or rewritten since, by a restore or an + older Nullius, is read again, and so is a store whose folders cannot all be listed.""" if not ws_dir: return False try: with open(_marker(ws_dir, into or home()), encoding="utf-8") as fh: - return fh.read() == _signature(_old_files(ws_dir)) + return fh.read() == _signature(ws_dir, _old_files(ws_dir)) except OSError: return False -def _mark(ws_dir: str, into: str, files) -> None: +def _mark(ws_dir: str, into: str, files, raw: Optional[dict] = None) -> None: os.makedirs(os.path.dirname(_marker(ws_dir, into)), exist_ok=True) - ondisk.write_whole(_marker(ws_dir, into), _signature(files)) + ondisk.write_whole(_marker(ws_dir, into), _signature(ws_dir, files, raw)) def forget(ws_dir: str, folders) -> None: @@ -407,20 +427,25 @@ def forget(ws_dir: str, folders) -> None: for d in folders: shutil.rmtree(d, ignore_errors=True) if was: - _mark(ws_dir, home(), _old_files(ws_dir)) + try: + _mark(ws_dir, home(), _old_files(ws_dir)) + except OSError: + pass def _places(ws_dir: str, job, into: str): """(an older file, the file of the user's store it belongs in) for each the workspace's store from before holds for `job`: under its job id its trials' and tries' (each by its own name), and - its dataset's task records.""" + its dataset's task records. The file is None where it is named by the job's identity and the job + has none yet (pending).""" names = {} for t in job.trials: for name in (t.trial_name, *(f"{t.trial_name}.try-{i}" for i in range(1, min(getattr(t, "n_retries", 0) or 0, 99) + 1))): names.update((n, key(name)) for n in _names(name)) places = [(lane, j, job.uid, names) for lane in ROOTS for j in _names(job.job_id)] # before, a dataset's task records were a job of their own, named `task:`, and a job naming none its id - places += [(TASKS, j, task_dataset(job), {}) for j in _names("task:" + (job.dataset_path or job.dataset or "job:" + job.job_id))] + places += [(TASKS, j, task_dataset(job) if job.uid or job.dataset_path or job.dataset else "", {}) + for j in _names("task:" + (job.dataset_path or job.dataset or "job:" + job.job_id))] for lane, old, new, rename in places: src = os.path.join(_root(ws_dir, "decision" if lane == TASKS else lane), old) try: @@ -428,42 +453,97 @@ def _places(ws_dir: str, job, into: str): except OSError: continue for f in files: - yield os.path.join(src, f), os.path.join(_root(into, lane), key(new), rename.get(f[:-5], f[:-5]) + ".json") + yield os.path.join(src, f), (os.path.join(_root(into, lane), key(new), rename.get(f[:-5], f[:-5]) + ".json") + if new else None) + + +def owners(ws, into: Optional[str] = None, names=None) -> Optional[dict]: + """Who each older file of the workspace `ws`'s store may belong to: {the file: {the file of the + user's store it belongs in: the job's folder}}, over every job its roots hold, read afresh. A + job with no identity yet claims the files it would own under ``("pending", its folder)``, so + they have no single owner until it has one. `names`: the job folders of these names only, all + that can claim a job's own files. None while one of its roots cannot be read: its jobs, and so + the owners, are unknown.""" + from nullius.runs import parse + into = into or home() + roots = ws.job_roots or ws.roots + if not all(os.path.isdir(r) for r in roots): + return None + out: dict = {} + for d in parse.find_job_dirs(roots): + if names is None or os.path.basename(d) in names: + for job in parse.split_agents([parse.parse_job(d)]): + for src, dest in _places(ws.dir, job, into): + out.setdefault(src, {}).setdefault(dest or ("pending", d), d) + return out -def _old(path: str) -> Optional[dict]: - """An older file's records; None when it cannot be read or holds no JSON object.""" +def single(owned: Optional[dict]) -> dict: + """{older file: (the file of the user's store it belongs in, its job's folder)} for each file + of `owners` that one job with an identity owns: the only ones ever copied.""" + out = {} + for src, dests in (owned or {}).items(): + [(dest, job_dir)] = dests.items() if len(dests) == 1 else [(None, None)] + if isinstance(dest, str): + out[src] = (dest, job_dir) + return out + + +def _old(path: str, raw: Optional[bytes] = None) -> Optional[dict]: + """An older file's records (from `raw`, its bytes, when given); None when it cannot be read or + holds no JSON object.""" + raw = _bytes(path) if raw is None else raw try: - with open(path, encoding="utf-8") as fh: - data = json.load(fh) - except (OSError, ValueError): + data = json.loads(raw) if raw is not None else False + except ValueError: return None return {} if data is None else data if isinstance(data, dict) else None -def overlay(ws_dir: Optional[str], job, into: Optional[str] = None) -> dict: +def overlay(ws_dir: Optional[str], job, into: Optional[str] = None, only=None) -> dict: """What the workspace's store from before (`ws_dir`) holds for `job` (`_places`), as {the file of the user's store (`into`, `home()` by default) it belongs in: [its contents]}. Read only; a file that cannot be read is left out. Two jobs of one id in that workspace each get the same - records, as each showed them before. {} once the workspace is `moved`.""" + records, as each showed them before. `only`: those older files alone (a save's, `single`). + {} once the workspace is `moved`.""" into = into or home() if not ws_dir or not job.uid or moved(ws_dir, into): return {} out: dict = {} for src, dest in _places(ws_dir, job, into): - data = _old(src) + data = _old(src) if dest and (only is None or src in only) else None if data: out.setdefault(dest, []).append(data) return out -def adopt(ws_dir: str, job, into: Optional[str] = None) -> None: - """Copy `overlay` into the user's store, file by file under each file's lock. The workspace's files are - left as they are.""" - for path, old in overlay(ws_dir, job, into).items(): +def adopt(ws_dir: str, job, into: Optional[str] = None, only=None) -> None: + """Copy `overlay` (`only` those older files) into the user's store, file by file under each + file's lock. The workspace's files are left as they are.""" + for path, old in overlay(ws_dir, job, into, only).items(): _merge_into(path, old, getattr(job, "dir", None)) +def adopt_owned(ws, into: Optional[str] = None, dirs=None) -> Optional[set]: + """Copy into the user's store each older file of the workspace `ws` that one job owns + (`single`), of the job folders `dirs` only when given: the files copied (read, if empty), or + None, nothing copied, while a root cannot be read. A file several jobs may own stays where it is.""" + owned = owners(ws, into) + if owned is None: + return None + by_dest, done = {}, set() + for src, (dest, job_dir) in single(owned).items(): + if dirs is None or job_dir in dirs: + data = _old(src) + if data is not None: + done.add(src) + if data: + by_dest.setdefault(dest, (job_dir, []))[1].append(data) + for dest, (job_dir, old) in by_dest.items(): + _merge_into(dest, old, job_dir) + return done + + 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.""" @@ -474,13 +554,16 @@ def records_of(base: str, uids, olds=()) -> int: def old_stores(home_dir: str, into: Optional[str] = None) -> list: """[(workspace, its count of older records)] for each workspace whose store from before holds - any, until it is `moved`.""" + any, until it is `moved`; one whose folders cannot all be listed counts those it can.""" from nullius import workspace out = [] for ws in workspace.list_all(home_dir): - n = len(_old_files(ws.dir)) + try: + n = len(_old_files(ws.dir)) + except OSError: + n = -1 if n and not moved(ws.dir, into): - out.append((ws, n)) + out.append((ws, max(n, 0))) return out @@ -492,41 +575,46 @@ def move(home_dir: str, into: Optional[str] = None) -> list: """Copy every workspace's older records into the user's store, the older files left as they are, and mark each workspace whose every file went (`moved`), so reads stop consulting it. A workspace is left for a later move, as one line in the list returned, while one of its roots - cannot be read, or one of its files cannot be read, belongs to no job its roots hold, or belongs - to several (a job id two jobs share): such a file is copied nowhere, and still read as before. - Safe to run again.""" - from nullius import workspace + 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, or one still starting): + such a file is copied nowhere, and still read as before. Safe to run again.""" into = into or home() left = [] for ws, _ in old_stores(home_dir, into): - files = _old_files(ws.dir) # first: one added during the move leaves the workspace unmarked - roots = ws.job_roots or ws.roots - if not all(os.path.isdir(r) for r in roots): + try: + files = _old_files(ws.dir) # first: one added during the move leaves the workspace unmarked + except OSError: + left.append(f"{ws.label} (a folder cannot be read)") + continue + owned = owners(ws, into) + if owned is None: left.append(f"{ws.label} (a root cannot be read)") continue - owners: dict = {} - for job in workspace.load_jobs(ws, roots): - if job.uid: - for src, dest in _places(ws.dir, job, into): - owners.setdefault(src, {}).setdefault(dest, job.dir) - unread, shared, by_dest = 0, 0, {} - for src, dests in owners.items(): - data = _old(src) + raw = {f: _bytes(os.path.join(ws.dir, f)) for f in files} + one = single(owned) + unread, shared, pending, by_dest = 0, 0, 0, {} + for src, dests in owned.items(): + rel = os.path.relpath(src, ws.dir) + data = _old(src, raw.get(rel)) if data is None: unread += 1 - elif len(dests) > 1: # unresolved: whose it is cannot be told - shared += 1 + elif src not in one: # unresolved: whose it is cannot be told + if all(isinstance(d, str) for d in dests): + shared += 1 + else: + pending += 1 elif data: - [(dest, job_dir)] = dests.items() + dest, job_dir = one[src] by_dest.setdefault(dest, (job_dir, []))[1].append(data) for dest, (job_dir, old) in by_dest.items(): _merge_into(dest, old, job_dir) - orphans = len({os.path.join(ws.dir, f) for f in files} - set(owners)) + orphans = len({os.path.join(ws.dir, f) for f in files} - set(owned)) why = [_plural(n, *w) for n, w in ((unread, ("file cannot be read", "files cannot be read")), (orphans, ("record of no job found", "records of no job found")), - (shared, ("record two jobs share", "records several jobs share"))) if n] + (shared, ("record two jobs share", "records several jobs share")), + (pending, ("record of a job still starting", "records of jobs still starting"))) if n] if why: left.append(f"{ws.label} ({', '.join(why)})") else: - _mark(ws.dir, into, files) + _mark(ws.dir, into, files, raw) return left diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 6bf62d1e8..dac2c1a77 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -252,7 +252,7 @@ def _check_roots(ws: Workspace) -> None: def _keep_judgements(ws: Workspace) -> None: """The judgements a workspace kept before they were kept by job (``/judgements{,-llm}/``): copied into the user's store under - each job its roots hold, then its files moved there whole, so none is + the one job its roots hold that owns each (`store.adopt_owned`), then its files moved there whole, so none is lost with it - a job its roots no longer reach included - and the User judge's failure analyses of its converted imports beside them, under ``imported/`` by their job folder's path. Refused while a root cannot be @@ -265,8 +265,7 @@ def _keep_judgements(ws: Workspace) -> None: return _check_roots(ws) if old and not store.moved(ws.dir): - for job in load_jobs(ws, ws.job_roots or ws.roots): - store.adopt(ws.dir, job) + 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}") os.makedirs(keep) for d in old: diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index b8a3c3655..f9cf2dff2 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -177,6 +177,28 @@ def test_a_workspace_is_moved_only_once_every_old_file_was_read_and_found_its_jo self.assertFalse(store.moved(ws.dir)) self.assertEqual([n for _, n in store.old_stores(home_dir)], [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") + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [root], label="w") + [j] = workspace.load_jobs(ws, ws.roots) + t0 = j.trials[0].trial_name + store.save(ws.dir, "job-a", t0, rec("2026-01-01T00:00:00Z", "first")) + self.assertEqual(store.move(home_dir), []) + self.assertTrue(store.moved(ws.dir)) + store.save(ws.dir, "job-a", t0, dict(rec("2026-01-02T00:00:00Z"), answers={"later": {"choice": "y"}})) # an older Nullius, in place + self.assertFalse(store.moved(ws.dir)) + self.assertIn("later", store.load(self.home, j.uid, t0, old=store.overlay(ws.dir, j))["answers"]) + self.assertEqual(store.move(home_dir), []) + real = os.scandir + def unlisted(p="."): + if isinstance(p, str) and os.path.basename(p) == "job-a": + raise PermissionError(13, "Permission denied", p) + return real(p) + with patch("os.scandir", unlisted): + self.assertFalse(store.moved(ws.dir)) + self.assertEqual(store.move(home_dir), ["w (a folder cannot be read)"]) + def test_a_record_two_jobs_of_one_id_share_is_moved_to_neither_and_still_shown_on_both(self): r1, r2 = (os.path.join(self.tmp, r) for r in ("r1", "r2")) _job_dir(r1, "job-x"); _job_dir(r2, "job-x") @@ -192,6 +214,25 @@ def test_a_record_two_jobs_of_one_id_share_is_moved_to_neither_and_still_shown_o self.assertFalse(os.path.isdir(os.path.join(self.home, "judgements")) and [d for d in os.listdir(os.path.join(self.home, "judgements")) if not d.startswith(".")]) self.assertEqual([bool(store.load(self.home, j.uid, t0, old=store.overlay(ws.dir, j))) for j in jobs], [True, True]) + workspace.delete(home_dir, ws.name) # nor by a delete: kept whole beside + self.assertFalse(os.path.isdir(os.path.join(self.home, "judgements"))) + [kept] = os.listdir(os.path.join(self.home, "judgements-of-deleted-workspaces")) + self.assertTrue(os.path.isfile(os.path.join(self.home, "judgements-of-deleted-workspaces", kept, "judgements", "job-x", t0 + ".json"))) + + def test_a_job_of_the_same_name_still_starting_may_own_them_too(self): + r1, r2 = (os.path.join(self.tmp, r) for r in ("r1", "r2")) + _job_dir(r1, "job-x") + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [r1, r2], label="w") + [j] = workspace.load_jobs(ws, ws.roots) # parsed before the other came + os.makedirs(os.path.join(r2, "job-x")) + with open(os.path.join(r2, "job-x", "config.json"), "w") as f: + json.dump({"job_name": "job-x", "agents": [{"name": "oracle"}]}, f) + t0 = j.trials[0].trial_name + store.save(ws.dir, "job-x", t0, rec("2026-01-01T00:00:00Z")) + self.assertEqual(store.move(home_dir), ["w (1 record of a job still starting)"]) + self.assertFalse(os.path.isdir(os.path.join(self.home, "judgements", j.uid))) + self.assertEqual(store.single(store.owners(ws, names={"job-x"})), {}) def test_deleting_a_workspace_keeps_the_failure_analyses_of_its_imports(self): from nullius.runs import failure_analysis as fa diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index 120e081ab..6ac43e4c3 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -158,7 +158,7 @@ def test_a_job_of_the_same_id_in_another_root_keeps_its_judgements(self): twin = os.path.join(self.tmp, "twin"); _job_dir(twin, "job-a") self.a.roots.append(twin); workspace.save(self.a); workspace.load_jobs(self.a, self.a.roots) execution.delete(["r1"], self.home, self.root) - self.assertEqual(len(store.job_dirs(self.a.dir, ["job-a"])), 2) + self.assertEqual(len(store.job_dirs(self.data, [self.uid("job-a", twin)])), 2) # a copy: its records follow it self.assertEqual(store.job_dirs(self.b.dir, ["job-a"]), []) def test_a_job_of_the_same_id_deleted_from_another_root_keeps_none(self): diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index b3b497bec..334fa24ef 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -81,6 +81,23 @@ def test_two_jobs_of_one_name_in_two_roots_keep_their_own_judgements(self): seen = {k: bool(web.judge.judgement_of(j, trial(j))) for k, j in jobs.items()} self.assertEqual(seen, {"one": True, "two": False}) + def test_a_record_kept_before_that_two_jobs_of_one_name_may_own_is_copied_by_neither_save(self): + copy_job(self.tmp / "one" / "job-x", "2026-01-01T00:00:00Z") + copy_job(self.tmp / "two" / "job-x", "2026-02-02T00:00:00Z") + both = workspace.create(web.shared.WS_HOME, [str(self.tmp / "one"), str(self.tmp / "two")], "Both") + web.shared.open_workspace(both) + old = Path(both.dir) / "judgements" / "job-x"; old.mkdir(parents=True) + (old / f"{TRIAL}.json").write_text(json.dumps({Q.VERSION: {"questions": Q.VERSION, "answers": {"kept": {"choice": "x"}}, + "asked_at": "2026-10-01T00:00:00Z"}})) + for j in workspace.load_jobs(both, both.roots): + t = next(t for t in j.trials if t.trial_name == TRIAL) + with web.app.test_request_context(f"/trial/job-x/{TRIAL}"): + web.judge.judge_trial(j, t, None) + self.assertTrue(web.judge.old_of(j)) # still read on both + saved = json.loads((self.tmp / "data" / "judgements" / j.uid / f"{TRIAL}.json").read_text()) + self.assertEqual({k: sorted(r["answers"]) if isinstance(r, dict) else r for k, r in saved.items()}, + {Q.VERSION: ["failure_cause"]}) + def tree(root: Path) -> dict: """Every file under *root* and its bytes, and every folder.""" diff --git a/app/web/judge.py b/app/web/judge.py index dcfc8dc0f..79e2cabbc 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -83,6 +83,19 @@ def old_of(job, name=None) -> dict: return memo[(d, job.dir, job.job_id)] +def own_of(job, name=None) -> dict: + """What a save copies of `old_of`: the records one job alone owns (`store.single`), its + owners read afresh; a record another job of its name may own stays unresolved, shown, never + copied. Once per request.""" + ws = shared._record_workspace(name) + memo = shared.request_memo("judgements_own") + k = (ws.dir if ws else None, job.dir, job.job_id) + if k not in memo: + one = store.single(store.owners(ws, names={os.path.basename(job.dir)})) if ws and job.uid else {} + memo[k] = store.overlay(ws.dir, job, only=set(one)) if one else {} + return memo[k] + + def batch_calibration() -> dict: """The calibration over the open workspace's jobs, read once for a batch and passed to each call; {} when there is no sample, so no call reads the store again.""" @@ -300,7 +313,7 @@ def judge_trial(job, trial, api_key: str, post=None, calibration=None) -> dict: if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) return batch.ask_and_store(store.home(), job_key(job), slot(trial), _trial_ids_and_states(trial, traj), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir, + calibration=calibration, started=started_of(trial), old=own_of(job), job_dir=job.dir, strict=strict(trial)) @@ -497,7 +510,7 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) return batch.ask_and_store(store.home(), job_key(job, column), trial.trial_name, _states_for(trial, traj, ids), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job, column), job_dir=job.dir, + calibration=calibration, started=started_of(trial), old=own_of(job, column), job_dir=job.dir, strict=strict(trial)) @@ -584,7 +597,7 @@ def judge_control(side, jobs, api_key: str, post=None, calibration=None) -> dict if trial is None: raise client.JudgeError(0, f"{side.control} trial {side.trial_name} is not in this workspace") return batch.ask_and_store(store.home(), job_key(job), trial.trial_name, control_states(side, trial), api_key, post=post, - calibration=calibration, started=started_of(trial), old=old_of(job), job_dir=job.dir, + calibration=calibration, started=started_of(trial), old=own_of(job), job_dir=job.dir, strict=strict(trial)) @@ -695,7 +708,7 @@ def judge_task(job, trial, api_key: str, post=None, calibration=None) -> dict | raise client.JudgeError(0, f"no instruction can be read for {trial.task_base}") states = batch.states_for(Q.group_ids("task"), lambda kind: judge_state.build(kind, None, instruction=instruction)) return batch.ask_and_store(store.home(), task_key(job), task_slot(trial), states, api_key, post=post, calibration=calibration, - lane=store.TASKS, old=old_of(job)) + lane=store.TASKS, old=own_of(job)) # -- the move of the judgements workspaces kept before into the user's store --------------- diff --git a/docs/judgement.md b/docs/judgement.md index 1db7a6d6c..2aec382f2 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, 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 or a file cannot be read, or a record belongs to no job found or to two jobs; such a record is still shown, never copied | +| 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 or to one still starting; such a record is still shown, never copied, even by a save | | 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 not yet moved is refused while one of its roots 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 | From be2d52145052867d8e91508e9079be20c1b0af29 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 10:59:39 +0100 Subject: [PATCH 10/24] fix(workspaces): keep a workspace whose imports cannot all be listed Deleting a workspace kept its imports' failure analyses by walking them, and a folder that could not be listed was skipped, its analysis then removed with the workspace. The delete is now refused, nothing removed, and the page says why. --- app/nullius/workspace.py | 10 +++++++--- app/tests/test_judge_adopt.py | 15 +++++++++++++++ app/web/workspaces.py | 7 ++++++- docs/judgement.md | 2 +- 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index dac2c1a77..6e772cf64 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -255,12 +255,16 @@ def _keep_judgements(ws: Workspace) -> None: the one job its roots hold that owns each (`store.adopt_owned`), then its files moved there whole, so none is lost with it - a job its roots no longer reach included - and the User judge's failure analyses of its converted imports beside them, under - ``imported/`` by their job folder's path. Refused while a root cannot be - read, since its jobs' records could not be copied.""" + ``imported/`` by their job folder's path. Refused while a root, or a folder + of its imports, cannot be read, since its jobs' records could not be kept.""" from nullius.judge import store from nullius.runs import failure_analysis old = [d for r in store.ROOTS.values() if os.path.isdir(d := os.path.join(ws.dir, r))] - made = [os.path.join(d, n) for d, _, names in os.walk(ws.imports_dir) for n in names if n.startswith(failure_analysis.FILE)] + try: + made = [os.path.join(d, n) for d, _, names in os.walk(ws.imports_dir, onerror=store._raise) + for n in names if n.startswith(failure_analysis.FILE)] if os.path.isdir(ws.imports_dir) else [] + except OSError as e: + raise ValueError(f"{ws.label} stays: {e.filename or ws.imports_dir} cannot be read, so its failure analyses cannot be kept. Try again.") if not old and not made: return _check_roots(ws) diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index f9cf2dff2..0e37f784c 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -244,6 +244,21 @@ def test_deleting_a_workspace_keeps_the_failure_analyses_of_its_imports(self): [kept] = os.listdir(os.path.join(self.home, "judgements-of-deleted-workspaces")) self.assertTrue(os.path.isfile(os.path.join(self.home, "judgements-of-deleted-workspaces", kept, "imported", "atif__x", fa.FILE))) + def test_a_workspace_whose_imports_cannot_all_be_listed_is_not_deleted(self): + from nullius.runs import failure_analysis as fa + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [], label="w") + j = _job_dir(ws.imports_dir, "atif__x") + fa.update(j, lambda a: a.set_label("t0", "agent", by="me")) + real = os.scandir + def unlisted(p="."): + if isinstance(p, str) and os.path.realpath(p) == os.path.realpath(j): + raise PermissionError(13, "Permission denied", p) + return real(p) + with patch("os.scandir", unlisted), self.assertRaisesRegex(ValueError, "cannot be read"): + workspace.delete(home_dir, ws.name) + self.assertTrue(os.path.isfile(os.path.join(j, fa.FILE))) + def test_a_save_or_a_copy_for_a_job_deleted_meanwhile_writes_nothing(self): gone = os.path.join(self.tmp, "deleted-job") store.save(self.a, "job-x", "t0", rec("2026-01-01T00:00:00Z")) diff --git a/app/web/workspaces.py b/app/web/workspaces.py index c2d609380..3dd78acd5 100644 --- a/app/web/workspaces.py +++ b/app/web/workspaces.py @@ -173,7 +173,12 @@ def workspace_delete(name): return redirect(url_for("workspaces_page")) if ws is not None and ws.name == name: shared.close_workspace() - if workspace.delete(shared.WS_HOME, name): + try: + removed = workspace.delete(shared.WS_HOME, name) + except ValueError as e: # a folder of it could not be read meanwhile: nothing removed + flash(str(e), "error") + return redirect(url_for("workspaces_page")) + if removed: flash(Markup(f'Removed workspace {escape(name)}; its job roots are untouched.'), "") else: flash(Markup(f'No workspace called {escape(name)}.'), "error") diff --git a/docs/judgement.md b/docs/judgement.md index 2aec382f2..523116de4 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -71,7 +71,7 @@ Follow the evidence: a recorded rate limit is a provider's failure whatever the | --- | --- | | 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, 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 or to one still starting; such a record is still shown, never copied, even by a save | -| 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 not yet moved is refused while one of its roots cannot be read | +| 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 not yet moved is refused while one of its roots cannot be read, and any while a folder of its imports cannot | | Version | `judgement.questions.v2`; v1 records marked *earlier* | | Cost | A batch button names its calls; each is checked against the token budget | | Noise floors | Each yes/no's run-to-run spread | From 22e8bcb69cd1e44a4f56dba8e63fb641221bdc70 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:23:38 +0100 Subject: [PATCH 11/24] fix(execution): keep a deleted launch's judgements while a copy's identity cannot be read A copy whose config.json or result.json is there but cannot be read made the parser derive another uid, so the copy was missed and the judgements removed. The copy scan now reads each job's identity strictly; a file it cannot read means the owner is unknown and the judgements stay. --- app/nullius/execution.py | 4 ++-- app/nullius/runs/uid.py | 29 +++++++++++++++++++++++++++++ app/tests/test_run_delete.py | 12 ++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 98752283f..ff917d282 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -120,7 +120,7 @@ from nullius import hosts, ondisk, paths, prices as price_list, progress, providers, redact, secrets, settings, workspace from nullius.judge import store as judgements -from nullius.runs import parse +from nullius.runs import parse, uid as job_uid from nullius.harbor import source as harbor_source from nullius.standard.backends import container from nullius.standard.runner import payload as standard_payload @@ -1881,7 +1881,7 @@ def _copies(home: str, paths: list, uids: set) -> set: roots += ws.job_roots or ws.roots roots += [j for parent in {os.path.dirname(p) for p in paths} for e in os.scandir(parent) if e.is_dir(follow_symlinks=False) and e.path not in paths and os.path.isdir(j := os.path.join(e.path, "jobs"))] - return {parse.parse_job(d, trials=False).uid for d in parse.find_job_dirs(roots) if outside(d)} & uids + return {job_uid.strict(d) for d in parse.find_job_dirs(roots) if outside(d)} & uids def deletion(names: List[str], home: str, root: Optional[str] = None, holding: Optional[Callable] = None, diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index f85e23fba..1424295da 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -84,6 +84,35 @@ def facts(job_dir: str, cfg: dict, res: dict): "start": start or ""} +def _strict_json(path: str) -> dict: + try: + with open(path, encoding="utf-8", errors="replace") as fh: + data = json.load(fh) + except FileNotFoundError: + return {} + except ValueError as e: + raise OSError(f"{path}: {e}") from e + if data is not None and not isinstance(data, dict): + raise OSError(f"{path}: not a JSON object") + return data or {} + + +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.""" + 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): + with os.scandir(job_dir) as entries: # the trials `_has_trial` looks for, each one strictly + for e in entries: + if e.is_dir(): + try: + os.stat(os.path.join(e.path, "result.json")) + except (FileNotFoundError, NotADirectoryError): + pass + return of(job_dir, cfg, res)[0] + + def of(job_dir: str, cfg: dict, res: dict) -> tuple: """``(uid, source)``: the job's identity and where it came from, ``declared``, ``derived`` or ``pending`` (uid "").""" diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index 6ac43e4c3..0ac15bf05 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -96,6 +96,18 @@ def test_a_copy_elsewhere_or_a_root_that_cannot_be_read_keeps_the_judgements(sel execution.delete(["r3"], self.home, self.root) self.assertEqual(store.job_dirs(self.data, [uid]), []) + def test_a_copy_whose_config_cannot_be_read_keeps_the_judgements(self): + cfg = os.path.join(self.jobs, "job-a", "config.json") + _write_json(cfg, dict(json.load(open(cfg)), standard={"uuid": "11111111-2222-3333-4444-555555555555"})) + uid = self.judged(self.jobs, "job-a") + twin = os.path.join(self.tmp, "twin"); shutil.copytree(os.path.join(self.jobs, "job-a"), os.path.join(twin, "job-a")) + workspace.create(self.home, [twin], label="d") + with open(os.path.join(twin, "job-a", "config.json"), "w") as fh: + fh.write('{"job_name": "job-a", "standard": {"uu') # cut short: whose it is, unknown + self.assertNotEqual(self.uid("job-a", twin), uid) # the display parse derives another + execution.delete(["r1"], self.home, self.root) + self.assertTrue(store.job_dirs(self.data, [uid])) + def test_another_job_of_the_same_name_does_not_keep_them(self): uid = self.judged(self.jobs, "job-a") other = os.path.join(self.tmp, "other"); _job_dir(other, "job-a") From 66d09a1f9e414437463f81bb2dce2a8fa2fa21c8 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:26:03 +0100 Subject: [PATCH 12/24] fix(judge): copy an older judgement on a save only when no job spelt alike or unreadable may own it Older stores spelt a job's folder with punctuation as underscores, so jobs x:y and x_y both read judgements/x_y. A save looked only at jobs of its own folder name and copied the record into x:y. It now looks at every job whose name shares a spelling, copies a record only into the file the one owner's job gives it, and counts a folder that cannot be searched as an unknown owner. --- app/nullius/judge/store.py | 33 ++++++++++++++-------- app/ui_tests/test_judgement_follows_job.py | 25 ++++++++++++++++ app/web/judge.py | 6 ++-- 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 4a323f755..0534cfe40 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -461,20 +461,31 @@ def owners(ws, into: Optional[str] = None, names=None) -> Optional[dict]: """Who each older file of the workspace `ws`'s store may belong to: {the file: {the file of the user's store it belongs in: the job's folder}}, over every job its roots hold, read afresh. A job with no identity yet claims the files it would own under ``("pending", its folder)``, so - they have no single owner until it has one. `names`: the job folders of these names only, all - that can claim a job's own files. None while one of its roots cannot be read: its jobs, and so - the owners, are unknown.""" + they have no single owner until it has one. `names`: the job folders whose names share a + spelling (`_names`) with one of these only, all that can claim a job's own files. None while one + of its roots, or a folder in one that may be a job, cannot be read: its jobs, and so the owners, + are unknown.""" from nullius.runs import parse into = into or home() roots = ws.job_roots or ws.roots + spelt = None if names is None else {s for n in names for s in _names(n)} + mine = lambda name: spelt is None or not spelt.isdisjoint(_names(name)) if not all(os.path.isdir(r) for r in roots): return None + try: + dirs = [d for d in parse.find_job_dirs(roots) if mine(os.path.basename(d))] + for r in roots: + with os.scandir(r) as entries: + for e in entries: + if e.is_dir() and mine(e.name): + os.scandir(e.path).close() + except OSError: + return None out: dict = {} - for d in parse.find_job_dirs(roots): - if names is None or os.path.basename(d) in names: - for job in parse.split_agents([parse.parse_job(d)]): - for src, dest in _places(ws.dir, job, into): - out.setdefault(src, {}).setdefault(dest or ("pending", d), d) + for d in dirs: + for job in parse.split_agents([parse.parse_job(d)]): + for src, dest in _places(ws.dir, job, into): + out.setdefault(src, {}).setdefault(dest or ("pending", d), d) return out @@ -504,14 +515,14 @@ def overlay(ws_dir: Optional[str], job, into: Optional[str] = None, only=None) - """What the workspace's store from before (`ws_dir`) holds for `job` (`_places`), as {the file of the user's store (`into`, `home()` by default) it belongs in: [its contents]}. Read only; a file that cannot be read is left out. Two jobs of one id in that workspace each get the same - records, as each showed them before. `only`: those older files alone (a save's, `single`). - {} once the workspace is `moved`.""" + records, as each showed them before. `only`: {older file: the file it belongs in} (a save's, + `single`), those alone and only where they belong in `job`'s. {} once the workspace is `moved`.""" into = into or home() if not ws_dir or not job.uid or moved(ws_dir, into): return {} out: dict = {} for src, dest in _places(ws_dir, job, into): - data = _old(src) if dest and (only is None or src in only) else None + data = _old(src) if dest and (only is None or only.get(src) == dest) else None if data: out.setdefault(dest, []).append(data) return out diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 334fa24ef..2b038a192 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -14,6 +14,7 @@ from nullius import workspace from nullius.judge import questions as Q +from nullius.runs import parse from .test_routes import web @@ -98,6 +99,30 @@ def test_a_record_kept_before_that_two_jobs_of_one_name_may_own_is_copied_by_nei self.assertEqual({k: sorted(r["answers"]) if isinstance(r, dict) else r for k, r in saved.items()}, {Q.VERSION: ["failure_cause"]}) + def test_a_record_a_job_spelt_alike_or_one_that_cannot_be_searched_may_own_is_not_copied_by_a_save(self): + kept = {Q.VERSION: {"questions": Q.VERSION, "answers": {"kept": {"choice": "x"}}, "asked_at": "2026-10-01T00:00:00Z"}} + for name, other, how in (("x:y", "x_y", "alike"), ("job-x", "job-x", "unsearchable")): + with self.subTest(how): + one, two = self.tmp / how / "one", self.tmp / how / "two" + copy_job(one / name, "2026-01-01T00:00:00Z"); copy_job(two / other, "2026-02-02T00:00:00Z") + ws = workspace.create(web.shared.WS_HOME, [str(one), str(two)], how) + web.shared.open_workspace(ws) + old = Path(ws.dir) / "judgements" / other; old.mkdir(parents=True) # x:y's older spelling is x_y's + (old / f"{TRIAL}.json").write_text(json.dumps(kept)) + j = next(j for j in workspace.load_jobs(ws, ws.roots) if j.dir == str(one / name)) + t = next(t for t in j.trials if t.trial_name == TRIAL) + twin, scandir, looks = str(two / other), web.judge.store.os.scandir, parse.looks_like_job_dir + hidden = how == "unsearchable" # as a folder without search permission looks + def scan(p): + if hidden and str(p) == twin: + raise PermissionError(13, "Permission denied", p) + return scandir(p) + with web.app.test_request_context(f"/trial/{name}/{TRIAL}"), patch.object(web.judge.store.os, "scandir", scan), \ + patch("nullius.runs.parse.looks_like_job_dir", lambda p: not (hidden and str(p) == twin) and looks(p)): + web.judge.judge_trial(j, t, None) + saved = json.loads((self.tmp / "data" / "judgements" / web.judge.store.key(j.uid) / f"{TRIAL}.json").read_text()) + self.assertNotIn("kept", saved[Q.VERSION]["answers"]) + def tree(root: Path) -> dict: """Every file under *root* and its bytes, and every folder.""" diff --git a/app/web/judge.py b/app/web/judge.py index 79e2cabbc..66de1ad78 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -85,14 +85,14 @@ def old_of(job, name=None) -> dict: def own_of(job, name=None) -> dict: """What a save copies of `old_of`: the records one job alone owns (`store.single`), its - owners read afresh; a record another job of its name may own stays unresolved, shown, never - copied. Once per request.""" + owners read afresh, and that job this one; a record another job of a name spelt alike may own + stays unresolved, shown, never copied. Once per request.""" ws = shared._record_workspace(name) memo = shared.request_memo("judgements_own") k = (ws.dir if ws else None, job.dir, job.job_id) if k not in memo: one = store.single(store.owners(ws, names={os.path.basename(job.dir)})) if ws and job.uid else {} - memo[k] = store.overlay(ws.dir, job, only=set(one)) if one else {} + memo[k] = store.overlay(ws.dir, job, only={src: dest for src, (dest, _) in one.items()}) if one else {} return memo[k] From c7ff190622129c191e15e9fd17cd73345a1373ca Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:29:11 +0100 Subject: [PATCH 13/24] fix(judge): save a batch's judgements with the workspace asked and a folded run's under each trial's shard A batch's threads have no request, so they read the open workspace's older records instead of the one the page named; the workspace is now read before the batch starts. A run folded from its shards carries its first shard's identity, so a Compare side of another shard was kept under the wrong job; each side now resolves the shard job its trial is in. --- app/ui_tests/test_judgement_follows_job.py | 26 +++++++++++++++++ app/web/judge.py | 34 +++++++++++++++++----- app/web/judge_tasks.py | 4 +-- 3 files changed, 54 insertions(+), 10 deletions(-) diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 2b038a192..56e4529b5 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -4,6 +4,7 @@ from __future__ import annotations import json +from dataclasses import replace import shutil import tempfile import unittest @@ -82,6 +83,31 @@ def test_two_jobs_of_one_name_in_two_roots_keep_their_own_judgements(self): seen = {k: bool(web.judge.judgement_of(j, trial(j))) for k, j in jobs.items()} self.assertEqual(seen, {"one": True, "two": False}) + def test_a_batch_copies_the_older_records_of_the_workspace_asked_and_a_folded_run_s_side_its_own_shard_s(self): + copy_job(self.tmp / "ra" / "job-x", "2026-01-01T00:00:00Z"); copy_job(self.tmp / "rb" / "job-x", "2026-02-02T00:00:00Z") + a = workspace.create(web.shared.WS_HOME, [str(self.tmp / "ra")], "A") + b = workspace.create(web.shared.WS_HOME, [str(self.tmp / "rb")], "B") + old = Path(b.dir) / "judgements" / "job-x"; old.mkdir(parents=True) + (old / f"{TRIAL}.json").write_text(json.dumps({"retired": {"questions": "retired", "answers": {"kept_in_b": {"choice": "x"}}}})) + web.shared.open_workspace(a) # a version no longer read: the trial is still to judge + jb = workspace.load_jobs(b, b.roots)[0] + with patch.object(web.shared, "_local_client", return_value=True), patch.object(web.shared, "_require_csrf"): + web.app.test_client().post(f"/judge/job/job-x?workspace={b.name}", data={"lane": "decision"}) + saved = json.loads((self.tmp / "data" / "judgements" / jb.uid / f"{TRIAL}.json").read_text()) + self.assertIn("retired", saved) # B's, though its threads have no request + with self.subTest("a folded run"): + copy_job(self.tmp / "ra" / "job-y", "2026-03-03T00:00:00Z") + jx, jy = sorted(workspace.load_jobs(a, a.roots), key=lambda j: j.job_id) + fold = replace(jx, trials=jx.trials + jy.trials) # as launches.fold makes it: the first shard's + t = next(t for t in jy.trials if t.trial_name == TRIAL) + view = SimpleNamespace(jobs=[fold, jb], selected=[SimpleNamespace(workspace=""), SimpleNamespace(workspace=b.name)], + tasks=[SimpleNamespace(task="hello", trials=[t, next(t for t in jb.trials if t.trial_name == TRIAL)])]) + with web.app.test_request_context("/compare"), patch.object(web.judge, "_states_for", return_value={}): + for _, job, trial, column in web.judge._sides_todo(view)[:1]: + web.judge.judge_side(job, trial, column, None) + self.assertTrue((self.tmp / "data" / "judgements" / jy.uid / f"{TRIAL}.json").is_file()) + self.assertFalse((self.tmp / "data" / "judgements" / jx.uid).exists()) + def test_a_record_kept_before_that_two_jobs_of_one_name_may_own_is_copied_by_neither_save(self): copy_job(self.tmp / "one" / "job-x", "2026-01-01T00:00:00Z") copy_job(self.tmp / "two" / "job-x", "2026-02-02T00:00:00Z") diff --git a/app/web/judge.py b/app/web/judge.py index 66de1ad78..f0e7959b6 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -303,20 +303,28 @@ def _trial_ids_and_states(trial, traj) -> dict: return _states_for(trial, traj, ids) -def judge_trial(job, trial, api_key: str, post=None, calibration=None) -> dict: +def judge_trial(job, trial, api_key: str, post=None, calibration=None, column=None) -> dict: """Ask every question the trial page shows, one call per state, and keep the merged record. Returns the record as stored. `calibration`: a - batch's, read once (`store.calibration`); the workspace's when none.""" + batch's, read once (`store.calibration`); the workspace's when none. + `column`: the name of the workspace that holds the job (`batch_workspace`), for a batch's threads.""" if not trial.has_trajectory: raise client.JudgeError(0, "this trial has no trajectory to judge") traj = trajectory.load(trial.trajectory_path) if traj.error: raise client.JudgeError(0, "the trajectory could not be read: " + traj.error) return batch.ask_and_store(store.home(), job_key(job), slot(trial), _trial_ids_and_states(trial, traj), api_key, post=post, - calibration=calibration, started=started_of(trial), old=own_of(job), job_dir=job.dir, + calibration=calibration, started=started_of(trial), old=own_of(job, column), job_dir=job.dir, strict=strict(trial)) +def batch_workspace(): + """The name of the workspace that holds the job on screen, read in the request: a batch's + threads have none, and would read the open one.""" + ws = shared._record_workspace() + return ws.name if ws else None + + def _guard(): shared._require_csrf() if not shared._local_client(): @@ -356,8 +364,8 @@ def judge_job_route(job_id): lane = request.form.get("lane") if request.form.get("lane") in client.LANES else "decision" judged = store.for_job(store.home(), job_key(job), started_by_name(job), lane=lane, old=old_of(job), strict=retried(job)) todo = [t for t in job.trials if t.has_trajectory and t.trial_name not in judged] - k, cal = key(lane), batch_calibration() - done, failed = run_batch(todo, lambda t: judge_trial(job, t, k, calibration=cal), lambda t: t.trial_name) + k, cal, col = key(lane), batch_calibration(), batch_workspace() + done, failed = run_batch(todo, lambda t: judge_trial(job, t, k, calibration=cal, column=col), lambda t: t.trial_name) from flask import flash flash(f"{'LLM judge' if lane == 'llm' else 'Decision model'}: judged {done} of {len(todo)} trial(s)." + (" Failed: " + "; ".join(failed[:3]) if failed else ""), "error" if failed else "") return redirect(url_for("job", job_id=job_id) + "#judgement") @@ -436,10 +444,20 @@ def side_ids(trial) -> list: return own + [q for q in Q.for_trial(trial.outcome == "resolved", trial.outcome) if q not in own] +def shard_of(job, trial, column=None): + """The job a trial's folder is in: a run folded from its shards (`launches.fold`) is its first + shard's job, and a trial of another shard keeps its judgement under that shard's identity.""" + inside = lambda j: os.path.commonpath([os.path.realpath(trial.dir), os.path.realpath(j.dir)]) == os.path.realpath(j.dir) + if inside(job): + return job + return next((j for j in shared._jobs_for_workspace(column) if inside(j)), job) + + def side_of(job, trial, column) -> dict | None: """One side's score as the compare page shows it, from the trial's own current record, the job opened from its column's workspace `column`: the expectation, the level it rounds to, the judge's confidence, the provenance. None until scored under the current vocabulary.""" + job = shard_of(job, trial, column) rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column), strict=strict(trial)) if not rec or not store.is_current(rec): @@ -521,7 +539,7 @@ def _sides_todo(view) -> list: for task, a, b in pairs_of(view): for job, t, d in ((view.jobs[0], a, da), (view.jobs[1], b, db)): if side_of(job, t, d) is None: - out.append((task, job, t, d)) + out.append((task, shard_of(job, t, d), t, d)) return out @@ -700,7 +718,7 @@ def task_summary(job) -> dict: return {"tasks": len(tasks), "judged": judged, "unjudged": len(tasks_todo(job)), "keyed": bool(key())} -def judge_task(job, trial, api_key: str, post=None, calibration=None) -> dict | None: +def judge_task(job, trial, api_key: str, post=None, calibration=None, column=None) -> dict | None: """Score one task's instruction over the `task` state alone, stored under the dataset's task slot and the instruction's digest - never under the trial.""" instruction = _task_instruction(trial) @@ -708,7 +726,7 @@ def judge_task(job, trial, api_key: str, post=None, calibration=None) -> dict | raise client.JudgeError(0, f"no instruction can be read for {trial.task_base}") states = batch.states_for(Q.group_ids("task"), lambda kind: judge_state.build(kind, None, instruction=instruction)) return batch.ask_and_store(store.home(), task_key(job), task_slot(trial), states, api_key, post=post, calibration=calibration, - lane=store.TASKS, old=own_of(job)) + lane=store.TASKS, old=own_of(job, column)) # -- the move of the judgements workspaces kept before into the user's store --------------- diff --git a/app/web/judge_tasks.py b/app/web/judge_tasks.py index 13e26e9c1..67cbcac24 100644 --- a/app/web/judge_tasks.py +++ b/app/web/judge_tasks.py @@ -19,8 +19,8 @@ def judge_tasks_route(job_id): abort(404) todo = judge.tasks_todo(job) judge._guard() - k, cal = judge.key(), judge.batch_calibration() - done, failed = judge.run_batch(todo, lambda t: judge.judge_task(job, t, k, calibration=cal), lambda t: t.task_base) + k, cal, col = judge.key(), judge.batch_calibration(), judge.batch_workspace() + done, failed = judge.run_batch(todo, lambda t: judge.judge_task(job, t, k, calibration=cal, column=col), lambda t: t.task_base) flash(f"Judged {done} of {len(todo)} task instruction(s)." + (" Failed: " + "; ".join(failed[:3]) if failed else ""), "error" if failed else "") return redirect(url_for("job", job_id=job_id) + "#task-quality") From 7b7602391d76e503937c17b91d1d50aac914b4c4 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:31:41 +0100 Subject: [PATCH 14/24] fix(judge): show a try's judgement only when its start matches, wherever it is read One try of a retried attempt took an unstamped record as its own when it had no start, and its fallback to the try's own name took any unstamped one. A save merged such a record's answers too. Both now need the same nonempty start. A stamped record set aside beside a newer unstamped one is kept under its start, so its try still finds it. Feasibility reads a control trial's verdict as the trial page does, so an earlier try's cause is not shown on the last. --- app/nullius/judge/store.py | 16 +++++++++------- app/tests/test_judge.py | 7 +++++++ app/ui_tests/test_judgement_follows_job.py | 10 +++++++++- app/web/judge.py | 11 ++++++----- 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 0534cfe40..c53cc0718 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -150,10 +150,12 @@ def _of(rec: Optional[dict], started: Optional[str], strict: bool = False) -> bo runs an attempt again under its trial's name, and what was asked of the try before is not this one's. A record from before tries were told apart, or a check that names no start, takes it as it is, unless - `strict` (an attempt with several tries): which try it judged is unknown.""" - if not started or not rec: + `strict` (an attempt with several tries): both starts are then needed, and the same.""" + if not rec: return True - return rec.get("trial_started_at") == started or (not strict and rec.get("trial_started_at") is None) + if strict: + return bool(started) and rec.get("trial_started_at") == started + return not started or rec.get("trial_started_at") in (started, None) def _try(version: str, started: str) -> str: @@ -323,9 +325,9 @@ def _merged(cur: dict, data: dict) -> dict: """`cur`, a file's records, with the records `data` of an older store added: each one not there yet. Where `cur` has another under its key, the one shown stays there and the other is kept beside: of two tries, the - later try's shown and the earlier under its own start (`_try`); of one - try, the newer by `asked_at` shown and the other under ``~``. Nothing is dropped, and a record copied in once is never + later try's shown; of one try, the newer by `asked_at`. The other is kept + under its start (`_try`), so a try still finds it, or with none under + ``~``. Nothing is dropped, and a record copied in once is never copied again (`ADOPTED`), even after a save has changed it.""" cur = dict(cur) adopted = set(cur.get(ADOPTED) or ()) @@ -346,7 +348,7 @@ def _merged(cur: dict, data: dict) -> dict: tries = bool(a and b and a != b) newer = str(b) > str(a) if tries else str(rec.get("asked_at") or "") > str(now.get("asked_at") or "") shown, other = (rec, now) if newer else (now, rec) - slot = _try(k, other["trial_started_at"]) if tries else f"{k}~{_digest(other)}" + slot = _try(k, other["trial_started_at"]) if other.get("trial_started_at") else f"{k}~{_digest(other)}" if slot in cur: slot = f"{slot}~{_digest(other)}" cur[k], cur[slot] = shown, other diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index e531aca1d..23ce06722 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -244,6 +244,13 @@ def test_a_record_is_the_try_it_judged_and_no_retry_under_its_name(self): # a record from before tries were told apart is taken as it is store.save(d, "job", "old", self.record(questions.VERSION, task_completed={"noul": 0.5})) self.assertIsNotNone(store.load(d, "job", "old", started=retry)) + # one of several tries is its own only by a start, and the same: an unstamped record is none's + self.assertIsNone(store.load(d, "job", "old", started=None, strict=True)) + got = store.save(d, "job", "old", self.record(questions.VERSION, failure_cause={"choice": "x"}), strict=True) + self.assertEqual(sorted(got["answers"]), ["failure_cause"]) + # a stamped record stays found by its start under an older, newer, unstamped one + old = {store._paths(d, "job", "t")[0]: [{questions.VERSION: dict(self.record(questions.VERSION, q={"choice": "y"}), asked_at="2099-01-01T00:00:00Z")}]} + self.assertEqual(sorted(store.load(d, "job", "t", started=retry, old=old, strict=True)["answers"]), ["failure_cause"]) class Batch(unittest.TestCase): diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 56e4529b5..11508a504 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -265,7 +265,12 @@ def test_a_try_judged_while_it_was_the_last_keeps_its_record_once_moved_aside(se patch.object(web.judge, "_trial_ids_and_states", return_value={}), \ patch.object(web.judge.batch, "ask_states", asked), web.app.test_request_context("/"): job = parse.parse_job(str(d)) - web.judge.judge_trial(job, next(t for t in job.trials if t.trial_name == TRIAL), "k", calibration={}) + t = next(t for t in job.trials if t.trial_name == TRIAL) + web.judge.judge_trial(job, t, "k", calibration={}) + web.judge.store.save(str(tmp / "data"), job.uid, TRIAL, {"questions": Q.VERSION, "answers": { + "control_failure_cause": {"choice": "x"}}}, started=web.judge.started_of(t)) + web.judge.store.save(str(tmp / "data"), job.uid, f"{TRIAL}.try-1", {"questions": Q.VERSION, "answers": { + "failure_cause": {"choice": "unstamped"}}}, lane="llm") # under the try's name, before starts were kept (d / "retried").mkdir() shutil.move(d / TRIAL, d / "retried" / f"{TRIAL}.try-1") # the runner tries the attempt again shutil.copytree(d / "retried" / f"{TRIAL}.try-1", d / TRIAL) @@ -277,6 +282,9 @@ def test_a_try_judged_while_it_was_the_last_keeps_its_record_once_moved_aside(se self.assertEqual(web.judge.judgement_of(job, first)["answers"]["failure_cause"]["choice"], "first") self.assertIsNone(web.judge.judgement_of(job, last)) self.assertEqual([web.judge.judgement_of(job, t, lane="llm") for t in (first, last)], [None, None]) # no start: whose is unknown + side = SimpleNamespace(present=True, failed=True, broke_tests=False, control="nop", job_id=job.job_id, trial_name=TRIAL) + report = SimpleNamespace(rows=[SimpleNamespace(verdict="unclear", task_base="hello", nop=side, oracle=SimpleNamespace(present=False))]) + self.assertEqual(web.judge.triage_summary(report, [job])["judged"], 0) # the first try's cause, not the last's if __name__ == "__main__": diff --git a/app/web/judge.py b/app/web/judge.py index f0e7959b6..c8627423c 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -114,8 +114,9 @@ def started_by_name(job) -> dict: def strict(trial) -> bool: - """Whether the trial is one try of an attempt with several: a record that names no start is then no try's.""" - return bool(trial.n_retries) or trial.key != trial.trial_name + """Whether the trial is one try of an attempt with several, read under its attempt's name: a + record is then its own only by its start. A try with no start keeps its own name (`slot`).""" + return (bool(trial.n_retries) or trial.key != trial.trial_name) and slot(trial) == trial.key def retried(job) -> set: @@ -133,7 +134,7 @@ def judgement_of(job, trial, lane: str = "decision") -> dict | None: """A try's record (`slot`); else one kept under the try's own name, as before.""" uid, start, old = job_key(job), started_of(trial), old_of(job) return (store.load(store.home(), uid, slot(trial), lane=lane, started=start, old=old, strict=strict(trial)) - or (store.load(store.home(), uid, trial.trial_name, lane=lane, started=start, old=old) + or (store.load(store.home(), uid, trial.trial_name, lane=lane, started=start, old=old, strict=strict(trial)) if slot(trial) != trial.trial_name else None)) @@ -625,8 +626,8 @@ def triage_summary(report, jobs) -> dict: sides = triage_sides(report) rows, judged, todo = {}, 0, [] for row, s in sides: - job, _ = _control_trial(s, jobs) - rec = store.load(store.home(), job_key(job), s.trial_name, old=old_of(job)) if job else None + job, trial = _control_trial(s, jobs) + rec = judgement_of(job, trial) if trial else None a = ((rec.get("answers") or {}).get("control_failure_cause")) if store.is_current(rec) else None if a: rows.setdefault(row.task_base, {})[s.control] = _choice_row("control_failure_cause", a) From 5d06c721223f7ef5e7723e9658125b9a60b5a0b7 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:33:46 +0100 Subject: [PATCH 15/24] fix(judge): keep a workspace's moved mark with its folder, and refuse a record that holds no judgement The mark was named by the workspace's folder, so a workspace renamed left it behind and a new one of that name, holding the same bytes for another job, was taken as moved. A rename now moves the mark, a workspace delete removes it, and forgetting a deleted job's older folders clears it instead of marking the files as they are then. A file whose version holds something other than a record now counts as one that cannot be read, so the move no longer marks it done. --- app/nullius/judge/store.py | 30 +++++++++++++++++++++--------- app/nullius/workspace.py | 4 ++++ app/tests/test_judge_adopt.py | 24 ++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 9 deletions(-) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index c53cc0718..a191225a9 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -423,16 +423,25 @@ def _mark(ws_dir: str, into: str, files, raw: Optional[dict] = None) -> None: ondisk.write_whole(_marker(ws_dir, into), _signature(ws_dir, files, raw)) +def unmark(ws_dir: str, to: Optional[str] = None) -> None: + """The workspace no longer `moved`, or, renamed to the folder `to`, still: a marker names a + workspace by its folder, and another made later under that name is not this one.""" + try: + if to: + os.replace(_marker(ws_dir, home()), _marker(to, home())) + else: + os.remove(_marker(ws_dir, home())) + except FileNotFoundError: + pass + + def forget(ws_dir: str, folders) -> None: - """A workspace's older folders of a deleted job removed, the workspace still `moved` if it was.""" - was = moved(ws_dir) + """A workspace's older folders of a deleted job removed, and the workspace read again until a + later `move`: a file changed meanwhile is never taken as one `move` read.""" for d in folders: shutil.rmtree(d, ignore_errors=True) - if was: - try: - _mark(ws_dir, home(), _old_files(ws_dir)) - except OSError: - pass + if folders: + unmark(ws_dir) def _places(ws_dir: str, job, into: str): @@ -504,13 +513,16 @@ def single(owned: Optional[dict]) -> dict: def _old(path: str, raw: Optional[bytes] = None) -> Optional[dict]: """An older file's records (from `raw`, its bytes, when given); None when it cannot be read or - holds no JSON object.""" + holds no JSON object, or a version in it holds no record.""" raw = _bytes(path) if raw is None else raw try: data = json.loads(raw) if raw is not None else False except ValueError: return None - return {} if data is None else data if isinstance(data, dict) else None + if data is None: + return {} + ok = isinstance(data, dict) and all(isinstance(r, dict) for k, r in data.items() if k != ADOPTED) + return data if ok else None def overlay(ws_dir: Optional[str], job, into: Optional[str] = None, only=None) -> dict: diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 6e772cf64..f3d76ab1d 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -205,6 +205,8 @@ def rename(home_dir: str, ws: Workspace, label: str) -> Workspace: name = _free(name, taken - {ws.name}) new_dir = os.path.join(home_dir, name) os.rename(ws.dir, new_dir) + from nullius.judge import store + store.unmark(ws.dir, to=new_dir) ws.name, ws.dir = name, new_dir ws.label = label save(ws) @@ -226,8 +228,10 @@ def delete(home_dir: str, name: str) -> bool: ws = load(home_dir, name) if ws is None: return False + from nullius.judge import store _keep_judgements(ws) shutil.rmtree(ws.dir, ignore_errors=True) + store.unmark(ws.dir) return True diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index 0e37f784c..d8f9ba6ae 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -198,6 +198,30 @@ def unlisted(p="."): with patch("os.scandir", unlisted): self.assertFalse(store.moved(ws.dir)) self.assertEqual(store.move(home_dir), ["w (a folder cannot be read)"]) + old = os.path.join(ws.dir, "judgements", "job-a", t0 + ".json"); kept = open(old, "rb").read() + + def made_again(): # its records alike, byte for byte + w = workspace.create(home_dir, [root], label="w") + os.makedirs(os.path.dirname(old)); open(old, "wb").write(kept) + return w + with self.subTest("renamed, then another made under its name"): + self.assertEqual(store.move(home_dir), []) + workspace.rename(home_dir, ws, "w2") + self.assertTrue(store.moved(ws.dir)) + again = made_again() + self.assertFalse(store.moved(again.dir)) + with self.subTest("deleted, then another made under its name"): + self.assertEqual(store.move(home_dir), []) + workspace.delete(home_dir, again.name) + self.assertFalse(store.moved(made_again().dir)) + with self.subTest("a job's older folder forgotten"): + self.assertEqual(store.move(home_dir), []) + store.forget(ws.dir, [os.path.join(ws.dir, "judgements-llm")]) + self.assertFalse(store.moved(ws.dir)) + with self.subTest("a version that holds no record"): + open(os.path.join(ws.dir, "judgements", "job-a", t0 + ".json"), "w").write(json.dumps({Q.VERSION: [1]})) + self.assertIn("w2 (1 file cannot be read)", store.move(home_dir)) + self.assertFalse(store.moved(ws.dir)) def test_a_record_two_jobs_of_one_id_share_is_moved_to_neither_and_still_shown_on_both(self): r1, r2 = (os.path.join(self.tmp, r) for r in ("r1", "r2")) From 1575d344434b27cf5e79081322a1e478672a22ed Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:35:25 +0100 Subject: [PATCH 16/24] fix(web): close a deleted workspace only once it is gone The delete closed the open workspace before its imports were walked, so a refused delete left it closed. It now closes after the delete succeeds, without saving the removed workspace again. --- app/ui_tests/test_judgement_follows_job.py | 15 +++++++++++++++ app/web/shared.py | 4 ++-- app/web/workspaces.py | 8 ++++---- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 11508a504..2c7b443d3 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -4,6 +4,7 @@ from __future__ import annotations import json +import os from dataclasses import replace import shutil import tempfile @@ -227,6 +228,20 @@ def test_a_workspace_with_a_root_that_cannot_be_read_is_not_deleted(self): self.assertTrue(Path(self.ws.dir, "judgements", "job-x", f"{TRIAL}.json").is_file()) self.assertIsNotNone(web.shared.STATE["workspace"]) # left open, as it was self.assertIn("cannot be read", self.get("/workspaces").get_data(as_text=True)) + copy_job(self.tmp / "runs" / "job-x") + with self.subTest("a folder of its imports cannot be listed once the delete has begun"): + os.makedirs(self.ws.imports_dir, exist_ok=True) + real = os.walk + def walk(top, *a, onerror=None, **k): + if os.path.realpath(top) == os.path.realpath(self.ws.imports_dir): + onerror(PermissionError(13, "Permission denied", top)); return iter(()) + return real(top, *a, onerror=onerror, **k) + with patch("os.walk", walk): + r = self.client.post(f"/workspaces/delete/{self.ws.name}", data={"csrf": self.token()}); self.addCleanup(r.close) + self.assertIsNotNone(web.shared.STATE["workspace"]) + r = self.client.post(f"/workspaces/delete/{self.ws.name}", data={"csrf": self.token()}); self.addCleanup(r.close) + self.assertIsNone(web.shared.STATE["workspace"]) + self.assertFalse(Path(self.ws.dir).exists()) # closed without being saved again class EachTryItsOwn(unittest.TestCase): diff --git a/app/web/shared.py b/app/web/shared.py index a47855ad2..f53c77c39 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -310,9 +310,9 @@ def open_workspace(ws, refresh=False): workspace.touch(ws) -def close_workspace(): +def close_workspace(save=True): ws = STATE["workspace"] - if ws is not None: + if ws is not None and save: ws.closed = True workspace.save(ws) STATE.update({"workspace": None, "roots": [], "label": "", "job_roots": []}) diff --git a/app/web/workspaces.py b/app/web/workspaces.py index 3dd78acd5..9187ef820 100644 --- a/app/web/workspaces.py +++ b/app/web/workspaces.py @@ -163,7 +163,7 @@ def workspace_rename(): @app.route("/workspaces/delete/", methods=["POST"]) def workspace_delete(name): """Remove a workspace - its cache and imports, never the job roots it - read. The open one closes first. Takes the form token.""" + read. The open one closes once it is removed. Takes the form token.""" shared._require_csrf() ws = shared.STATE["workspace"] try: @@ -171,13 +171,13 @@ def workspace_delete(name): except ValueError as e: flash(str(e), "error") return redirect(url_for("workspaces_page")) - if ws is not None and ws.name == name: - shared.close_workspace() try: removed = workspace.delete(shared.WS_HOME, name) - except ValueError as e: # a folder of it could not be read meanwhile: nothing removed + except ValueError as e: # a folder of it could not be read meanwhile: nothing removed, still open flash(str(e), "error") return redirect(url_for("workspaces_page")) + if removed and ws is not None and ws.name == name: + shared.close_workspace(save=False) # its folder is gone: nothing to save into if removed: flash(Markup(f'Removed workspace {escape(name)}; its job roots are untouched.'), "") else: From 7b83c384c25230954725c8b6a0074dadc33c0292 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:36:12 +0100 Subject: [PATCH 17/24] fix(judge): refuse a job with no identity yet before the judge is asked A pending job's judgement cannot be kept, but the trial action and a batch asked the judge first, paid for the call, and only then failed to save it. The refusal now comes first, and its reason is shown where the error of a judge call is. --- app/nullius/judge/batch.py | 5 ++++- app/tests/test_judge.py | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app/nullius/judge/batch.py b/app/nullius/judge/batch.py index bd4da21f6..f81c0e31d 100644 --- a/app/nullius/judge/batch.py +++ b/app/nullius/judge/batch.py @@ -108,7 +108,10 @@ def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, po the judge's own lane unless named (`store.TASKS`). `old`: the job's older records (`store.overlay`), the file's copied in by the save. `job_dir`: the job's folder, nothing saved once it is deleted (`store.Gone`). `strict`: an - attempt with several tries (`store.save`).""" + attempt with several tries (`store.save`). A job with no identity yet (pending) is refused + before the judge is asked: its record could not be kept.""" + if not job_id: + raise client.JudgeError(0, "this job has no identity until its result is written, so it is not judged yet") if calibration is None: calibration = store.calibration(base, [job_id]) rec = ask_states(states, key, post=post, calibration=calibration) diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index 23ce06722..7e374155a 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -287,6 +287,10 @@ def post(url, body, key): self.assertEqual(again["answers"].keys(), {"user_facing_answer"}) self.assertIsNone(batch.ask_and_store(str(self.tmp), "job", "empty", {"trial": ([], "", False)}, KEY, post=post)) self.assertIsNone(store.load(str(self.tmp), "job", "empty")) + n = len(calls) + with self.assertRaisesRegex(client.JudgeError, "no identity"): # a pending job: nothing asked, nothing paid + batch.ask_and_store(str(self.tmp), "", "t", states, KEY, post=post) + self.assertEqual(len(calls), n) def test_the_llm_judge_keeps_its_records_apart_from_decision_judge(self): import json as _json From a180dade007933e43a34b5511c72b414baf20f22 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 14:41:53 +0100 Subject: [PATCH 18/24] fix(judge): give a job with no identity and no dataset no task key Such a job's task judgements were kept under "job:", one key every such job shared. It now has none, so its task instructions are refused before the judge is asked, as its trials are. --- app/nullius/judge/store.py | 7 ++++--- app/tests/test_judge.py | 4 ++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index a191225a9..7f66d3c21 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -313,8 +313,9 @@ def task_dataset(job) -> str: """Where a dataset's task-instruction judgements are kept (lane `TASKS`), so an instruction is judged once for every run of that dataset: its recorded path, or its registry name, so two datasets of one folder name - keep apart; a job that names none, its own identity.""" - return job.dataset_path or job.dataset or "job:" + job.uid + keep apart; a job that names none, its own identity, and "" while it has none (pending), so it + has no key and is judged by no one's.""" + return job.dataset_path or job.dataset or ("job:" + job.uid if job.uid else "") def _digest(rec) -> str: @@ -455,7 +456,7 @@ def _places(ws_dir: str, job, into: str): names.update((n, key(name)) for n in _names(name)) places = [(lane, j, job.uid, names) for lane in ROOTS for j in _names(job.job_id)] # before, a dataset's task records were a job of their own, named `task:`, and a job naming none its id - places += [(TASKS, j, task_dataset(job) if job.uid or job.dataset_path or job.dataset else "", {}) + places += [(TASKS, j, task_dataset(job), {}) for j in _names("task:" + (job.dataset_path or job.dataset or "job:" + job.job_id))] for lane, old, new, rename in places: src = os.path.join(_root(ws_dir, "decision" if lane == TASKS else lane), old) diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index 7e374155a..ddc66d06b 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -10,6 +10,7 @@ import tempfile import unittest from pathlib import Path +from types import SimpleNamespace from nullius import redact, workspace from nullius.judge import batch, client, questions, state, store @@ -290,6 +291,9 @@ def post(url, body, key): n = len(calls) with self.assertRaisesRegex(client.JudgeError, "no identity"): # a pending job: nothing asked, nothing paid batch.ask_and_store(str(self.tmp), "", "t", states, KEY, post=post) + pending = SimpleNamespace(uid="", dataset="", dataset_path="") # nor its task lane: no key it would share + with self.assertRaisesRegex(client.JudgeError, "no identity"): + batch.ask_and_store(str(self.tmp), store.task_dataset(pending), "fix@abc", states, KEY, post=post, lane=store.TASKS) self.assertEqual(len(calls), n) def test_the_llm_judge_keeps_its_records_apart_from_decision_judge(self): From ed0c270f93cb09107037313d6d2793e213b45fc1 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 15:19:15 +0100 Subject: [PATCH 19/24] fix(workspaces): keep a workspace whose root is there but cannot be listed --- app/nullius/workspace.py | 11 ++++++++++- app/tests/test_judge_adopt.py | 8 ++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index f3d76ab1d..d803858ae 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -248,11 +248,20 @@ def _check_roots(ws: Workspace) -> None: from nullius.judge import store if store.moved(ws.dir) or not any(os.path.isdir(os.path.join(ws.dir, r)) for r in store.ROOTS.values()): return - unread = [r for r in ws.job_roots or ws.roots if not os.path.isdir(r)] + unread = [r for r in ws.job_roots or ws.roots if not _listable(r)] if unread: raise ValueError(f"{ws.label} stays: {unread[0]} cannot be read, so its judgements cannot be kept. Reconnect it or remove the root first.") +def _listable(folder: str) -> bool: + """Whether *folder* can be listed: a folder without permission exists but hides its jobs.""" + try: + with os.scandir(folder): + return True + except OSError: + return False + + def _keep_judgements(ws: Workspace) -> None: """The judgements a workspace kept before they were kept by job (``/judgements{,-llm}/``): copied into the user's store under diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index d8f9ba6ae..bb2df33b2 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -146,6 +146,14 @@ def test_the_move_waits_for_a_root_that_cannot_be_read(self): workspace.delete(home_dir, ws.name) self.assertTrue(os.path.isdir(ws.dir)) os.rename(root + ".away", root) + real = os.scandir + def unlisted(p="."): # a root without permission: there, but its jobs cannot be listed + if isinstance(p, str) and os.path.realpath(p) == os.path.realpath(root): + raise PermissionError(13, "Permission denied", p) + return real(p) + with patch("os.scandir", unlisted), self.assertRaisesRegex(ValueError, "cannot be read"): + workspace.delete(home_dir, ws.name) + 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), []) From 377c0691ad82da014c4d60c1906f8c02779a88fd Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 16:11:43 +0100 Subject: [PATCH 20/24] fix(execution): keep a deleted launch's judgements while a copy's folder cannot be searched --- app/nullius/execution.py | 2 +- app/nullius/judge/store.py | 7 +------ app/nullius/runs/parse.py | 14 ++++++++++++-- app/nullius/runs/uid.py | 27 ++++++++++++++++++++------- app/tests/test_run_delete.py | 16 ++++++++++++++++ 5 files changed, 50 insertions(+), 16 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index ff917d282..ad22adcab 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -1881,7 +1881,7 @@ def _copies(home: str, paths: list, uids: set) -> set: roots += ws.job_roots or ws.roots roots += [j for parent in {os.path.dirname(p) for p in paths} for e in os.scandir(parent) if e.is_dir(follow_symlinks=False) and e.path not in paths and os.path.isdir(j := os.path.join(e.path, "jobs"))] - return {job_uid.strict(d) for d in parse.find_job_dirs(roots) if outside(d)} & uids + return {job_uid.strict(d) for d in parse.find_job_dirs(roots, strict=lambda name: True) if outside(d)} & uids def deletion(names: List[str], home: str, root: Optional[str] = None, holding: Optional[Callable] = None, diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 7f66d3c21..2cb302461 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -485,12 +485,7 @@ def owners(ws, into: Optional[str] = None, names=None) -> Optional[dict]: if not all(os.path.isdir(r) for r in roots): return None try: - dirs = [d for d in parse.find_job_dirs(roots) if mine(os.path.basename(d))] - for r in roots: - with os.scandir(r) as entries: - for e in entries: - if e.is_dir() and mine(e.name): - os.scandir(e.path).close() + dirs = [d for d in parse.find_job_dirs(roots, strict=mine) if mine(os.path.basename(d))] except OSError: return None out: dict = {} diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index dcc53bf5c..139da6433 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -722,11 +722,14 @@ def looks_like_job_dir(path: str) -> bool: ) -def find_job_dirs(roots) -> list[str]: +def find_job_dirs(roots, strict=None) -> list[str]: """Return every job directory found under the given root paths. A root may itself be a job dir, or a parent containing job dirs (one level - down). Duplicates are dropped in first-seen order. + down). Duplicates are dropped in first-seen order. `strict`: for a reader + that must know every job (who owns a judgement), a test on a folder's name: + OSError when a root, or a folder in one whose name passes, cannot be + searched (`uid.searched`), so a hidden job is never taken for none. """ found: list[str] = [] seen: set[str] = set() @@ -740,10 +743,17 @@ def add(path: str) -> None: for root in roots: if not os.path.isdir(root): continue + if strict: + try: + os.stat(os.path.join(root, "result.json")) + except FileNotFoundError: + pass if looks_like_job_dir(root): add(root) for name in sorted(os.listdir(root)): p = os.path.join(root, name) + if strict and strict(name): + job_uid.searched(p) if os.path.isdir(p) and looks_like_job_dir(p): add(p) return found diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index 1424295da..af56f9e71 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -103,16 +103,29 @@ def strict(job_dir: str) -> str: never another uid. The trials are listed strictly too.""" 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): - with os.scandir(job_dir) as entries: # the trials `_has_trial` looks for, each one strictly - for e in entries: - if e.is_dir(): - try: - os.stat(os.path.join(e.path, "result.json")) - except (FileNotFoundError, NotADirectoryError): - pass + searched(job_dir) # the trials `_has_trial` looks for, each one strictly return of(job_dir, cfg, res)[0] +def searched(folder: str) -> None: + """OSError when the folder *folder* cannot be searched for a job's or its trials' + ``result.json``, or listed: whether it is a job, and whose, is then unknown. A file is no job.""" + try: + os.stat(os.path.join(folder, "result.json")) + except NotADirectoryError: + return + except FileNotFoundError: + if not os.path.isdir(folder): + return + with os.scandir(folder) as entries: + for e in entries: + if e.is_dir(): + try: + os.stat(os.path.join(e.path, "result.json")) + except (FileNotFoundError, NotADirectoryError): + pass + + def of(job_dir: str, cfg: dict, res: dict) -> tuple: """``(uid, source)``: the job's identity and where it came from, ``declared``, ``derived`` or ``pending`` (uid "").""" diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index 0ac15bf05..edf8a5fc7 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -108,6 +108,22 @@ def test_a_copy_whose_config_cannot_be_read_keeps_the_judgements(self): execution.delete(["r1"], self.home, self.root) self.assertTrue(store.job_dirs(self.data, [uid])) + def test_a_copy_whose_folder_cannot_be_searched_keeps_the_judgements(self): + uid = self.judged(self.jobs, "job-a") + twin = os.path.join(self.tmp, "twin"); shutil.copytree(os.path.join(self.jobs, "job-a"), os.path.join(twin, "job-a")) + workspace.create(self.home, [twin], label="d") + inside = os.path.join(twin, "job-a", "") + + def denied(real): # its root listed, the folder without search permission + def call(path, *a, **k): + if isinstance(path, (str, os.PathLike)) and os.fspath(path).startswith(inside): + raise PermissionError(13, "Permission denied", path) + return real(path, *a, **k) + return call + with patch.object(os, "stat", denied(os.stat)), patch("builtins.open", denied(open)): + execution.delete(["r1"], self.home, self.root) + self.assertTrue(store.job_dirs(self.data, [uid])) + def test_another_job_of_the_same_name_does_not_keep_them(self): uid = self.judged(self.jobs, "job-a") other = os.path.join(self.tmp, "other"); _job_dir(other, "job-a") From 9fef5032a18c17ad2617da64faf3fe69eacb245d Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 16:12:56 +0100 Subject: [PATCH 21/24] fix(judge): copy no older judgement to a job whose identity cannot be read --- app/nullius/judge/store.py | 25 +++++++++++++++++-------- app/tests/test_judge_adopt.py | 16 ++++++++++++++++ docs/judgement.md | 2 +- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index 2cb302461..eac2e66d3 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -472,12 +472,14 @@ def _places(ws_dir: str, job, into: str): def owners(ws, into: Optional[str] = None, names=None) -> Optional[dict]: """Who each older file of the workspace `ws`'s store may belong to: {the file: {the file of the user's store it belongs in: the job's folder}}, over every job its roots hold, read afresh. A - job with no identity yet claims the files it would own under ``("pending", its folder)``, so - they have no single owner until it has one. `names`: the job folders whose names share a + job with no identity yet claims the files it would own under ``("pending", its folder)``, and one + whose identity cannot be read (`uid.strict`) under ``("unread", its folder)``, so they have no + single owner until it has one. `names`: the job folders whose names share a spelling (`_names`) with one of these only, all that can claim a job's own files. None while one of its roots, or a folder in one that may be a job, cannot be read: its jobs, and so the owners, are unknown.""" - from nullius.runs import parse + from dataclasses import replace + from nullius.runs import parse, uid as job_uid into = into or home() roots = ws.job_roots or ws.roots spelt = None if names is None else {s for n in names for s in _names(n)} @@ -490,9 +492,13 @@ def owners(ws, into: Optional[str] = None, names=None) -> Optional[dict]: return None out: dict = {} for d in dirs: + try: + uid = job_uid.strict(d) # never the display parse's: a job read in part is no owner + except OSError: + uid = None for job in parse.split_agents([parse.parse_job(d)]): - for src, dest in _places(ws.dir, job, into): - out.setdefault(src, {}).setdefault(dest or ("pending", d), d) + for src, dest in _places(ws.dir, replace(job, uid=uid or ""), into): + out.setdefault(src, {}).setdefault(dest or ("pending" if uid == "" else "unread", d), d) return out @@ -597,7 +603,7 @@ def move(home_dir: str, into: Optional[str] = None) -> list: are, and mark each workspace whose every file went (`moved`), so reads stop consulting it. 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, or one still starting): + 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.""" into = into or home() left = [] @@ -613,7 +619,7 @@ def move(home_dir: str, into: Optional[str] = None) -> list: continue raw = {f: _bytes(os.path.join(ws.dir, f)) for f in files} one = single(owned) - unread, shared, pending, by_dest = 0, 0, 0, {} + unread, shared, pending, hidden, by_dest = 0, 0, 0, 0, {} for src, dests in owned.items(): rel = os.path.relpath(src, ws.dir) data = _old(src, raw.get(rel)) @@ -622,6 +628,8 @@ def move(home_dir: str, into: Optional[str] = None) -> list: elif src not in one: # unresolved: whose it is cannot be told if all(isinstance(d, str) for d in dests): shared += 1 + elif any(d[0] == "unread" for d in dests if not isinstance(d, str)): + hidden += 1 else: pending += 1 elif data: @@ -633,7 +641,8 @@ def move(home_dir: str, into: Optional[str] = None) -> list: why = [_plural(n, *w) for n, w in ((unread, ("file cannot be read", "files cannot be read")), (orphans, ("record of no job found", "records of no job found")), (shared, ("record two jobs share", "records several jobs share")), - (pending, ("record of a job still starting", "records of jobs still starting"))) if n] + (pending, ("record of a job still starting", "records of jobs still starting")), + (hidden, ("record of a job that cannot be read", "records of jobs that cannot be read"))) if n] if why: left.append(f"{ws.label} ({', '.join(why)})") else: diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index bb2df33b2..9c45b4dab 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -14,6 +14,7 @@ from nullius import workspace from nullius.judge import questions as Q, store +from nullius.runs import parse from tests.test_workspace import _job_dir @@ -266,6 +267,21 @@ def test_a_job_of_the_same_name_still_starting_may_own_them_too(self): self.assertFalse(os.path.isdir(os.path.join(self.home, "judgements", j.uid))) self.assertEqual(store.single(store.owners(ws, names={"job-x"})), {}) + def test_a_finished_job_whose_config_cannot_be_read_owns_none_of_them(self): + r1 = os.path.join(self.tmp, "r1") + d = _job_dir(r1, "job-x") + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [r1], label="w") + t0 = workspace.load_jobs(ws, ws.roots)[0].trials[0].trial_name + store.save(ws.dir, "job-x", t0, rec("2026-01-01T00:00:00Z")) + with open(os.path.join(d, "config.json"), "w") as f: + f.write('{"job_name": "job-x", "agents"') # the display parse still derives one + self.assertTrue(parse.parse_job(d).uid) + self.assertEqual(store.move(home_dir), ["w (1 record of a job that cannot be read)"]) + self.assertFalse(os.path.isdir(os.path.join(self.home, "judgements")) and + [n for n in os.listdir(os.path.join(self.home, "judgements")) if not n.startswith(".")]) + self.assertEqual(store.adopt_owned(ws), set()) + def test_deleting_a_workspace_keeps_the_failure_analyses_of_its_imports(self): from nullius.runs import failure_analysis as fa home_dir = os.path.join(self.tmp, "ws") diff --git a/docs/judgement.md b/docs/judgement.md index 523116de4..21d7b4b69 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, 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 or to one still starting; 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 | | 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 not yet moved is refused while one of its roots cannot be read, and any while a folder of its imports cannot | | Version | `judgement.questions.v2`; v1 records marked *earlier* | | Cost | A batch button names its calls; each is checked against the token budget | From 560d4b99b6817bd9da363662d0ee8ca86f5d7e09 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 16:16:27 +0100 Subject: [PATCH 22/24] fix(judge): match every retried try by its start, and show its newest revision --- app/nullius/judge/batch.py | 6 ++- app/nullius/judge/store.py | 43 ++++++++++++++++------ app/tests/test_judge.py | 13 +++++++ app/ui_tests/test_judgement_follows_job.py | 30 ++++++++++++--- app/web/judge.py | 9 +++-- docs/judgement.md | 2 +- 6 files changed, 79 insertions(+), 24 deletions(-) diff --git a/app/nullius/judge/batch.py b/app/nullius/judge/batch.py index f81c0e31d..5a5564691 100644 --- a/app/nullius/judge/batch.py +++ b/app/nullius/judge/batch.py @@ -108,10 +108,12 @@ def ask_and_store(base: str, job_id: str, trial_name: str, states: dict, key, po the judge's own lane unless named (`store.TASKS`). `old`: the job's older records (`store.overlay`), the file's copied in by the save. `job_dir`: the job's folder, nothing saved once it is deleted (`store.Gone`). `strict`: an - attempt with several tries (`store.save`). A job with no identity yet (pending) is refused - before the judge is asked: its record could not be kept.""" + attempt with several tries (`store.save`). A job with no identity yet (pending), or such a try + with no start, is refused before the judge is asked: its record could not be kept, or shown.""" if not job_id: raise client.JudgeError(0, "this job has no identity until its result is written, so it is not judged yet") + if strict and not started: + raise client.JudgeError(0, "this try has no start, so its judgement could not be told from another try's") if calibration is None: calibration = store.calibration(base, [job_id]) rec = ask_states(states, key, post=post, calibration=calibration) diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index eac2e66d3..13bb08714 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -163,14 +163,35 @@ def _try(version: str, started: str) -> str: return f"{version}@{started}" +def _newest(data: dict, version: str, started: Optional[str], strict: bool = False) -> Optional[str]: + """The key of the newest record (`asked_at`) of the try `started` under `version`: its own, + or one kept beside it (`_try`, and a revision of it beside that, ``~``).""" + at = started and _try(version, started) + keys = [k for k in data if k == version or at and (k == at or k.startswith(at + "~"))] + keys = [k for k in sorted(keys, key=lambda k: k != version) if isinstance(data[k], dict) and data[k] + and _of(data[k], started, strict)] + return max(keys, key=lambda k: str(data[k].get("asked_at") or ""), default=None) + + def _pick(data: dict, version: Optional[str], started: Optional[str] = None, strict: bool = False) -> Optional[dict]: for v in _versions(version): - for rec in (data.get(v), started and data.get(_try(v, started))): - if rec and _of(rec, started, strict): - return rec + k = _newest(data, v, started, strict) + if k: + return data[k] return None +def _aside(data: dict, key: str) -> None: + """The record under `key` kept beside under its start (`_try`), or with none under + ``~``, in a slot no other record holds.""" + rec = data.pop(key) + at = rec.get("trial_started_at") + slot = _try(key, at) if at else f"{key}~{_digest(rec)}" + if data.get(slot, rec) != rec: + slot = f"{slot}~{_digest(rec)}" + data[slot] = rec + + def load(base: str, job_id: str, trial_name: str, version: Optional[str] = None, lane: str = "decision", started: Optional[str] = None, old: Optional[dict] = None, strict: bool = False) -> Optional[dict]: """The record under `version`; with none named, the current version or @@ -213,11 +234,10 @@ def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "dec _still(path, job_dir) data = _with(_read(found, strict=True), _olds(old, found)) version = record.get("questions", Q.VERSION) - earlier = data.get(version) or {} - if not _of(earlier, started, strict): # another try's: kept beside, and none of its answers are this one's - at = earlier.get("trial_started_at") - data[_try(version, at) if at else f"{version}~{_digest(earlier)}"] = earlier # unstamped: whose is unknown - earlier = data.pop(_try(version, started), None) or {} + mine = _newest(data, version, started, strict) # this try's newest record, wherever it is kept + if data.get(version) and mine != version: # another try's, or an older revision: kept beside, and none + _aside(data, version) # of its answers are this one's + earlier = data.pop(mine) if mine and mine != version else data.get(version) or {} merged = dict(record, **({"trial_started_at": started} if started else {})) merged["answers"] = {**(earlier.get("answers") or {}), **(record.get("answers") or {})} if "hygiene" in earlier or "hygiene" in record: @@ -349,10 +369,9 @@ def _merged(cur: dict, data: dict) -> dict: tries = bool(a and b and a != b) newer = str(b) > str(a) if tries else str(rec.get("asked_at") or "") > str(now.get("asked_at") or "") shown, other = (rec, now) if newer else (now, rec) - slot = _try(k, other["trial_started_at"]) if other.get("trial_started_at") else f"{k}~{_digest(other)}" - if slot in cur: - slot = f"{slot}~{_digest(other)}" - cur[k], cur[slot] = shown, other + cur[k] = other + _aside(cur, k) + cur[k] = shown have |= {_digest(r) for r in cur.values() if isinstance(r, dict)} if adopted: cur[ADOPTED] = sorted(adopted) diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index ddc66d06b..5e7b1a50e 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -252,6 +252,19 @@ def test_a_record_is_the_try_it_judged_and_no_retry_under_its_name(self): # a stamped record stays found by its start under an older, newer, unstamped one old = {store._paths(d, "job", "t")[0]: [{questions.VERSION: dict(self.record(questions.VERSION, q={"choice": "y"}), asked_at="2099-01-01T00:00:00Z")}]} self.assertEqual(sorted(store.load(d, "job", "t", started=retry, old=old, strict=True)["answers"]), ["failure_cause"]) + # of two revisions of the try before, the newer is shown, kept beside the older; saves keep every one + path = store._paths(d, "job", "t")[0] + newer = dict(self.record(questions.VERSION, q={"choice": "newer"}), trial_started_at=first, asked_at="2099-01-01T00:00:00Z") + store._merge_into(path, [{questions.VERSION: newer}]) + self.assertEqual(store.load(d, "job", "t", started=first, strict=True)["answers"], {"q": {"choice": "newer"}}) + third = "2026-11-17T12:00:00+00:00" + for i, at in enumerate((third, first, third)): # each set aside where another is kept + store.save(d, "job", "t", dict(self.record(questions.VERSION, x={"choice": at}), asked_at=f"2100-01-0{i + 1}"), + started=at, strict=True) + self.assertEqual(store.load(d, "job", "t", started=first, strict=True)["answers"]["q"], {"choice": "newer"}) + with open(path) as fh: + kept = [r for r in json.load(fh).values() if isinstance(r, dict) and r.get("trial_started_at") == first] + self.assertEqual(len(kept), 2) class Batch(unittest.TestCase): diff --git a/app/ui_tests/test_judgement_follows_job.py b/app/ui_tests/test_judgement_follows_job.py index 2c7b443d3..66d47f4b2 100644 --- a/app/ui_tests/test_judgement_follows_job.py +++ b/app/ui_tests/test_judgement_follows_job.py @@ -246,7 +246,19 @@ def walk(top, *a, onerror=None, **k): class EachTryItsOwn(unittest.TestCase): """A retried trial's earlier try is judged, and shown, apart from its last - try, even when the try recorded no start.""" + try; a try that recorded no start is not judged, and shows no record.""" + def test_an_older_pair_record_names_no_start_so_no_retried_try_shows_it(self): + tmp = Path(tempfile.mkdtemp(prefix="nullius-judge-pair-")); self.addCleanup(shutil.rmtree, tmp, True) + side = lambda name, retries: SimpleNamespace(trial_name=name, key=name, n_retries=retries, started_at=None, has_trajectory=True) + job = SimpleNamespace(uid="u", job_id="j", dir=str(tmp)) + view = lambda a: SimpleNamespace(selected=[SimpleNamespace(workspace=None)], jobs=[job, job], + tasks=[SimpleNamespace(task="k", trials=[a, side("b", 0)])]) + with patch.object(web.judge.store, "home", return_value=str(tmp / "data")), \ + patch.object(web.judge, "old_of", return_value={}), patch.object(web.judge, "job_key", return_value="u"): + web.judge.store.save(str(tmp / "data"), "u", web.judge.store.pair_key("a", "b"), { + "questions": Q.EARLIER[0], "answers": {web.judge.LEGACY_QUESTION: {"choice": "A"}}}) + self.assertEqual([bool(web.judge.pair_records(view(side("a", n)))) for n in (0, 1)], [True, False]) + def test_two_tries_each_show_and_keep_their_own_record(self): from nullius.runs import parse tmp = Path(tempfile.mkdtemp(prefix="nullius-judge-tries-")); self.addCleanup(shutil.rmtree, tmp, True) @@ -265,10 +277,18 @@ def test_two_tries_each_show_and_keep_their_own_record(self): patch.object(web.judge, "_trial_ids_and_states", return_value={}), \ web.app.test_request_context("/"): for trial, choice in ((last, "last"), (first, "first"), (last, "last")): - with patch.object(web.judge.batch, "ask_states", asked(choice)): - web.judge.judge_trial(job, trial, "k", calibration={}) - shown = [web.judge.judgement_of(job, t)["answers"]["failure_cause"]["choice"] for t in (first, last)] - self.assertEqual(shown, ["first", "last"]) + with patch.object(web.judge.batch, "ask_states", side_effect=asked(choice)) as ask: + if trial is first: + with self.assertRaises(web.judge.client.JudgeError): + web.judge.judge_trial(job, trial, "k", calibration={}) + ask.assert_not_called() + else: + web.judge.judge_trial(job, trial, "k", calibration={}) + web.judge.store.save(str(tmp / "data"), job.uid, first.trial_name, {"questions": Q.VERSION, "answers": { + "failure_cause": {"choice": "first"}}}) # under its own name, as before + shown = [(web.judge.judgement_of(job, t) or {}).get("answers", {}).get("failure_cause", {}).get("choice") + for t in (first, last)] + self.assertEqual(shown, [None, "last"]) def test_a_try_judged_while_it_was_the_last_keeps_its_record_once_moved_aside(self): from nullius.runs import parse diff --git a/app/web/judge.py b/app/web/judge.py index c8627423c..5db3b7f19 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -114,9 +114,9 @@ def started_by_name(job) -> dict: def strict(trial) -> bool: - """Whether the trial is one try of an attempt with several, read under its attempt's name: a - record is then its own only by its start. A try with no start keeps its own name (`slot`).""" - return (bool(trial.n_retries) or trial.key != trial.trial_name) and slot(trial) == trial.key + """Whether the trial is one try of an attempt with several: a record is then its own only by + its start, wherever it is read, so a try with no start shows none.""" + return bool(trial.n_retries) or trial.key != trial.trial_name def retried(job) -> set: @@ -479,7 +479,8 @@ def pair_records(view) -> dict: return {} out, uid, old = {}, job_key(view.jobs[0]), old_of(view.jobs[0], view.selected[0].workspace) for task, a, b in pairs_of(view): - rec = store.load(store.home(), uid, store.pair_key(a.trial_name, b.trial_name), old=old) + rec = store.load(store.home(), uid, store.pair_key(a.trial_name, b.trial_name), old=old, + strict=strict(a) or strict(b)) # a pair record names no start: none of a retried try's if rec and (rec.get("answers") or {}).get(LEGACY_QUESTION): out[task] = rec return out diff --git a/docs/judgement.md b/docs/judgement.md index 21d7b4b69..f97507297 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -69,7 +69,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, in every workspace that holds the job; a renamed Harbor or imported job folder is a new job | +| 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 | | 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 not yet moved is refused while one of its roots cannot be read, and any while a folder of its imports cannot | | Version | `judgement.questions.v2`; v1 records marked *earlier* | From 976acab230cfdda51d5d88f02334d60eb561dddb Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Wed, 25 Nov 2026 16:17:40 +0100 Subject: [PATCH 23/24] fix(workspaces): refuse to delete a workspace holding judgements while any of its roots cannot be read --- app/nullius/workspace.py | 36 +++++++++++++++++++++-------------- app/tests/test_judge_adopt.py | 19 +++++++++++++++++- docs/judgement.md | 2 +- 3 files changed, 41 insertions(+), 16 deletions(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index d803858ae..aec94bf54 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -224,7 +224,7 @@ def delete(home_dir: str, name: str) -> bool: imports. The job roots it pointed at are not touched, nor the judgements of their jobs (`_keep_judgements`). True when something was removed; ValueError, nothing removed, while it holds judgements kept - before and one of its roots cannot be read.""" + before or failure analyses of its imports and one of its roots cannot be read.""" ws = load(home_dir, name) if ws is None: return False @@ -239,16 +239,17 @@ def check_deletable(home_dir: str, name: str) -> None: """Raise as `delete` would refuse the workspace *name*, removing nothing.""" ws = load(home_dir, name) if ws is not None: - _check_roots(ws) + _check_roots(ws, _analyses(ws)) -def _check_roots(ws: Workspace) -> None: - """ValueError while *ws* holds judgements kept before by job id, not yet copied into the - user's store, and one of its roots cannot be read: its jobs, and so their records, are unknown.""" +def _check_roots(ws: Workspace, made) -> None: + """ValueError while *ws* holds records its delete could lose - judgements kept before by job + id, or the failure analyses *made* of its imports - and one of its roots, as registered or as + converted, cannot be read: its jobs, and so their records, are unknown.""" from nullius.judge import store - if store.moved(ws.dir) or not any(os.path.isdir(os.path.join(ws.dir, r)) for r in store.ROOTS.values()): + if not made and not any(os.path.isdir(os.path.join(ws.dir, r)) for r in store.ROOTS.values()): return - unread = [r for r in ws.job_roots or ws.roots if not _listable(r)] + unread = [r for r in dict.fromkeys([*ws.roots, *ws.job_roots]) if not _listable(r)] if unread: raise ValueError(f"{ws.label} stays: {unread[0]} cannot be read, so its judgements cannot be kept. Reconnect it or remove the root first.") @@ -262,6 +263,18 @@ def _listable(folder: str) -> bool: return False +def _analyses(ws: Workspace) -> list: + """The User judge's failure analyses of the workspace's converted imports; ValueError when a + folder of its imports cannot be listed.""" + from nullius.judge import store + from nullius.runs import failure_analysis + try: + return [os.path.join(d, n) for d, _, names in os.walk(ws.imports_dir, onerror=store._raise) + for n in names if n.startswith(failure_analysis.FILE)] if os.path.isdir(ws.imports_dir) else [] + except OSError as e: + raise ValueError(f"{ws.label} stays: {e.filename or ws.imports_dir} cannot be read, so its failure analyses cannot be kept. Try again.") + + def _keep_judgements(ws: Workspace) -> None: """The judgements a workspace kept before they were kept by job (``/judgements{,-llm}/``): copied into the user's store under @@ -271,16 +284,11 @@ def _keep_judgements(ws: Workspace) -> None: ``imported/`` by their job folder's path. Refused while a root, or a folder of its imports, cannot be read, since its jobs' records could not be kept.""" from nullius.judge import store - from nullius.runs import failure_analysis old = [d for r in store.ROOTS.values() if os.path.isdir(d := os.path.join(ws.dir, r))] - try: - made = [os.path.join(d, n) for d, _, names in os.walk(ws.imports_dir, onerror=store._raise) - for n in names if n.startswith(failure_analysis.FILE)] if os.path.isdir(ws.imports_dir) else [] - except OSError as e: - raise ValueError(f"{ws.label} stays: {e.filename or ws.imports_dir} cannot be read, so its failure analyses cannot be kept. Try again.") + made = _analyses(ws) if not old and not made: return - _check_roots(ws) + _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}") diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index 9c45b4dab..1207470fd 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -285,13 +285,30 @@ def test_a_finished_job_whose_config_cannot_be_read_owns_none_of_them(self): def test_deleting_a_workspace_keeps_the_failure_analyses_of_its_imports(self): from nullius.runs import failure_analysis as fa home_dir = os.path.join(self.tmp, "ws") - ws = workspace.create(home_dir, [], label="w") + root = os.path.join(self.tmp, "atif") # not there: unmounted + ws = workspace.create(home_dir, [root], label="w") j = _job_dir(ws.imports_dir, "atif__x") fa.update(j, lambda a: a.set_label("t0", "agent", by="me")) + for check in (workspace.check_deletable, workspace.delete): + with self.assertRaisesRegex(ValueError, "cannot be read"): + check(home_dir, ws.name) + os.makedirs(root) workspace.delete(home_dir, ws.name) [kept] = os.listdir(os.path.join(self.home, "judgements-of-deleted-workspaces")) self.assertTrue(os.path.isfile(os.path.join(self.home, "judgements-of-deleted-workspaces", kept, "imported", "atif__x", fa.FILE))) + def test_a_moved_workspace_is_not_deleted_while_a_root_cannot_be_read(self): + root = os.path.join(self.tmp, "r1") + _job_dir(root, "job-x") + home_dir = os.path.join(self.tmp, "ws") + ws = workspace.create(home_dir, [root], label="w") + store.save(ws.dir, "job-x", workspace.load_jobs(ws, ws.roots)[0].trials[0].trial_name, rec("2026-01-01T00:00:00Z")) + self.assertEqual(store.move(home_dir), []) + os.rename(root, root + "-away") + with self.assertRaisesRegex(ValueError, "cannot be read"): + workspace.delete(home_dir, ws.name) + self.assertTrue(os.path.isdir(ws.dir)) + def test_a_workspace_whose_imports_cannot_all_be_listed_is_not_deleted(self): from nullius.runs import failure_analysis as fa home_dir = os.path.join(self.tmp, "ws") diff --git a/docs/judgement.md b/docs/judgement.md index f97507297..fb3a9cdd4 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -71,7 +71,7 @@ Follow the evidence: a recorded rate limit is a provider's failure whatever the | --- | --- | | 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 | -| 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 not yet moved is refused while one of its roots cannot be read, and any while a folder of its imports cannot | +| 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 | | Noise floors | Each yes/no's run-to-run spread | From 00e7f342b3322229da4d058e3fd4594e3d52840e Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 26 Nov 2026 11:41:13 +0100 Subject: [PATCH 24/24] fix(judge): keep a folded run's side judgement under its own shard's job in the user's store --- app/ui_tests/test_judge_other_workspace.py | 16 +++++++++------- app/web/judge.py | 1 + 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/app/ui_tests/test_judge_other_workspace.py b/app/ui_tests/test_judge_other_workspace.py index 82b77c5f0..905a1ede4 100644 --- a/app/ui_tests/test_judge_other_workspace.py +++ b/app/ui_tests/test_judge_other_workspace.py @@ -92,13 +92,15 @@ def test_a_folded_run_s_side_reads_and_keeps_its_own_shard_s_record(self): fold = replace(jx, trials=jx.trials + jy.trials) # as launches.fold makes it: the first shard's t = replace(next(t for t in jy.trials if t.trial_name == TRIAL), has_trajectory=True) rec = {"questions": Q.VERSION, "answers": {web.judge.SIDE_QUESTION: {"score": 1}}, "judge": {"model": "m"}} - store.save(self.b.dir, "job-y", TRIAL, dict(rec), started=web.judge.started_of(t)) - self.assertIsNotNone(web.judge.side_of(fold, t, self.b.dir), "the trial page's record is not read") - with patch.object(web.judge.trajectory, "load", return_value=unittest.mock.Mock(error=None)), \ - patch.object(web.judge, "_states_for", return_value={}), patch.object(web.judge.batch, "ask_states", return_value=dict(rec)), \ - patch.object(web.judge, "side_ids", return_value=["more"]): # one question still to ask - web.judge.judge_side(fold, t, self.b.dir, None) - self.assertIsNone(store.load(self.b.dir, "job-x", TRIAL), "saved under the first shard's job") + store.save(self.b.dir, "job-y", TRIAL, dict(rec), started=web.judge.started_of(t)) # kept by B before + with web.app.test_request_context(self.url): + self.assertIsNotNone(web.judge.side_of(fold, t, self.b.name), "the trial page's record is not read") + with patch.object(web.judge.trajectory, "load", return_value=unittest.mock.Mock(error=None)), \ + patch.object(web.judge, "_states_for", return_value={}), patch.object(web.judge.batch, "ask_states", return_value=dict(rec)), \ + patch.object(web.judge, "side_ids", return_value=["more"]): # one question still to ask + web.judge.judge_side(fold, t, self.b.name, None) + self.assertIsNone(store.load(store.home(), jx.uid, TRIAL), "saved under the first shard's job") + self.assertIsNotNone(store.load(store.home(), jy.uid, TRIAL), "not saved under its own shard's job") def test_a_job_of_the_open_workspace_keeps_its_store(self): with web.app.test_request_context(f"/trial/job-x/{TRIAL}"): diff --git a/app/web/judge.py b/app/web/judge.py index 5db3b7f19..ba7944e9c 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -520,6 +520,7 @@ def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> when it has them all.""" if not trial.has_trajectory: raise client.JudgeError(0, "this trial has no trajectory to judge") + job = shard_of(job, trial, column) rec = store.load(store.home(), job_key(job, column), trial.trial_name, started=started_of(trial), old=old_of(job, column), strict=strict(trial)) have = (rec.get("answers") or {}) if store.is_current(rec) else {}