File size: 26,822 Bytes
77e5321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#!/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_family_table(tex: str) -> tuple[dict[str, float], float | None]:
    """Table 5 -> (license family -> tokens in billions, declared total)."""
    body = _table_body(tex, "tab:s10-licencje").split(r"\begin{tabular}")[-1]
    families, total = {}, None
    for label, value in re.findall(r"^\s*([^&\\]+?)\s*&[^&]*&\s*\$?([\d.]+)\$?\s*\\\\",
                                   body, re.M):
        if label.strip().lower() == "total":
            total = float(value)
        elif license_family(label):
            families[license_family(label)] = float(value)
    return families, total


def license_family(text: str) -> str | None:
    """The Table 5 partition: like norm_license, but CC0 and public domain split.

    norm_license folds them together because the source table prints either for
    the same source; Table 5 reports them as separate families, so a source's
    own wording decides which side it lands on.
    """
    t = re.sub(r"[`_]", " ", text).upper()
    if re.search(r"PER-RECORD|PER-DOCUMENT|MIXED", t):
        return "Per-record (mixed)"
    if re.search(r"PUBLIC[- ]DOMAIN", t):
        return "Public domain"
    if "CC0" in t:
        return "CC0"
    if re.search(r"CC[- ]BY[- ]SA", t):
        return "CC-BY-SA"
    if re.search(r"CC[- ]BY", t):
        return "CC-BY"
    return None


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_families(report: Report, tex: str, root: Path, ref: str) -> None:
    """Table 5 must be a complete partition of Table 3 by license family."""
    paper, paper_total = parse_family_table(tex)
    registry, stats = load_registry(root), load_stats(root, ref)
    releases = load_release_map(root)
    if not (paper and registry and releases):
        report.add(WARN, "license family table", "no family table or no registry to partition")
        return

    repo: dict[str, int] = {}
    unclassified = []
    for name in released_at(releases, sorted(load_growth_series(root))[-1]):
        cfg = registry[name]
        # The row prints the content's own status; SPDX carries the CC0 wording.
        family = license_family(str(cfg.get("license", ""))) or license_family(str(cfg.get("license_spdx") or ""))
        if family is None:
            unclassified.append(name)
        else:
            repo[family] = repo.get(family, 0) + stats[name]["tokens"]

    if unclassified:
        report.add(FAIL, "every source has a license family", f"unclassifiable: {sorted(unclassified)}")
    if set(paper) != set(repo):
        report.add(FAIL, "Table 5 families match the corpus",
                   f"paper {sorted(paper)} != repo {sorted(repo)}")
    else:
        report.add(OK, "Table 5 families match the corpus", f"{len(repo)} families, no source left over")

    for family in sorted(repo, key=lambda f: -repo[f]):
        if family in paper:
            report.num(f"{family} tokens (B)", paper[family], round(repo[family] / 1e9, 6), TOL_BILLIONS)
    report.num("Table 5 Total row (B)", paper_total, round(sum(repo.values()) / 1e9, 6), TOL_BILLIONS)


def check_licenses(report: Report, tex: str, root: Path) -> None:
    report.section("Check 3 - licenses, footnotes and license families")

    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)
    check_families(report, tex, root, ref)
    return report.render()


if __name__ == "__main__":
    sys.exit(main())