kvbm-logical 1.3.0-dev.1

Logical layer for KVBM (Key-Value Buffer Manager), managing block metadata, allocation, and eviction policies.
Documentation
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
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use super::*;
use crate::KvbmSequenceHashProvider;
use crate::blocks::BlockError;
use crate::testing::{
    self, TestMeta, create_iota_token_block, create_test_token_block as testing_create_token_block,
};
use rstest::rstest;

// Type alias for backward compatibility
type TestBlockData = TestMeta;

/// Helper function to create a token block with specific data (local wrapper)
fn create_token_block(tokens: &[u32]) -> dynamo_tokens::TokenBlock {
    testing_create_token_block(tokens, tokens.len() as u32)
}

/// Helper function to create a token block using fill_iota pattern
fn create_test_token_block_from_iota(start: u32) -> dynamo_tokens::TokenBlock {
    create_iota_token_block(start, 4)
}

fn create_test_token_block_8_from_iota(start: u32) -> dynamo_tokens::TokenBlock {
    create_iota_token_block(start, 8)
}

/// Helper function to create a basic manager for testing
fn create_test_manager(block_count: usize) -> BlockManager<TestBlockData> {
    testing::create_test_manager(block_count)
}

// ============================================================================
// BUILDER PATTERN TESTS
// ============================================================================

mod builder_tests {
    use super::*;

    #[test]
    fn test_builder_default() {
        let registry = BlockRegistry::new();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .registry(registry)
            .build()
            .expect("Should build with defaults");

        // Verify initial gauge
        let snap = manager.metrics().snapshot();
        assert_eq!(snap.reset_pool_size, 100);
        assert_eq!(snap.inactive_pool_size, 0);

        // Verify we can allocate blocks
        let blocks = manager.allocate_blocks(5);
        assert!(blocks.is_some());
        assert_eq!(blocks.unwrap().len(), 5);
    }

    #[test]
    fn test_builder_with_lru_backend() {
        let registry = BlockRegistry::new();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .registry(registry)
            .with_lru_backend()
            .build()
            .expect("Should build with LRU backend");

        // Verify we can allocate blocks
        let blocks = manager.allocate_blocks(10);
        assert!(blocks.is_some());
        assert_eq!(blocks.unwrap().len(), 10);
    }

    #[test]
    fn test_builder_with_multi_lru_backend() {
        let registry = BlockRegistry::builder()
            .frequency_tracker(FrequencyTrackingCapacity::Small.create_tracker())
            .build();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .registry(registry)
            .with_multi_lru_backend()
            .build()
            .expect("Should build with MultiLRU backend");

        // Verify we can allocate blocks
        let blocks = manager.allocate_blocks(8);
        assert!(blocks.is_some());
        assert_eq!(blocks.unwrap().len(), 8);
    }

    #[test]
    fn test_builder_with_custom_multi_lru_thresholds() {
        let registry = BlockRegistry::builder()
            .frequency_tracker(FrequencyTrackingCapacity::Medium.create_tracker())
            .build();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .registry(registry)
            .with_multi_lru_backend_custom_thresholds(2, 6, 12)
            .build()
            .expect("Should build with custom thresholds");

        // Verify we can allocate blocks
        let blocks = manager.allocate_blocks(4);
        assert!(blocks.is_some());
        assert_eq!(blocks.unwrap().len(), 4);
    }

    #[test]
    fn test_builder_with_duplication_policy() {
        let registry = BlockRegistry::new();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(50)
            .registry(registry)
            .duplication_policy(BlockDuplicationPolicy::Reject)
            .with_lru_backend()
            .build()
            .expect("Should build with duplication policy");

        let blocks = manager.allocate_blocks(2);
        assert!(blocks.is_some());
        assert_eq!(blocks.unwrap().len(), 2);
    }

    #[test]
    fn test_builder_validation_zero_blocks() {
        let registry = BlockRegistry::new();
        let result = BlockManager::<TestBlockData>::builder()
            .block_count(0)
            .registry(registry)
            .build();

        assert!(result.is_err());
        if let Err(err) = result {
            assert!(
                err.to_string()
                    .contains("block_count must be greater than 0")
            );
        }
    }

    #[test]
    fn test_builder_validation_missing_block_count() {
        let registry = BlockRegistry::new();
        let result = BlockManager::<TestBlockData>::builder()
            .registry(registry)
            .with_lru_backend()
            .build();

        assert!(result.is_err());
        if let Err(err) = result {
            assert!(err.to_string().contains("block_count is required"));
        }
    }

    #[test]
    fn test_builder_validation_missing_registry() {
        let result = BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .with_lru_backend()
            .build();

        assert!(result.is_err());
        if let Err(err) = result {
            assert!(err.to_string().contains("registry is required"));
        }
    }

    #[test]
    #[should_panic(expected = "must be <= 15")]
    fn test_builder_invalid_threshold_too_high() {
        BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .with_multi_lru_backend_custom_thresholds(2, 6, 20); // 20 > 15, should panic
    }

    #[test]
    #[should_panic(expected = "must be in ascending order")]
    fn test_builder_invalid_threshold_order() {
        BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .with_multi_lru_backend_custom_thresholds(6, 2, 10); // Not ascending, should panic
    }

    #[test]
    fn test_builder_multi_lru_requires_frequency_tracking() {
        let registry = BlockRegistry::new(); // No frequency tracking
        let result = BlockManager::<TestBlockData>::builder()
            .block_count(100)
            .registry(registry)
            .with_multi_lru_backend()
            .build();

        assert!(result.is_err());
        if let Err(err) = result {
            assert!(err.to_string().contains("frequency tracking"));
        }
    }
}

// ============================================================================
// BLOCK ALLOCATION TESTS
// ============================================================================

mod allocation_tests {
    use super::*;

    #[test]
    fn test_allocate_single_block() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let initial_available = manager.available_blocks();
        let initial_total = manager.total_blocks();
        assert_eq!(initial_available, 10);

        let snap = m.snapshot();
        assert_eq!(snap.reset_pool_size, 10);

        let blocks = manager.allocate_blocks(1).expect("Should allocate 1 block");
        assert_eq!(blocks.len(), 1);

        // Verify available blocks decreased
        assert_eq!(manager.available_blocks(), initial_available - 1);
        assert_eq!(manager.total_blocks(), initial_total);

        let snap = m.snapshot();
        assert_eq!(snap.allocations, 1);
        assert_eq!(snap.inflight_mutable, 1);
        assert_eq!(snap.reset_pool_size, 9);

        let block = blocks.into_iter().next().unwrap();
        // Verify block has a valid ID
        let _block_id = block.block_id();

        // Drop the block and verify it returns to pool
        drop(block);
        assert_eq!(manager.available_blocks(), initial_available);
        assert_eq!(manager.total_blocks(), initial_total);

        let snap = m.snapshot();
        assert_eq!(snap.inflight_mutable, 0);
        assert_eq!(snap.reset_pool_size, 10);
    }

    #[test]
    fn test_allocate_multiple_blocks() {
        let manager = create_test_manager(20);
        let m = manager.metrics();

        let initial_available = manager.available_blocks();
        let initial_total = manager.total_blocks();
        assert_eq!(initial_available, 20);

        let blocks = manager
            .allocate_blocks(5)
            .expect("Should allocate 5 blocks");
        assert_eq!(blocks.len(), 5);

        // Verify available blocks decreased correctly
        assert_eq!(manager.available_blocks(), initial_available - 5);
        assert_eq!(manager.total_blocks(), initial_total);

        let snap = m.snapshot();
        assert_eq!(snap.allocations, 5);
        assert_eq!(snap.inflight_mutable, 5);

        // Verify all blocks have unique IDs
        let mut block_ids = Vec::new();
        for block in blocks {
            let id = block.block_id();
            assert!(!block_ids.contains(&id), "Block IDs should be unique");
            block_ids.push(id);
        }

        // All blocks should return to pool automatically on drop
        assert_eq!(manager.available_blocks(), initial_available);
        assert_eq!(manager.total_blocks(), initial_total);

        let snap = m.snapshot();
        assert_eq!(snap.inflight_mutable, 0);
    }

    #[test]
    fn test_allocate_all_blocks() {
        let manager = create_test_manager(10);

        let blocks = manager
            .allocate_blocks(10)
            .expect("Should allocate all blocks");
        assert_eq!(blocks.len(), 10);
    }

    #[test]
    fn test_allocate_more_than_available() {
        let manager = create_test_manager(5);

        let result = manager.allocate_blocks(10);
        assert!(
            result.is_none(),
            "Should not allocate more blocks than available"
        );
    }

    #[test]
    fn test_allocate_zero_blocks() {
        let manager = create_test_manager(10);

        let blocks = manager
            .allocate_blocks(0)
            .expect("Should allocate 0 blocks");
        assert_eq!(blocks.len(), 0);
    }

    #[test]
    fn test_sequential_allocations() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let total_blocks = manager.total_blocks();
        assert_eq!(manager.available_blocks(), total_blocks);
        assert_eq!(m.snapshot().reset_pool_size, 10);

        let blocks1 = manager.allocate_blocks(3).expect("First allocation");
        assert_eq!(blocks1.len(), 3);
        assert_eq!(manager.available_blocks(), total_blocks - 3);
        assert_eq!(m.snapshot().reset_pool_size, 7);

        let blocks2 = manager.allocate_blocks(4).expect("Second allocation");
        assert_eq!(blocks2.len(), 4);
        assert_eq!(manager.available_blocks(), total_blocks - 7);
        assert_eq!(m.snapshot().reset_pool_size, 3);

        let blocks3 = manager.allocate_blocks(3).expect("Third allocation");
        assert_eq!(blocks3.len(), 3);
        assert_eq!(manager.available_blocks(), 0);
        assert_eq!(m.snapshot().reset_pool_size, 0);

        let snap = m.snapshot();
        assert_eq!(snap.allocations, 10);
        assert_eq!(snap.inflight_mutable, 10);

        // Should have no blocks left
        let blocks4 = manager.allocate_blocks(1);
        assert!(blocks4.is_none(), "Should not have any blocks left");

        // Drop blocks in reverse order and verify counts
        drop(blocks3);
        assert_eq!(manager.available_blocks(), 3);
        assert_eq!(m.snapshot().reset_pool_size, 3);

        drop(blocks2);
        assert_eq!(manager.available_blocks(), 7);
        assert_eq!(m.snapshot().reset_pool_size, 7);

        drop(blocks1);
        assert_eq!(manager.available_blocks(), total_blocks);
        assert_eq!(manager.total_blocks(), total_blocks);

        let snap = m.snapshot();
        assert_eq!(snap.inflight_mutable, 0);
        assert_eq!(snap.reset_pool_size, 10);
    }
}

// ============================================================================
// BLOCK LIFECYCLE AND POOL RETURN TESTS
// ============================================================================

mod lifecycle_tests {
    use super::*;

    #[test]
    fn test_mutable_block_returns_to_reset_pool() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let initial_available = manager.available_blocks();
        let initial_total = manager.total_blocks();
        assert_eq!(initial_available, 10);
        assert_eq!(initial_total, 10);

        {
            let blocks = manager
                .allocate_blocks(3)
                .expect("Should allocate 3 blocks");
            assert_eq!(blocks.len(), 3);

            // Available blocks should decrease
            assert_eq!(manager.available_blocks(), initial_available - 3);
            assert_eq!(manager.total_blocks(), initial_total); // Total never changes

            let snap = m.snapshot();
            assert_eq!(snap.inflight_mutable, 3);
            assert_eq!(snap.reset_pool_size, 7);
        } // MutableBlocks dropped here - should return to reset pool

        // Available blocks should return to original count
        assert_eq!(manager.available_blocks(), initial_available);
        assert_eq!(manager.total_blocks(), initial_total);

