diff --git a/app/nullius/execution.py b/app/nullius/execution.py index bcb809a1..ff917d28 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 @@ -1830,34 +1830,73 @@ def deletable(names: List[str], root: Optional[str] = None) -> None: _deletable(n, root) -def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, ends: dict) -> dict: +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 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) 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 host = hosts.parse(plan["host"]) if plan.get("host") and (rec.get("launched") or rec.get("step") not in ("connect", "name")) else None - held = [] + held, olds = [], [] 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)] - # 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)} + jobs = workspace.load_jobs(ws, roots, ends) + 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} + 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, 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.""" + 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): + if not all(os.path.isdir(r) for r in ws.job_roots or ws.roots): + return set(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 {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) -> dict: +def deletion(names: List[str], home: str, root: Optional[str] = None, holding: Optional[Callable] = None, + final: bool = False) -> dict: """What deleting the runs *names* of one launch removes: per run (``runs``) its folder and size, the host copy that is its own, and per workspace that holds it its roots, parsed jobs and judgement folders; the totals, and the number of copies per host. ValueError when any of them is alive or is not a run: nothing goes then. ``holding``: a run folder's ``workspace.holding``, - when the caller has it already.""" + 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) for n in dict.fromkeys(names)] + runs = [_run_deletion(n, home, root, holding, ends, final) for n in dict.fromkeys(names)] copies: Dict[str, int] = {} for r in runs: if r["host"]: @@ -1872,9 +1911,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.""" - gone = deletion(names, home, root) + 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"]) @@ -1882,11 +1923,11 @@ 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 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: @@ -1896,4 +1937,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/nullius/judge/batch.py b/app/nullius/judge/batch.py index 80b11a54..f81c0e31 100644 --- a/app/nullius/judge/batch.py +++ b/app/nullius/judge/batch.py @@ -96,20 +96,30 @@ 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, 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. 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 + 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. `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.""" + 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(ws_dir) + calibration = store.calibration(base, [job_id]) 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, 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 c80c5c42..7f66d3c2 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -1,13 +1,25 @@ -"""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. - -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 +"""Where a judgement lives: the user's own store, by the job it judges - +``/judgements//.json`` (each name spelled by +`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 +``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}//``). 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. + +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 @@ -16,30 +28,70 @@ import json import os import re -import threading +import shutil 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`) +ADOPTED = "~adopted" # in a file: the digests of the older records copied in, so none is copied twice +MOVED = ".moved" # in ``/judgements/``: a file per workspace whose older records are all in the user's store -def _lock(path: str) -> threading.Lock: - with _LOCKS_GUARD: - return _LOCKS.setdefault(path, threading.Lock()) +class Unreadable(client.JudgeError, ValueError): + """A judgement file of the user's store that cannot be read: left as it is, never written over.""" + def __init__(self, path: str): + super().__init__(0, f"{path} cannot be read; it is left as it is. Repair or remove it, then try again.") -ROOTS = {"decision": "judgements", "llm": "judgements-llm"} # one directory per judgement +def home() -> str: + """The base of the user's own store: the user data directory.""" + return paths.data_dir() -def _root(ws_dir: str, lane: str) -> str: - return os.path.join(ws_dir, ROOTS.get(lane, "judgements")) +def _root(base: str, lane: str) -> str: + return os.path.join(base, "judgements-tasks" if lane == TASKS else 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. + 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: @@ -55,35 +107,55 @@ 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)] -def _read(paths) -> dict: - """The first judgement file of `paths` there is, read; {} when there is none or it cannot be read.""" +def _read(paths, strict: bool = False) -> dict: + """The first judgement file of `paths` there is, read; {} when there is none. One that + cannot be read, or holds no JSON object: {}, or `Unreadable` when `strict` (a write).""" for path in paths: try: with open(path, encoding="utf-8") as fh: - return json.load(fh) or {} + data = json.load(fh) except FileNotFoundError: continue except (OSError, ValueError): + data = False + if data is None: + return {} + if not isinstance(data, dict): + if strict: + raise Unreadable(path) return {} + return data return {} +def _with(data: dict, old) -> dict: + """`data` with the older records `old` (a list of files' contents) merged in, in memory (`_merged`).""" + for d in old or (): + data = _merged(data, d) + return data + + 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): both starts are then needed, and the same.""" + if not rec: + return True + 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: @@ -91,20 +163,30 @@ 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(ws_dir: str, job_id: str, trial_name: str, version: Optional[str] = None, lane: str = "decision", - started: Optional[str] = None) -> Optional[dict]: +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 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) + 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, strict) + + +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: @@ -112,21 +194,29 @@ 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", - started: Optional[str] = None) -> dict: +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, + 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 - 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] - os.makedirs(os.path.dirname(path), exist_ok=True) - with _lock(path): - data = _read(paths) + 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, `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] + _open_for(path, job_dir) + with _locked(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 - 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 {})} @@ -137,65 +227,60 @@ 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", + 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(ws_dir, job_id, name, version, lane, start) + rec = load(base, job_id, name, version, lane, start, old, strict=name in strict) 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", old: Optional[dict] = None): """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) + version, record). One job's when `job_id` is given, with its older + records `old` (`overlay`).""" + root = _root(base, lane) try: jobs = list(_names(job_id)) if job_id else sorted(os.listdir(root)) except OSError: - return + jobs = [] + files = {} for j in jobs: - d = os.path.join(root, j) try: - names = sorted(os.listdir(d)) + files.update((os.path.join(root, j, n), None) for n in os.listdir(os.path.join(root, j)) if n.endswith(".json")) except OSError: continue - for n in names: - if not n.endswith(".json"): - continue - try: - with open(os.path.join(d, n), encoding="utf-8") as fh: - data = json.load(fh) or {} - except (OSError, ValueError): - continue - for version, rec in data.items(): - if isinstance(rec, dict): - 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: + files.update((p, None) for p in old or {} if os.path.dirname(os.path.dirname(p)) == root) + for path in sorted(files): + for version, rec in _with(_read([path]), (old or {}).get(path)).items(): + if isinstance(rec, dict): + yield os.path.basename(os.path.dirname(path)), os.path.basename(path)[:-5], version, rec + + +def calibration(base: Optional[str], job_ids=()) -> Optional[dict]: + """The judge's observed characters per token over the stored calls of + the jobs `job_ids` (`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 j in dict.fromkeys(job_ids) if j for _, _, _, rec in all_records(base, j)) -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, old: Optional[dict] = 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 +289,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, old=old): records += 1 if rec.get("truncated"): truncated += 1 @@ -222,3 +307,340 @@ 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, 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: + return hashlib.sha256(json.dumps(rec, sort_keys=True).encode("utf-8")).hexdigest()[:10] + + +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; 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 ()) + have = {_digest(r) for r in cur.values() if isinstance(r, dict)} + for k, rec in data.items(): + if not isinstance(rec, dict) or k == ADOPTED: + continue + d = _digest(rec) + if d in adopted or d in have: + adopted.add(d) + continue + adopted.add(d) + now = cur.get(k) + if not isinstance(now, dict): + 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 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 + have |= {_digest(r) for r in cur.values() if isinstance(r, dict)} + if adopted: + cur[ADOPTED] = sorted(adopted) + return cur + + +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, + `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 _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. 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 _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 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(ws_dir, _old_files(ws_dir)) + except OSError: + return False + + +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(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, 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 folders: + unmark(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. 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))] + 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: + 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 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 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 + + +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, 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 + 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: + """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`: {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 only.get(src) == dest) else None + if data: + out.setdefault(dest, []).append(data) + return out + + +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.""" + dirs = {os.path.join(_root(base, lane), key(u)) for lane in ROOTS for u in uids if u} + found = {os.path.join(d, n) for d in dirs if os.path.isdir(d) for n in os.listdir(d) if n.endswith(".json")} + return len(found | {p for o in olds for p in o if os.path.dirname(p) in dirs}) + + +def old_stores(home_dir: str, into: Optional[str] = None) -> list: + """[(workspace, its count of older records)] for each workspace whose store from before holds + any, until it is `moved`; one whose folders cannot all be listed counts those it can.""" + from nullius import workspace + out = [] + for ws in workspace.list_all(home_dir): + try: + n = len(_old_files(ws.dir)) + except OSError: + n = -1 + if n and not moved(ws.dir, into): + out.append((ws, max(n, 0))) + 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, 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 + 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): + 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 + 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 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 = 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(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")), + (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, raw) + return left diff --git a/app/nullius/onboarding.py b/app/nullius/onboarding.py index b256325c..f0fc820f 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/runs/uid.py b/app/nullius/runs/uid.py index 8bee809c..355dfd1f 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -75,6 +75,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/nullius/workspace.py b/app/nullius/workspace.py index 5479fd3a..d803858a 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) @@ -219,14 +221,78 @@ 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; ValueError, nothing removed, while it holds judgements kept + before and one of its roots cannot be read.""" 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 +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) + + +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(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 _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 + 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, 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.") + if not old and not made: + return + _check_roots(ws) + 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}") + 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: """Every workspace with a root in *folder*: [(workspace, those roots)].""" return holding_all(home_dir, [folder])[folder] @@ -590,7 +656,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/static/judgements-move.js b/app/static/judgements-move.js new file mode 100644 index 00000000..121eb776 --- /dev/null +++ b/app/static/judgements-move.js @@ -0,0 +1,51 @@ +// Judgements kept in workspaces before they were kept by job: the dialog that moves them into the +// user's store, opened from Settings › Judges ([data-move-judgements]) and once per browser at a first page load. +(() => { + const me = document.currentScript, URL_ = me.dataset.url, CSRF = me.dataset.csrf, KEY = 'nullius-judgements-move'; + const esc = s => String(s).replace(/[&<>"']/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c])); + const remember = () => { try { localStorage.setItem(KEY, '1'); } catch {} }; + const notify = (m, o) => window.nulliusNotify && window.nulliusNotify(m, o); + + async function ask({later = false} = {}) { + const got = await nulliusFetch(URL_, {headers: {Accept: 'application/json'}}).then(r => r.ok ? r.json() : {workspaces: []}).catch(() => ({workspaces: []})); + if (!got.workspaces.length) { if (later) remember(); return; } // nothing to move: not asked again here + // a native modal, as the welcome: it keeps the focus, makes the page behind it inert and closes on Escape + const d = document.createElement('dialog'); + d.className = 'onb-dialog'; + d.setAttribute('aria-labelledby', 'jm-h'); + d.innerHTML = `

