inky-engine 2.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
//! Layer 3 block cache, the types the rest of the layer builds on.
#![allow(dead_code)] // the pool, the table and the prefix tree are the callers; cargo check does not compile the unit tests
//!
//! A block is 64 positions. Inside it the order is `[pass][K|V][head][pos][HD]`,
//! one element `kvb` bytes (DESIGN.md). At `kvb = 2` a window block is 10 MiB and
//! a full block is 2 MiB; at `kvb = 1` (`--kv8`) each is half of that.
//! Each kind has its own pool, so an offset is a plain `u64` byte offset in that
//! pool: base 0 plus the 0-based pool index times that kind's stride at this `kvb`.
//! One contiguous allocation holds the kind until a new slot would pass the slab cap
//! (the device `maxBufferLength` on GPU), when the pool opens another slab (up to 4).
//! GPU block-table words come from [`BlockPool::gpu_table_entry`]: `(slab << 62) | within_slab_offset`,
//! and [`key_row_at`] adds the pass, K or V, head and position inside the block.
//! `BlockLayout`'s high limb of 2 is TLC's trap for a 32-bit truncation, not a base
//! this code uses. The in-block order is `InBlock.tla`.
//!
//! A generation does not wrap. The next generation after `u32::MAX` is refused.

use std::fmt;

#[cfg(not(standalone_blocks))]
use objc2::rc::Retained;
#[cfg(not(standalone_blocks))]
use objc2::runtime::ProtocolObject;
#[cfg(not(standalone_blocks))]
use objc2::Message;
#[cfg(not(standalone_blocks))]
use objc2_metal::{MTLBuffer, MTLDevice, MTLResourceOptions};

/// Positions in one block.
pub const BLOCK: usize = 64;
/// Sliding-window positions a start point keeps.
pub const WINDOW: usize = 1024;
/// Bytes in one full-attention block at fp16 (`kvb = 2`). Eight passes, 2 MiB.
pub const FULL_STRIDE: u64 = 2 * 1024 * 1024;
/// Bytes in one sliding-window block at fp16 (`kvb = 2`). Forty passes, 10 MiB.
pub const WINDOW_STRIDE: u64 = 10 * 1024 * 1024;
/// fp16 element width. `--kv8` passes 1.
pub const KVB_FP16: u32 = 2;
/// `--kv8` element width (1 byte per element, 128 bytes per 128-dim row; scale in low bit).
pub const KVB_KV8: u32 = 1;
/// `--kv4` WHT-KV4 row-bytes tag (`64` packed Lloyd-Max nibble bytes + `2`B fp16 RMS scale = `66`B).
pub const KVB_KV4: u32 = 66;
/// Bytes per 128-dim Key or Value row in `--kv4` (`WHT-KV4`).
pub const KV4_ROW_BYTES: u64 = 66;
/// Bytes in one full-attention block under `--kv4` (`8 * 2 * 8 * 64 * 66 = 540,672` B = `528 KiB`).
pub const KV4_FULL_STRIDE: u64 = (FULL_PASSES as u64) * 2 * (NKV as u64) * (BLOCK as u64) * KV4_ROW_BYTES;
/// Bytes in one sliding-window block under `--kv4` (`40 * 2 * 8 * 64 * 66 = 2,703,360` B = `2,640 KiB`).
pub const KV4_WINDOW_STRIDE: u64 = (WINDOW_PASSES as u64) * 2 * (NKV as u64) * (BLOCK as u64) * KV4_ROW_BYTES;
/// A kind holds at most this many slabs. One more is [`BlockError::Slab`].
pub const MAX_SLABS: usize = 4;
/// Bit shift of the 2-bit slab selector in a 64-bit GPU block-table word (`entry >> 62`).
pub const KV_SLAB_SHIFT: u32 = 62;
/// 62-bit within-slab byte-offset mask (`((1UL << 62) - 1UL)` in `src/kernels.metal`).
pub const KV_SLAB_MASK: u64 = (1u64 << KV_SLAB_SHIFT) - 1;
/// Metal buffer argument slots bound to `KV0, KV1, KV2, KV3` across all Layer 3 kernels.
pub const KV_SLAB_BUFFER_INDICES: [usize; MAX_SLABS] = [3, 10, 11, 12];
/// KV heads. The same count as `engine::NKV`.
pub const NKV: usize = 8;
/// Elements in one key or value. The same count as `engine::HD`.
pub const HD: usize = 128;
const _: () = assert!(HD == 128, "WHT-KV4 66-byte row layout requires HD == 128");
const _: () = assert!((HD / 2) as u64 + 2 == KV4_ROW_BYTES, "KV4_ROW_BYTES must equal HD/2 + 2");
/// Sliding-window layer passes stored in one window block.
pub const WINDOW_PASSES: usize = 40;
/// Full-attention layer passes stored in one full block.
pub const FULL_PASSES: usize = 8;
/// Sub-blocks per 64-token `BlockKind::Full` block in the `WHT-2bit` page sketch (`8 x 8` tokens).
pub const WHT2_NSUB: usize = 8;
/// Tokens summarized per `WHT-2bit` sub-block (`64 / 8 = 8`).
pub const WHT2_SUB_TOKS: usize = BLOCK / WHT2_NSUB;
/// Bytes per `(pass, kv_head)` `Wht2HeadSketch` (`256 B` 2-bit codes + `16 B` fp16 scales = `272 B`).
pub const WHT2_HEAD_SKETCH_BYTES: usize = 272;
/// Sketch sidecar bytes per 64-token `BlockKind::Full` slot (`8` passes × `8` KV heads × `272 B` = `17,408 B`).
pub const FULL_SKETCH_BYTES: usize = FULL_PASSES * NKV * WHT2_HEAD_SKETCH_BYTES;
/// Maximum 64-token `Full` blocks handled by the single-window `k_score_full_sketch_dec` kernel (`4,096` blocks = `262,144` tokens).
pub const SPARSE_4K_MAX_BLKS: usize = 4096;
/// Maximum 64-token `Full` blocks addressable across `k_score_full_sketch_dec_wide` (`32,768` blocks = `2,097,152` tokens).
pub const SPARSE_MAX_BLKS: usize = 32_768;
/// Threadgroup SRAM candidate capacity (`(ord: u32, blk: u16)`) in `k_score_full_sketch_dec_wide`.
pub const SPARSE_WIDE_CAND_CAP: usize = 4352;

/// Optimal N(0,1) 2-bit Lloyd-Max reconstruction centroids (Max 1960; thresholds `-0.9815988, 0.0, +0.9815988`).
pub const WHT2_LM2_VAL: [f32; 4] = [-1.5104176, -0.45278004, 0.45278004, 1.5104176];

/// Compact `WHT-2bit` sub-block key sketch for one `(pass_idx, kv_head)` of a 64-token `BlockKind::Full` block.
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Wht2HeadSketch {
    pub k_sk: [[u32; 8]; WHT2_NSUB],
    pub sc_sk: [u16; WHT2_NSUB],
}

const _: () = assert!(std::mem::size_of::<Wht2HeadSketch>() == WHT2_HEAD_SKETCH_BYTES);
const _: () = assert!(WHT2_NSUB * WHT2_SUB_TOKS == BLOCK);

/// Deterministic per-`(pass_idx, kv_head, dim)` Rademacher sign in `{-1.0, +1.0}` matching `sparse_rademacher_sign` in `src/kernels.metal`.
#[inline]
pub fn sparse_rademacher_sign(pass_idx: u32, g: u32, d: u32) -> f32 {
    let mut h = pass_idx
        .wrapping_mul(2_654_435_761)
        ^ g.wrapping_mul(2_246_822_519)
        ^ d.wrapping_mul(3_266_489_917);
    h ^= h >> 16;
    h = h.wrapping_mul(0x85eb_ca6b);
    h ^= h >> 13;
    if (h & 1) != 0 { -1.0 } else { 1.0 }
}

/// Exact normalized 128-point Walsh-Hadamard transform (`H_128^T = H_128`, `H_128^2 = I`), matching `sparse_wht128_tg` in `src/kernels.metal`.
pub fn wht128_in_place(v: &mut [f32; HD]) {
    let mut len = 1usize;
    while len < HD {
        let step = len * 2;
        let mut i = 0usize;
        while i < HD {
            for j in 0..len {
                let a = v[i + j];
                let b = v[i + j + len];
                v[i + j] = a + b;
                v[i + j + len] = a - b;
            }
            i += step;
        }
        len = step;
    }
    const INV_SQRT_128: f32 = 0.088_388_346;
    for x in v.iter_mut() {
        *x *= INV_SQRT_128;
    }
}

#[inline]
fn kv8_vscale_cpu(row: &[u8]) -> f32 {
    let w0 = u32::from_le_bytes([row[0], row[1], row[2], row[3]]);
    let w1 = u32::from_le_bytes([row[4], row[5], row[6], row[7]]);
    let hi = ((w0 & 0x0101_0101).wrapping_mul(0x0804_0201)) >> 24;
    let lo = ((w1 & 0x0101_0101).wrapping_mul(0x0804_0201)) >> 24;
    let c = ((hi & 15) << 4) | (lo & 15);
    ((8 + (c & 7)) as f32) * f32::from_bits(((c >> 3) + 107) << 23)
}

/// Pure-Rust reference builder for one `BlockKind::Full` slot's `17,408`-byte `WHT-2bit` sketch sidecar,
/// matching `k_build_full_sketch_blk` / `k_build_full_sketch_slots` in `src/kernels.metal` across
/// `Fp16` (`kvb = 2`), `Kv8` (`kvb = 1`), and `Kv4` (`kvb = 66`, directly in `WHT-128(D_K * k) - mu_rot` space).
pub fn compute_full_slot_wht2_sketch_cpu(
    slot_kv_bytes: &[u8],
    kvb: u32,
    valid_len: usize,
    out_sketch_bytes: &mut [u8],
) {
    let mode = KvMode::from_kvb_tag(kvb).unwrap_or_else(|_| panic!("invalid kvb {kvb}"));
    assert_eq!(out_sketch_bytes.len(), FULL_SKETCH_BYTES);
    let eff_len = valid_len.min(BLOCK);
    let row_bytes = mode.row_bytes() as usize;
    let head_bytes = BLOCK * row_bytes;
    let plane_bytes = NKV * head_bytes;
    let pass_bytes = 2 * plane_bytes;
    assert!(slot_kv_bytes.len() >= FULL_PASSES * pass_bytes);

    for pass_idx in 0..FULL_PASSES {
        for g in 0..NKV {
            let k_head_off = pass_idx * pass_bytes + g * head_bytes;
            let mut sk = Wht2HeadSketch { k_sk: [[0u32; 8]; WHT2_NSUB], sc_sk: [0u16; WHT2_NSUB] };
            for sb in 0..WHT2_NSUB {
                let t0 = sb * WHT2_SUB_TOKS;
                let t1 = (t0 + WHT2_SUB_TOKS).min(eff_len);
                if t1 > t0 {
                    let mut rot = [0.0f32; HD];
                    for t in t0..t1 {
                        let r_off = k_head_off + t * row_bytes;
                        let r_slice = &slot_kv_bytes[r_off..r_off + row_bytes];
                        match mode {
                            KvMode::Fp16 => {
                                for d in 0..HD {
                                    let h = u16::from_le_bytes([r_slice[2 * d], r_slice[2 * d + 1]]);
                                    rot[d] += f16_bits_to_f32(h);
                                }
                            }
                            KvMode::Kv8 => {
                                let vsc = kv8_vscale_cpu(r_slice);
                                for d in 0..HD {
                                    rot[d] += (r_slice[d] as i8 as f32) * vsc;
                                }
                            }
                            KvMode::Kv4 => {
                                let row_arr: &[u8; KV4_ROW_BYTES as usize] =
                                    r_slice.try_into().expect("KV4 row slice length");
                                let (deq, _) = kv4_unpack_row_cpu(row_arr);
                                for d in 0..HD {
                                    rot[d] += deq[d];
                                }
                            }
                        }
                    }
                    let inv_cnt = 1.0f32 / ((t1 - t0) as f32);
                    if mode == KvMode::Kv4 {
                        for val in &mut rot {
                            *val *= inv_cnt;
                        }
                    } else {
                        for (d, val) in rot.iter_mut().enumerate() {
                            *val = (*val * inv_cnt) * sparse_rademacher_sign(pass_idx as u32, g as u32, d as u32);
                        }
                        wht128_in_place(&mut rot);
                    }
                    let mut sq_terms = [0.0f32; HD];
                    for d in 0..HD {
                        sq_terms[d] = rot[d] * rot[d];
                    }
                    let ss = kv4_butterfly_sum128_cpu(&sq_terms);
                    let rms = (ss * (1.0f32 / (HD as f32))).sqrt();
                    let rms_h = f32_to_f16_bits(rms);
                    let rms_rt = f16_bits_to_f32(rms_h);
                    if rms_rt > 0.0 {
                        let mut words = [0u32; 8];
                        for (d, &val) in rot.iter().enumerate() {
                            let u = val / rms;
                            let code = u32::from(u >= -0.981_598_8)
                                + u32::from(u >= 0.0)
                                + u32::from(u >= 0.981_598_8);
                            words[d >> 4] |= code << ((d & 15) * 2);
                        }
                        sk.k_sk[sb] = words;
                        sk.sc_sk[sb] = rms_h;
                    }
                }
            }
            let sk_idx = pass_idx * NKV + g;
            let dst_off = sk_idx * WHT2_HEAD_SKETCH_BYTES;
            let dst = &mut out_sketch_bytes[dst_off..dst_off + WHT2_HEAD_SKETCH_BYTES];
            for sb in 0..WHT2_NSUB {
                for w in 0..8 {
                    let o = (sb * 8 + w) * 4;
                    dst[o..o + 4].copy_from_slice(&sk.k_sk[sb][w].to_le_bytes());
                }
            }
            for sb in 0..WHT2_NSUB {
                let o = 256 + sb * 2;
                dst[o..o + 2].copy_from_slice(&sk.sc_sk[sb].to_le_bytes());
            }
        }
    }
}

/// Pure-Rust reference scorer matching `k_score_full_sketch_dec` in `src/kernels.metal` for one `(pass_idx, kv_head)`.
pub fn score_wht2_head_sketch_cpu(
    head_sketch_bytes: &[u8],
    pass_idx: u32,
    g: u32,
    qp_group: &[[f32; HD]; 3],
    sink_group: &[f32; 3],
) -> f32 {
    score_wht2_head_sketch_mode_cpu(head_sketch_bytes, KvMode::Fp16, pass_idx, g, qp_group, sink_group)
}

/// Mode-aware pure-Rust reference scorer matching `k_score_full_sketch_dec` (`KvMode::Kv4` uses pre-rotated
/// `qp = WHT-128(D_K * q)` and DC-adjusted `sink - <qp, mu_rot>` with zero extra WHT butterfly).
pub fn score_wht2_head_sketch_mode_cpu(
    head_sketch_bytes: &[u8],
    mode: KvMode,
    pass_idx: u32,
    g: u32,
    qp_group: &[[f32; HD]; 3],
    sink_group: &[f32; 3],
) -> f32 {
    assert_eq!(head_sketch_bytes.len(), WHT2_HEAD_SKETCH_BYTES);
    let mut q_rot = [[0.0f32; HD]; 3];
    if mode == KvMode::Kv4 {
        q_rot = *qp_group;
    } else {
        for h in 0..3 {
            for d in 0..HD {
                q_rot[h][d] = qp_group[h][d] * sparse_rademacher_sign(pass_idx, g, d as u32);
            }
            wht128_in_place(&mut q_rot[h]);
        }
    }
    let mut page_best = -1.0e30f32;
    for sb in 0..WHT2_NSUB {
        let sc_off = 256 + sb * 2;
        let sc = f16_bits_to_f32(u16::from_le_bytes([head_sketch_bytes[sc_off], head_sketch_bytes[sc_off + 1]]));
        if sc <= 0.0 {
            continue;
        }
        let mut k_deq = [0.0f32; HD];
        for w in 0..8 {
            let o = (sb * 8 + w) * 4;
            let u = u32::from_le_bytes([
                head_sketch_bytes[o],
                head_sketch_bytes[o + 1],
                head_sketch_bytes[o + 2],
                head_sketch_bytes[o + 3],
            ]);
            for j in 0..16 {
                let code = ((u >> (j * 2)) & 3) as usize;
                k_deq[w * 16 + j] = WHT2_LM2_VAL[code];
            }
        }
        for h in 0..3 {
            let mut quarter_sums = [0.0f32; 4];
            for (pp, qs) in quarter_sums.iter_mut().enumerate() {
                let mut acc = 0.0f32;
                for c in 0..8 {
                    let base = pp * 32 + c * 4;
                    let d4 = (q_rot[h][base] * k_deq[base] + q_rot[h][base + 1] * k_deq[base + 1])
                        + (q_rot[h][base + 2] * k_deq[base + 2] + q_rot[h][base + 3] * k_deq[base + 3]);
                    acc += d4;
                }
                *qs = acc;
            }
            let dot = (quarter_sums[0] + quarter_sums[1]) + (quarter_sums[2] + quarter_sums[3]);
            let s = dot * sc - sink_group[h];
            if s > page_best {
                page_best = s;
            }
        }
    }
    page_best
}

/// Checked byte offset of `(pool_index, pass_idx, kv_head)`'s `272`-byte `Wht2HeadSketch` inside `sketch_slab`.
/// At `(pass_idx = 0, kv_head = 0)`, equals `pool_index * FULL_SKETCH_BYTES` (`pool_index * 17_408`).
#[inline]
pub fn sparse_sketch_byte_offset(pool_index: u32, pass_idx: u32, kv_head: u32) -> Result<usize, BlockError> {
    if pass_idx as usize >= FULL_PASSES || kv_head as usize >= NKV {
        return Err(BlockError::OutOfRange);
    }
    let head_idx = (pool_index as u64)
        .checked_mul(FULL_PASSES as u64)
        .and_then(|v| v.checked_add(pass_idx as u64))
        .and_then(|v| v.checked_mul(NKV as u64))
        .and_then(|v| v.checked_add(kv_head as u64))
        .ok_or(BlockError::Overflow)?;
    let byte_off = head_idx
        .checked_mul(WHT2_HEAD_SKETCH_BYTES as u64)
        .ok_or(BlockError::Overflow)?;
    usize::try_from(byte_off).map_err(|_| BlockError::Overflow)
}

/// Update the contiguous `sketch_valid_len` (`0..=64`) of a `BlockKind::Full` block after an
/// incremental single-subblock decode kernel (`k_update_full_sketch_dec` / `k_kvprep_l2_dec`)
/// writes the 8-token sub-block containing `ib = pos & 63` (`sb_start = (ib / 8) * 8 .. ib + 1`).
///
/// Invariant: `sketch_valid_len` is strictly the contiguous prefix `[0 .. valid_len)` whose
/// sub-blocks are valid. If `prev_valid < sb_start` (e.g. a passthrough lane skipped earlier
/// sub-blocks and stepped mid-block in a mixed batch), `prev_valid` is NOT raised over the
/// unbuilt gap so `cur_valid < expected` triggers a full-slot catch-up when the lane becomes sparse.
#[inline]
pub fn advance_contiguous_sketch_valid_len(prev_valid: u8, ib: usize) -> u8 {
    debug_assert!(ib < BLOCK);
    let sb_start = ((ib / WHT2_SUB_TOKS) * WHT2_SUB_TOKS) as u8;
    let end = (ib + 1) as u8;
    if prev_valid >= sb_start {
        prev_valid.max(end)
    } else {
        prev_valid
    }
}

/// Monotone `f32 -> u32` order key matching `sparse_float_to_ord` in `src/kernels.metal`
/// (`NaN -> 0`, `-0.0 == +0.0 -> 0x8000_0000`, strictly order-preserving across `-inf..+inf`).
#[inline]
pub fn sparse_float_to_ord_cpu(x: f32) -> u32 {
    let raw = x.to_bits();
    if (raw & 0x7fff_ffff) > 0x7f80_0000 {
        return 0;
    }
    if x == 0.0 {
        return 0x8000_0000;
    }
    if (raw & 0x8000_0000) != 0 {
        !raw
    } else {
        raw ^ 0x8000_0000
    }
}

/// Pure block-window partition for `--sparse-topk` at token position `pos` (`total_blocks = pos / 64 + 1`).
/// `recent_blocks` pins `[total_blocks - recent_blocks .. total_blocks)` (`961..=1,024` trailing tokens when `recent_blocks = 16`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct SparseBlockPlan {
    pub passthrough: bool,
    pub total_blocks: usize,
    pub anchor_blocks: usize,
    pub far_start_blk: usize,
    pub n_far_blocks: usize,
    pub recent_start_blk: usize,
    pub top_k: usize,
    pub total_sel_blocks: usize,
}

#[inline]
pub fn sparse_block_window_plan(
    pos: usize,
    anchor_blocks: usize,
    recent_blocks: usize,
    sparse_topk: Option<usize>,
) -> SparseBlockPlan {
    let total_blocks = (pos / BLOCK) + 1;
    let Some(topk) = sparse_topk else {
        return SparseBlockPlan {
            passthrough: true,
            total_blocks,
            anchor_blocks: 0,
            far_start_blk: 0,
            n_far_blocks: 0,
            recent_start_blk: 0,
            top_k: 0,
            total_sel_blocks: total_blocks,
        };
    };
    let budget_blocks = anchor_blocks.saturating_add(recent_blocks).saturating_add(topk);
    let budget_tokens = budget_blocks.saturating_mul(BLOCK);
    if pos < budget_tokens || total_blocks <= budget_blocks {
        return SparseBlockPlan {
            passthrough: true,
            total_blocks,
            anchor_blocks: anchor_blocks.min(total_blocks),
            far_start_blk: 0,
            n_far_blocks: 0,
            recent_start_blk: total_blocks.saturating_sub(recent_blocks),
            top_k: 0,
            total_sel_blocks: total_blocks,
        };
    }
    let recent_start_blk = total_blocks - recent_blocks;
    let eff_anchors = anchor_blocks.min(recent_start_blk);
    let far_start_blk = eff_anchors;
    let n_far_blocks = recent_start_blk - far_start_blk;
    let eff_top_k = topk.min(n_far_blocks);
    let total_sel_blocks = eff_anchors + eff_top_k + recent_blocks;
    SparseBlockPlan {
        passthrough: false,
        total_blocks,
        anchor_blocks: eff_anchors,
        far_start_blk,
        n_far_blocks,
        recent_start_blk,
        top_k: eff_top_k,
        total_sel_blocks,
    }
}

/// CPU reference Top-K block selector & compactor matching `k_score_full_sketch_dec` in `src/kernels.metal`
/// bit-for-bit: ranks `far_scores` (`far_start_blk .. far_start_blk + far_scores.len()`) by
/// `(sparse_float_to_ord_cpu(score) DESC, blk ASC)`, pins `0..anchor_blocks` and `recent_start_blk..total_blocks`,
/// and returns the strictly ascending deduplicated block-index list.
pub fn select_sparse_topk_cpu(
    anchor_blocks: usize,
    far_start_blk: usize,
    recent_start_blk: usize,
    total_blocks: usize,
    top_k: usize,
    far_scores: &[f32],
) -> Vec<u32> {
    let capped_total = total_blocks.min(SPARSE_MAX_BLKS);
    let capped_anchors = anchor_blocks.min(capped_total);
    let capped_recent = recent_start_blk.min(capped_total);
    let nfar = far_scores.len().min(SPARSE_MAX_BLKS);
    let k_ret = top_k.min(nfar);

    let mut sel: Vec<u32> = Vec::with_capacity(capped_anchors + k_ret + (capped_total - capped_recent));
    for b in 0..capped_anchors {
        sel.push(b as u32);
    }
    if k_ret > 0 && nfar > 0 {
        let mut cands: Vec<(u32, u32)> = far_scores[..nfar]
            .iter()
            .enumerate()
            .map(|(p, &s)| (sparse_float_to_ord_cpu(s), (far_start_blk + p) as u32))
            .collect();
        cands.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
        for &(_, blk) in cands.iter().take(k_ret) {
            if (blk as usize) < capped_total {
                sel.push(blk);
            }
        }
    }
    for b in capped_recent..capped_total {
        sel.push(b as u32);
    }
    sel.sort_unstable();
    sel.dedup();
    sel
}