        let snap = m.snapshot();
        assert_eq!(snap.inflight_mutable, 0);
        assert_eq!(snap.reset_pool_size, 10);
    }

    #[test]
    fn test_complete_block_returns_to_reset_pool() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let initial_available = manager.available_blocks();
        let initial_total = manager.total_blocks();

        {
            let mutable_blocks = manager.allocate_blocks(2).expect("Should allocate blocks");
            assert_eq!(manager.available_blocks(), initial_available - 2);

            let snap = m.snapshot();
            assert_eq!(snap.reset_pool_size, 8);

            // Note: create_token_block uses 3 tokens but block_size is 4,
            // so complete() returns Err(BlockSizeMismatch) for all blocks.
            let _complete_blocks: Vec<_> = mutable_blocks
                .into_iter()
                .enumerate()
                .map(|(i, block)| {
                    let tokens = vec![400 + i as u32, 401 + i as u32, 402 + i as u32];
                    let token_block = create_token_block(&tokens);
                    block.complete(&token_block)
                })
                .collect();

            // Blocks are still unavailable while in Complete state
            assert_eq!(manager.available_blocks(), initial_available - 2);

            let snap = m.snapshot();
            assert_eq!(snap.inflight_mutable, 2);
            assert_eq!(snap.stagings, 0);
            assert_eq!(snap.reset_pool_size, 8);
        } // CompleteBlocks dropped here - should return to reset pool

        // Available blocks should return to original count since blocks weren't registered
        assert_eq!(manager.available_blocks(), initial_available);
        assert_eq!(manager.total_blocks(), initial_total);

        let snap = m.snapshot();
        assert_eq!(snap.inflight_mutable, 0);
        assert_eq!(snap.reset_pool_size, 10);
    }

    #[test]
    fn test_registered_block_lifecycle() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let initial_available = manager.available_blocks();
        let initial_total = manager.total_blocks();

        // Step 1: Allocate and complete blocks
        let token_block = create_test_token_block_from_iota(500);
        let seq_hash = token_block.kvbm_sequence_hash();

        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        assert_eq!(manager.available_blocks(), initial_available - 1);

        let snap = m.snapshot();
        assert_eq!(snap.allocations, 1);
        assert_eq!(snap.inflight_mutable, 1);
        assert_eq!(snap.reset_pool_size, 9);
        assert_eq!(snap.inactive_pool_size, 0);

        let complete_block = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block)
            .expect("Should complete block");

        // Still unavailable while in Complete state
        assert_eq!(manager.available_blocks(), initial_available - 1);

        let snap = m.snapshot();
        assert_eq!(snap.stagings, 1);
        assert_eq!(snap.inflight_mutable, 0);

        // Step 2: Register the block
        let immutable_blocks = manager.register_blocks(vec![complete_block]);
        assert_eq!(immutable_blocks.len(), 1);
        let immutable_block = immutable_blocks.into_iter().next().unwrap();

        // Block is still not available (it's now in active/inactive pools, not reset)
        assert_eq!(manager.available_blocks(), initial_available - 1);

        let snap = m.snapshot();
        assert_eq!(snap.registrations, 1);
        assert_eq!(snap.inflight_immutable, 1);
        assert_eq!(snap.reset_pool_size, 9);
        assert_eq!(snap.inactive_pool_size, 0);

        {
            // Step 3: Use the block and verify it can be matched
            let matched_blocks = manager.match_blocks(&[seq_hash]);
            assert_eq!(matched_blocks.len(), 1);
            assert_eq!(matched_blocks[0].sequence_hash(), seq_hash);

            // Still not available while being used
            assert_eq!(manager.available_blocks(), initial_available - 1);

            let snap = m.snapshot();
            assert_eq!(snap.match_hashes_requested, 1);
            assert_eq!(snap.match_blocks_returned, 1);
            assert_eq!(snap.inflight_immutable, 2);
        } // matched blocks dropped here

        let snap = m.snapshot();
        assert_eq!(snap.inflight_immutable, 1);

        // Step 4: Drop the original registered block → block moves to inactive
        drop(immutable_block);

        // Block should now be available again (moved to inactive pool when ref count reached 0)
        assert_eq!(manager.available_blocks(), initial_available);
        assert_eq!(manager.total_blocks(), initial_total);

        let snap = m.snapshot();
        assert_eq!(snap.inflight_immutable, 0);
        assert_eq!(snap.reset_pool_size, 9);
        assert_eq!(snap.inactive_pool_size, 1);

        // Step 5: Re-match from inactive pool → pulls block out
        {
            let re_matched = manager.match_blocks(&[seq_hash]);
            assert_eq!(re_matched.len(), 1);

            let snap = m.snapshot();
            assert_eq!(snap.inactive_pool_size, 0);
        } // re_matched dropped → block returns to inactive

        let snap = m.snapshot();
        assert_eq!(snap.inactive_pool_size, 1);
    }

    #[test]
    fn test_concurrent_allocation_and_return() {
        use std::sync::Arc;
        use std::thread;

        let manager = Arc::new(create_test_manager(20));
        let initial_total = manager.total_blocks();

        let handles: Vec<_> = (0..5)
            .map(|i| {
                let manager_clone = Arc::clone(&manager);
                thread::spawn(move || {
                    // Each thread allocates and drops some blocks
                    for j in 0..3 {
                        let blocks = manager_clone.allocate_blocks(2);
                        if let Some(blocks) = blocks {
                            // Complete one block
                            let token_block =
                                create_test_token_block_from_iota((600 + i * 10 + j) as u32);
                            let complete_block = blocks
                                .into_iter()
                                .next()
                                .unwrap()
                                .complete(&token_block)
                                .expect("Should complete block");

                            // Register and drop
                            let _immutable_blocks =
                                manager_clone.register_blocks(vec![complete_block]);
                            // blocks automatically dropped at end of scope
                        }
                    }
                })
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // All blocks should eventually be available again
        assert_eq!(manager.total_blocks(), initial_total);
        // Available might be less than total if some blocks are in inactive pool,
        // but total should be preserved
    }

    #[test]
    fn test_full_block_lifecycle() {
        let manager = create_test_manager(10);
        let total_blocks = manager.total_blocks();
        assert_eq!(manager.available_blocks(), total_blocks);

        // Step 1: Allocate 5 blocks
        let mutable_blocks = manager
            .allocate_blocks(5)
            .expect("Should allocate 5 blocks");
        assert_eq!(manager.available_blocks(), total_blocks - 5);
        assert_eq!(manager.total_blocks(), total_blocks);

        // Step 2: Complete 3 blocks, drop 2 mutable blocks
        let mut mutable_blocks_iter = mutable_blocks.into_iter();
        let complete_blocks: Vec<_> = (0..3)
            .map(|i| {
                let block = mutable_blocks_iter.next().unwrap();
                let tokens = vec![
                    700 + i as u32,
                    701 + i as u32,
                    702 + i as u32,
                    703 + i as u32,
                ];
                let token_block = create_token_block(&tokens);
                block.complete(&token_block).expect("Should complete block")
            })
            .collect();
        let mutable_part: Vec<_> = mutable_blocks_iter.collect();

        drop(mutable_part); // Drop 2 mutable blocks

        // Should have 2 blocks returned to reset pool
        assert_eq!(manager.available_blocks(), total_blocks - 3);

        // Step 3: Register the 3 completed blocks
        let immutable_blocks = manager.register_blocks(complete_blocks);
        assert_eq!(immutable_blocks.len(), 3);

        // Still 3 blocks unavailable (now in active pool)
        assert_eq!(manager.available_blocks(), total_blocks - 3);

        // Step 4: Match and use one of the blocks
        let seq_hash = create_test_token_block_from_iota(700).kvbm_sequence_hash();
        let matched_blocks = manager.match_blocks(&[seq_hash]);
        assert_eq!(matched_blocks.len(), 1);

        // Step 5: Drop one registered block, keep others
        drop(immutable_blocks.into_iter().next());

        // Still have registered blocks in use, so available count depends on ref counting
        let available_after_drop = manager.available_blocks();
        assert!(available_after_drop >= total_blocks - 3);
        assert!(available_after_drop <= total_blocks);

        // Step 6: Drop everything
        drop(matched_blocks);

        // Eventually all blocks should be available again
        // (Some might be in inactive pool, but available_blocks counts both reset and inactive)
        assert_eq!(manager.total_blocks(), total_blocks);
        let final_available = manager.available_blocks();
        assert_eq!(final_available, total_blocks); // Allow for some blocks in inactive pool
    }
}

// ============================================================================
// BLOCK SIZE VALIDATION TESTS
// ============================================================================

mod block_size_tests {

    use super::*;

    #[test]
    fn test_default_block_size() {
        let manager = create_test_manager(10);
        assert_eq!(manager.block_size(), 4); // create_test_manager uses block_size(4)
    }

    #[test]
    fn test_custom_block_size() {
        let registry = BlockRegistry::new();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(32)
            .registry(registry)
            .build()
            .expect("Should build with custom block size");
        assert_eq!(manager.block_size(), 32);
    }

    #[test]
    fn test_block_size_validation_correct_size() {
        let manager = create_test_manager(10);
        let token_block = create_test_token_block_from_iota(100); // 4 tokens

        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        let mutable_block = mutable_blocks.into_iter().next().unwrap();

        // Should succeed since token_block has exactly 4 tokens
        let result = mutable_block.complete(&token_block);
        assert!(result.is_ok());
    }

    #[test]
    fn test_block_size_validation_wrong_size() {
        // Create a manager expecting 8-token blocks
        let registry = BlockRegistry::new();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(8)
            .registry(registry)
            .with_lru_backend()
            .build()
            .expect("Should build manager");
        let token_block = create_test_token_block_from_iota(1); // 4 tokens, expected 8

        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        let mutable_block = mutable_blocks.into_iter().next().unwrap();

        // Should fail since token_block has 4 tokens but manager expects 8
        let result = mutable_block.complete(&token_block);
        assert!(result.is_err());

        if let Err(BlockError::BlockSizeMismatch {
            expected,
            actual,
            block: _,
        }) = result
        {
            assert_eq!(expected, 8);
            assert_eq!(actual, 4);
        } else {
            panic!("Expected BlockSizeMismatch error");
        }
    }

    #[rstest]
    #[case(1)]
    #[case(2)]
    #[case(4)]
    #[case(8)]
    #[case(16)]
    #[case(32)]
    #[case(64)]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1024)]
    fn test_builder_block_size_power_of_two(#[case] size: usize) {
        let registry = BlockRegistry::new();
        let result = BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(size)
            .registry(registry)
            .build();
        assert!(result.is_ok(), "Block size {} should be valid", size);
    }

    #[test]
    #[should_panic(expected = "block_size must be a power of 2")]
    fn test_builder_block_size_not_power_of_two() {
        BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(15); // Not a power of 2
    }

    #[test]
    #[should_panic(expected = "block_size must be between 1 and 1024")]
    fn test_builder_block_size_too_large() {
        BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(2048); // Too large
    }

    #[test]
    #[should_panic(expected = "block_size must be between 1 and 1024")]
    fn test_builder_block_size_zero() {
        BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(0); // Zero is invalid
    }

    #[test]
    #[should_panic(expected = "block_size must be a power of 2")]
    fn test_builder_validation_invalid_block_size() {
        BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(7); // Not a power of 2, panics immediately
    }

    #[test]
    fn test_different_block_sizes() {
        // Test with block size 4
        let registry_4 = BlockRegistry::new();
        let manager_4 = BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(4)
            .registry(registry_4)
            .build()
            .expect("Should build with block size 4");

        let token_block_4 = create_test_token_block_from_iota(10); // 4 tokens
        let mutable_blocks = manager_4
            .allocate_blocks(1)
            .expect("Should allocate blocks");
        let result = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block_4);
        assert!(result.is_ok());

        // Test with block size 8
        let registry_8 = BlockRegistry::new();
        let manager_8 = BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(8)
            .registry(registry_8)
            .build()
            .expect("Should build with block size 8");

        let token_block_8 = create_test_token_block_8_from_iota(20); // 8 tokens
        let mutable_blocks = manager_8
            .allocate_blocks(1)
            .expect("Should allocate blocks");
        let result = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block_8);
        assert!(result.is_ok());
    }
}

// ============================================================================
// BLOCK REGISTRATION AND DEDUPLICATION TESTS
// ============================================================================

mod registration_tests {
    use super::*;

    #[test]
    fn test_register_single_block() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let token_block = create_test_token_block_from_iota(150);
        let expected_hash = token_block.kvbm_sequence_hash();
        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        let complete_block = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block)
            .expect("Should complete block");

        let immutable_blocks = manager.register_blocks(vec![complete_block]);
        assert_eq!(immutable_blocks.len(), 1);

        let immutable_block = immutable_blocks.into_iter().next().unwrap();
        assert_eq!(immutable_block.sequence_hash(), expected_hash);

        let snap = m.snapshot();
        assert_eq!(snap.registrations, 1);
        assert_eq!(snap.stagings, 1);
    }

    #[test]
    fn test_register_multiple_blocks() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let mut complete_blocks = Vec::new();
        let mut expected_hashes = Vec::new();

        for i in 0..3 {
            let tokens = vec![100 + i, 101 + i, 102 + i, 103 + i];
            let token_block = create_token_block(&tokens);
            expected_hashes.push(token_block.kvbm_sequence_hash());

            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            complete_blocks.push(complete_block);
        }

        let immutable_blocks = manager.register_blocks(complete_blocks);
        assert_eq!(immutable_blocks.len(), 3);

        for (i, immutable_block) in immutable_blocks.iter().enumerate() {
            assert_eq!(immutable_block.sequence_hash(), expected_hashes[i]);
        }

        let snap = m.snapshot();
        assert_eq!(snap.registrations, 3);
        assert_eq!(snap.stagings, 3);
    }

    #[rstest]
    #[case(BlockDuplicationPolicy::Allow, 200, "allow", false)]
    #[case(BlockDuplicationPolicy::Reject, 300, "reject", true)]
    fn test_deduplication_policy(
        #[case] policy: BlockDuplicationPolicy,
        #[case] iota_base: u32,
        #[case] policy_name: &str,
        #[case] expect_same_block_id: bool,
    ) {
        let registry = BlockRegistry::new();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(10)
            .block_size(4)
            .registry(registry)
            .duplication_policy(policy)
            .with_lru_backend()
            .build()
            .expect("Should build manager");

        let token_block = create_test_token_block_from_iota(iota_base);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Register the same sequence hash twice
        let complete_block1 = {
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block")
        };

        let complete_block2 = {
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block")
        };

        let immutable_blocks1 = manager.register_blocks(vec![complete_block1]);
        let immutable_blocks2 = manager.register_blocks(vec![complete_block2]);

        assert_eq!(immutable_blocks1.len(), 1);
        assert_eq!(immutable_blocks2.len(), 1);

        // Both should have the same sequence hash
        assert_eq!(immutable_blocks1[0].sequence_hash(), seq_hash);
        assert_eq!(immutable_blocks2[0].sequence_hash(), seq_hash);

        // Check block IDs based on policy
        if expect_same_block_id {
            // Duplicates are rejected - same block ID
            assert_eq!(
                immutable_blocks1[0].block_id(),
                immutable_blocks2[0].block_id(),
                "With {} policy, duplicates should reuse the same block ID",
                policy_name
            );

            let snap = manager.metrics().snapshot();
            assert_eq!(snap.registration_dedup, 1);
        } else {
            // Duplicates are allowed - different block IDs
            assert_ne!(
                immutable_blocks1[0].block_id(),
                immutable_blocks2[0].block_id(),
                "With {} policy, duplicates should have different block IDs",
                policy_name
            );

            let snap = manager.metrics().snapshot();
            assert_eq!(snap.duplicate_blocks, 1);
        }
    }

    #[test]
    fn test_register_mutable_block_from_existing_reject_returns_block_to_reset_pool() {
        let registry = BlockRegistry::new();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(2)
            .block_size(4)
            .registry(registry)
            .duplication_policy(BlockDuplicationPolicy::Reject)
            .build()
            .expect("Should build manager");

        let blocks = manager
            .allocate_blocks(2)
            .expect("Should allocate two blocks");
        let mut iter = blocks.into_iter();
        let primary_mutable = iter.next().expect("Should have first block");
        let duplicate_mutable = iter.next().expect("Should have second block");

        let primary_id = primary_mutable.block_id();
        let duplicate_id = duplicate_mutable.block_id();

        let token_block = create_test_token_block_from_iota(42);
        let primary_complete = primary_mutable
            .complete(&token_block)
            .expect("Should complete primary block");

        let mut registered = manager.register_blocks(vec![primary_complete]);
        let primary_immutable = registered.pop().expect("Should register primary block");

        let duplicate_completed = duplicate_mutable
            .stage(primary_immutable.sequence_hash(), manager.block_size())
            .expect("block size should match");

        let result = manager.register_block(duplicate_completed);

        assert_eq!(
            result.block_id(),
            primary_id,
            "Should reuse existing primary when duplicates are rejected"
        );

        assert_eq!(
            manager.available_blocks(),
            1,
            "Rejected duplicate should be returned to the reset pool"
        );

        let mut returned_blocks = manager
            .allocate_blocks(1)
            .expect("Should allocate returned reset block");
        let returned_block = returned_blocks
            .pop()
            .expect("Should contain one returned block");

        assert_eq!(
            returned_block.block_id(),
            duplicate_id,
            "Returned block should be the rejected duplicate"
        );

        let snap = manager.metrics().snapshot();
        assert_eq!(snap.registrations, 2);
        assert_eq!(snap.registration_dedup, 1);
        // returned_block is still held, so reset pool is empty
        assert_eq!(snap.reset_pool_size, 0);

        // Drop returned_block → back to reset pool
        drop(returned_block);
        assert_eq!(manager.metrics().snapshot().reset_pool_size, 1);
    }
}

// ============================================================================
// BLOCK MATCHING TESTS
// ============================================================================

mod matching_tests {
    use super::*;

    #[test]
    fn test_match_no_blocks() {
        let manager = create_test_manager(10);

        let seq_hashes = vec![create_test_token_block_from_iota(400).kvbm_sequence_hash()];
        let matched_blocks = manager.match_blocks(&seq_hashes);
        assert_eq!(matched_blocks.len(), 0);
    }

