File size: 93,052 Bytes
cff1a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425a800
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cff1a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425a800
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cff1a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
#!/usr/bin/env python3
"""Build components/google-math: Google math-paper artifacts in Cayley-Math format.

One component, eight upstream subsets. Mirrors components/openai-math exactly:
same record core fields, same Parquet encoding, same SHA256-ordered group split
policy, and the same mmla-type2-packed-v1 packing code.

Nothing here verifies mathematics. No Lean project is compiled, no proof is
checked, and generated QA pairs are generator output rather than research
mathematics.
"""
from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import math
import re
import shutil
import subprocess
from collections import Counter, deque
from pathlib import Path

COMPONENT = 'google-math'
CORE = ('id', 'text', 'group', 'license', 'paper_id', 'split', 'record_type', 'source_url')
SPLITS = ('train', 'dev', 'test')
SEQ_LEN = 2048
SHARD_ROWS = 256
IGNORED_LOCAL = {'.DS_Store', 'manifest.json', 'validation.json'}

# ---------------------------------------------------------------------------
# Source registry. Every included source is a Google or Google DeepMind
# publication that ships math text, and every entry pins a fixed revision.
# ---------------------------------------------------------------------------
SOURCES = {
    'alphaproof-nexus': {
        'name': 'AlphaProof Nexus results',
        'repository': 'https://github.com/google-deepmind/alphaproof-nexus-results',
        'commit': '0647711a71183c1ea492ad60860776617ce1ea88',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'Lean math proofs generated by AlphaProof Nexus and accompanying natural language prose proofs',
        'checkout': 'alphaproof-nexus-results',
        'dir': 'alphaproof-nexus-results',
        'math_content': 'proofs',
    },
    'formal-conjectures': {
        'name': 'Formal Conjectures',
        'repository': 'https://github.com/google-deepmind/formal-conjectures',
        'commit': '6751c0f043985ac6647db28a45a63afdf21acffe',
        'license': 'Apache-2.0',
        'creators': ['The Formal Conjectures Authors', 'Google LLC'],
        'paper': 'Formalised statements of mathematical conjectures in Lean, arXiv:2605.13171',
        'checkout': 'formal-conjectures',
        'dir': 'formal-conjectures',
        'math_content': 'formal_statements',
    },
    'formal-imo': {
        'name': 'formal-imo benchmark',
        'repository': 'https://github.com/google-deepmind/formal-imo',
        'commit': 'a85d84b97c8e88a352c136b1e29c355139609bea',
        'license': 'Apache-2.0',
        'creators': ['Google LLC'],
        'paper': 'Lean 4 formalizations of International Mathematical Olympiad problem statements',
        'checkout': 'formal-imo',
        'dir': 'formal-imo',
        'math_content': 'formal_statements',
    },
    'formal-putnam-like': {
        'name': 'Putnam-like problems in Lean',
        'repository': 'https://github.com/google-deepmind/formal-putnam-like',
        'commit': '636c2d46b3a7d7e77a9f58209b0c17816f8d172b',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'Lean 4 formalizations of Putnam-like problems (eval_hub putnam_like companion)',
        'checkout': 'formal-putnam-like',
        'dir': 'formal-putnam-like',
        'math_content': 'formal_statements',
    },
    'cryptids': {
        'name': 'Cryptids: conjecture-checking and Busy Beaver Turing machines',
        'repository': 'https://github.com/google-deepmind/cryptids',
        'commit': '3647718b5df22e1a61462dec0376bd204526285a',
        'commit_source': 'the checkout as of this build; recorded because the repository moves',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'Certified Turing-machine reductions and Busy Beaver proofs, arXiv:2610.22603',
        'checkout': 'cryptids',
        'dir': 'cryptids',
        'math_content': 'proofs',
    },
    'mathematics-dataset': {
        'name': 'Mathematics Dataset generator',
        'repository': 'https://github.com/google-deepmind/mathematics_dataset',
        'commit': '427f45075f84b8b9774950196ad63867ca20ffb3',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'Analysing Mathematical Reasoning Abilities of Neural Models (Saxton, Grefenstette, Hill, Kohli), ICLR 2018',
        'checkout': 'mathematics_dataset',
        'generated': 'mathematics_dataset_sample.jsonl',
        'math_content': 'generated_qa',
    },
    'alphageometry': {
        'name': 'AlphaGeometry geometry problem artifacts',
        'repository': 'https://github.com/google-deepmind/alphageometry',
        'commit': '6777cb586cbb46beed28db12dc72c69770b68337',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'Solving Olympiad Geometry without Human Demonstrations, Nature 2024',
        'checkout': 'alphageometry',
        'dir': 'alphageometry',
        'math_content': 'problem_statements',
    },
    'mathematics-conjectures': {
        'name': 'Mathematics conjectures companion notebooks',
        'repository': 'https://github.com/google-deepmind/mathematics_conjectures',
        'commit': '8302f29101019434e5a0a25807a4e42cd9d96414',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'Advancing mathematics by guiding human intuition with AI, Nature 2021',
        'checkout': 'mathematics_conjectures',
        'dir': 'mathematics_conjectures',
        'math_content': 'natural_language_math',
    },
    # --- Added after the widened scan's three undecided candidates were measured. ---
    # Only the notebook artifacts of these repositories ship mathematical text: the
    # problem statements, the discovered constructions and the constructions' code.
    # Search harnesses, compressed caches and serialised index dumps are excluded
    # below with their measured sizes.
    'alphaevolve': {
        'name': 'AlphaEvolve mathematical constructions',
        'repository': 'https://github.com/google-deepmind/alphaevolve',
        'commit': 'c42694909d50f92cb01c2d50916f022b1c7e74d1',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'AlphaEvolve: A coding agent for scientific and algorithmic discovery',
        'checkout': 'alphaevolve',
        'dir': 'alphaevolve',
        'area': 'maths/**/verification.ipynb only',
        'math_content': 'constructions',
        'notebook_root': 'maths',
    },
    'alphaevolve_results': {
        'name': 'AlphaEvolve results notebook',
        'repository': 'https://github.com/google-deepmind/alphaevolve_results',
        'commit': '4226acbf237ff9ad10ba7673a2af127a2d8a5971',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'AlphaEvolve results: improved constructions and bounds reported in the AlphaEvolve paper',
        'checkout': 'alphaevolve_results',
        'dir': 'alphaevolve_results',
        'area': 'mathematical_results.ipynb only',
        'math_content': 'constructions',
        'notebook_root': '',
    },
    'funsearch': {
        'name': 'FunSearch mathematical discoveries',
        'repository': 'https://github.com/google-deepmind/funsearch',
        'commit': 'cc53f274237d7ab05c19df939edbc1f9616a7c19',
        'license': 'Apache-2.0',
        'creators': ['Google DeepMind'],
        'paper': 'Mathematical discoveries from program search with large language models, Nature 2023',
        'checkout': 'funsearch',
        'dir': 'funsearch',
        'area': 'cap_set, admissible_set, bin_packing, cyclic_graphs notebooks only',
        'math_content': 'constructions',
        'notebook_root': 'problems',
    },
}

# Candidates found by the widened scan and deliberately not included.
EXCLUDED_CANDIDATES = [
    {'repository': 'google-deepmind/eval_hub', 'area': 'eval_hub/putnam_like, eval_hub/live_math',
     'reason': 'Every problem directory carries a CANARY_ID benchmark-contamination canary '
               '(96 putnam_like problems across Sets 1-8, 250 live_math problems across regular/difficult/multimodal). '
               'live_math is an actively maintained evaluation benchmark whose multimodal problems depend on images '
               'that are not part of this text corpus. Copying them into a pretraining corpus would poison a public '
               'benchmark, so the whole repository is excluded despite being Google-published and Apache-2.0.'},
    {'repository': 'deepmind/aqua_rat', 'area': 'Hugging Face dataset',
     'reason': 'ACC-AQUA-RAT accompanies "Program Synthesis with Large Language Models", a code-generation paper, '
               'not a mathematics paper. The 97,467 rows are grade-school arithmetic word problems, so it fails the '
               'mathematics-paper test even though the license is Apache-2.0.'},
    {'repository': 'deepmind/math_dataset', 'area': 'Hugging Face dataset, 40.0 GB',
     'reason': 'A pre-generated mirror of the same mathematics_dataset paper already represented here. Included '
               'through the official generator at a pinned commit instead, which keeps provenance exact and avoids '
               'pulling 40 GB over the wire.'},
    {'repository': 'google-research/math-opt-benchmark',
     'area': 'C++ Bazel workspace',
     'reason': 'Ships no math text: only C++ sources plus download_data.sh, which fetches external instances at build '
               'time. Code-only utility with no shipped statements, proofs or generator.'},
    {'repository': 'google/mathsteps', 'area': 'JavaScript library',
     'reason': 'A step-by-step equation solver library with 76 lib and 55 test files and no shipped math corpus. '
               'It is an equation-solving utility, not an artifact of a mathematics paper.'},
    {'repository': 'google-deepmind/cartesian-frames', 'area': 'HOL4 .sml proof scripts',
     'reason': 'Formalises the Cartesian Frames sequence from the Alignment Forum, which is a philosophy-of-agency '
               'blog series rather than a mathematics paper, and it is HOL4 SML proof script rather than math text.'},
    {'repository': 'google-deepmind/miniF2F', 'area': 'Lean 4 fork',
     'reason': 'A fork of openai/miniF2F. Only the Lean 4 adaptation is Google work; the corpus itself is not a '
               'Google publication, so including it would import a non-Google mirror.'},
    {'repository': 'google-deepmind/alphageometry2', 'area': 'DDAR solver, 42 KB',
     'reason': 'The 26 olympiad problems live inside Python dict literals in test.py with point coordinates, so they '
               'are code text rather than a math dataset. alphageometry (AG1) already ships 261 olympiad geometry '
               'problems in the AG language verbatim, so AG2 would add solver code and no new math.'},
    {'repository': 'google-deepmind/alphatensor', 'area': 'Python/NumPy',
     'reason': '24 entries of matrix-multiplication search code and README files. No math statements, proofs or '
               'text-bearing artifacts to project.'},
    {'repository': 'google/feabench', 'area': 'Multiphysics benchmark',
     'reason': 'NeurIPS 2024 MATH-AI workshop benchmark for multiphysics reasoning, i.e. physics rather than '
               'mathematics, and its data ships separately.'},
    {'repository': 'google/phasecoder', 'area': 'Audio research code',
     'reason': 'Microphone geometry for spatial audio. The word geometry refers to microphone arrays, not mathematics.'},
    {'repository': 'google-research/pointdit', 'area': 'Diffusion model code',
     'reason': 'Monocular geometry estimation for images. Not a mathematics paper.'},
    {'repository': 'google/tree-math, google/mathfu, google/vector_math.dart, google-research/opengrm',
     'area': 'Software libraries',
     'reason': 'Math-named software libraries (JAX pytree ops, a C++ game math library, a Dart vector package, n-gram '
               'libraries). Code-only utilities with no math text and no mathematics paper.'},
    {'repository': 'google/research/mathlists, google-deepmind/isabelle_llm',
     'area': 'Probed repositories',
     'reason': 'Neither resolves: no repository exists at these paths, so there is nothing to include.'},
]