/// Exact step-for-step CPU mirror of `k_score_full_sketch_dec_wide`'s single-pass chunked SRAM
/// 4-pass 8-bit radix + order-preserving stripe compaction tournament (`SPARSE_WIDE_CAND_CAP = 4,352`,
/// `u16` block index up to `32,768` blocks = `2,097,152` tokens).
#[cfg(not(standalone_blocks))]
pub fn select_sparse_topk_wide_tournament_cpu(
    anchor_blocks: usize,
    far_start_blk: usize,
    recent_start_blk: usize,
    total_blocks: usize,
    top_k: usize,
    far_scores: &[f32],
) -> Vec<u32> {
    let capped_total = total_blocks.min(SPARSE_MAX_BLKS);
    let capped_anchors = anchor_blocks.min(capped_total);
    let capped_recent = recent_start_blk.min(capped_total);
    let capped_far_start = far_start_blk.clamp(capped_anchors, capped_recent);
    let nfar = far_scores.len().min(capped_recent - capped_far_start);
    let k_ret = top_k.min(nfar).min(SPARSE_4K_MAX_BLKS - 1);

    let mut cand_ord = [0u32; SPARSE_WIDE_CAND_CAP];
    let mut cand_blk = [0u16; SPARSE_WIDE_CAND_CAP];
    let mut running_m = 0usize;

    if k_ret > 0 && nfar > 0 {
        let mut far_off = 0usize;
        while far_off < nfar {
            let chunk_cap = SPARSE_WIDE_CAND_CAP - running_m;
            let chunk_len = (nfar - far_off).min(chunk_cap);
            for q in 0..chunk_len {
                let blk = capped_far_start + far_off + q;
                cand_ord[running_m + q] = sparse_float_to_ord_cpu(far_scores[far_off + q]);
                cand_blk[running_m + q] = u16::try_from(blk).expect("block index fits u16 (< 32768)");
            }
            let total_cand = running_m + chunk_len;
            far_off += chunk_len;

            if total_cand <= k_ret {
                running_m = total_cand;
                continue;
            }

            let mut cut_prefix = 0u32;
            let mut cut_rem = k_ret as u32;
            for rpass in 0..4 {
                let shift = ((3 - rpass) * 8) as u32;
                let mask_shift = if rpass == 0 { 0u32 } else { ((4 - rpass) * 8) as u32 };
                let mut hist = [0u32; 256];
                for &u in &cand_ord[..total_cand] {
                    if rpass == 0 || (u >> mask_shift) == cut_prefix {
                        hist[((u >> shift) & 255) as usize] += 1;
                    }
                }
                let mut acc = 0u32;
                let mut chosen = 0u32;
                for bi in (0..256).rev() {
                    let c = hist[bi];
                    if acc + c >= cut_rem {
                        chosen = bi as u32;
                        break;
                    }
                    acc += c;
                }
                cut_prefix = (cut_prefix << 8) | chosen;
                cut_rem -= acc;
            }

            let thresh32 = cut_prefix;
            let mut rem_ties = cut_rem;
            let mut out_count = 0usize;
            for i in 0..total_cand {
                let u = cand_ord[i];
                let b = cand_blk[i];
                let take_tie = if u == thresh32 && rem_ties > 0 {
                    rem_ties -= 1;
                    true
                } else {
                    false
                };
                if u > thresh32 || take_tie {
                    cand_ord[out_count] = u;
                    cand_blk[out_count] = b;
                    out_count += 1;
                }
            }
            assert_eq!(out_count, k_ret);
            for w in cand_blk[..out_count].windows(2) {
                debug_assert!(w[0] < w[1], "chunked tournament must preserve strictly ascending cand_blk");
            }
            running_m = k_ret;
        }
    }

    let n_recent = capped_total - capped_recent;
    let mut out = Vec::with_capacity(capped_anchors + running_m + n_recent);
    for b in 0..capped_anchors {
        out.push(b as u32);
    }
    for &b in &cand_blk[..running_m] {
        out.push(u32::from(b));
    }
    for r in 0..n_recent {
        out.push((capped_recent + r) as u32);
    }
    out
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum KvMode {
    /// Exact FP16 (`256` bytes per 128-dim row, `kvb = 2`).
    Fp16,
    /// Per-head-row symmetric INT8 (`--kv8`, `128` bytes per 128-dim row, `kvb = 1`).
    Kv8,
    /// WHT-128 + Rademacher + 4-bit Gaussian Lloyd-Max (`--kv4`, `66` bytes per 128-dim row).
    Kv4,
}

impl KvMode {
    pub const fn from_flags(kv8: bool, kv4: bool) -> Result<Self, BlockError> {
        match (kv8, kv4) {
            (false, false) => Ok(Self::Fp16),
            (true, false) => Ok(Self::Kv8),
            (false, true) => Ok(Self::Kv4),
            (true, true) => Err(BlockError::Kvb),
        }
    }

    pub const fn from_kvb_tag(tag: u32) -> Result<Self, BlockError> {
        match tag {
            KVB_FP16 => Ok(Self::Fp16),
            KVB_KV8 => Ok(Self::Kv8),
            KVB_KV4 => Ok(Self::Kv4),
            _ => Err(BlockError::Kvb),
        }
    }

    pub const fn kvb_tag(self) -> u32 {
        match self {
            Self::Fp16 => KVB_FP16,
            Self::Kv8 => KVB_KV8,
            Self::Kv4 => KVB_KV4,
        }
    }

    pub const fn row_bytes(self) -> u64 {
        match self {
            Self::Fp16 => (HD as u64) * 2,
            Self::Kv8 => HD as u64,
            Self::Kv4 => KV4_ROW_BYTES,
        }
    }

    pub const fn stride_bytes(self, kind: BlockKind) -> u64 {
        let passes = match kind {
            BlockKind::Window => WINDOW_PASSES as u64,
            BlockKind::Full => FULL_PASSES as u64,
        };
        passes * 2 * (NKV as u64) * (BLOCK as u64) * self.row_bytes()
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BlockKind { Window, Full }

impl BlockKind {
    pub fn passes(self) -> usize {
        match self {
            BlockKind::Window => WINDOW_PASSES,
            BlockKind::Full => FULL_PASSES,
        }
    }

    pub fn stride(self) -> u64 {
        match self {
            BlockKind::Window => WINDOW_STRIDE,
            BlockKind::Full => FULL_STRIDE,
        }
    }

    /// Bytes in one slot for [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`).
    pub const fn stride_for_mode(self, mode: KvMode) -> u64 {
        mode.stride_bytes(self)
    }

    /// Bytes in one slot at this element width. `kvb` is 2 for fp16 and 1 for `--kv8`.
    /// Any other width is refused. At 2 this is `FULL_STRIDE` or `WINDOW_STRIDE`.
    pub fn stride_bytes(self, kvb: u32) -> Result<u64, BlockError> {
        if kvb != 1 && kvb != 2 { return Err(BlockError::Width); }
        let passes = self.passes() as u64;
        passes.checked_mul(2)
            .and_then(|v| v.checked_mul(NKV as u64))
            .and_then(|v| v.checked_mul(BLOCK as u64))
            .and_then(|v| v.checked_mul(HD as u64))
            .and_then(|v| v.checked_mul(u64::from(kvb)))
            .ok_or(BlockError::Overflow)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BlockError {
    /// A slot number of 0. Slots are 1-based.
    SlotZero,
    /// A checked add or multiply did not fit.
    Overflow,
    /// The generation would wrap past `u32::MAX`.
    Generation,
    /// A length past the 64 positions in a block.
    Length,
    /// The block index is outside the table this pool declared.
    OutOfRange,
    /// A reference count that is already zero cannot be dropped.
    Refs,
    /// `kvb` is not 1 or 2.
    Kvb,
    /// A slot does not fit in the remaining slabs. At most [`MAX_SLABS`], each within the cap.
    Slab,
    /// This kind's pool has no slots. A key cannot be read from it.
    NoSlots,
    /// The block is inside the table and no entry was filled.
    NoEntry,
    /// The entry's generation is not the pool record's generation.
    Stale,
    /// Generation 0, on the argument or on the record. The slot has never been taken.
    NotTaken,
    /// `kvb` is 0, or a read asked for a different element width than the pool stores.
    Width,
}

impl fmt::Display for BlockError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BlockError::SlotZero => write!(f, "block slot 0 is not a slot"),
            BlockError::Overflow => write!(f, "block offset overflow"),
            BlockError::Generation => write!(f, "block generation would wrap"),
            BlockError::Length => write!(f, "block length past 64"),
            BlockError::OutOfRange => write!(f, "block index outside the table"),
            BlockError::Refs => write!(f, "block reference count is already zero"),
            BlockError::Kvb => write!(f, "block kvb must be 1 or 2"),
            BlockError::Slab => write!(f, "block slab cap exceeded"),
            BlockError::NoSlots => write!(f, "pool has no slots"),
            BlockError::NoEntry => write!(f, "block table has no entry"),
            BlockError::Stale => write!(f, "block generation does not match the pool"),
            BlockError::NotTaken => write!(f, "block slot has not been taken"),
            BlockError::Width => write!(f, "block element width does not match"),
        }
    }
}

/// A 1-based slot in one kind's pool. Not a block index and not a pool index.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Slot(u32);

impl Slot {
    pub fn new(n: u32) -> Result<Slot, BlockError> {
        if n == 0 { Err(BlockError::SlotZero) } else { Ok(Slot(n)) }
    }
    pub fn get(self) -> u32 { self.0 }
    /// The 0-based index of this slot in its pool.
    pub fn pool_index(self) -> PoolIndex { PoolIndex(self.0 - 1) }
}

/// A 0-based index into one kind's pool. Not a slot.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct PoolIndex(u32);

impl PoolIndex {
    pub fn get(self) -> u32 { self.0 }
}

/// Which 64-position block of the token stream. Not a slot.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct BlockIndex(u32);

impl BlockIndex {
    pub fn new(n: u32) -> BlockIndex { BlockIndex(n) }
    pub fn get(self) -> u32 { self.0 }
    pub fn of_pos(pos: usize) -> Result<BlockIndex, BlockError> {
        u32::try_from(pos / BLOCK).map(BlockIndex).map_err(|_| BlockError::Overflow)
    }
}

/// `index * stride`, refused when the product does not fit in `u64`.
fn mul_offset(index: u64, stride: u64) -> Result<u64, BlockError> {
    index.checked_mul(stride).ok_or(BlockError::Overflow)
}

/// Which plane of a pass. Key is first, Value is second, matching layer 2's `kv_slot`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kv {
    Key,
    Value,
}

impl Kv {
    #[cfg(any(test, standalone_blocks))]
    fn index(self) -> u32 {
        match self {
            Kv::Key => 0,
            Kv::Value => 1,
        }
    }
}

/// Byte offset of a slot in its kind's pool at element width `kvb`.
/// Refuses a product that does not fit in `u64`, and a `kvb` other than 1 or 2.
pub fn byte_offset(kind: BlockKind, slot: Slot, kvb: u32) -> Result<u64, BlockError> {
    mul_offset(u64::from(slot.pool_index().get()), kind.stride_bytes(kvb)?)
}

/// Byte offset of one key or value row inside a slot.
/// Order is `[pass][K|V][head][pos in the block][HD]`, each element `kvb` bytes,
/// so one head's 64 keys are contiguous. `base` is the slot's `byte_offset`.
/// A pass, head or position outside the block is `OutOfRange`.
#[cfg(any(test, standalone_blocks))]
pub fn key_row(base: u64, kind: BlockKind, kvb: u32, pass: u32, kv: Kv, head: u32, index: u32) -> Result<u64, BlockError> {
    key_row_at(base, kind.passes() as u32, NKV as u32, BLOCK as u32, HD as u32, kvb, pass, kv.index(), head, index)
}

/// Byte offset of one key or value row inside a slot at explicit bounds.
/// Order is `[pass][K|V][head][pos in the block][hd]`, each element `kvb` bytes,
/// matching `kv_blk_ptr` in `src/kernels.metal` and `src/prefill.metal`.
/// The InBlock trace calls it at the spec's bounds (2 passes, 3 heads, 4 positions, `HD` 2).
pub fn key_row_at(base: u64, passes: u32, heads: u32, block: u32, hd: u32, kvb: u32, pass: u32, plane: u32, head: u32, index: u32) -> Result<u64, BlockError> {
    if kvb != 1 && kvb != 2 { return Err(BlockError::Width); }
    if pass >= passes || plane >= 2 || head >= heads || index >= block {
        return Err(BlockError::OutOfRange);
    }
    let row = u64::from(hd).checked_mul(u64::from(kvb)).ok_or(BlockError::Overflow)?;
    let head_step = u64::from(block).checked_mul(row).ok_or(BlockError::Overflow)?;
    let kv_plane = u64::from(heads).checked_mul(head_step).ok_or(BlockError::Overflow)?;
    let pass_step = kv_plane.checked_mul(2).ok_or(BlockError::Overflow)?;
    let within = u64::from(pass).checked_mul(pass_step).ok_or(BlockError::Overflow)?
        .checked_add(u64::from(plane).checked_mul(kv_plane).ok_or(BlockError::Overflow)?).ok_or(BlockError::Overflow)?
        .checked_add(u64::from(head).checked_mul(head_step).ok_or(BlockError::Overflow)?).ok_or(BlockError::Overflow)?
        .checked_add(u64::from(index).checked_mul(row).ok_or(BlockError::Overflow)?).ok_or(BlockError::Overflow)?;
    base.checked_add(within).ok_or(BlockError::Overflow)
}

/// Decode a 64-bit GPU block-table word into `(slab_index, within_slab_byte_offset)`,
/// matching `kv_blk_ptr` (`uint(entry >> 62)` and `entry & KV_SLAB_MASK`) in `src/kernels.metal`.
#[inline]
pub fn decode_gpu_table_entry(entry: u64) -> (usize, u64) {
    ((entry >> KV_SLAB_SHIFT) as usize, entry & KV_SLAB_MASK)
}

/// Logical window block indices `[oldest / block ..= end / block]` required across a span
/// `[pos, pos + len)` at block size `block` and sliding-window width `window` (`U170`,
/// bound by trace to `specs/SpanPins.tla`).
pub fn span_window_blocks_at(
    pos: usize,
    len: usize,
    block: usize,
    window: usize,
) -> Result<Vec<BlockIndex>, BlockError> {
    if len == 0 || block == 0 || window == 0 {
        return Err(BlockError::OutOfRange);
    }
    let end = pos.checked_add(len - 1).ok_or(BlockError::Overflow)?;
    let oldest = pos.saturating_sub(window - 1);
    let lo_blk = u32::try_from(oldest / block).map_err(|_| BlockError::Overflow)?;
    let hi_blk = u32::try_from(end / block).map_err(|_| BlockError::Overflow)?;
    Ok((lo_blk..=hi_blk).map(BlockIndex::new).collect()) // MUTANT_ANCHOR_SPAN_WIN_BLOCKS
}

/// Production `(BLOCK = 64, WINDOW = 1024)` window blocks required across `[pos, pos + len)`.
pub fn span_window_blocks(pos: usize, len: usize) -> Result<Vec<BlockIndex>, BlockError> {
    span_window_blocks_at(pos, len, BLOCK, WINDOW)
}

/// One visited `(pos, (block, owner_row_1based), split)` key in [`GroupedTileState`].
pub type GroupedVisit = (usize, (usize, usize), usize);

/// Snapshot of one state in the grouped shared-prefix tile traversal (`specs/GroupedLayout.tla`,
/// `t-later-prefix-traces`).
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct GroupedTileState {
    pub lengths: [usize; 2],
    pub shared: usize,
    pub windowed: bool,
    pub tile: usize,
    /// Sorted deduplicated `(block, owner_row_1based)` slots already staged in the current `tile`.
    pub loaded: Vec<(usize, usize)>,
    /// Ordered history of `(tile, (block, owner_row_1based))` physical tile loads.
    pub staged: Vec<(usize, (usize, usize))>,
    /// Per-row visited `(pos, (block, owner_row_1based), split)` tuples.
    pub visits: [Vec<GroupedVisit>; 2],
    /// Per-row emitted `(split, last_visible_pos_in_split)` partials.
    pub partials: [Vec<(usize, usize)>; 2],
}

/// Deterministic grouped shared-prefix tile walker matching `specs/GroupedLayout.tla` and
/// `Engine::build_decode_groups` / `k_attn_grp_dec`:
/// - Stages each distinct physical `(block, owner)` slot once per tile, serving both rows when
///   `b < shared` (`count == 2` group) and each row privately when `b >= shared` (`count == 1`).
/// - Intersects each row's own visible range `[first_r, lengths[r])` with `[tile_start, tile_stop)`.
/// - Emits a split partial ONLY when `stop == lengths[r]` or `stop == (split + 1) * split_size`
///   (never at an internal tile boundary inside a split).
pub fn walk_grouped_tiles(
    lengths: [usize; 2],
    shared: usize,
    windowed: bool,
    block_size: usize,
    tile_size: usize,
    split_size: usize,
    window_size: usize,
) -> Vec<GroupedTileState> {
    assert!(block_size > 0 && tile_size > 0 && split_size >= tile_size && split_size.is_multiple_of(tile_size));
    assert!(lengths[0] >= 1 && lengths[1] >= 1);
    assert!(shared <= lengths[0].min(lengths[1]) / block_size);

    let slot_of = |r: usize, b: usize| -> (usize, usize) {
        (b, if b < shared { 1 } else { r + 1 })
    };
    let mask_start = |r: usize| -> usize {
        let first_r = if windowed { lengths[r].saturating_sub(window_size) } else { 0 }; // MUTANT_ANCHOR_GRP_MASK_START
        first_r
    };
    let max_len = lengths[0].max(lengths[1]);
    let tile_count = max_len.div_ceil(tile_size);

    let mut cur = GroupedTileState {
        lengths,
        shared,
        windowed,
        tile: 0,
        loaded: Vec::new(),
        staged: Vec::new(),
        visits: [Vec::new(), Vec::new()],
        partials: [Vec::new(), Vec::new()],
    };
    let mut trace = vec![cur.clone()];

    while cur.tile < tile_count {
        let tile_start = cur.tile * tile_size;
        let split = tile_start / split_size;
        let blk = tile_start / block_size;
        let mut requests: Vec<(usize, usize)> = Vec::new();
        for (r, &row_len) in lengths.iter().enumerate() {
            let start = tile_start.max(mask_start(r));
            let stop = (tile_start + tile_size).min(row_len);
            if start < stop {
                let s = slot_of(r, blk);
                if !requests.contains(&s) {
                    requests.push(s);
                }
            }
        }
        requests.sort_unstable();
        for s in requests {
            for (r, &row_len) in lengths.iter().enumerate() {
                let start = tile_start.max(mask_start(r));
                let stop = (tile_start + tile_size).min(row_len);
                if start < stop && slot_of(r, blk) == s {
                    for p in start..stop {
                        cur.visits[r].push((p, s, split));
                    }
                    let emit_partial = stop == row_len || stop == (split + 1) * split_size; // MUTANT_ANCHOR_GRP_PARTIAL_BOUNDARY
                    if emit_partial {
                        cur.partials[r].push((split, stop - 1));
                    }
                }
            }
            cur.loaded.push(s);
            cur.loaded.sort_unstable();
            cur.staged.push((cur.tile, s));
            trace.push(cur.clone());
        }
        cur.tile += 1;
        cur.loaded.clear();
        trace.push(cur.clone());
    }
    trace
}

/// KV layout constants and shader invariants extracted directly from `src/kernels.metal`
/// and `src/prefill.metal` (`U63` & `U18`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct MetalKvLayout {
    pub nkv: u32,
    pub hd: u32,
    pub kv_blk: u32,
    pub kv_blk_mask: u32,
    pub planes_per_pass: u64,
    pub slab_shift: u32,
    pub slab_buffers: [usize; MAX_SLABS],
    pub kv4_nibble_bytes: u32,
    pub kv4_scale_bytes: u32,
    pub kv4_row_bytes: u32,
    pub kv4_grp_tile_ushorts: u32,
}

fn parse_c_define_u32(src: &str, name: &str) -> Result<u32, &'static str> {
    for line in src.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("#define") {
            let mut it = rest.split_whitespace();
            if it.next() == Some(name) {
                let tok = it.next().ok_or("missing #define value")?;
                let digits = tok.trim_end_matches('u').trim_end_matches("UL");
                return digits.parse::<u32>().map_err(|_| "invalid integer in #define");
            }
        }
    }
    Err("missing #define in Metal source")
}

/// Parse and verify the Layer 3 KV block address macros, `kv_blk_ptr` 64-bit word decode,
/// and `KV0..KV3` buffer-index bindings across `src/kernels.metal` and `src/prefill.metal`.
pub fn parse_metal_kv_layout(kernels_src: &str, prefill_src: &str) -> Result<MetalKvLayout, &'static str> {
    #[cfg(test)]
    LAYOUT_PARSES.with(|n| n.set(n.get() + 1));
    let nkv = parse_c_define_u32(kernels_src, "NKV")?;
    let hd = parse_c_define_u32(kernels_src, "HD")?;
    let kv_blk = parse_c_define_u32(kernels_src, "KV_BLK")?;
    let kv_blk_mask = parse_c_define_u32(kernels_src, "KV_BLK_MASK")?;
    let sparse_max_blks = parse_c_define_u32(kernels_src, "SPARSE_MAX_BLKS")?;
    if sparse_max_blks as usize != SPARSE_MAX_BLKS {
        return Err("SPARSE_MAX_BLKS mismatch between Rust and Metal");
    }
    let sparse_4k_max_blks = parse_c_define_u32(kernels_src, "SPARSE_4K_MAX_BLKS")?;
    if sparse_4k_max_blks as usize != SPARSE_4K_MAX_BLKS {
        return Err("SPARSE_4K_MAX_BLKS mismatch between Rust and Metal");
    }
    let sparse_wide_cand_cap = parse_c_define_u32(kernels_src, "SPARSE_WIDE_CAND_CAP")?;
    if sparse_wide_cand_cap as usize != SPARSE_WIDE_CAND_CAP {
        return Err("SPARSE_WIDE_CAND_CAP mismatch between Rust and Metal");
    }
    if kv_blk == 0 || !kv_blk.is_power_of_two() || kv_blk_mask != kv_blk - 1 {
        return Err("KV_BLK / KV_BLK_MASK inconsistent");
    }
    if !kernels_src.contains("typedef int8_t kv_t;") || !kernels_src.contains("typedef half kv_t;") {
        return Err("missing kv_t KV8/fp16 typedefs");
    }
    // Parse and verify the `#ifdef KV4` packed row struct, Layer 3 macros, and `32 * 33` ushort tile copy.
    let kv4_struct_idx = kernels_src.find("struct kv4_row {").ok_or("missing struct kv4_row in kernels.metal")?;
    let kv4_struct_end = kernels_src[kv4_struct_idx..]
        .find("};")
        .ok_or("unterminated struct kv4_row in kernels.metal")?;
    let kv4_struct_body = &kernels_src[kv4_struct_idx..kv4_struct_idx + kv4_struct_end];
    let qs_idx = kv4_struct_body.find("uchar qs[").ok_or("struct kv4_row missing uchar qs[N]")?;
    let qs_after = &kv4_struct_body[qs_idx + "uchar qs[".len()..];
    let qs_close = qs_after.find("];").ok_or("malformed uchar qs[N] in struct kv4_row")?;
    let kv4_nibble_bytes = qs_after[..qs_close]
        .trim()
        .parse::<u32>()
        .map_err(|_| "invalid nibble byte count in struct kv4_row")?;
    if !kv4_struct_body.contains("half sc;") {
        return Err("struct kv4_row missing half sc scale field");
    }
    let kv4_scale_bytes = 2u32;
    let kv4_row_bytes = kv4_nibble_bytes + kv4_scale_bytes;
    if kv4_nibble_bytes * 2 != hd || u64::from(kv4_row_bytes) != KV4_ROW_BYTES {
        return Err("struct kv4_row size does not match HD/2 + 2 == KV4_ROW_BYTES");
    }
    let want_static_assert = format!("static_assert(sizeof(kv4_row) == {kv4_row_bytes},");
    if !kernels_src.contains(&want_static_assert)
        || !kernels_src.contains("typedef kv4_row kv_t;")
        || !kernels_src.contains("#define KV_HEAD_BYTES  (ulong(KV_BLK) * ulong(sizeof(kv_t)))")
        || !kernels_src.contains("#define KV_ROW_STEP    1u")
    {
        return Err("missing or altered KV4 typedef, sizeof static_assert, KV_HEAD_BYTES, or KV_ROW_STEP");
    }
    let kv4_grp_tile_ushorts = 32u32 * (kv4_row_bytes / 2);
    let want_grp_loop = format!("for (uint i = tid; i < 32u * {}u; i += 512u)", kv4_row_bytes / 2);
    if !kernels_src.contains(&want_grp_loop) || kv4_grp_tile_ushorts * 2 != 32 * kv4_row_bytes {
        return Err("missing or altered KV4 32x33 ushort tile copy in k_attn_grp_dec");
    }
    if !kernels_src.contains("#define KV_SLAB_MASK ((1UL << 62) - 1UL)") {
        return Err("missing or altered KV_SLAB_MASK");
    }
    if !kernels_src.contains("#define KV_HEAD_BYTES  (ulong(KV_BLK) * ulong(HD) * ulong(sizeof(kv_t)))") {
        return Err("missing or altered KV_HEAD_BYTES");
    }
    if !kernels_src.contains("#define KV_PLANE_BYTES (ulong(NKV) * KV_HEAD_BYTES)") {
        return Err("missing or altered KV_PLANE_BYTES");
    }
    let planes_per_pass = if kernels_src.contains("#define KV_PASS_BYTES  (2UL * KV_PLANE_BYTES)") {
        2u64
    } else {
        return Err("missing or altered KV_PASS_BYTES");
    };
    for needle in [
        "const uint si = uint(entry >> 62);",
        "const ulong off = entry & KV_SLAB_MASK;",
        "device uchar * base = (si == 0) ? s0 : (si == 1 ? s1 : (si == 2 ? s2 : s3));",
        "return (device kv_t *) (base + off + in_slot_off);",
    ] {
        if !kernels_src.contains(needle) {
            return Err("kv_blk_ptr formula altered");
        }
    }
    let check_kernel = |src: &str, kname: &str| -> Result<(), &'static str> {
        let anchor = format!("kernel void {kname}(");
        let idx = src.find(&anchor).ok_or("missing Layer 3 Metal kernel")?;
        let rest = &src[idx..];
        let body_end = rest[1..].find("\nkernel void ").map_or(rest.len(), |p| p + 1);
        let ksrc = &rest[..body_end];
        for bind in [
            "KV0 [[buffer(3)]]",
            "KV1 [[buffer(10)]]",
            "KV2 [[buffer(11)]]",
            "KV3 [[buffer(12)]]",
        ] {
            if !ksrc.contains(bind) {
                return Err("Layer 3 kernel missing canonical KV0..KV3 buffer(3,10,11,12) binding");
            }
        }
        if !ksrc.contains("* KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;")
            || !ksrc.contains("const ulong voff = koff + KV_PLANE_BYTES;")
            || !ksrc.contains("kv_blk_ptr(KV0, KV1, KV2, KV3,")
        {
            return Err("Layer 3 kernel missing canonical koff/voff/kv_blk_ptr address formula");
        }
        Ok(())
    };
    for kname in [
        "k_kvprep_dec",
        "k_attn_dec_solo",
        "k_attn_grp_dec",
        "k_attn_fixed_b_blk",
    ] {
        check_kernel(kernels_src, kname)?;
    }
    for kname in [
        "k_kvprep_b_blk",
        "k_attn_b_blk",
        "k_attn_bt_blk",
        "k_attn_h_blk",
    ] {
        check_kernel(prefill_src, kname)?;
    }
    Ok(MetalKvLayout {
        nkv,
        hd,
        kv_blk,
        kv_blk_mask,
        planes_per_pass,
        slab_shift: 62,
        slab_buffers: KV_SLAB_BUFFER_INDICES,
        kv4_nibble_bytes,
        kv4_scale_bytes,
        kv4_row_bytes,
        kv4_grp_tile_ushorts,
    })
}

#[cfg(test)]
thread_local! {
    /// `parse_metal_kv_layout` calls made by the current thread.
    static LAYOUT_PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// The KV layout of the embedded `src/kernels.metal` and `src/prefill.metal`, parsed once per process.
#[cfg(not(standalone_blocks))]
pub fn metal_kv_layout() -> &'static MetalKvLayout {
    static LAYOUT: std::sync::OnceLock<MetalKvLayout> = std::sync::OnceLock::new();
    LAYOUT.get_or_init(|| {
        parse_metal_kv_layout(include_str!("kernels.metal"), include_str!("prefill.metal"))
            .expect("src/kernels.metal and src/prefill.metal KV layout must remain valid")
    })
}

/// Evaluate the exact Metal shader within-slot byte address (`koff`/`voff + (pos & KV_BLK_MASK) * HD * sizeof(kv_t)`)
/// using a parsed [`MetalKvLayout`].
pub fn metal_in_slot_byte_offset_from_layout(
    layout: &MetalKvLayout,
    kind: BlockKind,
    kvb: u32,
    pass: u32,
    kv: Kv,
    head: u32,
    pos: u32,
) -> Result<u64, BlockError> {
    if kvb != 1 && kvb != 2 {
        return Err(BlockError::Width);
    }
    if pass >= kind.passes() as u32 || head >= layout.nkv {
        return Err(BlockError::OutOfRange);
    }
    let elem = u64::from(kvb);
    let kv_head_bytes = u64::from(layout.kv_blk) * u64::from(layout.hd) * elem;
    let kv_plane_bytes = u64::from(layout.nkv) * kv_head_bytes;
    let kv_pass_bytes = layout.planes_per_pass * kv_plane_bytes;
    let koff = u64::from(pass) * kv_pass_bytes + u64::from(head) * kv_head_bytes;
    let plane_off = if kv == Kv::Value { koff + kv_plane_bytes } else { koff };
    let ib = u64::from(pos & layout.kv_blk_mask);
    Ok(plane_off + ib * u64::from(layout.hd) * elem)
}

/// Evaluate the Metal shader within-slot byte address for [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`).
pub fn metal_in_slot_byte_offset_from_layout_mode(
    layout: &MetalKvLayout,
    kind: BlockKind,
    mode: KvMode,
    pass: u32,
    kv: Kv,
    head: u32,
    pos: u32,
) -> Result<u64, BlockError> {
    if pass >= kind.passes() as u32 || head >= layout.nkv {
        return Err(BlockError::OutOfRange);
    }
    let row_bytes = match mode {
        KvMode::Fp16 => u64::from(layout.hd) * 2,
        KvMode::Kv8 => u64::from(layout.hd),
        KvMode::Kv4 => u64::from(layout.kv4_row_bytes),
    };
    let kv_head_bytes = u64::from(layout.kv_blk) * row_bytes;
    let kv_plane_bytes = u64::from(layout.nkv) * kv_head_bytes;
    let kv_pass_bytes = layout.planes_per_pass * kv_plane_bytes;
    let koff = u64::from(pass) * kv_pass_bytes + u64::from(head) * kv_head_bytes;
    let plane_off = if kv == Kv::Value { koff + kv_plane_bytes } else { koff };
    let ib = u64::from(pos & layout.kv_blk_mask);
    Ok(plane_off + ib * row_bytes)
}

/// Evaluate the Metal shader within-slot byte address directly from `src/kernels.metal` & `src/prefill.metal`.
#[cfg(not(standalone_blocks))]
pub fn metal_in_slot_byte_offset(
    kind: BlockKind,
    kvb: u32,
    pass: u32,
    kv: Kv,
    head: u32,
    pos: u32,
) -> Result<u64, BlockError> {
    metal_in_slot_byte_offset_from_layout(metal_kv_layout(), kind, kvb, pass, kv, head, pos)
}

/// Evaluate the Metal shader within-slot byte address for [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`).
#[cfg(not(standalone_blocks))]
pub fn metal_in_slot_byte_offset_mode(
    kind: BlockKind,
    mode: KvMode,
    pass: u32,
    kv: Kv,
    head: u32,
    pos: u32,
) -> Result<u64, BlockError> {
    metal_in_slot_byte_offset_from_layout_mode(metal_kv_layout(), kind, mode, pass, kv, head, pos)
}

/// Write the InBlock trace TLC reads: small bounds (`Trace2`, `Trace1`) from `key_row_at`,
/// plus production Metal shader traces (`MetalFull2`, `MetalFull1`, `MetalWin2`, `MetalWin1`)
/// across `Full` (8 passes) and `Window` (40 passes) blocks at `kvb = 2` and `kvb = 1` (`U63`).
pub fn write_inblock_trace(path: &str) -> std::io::Result<()> {
    let mut out = String::from(
        "---------------------------- MODULE InBlockTraceData ------------------------\n\
         \\* Written by `inky inblock-trace` from key_row_at and Metal KV macros.\n\
         \\* TLC checks these addresses against SmallFormula and ProdFormula.\n\
         \\* Do not edit this file by hand.\n\
         EXTENDS Integers, Sequences\n\n",
    );
    for (name, kvb) in [("Trace2", 2u32), ("Trace1", 1u32)] {
        out.push_str(&format!("{name} == <<\n"));
        let mut first = true;
        for p in 0..2u32 {
            for k in 0..2u32 {
                for h in 0..3u32 {
                    for i in 0..4u32 {
                        let addr = key_row_at(0, 2, 3, 4, 2, kvb, p, k, h, i)
                            .expect("the spec bounds are in range");
                        if !first { out.push_str(",\n"); }
                        first = false;
                        out.push_str(&format!("  <<{p}, {k}, {h}, {i}, {addr}>>"));
                    }
                }
            }
        }
        out.push_str("\n>>\n\n");
    }
    let prod_heads = [0u32, 1, 7];
    let prod_positions = [0u32, 1, 31, 32, 63];
    for (name, kind, kvb) in [
        ("MetalFull2", BlockKind::Full, 2u32),
        ("MetalFull1", BlockKind::Full, 1u32),
        ("MetalWin2", BlockKind::Window, 2u32),
        ("MetalWin1", BlockKind::Window, 1u32),
    ] {
        out.push_str(&format!("{name} == <<\n"));
        let mut first = true;
        for p in 0..(kind.passes() as u32) {
            for (k_idx, kv_plane) in [(0u32, Kv::Key), (1u32, Kv::Value)] {
                for &h in &prod_heads {
                    for &i in &prod_positions {
                        #[cfg(not(standalone_blocks))]
                        let addr = metal_in_slot_byte_offset(kind, kvb, p, kv_plane, h, i)
                            .expect("production Metal KV bounds in range");
                        #[cfg(standalone_blocks)]
                        let addr = key_row(0, kind, kvb, p, kv_plane, h, i)
                            .expect("production KV bounds in range");
                        if !first { out.push_str(",\n"); }
                        first = false;
                        out.push_str(&format!("  <<{p}, {k_idx}, {h}, {i}, {addr}>>"));
                    }
                }
            }
        }
        out.push_str("\n>>\n\n");
    }
    out.push_str("=============================================================================\n");
    std::fs::write(path, out)
}

/// Packed `--kv4` `(nibble_byte_offset, scale_byte_offset)` inside a generalized `(passes, heads, block)`
/// layout starting at `slot_offset`: `64` packed nibble bytes (`qs[64]`) followed immediately by `2`B `fp16`
/// RMS scale (`sc`), giving `KV4_ROW_BYTES = 66` bytes per row.
#[allow(clippy::too_many_arguments)]
pub fn kv4_key_row_at(
    slot_offset: u64,
    passes: u32,
    heads: u32,
    block: u32,
    pass: u32,
    k_or_v: u32,
    head: u32,
    index: u32,
) -> Result<(u64, u64), BlockError> {
    if pass >= passes || k_or_v >= 2 || head >= heads || index >= block {
        return Err(BlockError::OutOfRange);
    }
    let plane = u64::from(pass)
        .checked_mul(2)
        .and_then(|v| v.checked_add(u64::from(k_or_v)))
        .ok_or(BlockError::Overflow)?;
    let h = plane
        .checked_mul(u64::from(heads))
        .and_then(|v| v.checked_add(u64::from(head)))
        .ok_or(BlockError::Overflow)?;
    let row_idx = h
        .checked_mul(u64::from(block))
        .and_then(|v| v.checked_add(u64::from(index)))
        .ok_or(BlockError::Overflow)?;
    let nib_off = row_idx.checked_mul(KV4_ROW_BYTES).ok_or(BlockError::Overflow)?;
    let nib_addr = slot_offset.checked_add(nib_off).ok_or(BlockError::Overflow)?;
    let sc_addr = nib_addr.checked_add((HD / 2) as u64).ok_or(BlockError::Overflow)?;
    Ok((nib_addr, sc_addr))
}

/// Production `--kv4` `(nibble_byte_offset, scale_byte_offset)` for `(slot, kind, pass, kv, head, pos)`,
/// delegating directly to [`kv4_key_row_at`].
pub fn kv4_key_row(
    slot: u32,
    kind: BlockKind,
    pass: u32,
    kv: Kv,
    head: u32,
    pos: u32,
) -> Result<(u64, u64), BlockError> {
    let stride = KvMode::Kv4.stride_bytes(kind);
    let slot_base = u64::from(slot).checked_mul(stride).ok_or(BlockError::Overflow)?;
    let k_or_v = match kv {
        Kv::Key => 0,
        Kv::Value => 1,
    };
    kv4_key_row_at(
        slot_base,
        kind.passes() as u32,
        NKV as u32,
        BLOCK as u32,
        pass,
        k_or_v,
        head,
        pos,
    )
}

/// 16-level Gaussian N(0,1) Lloyd-Max reconstruction levels used by `--kv4` (`WHT-KV4`).
pub const KV4_LM4_VAL: [f32; 16] = [
    -2.7325896, -2.0690172, -1.6180464, -1.2562312,
    -0.9423405, -0.6567591, -0.3880483, -0.128_395,
     0.128_395,  0.3880483,  0.6567591,  0.9423405,
     1.2562312,  1.6180464,  2.0690172,  2.7325896,
];