    #[test]
    fn test_match_single_block() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        let token_block = create_test_token_block_from_iota(500);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Register a block
        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        let complete_block = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block)
            .expect("Should complete block");
        let _immutable_blocks = manager.register_blocks(vec![complete_block]);

        // One-element prefix matches use the first-hash fast path.
        let matched_blocks = manager.match_blocks(&[seq_hash]);
        assert_eq!(matched_blocks.len(), 1);
        assert_eq!(matched_blocks[0].sequence_hash(), seq_hash);

        let snap = m.snapshot();
        assert_eq!(snap.match_hashes_requested, 1);
        assert_eq!(snap.match_blocks_returned, 1);

        drop(matched_blocks);
        drop(_immutable_blocks);

        // The same API must also reactivate an inactive block.
        let reactivated = manager.match_blocks(&[seq_hash]);
        assert_eq!(reactivated.len(), 1);
        assert_eq!(reactivated[0].sequence_hash(), seq_hash);

        let snap = m.snapshot();
        assert_eq!(snap.match_hashes_requested, 2);
        assert_eq!(snap.match_blocks_returned, 2);
        assert_eq!(snap.inactive_pool_size, 0);
    }

    #[test]
    fn test_match_multiple_blocks() {
        let manager = create_test_manager(10);

        let mut seq_hashes = Vec::new();

        // Register multiple blocks
        for i in 0..4 {
            let tokens = vec![600 + i, 601 + i, 602 + i, 603 + i];
            let token_block = create_token_block(&tokens);
            seq_hashes.push(token_block.kvbm_sequence_hash());

            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            let _immutable_blocks = manager.register_blocks(vec![complete_block]);
        }

        // Match all blocks
        let matched_blocks = manager.match_blocks(&seq_hashes);
        assert_eq!(matched_blocks.len(), 4);

        for (i, matched_block) in matched_blocks.iter().enumerate() {
            assert_eq!(matched_block.sequence_hash(), seq_hashes[i]);
        }

        let snap = manager.metrics().snapshot();
        assert_eq!(snap.match_hashes_requested, 4);
        assert_eq!(snap.match_blocks_returned, 4);
    }

    #[test]
    fn test_match_partial_blocks() {
        let manager = create_test_manager(10);

        let mut seq_hashes = Vec::new();

        // Register only some blocks
        for i in 0..3 {
            let tokens = vec![700 + i, 701 + i, 702 + i, 703 + i];
            let token_block = create_token_block(&tokens);
            seq_hashes.push(token_block.kvbm_sequence_hash());

            if i < 2 {
                // Only register first 2 blocks
                let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
                let complete_block = mutable_blocks
                    .into_iter()
                    .next()
                    .unwrap()
                    .complete(&token_block)
                    .expect("Should complete block");
                let _immutable_blocks = manager.register_blocks(vec![complete_block]);
            }
        }

        // Try to match all 3 - should only get 2
        let matched_blocks = manager.match_blocks(&seq_hashes);
        assert_eq!(matched_blocks.len(), 2);

        for matched_block in matched_blocks {
            assert!(seq_hashes[0..2].contains(&matched_block.sequence_hash()));
        }

        let snap = manager.metrics().snapshot();
        assert_eq!(snap.match_hashes_requested, 3);
        assert_eq!(snap.match_blocks_returned, 2);
    }

    #[test]
    fn test_match_blocks_returns_immutable_blocks() {
        let manager = create_test_manager(10);

        let token_block = create_test_token_block_from_iota(800);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Register a block
        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        let complete_block = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block)
            .expect("Should complete block");
        let _immutable_blocks = manager.register_blocks(vec![complete_block]);

        // Match and verify it's an ImmutableBlock
        let matched_blocks = manager.match_blocks(&[seq_hash]);
        assert_eq!(matched_blocks.len(), 1);

        let immutable_block = &matched_blocks[0];
        assert_eq!(immutable_block.sequence_hash(), seq_hash);

        // Test that we can downgrade it
        let weak_block = immutable_block.downgrade();
        assert_eq!(weak_block.sequence_hash(), seq_hash);
    }
}

// ============================================================================
// SINGLE-LOCK match_blocks REWRITE TESTS
// ============================================================================

/// Coverage for the single-lock `match_prefix_locked_batch` rewrite of
/// `match_blocks`. The pre-rewrite code already resolved each hash as
/// active-or-inactive (via `find_active_match` → `acquire_for_hash`), so
/// these are regression guards: they must pass identically on the old and
/// new code, locking in that collapsing N store-lock cycles into one did
/// not change the prefix the walk returns.
mod single_lock_match_tests {
    use super::*;

    /// Allocate, complete, and register one independent block. Returns its
    /// `SequenceHash` and the strong `ImmutableBlock` handle (hold it to
    /// keep the block `Primary`/active; drop it to push it to `Inactive`).
    fn register_one(
        manager: &BlockManager<TestBlockData>,
        base: u32,
    ) -> (SequenceHash, ImmutableBlock<TestBlockData>) {
        let token_block = create_token_block(&[base, base + 1, base + 2, base + 3]);
        let seq_hash = token_block.kvbm_sequence_hash();
        let mutable = manager
            .allocate_blocks(1)
            .expect("allocate")
            .into_iter()
            .next()
            .unwrap();
        let complete = mutable.complete(&token_block).expect("complete");
        let immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        (seq_hash, immutable)
    }

    /// `[A, A, I, I, A, A]` — a prefix mixing active and inactive blocks
    /// must return all 6. Each hash is resolved active-or-inactive under
    /// the single batched store-lock; an inactive hash in the middle does
    /// NOT truncate the prefix.
    #[test]
    fn match_mixed_active_inactive_prefix_returns_full_length() {
        let manager = create_test_manager(6);

        let mut hashes = Vec::new();
        let mut held = Vec::new();
        for i in 0..6u32 {
            let (h, imm) = register_one(&manager, 1_000 + i * 10);
            hashes.push(h);
            held.push(Some(imm));
        }
        // Drop the immutables for positions 2 and 3 → those fall to Inactive.
        held[2] = None;
        held[3] = None;

        let matched = manager.match_blocks(&hashes);
        assert_eq!(
            matched.len(),
            6,
            "mixed active/inactive prefix must not truncate"
        );
        for (i, block) in matched.iter().enumerate() {
            assert_eq!(block.sequence_hash(), hashes[i], "order preserved at {i}");
        }
    }

    /// `[I, A]` — leading inactive hash, trailing active. Returns 2.
    #[test]
    fn match_inactive_then_active() {
        let manager = create_test_manager(2);
        let (h0, imm0) = register_one(&manager, 2_000);
        let (h1, _imm1) = register_one(&manager, 2_010);
        drop(imm0); // h0 → Inactive; h1 stays active.

        let matched = manager.match_blocks(&[h0, h1]);
        assert_eq!(matched.len(), 2);
        assert_eq!(matched[0].sequence_hash(), h0);
        assert_eq!(matched[1].sequence_hash(), h1);
    }

    /// `[A, I, A]` — inactive hash sandwiched between active ones. Returns 3.
    #[test]
    fn match_active_inactive_active() {
        let manager = create_test_manager(3);
        let (h0, _imm0) = register_one(&manager, 3_000);
        let (h1, imm1) = register_one(&manager, 3_010);
        let (h2, _imm2) = register_one(&manager, 3_020);
        drop(imm1); // h1 → Inactive.

        let matched = manager.match_blocks(&[h0, h1, h2]);
        assert_eq!(matched.len(), 3);
        assert_eq!(matched[1].sequence_hash(), h1);
    }

    /// `[A, A, miss, A]` — an unregistered hash terminates the prefix even
    /// though a registered hash follows it. Returns 2.
    #[test]
    fn match_stops_at_first_total_miss() {
        let manager = create_test_manager(4);
        let (h0, _imm0) = register_one(&manager, 4_000);
        let (h1, _imm1) = register_one(&manager, 4_010);
        let (h3, _imm3) = register_one(&manager, 4_030);
        // `miss` is a hash for a block that was never registered.
        let miss = create_token_block(&[4_020, 4_021, 4_022, 4_023]).kvbm_sequence_hash();

        let matched = manager.match_blocks(&[h0, h1, miss, h3]);
        assert_eq!(
            matched.len(),
            2,
            "prefix terminates at the first total miss"
        );
        assert_eq!(matched[0].sequence_hash(), h0);
        assert_eq!(matched[1].sequence_hash(), h1);
    }

    /// Empty input is an allocation-free early return.
    #[test]
    fn match_empty_input_returns_empty() {
        let manager = create_test_manager(4);
        let _held = register_one(&manager, 5_000);
        assert!(manager.match_blocks(&[]).is_empty());
        assert_eq!(manager.metrics().snapshot().match_blocks_returned, 0);
    }

    /// The batched frequency-tracker touch fires exactly once per returned
    /// block across a mixed active/inactive prefix — N hits → N touches,
    /// no double-count, no miss.
    #[test]
    fn match_mixed_prefix_touches_once_per_returned_block() {
        let (manager, metered) = crate::testing::create_test_manager_metered::<TestBlockData>(5);

        let mut hashes = Vec::new();
        let mut held = Vec::new();
        for i in 0..5u32 {
            let (h, imm) = register_one(&manager, 6_000 + i * 10);
            hashes.push(h);
            held.push(Some(imm));
        }
        // Positions 1 and 3 → Inactive; 0, 2, 4 stay active.
        held[1] = None;
        held[3] = None;

        metered.reset();
        let matched = manager.match_blocks(&hashes);
        assert_eq!(matched.len(), 5);
        assert_eq!(
            metered.touches(),
            5,
            "match_blocks must touch the frequency tracker exactly once per \
             returned block (mix of active hits and inactive resurrections); \
             got {}",
            metered.touches()
        );
    }

    /// A whole-prefix total miss touches nothing and returns empty.
    #[test]
    fn match_total_miss_touches_nothing() {
        let (manager, metered) = crate::testing::create_test_manager_metered::<TestBlockData>(4);
        let _held = register_one(&manager, 7_000);
        let miss = create_token_block(&[9_000, 9_001, 9_002, 9_003]).kvbm_sequence_hash();

        metered.reset();
        assert!(manager.match_blocks(&[miss]).is_empty());
        assert_eq!(metered.touches(), 0, "a total miss must not touch");
    }
}

// ============================================================================
// IMMUTABLE BLOCK AND WEAK BLOCK TESTS
// ============================================================================

mod immutable_block_tests {
    use super::*;

    #[test]
    fn test_immutable_block_downgrade_upgrade() {
        let manager = create_test_manager(10);

        let token_block = create_test_token_block_from_iota(100);
        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        let complete_block = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block)
            .expect("Should complete block");

        let immutable_blocks = manager.register_blocks(vec![complete_block]);
        let immutable_block = immutable_blocks.into_iter().next().unwrap();

        // Test downgrade to WeakBlock
        let weak_block = immutable_block.downgrade();
        assert_eq!(weak_block.sequence_hash(), immutable_block.sequence_hash());

        // Test upgrade from WeakBlock
        let upgraded_block = weak_block.upgrade().expect("Should be able to upgrade");
        assert_eq!(
            upgraded_block.sequence_hash(),
            immutable_block.sequence_hash()
        );
        assert_eq!(upgraded_block.block_id(), immutable_block.block_id());
    }

    #[test]
    fn test_weak_block_upgrade_after_drop() {
        let manager = create_test_manager(10);

        let token_block = create_test_token_block_from_iota(200);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Create a weak block
        let weak_block = {
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            let immutable_blocks = manager.register_blocks(vec![complete_block]);
            let immutable_block = immutable_blocks.into_iter().next().unwrap();

            // Downgrade to weak
            immutable_block.downgrade()
        }; // immutable_block is dropped here

        // The upgrade function should still find the block through the pools
        let upgraded_block = weak_block.upgrade();

        // The result depends on whether the block is still in the pools
        if let Some(block) = upgraded_block {
            assert_eq!(block.sequence_hash(), seq_hash);
        }
    }

    #[test]
    fn test_weak_block_upgrade_nonexistent() {
        let manager = create_test_manager(10);

        let token_block = create_token_block(&[999, 998, 997, 996]); // Keep non-sequential for this test

        // Create an ImmutableBlock and immediately downgrade it
        let weak_block = {
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            let immutable_blocks = manager.register_blocks(vec![complete_block]);
            let immutable_block = immutable_blocks.into_iter().next().unwrap();
            immutable_block.downgrade()
        };

        // Force eviction by filling up the pool with other blocks
        for i in 0..10 {
            let tokens = vec![1000 + i, 1001 + i, 1002 + i, 1003 + i];
            let token_block = create_token_block(&tokens);
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            let _immutable_blocks = manager.register_blocks(vec![complete_block]);
        }

        // Try to upgrade - might fail if the original block was evicted
        let upgraded_block = weak_block.upgrade();
        assert!(upgraded_block.is_none());
        // // This test just verifies that upgrade doesn't panic, result can be None
        // if let Some(block) = upgraded_block {
        //     assert_eq!(
        //         block.sequence_hash(),
        //         create_token_block(&[999, 998, 997, 996]).sequence_hash()
        //     );
        // }
    }

    #[test]
    fn test_multiple_weak_blocks_same_sequence() {
        let manager = create_test_manager(10);

        let token_block = create_test_token_block_from_iota(150);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Create multiple weak blocks from the same immutable block
        let (weak1, weak2, weak3) = {
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            let immutable_blocks = manager.register_blocks(vec![complete_block]);
            let immutable_block = immutable_blocks.into_iter().next().unwrap();

            let w1 = immutable_block.downgrade();
            let w2 = immutable_block.downgrade();
            let w3 = immutable_block.downgrade();
            (w1, w2, w3)
        };

        // All weak blocks should have the same sequence hash
        assert_eq!(weak1.sequence_hash(), seq_hash);
        assert_eq!(weak2.sequence_hash(), seq_hash);
        assert_eq!(weak3.sequence_hash(), seq_hash);

        // All should be able to upgrade
        let upgraded1 = weak1.upgrade().expect("Should upgrade");
        let upgraded2 = weak2.upgrade().expect("Should upgrade");
        let upgraded3 = weak3.upgrade().expect("Should upgrade");

        assert_eq!(upgraded1.sequence_hash(), seq_hash);
        assert_eq!(upgraded2.sequence_hash(), seq_hash);
        assert_eq!(upgraded3.sequence_hash(), seq_hash);
    }
}

// ============================================================================
// UPGRADE FUNCTION TESTS
// ============================================================================

mod upgrade_function_tests {
    use super::*;

    #[test]
    fn test_upgrade_function_finds_active_blocks() {
        let manager = create_test_manager(10);

        let token_block = create_test_token_block_from_iota(250);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Register a block (this puts it in active pool initially)
        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
        let complete_block = mutable_blocks
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block)
            .expect("Should complete block");
        let immutable_blocks = manager.register_blocks(vec![complete_block]);
        let immutable_block = immutable_blocks.into_iter().next().unwrap();