MATH_CONTENT = {
    'formal_statements': 'formal_statement',
    'proofs': 'proof',
    'natural_language_math': 'natural_language_math',
    'generated_qa': 'generated_qa',
    'constructions': 'construction',
    'problem_statements': 'problem_statement',
    'none': 'none',
}

# Sub-paths of included repositories that were measured and left out. Kept separate from
# `EXCLUDED_CANDIDATES` so that `included` and `excluded_candidates` stay disjoint: every
# repository appears in exactly one of them.
EXCLUDED_SUBPATHS = [
    {'repository': 'google-deepmind/alphaevolve',
     'included_source_id': 'alphaevolve',
     'area': 'omega/',
     'math_content': 'none',
     'measured_bytes': 45511025,
     'reason': 'Excluded on measured evidence: the omega/ directory a first scan flagged is a search harness plus '
               'one compressed cache. 44,267,872 of its 45,511,025 bytes are the single .xz archive '
               'clean_level4.npz.xz; its 1,126,802-byte verification notebook is 1,098,419 characters of code of '
               'which 836,374 characters are decimal digits, i.e. rational vectors written as Python literals for a '
               '20 GB verification run. No statements, proofs or prose to project.'},
    {'repository': 'google-deepmind/alphaevolve',
     'included_source_id': 'alphaevolve',
     'area': 'src/, maths/**/*.py, maths/**/config*.yaml, matmul_tensor_decompositions/',
     'math_content': 'none',
     'measured_bytes': 1165195,
     'reason': 'Excluded on measured evidence: src/ is the 11-file, 58,453-byte AlphaEvolve search harness with no '
               'math text; maths/**/*.py is 87,725 bytes of initial search programs and maths/**/config*.yaml is '
               '60,949 bytes of run configuration; matmul_tensor_decompositions/ is 827,894 bytes of two '
               'notebooks whose projections share 4,820 of 4,830 substantial lines with the included '
               'alphaevolve_results notebook, so they would be near-duplicates.'},
    {'repository': 'google-deepmind/funsearch',
     'included_source_id': 'funsearch',
     'area': '**/*.txt, implementation/*.py',
     'math_content': 'none',
     'measured_bytes': 20442546,
     'reason': 'Excluded on measured evidence: 13 .txt files hold 20,389,203 bytes of comma-separated integer tuples '
               '(admissible_set_n24_w17_size237984.txt alone is 17,372,832 bytes). They serialise exactly the sets the '
               'included notebooks build and assert, so they add serialization rather than math text. '
               'implementation/ is 53,343 bytes of the FunSearch evolutionary algorithm, a program-search harness.'},
]

PDF_ARTIFACT_RANGES = (
    ('c0_c1_control', 0x00, 0x1F),
    ('c1_control', 0x7F, 0x9F),
    ('replacement_char', 0xFFFD, 0xFFFD),
    ('private_use', 0xE000, 0xF8FF),
    ('ligature_block', 0xFB00, 0xFB06),
    ('combining_mark', 0x0300, 0x036F),
)


def canonical(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))


def sha(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b''):
            h.update(chunk)
    return h.hexdigest()


