#!/usr/bin/env python3 """Verify the paper's numeric claims against repository ground truth. Two checks, matching the two things the paper asserts numerically: 1. Release trajectory (Table `tab:s04-wersje` + the hero figure): tokens and source counts for v0.2.0 -> v0.2.5. Ground truth: `src/plot_version_growth.py` literals (exact docs/tokens) and CHANGELOG.md / README.md (source counts per release). 2. Corpus composition (Table `tab:s05-zrodla` + the inline totals): per-source token counts, the source set, and the corpus totals. Ground truth: `data/*/*.stats.json` at a git ref. Usage: python src/verify_paper_claims.py # ref = pin found in the .tex python src/verify_paper_claims.py --ref worktree # current working tree python src/verify_paper_claims.py --tex paper.tex --ref HEAD """ from __future__ import annotations import argparse import ast import json import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent # Printed precision in the paper sets the comparison tolerance. TOL_BILLIONS = 0.005 # Table 2 / hero figure: 2 decimal places TOL_MILLIONS = 0.05 # Table 3: 1 decimal place OK, FAIL, WARN = "OK", "FAIL", "WARN" MARKER = re.compile(r"\$\^\{([^}]*)\}\$") class Report: def __init__(self) -> None: self.rows: list[tuple[str, str, str]] = [] def add(self, status: str, label: str, detail: str = "") -> None: self.rows.append((status, label, detail)) def num(self, label: str, claimed, actual, tol: float = 0.0) -> None: if claimed is None: self.add(WARN, label, "not found in .tex") elif abs(claimed - actual) <= tol: self.add(OK, label, f"{claimed} == {actual}") else: self.add(FAIL, label, f"paper {claimed} != repo {actual}") def section(self, title: str) -> None: self.rows.append(("", title, "")) def render(self) -> int: width = max(len(label) for _, label, _ in self.rows) + 2 for status, label, detail in self.rows: if not status: print(f"\n=== {label} ===") else: print(f" [{status:<4}] {label:<{width}} {detail}") failures = sum(1 for s, _, _ in self.rows if s == FAIL) warnings = sum(1 for s, _, _ in self.rows if s == WARN) print(f"\n{failures} failure(s), {warnings} warning(s)") return 1 if failures else 0 # -------------------------------------------------------------------------- # .tex parsing # -------------------------------------------------------------------------- def _unescape(name: str) -> str: return name.replace("\\_", "_").replace("\\&", "&") def _table_body(tex: str, label: str) -> str: """Return the body of the table environment carrying \\label{label}.""" for block in re.findall(r"\\begin\{table\}.*?\\end\{table\}", tex, re.S): if f"\\label{{{label}}}" in block: return block raise LookupError(f"no table with \\label{{{label}}} in the .tex") def parse_hero(tex: str) -> dict[str, float]: """Version -> tokens (billions) from the pgfplots hero figure coordinates.""" coords = re.search(r"\\addplot\[[^\]]*\]\s*coordinates\s*\{(.*?)\}", tex, re.S) if not coords: return {} return {v: float(t) for v, t in re.findall(r"\((v[\d.]+),\s*([\d.]+)\)", coords.group(1))} def parse_trajectory_table(tex: str) -> dict[str, tuple[float, str]]: """Version -> (tokens in billions, source-count cell verbatim).""" body = _table_body(tex, "tab:s04-wersje") rows = re.findall(r"^\s*(v[\d.]+)\s*&\s*([\d.]+)\s*&\s*(.+?)\s*\\\\", body, re.M) return {v: (float(tok), src.strip()) for v, tok, src in rows} def parse_source_table(tex: str) -> tuple[dict[str, float], float | None]: """(source name -> tokens in millions, declared total in millions).""" body = _table_body(tex, "tab:s05-zrodla") sources = { _unescape(name): float(tok) for name, tok in re.findall( r"\\texttt\{([^}]+)\}\s*&.*?&\s*([\d.]+)\s*\\\\", body ) } total_row = re.search(r"\\textbf\{Total\}.*?&.*?&\s*(.+?)\s*\\\\", body, re.S) total = None if total_row: digits = re.search(r"([\d.]+)", total_row.group(1)) if digits: total = float(digits.group(1)) return sources, total def parse_license_rows(tex: str) -> dict[str, tuple[str, set[str]]]: """Table 3 source rows -> (license cell without its markers, marker names).""" body = _table_body(tex, "tab:s05-zrodla").split(r"\begin{tabular}")[-1] rows = {} for name, cell in re.findall(r"\\texttt\{([^}]+)\}\s*&(.*?)&\s*[\d.]+\s*\\\\", body): rows[_unescape(name)] = (MARKER.sub("", cell).strip(), _markers(cell)) return rows def parse_footnote_defs(tex: str) -> set[str]: """Markers the Table 3 caption actually explains (a definition is followed by ~).""" caption = _table_body(tex, "tab:s05-zrodla").split(r"\begin{tabular}")[0] return {m for cell in re.findall(r"(\$\^\{[^}]*\}\$)~", caption) for m in _markers(cell)} def parse_total_license(tex: str) -> str | None: body = _table_body(tex, "tab:s05-zrodla") row = re.search(r"\\textbf\{Total\}\s*&\s*(.*?)\s*&", body) return MARKER.sub("", row.group(1)).strip() if row else None def _markers(cell: str) -> set[str]: return {m for group in MARKER.findall(cell) for m in re.findall(r"\\([a-zA-Z]+)", group)} def parse_inline_claims(tex: str, current: str | None = None) -> dict: """Claims the prose/captions make about the *current release* totals. A claim is skipped when its surrounding sentence scopes it to a different release or to a partition subtotal, so only whole-release assertions are compared against the current release's ground truth. """ CONTEXT = 160 SUBTOTAL = re.compile(r"share-alike|partitions?\b") VERSION = re.compile(r"v\d+\.\d+\.\d+") def sweep(pattern: str, cast): out = set() for match in re.finditer(pattern, tex): window = tex[max(0, match.start() - CONTEXT):match.end() + CONTEXT] if SUBTOTAL.search(window): continue if any(v != current for v in VERSION.findall(window)): continue raw = next(g for g in match.groups() if g) out.add(cast(raw)) return out docs = sweep( r"(?:\\num\{(\d+)\}|(\d[\d\\,]*\d))\s*~?\s*documents", lambda raw: int(re.sub(r"[^\d]", "", raw)), ) # ponytail: floor keeps small unrelated "N documents" counts (held-out set # sizes) out; scope by section if the paper grows other six-figure claims. docs = {value for value in docs if value >= 100_000} tokens = sweep( r"(?:\\num\{([\d.]+)\}|\$([\d.]+)\$|([\d.]+))\s*~?\s*billion\s+tokens", float, ) sources = sweep(r"\b(\d+)\s+sources\b", int) pin = re.search(r"commit\s+\\texttt\{([0-9a-f]{7,40})\}", tex) return { "documents": docs, "tokens_billions": tokens, "sources": sources, "pin": pin.group(1) if pin else None, } # -------------------------------------------------------------------------- # Ground truth # -------------------------------------------------------------------------- def load_growth_series(root: Path) -> dict[str, tuple[int, int]]: """Version -> (documents, tokens) from src/plot_version_growth.py literals.""" path = root / "src" / "plot_version_growth.py" tree = ast.parse(path.read_text(encoding="utf-8")) found: dict[str, list] = {} for node in tree.body: if isinstance(node, ast.Assign) and len(node.targets) == 1: target = node.targets[0] if isinstance(target, ast.Name) and target.id in {"VERSIONS", "DOCUMENTS", "TOKENS"}: found[target.id] = ast.literal_eval(node.value) missing = {"VERSIONS", "DOCUMENTS", "TOKENS"} - found.keys() if missing: raise LookupError(f"{path} is missing {sorted(missing)}") return dict(zip(found["VERSIONS"], zip(found["DOCUMENTS"], found["TOKENS"]))) def load_registry(root: Path) -> dict[str, dict]: """The SOURCES table from src/sources.py, read without importing the module. Always read from the working tree: the registry defines what a release *is*, independently of the ref the parquet stats are read from. """ path = root / "src" / "sources.py" if not path.exists(): return {} for node in ast.parse(path.read_text(encoding="utf-8")).body: if (isinstance(node, ast.Assign) and len(node.targets) == 1 and getattr(node.targets[0], "id", None) == "SOURCES"): return ast.literal_eval(node.value) return {} def load_release_map(root: Path) -> dict[str, str | None]: """Source name -> the release it entered. Empty when the registry is absent or predates the `release` field, in which case the CHANGELOG prose stays the only ground truth. """ sources = load_registry(root) if not any("release" in cfg for cfg in sources.values()): return {} return {name: cfg.get("release") for name, cfg in sources.items()} def released_at(releases: dict[str, str | None], version: str) -> set[str]: """Sources belonging to `version`, i.e. admitted at or before it.""" ceiling = _version_key(version) return { name for name, release in releases.items() if release and _version_key(release) <= ceiling } def _version_key(version: str) -> tuple[int, ...]: return tuple(int(part) for part in version.lstrip("v").split(".")) def _changelog_sections(root: Path) -> dict[str, str]: text = (root / "CHANGELOG.md").read_text(encoding="utf-8") parts = re.split(r"^## (v[\d.]+[\w.-]*)", text, flags=re.M) return dict(zip(parts[1::2], parts[2::2])) def load_declared_sources( root: Path, base_version: str | None = None ) -> tuple[dict[str, int | None], dict[str, list[str]]]: """Version -> declared source count (None when unrecorded), and sources added.""" sections = _changelog_sections(root) counts: dict[str, int | None] = {} added: dict[str, list[str]] = {} for version, body in sections.items(): match = re.search(r"\b(\d+)[-\s]sources?\b", body) counts[version] = int(match.group(1)) if match else None added[version] = re.findall( r"Added (?:the )?(?:community[- ]contributed |community contribution |reviewed )?`([\w.]+)`", body, ) # The first release predates the CHANGELOG; the README release table records it. if base_version and counts.get(base_version) is None: readme = (root / "README.md").read_text(encoding="utf-8") base = re.search( rf"`{re.escape(base_version)}`.*?(\d+) open/official sources", readme, re.S ) if base: counts[base_version] = int(base.group(1)) added.setdefault(base_version, []) return counts, added def load_stats(root: Path, ref: str) -> dict[str, dict]: """Source name -> parquet stats, read from a git ref or the working tree.""" stats: dict[str, dict] = {} if ref == "worktree": paths = sorted(root.glob("data/*/*.stats.json")) for path in paths: stats[path.name.removesuffix(".stats.json")] = json.loads( path.read_text(encoding="utf-8") ) return stats listing = subprocess.run( ["git", "-C", str(root), "ls-tree", "-r", "--name-only", ref, "--", "data/"], capture_output=True, text=True, check=True, ).stdout.splitlines() for rel in sorted(p for p in listing if p.endswith(".stats.json")): blob = subprocess.run( ["git", "-C", str(root), "show", f"{ref}:{rel}"], capture_output=True, text=True, check=True, ).stdout stats[Path(rel).name.removesuffix(".stats.json")] = json.loads(blob) return stats # -------------------------------------------------------------------------- # Checks # -------------------------------------------------------------------------- def check_trajectory(report: Report, tex: str, root: Path) -> None: report.section("Check 1 - release trajectory v0.2.0 -> v0.2.5 (Table 2 + hero figure)") table = parse_trajectory_table(tex) hero = parse_hero(tex) series = load_growth_series(root) declared, added = load_declared_sources(root, base_version=sorted(series)[0]) releases = load_release_map(root) if releases: for version in sorted(series): counted = len(released_at(releases, version)) if declared.get(version) is None: declared[version] = counted elif declared[version] != counted: report.add(FAIL, f"{version} registry vs CHANGELOG", f"src/sources.py counts {counted}, CHANGELOG says {declared[version]}") missing = sorted(set(series) - set(table)) extra = sorted(set(table) - set(series)) if missing or extra: report.add(FAIL, "table covers every release", f"missing {missing}, unexpected {extra}") else: report.add(OK, "table covers every release", f"{len(table)} rows") for version in sorted(series): docs, tokens = series[version] actual_b = tokens / 1e9 claimed_b = table.get(version, (None, None))[0] report.num(f"{version} tokens (B, Table 2)", claimed_b, round(actual_b, 6), TOL_BILLIONS) report.num(f"{version} tokens (B, hero figure)", hero.get(version), round(actual_b, 6), TOL_BILLIONS) # Source counts. "---" in the table means "unchanged from the previous release". previous: int | None = None for version in sorted(series): cell = table.get(version, (None, "?"))[1] if cell == "---": claimed = previous shown = f"--- (carries {previous})" else: digits = re.search(r"\d+", cell or "") claimed = int(digits.group()) if digits else None shown = str(claimed) previous = claimed truth = declared.get(version) label = f"{version} source count" if truth is None: report.add(WARN, label, f"paper {shown}; no count recorded in CHANGELOG/README") elif claimed == truth: report.add(OK, label, f"{shown} == {truth}") else: report.add(FAIL, label, f"paper {shown} != repo {truth}") if releases: return # the registry already resolves every release exactly # Back-fill unrecorded releases from the next release's "Added `source`" bullets. versions = sorted(series) for index, version in enumerate(versions[:-1]): if declared.get(version) is not None: continue following = versions[index + 1] if declared.get(following) is None: continue inferred = declared[following] - len(added.get(following, [])) report.add( WARN, f"{version} source count (derived)", f"{following} declares {declared[following]} and adds " f"{len(added.get(following, []))} -> {version} = {inferred}", ) def check_composition(report: Report, tex: str, root: Path, ref: str) -> None: report.section(f"Check 2 - corpus composition and totals (Table 3, ref={ref})") table, table_total = parse_source_table(tex) current = sorted(load_growth_series(root))[-1] claims = parse_inline_claims(tex, current=current) stats = load_stats(root, ref) releases = load_release_map(root) in_release = released_at(releases, current) if releases else set(stats) absent = sorted(set(table) - set(stats)) unlisted = sorted((set(stats) & in_release) - set(table)) unreleased = sorted(set(stats) - in_release) listed_but_unreleased = sorted(set(table) & set(unreleased)) if absent: report.add(FAIL, "every listed source exists at ref", f"missing from repo: {absent}") else: report.add(OK, "every listed source exists at ref", f"{len(table)} sources") if unlisted: report.add(FAIL, f"every {current} source is in Table 3", f"released but missing from Table 3: {unlisted}") else: report.add(OK, f"every {current} source is in Table 3", "") if listed_but_unreleased: report.add(FAIL, "Table 3 lists only released sources", f"not in any release: {listed_but_unreleased}") elif unreleased: report.add(OK, "Table 3 lists only released sources", f"correctly excludes {unreleased}") listed = [name for name in table if name in stats] for name in sorted(listed, key=lambda n: -stats[n]["tokens"]): report.num(f"{name} tokens (M)", table[name], round(stats[name]["tokens"] / 1e6, 6), TOL_MILLIONS) sum_tokens = sum(stats[name]["tokens"] for name in listed) sum_docs = sum(stats[name]["kept"] for name in listed) report.num("Table 3 rows sum to its Total row (M)", round(sum(table[n] for n in listed), 6), round(sum_tokens / 1e6, 6), TOL_MILLIONS * len(listed)) report.num("Table 3 Total row (M)", table_total, round(sum_tokens / 1e6, 6), 1.0) for value in sorted(claims["documents"]): report.num(f"prose claim: {value} documents", value, sum_docs) for value in sorted(claims["tokens_billions"]): report.num(f"prose claim: {value}B tokens", value, round(sum_tokens / 1e9, 6), TOL_BILLIONS) for value in sorted(claims["sources"]): report.num(f"prose claim: {value} sources", value, len(listed)) if unreleased: report.add( WARN, "totals over ALL sources at ref", f"{sum(s['kept'] for s in stats.values())} docs / " f"{sum(s['tokens'] for s in stats.values()) / 1e9:.3f}B tokens " f"across {len(stats)} sources", ) # Anchor: the trajectory series' last point must equal the composition sum. series = load_growth_series(root) last = sorted(series)[-1] report.num(f"{last} tokens in growth series == Table 3 sum", series[last][1], sum_tokens) report.num(f"{last} documents in growth series == Table 3 sum", series[last][0], sum_docs) def norm_license(text: str) -> tuple[str, str | None]: """Canonical (family, version) so paper, registry and datasheet can be compared. Public domain and CC0 are one family: SPDX spells "official documents are outside copyright" as CC0-1.0, and the paper prints both as PD. A version of None means the text states no version, and compares equal to any version -- the paper abbreviates nkjp1m's CC-BY-4.0 to "CC-BY" on purpose. """ t = re.sub(r"[`_]", " ", text).upper() if re.search(r"PER-RECORD|PER-DOCUMENT|MIXED", t): return ("MIXED", None) if re.search(r"CC0|PUBLIC[- ]DOMAIN|\bPD\b", t): return ("PD/CC0", None) match = re.search(r"CC[- ]BY(?:[- ](SA))?(?:[- ](\d+\.\d+))?", t) if match: return ("CC-BY-SA" if match.group(1) else "CC-BY", match.group(2)) return (t.strip(), None) def compatible(a: tuple[str, str | None], b: tuple[str, str | None]) -> bool: """Same family, and same version unless one side states none.""" return a[0] == b[0] and (a[1] is None or b[1] is None or a[1] == b[1]) def load_datasheet_license(root: Path, name: str) -> str | None: """The datasheet's declared License line (working tree, not the pinned ref).""" path = root / "data" / name / f"{name}.md" if not path.exists(): return None match = re.search(r"\*\*License:\*\*\s*(.+)", path.read_text(encoding="utf-8")) return match.group(1).strip() if match else None def check_licenses(report: Report, tex: str, root: Path) -> None: report.section("Check 3 - licenses and footnotes (Table 3 vs registry vs datasheets)") rows = parse_license_rows(tex) registry = load_registry(root) if not registry: report.add(WARN, "license audit", "src/sources.py carries no registry to compare against") return for name in sorted(rows, key=lambda n: n.lower()): paper, markers = rows[name] cfg = registry.get(name) if cfg is None: report.add(FAIL, f"{name} in registry", "listed in Table 3 but absent from src/sources.py") continue declared = norm_license(str(cfg.get("license", ""))) spdx = norm_license(str(cfg.get("license_spdx") or cfg.get("license", ""))) printed = norm_license(paper) if compatible(printed, declared) or compatible(printed, spdx): report.add(OK, f"{name} license", f"{paper} == {cfg.get('license')}") else: report.add(FAIL, f"{name} license", f"paper {paper!r} != registry {cfg.get('license')!r} / {cfg.get('license_spdx')!r}") sheet = load_datasheet_license(root, name) if sheet is None: report.add(WARN, f"{name} datasheet license", "no **License:** line in the datasheet") elif not compatible(norm_license(sheet), declared): report.add(FAIL, f"{name} datasheet license", f"datasheet {sheet!r} != registry {cfg.get('license')!r}") # A source whose content license differs from its redistribution license # states only half the story in a one-line cell; the footnote carries the rest. if not compatible(declared, spdx) and not markers: report.add(FAIL, f"{name} dual license is footnoted", f"content {cfg.get('license')!r} but redistributed as " f"{cfg.get('license_spdx')!r}; the row prints only {paper!r}") used = {m for _, markers in rows.values() for m in markers} defined = parse_footnote_defs(tex) if used - defined: report.add(FAIL, "every footnote marker is defined", f"used but not explained: {sorted(used - defined)}") elif defined - used: report.add(FAIL, "every footnote is used", f"explained but on no row: {sorted(defined - used)}") else: report.add(OK, "footnote markers", f"{len(used)} defined and used: {sorted(used)}") total = parse_total_license(tex) strongest = [n for n, (lic, _) in rows.items() if norm_license(lic)[0] == "CC-BY-SA"] if total is None: report.add(WARN, "Total row license", "no license cell in the Total row") elif strongest and norm_license(total)[0] != "CC-BY-SA": report.add(FAIL, "Total row license", f"{total} does not inherit the share-alike of {sorted(strongest)}") else: report.add(OK, "Total row license", f"{total} inherits share-alike from {len(strongest)} sources") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--tex", default=str(ROOT / "file.tex"), help="paper source") parser.add_argument("--root", default=str(ROOT), help="repository root") parser.add_argument("--ref", default=None, help="git ref for data/*.stats.json, or 'worktree' " "(default: the commit the .tex pins)") args = parser.parse_args(argv) root = Path(args.root).resolve() tex = Path(args.tex).read_text(encoding="utf-8") ref = args.ref or parse_inline_claims(tex)["pin"] or "HEAD" report = Report() check_trajectory(report, tex, root) check_composition(report, tex, root, ref) check_licenses(report, tex, root) return report.render() if __name__ == "__main__": sys.exit(main())