diff --git a/app/nullius/judge/store.py b/app/nullius/judge/store.py index eead47fc1..1cae94583 100644 --- a/app/nullius/judge/store.py +++ b/app/nullius/judge/store.py @@ -44,6 +44,7 @@ ADOPTED = "~adopted" # in a file: the digests of the older records copied in, so none is copied twice MOVED = ".moved" # in ``/judgements/``: a file per workspace whose older records are all in the user's store CURRENT = ".current" # in ``/judgements/``: the folders this version wrote, ``/``, ``*`` after one holding files before +STORED = "stored_by_identity" # in a record this version saved or copied in: the job's identity of now, never moved as an earlier one's SETTLED = ".settled" # in ``/judgements/``: the folders a scan found a current job's or all copied; the first-load prompt's alone @@ -245,10 +246,16 @@ def save(base: str, job_id: str, trial_name: str, record: dict, lane: str = "dec if data.get(version) and mine != version: # another try's, or an older revision: kept beside, and none _aside(data, version) # of its answers are this one's earlier = data.pop(mine) if mine and mine != version else data.get(version) or {} + if (earlier and not earlier.get(STORED) and _candidate(os.path.basename(os.path.dirname(path)), _DERIVED) + and not (started and earlier.get("trial_started_at") == started)): + data[version] = earlier # from before, and maybe an earlier identity's: kept whole, beside + _aside(data, version) + earlier = {} merged = dict(record, **({"trial_started_at": started} if started else {})) merged["answers"] = {**(earlier.get("answers") or {}), **(record.get("answers") or {})} if "hygiene" in earlier or "hygiene" in record: merged["hygiene"] = {**(earlier.get("hygiene") or {}), **(record.get("hygiene") or {})} + merged[STORED] = True # with the verdict, in one write: `move` never copies it data[version] = merged _written(os.path.dirname(path)) ondisk.write_whole(path, json.dumps(data, indent=1), mode=0o600) @@ -350,6 +357,11 @@ def _digest(rec) -> str: return hashlib.sha256(json.dumps(rec, sort_keys=True).encode("utf-8")).hexdigest()[:10] +def _verdict(rec) -> str: + """`_digest` of a record without `STORED`: one verdict, wherever it was saved.""" + return _digest({k: v for k, v in rec.items() if k != STORED}) + + 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 @@ -360,12 +372,13 @@ def _merged(cur: dict, data: dict) -> dict: 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)} + have = {_verdict(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: + rec = dict(rec, **{STORED: True}) + if d in adopted or _verdict(rec) in have: adopted.add(d) continue adopted.add(d) @@ -380,7 +393,7 @@ def _merged(cur: dict, data: dict) -> dict: cur[k] = other _aside(cur, k) cur[k] = shown - have |= {_digest(r) for r in cur.values() if isinstance(r, dict)} + have |= {_verdict(r) for r in cur.values() if isinstance(r, dict)} if adopted: cur[ADOPTED] = sorted(adopted) return cur @@ -636,6 +649,7 @@ def old_stores(home_dir: str, into: Optional[str] = None, exact: bool = False, h EARLIER_LABEL = "Earlier job identities" UNLISTED = "a folder of judgements cannot be listed" _UID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") +_DERIVED = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}") # `uid._derived`'s uuid5: every earlier identity is one def _entry(label: str, n: int) -> tuple: @@ -696,9 +710,9 @@ def _lane_entry(into: str, lane: str, name: str) -> str: return os.path.relpath(os.path.join(_root(into, lane), name), into) -def _candidate(name: str) -> bool: +def _candidate(name: str, uid=_UID) -> bool: """Whether a folder of a lane is named by a job identity (`key`), as an earlier one would be.""" - return any(_UID.fullmatch(name.partition("~")[0].removeprefix(_SAFE.sub("_", prefix))) for _, prefix in EARLIER_LANES) + return any(uid.fullmatch(name.partition("~")[0].removeprefix(_SAFE.sub("_", prefix))) for _, prefix in EARLIER_LANES) def earlier_maybe(into: str, hint: bool = False) -> bool: @@ -749,7 +763,7 @@ def stray(home_dir: str, into: str) -> tuple: cur = _lane_list(into, CURRENT) if cur is None: why.append("the list of judgements written cannot be read") - names = {(lane, n) for lane, n in names if _lane_entry(into, lane, n) not in (cur or ())} + every, names = names, {(lane, n) for lane, n in names if _lane_entry(into, lane, n) not in (cur or ())} written = {e[:-1] for e in cur or () if e.endswith("*")} jobs = {} for root in dict.fromkeys(r for ws in spaces for r in _walked(ws)): @@ -764,7 +778,8 @@ def stray(home_dir: str, into: str) -> tuple: uid_of = lambda lane, n: n.partition("~")[0][len("job_"):] if lane == TASKS else n # `key("job:" + uid)` held = {uid_of(lane, n) for lane, n in names} _note(into, SETTLED, {_lane_entry(into, lane, n) for lane, n in names if uid_of(lane, n) in now}) - unknown = {(lane, n) for lane, n in names if _candidate(n) and uid_of(lane, n) not in now} + unknown = {(lane, n) for lane, n in every if why and _candidate(n) and uid_of(lane, n) not in now + and _held_before(os.path.join(_root(into, lane), n))} # from its records: the list may miss a save out: dict = {} for d, (u, olds) in jobs.items(): for o in (olds & held) - now: @@ -776,12 +791,22 @@ def stray(home_dir: str, into: str) -> tuple: WRITTEN = "written" # `_earlier_left`: a folder this version wrote into while it held files, never copied +def _held_before(folder: str) -> bool: + """Whether the folder may hold a record not `STORED`: one, a file that cannot be read, or a folder that cannot be listed.""" + try: + files = [f for f in _listed(folder) if f.endswith(".json")] + except OSError: + return True + return any(data is None or any(not r.get(STORED) for k, r in data.items() if k != ADOPTED) + for data in (_old(os.path.join(folder, f)) for f in files)) + + def _copied(dest: str, data: dict) -> bool: """Whether every record of `data` is in the file `dest` already, or was copied into it (`ADOPTED`). `Unreadable` when that file cannot be read.""" cur = _read([dest], strict=True) - have = set(cur.get(ADOPTED) or ()) | {_digest(r) for r in cur.values() if isinstance(r, dict)} - return all(_digest(r) in have for k, r in data.items() if k != ADOPTED and isinstance(r, dict)) + adopted, have = set(cur.get(ADOPTED) or ()), {_verdict(r) for r in cur.values() if isinstance(r, dict)} + return all(_digest(r) in adopted or _verdict(r) in have for k, r in data.items() if k != ADOPTED and isinstance(r, dict)) def _earlier_left(into: str, found: tuple) -> list: @@ -809,6 +834,12 @@ def _earlier_left(into: str, found: tuple) -> list: n = len(out) for f in files: data, to = _old(os.path.join(src, f)), dest and os.path.join(dest, f) + if data: # `STORED`: this version's, never copied; a start that is no text: damaged + data = {k: r for k, r in data.items() if k != ADOPTED and not r.get(STORED)} + if not data: + continue + if any(not isinstance(r.get("trial_started_at"), (str, type(None))) for r in data.values()): + data = None try: if to and data is not None and _copied(to, data): continue diff --git a/app/tests/test_judge_adopt.py b/app/tests/test_judge_adopt.py index 6d6688a05..5dee85bd7 100644 --- a/app/tests/test_judge_adopt.py +++ b/app/tests/test_judge_adopt.py @@ -349,22 +349,30 @@ def _saved_before_793(self, root_is_job=True, lane="decision"): f = dict(job_uid.facts(pair, *files), folder="") old = str(uuid.uuid5(job_uid.NS_JOB, json.dumps(f, sort_keys=True, separators=(",", ":")))) name = "job:" + old if lane == store.TASKS else old - store.save(self.home, name, j.trials[0].trial_name, rec("2026-01-01T00:00:00Z", "before"), lane=lane) - os.remove(os.path.join(self.home, "judgements", store.CURRENT)) # a store from before keeps no list + self.t0 = j.trials[0].task_base + "@3a826e8bb00afa4e" if lane == store.TASKS else j.trials[0].trial_name # its slot + self._before(name, self.t0, "before", lane) return home_dir, pair, j, old + def _before(self, name, trial, choice, lane="decision", **more): + """A record as the version before #793 wrote it: no start, no `store.STORED`, and no list.""" + path = store._paths(self.home, name, trial, lane)[0] + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + json.dump({Q.VERSION: dict(rec("2026-01-01T00:00:00Z", choice), **more)}, fh, indent=1) + return path + def _copy(self, pair, home_dir, folder="copy"): shutil.copytree(pair, os.path.join(self.tmp, "other", folder)) return workspace.create(home_dir, [os.path.join(self.tmp, "other")], label="v") def test_a_record_under_an_identity_from_before_793_moves_when_asked_to_its_one_owner(self): - for root_is_job, lane in ((True, "decision"), (False, "decision"), (True, store.TASKS)): + for root_is_job, lane in ((True, "decision"), (False, "decision"), (True, "llm"), (True, store.TASKS)): with self.subTest(root_is_job=root_is_job, lane=lane): self.tmp = tempfile.mkdtemp(prefix="nullius-judge-adopt-"); self.addCleanup(shutil.rmtree, self.tmp, True) self.home = os.path.join(self.tmp, "data") patcher = patch.object(store, "home", return_value=self.home); patcher.start(); self.addCleanup(patcher.stop) home_dir, _, j, old = self._saved_before_793(root_is_job, lane) - name, t0 = ("job:" if lane == store.TASKS else "") + j.uid, j.trials[0].trial_name + name, t0 = ("job:" if lane == store.TASKS else "") + j.uid, self.t0 self.assertIsNone(store.load(self.home, name, t0, lane=lane)) # never merged on its own self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, hint=True)], [("Earlier job identities", 0)]) self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, exact=True)], [("Earlier job identities", 1)]) @@ -434,8 +442,7 @@ def denied(p="."): self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], ["Earlier job identities (a folder of judgements cannot be listed)"]) self.assertEqual(store.move(home_dir), ["Earlier job identities (a folder of judgements cannot be listed)"]) - store.save(self.home, old, t0, rec("2026-01-01T00:00:00Z", "llm"), lane="llm") - os.remove(os.path.join(self.home, "judgements", store.CURRENT)) # saved before #793 + self._before(old, t0, "llm", lane="llm") # saved before #793 lane = os.path.join(self.home, "judgements-llm", old) # its own folder this time with patch("os.listdir", denied): self.assertEqual(store.move(home_dir), ["Earlier job identities (1 folder cannot be listed)"]) @@ -470,8 +477,7 @@ def test_a_page_reads_no_workspace_for_them_and_offers_only_folders_no_save_wrot with open(os.path.join(self.home, "judgements", store.CURRENT), "wb") as fh: fh.write(b"\xff\xfe") # damaged list: offered self.assertEqual(len(store.old_stores(home_dir, hint=True)), 1) - self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], # read when the dialog opens - ["Earlier job identities (the list of judgements written cannot be read)"]) + self.assertEqual(store.old_stores(home_dir, exact=True), []) # read when the dialog opens: none from before def test_a_record_under_an_identity_from_before_793_its_destination_refuses_stays_for_later(self): home_dir, pair, j, old = self._saved_before_793() @@ -502,6 +508,72 @@ def test_a_folder_this_version_saved_to_is_never_recovered_as_an_earlier_identit self.assertEqual((store.old_stores(home_dir, exact=True), store.move(home_dir)), ([], [])) self.assertIsNone(store.load(self.home, j.uid, t0)) + def test_a_verdict_this_version_saved_is_never_moved_whatever_the_list(self): + """A job declaring B's earlier identity saves under it: its verdict is never B's, however the list missed it.""" + home_dir, pair, j, old = self._saved_before_793() + t0, listed = j.trials[0].trial_name, os.path.join(self.home, "judgements", store.CURRENT) + def saved_during_the_scan(*a, real=store.stray): + found = real(*a) + store.save(self.home, old, "t-new", rec("2026-06-01T00:00:00Z", "new")) + return found + for schedule in ("before the list", "the list unreadable", "during the move"): + with self.subTest(schedule): + if schedule != "during the move": + if schedule == "the list unreadable": + with open(listed, "wb") as fh: + fh.write(b"\xff\xfe") + store.save(self.home, old, "t-new", rec("2026-06-01T00:00:00Z", "new")) + os.remove(listed) # gone, or access back: an empty list + with patch.object(store, "stray", saved_during_the_scan if schedule == "during the move" else store.stray): + self.assertEqual(store.move(home_dir), []) + self.assertEqual(store.load(self.home, j.uid, t0)["answers"]["q"]["choice"], "before") + self.assertIsNone(store.load(self.home, j.uid, "t-new")) + shutil.rmtree(os.path.join(self.home, "judgements", j.uid)) + os.remove(os.path.join(self.home, "judgements", old, "t-new.json")) + for f in (listed, os.path.join(self.home, "judgements", store.SETTLED)): + if os.path.exists(f): + os.remove(f) + + def test_a_partial_save_keeps_a_record_from_before_whole_under_a_derived_identity(self): + for name, apart in ((str(uuid.uuid5(job_uid.NS_JOB, "x")), True), (str(uuid.uuid4()), False)): # a declared one is never earlier + with self.subTest(apart=apart): + path = self._before(name, "t0", "B") + store.save(self.home, name, "t0", dict(rec("2026-06-01T00:00:00Z"), answers={"r": {"choice": "A"}})) + self.assertEqual(sorted(store.load(self.home, name, "t0")["answers"]), ["r"] if apart else ["q", "r"]) + with open(path, encoding="utf-8") as fh: + kept = [r["answers"] for r in json.load(fh).values() if isinstance(r, dict) and not r.get(store.STORED)] + self.assertEqual(kept, [{"q": {"choice": "B"}}] if apart else []) + + def test_a_record_with_a_damaged_start_is_reported_and_its_neighbours_move(self): + home_dir, pair, j, old = self._saved_before_793() + self._before(old, "t-bad", "bad", trial_started_at=["2026"]) + self.assertEqual([(w.label, n) for w, n in store.old_stores(home_dir, exact=True)], + [("Earlier job identities", 1), ("Earlier job identities (a file cannot be read)", 1)]) + self.assertEqual(store.move(home_dir), ["Earlier job identities (1 file cannot be read)"]) + self.assertEqual(store.load(self.home, j.uid, j.trials[0].trial_name)["answers"]["q"]["choice"], "before") + + def test_an_unknown_owner_is_told_from_the_records_not_the_list(self): + home_dir, pair, j, old = self._saved_before_793() + [ws] = workspace.list_all(home_dir) + manifest = os.path.join(ws.dir, "workspace.json") + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + with open(manifest, "w", encoding="utf-8") as fh: + json.dump(dict(data, roots=None), fh) + with open(os.path.join(self.home, "judgements", store.CURRENT), "w") as fh: + fh.write(f"judgements/{old}\n") + line = f"Earlier job identities (workspace {ws.name} cannot be read)" + self.assertEqual([w.label for w, _ in store.old_stores(home_dir, exact=True)], [line]) + self.assertEqual(store.move(home_dir), [line]) + + def test_a_verdict_copied_already_is_not_copied_again_for_its_mark(self): + home_dir, pair, j, old = self._saved_before_793() + t0 = j.trials[0].trial_name + store.save(self.home, j.uid, t0, rec("2026-01-01T00:00:00Z", "before")) # the same verdict, marked + self.assertEqual((store.old_stores(home_dir, exact=True), store.move(home_dir)), ([], [])) + with open(os.path.join(self.home, "judgements", j.uid, t0 + ".json"), encoding="utf-8") as fh: + self.assertEqual([k for k in json.load(fh) if k != store.ADOPTED], [Q.VERSION]) + def test_an_unreadable_list_of_folders_written_is_left_as_it_is(self): listed = os.path.join(self.home, "judgements", store.CURRENT) os.makedirs(os.path.dirname(listed)) diff --git a/docs/judgement.md b/docs/judgement.md index 208a1f0ca..36ef31485 100644 --- a/docs/judgement.md +++ b/docs/judgement.md @@ -70,7 +70,7 @@ Follow the evidence: a recorded rate limit is a provider's failure whatever the | What | Detail | | --- | --- | | Where | `judgements//.json` below the user data directory, never in the job tree; task-instruction scores in `judgements-tasks//`. One record per trial and per try of a retried trial (a try that recorded no start is not judged), in every workspace that holds the job; a renamed Harbor or imported job folder is a new job | -| Before | Records under `workspaces//judgements/` are still shown; of two for one trial, the newer. *Move judgements* (first page, or Settings › Judges) copies them into the user data directory; the old files stay. A workspace is left for later while a root, a folder or a file cannot be read, or a record belongs to no job found, to two jobs, to one still starting or to one whose files cannot be read; such a record is still shown, never copied, even by a save. It also copies records an earlier version kept for a job opened from a root ending in `/`, `.` or `..`, when exactly one job of the readable registered workspaces derives them (register the folder holding a job to bring it in); one several jobs derive is listed with them, never copied | +| Before | Records under `workspaces//judgements/` are still shown; of two for one trial, the newer. *Move judgements* (first page, or Settings › Judges) copies them into the user data directory; the old files stay. A workspace is left for later while a root, a folder or a file cannot be read, or a record belongs to no job found, to two jobs, to one still starting or to one whose files cannot be read; such a record is still shown, never copied, even by a save. It also copies records an earlier version kept for a job opened from a root ending in `/`, `.` or `..`, when exactly one job of the readable registered workspaces derives them (register the folder holding a job to bring it in); one several jobs derive is listed with them, never copied; one this version saved is never copied | | Deleted | With the launch they judge (*Delete launch* in Runs, [Run](builder.md#run)), unless a copy of the job is found, or a root or workspace cannot be read: the result then says which. Still lost when another run's folder cannot be searched, or a root goes during the delete. Refused while a workspace holding it lists roots that are not all paths: repair its `workspace.json`. Deleting a workspace keeps them, its old records and its imports' failure analyses in `judgements-of-deleted-workspaces/`; one with old records or failure analyses is refused while one of its roots, or a folder of its imports, cannot be read | | Version | `judgement.questions.v2`; v1 records marked *earlier* | | Cost | A batch button names its calls; each is checked against the token budget |