File size: 53,427 Bytes
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66746ff
84189a5
66746ff
84189a5
 
dc53acb
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66746ff
 
 
f9d92af
 
 
 
 
 
 
dc53acb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66746ff
 
 
 
dc53acb
f9d92af
 
 
 
 
 
 
dc53acb
f9d92af
 
 
 
 
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc53acb
 
 
 
 
 
 
 
 
 
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
 
 
f9d92af
84189a5
 
 
 
 
f9d92af
 
84189a5
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
 
 
f9d92af
84189a5
 
 
 
f9d92af
84189a5
 
f9d92af
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
 
 
 
f9d92af
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
f9d92af
 
 
 
 
 
84189a5
dc53acb
 
 
84189a5
 
f9d92af
 
 
 
 
 
 
 
 
84189a5
 
f9d92af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84189a5
 
 
f9d92af
 
 
 
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9d92af
84189a5
 
 
f9d92af
84189a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build the versioned Sudoku_DLM_Reasoning dataset release.

The release is deliberately small enough for controlled model and decoding
experiments while preserving the upstream train/test boundary:

* train:      65,536 examples from each of original, r0, and r1_4
* validation:  2,048 examples from each of original, r0, and r1_4
* test:         1,000 examples from each of original, r0, r1_4, and r5_19
* confirm:      4,000 additional r5_19 examples, reserved for final confirmation

Selection is deterministic. Rows are ranked by SHA-256 within metadata strata,
not by their position in the source CSV. Exact-puzzle and digit-renaming overlap
is excluded across all released splits.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import heapq
import json
import math
import shutil
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable, Iterator, Mapping, MutableMapping, Sequence

import pyarrow as pa
import pyarrow.parquet as pq


DATASET_VERSION = "1.1.0"
DEFAULT_DATASET_ID = "stwistzz/Sudoku_DLM_Reasoning"
DEFAULT_SEED = "0"
SOURCE_REPO = "fhyfhy/diffusion-vs-ar-hard-sudoku"
SOURCE_REVISION = "527859f62c745c16833aded130ad9f9ddddb76af"
TDOKU_REFERENCE_REVISION = "af426180dc53aef89b82868e7b3fdfcf42165654"

TRAIN_PER_BUCKET = 65_536
VALIDATION_PER_BUCKET = 2_048
TEST_PER_BUCKET = 1_000
OOD_CONFIRM_SIZE = 4_000

BUCKET_ORDER = {"original": 0, "r0": 1, "r1_4": 2, "r5_19": 3}
TEST_PRIORITY = ("r5_19", "r1_4", "r0", "original")
TRAIN_PRIORITY = ("r1_4", "r0", "original")

SCHEMA = pa.schema(
    [
        pa.field("example_id", pa.string(), nullable=False),
        pa.field("puzzle_id", pa.string(), nullable=False),
        pa.field("digit_normalized_id", pa.string(), nullable=False),
        pa.field("puzzle", pa.string(), nullable=False),
        pa.field("solution", pa.string(), nullable=False),
        pa.field("difficulty_bucket", pa.string(), nullable=False),
        pa.field("difficulty_subbucket", pa.string(), nullable=False),
        pa.field("source_family", pa.string(), nullable=False),
        pa.field("source_collection", pa.string(), nullable=False),
        pa.field("official_rating", pa.float64(), nullable=True),
        pa.field("rating_type", pa.string(), nullable=False),
        pa.field("clues", pa.int16(), nullable=False),
        pa.field("upstream_split", pa.string(), nullable=False),
        pa.field("release_split", pa.string(), nullable=False),
        pa.field("evaluation_role", pa.string(), nullable=False),
        pa.field("is_ood", pa.bool_(), nullable=False),
        pa.field("source_file", pa.string(), nullable=False),
        pa.field("source_row_index", pa.int64(), nullable=False),
        pa.field("stratum", pa.string(), nullable=False),
    ]
)


@dataclass(frozen=True)
class PoolSpec:
    bucket: str
    upstream_split: str
    relative_path: str
    expected_rows: int
    is_original: bool = False


POOLS = {
    ("original", "train"): PoolSpec(
        "original", "train", "sudoku_train.csv", 100_000, True
    ),
    ("original", "test"): PoolSpec(
        "original", "test", "sudoku_test.csv", 1_000, True
    ),
    ("r0", "train"): PoolSpec(
        "r0", "train", "processed/sudoku_extreme_train_r0.csv", 553_009
    ),
    ("r0", "test"): PoolSpec(
        "r0", "test", "processed/sudoku_extreme_test_r0.csv", 61_127
    ),
    ("r1_4", "train"): PoolSpec(
        "r1_4", "train", "processed/sudoku_extreme_train_r1_4.csv", 529_736
    ),
    ("r1_4", "test"): PoolSpec(
        "r1_4", "test", "processed/sudoku_extreme_test_r1_4.csv", 58_717
    ),
    ("r5_19", "test"): PoolSpec(
        "r5_19", "test", "processed/sudoku_extreme_test_r5_19.csv", 111_831
    ),
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-dir", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--dataset-id", default=DEFAULT_DATASET_ID)
    parser.add_argument("--seed", default=DEFAULT_SEED)
    return parser.parse_args()