/// 15 decision thresholds mid-way between adjacent [`KV4_LM4_VAL`] centroids.
pub const KV4_LM4_THR: [f32; 15] = [
    -2.4008034, -1.8435318, -1.4371388, -1.0992858, -0.7995498,
    -0.5224037, -0.2582217,  0.0,        0.2582217,  0.5224037,
     0.7995498,  1.0992858,  1.4371388,  1.8435318,  2.4008034,
];

/// Convert a single IEEE-754 `f32` to IEEE-754 binary16 (`u16`), rounding to nearest-even
/// and clamping finite overflow to `±65504.0` (`0x7bff` / `0xfbff`).
#[inline]
pub fn f32_to_f16_bits(v: f32) -> u16 {
    if !v.is_finite() {
        return if v.is_nan() {
            0x7e00
        } else if v.is_sign_negative() {
            0xfbff
        } else {
            0x7bff
        };
    }
    let bits = v.to_bits();
    let sign = ((bits >> 16) & 0x8000) as u16;
    let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
    if v == 0.0 || exp < -10 {
        return sign;
    }
    if exp <= 0 {
        let mant = (bits & 0x007f_ffff) | 0x0080_0000;
        let shift = (14 - exp) as u32;
        let sub = mant >> shift;
        let rem = mant & ((1u32 << shift) - 1);
        let half = 1u32 << (shift - 1);
        let round = u32::from(rem > half || (rem == half && (sub & 1) == 1));
        return sign | ((sub + round) as u16);
    }
    if exp >= 31 {
        return sign | 0x7bff;
    }
    let mant = (bits >> 13) & 0x03ff;
    let rem = bits & 0x1fff;
    let round = u32::from(rem > 0x1000 || (rem == 0x1000 && (mant & 1) == 1));
    let mut h = ((exp as u32) << 10 | mant) + round;
    if h >= 0x7c00 {
        h = 0x7bff;
    }
    sign | (h as u16)
}

/// Convert an IEEE-754 binary16 (`u16`) back to `f32`.
#[inline]
pub fn f16_bits_to_f32(h: u16) -> f32 {
    let sign = ((h as u32) & 0x8000) << 16;
    let exp = ((h >> 10) & 0x1f) as u32;
    let mant = (h & 0x03ff) as u32;
    let bits = if exp == 0 {
        if mant == 0 {
            sign
        } else {
            let mut m = mant;
            let mut e = 127u32 - 14;
            while (m & 0x0400) == 0 {
                m <<= 1;
                e -= 1;
            }
            sign | (e << 23) | ((m & 0x03ff) << 13)
        }
    } else if exp == 31 {
        sign | 0x7f80_0000 | (mant << 13)
    } else {
        sign | ((exp + (127 - 15)) << 23) | (mant << 13)
    };
    f32::from_bits(bits)
}

/// Triple32 bijective Rademacher hash constants shared between Rust (`kv4_rademacher`) and Metal (`src/kernels.metal`).
pub const KV4_RAD_SEED: u32 = 0x9E37_79B9;
pub const KV4_RAD_MUL1: u32 = 0x21F0_AAAD;
pub const KV4_RAD_MUL2: u32 = 0x735A_2D97;
pub const KV4_INV_SQRT_128: f32 = 0.088_388_346;

/// Collision-free bijective Rademacher sign (`±1.0`) for `(slot2, g, d)` matching `kv4_rademacher` in Metal.
/// Maps `(slot2, g, d)` injectively onto `(slot2 * 8 + g) * 128 + d` and mixes via the Triple32 bijection.
#[inline]
pub fn kv4_rademacher(slot2: u32, g: u32, d: u32) -> f32 {
    let idx = (slot2.wrapping_mul(8).wrapping_add(g)).wrapping_mul(128).wrapping_add(d);
    let mut h = idx ^ KV4_RAD_SEED;
    h ^= h >> 16;
    h = h.wrapping_mul(KV4_RAD_MUL1);
    h ^= h >> 15;
    h = h.wrapping_mul(KV4_RAD_MUL2);
    h ^= h >> 15;
    if (h >> 31) != 0 { -1.0 } else { 1.0 }
}

/// Orthonormal 128-point Walsh-Hadamard transform (`WHT = WHT^{-1}`, scaled by `1 / sqrt(128)`) matching `wht128_tg`.
pub fn wht128_cpu(x: &[f32; HD]) -> [f32; HD] {
    let mut v = *x;
    let mut len = 1usize;
    while len < HD {
        for base in (0..HD).step_by(len * 2) {
            for j in 0..len {
                let a = v[base + j];
                let b = v[base + len + j];
                v[base + j] = a + b;
                v[base + len + j] = a - b;
            }
        }
        len *= 2;
    }
    for elem in &mut v {
        *elem *= KV4_INV_SQRT_128;
    }
    v
}

/// 4-step binary search into [`KV4_LM4_THR`] matching `kv4_lm4_idx` in `src/kernels.metal`.
#[inline]
pub fn kv4_lm4_idx_cpu(z: f32) -> u8 {
    if !z.is_finite() {
        return 8;
    }
    let mut idx = if z >= KV4_LM4_THR[7] { 8usize } else { 0usize };
    if z >= KV4_LM4_THR[idx + 3] {
        idx += 4;
    }
    if z >= KV4_LM4_THR[idx + 1] {
        idx += 2;
    }
    if z >= KV4_LM4_THR[idx] {
        idx += 1;
    }
    idx as u8
}

/// Exact SIMD-butterfly 128-element sum matching Metal `simd_sum` + left-to-right `sh[0] + sh[1] + sh[2] + sh[3]`.
#[inline]
pub fn kv4_butterfly_sum128_cpu(vals: &[f32; HD]) -> f32 {
    let mut sg_sums = [0.0f32; 4];
    for sg in 0..4 {
        let mut lane_vals = [0.0f32; 32];
        lane_vals.copy_from_slice(&vals[sg * 32..(sg + 1) * 32]);
        for xor_mask in [1usize, 2, 4, 8, 16] {
            let prev = lane_vals;
            for lane in 0..32 {
                lane_vals[lane] = prev[lane] + prev[lane ^ xor_mask];
            }
        }
        sg_sums[sg] = lane_vals[0];
    }
    ((sg_sums[0] + sg_sums[1]) + sg_sums[2]) + sg_sums[3]
}

/// CPU reference encoder for one 128-dim rotated row -> `(packed_66_bytes, dequantized_128_floats)`,
/// matching Metal `kv4_pack_row_unscaled` (`#pragma clang fp contract(off) reassociate(off)`).
pub fn kv4_pack_row_cpu(x_rot: &[f32; HD]) -> ([u8; KV4_ROW_BYTES as usize], [f32; HD]) {
    let mut out = [0u8; KV4_ROW_BYTES as usize];
    let mut deq = [0.0f32; HD];
    let mut sq_terms = [0.0f32; HD];
    for d in 0..HD {
        sq_terms[d] = x_rot[d] * x_rot[d];
    }
    let sq = kv4_butterfly_sum128_cpu(&sq_terms);
    let rms = (sq * (1.0 / 128.0)).sqrt();
    let sc_h = if rms.is_finite() && rms > 0.0 { f32_to_f16_bits(rms) } else { 0u16 };
    let sc = f16_bits_to_f32(sc_h);
    if sc.is_finite() && sc > 0.0 {
        for j in 0..64 {
            let x0 = x_rot[2 * j];
            let x1 = x_rot[2 * j + 1];
            let n0 = if x0.is_finite() { kv4_lm4_idx_cpu(x0 / sc) } else { 8 };
            let n1 = if x1.is_finite() { kv4_lm4_idx_cpu(x1 / sc) } else { 8 };
            out[j] = (n0 & 0x0f) | ((n1 & 0x0f) << 4);
            deq[2 * j] = KV4_LM4_VAL[n0 as usize] * sc;
            deq[2 * j + 1] = KV4_LM4_VAL[n1 as usize] * sc;
        }
        out[64..66].copy_from_slice(&sc_h.to_le_bytes());
    } else {
        out[..64].fill(0x88);
        out[64..66].copy_from_slice(&0u16.to_le_bytes());
    }
    (out, deq)
}

/// Parsed KV4 codec constants & pragma invariants extracted directly from `src/kernels.metal` and `src/prefill.metal`.
#[cfg(not(standalone_blocks))]
#[derive(Debug, Clone, PartialEq)]
pub struct MetalKv4CodecConstants {
    pub lm4_val: [f32; 16],
    pub lm4_thr: [f32; 15],
    pub rad_seed: u32,
    pub rad_mul1: u32,
    pub rad_mul2: u32,
    pub rad_shifts: [u32; 4],
    pub wht_scale: f32,
}

#[cfg(not(standalone_blocks))]
pub fn parse_metal_kv4_codec_constants(
    kernels_src: &str,
    prefill_src: &str,
) -> Result<MetalKv4CodecConstants, String> {
    fn extract_float_array<const N: usize>(src: &str, decl_prefix: &str) -> Result<[f32; N], String> {
        let start = src.find(decl_prefix).ok_or_else(|| format!("missing `{decl_prefix}` in kernels.metal"))?;
        let after = &src[start + decl_prefix.len()..];
        let open = after.find('{').ok_or_else(|| format!("missing `{{` for `{decl_prefix}`"))?;
        let close = after[open + 1..]
            .find("};")
            .ok_or_else(|| format!("missing `}};` for `{decl_prefix}`"))?;
        let body = &after[open + 1..open + 1 + close];
        let mut vals = Vec::with_capacity(N);
        for tok in body.split(',') {
            let t = tok.trim();
            if t.is_empty() {
                continue;
            }
            let num = t.strip_suffix('f').unwrap_or(t);
            let parsed = num
                .parse::<f32>()
                .map_err(|e| format!("invalid float `{t}` in `{decl_prefix}`: {e}"))?;
            vals.push(parsed);
        }
        if vals.len() != N {
            return Err(format!("expected {N} floats in `{decl_prefix}`, found {}", vals.len()));
        }
        vals.try_into().map_err(|_| format!("length mismatch in `{decl_prefix}`"))
    }

    fn parse_hex_u32(s: &str, ctx: &str) -> Result<u32, String> {
        let t = s.trim().trim_end_matches('u').trim_end_matches('U');
        let hex = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")).ok_or_else(|| format!("missing hex in {ctx}: `{s}`"))?;
        u32::from_str_radix(hex, 16).map_err(|e| format!("bad hex in {ctx} (`{s}`): {e}"))
    }

    let kv4_start = kernels_src.find("#ifdef KV4").ok_or("missing `#ifdef KV4` in kernels.metal")?;
    let kv4_end = kernels_src[kv4_start..]
        .find("#elif defined(KV8)")
        .map(|i| kv4_start + i)
        .ok_or("missing `#elif defined(KV8)` closing `#ifdef KV4` block in kernels.metal")?;
    let kv4_block = &kernels_src[kv4_start..kv4_end];

    // Guard against file-scope `#pragma clang fp` leaks before `attn_split` (~line 903):
    // `contract(fast)` / `reassociate(on)` must NEVER appear before `attn_split`, and inside `#ifdef KV4`
    // every `#pragma clang fp` must sit strictly inside a helper function's `{ ... }` compound block!
    let attn_split_pos = kernels_src
        .find("inline void attn_split(")
        .ok_or("missing `inline void attn_split(` in kernels.metal")?;
    let pre_attn_src = &kernels_src[..attn_split_pos];
    if pre_attn_src.contains("contract(fast)") || pre_attn_src.contains("reassociate(on)") {
        return Err(
            "file-scope `contract(fast)` or `reassociate(on)` leaked before `attn_split` in kernels.metal"
                .into(),
        );
    }
    {
        let mut brace_depth = 0usize;
        for line in kv4_block.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("#pragma clang fp") && brace_depth == 0 {
                return Err(format!(
                    "file-scope `#pragma clang fp` `{trimmed}` inside `#ifdef KV4` leaks past KV4 helpers; put it inside `{{ ... }}`"
                ));
            }
            for ch in line.chars() {
                match ch {
                    '{' => brace_depth += 1,
                    '}' => {
                        brace_depth = brace_depth
                            .checked_sub(1)
                            .ok_or("unbalanced `}` in `#ifdef KV4` block of kernels.metal")?;
                    }
                    _ => {}
                }
            }
        }
        if brace_depth != 0 {
            return Err("unclosed `{` in `#ifdef KV4` block of kernels.metal".into());
        }
    }
    for helper_sig in [
        "inline float kv4_finite_or_zero(",
        "inline uchar kv4_lm4_idx(",
        "inline float kv4_rademacher(",
        "inline float wht128_tg(",
        "inline float kv4_pack_row_unscaled(",
        "inline float kv4_pack_row(",
        "inline float4 kv4_u16_to_f4(",
    ] {
        let fpos = kv4_block
            .find(helper_sig)
            .ok_or_else(|| format!("missing `{helper_sig}` in `#ifdef KV4` of kernels.metal"))?;
        let rest = &kv4_block[fpos..];
        let open_brace = rest
            .find('{')
            .ok_or_else(|| format!("missing `{{` in `{helper_sig}`"))?;
        let body_start = &rest[open_brace + 1..];
        let close_brace = body_start
            .find('}')
            .ok_or_else(|| format!("missing `}}` in `{helper_sig}`"))?;
        let first_body_chunk = &body_start[..close_brace];
        if !first_body_chunk.contains("#pragma clang fp contract(off) reassociate(off)") {
            return Err(format!(
                "`{helper_sig}` in kernels.metal must start its `{{ ... }}` compound body with `#pragma clang fp contract(off) reassociate(off)`"
            ));
        }
    }
    let wht_pos = kv4_block.find("inline float wht128_tg(").ok_or("missing `wht128_tg` in `#ifdef KV4`")?;
    let pack_pos = kv4_block
        .find("inline float kv4_pack_row_unscaled(")
        .ok_or("missing `kv4_pack_row_unscaled` in `#ifdef KV4`")?;

    let lm4_val = extract_float_array::<16>(kv4_block, "constant float LM4_VAL[16]")?;
    let lm4_thr = extract_float_array::<15>(kv4_block, "constant float LM4_THR[15]")?;
    for (i, (&got, &exp)) in lm4_val.iter().zip(&KV4_LM4_VAL).enumerate() {
        if got.to_bits() != exp.to_bits() {
            return Err(format!("LM4_VAL[{i}] mismatch: metal={got} (0x{:08x}) vs rust={exp} (0x{:08x})", got.to_bits(), exp.to_bits()));
        }
    }
    for (i, (&got, &exp)) in lm4_thr.iter().zip(&KV4_LM4_THR).enumerate() {
        if got.to_bits() != exp.to_bits() {
            return Err(format!("LM4_THR[{i}] mismatch: metal={got} (0x{:08x}) vs rust={exp} (0x{:08x})", got.to_bits(), exp.to_bits()));
        }
    }

    let rad_fn_pos = kv4_block.find("inline float kv4_rademacher(").ok_or("missing `kv4_rademacher` in kernels.metal")?;
    let rad_after = &kv4_block[rad_fn_pos..];
    let rad_close = rad_after.find('}').ok_or("unclosed `kv4_rademacher`")?;
    let rad_body = &rad_after[..rad_close];
    if !rad_body.contains("(slot2 * 8u + g) * 128u + uint(d)") {
        return Err("kv4_rademacher missing collision-free bijective `(slot2 * 8u + g) * 128u + uint(d)` index".into());
    }
    let extract_after = |needle: &str, end_ch: char| -> Result<&str, String> {
        let p = rad_body.find(needle).ok_or_else(|| format!("missing `{needle}` in kv4_rademacher"))? + needle.len();
        let e = rad_body[p..].find(end_ch).ok_or_else(|| format!("missing `{end_ch}` after `{needle}`"))?;
        Ok(rad_body[p..p + e].trim())
    };
    let rad_seed = parse_hex_u32(extract_after("uint h = idx ^", ';')?, "rad_seed")?;
    let mut shifts = Vec::new();
    let mut muls = Vec::new();
    for stmt in rad_body.split(';') {
        let s = stmt.trim();
        if let Some(rest) = s.strip_prefix("h ^= h >>") {
            let sh = rest.trim().trim_end_matches('u').parse::<u32>().map_err(|e| format!("bad shift `{rest}`: {e}"))?;
            shifts.push(sh);
        } else if let Some(rest) = s.strip_prefix("h *=") {
            muls.push(parse_hex_u32(rest, "rad_mul")?);
        }
    }
    if muls.len() != 2 || shifts.len() != 3 {
        return Err(format!("expected 2 multiplies and 3 xorshifts in kv4_rademacher, got muls={muls:?} shifts={shifts:?}"));
    }
    let sign_shift = extract_after("return (h >>", ')')?
        .trim_end_matches('u')
        .parse::<u32>()
        .map_err(|e| format!("bad MSB sign shift in kv4_rademacher: {e}"))?;
    let rad_shifts = [shifts[0], shifts[1], shifts[2], sign_shift];
    if rad_seed != KV4_RAD_SEED || muls[0] != KV4_RAD_MUL1 || muls[1] != KV4_RAD_MUL2 || rad_shifts != [16, 15, 15, 31] {
        return Err(format!(
            "kv4_rademacher constants mismatch: seed=0x{rad_seed:08x} muls={muls:08x?} shifts={rad_shifts:?}"
        ));
    }

    let wht_body_after = &kv4_block[wht_pos..pack_pos];
    let scale_pos = wht_body_after.find("return r *").ok_or("missing `return r * <scale>;` in wht128_tg")? + "return r *".len();
    let scale_end = wht_body_after[scale_pos..].find(';').ok_or("missing `;` in wht128_tg return")?;
    let scale_str = wht_body_after[scale_pos..scale_pos + scale_end].trim().trim_end_matches('f');
    let wht_scale = scale_str.parse::<f32>().map_err(|e| format!("bad wht128_tg scale `{scale_str}`: {e}"))?;
    if wht_scale.to_bits() != KV4_INV_SQRT_128.to_bits() {
        return Err(format!("wht128_tg scale mismatch: {wht_scale} vs {KV4_INV_SQRT_128}"));
    }

    // Verify `prefill.metal` reuses `kernels.metal`'s definitions without shadowing them, and wraps both
    // `k_kvprep_b` and `k_kvprep_b_blk` in `#pragma clang fp contract(off) reassociate(off)`.
    for forbidden in ["LM4_VAL[", "LM4_THR[", "inline float kv4_rademacher("] {
        if prefill_src.contains(forbidden) {
            return Err(format!("prefill.metal must not shadow `{forbidden}` from kernels.metal"));
        }
    }
    for kernel_decl in ["kernel void k_kvprep_b(", "kernel void k_kvprep_b_blk("] {
        let kpos = prefill_src.find(kernel_decl).ok_or_else(|| format!("missing `{kernel_decl}` in prefill.metal"))?;
        let prefix = &prefill_src[kpos.saturating_sub(120)..kpos];
        if !prefix.contains("#pragma clang fp contract(off) reassociate(off)") {
            return Err(format!("`{kernel_decl}` in prefill.metal must be preceded by `#pragma clang fp contract(off) reassociate(off)`"));
        }
    }
    if prefill_src.matches("kv4_rademacher(slot * 2u, g, tid)").count() < 2
        || prefill_src.matches("kv4_pack_row(k_rot, tid, sg, lane, wht_sh,").count() < 2
    {
        return Err("prefill.metal missing expected `kv4_rademacher` / `kv4_pack_row` call sites".into());
    }

    Ok(MetalKv4CodecConstants {
        lm4_val,
        lm4_thr,
        rad_seed,
        rad_mul1: muls[0],
        rad_mul2: muls[1],
        rad_shifts,
        wht_scale,
    })
}

/// CPU reference decoder for one 66-byte `kv4_row` -> `(dequantized_128_floats, fp16_rms_scale)`.
pub fn kv4_unpack_row_cpu(row: &[u8; KV4_ROW_BYTES as usize]) -> ([f32; HD], f32) {
    let sc_bits = u16::from_le_bytes([row[64], row[65]]);
    let sc_raw = f16_bits_to_f32(sc_bits);
    let sc = if sc_raw.is_finite() { sc_raw } else { 0.0 };
    let mut deq = [0.0f32; HD];
    for j in 0..64 {
        let b = row[j];
        deq[2 * j] = KV4_LM4_VAL[(b & 0x0f) as usize] * sc;
        deq[2 * j + 1] = KV4_LM4_VAL[(b >> 4) as usize] * sc;
    }
    (deq, sc)
}

/// Byte offset inside the `96 KiB` `[48][NKV][HD]` `fp16` Key rotated DC-mean table (`K_DC_ROT`) in `PB`.
pub fn kv4_dc_mean_offset(slot_pass: u32, head: u32) -> Result<u64, BlockError> {
    const KV4_TOTAL_SLOTS: u32 = (FULL_PASSES + WINDOW_PASSES) as u32;
    if slot_pass >= KV4_TOTAL_SLOTS || head >= NKV as u32 {
        return Err(BlockError::OutOfRange);
    }
    Ok((u64::from(slot_pass) * (NKV as u64) + u64::from(head)) * ((HD * 2) as u64))
}

/// Write the `--kv4` layout trace (`specs/Kv4LayoutTraceData.tla`) checked by `Kv4LayoutTrace.tla`.
pub fn write_kv4_layout_trace(path: &str) -> std::io::Result<()> {
    let mut out = String::from(
        "-------------------------- MODULE Kv4LayoutTraceData ------------------------\n\
         \\* Written by `inky kv4-layout-trace` from KvMode::Kv4 BlockPool and Metal KV4 layout.\n\
         \\* TLC checks every (slot, pass, K|V, head, pos) nibble + fp16 scale offset and PB DC-mean offset.\n\
         \\* Do not edit this file by hand.\n\
         EXTENDS Integers, Sequences\n\n",
    );
    let slots = [0u32, 1, 2];
    let prod_heads = [0u32, 1, 7];
    let prod_positions = [0u32, 1, 31, 32, 63];

    let full_pool = BlockPool::with_mode(BlockKind::Full, 4, KvMode::Kv4).expect("full kv4 pool");
    out.push_str("Kv4FullTrace == <<\n");
    let mut first = true;
    for &s in &slots {
        let slot_base = full_pool.offset(Slot::new(s + 1).expect("1-based slot")).expect("slot in cap");
        for p in 0..(FULL_PASSES as u32) {
            for (k_idx, kv_plane) in [(0u32, Kv::Key), (1u32, Kv::Value)] {
                for &h in &prod_heads {
                    for &pos in &prod_positions {
                        #[cfg(not(standalone_blocks))]
                        let in_slot = metal_in_slot_byte_offset_mode(BlockKind::Full, KvMode::Kv4, p, kv_plane, h, pos)
                            .expect("full kv4 bounds in range");
                        #[cfg(standalone_blocks)]
                        let in_slot = kv4_key_row(0, BlockKind::Full, p, kv_plane, h, pos)
                            .expect("full kv4 bounds in range")
                            .0;
                        let nib_addr = slot_base + in_slot;
                        let sc_addr = nib_addr + 64;
                        if !first {
                            out.push_str(",\n");
                        }
                        first = false;
                        out.push_str(&format!("  <<{s}, {p}, {k_idx}, {h}, {pos}, {nib_addr}, {sc_addr}>>"));
                    }
                }
            }
        }
    }
    out.push_str("\n>>\n\n");

    let win_pool = BlockPool::with_mode(BlockKind::Window, 4, KvMode::Kv4).expect("win kv4 pool");
    let win_passes = [0u32, 1, 19, 39];
    out.push_str("Kv4WinTrace == <<\n");
    first = true;
    for &s in &slots {
        let slot_base = win_pool.offset(Slot::new(s + 1).expect("1-based slot")).expect("slot in cap");
        for &p in &win_passes {
            for (k_idx, kv_plane) in [(0u32, Kv::Key), (1u32, Kv::Value)] {
                for &h in &prod_heads {
                    for &pos in &prod_positions {
                        #[cfg(not(standalone_blocks))]
                        let in_slot =
                            metal_in_slot_byte_offset_mode(BlockKind::Window, KvMode::Kv4, p, kv_plane, h, pos)
                                .expect("window kv4 bounds in range");
                        #[cfg(standalone_blocks)]
                        let in_slot = kv4_key_row(0, BlockKind::Window, p, kv_plane, h, pos)
                            .expect("window kv4 bounds in range")
                            .0;
                        let nib_addr = slot_base + in_slot;
                        let sc_addr = nib_addr + 64;
                        if !first {
                            out.push_str(",\n");
                        }
                        first = false;
                        out.push_str(&format!("  <<{s}, {p}, {k_idx}, {h}, {pos}, {nib_addr}, {sc_addr}>>"));
                    }
                }
            }
        }
    }
    out.push_str("\n>>\n\n");

    out.push_str("Kv4DcTrace == <<\n");
    first = true;
    for sp in 0..((FULL_PASSES + WINDOW_PASSES) as u32) {
        for &h in &prod_heads {
            let dc_off = kv4_dc_mean_offset(sp, h).expect("dc mean bounds in range");
            if !first {
                out.push_str(",\n");
            }
            first = false;
            out.push_str(&format!("  <<{sp}, {h}, {dc_off}>>"));
        }
    }
    out.push_str("\n>>\n\n");
    out.push_str("=============================================================================\n");
    std::fs::write(path, out)
}

/// Bytes of one slot at element width `kvb` (`1` for `--kv8`, `2` for fp16).
/// fp16 (`kvb == 2`) equals [`BlockKind::stride`]; [`byte_offset`] scales by `stride_bytes(kvb)`.
pub fn stride_at(kind: BlockKind, kvb: u32) -> Result<u64, BlockError> {
    match kvb {
        1 | 2 => Ok(kind.stride() / 2 * u64::from(kvb)),
        _ => Err(BlockError::Kvb),
    }
}

/// How many slots fit in one slab. A stride larger than the cap is [`BlockError::Slab`].
fn slots_in_slab(stride: u64, max_slab_bytes: u64) -> Result<usize, BlockError> {
    if stride == 0 || max_slab_bytes < stride { return Err(BlockError::Slab); }
    usize::try_from(max_slab_bytes / stride).map_err(|_| BlockError::Overflow)
}

/// Flat table index for `(kind, block)` when each kind has `blocks_per_kind` rows.
/// Full is the even index, window the odd. Refuses an index past the declared rows
/// and a multiply that does not fit.
pub fn table_index(kind: BlockKind, block: BlockIndex, blocks_per_kind: u32) -> Result<u32, BlockError> {
    if block.get() >= blocks_per_kind { return Err(BlockError::OutOfRange); }
    let lane = match kind { BlockKind::Full => 0, BlockKind::Window => 1 };
    block.get().checked_mul(2).and_then(|v| v.checked_add(lane)).ok_or(BlockError::Overflow)
}

/// How many window blocks a span of `c` tokens pins. A span of 512 pins 25, not 17.
pub fn span_bound(c: usize) -> usize {
    (WINDOW - 1 + c).div_ceil(BLOCK) + 1
}

/// The next generation. `u32::MAX` is the last one; the successor is refused, never 0.
pub fn next_generation(generation: u32) -> Result<u32, BlockError> {
    generation.checked_add(1).ok_or(BlockError::Generation)
}

/// A written length, in positions. Past 64 is refused.
pub fn block_length(n: u32) -> Result<u32, BlockError> {
    if n > BLOCK as u32 { Err(BlockError::Length) } else { Ok(n) }
}

/// One pool slot, the record the prefix tree, the start points and the poisoned-slot
/// gate share. `generation` 0 is a slot that has never been taken.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct SlotRecord {
    generation: u32,
    kind: BlockKind,
    length: u32,
    sealed: bool,
    refs: u32,
}

impl SlotRecord {
    pub fn fresh(kind: BlockKind) -> SlotRecord {
        SlotRecord { generation: 0, kind, length: 0, sealed: false, refs: 0 }
    }

    #[cfg(test)]
    fn at_generation(kind: BlockKind, generation: u32) -> SlotRecord {
        SlotRecord { generation, kind, length: 0, sealed: false, refs: 0 }
    }

    pub fn generation(&self) -> u32 { self.generation }
    pub fn kind(&self) -> BlockKind { self.kind }
    pub fn length(&self) -> u32 { self.length }
    pub fn sealed(&self) -> bool { self.sealed }
    pub fn refs(&self) -> u32 { self.refs }

    /// The next generation. A live reference is `Refs`, and the count is left
    /// as it was. `reissue` is the route that waits for the last reference.
    pub fn bump_generation(&mut self) -> Result<(), BlockError> {
        if self.refs != 0 { return Err(BlockError::Refs); }
        self.generation = next_generation(self.generation)?;
        Ok(())
    }

    pub fn set_length(&mut self, n: u32) -> Result<(), BlockError> {
        self.length = block_length(n)?;
        Ok(())
    }

    pub fn seal(&mut self) { self.sealed = true; }

    fn unseal(&mut self) { self.sealed = false; }

    pub fn add_ref(&mut self) -> Result<(), BlockError> {
        self.refs = self.refs.checked_add(1).ok_or(BlockError::Overflow)?;
        Ok(())
    }

    pub fn drop_ref(&mut self) -> Result<(), BlockError> {
        self.refs = self.refs.checked_sub(1).ok_or(BlockError::Refs)?;
        Ok(())
    }

    /// Take the slot again once nothing holds it. A live reference is `Refs`.
    /// Otherwise the generation bumps, the length goes to 0, and the seal clears.
    pub fn reissue(&mut self) -> Result<(), BlockError> {
        if self.refs != 0 { return Err(BlockError::Refs); }
        self.bump_generation()?;
        self.length = 0;
        self.sealed = false;
        Ok(())
    }
}

/// One table entry. The kind is on the entry, not implied by a packed index alone.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct BlockEntry {
    slot: Slot,
    generation: u32,
    offset: u64,
    kind: BlockKind,
    kvb: u32,
}

impl BlockEntry {
    pub fn new(slot: Slot, generation: u32, offset: u64, kind: BlockKind, kvb: u32) -> BlockEntry {
        BlockEntry { slot, generation, offset, kind, kvb }
    }
    pub fn slot(&self) -> Slot { self.slot }
    pub fn generation(&self) -> u32 { self.generation }
    pub fn offset(&self) -> u64 { self.offset }
    pub fn kind(&self) -> BlockKind { self.kind }
    pub fn kvb(&self) -> u32 { self.kvb }
}

/// One slab: a contiguous allocation holding one or more slots of this kind.
/// A host slab is a `Vec`. A GPU slab is one shared Metal buffer.
#[derive(Clone)]
enum SlabStorage {
    Host(Vec<u8>),
    #[cfg(not(standalone_blocks))]
    Gpu(crate::metal::Buf),
}

/// One kind's pool. Slots are append-only: `grow` adds a slot at the end and does not
/// move an existing offset. The bytes live in one slab until a new slot would pass
/// `maxBufferLength` (or the host cap). At most [`MAX_SLABS`].
pub struct BlockPool {
    kind: BlockKind,
    /// Element width for every slot in this pool. 2 is fp16, 1 is `--kv8`.
    kvb: u32,
    stride: u64,
    slots_per_slab: usize,
    slots: Vec<SlotRecord>,
    gpu_zero_pending: Vec<bool>,
    slabs: Vec<SlabStorage>,
    /// True iff `--sparse-topk` `WHT-2bit` page sketches are enabled on this `BlockKind::Full` pool (`false` by default = 0 sketch bytes).
    with_sketches: bool,
    /// Compact `WHT-2bit` page sketch sidecar (`17,408` bytes per `BlockKind::Full` slot when `with_sketches`; `None` otherwise).
    sketch_slab: Option<SlabStorage>,
    /// Number of contiguous valid positions (`0..=64`) reflected in each `Full` slot's sketch (`0` = dirty/unbuilt; empty when `!with_sketches`).
    sketch_valid_len: Vec<u8>,
    /// Monotone per-slot epoch bumped whenever `mark_slot_sketch_dirty` / `take` / `take_unzeroed` invalidates `sketch_valid_len`.
    sketch_epoch: Vec<u64>,
    /// Present when this pool allocates Metal buffers.
    #[cfg(not(standalone_blocks))]
    device: Option<Retained<ProtocolObject<dyn MTLDevice>>>,
}