        // Create a weak block and test upgrade
        let weak_block = immutable_block.downgrade();
        let upgraded = weak_block
            .upgrade()
            .expect("Should find block in active pool");
        assert_eq!(upgraded.sequence_hash(), seq_hash);
    }

    #[test]
    fn test_upgrade_function_finds_inactive_blocks() {
        let manager = create_test_manager(20);

        let token_block = create_test_token_block_from_iota(350);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Register a block
        let weak_block = {
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            let immutable_blocks = manager.register_blocks(vec![complete_block]);
            let immutable_block = immutable_blocks.into_iter().next().unwrap();
            immutable_block.downgrade()
        };

        // Force the block to potentially move to inactive pool by creating many other blocks
        for i in 0..10 {
            let tokens = vec![400 + i, 401 + i, 402 + i, 403 + i];
            let token_block = create_token_block(&tokens);
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate blocks");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            let _immutable_blocks = manager.register_blocks(vec![complete_block]);
        }

        // Try to upgrade - should still find the original block
        let upgraded = weak_block.upgrade();
        if let Some(block) = upgraded {
            assert_eq!(block.sequence_hash(), seq_hash);
        }
    }
}

// ============================================================================
// ERROR HANDLING AND EDGE CASE TESTS
// ============================================================================

mod error_handling_tests {
    use super::*;

    #[test]
    fn test_allocation_exhaustion() {
        let manager = create_test_manager(3);

        // Allocate all blocks
        let blocks1 = manager
            .allocate_blocks(2)
            .expect("Should allocate 2 blocks");
        let blocks2 = manager.allocate_blocks(1).expect("Should allocate 1 block");

        // Try to allocate more - should fail
        let blocks3 = manager.allocate_blocks(1);
        assert!(
            blocks3.is_none(),
            "Should not be able to allocate when pool is empty"
        );

        // Drop some blocks and try again
        drop(blocks1);
        drop(blocks2);

        // Blocks should be returned to pool automatically
        let blocks4 = manager.allocate_blocks(1);
        assert!(
            blocks4.is_some(),
            "Should be able to allocate after blocks are returned"
        );
    }

    #[test]
    fn test_empty_sequence_matching() {
        let manager = create_test_manager(10);

        let matched_blocks = manager.match_blocks(&[]);
        assert_eq!(matched_blocks.len(), 0);
    }

    #[test]
    fn test_register_empty_block_list() {
        let manager = create_test_manager(10);

        let immutable_blocks = manager.register_blocks(vec![]);
        assert_eq!(immutable_blocks.len(), 0);
    }
}

// ============================================================================
// INTEGRATION TESTS
// ============================================================================

mod integration_tests {
    use super::*;

    #[test]
    fn test_full_lifecycle_single_block() {
        let manager = create_test_manager(10);

        // 1. Allocate a mutable block
        let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate");
        let mutable_block = mutable_blocks.into_iter().next().unwrap();
        let block_id = mutable_block.block_id();

        // 2. Complete the block
        let token_block = create_test_token_block_from_iota(1);
        let seq_hash = token_block.kvbm_sequence_hash();
        let complete_block = mutable_block
            .complete(&token_block)
            .expect("Should complete block");

        assert_eq!(complete_block.block_id(), block_id);
        assert_eq!(complete_block.sequence_hash(), seq_hash);

        // 3. Register the block
        let immutable_blocks = manager.register_blocks(vec![complete_block]);
        let immutable_block = immutable_blocks.into_iter().next().unwrap();

        assert_eq!(immutable_block.block_id(), block_id);
        assert_eq!(immutable_block.sequence_hash(), seq_hash);

        // 4. Match the block
        let matched_blocks = manager.match_blocks(&[seq_hash]);
        assert_eq!(matched_blocks.len(), 1);
        assert_eq!(matched_blocks[0].sequence_hash(), seq_hash);

        // 5. Create weak reference and upgrade
        let weak_block = immutable_block.downgrade();
        let upgraded_block = weak_block.upgrade().expect("Should upgrade");
        assert_eq!(upgraded_block.sequence_hash(), seq_hash);
    }

    #[rstest]
    #[case("lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lru_backend())]
    #[case("multi_lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_multi_lru_backend())]
    fn test_multiple_blocks_different_backends(
        #[case] backend_name: &str,
        #[case] backend_builder: fn(
            BlockManagerConfigBuilder<TestBlockData>,
        ) -> BlockManagerConfigBuilder<TestBlockData>,
    ) {
        let registry = BlockRegistry::builder()
            .frequency_tracker(FrequencyTrackingCapacity::default().create_tracker())
            .build();
        let manager = backend_builder(
            BlockManager::<TestBlockData>::builder()
                .block_count(20)
                .block_size(4)
                .registry(registry),
        )
        .build()
        .expect("Should build");

        // Allocate, complete, and register blocks using BlockSequenceBuilder
        let base = 1000; // Use fixed base since we only test one backend per test now
        let tokens: Vec<u32> = (base as u32..base as u32 + 20).collect(); // 5 blocks * 4 tokens each = 20 tokens

        let mut seq_hashes = Vec::new();
        let mut complete_blocks = Vec::new();

        // Create token blocks from sequence
        let token_blocks = {
            let token_seq = dynamo_tokens::TokenBlockSequence::from_slice(&tokens, 4, Some(42));
            token_seq.blocks().to_vec()
        };

        for token_block in token_blocks.iter() {
            let seq_hash = token_block.kvbm_sequence_hash();
            seq_hashes.push(seq_hash);

            // Allocate mutable block and complete it
            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(token_block)
                .expect("Should complete block");
            complete_blocks.push(complete_block);
        }

        // Register all blocks
        let _immutable_blocks = manager.register_blocks(complete_blocks);

        // Verify all blocks can be matched
        let matched_blocks = manager.match_blocks(&seq_hashes);
        assert_eq!(
            matched_blocks.len(),
            5,
            "Manager with {} backend should match all blocks",
            backend_name
        );
    }

    #[test]
    fn test_concurrent_allocation_simulation() {
        let manager = create_test_manager(50);

        // Simulate concurrent allocations by interleaving operations
        let mut all_blocks = Vec::new();
        let mut all_hashes = Vec::new();

        // Phase 1: Allocate and complete some blocks
        for i in 0..10 {
            let tokens = vec![2000 + i, 2001 + i, 2002 + i, 2003 + i];
            let token_block = create_token_block(&tokens);
            all_hashes.push(token_block.kvbm_sequence_hash());

            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            all_blocks.push(complete_block);
        }

        // Phase 2: Register half the blocks
        let mut remaining_blocks = all_blocks.split_off(5);
        let _immutable_blocks1 = manager.register_blocks(all_blocks);

        // Phase 3: Allocate more blocks while some are registered
        for i in 10..15 {
            let tokens = vec![2000 + i, 2001 + i, 2002 + i, 2003 + i];
            let token_block = create_token_block(&tokens);
            all_hashes.push(token_block.kvbm_sequence_hash());

            let mutable_blocks = manager.allocate_blocks(1).expect("Should allocate");
            let complete_block = mutable_blocks
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .expect("Should complete block");
            remaining_blocks.push(complete_block);
        }

        // Phase 4: Register remaining blocks
        let _immutable_blocks2 = manager.register_blocks(remaining_blocks);

        // Phase 5: Verify we can match all registered blocks
        let matched_blocks = manager.match_blocks(&all_hashes);
        assert_eq!(
            matched_blocks.len(),
            15,
            "Should match all registered blocks"
        );
    }

    #[test]
    fn test_shared_registry_across_managers() {
        // Create shared registry with frequency tracking
        let tracker = FrequencyTrackingCapacity::Medium.create_tracker();
        let registry = BlockRegistry::builder().frequency_tracker(tracker).build();

        #[derive(Clone, Debug)]
        struct G1;

        #[derive(Clone, Debug)]
        struct G2;

        // Create two managers with different metadata types and policies
        let manager1 = BlockManager::<G1>::builder()
            .block_count(100)
            .block_size(4)
            .registry(registry.clone())
            .duplication_policy(BlockDuplicationPolicy::Allow)
            .with_multi_lru_backend()
            .build()
            .expect("Should build manager1");

        let manager2 = BlockManager::<G2>::builder()
            .block_count(100)
            .block_size(4)
            .registry(registry.clone())
            .duplication_policy(BlockDuplicationPolicy::Reject)
            .with_multi_lru_backend()
            .build()
            .expect("Should build manager2");

        // Verify both managers work
        assert_eq!(manager1.total_blocks(), 100);
        assert_eq!(manager2.total_blocks(), 100);

        // Verify they share the same registry (frequency tracking works across both)
        let token_block = create_test_token_block_from_iota(3000);
        let seq_hash = token_block.kvbm_sequence_hash();

        // Register in manager1
        let mutable_blocks1 = manager1.allocate_blocks(1).expect("Should allocate");
        let complete_block1 = mutable_blocks1
            .into_iter()
            .next()
            .unwrap()
            .complete(&token_block)
            .expect("Should complete");
        let _immutable1 = manager1.register_blocks(vec![complete_block1]);

        // Both managers should see the registered block count in shared registry
        assert!(registry.is_registered(seq_hash));
    }
}

mod capacity_lifecycle_tests {
    use super::*;

    /// Build a BlockManager with any backend. Always includes frequency_tracker
    /// so MultiLRU works; LRU/Lineage ignore it.
    fn create_backend_manager(
        block_count: usize,
        backend_builder: fn(
            BlockManagerConfigBuilder<TestBlockData>,
        ) -> BlockManagerConfigBuilder<TestBlockData>,
    ) -> BlockManager<TestBlockData> {
        let registry = BlockRegistry::builder()
            .frequency_tracker(FrequencyTrackingCapacity::default().create_tracker())
            .build();
        backend_builder(
            BlockManager::<TestBlockData>::builder()
                .block_count(block_count)
                .block_size(4)
                .registry(registry),
        )
        .build()
        .expect("Should build manager")
    }

    /// Allocate N, complete each with a unique token block, register all.
    /// Returns the ImmutableBlocks.
    fn allocate_complete_register_all(
        manager: &BlockManager<TestBlockData>,
        block_count: usize,
        iota_base: u32,
    ) -> Vec<ImmutableBlock<TestBlockData>> {
        let mutable = manager
            .allocate_blocks(block_count)
            .expect("allocate failed");
        let complete: Vec<_> = mutable
            .into_iter()
            .enumerate()
            .map(|(i, mb)| {
                let tb = create_iota_token_block(iota_base + (i as u32 * 4), 4);
                mb.complete(&tb).expect("complete failed")
            })
            .collect();
        manager.register_blocks(complete)
    }

    // ====================================================================
    // 1. Full capacity register and return to inactive
    // ====================================================================