def sha256_text(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def digit_normalized_pair(puzzle: str, solution: str) -> tuple[str, str]:
    """Canonicalize digit names using their first occurrence in the solution."""
    mapping: dict[str, str] = {}
    for digit in solution:
        if digit not in mapping:
            mapping[digit] = str(len(mapping) + 1)
    if len(mapping) != 9:
        raise ValueError("solution does not contain all nine digits")
    normalized_solution = "".join(mapping[digit] for digit in solution)
    normalized_puzzle = "".join("0" if digit == "0" else mapping[digit] for digit in puzzle)
    return normalized_puzzle, normalized_solution


def subbucket(bucket: str, rating: float | None) -> str:
    if bucket in {"original", "r0"}:
        return bucket
    if rating is None:
        raise ValueError(f"missing official rating for {bucket}")
    if bucket == "r1_4":
        if not 1 <= rating < 5:
            raise ValueError(f"rating {rating} is outside r1_4")
        lower = math.floor(rating)
        return f"r{lower}_{lower + 1}"
    if bucket == "r5_19":
        if not 5 <= rating < 20:
            raise ValueError(f"rating {rating} is outside r5_19")
        if rating < 8:
            return "r5_7"
        if rating < 12:
            return "r8_11"
        if rating < 16:
            return "r12_15"
        return "r16_19"
    raise ValueError(f"unknown difficulty bucket: {bucket}")


def make_stratum(record: Mapping[str, object]) -> str:
    bucket = str(record["difficulty_bucket"])
    clues = int(record["clues"])
    if bucket == "original":
        return f"bucket=original|clues={clues}"
    source = str(record["source_collection"])
    if bucket == "r0":
        return f"bucket=r0|source={source}|clues={clues}"
    return (
        f"bucket={bucket}|sub={record['difficulty_subbucket']}|"
        f"source={source}|clues={clues}"
    )


def validate_strings(puzzle: str, solution: str, context: str) -> None:
    if len(puzzle) != 81 or any(char not in "0123456789" for char in puzzle):
        raise ValueError(f"{context}: puzzle must contain 81 digits")
    if len(solution) != 81 or any(char not in "123456789" for char in solution):
        raise ValueError(f"{context}: solution must contain 81 digits 1-9")
    for index, clue in enumerate(puzzle):
        if clue != "0" and clue != solution[index]:
            raise ValueError(f"{context}: clue disagrees with solution at cell {index}")


def validate_solution(solution: str, context: str) -> None:
    expected = set("123456789")
    rows = [solution[index : index + 9] for index in range(0, 81, 9)]
    columns = [solution[index::9] for index in range(9)]
    boxes = []
    for box_row in range(3):
        for box_col in range(3):
            cells = []
            for row in range(box_row * 3, box_row * 3 + 3):
                start = row * 9 + box_col * 3
                cells.extend(solution[start : start + 3])
            boxes.append("".join(cells))
    if any(set(unit) != expected for unit in rows + columns + boxes):
        raise ValueError(f"{context}: invalid completed Sudoku solution")


def iter_pool(source_dir: Path, spec: PoolSpec) -> Iterator[dict[str, object]]:
    path = source_dir / Path(spec.relative_path)
    with path.open("r", encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        required = {"quizzes", "solutions"}
        if not required.issubset(reader.fieldnames or []):
            raise ValueError(f"{path}: missing required columns {sorted(required)}")
        for row_index, row in enumerate(reader):
            puzzle = row["quizzes"].strip()
            solution = row["solutions"].strip()
            context = f"{spec.relative_path}:{row_index + 2}"
            validate_strings(puzzle, solution, context)
            clues = sum(char != "0" for char in puzzle)

            if spec.is_original:
                source_family = "original"
                source_collection = "diffusion_vs_ar_original"
                official_rating = None
                rating_type = "not_rated"
            else:
                if row.get("dataset") != "sudoku_extreme":
                    raise ValueError(f"{context}: unexpected dataset family {row.get('dataset')!r}")
                if row.get("difficulty_bucket") != spec.bucket:
                    raise ValueError(f"{context}: unexpected difficulty bucket")
                if row.get("split") != spec.upstream_split:
                    raise ValueError(f"{context}: unexpected upstream split")
                source_family = "sudoku_extreme"
                source_collection = row["source"].strip()
                official_rating = float(row["official_rating"])
                rating_type = row["rating_type"].strip()
                declared_clues = int(row["clues"])
                if declared_clues != clues:
                    raise ValueError(
                        f"{context}: declared clues {declared_clues} != computed clues {clues}"
                    )

            normalized_puzzle, normalized_solution = digit_normalized_pair(puzzle, solution)
            record: dict[str, object] = {
                "example_id": sha256_text(f"{puzzle}|{solution}"),
                "puzzle_id": sha256_text(puzzle),
                "digit_normalized_id": sha256_text(
                    f"{normalized_puzzle}|{normalized_solution}"
                ),
                "puzzle": puzzle,
                "solution": solution,
                "difficulty_bucket": spec.bucket,
                "difficulty_subbucket": subbucket(spec.bucket, official_rating),
                "source_family": source_family,
                "source_collection": source_collection,
                "official_rating": official_rating,
                "rating_type": rating_type,
                "clues": clues,
                "upstream_split": spec.upstream_split,
                "source_file": spec.relative_path.replace("\\", "/"),
                "source_row_index": row_index,
            }
            record["stratum"] = make_stratum(record)
            yield record


def ordered_specs(split: str, priority: Sequence[str]) -> list[PoolSpec]:
    return [POOLS[(bucket, split)] for bucket in priority]


def scan_pools(
    source_dir: Path,
    specs: Sequence[PoolSpec],
    *,
    protected_puzzles: set[str] | None = None,
    protected_digit_normalized: set[str] | None = None,
    collect_all_ids: bool = False,
) -> dict[str, object]:
    protected_puzzles = protected_puzzles or set()
    protected_digit_normalized = protected_digit_normalized or set()
    seen_puzzles: set[str] = set()
    seen_digit_normalized: set[str] = set()
    all_puzzles: set[str] = set()
    all_digit_normalized: set[str] = set()
    counts: dict[str, Counter[str]] = defaultdict(Counter)
    stratum_groups: dict[str, str] = {}
    raw_counts: Counter[str] = Counter()
    accepted_counts: Counter[str] = Counter()
    exclusions: Counter[str] = Counter()

    for spec in specs:
        for record in iter_pool(source_dir, spec):
            raw_counts[spec.bucket] += 1
            puzzle_id = str(record["puzzle_id"])
            normalized_id = str(record["digit_normalized_id"])
            if collect_all_ids:
                all_puzzles.add(puzzle_id)
                all_digit_normalized.add(normalized_id)
            if puzzle_id in protected_puzzles:
                exclusions["protected_exact_puzzle"] += 1
                continue
            if normalized_id in protected_digit_normalized:
                exclusions["protected_digit_normalized"] += 1
                continue
            if puzzle_id in seen_puzzles:
                exclusions["duplicate_exact_puzzle"] += 1
                continue
            if normalized_id in seen_digit_normalized:
                exclusions["duplicate_digit_normalized"] += 1
                continue
            seen_puzzles.add(puzzle_id)
            seen_digit_normalized.add(normalized_id)
            stratum = str(record["stratum"])
            group = str(record["difficulty_subbucket"])
            if stratum in stratum_groups and stratum_groups[stratum] != group:
                raise AssertionError(f"stratum {stratum} mapped to two groups")
            stratum_groups[stratum] = group
            counts[spec.bucket][stratum] += 1
            accepted_counts[spec.bucket] += 1

        if raw_counts[spec.bucket] != spec.expected_rows:
            raise ValueError(
                f"{spec.relative_path}: expected {spec.expected_rows} rows, "
                f"found {raw_counts[spec.bucket]}"
            )

    return {
        "counts": dict(counts),
        "stratum_groups": stratum_groups,
        "raw_counts": dict(raw_counts),
        "accepted_counts": dict(accepted_counts),
        "exclusions": dict(exclusions),
        "seen_puzzles": seen_puzzles,
        "seen_digit_normalized": seen_digit_normalized,
        "all_puzzles": all_puzzles,
        "all_digit_normalized": all_digit_normalized,
    }


def allocate_proportional(counts: Mapping[str, int], total: int) -> dict[str, int]:
    available = sum(counts.values())
    if total < 0 or total > available:
        raise ValueError(f"cannot allocate {total} rows from {available}")
    if total == 0:
        return {key: 0 for key in counts}
    exact = {key: value * total / available for key, value in counts.items()}
    allocation = {key: min(value, math.floor(exact[key])) for key, value in counts.items()}
    remaining = total - sum(allocation.values())
    order = sorted(
        counts,
        key=lambda key: (-(exact[key] - math.floor(exact[key])), key),
    )
    while remaining:
        changed = False
        for key in order:
            if allocation[key] < counts[key]:
                allocation[key] += 1
                remaining -= 1
                changed = True
                if remaining == 0:
                    break
        if not changed:
            raise AssertionError("capacity-aware quota allocation stalled")
    return allocation


def subtract_counts(
    counts: Mapping[str, int], allocation: Mapping[str, int]
) -> dict[str, int]:
    return {key: counts[key] - allocation.get(key, 0) for key in counts}


def add_allocations(*allocations: Mapping[str, int]) -> dict[str, int]:
    result: Counter[str] = Counter()
    for allocation in allocations:
        result.update(allocation)
    return dict(result)


def allocate_balanced_groups(
    counts: Mapping[str, int],
    stratum_groups: Mapping[str, str],
    targets: Mapping[str, int],
) -> dict[str, int]:
    allocation: dict[str, int] = {key: 0 for key in counts}
    for group, target in targets.items():
        group_counts = {
            key: value for key, value in counts.items() if stratum_groups[key] == group
        }
        if not group_counts:
            raise ValueError(f"no rows available for required group {group}")
        allocation.update(allocate_proportional(group_counts, target))
    if sum(allocation.values()) != sum(targets.values()):
        raise AssertionError("balanced group allocation returned the wrong total")
    return allocation


def allocation_rank(seed: str, scope: str, bucket: str, example_id: str) -> int:
    digest = hashlib.sha256(f"{seed}|{scope}|{bucket}|{example_id}".encode()).digest()
    return int.from_bytes(digest, byteorder="big", signed=False)


def collect_ranked_candidates(
    source_dir: Path,
    specs: Sequence[PoolSpec],
    capacities: Mapping[str, int],
    *,
    seed: str,
    scope: str,
    protected_puzzles: set[str] | None = None,
    protected_digit_normalized: set[str] | None = None,
) -> dict[str, list[dict[str, object]]]:
    protected_puzzles = protected_puzzles or set()
    protected_digit_normalized = protected_digit_normalized or set()
    seen_puzzles: set[str] = set()
    seen_digit_normalized: set[str] = set()
    heaps: dict[str, list[tuple[int, str, dict[str, object]]]] = defaultdict(list)

    for spec in specs:
        for record in iter_pool(source_dir, spec):
            puzzle_id = str(record["puzzle_id"])
            normalized_id = str(record["digit_normalized_id"])
            if puzzle_id in protected_puzzles or normalized_id in protected_digit_normalized:
                continue
            if puzzle_id in seen_puzzles or normalized_id in seen_digit_normalized:
                continue
            seen_puzzles.add(puzzle_id)
            seen_digit_normalized.add(normalized_id)

            stratum = str(record["stratum"])
            capacity = capacities.get(stratum, 0)
            if capacity == 0:
                continue
            rank = allocation_rank(seed, scope, spec.bucket, str(record["example_id"]))
            record["_allocation_rank"] = rank
            heap = heaps[stratum]
            entry = (-rank, str(record["example_id"]), record)
            if len(heap) < capacity:
                heapq.heappush(heap, entry)
            elif rank < -heap[0][0]:
                heapq.heapreplace(heap, entry)

    selected: dict[str, list[dict[str, object]]] = {}
    for stratum, capacity in capacities.items():
        records = [entry[2] for entry in heaps.get(stratum, [])]
        records.sort(key=lambda record: (int(record["_allocation_rank"]), record["example_id"]))
        if len(records) != capacity:
            raise ValueError(
                f"stratum {stratum}: selected {len(records)} rows, expected {capacity}"
            )
        selected[stratum] = records
    return selected


def assign_release_rows(
    selected: Mapping[str, Sequence[dict[str, object]]],
    first_allocation: Mapping[str, int],
    second_allocation: Mapping[str, int] | None,
    *,
    first_split: str,
    second_split: str | None,
) -> tuple[list[dict[str, object]], list[dict[str, object]]]:
    first_rows: list[dict[str, object]] = []
    second_rows: list[dict[str, object]] = []
    second_allocation = second_allocation or {}
    for stratum, records in selected.items():
        first_n = first_allocation.get(stratum, 0)
        second_n = second_allocation.get(stratum, 0)
        if len(records) != first_n + second_n:
            raise AssertionError(f"allocation mismatch for {stratum}")
        for record in records[:first_n]:
            first_rows.append(finalize_record(record, first_split))
        for record in records[first_n : first_n + second_n]:
            if second_split is None:
                raise AssertionError("second allocation supplied without a split name")
            second_rows.append(finalize_record(record, second_split))
    return first_rows, second_rows


def finalize_record(record: Mapping[str, object], release_split: str) -> dict[str, object]:
    result = {key: value for key, value in record.items() if not key.startswith("_")}
    bucket = str(result["difficulty_bucket"])
    is_ood = bucket == "r5_19"
    if release_split == "train":
        role = "train_id"
    elif release_split == "validation":
        role = "validation_id"
    elif release_split == "test":
        role = "test_ood" if is_ood else "test_id"
    elif release_split == "test_ood_confirm":
        role = "confirm_ood"
    else:
        raise ValueError(f"unknown release split {release_split}")
    result["release_split"] = release_split
    result["evaluation_role"] = role
    result["is_ood"] = is_ood
    return result


def stable_output_order(rows: list[dict[str, object]], seed: str, split: str) -> None:
    rows.sort(
        key=lambda row: sha256_text(f"{seed}|output|{split}|{row['example_id']}")
    )


def strict_validate_selected(rows: Sequence[Mapping[str, object]]) -> None:
    for row in rows:
        context = f"selected:{row['release_split']}:{row['example_id']}"
        validate_strings(str(row["puzzle"]), str(row["solution"]), context)
        validate_solution(str(row["solution"]), context)


def summarize_rows(rows: Sequence[Mapping[str, object]]) -> dict[str, object]:
    bucket_counts = Counter(str(row["difficulty_bucket"]) for row in rows)
    subbucket_counts = Counter(str(row["difficulty_subbucket"]) for row in rows)
    source_counts = Counter(str(row["source_collection"]) for row in rows)
    clue_counts = [int(row["clues"]) for row in rows]
    ratings = [float(row["official_rating"]) for row in rows if row["official_rating"] is not None]
    return {
        "rows": len(rows),
        "difficulty_buckets": dict(sorted(bucket_counts.items())),
        "difficulty_subbuckets": dict(sorted(subbucket_counts.items())),
        "source_collections": dict(sorted(source_counts.items())),
        "clues": {
            "min": min(clue_counts),
            "max": max(clue_counts),
            "mean": sum(clue_counts) / len(clue_counts),
        },
        "official_rating": (
            {
                "min": min(ratings),
                "max": max(ratings),
                "mean": sum(ratings) / len(ratings),
            }
            if ratings
            else None
        ),
        "unique_example_ids": len({str(row["example_id"]) for row in rows}),
        "unique_puzzle_ids": len({str(row["puzzle_id"]) for row in rows}),
        "unique_digit_normalized_ids": len(
            {str(row["digit_normalized_id"]) for row in rows}
        ),
    }


def overlap_audit(splits: Mapping[str, Sequence[Mapping[str, object]]]) -> dict[str, object]:
    identifiers = ("example_id", "puzzle_id", "digit_normalized_id")
    sets = {
        split: {identifier: {str(row[identifier]) for row in rows} for identifier in identifiers}
        for split, rows in splits.items()
    }
    pairwise: dict[str, dict[str, int]] = {}
    split_names = list(splits)
    for left_index, left in enumerate(split_names):
        for right in split_names[left_index + 1 :]:
            key = f"{left}__vs__{right}"
            pairwise[key] = {
                identifier: len(sets[left][identifier] & sets[right][identifier])
                for identifier in identifiers
            }
    if any(value for result in pairwise.values() for value in result.values()):
        raise ValueError(f"cross-split overlap detected: {pairwise}")
    return pairwise


def write_parquet(path: Path, rows: list[dict[str, object]]) -> None:
    table = pa.Table.from_pylist(rows, schema=SCHEMA)
    pq.write_table(
        table,
        path,
        compression="zstd",
        compression_level=9,
        use_dictionary=True,
        write_statistics=True,
        row_group_size=8_192,
    )


def write_json(path: Path, value: object) -> None:
    path.write_text(
        json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n",
        encoding="utf-8",
    )


def source_metadata(source_dir: Path, specs: Iterable[PoolSpec]) -> dict[str, object]:
    result: dict[str, object] = {}
    for spec in sorted(set(specs), key=lambda item: item.relative_path):
        path = source_dir / spec.relative_path
        result[spec.relative_path] = {
            "bytes": path.stat().st_size,
            "sha256": sha256_file(path),
            "expected_rows": spec.expected_rows,
            "upstream_split": spec.upstream_split,
            "difficulty_bucket": spec.bucket,
        }
    return result


def render_raw_readme() -> str:
    return f"""# Raw source snapshot

This directory is explicitly labeled **raw**. It contains unmodified copies of
the seven upstream CSV files scanned by the `{DATASET_VERSION}` builder:

| raw path | upstream split | difficulty | rows |
|---|---|---|---:|
| `sudoku_train.csv` | train | original | 100,000 |
| `sudoku_test.csv` | test | original | 1,000 |
| `processed/sudoku_extreme_train_r0.csv` | train | r0 | 553,009 |
| `processed/sudoku_extreme_test_r0.csv` | test | r0 | 61,127 |
| `processed/sudoku_extreme_train_r1_4.csv` | train | r1_4 | 529,736 |
| `processed/sudoku_extreme_test_r1_4.csv` | test | r1_4 | 58,717 |
| `processed/sudoku_extreme_test_r5_19.csv` | test | r5_19 | 111,831 |

Total: **1,415,420 rows**. This is the complete candidate pool for the v1
protocol, not the complete 8.1M-row upstream repository. Unused difficulty
buckets and unrelated dataset families are intentionally excluded.

These files are not additional Hugging Face splits. The dataset card explicitly
maps only `data/*.parquet` into the `default` config. See
`metadata/raw_manifest.json` for SHA-256 hashes and exact provenance, and
`RAW_DATA_LICENSES.md` before redistributing the raw files.
"""


def render_building_guide(dataset_id: str, seed: str) -> str:
    return f"""# Building the processed dataset from `raw/`

The repository is self-contained for reconstructing the processed release.

## Inputs

- Raw snapshot: `raw/`
- Dataset ID: `{dataset_id}`
- Release seed: `{seed}`
- Upstream revision: `{SOURCE_REVISION}`

First verify that the raw files match `metadata/raw_manifest.json`. Then run the
builder from the repository root:

```bash
python scripts/build_dataset.py \\
  --source-dir raw \\
  --output-dir rebuilt-release \\
  --dataset-id {dataset_id} \\
  --seed {seed}
```

The builder performs two full source scans. It validates formats and clues,
protects all upstream test IDs, removes exact and digit-renaming-equivalent
cross-split overlap, allocates metadata-stratified quotas, selects by seeded
SHA-256 rank, validates every selected Sudoku solution, and writes Parquet plus
machine-readable audits.

Verify the result independently:

```bash
python scripts/verify_dataset.py rebuilt-release \
  --expected-version {DATASET_VERSION} \
  --expected-seed {seed}
```

The expected processed split hashes are recorded in `metadata/manifest.json`.
Timestamp fields may differ across rebuilds; the Parquet content hashes must not.
"""


def render_difficulty_guide() -> str:
    return f"""# Difficulty definition and quantitative audit

This document defines the difficulty fields used by Sudoku DLM Reasoning release
`{DATASET_VERSION}`. Difficulty is an operational, solver-relative measurement;
it is not a human Sudoku grade and is not defined by the number of clues.

## 1. Provenance of the rating

For the Sudoku Extreme rows, the upstream `rating` column is copied into
`official_rating` and labeled `rating_type = tdoku_backtracks`. The converter
does not recompute the rating:

- Sudoku Extreme card: https://huggingface.co/datasets/sapientinc/sudoku-extreme
- Conversion code: https://github.com/hengyuf/diffusion-vs-ar/blob/ba0445f4d0808113bf08a9a9d8c7041086bfdf10/tools/prepare_sudoku_datasets.py

The upstream card describes the value as the number of backtracks required by
Tdoku. At public Tdoku commit `{TDOKU_REFERENCE_REVISION}`, the counter is named
`num_guesses_` and is incremented whenever the DPLL solver expands a binary
configuration decision:

- Branch implementation: https://github.com/t-dillon/tdoku/blob/{TDOKU_REFERENCE_REVISION}/src/solver_dpll_triad_simd.cc#L539-L559
- Branch-variable selection: https://github.com/t-dillon/tdoku/blob/{TDOKU_REFERENCE_REVISION}/src/solver_dpll_triad_simd.cc#L473-L536

Operationally, `official_rating` is best interpreted as the number of search
decision nodes visited before the first solution, rather than literal failed
undo operations.

## 2. Constraint propagation and the DFS root

Tdoku does not begin search from an empty board or from the first empty cell.
For a standard 81-character puzzle it:

1. loads every given digit;
2. eliminates incompatible row, column, box, band, and stack configurations;
3. propagates those eliminations until the initialized state is consistent; and
4. calls depth-first search on that propagated partial state.

The initialization and call path are visible in that pinned public source:

- Initialization: https://github.com/t-dillon/tdoku/blob/{TDOKU_REFERENCE_REVISION}/src/solver_dpll_triad_simd.cc#L612-L634
- Solve entry point: https://github.com/t-dillon/tdoku/blob/{TDOKU_REFERENCE_REVISION}/src/solver_dpll_triad_simd.cc#L680-L693

Propagation applies only logical consequences of the current givens or branch
assumption. It makes no new hypothesis and is not counted by the rating. It can
end in a complete solution, a contradiction, or a fixed point that still has
multiple configurations.

This matters because two puzzles can both have rating zero while requiring very
different amounts of propagation.

## 3. What one branch means

For one digit in a three-row band (or a three-column stack), there are six
possible global placements across the three boxes. Tdoku represents these as
band configurations. When propagation leaves multiple configurations, the
branching heuristic selects:

1. the unresolved band or stack with the fewest configurations; then
2. the digit in that band or stack with the fewest configurations.

It then creates a binary decision:

- left branch: force the first remaining configuration;
- right branch: exclude that configuration and retain the others.

The counter increases once for this binary split. If the left branch fails and
the right branch immediately solves the puzzle, the count for that decision is
still one. A later split of the remaining configurations increases it again.
Therefore the rating is not the recursion depth, the number of filled cells, the
number of contradictions, or a human solving-step count.

## 4. Bucket definitions

The source converter applies these thresholds:

| release label | operational rule | interpretation |
|---|---:|---|
| `original` | no Tdoku rating | separate easy collection; not numerically calibrated to Extreme |
| `r0` | rating = 0 | propagation resolves the puzzle without a search decision |
| `r1_4` | 1 <= rating < 5 | 1--4 visited decision nodes |
| `r5_19` | 5 <= rating < 20 | 5--19 visited decision nodes |

The upstream converter also defines `r20_49`, `r50_99`, and `r100_plus`, but
those buckets are outside this v1 candidate pool. Thus `r5_19` is an adjacent
held-out difficulty band, not the hardest part of the upstream corpus.

## 5. Quantitative audit of the raw candidate pool

The following statistics were computed over all 1,415,420 rows included under
`raw/`. Rating and clue statistics use the full pool.

| bucket | rows | rating mean / median | clue mean / median | clue range |
|---|---:|---:|---:|---:|
| `original` | 101,000 | not rated | 33.813 / 34 | 29--37 |
| `r0` | 614,136 | 0 / 0 | 26.282 / 26 | 17--37 |
| `r1_4` | 588,453 | 1.976 / 2 | 25.604 / 26 | 17--31 |
| `r5_19` | 111,831 | 11.776 / 12 | 24.932 / 25 | 17--30 |

Clue count is not a substitute for this rating. Within `r1_4`, the Pearson
correlation between rating and clues is -0.035; within `r5_19` it is 0.002.

As an independent diagnostic, standard row/column/box naked-single propagation
was run over all 101,000 original rows and deterministic 20,000-row reservoir
samples of each Extreme bucket. The reservoir seeds were `20260816` for `r0`,
`20260817` for `r1_4`, and `20260818` for `r5_19`:

| bucket | rows checked | solved by naked singles |
|---|---:|---:|
| `original` | 101,000 | 100,959 (99.959%) |
| `r0` | 20,000 | 3,691 (18.455%) |
| `r1_4` | 20,000 | 0 |
| `r5_19` | 20,000 | 0 |

The 41 original rows that stalled under naked singles were all solved after
adding hidden-single propagation. This independent audit describes basic Sudoku
logic, not Tdoku's own internal propagation, which is configuration-based and
stronger.

## 6. Released train and evaluation distributions

The three training buckets are equal in size, but exact ratings inside `r1_4`
retain the upstream proportions:

| exact rating | train rows |
|---:|---:|
| 1 | 29,584 |
| 2 | 16,809 |
| 3 | 10,244 |
| 4 | 8,899 |

The main `r1_4` test allocation instead uses 250 rows at each exact rating 1,
2, 3, and 4. The `r5_19` test allocation uses 250 rows from each of `[5,8)`,
`[8,12)`, `[12,16)`, and `[16,20)`; `test_ood_confirm` uses 1,000 per range.
This supports per-rating or per-range reporting rather than only a bucket-wide
average.

## 7. Source confounding

Difficulty and source collection are not independent in the raw pool:

- `r0`: 77.40% `puzzles1_unbiased`, 16.28% `puzzles0_kaggle`, and 6.30%
  `puzzles2_17_clue`;
- `r1_4`: 85.02% `puzzles1_unbiased`, 9.70%
  `puzzles4_forum_hardest_1905`, and 3.40% `01_file1`;
- `r5_19`: 68.19% `puzzles4_forum_hardest_1905`, 28.15% `01_file1`, and only
  2.18% `puzzles1_unbiased`.

Consequently, an `r5_19` result combines a Tdoku-rating shift, a held-out
training-exposure shift, and a source-distribution shift. It must not be
interpreted as a pure causal effect of search count.

Recommended reporting includes exact rating or subrange, source collection, and
clue count. A source- and clue-matched diagnostic set is appropriate when the
goal is to isolate the rating axis.

## 8. Reproducibility limitation

The public Sudoku Extreme card does not pin the Tdoku commit, build flags,
command, permutation policy, or seed used to create its rating column. This
release therefore preserves `official_rating` as an upstream measurement rather
than claiming to reproduce it.

For a fully controlled future rating, pin a Tdoku commit and configuration,
record the branch count for the exact stored puzzle, and optionally measure its
mean and variance over Sudoku-preserving isomorphic transformations.
"""


def render_raw_license_notice() -> str:
    return """# Raw data licensing and provenance notice

This dataset repository uses `license: other` because the included raw data does
not have one uniform declared license.

- Construction code in `hengyuf/diffusion-vs-ar` is distributed under the
  Apache License 2.0. That software license does not automatically relicense all
  third-party puzzle data.
- The original easy Sudoku CSV files are mirrored from the pinned
  `fhyfhy/diffusion-vs-ar-hard-sudoku` dataset snapshot.
- The `sudoku_extreme_*` files derive from `sapientinc/sudoku-extreme`, which
  combines several community benchmark sources and does not declare one uniform
  dataset license.

Files under `raw/` are unmodified research mirrors with byte-level provenance in
`metadata/raw_manifest.json`. Their inclusion here does not grant rights beyond
those provided by their respective upstream sources. Users are responsible for
reviewing and complying with the upstream terms before redistribution or use,
especially outside research contexts.

Upstream references:

- https://huggingface.co/datasets/fhyfhy/diffusion-vs-ar-hard-sudoku
- https://huggingface.co/datasets/sapientinc/sudoku-extreme
- https://github.com/hengyuf/diffusion-vs-ar/tree/hard-sudoku-datasets
"""


def copy_raw_snapshot(
    source_dir: Path, output_dir: Path, specs: Iterable[PoolSpec]
) -> dict[str, object]:
    raw_dir = output_dir / "raw"
    raw_dir.mkdir()
    files: dict[str, object] = {}
    for spec in sorted(set(specs), key=lambda item: item.relative_path):
        source = source_dir / spec.relative_path
        destination = raw_dir / spec.relative_path
        destination.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, destination)
        relative = destination.relative_to(output_dir).as_posix()
        source_hash = sha256_file(source)
        destination_hash = sha256_file(destination)
        if source_hash != destination_hash:
            raise IOError(f"raw copy hash mismatch: {spec.relative_path}")
        files[relative] = {
            "bytes": destination.stat().st_size,
            "sha256": destination_hash,
            "rows": spec.expected_rows,
            "upstream_path": spec.relative_path,
            "upstream_split": spec.upstream_split,
            "difficulty_bucket": spec.bucket,
        }

    upstream_manifest = source_dir / "processed/manifest.json"
    if upstream_manifest.is_file():
        shutil.copy2(upstream_manifest, raw_dir / "upstream_processed_manifest.json")
    (raw_dir / "README.md").write_text(render_raw_readme(), encoding="utf-8")
    return files


def render_readme(dataset_id: str, seed: str) -> str:
    return f"""---
license: other
task_categories:
- text-generation
tags:
- sudoku
- reasoning
- planning
- discrete-diffusion
- out-of-distribution
pretty_name: Sudoku DLM Reasoning
configs:
- config_name: default
  data_files:
  - split: train
    path: data/train.parquet
  - split: validation
    path: data/validation.parquet
  - split: test
    path: data/test.parquet
  - split: test_ood_confirm
    path: data/test_ood_confirm.parquet
---

# Sudoku DLM Reasoning

`{dataset_id}` is a deterministic 9x9 Sudoku benchmark for studying masked
diffusion language models, depth, and iterative decoding. Version {DATASET_VERSION}
trains only on `original`, `r0`, and `r1_4`; `r5_19` is held out for adjacent
difficulty extrapolation.

Version {DATASET_VERSION} changes only the deterministic selection seed to `0`
relative to v1.0.2. The raw CSV files, sources, bucket definitions, split quotas,
schema, and validation rules are unchanged; the four Parquet splits are
regenerated deterministically from the same candidate pool.

## Repository layout

- `raw/`: complete 1,415,420-row candidate snapshot used by this protocol
- `data/`: selected, leakage-audited Parquet splits used for experiments
- `metadata/`: source/release hashes, split specification, and audits
- `scripts/`: deterministic builder and independent verifier
- `docs/BUILDING.md`: end-to-end reconstruction instructions
- `docs/DIFFICULTY.md`: operational difficulty definition and quantitative audit

Files under `raw/` are explicitly source data and are not loaded as extra splits.
Only the four `data/*.parquet` paths declared in the card metadata form the
`default` dataset config.

## Splits

| split | original | r0 | r1_4 | r5_19 | total |
|---|---:|---:|---:|---:|---:|
| train | 65,536 | 65,536 | 65,536 | 0 | 196,608 |
| validation | 2,048 | 2,048 | 2,048 | 0 | 6,144 |
| test | 1,000 | 1,000 | 1,000 | 1,000 | 4,000 |
| test_ood_confirm | 0 | 0 | 0 | 4,000 | 4,000 |

The primary zero-shot protocol selects the checkpoint, decoding strategy, and
number of decoding steps using only `validation`. It must not use `r5_19` before
the final `test` evaluation. `test_ood_confirm` is reserved for confirming a
small number of already-selected configurations; it is not a tuning split.

## Difficulty

`r0`, `r1_4`, and `r5_19` use an upstream Tdoku search measurement. In public
Tdoku commit `{TDOKU_REFERENCE_REVISION}`, the counter increments when the
solver expands a binary band/stack-configuration decision after constraint propagation.
It is therefore best interpreted as visited search decision nodes, not recursion
depth, failed undo count, clue count, or human difficulty. `original` comes from
a separate easy collection and has no official rating on this scale.

See `docs/DIFFICULTY.md` for the DFS root, propagation and branch semantics,
bucket formulas, full raw-pool statistics, source confounding, and the upstream
rating-provenance limitation.

The evaluation sample deliberately covers subranges:

- `r1_4`: `[1,2)`, `[2,3)`, `[3,4)`, `[4,5)`
- `r5_19`: `[5,8)`, `[8,12)`, `[12,16)`, `[16,20)`

The 1,000-row test allocation uses 250 rows from each subrange. The 4,000-row
confirmation allocation uses 1,000 rows from each `r5_19` subrange. Within a
subrange, source collection and clue count retain their upstream proportions.

## Deterministic construction

- Upstream repository: [`{SOURCE_REPO}`](https://huggingface.co/datasets/{SOURCE_REPO})
- Pinned upstream revision: `{SOURCE_REVISION}`
- Release seed: `{seed}`
- Sampling: proportional metadata-stratified bottom-k by SHA-256 rank
- Leakage checks: exact puzzle plus digit-renaming-normalized puzzle/solution pair
- Validation: 81-character format, clue consistency, and Sudoku row/column/box validity

The source train/test boundary is preserved. Validation rows come only from
unused upstream training rows. Test and confirmation rows come only from upstream
test files. Full file hashes, row provenance, exclusions, and pairwise overlap
checks are in `metadata/manifest.json` and `metadata/audit.json`.

The upstream Sudoku Extreme corpus states that its official train and test sets
are mathematically inequivalent. This release additionally audits exact and digit
renaming overlap across the mixed original/Extreme sources. It does not implement
full canonicalization over every Sudoku row, column, band, stack, and transpose
symmetry; that remains a documented limitation.

## Schema

The main columns are `puzzle`, `solution`, `difficulty_bucket`,
`difficulty_subbucket`, `official_rating`, `clues`, `source_collection`, and
`release_split`. `example_id`, `puzzle_id`, and `digit_normalized_id` are stable
SHA-256 identifiers. `source_file` and `source_row_index` provide exact provenance.

```python
from datasets import load_dataset

dataset = load_dataset("{dataset_id}")
train = dataset["train"]
validation = dataset["validation"]
test = dataset["test"]
```

Puzzles and solutions are 81-character row-major strings. `0` denotes an empty
cell in `puzzle`.

## Rebuild

The pinned source CSV files are included under `raw/`. Run:

```bash
python scripts/build_dataset.py \\
  --source-dir raw \\
  --output-dir /path/to/release \\
  --dataset-id {dataset_id} \\
  --seed {seed}
```

The builder requires Python 3.10+ and PyArrow. See `docs/BUILDING.md`, then run
`scripts/verify_dataset.py` against the rebuilt release.

## Attribution and license

The data is derived from
[`fhyfhy/diffusion-vs-ar-hard-sudoku`](https://huggingface.co/datasets/{SOURCE_REPO}),
which packages the original Sudoku data from
[`HKUNLP/diffusion-vs-ar`](https://github.com/HKUNLP/diffusion-vs-ar) and the
[`sapientinc/sudoku-extreme`](https://huggingface.co/datasets/sapientinc/sudoku-extreme)
corpus. Please consult and comply with the licenses and attribution requirements
of all upstream sources. This derived release does not grant rights beyond them.
See `RAW_DATA_LICENSES.md` for the raw-snapshot notice.
"""


def build_dataset(
    source_dir: Path,
    output_dir: Path,
    *,
    dataset_id: str,
    seed: str,
) -> None:
    if not source_dir.is_dir():
        raise FileNotFoundError(f"source directory does not exist: {source_dir}")
    if output_dir.exists() and any(output_dir.iterdir()):
        raise FileExistsError(f"output directory must be absent or empty: {output_dir}")
    output_dir.mkdir(parents=True, exist_ok=True)
    data_dir = output_dir / "data"
    metadata_dir = output_dir / "metadata"
    scripts_dir = output_dir / "scripts"
    docs_dir = output_dir / "docs"
    data_dir.mkdir()
    metadata_dir.mkdir()
    scripts_dir.mkdir()
    docs_dir.mkdir()

    test_specs = ordered_specs("test", TEST_PRIORITY)
    train_specs = ordered_specs("train", TRAIN_PRIORITY)

    print("[1/9] Scanning and de-duplicating all protected upstream test pools...")
    test_scan = scan_pools(source_dir, test_specs, collect_all_ids=True)

    print("[2/9] Scanning train pools and excluding all test-equivalent rows...")
    train_scan = scan_pools(
        source_dir,
        train_specs,
        protected_puzzles=test_scan["all_puzzles"],
        protected_digit_normalized=test_scan["all_digit_normalized"],
    )

    train_allocations: dict[str, dict[str, int]] = {}
    validation_allocations: dict[str, dict[str, int]] = {}
    for bucket in TRAIN_PRIORITY:
        counts = train_scan["counts"][bucket]
        train_quota = allocate_proportional(counts, TRAIN_PER_BUCKET)
        validation_quota = allocate_proportional(
            subtract_counts(counts, train_quota), VALIDATION_PER_BUCKET
        )
        train_allocations[bucket] = train_quota
        validation_allocations[bucket] = validation_quota

    test_allocations: dict[str, dict[str, int]] = {}
    confirm_allocations: dict[str, dict[str, int]] = {}
    for bucket in TEST_PRIORITY:
        counts = test_scan["counts"][bucket]
        if bucket in {"original", "r0"}:
            test_quota = allocate_proportional(counts, TEST_PER_BUCKET)
        elif bucket == "r1_4":
            test_quota = allocate_balanced_groups(
                counts,
                test_scan["stratum_groups"],
                {"r1_2": 250, "r2_3": 250, "r3_4": 250, "r4_5": 250},
            )
        else:
            test_quota = allocate_balanced_groups(
                counts,
                test_scan["stratum_groups"],
                {"r5_7": 250, "r8_11": 250, "r12_15": 250, "r16_19": 250},
            )
        test_allocations[bucket] = test_quota
        remaining = subtract_counts(counts, test_quota)
        if bucket == "r5_19":
            confirm_allocations[bucket] = allocate_balanced_groups(
                remaining,
                test_scan["stratum_groups"],
                {
                    "r5_7": 1_000,
                    "r8_11": 1_000,
                    "r12_15": 1_000,
                    "r16_19": 1_000,
                },
            )
        else:
            confirm_allocations[bucket] = {key: 0 for key in counts}

    train_quota_all = add_allocations(*train_allocations.values())
    validation_quota_all = add_allocations(*validation_allocations.values())
    test_quota_all = add_allocations(*test_allocations.values())
    confirm_quota_all = add_allocations(*confirm_allocations.values())

    print("[3/9] Selecting deterministic train and validation rows...")
    selected_train = collect_ranked_candidates(
        source_dir,
        train_specs,
        add_allocations(train_quota_all, validation_quota_all),
        seed=seed,
        scope="train_validation",
        protected_puzzles=test_scan["all_puzzles"],
        protected_digit_normalized=test_scan["all_digit_normalized"],
    )
    train_rows, validation_rows = assign_release_rows(
        selected_train,
        train_quota_all,
        validation_quota_all,
        first_split="train",
        second_split="validation",
    )

    print("[4/9] Selecting deterministic ID/OOD test and OOD confirmation rows...")
    selected_test = collect_ranked_candidates(
        source_dir,
        test_specs,
        add_allocations(test_quota_all, confirm_quota_all),
        seed=seed,
        scope="test_confirm",
    )
    test_rows, confirm_rows = assign_release_rows(
        selected_test,
        test_quota_all,
        confirm_quota_all,
        first_split="test",
        second_split="test_ood_confirm",
    )

    splits = {
        "train": train_rows,
        "validation": validation_rows,
        "test": test_rows,
        "test_ood_confirm": confirm_rows,
    }
    expected_sizes = {
        "train": 3 * TRAIN_PER_BUCKET,
        "validation": 3 * VALIDATION_PER_BUCKET,
        "test": 4 * TEST_PER_BUCKET,
        "test_ood_confirm": OOD_CONFIRM_SIZE,
    }
    for split, rows in splits.items():
        if len(rows) != expected_sizes[split]:
            raise AssertionError(f"{split}: got {len(rows)}, expected {expected_sizes[split]}")
        stable_output_order(rows, seed, split)

    print("[5/9] Strictly validating every selected puzzle and solution...")
    for rows in splits.values():
        strict_validate_selected(rows)
    overlaps = overlap_audit(splits)

    print("[6/9] Writing Parquet splits and processed-split audits...")
    parquet_paths: dict[str, Path] = {}
    for split, rows in splits.items():
        path = data_dir / f"{split}.parquet"
        write_parquet(path, rows)
        parquet_paths[split] = path

    split_summaries = {split: summarize_rows(rows) for split, rows in splits.items()}
    audit = {
        "dataset_version": DATASET_VERSION,
        "seed": seed,
        "selected_splits": split_summaries,
        "pairwise_overlap": overlaps,
        "source_test_scan": {
            key: test_scan[key]
            for key in ("raw_counts", "accepted_counts", "exclusions")
        },
        "source_train_scan": {
            key: train_scan[key]
            for key in ("raw_counts", "accepted_counts", "exclusions")
        },
        "symmetry_audit_scope": {
            "exact_puzzle": True,
            "digit_renaming": True,
            "full_row_column_band_stack_transpose_group": False,
        },
        "strict_selected_rows_verified": sum(len(rows) for rows in splits.values()),
    }
    write_json(metadata_dir / "audit.json", audit)

    split_spec = {
        "dataset_version": DATASET_VERSION,
        "seed": seed,
        "training_buckets": ["original", "r0", "r1_4"],
        "ood_bucket": "r5_19",
        "counts": {
            "train_per_bucket": TRAIN_PER_BUCKET,
            "validation_per_bucket": VALIDATION_PER_BUCKET,
            "test_per_bucket": TEST_PER_BUCKET,
            "test_ood_confirm": OOD_CONFIRM_SIZE,
        },
        "test_subbucket_targets": {
            "r1_4": {"r1_2": 250, "r2_3": 250, "r3_4": 250, "r4_5": 250},
            "r5_19": {"r5_7": 250, "r8_11": 250, "r12_15": 250, "r16_19": 250},
        },
        "confirm_subbucket_targets": {
            "r5_19": {
                "r5_7": 1_000,
                "r8_11": 1_000,
                "r12_15": 1_000,
                "r16_19": 1_000,
            }
        },
        "selection": "metadata-stratified bottom-k SHA-256 rank",
        "bucket_mix": "equal across training buckets; natural proportions within buckets",
    }
    write_json(metadata_dir / "split_spec.json", split_spec)

    print("[7/9] Writing dataset card, documentation, and reproducibility scripts...")
    (output_dir / "README.md").write_text(render_readme(dataset_id, seed), encoding="utf-8")
    (output_dir / "requirements.txt").write_text("pyarrow>=17\n", encoding="utf-8")
    (output_dir / "RAW_DATA_LICENSES.md").write_text(
        render_raw_license_notice(), encoding="utf-8"
    )
    (docs_dir / "BUILDING.md").write_text(
        render_building_guide(dataset_id, seed), encoding="utf-8"
    )
    (docs_dir / "DIFFICULTY.md").write_text(
        render_difficulty_guide(), encoding="utf-8"
    )
    shutil.copy2(Path(__file__), scripts_dir / "build_dataset.py")

    verifier_candidates = (
        Path(__file__).with_name("verify_sudoku_dlm_reasoning_dataset.py"),
        Path(__file__).with_name("verify_dataset.py"),
    )
    verifier_source = next((path for path in verifier_candidates if path.is_file()), None)
    if verifier_source is None:
        raise FileNotFoundError("independent dataset verifier is missing")
    shutil.copy2(verifier_source, scripts_dir / "verify_dataset.py")

    all_specs = list(POOLS.values())
    source_files = source_metadata(source_dir, all_specs)

    print("[8/9] Copying the complete v1 candidate pool under raw/...")
    raw_files = copy_raw_snapshot(source_dir, output_dir, all_specs)
    raw_manifest = {
        "label": "raw",
        "scope": "complete candidate pool used by the v1 protocol",
        "candidate_rows": sum(spec.expected_rows for spec in all_specs),
        "source_repo": SOURCE_REPO,
        "source_revision": SOURCE_REVISION,
        "files": raw_files,
        "upstream_processed_manifest": "raw/upstream_processed_manifest.json",
        "license_notice": "RAW_DATA_LICENSES.md",
    }
    write_json(metadata_dir / "raw_manifest.json", raw_manifest)

    row_counts = {
        path.relative_to(output_dir).as_posix(): len(splits[split])
        for split, path in parquet_paths.items()
    }
    row_counts.update(
        {relative: int(details["rows"]) for relative, details in raw_files.items()}
    )
    release_files: dict[str, object] = {}
    for path in sorted(output_dir.rglob("*")):
        if not path.is_file():
            continue
        relative = path.relative_to(output_dir).as_posix()
        if relative == "metadata/manifest.json":
            continue
        entry: dict[str, object] = {
            "bytes": path.stat().st_size,
            "sha256": sha256_file(path),
        }
        if relative in row_counts:
            entry["rows"] = row_counts[relative]
        release_files[relative] = entry

    manifest = {
        "dataset_id": dataset_id,
        "dataset_version": DATASET_VERSION,
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "seed": seed,
        "source": {
            "repo_id": SOURCE_REPO,
            "revision": SOURCE_REVISION,
            "files": source_files,
        },
        "schema": [{"name": field.name, "type": str(field.type)} for field in SCHEMA],
        "splits": split_summaries,
        "files": release_files,
        "audit_file": "metadata/audit.json",
        "split_spec_file": "metadata/split_spec.json",
        "raw_snapshot_file": "metadata/raw_manifest.json",
    }
    write_json(metadata_dir / "manifest.json", manifest)

    print("[9/9] Build complete.")
    print(json.dumps({"output_dir": str(output_dir), "splits": expected_sizes}, indent=2))


def main() -> None:
    args = parse_args()
    build_dataset(
        args.source_dir.resolve(),
        args.output_dir.resolve(),
        dataset_id=args.dataset_id,
        seed=str(args.seed),
    )


if __name__ == "__main__":
    main()