def write_json(path, obj):
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    Path(path).write_text(json.dumps(obj, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')


def write_jsonl(path, rows):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.suffix == '.gz':
        with path.open('wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0) as gz:
            for row in rows:
                gz.write((canonical(row) + '\n').encode('utf-8'))
    else:
        with path.open('w', encoding='utf-8') as f:
            for row in rows:
                f.write(canonical(row) + '\n')


def write_parquet(path, rows):
    import pyarrow as pa
    import pyarrow.parquet as pq
    columns = {key: [str(row.get(key) or '') for row in rows] for key in CORE}
    columns['metadata_json'] = [canonical({k: v for k, v in row.items() if k not in CORE}) for row in rows]
    schema = pa.schema([(key, pa.string()) for key in (*CORE, 'metadata_json')])
    pq.write_table(pa.Table.from_pydict(columns, schema=schema), path, compression='zstd', row_group_size=1024)


def split_groups(groups):
    """Identical policy to components/openai-math/tools/finalize_openai_math.py."""
    ordered = sorted(groups, key=lambda g: (hashlib.sha256(g.encode()).hexdigest(), g))
    if len(ordered) < 3:
        raise ValueError('Need at least 3 groups for nonempty leakage-safe splits')
    holdout = max(1, math.ceil(len(ordered) * .01))
    if 2 * holdout >= len(ordered):
        holdout = 1
    return {g: ('dev' if i < holdout else 'test' if i < 2 * holdout else 'train') for i, g in enumerate(ordered)}


def pack_split(root, split, records, sp, seq_len=SEQ_LEN, shard_rows=SHARD_ROWS):
    """Copied verbatim in behaviour from components/openai-math/tools/finalize_openai_math.py."""
    import numpy as np
    packed = root / 'packed'
    packed.mkdir(exist_ok=True)
    shard_entries, pending_rows, pending_labels, pending_attrs = [], [], [], []
    buffer, docs, stream_start, total_tokens, label_count, row_number = [], deque(), 0, 0, 0, 0
    attr_file = (packed / f'{split}-rows.jsonl').open('w', encoding='utf-8')
    token_file = (packed / f'{split}-records.jsonl').open('w', encoding='utf-8')

    def flush():
        nonlocal pending_rows, pending_labels, pending_attrs
        if not pending_rows:
            return
        shard = len(shard_entries)
        fields = {}
        arrays = {'input_ids': np.asarray(pending_rows, dtype=np.int32),
                  'labels': np.asarray(pending_labels, dtype=np.int32),
                  'role_ids': np.zeros((len(pending_rows), seq_len), dtype=np.int32)}
        for name, array in arrays.items():
            path = packed / f'{split}-{shard:06d}-{name}.npy'
            np.save(path, array, allow_pickle=False)
            fields[name] = {'path': path.name, 'sha256': sha(path), 'bytes': path.stat().st_size,
                            'dtype': 'int32', 'shape': list(array.shape)}
        shard_entries.append({'count': len(pending_rows), 'fields': fields})
        for index, attr in enumerate(pending_attrs):
            attr.update(shard=shard, shard_row=index)
            attr_file.write(canonical(attr) + '\n')
        pending_rows, pending_labels, pending_attrs = [], [], []

    def emit():
        nonlocal buffer, stream_start, label_count, row_number
        n = min(seq_len, len(buffer))
        values = buffer[:n]
        targets = buffer[1:min(n + 1, len(buffer))]
        if len(targets) < n:
            targets.append(-100)
        targets = [-100 if t == 1 else t for t in targets]
        label_count += sum(t != -100 for t in targets)
        pending_rows.append(values + [0] * (seq_len - n))
        pending_labels.append(targets + [-100] * (seq_len - n))
        stop = stream_start + n
        spans = []
        for doc in docs:
            lo, hi = max(stream_start, doc['start']), min(stop, doc['end'])
            if lo < hi:
                spans.append({'record_id': doc['id'], 'paper_id': doc['paper_id'],
                              'row_start': lo - stream_start, 'row_end': hi - stream_start,
                              'record_start': lo - doc['start'], 'record_end': hi - doc['start']})
        pending_attrs.append({'row': row_number, 'stream_start': stream_start, 'length': n, 'segments': spans})
        row_number += 1
        stream_start = stop
        del buffer[:n]
        while docs and docs[0]['end'] <= stream_start:
            docs.popleft()
        if len(pending_rows) == shard_rows:
            flush()

    for record in records:
        tokens = [1] + sp.encode(record['text'], out_type=int) + [2]
        array = np.asarray(tokens, dtype='<i4')
        token_file.write(canonical({'id': record['id'], 'paper_id': record['paper_id'], 'tokens': len(tokens),
                                    'token_sha256': hashlib.sha256(array.tobytes()).hexdigest()}) + '\n')
        docs.append({'id': record['id'], 'paper_id': record['paper_id'], 'start': total_tokens,
                     'end': total_tokens + len(tokens)})
        total_tokens += len(tokens)
        buffer.extend(tokens)
        while len(buffer) >= seq_len + 1:
            emit()
    if buffer:
        emit()
    flush()
    attr_file.close()
    token_file.close()
    return shard_entries, {'rows': row_number, 'tokens': total_tokens, 'loss_bearing_labels': label_count}


def write_manifest(root):
    entries = []
    for path in sorted(root.rglob('*')):
        relative = path.relative_to(root).as_posix()
        if path.is_file() and relative not in IGNORED_LOCAL and '.tmp' not in path.name:
            entries.append({'path': relative, 'bytes': path.stat().st_size, 'sha256': sha(path)})
    write_json(root / 'manifest.json', {'format': 'cayley-contribution-file-manifest-v1',
                                        'excludes': sorted(IGNORED_LOCAL), 'files': entries})


def extract_pdf(path):
    import pypdf
    reader = pypdf.PdfReader(str(path))
    pages = [page.extract_text() or '' for page in reader.pages]
    raw = '\n'.join(pages)
    control = sum(1 for c in raw if (ord(c) < 32 and c not in '\n\t') or 0x7F <= ord(c) <= 0x9F)
    text = ''.join(' ' if (ord(c) < 32 and c not in '\n\t') or 0x7F <= ord(c) <= 0x9F else c for c in raw)
    text = '\n'.join(line.rstrip() for line in text.split('\n'))
    text = re.sub(r'\n{3,}', '\n\n', text).strip() + '\n'
    non_ascii = sum(1 for c in text if ord(c) > 127)
    artifacts = Counter()
    for name, lo, hi in PDF_ARTIFACT_RANGES:
        artifacts[name] = sum(1 for c in text if lo <= ord(c) <= hi)
    return {
        'text': text,
        'pages': len(pages),
        'raw_characters': len(raw),
        'characters': len(text),
        'page_characters': [len(page) for page in pages],
        'non_ascii_characters': non_ascii,
        'non_ascii_ratio': round(non_ascii / len(text), 6) if text else 0.0,
        'control_characters_replaced': control,
        'artifact_characters': {k: v for k, v in artifacts.items() if v},
    }


# ---------------------------------------------------------------------------
# Per-source record builders.
# ---------------------------------------------------------------------------
def base_record(source_id, group, paper_id, record_type, source_url, path, digest, text, license_id):
    return {
        'id': None,
        'text': text,
        'group': group,
        'license': license_id,
        'paper_id': paper_id,
        'split': None,
        'record_type': record_type,
        'source_url': source_url,
        'source_id': source_id,
        'source_path': path,
        'source_sha256': digest,
        'text_sha256': hashlib.sha256(text.encode('utf-8')).hexdigest(),
        'creators': SOURCES[source_id]['creators'],
        'math_content': SOURCES[source_id].get('math_content', 'none'),
        'verification_status': 'unverified_source_claim',
        'lean_verified': False,
        'mathematical_verification': 'not_performed',
    }


def build_alphaproof_nexus(root, source_id, checkout, files, seen):
    """The staged AlphaProof Nexus projection, reused unchanged (83 records)."""
    source = SOURCES[source_id]
    commit, repo = source['commit'], source['repository']
    records = []
    for rel in files:
        path = checkout / rel
        digest = sha(path)
        stem = Path(rel).stem
        if rel.endswith('.lean'):
            text = path.read_text(encoding='utf-8')
            group = lean_group(rel)
            record_type, origin = 'formal_lean_proof', 'source_verbatim'
            quality, transform = 'verbatim_source_text', 'identity_verbatim_bytes'
            metrics = {'source_characters': len(text)}
        elif rel.endswith('.pdf'):
            extracted = extract_pdf(path)
            group = pdf_group(rel)
            text = extracted.pop('text')
            record_type, origin = 'natural_language_proof', 'source_pdf_extraction'
            quality = 'lossy_pdf_text_layer'
            transform = 'pypdf_page_text_control_chars_replaced_blank_runs_collapsed'
            metrics = extracted
            global EXTRACTION_AUDIT
            EXTRACTION_AUDIT.append({'source_id': source_id, 'source_path': rel, **metrics,
                                     'extraction_quality': quality,
                                     'source_url': f'{repo}/blob/{commit}/{rel}'})
        else:
            continue
        kind = 'lean' if rel.endswith('.lean') else 'nl'
        upstream_group = group
        group = f'{source_id}::{upstream_group}'
        record = base_record(source_id, group, upstream_group, record_type,
                             f'{repo}/blob/{commit}/{rel}', rel, digest, text, source['license'])
        record['id'] = f'{COMPONENT}:{source_id}:{upstream_group}:{kind}:{stem}'
        record['upstream_group'] = upstream_group
        record['content_origin'] = origin
        record['transform'] = transform
        record['extraction_quality'] = quality
        record['extraction_metrics'] = metrics
        record['upstream_category'] = rel.split('/')[1]
        record['source_commit'] = commit
        records.append(record)
    return records


def lean_group(rel):
    """Problem-stem group for an APNOutputs Lean file (unchanged from the staged build)."""
    parts = Path(rel).parts
    category, stem = parts[1], Path(rel).stem
    if category == 'ErdosProblems':
        return 'erdos_' + stem.split('_')[1].split('.')[0]
    if category == 'OEIS':
        tokens = stem.split('_')
        ident = tokens[1] if tokens[0].lower() == 'oeis' else tokens[0]
        return 'oeis_' + ident.lower()
    if category == 'StacksProject':
        return 'stacks_project'
    if category == 'AICollaborator':
        subject = parts[2]
        if stem.startswith('hilbert_functions'):
            return 'ai_hilbert_functions'
        if stem == 'bipartite_graph_reconstruction_conjecture_2':
            return 'ai_graph_reconstruction'
        return 'ai_' + subject.lower()
    raise ValueError(f'Unknown Lean category: {rel}')


def pdf_group(rel):
    """Problem-stem group for a NaturalLanguageProofs PDF (unchanged from the staged build)."""
    category, stem = Path(rel).parts[1], Path(rel).stem
    if category == 'ErdosProblems':
        match = re.fullmatch(r'erdos(\d+)(i{1,2})?', stem)
        if not match:
            raise ValueError(f'Unparsed Erdos PDF name: {rel}')
        return 'erdos_' + match.group(1)
    if category == 'OEIS':
        match = re.fullmatch(r'oeis_(\d+)', stem.lower())
        if not match:
            raise ValueError(f'Unparsed OEIS PDF name: {rel}')
        return 'oeis_' + match.group(1)
    if category == 'AICollaborator':
        if stem == 'hilbert':
            return 'ai_hilbert_functions'
        if stem == 'graph_reconstruction':
            return 'ai_graph_reconstruction'
    raise ValueError(f'Unpaired PDF name: {rel}')


def build_lean_corpus(source_id, checkout, files, record_type):
    """Verbatim projection of Lean source text, one record per file."""
    source = SOURCES[source_id]
    commit, repo = source['commit'], source['repository']
    records = []
    for rel in files:
        path = checkout / rel
        text = path.read_text(encoding='utf-8')
        if not text.strip():
            continue
        group = f'{source_id}::{rel[:-len(".lean")]}'
        record = base_record(source_id, group, group, record_type,
                             f'{repo}/blob/{commit}/{rel}', rel, sha(path), text, source['license'])
        record['id'] = f'{COMPONENT}:{source_id}:{rel[:-len(".lean")]}'
        record['content_origin'] = 'source_verbatim'
        record['transform'] = 'identity_verbatim_bytes'
        record['extraction_quality'] = 'verbatim_source_text'
        record['source_commit'] = commit
        record['source_characters'] = len(text)
        records.append(record)
    return records


def build_alphageometry(source_id, checkout):
    """Verbatim problem statements from the AG language text artifacts."""
    source = SOURCES[source_id]
    commit, repo = source['commit'], source['repository']
    records = []
    pairs = {'examples.txt': 'library_example', 'imo_ag_30.txt': 'olympiad_geometry_problem',
             'jgex_ag_231.txt': 'jgex_geometry_problem'}
    for name, kind in pairs.items():
        path = checkout / name
        lines = [line.strip() for line in path.read_text(encoding='utf-8').splitlines()]
        body = [line for line in lines if line and not line.startswith('#')]
        if len(body) % 2:
            raise ValueError(f'{name}: odd number of problem lines ({len(body)})')
        for index in range(0, len(body), 2):
            problem_id, statement = body[index], body[index + 1]
            text = f'{problem_id}\n{statement}\n'
            group = f'{source_id}::{name}::{problem_id}'
            record = base_record(source_id, group, group, 'formal_geometry_problem',
                                 f'{repo}/blob/{commit}/{name}', name, sha(path), text, source['license'])
            record['id'] = f'{COMPONENT}:{source_id}:{name}:{problem_id}'
            record['content_origin'] = 'source_verbatim'
            record['transform'] = 'identity_verbatim_lines'
            record['extraction_quality'] = 'verbatim_source_text'
            record['source_commit'] = commit
            record['geometry_problem_id'] = problem_id
            record['geometry_problem_kind'] = kind
            record['source_line'] = index + 1
            records.append(record)
    for name in ('defs.txt', 'rules.txt'):
        path = checkout / name
        text = path.read_text(encoding='utf-8')
        group = f'{source_id}::{name}'
        record = base_record(source_id, group, group, 'geometry_rule_table',
                             f'{repo}/blob/{commit}/{name}', name, sha(path), text, source['license'])
        record['id'] = f'{COMPONENT}:{source_id}:{name}'
        record['content_origin'] = 'source_verbatim'
        record['transform'] = 'identity_verbatim_bytes'
        record['extraction_quality'] = 'verbatim_source_text'
        record['source_commit'] = commit
        records.append(record)
    return records


def build_mathematics_dataset(source_id, generated, params):
    """Seeded projection of the official generator's curriculum."""
    source = SOURCES[source_id]
    commit, repo = source['commit'], source['repository']
    records = []
    for row in generated:
        group = f'{source_id}::{row["regime"]}::{row["module"]}'
        text = row['question'] + '\n' + row['answer'] + '\n'
        record = base_record(source_id, group, row['module'], 'generated_qa_pair',
                             f'{repo}/tree/{commit}', f'generated/{row["regime"]}/{row["module"]}',
                             None, text, source['license'])
        record['id'] = f'{COMPONENT}:{source_id}:{row["regime"]}:{row["module"]}:{row["index"]:05d}'
        record['content_origin'] = 'generator_output'
        record['transform'] = 'identity_generator_question_and_answer_lines'
        record['extraction_quality'] = 'verbatim_generator_output'
        record['source_commit'] = commit
        record['generator_regime'] = row['regime']
        record['generator_module'] = row['module']
        record['generator_index'] = row['index']
        record['generator_seed'] = params['seed']
        record['question'] = row['question']
        record['answer'] = row['answer']
        records.append(record)
    return records


def build_notebooks(source_id, checkout):
    """Notebook cell sources joined by newlines, verbatim."""
    source = SOURCES[source_id]
    commit, repo = source['commit'], source['repository']
    records = []
    for path in sorted(checkout.glob('*.ipynb')):
        notebook = json.loads(path.read_text(encoding='utf-8'))
        cells = [(cell['cell_type'], ''.join(cell['source'])) for cell in notebook['cells']]
        text = '\n'.join(content for _, content in cells)
        group = f'{source_id}::{path.name}'
        record = base_record(source_id, group, path.stem, 'research_notebook',
                             f'{repo}/blob/{commit}/{path.name}', path.name, sha(path), text, source['license'])
        record['id'] = f'{COMPONENT}:{source_id}:{path.stem}'
        record['content_origin'] = 'source_notebook_projection'
        record['transform'] = 'notebook_cell_sources_joined_by_newline'
        record['extraction_quality'] = 'verbatim_cell_text'
        record['source_commit'] = commit
        record['cell_counts'] = dict(Counter(kind for kind, _ in cells))
        EXTRACTION_AUDIT.append({'source_id': source_id, 'source_path': path.name,
                                 'cells': len(cells), 'characters': len(text),
                                 'markdown_cells': sum(1 for k, _ in cells if k == 'markdown'),
                                 'code_cells': sum(1 for k, _ in cells if k == 'code'),
                                 'extraction_quality': 'verbatim_cell_text',
                                 'source_url': f'{repo}/blob/{commit}/{path.name}'})
        records.append(record)
    return records


def strip_notebook_outputs(path, relative):
    """Return the notebook's cell sources with every output and execution counter removed.

    A record must carry the notebook's source text, never executed output or embedded
    base64. When a notebook has output blobs, the projection drops only those, keeps
    every cell's code and markdown verbatim, and records the byte cost of what it
    stripped so the drop is measurable rather than silent.
    """
    notebook = json.loads(Path(path).read_text(encoding='utf-8'))
    cells = [(cell['cell_type'], ''.join(cell['source'])) for cell in notebook['cells']]
    output_cells = sum(1 for cell in notebook['cells'] if cell.get('outputs'))
    output_count = sum(len(cell.get('outputs') or []) for cell in notebook['cells'])
    output_bytes = sum(len(json.dumps(cell.get('outputs') or [], ensure_ascii=False).encode('utf-8'))
                       for cell in notebook['cells'])
    image_bytes = 0
    for cell in notebook['cells']:
        for output in cell.get('outputs') or []:
            for mime, value in (output.get('data') or {}).items():
                if mime.startswith('image/'):
                    image_bytes += len(value if isinstance(value, str) else ''.join(value))
    text = '\n'.join(content for _, content in cells)
    stripped = {
        'cells_with_outputs': output_cells,
        'output_objects_removed': output_count,
        'output_bytes_removed': output_bytes,
        'embedded_image_bytes_removed': image_bytes,
        'projection_rule': 'cell sources joined by a newline; outputs and execution counters dropped',
    }
    return text, cells, stripped


def build_notebook_files(source_id, checkout, files):
    """Verbatim cell-source projection of the notebooks a source actually ships."""
    source = SOURCES[source_id]
    commit, repo = source['commit'], source['repository']
    records, audit = [], []
    for relative in files:
        path = checkout / relative
        text, cells, stripped = strip_notebook_outputs(path, relative)
        group = f'{source_id}::{relative}'
        record = base_record(source_id, group, relative, 'research_notebook',
                             f'{repo}/blob/{commit}/{relative}', relative, sha(path), text,
                             source['license'])
        record['id'] = f'{COMPONENT}:{source_id}:{relative[:-len(".ipynb")]}'
        record['content_origin'] = 'source_notebook_projection'
        record['transform'] = 'notebook_cell_sources_joined_by_newline_outputs_stripped'
        record['extraction_quality'] = 'verbatim_cell_text'
        record['source_commit'] = commit
        record['math_content'] = source['math_content']
        record['cell_counts'] = dict(Counter(kind for kind, _ in cells))
        record['stripped_outputs'] = stripped
        records.append(record)
        audit.append({'source_id': source_id, 'source_path': relative, 'cells': len(cells),
                      'characters': len(text),
                      'markdown_cells': sum(1 for k, _ in cells if k == 'markdown'),
                      'code_cells': sum(1 for k, _ in cells if k == 'code'),
                      'extraction_quality': 'verbatim_cell_text', **stripped,
                      'source_url': f'{repo}/blob/{commit}/{relative}'})
    return records, audit


EXTRACTION_AUDIT = []


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--component', type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument('--source-root', type=Path, required=False,
                        help='Directory holding the pinned checkouts of every included repository')
    parser.add_argument('--generated-root', type=Path, required=False,
                        help='Directory holding the pinned mathematics_dataset generator sample')
    parser.add_argument('--tokenizer', type=Path,
                        default=Path('/Users/zxy/Cayley-Math/tokenizer/tokenizer.model'))
    parser.add_argument('--pack', action='store_true')
    parser.add_argument('--manifest-only', action='store_true',
                        help='Rewrite manifest.json from the current directory contents and exit')
    args = parser.parse_args()
    root = args.component.resolve()
    if args.manifest_only:
        stats = json.loads((root / 'statistics.json').read_text(encoding='utf-8'))
        write_readme(root, stats, stats['per_source'])
        write_manifest(root)
        print(json.dumps({'manifest': 'rewritten',
                          'files': len(json.loads((root / 'manifest.json').read_text())['files'])}, indent=2))
        return
    src = args.source_root.resolve()

    # --- pin every checkout and refuse to build against a drifting revision ---
    for source_id, source in SOURCES.items():
        checkout = src / source['checkout']
        if not checkout.is_dir():
            raise ValueError(f'Missing pinned checkout for {source_id}: {checkout}')
        if source.get('generated') or not source.get('commit'):
            continue
        live = subprocess.check_output(['git', '-C', str(checkout), 'rev-parse', 'HEAD'], text=True).strip()
        if live != source['commit']:
            raise ValueError(f'{source_id} checkout {live} differs from pinned {source["commit"]}')

    generated_path = args.generated_root.resolve() / SOURCES['mathematics-dataset']['generated']
    generated = [json.loads(line) for line in generated_path.read_text(encoding='utf-8').splitlines() if line]
    gen_params = json.loads(Path(str(generated_path) + '.params.json').read_text(encoding='utf-8'))

    all_files = []
    records = []

    # 1. AlphaProof Nexus (verbatim staged projection, 83 records)
    apn = src / SOURCES['alphaproof-nexus']['checkout']
    apn_files = sorted(p.relative_to(apn).as_posix() for p in apn.rglob('*')
                       if p.is_file() and '.git' not in p.parts and p.suffix in ('.lean', '.pdf'))
    records += build_alphaproof_nexus(root, 'alphaproof-nexus', apn, apn_files, None)
    all_files += [{'source_id': 'alphaproof-nexus', 'path': rel} for rel in apn_files]

    # 2. Formal Conjectures library (statements only; tests and build scripts excluded)
    fc = src / SOURCES['formal-conjectures']['checkout']
    fc_files = sorted(p.relative_to(fc).as_posix() for p in fc.rglob('*.lean')
                      if '.git' not in p.parts
                      and p.relative_to(fc).parts[0] in ('FormalConjectures', 'FormalConjecturesForMathlib',
                                                         'FormalConjecturesUtil'))
    records += build_lean_corpus('formal-conjectures', fc, fc_files, 'formal_lean_statement')
    all_files += [{'source_id': 'formal-conjectures', 'path': rel} for rel in fc_files]

    # 3. formal-imo
    imo = src / SOURCES['formal-imo']['checkout']
    imo_files = sorted(p.relative_to(imo).as_posix() for p in imo.rglob('*.lean')
                       if '.git' not in p.parts and p.relative_to(imo).parts[0] == 'Imo')
    records += build_lean_corpus('formal-imo', imo, imo_files, 'formal_lean_statement')
    all_files += [{'source_id': 'formal-imo', 'path': rel} for rel in imo_files]

    # 4. formal-putnam-like
    pl = src / SOURCES['formal-putnam-like']['checkout']
    pl_files = sorted(p.relative_to(pl).as_posix() for p in pl.rglob('*.lean')
                      if '.git' not in p.parts and p.relative_to(pl).parts[0] == 'PutnamLike')
    records += build_lean_corpus('formal-putnam-like', pl, pl_files, 'formal_lean_statement')
    all_files += [{'source_id': 'formal-putnam-like', 'path': rel} for rel in pl_files]

    # 5. Cryptids (whole Lean library, including the Busy Beaver holdout proofs)
    cr = src / SOURCES['cryptids']['checkout']
    cr_files = sorted(p.relative_to(cr).as_posix() for p in cr.rglob('*.lean') if '.git' not in p.parts)
    records += build_lean_corpus('cryptids', cr, cr_files, 'formal_lean_proof')
    all_files += [{'source_id': 'cryptids', 'path': rel} for rel in cr_files]

    # 6. Mathematics Dataset generator sample
    records += build_mathematics_dataset('mathematics-dataset', generated, gen_params)
    all_files.append({'source_id': 'mathematics-dataset', 'path': f'generated/{generated_path.name}',
                      'generated_bytes': generated_path.stat().st_size,
                      'generated_sha256': sha(generated_path)})

    # 7. AlphaGeometry text artifacts
    ag = src / SOURCES['alphageometry']['checkout']
    ag_files = [name for name in ('examples.txt', 'imo_ag_30.txt', 'jgex_ag_231.txt', 'defs.txt', 'rules.txt')]
    records += build_alphageometry('alphageometry', ag)
    all_files += [{'source_id': 'alphageometry', 'path': rel} for rel in ag_files]

    # 8. Mathematics conjectures notebooks
    mc = src / SOURCES['mathematics-conjectures']['checkout']
    mc_files = sorted(p.name for p in mc.glob('*.ipynb'))
    records += build_notebooks('mathematics-conjectures', mc)
    all_files += [{'source_id': 'mathematics-conjectures', 'path': rel} for rel in mc_files]

    # 9. AlphaEvolve maths/ verification notebooks (16 notebooks over 15 problem directories)
    ae = src / SOURCES['alphaevolve']['checkout']
    ae_files = sorted(p.relative_to(ae).as_posix() for p in (ae / SOURCES['alphaevolve']['notebook_root']).rglob('verification*.ipynb'))
    ae_records, ae_audit = build_notebook_files('alphaevolve', ae, ae_files)
    records += ae_records
    all_files += [{'source_id': 'alphaevolve', 'path': rel} for rel in ae_files]
    EXTRACTION_AUDIT.extend(ae_audit)

    # 10. AlphaEvolve results notebook (one notebook, 36 markdown cells and 92 code cells)
    aer = src / SOURCES['alphaevolve_results']['checkout']
    aer_files = ['mathematical_results.ipynb']
    aer_records, aer_audit = build_notebook_files('alphaevolve_results', aer, aer_files)
    records += aer_records
    all_files += [{'source_id': 'alphaevolve_results', 'path': rel} for rel in aer_files]
    EXTRACTION_AUDIT.extend(aer_audit)

    # 11. FunSearch problem notebooks (four: cap_set, admissible_set, bin_packing, cyclic_graphs)
    fs = src / SOURCES['funsearch']['checkout']
    fs_dirs = ('cap_set', 'admissible_set', 'bin_packing', 'cyclic_graphs')
    fs_files = sorted(p.relative_to(fs).as_posix() for p in fs.rglob('*.ipynb')
                      if p.relative_to(fs).parts[0] in fs_dirs)
    fs_records, fs_audit = build_notebook_files('funsearch', fs, fs_files)
    records += fs_records
    all_files += [{'source_id': 'funsearch', 'path': rel} for rel in fs_files]
    EXTRACTION_AUDIT.extend(fs_audit)

    # --- exact text dedup ---
    duplicates, seen = [], {}
    kept = []
    for record in records:
        digest = record['text_sha256']
        if digest in seen:
            duplicates.append({'excluded_id': record['id'], 'kept_id': seen[digest],
                               'source_id': record['source_id'], 'group': record['group'],
                               'text_sha256': digest})
            continue
        seen[digest] = record['id']
        kept.append(record)
    records = kept
    ids = [r['id'] for r in records]
    if len(set(ids)) != len(ids):
        raise ValueError('Duplicate record IDs')

    # --- splits, assigned per group ---
    groups = sorted({r['group'] for r in records})
    split_of = split_groups(groups)
    empty = [s for s in SPLITS if s not in split_of.values()]
    if empty:
        raise ValueError(f'Empty splits: {empty}')
    for record in records:
        record['split'] = split_of[record['group']]
        # a group key is namespaced by source, so paper_id stays the upstream work unit
    records.sort(key=lambda r: (r['source_id'], r['group'], r['record_type'], r['source_path'], r['id']))

    split_records = {}
    for split in SPLITS:
        selected = [r for r in records if r['split'] == split]
        if not selected:
            raise ValueError(f'Empty {split} split')
        write_jsonl(root / f'data/{split}.jsonl.gz', selected)
        write_parquet(root / f'data/{split}.parquet', selected)
        split_records[split] = selected

    # --- licenses, one per source subdirectory plus an index ---
    for source_id, source in SOURCES.items():
        checkout = src / source['checkout']
        destination = root / 'licenses' / source_id
        destination.mkdir(parents=True, exist_ok=True)
        license_file = checkout / 'LICENSE'
        if license_file.is_file():
            shutil.copy2(license_file, destination / 'LICENSE')
        else:
            raise ValueError(f'{source_id}: upstream LICENSE missing')
    root_license = (root / 'licenses' / 'alphaproof-nexus' / 'LICENSE').read_text(encoding='utf-8')
    (root / 'LICENSE').write_text(root_license, encoding='utf-8')

    # --- audit ---
    audit = root / 'audit'
    audit.mkdir(parents=True, exist_ok=True)
    source_file_rows = []
    for item in all_files:
        source = SOURCES[item['source_id']]
        if 'generated_sha256' in item:
            source_file_rows.append({
                'source_id': item['source_id'], 'path': item['path'],
                'sha256': item['generated_sha256'], 'bytes': item['generated_bytes'],
                'source_url': f'{source["repository"]}/tree/{source["commit"]}',
                'kind': 'generated_by_pinned_generator',
            })
            continue
        path = (src / source['checkout'] / item['path'])
        source_file_rows.append({
            'source_id': item['source_id'], 'path': item['path'], 'sha256': sha(path),
            'bytes': path.stat().st_size,
            'source_url': f'{source["repository"]}/blob/{source["commit"]}/{item["path"]}',
            'kind': 'upstream_blob',
        })
    write_jsonl(audit / 'source-files.jsonl', source_file_rows)
    write_jsonl(audit / 'extraction.jsonl', EXTRACTION_AUDIT)
    write_jsonl(audit / 'excluded-duplicates.jsonl', duplicates)
    write_json(audit / 'group-splits.json', {
        'format': 'cayley-group-splits-v1',
        'policy': 'sorted SHA256(group), first ceil(1%) groups to dev, next ceil(1%) to test, rest train',
        'group_namespacing': 'every group key starts with its source_id so two upstreams never share a group',
        'splits': split_of,
        'groups_by_source': dict(Counter(g.split('::')[0] for g in groups)),
        'records_by_source': dict(Counter(r['source_id'] for r in records)),
    })
    write_json(audit / 'mathematics-dataset-generation.json', {
        'source_id': 'mathematics-dataset',
        'generator_repository': SOURCES['mathematics-dataset']['repository'],
        'generator_commit': SOURCES['mathematics-dataset']['commit'],
        'driver_script': 'tools/generate_mathematics_dataset_sample.py',
        'projection': 'sampled projection of the paper curriculum, not the paper-complete dataset',
        'measured': {
            'records': len(generated),
            'records_by_regime': dict(Counter(r['regime'] for r in generated)),
            'modules': len({r['module'] for r in generated}),
            'characters': sum(len(r['question']) + len(r['answer']) + 2 for r in generated),
            'records_retained_after_exact_dedup': sum(1 for r in records if r['source_id'] == 'mathematics-dataset'),
            'records_removed_as_exact_duplicates': sum(1 for d in duplicates
                                                       if d['source_id'] == 'mathematics-dataset'),
            'modules_stopped_early': [k for k, v in gen_params.get('module_yield', {}).items() if v['stopped_early']],
        },
        'parameters': gen_params,
    })
    write_json(audit / 'source-scan.json', {
        'format': 'cayley-source-scan-v1',
        'queries': [
            'GitHub search repositories: org:google-deepmind + math|proof|theorem|formal|lean|geometry|olympiad|conjecture',
            'GitHub search repositories: org:google + math|theorem|lean|proof',
            'GitHub search repositories: org:google-research + math|proof|theorem|lean|geometry|olympiad|formal',
            'Direct probes of every candidate named in the brief, plus every google-deepmind repository page 1-2 '
            'filtered on math/theorem/proof/formal/lean/geometry/olympiad/conjecture/arithmetic/algebra keywords',
            'Hugging Face dataset listing: authors google (76 datasets), google-research-datasets (37), deepmind (6)',
        ],
        'included': [{'source_id': sid, **{k: s[k] for k in ('name', 'repository', 'commit', 'license',
                                                              'paper', 'creators', 'math_content')}}
                     for sid, s in SOURCES.items()],
        'excluded_candidates': EXCLUDED_CANDIDATES,
        'excluded_subpaths': EXCLUDED_SUBPATHS,
    })

    # --- packed arrays ---
    packed_stats = {}
    if args.pack:
        import sentencepiece as spm
        sp = spm.SentencePieceProcessor(model_file=str(args.tokenizer))
        if (sp.pad_id(), sp.bos_id(), sp.eos_id(), sp.unk_id(), sp.vocab_size()) != (0, 1, 2, 3, 32768):
            raise ValueError('Unexpected tokenizer special IDs or vocabulary size')
        tokenizer_dir = root / 'tokenizer'
        tokenizer_dir.mkdir(exist_ok=True)
        shutil.copy2(args.tokenizer, tokenizer_dir / 'tokenizer.model')
        packed = root / 'packed'
        packed.mkdir(exist_ok=True)
        for stale in packed.glob('*'):
            if stale.is_file():
                stale.unlink()
        shards = {}
        for split in SPLITS:
            shards[split], packed_stats[split] = pack_split(root, split, split_records[split], sp)
        write_json(packed / 'manifest.json', {
            'format': 'mmla-type2-packed-v1', 'phase': 'pretrain', 'layout': 'lm', 'seq_len': SEQ_LEN,
            'tokenizer': {'kind': 'sentencepiece', 'vocab_size': 32768, 'sha256': sha(args.tokenizer),
                          'path': '../tokenizer/tokenizer.model',
                          'ids': {'pad': 0, 'bos': 1, 'eos': 2, 'unk': 3, 'boundary': 4}},
            'quota_units': 'tokens', 'source': COMPONENT, 'splits': shards, 'statistics': packed_stats,
            'packing': {'stride': SEQ_LEN, 'bos_per_record': True, 'eos_per_record': True,
                        'mask_target_bos': True, 'mask_final_target': True, 'loss_mask': -100,
                        'row_attribution': '{split}-rows.jsonl', 'record_tokens': '{split}-records.jsonl'},
        })
        write_json(audit / 'packing.json', {
            'packer': 'tools/build_google_math.py:pack_split (copied from components/openai-math)',
            'tokenizer_sha256': sha(tokenizer_dir / 'tokenizer.model'),
            'tokenizer_note': 'SentencePiece decode is whitespace-normalising for runs of spaces; every packed row is '
                              'verified by re-encoding.',
            'sequence_length': SEQ_LEN, 'shard_rows': SHARD_ROWS,
        })

    # --- measured upstream bytes per included source, from the pinned checkouts ---
    measured_source_bytes = {}
    for source_id, item in SOURCES.items():
        checkout = src / item['checkout']
        if item.get('notebook_root') == 'problems':
            paths = sorted(p for d in ('cap_set', 'admissible_set', 'bin_packing', 'cyclic_graphs')
                           for p in (checkout / d).glob('*.ipynb'))
        elif 'notebook_root' in item and item['notebook_root']:
            paths = sorted((checkout / item['notebook_root']).rglob('verification*.ipynb'))
        elif 'notebook_root' in item:
            paths = [checkout / 'mathematical_results.ipynb']
        elif item.get('generated'):
            paths = [args.generated_root.resolve() / item['generated']]
        else:
            paths = [p for p in checkout.rglob('*') if p.is_file() and '.git' not in p.parts]
        measured_source_bytes[source_id] = {
            'included_files': len(paths),
            'included_bytes': sum(p.stat().st_size for p in paths),
            'whole_repository_bytes': sum(p.stat().st_size for p in checkout.rglob('*')
                                          if p.is_file() and '.git' not in p.parts),
        }

    # --- statistics ---
    source_stats = {}
    for source_id in SOURCES:
        rows = [r for r in records if r['source_id'] == source_id]
        packed_rows = [r for r in rows if r['split'] == 'train']
        source_stats[source_id] = {
            'math_content': SOURCES[source_id]['math_content'],
            'records': len(rows),
            'groups': len({r['group'] for r in rows}),
            'record_types': dict(Counter(r['record_type'] for r in rows)),
            'text_characters': sum(len(r['text']) for r in rows),
            'upstream_files': sum(1 for x in source_file_rows if x['source_id'] == source_id),
            'split_records': {s: sum(1 for r in rows if r['split'] == s) for s in SPLITS},
        }
    stats = {
        'component': COMPONENT,
        'sources': len(SOURCES),
        'source_commits': {sid: s['commit'] for sid, s in SOURCES.items()},
        'records_before_deduplication': len(records) + len(duplicates),
        'records': len(records),
        'excluded_exact_duplicates': len(duplicates),
        'groups': len(groups),
        'record_types': dict(Counter(r['record_type'] for r in records)),
        'record_type_characters': {t: sum(len(r['text']) for r in records if r['record_type'] == t)
                                   for t in sorted({r['record_type'] for r in records})},
        'math_content_records': dict(Counter(r['math_content'] for r in records)),
        'text_characters': sum(len(r['text']) for r in records),
        'per_source': source_stats,
        'splits': {s: {'records': len(v), 'groups': len({r['group'] for r in v}),
                       'sources': len({r['source_id'] for r in v}),
                       'text_characters': sum(len(r['text']) for r in v)} for s, v in split_records.items()},
        'packed': packed_stats,
        'notebook_projection': {
            'records': sum(1 for r in records if r['record_type'] == 'research_notebook'),
            'cells_with_outputs': sum(a.get('cells_with_outputs', 0) for a in EXTRACTION_AUDIT
                                      if a.get('cells_with_outputs') is not None),
            'output_objects_removed': sum(a.get('output_objects_removed', 0) for a in EXTRACTION_AUDIT),
            'output_bytes_removed': sum(a.get('output_bytes_removed', 0) for a in EXTRACTION_AUDIT),
            'embedded_image_bytes_removed': sum(a.get('embedded_image_bytes_removed', 0) for a in EXTRACTION_AUDIT),
            'bytes_kept': sum(len(r['text'].encode('utf-8')) for r in records
                              if r['record_type'] == 'research_notebook'),
        },
        'math_content': {sid: s['math_content'] for sid, s in SOURCES.items()},
        'mathematical_verification': 'not_performed',
        'lean_compilation': 'not_performed',
    }
    write_json(root / 'statistics.json', stats)

    sources_index = {
        'component': COMPONENT,
        'format': 'cayley-sources-v1',
        'all_records_license': 'per-record',
        'license_index': {sid: {'license': s['license'],
                                'license_file': f'licenses/{sid}/LICENSE',
                                'creators': s['creators']} for sid, s in SOURCES.items()},
        'included': {sid: {
            'name': s['name'],
            'repository': s['repository'],
            'commit': s['commit'],
            'fixed_revision_url': f'{s["repository"]}/tree/{s["commit"]}',
            'license': s['license'],
            'license_file': f'licenses/{sid}/LICENSE',
            'creators': s['creators'],
            'paper': s['paper'],
            'math_content': s['math_content'],
            'math_content_scope': s.get('area', 'whole repository'),
            'measured_bytes': measured_source_bytes.get(sid, {}),
            'records': source_stats[sid]['records'],
            'text_characters': source_stats[sid]['text_characters'],
        } for sid, s in SOURCES.items()},
        'excluded_candidates': EXCLUDED_CANDIDATES,
        'excluded_subpaths': EXCLUDED_SUBPATHS,
        'math_content_classes': list(MATH_CONTENT),
        'math_content_note': 'constructions is the honest class for AlphaEvolve and FunSearch findings: the '
                             'decompositions, coordinate sets and step functions are the results, not proofs of them',
        'excluded_subpaths': EXCLUDED_SUBPATHS,
        'changes': [
            'Verbatim text projection of Lean sources, geometry problem language, notebooks and PDFs; no rewriting',
            'Deterministically seeded sample from the official mathematics_dataset generator at a pinned commit',
            'Group keys namespaced per source so a proof and its prose companion and a generated QA family stay together',
            'Exact text deduplication and deterministic SHA256-ordered group split assignment',
            'Lossless JSONL/Parquet export; SentencePiece causal-window packing in the existing openai-math format',
        ],
        'record_changes': [
            'No text was generated, summarised, translated or repaired beyond PDF control-character handling',
            'Notebook execution outputs and embedded images were dropped; code and markdown cells stay verbatim',
            'PDF text control characters were replaced and blank-line runs collapsed; original bytes stay identified by sha256',
            'No Lean compilation, proof checking or mathematical verification was performed',
        ],
        'mathematical_verification': 'not_performed',
    }
    write_json(root / 'sources.json', sources_index)

    # --- README ---
    write_readme(root, stats, source_stats)
    write_manifest(root)
    print(json.dumps(stats, ensure_ascii=False, indent=2))


def _sum_by_split(mapping, key, splits):
    """Sum one per-split counter out of a gate section keyed by split name."""
    if not isinstance(mapping, dict):
        return 0
    return sum(int((mapping.get(split) or {}).get(key, 0) or 0) for split in splits)


def read_gate_evidence(root, records):
    """Normalise the publish gate into one evidence record, whichever schema it uses.

    The gate has been produced by two different generators. The earlier one reports
    whole-run totals (`rows_decoded`, `segments_compared`, `parquet_roundtrip.rows_checked`,
    `split_separation`). The later one reports the same measurements per split
    (`packed_decode.train/dev/test`, `parquet_roundtrip.rows/exact`, `group_separation`).
    They measure identical things, so nothing here is reinterpreted: per-split counts are
    summed and legacy totals are read directly, which keeps every field meaning exactly what
    the gate that wrote it meant. Fields the later schema adds (how many boundary fragments
    carried text, carried none, or needed a multi-byte edge trim) stay None under the legacy
    schema; the README omits those clauses rather than inventing numbers for them.

    Returns None when the gate is absent or describes a different corpus than `statistics.json`.
    """
    splits = ('train', 'dev', 'test')
    path = root / 'audit/publish-check.json'
    if not path.is_file():
        return None
    gate = json.loads(path.read_text(encoding='utf-8'))
    totals = gate.get('measured_totals') or {}
    if totals.get('records') != records:
        return None

    packed = gate.get('packed_decode') or {}
    rounds = gate.get('parquet_roundtrip') or {}
    separation = gate.get('group_separation') or gate.get('split_separation') or {}
    per_split = 'train' in {key for key in packed if isinstance(key, str)}

    if per_split:
        rows_per_split = {split: int((packed.get(split) or {}).get('rows', 0) or 0) for split in splits}
        evidence = {
            'schema': 'per-split',
            'rows_decoded': sum(rows_per_split.values()),
            'rows_per_split': rows_per_split,
            'splits_covered': sorted(split for split, n in rows_per_split.items() if n),
            'segments_compared': _sum_by_split(packed, 'segments', splits),
            'token_slice_exact': _sum_by_split(packed, 'token_slice_exact', splits),
            'whole_record_segments': _sum_by_split(packed, 'whole_record_segments', splits),
            'whole_record_text_identical': _sum_by_split(packed, 'whole_record_text_exact', splits),
            'whole_record_reencoded_identical': _sum_by_split(packed, 'whole_record_reencode_exact', splits),
            'fragment_segments': _sum_by_split(packed, 'fragment_segments', splits),
            'fragment_verbatim_contained': _sum_by_split(packed, 'fragment_verbatim_contained', splits),
            'fragment_no_text': _sum_by_split(packed, 'fragment_no_text', splits),
            'fragment_boundary_trimmed': _sum_by_split(packed, 'fragment_boundary_trimmed', splits),
            'parquet_rows': int(rounds.get('rows', 0) or 0),
            'parquet_exact': int(rounds.get('exact', 0) or 0),
        }
    else:
        evidence = {
            'schema': 'legacy',
            'rows_decoded': int(packed.get('rows_decoded', 0) or 0),
            'rows_per_split': None,
            'splits_covered': sorted(packed.get('splits_covered') or []),
            'segments_compared': int(packed.get('segments_compared', 0) or 0),
            'token_slice_exact': int(packed.get('segments_whose_row_slice_equals_canonical_token_slice', 0) or 0),
            'whole_record_segments': int(packed.get('whole_record_segments_decoded', 0) or 0),
            'whole_record_text_identical': int(
                packed.get('whole_record_segments_with_identical_whitespace_normalised_text', 0) or 0),
            'whole_record_reencoded_identical': int(
                packed.get('whole_record_segments_reencoded_token_identically', 0) or 0),
            'fragment_segments': int(packed.get('fragment_segments_not_reencoded_per_segment', 0) or 0),
            'fragment_verbatim_contained': None,
            'fragment_no_text': None,
            'fragment_boundary_trimmed': None,
            'parquet_rows': int(rounds.get('rows_checked', 0) or 0),
            'parquet_exact': int(rounds.get('exact_matches', 0) or 0),
        }
    evidence['records'] = totals.get('records')
    evidence['groups_total'] = int(separation.get('groups_total', 0) or 0)
    evidence['groups_spanning'] = len(separation.get('groups_spanning_two_or_more_splits') or [])
    evidence['status'] = gate.get('status')
    return evidence


def write_readme(root, stats, source_stats):
    records = stats['records']
    chars = stats['text_characters']
    types = stats['record_types']
    type_chars = stats['record_type_characters']
    gen_records = types.get('generated_qa_pair', 0)
    gen_chars = type_chars.get('generated_qa_pair', 0)
    lean_records = types.get('formal_lean_proof', 0) + types.get('formal_lean_statement', 0)
    lean_chars = type_chars.get('formal_lean_proof', 0) + type_chars.get('formal_lean_statement', 0)
    other_records = records - gen_records
    other_chars = chars - gen_chars
    sorted_types = sorted(type_chars.items(), key=lambda kv: (-kv[1], kv[0]))

    def pct(numerator, denominator):
        return f'{100 * numerator / denominator:.2f}%'

    def ratio(numerator, denominator):
        return f'{numerator / denominator:.6f}'

    def count(number):
        return f'{number:,}'

    composition = '\n'.join(
        f'{pct(chars_of, chars)} of text characters (ratio {ratio(chars_of, chars)}) in `{name}`'
        for name, chars_of in sorted_types)
    per_source_table = '\n'.join(
        f'| `{sid}` | [{SOURCES[sid]["repository"].rsplit("/", 1)[-1]}]({SOURCES[sid]["repository"]}) '
        f'`{SOURCES[sid]["commit"][:12]}` | {src["records"]:,} | {src["groups"]:,} | '
        f'{src["text_characters"]:,} | {", ".join(sorted(src["record_types"]))} | {src["math_content"]} |'
        for sid, src in source_stats.items())
    new_sources = ('alphaevolve', 'alphaevolve_results', 'funsearch')
    new_records = sum(source_stats[s]['records'] for s in new_sources)
    new_chars = sum(source_stats[s]['text_characters'] for s in new_sources)
    new_groups = sum(source_stats[s]['groups'] for s in new_sources)
    notebook = stats.get('notebook_projection', {})
    stripped_outputs = notebook.get('output_objects_removed', 0)
    stripped_bytes = notebook.get('output_bytes_removed', 0)
    stripped_images = notebook.get('embedded_image_bytes_removed', 0)
    stripped_cells = notebook.get('cells_with_outputs', 0)
    construction_chars = type_chars.get('research_notebook', 0)
    stats_json = json.dumps(stats, indent=2)
    publication = {}
    publication_note = (
        'The pull request that carries this build is recorded in `audit/publication.json` with its number,\n'
        'URL and the parent commit it was opened against. It adds the whole component and the top-level\n'
        '`README.md` config row and has not been merged into `main`.')
    if (root / 'audit/publication.json').is_file():
        publication = json.loads((root / 'audit/publication.json').read_text(encoding='utf-8'))
        publication_note = (
            f'The component is delivered as Hugging Face dataset pull request\n'
            f'[MMLA-ORG/Cayley-Math discussion #{publication["pr_num"]}]({publication["pr_url"]})\n'
            f'on ref `{publication["pr_revision"]}`, opened against main at `{publication["parent"][:12]}`.\n'
            f'It adds the whole component and the top-level `README.md` config row, and it has not been merged\n'
            f'into `main`. Consult that discussion for the current merge state.')
    import textwrap

    def para(*sentences):
        return textwrap.fill(' '.join(sentences), width=100, break_long_words=False,
                             break_on_hyphens=False)

    notebook_sources = sum(1 for v in source_stats.values() if v['record_types'].get('research_notebook'))
    composition_paragraph = para(
        '**This corpus is mostly seeded generator output, not research mathematics.**',
        f'Measured over the delivered data, `generated_qa_pair` records are {count(gen_records)} of',
        f'{count(records)} records, which is {pct(gen_records, records)} of records',
        f'(ratio {ratio(gen_records, records)}) and {count(gen_chars)} of {count(chars)} text characters',
        f'({pct(gen_chars, chars)}, ratio {ratio(gen_chars, chars)}).',
        f'Lean records total {count(lean_records)}, namely {count(types.get("formal_lean_proof", 0))}',
        f'`formal_lean_proof` plus {count(types.get("formal_lean_statement", 0))} `formal_lean_statement`,',
        f'which is {pct(lean_records, records)} of records (ratio {ratio(lean_records, records)}), and lean',
        f'text carries {pct(lean_chars, chars)} of the characters (ratio {ratio(lean_chars, chars)}).',
        f'Geometry problems, prose proofs and notebook records add {count(other_records - lean_records)} more',
        f'records, so every non-generator record together is {count(other_records)} records,',
        f'{pct(other_records, records)} of the corpus (ratio {ratio(other_records, records)}), carrying',
        f'{count(other_chars)} characters ({pct(other_chars, chars)}, ratio {ratio(other_chars, chars)}).',
        'Lean files are long, so a character-weighted view inverts the record-weighted balance, and the',
        'construction notebooks are longer still because their coordinates and step-function coefficients',
        'are decimal literals. Read the composition from records first, then from characters.',
        '**No Lean compilation and no proof verification was performed on any subset**, so no record in',
        'this corpus has a checked proof or a checked statement, and no construction in it was re-verified',
        'here.')
    math_content_paragraph = para(
        f'`math_content` classifies each record\'s mathematical payload as one of formal_statements, proofs,',
        'natural_language_math, generated_qa, constructions, problem_statements or none. Measured by records:',
        f'{json.dumps(stats.get("math_content_records", {}), sort_keys=True)}.')
    notebook_paragraph = para(
        'Notebook records are the cell sources of each file joined by a newline and nothing else.',
        f'Across the {count(notebook_sources)} sources that ship notebooks, {count(stripped_cells)} cells',
        f'carried {count(stripped_outputs)} output objects totalling {count(stripped_bytes)} bytes, of which',
        f'{count(stripped_images)} bytes were embedded images; every one of those outputs was removed and',
        'every code and markdown cell stayed verbatim.',
        '`audit/extraction.jsonl` records the same counts per notebook.')

    gate_paragraph = para('[' + '`audit/publish-check.json`' + '](audit/publish-check.json) is a second publish gate '
                          'with its own code that re-derives every total in this file from the delivered '
                          '`data/*.jsonl.gz` and `packed/` files.')
    gate_note = ('decodes packed rows from each split with token identity and whitespace-normalised text '
                 'identity required for whole-record segments, matches Parquet rows to their JSONL records, and '
                 'recomputes group separation from the data with zero groups spanning two splits. '
                 '`audit/publish-check-previous.json` keeps the gate as it stood before this build so the growth '
                 'of the corpus can be diffed rather than asserted.')
    evidence = read_gate_evidence(root, records)
    if evidence is not None:
        rows_desc = (f'{count(evidence["rows_decoded"])} packed rows, '
                     f'{count(evidence["rows_per_split"]["train"])} per split across train, dev and test,'
                     if evidence['rows_per_split'] else
                     f'{count(evidence["rows_decoded"])} packed rows across '
                     f'{", ".join(evidence["splits_covered"])}')
        fragments = evidence['fragment_segments']
        if evidence['fragment_no_text'] is None:
            fragment_clause = (f'and the remaining {count(fragments)} row-boundary fragments are covered by '
                               f'that same token-slice identity')
        else:
            fragment_clause = (
                f'and of the {count(fragments)} row-boundary fragments, '
                f'{count(evidence["fragment_verbatim_contained"])} decoded to text appearing verbatim inside '
                f'their source record and {count(evidence["fragment_no_text"])} carried no text at all '
                f'because they contributed only BOS, EOS or bare whitespace')
            if evidence['fragment_boundary_trimmed']:
                fragment_clause += (
                    f'. Boundary fragments can start or end inside a multi-byte glyph, so their edges are '
                    f'trimmed of replacement characters before that containment test')
        note = (f'Its latest measured run decoded {rows_desc} and compared '
                f'{count(evidence["segments_compared"])} attributed segments: every row slice equalled its '
                f'canonical token slice ({count(evidence["token_slice_exact"])} of '
                f'{count(evidence["segments_compared"])} by exact identity), the '
                f'{count(evidence["whole_record_segments"])} segments that cover a whole record all decoded to '
                f'text identical to the source record under whitespace normalisation and all re-encoded to the '
                f'identical token sequence, {fragment_clause}. It matched '
                f'{count(evidence["parquet_exact"])} of {count(evidence["parquet_rows"])} Parquet round-trips '
                f'exactly and found {count(evidence["groups_spanning"])} groups spanning two splits out of '
                f'{count(evidence["groups_total"])}.')
        gate_note = para(note)
        gate_paragraph = para('[' + '`audit/publish-check.json`' + '](audit/publish-check.json) is a second '
                              'publish gate with its own code that re-derives every total in this file from '
                              'the delivered `data/*.jsonl.gz` and `packed/` files.', note)
    record_mix_paragraph = para(
        'The record mix is deliberately stated because it is skewed: `generated_qa_pair` records are',
        f'{pct(gen_records, records)} of records and {pct(gen_chars, chars)} of characters, while Lean records',
        f'are {pct(lean_records, records)} of records and {pct(lean_chars, chars)} of characters, and all',
        f'non-generator records together are {pct(other_records, records)} of records.',
        'A consumer wanting formal, prose or construction mathematics should filter on `record_type` or',
        '`math_content` rather than read the corpus whole.')

    packed_paragraph = para(
        f"Measured packed counts: train {stats['packed'].get('train', {}).get('rows', 0)} rows /",
        f"{stats['packed'].get('train', {}).get('tokens', 0)} tokens /",
        f"{stats['packed'].get('train', {}).get('loss_bearing_labels', 0)} loss-bearing labels; dev",
        f"{stats['packed'].get('dev', {}).get('rows', 0)} /",
        f"{stats['packed'].get('dev', {}).get('tokens', 0)} /",
        f"{stats['packed'].get('dev', {}).get('loss_bearing_labels', 0)}; test",
        f"{stats['packed'].get('test', {}).get('rows', 0)} /",
        f"{stats['packed'].get('test', {}).get('tokens', 0)} /",
        f"{stats['packed'].get('test', {}).get('loss_bearing_labels', 0)}.")
    split_paragraph = para(
        '`audit/group-splits.json` freezes every assignment: train',
        f"{stats['splits']['train']['records']:,} records over {stats['splits']['train']['groups']:,} groups,",
        f"dev {stats['splits']['dev']['records']:,} over {stats['splits']['dev']['groups']:,},",
        f"test {stats['splits']['test']['records']:,} over {stats['splits']['test']['groups']:,}.")

    new_sources_paragraph = para(
        '`alphaevolve`, `alphaevolve_results` and `funsearch` are the constructions behind their papers,',
        'labelled `math_content = constructions`. They add',
        f'{count(new_records)} records over {count(new_groups)} groups and {count(new_chars)} characters,',
        f'which is {pct(new_chars, chars)} of the corpus characters.')

    readme = f"""# Google math papers contribution to Cayley-Math

An independently versioned component holding source-derived text from {stats['sources']} Google and Google DeepMind
publications about mathematics, formal mathematics and mathematical reasoning. It follows Cayley-Math's
`components/` convention and reuses the record schema, Parquet encoding, split policy and packed-array
format of `components/openai-math/`. The frozen Phase 1 mirror is unchanged.

## What this is, and what it is not

These are **artifacts of specific Google math papers** (Lean libraries, geometry problem files, generator
output, paper notebooks, proof PDFs and the constructions their search programs found), not a survey of
Google's mathematics output and not a paper-complete reproduction of any one of them. The corpus is a
curated projection: a bounded, seeded sample for the generator source, a verbatim text projection for the
file sources.

Nothing here establishes mathematical truth. **No Lean project was compiled, no proof was checked, no
`lake build` or Comparator run was performed, and no mathematical verification of any kind took place.**
`record_type` labels the artifact kind, not the validity of its content. Records that contain `sorry`
placeholders remain placeholders.

The `mathematics-dataset` subset is output of the Saxton/Grefenstette/Hill/Kohli ICLR 2018 generator at
school-level difficulty. Those pairs are **not research mathematics**, and the subset is a sampled
projection of the paper's curriculum rather than the paper's dataset. Every record carries
`content_origin` and `math_content` so consumers can separate verbatim source text from
`generator_output`, and formal statements from constructions.

{composition_paragraph}

{math_content_paragraph}

## Included sources

Each source is pinned to a commit or dataset revision, and each ships math text under Apache-2.0
software terms with CC-BY 4.0 for non-software materials where the upstream states so.

| Source | Upstream at pinned revision | Records | Groups | Text characters | Record types | math_content |
| --- | --- | ---: | ---: | ---: | --- | --- |
{per_source_table}

`alphaproof-nexus` keeps all 83 records of the earlier standalone build unchanged in content: 71 Lean
proof files plus 12 pypdf-extracted prose proof PDFs over 51 problem groups. Only its split assignment
changed, because splits are recomputed over the merged group set of all sources rather than over its own
51 groups. `formal-conjectures` is the 1,861-file `FormalConjectures/` statement library plus its 274
helper-library files. `formal-imo` and `formal-putnam-like` are Lean 4 problem statements. `cryptids` is
the whole Lean library, including the Busy Beaver holdout proofs, whose individual files reach 1.4 MB of
mechanically generated state traces. `alphageometry` contributes 265 geometry problems in the
AlphaGeometry language: 231 JGEX problems, 30 olympiad problems and 4 library examples, plus the
`defs.txt` and `rules.txt` rule tables. The two `mathematics-conjectures` notebooks accompany the Nature
2021 knot-theory and representation-theory paper.

{new_sources_paragraph}

- `alphaevolve` ships 16 `verification.ipynb` notebooks over the 15 problem directories under `maths/`
  (cap_sets, circle_packing, erdos_minimum_overlap, extremal_girth_5, first_autocorrelation_inequality,
  heilbronn_convex, heilbronn_triangle, hexagon_packing, kissing, max_min_ratio,
  second_autocorrelation_inequality, shannon_cycle, sums_and_differences,
  third_autocorrelation_inequality, uncertainty_principles, the last with separate Hermite and Laguerre
  notebooks). Each notebook states the problem, records the coordinates the search found and carries the
  code that checks them. One record per notebook.
- `alphaevolve_results` ships `mathematical_results.ipynb`, 128 cells (36 markdown, 92 code), holding the
  paper's improved tensor decompositions, autocorrelation and uncertainty-principle bounds, Erdős minimum
  overlap, sums and differences, hexagon packing, Heilbronn, kissing-number, circle-packing and
  max-to-min-ratio constructions, each with its verification code. One record.
- `funsearch` ships four problem notebooks (cap_set, admissible_set, bin_packing, cyclic_graphs) with the
  skeleton the search evolved, the discovered `priority` functions and the explicit constructions they
  justify. Four records.

{notebook_paragraph}

## Excluded candidates and why

The widened scan is recorded in full in `sources.json` (`excluded_candidates` for whole repositories and
`excluded_subpaths` for parts of included ones) and `audit/source-scan.json`. A repository appears in
`included` or in `excluded_candidates`, never both. The short version:

- `google-deepmind/eval_hub` (putnam_like and live_math) is excluded because every problem carries a
  `CANARY_ID` benchmark-contamination canary and live_math is an actively maintained benchmark whose
  multimodal problems depend on images absent from this text corpus.
- `deepmind/aqua_rat` accompanies a program-synthesis paper, not a mathematics paper.
- `deepmind/math_dataset` is a 40 GB pre-generated mirror of the generator already used here.
- `google-research/math-opt-benchmark`, `google/mathsteps`, `google-deepmind/alphatensor` and every
  math-named software library (`tree-math`, `mathfu`, `vector_math.dart`, `opengrm`) ship code and no
  math text. `alphatensor` remains excluded on its original measurement of 24 search-code entries: it is
  a search harness, the same class of artifact as the `alphaevolve` sub-paths excluded below.
- `google-deepmind/cartesian-frames` formalises an alignment blog sequence in HOL4 SML, not a
  mathematics paper.
- `google-deepmind/miniF2F` is a fork of a non-Google corpus.
- `google-deepmind/alphageometry2` embeds 26 problems in Python dict literals, and AG1 already ships
  the same olympiad problems verbatim in the AlphaGeometry language.
- `google/feabench`, `google/phasecoder` and `google-research/pointdit` are physics, audio and vision
  papers whose titles happen to contain mathematical words.

Two included repositories also ship sub-paths that were measured and left out in part, so those exclusions
are recorded separately in `excluded_subpaths` and each reason names the measured bytes:

- `alphaevolve` `omega/` (45,511,025 bytes measured) is a search harness plus one compressed cache:
  44,267,872 bytes are the single `.xz` archive `clean_level4.npz.xz`, and its 1,126,802-byte
  `verification.ipynb` is 1,098,419 characters of code, 836,374 of them decimal digits holding rational
  vectors for a 20 GB verification run. Code-only, so nothing from it is projected.
- `alphaevolve` `src/`, `maths/**/*.py`, `maths/**/config*.yaml` and `matmul_tensor_decompositions/`
  (1,165,195 bytes measured) are the 58,453-byte search harness, 87,725 bytes of initial programs,
  60,949 bytes of run configuration, and 827,894 bytes of two tensor-rank notebooks whose projections
  share 4,820 of 4,830 substantial lines with the included `alphaevolve_results` notebook. Code-only or
  near-duplicate, so none of it is projected.
- `funsearch` `**/*.txt` and `implementation/*.py` (20,442,546 bytes measured): 13 `.txt` files hold
  20,389,203 bytes of comma-separated integer tuples, one alone 17,372,832 bytes, serialising exactly the
  sets the included notebooks build and assert; `implementation/` is 53,343 bytes of the search algorithm.
  Serialization and harness code, so none of it is projected.

## Files and schema

- `data/{{train,dev,test}}.jsonl.gz`: source records with required fields text, group, license; unique id,
  paper_id, split, record_type, source_url, and `source_id` naming the upstream.
- `data/{{train,dev,test}}.parquet`: identical records. Core fields
  (id,text,group,license,paper_id,split,record_type,source_url) are string columns; all remaining JSON
  fields are serialised in `metadata_json`. Merge `json.loads(metadata_json)` with the core columns to
  reconstruct each JSONL record.
- `sources.json`: every included source with its pinned revision, license, `math_content` class and
  measured counts, plus every excluded candidate with its measured reason and every excluded sub-path of
  an included repository.
- `licenses/<source_id>/LICENSE`: one upstream license per source; `LICENSE` at the component root is the
  Apache-2.0 text shared by all {stats['sources']}.
- `audit/source-files.jsonl`: path, sha256, bytes, source_id, kind and pinned source_url for every blob and
  for the generated corpus file.
- `audit/source-scan.json`: the scan queries, the included set and the whole-repository exclusions, plus
  the measured sub-path exclusions of included repositories.
- `audit/group-splits.json`: the group assignment, the policy, and per-source group counts.
- `audit/extraction.jsonl`: per-PDF and per-notebook extraction metrics, quality flags, and for notebooks
  the exact number of output cells and bytes removed.
- `audit/mathematics-dataset-generation.json`: generator commit, seed, per-regime quotas, module list, and
  measured yield.
- `audit/excluded-duplicates.jsonl`, `audit/packing.json`, `audit/source-scan.json`.
- `audit/validation-evidence.json`: the independent decode and round-trip evidence described below.
- `audit/publish-check.json`: the second publish gate, measured from the delivered files after the build;
  `audit/publish-check-previous.json` preserves the gate as it stood before this build so the delta is
  auditable.
- `statistics.json`: measured records, groups, splits, characters and packed counts, per source, plus
  per-record-type and per-`math_content` counts.
- `manifest.json`: SHA256 and byte size for every delivered file except itself and validation.json.
- `packed/`: mmla-type2-packed-v1 arrays, manifest, row attribution and per-record token counts.
- `tools/`: the generator driver, the build script and the validation scripts actually run.

## Loading

~~~python
import gzip, json
from pathlib import Path
component = Path('components/google-math')
with gzip.open(component / 'data/train.jsonl.gz', 'rt', encoding='utf-8') as f:
    first_record = json.loads(next(f))

import pyarrow.parquet as pq
row = pq.read_table(component / 'data/train.parquet').slice(0, 1).to_pylist()[0]
metadata = json.loads(row.pop('metadata_json'))
first_parquet_record = {{**row, **metadata}}
~~~

## Packed training arrays

`packed/manifest.json` uses `mmla-type2-packed-v1`: input_ids, labels and role_ids are int32 arrays of
shape [rows, {SEQ_LEN}], pad=0, role=0, ignored labels=-100. Each record is encoded as
BOS + SentencePiece(text) + EOS with the included Cayley-Math tokenizer (32768 pieces); window stride is
{SEQ_LEN} with one-token lookahead, labels predict the following token, and targets that cross into a new
record's BOS or into padding are masked. Split-specific `rows.jsonl` maps every non-padding token back to
its record; `records.jsonl` stores token counts and hashes. This component does not reproduce Phase 1
quotas, packing or splits.

{packed_paragraph}

## Splits

Splits are assigned per group, never per record, so companions and families stay together: a Lean proof
and its prose proof, a conjecture file and its helper library, or one generated question family. Every
group key is namespaced by its `source_id`. Assignment sorts SHA256(group) as hex, reserves the first
ceil(1%) of groups for dev, the next ceil(1%) for test, and the rest for train.
{split_paragraph}

## Text projection

Lean, geometry-problem and rule files are byte-identical to the pinned blob, license headers included.
Notebook records join the cell sources of each notebook with a newline; no cell text is altered, and only
execution output is dropped where it existed. `natural_language_proof` records come from pypdf page-text
extraction and are **lossy**: math symbols arrive as Unicode substitutions, ligature artifacts appear, and
inline formulas lose their two-dimensional layout. C0/C1 control characters were replaced and blank-line
runs collapsed. Each PDF record carries `extraction_quality = lossy_pdf_text_layer` with page and
character counts, and `audit/extraction.jsonl` holds the same per-file audit. The construction notebooks
carry `math_content = constructions` because their decimals are the construction itself, not a proof of
it; the code in them checks the construction, and this component never ran it.

## Verification evidence

`tools/validate_google_math.py` checks file hashes, source coverage, unique record IDs and unique text,
group split separation, lossless Parquet reconstruction, packed array shapes, causal shift, padding and
boundary masks, and re-encodes every record's token stream against `data/*.jsonl.gz`. It writes
`validation.json`; the last run passed all 13 checks
(`all_delivered_file_hashes_and_sizes`, `pinned_sources_metadata_and_excluded_candidates`,
`source_file_inventory_local_bytes`, `group_split_policy_recomputed_from_scratch`,
`lossless_jsonl_parquet_exact_text_uniqueness_and_record_provenance`, `group_split_separation`,
`verbatim_lean_source_equality_local_bytes`, `lean_and_generated_records_survive`,
`per_file_extraction_audit`, `dedup_audit_present`, `generator_audit_seed_and_quota`,
`all_packed_tokens_reencoded_source_shift_padding_masks_and_attribution`, `statistics_match_artifacts`).

`tools/verify_google_math.py` is an independent check against the delivered files, and its output is
[`audit/validation-evidence.json`](audit/validation-evidence.json). It re-encodes and decodes sampled
packed rows across all three splits, compared against the records they are attributed to rather than
against the build's own manifest, and it round-trips sampled Parquet rows back to their JSONL records. It
also recomputes split separation from the delivered data instead of trusting `audit/group-splits.json`.

{gate_paragraph}

{record_mix_paragraph}

## Publication

{publication_note}

A token with `write` scope or org-admin rights is required to merge it. The token used for this build can
read the repository and open pull requests, but a direct commit to `main` is rejected with
`403 Forbidden: You have read access but not the required permissions for this operation`. Merging the
pull request, or re-running an upload without `--create-pr` once such a token is available, completes the
submission.

## Limitations

- No Lean compilation, proof checking, Comparator run or mathematical verification of any kind. The
  construction notebooks' verifier code was read as text and never executed, so no construction here was
  re-checked against its claim.
- The build ran in a sandbox-free subprocess only for the generator; every other source was never built
  or executed, only read as text.
- PDF prose proofs are noisy pypdf text; symbol and ligature fidelity is not guaranteed.
- The generator subset is a seeded sample of one curriculum, not the paper's full dataset, and its
  questions are school-level rather than research mathematics. One module, `algebra__linear_1d`, stopped
  at 3,055 of its 8,000 quota when upstream's own `assert entropy == 0` fired; nothing was repaired, and
  the shortfall is recorded in `audit/mathematics-dataset-generation.json`.
- The construction notebooks record decimal literals for coordinates and coefficients at the precision
  upstream wrote them. They are verbatim, so rounding past 16 digits is upstream's, not this component's;
  no construction was recomputed in exact arithmetic.
- `funsearch` sets whose only form upstream ships is the integer tuple list in `.txt` are represented here
  through the notebook that constructs them, not through the serialized list.
- `formal-conjectures` upstream states that some content derives from third-party sources (Wikipedia,
  MathOverflow and OEIS under CC-BY-SA 4.0). Per-file reference URLs are retained inside the Lean text; no
  separate per-file license audit was performed.
- Near-duplicate detection is limited to exact text duplicates and the recorded line overlap between the
  `matmul_tensor_decompositions` notebooks and `alphaevolve_results`. Phase 1 overlap analysis and
  editorial review were not performed. {stats['excluded_exact_duplicates']:,} exact duplicate texts were
  dropped and are listed in `audit/excluded-duplicates.jsonl`.
- The SentencePiece model normalises runs of spaces, so packed text decodes whitespace-normalised rather
  than byte-identically to the sources.
- Only problems that upstream published are present, so several subsets are selection-biased. `cryptids`
  contributes 31.6M characters because a handful of Busy Beaver traces are enormous, and the `kissing`
  notebook alone contributes 5.8M of the {count(construction_chars)} notebook characters because its
  593-sphere configuration is 5.8M characters of coordinates. Both are machine-generated artifacts rather
  than mathematics prose.

## Statistics

~~~json
{stats_json}
~~~
"""
    (root / 'README.md').write_text(readme, encoding='utf-8')


if __name__ == '__main__':
    main()