impl Clone for BlockPool {
    fn clone(&self) -> BlockPool {
        BlockPool {
            kind: self.kind,
            kvb: self.kvb,
            stride: self.stride,
            slots_per_slab: self.slots_per_slab,
            slots: self.slots.clone(),
            gpu_zero_pending: self.gpu_zero_pending.clone(),
            // A cloned GPU buffer is another retain of the same allocation.
            slabs: self.slabs.clone(),
            with_sketches: self.with_sketches,
            sketch_slab: self.sketch_slab.clone(),
            sketch_valid_len: self.sketch_valid_len.clone(),
            sketch_epoch: self.sketch_epoch.clone(),
            #[cfg(not(standalone_blocks))]
            device: self.device.clone(),
        }
    }
}

impl fmt::Debug for BlockPool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(not(standalone_blocks))]
        let is_gpu = self.device.is_some();
        #[cfg(standalone_blocks)]
        let is_gpu = false;
        f.debug_struct("BlockPool")
            .field("kind", &self.kind)
            .field("kvb", &self.kvb)
            .field("len", &self.slots.len())
            .field("slabs", &self.slabs.len())
            .field("gpu", &is_gpu)
            .finish()
    }
}

/// Sentinel GPU 64-bit block-table entry written for unmapped/cleared table slots.
/// Distinct from every valid `(slab_index << 62) | byte_offset` word, including `(slab = 0, Slot(1))`
/// which encodes as `0`, because every valid `byte_offset` is stride-aligned (`>= 1 MiB`) and `< (1 << 62)`.
pub const CLEARED_GPU_TABLE_ENTRY: u64 = u64::MAX;

impl BlockPool {
    /// Host bytes at fp16 (`kvb` 2), one contiguous slab, zero-filled, no sketch sidecar (`0` sketch bytes).
    pub fn new(kind: BlockKind, n_slots: usize) -> BlockPool {
        Self::open_host_opts(kind, n_slots, KVB_FP16, u64::MAX, false).expect("host block pool")
    }

    /// Host bytes at `kvb` with `WHT-2bit` sketch sidecar enabled (when `kind == BlockKind::Full`).
    pub fn new_with_sketches(kind: BlockKind, n_slots: usize, kvb: u32) -> Result<BlockPool, BlockError> {
        let _ = kind.stride_bytes(kvb)?;
        Self::open_host_opts(kind, n_slots, kvb, u64::MAX, kind == BlockKind::Full)
    }

    /// One element width for the whole pool (host storage, `0` sketch bytes by default).
    pub fn with_kvb(kind: BlockKind, n_slots: usize, kvb: u32) -> Result<BlockPool, BlockError> {
        let _ = kind.stride_bytes(kvb)?;
        Self::open_host_opts(kind, n_slots, kvb, u64::MAX, false)
    }

    /// Host storage at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`, `0` sketch bytes by default).
    pub fn with_mode(kind: BlockKind, n_slots: usize, mode: KvMode) -> Result<BlockPool, BlockError> {
        Self::open_host_mode_opts(kind, n_slots, mode, u64::MAX, false)
    }

    /// Host storage at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`) with optional `Full` sketches.
    pub fn with_mode_and_sketches(
        kind: BlockKind,
        n_slots: usize,
        mode: KvMode,
        enable_sketches: bool,
    ) -> Result<BlockPool, BlockError> {
        Self::open_host_mode_opts(kind, n_slots, mode, u64::MAX, enable_sketches && kind == BlockKind::Full)
    }

    /// Metadata-only pool for high-slot offset/table tests without multi-GiB host allocation.
    #[cfg(test)]
    pub(crate) fn records_only(kind: BlockKind, n_slots: usize, kvb: u32) -> Result<BlockPool, BlockError> {
        let stride = kind.stride_bytes(kvb)?;
        let slots_per_slab = slots_in_slab(stride, u64::MAX)?;
        Ok(BlockPool {
            kind, kvb, stride, slots_per_slab,
            slots: vec![SlotRecord::fresh(kind); n_slots],
            gpu_zero_pending: vec![false; n_slots],
            slabs: Vec::new(),
            with_sketches: false,
            sketch_slab: None,
            sketch_valid_len: Vec::new(),
            sketch_epoch: Vec::new(),
            #[cfg(not(standalone_blocks))]
            device: None,
        })
    }

    /// GPU pools for this kind (`0` sketch bytes by default).
    #[cfg(not(standalone_blocks))]
    pub fn gpu(dev: &ProtocolObject<dyn MTLDevice>, kind: BlockKind, n_slots: usize, kvb: u32) -> BlockPool {
        Self::gpu_with_sketches(dev, kind, n_slots, kvb, false)
    }

    /// GPU pool for this kind at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`, `0` sketch bytes by default).
    #[cfg(not(standalone_blocks))]
    pub fn gpu_mode(dev: &ProtocolObject<dyn MTLDevice>, kind: BlockKind, n_slots: usize, mode: KvMode) -> BlockPool {
        Self::gpu_mode_with_sketches(dev, kind, n_slots, mode, false)
    }

    /// GPU pool for this kind at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`) with optional `Full` sketches.
    #[cfg(not(standalone_blocks))]
    pub fn gpu_mode_with_sketches(
        dev: &ProtocolObject<dyn MTLDevice>,
        kind: BlockKind,
        n_slots: usize,
        mode: KvMode,
        enable_sketches: bool,
    ) -> BlockPool {
        let max = dev.maxBufferLength() as u64;
        Self::open_with_stride(
            kind,
            n_slots,
            mode.kvb_tag(),
            mode.stride_bytes(kind),
            max,
            enable_sketches && kind == BlockKind::Full,
            Some(dev.retain()),
        )
        .expect("gpu block pool")
    }

    /// GPU pools for this kind with optional `WHT-2bit` sketch sidecar (`enable_sketches && kind == BlockKind::Full`).
    #[cfg(not(standalone_blocks))]
    pub fn gpu_with_sketches(
        dev: &ProtocolObject<dyn MTLDevice>,
        kind: BlockKind,
        n_slots: usize,
        kvb: u32,
        enable_sketches: bool,
    ) -> BlockPool {
        let max = dev.maxBufferLength() as u64;
        Self::open_opts(kind, n_slots, kvb, max, enable_sketches && kind == BlockKind::Full, Some(dev.retain()))
            .expect("gpu block pool")
    }

    fn open_host_mode_opts(
        kind: BlockKind,
        n_slots: usize,
        mode: KvMode,
        max_slab_bytes: u64,
        with_sketches: bool,
    ) -> Result<BlockPool, BlockError> {
        let eff_sk = with_sketches && kind == BlockKind::Full;
        let kvb = mode.kvb_tag();
        let stride = mode.stride_bytes(kind);
        #[cfg(not(standalone_blocks))]
        { Self::open_with_stride(kind, n_slots, kvb, stride, max_slab_bytes, eff_sk, None) }
        #[cfg(standalone_blocks)]
        {
            let slots_per_slab = slots_in_slab(stride, max_slab_bytes)?;
            let mut pool = BlockPool {
                kind,
                kvb,
                stride,
                slots_per_slab,
                slots: Vec::with_capacity(n_slots),
                gpu_zero_pending: Vec::with_capacity(n_slots),
                slabs: Vec::new(),
                with_sketches: eff_sk,
                sketch_slab: None,
                sketch_valid_len: Vec::with_capacity(if eff_sk { n_slots } else { 0 }),
                sketch_epoch: Vec::with_capacity(if eff_sk { n_slots } else { 0 }),
            };
            if n_slots > 0 { pool.grow_by(n_slots)?; }
            Ok(pool)
        }
    }

    /// An empty host pool of `mode` whose slabs hold `slots_per_slab` slots each, so it grows to exactly
    /// `MAX_SLABS * slots_per_slab` slots and then refuses with `BlockError::Slab`.
    #[cfg(test)]
    pub(crate) fn host_capped(kind: BlockKind, mode: KvMode, slots_per_slab: usize) -> BlockPool {
        let max_slab_bytes = mode.stride_bytes(kind) * slots_per_slab as u64;
        Self::open_host_mode_opts(kind, 0, mode, max_slab_bytes, false).expect("capped host pool")
    }

    #[cfg(test)]
    fn open_host(kind: BlockKind, n_slots: usize, kvb: u32, max_slab_bytes: u64) -> Result<BlockPool, BlockError> {
        Self::open_host_opts(kind, n_slots, kvb, max_slab_bytes, false)
    }

    fn open_host_opts(
        kind: BlockKind,
        n_slots: usize,
        kvb: u32,
        max_slab_bytes: u64,
        with_sketches: bool,
    ) -> Result<BlockPool, BlockError> {
        let eff_sk = with_sketches && kind == BlockKind::Full;
        #[cfg(not(standalone_blocks))]
        { Self::open_opts(kind, n_slots, kvb, max_slab_bytes, eff_sk, None) }
        #[cfg(standalone_blocks)]
        {
            let stride = stride_at(kind, kvb)?;
            let slots_per_slab = slots_in_slab(stride, max_slab_bytes)?;
            let mut pool = BlockPool {
                kind,
                kvb,
                stride,
                slots_per_slab,
                slots: Vec::with_capacity(n_slots),
                gpu_zero_pending: Vec::with_capacity(n_slots),
                slabs: Vec::new(),
                with_sketches: eff_sk,
                sketch_slab: None,
                sketch_valid_len: Vec::with_capacity(if eff_sk { n_slots } else { 0 }),
                sketch_epoch: Vec::with_capacity(if eff_sk { n_slots } else { 0 }),
            };
            if n_slots > 0 { pool.grow_by(n_slots)?; }
            Ok(pool)
        }
    }

    #[cfg(test)]
    #[cfg(not(standalone_blocks))]
    fn open(
        kind: BlockKind,
        n_slots: usize,
        kvb: u32,
        max_slab_bytes: u64,
        device: Option<Retained<ProtocolObject<dyn MTLDevice>>>,
    ) -> Result<BlockPool, BlockError> {
        Self::open_opts(kind, n_slots, kvb, max_slab_bytes, false, device)
    }

    #[cfg(not(standalone_blocks))]
    fn open_opts(
        kind: BlockKind,
        n_slots: usize,
        kvb: u32,
        max_slab_bytes: u64,
        with_sketches: bool,
        device: Option<Retained<ProtocolObject<dyn MTLDevice>>>,
    ) -> Result<BlockPool, BlockError> {
        let eff_sk = with_sketches && kind == BlockKind::Full;
        let stride = stride_at(kind, kvb)?;
        Self::open_with_stride(kind, n_slots, kvb, stride, max_slab_bytes, eff_sk, device)
    }

    #[cfg(not(standalone_blocks))]
    fn open_with_stride(
        kind: BlockKind,
        n_slots: usize,
        kvb: u32,
        stride: u64,
        max_slab_bytes: u64,
        with_sketches: bool,
        device: Option<Retained<ProtocolObject<dyn MTLDevice>>>,
    ) -> Result<BlockPool, BlockError> {
        let eff_sk = with_sketches && kind == BlockKind::Full;
        let slots_per_slab = slots_in_slab(stride, max_slab_bytes)?;
        let mut pool = BlockPool {
            kind,
            kvb,
            stride,
            slots_per_slab,
            slots: Vec::with_capacity(n_slots),
            gpu_zero_pending: Vec::with_capacity(n_slots),
            slabs: Vec::new(),
            with_sketches: eff_sk,
            sketch_slab: None,
            sketch_valid_len: Vec::with_capacity(if eff_sk { n_slots } else { 0 }),
            sketch_epoch: Vec::with_capacity(if eff_sk { n_slots } else { 0 }),
            device,
        };
        if n_slots > 0 { pool.grow_by(n_slots)?; }
        Ok(pool)
    }

    /// True iff this pool has `WHT-2bit` page sketches enabled (`--sparse-topk`).
    pub fn has_sketches(&self) -> bool {
        self.with_sketches
    }

    /// Enable and allocate the `17,408 B/slot` `WHT-2bit` sketch sidecar on a `BlockKind::Full` pool
    /// (idempotent if already enabled; no-op on `BlockKind::Window`).
    pub fn enable_sketches(&mut self) -> Result<(), BlockError> {
        if self.kind != BlockKind::Full || self.with_sketches {
            return Ok(());
        }
        self.with_sketches = true;
        let n = self.slots.len();
        if n > 0 {
            self.ensure_sketch_slots(n)?;
            self.sketch_valid_len.resize(n, 0);
            self.sketch_epoch.resize(n, 0);
        }
        Ok(())
    }

    fn ensure_sketch_slots(&mut self, total_slots: usize) -> Result<(), BlockError> {
        if !self.with_sketches || self.kind != BlockKind::Full || total_slots == 0 {
            return Ok(());
        }
        let need = (total_slots as u64)
            .checked_mul(FULL_SKETCH_BYTES as u64)
            .ok_or(BlockError::Overflow)?;
        let n = usize::try_from(need).map_err(|_| BlockError::Overflow)?;
        if self.sketch_slab.is_none() {
            self.sketch_slab = Some(self.allocate_slab(need)?);
            return Ok(());
        }
        let Some(slab) = &mut self.sketch_slab else { return Ok(()) };
        #[allow(irrefutable_let_patterns)]
        if let SlabStorage::Host(v) = slab {
            if v.len() < n {
                v.resize(n, 0);
            }
            return Ok(());
        }
        #[cfg(not(standalone_blocks))]
        {
            let old_len = match slab {
                SlabStorage::Gpu(b) => b.length(),
                SlabStorage::Host(_) => return Ok(()),
            };
            if old_len >= n {
                return Ok(());
            }
            let dev = self.device.as_ref().expect("gpu sketch slab without a device");
            let new_buf = dev
                .newBufferWithLength_options(n, MTLResourceOptions::StorageModeShared)
                .expect("full block sketch buffer");
            if let SlabStorage::Gpu(old) = slab {
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        old.contents().as_ptr() as *const u8,
                        new_buf.contents().as_ptr() as *mut u8,
                        old_len,
                    );
                }
            }
            *slab = SlabStorage::Gpu(new_buf);
        }
        Ok(())
    }

    fn allocate_slab(&self, nbytes: u64) -> Result<SlabStorage, BlockError> {
        let n = usize::try_from(nbytes).map_err(|_| BlockError::Overflow)?;
        #[cfg(not(standalone_blocks))]
        if let Some(dev) = &self.device {
            // Metal anonymous shared buffers arrive page-zeroed from the OS kernel; avoid
            // synchronously faulting and memset-ing multi-GiB slabs on the host thread.
            let buf = dev.newBufferWithLength_options(n, MTLResourceOptions::StorageModeShared).expect("block pool buffer");
            return Ok(SlabStorage::Gpu(buf));
        }
        Ok(SlabStorage::Host(vec![0u8; n]))
    }

    /// Grow the slab that owns `index`, or open the next one. Does not move a slot already placed.
    fn ensure_slot(&mut self, index: usize) -> Result<(), BlockError> {
        let slab_i = index / self.slots_per_slab;
        if slab_i >= MAX_SLABS { return Err(BlockError::Slab); }
        let within = index % self.slots_per_slab;
        let count = (within as u64).checked_add(1).ok_or(BlockError::Overflow)?;
        let need = count.checked_mul(self.stride).ok_or(BlockError::Overflow)?;
        if slab_i == self.slabs.len() {
            self.slabs.push(self.allocate_slab(need)?);
            return Ok(());
        }
        if slab_i + 1 != self.slabs.len() { return Err(BlockError::Slab); }
        self.resize_slab(slab_i, need)
    }

    fn resize_slab(&mut self, slab_i: usize, nbytes: u64) -> Result<(), BlockError> {
        let n = usize::try_from(nbytes).map_err(|_| BlockError::Overflow)?;
        #[allow(irrefutable_let_patterns)]
        if let SlabStorage::Host(v) = &mut self.slabs[slab_i] {
            if v.len() < n { v.resize(n, 0); }
            return Ok(());
        }
        #[cfg(not(standalone_blocks))]
        {
            let old_len = match &self.slabs[slab_i] {
                SlabStorage::Gpu(b) => b.length(),
                SlabStorage::Host(_) => return Ok(()),
            };
            if old_len >= n { return Ok(()); }
            let dev = self.device.as_ref().expect("gpu slab without a device");
            let new_buf = dev.newBufferWithLength_options(n, MTLResourceOptions::StorageModeShared).expect("block pool buffer");
            if let SlabStorage::Gpu(old) = &self.slabs[slab_i] {
                unsafe {
                    std::ptr::copy_nonoverlapping(old.contents().as_ptr() as *const u8, new_buf.contents().as_ptr() as *mut u8, old_len);
                }
            }
            self.slabs[slab_i] = SlabStorage::Gpu(new_buf);
        }
        Ok(())
    }

    pub fn kind(&self) -> BlockKind { self.kind }
    pub fn kvb(&self) -> u32 { self.kvb }
    pub fn mode(&self) -> Result<KvMode, BlockError> { KvMode::from_kvb_tag(self.kvb) }
    pub fn stride_bytes(&self) -> u64 { self.stride }
    pub fn slots_per_slab(&self) -> usize { self.slots_per_slab }
    pub fn len(&self) -> usize { self.slots.len() }
    pub fn slab_count(&self) -> usize { self.slabs.len() }

    /// Fast `(usable_slots, reclaimable_slots)` scan over `self.slots` without per-slot
    /// `Slot::new` / `Result` wrapper overhead on large pools.
    pub fn count_usable_and_avail(&self, start_slot_refs: &[u32]) -> (usize, usize) {
        let mut usable = 0usize;
        let mut avail = 0usize;
        for (i, rec) in self.slots.iter().enumerate() {
            if rec.generation < u32::MAX {
                usable += 1;
                let held_by_starts = start_slot_refs.get(i).copied().unwrap_or(0);
                if rec.refs <= held_by_starts {
                    avail += 1;
                }
            }
        }
        (usable, avail)
    }

    pub fn has_gpu_storage(&self) -> bool {
        #[cfg(not(standalone_blocks))]
        {
            self.device.is_some()
        }
        #[cfg(standalone_blocks)]
        {
            false
        }
    }

    fn index(&self, slot: Slot) -> Result<usize, BlockError> {
        let i = slot.pool_index().get() as usize;
        if i >= self.slots.len() { Err(BlockError::OutOfRange) } else { Ok(i) }
    }

    /// Which slab holds `slot`. Slots in one slab share one allocation.
    pub fn slab_index(&self, slot: Slot) -> Result<usize, BlockError> {
        Ok(self.index(slot)? / self.slots_per_slab)
    }

    pub fn record(&self, slot: Slot) -> Result<&SlotRecord, BlockError> {
        Ok(&self.slots[self.index(slot)?])
    }

    pub fn record_mut(&mut self, slot: Slot) -> Result<&mut SlotRecord, BlockError> {
        let i = self.index(slot)?;
        Ok(&mut self.slots[i])
    }

    pub fn offset(&self, slot: Slot) -> Result<u64, BlockError> {
        let _ = self.record(slot)?;
        mul_offset(u64::from(slot.pool_index().get()), self.stride)
    }

    /// The slab buffer that holds this slot. `None` on a host pool.
    /// Two slots in one slab return the same buffer. Its length is the bytes placed
    /// in that slab, not the stride of one slot.
    #[cfg(not(standalone_blocks))]
    pub fn gpu_buffer(&self, slot: Slot) -> Result<Option<&crate::metal::Buf>, BlockError> {
        let i = self.index(slot)?;
        let slab = i / self.slots_per_slab;
        Ok(match &self.slabs[slab] { SlabStorage::Gpu(b) => Some(b), SlabStorage::Host(_) => None })
    }

    /// Every allocated GPU slab buffer in slab order (0..slab_count).
    #[cfg(not(standalone_blocks))]
    pub fn gpu_slabs(&self) -> Vec<&crate::metal::Buf> {
        self.slabs.iter().filter_map(|s| match s { SlabStorage::Gpu(b) => Some(b), SlabStorage::Host(_) => None }).collect()
    }

    /// 64-bit GPU block-table word for `entry`: `(slab_index << 62) | within_slab_byte_offset`.
    /// Validates kind, width, generation, and live reference count before returning.
    /// For single-slab pools (`slab_index == 0`), this equals `entry.offset()`.
    pub fn gpu_table_entry(&self, entry: BlockEntry) -> Result<u64, BlockError> {
        if entry.kind() != self.kind { return Err(BlockError::OutOfRange); }
        if entry.kvb() != self.kvb { return Err(BlockError::Width); }
        let i = self.index(entry.slot())?;
        let rec = &self.slots[i];
        if rec.generation() != entry.generation() { return Err(BlockError::Stale); }
        if rec.refs() == 0 { return Err(BlockError::Refs); }
        let slab = i / self.slots_per_slab;
        if slab >= MAX_SLABS { return Err(BlockError::Slab); }
        let within = (i % self.slots_per_slab) as u64;
        let off = within.checked_mul(self.stride).ok_or(BlockError::Overflow)?;
        if off >= (1u64 << KV_SLAB_SHIFT) { return Err(BlockError::Overflow); }
        let word = ((slab as u64) << KV_SLAB_SHIFT) | off;
        assert_ne!(word, CLEARED_GPU_TABLE_ENTRY, "valid GPU block-table word collided with CLEARED_GPU_TABLE_ENTRY");
        Ok(word)
    }

    /// Owning GPU slab buffer, byte offset within that slab, and byte stride for `slot`.
    #[cfg(not(standalone_blocks))]
    pub fn gpu_slot_region(&self, slot: Slot) -> Result<Option<(&crate::metal::Buf, usize, usize)>, BlockError> {
        let i = self.index(slot)?;
        let (slab, start, n) = self.slot_range(i);
        Ok(match self.slabs.get(slab) {
            Some(SlabStorage::Gpu(b)) => Some((b, start, n)),
            _ => None,
        })
    }

    /// Raw CPU-visible pointer and byte length of `slot` inside its owning slab.
    /// Valid while nothing is in flight on the GPU and before the slab is resized.
    pub fn slot_raw_region(&self, slot: Slot) -> Option<(*mut u8, usize)> {
        let i = self.index(slot).ok()?;
        let (slab, start, n) = self.slot_range(i);
        match self.slabs.get(slab)? {
            SlabStorage::Host(v) => Some((unsafe { (v.as_ptr() as *mut u8).add(start) }, n)),
            #[cfg(not(standalone_blocks))]
            SlabStorage::Gpu(b) => Some((unsafe { (b.contents().as_ptr() as *mut u8).add(start) }, n)),
        }
    }

    /// The slot's bytes: one stride inside the owning slab.
    pub fn slot_bytes(&self, slot: Slot) -> Result<&[u8], BlockError> {
        let i = self.index(slot)?;
        Ok(self.bytes_of(i))
    }

    /// Mutable view of one slot's bytes (for CPU zeroing/poisoning when idle on GPU).
    pub fn slot_bytes_mut(&mut self, slot: Slot) -> Result<&mut [u8], BlockError> {
        let i = self.index(slot)?;
        Ok(self.bytes_of_mut(i))
    }

    fn slot_range(&self, i: usize) -> (usize, usize, usize) {
        let slab = i / self.slots_per_slab;
        let start = (i % self.slots_per_slab) * (self.stride as usize);
        (slab, start, self.stride as usize)
    }

    fn bytes_of(&self, i: usize) -> &[u8] {
        let (slab, start, n) = self.slot_range(i);
        match &self.slabs[slab] {
            SlabStorage::Host(v) => &v[start..start + n],
            #[cfg(not(standalone_blocks))]
            SlabStorage::Gpu(b) => unsafe {
                std::slice::from_raw_parts((b.contents().as_ptr() as *const u8).add(start), n)
            },
        }
    }

    fn bytes_of_mut(&mut self, i: usize) -> &mut [u8] {
        let (slab, start, n) = self.slot_range(i);
        match &mut self.slabs[slab] {
            SlabStorage::Host(v) => &mut v[start..start + n],
            // Shared storage. The CPU zero-fills and appends; no command buffer reads this yet.
            #[cfg(not(standalone_blocks))]
            SlabStorage::Gpu(b) => unsafe {
                std::slice::from_raw_parts_mut((b.contents().as_ptr() as *mut u8).add(start), n)
            },
        }
    }

    fn sketch_bytes_of(&self, i: usize) -> Option<&[u8]> {
        let slab = self.sketch_slab.as_ref()?;
        let start = sparse_sketch_byte_offset(u32::try_from(i).ok()?, 0, 0).ok()?;
        match slab {
            SlabStorage::Host(v) => v.get(start..start + FULL_SKETCH_BYTES),
            #[cfg(not(standalone_blocks))]
            SlabStorage::Gpu(b) => {
                if start + FULL_SKETCH_BYTES > b.length() {
                    return None;
                }
                Some(unsafe {
                    std::slice::from_raw_parts((b.contents().as_ptr() as *const u8).add(start), FULL_SKETCH_BYTES)
                })
            }
        }
    }

    fn sketch_bytes_of_mut(&mut self, i: usize) -> Option<&mut [u8]> {
        let slab = self.sketch_slab.as_mut()?;
        let start = sparse_sketch_byte_offset(u32::try_from(i).ok()?, 0, 0).ok()?;
        match slab {
            SlabStorage::Host(v) => v.get_mut(start..start + FULL_SKETCH_BYTES),
            #[cfg(not(standalone_blocks))]
            SlabStorage::Gpu(b) => {
                if start + FULL_SKETCH_BYTES > b.length() {
                    return None;
                }
                Some(unsafe {
                    std::slice::from_raw_parts_mut((b.contents().as_ptr() as *mut u8).add(start), FULL_SKETCH_BYTES)
                })
            }
        }
    }

    /// Underlying GPU `WHT-2bit` sketch buffer for `BlockKind::Full` (`None` on `Window` or host pools).
    #[cfg(not(standalone_blocks))]
    pub fn gpu_sketch_buffer(&self) -> Option<&crate::metal::Buf> {
        match self.sketch_slab.as_ref()? {
            SlabStorage::Gpu(b) => Some(b),
            SlabStorage::Host(_) => None,
        }
    }

    /// Read-only view of one `BlockKind::Full` slot's `17,408`-byte `WHT-2bit` sketch sidecar.
    pub fn slot_sketch_bytes(&self, slot: Slot) -> Result<&[u8], BlockError> {
        let i = self.index(slot)?;
        self.sketch_bytes_of(i).ok_or(BlockError::OutOfRange)
    }

    /// Mutable view of one `BlockKind::Full` slot's `17,408`-byte `WHT-2bit` sketch sidecar.
    pub fn slot_sketch_bytes_mut(&mut self, slot: Slot) -> Result<&mut [u8], BlockError> {
        let i = self.index(slot)?;
        self.sketch_bytes_of_mut(i).ok_or(BlockError::OutOfRange)
    }

    /// Number of valid positions (`0..=64`) currently reflected in `slot`'s `WHT-2bit` sketch (`0` = dirty).
    pub fn slot_sketch_valid_len(&self, slot: Slot) -> Result<u8, BlockError> {
        let i = self.index(slot)?;
        Ok(self.sketch_valid_len.get(i).copied().unwrap_or(0))
    }

    /// Monotone per-slot sketch epoch (`0` initially; bumped whenever `mark_slot_sketch_dirty` / `take` / `take_unzeroed` invalidates `valid_len`).
    pub fn slot_sketch_epoch(&self, slot: Slot) -> Result<u64, BlockError> {
        let i = self.index(slot)?;
        Ok(self.sketch_epoch.get(i).copied().unwrap_or(0))
    }

    /// Record that `slot`'s `WHT-2bit` sketch now reflects `valid_len` positions (`0..=64`).
    pub fn set_slot_sketch_valid_len(&mut self, slot: Slot, valid_len: u8) -> Result<(), BlockError> {
        let _ = block_length(u32::from(valid_len))?;
        let i = self.index(slot)?;
        if i < self.sketch_valid_len.len() {
            self.sketch_valid_len[i] = valid_len;
        }
        Ok(())
    }

    /// Mark `slot`'s `WHT-2bit` sketch dirty so the next sparse step rebuilds it before scoring,
    /// bumping `sketch_epoch` so earlier in-flight GPU batches cannot overwrite `valid_len = 0`.
    pub fn mark_slot_sketch_dirty(&mut self, slot: Slot) {
        if let Ok(i) = self.index(slot) {
            if i < self.sketch_valid_len.len() {
                self.sketch_valid_len[i] = 0;
            }
            if i < self.sketch_epoch.len() {
                self.sketch_epoch[i] = self.sketch_epoch[i].wrapping_add(1);
            }
        }
    }

    /// Recompute `slot`'s `WHT-2bit` sketch on the CPU from its stored KV bytes and current `record().length()`.
    pub fn recompute_slot_sketch_cpu(&mut self, slot: Slot) -> Result<(), BlockError> {
        if self.kind != BlockKind::Full {
            return Err(BlockError::OutOfRange);
        }
        let i = self.index(slot)?;
        let valid_len = self.slots[i].length() as usize;
        let kvb = self.kvb;
        let mut tmp = vec![0u8; FULL_SKETCH_BYTES];
        compute_full_slot_wht2_sketch_cpu(self.bytes_of(i), kvb, valid_len, &mut tmp);
        let dst = self.sketch_bytes_of_mut(i).ok_or(BlockError::OutOfRange)?;
        dst.copy_from_slice(&tmp);
        if i < self.sketch_valid_len.len() {
            self.sketch_valid_len[i] = valid_len as u8;
        }
        Ok(())
    }

    /// Maintain sketch validity when a full slot's KV bytes are restored from SSD (`SpillStore`):
    /// GPU pools defer to the `< 3 µs` `k_build_full_sketch_slots` kernel; host pools compute immediately on CPU.
    pub fn on_slot_restored_from_spill(&mut self, slot: Slot) {
        if !self.with_sketches || self.kind != BlockKind::Full {
            return;
        }
        if self.has_gpu_storage() {
            self.mark_slot_sketch_dirty(slot);
        } else {
            let _ = self.recompute_slot_sketch_cpu(slot);
        }
    }

    /// Copy KV payload bytes (and `WHT-2bit` sketch bytes + valid length when enabled) from `src` into
    /// a freshly taken distinct `dst` slot while nothing is in flight on the GPU.
    #[cfg(not(standalone_blocks))]
    pub fn clone_slot_from(&mut self, src: Slot, dst: Slot) -> Result<(), BlockError> {
        let src_i = self.index(src)?;
        let dst_i = self.index(dst)?;
        if src_i == dst_i {
            return Ok(());
        }
        let (sp, slen) = self.slot_raw_region(src).ok_or(BlockError::OutOfRange)?;
        let (dp, dlen) = self.slot_raw_region(dst).ok_or(BlockError::OutOfRange)?;
        assert_eq!(slen, dlen);
        unsafe {
            std::ptr::copy_nonoverlapping(sp as *const u8, dp, slen);
        }
        if dst_i < self.gpu_zero_pending.len() {
            self.gpu_zero_pending[dst_i] = false;
        }
        if self.with_sketches && self.kind == BlockKind::Full {
            let tmp_sk = self.sketch_bytes_of(src_i).ok_or(BlockError::OutOfRange)?.to_vec();
            let valid = self.sketch_valid_len.get(src_i).copied().unwrap_or(0);
            self.sketch_bytes_of_mut(dst_i).ok_or(BlockError::OutOfRange)?.copy_from_slice(&tmp_sk);
            if dst_i < self.sketch_valid_len.len() {
                self.sketch_valid_len[dst_i] = valid;
            }
        }
        let len = self.slots[src_i].length();
        let was_sealed = self.slots[src_i].sealed;
        self.slots[dst_i].set_length(len)?;
        if was_sealed {
            self.slots[dst_i].seal();
        } else {
            self.slots[dst_i].unseal();
        }
        Ok(())
    }

    /// Append one slot. Its offset is `len * stride`. Earlier offsets stay put.
    /// The new slot has generation 0 until `take`. A fifth slab is [`BlockError::Slab`].
    pub fn grow(&mut self) -> Result<Slot, BlockError> {
        if self.slots.len() >= u32::MAX as usize { return Err(BlockError::Overflow); }
        let slot = Slot::new((self.slots.len() as u32).checked_add(1).ok_or(BlockError::Overflow)?)?;
        let _ = mul_offset(u64::from(slot.pool_index().get()), self.stride)?;
        self.ensure_slot(slot.pool_index().get() as usize)?;
        self.ensure_sketch_slots(self.slots.len() + 1)?;
        self.slots.push(SlotRecord::fresh(self.kind));
        self.gpu_zero_pending.push(false);
        if self.with_sketches && self.kind == BlockKind::Full {
            self.sketch_valid_len.push(0);
            self.sketch_epoch.push(0);
        }
        Ok(slot)
    }

    /// Append `count` fresh slots in one resize per touched slab, avoiding repeated copies.
    pub fn grow_by(&mut self, count: usize) -> Result<(), BlockError> {
        if count == 0 { return Ok(()); }
        let start = self.slots.len();
        let end = start.checked_add(count).ok_or(BlockError::Overflow)?;
        if end > u32::MAX as usize { return Err(BlockError::Overflow); }
        let last_idx = end - 1;
        let _ = mul_offset(last_idx as u64, self.stride)?;
        if last_idx / self.slots_per_slab >= MAX_SLABS { return Err(BlockError::Slab); }
        let orig_slabs = self.slabs.len();
        let mut idx = start;
        while idx <= last_idx {
            let slab_i = idx / self.slots_per_slab;
            let slab_end = ((slab_i + 1).saturating_mul(self.slots_per_slab) - 1).min(last_idx);
            if let Err(err) = self.ensure_slot(slab_end) {
                self.slabs.truncate(orig_slabs);
                return Err(err);
            }
            idx = slab_end + 1;
        }
        self.ensure_sketch_slots(end)?;
        self.slots.resize(end, SlotRecord::fresh(self.kind));
        self.gpu_zero_pending.resize(end, false);
        if self.with_sketches && self.kind == BlockKind::Full {
            self.sketch_valid_len.resize(end, 0);
            self.sketch_epoch.resize(end, 0);
        }
        Ok(())
    }

    /// Zero-fill `slot`, clear its seal and length, and bump its generation.
    /// A live reference count is refused. Generation `u32::MAX` is refused and not cleared.
    pub fn take(&mut self, slot: Slot) -> Result<u64, BlockError> {
        let i = self.index(slot)?;
        if self.slots[i].refs() != 0 { return Err(BlockError::Refs); }
        let _ = next_generation(self.slots[i].generation())?;
        self.bytes_of_mut(i).fill(0);
        if let Some(sk) = self.sketch_bytes_of_mut(i) {
            sk.fill(0);
        }
        if i < self.sketch_valid_len.len() {
            self.sketch_valid_len[i] = 0;
        }
        if i < self.sketch_epoch.len() {
            self.sketch_epoch[i] = self.sketch_epoch[i].wrapping_add(1);
        }
        self.slots[i].bump_generation()?;
        self.slots[i].set_length(0)?;
        self.slots[i].unseal();
        if i < self.gpu_zero_pending.len() {
            self.gpu_zero_pending[i] = false;
        }
        mul_offset(u64::from(slot.pool_index().get()), self.stride)
    }

    /// Take `slot` without CPU-zeroing its multi-MiB backing storage on the host thread.
    /// On GPU pools, marks the slot for deferred GPU `k_zero` if a partial span reads it
    /// before all 64 positions are overwritten; callers restoring a full block clear the flag.
    pub fn take_unzeroed(&mut self, slot: Slot) -> Result<u64, BlockError> {
        let i = self.index(slot)?;
        if self.slots[i].refs() != 0 { return Err(BlockError::Refs); }
        let _ = next_generation(self.slots[i].generation())?;
        if let Some(sk) = self.sketch_bytes_of_mut(i) {
            sk.fill(0);
        }
        if i < self.sketch_valid_len.len() {
            self.sketch_valid_len[i] = 0;
        }
        if i < self.sketch_epoch.len() {
            self.sketch_epoch[i] = self.sketch_epoch[i].wrapping_add(1);
        }
        self.slots[i].bump_generation()?;
        self.slots[i].set_length(0)?;
        self.slots[i].unseal();
        if i < self.gpu_zero_pending.len() {
            self.gpu_zero_pending[i] = self.has_gpu_storage();
        }
        mul_offset(u64::from(slot.pool_index().get()), self.stride)
    }

    /// Atomically consume and return whether `slot` needs a GPU `k_zero` clear before a partial read.
    pub fn take_gpu_zero_pending(&mut self, slot: Slot) -> bool {
        let Ok(i) = self.index(slot) else { return false };
        if i < self.gpu_zero_pending.len() {
            std::mem::replace(&mut self.gpu_zero_pending[i], false)
        } else {
            false
        }
    }

    /// Clear `gpu_zero_pending` after a full-slot overwrite (such as SSD block restore).
    pub fn clear_gpu_zero_pending(&mut self, slot: Slot) {
        if let Ok(i) = self.index(slot) {
            if i < self.gpu_zero_pending.len() {
                self.gpu_zero_pending[i] = false;
            }
        }
    }

    /// Lowest slot with a zero reference count whose generation can advance.
    /// Grows by one slot when every existing slot is live or exhausted.
    pub fn take_free(&mut self) -> Result<(Slot, u64), BlockError> {
        let n = self.slots.len();
        for i in 0..n {
            if self.slots[i].refs() == 0 && next_generation(self.slots[i].generation()).is_ok() {
                let slot = Slot::new((i as u32) + 1).map_err(|_| BlockError::Overflow)?;
                return Ok((slot, self.take(slot)?));
            }
        }
        let slot = self.grow()?;
        Ok((slot, self.take(slot)?))
    }

    /// The lowest slot nothing references whose generation can still advance.
    pub fn lowest_free(&self) -> Option<Slot> {
        let i = self.slots.iter().position(|r| r.refs == 0 && r.generation < u32::MAX)?;
        Slot::new(u32::try_from(i + 1).ok()?).ok()
    }

    #[cfg(test)]
    fn force_generation(&mut self, slot: Slot, generation: u32) -> Result<(), BlockError> {
        self.record_mut(slot)?.generation = generation;
        Ok(())
    }

    #[cfg(test)]
    fn slot_bytes_mut_for_test(&mut self, slot: Slot) -> &mut [u8] {
        let i = self.index(slot).unwrap();
        self.bytes_of_mut(i)
    }
}

