| """Dataset verifier for FlashFacts. Every card claim maps to a check here. |
| |
| The check that matters most, and the reason this file exists at all: |
| |
| THE GATE IMPORTS THE RELEASED SCORER. |
| |
| Every row's own completion is scored against its own reference by |
| score_flashfacts.verdict, the same function that will grade the model. A row that cannot |
| pass its own scorer is a row the model can never get credit for, and building 15,000 of |
| those and discovering it after a GPU run is the single most expensive mistake available |
| here. Reimplementing the comparison in the builder is how that happens, so the builder |
| does not have one. |
| |
| python verify_flashfacts.py <rows.jsonl> [more.jsonl ...] |
| python verify_flashfacts.py --selftest |
| """ |
| from __future__ import annotations |
|
|
| import json |
| import sys |
| from collections import Counter |
| from pathlib import Path |
|
|
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) |
|
|
| from common.verify import Checker, provenance_checks, split_checks, style_checks |
| from flashfacts import balance as BAL |
| from flashfacts import score_flashfacts as S |
|
|
|
|
| def load(path: Path) -> list[dict]: |
| return [json.loads(l) for l in path.read_text().splitlines() if l.strip()] |
|
|
|
|
| def self_score(rows: list[dict]) -> tuple[int, list[dict]]: |
| """How many rows pass the RELEASED scorer against their own reference.""" |
| bad = [] |
| n_ok = 0 |
| for r in rows: |
| gold = S.extract_json(r.get("reference", "") or "") |
| pred = S.extract_json(r.get("completion", "") or "") |
| if gold is None: |
| bad.append({"id": r.get("id"), "why": "reference does not parse"}) |
| continue |
| v = S.verdict(pred, gold) |
| if v["strict_match"]: |
| n_ok += 1 |
| else: |
| wrong = [k for k, ok in v["fields"].items() if not ok] |
| bad.append({"id": r.get("id"), "why": "completion fails its own scorer", |
| "fields": wrong}) |
| return n_ok, bad |
|
|
|
|
| def schema_checks(c: Checker, rows: list[dict]) -> None: |
| bad_keys = bad_months = bad_date = bad_metric = bad_yoy = bad_types = 0 |
| for r in rows: |
| g = S.extract_json(r.get("reference", "") or "") |
| if g is None: |
| bad_keys += 1 |
| continue |
| if set(g) != set(S.KEYS): |
| bad_keys += 1 |
| if g.get("period_months") not in S.PERIOD_MONTHS_ALLOWED: |
| bad_months += 1 |
| pe = str(g.get("period_end", "")) |
| if len(pe) != 10 or pe[4] != "-" or pe[7] != "-": |
| bad_date += 1 |
| gd = g.get("guidance") |
| if gd is not None and (not isinstance(gd, dict) |
| or set(gd) != set(S.GUIDANCE_KEYS) |
| or gd.get("metric") not in S.GUIDANCE_METRICS): |
| bad_metric += 1 |
| for k in S.MONEY_KEYS: |
| v = g.get(k) |
| if not isinstance(v, int) or isinstance(v, bool): |
| bad_types += 1 |
| break |
| rev, pyr, yoy = g.get("revenue_usd"), g.get("prior_year_revenue_usd"), g.get("revenue_yoy_pct") |
| if isinstance(rev, (int, float)) and isinstance(pyr, (int, float)) and pyr: |
| if S.round_half_away((rev - pyr) / pyr * 100.0, 1) != S.round_half_away(float(yoy), 1): |
| bad_yoy += 1 |
| else: |
| bad_yoy += 1 |
| c.check("SCHEMA: every reference carries exactly the 11 keys", bad_keys == 0, f"{bad_keys} bad") |
| c.check("SCHEMA: period_months is 3, 6, 9 or 12", bad_months == 0, f"{bad_months} bad") |
| c.check("SCHEMA: period_end is an ISO date", bad_date == 0, f"{bad_date} bad") |
| c.check("SCHEMA: guidance is null or the closed 4-key object with an enum metric", |
| bad_metric == 0, f"{bad_metric} bad") |
| c.check("SCHEMA: money fields are JSON integers", bad_types == 0, f"{bad_types} bad") |
| c.check("ARITHMETIC: revenue_yoy_pct recomputes from the two gated revenues", |
| bad_yoy == 0, f"{bad_yoy} bad") |
|
|
|
|
| def provenance_row_checks(c: Checker, rows: list[dict]) -> None: |
| no_url = sum(1 for r in rows if "/Archives/edgar/data/" not in str(r.get("accession_url", ""))) |
| c.check("PROVENANCE: every row carries an EDGAR accession URL", no_url == 0, f"{no_url} missing") |
| no_sha = sum(1 for r in rows if len(str(r.get("exhibit_sha256", ""))) != 64) |
| c.check("PROVENANCE: every row carries a sha256 of its source exhibit", |
| no_sha == 0, f"{no_sha} missing") |
| rendered = sum(1 for r in rows if r.get("rendered")) |
| c.check("EVAL: zero programmatically rendered rows in an eval slice", |
| rendered == 0, f"{rendered} rendered") |
|
|
|
|
| def leak_checks(c: Checker, holdout: list[dict], train: list[dict]) -> None: |
| """The claim we publish, not a weaker cousin of it (HANDOFF 5.13 corollary).""" |
| if not train: |
| c.skip("LEAK: no held-out excerpt appears in training", "no training file given") |
| c.skip("LEAK: train and held-out CIK sets are disjoint", "no training file given") |
| c.skip("LEAK: every held-out filing is later than every training filing", |
| "no training file given") |
| return |
| tex = {r["prompt"] for r in train} |
| shared = sum(1 for r in holdout if r["prompt"] in tex) |
| c.check("LEAK: no held-out excerpt appears in training", shared == 0, f"{shared} shared") |
| tc = {r.get("cik") for r in train} |
| hc = {r.get("cik") for r in holdout} |
| c.check("LEAK: train and held-out CIK sets are disjoint", not (tc & hc), |
| f"{len(tc & hc)} shared CIKs") |
| tmax = max((r.get("filing_date", "") for r in train), default="") |
| hmin = min((r.get("filing_date", "") for r in holdout), default="") |
| c.check("LEAK: every held-out filing is later than every training filing", |
| bool(hmin) and hmin > tmax, f"train max {tmax}, holdout min {hmin}") |
|
|
|
|
| def balance_report(rows: list[dict]) -> dict: |
| """Requested period against the column the answer sits in, plus the shortcut gain.""" |
| pairs = Counter((r.get("period_months"), r.get("table_col")) for r in rows) |
| out = dict(BAL.shortcut_stats(rows)) |
| out["period_months_by_column"] = {f"{m}m/col{c}": n for (m, c), n in pairs.most_common()} |
| return out |
|
|
|
|
| def balance_checks(c: Checker, rows: list[dict]) -> None: |
| """The positional shortcut is asserted, not merely reported. |
| |
| A distribution printed in a summary is a promise. This is the check: how much better |
| than guessing the majority class can the requested period be predicted from the |
| answer's column index alone. The first probe build scored a gain of 0.40 and would |
| have failed here loudly. |
| """ |
| s = BAL.shortcut_stats(rows) |
| c.check("BALANCE: column position does not predict the requested period", |
| s["shortcut_gain"] <= BAL.MAX_SHORTCUT_GAIN, |
| f"gain {s['shortcut_gain']:.3f} = column-only {s['column_only_accuracy']:.3f} " |
| f"minus majority {s['majority_baseline']:.3f}, max {BAL.MAX_SHORTCUT_GAIN}") |
| both = s["by_period_type"] |
| c.check("BALANCE: both quarter and year-to-date requests are present", |
| both.get("quarter", 0) > 0 and both.get("ytd", 0) > 0, str(both)) |
|
|
|
|
| def null_report(rows: list[dict]) -> dict: |
| n_gnull = n_ngnull = n_either = 0 |
| for r in rows: |
| g = S.extract_json(r.get("reference", "") or "") or {} |
| gn = g.get("guidance") is None |
| nn = g.get("non_gaap_eps_usd") is None |
| n_gnull += gn |
| n_ngnull += nn |
| n_either += gn or nn |
| return {"rows": len(rows), "guidance_null": n_gnull, |
| "non_gaap_null": n_ngnull, "any_null": n_either, |
| "any_null_pct": round(100.0 * n_either / len(rows), 1) if rows else 0.0} |
|
|
|
|
| def verify(paths: list[Path], train_path: Path | None = None) -> None: |
| rows: list[dict] = [] |
| for p in paths: |
| rows.extend(load(p)) |
| train = load(train_path) if train_path and train_path.exists() else [] |
|
|
| c = Checker("flashfacts") |
| n_ok, bad = self_score(rows) |
| c.check("GATE: every row's completion passes the RELEASED scorer against its own " |
| "reference", not bad, f"{len(bad)} of {len(rows)} fail") |
| if bad: |
| for b in bad[:5]: |
| print(f" {b}") |
|
|
| style_checks(c, rows) |
| provenance_checks(c, rows) |
| provenance_row_checks(c, rows) |
| schema_checks(c, rows) |
| balance_checks(c, rows) |
| if train: |
| split_checks(c, train, rows) |
| leak_checks(c, rows, train) |
|
|
| ids = [r["id"] for r in rows] |
| c.check("IDS: unique", len(set(ids)) == len(ids), f"{len(ids) - len(set(ids))} duplicates") |
|
|
| print("\ncomposition:", dict(Counter(r.get("category", "") for r in rows).most_common())) |
| print("nulls:", json.dumps(null_report(rows))) |
| print("balance:", json.dumps(balance_report(rows))) |
| c.done() |
|
|
|
|
| def _selftest() -> None: |
| """Prove the gate can FAIL. A guard never shown to fail is not a guard.""" |
| g = dict(S.GOLD_EXAMPLE) |
| good = { |
| "id": "ff-1", "category": "plain", "shard": "plain", |
| "license": "SEC EDGAR public records, no formal license text", |
| "source": "https://www.sec.gov/Archives/edgar/data/1/x-index.htm", |
| "accession_url": "https://www.sec.gov/Archives/edgar/data/1/x-index.htm", |
| "exhibit_sha256": "a" * 64, "filing_date": "2026-04-25", |
| "prompt": "p", "reference": json.dumps(g), |
| "completion": "notes: shown\n" + json.dumps(g), |
| "table_col": 0, "period_months": 3, "rendered": False, |
| } |
| n_ok, bad = self_score([good]) |
| assert n_ok == 1 and not bad, bad |
|
|
| broken = dict(good, completion="notes: shown\n" |
| + json.dumps(dict(g, revenue_usd=g["revenue_usd"] * 1000))) |
| n_ok2, bad2 = self_score([broken]) |
| assert n_ok2 == 0 and bad2 and "revenue_usd" in bad2[0]["fields"], bad2 |
|
|
| missing = dict(good, completion="I cannot help with that.") |
| n_ok3, bad3 = self_score([missing]) |
| assert n_ok3 == 0 and bad3 |
|
|
| c = Checker("selftest-schema") |
| schema_checks(c, [dict(good, reference=json.dumps(dict(g, period_months=5)))]) |
| assert "SCHEMA: period_months is 3, 6, 9 or 12" in c.fails, c.fails |
| c2 = Checker("selftest-yoy") |
| schema_checks(c2, [dict(good, reference=json.dumps(dict(g, revenue_yoy_pct=99.9)))]) |
| assert "ARITHMETIC: revenue_yoy_pct recomputes from the two gated revenues" in c2.fails |
| cb = Checker("selftest-balance") |
| balance_checks(cb, [dict(good, period_months=3, table_col=0) for _ in range(24)] |
| + [dict(good, period_months=6, table_col=2) for _ in range(24)]) |
| assert "BALANCE: column position does not predict the requested period" in cb.fails, cb.fails |
| cb2 = Checker("selftest-balance-ok") |
| mixed = [] |
| for col in (0, 2): |
| mixed += [dict(good, period_months=3, table_col=col) for _ in range(12)] |
| mixed += [dict(good, period_months=6, table_col=col) for _ in range(12)] |
| balance_checks(cb2, mixed) |
| assert not cb2.fails, cb2.fails |
|
|
| c3 = Checker("selftest-leak") |
| leak_checks(c3, [dict(good, cik=7, filing_date="2020-01-01")], |
| [dict(good, cik=7, filing_date="2026-01-01")]) |
| assert "LEAK: train and held-out CIK sets are disjoint" in c3.fails |
| assert "LEAK: every held-out filing is later than every training filing" in c3.fails |
| assert "LEAK: no held-out excerpt appears in training" in c3.fails |
|
|
| print("verify_flashfacts selftest: OK (clean row passes, 8 injected defects all " |
| "fire, balanced data passes the balance check)") |
|
|
|
|
| def main() -> int: |
| args = [a for a in sys.argv[1:]] |
| if "--selftest" in args: |
| _selftest() |
| return 0 |
| train = None |
| if "--train" in args: |
| i = args.index("--train") |
| train = Path(args[i + 1]) |
| del args[i:i + 2] |
| if not args: |
| print(__doc__) |
| return 2 |
| verify([Path(a) for a in args], train) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|