Move judgements to your profile

+

They are now kept by job, so every workspace shows them. The old files stay.

+
    ${got.workspaces.map(w => `
  • ${esc(w.label)}: ${w.n}
  • `).join('')}
+
`; + 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/static/settings/settings.css b/app/static/settings/settings.css index f1d5793b..5b6eaeac 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; } } diff --git a/app/templates/base.html b/app/templates/base.html index fd439811..063b355f 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 ca2a3a58..4e909a3d 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 92fd9257..cda4b264 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 6b6331ce..980133b2 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/templates/workspaces/workspaces.html b/app/templates/workspaces/workspaces.html index 0e226d33..07e69047 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 %} @@ -75,7 +75,7 @@

Delete workspace

-

Its run folders stay on disk.

+

Its roots and judgements stay; its converted imports go.

@@ -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 00000000..323e2319 --- /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 00000000..40443ec8 --- /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 543ff55c..ddc66d06 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 @@ -192,13 +193,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): @@ -244,6 +245,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): @@ -280,6 +288,13 @@ 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) + 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): import json as _json diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py new file mode 100644 index 00000000..bb2df33b --- /dev/null +++ b/app/tests/test_judge_adopt.py @@ -0,0 +1,306 @@ +"""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, key=t, n_retries=0) 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, 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): + 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"))) + + 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 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("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")) + 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 (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) + 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), []) + 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_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)"]) + 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")) + _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]) + 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 + 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_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")) + 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/tests/test_judge_cost.py b/app/tests/test_judge_cost.py index 8582b14f..b6f32c5b 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_judge_store_race.py b/app/tests/test_judge_store_race.py index 7d0b1c2e..82b9a25f 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 99f0bee9..0ac15bf0 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,19 +68,116 @@ 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 test_a_job_of_the_same_id_in_another_root_keeps_its_judgements(self): + 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"], 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.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.run_("r3") + 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") + _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_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_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") + 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) + execution.delete(["r1"], self.home, self.root) + 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): 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 2d5fe5cb..f4728f72 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 91b49d92..045702f8 100644 --- a/app/ui_tests/test_judge_calibration_reads.py +++ b/app/ui_tests/test_judge_calibration_reads.py @@ -26,8 +26,9 @@ 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)) 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", 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] 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 558349fc..95d15ed7 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 @@ -8,6 +9,7 @@ import unittest from contextlib import ExitStack from pathlib import Path +from types import SimpleNamespace from unittest.mock import patch from flask import url_for @@ -28,6 +30,7 @@ def setUp(self): tmp = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="nullius-judge-ws-"))) shutil.copytree(JOB, tmp / "a" / "job-x") shutil.copytree(JOB, tmp / "b" / "job-y") + 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") @@ -44,14 +47,18 @@ 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)) + 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_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 00000000..2c7b443d --- /dev/null +++ b/app/ui_tests/test_judgement_follows_job.py @@ -0,0 +1,306 @@ +"""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 os +from dataclasses import replace +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 nullius.runs import parse + +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}) + + 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") + 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 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.""" + 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)) + 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): + """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"]) + + 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)) + 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) + 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 + 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__": + unittest.main() diff --git a/app/ui_tests/test_reconcile_routes.py b/app/ui_tests/test_reconcile_routes.py index 59be52b1..6edfef04 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 cd25e91f..a456c9b4 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
', 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 @@ -1260,16 +1262,15 @@ def test_ws_presets_the_launches_filter(self): self.assertEqual(set(boxes(self.get(f"/launches{q}").get_data(as_text=True)).values()), {" checked"}) def test_delete_workspace_says_what_is_lost(self): - from nullius.judge import store - store.save(self.ws.dir, "r1-b", "t0", {"questions": "v", "answers": {}}, lane="llm") # beside the one setUp saved html = self.get("/workspaces").get_data(as_text=True) ask = html.split('", 1)[0] # one, filled from the row's button self.assertEqual(html.count("Delete workspace ', ask) self.assertIn(f'', ask) - self.assertIn("

Its run folders stay on disk.

", ask) - for ws, n in ((self.ws, 2), (self.other(), 0)): # none: nothing lost but the cache - self.assertIn(f'data-ask="ws-ask-delete" data-label="{ws.label}" data-action="/workspaces/delete/{ws.name}" data-judged="{n}"', self.row(ws, html)) + 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)) def test_a_shard_s_folder_stays_while_another_shard_of_its_launch_runs(self): for i, state in ((1, "done"), (2, "running")): diff --git a/app/ui_tests/test_task_judgement_slot.py b/app/ui_tests/test_task_judgement_slot.py index 9e7290af..e77c30c3 100644 --- a/app/ui_tests/test_task_judgement_slot.py +++ b/app/ui_tests/test_task_judgement_slot.py @@ -3,6 +3,7 @@ judged on its own.""" from __future__ import annotations +import os import tempfile import unittest from contextlib import ExitStack @@ -25,6 +26,8 @@ def setUp(self): self.addCleanup(stack.close) tmp = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="nullius-task-slot-"))) stack.enter_context(patch.object(web.shared, "WS_HOME", str(tmp / "workspaces"))) + self.home = str(tmp / "data") + stack.enter_context(patch.object(store, "home", return_value=self.home)) stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) web.shared.open_workspace(workspace.create(web.shared.WS_HOME, [], "w")) self.instruction = "Fix the bug in parse.py." @@ -32,8 +35,8 @@ 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", has_trajectory=True) - return NS(job_id=job_id, dataset=dataset, dataset_path=path, trials=[trial]), trial + 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): job, trial = self.job("run-1", "tasks") @@ -43,7 +46,7 @@ def test_a_changed_instruction_is_judged_again(self): "still scored: " + str(web.judge.task_quality_of(job, trial))) job, trial = self.job("legacy-run", "tasks", "/x/bench-a/tasks") - store.save(web.judge.ws_dir(), web.judge.task_key(job), "fix-bug", dict(SCORED)) # as kept before the digest + store.save(self.home, web.judge.task_key(job), "fix-bug", dict(SCORED), lane=store.TASKS) # as kept before the digest self.assertIsNone(web.judge.task_quality_of(job, trial)) self.assertEqual(web.judge.tasks_todo(job), [trial]) @@ -54,6 +57,13 @@ def test_two_datasets_with_one_folder_name_are_judged_apart(self): self.assertIsNone(web.judge.task_quality_of(b, tb), "bench-b shows bench-a's score, slot " + web.judge.task_key(b)) again, _ = self.job("run-2", "tasks", "/x/bench-a/tasks") self.assertEqual(web.judge.task_quality_of(again, ta)["score"], 2) # another run of bench-a: judged once for both + self.assertEqual(os.listdir(os.path.join(self.home, "judgements-tasks")), [store.key("/x/bench-a/tasks")]) + self.assertFalse(os.path.exists(os.path.join(self.home, "judgements"))) # a dataset is no job of the store + + def test_a_score_kept_in_a_workspace_before_is_read(self): + job, trial = self.job("run-1", "tasks", "/x/bench-a/tasks") + store.save(web.judge.ws_dir(), "task:/x/bench-a/tasks", web.judge.task_slot(trial), dict(SCORED)) + self.assertEqual(web.judge.task_quality_of(job, trial)["score"], 2) def test_two_jobs_of_no_dataset_are_judged_apart(self): a, ta = self.job("run-1", "") diff --git a/app/ui_tests/test_trial_head.py b/app/ui_tests/test_trial_head.py index faff292c..8b1689c5 100644 --- a/app/ui_tests/test_trial_head.py +++ b/app/ui_tests/test_trial_head.py @@ -271,6 +271,7 @@ def setUp(self): 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", {"failed": 0, "plain": 0}) self.stack.enter_context(patch.object(web.shared, "_jobs_for_request", return_value=[self.job])) self.ws = workspace.create(self.tmp.name + "/home", [self.tmp.name], label="notes") diff --git a/app/web/judge.py b/app/web/judge.py index 3247a817..c8627423 100644 --- a/app/web/judge.py +++ b/app/web/judge.py @@ -1,6 +1,7 @@ """Judgement: asking the judge about a trial, a job's trials, or matched -pairs; what the pages show comes from the workspace store. Advisory beside -the recorded evidence, never in its place.""" +pairs; what the pages show comes from the user's store, by the job's +identity (`nullius.judge.store`). Advisory beside the recorded evidence, +never in its place.""" from __future__ import annotations import functools @@ -58,17 +59,47 @@ def one(item): def ws_dir(name=None): - """The judgement store of the workspace that holds the job on screen + """The folder of the workspace that holds the job on screen (`shared._record_workspace`): a job opened from another workspace, or a - Compare column (`name`), keeps its judgements in its own.""" + Compare column (`name`), reads the judgements its own kept before + (`job_key`).""" ws = shared._record_workspace(name) return ws.dir if ws else None +def job_key(job, name=None) -> str: + """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 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, 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={src: dest for src, (dest, _) in one.items()}) if one else {} + return memo[k] + + def batch_calibration() -> dict: - """The workspace'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(ws_dir()) or {} + return store.calibration(store.home(), [j.uid for j in shared._jobs_for_request()]) or {} def started_of(trial) -> str | None: @@ -82,9 +113,29 @@ 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, 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: + """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: - d = ws_dir() - return store.load(d, job.job_id, trial.trial_name, lane=lane, started=started_of(trial)) if d else 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, strict=strict(trial)) + if slot(trial) != trial.trial_name else None)) def panel(job, trial, lane: str = "decision") -> dict: @@ -253,17 +304,26 @@ 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(ws_dir(), job.job_id, trial.trial_name, _trial_ids_and_states(trial, traj), api_key, post=post, - calibration=calibration, started=started_of(trial)) + 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, 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(): @@ -271,7 +331,7 @@ def _guard(): if not shared._local_client(): abort(403, description="Judging is asked from a browser on the application host only: it is a paid call.") if ws_dir() is None: - abort(400, description="No workspace is open; judgements live in the workspace.") + abort(400, description="No workspace is open.") @app.route("/judge/trial//", methods=["POST"]) @@ -298,16 +358,15 @@ 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" - d = ws_dir() - judged = store.for_job(d, job_id, started_by_name(job), lane=lane) if d else {} + 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] - _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) + 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") @@ -322,8 +381,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 = ws_dir() - judged = store.for_job(d, job.job_id, started_by_name(job)) if d else {} + d, uid, old = store.home(), job_key(job), old_of(job) + 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 = {} @@ -348,7 +407,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, job.job_id) if d and 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)} @@ -356,7 +415,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.job_id, started_by_name(job), lane="llm") if d else {} + 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"))} @@ -386,11 +445,22 @@ 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 side_of(job, trial, d) -> dict | None: +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 in its column's store `d`: the expectation, the level it rounds to, the judge's + 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(d, job.job_id, trial.trial_name, started=started_of(trial)) if d else None + 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): return None a = (rec.get("answers") or {}).get(SIDE_QUESTION) @@ -404,13 +474,12 @@ def side_of(job, trial, d) -> dict | None: def pair_records(view) -> dict: """{task: record} for the pairs judged under v1 - the pair state, the - model's own pick - under job A in its column's workspace. Read, never written.""" - d = ws_dir(view.selected[0].workspace) if view.selected else None - if d is None or len(view.jobs) != 2: + model's own pick - under job A. Read, never written.""" + if not view.selected or len(view.jobs) != 2: return {} - out = {} + 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(d, view.jobs[0].job_id, 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 @@ -427,7 +496,7 @@ def compare_summary(view) -> dict | None: pairs = pairs_of(view) legacy = pair_records(view) rows, judged, earlier = {}, 0, 0 - da, db = (ws_dir(s.workspace) for s in view.selected) + da, db = (s.workspace for s in view.selected) for task, a, b in pairs: sa, sb = side_of(view.jobs[0], a, da), side_of(view.jobs[1], b, db) if sa or sb: @@ -443,14 +512,15 @@ def compare_summary(view) -> dict | None: "margin": comparison.TIE_MARGIN, "question": SIDE_QUESTION} -def judge_side(job, trial, d, api_key: str, post=None, calibration=None) -> dict | None: +def judge_side(job, trial, column, api_key: str, post=None, calibration=None) -> dict | None: """Score one side: the questions it still lacks under the current - vocabulary, one call per state, merged over the trial's own record in - its column's store `d` - the same record the trial page shows. Nothing + vocabulary, one call per state, merged over the trial's own record, the + job opened from its column's workspace `column` - the same record the trial page shows. Nothing when it has them all.""" if not trial.has_trajectory: raise client.JudgeError(0, "this trial has no trajectory to judge") - rec = store.load(d, job.job_id, trial.trial_name, started=started_of(trial)) + 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: @@ -458,18 +528,19 @@ def judge_side(job, trial, d, 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(d, job.job_id, trial.trial_name, _states_for(trial, traj, ids), api_key, post=post, - calibration=calibration, started=started_of(trial)) + 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=own_of(job, column), job_dir=job.dir, + strict=strict(trial)) def _sides_todo(view) -> list: - """(task, job, trial, its column's store) for every side of an unjudged pair that lacks its score.""" + """(task, job, trial, its column's workspace) for every side of an unjudged pair that lacks its score.""" out = [] - da, db = (ws_dir(s.workspace) for s in view.selected) + da, db = (s.workspace for s in view.selected) 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 @@ -544,18 +615,19 @@ 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(ws_dir(), job.job_id, trial.trial_name, control_states(side, trial), api_key, post=post, - calibration=calibration, started=started_of(trial)) + 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=own_of(job), job_dir=job.dir, + strict=strict(trial)) def triage_summary(report, jobs) -> dict: """For the feasibility page: per task and side the judged cause, the counts, and what judging the rest would cost.""" - d = ws_dir() sides = triage_sides(report) rows, judged, todo = {}, 0, [] for row, s in sides: - rec = store.load(d, s.job_id, s.trial_name) if d 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) @@ -569,11 +641,8 @@ def triage_summary(report, jobs) -> dict: # -- task-instruction quality: once per dataset, task and instruction text --------------- def task_key(job) -> str: - """The store's job slot for a dataset's task judgements: `task:`, - so an instruction is judged once for every run of that dataset. The - dataset is named by its recorded path, or its registry name, so two - datasets of one folder name keep apart; a job that names none has its own.""" - return "task:" + (job.dataset_path or job.dataset or "job:" + job.job_id) + """The dataset a job's task judgements are kept under (`store.task_dataset`).""" + return store.task_dataset(job) def task_slot(trial) -> str: @@ -583,8 +652,7 @@ def task_slot(trial) -> str: def task_record(job, trial) -> dict | None: - d = ws_dir() - rec = store.load(d, task_key(job), task_slot(trial)) if d else None + 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 @@ -651,11 +719,40 @@ 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) if not instruction: 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(ws_dir(), task_key(job), task_slot(trial), states, api_key, post=post, calibration=calibration) + 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, column)) + + +# -- the move of the judgements workspaces kept before into the user's store --------------- + +@app.template_global() +def judgements_unmoved() -> bool: + """Whether a workspace's judgements kept before still wait to be moved (`store.old_stores`).""" + return bool(store.old_stores(shared.WS_HOME)) + + +@app.route("/judgements/move", methods=["GET", "POST"]) +def judgements_move(): + """GET: the workspaces whose store from before holds judgements, and how + many each (`store.old_stores`). POST: every one of them copied into the + user's store (`store.move`), the old files kept; the error names the + 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: + left = store.move(shared.WS_HOME) + except store.Unreadable as e: + return jsonify(ok=False, error=str(e)), 409 + if left: + return jsonify(ok=False, error="Left for later: " + "; ".join(left) + "."), 409 + return jsonify(ok=True) diff --git a/app/web/judge_tasks.py b/app/web/judge_tasks.py index 13e26e9c..67cbcac2 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") diff --git a/app/web/reconcile.py b/app/web/reconcile.py index 6d0d0f4b..1c7df276 100644 --- a/app/web/reconcile.py +++ b/app/web/reconcile.py @@ -25,8 +25,8 @@ def threshold_requested() -> float: def view_of(job, threshold: float) -> dict: - d = judge.ws_dir() - records = store.for_job(d, job.job_id, judge.started_by_name(job)) if d else {} + 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) diff --git a/app/web/settings.py b/app/web/settings.py index 656df7ce..3108ae99 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/shared.py b/app/web/shared.py index a47855ad..f53c77c3 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 07b414b4..9187ef82 100644 --- a/app/web/workspaces.py +++ b/app/web/workspaces.py @@ -10,7 +10,6 @@ from nullius.runs import parse from nullius import execution, workspace from nullius.catalogue import catalog -from nullius.judge import store from .core import app from . import shared @@ -100,7 +99,7 @@ def workspaces_page(): held = [w.name for _, _, holders in launched[0] for w in holders] recs, cat = tuple((e.id, e.state) for e in execution.EXECUTIONS.values()), catalog.signature() return render_template("workspaces/workspaces.html", workspaces=wss, csrf=shared._csrf_token(), - counts={ws.name: _counts(ws, recs, cat) for ws in wss}, n_judged={ws.name: store.count(ws.dir) for ws in wss}, n_launches={ws.name: held.count(ws.name) for ws in wss}) + counts={ws.name: _counts(ws, recs, cat) for ws in wss}, n_launches={ws.name: held.count(ws.name) for ws in wss}) @app.route("/workspaces/open/", methods=["POST"]) @@ -164,12 +163,22 @@ 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"] - if ws is not None and ws.name == name: - shared.close_workspace() - if workspace.delete(shared.WS_HOME, name): + try: + workspace.check_deletable(shared.WS_HOME, name) + except ValueError as e: + flash(str(e), "error") + return redirect(url_for("workspaces_page")) + try: + removed = workspace.delete(shared.WS_HOME, name) + 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: flash(Markup(f'No workspace called {escape(name)}.'), "error") diff --git a/docs/builder.md b/docs/builder.md index e4c9d867..a3f9052e 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 in every workspace, 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/concepts.md b/docs/concepts.md index c7281152..433d4de3 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -70,7 +70,7 @@ A count of runs leaves out the checks. The checks have a count of their own. ## Workspace -The roots you opened, the imports converted and the judgements saved; the same roots reopen the same workspace. +The roots you opened and the imports converted; the same roots reopen the same workspace. Judgements belong to the job, in every workspace that holds it.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md index dd80515c..50de37da 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -70,7 +70,6 @@ workspace root. `nullius paths` shows the active location. | `workspaces//jobs/.json` | Parse cache | | `workspaces//jobs/counts.json` | Runs and checks of a closed workspace whose jobs ended | | `workspaces//imported/` | Converted foreign roots | -| `workspaces//judgements//.json` | Judge records | ## Page by page diff --git a/docs/judgement.md b/docs/judgement.md index 1ff091df..523116de 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -69,8 +69,9 @@ Follow the evidence: a recorded rate limit is a provider's failure whatever the | What | Detail | | --- | --- | -| Where | `workspaces//judgements//.json` below the user data directory (`WORKSPACES_DIR` can override it), never in the job tree | -| Deleted | With the launch they judge (*Delete launch* in Runs, [Run](builder.md#run)) | +| 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, 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 | diff --git a/docs/settings/llm-judge.md b/docs/settings/llm-judge.md index 4180df55..65a1eefa 100644 --- a/docs/settings/llm-judge.md +++ b/docs/settings/llm-judge.md @@ -13,7 +13,7 @@ The same questions as Decision, answered as JSON by a chat model. | --- | --- | | Answers | What the model states; no confidence value | | Out of range | An answer outside its question's options or range is left out | -| Records | `judgements-llm/` in the workspace, its own trial tab | +| Records | `judgements-llm/` below the user data directory, its own trial tab | ## Configure