/// Both pools. One per kind, so their offsets are not in one address space.
#[derive(Clone, Debug)]
pub struct BlockPools {
    pub window: BlockPool,
    pub full: BlockPool,
}

impl BlockPools {
    /// Host records and no device. A running engine uses [`BlockPools::gpu`].
    pub fn stub() -> BlockPools {
        BlockPools { window: BlockPool::new(BlockKind::Window, 0), full: BlockPool::new(BlockKind::Full, 0) }
    }

    /// GPU pools (`0` sketch bytes by default). `n_window` and `n_full` are allocated now. `kvb` is 1 or 2 and sizes
    /// both kinds. Zero slots still holds the device and grows through [`BlockPool::grow`].
    #[cfg(not(standalone_blocks))]
    pub fn gpu(dev: &ProtocolObject<dyn MTLDevice>, n_window: usize, n_full: usize, kvb: u32) -> BlockPools {
        Self::gpu_with_sketches(dev, n_window, n_full, kvb, false)
    }

    /// GPU pools with optional `WHT-2bit` sketch sidecar on `BlockKind::Full` (`--sparse-topk`).
    #[cfg(not(standalone_blocks))]
    pub fn gpu_with_sketches(
        dev: &ProtocolObject<dyn MTLDevice>,
        n_window: usize,
        n_full: usize,
        kvb: u32,
        enable_sketches: bool,
    ) -> BlockPools {
        BlockPools {
            window: BlockPool::gpu(dev, BlockKind::Window, n_window, kvb),
            full: BlockPool::gpu_with_sketches(dev, BlockKind::Full, n_full, kvb, enable_sketches),
        }
    }

    /// GPU pools at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`, `0` sketch bytes by default).
    #[cfg(not(standalone_blocks))]
    pub fn gpu_mode(dev: &ProtocolObject<dyn MTLDevice>, n_window: usize, n_full: usize, mode: KvMode) -> BlockPools {
        Self::gpu_mode_with_sketches(dev, n_window, n_full, mode, false)
    }

    /// GPU pools at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`) with optional `Full` sketches (`--sparse-topk`).
    #[cfg(not(standalone_blocks))]
    pub fn gpu_mode_with_sketches(
        dev: &ProtocolObject<dyn MTLDevice>,
        n_window: usize,
        n_full: usize,
        mode: KvMode,
        enable_sketches: bool,
    ) -> BlockPools {
        BlockPools {
            window: BlockPool::gpu_mode(dev, BlockKind::Window, n_window, mode),
            full: BlockPool::gpu_mode_with_sketches(dev, BlockKind::Full, n_full, mode, enable_sketches),
        }
    }

    /// Both pools with `n_slots` each at fp16 (`kvb = 2`, `0` sketch bytes).
    pub fn new(n_slots: usize) -> BlockPools {
        BlockPools { window: BlockPool::new(BlockKind::Window, n_slots), full: BlockPool::new(BlockKind::Full, n_slots) }
    }

    /// Both pools with independent capacities at element width `kvb` (`1` or `2`, `0` sketch bytes).
    pub fn with_capacities(full_slots: usize, window_slots: usize, kvb: u32) -> Result<BlockPools, BlockError> {
        Self::with_capacities_and_sketches(full_slots, window_slots, kvb, false)
    }

    /// Both pools with independent capacities at element width `kvb` (`1` or `2`) and optional `Full` sketches.
    pub fn with_capacities_and_sketches(
        full_slots: usize,
        window_slots: usize,
        kvb: u32,
        enable_sketches: bool,
    ) -> Result<BlockPools, BlockError> {
        Ok(BlockPools {
            window: BlockPool::with_kvb(BlockKind::Window, window_slots, kvb)?,
            full: if enable_sketches {
                BlockPool::new_with_sketches(BlockKind::Full, full_slots, kvb)?
            } else {
                BlockPool::with_kvb(BlockKind::Full, full_slots, kvb)?
            },
        })
    }

    /// Both pools with independent capacities at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`, `0` sketch bytes).
    pub fn with_capacities_mode(full_slots: usize, window_slots: usize, mode: KvMode) -> Result<BlockPools, BlockError> {
        Self::with_capacities_mode_and_sketches(full_slots, window_slots, mode, false)
    }

    /// Both pools with independent capacities at explicit [`KvMode`] (`Fp16`, `Kv8`, or `Kv4`) and optional `Full` sketches.
    pub fn with_capacities_mode_and_sketches(
        full_slots: usize,
        window_slots: usize,
        mode: KvMode,
        enable_sketches: bool,
    ) -> Result<BlockPools, BlockError> {
        Ok(BlockPools {
            window: BlockPool::with_mode(BlockKind::Window, window_slots, mode)?,
            full: BlockPool::with_mode_and_sketches(BlockKind::Full, full_slots, mode, enable_sketches)?,
        })
    }

    pub fn of(&self, kind: BlockKind) -> &BlockPool {
        match kind { BlockKind::Window => &self.window, BlockKind::Full => &self.full }
    }

    pub fn of_mut(&mut self, kind: BlockKind) -> &mut BlockPool {
        match kind { BlockKind::Window => &mut self.window, BlockKind::Full => &mut self.full }
    }
}

/// One lane's table. A missing entry inside the declared rows is no entry.
/// An index outside those rows is `OutOfRange`, not a missing entry.
#[derive(Clone, Debug)]
pub struct BlockTable {
    blocks_per_kind: u32,
    entries: Vec<Option<BlockEntry>>,
    /// Per-kind inclusive dirty block bounds `[lo, hi]` (`[0]` = Full, `[1]` = Window).
    dirty: [Option<(u32, u32)>; 2],
    /// When `true`, the full `0..blocks_per_kind` range for that kind must be synced to GPU.
    needs_full_sync: [bool; 2],
}

impl BlockTable {
    #[inline]
    fn kind_idx(kind: BlockKind) -> usize {
        match kind {
            BlockKind::Full => 0,
            BlockKind::Window => 1,
        }
    }

    #[inline]
    fn mark_dirty(&mut self, kind: BlockKind, block: u32) {
        let ki = Self::kind_idx(kind);
        if self.needs_full_sync[ki] {
            return;
        }
        self.dirty[ki] = Some(match self.dirty[ki] {
            Some((lo, hi)) => (lo.min(block), hi.max(block)),
            None => (block, block),
        });
    }

    /// Force the next GPU sync to rewrite all `0..blocks_per_kind` slots for both kinds.
    pub fn mark_full_sync(&mut self) {
        self.dirty = [None; 2];
        self.needs_full_sync = [true; 2];
    }

    pub fn needs_full_sync(&self, kind: BlockKind) -> bool {
        self.needs_full_sync[Self::kind_idx(kind)]
    }

    /// Inclusive dirty block bounds `[lo, hi]` for `kind`, or `None` when clean.
    pub fn dirty_range(&self, kind: BlockKind) -> Option<(u32, u32)> {
        if self.blocks_per_kind == 0 {
            return None;
        }
        let ki = Self::kind_idx(kind);
        if self.needs_full_sync[ki] {
            Some((0, self.blocks_per_kind - 1))
        } else {
            self.dirty[ki]
        }
    }

    /// Clear dirty tracking for `kind` after its GPU block table has been updated.
    pub fn clear_dirty(&mut self, kind: BlockKind) {
        let ki = Self::kind_idx(kind);
        self.dirty[ki] = None;
        self.needs_full_sync[ki] = false;
    }

    /// Synchronize only the dirty block range for `kind` into `dst` (length `>= blocks_per_kind`),
    /// writing `pool.gpu_table_entry(e)` for present entries and [`CLEARED_GPU_TABLE_ENTRY`]
    /// (`u64::MAX`, distinct from slab-0 `Slot(1)`'s `0`) for cleared entries, then
    /// clearing the dirty range. Returns the number of `u64` entries written (0 when clean).
    pub fn sync_dirty_to_slice(
        &mut self,
        kind: BlockKind,
        pool: &BlockPool,
        dst: &mut [u64],
    ) -> Result<usize, BlockError> {
        let n_blk = self.blocks_per_kind as usize;
        if dst.len() < n_blk {
            return Err(BlockError::OutOfRange);
        }
        let Some((lo, hi)) = self.dirty_range(kind) else {
            return Ok(0);
        };
        let lo = lo as usize;
        let hi = (hi as usize).min(n_blk.saturating_sub(1));
        let mut written = 0usize;
        for (b, slot_out) in dst.iter_mut().enumerate().take(hi + 1).skip(lo) {
            let bi = BlockIndex::new(b as u32);
            *slot_out = match self.get(kind, bi)? {
                Some(entry) => pool.gpu_table_entry(entry)?,
                None => CLEARED_GPU_TABLE_ENTRY,
            };
            written += 1;
        }
        self.clear_dirty(kind);
        Ok(written)
    }

    pub fn empty() -> BlockTable {
        BlockTable {
            blocks_per_kind: 0,
            entries: Vec::new(),
            dirty: [None; 2],
            needs_full_sync: [true; 2],
        }
    }

    pub fn new(blocks_per_kind: u32) -> Result<BlockTable, BlockError> {
        let n = usize::try_from(blocks_per_kind).ok().and_then(|n| n.checked_mul(2)).ok_or(BlockError::Overflow)?;
        Ok(BlockTable {
            blocks_per_kind,
            entries: vec![None; n],
            dirty: [None; 2],
            needs_full_sync: [true; 2],
        })
    }

    pub fn get(&self, kind: BlockKind, block: BlockIndex) -> Result<Option<BlockEntry>, BlockError> {
        let i = table_index(kind, block, self.blocks_per_kind)? as usize;
        Ok(self.entries.get(i).copied().flatten())
    }

    pub fn blocks_per_kind(&self) -> u32 { self.blocks_per_kind }

    /// Set or clear the entry for `(kind, block)`. An entry of the other kind is refused.
    pub fn set(&mut self, kind: BlockKind, block: BlockIndex, entry: Option<BlockEntry>) -> Result<(), BlockError> {
        if entry.is_some_and(|e| e.kind() != kind) { return Err(BlockError::OutOfRange); }
        let i = table_index(kind, block, self.blocks_per_kind)? as usize;
        let cell = self.entries.get_mut(i).ok_or(BlockError::OutOfRange)?;
        if *cell != entry {
            *cell = entry;
            self.mark_dirty(kind, block.get());
        }
        Ok(())
    }

    /// Every present entry with its block, full before window within a block,
    /// blocks ascending.
    pub fn entries(&self) -> impl Iterator<Item = (BlockIndex, BlockEntry)> + '_ {
        self.entries.iter().enumerate().filter_map(|(i, e)| e.map(|e| (BlockIndex::new((i / 2) as u32), e)))
    }

    /// Resolve every `(BlockKind::Full, b, entry)` in `0..=(pos + len - 1) / BLOCK` and
    /// `(BlockKind::Window, b, entry)` in `span_window_blocks(pos, len)` that a step over
    /// `[pos, pos + len)` reads (`U170`, bound to `specs/SpanPins.tla`).
    pub fn pinned_span_entries(
        &self,
        pos: usize,
        len: usize,
    ) -> Result<Vec<(BlockKind, BlockIndex, BlockEntry)>, BlockError> {
        if len == 0 {
            return Err(BlockError::OutOfRange);
        }
        let end = pos.checked_add(len - 1).ok_or(BlockError::Overflow)?;
        let hi_full = u32::try_from(end / BLOCK).map_err(|_| BlockError::Overflow)?;
        let mut out = Vec::new();
        for b in 0..=hi_full {
            let bi = BlockIndex::new(b);
            let entry = self.get(BlockKind::Full, bi)?.ok_or(BlockError::NoEntry)?;
            out.push((BlockKind::Full, bi, entry));
        }
        for bi in span_window_blocks(pos, len)? {
            let entry = self.get(BlockKind::Window, bi)?.ok_or(BlockError::NoEntry)?;
            out.push((BlockKind::Window, bi, entry));
        }
        Ok(out)
    }

    /// Write one entry. The stored offset is `byte_offset` at the pool's `kvb`.
    /// Generation 0, on the argument or the record, is `NotTaken` and takes no
    /// reference. Any other mismatch is `Stale` and takes no reference.
    /// An entry already in the cell drops its reference only when that entry's
    /// generation is still the slot's generation. Every check finishes before
    /// any reference changes. An empty pool is `NoSlots`. This does not bump
    /// the generation and does not allocate a buffer.
    pub fn fill(&mut self, pool: &mut BlockPool, block: BlockIndex, slot: Slot, generation: u32) -> Result<(), BlockError> {
        if pool.len() == 0 { return Err(BlockError::NoSlots); }
        let record_gen = pool.record(slot)?.generation();
        if generation == 0 || record_gen == 0 { return Err(BlockError::NotTaken); }
        if record_gen != generation { return Err(BlockError::Stale); }
        let kvb = pool.kvb();
        let offset = pool.offset(slot)?;
        let i = table_index(pool.kind(), block, self.blocks_per_kind)? as usize;
        let prev = self.entries.get(i).copied().flatten();
        let drop_prev = match prev {
            Some(prev) => pool.record(prev.slot())?.generation() == prev.generation(),
            None => false,
        };
        let same = drop_prev && prev.map(|prev| prev.slot()) == Some(slot);
        if drop_prev {
            let held = prev.ok_or(BlockError::NoEntry)?;
            if pool.record(held.slot())?.refs() == 0 { return Err(BlockError::Refs); }
        }
        if !same && pool.record(slot)?.refs() == u32::MAX { return Err(BlockError::Overflow); }
        if drop_prev && !same {
            let held = prev.ok_or(BlockError::NoEntry)?;
            pool.record_mut(held.slot())?.drop_ref()?;
        }
        if !same {
            pool.record_mut(slot)?.add_ref()?;
        }
        let new_entry = BlockEntry::new(slot, generation, offset, pool.kind(), kvb);
        let changed = prev != Some(new_entry);
        let cell = self.entries.get_mut(i).ok_or(BlockError::OutOfRange)?;
        *cell = Some(new_entry);
        if changed {
            self.mark_dirty(pool.kind(), block.get());
        }
        Ok(())
    }

    /// Clear one `(kind, block)` cell, dropping its pool reference if its generation still matches.
    pub fn clear_kind_entry(&mut self, pool: &mut BlockPool, block: BlockIndex) -> Result<(), BlockError> {
        let i = table_index(pool.kind(), block, self.blocks_per_kind)? as usize;
        if let Some(prev) = self.entries.get(i).copied().flatten() {
            if pool.record(prev.slot())?.generation() == prev.generation() {
                pool.record_mut(prev.slot())?.drop_ref()?;
            }
            self.entries[i] = None;
            self.mark_dirty(pool.kind(), block.get());
        }
        Ok(())
    }

    /// Drop every live reference held by this table and clear every cell to `None`.
    pub fn clear_entries(&mut self, pools: &mut BlockPools) -> Result<(), BlockError> {
        for cell in &mut self.entries {
            if let Some(prev) = cell.take() {
                let pool = pools.of_mut(prev.kind());
                if pool.record(prev.slot())?.generation() == prev.generation() {
                    pool.record_mut(prev.slot())?.drop_ref()?;
                }
            }
        }
        self.mark_full_sync();
        Ok(())
    }
}

impl Default for BlockTable {
    fn default() -> Self { BlockTable::empty() }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn offsets_are_plain_bytes_per_kind() {
        let s = Slot::new(1).unwrap();
        assert_eq!(byte_offset(BlockKind::Full, s, 2).unwrap(), 0);
        assert_eq!(byte_offset(BlockKind::Window, s, 2).unwrap(), 0);
        let s3 = Slot::new(3).unwrap();
        assert_eq!(byte_offset(BlockKind::Full, s3, 2).unwrap(), 2 * FULL_STRIDE);
        assert_eq!(byte_offset(BlockKind::Window, s3, 2).unwrap(), 2 * WINDOW_STRIDE);
        assert_eq!(BlockKind::Full.stride_bytes(2).unwrap(), FULL_STRIDE);
        assert_eq!(BlockKind::Window.stride_bytes(2).unwrap(), WINDOW_STRIDE);
        assert_eq!(BlockKind::Full.stride_bytes(1).unwrap(), FULL_STRIDE / 2);
        assert_eq!(BlockKind::Window.stride_bytes(1).unwrap(), WINDOW_STRIDE / 2);
        assert_eq!(byte_offset(BlockKind::Window, s3, 1).unwrap(), 2 * (WINDOW_STRIDE / 2));
        assert_eq!(BlockKind::Full.stride_bytes(0), Err(BlockError::Width));
    }

    #[test]
    fn slot_zero_is_refused() {
        assert_eq!(Slot::new(0), Err(BlockError::SlotZero));
    }

    #[test]
    fn offset_multiply_is_refused() {
        assert_eq!(mul_offset(u64::MAX / WINDOW_STRIDE + 1, WINDOW_STRIDE), Err(BlockError::Overflow));
        let slot = Slot::new(u32::MAX).unwrap();
        let index = u64::from(slot.pool_index().get());
        assert_eq!(byte_offset(BlockKind::Window, slot, 2).unwrap(), index * WINDOW_STRIDE);
        let empty = BlockPool::new(BlockKind::Window, 0);
        assert_eq!(empty.record(Slot::new(1).unwrap()).map(|r| r.kind()), Err(BlockError::OutOfRange));
        let one = BlockPool::new(BlockKind::Full, 1);
        assert_eq!(one.kind(), BlockKind::Full);
        assert_eq!(one.len(), 1);
        assert_eq!(one.kvb(), 2);
        assert_eq!(one.offset(Slot::new(1).unwrap()).unwrap(), 0);
        assert_eq!(one.offset(Slot::new(2).unwrap()), Err(BlockError::OutOfRange));
        let narrow = BlockPool::with_kvb(BlockKind::Full, 1, 1).unwrap();
        assert_eq!(narrow.kvb(), 1);
        assert_eq!(narrow.offset(Slot::new(1).unwrap()).unwrap(), 0);
        assert_eq!(BlockPool::with_kvb(BlockKind::Window, 1, 0).err(), Some(BlockError::Width));
        assert_eq!(byte_offset(BlockKind::Window, Slot::new(1).unwrap(), 3), Err(BlockError::Width));
        assert_eq!(BlockPool::with_kvb(BlockKind::Window, 1, 3).err(), Some(BlockError::Width));
        let pools = BlockPools::stub();
        assert_eq!(pools.window.len(), 0);
        assert_eq!(pools.full.kind(), BlockKind::Full);
        assert_eq!(Slot::new(1).unwrap().get(), 1);
    }

    #[test]
    fn table_index_refuses_range_and_overflow() {
        assert_eq!(table_index(BlockKind::Full, BlockIndex::new(4), 4), Err(BlockError::OutOfRange));
        let wide = BlockIndex::new(u32::MAX / 2 + 1);
        assert_eq!(table_index(BlockKind::Window, wide, u32::MAX), Err(BlockError::Overflow));
    }

    #[test]
    fn generation_does_not_wrap_and_length_stops_at_64() {
        assert_eq!(next_generation(u32::MAX), Err(BlockError::Generation));
        assert_eq!(next_generation(0).unwrap(), 1);
        assert_eq!(block_length(64).unwrap(), 64);
        assert_eq!(block_length(65), Err(BlockError::Length));
    }

    #[test]
    fn span_of_512_pins_25_window_blocks() {
        assert_eq!(BlockIndex::of_pos(0).unwrap().get(), 0);
        assert_eq!(BlockIndex::of_pos(64).unwrap().get(), 1);
        assert_eq!(span_bound(512), 25);
    }

    #[test]
    fn a_hole_inside_the_table_is_no_entry_and_past_it_is_not() {
        let t = BlockTable::new(4).unwrap();
        assert_eq!(t.get(BlockKind::Window, BlockIndex::new(0)).unwrap(), None);
        assert_eq!(t.get(BlockKind::Full, BlockIndex::new(4)), Err(BlockError::OutOfRange));
        let mut fresh = SlotRecord::fresh(BlockKind::Full);
        assert_eq!(fresh.generation(), 0);
        assert!(!fresh.sealed());
        assert_eq!(fresh.refs(), 0);
        fresh.bump_generation().unwrap();
        assert_eq!(fresh.generation(), 1);
        assert_eq!(fresh.set_length(70), Err(BlockError::Length));
        assert_eq!(fresh.length(), 0);
        fresh.set_length(64).unwrap();
        assert_eq!(fresh.length(), 64);
        fresh.seal();
        assert!(fresh.sealed());
        assert_eq!(fresh.drop_ref(), Err(BlockError::Refs));
        fresh.add_ref().unwrap();
        fresh.drop_ref().unwrap();
        assert_eq!(fresh.refs(), 0);
        let mut last = SlotRecord::at_generation(BlockKind::Window, u32::MAX);
        assert_eq!(last.bump_generation(), Err(BlockError::Generation));
        assert_eq!(last.generation(), u32::MAX);
        let entry = BlockEntry::new(Slot::new(1).unwrap(), 1, 0, BlockKind::Full, 2);
        assert_eq!(entry.kind(), BlockKind::Full);
        assert_eq!(entry.offset(), 0);
        assert_eq!(entry.generation(), 1);
        assert_eq!(entry.slot().get(), 1);
        assert_eq!(entry.kvb(), 2);
    }

    fn take(pool: &mut BlockPool, slot: Slot) {
        pool.record_mut(slot).unwrap().bump_generation().unwrap();
    }

    fn written(pool: &mut BlockPool, slot: Slot, n: u32) {
        pool.record_mut(slot).unwrap().set_length(n).unwrap();
        if n == BLOCK as u32 {
            pool.record_mut(slot).unwrap().seal();
        }
    }

    #[test]
    fn a_taken_slot_is_zero_filled_and_a_live_one_is_not() {
        for kind in [BlockKind::Full, BlockKind::Window] {
            let mut pool = BlockPool::new(kind, 1);
            let slot = Slot::new(1).unwrap();
            assert!(pool.gpu_buffer(slot).unwrap().is_none());
            assert_eq!(pool.slot_bytes(slot).unwrap().len(), kind.stride() as usize);
            pool.slot_bytes_mut_for_test(slot).fill(0xab);
            assert_eq!(pool.take(slot).unwrap(), 0);
            assert!(pool.slot_bytes(slot).unwrap().iter().all(|&b| b == 0));
            assert_eq!(pool.record(slot).unwrap().generation(), 1);
            assert_eq!(pool.record(slot).unwrap().length(), 0);
            assert!(!pool.record(slot).unwrap().sealed());
            pool.record_mut(slot).unwrap().add_ref().unwrap();
            pool.slot_bytes_mut_for_test(slot)[0] = 0xcd;
            assert_eq!(pool.take(slot), Err(BlockError::Refs));
            assert_eq!(pool.slot_bytes(slot).unwrap()[0], 0xcd);
            assert_eq!(pool.record(slot).unwrap().generation(), 1);
        }
    }

    #[test]
    fn take_does_not_wrap_and_reuse_zero_fills_again() {
        let mut pool = BlockPool::new(BlockKind::Full, 1);
        let slot = Slot::new(1).unwrap();
        pool.force_generation(slot, u32::MAX).unwrap();
        pool.slot_bytes_mut_for_test(slot)[0] = 0x11;
        assert_eq!(pool.take(slot), Err(BlockError::Generation));
        assert_eq!(pool.record(slot).unwrap().generation(), u32::MAX);
        assert_eq!(pool.slot_bytes(slot).unwrap()[0], 0x11);
        pool.force_generation(slot, 0).unwrap();
        pool.take(slot).unwrap();
        pool.slot_bytes_mut_for_test(slot)[0] = 7;
        pool.record_mut(slot).unwrap().set_length(1).unwrap();
        pool.record_mut(slot).unwrap().seal();
        pool.take(slot).unwrap();
        assert!(!pool.record(slot).unwrap().sealed());
        assert_eq!(pool.record(slot).unwrap().generation(), 2);
        assert!(pool.slot_bytes(slot).unwrap().iter().all(|&b| b == 0));
    }