    #[rstest]
    #[case("lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lru_backend())]
    #[case("multi_lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_multi_lru_backend())]
    #[case("lineage", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lineage_backend())]
    fn test_full_capacity_register_and_return_to_inactive(
        #[case] _backend_name: &str,
        #[case] backend_builder: fn(
            BlockManagerConfigBuilder<TestBlockData>,
        ) -> BlockManagerConfigBuilder<TestBlockData>,
    ) {
        let manager = create_backend_manager(32, backend_builder);

        // Allocate, complete, register all 32
        let immutable = allocate_complete_register_all(&manager, 32, 5000);
        assert_eq!(manager.store.inactive_len(), 0);
        assert_eq!(manager.store.reset_len(), 0);

        let snap = manager.metrics.snapshot();
        assert_eq!(snap.reset_pool_size, 0);
        assert_eq!(snap.inactive_pool_size, 0);

        // Drop all ImmutableBlocks → should all land in inactive pool
        drop(immutable);
        assert_eq!(manager.store.inactive_len(), 32);
        assert_eq!(manager.store.reset_len(), 0);

        // Check metrics
        let snap = manager.metrics.snapshot();
        assert_eq!(snap.allocations, 32);
        assert_eq!(snap.registrations, 32);
        assert_eq!(snap.inflight_immutable, 0);
        assert_eq!(snap.inflight_mutable, 0);
        assert_eq!(snap.inactive_pool_size, 32);
        assert_eq!(snap.reset_pool_size, 0);

        // Check totals
        assert_eq!(manager.available_blocks(), 32);
        assert_eq!(manager.total_blocks(), 32);
    }

    // ====================================================================
    // 2. Full capacity eviction cycle
    // ====================================================================

    #[rstest]
    #[case("lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lru_backend())]
    #[case("multi_lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_multi_lru_backend())]
    #[case("lineage", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lineage_backend())]
    fn test_full_capacity_eviction_cycle(
        #[case] _backend_name: &str,
        #[case] backend_builder: fn(
            BlockManagerConfigBuilder<TestBlockData>,
        ) -> BlockManagerConfigBuilder<TestBlockData>,
    ) {
        let manager = create_backend_manager(16, backend_builder);

        // Allocate, register all 16
        let immutable = allocate_complete_register_all(&manager, 16, 6000);
        assert_eq!(manager.store.reset_len(), 0);
        assert_eq!(manager.store.inactive_len(), 0);

        // Drop all → inactive pool
        drop(immutable);
        assert_eq!(manager.store.inactive_len(), 16);
        assert_eq!(manager.store.reset_len(), 0);

        let snap = manager.metrics.snapshot();
        assert_eq!(snap.inactive_pool_size, 16);
        assert_eq!(snap.reset_pool_size, 0);

        // Allocate 16 again (evicts from inactive)
        let mutable = manager.allocate_blocks(16).expect("second allocate failed");
        assert_eq!(manager.store.inactive_len(), 0);
        assert_eq!(manager.store.reset_len(), 0);

        let snap = manager.metrics.snapshot();
        assert_eq!(snap.inactive_pool_size, 0);
        assert_eq!(snap.reset_pool_size, 0);

        // Drop mutable blocks → reset pool
        drop(mutable);
        assert_eq!(manager.store.reset_len(), 16);
        assert_eq!(manager.store.inactive_len(), 0);

        // Check metrics
        let snap = manager.metrics.snapshot();
        assert_eq!(snap.evictions, 16);
        assert_eq!(snap.allocations, 32);
        assert_eq!(snap.reset_pool_size, 16);
        assert_eq!(snap.inactive_pool_size, 0);
    }

    // ====================================================================
    // 3. Mutable drops go to reset, not inactive
    // ====================================================================

    #[test]
    fn test_mutable_drops_go_to_reset_not_inactive() {
        let manager = create_backend_manager(16, |b| b.with_lru_backend());

        let mutable = manager.allocate_blocks(16).expect("allocate failed");
        assert_eq!(manager.store.reset_len(), 0);
        assert_eq!(manager.store.inactive_len(), 0);

        // Drop all mutable blocks → reset pool
        drop(mutable);
        assert_eq!(manager.store.reset_len(), 16);
        assert_eq!(manager.store.inactive_len(), 0);

        let snap = manager.metrics.snapshot();
        assert_eq!(snap.inflight_mutable, 0);
        assert_eq!(snap.registrations, 0);
    }

    // ====================================================================
    // 4. Complete drops go to reset, not inactive
    // ====================================================================

    #[test]
    fn test_complete_drops_go_to_reset_not_inactive() {
        let manager = create_backend_manager(16, |b| b.with_lru_backend());

        let mutable = manager.allocate_blocks(16).expect("allocate failed");
        let complete: Vec<_> = mutable
            .into_iter()
            .enumerate()
            .map(|(i, mb)| {
                let tb = create_iota_token_block(7000 + (i as u32 * 4), 4);
                mb.complete(&tb).expect("complete failed")
            })
            .collect();
        assert_eq!(manager.store.reset_len(), 0);

        // Drop all CompleteBlocks (not registered) → reset pool
        drop(complete);
        assert_eq!(manager.store.reset_len(), 16);
        assert_eq!(manager.store.inactive_len(), 0);

        let snap = manager.metrics.snapshot();
        assert_eq!(snap.stagings, 16);
        assert_eq!(snap.registrations, 0);
    }

    // ====================================================================
    // 5. Mixed return paths
    // ====================================================================

    #[rstest]
    #[case("lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lru_backend())]
    #[case("multi_lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_multi_lru_backend())]
    #[case("lineage", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lineage_backend())]
    fn test_mixed_return_paths(
        #[case] _backend_name: &str,
        #[case] backend_builder: fn(
            BlockManagerConfigBuilder<TestBlockData>,
        ) -> BlockManagerConfigBuilder<TestBlockData>,
    ) {
        let manager = create_backend_manager(24, backend_builder);

        let mutable = manager.allocate_blocks(24).expect("allocate failed");
        let mut mutable_iter = mutable.into_iter();

        // Group A (8): drop as MutableBlocks
        {
            let group_a: Vec<_> = mutable_iter.by_ref().take(8).collect();
            drop(group_a);
        }
        assert_eq!(manager.store.reset_len(), 8);
        assert_eq!(manager.metrics.snapshot().reset_pool_size, 8);

        // Group B (8): complete, drop as CompleteBlocks
        {
            let group_b: Vec<_> = mutable_iter
                .by_ref()
                .take(8)
                .enumerate()
                .map(|(i, mb)| {
                    let tb = create_iota_token_block(8000 + (i as u32 * 4), 4);
                    mb.complete(&tb).expect("complete failed")
                })
                .collect();
            drop(group_b);
        }
        assert_eq!(manager.store.reset_len(), 16);
        assert_eq!(manager.metrics.snapshot().reset_pool_size, 16);

        // Group C (8): complete, register, hold ImmutableBlocks
        let group_c_complete: Vec<_> = mutable_iter
            .enumerate()
            .map(|(i, mb)| {
                let tb = create_iota_token_block(8100 + (i as u32 * 4), 4);
                mb.complete(&tb).expect("complete failed")
            })
            .collect();
        let group_c_immutable = manager.register_blocks(group_c_complete);
        assert_eq!(manager.store.inactive_len(), 0);

        // Drop Group C → inactive pool
        drop(group_c_immutable);
        assert_eq!(manager.store.inactive_len(), 8);
        assert_eq!(manager.store.reset_len(), 16);

        // Check totals
        assert_eq!(manager.available_blocks(), 24);

        // Check metrics
        let snap = manager.metrics.snapshot();
        assert_eq!(snap.allocations, 24);
        assert_eq!(snap.stagings, 16); // Group B (8) + Group C (8)
        assert_eq!(snap.registrations, 8);
        assert_eq!(snap.inflight_mutable, 0);
        assert_eq!(snap.inflight_immutable, 0);
        assert_eq!(snap.inactive_pool_size, 8);
        assert_eq!(snap.reset_pool_size, 16);
    }

    // ====================================================================
    // 6. MultiLRU all cold blocks at capacity (regression)
    // ====================================================================

    #[test]
    fn test_multi_lru_all_cold_blocks_at_capacity() {
        let manager = create_backend_manager(64, |b| b.with_multi_lru_backend());

        // Allocate, register all 64 (no frequency touches → all cold)
        let immutable = allocate_complete_register_all(&manager, 64, 9000);

        // Drop all → all go to level 0 (cold). With old div_ceil(4)=16
        // per-level capacity this would panic at block 17.
        drop(immutable);
        assert_eq!(manager.store.inactive_len(), 64);

        let snap = manager.metrics.snapshot();
        assert_eq!(snap.evictions, 0);
        assert_eq!(snap.allocations, 64);
    }

    // ====================================================================
    // 7. MultiLRU mixed frequency levels
    // ====================================================================

    #[test]
    fn test_multi_lru_mixed_frequency_levels() {
        // thresholds [3, 8, 15]: cold=0-2, warm=3-7, hot=8-14, very_hot=15
        let registry = BlockRegistry::builder()
            .frequency_tracker(FrequencyTrackingCapacity::default().create_tracker())
            .build();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(32)
            .block_size(4)
            .registry(registry)
            .with_multi_lru_backend()
            .build()
            .expect("Should build manager");

        // Allocate, register all 32
        let immutable = allocate_complete_register_all(&manager, 32, 10000);

        // Touch frequency tracker for different blocks to spread across levels
        let tracker = manager.block_registry().frequency_tracker().unwrap();
        for block in &immutable {
            let hash = block.sequence_hash();
            let idx = block.block_id();
            let touches = if idx < 8 {
                0 // cold: 0-7 untouched
            } else if idx < 16 {
                3 // warm: 8-15
            } else if idx < 24 {
                8 // hot: 16-23
            } else {
                15 // very hot: 24-31
            };
            for _ in 0..touches {
                tracker.touch(hash.as_u128());
            }
        }

        // Drop all → distributed across 4 levels
        drop(immutable);
        assert_eq!(manager.store.inactive_len(), 32);

        // Allocate 32 again → evicts from all levels
        let mutable = manager.allocate_blocks(32).expect("eviction allocate");
        assert_eq!(manager.store.inactive_len(), 0);
        drop(mutable);

        let snap = manager.metrics.snapshot();
        assert_eq!(snap.evictions, 32);
        assert_eq!(snap.allocations, 64);
    }

    // ====================================================================
    // 8. Double lifecycle cycle
    // ====================================================================

    #[rstest]
    #[case("lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lru_backend())]
    #[case("multi_lru", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_multi_lru_backend())]
    #[case("lineage", |b: BlockManagerConfigBuilder<TestBlockData>| b.with_lineage_backend())]
    fn test_double_lifecycle_cycle(
        #[case] _backend_name: &str,
        #[case] backend_builder: fn(
            BlockManagerConfigBuilder<TestBlockData>,
        ) -> BlockManagerConfigBuilder<TestBlockData>,
    ) {
        let manager = create_backend_manager(16, backend_builder);
        let m = &manager.metrics;

        // Cycle 1: allocate, register, drop → inactive
        {
            let immutable = allocate_complete_register_all(&manager, 16, 11000);
            drop(immutable);
        }
        assert_eq!(manager.store.inactive_len(), 16);
        let snap = m.snapshot();
        assert_eq!(snap.inactive_pool_size, 16);
        assert_eq!(snap.reset_pool_size, 0);

        // Evict all: allocate from inactive, drop mutable → reset
        {
            let mutable = manager.allocate_blocks(16).expect("eviction allocate");

            let snap = m.snapshot();
            assert_eq!(snap.inactive_pool_size, 0);
            assert_eq!(snap.reset_pool_size, 0);

            drop(mutable);
        }
        assert_eq!(manager.store.reset_len(), 16);
        assert_eq!(manager.store.inactive_len(), 0);
        let snap = m.snapshot();
        assert_eq!(snap.reset_pool_size, 16);
        assert_eq!(snap.inactive_pool_size, 0);

        // Cycle 2: allocate, register (different tokens), drop → inactive
        {
            let immutable = allocate_complete_register_all(&manager, 16, 12000);
            drop(immutable);
        }
        assert_eq!(manager.store.inactive_len(), 16);

        // Check metrics
        let snap = m.snapshot();
        assert_eq!(snap.allocations, 48);
        assert_eq!(snap.registrations, 32);
        assert_eq!(snap.evictions, 16);
        assert_eq!(snap.inactive_pool_size, 16);
        assert_eq!(snap.reset_pool_size, 0);

        // Check totals
        assert_eq!(manager.available_blocks(), 16);
        assert_eq!(manager.total_blocks(), 16);
    }
}

// ============================================================================
// SCAN MATCHES POOL SIZE GAUGE TESTS
// ============================================================================

mod scan_matches_tests {
    use super::*;

    #[test]
    fn test_scan_matches_with_pool_size_gauges() {
        let manager = create_test_manager(10);
        let m = manager.metrics();

        // Register 3 blocks with distinct hashes
        let mut seq_hashes = Vec::new();
        for i in 0..3 {
            let tb = create_iota_token_block(13000 + (i as u32 * 4), 4);
            seq_hashes.push(tb.kvbm_sequence_hash());

            let mutable = manager.allocate_blocks(1).expect("allocate");
            let complete = mutable
                .into_iter()
                .next()
                .unwrap()
                .complete(&tb)
                .expect("complete");
            let immutable = manager.register_blocks(vec![complete]);
            drop(immutable);
        }

        // All 3 should be in inactive pool
        assert_eq!(manager.store.inactive_len(), 3);
        let snap = m.snapshot();
        assert_eq!(snap.inactive_pool_size, 3);
        assert_eq!(snap.reset_pool_size, 7);

        // scan_matches with 2 matching + 1 missing hash
        let missing_hash = create_iota_token_block(99000, 4).kvbm_sequence_hash();
        let scan_hashes = vec![seq_hashes[0], missing_hash, seq_hashes[2]];

        let found = manager.scan_matches(&scan_hashes, true);
        assert_eq!(found.len(), 2);

        // inactive_pool_size decreased by 2
        let snap = m.snapshot();
        assert_eq!(snap.inactive_pool_size, 1);

        // Drop scanned blocks → they return to inactive
        drop(found);

        let snap = m.snapshot();
        assert_eq!(snap.inactive_pool_size, 3);
    }
}

// ============================================================================
// RACE-CONDITION REGRESSION TESTS
//
// These tests cover the three high-severity races that motivated the
// move of active-by-hash, slot Weak ownership, and presence refcounting
// into BlockStore. They stress concurrent code paths that were known to
// produce inconsistent state under the previous two-lock design.
// ============================================================================

