diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index 720f3853..1ead121f 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -19,6 +19,7 @@ from nullius.runs import verifier from nullius.runs import classify +from nullius.runs import uid as job_uid from nullius.redact import redact # What a trace document in a trial's `agent/` may be called: the producer's own @@ -31,7 +32,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "19" +SCHEMA = "20" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — @@ -344,6 +345,14 @@ def stop_reason(self) -> str: """The benchmark's own reason when it is too long for a tag.""" return self.ended_label if len(self.ended_label) > ENDED_CHARS else "" + @property + def key(self) -> str: + """The trial within its job's identity (Job.uid): its name; a try under + ``retried/``, the name of the attempt it is a try of.""" + if os.path.basename(os.path.dirname(self.dir)) == "retried": + return re.sub(r"\.try-\d+$", "", self.trial_name) + return self.trial_name + @property def dur_phases(self) -> float: """Sum of the four phases Harbor breaks out.""" @@ -452,6 +461,10 @@ class Job: launch_id: str = "" # Source job names explicitly recorded by standard merge. merged_from: list[str] = field(default_factory=list) + # The job's identity wherever its folder is (nullius.runs.uid), and whether it was + # "declared" by its producer, "derived" from its files or is "pending" ("" uid). + uid: str = "" + uid_source: str = "" # How the job was launched, as its config.json recorded it with Harbor's # defaults filled in (launch_of). Empty when config.json is absent. launch: dict = field(default_factory=dict) @@ -1224,6 +1237,7 @@ def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job: harbor = lock.get("harbor") if isinstance(lock.get("harbor"), dict) else {} job.harbor_version = str(harbor.get("version") or "") job.harbor_editable = harbor.get("is_editable") if isinstance(harbor.get("is_editable"), bool) else None + job.uid, job.uid_source = job_uid.of(job_dir, cfg, res) return job diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py new file mode 100644 index 00000000..8bee809c --- /dev/null +++ b/app/nullius/runs/uid.py @@ -0,0 +1,87 @@ +"""A job's identity: one UUID that stays the same wherever its folder is. + +A job folder is copied, moved, mirrored from a host and opened in several +workspaces; its name is not unique either, since two roots can each hold a +job of one name. What Nullius records about a job (a judgement) is kept +under this identity, so it follows the job and not the folder. + +- **declared**: the producer wrote one. A Nullius standard job carries + ``standard.uuid`` in its ``config.json``, made at creation, kept by a run + resumed into the same folder and new for a merge. +- **derived**: none was written (Harbor, imports, standard jobs from before + ``standard.uuid``). A ``uuid5`` over fixed facts read from the files: the + format, the folder name, what ran and when it started. No path is a fact, + so a copy or a move keeps it; a renamed folder is a new job. +- **pending**: nothing fixed to derive from yet: a job with no trial and no + start (a Harbor job preparing), or a standard job from before + ``standard.uuid`` without its ``result.json`` (still running, or killed). + Its start is the one ``result.json`` will record; the feed's start is + never read, since it differs from the result's and would change the uid. + +Old files are never rewritten to gain an id: a derived id is a pure function +of the files. The facts carry ``"v": 1``; a change of their canonical form +bumps it and keeps this function as the reader of ``v`` 1. +""" +from __future__ import annotations + +import json +import os +import uuid + +#: fixed for good: changing one changes every derived identity +NS_JOB = uuid.UUID("6f0f3a52-5c1e-4d39-9a2b-6a4c1f0e7d21") + +def _declared(cfg: dict): + std = cfg.get("standard") if isinstance(cfg.get("standard"), dict) else {} + try: + return str(uuid.UUID(str(std["uuid"]))) + except (KeyError, ValueError, TypeError, AttributeError): + return None + + +def _has_trial(job_dir: str) -> bool: + try: + with os.scandir(job_dir) as entries: + return any(e.is_dir() and os.path.isfile(os.path.join(e.path, "result.json")) for e in entries) + except OSError: + return False + + +def facts(job_dir: str, cfg: dict, res: dict): + """The fixed facts a derived identity is made of, as strings, or None while + pending. The start is ``result.json``'s only, which nothing later rewrites.""" + std = cfg.get("standard") if isinstance(cfg.get("standard"), dict) else {} + agents = [a for a in cfg.get("agents") or [] if isinstance(a, dict)] + if isinstance(cfg.get("harness"), str): # an import: its folder names its source + # shortcut: two imports of one source basename share an identity; a per-source id replaces this. + return {"v": 1, "format": cfg["harness"], "folder": os.path.basename(job_dir)} + start = str(res["started_at"]) if res.get("started_at") else None + if std and not res: + return None + if start is None and not _has_trial(job_dir): + return None + if std: + return {"v": 1, "format": "standard", "folder": os.path.basename(job_dir), + "benchmark": str(std.get("benchmark") or ""), "plugged": str(std.get("plugged") or ""), + "model": str((agents[0] if agents else {}).get("model_name") or ""), + "launch": str(std.get("launch") or ""), + "shard": json.dumps(std.get("shard"), sort_keys=True) if std.get("shard") else "", + "start": start or ""} + return {"v": 1, "format": "harbor", "folder": os.path.basename(job_dir), "job_name": str(cfg.get("job_name") or ""), + "agents": json.dumps([[str(a.get("name") or a.get("import_path") or ""), str(a.get("model_name") or "")] + for a in agents]), + "datasets": json.dumps([str(d.get("name") or d.get("path") or "") for d in cfg.get("datasets") or [] + if isinstance(d, dict)]), + "start": start or ""} + + +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 "").""" + got = _declared(cfg) + if got: + return got, "declared" + f = facts(job_dir, cfg, res) + if f is None: + return "", "pending" + return str(uuid.uuid5(NS_JOB, json.dumps(f, sort_keys=True, separators=(",", ":")))), "derived" diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index 6a4781ef..ab4ad58f 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -26,6 +26,7 @@ import shutil import os import re +import uuid from datetime import datetime, timezone from typing import Dict, List, Optional @@ -572,6 +573,34 @@ def write_trial(trial_dir: str, *, job: str, bench: dict, other: dict, model: st return res +def job_uuid(job_dir: str, *, benchmark: str, plugged: str, model: str, dataset: str) -> Optional[str]: + """The identity a job already in ``job_dir`` keeps when the run is the same job: its + ``config.json`` names the same benchmark, plugged agent or capability, model and dataset. + The uid it is read under (``nullius.runs.uid``): its declared ``standard.uuid`` when that + is a UUID, else the derived one, so what was recorded against it still finds it. None + otherwise: another job under the same name is a job of its own.""" + from nullius.runs import uid as job_uid + try: + with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as f: + old = json.load(f) + except (OSError, ValueError): + return None + if not isinstance(old, dict): + return None + std = old.get("standard") if isinstance(old.get("standard"), dict) else {} + agents = [a for a in old.get("agents") or [] if isinstance(a, dict)] + datasets = [d for d in old.get("datasets") or [] if isinstance(d, dict)] + if (std.get("benchmark"), std.get("plugged"), (agents[0] if agents else {}).get("model_name"), + (datasets[0] if datasets else {}).get("name")) != (benchmark, plugged, model, dataset): + return None + try: + with open(os.path.join(job_dir, "result.json"), encoding="utf-8") as f: + res = json.load(f) + except (OSError, ValueError): + res = {} + return job_uid.of(job_dir, old, res if isinstance(res, dict) else {})[0] or None + + def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str, provider: str, dataset: str, units: List[str], concurrency: int, granted: bool, judge: str = "", backend: str = "local", image: str = "", boat_size: str = "", options: Optional[dict] = None, launch: str = "", shard: Optional[dict] = None, repeat: int = 1, @@ -603,9 +632,13 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str (``--served-by``), said only for a run that pinned them. ``exchanges`` and ``exchanges_max_mb``: what each unit's relay kept of its agent's calls (``run --exchanges``) and its bound in MB, said for - every run that gives them.""" + every run that gives them. + ``uuid``: the job's identity, made once; a run resumed into the same + folder keeps the one already written when it is the same job (``job_uuid``).""" + uid = job_uuid(job_dir, benchmark=bench["key"], plugged=other.get("_ref") or other["key"], model=model, + dataset=f"{bench['key']}/{dataset}") or str(uuid.uuid4()) ondisk.write_whole(os.path.join(job_dir, "config.json"), json.dumps({"job_name": job, "runner": "standard", "runner_label": "Nullius", - "standard": {"benchmark": bench["key"], **_version(bench), "plugged": other.get("_ref") or other["key"], "kind": other["_kind"], "provider": provider, + "standard": {"uuid": uid, "benchmark": bench["key"], **_version(bench), "plugged": other.get("_ref") or other["key"], "kind": other["_kind"], "provider": provider, "needs": bench["needs"], "permissions_granted": granted, "unsandboxed": granted and backend == "local", "backend": backend, **({"image": image} if image else {}), **({"boat_size": boat_size} if boat_size else {}), diff --git a/app/nullius/standard/runner/merge.py b/app/nullius/standard/runner/merge.py index 1f4b49a9..b6117862 100644 --- a/app/nullius/standard/runner/merge.py +++ b/app/nullius/standard/runner/merge.py @@ -34,8 +34,10 @@ import json import os import shutil +import uuid from typing import Dict, List, Optional +from nullius import ondisk from nullius.standard.runner import job from nullius.standard.contract.names import backend as backend_name @@ -317,8 +319,6 @@ def merge(job_dirs: List[str], out: str, force: bool = False) -> dict: results.append(_read(os.path.join(out, t, "result.json"))) summary = result_of(shards, results) planned = summary["n_total_trials"] - with open(os.path.join(out, "result.json"), "w", encoding="utf-8") as f: - json.dump({"id": name, **summary, **({"served": who} if (who := _served(shards, results)) else {})}, f, indent=1) cfg = json.loads(json.dumps(shards[0]["config"])) cfg["job_name"] = name std = cfg.setdefault("standard", {}) @@ -326,6 +326,7 @@ def merge(job_dirs: List[str], out: str, force: bool = False) -> dict: own = len({json.dumps(_at(s["config"], ("standard", "benchmark_options")), sort_keys=True) for s in shards}) > 1 if own: std.pop("benchmark_options", None) + std["uuid"] = str(uuid.uuid4()) # a merge is a job of its own, not shard 0 std["merged_from"] = [{"job": s["name"], "trials": len(s["trials"]), **({"shard": f"{s['shard'].get('index')}/{s['shard'].get('of')}"} if s["shard"] else {}), **({"benchmark_options": _at(s["config"], ("standard", "benchmark_options")) or {}} if own else {}), @@ -338,7 +339,9 @@ def merge(job_dirs: List[str], out: str, force: bool = False) -> dict: std["merged_despite"] = got["differ"] if cfg.get("datasets"): cfg["datasets"][0]["n_tasks"] = planned - with open(os.path.join(out, "config.json"), "w", encoding="utf-8") as f: - json.dump(cfg, f, indent=2) + # the config first, whole: a reader never sees the merged result without the merge's own uuid + ondisk.write_whole(os.path.join(out, "config.json"), json.dumps(cfg, indent=2)) + ondisk.write_whole(os.path.join(out, "result.json"), + json.dumps({"id": name, **summary, **({"served": who} if (who := _served(shards, results)) else {})}, indent=1)) return {"out": out, "trials": len(results), "merged_from": [s["name"] for s in shards], "notes": got["notes"], "missing": got["missing"]} diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 1a59d3d8..5479fd3a 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -17,7 +17,8 @@ and trajectory.json under it, with size and mtime), never by time: a run still going changes its files, the signature moves, the job is parsed again. A cached job that was parsed by an older version of ``parse`` is refreshed -too — the signature carries ``parse.SCHEMA`` so a change there invalidates. +too — the signature carries ``parse.SCHEMA`` and the Job and Trial field names, so a +change of either invalidates. A job that has ended (``_ended``) is checked by its *head* alone: its own result.json and config.json, and its folder, whose mtime moves when a trial folder comes or @@ -276,6 +277,13 @@ def _drop(ws: Workspace, index: dict, job_dir: str, keep=()) -> None: pass +def _schema() -> str: + """The cached shape: both SCHEMAs and the Job and Trial field names, so a cache written + with another field set is never current, even when two changes bumped SCHEMA alike.""" + shape = hashlib.sha256(" ".join(_JOB_FIELDS + ("/",) + _TRIAL_FIELDS).encode()).hexdigest()[:12] + return f"schema={SCHEMA}/{parse.SCHEMA}/{shape}" + + def signature(job_dir: str) -> str: """What the parse of *job_dir* depends on: the files it reads, by size and mtime.""" @@ -286,7 +294,7 @@ def _signatures(job_dir: str) -> tuple: """(the job's signature, {trial folder: its own part of it}): a trial whose part is unchanged parses the same, so a running job re-reads only the trials that moved (load_job), not all of them at each one that ends.""" - parts = [f"schema={SCHEMA}/{parse.SCHEMA}"] + parts = [_schema()] trials = {} try: names = sorted(os.listdir(job_dir)) @@ -318,7 +326,7 @@ def stat(path): def _head(job_dir: str) -> str: """What an ended job's parse can change by without a trial changing in place: its own records, and its folder's mtime (a trial folder added or removed).""" - parts = [f"schema={SCHEMA}/{parse.SCHEMA}"] + parts = [_schema()] for path in (job_dir, os.path.join(job_dir, "result.json"), os.path.join(job_dir, "config.json")): try: st = os.stat(path) diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index dc95d5c9..3d6c8670 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -422,6 +422,8 @@ "total_input_tokens", "total_output_tokens", "trials", + "uid", + "uid_source", "vocab" ], "Trial": [ @@ -451,6 +453,7 @@ "is_infra", "is_regression", "job_id", + "key", "model_name", "n_cache_tokens", "n_input_tokens", diff --git a/app/tests/test_job_uid.py b/app/tests/test_job_uid.py new file mode 100644 index 00000000..271f8aa0 --- /dev/null +++ b/app/tests/test_job_uid.py @@ -0,0 +1,186 @@ +"""A job's identity (Job.uid): the same wherever its folder is copied or +moved, apart for two jobs of one name, made once by the standard runner, +kept by a run resumed into its folder and new for a merge.""" +from __future__ import annotations + +import json +import os +import shutil +import tempfile +import unittest + +from nullius import workspace +from nullius.runs import parse +from nullius.standard.runner import job + +HERE = os.path.dirname(os.path.abspath(__file__)) +HARBOR = os.path.join(HERE, "fixtures", "harbor-jobs", "liveboard-oracle-x4") +BENCH = {"key": "fakebench", "_ref": "fakebench", "needs": ["agent.workspace/v1"], "units": {"noun": "task", "nouns": "tasks"}} +AGENT = {"key": "fake", "_kind": "agent", "_ref": "fake"} + + +def read(path): + with open(path) as f: + return json.load(f) + + +def write(path, data): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as f: + json.dump(data, f) + + +class JobUid(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="nullius-uid-") + self.addCleanup(shutil.rmtree, self.tmp, True) + + def config(self, d, name="run", model="m", dataset="all", other=AGENT): + os.makedirs(d, exist_ok=True) + job.write_config(d, job=name, bench=BENCH, other=other, model=model, provider="openai", dataset=dataset, + units=["a"], concurrency=1, granted=True) + return read(os.path.join(d, "config.json"))["standard"]["uuid"] + + def older_standard(self, root, started): + """A standard job written before jobs carried a uuid: one trial, its result.""" + d = os.path.join(root, "run") + write(os.path.join(d, "config.json"), {"job_name": "run", "runner": "standard", + "standard": {"benchmark": "fakebench", "plugged": "fake"}, + "agents": [{"name": "fake", "model_name": "m"}]}) + write(os.path.join(d, "result.json"), {"id": "run", "started_at": started}) + write(os.path.join(d, "a__u0000", "result.json"), {"task_name": "a", "trial_name": "a__u0000"}) + return d + + def test_a_new_standard_job_declares_a_uuid_a_resume_into_its_folder_keeps(self): + d = os.path.join(self.tmp, "run") + first = self.config(d) + self.assertEqual(self.config(d), first) # the same --name, the same folder + self.assertNotEqual(self.config(os.path.join(self.tmp, "other")), first) + j = parse.parse_job(d) + self.assertEqual((j.uid, j.uid_source), (first, "declared")) + + def test_another_job_under_the_same_name_gets_a_uuid_of_its_own(self): + d = os.path.join(self.tmp, "run") + first = self.config(d) + for what, kw in (("model", {"model": "m2"}), ("dataset", {"dataset": "hard"}), + ("plugged", {"other": dict(AGENT, key="other", _ref="other")})): + with self.subTest(what): + self.assertNotEqual(self.config(d, **kw), first) + first = self.config(d) # back to the first job: a new one again + self.assertEqual(self.config(d), first) + + def test_resuming_a_job_from_before_uuids_declares_the_identity_it_was_read_under(self): + d = self.older_standard(self.tmp, "2026-01-01T00:00:00Z") + cfg = read(os.path.join(d, "config.json")) + write(os.path.join(d, "config.json"), dict(cfg, datasets=[{"name": "fakebench/all"}])) + before = parse.parse_job(d) + self.assertEqual(before.uid_source, "derived") + self.assertEqual(self.config(d), before.uid) + self.assertEqual((parse.parse_job(d).uid, parse.parse_job(d).uid_source), (before.uid, "declared")) + with self.subTest("another job under its name"): + other = self.older_standard(os.path.join(self.tmp, "b"), "2026-01-01T00:00:00Z") + derived = parse.parse_job(other).uid + self.assertNotEqual(self.config(other, model="m2"), derived) + + def test_a_harbor_jobs_identity_does_not_follow_the_feed(self): + d = shutil.copytree(HARBOR, os.path.join(self.tmp, "h", "liveboard-oracle-x4")) + feed = os.path.join(d, "events.jsonl") + if os.path.exists(feed): + os.remove(feed) + without = parse.parse_job(d).uid + with open(feed, "w") as f: + f.write(json.dumps({"event": "job.start", "ts": "2020-01-01T00:00:00Z"}) + "\n") + self.assertEqual(parse.parse_job(d).uid, without) + + def feed(self, d, ts, junk=b""): + with open(os.path.join(d, "events.jsonl"), "wb") as f: + f.write(junk + json.dumps({"event": "job.start", "ts": ts}).encode() + b"\n") + + def test_an_older_standard_job_is_pending_until_its_result_and_never_follows_the_feed(self): + with self.subTest("ended: a feed that appears or goes leaves it"): + d = self.older_standard(os.path.join(self.tmp, "ended"), "2026-01-01T00:00:00Z") + before = parse.parse_job(d).uid + self.feed(d, "2026-02-02T00:00:00Z") # a re-run in place, or a copy with its feed + self.assertEqual(parse.parse_job(d).uid, before) + with self.subTest("running or killed: pending, feed or not, until result.json, read through the cache"): + d = self.older_standard(os.path.join(self.tmp, "killed"), "2026-01-01T00:00:00Z") + ended = parse.parse_job(d).uid + res = read(os.path.join(d, "result.json")) + os.remove(os.path.join(d, "result.json")) + ws = workspace.create(os.path.join(self.tmp, "ws"), [os.path.dirname(d)], label="w") + for junk in (None, b"\xff\xfe not text\n"): + if junk is not None: + self.feed(d, "2026-01-01T00:00:01Z", junk=junk) + for j in (parse.parse_job(d), workspace.load_job(ws, d)[0]): + self.assertEqual((j.uid, j.uid_source), ("", "pending")) + write(os.path.join(d, "result.json"), res) + j = workspace.load_job(ws, d)[0] + self.assertEqual((j.uid, j.uid_source), (ended, "derived")) + + def test_a_resumed_job_whose_uuid_is_not_one_keeps_the_identity_it_was_read_under(self): + d = self.older_standard(self.tmp, "2026-01-01T00:00:00Z") + cfg = read(os.path.join(d, "config.json")) + write(os.path.join(d, "config.json"), dict(cfg, standard=dict(cfg["standard"], uuid="run-1"), + datasets=[{"name": "fakebench/all"}])) + read_as = parse.parse_job(d) + self.assertEqual(read_as.uid_source, "derived") + self.assertEqual(self.config(d), read_as.uid) + self.assertEqual((parse.parse_job(d).uid, parse.parse_job(d).uid_source), (read_as.uid, "declared")) + + def test_a_config_that_cannot_be_written_leaves_the_one_before_whole(self): + d = os.path.join(self.tmp, "run") + first = self.config(d) + with self.assertRaises(TypeError): + job.write_config(d, job="run", bench=BENCH, other=AGENT, model="m", provider="openai", dataset="all", + units=["a"], concurrency=1, granted=True, options={"x": object()}) + self.assertEqual(read(os.path.join(d, "config.json"))["standard"]["uuid"], first) + self.assertEqual(os.listdir(d), ["config.json"]) + + def test_two_jobs_alike_but_for_their_folder_or_their_start_are_two_jobs(self): + for name, make in (("harbor", lambda root: shutil.copytree(HARBOR, os.path.join(root, "liveboard-oracle-x4"))), + ("older standard", lambda root: self.older_standard(root, "2026-01-01T00:00:00Z"))): + with self.subTest(name): + src = make(os.path.join(self.tmp, name, "a")) + renamed = shutil.copytree(src, os.path.join(self.tmp, name, "b", "renamed")) # its files untouched + self.assertNotEqual(parse.parse_job(renamed).uid, parse.parse_job(src).uid) + later = shutil.copytree(src, os.path.join(self.tmp, name, "c", os.path.basename(src))) + res = read(os.path.join(later, "result.json")) + write(os.path.join(later, "result.json"), dict(res, started_at="2026-03-03T00:00:00Z")) + if os.path.exists(os.path.join(later, "events.jsonl")): + os.remove(os.path.join(later, "events.jsonl")) + self.assertNotEqual(parse.parse_job(later).uid, parse.parse_job(src).uid) + + def test_a_copy_or_a_move_keeps_the_identity(self): + for name, make in (("harbor", lambda root: shutil.copytree(HARBOR, os.path.join(root, "liveboard-oracle-x4"))), + ("older standard", lambda root: self.older_standard(root, "2026-01-01T00:00:00Z"))): + with self.subTest(name): + base = os.path.join(self.tmp, name) + src = make(os.path.join(base, "a")) + j = parse.parse_job(src) + self.assertEqual(j.uid_source, "derived") + copy = shutil.copytree(src, os.path.join(base, "b", os.path.basename(src))) + moved = os.path.join(base, "c", os.path.basename(src)) + os.makedirs(os.path.dirname(moved)) + os.rename(src, moved) + self.assertEqual({parse.parse_job(copy).uid, parse.parse_job(moved).uid}, {j.uid}) + + def test_a_job_with_no_trial_and_no_start_is_pending(self): + d = os.path.join(self.tmp, "preparing") + write(os.path.join(d, "config.json"), {"job_name": "preparing", "agents": [{"name": "oracle"}]}) + j = parse.parse_job(d) + self.assertEqual((j.uid, j.uid_source), ("", "pending")) + + def test_a_try_is_keyed_by_its_attempt(self): + d = self.older_standard(self.tmp, "2026-01-01T00:00:00Z") + t = parse.parse_job(d).trials[0] + cfg = read(os.path.join(d, "config.json")) + cfg["standard"]["retries"] = 1 + write(os.path.join(d, "config.json"), cfg) + write(os.path.join(d, "retried", "a__u0000.try-1", "result.json"), {"task_name": "a", "trial_name": "a__u0000"}) + write(t.dir + "/result.json", {"task_name": "a", "trial_name": "a__u0000", "standard": {"retries": 1}}) + t = parse.parse_job(d).trials[0] + self.assertEqual([(n, x.key) for n, x in parse.tries(t)], [(1, "a__u0000"), (2, "a__u0000")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_standard_shard.py b/app/tests/test_standard_shard.py index 842c1afb..d2b8120b 100644 --- a/app/tests/test_standard_shard.py +++ b/app/tests/test_standard_shard.py @@ -123,6 +123,8 @@ def test_the_merged_job_reads_as_one_run_of_every_trial(self): self.assertEqual(got["notes"], []) j = parse.parse_job(got["out"]) self.assertEqual((j.job_id, j.n_tasks, j.n_total_trials, len(j.trials)), ("run", 10, 10, 10)) + # a merge is a job of its own: a new identity, none of its shards' + self.assertEqual((j.uid_source, len({parse.parse_job(d).uid for d in dirs} | {j.uid})), ("declared", 4)) self.assertEqual(sorted(t.trial_name for t in j.trials), sorted(f"t-{i}__u{i:04d}" for i in range(10))) self.assertEqual(sum(1 for t in j.trials if t.reward == 1.0), 5) # the odd ones pass; t-4 ended in an error self.assertEqual(j.n_errored_trials, 1) @@ -140,6 +142,19 @@ def test_the_merged_job_reads_as_one_run_of_every_trial(self): self.assertTrue(os.path.samefile(os.path.join(src, "workspace", "solution.py"), os.path.join(got["out"], "t-1__u0001", "workspace", "solution.py"))) + def test_the_merged_jobs_config_is_whole_before_its_result_is_written(self): + seen = [] + real = merge.ondisk.write_whole + + def write_whole(path, data, mode=None): + if os.path.basename(path) == "result.json" and os.path.dirname(path) == out: + seen.append(read(os.path.join(out, "config.json"))["standard"].get("uuid")) + return real(path, data, mode) + out = os.path.join(self.tmp, "out", "run") + with patch.object(merge.ondisk, "write_whole", write_whole): + merge.merge(self.shards(), out) + self.assertEqual(seen, [read(os.path.join(out, "config.json"))["standard"]["uuid"]]) + def retried(self, dirs, retries=1): """The launch allowed each attempt one retry, and the first shard's first attempt took it: its try before kept under retried/, as a run leaves it. The attempt's name.""" diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index 9280e63b..ad853395 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -237,6 +237,15 @@ def test_schema_bump_invalidates(self): workspace.SCHEMA = old self.assertFalse(from_cache) + def test_a_cache_of_another_field_set_is_not_current(self): + """Two changes that each add a field and bump parse.SCHEMA to one value: a cache + written by one is not read as current by the other, whose new field would read blank.""" + with patch.object(workspace, "_JOB_FIELDS", tuple(n for n in workspace._JOB_FIELDS if n != "uid")): + workspace.load_job(self.ws, self.job_dir) + job, from_cache = workspace.load_job(self.ws, self.job_dir) + self.assertFalse(from_cache) + self.assertEqual(job.uid, parse.parse_job(self.job_dir).uid) + def test_two_requests_writing_the_same_cache_at_once_both_return(self): """The job page and its /live poll both re-parse a job whose files keep changing, and both wrote the cache through one shared `.json.tmp`: diff --git a/docs/standard.md b/docs/standard.md index 012654a9..be354007 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -365,7 +365,7 @@ N machines are N runs of the same command, each with `--shard I/N`, and one merg | Shards by the unit's id | `sha256(unit id) mod N`; changing N moves most units. Order: the driver's `units`, the units `--units FILE` lists, the shard, then `--limit` (`--shard 1/2 --limit 6` is the first six units of shard 1) | | A unit keeps its place | `u0042` is the 43rd unit of the whole dataset in every shard | | One launch | Each shard's `config.json` records `standard.shard` (`index`, `of`, `units_total`, `partition`, `planned`, `limit`) and `standard.launch` (`--launch`, else the UTC day, benchmark, agent or capability and model). With `--units`, `units_total` counts the listed units. The shards' lists hold the same units; a list's file name, comments and sha256 may differ from shard to shard | -| `cli merge JOB_DIR... -o OUT` | One job: trials hard-linked, `result.json` recomputed, `config.json` with `merged_from`. Shards that differ in launch, version, dataset, agent, model, serving providers, backend or N are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. | +| `cli merge JOB_DIR... -o OUT` | One job: trials hard-linked, `result.json` recomputed, `config.json` with `merged_from` and a `standard.uuid` of its own. Shards that differ in launch, version, dataset, agent, model, serving providers, backend or N are refused unless `--force`. Shards whose lists hold different units, and two trials of one unit, are refused always. | | `cli prove --shard I/N` | The controls and the leak check on that shard's units; each record says `shard` | | Different options per shard | Shards of one launch may differ in `--bench-option` (a unit that needs a service its machine serves); the merged config keeps each shard's in `merged_from` | | `cli prove --job nop=MERGED` | Checks a merged launch of a control against its bound instead of running it. The job and each of its trials name that benchmark, version, control and job; each unit of the dataset has one trial, scored 0 to 1; the units check passes. `--dataset` named, no `--limit` or `--shard`. The record names the job and its options |