cataflow-bench / sync.py
angelo-piletti's picture
fix(sync): the leaderboard reads declarations from the agent's results root
f3aee1c
Raw History Blame Contribute Delete
11.8 kB
"""Publishing tasks from the agent repository's ``data/tasks`` into this dataset.
For every task directory with a plan the agent's schema accepts:
* ``tasks/<name>/`` gets the manifest and exactly the files the manifest names, nothing
else (no results, no scorer cache, no plan);
* ``truth/<name>/`` gets the plan and, when there is one, the recipe;
* ``tasks.jsonl`` gets the task's row: what it is, how big, and the hashes of its inputs
and its truth;
* the card's leaderboard is written again from the agent's benchmark summaries
(``cataflow_agent.benchmark.leaderboard``, shared with ``cataflow-bench-runs``).
A task published before is compared by hash: unchanged tasks are left alone, changed ones
are refused unless ``--force`` is given, since a run that cites the task by hash must keep
finding it. A file the manifest names that is missing fails the task; a file lying in the
source that the manifest does not name is reported and not published.
uv run python sync.py [--source ../agent/data/tasks] [--summaries ../agent/benchmarks/results]
[--only PATTERN]... [--force] [--dry-run]
"""
from __future__ import annotations
import argparse
import fnmatch
import hashlib
import json
import shutil
import sys
from collections.abc import Iterable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from cataflow_agent.benchmark import leaderboard
from cataflow_generator.plan import TaskPlan
from pydantic import ValidationError
MANIFEST = "task.json"
PLAN = "plan.json"
RECIPE = "recipe.json"
TASKS_DIR = "tasks"
TRUTH_DIR = "truth"
INDEX = "tasks.jsonl"
FILE_KEYS = ("files", "referenceImages")
"""The manifest keys whose values name files, wherever they sit."""
NOT_INPUTS = {PLAN, RECIPE, "oracle.json", "results", "images", "__pycache__"}
"""What lies in a source task directory besides the inputs: truth, verdicts, run leftovers."""
DEFAULT_SOURCE = Path("../agent/data/tasks")
DEFAULT_SUMMARIES = Path("../agent/benchmarks/results")
DEFAULT_RESULTS = Path("../agent/results")
@dataclass
class Outcome:
name: str
state: str
"""``new``, ``unchanged``, ``changed``, ``refused``, ``skipped``, ``failed``."""
detail: str = ""
row: dict[str, Any] | None = None
unreferenced: list[str] = field(default_factory=list)
def referenced_files(manifest: Any) -> list[str]:
"""Every file the manifest names, under any ``files`` or ``referenceImages`` key at any
depth: sorted, each once."""
found: set[str] = set()
def walk(node: Any) -> None:
if isinstance(node, dict):
for key, value in node.items():
if key in FILE_KEYS and isinstance(value, list):
found.update(v for v in value if isinstance(v, str))
walk(value)
elif isinstance(node, list):
for value in node:
walk(value)
walk(manifest)
return sorted(found)
def hash_files(root: Path, files: Iterable[str]) -> str:
"""One hash over the named files: their paths and their bytes, in path order."""
digest = hashlib.sha256()
for name in sorted(set(files)):
digest.update(name.encode("utf-8"))
digest.update(b"\0")
digest.update(hashlib.sha256((root / name).read_bytes()).hexdigest().encode("ascii"))
digest.update(b"\n")
return digest.hexdigest()
def describe(plan: TaskPlan, inputs: list[str], root: Path, truth: list[str]) -> dict[str, Any]:
"""The task's row in the index."""
batches = plan.batches
return {
"name": plan.name,
"store": plan.store,
"split": plan.split,
"generator_version": plan.generator_version,
"seed": plan.seed,
"batches": len(batches),
"cards": sum(len(b.cards) for b in batches),
"documents": sum(len(b.documents) for b in batches),
"expected_products": sum(len(b.expected) for b in batches),
"hidden_answers": sum(len(b.hidden_answers) for b in batches),
"difficulty": max((b.difficulty for b in batches), default=0),
"answer_languages": sorted({b.answer_language for b in batches if b.answer_language}),
"scenarios": sorted({s for b in batches for s in b.scenarios}),
"files": len(inputs),
"bytes": sum((root / f).stat().st_size for f in inputs),
"content_sha256": hash_files(root, inputs),
"truth_sha256": hash_files(root, truth),
}
def unreferenced_files(source: Path, inputs: set[str]) -> list[str]:
"""Files in the source that are neither inputs nor known non-inputs: something the
manifest forgot, or a leftover of a run written into the task's root."""
found: list[str] = []
for path in sorted(source.rglob("*")):
if not path.is_file():
continue
parts = path.relative_to(source).parts
if parts[0] in NOT_INPUTS or parts[0] == MANIFEST:
continue
name = "/".join(parts)
if name not in inputs:
found.append(name)
return found
def inspect(source: Path, previous: dict[str, Any] | None) -> Outcome:
"""What publishing this source directory would do, without doing it."""
name = source.name
if not (source / PLAN).is_file() or not (source / MANIFEST).is_file():
return Outcome(name, "skipped", "no plan.json or task.json")
try:
plan = TaskPlan.model_validate_json((source / PLAN).read_text(encoding="utf-8"))
except ValidationError as exc:
first = exc.errors()[0]
where = ".".join(str(p) for p in first["loc"])
return Outcome(name, "skipped", f"plan does not validate: {where}: {first['msg']}")
if plan.name != name:
return Outcome(name, "failed", f"plan is named {plan.name!r}, the directory {name!r}")
manifest = json.loads((source / MANIFEST).read_text(encoding="utf-8"))
inputs = referenced_files(manifest)
missing = [f for f in inputs if not (source / f).is_file()]
if missing:
return Outcome(name, "failed", f"the manifest names files that are missing: {missing}")
truth = [PLAN] + ([RECIPE] if (source / RECIPE).is_file() else [])
row = describe(plan, [MANIFEST, *inputs], source, truth)
outcome = Outcome(name, "new", row=row, unreferenced=unreferenced_files(source, set(inputs)))
if previous is not None:
same = (
previous.get("content_sha256") == row["content_sha256"]
and previous.get("truth_sha256") == row["truth_sha256"]
)
outcome.state = "unchanged" if same else "changed"
return outcome
def publish(source: Path, target: Path, outcome: Outcome) -> None:
"""Writes the task under ``tasks/`` and its truth under ``truth/``, replacing what was
there."""
assert outcome.row is not None
task_dir = target / TASKS_DIR / outcome.name
truth_dir = target / TRUTH_DIR / outcome.name
for place in (task_dir, truth_dir):
if place.exists():
shutil.rmtree(place)
manifest = json.loads((source / MANIFEST).read_text(encoding="utf-8"))
for name in [MANIFEST, *referenced_files(manifest)]:
_copy(source / name, task_dir / name)
for name in (PLAN, RECIPE):
if (source / name).is_file():
_copy(source / name, truth_dir / name)
def read_index(target: Path) -> dict[str, dict[str, Any]]:
path = target / INDEX
if not path.is_file():
return {}
rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]
return {row["name"]: row for row in rows}
def write_index(target: Path, rows: dict[str, dict[str, Any]]) -> None:
lines = [json.dumps(rows[name], ensure_ascii=False) for name in sorted(rows)]
(target / INDEX).write_text("\n".join(lines) + "\n", encoding="utf-8")
def sync(
source_root: Path,
target: Path,
*,
only: list[str] | None = None,
force: bool = False,
dry_run: bool = False,
) -> list[Outcome]:
"""Publishes every matching task; the outcomes, one per source directory."""
index = read_index(target)
outcomes: list[Outcome] = []
for source in sorted(p for p in source_root.iterdir() if p.is_dir()):
if only and not any(fnmatch.fnmatch(source.name, pattern) for pattern in only):
continue
outcome = inspect(source, index.get(source.name))
if outcome.state == "changed" and not force:
outcome.state = "refused"
outcome.detail = "inputs or truth changed since it was published; --force replaces it"
published = (target / TASKS_DIR / outcome.name / MANIFEST).is_file()
if outcome.state == "unchanged" and not published:
outcome.state = "new"
outcome.detail = "listed but not on disk"
if outcome.state in ("new", "changed") and not dry_run:
publish(source, target, outcome)
assert outcome.row is not None
index[outcome.name] = outcome.row
outcomes.append(outcome)
if not dry_run and any(o.state in ("new", "changed") for o in outcomes):
write_index(target, index)
return outcomes
def report(outcomes: list[Outcome]) -> None:
for o in outcomes:
line = f"{o.state:10} {o.name}"
if o.detail:
line += f" {o.detail}"
if o.row and o.state in ("new", "changed", "unchanged"):
line += f" ({o.row['files']} files, {o.row['bytes'] / 1e6:.1f} MB)"
print(line)
for name in o.unreferenced:
print(f"{'':10} {o.name}: not in the manifest, not published: {name}")
counts: dict[str, int] = {}
for o in outcomes:
counts[o.state] = counts.get(o.state, 0) + 1
print(", ".join(f"{n} {state}" for state, n in sorted(counts.items())))
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="cataflow-bench sync")
parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE, help="the agent's tasks")
parser.add_argument(
"--results",
type=Path,
default=DEFAULT_RESULTS,
help="the agent's runs (results/<label>/<task>/), for the leaderboard's declarations",
)
parser.add_argument("--target", type=Path, default=Path(__file__).parent, help="this dataset")
parser.add_argument("--only", action="append", default=[], help="task name patterns")
parser.add_argument(
"--summaries",
type=Path,
default=DEFAULT_SUMMARIES,
help="the agent's benchmark summaries, for the card's leaderboard",
)
parser.add_argument("--force", action="store_true", help="replace tasks whose inputs changed")
parser.add_argument("--dry-run", action="store_true", help="report, write nothing")
args = parser.parse_args(argv)
if not args.source.is_dir():
print(f"no such source: {args.source}", file=sys.stderr)
return 2
outcomes = sync(
args.source, args.target, only=args.only, force=args.force, dry_run=args.dry_run
)
report(outcomes)
found = leaderboard.benchmarks(args.summaries)
if not args.dry_run:
section = leaderboard.leaderboard(
args.summaries, read_index(args.target), results_root=args.results
)
changed = leaderboard.write(args.target / "README.md", section)
state = "updated" if changed else "unchanged"
print(f"leaderboard: {len(found)} benchmark(s); README {state}")
else:
print(f"leaderboard: {len(found)} benchmark(s) would be written to the README")
return 1 if any(o.state in ("refused", "failed") for o in outcomes) else 0
def _copy(src: Path, dst: Path) -> None:
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dst)
if __name__ == "__main__":
sys.exit(main())