# SPDX-License-Identifier: Apache-2.0 """Baseline and regression rule of the benchmark harness. A baseline summarises history records of the same code over several seeds (at least 5 for the real databases). For each dataset it keeps, per seed, the pass rate (passed / judged checks), and per check the seeds on which it passed. A new record regresses on a dataset when R1 a *calibrated* check fails: one that passed on every baseline seed (at least 3) and is judged in the new run. An exact check (an identity, or a scorecard item whose limit is 0) regresses on any failing seed; a statistical check (a distance under a positive limit) only when it fails on more than half of the new seeds, or R2 the mean pass rate over the new seeds (on the checks the baseline has) drops below the baseline mean by more than the run-to-run spread, spread = max(2 sd, 1 / judged checks): two standard deviations of the per-seed pass rates (a 95% band if the rates were normal), and never less than one check, or R3 a run errors, or a dataset the baseline has is missing from a full run, or R4 a tracked value (a `metric:` item: SyntheRela summaries, area pass rates, utility gap, attack values) moves the wrong way: its mean over the new seeds is worse than the baseline mean by more than max(0.02 x max(1, |baseline mean|), 2 sd of the baseline seeds) -- the "benchmark regression flag" of docs/acceptance-metrics.md. Cost values (CPU seconds, memory) depend on the machine and are only noted when they grow by more than 25%. A failed R1 statistical check is *marginal* when its value misses its limit by at most MARGIN (5%) of the limit. A marginal failure is reported as a warning, not a regression: such a miss is within the variation of the draws and of the machine (the 5% rule set by the owner on 2026-11-27). Exact checks (identities, limit 0), integrity items (fk_integrity, tree_cycles, goals) and privacy checks (the attack suite and the scorecard's disclosure items: dcr_ratio, exact_match_rate, text_rare_*) are never marginal: an identity holds or not, and privacy is judged strictly (privacy first). R4 keeps its own tolerance (the allowed drift below). Checks that failed on some baseline seed are "unstable": they count in R2 but cannot trigger R1, so a borderline statistical check flipping with the seed is not reported as a regression, while an identity or a check that always passed is. Five baseline seeds cannot show that a statistical check never fails: with about 1,300 of them, a few that passed five times by chance fail on one seed of another machine (BLAS and thread counts change the draws). A broken table fails on most seeds, which the majority rule still reports. The rule is a heuristic chosen for this harness, not a test with a stated level; docs/development/benchmarks.md explains the choice. """ from __future__ import annotations import math import re import statistics from collections import defaultdict from pathlib import Path MIN_SEEDS_CALIBRATED = 3 MARGIN = 0.05 # a failure within 5% of its limit is a warning, not a regression def error_summary(err: str, n: int = 300) -> str: """A run's error for a log line: its first line and, for a Python traceback, the exception (the last non-empty line), which a head of the text alone cuts off. A faulthandler dump (the memory watchdog's) lists the most recent call first, so its innermost frames are kept instead, each as file:line in function.""" text = str(err) if "Current thread" in text: frames = re.findall(r'File "([^"]+)", line (\d+) in (\S+)', text[text.index("Current thread"):]) if frames: where = " < ".join(f"{Path(f).name}:{ln} in {fn}" for f, ln, fn in frames[:6]) head = text[: text.index("Current thread")].strip() return ((head + " " if head else "") + where)[:n] lines = [x.strip() for x in text.splitlines() if x.strip()] if len(lines) <= 1: return text[:n] head, last = lines[0], lines[-1] return (head[: n // 3] + " ... " + last[: n - n // 3]) def _runs(records: list[dict]): for rec in records: for r in rec.get("runs", []): if "checks" in r: yield r def judged(r: dict) -> list[dict]: return [c for c in r.get("checks", []) if c.get("pass") is not None] def exact(c: dict) -> bool: """An identity (judged against the real value) or a scorecard item with limit 0.""" return "limit" not in c or not c["limit"] def tracked(r: dict) -> list[dict]: return [c for c in r.get("checks", []) if c.get("pass") is None and c.get("direction") and c.get("value") is not None] R4_FLOOR, COST_NOTE = 0.02, 0.25 # Scorecard items that measure disclosure (the item name after "|"): judged strictly, like the attack suite. PRIVACY_ITEMS = ("dcr_ratio", "exact_match_rate", "text_rare_exact_copies", "text_rare_ngram_copies", "text_rare_token_leaks") # Items that hold or not (referential integrity, acyclic trees, goals): a near miss is still a broken key, # so they are never marginal whatever their limit. EXACT_ITEMS = ("fk_integrity", "tree_cycles") def _item(check_id: str) -> str: return check_id.rsplit("|", 1)[-1] if "|" in check_id else "" def _privacy(check_id: str) -> bool: return (check_id.startswith(("privacy", "metric:privacy", "goal:privacy")) or _item(check_id) in PRIVACY_ITEMS) def _strict(check_id: str) -> bool: return check_id.startswith("goal:") or _item(check_id) in EXACT_ITEMS def _within(value: float, limit: float) -> bool: return abs(value - limit) <= MARGIN * abs(limit) + 1e-12 def marginal(c: dict) -> bool: """A failed statistical check whose value misses its limit by at most MARGIN of the limit.""" v, lim = c.get("value"), c.get("limit") if exact(c) or _privacy(c["id"]) or _strict(c["id"]): return False if not all(isinstance(x, (int, float)) and math.isfinite(x) for x in (v, lim)): return False return _within(float(v), float(lim)) def rate(r: dict) -> float: j = judged(r) return sum(c["pass"] for c in j) / len(j) if j else float("nan") def merge(old: dict, new: dict, keep: set[str]) -> dict: """The baseline `new` plus the entries of `old` for datasets that `new` does not cover (and that still exist: names in `keep`). The file-level lists (sources, relsynth, git, machines) describe every entry, so they become the union of both; `kept` names the entries carried over from `old`.""" carried = {k: v for k, v in old.get("datasets", {}).items() if k not in new["datasets"] and k in keep} if not carried: return new out = dict(new) out["sources"] = list(dict.fromkeys([*(old.get("sources") or []), *(new.get("sources") or [])])) for f in ("relsynth", "git", "machines"): out[f] = sorted({*(old.get(f) or []), *(new.get(f) or [])}, key=str) out["datasets"] = dict(sorted({**carried, **new["datasets"]}.items())) out["kept"] = sorted(carried) return out def build(records: list[dict], sources: list[str] | None = None) -> dict: """The regression baseline of bench records: per dataset, pass rates and judged checks over seeds.""" by_ds: dict = defaultdict(list) for r in _runs(records): by_ds[r["dataset"]].append(r) out = {"schema": 1, "sources": sources or [], "relsynth": sorted({rec.get("relsynth") for rec in records}), "git": sorted({(rec.get("git") or {}).get("sha", "")[:12] for rec in records}), "machines": sorted({(rec.get("machine") or {}).get("node", "") for rec in records}), "datasets": {}} for ds, runs in sorted(by_ds.items()): rates = [rate(r) for r in runs] ok = [x for x in rates if not math.isnan(x)] # a run without verdicts (an error) counts under R3 n_judged = statistics.median(len(judged(r)) for r in runs) or 1 sd = statistics.stdev(ok) if len(ok) > 1 else 0.0 per_check: dict = defaultdict(lambda: {"passed": 0, "judged": 0, "failed_seeds": []}) for r in runs: for c in judged(r): pc = per_check[c["id"]] pc["judged"] += 1 if c["pass"]: pc["passed"] += 1 else: pc["failed_seeds"].append(r.get("seed")) out["datasets"][ds] = { "seeds": [r.get("seed") for r in runs], "pass_rates": [None if math.isnan(x) else round(x, 6) for x in rates], "passed": [sum(c["pass"] for c in judged(r)) for r in runs], "judged": [len(judged(r)) for r in runs], "mean": round(statistics.fmean(ok), 6) if ok else None, "sd": round(sd, 6), "spread": round(max(2 * sd, 1 / n_judged), 6), "seconds": [r.get("seconds") for r in runs], "checks": {k: {"passed": v["passed"], "judged": v["judged"], "calibrated": v["passed"] == v["judged"] >= MIN_SEEDS_CALIBRATED or (ds == "fake" and v["passed"] == v["judged"] >= 1), **({"failed_seeds": v["failed_seeds"]} if v["failed_seeds"] else {})} for k, v in sorted(per_check.items())}, "errors": sum(1 for r in runs if r.get("error"))} vals: dict = defaultdict(list) meta: dict = {} for r in runs: for c in tracked(r): vals[c["id"]].append(float(c["value"])) meta[c["id"]] = (c["direction"], c.get("kind")) if vals: out["datasets"][ds]["tracked"] = { k: {"mean": round(statistics.fmean(v), 6), "sd": round(statistics.stdev(v), 6) if len(v) > 1 else 0.0, "n": len(v), "direction": meta[k][0], **({"kind": meta[k][1]} if meta[k][1] else {})} for k, v in sorted(vals.items())} return out def drift(b: dict, rs: list[dict]) -> tuple[list[str], list[str]]: """R4: tracked values whose new mean is worse than the baseline's beyond the spread.""" regs, notes = [], [] vals: dict = defaultdict(list) for r in rs: for c in tracked(r): vals[c["id"]].append(float(c["value"])) for k, v in sorted(vals.items()): bt = (b.get("tracked") or {}).get(k) if not bt: continue sign = 1 if bt["direction"] == "lower" else -1 worse = sign * (statistics.fmean(v) - bt["mean"]) if bt.get("kind") == "cost": if worse > COST_NOTE * abs(bt["mean"]): notes.append(f"cost {k}: {statistics.fmean(v):.1f} against {bt['mean']:.1f} in the baseline") continue allowed = max(R4_FLOOR * max(1.0, abs(bt["mean"])), 2 * bt["sd"]) if worse > allowed + 1e-12: regs.append(f"R4 {k}: mean {statistics.fmean(v):.4f} against baseline {bt['mean']:.4f} " f"({'lower' if sign > 0 else 'higher'} is better; allowed drift {allowed:.4f})") return regs, notes def accepted_reason(accepted: dict | None, ds: str, check_id: str) -> str | None: """The reason the owner gave for accepting drift on this check of dataset ds, if any.""" for pat, why in (accepted or {}).get(ds, ()): if re.search(pat, check_id): return why return None def compare(baseline: dict, record: dict, full: bool = False, expected: set | None = None, accepted: dict | None = None) -> tuple[list[str], list[str], dict]: """(regressions, notes, per-dataset summary) of a record against a baseline; with `full`, every dataset of the baseline (or of `expected`, the datasets of the tiers that ran) must have run. `accepted` ({dataset: [(check id pattern, reason)]}) turns matching R1/R4 items into notes that give the reason.""" regressions, notes, summary = [], [], {} runs: dict = defaultdict(list) for r in record.get("runs", []): if "skipped" in r: notes.append(f"{r['dataset']}: skipped ({r['skipped']})") continue if r.get("private"): notes.append(f"{r['dataset']} seed {r.get('seed')}: private result, not available here") continue runs[r["dataset"]].append(r) for ds, rs in sorted(runs.items()): b = baseline["datasets"].get(ds) for r in rs: if r.get("error"): regressions.append(f"R3 {ds} seed {r.get('seed')}: run failed: {error_summary(r['error'], 400)}") if b is None: notes.append(f"{ds}: not in the baseline; recorded only") continue # the pass rate over the checks the baseline knows: a new kind of check (a new suite) # enters R2 only once a baseline that has it is built known = set(b["checks"]) rates = [rate({"checks": [c for c in r["checks"] if c["id"] in known]}) for r in rs if r.get("checks")] mean = statistics.fmean(rates) if rates else float("nan") summary[ds] = {"seeds": [r.get("seed") for r in rs], "mean": round(mean, 6), "baseline_mean": b["mean"], "spread": b["spread"], "passed": [sum(c["pass"] for c in judged(r)) for r in rs], "judged": [len(judged(r)) for r in rs]} if rates and b["mean"] is not None and mean < b["mean"] - b["spread"] - 1e-12: regressions.append(f"R2 {ds}: mean pass rate {mean:.4f} < baseline {b['mean']:.4f} - spread {b['spread']:.4f}") reg4, note4 = drift(b, rs) for x in reg4: why = accepted_reason(accepted, ds, x[3:x.index(": mean ")]) if why: notes.append(f"{ds} accepted drift ({why}): {x[3:]}") else: regressions.append(x.replace("R4 ", f"R4 {ds} ", 1)) notes += [f"{ds} {x}" for x in note4] n_seeds = sum(1 for r in rs if r.get("checks")) failed_on: dict = defaultdict(int) for r in rs: for c in judged(r): failed_on[c["id"]] += not c["pass"] for r in rs: seen = set() for c in judged(r): seen.add(c["id"]) bc = b["checks"].get(c["id"]) if bc and bc["calibrated"] and not c["pass"] and (exact(c) or 2 * failed_on[c["id"]] > n_seeds): v = f" (value {c.get('value')}, limit {c.get('limit')}, real {c.get('real')})" why = accepted_reason(accepted, ds, c["id"]) if why: notes.append(f"{ds} seed {r.get('seed')}: accepted drift ({why}): {c['id']}{v}") elif marginal(c): notes.append(f"warning (marginal, within 5%): R1 {ds} seed {r.get('seed')}: {c['id']}{v}") else: regressions.append(f"R1 {ds} seed {r.get('seed')}: calibrated check failed: {c['id']}{v}") elif bc and bc["calibrated"] and not c["pass"]: notes.append(f"{ds} seed {r.get('seed')}: statistical check {c['id']} failed on " f"{failed_on[c['id']]} of {n_seeds} seeds (value {c.get('value')}, limit {c.get('limit')})") gone = [k for k, v in b["checks"].items() if v["calibrated"] and k not in seen] if gone and r.get("checks"): notes.append(f"{ds} seed {r.get('seed')}: {len(gone)} calibrated check(s) not reported, e.g. {gone[0]}") if full: # a dataset of the tiers that ran must have run even when the baseline does not have it yet: # a job stopped at the runner's time limit leaves a record without its runs for ds in sorted(set(baseline["datasets"]) | (expected or set())): if expected is not None and ds not in expected: continue if ds not in runs and not any(n.startswith(f"{ds}: skipped") or n.startswith(f"{ds} seed") for n in notes): where = "in the baseline" if ds in baseline["datasets"] else "in the tier" regressions.append(f"R3 {ds}: {where} but not run") return regressions, notes, summary def report(regressions: list[str], notes: list[str], summary: dict) -> str: lines = ["## Benchmark comparison", "", "| Dataset | Seeds | Passed / judged | Mean pass rate | Baseline mean | Spread |", "|---|---|---|---|---|---|"] for ds, s in summary.items(): pj = ", ".join(f"{p}/{j}" for p, j in zip(s["passed"], s["judged"])) lines.append(f"| {ds} | {', '.join(map(str, s['seeds']))} | {pj} | {s['mean']:.4f} | {s['baseline_mean']:.4f} | " f"{s['spread']:.4f} |") lines += ["", f"**{'REGRESSION' if regressions else 'No regression'}**", ""] lines += [f"- {x}" for x in regressions] warns = [x for x in notes if x.startswith("warning")] if warns: lines += ["", f"Warnings ({len(warns)}, marginal misses within 5% of the limit):", ""] + [f"- {x}" for x in warns] rest = [x for x in notes if not x.startswith("warning")] if rest: lines += ["", "Notes:", ""] + [f"- {x}" for x in rest] return "\n".join(lines) + "\n" def load(paths: list[str | Path]) -> list[dict]: from .runner import load_record out = [] for p in paths: p = Path(p) for f in sorted(p.glob("*.json")) if p.is_dir() else [p]: out.append(load_record(f)) return out