"""Aggregate Phase-4 :class:`RunRecord` JSONs into per-task tables. Reads one or more ``RunRecord``-list JSON files (the canonical artefact written by :mod:`experiments.run_all`), validates each via Pydantic, and emits a per-task pandas DataFrame keyed by ``[method_id, metric_name, value, ci_lo, ci_hi, n_boot]``. Compared to the legacy aggregator (which merged per-family `_results.json` dicts), this module: 1. Accepts an input glob (``--input``) defaulting to ``experiments/results/canon_*.json``. 2. Round-trips JSON through ``pydantic.TypeAdapter[list[RunRecord]]``. 3. Skips records with ``status != "ok"`` (footnote count printed). 4. Migrates any ``schema_version=1`` records via :func:`tools.migrate_results._migrate_one` before validation. 5. Groups by ``(task, method_id, granularity, seed)`` and emits one DataFrame per task with one row per ``(method, metric)`` pair. CLI:: python -m projects.agent_builder.scripts.whatif_bench.experiments.aggregate_results \\ --input 'experiments/results/canon_*.json' \\ --output experiments/paper_artifacts/aggregate.parquet """ from __future__ import annotations import argparse import glob import json import logging from collections import defaultdict from pathlib import Path from typing import Any import pandas as pd import pydantic from .. import config from ..macrolens import RunRecord from ..tools.migrate_results import _migrate_one logger = logging.getLogger(__name__) _TASK_ORDER: tuple[str, ...] = ("T1", "T2", "T3", "T4", "T5", "T6", "T7") def _panel_method_ids() -> tuple[set[str], set[str]]: """Return ``(panel_methods, ablation_methods)`` as id sets. Allow-list source of truth: only ``method_id``s in :data:`experiments.panel.ALL_METHODS` (the 19 canonical panel methods) plus the deferred FT slot (``"scout_ft"``, Family-7) are surfaced in aggregation. Anything else (stale ``gpt_oss_120b``, ``gemma4``, etc.) is invisible to the aggregator. The ablation allow-list is :data:`panel.ABLATION_MODEL_IDS` (``gpt51``, ``gemini3_flash``) ∪ ``{"lightgbm"}`` (Phase 2.1) ∪ ``{"scout_ft"}`` (Phase 3.1). """ from .panel import ABLATION_MODEL_IDS, ALL_METHODS as _PANEL_METHODS panel = {m.id for m in _PANEL_METHODS} panel.add("scout_ft") # deferred Family-7 FT slot (Phase 3.1) ablation = set(ABLATION_MODEL_IDS) | {"lightgbm", "scout_ft"} return panel, ablation # Per-task primary metric for the leaderboard view emitted by ``--summary``. # Mirrors :data:`experiments.panel.TASK_METADATA` but resolved to the metric # *key* the runners emit (matches what aggregate_results writes to the long # DataFrame's ``metric_name`` column). _PRIMARY_METRIC_KEY: dict[str, str] = { "T1": "mse", "T2": "median_ape", "T3": "overall_mape", "T4": "return_mae_pct", "T5": "median_ape", "T6": "overall_mape", "T7": "rent_MAPE", } # Whether lower is better (True) or higher is better (False) for each task's # primary metric. All current MacroLens primary metrics are loss-style; this # table stays explicit for safety in case of future additions. _PRIMARY_METRIC_LOWER_IS_BETTER: dict[str, bool] = { "T1": True, "T2": True, "T3": True, "T4": True, "T5": True, "T6": True, "T7": True, } def _load_records( paths: list[Path], ) -> tuple[list[tuple[RunRecord, int | None]], int, int, int, int, int]: """Read every JSON in ``paths`` and validate as ``list[RunRecord]``. Returns ``(records, n_skipped_non_ok, n_migrated_v1, n_dedup_dropped, n_partial_dropped, n_off_panel)``. Validity gates (in order): 1. dedupe (method_id, task, granularity, seed) keeping the LATEST ``timestamp`` (mtime tiebreaker) — newer reruns supersede older tainted records EVEN IF the newer record is ``predict_failed``. This ensures a rerun that legitimately fails replaces an old silently-tainted "ok" record. 2. status == "ok" — drop the record if the latest run failed. 3. **All-NaN gate**: drop records whose primary-metric ``value`` is ``None`` (eval returned None because every prediction was NaN). 4. **Partial-NaN gate**: drop records whose ``n_predictions`` (or ``n_instances``) is less than the canonical eval N for that task, OR whose ``success_rate`` (T3/T6) is < 1.0. This catches the silent-NaN-on-some-rows cells that the all-NaN gate misses. """ import re as _re from ..dataloader.budgets import EVAL_N_PER_TASK adapter = pydantic.TypeAdapter(list[RunRecord]) n_migrated = 0 # Filename horizon parser: canon files written by the MH chains carry # ``_h_`` in the filename. The RunRecord schema does not store # horizon explicitly, so we recover it from the source path so the # aggregator can distinguish two horizons on the same (method, task, # granularity, seed) tuple instead of collapsing them. _H_RE = _re.compile(r"_h(\d+)_") def _file_horizon(path: Path) -> int | None: m = _H_RE.search(path.name) if m is None: return None try: return int(m.group(1)) except ValueError: return None # Allow-list filter: load the canonical 19-panel + FT-slot ids. Records # whose method_id is outside this set are silently dropped here so they # never reach dedupe, leaderboard, or coverage stages. panel_ids, _ablation_ids = _panel_method_ids() # First pass: gather ALL records (including non-ok) so dedupe can let # newer rerun-failures supersede older partial-coverage "ok" records. candidates: list[tuple[RunRecord, float, int | None]] = [] n_off_panel = 0 for p in paths: try: raw = json.loads(p.read_text()) except (OSError, json.JSONDecodeError) as exc: logger.warning("Skipping unreadable JSON %s: %s", p, exc) continue if not isinstance(raw, list): logger.warning("Skipping non-list JSON %s", p) continue migrated_raw: list[dict[str, Any]] = [] for rec in raw: if isinstance(rec, dict) and rec.get("schema_version") != 2: migrated_raw.append(_migrate_one(rec, p)) n_migrated += 1 else: migrated_raw.append(rec) try: recs = adapter.validate_python(migrated_raw) except pydantic.ValidationError as exc: logger.warning("Skipping %s: validation failed: %s", p, exc) continue try: mtime = p.stat().st_mtime except OSError: mtime = 0.0 h = _file_horizon(p) for r in recs: if r.method_id not in panel_ids: n_off_panel += 1 continue candidates.append((r, mtime, h)) # Second pass: dedupe by latest (timestamp, mtime); newer wins. # KEY INCLUDES ``ablation_setting`` AND ``horizon`` (parsed from # filename for T1 multi-horizon cells) so the aggregator never collapses # different horizons of the same (method, task, granularity, seed) # tuple into one row. best: dict[ tuple[str, str, str, int, str | None, int | None], tuple[RunRecord, float, int | None], ] = {} for rec, mtime, h in candidates: key = (rec.method_id, rec.task, rec.granularity, rec.seed, rec.ablation_setting, h) prev = best.get(key) if prev is None: best[key] = (rec, mtime, h) continue prev_rec, prev_mtime, _ = prev if (rec.timestamp, mtime) > (prev_rec.timestamp, prev_mtime): best[key] = (rec, mtime, h) n_dedup_dropped = len(candidates) - len(best) # Third + fourth passes: status + coverage gates. out: list[tuple[RunRecord, int | None]] = [] n_skip = 0 n_partial = 0 for rec, _mtime, h in best.values(): if rec.status != "ok": n_skip += 1 continue m_dict = rec.metrics or {} primary = _PRIMARY_METRIC_KEY.get(rec.task, "mse") m = m_dict.get(primary) val = m.value if m is not None else None if val is None: n_partial += 1 continue # Partial-NaN gate # NOTE: For T3/T6, a low success_rate (even 0) is a LEGITIMATE # benchmark measurement: it means the method could not produce the # canonical 11-field XBRL schema; eval-side fillna(0) -> APE 100% # scores it as 100% MAPE per ``feedback_penalize_incomplete``. We # only drop when ``success_rate`` is *missing entirely* (None), # which signals a recording-side bug, not a real model failure. if rec.task in ("T3", "T6"): sr = m_dict.get("success_rate") sr_v = sr.value if sr is not None else None if sr_v is None: n_partial += 1 continue else: # n_predictions or n_instances must equal canonical eval N. expected = EVAL_N_PER_TASK.get(rec.task) # type: ignore[arg-type] np_metric = m_dict.get("n_predictions") or m_dict.get("n_instances") np_v = np_metric.value if np_metric is not None else None if expected is not None and np_v is not None and int(np_v) < int(expected): n_partial += 1 continue out.append((rec, h)) return out, n_skip, n_migrated, n_dedup_dropped, n_partial, n_off_panel def _records_to_long_df( records: list[tuple[RunRecord, int | None]], ) -> pd.DataFrame: """Flatten records into a long-form DataFrame keyed by metric name. Backfills ``method_family`` from the modal non-null value seen for each ``method_id`` so stale re-eval bundles (which strip ``method_family``) don't split a method into two leaderboard rows (e.g., ``random_forest (classical)`` and ``random_forest (unknown)``). """ # Seed family map from the live Method registry — covers methods whose # writers never tagged ``method_family`` in the RunRecord (closed LLMs # gpt51/gpt_oss_120b/gemini3_flash, naive baselines historical_analogue/ # metro_median/sector_median, etc.). family_by_method: dict[str, str] = {} try: # Import is deferred so the aggregator stays importable in # environments without the methods/ tree (e.g. paper-only checkouts). from projects.agent_builder.scripts.whatif_bench import methods # noqa: F401 from projects.agent_builder.scripts.whatif_bench.methods._registry import ALL_METHODS for _name, _cls in ALL_METHODS.items(): _fam = getattr(_cls, "family", None) if _fam: family_by_method[_name] = _fam except Exception: # Registry not importable in this environment — fall back to # in-record backfill only. pass for r, _h in records: fam = r.method_family if fam and fam != "unknown" and r.method_id not in family_by_method: family_by_method[r.method_id] = fam rows: list[dict[str, Any]] = [] for r, h in records: if r.metrics is None: continue fam = r.method_family if fam in (None, "", "unknown"): fam = family_by_method.get(r.method_id, "unknown") family = fam for metric_name, mv in r.metrics.items(): rows.append({ "task": r.task, "method_id": r.method_id, "method_family": family, "granularity": r.granularity, "seed": r.seed, "ablation_setting": r.ablation_setting, "horizon": h, "metric_name": metric_name, "value": mv.value, "ci_lo": mv.ci_lo, "ci_hi": mv.ci_hi, "std": mv.std, "n_boot": mv.n_boot, "resample": mv.resample, }) return pd.DataFrame(rows) def aggregate( input_glob: str | None = None, *, output_path: Path | None = None, ) -> dict[str, pd.DataFrame]: """Aggregate every JSON matching ``input_glob`` into per-task DataFrames. Parameters ---------- input_glob Glob (default: ``experiments/results/canon_*.json``). output_path Optional Parquet path; when supplied, writes the *long-form* table (``[task, method_id, metric_name, value, ci_lo, ci_hi, n_boot, ...]``) and the per-task split is reconstructable via groupby. """ if input_glob is None: # Results live under experiments/results/, NOT data_small_caps/. # data_small_caps/ is the immutable raw-data tree; mixing experiment # outputs into it pollutes the data layer. input_glob = str( Path(__file__).parent / "results" / "canon_*.json" ) paths = [Path(p) for p in sorted(glob.glob(input_glob))] if not paths: logger.warning("No JSON matched glob %s", input_glob) records, n_skipped, n_migrated, n_dedup, n_partial, n_off_panel = _load_records(paths) logger.info( "Loaded %d paper-valid records from %d files " "(%d off-panel filtered, %d non-ok skipped, %d v1->v2 migrated, " "%d duplicate cells deduped, %d tainted cells dropped)", len(records), len(paths), n_off_panel, n_skipped, n_migrated, n_dedup, n_partial, ) if n_off_panel: print(f"FOOTNOTE: {n_off_panel} record(s) had method_id outside " "panel.ALL_METHODS and were filtered (e.g. stale gpt_oss_120b, gemma4).") if n_skipped: print(f"FOOTNOTE: {n_skipped} record(s) had status != 'ok' and were skipped.") if n_migrated: print(f"FOOTNOTE: {n_migrated} record(s) migrated from schema_version=1 to 2.") if n_dedup: print(f"FOOTNOTE: {n_dedup} duplicate (method, task, gran, seed) " "cell(s) deduped — kept latest timestamp.") if n_partial: print(f"FOOTNOTE: {n_partial} cell(s) dropped because primary metric " "value was None (silent-NaN tainted; need rerun).") long_df = _records_to_long_df(records) per_task: dict[str, pd.DataFrame] = {} for task in _TASK_ORDER: if long_df.empty: per_task[task] = long_df.copy() continue sub = long_df[long_df["task"] == task].copy() per_task[task] = ( sub.sort_values(["method_id", "metric_name"]).reset_index(drop=True) ) if output_path is not None: output_path = Path(output_path) output_path.parent.mkdir(parents=True, exist_ok=True) if output_path.suffix == ".parquet": long_df.to_parquet(output_path, index=False) else: long_df.to_csv(output_path, index=False) logger.info("Wrote aggregate %s (%d rows)", output_path, len(long_df)) return per_task def _print_leaderboard_for_cells( df: pd.DataFrame, *, label: str, eligible_methods: set[str], ) -> None: """Emit per-task leaderboard restricted to a single cell-set ``df``. No groupby across heterogeneous cells; each method contributes exactly one row (single seed). Missing-from-cell methods are listed below the ranked block so coverage gaps are explicit. """ print(f"\n=== {label} ===") for task in _TASK_ORDER: sub_task = df[df["task"] == task] eligible_for_task = eligible_methods if sub_task.empty: present = set() else: present = set(sub_task["method_id"].unique()) missing = sorted(eligible_for_task - present) primary = _PRIMARY_METRIC_KEY.get(task, "mse") ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True) ranked = sub_task[sub_task["metric_name"] == primary].dropna( subset=["value"] ).copy() if ranked.empty: print(f"\n[{task}] no valid records in this cell-set " f"({len(missing)} eligible methods missing).") if missing: print(f" missing: {missing}") continue ranked = ranked.sort_values( "value", ascending=ascending, ).reset_index(drop=True) print(f"\n[{task}] primary={primary} " f"({'lower' if ascending else 'higher'}=better) — " f"{len(ranked)}/{len(eligible_for_task)} methods present:") for i, row in ranked.iterrows(): print(f" {i+1:2d}. {row['method_id']:30s} " f"({row['method_family']:14s}) {row['value']:14.4f}") if missing: print(f" ... missing this cell: {missing}") def print_summary( per_task: dict[str, pd.DataFrame], long_df: pd.DataFrame | None = None, ) -> None: """Three per-cell-set leaderboards: main panel / MH T1 / A-E ablation. Each cell-set restricts both the records considered and the eligible method allow-list, so rankings compare like-with-like. """ from .panel import ( ALL_METHODS as _PANEL_METHODS, methods_for_task_panel, ) if long_df is None: # Reconstruct from per-task. (Older callers passed only per_task.) long_df = pd.concat(per_task.values(), ignore_index=True) if per_task else pd.DataFrame() if long_df.empty: print("\n(no records to summarise)") return panel_ids, ablation_ids = _panel_method_ids() # Cell-set 1: MAIN PANEL — daily, horizon is None (= h=252 main), no ablation. main_df = long_df[ (long_df["granularity"] == "daily") & (long_df["horizon"].isna()) & (long_df["ablation_setting"].isna()) & (long_df["method_id"].isin(panel_ids)) ].copy() # Eligible methods per task = panel methods whose ``tasks`` include task. main_eligible_by_task = { t: {m.id for m in methods_for_task_panel(t)} for t in _TASK_ORDER } # Print task-by-task with task-specific eligibility. print("\n=== MAIN PANEL (daily, h=252 default, no ablation) ===") for task in _TASK_ORDER: sub_task = main_df[main_df["task"] == task] eligible = main_eligible_by_task[task] present = set(sub_task["method_id"].unique()) if not sub_task.empty else set() missing = sorted(eligible - present) primary = _PRIMARY_METRIC_KEY.get(task, "mse") ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True) ranked = sub_task[sub_task["metric_name"] == primary].dropna( subset=["value"] ).copy() if ranked.empty: print(f"\n[{task}] no valid records " f"({len(missing)}/{len(eligible)} eligible methods missing).") if missing: print(f" missing: {missing}") continue ranked = ranked.sort_values( "value", ascending=ascending, ).reset_index(drop=True) print(f"\n[{task}] primary={primary} " f"({'lower' if ascending else 'higher'}=better) — " f"{len(ranked)}/{len(eligible)} methods present:") for i, row in ranked.iterrows(): print(f" {i+1:2d}. {row['method_id']:30s} " f"({row['method_family']:14s}) {row['value']:14.4f}") if missing: print(f" ... missing: {missing}") # Cell-set 2: MULTI-HORIZON T1 — one ranking per (granularity, horizon). mh_df = long_df[ (long_df["task"] == "T1") & (long_df["horizon"].notna()) & (long_df["ablation_setting"].isna()) & (long_df["method_id"].isin(panel_ids)) ].copy() mh_eligible = main_eligible_by_task["T1"] # T1-capable panel methods if not mh_df.empty: print("\n=== MULTI-HORIZON T1 (per (granularity, horizon)) ===") grans_horizons = ( mh_df[["granularity", "horizon"]].drop_duplicates() .sort_values(["granularity", "horizon"]) .itertuples(index=False, name=None) ) for gran, h in grans_horizons: h_int = int(h) sub = mh_df[(mh_df["granularity"] == gran) & (mh_df["horizon"] == h)] ranked = sub[sub["metric_name"] == "mse"].dropna( subset=["value"] ).copy() present = set(sub["method_id"].unique()) missing = sorted(mh_eligible - present) print(f"\n[T1] {gran}/h={h_int} — " f"{len(ranked)}/{len(mh_eligible)} methods present:") ranked = ranked.sort_values("value").reset_index(drop=True) for i, row in ranked.iterrows(): print(f" {i+1:2d}. {row['method_id']:30s} " f"({row['method_family']:14s}) {row['value']:14.4f}") if missing: print(f" ... missing: {missing}") # Cell-set 3: A-E ABLATION — per (setting, task) for ablation_ids only. abl_df = long_df[ (long_df["ablation_setting"].notna()) & (long_df["method_id"].isin(ablation_ids)) ].copy() if not abl_df.empty: print("\n=== A→E ABLATION (gpt51, gemini3_flash, lightgbm [+scout_ft when ready]) ===") from .panel import ABLATION_TASKS, ABLATION_SETTINGS for setting in sorted(ABLATION_SETTINGS.keys()): for task in ABLATION_TASKS: sub = abl_df[ (abl_df["ablation_setting"] == setting) & (abl_df["task"] == task) ] if sub.empty: print(f"\n[{setting}/{task}] no records " f"(eligible: {sorted(ablation_ids)})") continue primary = _PRIMARY_METRIC_KEY.get(task, "mse") ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True) ranked = sub[sub["metric_name"] == primary].dropna( subset=["value"] ).copy() if ranked.empty: print(f"\n[{setting}/{task}] no valid records for {primary}") continue ranked = ranked.sort_values( "value", ascending=ascending, ).reset_index(drop=True) present = set(sub["method_id"].unique()) missing = sorted(ablation_ids - present) print(f"\n[{setting}/{task}] primary={primary} — " f"{len(ranked)}/{len(ablation_ids)} methods:") for i, row in ranked.iterrows(): print(f" {i+1:2d}. {row['method_id']:30s} " f"({row['method_family']:14s}) {row['value']:14.4f}") if missing: print(f" ... missing: {missing}") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--input", type=str, default=None, help="Glob pointing to RunRecord JSON files " "(default: experiments/results/*.json)", ) parser.add_argument( "--output", type=Path, default=None, help="Optional aggregated table output (.parquet or .csv).", ) parser.add_argument( "--summary", action="store_true", help="Print per-task method leaderboard sorted by the task's primary metric.", ) args = parser.parse_args(argv) logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") per_task = aggregate(input_glob=args.input, output_path=args.output) if args.summary: print_summary(per_task) return 0 if __name__ == "__main__": # pragma: no cover import sys sys.exit(main())