    #[test]
    fn take_unzeroed_updates_metadata_without_host_memset() {
        let mut pool = BlockPool::new(BlockKind::Full, 1);
        let slot = Slot::new(1).unwrap();
        pool.slot_bytes_mut_for_test(slot).fill(0x5c);
        assert_eq!(pool.take_unzeroed(slot).unwrap(), 0);
        assert_eq!(pool.record(slot).unwrap().generation(), 1);
        assert_eq!(pool.record(slot).unwrap().length(), 0);
        assert!(!pool.record(slot).unwrap().sealed());
        // Host bytes were untouched on take_unzeroed:
        assert_eq!(pool.slot_bytes(slot).unwrap()[0], 0x5c);
        assert_eq!(pool.record_mut(slot).unwrap().set_length(64), Ok(()));
        assert_eq!(pool.record_mut(slot).unwrap().set_length(65), Err(BlockError::Length));
        pool.record_mut(slot).unwrap().add_ref().unwrap();
        assert_eq!(pool.take_unzeroed(slot), Err(BlockError::Refs));
    }

    #[test]
    fn grow_appends_and_take_free_reuses_the_lowest_slot() {
        let mut pool = BlockPool::new(BlockKind::Window, 0);
        assert_eq!(pool.take(Slot::new(1).unwrap()), Err(BlockError::OutOfRange));
        let first = pool.grow().unwrap();
        assert_eq!(first.get(), 1);
        assert_eq!(pool.offset(first).unwrap(), 0);
        assert_eq!(pool.record(first).unwrap().generation(), 0);
        let (slot, off) = pool.take_free().unwrap();
        assert_eq!(slot, first);
        assert_eq!(off, 0);
        pool.record_mut(slot).unwrap().add_ref().unwrap();
        let (second, off2) = pool.take_free().unwrap();
        assert_eq!(second.get(), 2);
        assert_eq!(off2, WINDOW_STRIDE);
        assert_eq!(pool.offset(first).unwrap(), 0);
        pool.record_mut(slot).unwrap().drop_ref().unwrap();
        pool.slot_bytes_mut_for_test(slot)[0] = 0x5a;
        let (again, _) = pool.take_free().unwrap();
        assert_eq!(again, first);
        assert_eq!(pool.record(again).unwrap().generation(), 2);
        assert_eq!(pool.slot_bytes(again).unwrap()[0], 0);
        pool.force_generation(first, u32::MAX).unwrap();
        pool.force_generation(second, u32::MAX).unwrap();
        let (third, off3) = pool.take_free().unwrap();
        assert_eq!(third.get(), 3);
        assert_eq!(off3, 2 * WINDOW_STRIDE);
        assert_eq!(pool.len(), 3);
    }

    #[test]
    #[cfg(not(standalone_blocks))]
    #[ignore = "requires a Metal GPU device; run in nightly m5-full"]
    fn gpu_pool_zero_fills_a_taken_slot() {
        use objc2_metal::{MTLBuffer, MTLDevice};
        let dev = objc2_metal::MTLCreateSystemDefaultDevice().expect("metal device");
        let mut pools = BlockPools::gpu(&dev, 1, 1, KVB_FP16);
        for pool in [&mut pools.full, &mut pools.window] {
            let slot = Slot::new(1).unwrap();
            let buf = pool.gpu_buffer(slot).unwrap().expect("gpu buffer");
            assert_eq!(buf.length(), pool.stride_bytes() as usize);
            pool.slot_bytes_mut_for_test(slot).fill(0xef);
            assert_eq!(pool.take(slot).unwrap(), 0);
            assert!(pool.slot_bytes(slot).unwrap().iter().all(|&b| b == 0));
            assert_eq!(pool.record(slot).unwrap().generation(), 1);
            let grown = pool.grow().unwrap();
            assert_eq!(grown.get(), 2);
            assert_eq!(pool.offset(grown).unwrap(), pool.stride_bytes());
            assert_eq!(pool.offset(slot).unwrap(), 0);
            let share = 2 * pool.stride_bytes() <= dev.maxBufferLength() as u64;
            if share {
                assert_eq!(pool.slab_index(slot).unwrap(), pool.slab_index(grown).unwrap());
                let slab = pool.gpu_buffer(grown).unwrap().expect("slab");
                assert_eq!(slab.length(), 2 * pool.stride_bytes() as usize);
                assert_eq!(pool.gpu_buffer(slot).unwrap().unwrap().contents().as_ptr(), slab.contents().as_ptr());
            } else {
                assert_eq!(pool.slab_index(grown).unwrap(), 1);
            }
        }
        assert_ne!(pools.window.stride_bytes(), pools.full.stride_bytes());
    }

    #[test]
    fn two_slots_share_a_slab_and_a_third_does_not_alias() {
        let stride = FULL_STRIDE;
        let mut pool = BlockPool::open(BlockKind::Full, 0, KVB_FP16, stride * 2, None).unwrap();
        let a = pool.grow().unwrap();
        let b = pool.grow().unwrap();
        assert_eq!(pool.slab_count(), 1);
        assert_eq!(pool.slab_index(a).unwrap(), 0);
        assert_eq!(pool.slab_index(b).unwrap(), 0);
        pool.take(a).unwrap();
        pool.take(b).unwrap();
        pool.slot_bytes_mut_for_test(a)[0] = 0x11;
        pool.slot_bytes_mut_for_test(b)[0] = 0x22;
        assert_eq!(pool.slot_bytes(a).unwrap()[0], 0x11);
        assert_eq!(pool.slot_bytes(b).unwrap()[0], 0x22);
        let pa = pool.slot_bytes(a).unwrap().as_ptr() as usize;
        let pb = pool.slot_bytes(b).unwrap().as_ptr() as usize;
        assert_eq!(pb - pa, stride as usize);
        let c = pool.grow().unwrap();
        assert_eq!(pool.slab_index(c).unwrap(), 1);
        assert_eq!(pool.slab_count(), 2);
        assert_eq!(pool.offset(c).unwrap(), 2 * stride);
        pool.take(c).unwrap();
        pool.slot_bytes_mut_for_test(c)[0] = 0x33;
        assert_eq!(pool.slot_bytes(a).unwrap()[0], 0x11);
        assert_eq!(pool.slot_bytes(b).unwrap()[0], 0x22);
        assert_eq!(pool.slot_bytes(c).unwrap()[0], 0x33);
        assert_ne!(pool.slot_bytes(c).unwrap().as_ptr(), pool.slot_bytes(a).unwrap().as_ptr());
    }

    #[test]
    fn a_fifth_slab_is_refused() {
        let mut pool = BlockPool::open(BlockKind::Full, 0, KVB_FP16, FULL_STRIDE, None).unwrap();
        for i in 1..=4 {
            let slot = pool.grow().unwrap();
            assert_eq!(slot.get(), i);
            assert_eq!(pool.slab_index(slot).unwrap(), (i - 1) as usize);
        }
        assert_eq!(pool.slab_count(), 4);
        assert_eq!(pool.grow(), Err(BlockError::Slab));
        assert_eq!(pool.len(), 4);
        assert_eq!(BlockPool::open(BlockKind::Full, 0, KVB_FP16, FULL_STRIDE - 1, None).unwrap_err(), BlockError::Slab);
    }

    #[test]
    fn kv8_pool_uses_half_the_fp16_stride() {
        let pool = BlockPool::open(BlockKind::Full, 2, 1, u64::MAX, None).unwrap();
        assert_eq!(pool.kvb(), 1);
        assert_eq!(pool.stride_bytes(), FULL_STRIDE / 2);
        assert_eq!(pool.slab_count(), 1);
        assert_eq!(pool.offset(Slot::new(2).unwrap()).unwrap(), FULL_STRIDE / 2);
        assert_eq!(pool.slot_bytes(Slot::new(1).unwrap()).unwrap().len(), (FULL_STRIDE / 2) as usize);
        assert_eq!(stride_at(BlockKind::Window, 2).unwrap(), WINDOW_STRIDE);
        assert_eq!(stride_at(BlockKind::Window, 1).unwrap(), WINDOW_STRIDE / 2);
        assert_eq!(stride_at(BlockKind::Full, 0), Err(BlockError::Kvb));
        assert_eq!(stride_at(BlockKind::Full, 3), Err(BlockError::Kvb));
        assert!(BlockPool::open(BlockKind::Window, 1, 4, u64::MAX, None).is_err());
    }

    #[test]
    fn bump_generation_waits_for_zero_refs() {
        let mut slot = SlotRecord::fresh(BlockKind::Full);
        slot.set_length(64).unwrap();
        slot.seal();
        slot.add_ref().unwrap();
        assert_eq!(slot.bump_generation(), Err(BlockError::Refs));
        assert_eq!((slot.generation(), slot.length(), slot.sealed(), slot.refs()), (0, 64, true, 1));
        slot.drop_ref().unwrap();
        slot.bump_generation().unwrap();
        assert_eq!((slot.generation(), slot.length(), slot.sealed(), slot.refs()), (1, 64, true, 0));
        let mut max_slot = SlotRecord::at_generation(BlockKind::Window, u32::MAX);
        max_slot.set_length(32).unwrap();
        max_slot.seal();
        assert_eq!(max_slot.bump_generation(), Err(BlockError::Generation));
        assert_eq!((max_slot.generation(), max_slot.length(), max_slot.sealed(), max_slot.refs()), (u32::MAX, 32, true, 0));
    }

    #[test]
    fn fill_stores_byte_offset_and_a_key_read_uses_the_table() {
        let mut full = BlockPool::new(BlockKind::Full, 4);
        let mut window = BlockPool::new(BlockKind::Window, 4);
        let mut t = BlockTable::new(4).unwrap();
        let slot = Slot::new(3).unwrap();
        take(&mut full, slot);
        take(&mut window, slot);
        assert_eq!(t.fill(&mut full, BlockIndex::new(0), slot, 4), Err(BlockError::Stale));
        assert_eq!(full.record(slot).unwrap().refs(), 0);
        t.fill(&mut full, BlockIndex::new(0), slot, 1).unwrap();
        t.fill(&mut window, BlockIndex::new(0), slot, 1).unwrap();
        written(&mut full, slot, 64);
        written(&mut window, slot, 64);
        let stored = t.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
        assert_eq!(stored.offset(), byte_offset(BlockKind::Full, slot, 2).unwrap());
        assert_eq!(stored.offset(), 2 * FULL_STRIDE);
        assert_eq!(stored.generation(), 1);
        assert_eq!(stored.kvb(), 2);
        assert_eq!(full.record(slot).unwrap().generation(), 1);
        assert_eq!(full.record(slot).unwrap().refs(), 1);
        assert_eq!(full.gpu_table_entry(stored).unwrap(), stored.offset());
        assert_eq!(
            key_row_at(stored.offset(), FULL_PASSES as u32, NKV as u32, BLOCK as u32, HD as u32, 2, 0, 0, 0, 0).unwrap(),
            stored.offset()
        );
        assert_eq!(
            key_row_at(stored.offset(), FULL_PASSES as u32, NKV as u32, BLOCK as u32, HD as u32, 2, 0, 0, 0, 63).unwrap(),
            stored.offset() + 63 * (HD as u64) * 2
        );
        let win_stored = t.get(BlockKind::Window, BlockIndex::new(0)).unwrap().unwrap();
        assert_eq!(win_stored.offset(), byte_offset(BlockKind::Window, slot, 2).unwrap());
        assert_eq!(win_stored.offset(), 2 * WINDOW_STRIDE);
        assert_eq!(
            key_row_at(win_stored.offset(), WINDOW_PASSES as u32, NKV as u32, BLOCK as u32, HD as u32, 2, 0, 0, 0, 1).unwrap(),
            win_stored.offset() + (HD as u64) * 2
        );
        take(&mut full, Slot::new(1).unwrap());
        t.fill(&mut full, BlockIndex::new(1), Slot::new(1).unwrap(), 1).unwrap();
        written(&mut full, Slot::new(1).unwrap(), 64);
        let next = t.get(BlockKind::Full, BlockIndex::new(1)).unwrap().unwrap();
        assert_eq!(next.offset(), byte_offset(BlockKind::Full, Slot::new(1).unwrap(), 2).unwrap());
        assert_eq!(full.gpu_table_entry(next).unwrap(), 0);
    }

    #[test]
    fn a_reused_slot_is_refused_at_the_old_generation() {
        let mut full = BlockPool::new(BlockKind::Full, 4);
        let mut t = BlockTable::new(4).unwrap();
        let slot = Slot::new(3).unwrap();
        take(&mut full, slot);
        t.fill(&mut full, BlockIndex::new(0), slot, 1).unwrap();
        written(&mut full, slot, 1);
        let stored = t.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
        assert_eq!(stored.generation(), 1);
        assert_eq!(full.record_mut(slot).unwrap().bump_generation(), Err(BlockError::Refs));
        assert_eq!(full.record(slot).unwrap().generation(), 1);
        assert_eq!(full.record(slot).unwrap().refs(), 1);
        assert_eq!(full.gpu_table_entry(stored).unwrap(), stored.offset());
        assert_eq!(t.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot(), slot);
    }

    #[test]
    fn a_key_row_is_pass_then_plane_then_head_then_position() {
        let row_at = |base, kind: BlockKind, kvb, pass, plane, head, index| {
            key_row_at(base, kind.passes() as u32, NKV as u32, BLOCK as u32, HD as u32, kvb, pass, plane, head, index)
        };
        let base = byte_offset(BlockKind::Window, Slot::new(1).unwrap(), 2).unwrap();
        assert_eq!(base, 0);
        let old_step = WINDOW_STRIDE / BLOCK as u64;
        assert_eq!(old_step, 163840);
        assert_eq!(row_at(base, BlockKind::Window, 2, 0, 1, 2, 0).unwrap(), old_step);
        assert_eq!(row_at(base, BlockKind::Window, 2, 0, 0, 0, 1).unwrap(), (HD as u64) * 2);
        assert_eq!(row_at(0, BlockKind::Window, 2, 0, 0, 0, 0).unwrap(), 0);
        assert_eq!(row_at(0, BlockKind::Window, 2, 0, 0, 0, 1).unwrap(), 256);
        assert_eq!(row_at(0, BlockKind::Window, 2, 0, 0, 1, 0).unwrap(), 16_384);
        assert_eq!(row_at(0, BlockKind::Window, 2, 0, 1, 2, 0).unwrap(), 163_840);
        let head = (BLOCK as u64) * (HD as u64) * 2;
        assert_eq!(row_at(base, BlockKind::Full, 2, 0, 0, 1, 0).unwrap(), head);
        assert_eq!(row_at(base, BlockKind::Full, 2, 0, 0, 0, 0).unwrap(), 0);
        assert_eq!(row_at(base, BlockKind::Full, 1, 0, 0, 1, 0).unwrap(), head / 2);
        assert_eq!(row_at(0, BlockKind::Window, 1, 1, 1, 3, 7).unwrap(), 222_080);
        assert_eq!(row_at(0, BlockKind::Window, 2, 40, 0, 0, 0), Err(BlockError::OutOfRange));
        assert_eq!(row_at(0, BlockKind::Full, 2, 8, 0, 0, 0), Err(BlockError::OutOfRange));
        assert_eq!(row_at(0, BlockKind::Full, 2, 0, 2, 0, 0), Err(BlockError::OutOfRange));
        assert_eq!(row_at(0, BlockKind::Full, 2, 0, 0, NKV as u32, 0), Err(BlockError::OutOfRange));
        assert_eq!(row_at(0, BlockKind::Full, 0, 0, 0, 0, 0), Err(BlockError::Width));
    }

    #[test]
    fn an_empty_pool_has_no_slots() {
        let mut pools = BlockPools::stub();
        let mut t = BlockTable::new(2).unwrap();
        let err = t.fill(pools.of_mut(BlockKind::Window), BlockIndex::new(0), Slot::new(1).unwrap(), 1).unwrap_err();
        assert_eq!(err, BlockError::NoSlots);
        assert_eq!(err.to_string(), "pool has no slots");
        assert_eq!(pools.full.len(), 0);
        assert_eq!(t.get(BlockKind::Full, BlockIndex::new(0)).unwrap(), None);
        let mut one = BlockPool::new(BlockKind::Full, 1);
        assert_eq!(t.fill(&mut one, BlockIndex::new(0), Slot::new(2).unwrap(), 1), Err(BlockError::OutOfRange));
        let empty_table = BlockTable::empty();
        assert_eq!(empty_table.get(BlockKind::Full, BlockIndex::new(0)), Err(BlockError::OutOfRange));
        let bare = BlockTable::new(4).unwrap();
        assert_eq!(bare.get(BlockKind::Window, BlockIndex::new(0)).unwrap(), None);
        assert_eq!(bare.get(BlockKind::Window, BlockIndex::new(4)), Err(BlockError::OutOfRange));
    }

    #[test]
    fn a_key_offset_is_a_u64_past_the_layer2_base() {
        let index = u32::MAX / (WINDOW_STRIDE as u32) + 1;
        let slot = Slot::new(index + 1).unwrap();
        let mut pool = BlockPool::records_only(BlockKind::Window, (index + 1) as usize, 2).unwrap();
        take(&mut pool, slot);
        let mut t = BlockTable::new(1).unwrap();
        t.fill(&mut pool, BlockIndex::new(0), slot, 1).unwrap();
        written(&mut pool, slot, 1);
        let entry = t.get(BlockKind::Window, BlockIndex::new(0)).unwrap().unwrap();
        let off = key_row_at(entry.offset(), WINDOW_PASSES as u32, NKV as u32, BLOCK as u32, HD as u32, 2, 0, 0, 0, 0).unwrap();
        assert_eq!(off, byte_offset(BlockKind::Window, slot, 2).unwrap());
        assert!(off > u64::from(u32::MAX));
        assert!(u32::try_from(off).is_err());
    }

    #[test]
    fn overwriting_an_entry_drops_the_previous_reference() {
        let mut pool = BlockPool::new(BlockKind::Full, 4);
        let mut t = BlockTable::new(1).unwrap();
        let a = Slot::new(1).unwrap();
        let b = Slot::new(2).unwrap();
        take(&mut pool, a);
        take(&mut pool, b);
        t.fill(&mut pool, BlockIndex::new(0), a, 1).unwrap();
        assert_eq!(pool.record(a).unwrap().refs(), 1);
        t.fill(&mut pool, BlockIndex::new(0), b, 1).unwrap();
        assert_eq!(pool.record(a).unwrap().refs(), 0);
        assert_eq!(pool.record(b).unwrap().refs(), 1);
        t.fill(&mut pool, BlockIndex::new(0), b, 1).unwrap();
        assert_eq!(pool.record(b).unwrap().refs(), 1);
    }

    #[test]
    fn a_fresh_slot_is_not_taken() {
        let mut pool = BlockPool::new(BlockKind::Full, 2);
        let mut t = BlockTable::new(1).unwrap();
        let slot = Slot::new(1).unwrap();
        assert_eq!(t.fill(&mut pool, BlockIndex::new(0), slot, 0), Err(BlockError::NotTaken));
        assert_eq!(pool.record(slot).unwrap().refs(), 0);
        assert_eq!(t.fill(&mut pool, BlockIndex::new(0), slot, 1), Err(BlockError::NotTaken));
        assert_eq!(pool.record(slot).unwrap().refs(), 0);
    }

    #[test]
    fn block_length_bounds_and_seal_state_hold() {
        let mut pool = BlockPool::new(BlockKind::Window, 2);
        let mut t = BlockTable::new(1).unwrap();
        let slot = Slot::new(1).unwrap();
        take(&mut pool, slot);
        t.fill(&mut pool, BlockIndex::new(0), slot, 1).unwrap();
        assert_eq!(pool.record(slot).unwrap().length(), 0);
        written(&mut pool, slot, 3);
        assert_eq!(pool.record(slot).unwrap().length(), 3);
        assert!(!pool.record(slot).unwrap().sealed());
        assert_eq!(pool.record_mut(slot).unwrap().set_length(65), Err(BlockError::Length));
        written(&mut pool, slot, 64);
        assert_eq!(pool.record(slot).unwrap().length(), 64);
        assert!(pool.record(slot).unwrap().sealed());
    }

    #[test]
    fn reissue_waits_for_the_last_reference_and_resets_the_slot() {
        let mut r = SlotRecord::fresh(BlockKind::Window);
        r.reissue().unwrap();
        r.set_length(64).unwrap();
        r.seal();
        r.add_ref().unwrap();
        assert_eq!(r.reissue(), Err(BlockError::Refs));
        assert_eq!((r.generation(), r.length(), r.sealed()), (1, 64, true));
        r.drop_ref().unwrap();
        r.reissue().unwrap();
        assert_eq!((r.generation(), r.length(), r.sealed(), r.refs()), (2, 0, false, 0));
        let mut last = SlotRecord::at_generation(BlockKind::Full, u32::MAX);
        assert_eq!(last.reissue(), Err(BlockError::Generation));
        assert_eq!(last.generation(), u32::MAX);
    }

    #[test]
    fn a_fill_does_not_drop_a_reissued_slot() {
        let mut pool = BlockPool::new(BlockKind::Full, 4);
        let mut lane1 = BlockTable::new(1).unwrap();
        let mut lane2 = BlockTable::new(1).unwrap();
        let a = Slot::new(1).unwrap();
        let b = Slot::new(2).unwrap();
        take(&mut pool, a);
        lane1.fill(&mut pool, BlockIndex::new(0), a, 1).unwrap();
        pool.record_mut(a).unwrap().drop_ref().unwrap();
        pool.record_mut(a).unwrap().reissue().unwrap();
        lane2.fill(&mut pool, BlockIndex::new(0), a, 2).unwrap();
        assert_eq!(pool.record(a).unwrap().refs(), 1);
        take(&mut pool, b);
        lane1.fill(&mut pool, BlockIndex::new(0), b, 1).unwrap();
        assert_eq!(pool.record(a).unwrap().refs(), 1);
        assert_eq!(pool.record(b).unwrap().refs(), 1);
    }

    #[test]
    fn a_fill_refuses_before_it_changes_a_reference() {
        let mut pool = BlockPool::new(BlockKind::Full, 4);
        let mut t = BlockTable::new(1).unwrap();
        let a = Slot::new(1).unwrap();
        let b = Slot::new(2).unwrap();
        take(&mut pool, a);
        take(&mut pool, b);
        t.fill(&mut pool, BlockIndex::new(0), a, 1).unwrap();
        pool.record_mut(b).unwrap().refs = u32::MAX;
        assert_eq!(t.fill(&mut pool, BlockIndex::new(0), b, 1), Err(BlockError::Overflow));
        assert_eq!(pool.record(a).unwrap().refs(), 1);
        assert_eq!(t.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap().slot(), a);
    }

    #[test]
    fn gpu_table_entry_refuses_a_slot_nothing_references() {
        let mut pool = BlockPool::new(BlockKind::Full, 2);
        let mut t = BlockTable::new(1).unwrap();
        let slot = Slot::new(1).unwrap();
        take(&mut pool, slot);
        t.fill(&mut pool, BlockIndex::new(0), slot, 1).unwrap();
        written(&mut pool, slot, 1);
        let entry = t.get(BlockKind::Full, BlockIndex::new(0)).unwrap().unwrap();
        pool.record_mut(slot).unwrap().drop_ref().unwrap();
        assert_eq!(pool.gpu_table_entry(entry), Err(BlockError::Refs));
    }

    fn trace_rows(text: &str, name: &str) -> Vec<(u32, u32, u32, u32, u64)> {
        let start = text.find(&format!("{name} == <<")).expect(name);
        let rest = &text[start..];
        let end = rest.find("\n>>").expect("trace end");
        let mut rows = Vec::new();
        for line in rest[..end].lines() {
            let line = line.trim().trim_end_matches(',');
            if !line.starts_with("<<") { continue; }
            let inner = line.trim_start_matches("<<").trim_end_matches(">>");
            let nums: Vec<u64> = inner.split(',').map(|s| s.trim().parse().unwrap()).collect();
            rows.push((nums[0] as u32, nums[1] as u32, nums[2] as u32, nums[3] as u32, nums[4]));
        }
        rows
    }

    #[test]
    fn key_row_at_matches_the_inblock_trace() {
        let text = include_str!("../specs/InBlockTraceData.tla");
        for (kvb, name) in [(2, "Trace2"), (1, "Trace1")] {
            let rows = trace_rows(text, name);
            assert_eq!(rows.len(), 48);
            for (p, k, h, i, addr) in rows {
                assert_eq!(key_row_at(0, 2, 3, 4, 2, kvb, p, k, h, i).unwrap(), addr);
            }
        }
    }

    #[test]
    fn lowest_free_skips_referenced_and_exhausted_slots_and_set_checks_kind() {
        let mut pools = BlockPools::new(3);
        let one = Slot::new(1).unwrap();
        pools.of_mut(BlockKind::Full).record_mut(one).unwrap().add_ref().unwrap();
        pools.full.slots[1] = SlotRecord::at_generation(BlockKind::Full, u32::MAX);
        assert_eq!(pools.of(BlockKind::Full).lowest_free(), Some(Slot::new(3).unwrap()));
        assert_eq!(pools.of(BlockKind::Window).lowest_free(), Some(one));
        assert_eq!(BlockPool::new(BlockKind::Full, 0).lowest_free(), None);
        let mut t = BlockTable::new(2).unwrap();
        let e = BlockEntry::new(one, 1, 0, BlockKind::Full, 2);
        assert_eq!(t.set(BlockKind::Window, BlockIndex::new(0), Some(e)), Err(BlockError::OutOfRange));
        assert_eq!(t.set(BlockKind::Full, BlockIndex::new(2), Some(e)), Err(BlockError::OutOfRange));
        t.set(BlockKind::Full, BlockIndex::new(1), Some(e)).unwrap();
        assert_eq!(t.entries().map(|(b, e)| (b.get(), e.kind())).collect::<Vec<_>>(), vec![(1, BlockKind::Full)]);
        t.set(BlockKind::Full, BlockIndex::new(1), None).unwrap();
        assert_eq!(t.entries().count(), 0);
        assert_eq!(t.blocks_per_kind(), 2);
    }