mod race_regression_tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::thread;

    use crate::pools::BlockDuplicationPolicy;

    fn build_manager_with_policy(
        block_count: usize,
        policy: BlockDuplicationPolicy,
    ) -> BlockManager<TestBlockData> {
        let registry = BlockRegistry::new();
        BlockManager::<TestBlockData>::builder()
            .block_count(block_count)
            .block_size(4)
            .registry(registry)
            .duplication_policy(policy)
            .build()
            .expect("build manager")
    }

    /// Finding 1: an active-pool lookup that races with the last
    /// `ImmutableBlock` drop must either succeed (returning the existing
    /// or a freshly resurrected block) or miss cleanly. It must never
    /// produce a state where two slots claim the same `seq_hash` as
    /// Primary.
    #[test]
    fn active_lookup_concurrent_with_last_drop() {
        const ITERATIONS: usize = 200;
        let manager = Arc::new(create_test_manager(8));

        for i in 0..ITERATIONS {
            let token_block = create_test_token_block_from_iota((10_000 + i * 4) as u32);
            let seq_hash = token_block.kvbm_sequence_hash();

            // Stage and register one primary.
            let mutables = manager.allocate_blocks(1).unwrap();
            let complete = mutables
                .into_iter()
                .next()
                .unwrap()
                .complete(&token_block)
                .unwrap();
            let immutable = manager
                .register_blocks(vec![complete])
                .into_iter()
                .next()
                .unwrap();

            // Race: thread A drops the last strong reference; thread B
            // looks the hash up. Repeat with manager-shared barriers.
            let manager_a = Arc::clone(&manager);
            let manager_b = Arc::clone(&manager);
            let drop_thread = thread::spawn(move || {
                drop(immutable);
                // One additional touch to ensure release_primary runs.
                manager_a.available_blocks();
            });
            let lookup_thread = thread::spawn(move || manager_b.match_blocks(&[seq_hash]));

            drop_thread.join().unwrap();
            let matched = lookup_thread.join().unwrap();
            assert!(
                matched.len() <= 1,
                "double-primary detected for {seq_hash:?}"
            );

            // Drop the lookup result; the system must converge.
            drop(matched);

            // Total slots must always equal block_count.
            assert_eq!(manager.total_blocks(), 8);
        }
    }

    /// Finding 2: when a block is evicted from the inactive pool while
    /// another thread re-registers a fresh `CompleteBlock` for the same
    /// hash, `check_presence::<T>` must report `true` afterwards. The
    /// previous design lost the new presence marker to the trailing
    /// `mark_absent` from the eviction path.
    #[test]
    fn eviction_concurrent_with_reregister_preserves_presence() {
        const ITERATIONS: usize = 100;
        // 1 block so a fresh registration must evict the inactive entry.
        let manager = Arc::new(create_test_manager(1));

        for i in 0..ITERATIONS {
            let token_a = create_test_token_block_from_iota((20_000 + i * 8) as u32);
            let token_b = create_test_token_block_from_iota((20_000 + i * 8 + 4) as u32);
            let hash_a = token_a.kvbm_sequence_hash();
            let hash_b = token_b.kvbm_sequence_hash();

            // Register one block, drop it so it lands in inactive.
            let mut mutables = manager.allocate_blocks(1).unwrap();
            let complete = mutables.pop().unwrap().complete(&token_a).unwrap();
            let immutable = manager
                .register_blocks(vec![complete])
                .into_iter()
                .next()
                .unwrap();
            drop(immutable);

            // Now allocate (forcing eviction of hash_a) and concurrently
            // register hash_b (the freshly evicted slot will be re-used
            // for hash_b). With one slot total, the only path possible
            // is "register a fresh hash_b that displaces hash_a".
            let mut mutables = manager.allocate_blocks(1).unwrap();
            let complete_b = mutables.pop().unwrap().complete(&token_b).unwrap();
            let immutable_b = manager
                .register_blocks(vec![complete_b])
                .into_iter()
                .next()
                .unwrap();

            // hash_a must no longer be present (evicted), hash_b must be
            // present.
            let presence = manager
                .block_registry()
                .check_presence::<TestBlockData>(&[hash_a, hash_b]);
            assert_eq!(
                presence,
                vec![(hash_a, false), (hash_b, true)],
                "iteration {i}: presence after eviction-vs-register"
            );

            drop(immutable_b);
        }
    }

    /// Finding 3: dropping an allowed duplicate must not clear presence
    /// while the primary is still alive. With the old boolean-set
    /// presence_markers, `release_duplicate` unconditionally cleared
    /// presence even though a primary remained.
    #[test]
    fn duplicate_drop_preserves_presence() {
        let manager = build_manager_with_policy(4, BlockDuplicationPolicy::Allow);
        let token = create_test_token_block_from_iota(30_000);

        // Allocate two slots, complete both with the same hash. The
        // second registration becomes a duplicate.
        let mutables = manager.allocate_blocks(2).unwrap();
        let mut iter = mutables.into_iter();
        let complete_primary = iter.next().unwrap().complete(&token).unwrap();
        let complete_dup = iter.next().unwrap().complete(&token).unwrap();

        let primary = manager
            .register_blocks(vec![complete_primary])
            .into_iter()
            .next()
            .unwrap();
        let dup = manager
            .register_blocks(vec![complete_dup])
            .into_iter()
            .next()
            .unwrap();

        let handle = primary.registration_handle();
        assert!(handle.has_block::<TestBlockData>(), "before any drop");

        // Drop the duplicate: presence must remain true (primary still
        // alive).
        drop(dup);
        assert!(
            handle.has_block::<TestBlockData>(),
            "after duplicate drop, primary still alive"
        );

        // Drop the primary: it transitions to Inactive — still
        // presence-bearing.
        drop(primary);
        assert!(
            handle.has_block::<TestBlockData>(),
            "after primary drop, slot in Inactive still counts"
        );
    }

    /// Allocation atomicity: with `free + inactive == N`, two concurrent
    /// requests for `N` blocks each must not both succeed at the same
    /// time. We synchronize all threads at a barrier before allocating
    /// and have each successful thread hold its blocks until all
    /// threads have attempted, so no thread can refill the pool early.
    #[test]
    fn allocate_atomic_no_over_commit_under_contention() {
        use std::sync::Barrier;

        const TOTAL: usize = 16;
        const THREADS: usize = 8;
        let manager = Arc::new(create_test_manager(TOTAL));
        let granted = Arc::new(AtomicUsize::new(0));
        let start = Arc::new(Barrier::new(THREADS));
        let after_alloc = Arc::new(Barrier::new(THREADS));

        let handles: Vec<_> = (0..THREADS)
            .map(|_| {
                let m = Arc::clone(&manager);
                let g = Arc::clone(&granted);
                let s = Arc::clone(&start);
                let a = Arc::clone(&after_alloc);
                thread::spawn(move || {
                    s.wait();
                    let blocks = m.allocate_blocks(TOTAL);
                    if let Some(b) = &blocks {
                        g.fetch_add(b.len(), Ordering::SeqCst);
                    }
                    // Hold (or not) until everyone has attempted; this
                    // prevents an early dropper from refilling the pool
                    // and giving a second thread a green light.
                    a.wait();
                    drop(blocks);
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }

        // Exactly one thread (or zero, in pathological scheduling)
        // should have received TOTAL blocks. No double-allocation.
        let g = granted.load(Ordering::SeqCst);
        assert!(
            g == 0 || g == TOTAL,
            "concurrent over-commit detected: granted={g}, expected 0 or {TOTAL}"
        );
        assert_eq!(manager.available_blocks(), TOTAL);
    }
}

// ============================================================================
// LOCK-ORDER ENFORCEMENT (tracing-mutex DAG)
//
// Under `#[cfg(test)]` the crate's parking_lot::Mutex types are
// swapped for `tracing_mutex::parkinglot::Mutex`, which builds a
// global lock-acquisition DAG and panics on cycle detection. This
// runtime-enforces the documented `attachments → store` ordering
// throughout the test suite. The sentinel test below proves the DAG
// is wired and active — if `tracing-mutex` is ever silently dropped
// or downgraded, this test stops panicking and the
// `#[should_panic]` mismatch flags the regression.
// ============================================================================

mod lock_order_enforcement_tests {
    use tracing_mutex::parkinglot::Mutex;

    /// Sentinel: deliberately introduce a cycle (a→b followed by
    /// b→a) using two `tracing_mutex::parkinglot::Mutex` instances
    /// drawn from the same dependency-tracking type that the crate's
    /// real locks use under `#[cfg(test)]`. The DAG must detect the
    /// cycle and panic. Failing this test means lock-order
    /// enforcement is no longer in place crate-wide.
    #[test]
    #[should_panic(expected = "Found cycle in mutex dependency graph")]
    fn deliberate_inversion_is_caught_by_tracing_mutex_dag() {
        let a: Mutex<()> = Mutex::new(());
        let b: Mutex<()> = Mutex::new(());

        // Forward edge a → b.
        {
            let _ga = a.lock();
            let _gb = b.lock();
        }
        // Reverse edge b → a — DAG cycle; tracing-mutex panics here.
        let _gb = b.lock();
        let _ga = a.lock();
    }
}

// ============================================================================
// AUDIT-COUNTER COVERAGE TESTS
//
// These tests target normally-rare branches by asserting on the audit
// counters added to BlockPoolMetrics. They catch regressions that
// emergent-behavior assertions would miss (e.g. the multi-LRU
// double-touch slipped past behavior tests because TinyLFU is a sketch
// and `count()` is approximate; an exact `touches()` counter on a
// metered FrequencyTracker fails loudly the moment it doubles).
// ============================================================================

mod audit_counter_tests {
    use super::*;
    use std::num::NonZeroUsize;
    use std::sync::Arc;
    use std::thread;

    use crate::SequenceHash;
    use crate::blocks::BlockId;
    use crate::manager::FrequencyTrackingCapacity;
    use crate::pools::backends::MultiLruBackend;
    use crate::pools::store::InactiveIndex;
    use crate::testing::MeteredFrequencyTracker;

    fn build_manager_with_metered_multi_lru(
        block_count: usize,
    ) -> (BlockManager<TestBlockData>, Arc<MeteredFrequencyTracker>) {
        let metered =
            MeteredFrequencyTracker::with_tinylfu(FrequencyTrackingCapacity::default().size());
        let registry = BlockRegistry::builder()
            .frequency_tracker(metered.clone())
            .build();
        let mgr = BlockManager::<TestBlockData>::builder()
            .block_count(block_count)
            .block_size(4)
            .registry(registry)
            .with_multi_lru_backend()
            .build()
            .expect("build manager");
        (mgr, metered)
    }

    /// Exact-call counter test: a single `match_blocks([hash])` against
    /// a hash that lives in the inactive pool must increment the
    /// frequency tracker `touch()` exactly once. The previous design
    /// double-counted (registry touch + backend touch). This test would
    /// have failed loudly when the double-touch was introduced.
    #[test]
    fn match_inactive_block_touches_frequency_tracker_exactly_once() {
        let (manager, metered) = build_manager_with_metered_multi_lru(4);

        // Stage one block, register it, drop the immutable so it lands
        // in inactive.
        let token = create_test_token_block_from_iota(40_000);
        let hash = token.kvbm_sequence_hash();
        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        drop(immutable);

        // Reset counters to isolate the match() under test.
        metered.reset();

        let matched = manager.match_blocks(&[hash]);
        assert_eq!(matched.len(), 1);
        assert_eq!(
            metered.touches(),
            1,
            "match_blocks against an inactive hash must touch the frequency \
             tracker exactly once; got {} (likely a registry+backend \
             double-touch regression)",
            metered.touches()
        );
    }

    /// Same invariant for `scan_matches(touch=true)`.
    #[test]
    fn scan_inactive_block_touches_frequency_tracker_exactly_once() {
        let (manager, metered) = build_manager_with_metered_multi_lru(4);
        let token = create_test_token_block_from_iota(40_100);
        let hash = token.kvbm_sequence_hash();
        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        drop(immutable);

        metered.reset();
        let scanned = manager.scan_matches(&[hash], /*touch=*/ true);
        assert_eq!(scanned.len(), 1);
        assert_eq!(
            metered.touches(),
            1,
            "scan_matches(touch=true) against an inactive hash must touch \
             the frequency tracker exactly once; got {}",
            metered.touches()
        );
    }

    /// `scan_matches(touch=false)` must not touch.
    #[test]
    fn scan_inactive_block_with_touch_false_does_not_touch() {
        let (manager, metered) = build_manager_with_metered_multi_lru(4);
        let token = create_test_token_block_from_iota(40_200);
        let hash = token.kvbm_sequence_hash();
        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        drop(immutable);

        metered.reset();
        let scanned = manager.scan_matches(&[hash], /*touch=*/ false);
        assert_eq!(scanned.len(), 1);
        assert_eq!(metered.touches(), 0, "touch=false must not touch");
    }

    /// `match_blocks` against an *active* hash also touches exactly once.
    #[test]
    fn match_active_block_touches_frequency_tracker_exactly_once() {
        let (manager, metered) = build_manager_with_metered_multi_lru(4);
        let token = create_test_token_block_from_iota(40_300);
        let hash = token.kvbm_sequence_hash();
        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let _immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        // Hold _immutable so the slot stays Primary (active).

        metered.reset();
        let matched = manager.match_blocks(&[hash]);
        assert_eq!(matched.len(), 1);
        assert_eq!(
            metered.touches(),
            1,
            "match_blocks on an active hash should touch exactly once"
        );
    }

    /// Deterministic eager-transition test using the test-only
    /// `pause_release_primary` hook on `BlockStore`. A held guard
    /// blocks every `release_primary` *before* it takes the store
    /// lock, so the test can:
    ///   1. Spawn a thread that drops the last `ImmutableBlock`. Its
    ///      `Inner::drop` enters `release_primary` and parks on the
    ///      gate — the `Arc` strong count is 0 but the slot is still
    ///      `Primary` with a now-dead `Weak`.
    ///   2. From the main thread call `match_blocks([hash])`. It takes
    ///      the store lock, sees `Primary` with a dead `Weak`, and
    ///      drives `eager_primary_to_inactive_locked` then resurrects
    ///      from the inactive pool.
    ///   3. Release the gate; the parked drop completes and observes
    ///      the slot is no longer `Primary` for its `self_ptr`, so it
    ///      no-ops via `release_primary_noop`.
    ///
    /// Both audit counters tick exactly once. No timing dependencies.
    #[test]
    fn eager_primary_to_inactive_is_deterministic_with_pause_hook() {
        let manager = Arc::new(create_test_manager(4));
        let token = create_test_token_block_from_iota(70_000);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();

        let store = manager.store_for_test();

        let snap_before = manager.metrics().snapshot();
        assert_eq!(snap_before.eager_primary_to_inactive_total, 0);
        assert_eq!(snap_before.release_primary_noop_total, 0);

        // Hold the gate. Spawn a thread that drops the immutable —
        // its Inner::drop will park inside release_primary after its
        // own Arc strong-count went to zero.
        let gate = store.pause_release_primary();
        let arrivals_before = store.release_primary_arrivals();
        let drop_t = thread::spawn(move || drop(immutable));

        // Spin (yielding) until the drop thread has entered
        // release_primary and is about to park on the gate. The
        // arrivals counter is bumped at the first instruction of
        // release_primary, so once it ticks we know the drop has
        // committed to the gate path; the gate we hold then forces
        // it to park before mutating any slot state. No sleep — no
        // scheduler dependency.
        while store.release_primary_arrivals() == arrivals_before {
            std::thread::yield_now();
        }

        // Now the slot is `Primary { weak: dead }`. A lookup should
        // drive the eager transition and resurrect under one lock.
        let matched = manager.match_blocks(&[hash]);
        assert_eq!(matched.len(), 1, "lookup must resurrect");
        let snap_mid = manager.metrics().snapshot();
        assert_eq!(
            snap_mid.eager_primary_to_inactive_total, 1,
            "eager-transition counter must tick exactly once"
        );

        // Release the gate FIRST so the parked drop_t can run. We
        // cannot drop `matched` while holding the gate — that would
        // re-enter `release_primary` on the current thread and
        // deadlock against our own held guard (parking_lot::Mutex is
        // non-reentrant).
        drop(gate);
        drop_t.join().unwrap();

        let snap_after_drop = manager.metrics().snapshot();
        assert_eq!(
            snap_after_drop.release_primary_noop_total, 1,
            "release-primary no-op must tick exactly once (the parked \
             drop saw a slot that no longer matched its self_ptr)"
        );

        // Now safely drop the resurrected matched. This goes through
        // a normal (non-noop) `release_primary`, which must NOT bump
        // the no-op counter again.
        drop(matched);
        let snap_final = manager.metrics().snapshot();
        assert_eq!(
            snap_final.release_primary_noop_total, 1,
            "no-op counter unchanged after normal drop"
        );
    }

    /// `allocate_atomic` rollback path: wire the manager against a fake
    /// `InactiveIndex` that lies about its `len()` so `allocate(n)`
    /// returns fewer than `n`. The defensive rollback in
    /// `BlockStore::allocate_atomic` must restore reset-pool order, leave
    /// inactive intact, and bump `allocate_atomic_rollback_total`.
    #[test]
    fn allocate_atomic_rollback_counter_ticks_with_under_allocating_backend() {
        // A backend that claims `len() == reported_len` but returns 0
        // pairs from `allocate()`. Built by wrapping a real
        // `MultiLruBackend` and overriding only `len()`.
        struct UnderAllocatingBackend {
            inner: MultiLruBackend,
            reported_len: usize,
        }
        impl InactiveIndex for UnderAllocatingBackend {
            fn find_matches(
                &mut self,
                hashes: &[SequenceHash],
                touch: bool,
            ) -> Vec<(SequenceHash, BlockId)> {
                self.inner.find_matches(hashes, touch)
            }
            fn scan_matches(
                &mut self,
                hashes: &[SequenceHash],
                touch: bool,
            ) -> Vec<(SequenceHash, BlockId)> {
                self.inner.scan_matches(hashes, touch)
            }
            fn allocate(&mut self, _count: usize) -> Vec<(SequenceHash, BlockId)> {
                Vec::new() // Under-allocates: returns 0 regardless.
            }
            fn insert(&mut self, seq_hash: SequenceHash, block_id: BlockId) {
                self.inner.insert(seq_hash, block_id);
            }
            fn len(&self) -> usize {
                self.reported_len
            }
            fn has(&self, seq_hash: SequenceHash) -> bool {
                self.inner.has(seq_hash)
            }
            fn take(&mut self, seq_hash: SequenceHash, block_id: BlockId) -> bool {
                self.inner.take(seq_hash, block_id)
            }
        }

        // Build a BlockStore directly with the under-allocating backend.
        // We can't easily go through the BlockManager builder for this
        // because it picks its own backend; instead we hand-roll the
        // store and call `allocate_atomic` against it.
        use crate::metrics::BlockPoolMetrics;
        use crate::pools::store::BlockStore;

        let metrics = Arc::new(BlockPoolMetrics::new("test".to_string()));
        let tracker = FrequencyTrackingCapacity::default().create_tracker();
        let backend = UnderAllocatingBackend {
            inner: MultiLruBackend::new(NonZeroUsize::new(4).unwrap(), tracker),
            reported_len: 2, // lie: claims 2, allocate() returns 0
        };
        let store: Arc<BlockStore<TestBlockData>> =
            BlockStore::new(4, 4, Box::new(backend), metrics.clone(), false);

        // free.len() is 4 (all reset). Asking for 5 forces from_inactive=1
        // which trips into the allocate path → backend lies → rollback.
        let result = store.allocate_atomic(5);
        assert!(result.is_none(), "rollback must yield None");
        let snap = metrics.snapshot();
        assert_eq!(
            snap.allocate_atomic_rollback_total, 1,
            "rollback counter must tick exactly once"
        );
        // Reset pool must be intact (FIFO preserved).
        assert_eq!(store.reset_len(), 4, "all reset blocks restored");
    }

    /// Concurrency stress against `allocate_atomic` to confirm the
    /// rollback counter stays at zero with shipped backends (i.e. no
    /// false positives in production).
    #[test]
    fn allocate_atomic_rollback_counter_zero_with_real_backend() {
        const TOTAL: usize = 16;
        const THREADS: usize = 8;
        let manager = Arc::new(create_test_manager(TOTAL));
        let handles: Vec<_> = (0..THREADS)
            .map(|_| {
                let m = Arc::clone(&manager);
                thread::spawn(move || {
                    let _ = m.allocate_blocks(TOTAL / 4);
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        let snap = manager.metrics().snapshot();
        assert_eq!(
            snap.allocate_atomic_rollback_total, 0,
            "real LRU backend must never trigger rollback"
        );
    }

    /// `BlockManager::reset_inactive_pool` lifecycle: drop registered
    /// blocks so they land in the inactive pool, then reset and verify
    /// (1) reset gauge fully restored, (2) inactive gauge zeroed,
    /// (3) registry presence cleared for the type, (4) `mark_absent`
    /// counters in `presence_markers` reach zero.
    #[test]
    fn reset_inactive_pool_drains_and_clears_presence() {
        const N: usize = 4;
        let manager = create_test_manager(N);
        let mut hashes = Vec::with_capacity(N);

        // Register N blocks, drop the immutables → all land in inactive.
        let mutables = manager.allocate_blocks(N).unwrap();
        let mut completes = Vec::with_capacity(N);
        for (i, mb) in mutables.into_iter().enumerate() {
            let tb = create_test_token_block_from_iota((80_000 + i * 4) as u32);
            hashes.push(tb.kvbm_sequence_hash());
            completes.push(mb.complete(&tb).unwrap());
        }
        let immutables = manager.register_blocks(completes);
        drop(immutables);

        // Pre-reset state: all in inactive, presence true.
        let snap = manager.metrics().snapshot();
        assert_eq!(snap.inactive_pool_size, N as i64);
        assert_eq!(snap.reset_pool_size, 0);
        let presence = manager
            .block_registry()
            .check_presence::<TestBlockData>(&hashes);
        assert!(
            presence.iter().all(|(_, p)| *p),
            "all hashes present pre-reset"
        );

        // Reset.
        manager.reset_inactive_pool().expect("reset succeeds");

        // Post-reset state.
        let snap = manager.metrics().snapshot();
        assert_eq!(
            snap.inactive_pool_size, 0,
            "inactive gauge zeroed after reset"
        );
        assert_eq!(snap.reset_pool_size, N as i64, "reset gauge fully restored");
        assert_eq!(manager.available_blocks(), N);
        let presence = manager
            .block_registry()
            .check_presence::<TestBlockData>(&hashes);
        assert!(
            presence.iter().all(|(_, p)| !*p),
            "all hashes absent post-reset"
        );
    }

    /// Partial under-allocation: backend reports `len=4`, returns 2
    /// pairs from `allocate(3)`. Rollback must reinsert those 2 into
    /// the inactive index (covering the loop body in the rollback
    /// path) and restore the reset queue. Counter ticks.
    #[test]
    fn allocate_atomic_rollback_handles_partial_under_allocation() {
        struct PartiallyUnderAllocatingBackend {
            inner: MultiLruBackend,
            reported_len: usize,
            return_count: usize,
        }
        impl InactiveIndex for PartiallyUnderAllocatingBackend {
            fn find_matches(
                &mut self,
                hashes: &[SequenceHash],
                touch: bool,
            ) -> Vec<(SequenceHash, BlockId)> {
                self.inner.find_matches(hashes, touch)
            }
            fn scan_matches(
                &mut self,
                hashes: &[SequenceHash],
                touch: bool,
            ) -> Vec<(SequenceHash, BlockId)> {
                self.inner.scan_matches(hashes, touch)
            }
            fn allocate(&mut self, _count: usize) -> Vec<(SequenceHash, BlockId)> {
                // Return only `return_count` items even if asked for more.
                self.inner.allocate(self.return_count)
            }
            fn insert(&mut self, seq_hash: SequenceHash, block_id: BlockId) {
                self.inner.insert(seq_hash, block_id);
            }
            fn len(&self) -> usize {
                self.reported_len
            }
            fn has(&self, seq_hash: SequenceHash) -> bool {
                self.inner.has(seq_hash)
            }
            fn take(&mut self, seq_hash: SequenceHash, block_id: BlockId) -> bool {
                self.inner.take(seq_hash, block_id)
            }
        }

        use crate::metrics::BlockPoolMetrics;
        use crate::pools::store::BlockStore;

        let metrics = Arc::new(BlockPoolMetrics::new("test".to_string()));
        let tracker = FrequencyTrackingCapacity::default().create_tracker();
        // Pre-populate the inner backend with 4 entries by inserting
        // synthetic (hash, block_id) pairs.
        let mut inner = MultiLruBackend::new(NonZeroUsize::new(4).unwrap(), tracker);
        for i in 0..4u32 {
            let h = create_test_token_block_from_iota(90_000 + i * 4).kvbm_sequence_hash();
            inner.insert(h, i as BlockId);
        }
        let backend = PartiallyUnderAllocatingBackend {
            inner,
            reported_len: 4, // claims 4
            return_count: 2, // returns only 2 from allocate()
        };
        // 4 reset slots; backend lies that it has 4 inactive entries.
        // Asking for 7 forces from_reset=4, from_inactive=3, then
        // backend.allocate(3) returns 2 → rollback fires and reinserts
        // those 2 partial pairs into the inactive index.
        let store: Arc<BlockStore<TestBlockData>> =
            BlockStore::new(4, 4, Box::new(backend), metrics.clone(), false);

        let result = store.allocate_atomic(7);
        assert!(result.is_none(), "rollback returns None");

        let snap = metrics.snapshot();
        assert_eq!(
            snap.allocate_atomic_rollback_total, 1,
            "rollback counter ticks exactly once"
        );
        // Reset queue restored to original 4 (FIFO via push_front in reverse).
        assert_eq!(store.reset_len(), 4);
        // The partial pairs were reinserted into the index — exercises
        // the `for (h, id) in evicted_pairs { inner.inactive.insert ... }`
        // loop body in the rollback path.
    }
}

// ============================================================================
// RESET-ON-RELEASE TESTS
// ============================================================================
//
// `ImmutableBlock::set_evict_on_reset(true)` and the store-wide
// `with_default_reset_on_release(true)` cause the last drop of a primary
// to bypass the inactive pool and return the slot straight to the
// reset/free list (matching `release_duplicate`).

mod reset_on_release_tests {
    use super::*;
    use crate::testing::create_test_manager_with_default_reset_on_release;

    /// Per-block opt-in: a flagged block goes straight to reset on its
    /// last drop. The inactive pool stays empty and the seq_hash is no
    /// longer registered or matchable.
    #[test]
    fn per_block_flag_bypasses_inactive_pool() {
        let manager = create_test_manager(4);
        let m = manager.metrics();
        let token = create_test_token_block_from_iota(50_000);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();

        immutable.set_evict_on_reset(true);

        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 0);
        assert_eq!(store.reset_len(), 3);

        drop(immutable);

        assert_eq!(store.inactive_len(), 0, "inactive pool stays empty");
        assert_eq!(store.reset_len(), 4, "slot returned to free list");
        assert!(
            !store.has_inactive(hash),
            "hash not present in inactive index"
        );
        assert!(
            !manager.block_registry().is_registered(hash),
            "registry handle marked absent"
        );
        assert!(
            manager.match_blocks(&[hash]).is_empty(),
            "block cannot be matched after reset"
        );

        let snap = m.snapshot();
        assert_eq!(snap.inflight_immutable, 0);
        assert_eq!(snap.inactive_pool_size, 0);
        assert_eq!(snap.reset_pool_size, 4);
    }

    /// Flag does not prevent in-flight sharing. While clones exist, the
    /// block is matchable. Only the *last* drop honors the flag.
    #[test]
    fn flag_does_not_prevent_inflight_sharing() {
        let manager = create_test_manager(4);
        let token = create_test_token_block_from_iota(50_001);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let a = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        let b = a.clone();
        a.set_evict_on_reset(true);

        // Drop only `a`. `b` is still alive; slot stays Primary.
        drop(a);
        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 0);
        assert_eq!(store.reset_len(), 3);

        // Lookup must still succeed — flag has no effect while clones live.
        let matched = manager.match_blocks(&[hash]);
        assert_eq!(matched.len(), 1);
        drop(matched);
        drop(b);

        // Now the last clone is gone — flag fires, slot resets.
        assert_eq!(store.inactive_len(), 0);
        assert_eq!(store.reset_len(), 4);
        assert!(!manager.block_registry().is_registered(hash));
    }

    /// The flag is shared across clones via the Arc-backed AtomicBool.
    /// Last setter wins.
    #[test]
    fn last_writer_wins_across_clones() {
        let manager = create_test_manager(4);
        let token = create_test_token_block_from_iota(50_002);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let a = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        let b = a.clone();

        a.set_evict_on_reset(true);
        b.set_evict_on_reset(false); // overrides — clones share one atomic

        drop(a);
        drop(b);

        let store = manager.store_for_test();
        // Last writer was `false`, so the block went to the inactive
        // pool, not the reset pool.
        assert_eq!(store.inactive_len(), 1);
        assert_eq!(store.reset_len(), 3);
        assert!(store.has_inactive(hash));
    }

    /// Resetting one block's slot does NOT poison a future registration
    /// of the same `BlockId`. The next holder starts with the store's
    /// default (`false` here).
    #[test]
    fn no_poisoning_across_registrations() {
        let manager = create_test_manager(1);
        let store = manager.store_for_test();

        // First registration: flag = true, reset on drop.
        let token1 = create_test_token_block_from_iota(50_003);
        let hash1 = token1.kvbm_sequence_hash();
        {
            let mutables = manager.allocate_blocks(1).unwrap();
            let complete = mutables
                .into_iter()
                .next()
                .unwrap()
                .complete(&token1)
                .unwrap();
            let imm = manager
                .register_blocks(vec![complete])
                .into_iter()
                .next()
                .unwrap();
            imm.set_evict_on_reset(true);
            drop(imm);
        }
        assert_eq!(store.reset_len(), 1, "first registration reset");
        assert!(!manager.block_registry().is_registered(hash1));

        // Second registration: same BlockId (only one available),
        // different hash. Must NOT inherit the previous flag.
        let token2 = create_test_token_block_from_iota(50_004);
        let hash2 = token2.kvbm_sequence_hash();
        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token2)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        drop(imm);

        // If poisoning happened, this would reset; with the default
        // (false), the block should land in the inactive pool.
        assert_eq!(
            store.inactive_len(),
            1,
            "second block went to inactive, flag NOT inherited"
        );
        assert_eq!(store.reset_len(), 0);
        assert!(store.has_inactive(hash2));
    }

    /// Store-wide default: every primary release bypasses inactive.
    #[test]
    fn store_wide_default_resets_on_release() {
        let manager = create_test_manager_with_default_reset_on_release::<TestBlockData>(4, true);
        let token = create_test_token_block_from_iota(50_005);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        // No explicit set_evict_on_reset call — relying on the store default.
        drop(imm);

        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 0);
        assert_eq!(store.reset_len(), 4);
        assert!(!manager.block_registry().is_registered(hash));
    }

    /// Sticky override: with store default = true, a holder opts out
    /// via `set_evict_on_reset(false)`. After Drop the block lands in
    /// the inactive pool (correct). A later `match_blocks` resurrects
    /// it; the resurrected `ImmutableBlock` inherits the *stored*
    /// override, NOT the store default. Dropping the resurrected clone
    /// must keep the block in the inactive pool, not reset it.
    ///
    /// Regression test for the Codex review finding:
    /// "Preserve per-block opt-out across inactive hits".
    #[test]
    fn opt_out_survives_inactive_resurrection() {
        let manager = create_test_manager_with_default_reset_on_release::<TestBlockData>(4, true);
        let token = create_test_token_block_from_iota(50_009);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        imm.set_evict_on_reset(false); // opt out of store-wide default
        drop(imm);

        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 1, "opt-out kept block in inactive");
        assert_eq!(store.reset_len(), 3);

        // Resurrect via the inactive cache.
        let resurrected = manager.match_blocks(&[hash]);
        assert_eq!(resurrected.len(), 1);
        assert_eq!(store.inactive_len(), 0, "resurrection drained inactive");

        // Drop the resurrected clone. The override stored in
        // SlotState::Inactive must have travelled into the new Inner —
        // so this drop also keeps the block in the inactive pool
        // instead of resetting per the store default.
        drop(resurrected);

        assert_eq!(
            store.inactive_len(),
            1,
            "override survived resurrection — block stayed in inactive"
        );
        assert_eq!(store.reset_len(), 3);
        assert!(store.has_inactive(hash));
        assert!(manager.block_registry().is_registered(hash));
    }

    /// Holder can opt out of the store-wide default for a specific block.
    #[test]
    fn per_block_can_opt_out_of_store_default() {
        let manager = create_test_manager_with_default_reset_on_release::<TestBlockData>(4, true);
        let token = create_test_token_block_from_iota(50_006);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        imm.set_evict_on_reset(false); // overrides store default
        drop(imm);

        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 1, "kept in inactive despite default");
        assert_eq!(store.reset_len(), 3);
        assert!(store.has_inactive(hash));
    }

    /// Eager-resurrection path (concurrent lookup observes Arc strong=0
    /// before Drop's `release_primary` fires) preserves the per-block
    /// override. The override lives in the store-owned per-slot atomic
    /// (not on the dropping Inner), so the eager `Primary → Inactive`
    /// transition rides over the race window without losing the flag.
    /// The resurrected block reads the same atomic on its own drop.
    ///
    /// Mirrors `eager_primary_to_inactive_is_deterministic_with_pause_hook`
    /// in `race_regression_tests`. Regression test for the review finding
    /// at https://github.com/ai-dynamo/dynamo/pull/9504#discussion_r3238515930.
    #[test]
    fn eager_resurrection_preserves_flag() {
        use std::sync::Arc;
        use std::thread;

        let manager = Arc::new(create_test_manager(4));
        let token = create_test_token_block_from_iota(50_007);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let immutable = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        immutable.set_evict_on_reset(true);

        let store = manager.store_for_test().clone();

        let gate = store.pause_release_primary();
        let arrivals_before = store.release_primary_arrivals();
        let drop_t = thread::spawn(move || drop(immutable));

        while store.release_primary_arrivals() == arrivals_before {
            std::thread::yield_now();
        }

        // Concurrent lookup drives the eager `Primary → Inactive`
        // transition. The dropping Inner had flag=true; the eager path
        // leaves the per-slot atomic untouched, so the override rides
        // over the race window.
        let matched = manager.match_blocks(&[hash]);
        assert_eq!(matched.len(), 1, "eager resurrection must succeed");

        let snap_mid = manager.metrics().snapshot();
        assert_eq!(
            snap_mid.eager_primary_to_inactive_total, 1,
            "eager transition fired"
        );

        drop(gate);
        drop_t.join().unwrap();

        // The parked drop saw a slot that no longer matched its self_ptr
        // and no-opped — its destination decision was preempted by the
        // eager path.
        let snap_after = manager.metrics().snapshot();
        assert_eq!(snap_after.release_primary_noop_total, 1);

        // The resurrected Inner reads the per-slot atomic on its own
        // drop. Because the original holder had set the override to
        // `true`, this drop must bypass the inactive pool and reset the
        // slot — proving the override survived the race window.
        drop(matched);

        let store = manager.store_for_test();
        assert_eq!(
            store.inactive_len(),
            0,
            "override preserved — block bypasses inactive on drop",
        );
        assert_eq!(store.reset_len(), 4);
        assert!(
            !manager.block_registry().is_registered(hash),
            "registry handle marked absent",
        );
    }

    /// Duplicate blocks always reset on drop regardless of the flag —
    /// this is the pre-existing `release_duplicate` behavior and the
    /// shared helper. The store-wide default does not change it.
    #[test]
    fn duplicate_release_still_resets_with_default_false() {
        // Use Allow policy so duplicates are created.
        let registry = crate::registry::BlockRegistry::builder()
            .frequency_tracker(
                crate::manager::FrequencyTrackingCapacity::default().create_tracker(),
            )
            .build();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(4)
            .block_size(4)
            .registry(registry)
            .with_lru_backend()
            .duplication_policy(BlockDuplicationPolicy::Allow)
            .build()
            .expect("Should build manager");

        let token = create_test_token_block_from_iota(50_008);
        let _hash = token.kvbm_sequence_hash();

        // Primary
        let m1 = manager.allocate_blocks(1).unwrap();
        let c1 = m1.into_iter().next().unwrap().complete(&token).unwrap();
        let primary = manager
            .register_blocks(vec![c1])
            .into_iter()
            .next()
            .unwrap();

        // Duplicate (same hash on a different BlockId)
        let m2 = manager.allocate_blocks(1).unwrap();
        let c2 = m2.into_iter().next().unwrap().complete(&token).unwrap();
        let dup = manager
            .register_blocks(vec![c2])
            .into_iter()
            .next()
            .unwrap();
        assert_eq!(dup.block_id(), 1);
        assert_ne!(primary.block_id(), dup.block_id());

        let store = manager.store_for_test();
        let reset_before = store.reset_len();
        let inactive_before = store.inactive_len();

        // Drop duplicate first — always resets, never enters inactive.
        drop(dup);
        assert_eq!(
            store.reset_len(),
            reset_before + 1,
            "duplicate drop returned to reset pool"
        );
        assert_eq!(
            store.inactive_len(),
            inactive_before,
            "duplicate never enters inactive"
        );

        // Primary drop (flag = false default) → goes to inactive normally.
        drop(primary);
        assert_eq!(store.inactive_len(), inactive_before + 1);
    }

    /// Override survives two full `Inactive → Primary → Inactive`
    /// hops. Extends `opt_out_survives_inactive_resurrection` (one hop)
    /// to guarantee the carry path in `acquire_for_hash` /
    /// `match_blocks` is idempotent across repeated cache hits.
    #[test]
    fn override_survives_multiple_resurrection_cycles() {
        let manager = create_test_manager_with_default_reset_on_release::<TestBlockData>(4, true);
        let token = create_test_token_block_from_iota(50_010);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        imm.set_evict_on_reset(false); // opt out of store-wide default
        drop(imm);

        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 1, "first drop landed in inactive");
        assert_eq!(store.reset_len(), 3);

        // First resurrection
        let r1 = manager.match_blocks(&[hash]);
        assert_eq!(r1.len(), 1);
        assert_eq!(store.inactive_len(), 0);
        drop(r1);
        assert_eq!(
            store.inactive_len(),
            1,
            "override survived first resurrection"
        );
        assert_eq!(store.reset_len(), 3);

        // Second resurrection — same path, must still honor the override.
        let r2 = manager.match_blocks(&[hash]);
        assert_eq!(r2.len(), 1);
        assert_eq!(store.inactive_len(), 0);
        drop(r2);
        assert_eq!(
            store.inactive_len(),
            1,
            "override survived second resurrection"
        );
        assert_eq!(store.reset_len(), 3);
        assert!(store.has_inactive(hash));
        assert!(manager.block_registry().is_registered(hash));
    }

    /// Calling `set_evict_on_reset` on a resurrected `ImmutableBlock`
    /// must take effect — the resurrected Inner's atomic is the
    /// authoritative one. Resurrect with an inherited `false`, then
    /// flip to `true` and drop: slot must reset, not stay in inactive.
    ///
    /// Guards against a regression where `new_primary_resurrected` is
    /// decoupled from the setter (e.g. wrong Arc, wrong field).
    #[test]
    fn set_evict_on_reset_on_resurrected_inner_takes_effect() {
        let manager = create_test_manager_with_default_reset_on_release::<TestBlockData>(4, true);
        let token = create_test_token_block_from_iota(50_011);
        let hash = token.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(1).unwrap();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        imm.set_evict_on_reset(false);
        drop(imm);

        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 1);

        // Resurrect: inherited override is `false`.
        let resurrected = manager.match_blocks(&[hash]);
        assert_eq!(resurrected.len(), 1);

        // Flip on the *resurrected* Inner. If the setter wires through
        // correctly, the next drop honors `true` and resets.
        resurrected[0].set_evict_on_reset(true);
        drop(resurrected);

        assert_eq!(
            store.inactive_len(),
            0,
            "resurrected-Inner setter took effect"
        );
        assert_eq!(store.reset_len(), 4, "slot returned to free list");
        assert!(!manager.block_registry().is_registered(hash));
    }

    /// Three blocks registered in a single `register_blocks` call must
    /// honor independent per-block flags. Guards against any future
    /// refactor that shares state across the registration loop.
    #[test]
    fn mixed_flags_in_single_register_blocks_call() {
        let manager = create_test_manager(4);
        let t0 = create_test_token_block_from_iota(50_020);
        let t1 = create_test_token_block_from_iota(50_021);
        let t2 = create_test_token_block_from_iota(50_022);
        let h0 = t0.kvbm_sequence_hash();
        let h1 = t1.kvbm_sequence_hash();
        let h2 = t2.kvbm_sequence_hash();

        let mutables = manager.allocate_blocks(3).unwrap();
        let mut iter = mutables.into_iter();
        let c0 = iter.next().unwrap().complete(&t0).unwrap();
        let c1 = iter.next().unwrap().complete(&t1).unwrap();
        let c2 = iter.next().unwrap().complete(&t2).unwrap();

        let immutables = manager.register_blocks(vec![c0, c1, c2]);
        assert_eq!(immutables.len(), 3);
        immutables[0].set_evict_on_reset(true);
        // immutables[1] left at default (false)
        immutables[2].set_evict_on_reset(true);

        let store = manager.store_for_test();
        assert_eq!(store.inactive_len(), 0);
        assert_eq!(store.reset_len(), 1, "1 of 4 slots still free");

        drop(immutables);

        assert_eq!(
            store.inactive_len(),
            1,
            "only the default-flag block kept in inactive"
        );
        assert_eq!(
            store.reset_len(),
            3,
            "two flagged blocks reset + one originally free"
        );
        assert!(!store.has_inactive(h0), "flagged block 0 not in inactive");
        assert!(store.has_inactive(h1), "default-flag block 1 in inactive");
        assert!(!store.has_inactive(h2), "flagged block 2 not in inactive");
        assert!(!manager.block_registry().is_registered(h0));
        assert!(manager.block_registry().is_registered(h1));
        assert!(!manager.block_registry().is_registered(h2));
    }

    /// The per-block override must be discarded when the slot leaves
    /// `Inactive` via eviction back to `Mutable`. A subsequent fresh
    /// registration on the same `BlockId` must read the store default,
    /// not inherit the previous holder's override.
    ///
    /// Documented invariant from `pools/store.rs`: "The flag is
    /// discarded when the slot leaves `Inactive` via eviction
    /// (`Inactive → Mutable`); a future fresh registration on the same
    /// `BlockId` reads the store default again."
    #[test]
    fn override_discarded_on_eviction_back_to_mutable() {
        // block_count=1 so the second allocate must evict from inactive.
        let manager = create_test_manager_with_default_reset_on_release::<TestBlockData>(1, true);
        let store = manager.store_for_test().clone();

        // First registration: opt OUT of the store default → Inactive(false).
        let token1 = create_test_token_block_from_iota(50_030);
        let hash1 = token1.kvbm_sequence_hash();
        {
            let mutables = manager.allocate_blocks(1).unwrap();
            let complete = mutables
                .into_iter()
                .next()
                .unwrap()
                .complete(&token1)
                .unwrap();
            let imm = manager
                .register_blocks(vec![complete])
                .into_iter()
                .next()
                .unwrap();
            imm.set_evict_on_reset(false);
            drop(imm);
        }
        assert_eq!(store.inactive_len(), 1, "first drop kept in inactive");
        assert_eq!(store.reset_len(), 0);

        // Force eviction: only slot is in inactive, allocate must evict.
        let mutables = manager.allocate_blocks(1).unwrap();
        assert_eq!(store.inactive_len(), 0, "inactive evicted to mutable");
        assert!(!manager.block_registry().is_registered(hash1));

        // Re-register on the same BlockId with a fresh hash. The fresh
        // Inner is constructed via `new_primary` (not resurrected) and
        // must read the store default (true) — NOT inherit the discarded
        // `false` override.
        let token2 = create_test_token_block_from_iota(50_031);
        let hash2 = token2.kvbm_sequence_hash();
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token2)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        // No explicit `set_evict_on_reset` — fresh Inner must read the
        // store default (true) from `BlockStore::default_reset_on_release`.
        drop(imm);

        assert_eq!(
            store.reset_len(),
            1,
            "fresh Inner used store default — slot reset, not inactive"
        );
        assert_eq!(store.inactive_len(), 0);
        assert!(!store.has_inactive(hash2));
        assert!(!manager.block_registry().is_registered(hash2));
    }

    /// Calling `set_evict_on_reset(true)` on a *duplicate* must not
    /// affect its drop (always resets via `release_duplicate`) and must
    /// not affect the *primary*'s atomic — they live on separate Inners.
    /// Guards against a refactor that unifies primary/duplicate Inner
    /// state and silently makes the duplicate's flag observable on the
    /// primary.
    #[test]
    fn duplicate_set_evict_on_reset_is_noop() {
        let registry = crate::registry::BlockRegistry::builder()
            .frequency_tracker(
                crate::manager::FrequencyTrackingCapacity::default().create_tracker(),
            )
            .build();
        let manager = BlockManager::<TestBlockData>::builder()
            .block_count(4)
            .block_size(4)
            .registry(registry)
            .with_lru_backend()
            .duplication_policy(BlockDuplicationPolicy::Allow)
            .build()
            .expect("Should build manager");

        let token = create_test_token_block_from_iota(50_040);
        let hash = token.kvbm_sequence_hash();

        // Primary
        let m1 = manager.allocate_blocks(1).unwrap();
        let c1 = m1.into_iter().next().unwrap().complete(&token).unwrap();
        let primary = manager
            .register_blocks(vec![c1])
            .into_iter()
            .next()
            .unwrap();

        // Duplicate
        let m2 = manager.allocate_blocks(1).unwrap();
        let c2 = m2.into_iter().next().unwrap().complete(&token).unwrap();
        let dup = manager
            .register_blocks(vec![c2])
            .into_iter()
            .next()
            .unwrap();
        assert_ne!(primary.block_id(), dup.block_id());

        // Flag on the duplicate — must be a no-op at drop.
        dup.set_evict_on_reset(true);

        let store = manager.store_for_test();
        let reset_before = store.reset_len();
        let inactive_before = store.inactive_len();

        drop(dup);
        assert_eq!(
            store.reset_len(),
            reset_before + 1,
            "duplicate drop resets regardless of flag"
        );
        assert_eq!(
            store.inactive_len(),
            inactive_before,
            "duplicate drop never enters inactive"
        );

        // Primary must be entirely unaffected by the duplicate's flag:
        // still matchable, its own atomic still at default (false), so
        // dropping it lands in inactive.
        let matched = manager.match_blocks(&[hash]);
        assert_eq!(matched.len(), 1, "primary still matchable after dup drop");
        assert_eq!(matched[0].block_id(), primary.block_id());
        drop(matched);
        drop(primary);

        assert_eq!(
            store.inactive_len(),
            inactive_before + 1,
            "primary drop honors its own flag (default false → inactive), \
             unaffected by duplicate's flag"
        );
    }

    /// Pool gauges (`inflight_immutable`, `inactive_pool_size`,
    /// `reset_pool_size`) must stay coherent across the full lifecycle
    /// when the reset-on-release flag fires. Regression-protects the
    /// metric plumbing in `release_primary`.
    #[test]
    fn metric_gauges_stay_coherent_under_reset_flag() {
        let manager = create_test_manager(4);
        let m = manager.metrics();
        let token = create_test_token_block_from_iota(50_050);

        // Baseline: 4 free slots, nothing in flight.
        let s = m.snapshot();
        assert_eq!(s.inflight_immutable, 0);
        assert_eq!(s.inactive_pool_size, 0);
        assert_eq!(s.reset_pool_size, 4);

        // Allocate 1 mutable → reset pool decrements; no immutable yet.
        let mutables = manager.allocate_blocks(1).unwrap();
        let s = m.snapshot();
        assert_eq!(s.inflight_immutable, 0, "no immutable until register");
        assert_eq!(s.inactive_pool_size, 0);
        assert_eq!(s.reset_pool_size, 3);

        // Complete + register → 1 in flight.
        let complete = mutables
            .into_iter()
            .next()
            .unwrap()
            .complete(&token)
            .unwrap();
        let imm = manager
            .register_blocks(vec![complete])
            .into_iter()
            .next()
            .unwrap();
        let s = m.snapshot();
        assert_eq!(s.inflight_immutable, 1);
        assert_eq!(s.inactive_pool_size, 0);
        assert_eq!(s.reset_pool_size, 3);

        // Flip the flag — pure state change, no gauge movement.
        imm.set_evict_on_reset(true);
        let s = m.snapshot();
        assert_eq!(s.inflight_immutable, 1);
        assert_eq!(s.inactive_pool_size, 0);
        assert_eq!(s.reset_pool_size, 3);

        // Drop with flag=true → bypasses inactive, slot returns to reset.
        drop(imm);
        let s = m.snapshot();
        assert_eq!(s.inflight_immutable, 0, "drop decremented immutable");
        assert_eq!(s.inactive_pool_size, 0, "inactive gauge unchanged");
        assert_eq!(
            s.reset_pool_size, 4,
            "reset gauge incremented, not inactive"
        );
    }
}