Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion app/nullius/runs/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 —
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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


Expand Down
87 changes: 87 additions & 0 deletions app/nullius/runs/uid.py
Original file line number Diff line number Diff line change
@@ -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"
37 changes: 35 additions & 2 deletions app/nullius/standard/runner/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import shutil
import os
import re
import uuid
from datetime import datetime, timezone
from typing import Dict, List, Optional

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 {}),
Expand Down
11 changes: 7 additions & 4 deletions app/nullius/standard/runner/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -317,15 +319,14 @@ 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", {})
std.pop("shard", None)
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 {}),
Expand All @@ -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"]}
14 changes: 11 additions & 3 deletions app/nullius/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand All @@ -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))
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions app/tests/field_contract.json
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,8 @@
"total_input_tokens",
"total_output_tokens",
"trials",
"uid",
"uid_source",
"vocab"
],
"Trial": [
Expand Down Expand Up @@ -451,6 +453,7 @@
"is_infra",
"is_regression",
"job_id",
"key",
"model_name",
"n_cache_tokens",
"n_input_tokens",
Expand Down
Loading
Loading