    #[test]
    fn dirty_range_initial_full_sync_and_63_clean_decode_steps() {
        let mut pools = BlockPools::new(8);
        let mut t = BlockTable::new(32).unwrap();
        assert!(t.needs_full_sync(BlockKind::Full));
        assert!(t.needs_full_sync(BlockKind::Window));
        assert_eq!(t.dirty_range(BlockKind::Full), Some((0, 31)));
        assert_eq!(t.dirty_range(BlockKind::Window), Some((0, 31)));

        let (sf0, _) = pools.full.take_free().unwrap();
        let (sw0, _) = pools.window.take_free().unwrap();
        t.fill(&mut pools.full, BlockIndex::new(0), sf0, 1).unwrap();
        t.fill(&mut pools.window, BlockIndex::new(0), sw0, 1).unwrap();
        // Still needs full sync until first upload clears it.
        assert_eq!(t.dirty_range(BlockKind::Full), Some((0, 31)));
        assert_eq!(t.dirty_range(BlockKind::Window), Some((0, 31)));

        let mut gpu_full = vec![0xDEAD_BEEF_u64; 32];
        let mut gpu_win = vec![0xCAFE_BABE_u64; 32];
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 32);
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 32);
        assert!(!t.needs_full_sync(BlockKind::Full));
        assert!(!t.needs_full_sync(BlockKind::Window));
        assert_eq!(t.dirty_range(BlockKind::Full), None);
        assert_eq!(t.dirty_range(BlockKind::Window), None);
        assert_eq!(gpu_full[0], 0);
        assert_ne!(gpu_full[0], CLEARED_GPU_TABLE_ENTRY);
        assert!(gpu_full[1..].iter().all(|&w| w == CLEARED_GPU_TABLE_ENTRY));
        assert_eq!(gpu_win[0], 0);
        assert_ne!(gpu_win[0], CLEARED_GPU_TABLE_ENTRY);
        assert!(gpu_win[1..].iter().all(|&w| w == CLEARED_GPU_TABLE_ENTRY));

        // 63 steady-state decode steps inside block 0 write 0 entries to unified memory.
        // Place sentinels to prove `sync_dirty_to_slice` does not touch `dst` at all when clean.
        gpu_full[1] = 0x1111_2222;
        gpu_win[1] = 0x3333_4444;
        for _step in 1..64 {
            assert_eq!(t.dirty_range(BlockKind::Full), None);
            assert_eq!(t.dirty_range(BlockKind::Window), None);
            assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 0);
            assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 0);
        }
        assert_eq!(gpu_full[1], 0x1111_2222);
        assert_eq!(gpu_win[1], 0x3333_4444);
    }

    #[test]
    fn dirty_range_single_allocation_coalescing_and_window_pruning() {
        let mut pools = BlockPools::new(8);
        let mut t = BlockTable::new(32).unwrap();
        let mut gpu_full = vec![0u64; 32];
        let mut gpu_win = vec![0u64; 32];
        // Initial sync on empty table marks every cleared slot with CLEARED_GPU_TABLE_ENTRY and clears dirty flags.
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 32);
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 32);
        assert!(gpu_full.iter().all(|&w| w == CLEARED_GPU_TABLE_ENTRY));
        assert!(gpu_win.iter().all(|&w| w == CLEARED_GPU_TABLE_ENTRY));

        // Allocate block 0 for both kinds (e.g. token 0): Slot(1) in slab 0 encodes as 0 != CLEARED_GPU_TABLE_ENTRY.
        let (sf0, _) = pools.full.take_free().unwrap();
        let (sw0, _) = pools.window.take_free().unwrap();
        t.fill(&mut pools.full, BlockIndex::new(0), sf0, 1).unwrap();
        t.fill(&mut pools.window, BlockIndex::new(0), sw0, 1).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Full), Some((0, 0)));
        assert_eq!(t.dirty_range(BlockKind::Window), Some((0, 0)));
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 1);
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 1);
        assert_eq!(gpu_full[0], 0);
        assert_eq!(gpu_win[0], 0);

        // Allocate single new block at index 1 (token 64).
        let (sf1, off_f1) = pools.full.take_free().unwrap();
        let (sw1, off_w1) = pools.window.take_free().unwrap();
        t.fill(&mut pools.full, BlockIndex::new(1), sf1, 1).unwrap();
        t.fill(&mut pools.window, BlockIndex::new(1), sw1, 1).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Full), Some((1, 1)));
        assert_eq!(t.dirty_range(BlockKind::Window), Some((1, 1)));

        // Re-filling the exact same entry is a no-op and does not expand the dirty range.
        t.fill(&mut pools.full, BlockIndex::new(0), sf0, 1).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Full), Some((1, 1)));
        // Failed fill (stale generation) does not dirty.
        assert_eq!(t.fill(&mut pools.full, BlockIndex::new(5), sf1, 99), Err(BlockError::Stale));
        assert_eq!(t.dirty_range(BlockKind::Full), Some((1, 1)));

        gpu_full[0] = 0xAAAA;
        gpu_full[2] = 0xBBBB;
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 1);
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 1);
        assert_eq!(gpu_full[0], 0xAAAA); // untouched
        assert_eq!(gpu_full[1], off_f1);
        assert_eq!(gpu_full[2], 0xBBBB); // untouched
        assert_eq!(gpu_win[1], off_w1);

        // Window block pruning: clearing window block 0 dirties ONLY window block 0 and writes CLEARED_GPU_TABLE_ENTRY.
        gpu_win[0] = 0x9999;
        t.clear_kind_entry(&mut pools.window, BlockIndex::new(0)).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Full), None);
        assert_eq!(t.dirty_range(BlockKind::Window), Some((0, 0)));
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 1);
        assert_eq!(gpu_win[0], CLEARED_GPU_TABLE_ENTRY);
        assert_eq!(gpu_win[1], off_w1);
        // Clearing an already-empty entry is a no-op (stays clean).
        t.clear_kind_entry(&mut pools.window, BlockIndex::new(0)).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Window), None);

        // Coalesced range: mutate block 5 then block 2 -> [2..=5] (4 entries).
        let (sf5, off_f5) = pools.full.take_free().unwrap();
        t.fill(&mut pools.full, BlockIndex::new(5), sf5, 1).unwrap();
        let (sf2, off_f2) = pools.full.take_free().unwrap();
        t.fill(&mut pools.full, BlockIndex::new(2), sf2, 1).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Full), Some((2, 5)));
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 4);
        assert_eq!(gpu_full[2], off_f2);
        assert_eq!(gpu_full[3], CLEARED_GPU_TABLE_ENTRY);
        assert_eq!(gpu_full[4], CLEARED_GPU_TABLE_ENTRY);
        assert_eq!(gpu_full[5], off_f5);
    }

    #[test]
    fn dirty_range_full_reset_and_rebind() {
        let mut pools = BlockPools::new(8);
        let mut t = BlockTable::new(16).unwrap();
        let mut gpu_full = vec![0u64; 16];
        let mut gpu_win = vec![0u64; 16];

        let (sf0, _) = pools.full.take_free().unwrap();
        t.fill(&mut pools.full, BlockIndex::new(0), sf0, 1).unwrap();
        let (sf1, off_f1) = pools.full.take_free().unwrap();
        t.fill(&mut pools.full, BlockIndex::new(1), sf1, 1).unwrap();
        let (sw0, _) = pools.window.take_free().unwrap();
        t.fill(&mut pools.window, BlockIndex::new(0), sw0, 1).unwrap();
        let (sw1, off_w1) = pools.window.take_free().unwrap();
        t.fill(&mut pools.window, BlockIndex::new(1), sw1, 1).unwrap();
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 16);
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 16);
        assert_eq!(gpu_full[1], off_f1);
        assert_eq!(gpu_win[1], off_w1);

        // Full reset via `clear_entries` triggers full sync on both kinds.
        t.clear_entries(&mut pools).unwrap();
        assert!(t.needs_full_sync(BlockKind::Full));
        assert!(t.needs_full_sync(BlockKind::Window));
        assert_eq!(t.dirty_range(BlockKind::Full), Some((0, 15)));
        assert_eq!(t.dirty_range(BlockKind::Window), Some((0, 15)));
        assert_eq!(pools.full.record(sf0).unwrap().refs(), 0);
        assert_eq!(pools.full.record(sf1).unwrap().refs(), 0);

        // Rebind a single prefix block (block 0) before the next sync: still does full sync so stale
        // GPU slot 1 from the previous request is overwritten with CLEARED_GPU_TABLE_ENTRY!
        t.fill(&mut pools.full, BlockIndex::new(0), sf0, 1).unwrap();
        t.fill(&mut pools.window, BlockIndex::new(0), sw0, 1).unwrap();
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Full, &pools.full, &mut gpu_full).unwrap(), 16);
        assert_eq!(t.sync_dirty_to_slice(BlockKind::Window, &pools.window, &mut gpu_win).unwrap(), 16);
        assert_eq!(gpu_full[0], 0);
        assert_eq!(gpu_full[1], CLEARED_GPU_TABLE_ENTRY);
        assert_eq!(gpu_win[0], 0);
        assert_eq!(gpu_win[1], CLEARED_GPU_TABLE_ENTRY);
        assert_eq!(t.dirty_range(BlockKind::Full), None);
        assert_eq!(t.dirty_range(BlockKind::Window), None);

        // Direct `set` mutation vs no-op `set`.
        let e = BlockEntry::new(sf1, 1, off_f1, BlockKind::Full, 2);
        t.set(BlockKind::Full, BlockIndex::new(3), None).unwrap(); // already None -> no-op
        assert_eq!(t.dirty_range(BlockKind::Full), None);
        t.set(BlockKind::Full, BlockIndex::new(3), Some(e)).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Full), Some((3, 3)));
        t.set(BlockKind::Full, BlockIndex::new(3), Some(e)).unwrap(); // same value -> stays (3, 3)
        t.set(BlockKind::Full, BlockIndex::new(3), None).unwrap();
        assert_eq!(t.dirty_range(BlockKind::Full), Some((3, 3)));
    }

    #[test]
    #[ignore = "slow: runs in nightly unit-extras"]
    #[cfg(not(standalone_blocks))]
    fn metal_in_slot_formula_matches_key_row_and_inblock_trace_across_full_and_window() {
        let kernels_src = include_str!("kernels.metal");
        let prefill_src = include_str!("prefill.metal");
        let layout = parse_metal_kv_layout(kernels_src, prefill_src).unwrap();
        assert_eq!(layout.nkv, NKV as u32);
        assert_eq!(layout.hd, HD as u32);
        assert_eq!(layout.kv_blk, BLOCK as u32);
        assert_eq!(layout.kv_blk_mask, (BLOCK - 1) as u32);
        assert_eq!(layout.planes_per_pass, 2);
        assert_eq!(layout.slab_shift, KV_SLAB_SHIFT);
        assert_eq!(layout.slab_buffers, [3, 10, 11, 12]);

        // Exhaustively check all 8,192 Full coordinates and 40,960 Window coordinates at fp16 and KV8.
        for kvb in [2u32, 1u32] {
            for kind in [BlockKind::Full, BlockKind::Window] {
                let stride = kind.stride_bytes(kvb).unwrap();
                let mut prev = None;
                for pass in 0..(kind.passes() as u32) {
                    for kv in [Kv::Key, Kv::Value] {
                        for head in 0..(NKV as u32) {
                            for blk in [0u32, 17u32] {
                                for ib in 0..(BLOCK as u32) {
                                    let stream_pos = blk * (BLOCK as u32) + ib;
                                    let got = metal_in_slot_byte_offset_from_layout(
                                        &layout, kind, kvb, pass, kv, head, stream_pos,
                                    )
                                    .unwrap();
                                    let want = key_row(0, kind, kvb, pass, kv, head, ib).unwrap();
                                    assert_eq!(got, want);
                                    assert!(got + (HD as u64) * u64::from(kvb) <= stride);
                                    if blk == 0 {
                                        if let Some(p) = prev {
                                            assert_eq!(got - p, (HD as u64) * u64::from(kvb));
                                        }
                                        prev = Some(got);
                                    }
                                }
                            }
                        }
                    }
                }
                assert_eq!(
                    prev.unwrap() + (HD as u64) * u64::from(kvb),
                    stride,
                    "last row in {kind:?} at kvb={kvb} must end exactly at slot stride"
                );
            }
        }

        // Verify `specs/InBlockTraceData.tla` matches `write_inblock_trace` and `metal_in_slot_byte_offset`.
        let trace_text = include_str!("../specs/InBlockTraceData.tla");
        for (name, kind, kvb, expected_len) in [
            ("MetalFull2", BlockKind::Full, 2u32, 240usize),
            ("MetalFull1", BlockKind::Full, 1u32, 240usize),
            ("MetalWin2", BlockKind::Window, 2u32, 1200usize),
            ("MetalWin1", BlockKind::Window, 1u32, 1200usize),
        ] {
            let rows = trace_rows(trace_text, name);
            assert_eq!(rows.len(), expected_len, "{name} row count");
            for (p, k, h, i, addr) in rows {
                let plane = if k == 0 { Kv::Key } else { Kv::Value };
                assert_eq!(metal_in_slot_byte_offset(kind, kvb, p, plane, h, i).unwrap(), addr);
                assert_eq!(key_row(0, kind, kvb, p, plane, h, i).unwrap(), addr);
            }
        }

        // Planted shader macro & buffer-binding mutations MUST fail `parse_metal_kv_layout`.
        assert!(parse_metal_kv_layout(
            &kernels_src.replacen("#define KV_PASS_BYTES  (2UL * KV_PLANE_BYTES)", "#define KV_PASS_BYTES  KV_PLANE_BYTES", 1),
            prefill_src,
        ).is_err());
        assert!(parse_metal_kv_layout(
            &kernels_src.replacen("#define KV_SLAB_MASK ((1UL << 62) - 1UL)", "#define KV_SLAB_MASK ((1UL << 60) - 1UL)", 1),
            prefill_src,
        ).is_err());
        assert!(parse_metal_kv_layout(
            kernels_src,
            &prefill_src.replacen("KV1 [[buffer(10)]]", "KV1 [[buffer(9)]]", 1),
        ).is_err());
    }

    #[test]
    fn multi_slab_gpu_table_entry_packs_all_four_slabs_decodes_shader_ptr_and_refuses_overflow() {
        // 1. Allocate across all 4 slabs (`KV0..KV3`, 2 slots per slab -> 8 slots total) at fp16 and KV8.
        for kvb in [2u32, 1u32] {
            let stride = stride_at(BlockKind::Full, kvb).unwrap();
            let mut pool = BlockPool::open_host(BlockKind::Full, 0, kvb, stride * 2).unwrap();
            let mut table = BlockTable::new(8).unwrap();
            let mut slots = Vec::new();
            for bi in 0..8u32 {
                let (slot, logical_off) = pool.take_free().unwrap();
                assert_eq!(logical_off, u64::from(bi) * stride);
                let gen = pool.record(slot).unwrap().generation();
                table.fill(&mut pool, BlockIndex::new(bi), slot, gen).unwrap();
                // Stamp a unique 8-byte tag at the start and end of each slot's backing storage.
                let tag = 0xA500_0000_0000_0000u64 | (u64::from(kvb) << 16) | u64::from(bi + 1);
                let sb = pool.slot_bytes_mut(slot).unwrap();
                sb[..8].copy_from_slice(&tag.to_le_bytes());
                let end = sb.len() - 8;
                sb[end..].copy_from_slice(&(tag ^ 0xFFFF).to_le_bytes());
                slots.push(slot);
            }
            assert_eq!(pool.slab_count(), MAX_SLABS);
            // A 9th slot requires a 5th slab (`KV4`), which MUST be refused with `BlockError::Slab`.
            assert_eq!(pool.grow(), Err(BlockError::Slab));

            // Upload all 8 entries via `sync_dirty_to_slice` and decode every word with `kv_blk_ptr` bit logic.
            let mut gpu_bt = vec![0u64; 8];
            assert_eq!(table.sync_dirty_to_slice(BlockKind::Full, &pool, &mut gpu_bt).unwrap(), 8);

            // Collect raw slab base slices (`s0, s1, s2, s3` bound at buffers `3, 10, 11, 12`).
            assert_eq!(KV_SLAB_BUFFER_INDICES, [3, 10, 11, 12]);
            for (bi, &word) in gpu_bt.iter().enumerate().take(8usize) {
                let expected_slab = bi / 2;
                let expected_off = ((bi % 2) as u64) * stride;
                assert_eq!(word, ((expected_slab as u64) << 62) | expected_off);
                let (si, off) = decode_gpu_table_entry(word);
                assert_eq!(si, expected_slab);
                assert_eq!(off, expected_off);
                assert!(off + stride <= stride * 2);

                // Verify `base + off + in_slot_off` resolves to the exact stamped slot without aliasing.
                let slab_first_slot = slots[si * 2];
                let (s_ptr, _) = pool.slot_raw_region(slab_first_slot).unwrap();
                let resolved_start = unsafe { std::slice::from_raw_parts(s_ptr.add(off as usize), 8) };
                let resolved_end = unsafe {
                    std::slice::from_raw_parts(s_ptr.add((off + stride - 8) as usize), 8)
                };
                let want_tag = 0xA500_0000_0000_0000u64 | (u64::from(kvb) << 16) | ((bi as u64) + 1);
                assert_eq!(u64::from_le_bytes(resolved_start.try_into().unwrap()), want_tag);
                assert_eq!(u64::from_le_bytes(resolved_end.try_into().unwrap()), want_tag ^ 0xFFFF);
            }
        }

        // 2. Boundary & 62-bit overflow checks on `gpu_table_entry` (`NoOffsetClobbersSlab` in `SlabWord.tla`).
        let stride = FULL_STRIDE; // 2 MiB (`1 << 21`)
        let max_valid_within = ((1u64 << KV_SLAB_SHIFT) / stride - 1) as usize; // `(1 << 41) - 1`
        let overflow_within = (1u64 << KV_SLAB_SHIFT) / stride; // `1 << 41` -> `off == 1 << 62`!
        let slots_per_slab = (overflow_within as usize) + 2;

        // Construct a lightweight metadata-only pool at the 62-bit boundary (`slab = 1` and `slab = 2`).
        let boundary_slots = vec![
            (0usize, max_valid_within),                  // slab 0, highest valid 62-bit offset `(1<<62) - 2 MiB`
            (1usize, max_valid_within),                  // slab 1, highest valid 62-bit offset
            (2usize, overflow_within as usize),          // slab 2, `off == 1<<62` -> MUST refuse `Overflow`!
        ];
        for (slab_i, within_i) in boundary_slots {
            // Shift `slots` sparse window by testing a 1-slot custom `BlockPool` via `slots_per_slab`?
            // Note `i = slot.pool_index()`, so for `slab = 0` at `max_valid_within` we can test directly
            // with a custom `stride` where `slots_per_slab = 4`:
            let _ = (slab_i, within_i, slots_per_slab);
        }
        let half_limit = 1u64 << 61; // 2 EiB stride -> within=0 is 0, within=1 is 2 EiB (< 2^62), within=2 is 4 EiB (== 2^62)!
        let mut synthetic = BlockPool {
            kind: BlockKind::Full,
            kvb: 2,
            stride: half_limit,
            slots_per_slab: 3, // within \in {0, 1, 2}, where within=2 hits `1 << 62`!
            slots: vec![SlotRecord::fresh(BlockKind::Full); 12],
            slabs: Vec::new(),
            with_sketches: false,
            sketch_slab: None,
            sketch_valid_len: Vec::new(),
            sketch_epoch: Vec::new(),
            #[cfg(not(standalone_blocks))]
            device: None,
            gpu_zero_pending: vec![false; 12],
        };
        for idx in 1..=12u32 {
            let s = Slot::new(idx).unwrap();
            synthetic.record_mut(s).unwrap().bump_generation().unwrap();
            synthetic.record_mut(s).unwrap().add_ref().unwrap();
        }
        // For every slab 0..4: `within = 0` and `within = 1` (`off = 1 << 61`) succeed and preserve `slab << 62`,
        // while `within = 2` (`off = 1 << 62`) is refused with `BlockError::Overflow`!
        for slab in 0..MAX_SLABS {
            for within in 0..3usize {
                let s = Slot::new((slab * 3 + within + 1) as u32).unwrap();
                let entry = BlockEntry::new(s, 1, 0, BlockKind::Full, 2);
                let res = synthetic.gpu_table_entry(entry);
                if within < 2 {
                    let word = res.expect("valid < 2^62 offset");
                    assert_eq!(decode_gpu_table_entry(word), (slab, (within as u64) * half_limit));
                } else {
                    assert_eq!(res, Err(BlockError::Overflow), "offset >= 2^62 must be refused");
                }
            }
        }
        // Also verify `within * stride` wrapping past `2^64` is caught via `checked_mul` -> `BlockError::Overflow`.
        synthetic.stride = (1u64 << 63) + 1024; // within=2 would wrap modulo 2^64 to `2048 < 2^62` without checked_mul!
        let wrap_slot = Slot::new(3).unwrap(); // i = 2 -> within = 2
        let wrap_entry = BlockEntry::new(wrap_slot, 1, 0, BlockKind::Full, 2);
        assert_eq!(synthetic.gpu_table_entry(wrap_entry), Err(BlockError::Overflow));
    }

    #[test]
    fn span_window_blocks_and_table_pinning_reach_25_at_worst_alignment() {
        let mut pools = BlockPools::new(32);
        let mut tbl = BlockTable::new(32).unwrap();
        for b in 0..32u32 {
            let slot = Slot::new(b + 1).unwrap();
            let _ = pools.full.take(slot).unwrap();
            let _ = pools.window.take(slot).unwrap();
            tbl.fill(&mut pools.full, BlockIndex::new(b), slot, 1).unwrap();
            tbl.fill(&mut pools.window, BlockIndex::new(b), slot, 1).unwrap();
        }
        let mut max_win = 0usize;
        for offset in 0..BLOCK {
            let pos = (WINDOW - 1) + offset;
            let win_blks = span_window_blocks(pos, 512).unwrap();
            let pinned = tbl.pinned_span_entries(pos, 512).unwrap();
            let table_win: Vec<u32> = pinned
                .iter()
                .filter(|(k, _, _)| *k == BlockKind::Window)
                .map(|(_, bi, _)| bi.get())
                .collect();
            let direct_win: Vec<u32> = win_blks.iter().map(|bi| bi.get()).collect();
            assert_eq!(table_win, direct_win);
            assert!(table_win.len() <= 25, "alignment {offset} exceeded 25 window blocks");
            max_win = max_win.max(table_win.len());
            if offset == BLOCK - 1 {
                let expected: Vec<u32> = (0..=24).collect();
                assert_eq!(table_win, expected, "offset 63 must pin blocks 0..=24 (25 blocks, not 17)");
            }
        }
        assert_eq!(max_win, 25);
        assert_eq!(span_window_blocks(0, 0), Err(BlockError::OutOfRange));
    }

    #[test]
    fn cleared_gpu_table_entry_is_distinct_from_slab_zero_first_slot() {
        // Multi-slab pool across all 4 slabs: neither slab 0 Slot(1) (`0`) nor any other slot in slabs 0..4
        // ever encodes as CLEARED_GPU_TABLE_ENTRY (`u64::MAX`).
        let mut pool = BlockPool::open(BlockKind::Full, 0, KVB_FP16, FULL_STRIDE * 2, None).unwrap();
        let mut table = BlockTable::new(8).unwrap();
        for b in 0..8u32 {
            let slot = pool.grow().unwrap();
            let off = pool.take(slot).unwrap();
            let gen = pool.record(slot).unwrap().generation();
            table.fill(&mut pool, BlockIndex::new(b), slot, gen).unwrap();
            let entry = BlockEntry::new(slot, gen, off, BlockKind::Full, KVB_FP16);
            let word = pool.gpu_table_entry(entry).unwrap();
            if slot.get() == 1 {
                assert_eq!(word, 0, "slab 0 Slot(1) encodes as 0");
            }
            assert_ne!(word, CLEARED_GPU_TABLE_ENTRY);
        }
    }

    #[test]
    fn grouped_tile_walker_matches_private_key_and_partial_references_and_decode_groups() {
        // Scaled model bounds (GroupedLayout.tla: BlockSize=2, TileSize=2, SplitSize=4, WindowSize=3, Capacity=4)
        for l1 in 1..=8usize {
            for l2 in 1..=8usize {
                let max_shared = l1.min(l2) / 2;
                for shared in 0..=max_shared {
                    let mut resident = std::collections::BTreeSet::new();
                    for b in 0..=((l1 - 1) / 2) {
                        resident.insert((b, 1usize));
                    }
                    for b in 0..=((l2 - 1) / 2) {
                        resident.insert((b, if b < shared { 1 } else { 2 }));
                    }
                    if resident.len() > 4 {
                        continue;
                    }
                    for windowed in [false, true] {
                        let trace = walk_grouped_tiles([l1, l2], shared, windowed, 2, 2, 4, 3);
                        let last = trace.last().unwrap();
                        for (r, &len) in [l1, l2].iter().enumerate() {
                            let first = if windowed { len.saturating_sub(3) } else { 0 };
                            let want_visits: Vec<_> = (first..len)
                                .map(|p| {
                                    let b = p / 2;
                                    (p, (b, if b < shared { 1 } else { r + 1 }), p / 4)
                                })
                                .collect();
                            assert_eq!(last.visits[r], want_visits);
                            let sp_a = first / 4;
                            let sp_b = (len - 1) / 4;
                            let want_partials: Vec<_> = (sp_a..=sp_b)
                                .map(|s| (s, ((s + 1) * 4).min(len) - 1))
                                .collect();
                            assert_eq!(last.partials[r], want_partials);
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn grow_by_rejected_past_max_slabs_leaves_pool_intact_for_subsequent_growth() {
        let stride = stride_at(BlockKind::Full, 2).unwrap();
        let max_slots = MAX_SLABS * 2;
        let mut pool = BlockPool::open_host(BlockKind::Full, 0, 2, stride * 2).unwrap();

        // Reject oversized growth from an empty pool without allocating partial slabs.
        assert_eq!(pool.grow_by(max_slots + 1), Err(BlockError::Slab));
        assert_eq!(pool.len(), 0);
        assert_eq!(pool.slab_count(), 0);

        // Overflowing count must also leave the pool unchanged.
        assert_eq!(pool.grow_by(usize::MAX), Err(BlockError::Overflow));
        assert_eq!(pool.len(), 0);
        assert_eq!(pool.slab_count(), 0);

        // Subsequent single-slot and batch growth must succeed cleanly.
        let s1 = pool.grow().unwrap();
        assert_eq!(s1.pool_index().get(), 0);
        assert_eq!(pool.len(), 1);
        assert_eq!(pool.slab_count(), 1);

        // Reject oversized growth from a partially populated pool without leaking slabs 1..MAX_SLABS.
        assert_eq!(pool.grow_by(max_slots), Err(BlockError::Slab));
        assert_eq!(pool.len(), 1);
        assert_eq!(pool.slab_count(), 1);

        // Growing up to exact capacity across all MAX_SLABS succeeds, then one more is rejected cleanly.
        pool.grow_by(1).unwrap();
        assert_eq!(pool.len(), 2);
        assert_eq!(pool.slab_count(), 1);
        pool.grow_by(max_slots - 2).unwrap();
        assert_eq!(pool.len(), max_slots);
        assert_eq!(pool.slab_count(), MAX_SLABS);
        assert_eq!(pool.grow(), Err(BlockError::Slab));
        assert_eq!(pool.grow_by(1), Err(BlockError::Slab));
        assert_eq!(pool.len(), max_slots);
        assert_eq!(pool.slab_count(), MAX_SLABS);
    }

    #[test]
    fn kv4_mode_strides_pools_tables_and_in_slot_offsets() {
        assert_eq!(KV4_ROW_BYTES, 66);
        assert_eq!(KV4_FULL_STRIDE, 540_672);
        assert_eq!(KV4_WINDOW_STRIDE, 2_703_360);
        assert_eq!(KvMode::from_flags(false, false), Ok(KvMode::Fp16));
        assert_eq!(KvMode::from_flags(true, false), Ok(KvMode::Kv8));
        assert_eq!(KvMode::from_flags(false, true), Ok(KvMode::Kv4));
        assert_eq!(KvMode::from_flags(true, true), Err(BlockError::Kvb));
        assert_eq!(KvMode::Fp16.stride_bytes(BlockKind::Full), FULL_STRIDE);
        assert_eq!(KvMode::Fp16.stride_bytes(BlockKind::Window), WINDOW_STRIDE);
        assert_eq!(KvMode::Kv8.stride_bytes(BlockKind::Full), FULL_STRIDE / 2);
        assert_eq!(KvMode::Kv8.stride_bytes(BlockKind::Window), WINDOW_STRIDE / 2);
        assert_eq!(KvMode::Kv4.stride_bytes(BlockKind::Full), KV4_FULL_STRIDE);
        assert_eq!(KvMode::Kv4.stride_bytes(BlockKind::Window), KV4_WINDOW_STRIDE);

        let mut pools = BlockPools::with_capacities_mode(2, 2, KvMode::Kv4).unwrap();
        assert_eq!(pools.full.kvb(), KVB_KV4);
        assert_eq!(pools.window.kvb(), KVB_KV4);
        assert_eq!(pools.full.mode(), Ok(KvMode::Kv4));
        assert_eq!(pools.window.mode(), Ok(KvMode::Kv4));
        assert_eq!(pools.full.stride_bytes(), KV4_FULL_STRIDE);
        assert_eq!(pools.window.stride_bytes(), KV4_WINDOW_STRIDE);

        let mut tbl = BlockTable::new(4).unwrap();
        let (s1, off1) = pools.full.take_free().unwrap();
        assert_eq!(off1, 0);
        tbl.fill(&mut pools.full, BlockIndex::new(0), s1, 1).unwrap();
        let (s2, off2) = pools.full.take_free().unwrap();
        assert_eq!(off2, KV4_FULL_STRIDE);
        assert_eq!(pools.full.slot_bytes(s2).unwrap().len(), KV4_FULL_STRIDE as usize);
        tbl.fill(&mut pools.full, BlockIndex::new(1), s2, 1).unwrap();
        let e2 = tbl.get(BlockKind::Full, BlockIndex::new(1)).unwrap().unwrap();
        assert_eq!(e2.offset(), KV4_FULL_STRIDE);
        assert_eq!(e2.kvb(), KVB_KV4);
        assert_eq!(pools.full.gpu_table_entry(e2).unwrap(), KV4_FULL_STRIDE);

        // Width mismatch with an FP16 pool is rejected.
        let fp16_pool = BlockPool::new(BlockKind::Full, 2);
        assert_eq!(fp16_pool.gpu_table_entry(e2), Err(BlockError::Width));

        // Verify within-slot byte offsets pack 66-byte rows tightly up to exact stride_bytes.
        let last_full = metal_in_slot_byte_offset_mode(
            BlockKind::Full,
            KvMode::Kv4,
            (FULL_PASSES - 1) as u32,
            Kv::Value,
            (NKV - 1) as u32,
            (BLOCK - 1) as u32,
        )
        .unwrap();
        assert_eq!(last_full + KV4_ROW_BYTES, KV4_FULL_STRIDE);
        let last_win = metal_in_slot_byte_offset_mode(
            BlockKind::Window,
            KvMode::Kv4,
            (WINDOW_PASSES - 1) as u32,
            Kv::Value,
            (NKV - 1) as u32,
            (BLOCK - 1) as u32,
        )
        .unwrap();
        assert_eq!(last_win + KV4_ROW_BYTES, KV4_WINDOW_STRIDE);
    }

    #[test]
    #[cfg(not(standalone_blocks))]
    fn kv4_layout_trace_matches_committed_tla_data_and_metal_offsets() {
        let committed = include_str!("../specs/Kv4LayoutTraceData.tla");
        let tmp = std::env::temp_dir().join(format!("inky-kv4-trace-{}.tla", std::process::id()));
        write_kv4_layout_trace(tmp.to_str().unwrap()).unwrap();
        let fresh = std::fs::read_to_string(&tmp).unwrap();
        let _ = std::fs::remove_file(&tmp);
        assert_eq!(fresh, committed, "specs/Kv4LayoutTraceData.tla must stay in sync with write_kv4_layout_trace");

        // Spot-check kv4_key_row and kv4_dc_mean_offset bounds and exact correspondence with Metal KV4 formula.
        assert_eq!(kv4_key_row(0, BlockKind::Full, 8, Kv::Key, 0, 0), Err(BlockError::OutOfRange));
        assert_eq!(kv4_key_row(0, BlockKind::Full, 0, Kv::Key, 8, 0), Err(BlockError::OutOfRange));
        assert_eq!(kv4_key_row(0, BlockKind::Full, 0, Kv::Key, 0, 64), Err(BlockError::OutOfRange));
        assert_eq!(kv4_dc_mean_offset(48, 0), Err(BlockError::OutOfRange));
        assert_eq!(kv4_dc_mean_offset(0, 8), Err(BlockError::OutOfRange));
        assert_eq!(kv4_dc_mean_offset(47, 7), Ok(98_048));

        for (kind, passes) in [(BlockKind::Full, FULL_PASSES), (BlockKind::Window, WINDOW_PASSES)] {
            let stride = KvMode::Kv4.stride_bytes(kind);
            for slot in [0u32, 2] {
                for p in [0u32, (passes - 1) as u32] {
                    for kv in [Kv::Key, Kv::Value] {
                        for h in [0u32, 7] {
                            for pos in [0u32, 1, 63] {
                                let (nib, sc) = kv4_key_row(slot, kind, p, kv, h, pos).unwrap();
                                let in_slot = metal_in_slot_byte_offset_mode(kind, KvMode::Kv4, p, kv, h, pos).unwrap();
                                assert_eq!(nib, u64::from(slot) * stride + in_slot);
                                assert_eq!(sc, nib + 64);
                                assert_eq!(sc % 2, 0);
                            }
                        }
                    }
                }
            }
        }

        // Verify `parse_metal_kv_layout` binds directly to `src/kernels.metal` KV4 definitions and rejects mutations.
        let kernels_src = include_str!("kernels.metal");
        let prefill_src = include_str!("prefill.metal");
        let layout = parse_metal_kv_layout(kernels_src, prefill_src).unwrap();
        assert_eq!(layout.kv4_nibble_bytes, 64);
        assert_eq!(layout.kv4_scale_bytes, 2);
        assert_eq!(layout.kv4_row_bytes, 66);
        assert_eq!(layout.kv4_grp_tile_ushorts, 32 * 33);
        for (needle, replacement) in [
            ("uchar qs[64];", "uchar qs[62];"),
            ("static_assert(sizeof(kv4_row) == 66,", "static_assert(sizeof(kv4_row) == 64,"),
            ("#define KV_ROW_STEP    1u", "#define KV_ROW_STEP    128u"),
            ("for (uint i = tid; i < 32u * 33u; i += 512u)", "for (uint i = tid; i < 32u * 32u; i += 512u)"),
        ] {
            assert!(kernels_src.contains(needle), "expected needle `{needle}` in kernels.metal");
            let mutated = kernels_src.replacen(needle, replacement, 1);
            assert!(
                parse_metal_kv_layout(&mutated, prefill_src).is_err(),
                "mutating `{needle}` -> `{replacement}` must fail parse_metal_kv_layout"
            );
        }
    }

    #[test]
    fn kv4_cpu_wht_orthonormality_rademacher_orthogonality_lm4_and_pack_roundtrip() {
        // 1. WHT-128 involution (`WHT(WHT(x)) == x`) & rotated inner-product invariance (`<WHT(D*x), WHT(D*y)> == <x, y>`).
        let mut x = [0.0f32; HD];
        let mut y = [0.0f32; HD];
        for d in 0..HD {
            x[d] = ((d as f32 * 0.37).sin() * 2.5) + ((d as f32 * 1.13).cos() * 0.7);
            y[d] = ((d as f32 * 0.71).cos() * 1.9) - ((d as f32 * 0.29).sin() * 1.1);
        }
        let x_rot = wht128_cpu(&x);
        let x_back = wht128_cpu(&x_rot);
        for d in 0..HD {
            assert!((x_back[d] - x[d]).abs() < 1e-5, "WHT involution drift at {d}: {} vs {}", x_back[d], x[d]);
        }
        let dot_raw: f32 = x.iter().zip(&y).map(|(&a, &b)| a * b).sum();
        for (slot2, g) in [(0u32, 0u32), (17, 3), (95, 7)] {
            let mut dx = [0.0f32; HD];
            let mut dy = [0.0f32; HD];
            for d in 0..HD {
                let s = kv4_rademacher(slot2, g, d as u32);
                dx[d] = s * x[d];
                dy[d] = s * y[d];
            }
            let wx = wht128_cpu(&dx);
            let wy = wht128_cpu(&dy);
            let dot_rot: f32 = wx.iter().zip(&wy).map(|(&a, &b)| a * b).sum();
            assert!((dot_rot - dot_raw).abs() < 1e-4, "dot mismatch ({slot2},{g}): {dot_rot} vs {dot_raw}");
        }

        // 2. Collision-free Rademacher signs across all `96 * 8 = 768` `(slot2, g)` rows:
        //    zero duplicate/negated/cyclic-shifted rows, and bounded pairwise correlation (`|dot| <= 56 << 128`).
        let mut masks = Vec::with_capacity(96 * NKV);
        let mut canon_orbits = std::collections::HashSet::with_capacity(96 * NKV);
        for slot2 in 0..96u32 {
            for g in 0..(NKV as u32) {
                let mut m = 0u128;
                for d in 0..HD {
                    if kv4_rademacher(slot2, g, d as u32) < 0.0 {
                        m |= 1u128 << d;
                    }
                }
                // Balanced per row (not degenerate).
                let ones = m.count_ones();
                assert!((36..=92).contains(&ones), "unbalanced Rademacher row ({slot2},{g}): ones={ones}");
                // Canonical representative under all 128 cyclic rotations and sign negation (`!m`).
                let mut canon = u128::MAX;
                for shift in 0..128u32 {
                    let r = m.rotate_left(shift);
                    canon = canon.min(r).min(!r);
                }
                assert!(
                    canon_orbits.insert(canon),
                    "duplicate, negated, or cyclic-shifted Rademacher row at ({slot2},{g})"
                );
                masks.push(m);
            }
        }
        assert_eq!(masks.len(), 768);
        let mut max_abs_dot = 0i32;
        for i in 0..masks.len() {
            let mi = masks[i];
            for &mj in &masks[i + 1..] {
                let diff = (mi ^ mj).count_ones() as i32;
                let dot = (128 - 2 * diff).abs();
                max_abs_dot = max_abs_dot.max(dot);
            }
        }
        assert!(max_abs_dot <= 56, "pairwise Rademacher |dot| too high: {max_abs_dot}");

        // 3. `kv4_lm4_idx_cpu` monotonicity & exact decision-threshold boundaries.
        let mut prev_idx = 0u8;
        for k in 0..=2000 {
            let z = -5.0 + (k as f32) * 0.005;
            let idx = kv4_lm4_idx_cpu(z);
            assert!(idx < 16);
            assert!(idx >= prev_idx, "non-monotonic kv4_lm4_idx_cpu at z={z}: {idx} < {prev_idx}");
            prev_idx = idx;
        }
        assert_eq!(kv4_lm4_idx_cpu(0.0), 8);
        assert_eq!(kv4_lm4_idx_cpu(-0.0), 8);
        assert_eq!(kv4_lm4_idx_cpu(f32::NAN), 8);
        for (ti, &thr) in KV4_LM4_THR.iter().enumerate() {
            assert_eq!(kv4_lm4_idx_cpu(thr - 1e-5), ti as u8, "below threshold {ti} ({thr})");
            assert_eq!(kv4_lm4_idx_cpu(thr + 1e-5), (ti + 1) as u8, "above threshold {ti} ({thr})");
        }

        // 4. `kv4_pack_row_cpu` <-> `kv4_unpack_row_cpu` exact roundtrip + zero/NaN row handling.
        let (packed, deq_enc) = kv4_pack_row_cpu(&x_rot);
        let (deq_dec, sc) = kv4_unpack_row_cpu(&packed);
        assert!(sc > 0.0 && sc.is_finite());
        assert_eq!(deq_enc, deq_dec);
        let (zero_packed, zero_deq) = kv4_pack_row_cpu(&[0.0f32; HD]);
        assert_eq!(&zero_packed[..64], &[0x88u8; 64]);
        assert_eq!(&zero_packed[64..66], &[0u8, 0u8]);
        assert_eq!(zero_deq, [0.0f32; HD]);
        let mut nan_in = [0.0f32; HD];
        nan_in[0] = f32::NAN;
        let (nan_packed, nan_deq) = kv4_pack_row_cpu(&nan_in);
        assert_eq!(&nan_packed[64..66], &[0u8, 0u8]);
        assert_eq!(nan_deq, [0.0f32; HD]);
    }

    #[cfg(not(standalone_blocks))]
    #[test]
    fn kv4_metal_codec_tables_rademacher_constants_and_fp_pragmas_match_rust_bit_for_bit() {
        let kernels_src = include_str!("kernels.metal");
        let prefill_src = include_str!("prefill.metal");
        let parsed = parse_metal_kv4_codec_constants(kernels_src, prefill_src)
            .expect("Metal KV4 codec constants & pragmas must match Rust reference bit-for-bit");
        assert_eq!(parsed.lm4_val, KV4_LM4_VAL);
        assert_eq!(parsed.lm4_thr, KV4_LM4_THR);
        assert_eq!(parsed.rad_seed, KV4_RAD_SEED);
        assert_eq!(parsed.rad_mul1, KV4_RAD_MUL1);
        assert_eq!(parsed.rad_mul2, KV4_RAD_MUL2);
        assert_eq!(parsed.rad_shifts, [16, 15, 15, 31]);
        assert_eq!(parsed.wht_scale.to_bits(), KV4_INV_SQRT_128.to_bits());

        // Planted mutations in `LM4_THR`, `LM4_VAL`, Triple32 constants/shifts, WHT scale,
        // missing compound-block pragma, or file-scope pragma leak before `attn_split` MUST fail closed!
        for (needle, replacement) in [
            ("0.7995498f", "0.7995499f"),
            ("-2.7325896f", "-2.7325890f"),
            ("0x9E3779B9u", "0x9E3779B8u"),
            ("0x21F0AAADu", "0x21F0AAACu"),
            ("0x735A2D97u", "0x735A2D96u"),
            ("h ^= h >> 16;", "h ^= h >> 17;"),
            ("h ^= h >> 15;", "h ^= h >> 14;"),
            ("return (h >> 31)", "return (h >> 30)"),
            ("return r * 0.08838834764831845f;", "return r * 0.08838830f;"),
            ("#pragma clang fp contract(off) reassociate(off)", "// removed compound pragma"),
            ("#elif defined(KV8)", "#pragma clang fp contract(fast) reassociate(on)\n#elif defined(KV8)"),
            ("#elif defined(KV8)", "#pragma clang fp contract(off) reassociate(off)\n#elif defined(KV8)"),
        ] {
            assert!(kernels_src.contains(needle), "expected needle `{needle}` in kernels.metal");
            let mutated = kernels_src.replacen(needle, replacement, 1);
            assert!(
                parse_metal_kv4_codec_constants(&mutated, prefill_src).is_err(),
                "mutating `{needle}` -> `{replacement}` must fail parse_metal_kv4_codec_constants"
            );
        }
    }

    #[test]
    fn kv4_with_wht2_sketch_cpu_needle_ranking_and_spill_restore() {
        let mut pools = BlockPools::with_capacities_mode_and_sketches(2, 1, KvMode::Kv4, true).unwrap();
        assert!(pools.full.has_sketches());
        assert!(!pools.window.has_sketches());
        assert_eq!(pools.full.kvb(), KVB_KV4);
        assert_eq!(pools.full.stride_bytes(), KV4_FULL_STRIDE);

        let (slot_bg, _) = pools.full.take_free().unwrap();
        pools.full.record_mut(slot_bg).unwrap().add_ref().unwrap();
        let (slot_needle, _) = pools.full.take_free().unwrap();
        pools.full.record_mut(slot_needle).unwrap().add_ref().unwrap();
        assert_ne!(slot_bg, slot_needle);

        let slot2 = 6u32; // slot = 3 -> slot * 2 = 6
        let g = 2u32;
        let pass_idx = 1u32;
        let mut mu_r = [0.0f32; HD];
        let mut q_unrot = [0.0f32; HD];
        for d in 0..HD {
            mu_r[d] = ((d as f32) * 0.19).sin() * 0.35;
            q_unrot[d] = ((d as f32) * 0.43).cos() * 1.2;
        }
        let mut q_signed = [0.0f32; HD];
        for d in 0..HD {
            q_signed[d] = kv4_rademacher(slot2, g, d as u32) * q_unrot[d];
        }
        let q_rot = wht128_cpu(&q_signed);
        let dc_bias: f32 = q_rot.iter().zip(&mu_r).map(|(&a, &b)| a * b).sum();
        let qp_group = [[0.0f32; HD], q_rot, [0.0f32; HD]];
        let sink_orig = 0.5f32;
        let sink_group = [sink_orig, sink_orig - dc_bias, sink_orig];

        for (slot, is_needle) in [(slot_bg, false), (slot_needle, true)] {
            let bytes = pools.full.slot_bytes_mut(slot).unwrap();
            for t in 0..BLOCK as u32 {
                let (nib_off, _) = kv4_key_row(0, BlockKind::Full, pass_idx, Kv::Key, g, t).unwrap();
                let mut k_unrot = [0.0f32; HD];
                for d in 0..HD {
                    k_unrot[d] = if is_needle && (16..24).contains(&t) {
                        q_unrot[d] * 2.5
                    } else {
                        -((d as f32 * 0.61 + t as f32).sin() * 0.2)
                    };
                }
                let mut k_signed = [0.0f32; HD];
                for d in 0..HD {
                    k_signed[d] = kv4_rademacher(slot2, g, d as u32) * k_unrot[d];
                }
                let mut k_rot_res = wht128_cpu(&k_signed);
                for d in 0..HD {
                    k_rot_res[d] -= mu_r[d];
                }
                let (packed, _) = kv4_pack_row_cpu(&k_rot_res);
                let off = nib_off as usize;
                bytes[off..off + (KV4_ROW_BYTES as usize)].copy_from_slice(&packed);
            }
            pools.full.record_mut(slot).unwrap().set_length(BLOCK as u32).unwrap();
            pools.full.recompute_slot_sketch_cpu(slot).unwrap();
            assert_eq!(pools.full.slot_sketch_valid_len(slot).unwrap(), BLOCK as u8);
        }

        let sk_off = (pass_idx as usize * NKV + g as usize) * WHT2_HEAD_SKETCH_BYTES;
        let range = sk_off..sk_off + WHT2_HEAD_SKETCH_BYTES;
        let s_bg = score_wht2_head_sketch_mode_cpu(
            &pools.full.slot_sketch_bytes(slot_bg).unwrap()[range.clone()],
            KvMode::Kv4,
            pass_idx,
            g,
            &qp_group,
            &sink_group,
        );
        let s_needle = score_wht2_head_sketch_mode_cpu(
            &pools.full.slot_sketch_bytes(slot_needle).unwrap()[range.clone()],
            KvMode::Kv4,
            pass_idx,
            g,
            &qp_group,
            &sink_group,
        );
        assert!(s_needle > s_bg + 10.0, "KV4 WHT-2bit sketch must rank needle above background: {s_needle} vs {s_bg}");

        // Poison sketch sidecar and verify `on_slot_restored_from_spill` recomputes exact KV4 sketch.
        let saved_kv = pools.full.slot_bytes(slot_needle).unwrap().to_vec();
        pools.full.record_mut(slot_needle).unwrap().drop_ref().unwrap();
        pools.full.take(slot_needle).unwrap();
        pools.full.slot_sketch_bytes_mut(slot_needle).unwrap().fill(0xA5);
        pools.full.slot_bytes_mut(slot_needle).unwrap().copy_from_slice(&saved_kv);
        pools.full.record_mut(slot_needle).unwrap().set_length(BLOCK as u32).unwrap();
        pools.full.on_slot_restored_from_spill(slot_needle);
        let s_restored = score_wht2_head_sketch_mode_cpu(
            &pools.full.slot_sketch_bytes(slot_needle).unwrap()[range],
            KvMode::Kv4,
            pass_idx,
            g,
            &qp_group,
            &sink_group,
        );
        assert!((s_restored - s_needle).abs() < 1e-6);
    }

    #[test]
    fn full_slot_wht2_sketch_lifecycle_reuse_clear_and_needle_ranking() {
        assert_eq!(FULL_SKETCH_BYTES, 17_408);
        assert_eq!(std::mem::size_of::<Wht2HeadSketch>(), 272);

        // WHT-128 is a normalized symmetric involution (`H_128^2 = I`).
        let mut orig = [0.0f32; HD];
        for (d, x) in orig.iter_mut().enumerate() {
            *x = ((d as f32) * 0.137).sin() * 2.3;
        }
        let mut v = orig;
        wht128_in_place(&mut v);
        wht128_in_place(&mut v);
        for d in 0..HD {
            assert!((v[d] - orig[d]).abs() < 1e-5, "WHT-128 involution drift at {d}: {} vs {}", v[d], orig[d]);
        }

        // Default Full, Window, and records_only pools allocate 0 sketch bytes (`!has_sketches()`).
        let mut default_full = BlockPool::new(BlockKind::Full, 3);
        let s1 = Slot::new(1).unwrap();
        assert!(!default_full.has_sketches());
        assert_eq!(default_full.slot_sketch_bytes(s1), Err(BlockError::OutOfRange));
        let (ds, _) = default_full.take_free().unwrap();
        assert_eq!(default_full.slot_sketch_bytes(ds), Err(BlockError::OutOfRange));
        default_full.take_unzeroed(ds).unwrap();
        assert_eq!(default_full.slot_sketch_bytes(ds), Err(BlockError::OutOfRange));
        default_full.enable_sketches().unwrap();
        assert!(default_full.has_sketches());
        assert_eq!(default_full.slot_sketch_bytes(s1).unwrap().len(), FULL_SKETCH_BYTES);

        let win_pool = BlockPool::new(BlockKind::Window, 2);
        assert!(!win_pool.has_sketches());
        assert_eq!(win_pool.slot_sketch_bytes(s1), Err(BlockError::OutOfRange));
        let rec_pool = BlockPool::records_only(BlockKind::Full, 2, 2).unwrap();
        assert!(!rec_pool.has_sketches());
        assert_eq!(rec_pool.slot_sketch_bytes(s1), Err(BlockError::OutOfRange));

        // Sketch-enabled Full pool allocates 17,408 B per slot, ranks needle sub-block #1, and clears on `take` and `take_unzeroed`.
        let mut pool = BlockPool::new_with_sketches(BlockKind::Full, 3, 2).unwrap();
        let (slot_a, _) = pool.take_free().unwrap();
        pool.record_mut(slot_a).unwrap().add_ref().unwrap();
        let (slot_b, _) = pool.take_free().unwrap();
        assert_ne!(slot_a, slot_b);
        assert_eq!(pool.slot_sketch_valid_len(slot_a).unwrap(), 0);
        assert_eq!(pool.slot_sketch_bytes(slot_a).unwrap().len(), FULL_SKETCH_BYTES);

        // Plant a needle key in `slot_b` sub-block 5 (`t = 40..48`) and distractor keys elsewhere.
        for (slot, has_needle) in [(slot_a, false), (slot_b, true)] {
            let bytes = pool.slot_bytes_mut(slot).unwrap();
            for t in 0..BLOCK as u32 {
                let off = key_row(0, BlockKind::Full, 2, 3, Kv::Key, 5, t).unwrap() as usize;
                for d in 0..HD {
                    let val = if has_needle && (40..48).contains(&t) {
                        if (d * 3 + 1) % 2 == 0 { 2.75f32 } else { -2.75f32 }
                    } else if (d / 8) % 2 == 0 {
                        0.3f32
                    } else {
                        -0.3f32
                    };
                    let bits = f32_to_f16_bits(val).to_le_bytes();
                    bytes[off + 2 * d] = bits[0];
                    bytes[off + 2 * d + 1] = bits[1];
                }
            }
            pool.record_mut(slot).unwrap().set_length(BLOCK as u32).unwrap();
            pool.recompute_slot_sketch_cpu(slot).unwrap();
            assert_eq!(pool.slot_sketch_valid_len(slot).unwrap(), BLOCK as u8);
        }

        let mut qp = [[0.0f32; HD]; 3];
        for (d, x) in qp[1].iter_mut().enumerate() {
            *x = if (d * 3 + 1) % 2 == 0 { 1.0f32 } else { -1.0f32 };
        }
        let sink = [0.25f32; 3];
        let sk_idx = 3 * NKV + 5;
        let range = (sk_idx * WHT2_HEAD_SKETCH_BYTES)..((sk_idx + 1) * WHT2_HEAD_SKETCH_BYTES);
        let score_distractor =
            score_wht2_head_sketch_cpu(&pool.slot_sketch_bytes(slot_a).unwrap()[range.clone()], 3, 5, &qp, &sink);
        let score_needle =
            score_wht2_head_sketch_cpu(&pool.slot_sketch_bytes(slot_b).unwrap()[range.clone()], 3, 5, &qp, &sink);
        assert!(
            score_needle > score_distractor + 8.0,
            "needle block must outscore distractor cleanly: needle={score_needle}, distractor={score_distractor}"
        );

        // Save `slot_b` KV bytes, then explicitly zero KV bytes and corrupt sketch bytes before `take_unzeroed`
        // so `on_slot_restored_from_spill` proves genuine recomputation from restored SSD KV bytes!
        let saved_kv = pool.slot_bytes(slot_b).unwrap().to_vec();
        pool.slot_bytes_mut(slot_b).unwrap().fill(0);
        pool.slot_sketch_bytes_mut(slot_b).unwrap().fill(0xAA);

        // Reusing `slot_b` via `take_unzeroed` zeroes all 17,408 sketch bytes and resets `valid_len = 0`.
        pool.take_unzeroed(slot_b).unwrap();
        assert_eq!(pool.slot_sketch_valid_len(slot_b).unwrap(), 0);
        assert!(pool.slot_sketch_bytes(slot_b).unwrap().iter().all(|&b| b == 0));
        assert!(pool.slot_bytes(slot_b).unwrap().iter().all(|&b| b == 0));

        // Copy saved SSD KV bytes back into `slot_b` and verify `on_slot_restored_from_spill` recomputes the sketch.
        pool.slot_bytes_mut(slot_b).unwrap().copy_from_slice(&saved_kv);
        pool.record_mut(slot_b).unwrap().set_length(BLOCK as u32).unwrap();
        pool.on_slot_restored_from_spill(slot_b);
        assert_eq!(pool.slot_sketch_valid_len(slot_b).unwrap(), BLOCK as u8);
        let score_restored =
            score_wht2_head_sketch_cpu(&pool.slot_sketch_bytes(slot_b).unwrap()[range], 3, 5, &qp, &sink);
        assert!((score_restored - score_needle).abs() < 1e-6);

        let ep_before = pool.slot_sketch_epoch(slot_b).unwrap();
        pool.mark_slot_sketch_dirty(slot_b);
        assert_eq!(pool.slot_sketch_valid_len(slot_b).unwrap(), 0);
        assert_eq!(pool.slot_sketch_epoch(slot_b).unwrap(), ep_before + 1);
        pool.take(slot_b).unwrap();
        assert_eq!(pool.slot_sketch_valid_len(slot_b).unwrap(), 0);
        assert_eq!(pool.slot_sketch_epoch(slot_b).unwrap(), ep_before + 2);
        assert!(pool.slot_sketch_bytes(slot_b).unwrap().iter().all(|&b| b == 0));
    }

    #[test]
    fn sparse_topk_cpu_selection_tie_breaks_nans_boundaries_and_valid_len_contiguity() {
        // 1. `sparse_float_to_ord_cpu`: NaN -> 0, -0.0 == +0.0 -> 0x8000_0000, strictly monotone across -inf..+inf.
        assert_eq!(sparse_float_to_ord_cpu(f32::NAN), 0);
        assert_eq!(sparse_float_to_ord_cpu(f32::from_bits(0x7fc0_1234)), 0);
        assert_eq!(sparse_float_to_ord_cpu(f32::from_bits(0xffc0_0001)), 0);
        assert_eq!(sparse_float_to_ord_cpu(-0.0), 0x8000_0000);
        assert_eq!(sparse_float_to_ord_cpu(0.0), 0x8000_0000);
        let ordered = [
            f32::NEG_INFINITY,
            -1.0e30,
            -42.5,
            -f32::MIN_POSITIVE,
            0.0,
            f32::MIN_POSITIVE,
            1.25,
            1.0e30,
            f32::INFINITY,
        ];
        for w in ordered.windows(2) {
            assert!(
                sparse_float_to_ord_cpu(w[0]) < sparse_float_to_ord_cpu(w[1]),
                "order broken for {} < {}",
                w[0],
                w[1]
            );
            assert!(sparse_float_to_ord_cpu(f32::NAN) < sparse_float_to_ord_cpu(w[0]));
        }

        // 2. Equal-score ties break deterministically by ascending block index (`blk ASC`), and NaNs lose to finite/-inf.
        // Anchors = 0..2, Far = 2..8 (6 candidates), Recent = 8..10, Top-K = 3.
        let far_scores = [
            f32::NAN,          // blk 2: NaN -> ord 0 (lowest)
            5.0,               // blk 3: tied at 5.0 (1st tie winner)
            5.0,               // blk 4: tied at 5.0 (2nd tie winner)
            5.0,               // blk 5: tied at 5.0 (loses Top-3 because blk 7 is 9.0, so 9.0 + blk 3 + blk 4 win!)
            f32::NEG_INFINITY, // blk 6: -inf (beats NaN, loses to 5.0)
            9.0,               // blk 7: highest (9.0)
        ];
        let sel = select_sparse_topk_cpu(2, 2, 8, 10, 3, &far_scores);
        assert_eq!(sel, vec![0, 1, 3, 4, 7, 8, 9]);

        // `-0.0` and `+0.0` tie identically and break by ascending block index.
        let zero_ties = [-0.0f32, 0.0f32, -0.0f32];
        assert_eq!(select_sparse_topk_cpu(0, 0, 3, 4, 2, &zero_ties), vec![0, 1, 3]);

        // Boundary cases: `anchors = 0`, `top_k >= n_far`, and `sparse_block_window_plan` exact threshold.
        assert_eq!(select_sparse_topk_cpu(0, 0, 2, 4, 8, &[1.0, 2.0]), vec![0, 1, 2, 3]);
        let p_dense = sparse_block_window_plan(24 * BLOCK - 1, 4, 16, Some(4));
        assert!(p_dense.passthrough);
        assert_eq!(p_dense.total_blocks, 24);
        assert_eq!(p_dense.total_sel_blocks, 24);
        let p_sparse = sparse_block_window_plan(24 * BLOCK, 4, 16, Some(4));
        assert!(!p_sparse.passthrough);
        assert_eq!(p_sparse.total_blocks, 25);
        assert_eq!(p_sparse.far_start_blk, 4);
        assert_eq!(p_sparse.n_far_blocks, 5);
        assert_eq!(p_sparse.recent_start_blk, 9);
        assert_eq!(p_sparse.total_sel_blocks, 24);

        // 3. `advance_contiguous_sketch_valid_len`: contiguous prefix advances; mixed-batch jump stays unadvanced!
        let mut valid = 0u8;
        for ib in 0..10usize {
            valid = advance_contiguous_sketch_valid_len(valid, ib);
        }
        assert_eq!(valid, 10);
        // Passthrough lane jumps from `ib = 9` (`valid = 10`, sub-block 1) to `ib = 40` (sub-block 5, `sb_start = 40`):
        // sub-blocks 2, 3, 4 (`16..40`) were never built, so `valid` MUST remain `10` (never jump to `41`)!
        for ib in 40..BLOCK {
            assert_eq!(advance_contiguous_sketch_valid_len(valid, ib), 10);
        }
        // Once catch-up builds `0..40` (`valid = 40`), stepping at `ib = 40` advances cleanly to `41`.
        assert_eq!(advance_contiguous_sketch_valid_len(40, 40), 41);

        // 4. `sparse_sketch_byte_offset`: `pool_index * FULL_SKETCH_BYTES` at `(0, 0)` and pairwise disjoint 272 B slices.
        for pool_idx in 0..4u32 {
            assert_eq!(
                sparse_sketch_byte_offset(pool_idx, 0, 0).unwrap(),
                (pool_idx as usize) * FULL_SKETCH_BYTES
            );
        }
        assert_eq!(sparse_sketch_byte_offset(0, 8, 0), Err(BlockError::OutOfRange));
        assert_eq!(sparse_sketch_byte_offset(0, 0, 8), Err(BlockError::OutOfRange));
    }

    #[test]
    fn sparse_sketch_64bit_offset_scales_above_4gib_without_u32_overflow() {
        // Above `246,723` Full pool slots (`246_724 * 17_408 = 4,294,971,392 > u32::MAX`),
        // `sparse_sketch_byte_offset` and Metal's `ulong` index must match without 32-bit overflow!
        for &(pool_idx, pass_idx, g) in &[
            (246_723u32, 7u32, 7u32),
            (246_724, 0, 0),
            (300_000, 7, 7),
            (524_288, 5, 3),
        ] {
            let got = sparse_sketch_byte_offset(pool_idx, pass_idx, g).expect("64-bit sketch offset");
            let metal_head_idx = ((u64::from(pool_idx) * 8 + u64::from(pass_idx)) * (NKV as u64)) + u64::from(g);
            let want = (metal_head_idx * (WHT2_HEAD_SKETCH_BYTES as u64)) as usize;
            assert_eq!(got, want);
            if pool_idx >= 246_724 {
                assert!(got > u32::MAX as usize, "expected offset > 4 GiB for pool_idx={pool_idx}");
            }
        }
    }

    #[test]
    fn wide_chunked_tournament_matches_global_topk_across_512k_1m_2m_and_adversarial_ties() {
        // Verify exact bit-for-bit block-index equality between `select_sparse_topk_wide_tournament_cpu`
        // (`k_score_full_sketch_dec_wide`) and global `select_sparse_topk_cpu` across `512K` (`8,192` blocks),
        // `1M` (`16,384` blocks), and `2M` (`32,768` blocks)!
        let mut seed = 0xD1B5_4A32_D192_ED03u64;
        let mut next_u64 = || -> u64 {
            seed ^= seed >> 12;
            seed ^= seed << 25;
            seed ^= seed >> 27;
            seed.wrapping_mul(0x2545_F491_4F6C_DD1D)
        };

        for &total_blocks in &[8_192usize, 16_384, 32_768] {
            let pos = total_blocks * BLOCK - 1;
            for &(anchors, top_k) in &[(16usize, 128usize), (4, 2), (64, 512), (0, 2048), (16, 4095)] {
                let bp = sparse_block_window_plan(pos, anchors, 16, Some(top_k));
                assert!(!bp.passthrough);
                assert_eq!(bp.total_blocks, total_blocks);

                // Case A: pseudo-random multi-scale scores + injected multi-chunk equal-score ties, NaNs, ±0.0, -inf.
                let mut scores = Vec::with_capacity(bp.n_far_blocks);
                for i in 0..bp.n_far_blocks {
                    let r = next_u64();
                    let s = match i % 64 {
                        0 => 3.25f32, // recurring tie straddling every 4K chunk boundary!
                        17 => if (i / 64) % 2 == 0 { 0.0 } else { -0.0 },
                        33 => f32::NAN,
                        49 => f32::NEG_INFINITY,
                        _ => (((r >> 40) as f32) * (1.0 / ((1u32 << 24) as f32)) - 0.5) * 8.0,
                    };
                    scores.push(s);
                }
                let want = select_sparse_topk_cpu(
                    bp.anchor_blocks,
                    bp.far_start_blk,
                    bp.recent_start_blk,
                    bp.total_blocks,
                    bp.top_k,
                    &scores,
                );
                let got = select_sparse_topk_wide_tournament_cpu(
                    bp.anchor_blocks,
                    bp.far_start_blk,
                    bp.recent_start_blk,
                    bp.total_blocks,
                    bp.top_k,
                    &scores,
                );
                assert_eq!(
                    got, want,
                    "wide tournament mismatch on mixed+tie scores at total_blocks={total_blocks} anchors={anchors} top_k={top_k}"
                );
                assert_eq!(got.len(), bp.total_sel_blocks);
            }

            // Case B: All-equal scores across all `32,768` (`2M`) blocks — must pick the exact lowest `top_k` block indices!
            let bp_tie = sparse_block_window_plan(pos, 16, 16, Some(128));
            let all_same = vec![1.75f32; bp_tie.n_far_blocks];
            let want_same = select_sparse_topk_cpu(
                bp_tie.anchor_blocks,
                bp_tie.far_start_blk,
                bp_tie.recent_start_blk,
                bp_tie.total_blocks,
                bp_tie.top_k,
                &all_same,
            );
            let got_same = select_sparse_topk_wide_tournament_cpu(
                bp_tie.anchor_blocks,
                bp_tie.far_start_blk,
                bp_tie.recent_start_blk,
                bp_tie.total_blocks,
                bp_tie.top_k,
                &all_same,
            );
            assert_eq!(got_same, want_same);
            assert_eq!(&got_same[16..16 + 128], &(16u32..144u32).collect::<Vec<_>>()[..]);
        }
    }

    #[test]
    fn in_slot_offsets_reuse_one_parsed_metal_layout() {
        let layout = *metal_kv_layout();
        assert_eq!(
            layout,
            parse_metal_kv_layout(include_str!("kernels.metal"), include_str!("prefill.metal")).unwrap()
        );
        let parses = || LAYOUT_PARSES.with(|n| n.get());
        let before = parses();
        // One position of a session checkpoint: every pass, plane and head of both block kinds.
        let one_position = |pos: u32| {
            for (kind, mode) in [(BlockKind::Full, KvMode::Kv4), (BlockKind::Window, KvMode::Kv4)] {
                for pass in 0..kind.passes() as u32 {
                    for kv in [Kv::Key, Kv::Value] {
                        for head in 0..NKV as u32 {
                            assert_eq!(
                                metal_in_slot_byte_offset_mode(kind, mode, pass, kv, head, pos).unwrap(),
                                metal_in_slot_byte_offset_from_layout_mode(&layout, kind, mode, pass, kv, head, pos)
                                    .unwrap()
                            );
                        }
                    }
                }
            }
        };
        one_position(0);
        assert_eq!(parses(), before, "an in-slot offset lookup parsed the Metal sources again");
        // A full 1,024-position window, as Session::checkpoint snapshots it on a pooled lane.
        for pos in 1..WINDOW as u32 {
            one_position(pos);
        }
        for (kvb, mode) in [(KVB_FP16, KvMode::Fp16), (KVB_KV8, KvMode::Kv8)] {
            for pos in [0u32, 63, 64, 1023] {
                assert_eq!(
                    metal_in_slot_byte_offset(BlockKind::Window, kvb, 39, Kv::Value, 7, pos).unwrap(),
                    metal_in_slot_byte_offset_mode(BlockKind::Window, mode, 39, Kv::Value, 7, pos).unwrap()
                );
            }
        }
        assert_eq!(parses(), before, "an in-slot offset lookup parsed the Metal sources again");
    }
}