segstore 0.8.0

Generic durable segmented store: write-ahead log, immutable segments, tombstones, checkpoint, and compaction
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
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
#![doc = include_str!("../README.md")]
//! Generic durable segmented store.
//!
//! `segstore` provides the LSM-style lifecycle shared by updatable indexes,
//! immutable segments plus tombstone deletes plus a write-ahead log plus
//! checkpoint and compaction, on top of [`durability`]. It is generic over the
//! segment payload: a consumer implements [`Store`] to say how a batch of items
//! becomes a segment and how segments merge during compaction, and `segstore`
//! owns the durability and the orchestration.
//!
//! The split mirrors the rest of the retrieval stack: a storage substrate
//! (`postings`, a graph index) keeps its own representation while delegating the
//! mutable-and-persistent machinery here, the same way it already delegates the
//! raw WAL/checkpoint primitives to [`durability`].
//!
//! # What it owns vs what the consumer owns
//!
//! - `segstore` owns: the append-only WAL of operations, the in-memory buffer of
//!   not-yet-flushed adds, the ordered list of immutable segments, the tombstone
//!   set, checkpoint snapshots, and crash recovery (replay the WAL past the last
//!   checkpoint).
//! - The consumer owns: the segment representation (an opaque `Serialize` type),
//!   how a batch of live items becomes one segment ([`Store::build_segment`]),
//!   how segments merge while dropping tombstoned ids ([`Store::merge_segments`]),
//!   and querying (iterate [`SegmentedStore::segments`] + [`SegmentedStore::buffer`],
//!   filtering each segment's copies with [`SegmentedStore::is_live_in`]).
//!
//! # Example
//!
//! ```
//! use segstore::{DefaultStore, SegmentedStore};
//! use durability::MemoryDirectory;
//!
//! let dir = MemoryDirectory::arc();
//! let mut s = SegmentedStore::open(dir, DefaultStore::<u32, String>::new(), 2).unwrap();
//! s.add(1, "a".into()).unwrap();
//! s.add(2, "b".into()).unwrap();
//! s.delete(2).unwrap();
//! assert!(s.is_live(&1) && !s.is_live(&2));
//! ```
//!
//! For custom segment layouts, implement [`Store`] directly.
//!
//! # Durability
//!
//! A checkpoint is the commit point. It persists each new segment to its own
//! `segstore.seg.<id>` file (written once, never rewritten), then atomically
//! writes a small manifest (`segstore.manifest`, CRC-checked) naming the current
//! segment files + tombstones, then rotates the WAL: a fresh generation
//! (`segstore.wal.<epoch>`) is started and the old one deleted, so the log never
//! grows past one checkpoint interval. Because only *new* segments are written, a
//! checkpoint is O(new data), not O(total): the Lucene `segments_N` / RocksDB
//! MANIFEST model. The manifest records the epoch it covers; recovery loads the
//! named segment files and replays only that epoch's WAL.
//!
//! The write order makes every crash window safe: new segment files are durable
//! before the manifest names them, and superseded segment files are GC'd only
//! after the new manifest is durable. A crash before the manifest leaves orphan
//! segment files the next open never reads and garbage-collects; a crash after it
//! leaves the old files as the orphans, GC'd the same way. The WAL, not the
//! segment files, is the durability backbone: an `add`/`delete` is durable once
//! its WAL record is, so a partial checkpoint never loses an acknowledged write
//! (recovery replays the WAL onto the last good manifest). On a filesystem backend
//! each segment file and the manifest pass a power-loss barrier (fsync of the file
//! and parent dir); in-memory backends publish atomically without one.
//!
//! [`SyncPolicy`] chooses the WAL write durability: the default [`SyncPolicy::Flush`]
//! is a visibility boundary (userspace -> OS), while [`SyncPolicy::Fsync`] syncs
//! every record to stable storage (filesystem backend only).
//!
//! Recovery is *point-in-time*: the WAL is read best-effort, so a torn final record
//! (the expected damage from a crash mid-write) is truncated and the consistent
//! prefix recovered. This is the same default as RocksDB's `kPointInTimeRecovery`.
//! It does NOT detect corruption *beyond* the torn tail (a bit-flip of an
//! already-committed interior record): each record is CRC-checked, so such a record
//! is never decoded as garbage, but best-effort read stops at it and drops the rest.
//! Media-rot detection (a strict "fail on any corruption" mode) is out of scope for
//! this crash-consistency WAL; a consumer needing it should use checksummed storage.
//! A CRC-corrupt manifest or segment file is a hard error on open, never misread.
//!
//! On-disk format note: 0.3 replaced 0.2's single monolithic `segstore.ckpt`
//! checkpoint blob with the manifest + per-segment-file layout above. A 0.1
//! unsuffixed `segstore.wal` and a 0.2 `segstore.ckpt` (with no manifest) are each
//! detected and rejected with a clear error rather than misread. The manifest
//! now ends with a versioned extension listing superseded copies (see
//! [`SegmentedStore::add`]); a manifest without it is read as having none, and
//! an older segstore that does not know the extension ignores it.
//!
//! # Memory model
//!
//! The on-disk layout is segment-per-file, but the current read API is still an
//! in-memory segment model: [`SegmentedStore::open`] deserializes every manifest
//! segment into `Arc<Store::Segment>`, and [`View::segments`] exposes those loaded
//! segments. This is not yet an out-of-core reader for corpora larger than RAM.
//! Such consumers need a future reader shape that exposes stable segment ids and
//! segment file handles (or mmap-backed consumer readers) while preserving the
//! same manifest, checkpoint, and garbage-collection invariants.

use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::io::Read;
use std::marker::PhantomData;
use std::sync::Arc;

use durability::checkpoint::{CheckpointFile, MAX_CHECKPOINT_PAYLOAD_BYTES};
use durability::recordlog::{RecordLogReadMode, RecordLogReader, RecordLogWriter};
use durability::{Directory, PersistenceError, PersistenceResult};
use serde::{de::DeserializeOwned, Deserialize, Serialize};

#[cfg(feature = "conformance")]
pub mod conformance;
pub mod sidecar;

/// Prefix for epoch-suffixed WAL files (`segstore.wal.<epoch>`).
const WAL_PREFIX: &str = "segstore.wal.";
/// The single unsuffixed WAL of the 0.1 on-disk format; its presence flags a
/// store written by segstore 0.1, which later formats cannot read.
const LEGACY_WAL_PATH: &str = "segstore.wal";
/// The monolithic checkpoint blob of the 0.2 on-disk format; its presence with no
/// manifest flags a 0.2 store, which the 0.3 manifest format cannot read.
const LEGACY_CKPT_PATH: &str = "segstore.ckpt";
/// The 0.3 checkpoint commit point: a small manifest naming the current segment
/// files + tombstones (see the module-level Durability docs).
const MANIFEST_PATH: &str = "segstore.manifest";

/// Advisory lock file held exclusively for a store's lifetime.
const LOCK_PATH: &str = "segstore.lock";
/// Prefix for per-segment files (`segstore.seg.<id>`); each holds one immutable
/// segment, written once and never rewritten.
const SEG_PREFIX: &str = "segstore.seg.";
const CHECKPOINT_MAGIC: [u8; 4] = *b"VCKP";
const CHECKPOINT_FORMAT_VERSION_V1: u32 = 1;
const CHECKPOINT_FORMAT_VERSION_V2: u32 = 2;
const CHECKPOINT_HEADER_BYTES: u64 = 4 + 4 + 8 + 8 + 4;
const SIDECAR_ENVELOPE_HEADER_BYTES: usize = 8 + 4 + 8 + 4 + 4;

/// The WAL file path for a given epoch.
fn wal_path(epoch: u64) -> String {
    format!("{WAL_PREFIX}{epoch}")
}

/// The file path for the segment with the given id.
fn seg_path(id: u64) -> String {
    format!("{SEG_PREFIX}{id}")
}

/// Each segment (and the manifest) is written as one checkpoint blob, so it is
/// bounded by [`MAX_CHECKPOINT_PAYLOAD_BYTES`] (256 MiB). That byte cap and the
/// item-count cap [`TierConfig::max_merged_len`] are in different units and do
/// not know about each other, so a compaction can target an item count whose
/// serialized bytes exceed the blob cap and fail here. This rewraps
/// durability's generic "payload too large" into an actionable message naming
/// the artifact and the levers; unrelated errors pass through unchanged.
fn size_cap_context(e: PersistenceError, what: &str) -> PersistenceError {
    match &e {
        PersistenceError::Format(msg) if msg.contains("payload too large") => {
            PersistenceError::Format(format!(
                "{what} does not fit the {MAX_CHECKPOINT_PAYLOAD_BYTES}-byte per-blob limit \
                 (durability::MAX_CHECKPOINT_PAYLOAD_BYTES): {msg}. Each segment and the \
                 manifest are written as a single checkpoint blob. Keep them under the cap: \
                 lower TierConfig::max_merged_len (it counts items, not bytes) or the open() \
                 flush_threshold so segments stay smaller, and run compact() to drop \
                 tombstones from the manifest."
            ))
        }
        _ => e,
    }
}

fn reject_legacy_formats(dir: &dyn Directory) -> PersistenceResult<()> {
    // A 0.1 store wrote a single unsuffixed WAL; later formats are epoch-suffixed.
    // Reject it explicitly rather than misread its ops as an epoch.
    if dir.exists(LEGACY_WAL_PATH) {
        return Err(PersistenceError::InvalidConfig(
            "segstore 0.1 on-disk store detected (unsuffixed segstore.wal); the \
             on-disk format is epoch-suffixed and cannot read it"
                .into(),
        ));
    }
    // A 0.2 store wrote one monolithic segstore.ckpt blob; 0.3 uses a manifest
    // + per-segment files. A ckpt with no manifest is a 0.2 store; reject it
    // rather than ignore the data it holds.
    if dir.exists(LEGACY_CKPT_PATH) && !dir.exists(MANIFEST_PATH) {
        return Err(PersistenceError::InvalidConfig(
            "segstore 0.2 on-disk store detected (monolithic segstore.ckpt); the 0.3 \
             on-disk format is a manifest + per-segment files and cannot read it"
                .into(),
        ));
    }
    Ok(())
}

/// Reserved prefix for consumer-written per-segment index sidecar files
/// (`segstore.idx.<id>.<kind>`). A consumer persists a built per-segment index
/// (an HNSW graph, posting lists, ...) here keyed by a stable segment id; segstore
/// garbage-collects any file in this namespace whose segment id is not in the
/// current manifest, on the same crash-safe schedule as the segment files. The
/// consumer owns the file's encoding and full compatibility checks (segstore
/// never reads it). Those checks should include the expected segment id when a
/// copied or misnamed sidecar would otherwise be unsafe to accept. `kind` is
/// only a short namespace/coexistence tag; new names are validated by
/// [`try_index_name`], while GC accepts older non-empty kind strings so upgrades
/// do not strand legacy sidecars.
const IDX_PREFIX: &str = "segstore.idx.";

/// The segment id named by an index sidecar file `segstore.idx.<id>.<kind>`, or
/// `None` if `name` is not in the index namespace.
fn idx_seg_id(name: &str) -> Option<u64> {
    let rest = name.strip_prefix(IDX_PREFIX)?;
    let (id, kind) = rest.split_once('.')?;
    if kind.is_empty() {
        return None;
    }
    id.parse::<u64>().ok()
}

fn validate_index_kind(kind: &str) -> PersistenceResult<()> {
    if kind.is_empty() {
        return Err(PersistenceError::InvalidConfig(
            "index sidecar kind must be non-empty".into(),
        ));
    }
    if !kind
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
    {
        return Err(PersistenceError::InvalidConfig(format!(
            "index sidecar kind must contain only ASCII letters, digits, '_' or '-': {kind:?}"
        )));
    }
    Ok(())
}

fn index_sidecar_name(id: u64, kind: &str) -> PersistenceResult<String> {
    validate_index_kind(kind)?;
    Ok(format!("{IDX_PREFIX}{id}.{kind}"))
}

fn delete_files_best_effort(dir: &dyn Directory, names: Vec<String>, durable: bool) {
    let mut deleted = false;
    for name in names {
        if dir.exists(&name) && dir.delete(&name).is_ok() {
            deleted = true;
        }
    }
    if durable && deleted {
        let _ = dir.durable_sync_parent_dir(MANIFEST_PATH);
    }
}

/// Location and integrity metadata for the serialized payload inside a segment file.
///
/// `segstore.seg.<id>` files are checkpoint envelopes: a fixed header followed by
/// the serialized `Store::Segment` payload. This metadata lets filesystem-backed
/// consumers map or range-read only the payload bytes while keeping header parsing
/// in `segstore`. The CRC is the expected checksum of the payload; callers that
/// bypass [`SegmentCatalog::read_segment_payload`] or
/// [`SegmentCatalog::read_segment_payload_into`] must verify it before trusting
/// bytes from untrusted storage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SegmentPayloadInfo {
    /// Byte offset in the segment file where the serialized payload starts.
    pub payload_offset: u64,
    /// Length of the serialized payload in bytes.
    pub payload_len: usize,
    /// CRC32 expected for the serialized payload bytes.
    pub payload_crc32: u32,
}

impl SegmentPayloadInfo {
    /// Verify bytes read from [`Self::payload_offset`] match this payload record.
    ///
    /// This is the check mmap and range-read consumers should run before
    /// trusting bytes obtained without [`SegmentCatalog::read_segment_payload`]
    /// or [`SegmentCatalog::read_segment_payload_into`].
    pub fn verify_payload(&self, payload: &[u8]) -> PersistenceResult<()> {
        if payload.len() != self.payload_len {
            return Err(PersistenceError::Format(format!(
                "segment payload length mismatch: got {} bytes, expected {}",
                payload.len(),
                self.payload_len
            )));
        }
        let actual = crc32fast::hash(payload);
        if actual != self.payload_crc32 {
            return Err(PersistenceError::CrcMismatch {
                expected: self.payload_crc32,
                actual,
            });
        }
        Ok(())
    }
}

fn read_checkpoint_payload_header<R: Read + ?Sized>(
    f: &mut R,
) -> PersistenceResult<CheckpointPayloadHeader> {
    let mut buf4 = [0u8; 4];
    let mut buf8 = [0u8; 8];

    f.read_exact(&mut buf4)?;
    if buf4 != CHECKPOINT_MAGIC {
        return Err(PersistenceError::Format("invalid checkpoint magic".into()));
    }

    f.read_exact(&mut buf4)?;
    let version = u32::from_le_bytes(buf4);
    if !matches!(
        version,
        CHECKPOINT_FORMAT_VERSION_V1 | CHECKPOINT_FORMAT_VERSION_V2
    ) {
        return Err(PersistenceError::Format(format!(
            "checkpoint version mismatch (got {version})"
        )));
    }

    f.read_exact(&mut buf8)?;
    let last_applied_id = u64::from_le_bytes(buf8);
    f.read_exact(&mut buf8)?;
    let payload_len_u64 = u64::from_le_bytes(buf8);
    let payload_len = usize::try_from(payload_len_u64)
        .map_err(|_| PersistenceError::Format("payload_len overflow".into()))?;
    if payload_len > MAX_CHECKPOINT_PAYLOAD_BYTES {
        return Err(PersistenceError::Format(format!(
            "checkpoint payload too large: {} bytes (max {})",
            payload_len, MAX_CHECKPOINT_PAYLOAD_BYTES
        )));
    }

    f.read_exact(&mut buf4)?;
    let checksum = u32::from_le_bytes(buf4);
    Ok(CheckpointPayloadHeader {
        version,
        last_applied_id,
        payload_len_u64,
        payload_len,
        checksum,
    })
}

#[derive(Debug, Clone, Copy)]
struct CheckpointPayloadHeader {
    version: u32,
    last_applied_id: u64,
    payload_len_u64: u64,
    payload_len: usize,
    checksum: u32,
}

impl CheckpointPayloadHeader {
    fn verify_payload(&self, payload: &[u8]) -> PersistenceResult<()> {
        if payload.len() != self.payload_len {
            return Err(PersistenceError::Format(format!(
                "checkpoint payload truncated: got {} of {} bytes",
                payload.len(),
                self.payload_len
            )));
        }
        let actual = match self.version {
            CHECKPOINT_FORMAT_VERSION_V1 => crc32fast::hash(payload),
            CHECKPOINT_FORMAT_VERSION_V2 => {
                let mut hasher = crc32fast::Hasher::new();
                hasher.update(&CHECKPOINT_MAGIC);
                hasher.update(&self.version.to_le_bytes());
                hasher.update(&self.last_applied_id.to_le_bytes());
                hasher.update(&self.payload_len_u64.to_le_bytes());
                hasher.update(payload);
                hasher.finalize()
            }
            _ => unreachable!("checkpoint header version is validated at parse time"),
        };
        if actual != self.checksum {
            return Err(PersistenceError::CrcMismatch {
                expected: self.checksum,
                actual,
            });
        }
        Ok(())
    }

    fn payload_info(&self, payload: &[u8]) -> SegmentPayloadInfo {
        SegmentPayloadInfo {
            payload_offset: CHECKPOINT_HEADER_BYTES,
            payload_len: self.payload_len,
            payload_crc32: crc32fast::hash(payload),
        }
    }
}

fn read_checkpoint_payload_info(
    dir: &dyn Directory,
    path: &str,
) -> PersistenceResult<SegmentPayloadInfo> {
    let mut f = dir.open_file(path)?;
    let header = read_checkpoint_payload_header(&mut *f)?;
    let mut payload = Vec::new();
    read_checkpoint_payload_into_reader(&mut *f, &header, &mut payload)?;
    Ok(header.payload_info(&payload))
}

fn read_checkpoint_payload_into(
    dir: &dyn Directory,
    path: &str,
    payload: &mut Vec<u8>,
) -> PersistenceResult<()> {
    let mut f = dir.open_file(path)?;
    let header = read_checkpoint_payload_header(&mut *f)?;
    match read_checkpoint_payload_into_reader(&mut *f, &header, payload) {
        Ok(()) => Ok(()),
        Err(err) => {
            payload.clear();
            Err(err)
        }
    }
}

fn read_checkpoint_payload_into_reader<R: Read + ?Sized>(
    f: &mut R,
    header: &CheckpointPayloadHeader,
    payload: &mut Vec<u8>,
) -> PersistenceResult<()> {
    // Don't trust `len` for the upfront allocation: a corrupt length prefix
    // under the cap would otherwise force a zeroed allocation up to 256 MiB
    // before the read fails. Grow with the bytes actually present instead
    // (mirrors durability's read_exact_bounded).
    payload.clear();
    let reserve = header.payload_len.min(1 << 20);
    if payload.capacity() < reserve {
        payload.reserve(reserve - payload.capacity());
    }
    let n = std::io::Read::take(&mut *f, header.payload_len as u64).read_to_end(payload)?;
    if n < header.payload_len {
        return Err(PersistenceError::Format(format!(
            "checkpoint payload truncated: got {n} of {} bytes",
            header.payload_len
        )));
    }
    header.verify_payload(payload)?;
    Ok(())
}

fn read_checkpoint_payload(dir: &dyn Directory, path: &str) -> PersistenceResult<Vec<u8>> {
    let mut payload = Vec::new();
    read_checkpoint_payload_into(dir, path, &mut payload)?;
    Ok(payload)
}

/// The reserved sidecar file name for a consumer's per-segment built index.
///
/// Use this with [`View::segment_ids`] when a reader/searcher needs to load a
/// persisted sidecar without holding the writer's [`SegmentedStore`] handle.
/// `kind` must be non-empty ASCII alphanumeric plus `_` or `-`. It is a short
/// namespace tag, not a compatibility proof; put full algorithm/config/input
/// fingerprints in the sidecar bytes, include the expected segment id when
/// accepting a copied sidecar would be unsafe, and rebuild from the raw segment
/// when they mismatch.
pub fn try_index_name(id: u64, kind: &str) -> PersistenceResult<String> {
    index_sidecar_name(id, kind)
}

/// Infallible convenience wrapper around [`try_index_name`].
///
/// Panics if `kind` violates the documented sidecar-kind grammar.
pub fn index_name(id: u64, kind: &str) -> String {
    try_index_name(id, kind).unwrap_or_else(|e| panic!("invalid segstore index kind: {e}"))
}

/// How durable each WAL write is before [`SegmentedStore::add`] / [`SegmentedStore::delete`]
/// returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncPolicy {
    /// Flush each record to the underlying writer (userspace -> OS). The default;
    /// works on every [`Directory`] backend.
    Flush,
    /// fsync each record to stable storage. Stronger (survives power loss) and
    /// slower; requires a filesystem-backed [`Directory`] (one that provides
    /// `file_path()`), else [`SegmentedStore::open_with_options`] errors.
    Fsync,
}

/// Size-tiered compaction tuning. Defaults follow Cassandra's SizeTieredCompactionStrategy
/// (`min_threshold = 4`, `max_threshold = 32`, bucket band `0.5x .. 1.5x`) and Lucene's
/// `TieredMergePolicy` (a max merged-segment cap, above half of which a segment is frozen
/// out of further tier merges).
///
/// The size metric is item count ([`Store::segment_len`]); these are item counts, not
/// bytes. Because a query scans every segment, the per-tier segment count is paid on every
/// read, so `min_merge` is kept small.
#[derive(Debug, Clone, Copy)]
pub struct TierConfig {
    /// Minimum segments in a size bucket before it is eligible to merge (Cassandra
    /// `min_threshold`). 2 degenerates tiering into leveling, so 4 is the practical floor.
    pub min_merge: usize,
    /// Maximum segments merged in one job (Cassandra `max_threshold`), bounding per-merge
    /// cost and pause.
    pub max_merge: usize,
    /// Lower size-band multiplier for bucket membership (Cassandra `bucket_low`).
    pub bucket_low: f64,
    /// Upper size-band multiplier for bucket membership (Cassandra `bucket_high`).
    pub bucket_high: f64,
    /// Cap on a merged segment's item count. A segment larger than half of this is frozen
    /// out of tier merges (Lucene's rule), so the largest segment is never rewritten by
    /// tiering, only by a full [`SegmentedStore::compact`]. Without this, top-tier merges
    /// rewrite the whole dataset (O(N^2) write amplification).
    ///
    /// This is an item count, but each segment is persisted as one checkpoint blob
    /// bounded by [`MAX_CHECKPOINT_PAYLOAD_BYTES`] (256 MiB). The two caps are in
    /// different units: keep `max_merged_len * (your serialized bytes per item)` under
    /// that byte cap, or a large merge fails: the compaction returns the size-cap
    /// error and leaves the segment set unchanged, and later checkpoints proceed.
    /// The default (10 million items) is far above the byte cap for most payloads;
    /// dense `f32` vectors of dimension `d` take about `4 * d` bytes per item, so
    /// a 768-dimensional store reaches 256 MiB near 87,000 items. There is no
    /// byte-aware merge planning yet (see the size-cap discussion in the crate docs).
    pub max_merged_len: usize,
}

impl Default for TierConfig {
    fn default() -> Self {
        Self {
            min_merge: 4,
            max_merge: 32,
            bucket_low: 0.5,
            bucket_high: 1.5,
            max_merged_len: 10_000_000,
        }
    }
}

/// What a compaction did, for the consumer to track merge cost vs corpus size (the signal
/// that a multi-segment store is outgrowing the search-all-segments model).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CompactionStats {
    /// Number of merge operations performed.
    pub merges: usize,
    /// Segment count before the compaction.
    pub segments_before: usize,
    /// Segment count after the compaction.
    pub segments_after: usize,
    /// Total items written into the merged output segment(s).
    pub items_merged: usize,
}

/// Options for opening a [`SegmentedStore`].
#[derive(Debug, Clone, Copy)]
pub struct Options {
    /// Buffered-add count that seals a new segment.
    pub flush_threshold: usize,
    /// Per-write WAL durability.
    pub sync: SyncPolicy,
    /// Size-tiered compaction tuning (used by [`SegmentedStore::compact_tiers`]).
    pub tiering: TierConfig,
    /// When true, [`SegmentedStore::add`] runs `compact_tiers` after sealing a segment if a
    /// bucket is eligible, on the calling thread. Default false: the consumer drives
    /// `compact_tiers` when convenient (e.g. on a background thread), so the merge latency
    /// never lands on the ingest hot path.
    pub auto_compact: bool,
}

impl Options {
    /// Options with the given flush threshold and defaults for the rest (`Flush` sync,
    /// default tiering, no auto-compaction).
    pub fn new(flush_threshold: usize) -> Self {
        Self {
            flush_threshold,
            sync: SyncPolicy::Flush,
            tiering: TierConfig::default(),
            auto_compact: false,
        }
    }
}

/// The consumer-defined payload model: how items batch into a segment and how
/// segments merge during compaction.
///
/// `segstore` never inspects a segment's contents; it only stores, snapshots,
/// and hands segments back to these two methods, so the representation is
/// entirely the consumer's (posting lists, a graph delta, a vector block, ...).
pub trait Store {
    /// Stable identity of an item, used for tombstones and WAL replay.
    type Id: Clone + Eq + Hash + Serialize + DeserializeOwned;
    /// The per-item payload carried in the WAL until it is flushed to a segment.
    type Item: Clone + Serialize + DeserializeOwned;
    /// An immutable batch of items. Opaque to `segstore`.
    type Segment: Clone + Serialize + DeserializeOwned;

    /// Build one immutable segment from a batch of live `(id, item)` pairs.
    fn build_segment(&self, batch: &[(Self::Id, Self::Item)]) -> Self::Segment;

    /// Merge `segments` into one during compaction, keeping only ids for which
    /// `live(id)` is true (i.e. dropping tombstoned ids).
    ///
    /// Segments arrive by reference (`&[&Self::Segment]`) so `segstore` can pass
    /// its `Arc`-held segments straight through without cloning the payloads.
    fn merge_segments(
        &self,
        segments: &[&Self::Segment],
        live: &dyn Fn(&Self::Id) -> bool,
    ) -> Self::Segment;

    /// The number of items in `segment`. This is the size metric size-tiered
    /// compaction groups segments by, so a count of *live* items (after any
    /// tombstone drop a merge applied) is the right answer. For the common
    /// `Vec`-backed segment this is just `segment.len()`.
    fn segment_len(&self, segment: &Self::Segment) -> usize;

    /// The number of items in `segment` for which `live` is true (i.e. excluding
    /// tombstoned ids), if the consumer can compute it cheaply. Returning `Some`
    /// enables space-amplification reporting ([`SegmentedStore::space_amplification`])
    /// and tombstone-reclaiming compaction ([`SegmentedStore::reclaim_tombstones`]).
    /// The default `None` disables both; the size-tiered path does not need it.
    /// For a `Vec`-backed segment: `Some(segment.iter().filter(|(id, _)| live(id)).count())`.
    fn live_len(
        &self,
        _segment: &Self::Segment,
        _live: &dyn Fn(&Self::Id) -> bool,
    ) -> Option<usize> {
        None
    }

    /// The ids of every item in `segment`, or `None` if the consumer cannot list
    /// them. A store must answer the same way for every segment.
    ///
    /// Returning `Some` turns on replace semantics across sealed segments: a
    /// re-add or delete of an id marks its older sealed copy superseded, so
    /// [`SegmentedStore::is_live_in`] (and the [`View`] and [`SegmentCatalog`]
    /// forms) report only the newest copy and merges drop the rest. segstore
    /// calls this when it opens a store and on each merge output, to learn
    /// which segment holds each id's live copy. With the default `None`, a
    /// re-add still replaces a copy that is in the buffer, but an older copy in
    /// a sealed segment stays live next to the new one.
    fn item_ids(&self, _segment: &Self::Segment) -> Option<Vec<Self::Id>> {
        None
    }
}

/// Default vec-backed segment model for append-only source batches.
///
/// This is the common consumer shape where each immutable segment is just
/// `Vec<(Id, Item)>`, `build_segment` copies the sealed buffer, and compaction
/// concatenates live entries from the merged segments. It implements
/// [`Store::item_ids`], so a re-add replaces the older copy (last write wins)
/// as described on [`SegmentedStore::add`]. Consumers that need sorted
/// segments or custom merge logic should keep their own [`Store`]
/// implementation.
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultStore<Id, Item> {
    _marker: PhantomData<fn() -> (Id, Item)>,
}

impl<Id, Item> DefaultStore<Id, Item> {
    /// Create a default vec-backed store model.
    pub fn new() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

impl<Id, Item> Store for DefaultStore<Id, Item>
where
    Id: Clone + Eq + Hash + Serialize + DeserializeOwned,
    Item: Clone + Serialize + DeserializeOwned,
{
    type Id = Id;
    type Item = Item;
    type Segment = Vec<(Id, Item)>;

    fn build_segment(&self, batch: &[(Id, Item)]) -> Self::Segment {
        batch.to_vec()
    }

    fn merge_segments(
        &self,
        segments: &[&Self::Segment],
        live: &dyn Fn(&Id) -> bool,
    ) -> Self::Segment {
        segments
            .iter()
            .flat_map(|segment| segment.iter())
            .filter(|(id, _)| live(id))
            .cloned()
            .collect()
    }

    fn segment_len(&self, segment: &Self::Segment) -> usize {
        segment.len()
    }

    fn live_len(&self, segment: &Self::Segment, live: &dyn Fn(&Id) -> bool) -> Option<usize> {
        Some(segment.iter().filter(|(id, _)| live(id)).count())
    }

    fn item_ids(&self, segment: &Self::Segment) -> Option<Vec<Id>> {
        Some(segment.iter().map(|(id, _)| id.clone()).collect())
    }
}

/// Consumer-owned sidecar envelope with checked shared mechanics.
///
/// The envelope covers the repeated cross-consumer header pattern:
/// `magic[8] | version:u32 | segment_id:u64 | recipe_len:u32 | crc32:u32 |
/// recipe | payload`. The CRC covers every byte except the CRC field itself,
/// so corrupt fixed header fields, recipe bytes, or payload bytes are rejected
/// before the payload is trusted.
///
/// This type does not define a sidecar format for consumers. `magic`, `version`,
/// `recipe`, and the payload codec remain consumer-owned compatibility choices;
/// this helper only centralizes the bounds checks and CRC framing.
pub struct SidecarEnvelope;

/// Payload range described by a sidecar envelope header.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SidecarPayloadInfo {
    payload_offset: u64,
    payload_len: u64,
    crc32: u32,
}

impl SidecarPayloadInfo {
    /// Byte offset of the payload inside the containing sidecar file.
    pub fn payload_offset(self) -> u64 {
        self.payload_offset
    }

    /// Byte length of the payload inside the containing sidecar file.
    pub fn payload_len(self) -> u64 {
        self.payload_len
    }

    /// Stored envelope CRC32.
    ///
    /// [`SidecarEnvelope::payload_info`] returns this value without verifying
    /// it, so lazy readers can decide whether to verify the full envelope or
    /// rely on payload-format checksums.
    pub fn crc32(self) -> u32 {
        self.crc32
    }
}

impl SidecarEnvelope {
    /// Encode a payload with the common sidecar envelope.
    pub fn encode(
        magic: &[u8; 8],
        version: u32,
        segment_id: u64,
        recipe: &[u8],
        payload: &[u8],
    ) -> PersistenceResult<Vec<u8>> {
        let recipe_len = u32::try_from(recipe.len()).map_err(|_| {
            PersistenceError::InvalidConfig(format!(
                "sidecar recipe too large: {} bytes (max {})",
                recipe.len(),
                u32::MAX
            ))
        })?;
        let mut bytes =
            Vec::with_capacity(SIDECAR_ENVELOPE_HEADER_BYTES + recipe.len() + payload.len());
        bytes.extend_from_slice(magic);
        bytes.extend_from_slice(&version.to_le_bytes());
        bytes.extend_from_slice(&segment_id.to_le_bytes());
        bytes.extend_from_slice(&recipe_len.to_le_bytes());
        bytes.extend_from_slice(&0u32.to_le_bytes());
        bytes.extend_from_slice(recipe);
        bytes.extend_from_slice(payload);
        let crc = sidecar_envelope_crc(&bytes);
        bytes[24..28].copy_from_slice(&crc.to_le_bytes());
        Ok(bytes)
    }

    /// Decode and validate a common sidecar envelope, returning the payload.
    pub fn decode<'a>(
        expected_magic: &[u8; 8],
        expected_version: u32,
        expected_segment_id: u64,
        expected_recipe: &[u8],
        bytes: &'a [u8],
    ) -> PersistenceResult<&'a [u8]> {
        if bytes.len() < SIDECAR_ENVELOPE_HEADER_BYTES {
            return Err(PersistenceError::Format(
                "sidecar envelope header is truncated".into(),
            ));
        }
        if &bytes[..8] != expected_magic {
            return Err(PersistenceError::Format(
                "sidecar envelope magic mismatch".into(),
            ));
        }
        let version = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
        if version != expected_version {
            return Err(PersistenceError::Format(format!(
                "sidecar envelope version mismatch: got {version}, expected {expected_version}"
            )));
        }
        let segment_id = u64::from_le_bytes(bytes[12..20].try_into().unwrap());
        if segment_id != expected_segment_id {
            return Err(PersistenceError::Format(format!(
                "sidecar envelope segment id mismatch: got {segment_id}, expected {expected_segment_id}"
            )));
        }
        let recipe_len = u32::from_le_bytes(bytes[20..24].try_into().unwrap()) as usize;
        let recipe_start = SIDECAR_ENVELOPE_HEADER_BYTES;
        let recipe_end = recipe_start
            .checked_add(recipe_len)
            .ok_or_else(|| PersistenceError::Format("sidecar recipe length overflow".into()))?;
        if bytes.len() < recipe_end {
            return Err(PersistenceError::Format(
                "sidecar envelope recipe is truncated".into(),
            ));
        }

        let expected_crc = u32::from_le_bytes(bytes[24..28].try_into().unwrap());
        let actual_crc = sidecar_envelope_crc(bytes);
        if actual_crc != expected_crc {
            return Err(PersistenceError::CrcMismatch {
                expected: expected_crc,
                actual: actual_crc,
            });
        }

        if &bytes[recipe_start..recipe_end] != expected_recipe {
            return Err(PersistenceError::Format(
                "sidecar envelope recipe mismatch".into(),
            ));
        }
        Ok(&bytes[recipe_end..])
    }

    /// Read and validate the sidecar header/recipe, returning the payload range.
    ///
    /// This reads only the fixed header and recipe from `reader`, which must be
    /// positioned at the start of the sidecar. It does not verify the stored
    /// envelope CRC over the payload; use [`Self::decode`] when the full sidecar
    /// is already resident and must be fully verified before use. This helper is
    /// for payload formats that have their own lazy checksums and need to keep
    /// the payload file-backed.
    pub fn payload_info<R: Read + ?Sized>(
        expected_magic: &[u8; 8],
        expected_version: u32,
        expected_segment_id: u64,
        expected_recipe: &[u8],
        reader: &mut R,
        sidecar_len: u64,
    ) -> PersistenceResult<SidecarPayloadInfo> {
        if sidecar_len < SIDECAR_ENVELOPE_HEADER_BYTES as u64 {
            return Err(PersistenceError::Format(
                "sidecar envelope header is truncated".into(),
            ));
        }

        let mut header = [0u8; SIDECAR_ENVELOPE_HEADER_BYTES];
        reader.read_exact(&mut header)?;
        if &header[..8] != expected_magic {
            return Err(PersistenceError::Format(
                "sidecar envelope magic mismatch".into(),
            ));
        }
        let version = u32::from_le_bytes(header[8..12].try_into().unwrap());
        if version != expected_version {
            return Err(PersistenceError::Format(format!(
                "sidecar envelope version mismatch: got {version}, expected {expected_version}"
            )));
        }
        let segment_id = u64::from_le_bytes(header[12..20].try_into().unwrap());
        if segment_id != expected_segment_id {
            return Err(PersistenceError::Format(format!(
                "sidecar envelope segment id mismatch: got {segment_id}, expected {expected_segment_id}"
            )));
        }
        let recipe_len = u32::from_le_bytes(header[20..24].try_into().unwrap()) as u64;
        let payload_offset = (SIDECAR_ENVELOPE_HEADER_BYTES as u64)
            .checked_add(recipe_len)
            .ok_or_else(|| PersistenceError::Format("sidecar recipe length overflow".into()))?;
        if sidecar_len < payload_offset {
            return Err(PersistenceError::Format(
                "sidecar envelope recipe is truncated".into(),
            ));
        }
        if recipe_len != expected_recipe.len() as u64 {
            return Err(PersistenceError::Format(
                "sidecar envelope recipe mismatch".into(),
            ));
        }

        let mut recipe = vec![0; expected_recipe.len()];
        reader.read_exact(&mut recipe)?;
        if recipe != expected_recipe {
            return Err(PersistenceError::Format(
                "sidecar envelope recipe mismatch".into(),
            ));
        }

        Ok(SidecarPayloadInfo {
            payload_offset,
            payload_len: sidecar_len - payload_offset,
            crc32: u32::from_le_bytes(header[24..28].try_into().unwrap()),
        })
    }
}

fn sidecar_envelope_crc(bytes: &[u8]) -> u32 {
    let mut hasher = crc32fast::Hasher::new();
    hasher.update(&bytes[..24]);
    hasher.update(&bytes[28..]);
    hasher.finalize()
}

/// One write-ahead-log operation.
#[derive(Serialize, Deserialize)]
enum Op<Id, Item> {
    Add(Id, Item),
    Delete(Id),
}

/// The checkpoint manifest: the commit point of the on-disk state. It names the
/// current segment files by id and carries the tombstone set; the segments
/// themselves live in `segstore.seg.<id>` files written once and never rewritten,
/// so a checkpoint writes only the *new* segments plus this small manifest
/// (O(delta), not O(total)). The epoch lives in the [`CheckpointFile`] header,
/// not the body. This owned form is the *read* side (recovery decodes into it).
///
/// This is the original layout, which ends after the tombstones. Current writers
/// append a [`ManifestExt`]; see [`ManifestV2`].
#[derive(Deserialize)]
struct Manifest<Id> {
    next_seg_id: u64,
    segment_ids: Vec<u64>,
    tombstones: Vec<Id>,
}

/// Version of the [`ManifestExt`] layout that current writers append.
const MANIFEST_EXT_VERSION: u32 = 1;

/// The current manifest: the original fields, then a versioned extension.
/// Appending keeps older readers working: postcard decodes the leading fields
/// and ignores trailing bytes, so an older segstore reads this as a
/// [`Manifest`] (and loses only the superseded-copy information).
#[derive(Deserialize)]
struct ManifestV2<Id> {
    next_seg_id: u64,
    segment_ids: Vec<u64>,
    tombstones: Vec<Id>,
    ext: ManifestExt<Id>,
}

/// Manifest extension, version [`MANIFEST_EXT_VERSION`].
#[derive(Deserialize)]
struct ManifestExt<Id> {
    version: u32,
    /// Per segment id, the ids whose copy in that segment was superseded by a
    /// later add or delete.
    superseded: Vec<(u64, Vec<Id>)>,
}

/// Borrowing view of the manifest for *writing*: serializes the ids + tombstones
/// in place. Wire-identical to [`ManifestV2`] (postcard encodes a struct as its
/// fields in order, and a `&[&Id]` as the same sequence as a `Vec<Id>`).
#[derive(Serialize)]
struct ManifestRef<'a, Id> {
    next_seg_id: u64,
    segment_ids: &'a [u64],
    tombstones: &'a [&'a Id],
    ext: ManifestExtRef<'a, Id>,
}

/// Borrowing write form of [`ManifestExt`].
#[derive(Serialize)]
struct ManifestExtRef<'a, Id> {
    version: u32,
    superseded: &'a [(u64, Vec<&'a Id>)],
}

/// A decoded manifest of either layout.
struct LoadedManifest<Id> {
    has_ownership_metadata: bool,
    epoch: u64,
    next_seg_id: u64,
    segment_ids: Vec<u64>,
    tombstones: HashSet<Id>,
    superseded: HashMap<u64, HashSet<Id>>,
}

/// Read the manifest in `dir`, if there is one.
fn read_manifest<Id>(dir: &Arc<dyn Directory>) -> PersistenceResult<Option<LoadedManifest<Id>>>
where
    Id: Eq + Hash + DeserializeOwned,
{
    if !dir.exists(MANIFEST_PATH) {
        return Ok(None);
    }
    let ckpt = CheckpointFile::new(dir.clone());
    let loaded = match ckpt.read_postcard::<ManifestV2<Id>>(MANIFEST_PATH) {
        Ok((epoch, m)) => {
            if m.ext.version != MANIFEST_EXT_VERSION {
                return Err(PersistenceError::Format(format!(
                    "unsupported segstore manifest extension version {} (expected {})",
                    m.ext.version, MANIFEST_EXT_VERSION
                )));
            }
            LoadedManifest {
                has_ownership_metadata: true,
                epoch,
                next_seg_id: m.next_seg_id,
                segment_ids: m.segment_ids,
                tombstones: m.tombstones.into_iter().collect(),
                superseded: m
                    .ext
                    .superseded
                    .into_iter()
                    .map(|(seg, ids)| (seg, ids.into_iter().collect()))
                    .collect(),
            }
        }
        // The CRC already passed, so a decode failure here is the original
        // layout ending before the extension. Anything else still fails below.
        Err(PersistenceError::Decode(_)) => {
            let (epoch, m): (u64, Manifest<Id>) = ckpt.read_postcard(MANIFEST_PATH)?;
            LoadedManifest {
                has_ownership_metadata: false,
                epoch,
                next_seg_id: m.next_seg_id,
                segment_ids: m.segment_ids,
                tombstones: m.tombstones.into_iter().collect(),
                superseded: HashMap::new(),
            }
        }
        Err(e) => return Err(e),
    };
    Ok(Some(loaded))
}

/// Whether the copy of `id` sealed in segment `seg` is the live one: `id` is not
/// tombstoned and that copy was not superseded by a later add.
fn copy_is_live<Id: Eq + Hash>(
    tombstones: &HashSet<Id>,
    superseded: &HashMap<u64, HashSet<Id>>,
    seg: u64,
    id: &Id,
) -> bool {
    !tombstones.contains(id) && !matches!(superseded.get(&seg), Some(ids) if ids.contains(id))
}

/// The reader-visible published state: the segments and tombstones as of the last
/// checkpoint, behind `Arc`s so a [`View`] is a cheap, consistent snapshot.
struct PubState<S: Store> {
    segments: Arc<Vec<Arc<S::Segment>>>,
    segment_ids: Arc<Vec<u64>>,
    tombstones: Arc<HashSet<S::Id>>,
    superseded: Arc<HashMap<u64, HashSet<S::Id>>>,
}

/// Checkpointed segment metadata without deserializing segment payloads.
///
/// `SegmentCatalog` is a manifest reader, not an out-of-core query engine. It
/// exposes the segment ids and tombstones named by the last checkpoint so a
/// consumer can find segment files or sidecars without opening a
/// [`SegmentedStore`] writer, but the current `segstore.seg.<id>` payloads are
/// still checkpoint-wrapped encodings of `Store::Segment`.
pub struct SegmentCatalog<Id> {
    dir: Arc<dyn Directory>,
    epoch: u64,
    next_segment_id: u64,
    segment_ids: Vec<u64>,
    tombstones: HashSet<Id>,
    superseded: HashMap<u64, HashSet<Id>>,
}

impl<Id> SegmentCatalog<Id>
where
    Id: Eq + Hash + DeserializeOwned,
{
    /// Open the last checkpoint manifest without reading any segment files.
    ///
    /// Visibility matches [`Reader::view`]: this reflects only the most recent
    /// checkpoint. WAL suffix records after that checkpoint are not exposed
    /// because they have not been sealed into immutable segment files.
    ///
    /// Returns a format error for a nonempty legacy manifest without per-copy
    /// ownership metadata. Catalog access cannot resolve duplicate copies without
    /// reading segment payloads. Writer recovery and checkpoint can upgrade
    /// duplicates across segments, but duplicate live ids within one segment
    /// require rebuilding from validated records instead.
    pub fn open(dir: Arc<dyn Directory>) -> PersistenceResult<Self> {
        reject_legacy_formats(&*dir)?;

        let m = read_manifest(&dir)?.unwrap_or_else(|| LoadedManifest {
            has_ownership_metadata: true,
            epoch: 0,
            next_seg_id: 0,
            segment_ids: Vec::new(),
            tombstones: HashSet::new(),
            superseded: HashMap::new(),
        });
        if !m.has_ownership_metadata && !m.segment_ids.is_empty() {
            return Err(PersistenceError::Format(
                "legacy manifest lacks per-copy ownership metadata; read-only catalog access requires explicit migration or rebuilding from validated records".into(),
            ));
        }
        Ok(Self {
            dir,
            epoch: m.epoch,
            next_segment_id: m.next_seg_id,
            segment_ids: m.segment_ids,
            tombstones: m.tombstones,
            superseded: m.superseded,
        })
    }

    /// WAL epoch covered by the checkpoint manifest.
    pub fn epoch(&self) -> u64 {
        self.epoch
    }

    /// Next segment id recorded in the manifest.
    pub fn next_segment_id(&self) -> u64 {
        self.next_segment_id
    }

    /// Stable ids of the checkpointed immutable segments, oldest first.
    pub fn segment_ids(&self) -> &[u64] {
        &self.segment_ids
    }

    /// Number of checkpointed immutable segments.
    pub fn segment_count(&self) -> usize {
        self.segment_ids.len()
    }

    /// Number of tombstoned ids in the checkpoint.
    pub fn tombstone_count(&self) -> usize {
        self.tombstones.len()
    }

    /// Whether `id` is not tombstoned in this checkpoint.
    ///
    /// This is per-id: when a re-added id has copies in several segments, it is
    /// true for all of them. Filter a segment's contents with
    /// [`Self::is_live_in`] instead.
    pub fn is_live(&self, id: &Id) -> bool {
        !self.tombstones.contains(id)
    }

    /// Whether the copy of `id` in segment `segment_id` is live in this
    /// checkpoint: `id` is not tombstoned and was not re-added after that
    /// segment sealed. At most one copy of an id passes this check (see
    /// [`SegmentedStore::add`]).
    pub fn is_live_in(&self, segment_id: u64, id: &Id) -> bool {
        copy_is_live(&self.tombstones, &self.superseded, segment_id, id)
    }

    /// The directory backing this catalog.
    pub fn dir(&self) -> &Arc<dyn Directory> {
        &self.dir
    }

    /// Segment file name for `id`, if the checkpoint names that segment.
    pub fn segment_name(&self, id: u64) -> PersistenceResult<String> {
        self.ensure_segment_id(id)?;
        Ok(seg_path(id))
    }

    /// Filesystem path for `id`, if this directory exposes paths.
    pub fn segment_file_path(&self, id: u64) -> PersistenceResult<Option<std::path::PathBuf>> {
        Ok(self.dir.file_path(&self.segment_name(id)?))
    }

    /// Open the raw segment file for `id`.
    ///
    /// The returned file is the current segstore segment file, including its
    /// durability checkpoint envelope. This method intentionally does not decode
    /// `Store::Segment`; consumers that need byte-native segments need the raw
    /// segment API described in `docs/out-of-core-segment-reader.md`.
    pub fn open_segment_file(&self, id: u64) -> PersistenceResult<Box<dyn std::io::Read + Send>> {
        self.dir.open_file(&self.segment_name(id)?)
    }

    /// Read one segment file's header and return where its serialized payload lives.
    ///
    /// This validates the checkpoint envelope and reads the payload bytes once
    /// to compute the public payload CRC. Use the returned offset and length
    /// with [`Self::segment_file_path`] for mmap/range-read sidecar rebuilders,
    /// then verify [`SegmentPayloadInfo::payload_crc32`] over the mapped bytes
    /// before trusting them. If you want segstore to return the payload bytes
    /// directly, use [`Self::read_segment_payload`] or
    /// [`Self::read_segment_payload_into`].
    pub fn segment_payload_info(&self, id: u64) -> PersistenceResult<SegmentPayloadInfo> {
        read_checkpoint_payload_info(&*self.dir, &self.segment_name(id)?)
    }

    /// Read one checkpointed segment's CRC-validated serialized payload bytes.
    ///
    /// This avoids opening a full [`SegmentedStore`] and avoids deserializing
    /// `Store::Segment`, but it is still a whole-payload read of the postcard
    /// bytes that segstore wrote for that segment. It is a loader/build helper,
    /// not a streaming or mmap-backed query reader. Tombstones are NOT applied:
    /// the payload is the segment as written, including records later deleted;
    /// filter with [`Self::is_live_in`] before treating contents as live data.
    pub fn read_segment_payload(&self, id: u64) -> PersistenceResult<Vec<u8>> {
        read_checkpoint_payload(&*self.dir, &self.segment_name(id)?)
    }

    /// Read one checkpointed segment's CRC-validated serialized payload bytes into
    /// `payload`.
    ///
    /// This is the reusable-buffer form of [`Self::read_segment_payload`] for
    /// sidecar builders that scan many segments. `payload` is cleared before the
    /// read; on error it is left empty.
    pub fn read_segment_payload_into(
        &self,
        id: u64,
        payload: &mut Vec<u8>,
    ) -> PersistenceResult<()> {
        read_checkpoint_payload_into(&*self.dir, &self.segment_name(id)?, payload)
    }

    /// Decode one checkpointed segment by id.
    ///
    /// This is a bounded restart/build helper: it decodes only the requested
    /// segment file instead of opening a full [`SegmentedStore`] and decoding
    /// every segment in the manifest. It is still a whole-segment postcard decode,
    /// not a byte-native or mmap-backed query reader. Tombstones are NOT applied:
    /// the decoded segment is as written, including records later deleted;
    /// filter with [`Self::is_live_in`] before treating contents as live data.
    pub fn read_segment<Segment>(&self, id: u64) -> PersistenceResult<Segment>
    where
        Segment: DeserializeOwned,
    {
        let ckpt = CheckpointFile::new(self.dir.clone());
        let (_, segment) = ckpt.read_postcard(&self.segment_name(id)?)?;
        Ok(segment)
    }

    /// Reserved sidecar file name for a per-segment index of the given `kind`.
    pub fn try_index_name(&self, id: u64, kind: &str) -> PersistenceResult<String> {
        self.ensure_segment_id(id)?;
        try_index_name(id, kind)
    }

    /// Canonical live-id set of one checkpointed segment.
    ///
    /// `ids` must be the ids of the copies stored in `segment_id` (the consumer
    /// enumerates them from its own decoded segment); segstore filters them by
    /// [`Self::is_live_in`] and returns them sorted and deduped. A
    /// [`SegmentCatalog`] cannot enumerate a segment's ids itself because it
    /// does not hold a [`Store`] value.
    pub fn live_ids<I>(&self, segment_id: u64, ids: I) -> crate::sidecar::LiveIds<Id>
    where
        Id: Ord,
        I: IntoIterator<Item = Id>,
    {
        crate::sidecar::LiveIds::new(ids.into_iter().filter(|id| self.is_live_in(segment_id, id)))
    }

    /// Infallible convenience wrapper around [`Self::try_index_name`].
    ///
    /// Panics if `id` is not in this catalog or `kind` violates the documented
    /// sidecar-kind grammar.
    pub fn index_name(&self, id: u64, kind: &str) -> String {
        self.try_index_name(id, kind)
            .unwrap_or_else(|e| panic!("invalid segstore catalog index name: {e}"))
    }

    fn ensure_segment_id(&self, id: u64) -> PersistenceResult<()> {
        // Segment ids are allocated monotonically and kept oldest-first, so the
        // manifest vector is sorted without an extra lookup structure.
        if self.segment_ids.binary_search(&id).is_ok() {
            Ok(())
        } else {
            Err(PersistenceError::NotFound(format!(
                "segment id {id} is not in the checkpoint manifest"
            )))
        }
    }
}

/// A consistent, point-in-time read view of the store, independent of the writer.
///
/// A [`Reader`] hands these out; holding one keeps its segments alive for the whole
/// query even as the writer adds, deletes, or compacts concurrently (single-writer,
/// many-readers, like Lucene's `SearcherManager` / Tantivy's `Searcher`). Visibility
/// is *commit-style*: a view reflects the state as of the last [`SegmentedStore::checkpoint`]
/// (which compaction also performs), so adds and deletes since then become visible
/// after the next checkpoint. Publishing only at the checkpoint keeps it off the
/// ingest hot path (republishing per write made bulk ingest quadratic).
pub struct View<S: Store> {
    segments: Arc<Vec<Arc<S::Segment>>>,
    segment_ids: Arc<Vec<u64>>,
    tombstones: Arc<HashSet<S::Id>>,
    superseded: Arc<HashMap<u64, HashSet<S::Id>>>,
    dir: Arc<dyn Directory>,
}

impl<S: Store> View<S> {
    /// The snapshot's immutable segments, oldest first. Query these (each derefs to
    /// `S::Segment`), filtering each one's copies with [`Self::is_live_in`].
    pub fn segments(&self) -> &[Arc<S::Segment>] {
        &self.segments
    }

    /// The stable persistence id of each segment in [`Self::segments`], same order.
    /// Unlike the segment's `Arc` pointer, this id is stable across checkpoints AND
    /// restarts (it names the segment's `segstore.seg.<id>` file), so a consumer can
    /// key a *persisted* per-segment built-index cache on it (via
    /// [`try_index_name`]) and reload across a process restart instead of rebuilding
    /// from the raw payload.
    pub fn segment_ids(&self) -> &[u64] {
        &self.segment_ids
    }

    /// The directory this snapshot's segments live in.
    ///
    /// Together with [`Self::try_index_name`] this lets a reader/searcher resolve
    /// `segstore.idx.<id>.<kind>` without holding the writer, so a snapshot can
    /// load a persisted sidecar instead of rebuilding it.
    pub fn dir(&self) -> &Arc<dyn Directory> {
        &self.dir
    }

    /// Reserved sidecar file name for a per-segment index of the given `kind`,
    /// for a segment in this snapshot.
    pub fn try_index_name(&self, id: u64, kind: &str) -> PersistenceResult<String> {
        if self.segment_ids.binary_search(&id).is_err() {
            return Err(PersistenceError::NotFound(format!(
                "segment id {id} is not in this view"
            )));
        }
        try_index_name(id, kind)
    }

    /// Infallible convenience wrapper around [`Self::try_index_name`].
    ///
    /// Panics if `id` is not in this snapshot or `kind` violates the documented
    /// sidecar-kind grammar.
    pub fn index_name(&self, id: u64, kind: &str) -> String {
        self.try_index_name(id, kind)
            .unwrap_or_else(|e| panic!("invalid segstore view index name: {e}"))
    }

    /// Whether `id` is not tombstoned in this snapshot.
    ///
    /// This is per-id: when a re-added id has copies in several segments, it is
    /// true for all of them. Filter a segment's contents with
    /// [`Self::is_live_in`] instead.
    pub fn is_live(&self, id: &S::Id) -> bool {
        !self.tombstones.contains(id)
    }

    /// Whether the copy of `id` in segment `segment_id` (an entry of
    /// [`Self::segment_ids`]) is live in this snapshot: `id` is not tombstoned
    /// and was not re-added after that segment sealed. At most one copy of an
    /// id passes this check (see [`SegmentedStore::add`]).
    pub fn is_live_in(&self, segment_id: u64, id: &S::Id) -> bool {
        copy_is_live(&self.tombstones, &self.superseded, segment_id, id)
    }

    /// Canonical live-id set of one segment in this snapshot.
    ///
    /// `ids` must be the ids of the copies stored in `segment_id` (the consumer
    /// enumerates them from its own decoded segment); segstore filters them by
    /// [`Self::is_live_in`] and returns them sorted and deduped. A [`View`]
    /// cannot enumerate a segment's ids itself because it holds no [`Store`]
    /// value.
    pub fn live_ids<I>(&self, segment_id: u64, ids: I) -> crate::sidecar::LiveIds<S::Id>
    where
        S::Id: Ord,
        I: IntoIterator<Item = S::Id>,
    {
        crate::sidecar::LiveIds::new(ids.into_iter().filter(|id| self.is_live_in(segment_id, id)))
    }

    /// Number of segments in this snapshot.
    pub fn segment_count(&self) -> usize {
        self.segments.len()
    }
}

/// A cloneable, thread-safe handle for concurrent snapshot reads while the writer
/// mutates. Obtain via [`SegmentedStore::reader`]; clone freely across threads.
pub struct Reader<S: Store> {
    published: Arc<std::sync::RwLock<Arc<PubState<S>>>>,
    dir: Arc<dyn Directory>,
}

impl<S: Store> Clone for Reader<S> {
    fn clone(&self) -> Self {
        Reader {
            published: self.published.clone(),
            dir: self.dir.clone(),
        }
    }
}

impl<S: Store> Reader<S> {
    /// Take a consistent [`View`] of the store as of the last published mutation.
    /// Cheap (a couple of `Arc` clones under a brief read lock); the view is then
    /// held lock-free for the query's duration.
    pub fn view(&self) -> View<S> {
        let state = self.published.read().unwrap().clone();
        View {
            segments: state.segments.clone(),
            segment_ids: state.segment_ids.clone(),
            tombstones: state.tombstones.clone(),
            superseded: state.superseded.clone(),
            dir: self.dir.clone(),
        }
    }
}

/// Take the store's exclusive advisory lock (flock / LockFileEx).
///
/// The kernel drops it when the process exits, so a crash never leaves a
/// stale lock behind.
fn acquire_store_lock(dir: &dyn Directory) -> PersistenceResult<Option<std::fs::File>> {
    let Some(path) = dir.file_path(LOCK_PATH) else {
        return Ok(None);
    };
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)?;
    use fs4::fs_std::FileExt;
    // fs4 reports contention as `Ok(false)`, not as an error.
    if !file.try_lock_exclusive()? {
        return Err(PersistenceError::LockFailed {
            resource: path.display().to_string(),
            reason: "another SegmentedStore holds this directory".into(),
        });
    }
    Ok(Some(file))
}

/// A generic, durable, segmented mutable store.
pub struct SegmentedStore<S: Store> {
    store: S,
    dir: Arc<dyn Directory>,
    /// Live adds not yet flushed into a segment.
    buffer: Vec<(S::Id, S::Item)>,
    /// Immutable segments, oldest first.
    segments: Vec<Arc<S::Segment>>,
    /// Logically-deleted ids.
    tombstones: HashSet<S::Id>,
    /// Ids currently in `buffer` (at most one copy each), so a re-add can
    /// replace its buffered copy without scanning the buffer.
    buffer_ids: HashSet<S::Id>,
    /// Per segment id, the ids whose copy there was superseded by a later add
    /// or delete. Persisted in the manifest so readers can skip stale copies.
    superseded: HashMap<u64, HashSet<S::Id>>,
    /// The segment holding each sealed id's live copy, used to mark that copy
    /// superseded on a re-add or delete. `None` when [`Store::item_ids`] is not
    /// implemented, which leaves sealed copies untracked.
    owners: Option<HashMap<S::Id, u64>>,
    /// Published snapshot for concurrent readers (rebuilt on each checkpoint).
    published: Arc<std::sync::RwLock<Arc<PubState<S>>>>,
    wal: RecordLogWriter,
    /// Current WAL generation; the live WAL is `segstore.wal.<epoch>` and the
    /// checkpoint records the epoch it covers.
    epoch: u64,
    /// Per-write WAL durability.
    sync: SyncPolicy,
    /// Buffer size that triggers a flush into a new segment.
    flush_threshold: usize,
    /// Size-tiered compaction tuning.
    tiering: TierConfig,
    /// Whether `add` auto-runs `compact_tiers` when a bucket is eligible.
    auto_compact: bool,
    /// The persisted id of each in-memory segment, parallel to `segments` and kept
    /// in lockstep through every segment mutation. The id names the segment's
    /// `segstore.seg.<id>` file.
    segment_ids: Vec<u64>,
    /// Monotonic source of new segment ids, persisted in the manifest so an id is
    /// never reused after its `seg.<id>` file is GC'd.
    next_seg_id: u64,
    /// Ids whose `segstore.seg.<id>` file is durably on disk, so a checkpoint can
    /// skip rewriting an unchanged segment.
    persisted_ids: HashSet<u64>,
    /// Set when a manifest write fails. The new manifest may already be visible,
    /// and reopen would then GC the current WAL generation, so later writes are
    /// refused rather than acknowledged into a log that recovery deletes.
    poisoned: bool,
    /// Exclusive lock on `segstore.lock`, held until drop. `None` for backends
    /// without a filesystem path, which cannot be shared across processes.
    _lock: Option<std::fs::File>,
}

impl<S: Store> SegmentedStore<S> {
    /// Open (or create) a store backed by `dir`, recovering any prior state from
    /// the checkpoint plus the write-ahead log.
    ///
    /// `flush_threshold` is the buffered-add count that triggers a new segment.
    pub fn open(
        dir: Arc<dyn Directory>,
        store: S,
        flush_threshold: usize,
    ) -> PersistenceResult<Self> {
        Self::open_with_options(dir, store, Options::new(flush_threshold))
    }

    /// Like [`Self::open`], but with full [`Options`] (per-write durability,
    /// size-tiered compaction tuning, auto-compaction).
    ///
    /// [`SyncPolicy::Fsync`] requires a filesystem-backed `Directory`; opening
    /// with it on a backend that lacks `file_path()` (e.g. an in-memory
    /// directory) returns an error rather than silently degrading to a flush.
    pub fn open_with_options(
        dir: Arc<dyn Directory>,
        store: S,
        opts: Options,
    ) -> PersistenceResult<Self> {
        let Options {
            flush_threshold,
            sync,
            tiering,
            auto_compact,
        } = opts;
        if sync == SyncPolicy::Fsync && dir.file_path(MANIFEST_PATH).is_none() {
            return Err(PersistenceError::InvalidConfig(
                "SyncPolicy::Fsync requires a filesystem-backed Directory".into(),
            ));
        }
        reject_legacy_formats(&*dir)?;
        // A second writer would checkpoint and GC this writer's WAL epoch,
        // silently dropping acknowledged writes, so take the lock before
        // reading any state.
        let lock = acquire_store_lock(&*dir)?;

        // Load the manifest if one exists. It records the WAL epoch it covers (in
        // the CheckpointFile header) and names the current segment files; recovery
        // loads each segment file, then replays only that epoch's WAL.
        let mut segments: Vec<Arc<S::Segment>> = Vec::new();
        let mut segment_ids: Vec<u64> = Vec::new();
        let mut tombstones: HashSet<S::Id> = HashSet::new();
        let mut superseded: HashMap<u64, HashSet<S::Id>> = HashMap::new();
        let mut epoch = 0u64;
        let mut next_seg_id = 0u64;
        if let Some(manifest) = read_manifest::<S::Id>(&dir)? {
            let ckpt = CheckpointFile::new(dir.clone());
            epoch = manifest.epoch;
            next_seg_id = manifest.next_seg_id;
            tombstones = manifest.tombstones;
            superseded = manifest.superseded;
            for id in manifest.segment_ids {
                let (_, seg): (u64, S::Segment) = ckpt.read_postcard(&seg_path(id))?;
                segments.push(Arc::new(seg));
                segment_ids.push(id);
            }
        }
        // Reader visibility is checkpoint-only, so retain the manifest state before
        // WAL replay reconstructs the writer's newer, uncommitted state.
        let published_segments = segments.clone();
        let published_segment_ids = segment_ids.clone();
        let published_tombstones = tombstones.clone();
        let persisted_ids: HashSet<u64> = segment_ids.iter().copied().collect();
        let durable = dir.file_path(MANIFEST_PATH).is_some();

        // Rebuild which segment holds each id's live copy. A store written before
        // superseded copies were tracked can hold several live copies of one id;
        // keep the copy in the newest segment and mark the rest superseded.
        let mut owners: Option<HashMap<S::Id, u64>> = Some(HashMap::new());
        for (seg, &seg_id) in segments.iter().zip(&segment_ids) {
            let (Some(map), Some(ids)) = (owners.as_mut(), store.item_ids(seg)) else {
                owners = None;
                break;
            };
            for id in ids {
                if !copy_is_live(&tombstones, &superseded, seg_id, &id) {
                    continue;
                }
                if let Some(older) = map.insert(id.clone(), seg_id) {
                    if older == seg_id {
                        return Err(PersistenceError::Format(format!(
                            "duplicate live id in the same segment {seg_id}; automatic recovery is unsafe; restore a known-good generation or rebuild from validated latest-per-id records"
                        )));
                    }
                    superseded.entry(older).or_default().insert(id);
                }
            }
        }

        // Legacy checkpoint ownership is now reconstructed. Publish that state,
        // before WAL replay can supersede copies with uncheckpointed replacements.
        let published_superseded = superseded.clone();

        // Read the current epoch's WAL in full. It holds exactly the ops since
        // the checkpoint, so every record is applied (no skip offset).
        let live_wal = wal_path(epoch);
        let mut ops: Vec<Op<S::Id, S::Item>> = Vec::new();
        if dir.exists(&live_wal) {
            let reader = RecordLogReader::new(dir.clone(), live_wal.clone());
            ops = reader.read_all_postcard(RecordLogReadMode::BestEffort)?;
        }

        // Best-effort GC of crash leftovers: stale WAL generations (any
        // `segstore.wal.<k>` with k != epoch is superseded by the manifest) and
        // orphan segment files (any `segstore.seg.<k>` the manifest does not name,
        // left by a crash between a segment write and the manifest write), and
        // `segstore.seg.<k>.tmp` files left by a crash inside a segment's atomic
        // write. Segment ids are never reused, so nothing else would replace them;
        // the writer lock is held, so no segment write is in flight.
        if let Ok(names) = dir.list_dir("") {
            let mut garbage = Vec::new();
            for name in names {
                if let Some(k) = name
                    .strip_prefix(WAL_PREFIX)
                    .and_then(|s| s.parse::<u64>().ok())
                {
                    if k != epoch {
                        garbage.push(name);
                    }
                } else if name
                    .strip_prefix(SEG_PREFIX)
                    .and_then(|s| s.strip_suffix(".tmp"))
                    .is_some_and(|s| s.parse::<u64>().is_ok())
                {
                    garbage.push(name);
                } else if let Some(k) = name
                    .strip_prefix(SEG_PREFIX)
                    .and_then(|s| s.parse::<u64>().ok())
                {
                    if !persisted_ids.contains(&k) {
                        garbage.push(name);
                    }
                } else if let Some(k) = idx_seg_id(&name) {
                    // Consumer index sidecar whose segment is gone: orphan, GC it.
                    if !persisted_ids.contains(&k) {
                        garbage.push(name);
                    }
                }
            }
            delete_files_best_effort(&*dir, garbage, durable);
        }

        let wal = RecordLogWriter::new(dir.clone(), live_wal);
        let published = Arc::new(std::sync::RwLock::new(Arc::new(PubState {
            segments: Arc::new(published_segments),
            segment_ids: Arc::new(published_segment_ids),
            tombstones: Arc::new(published_tombstones),
            superseded: Arc::new(published_superseded),
        })));
        let mut s = Self {
            store,
            dir,
            buffer: Vec::new(),
            segments,
            segment_ids,
            tombstones,
            buffer_ids: HashSet::new(),
            superseded,
            owners,
            wal,
            epoch,
            next_seg_id,
            persisted_ids,
            sync,
            flush_threshold,
            tiering,
            auto_compact,
            published,
            poisoned: false,
            _lock: lock,
        };
        // Replay through the same apply and seal steps as live writes, so a long
        // WAL epoch reconstructs the same segment boundaries (not one oversized
        // buffer) and the same superseded copies.
        for op in ops {
            s.apply(op);
            if s.buffer.len() >= s.flush_threshold {
                s.flush_buffer();
            }
        }
        Ok(s)
    }

    /// A cloneable handle for concurrent snapshot reads while this writer mutates.
    /// Clone it across threads; each [`Reader::view`] is a consistent snapshot.
    pub fn reader(&self) -> Reader<S> {
        Reader {
            published: self.published.clone(),
            dir: self.dir.clone(),
        }
    }

    /// Rebuild the published snapshot from the current segments + tombstones. Called
    /// only at the checkpoint (commit point). Segments are held as `Arc`, so this
    /// shares them by refcount (no data clone) and an *unchanged* segment keeps its
    /// `Arc` identity across checkpoints -- which lets a consumer cache per-segment
    /// state (a built index) keyed by that identity and rebuild only new segments.
    fn republish(&self) {
        let state = Arc::new(PubState {
            segments: Arc::new(self.segments.clone()),
            segment_ids: Arc::new(self.segment_ids.clone()),
            tombstones: Arc::new(self.tombstones.clone()),
            superseded: Arc::new(self.superseded.clone()),
        });
        *self.published.write().unwrap() = state;
    }

    /// Add (or re-add) an item. Durably logged before it becomes visible.
    ///
    /// A re-add replaces the id's previous value (last write wins), including a
    /// value deleted earlier. The buffered copy is replaced in place. A copy
    /// already sealed in a segment stays in that segment's payload until a merge
    /// drops it, but is marked superseded: [`Self::is_live_in`],
    /// [`View::is_live_in`], and [`SegmentCatalog::is_live_in`] report it dead,
    /// so a consumer that filters each segment with them sees only the newest
    /// copy. Tracking sealed copies needs [`Store::item_ids`] (implemented by
    /// [`DefaultStore`]); without it only the buffered copy is replaced, and a
    /// sealed copy stays live next to the new one.
    pub fn add(&mut self, id: S::Id, item: S::Item) -> PersistenceResult<()> {
        self.check_poisoned()?;
        self.wal
            .append_postcard(&Op::Add(id.clone(), item.clone()))?;
        self.sync_wal()?;
        self.apply(Op::Add(id, item));
        if self.buffer.len() >= self.flush_threshold {
            self.flush_buffer();
            if self.auto_compact && self.has_eligible_tier() {
                self.compact_tiers()?;
            }
        }
        Ok(())
    }

    /// Add (or re-add) many items, syncing the WAL once for the whole batch
    /// instead of per item. This is the bulk-ingest path (the build phase of an
    /// index, e.g. lexir/sporse loading a corpus): per-item flush is the dominant
    /// cost there, and one sync per batch is several times faster on a real disk.
    ///
    /// The durability boundary is the batch's final sync, so a crash mid-batch may
    /// leave a *prefix* of the batch durable (each item is an independently
    /// CRC-checked WAL record); recovery yields a consistent prefix, never a
    /// half-written item. Auto-compaction (if enabled) still runs when a segment
    /// seals during the batch.
    pub fn extend(
        &mut self,
        items: impl IntoIterator<Item = (S::Id, S::Item)>,
    ) -> PersistenceResult<()> {
        self.check_poisoned()?;
        let mut any = false;
        for (id, item) in items {
            self.wal
                .append_postcard(&Op::Add(id.clone(), item.clone()))?;
            self.apply(Op::Add(id, item));
            any = true;
            if self.buffer.len() >= self.flush_threshold {
                self.flush_buffer();
                if self.auto_compact && self.has_eligible_tier() {
                    self.sync_wal()?; // make the sealed batch durable before a merge rewrites it
                    self.compact_tiers()?;
                }
            }
        }
        if any {
            self.sync_wal()?;
        }
        Ok(())
    }

    /// Tombstone an item. Durably logged before it takes effect.
    pub fn delete(&mut self, id: S::Id) -> PersistenceResult<()> {
        self.check_poisoned()?;
        self.wal
            .append_postcard::<Op<S::Id, S::Item>>(&Op::Delete(id.clone()))?;
        self.sync_wal()?;
        self.apply(Op::Delete(id));
        Ok(())
    }

    /// Apply one operation to the in-memory state. Shared by live writes and WAL
    /// replay so the two paths cannot diverge.
    fn apply(&mut self, op: Op<S::Id, S::Item>) {
        match op {
            Op::Add(id, item) => {
                // A re-add revives a previously-deleted id and replaces any older
                // copy, buffered or sealed.
                self.tombstones.remove(&id);
                if self.buffer_ids.contains(&id) {
                    self.buffer.retain(|(bid, _)| bid != &id);
                } else {
                    self.buffer_ids.insert(id.clone());
                }
                self.supersede_sealed_copy(&id);
                self.buffer.push((id, item));
            }
            Op::Delete(id) => {
                if self.buffer_ids.remove(&id) {
                    self.buffer.retain(|(bid, _)| bid != &id);
                }
                // Also mark the sealed copy, so a later re-add cannot revive it.
                self.supersede_sealed_copy(&id);
                self.tombstones.insert(id);
            }
        }
    }

    /// Mark `id`'s live sealed copy, if any, as superseded.
    fn supersede_sealed_copy(&mut self, id: &S::Id) {
        if let Some(seg) = self.owners.as_mut().and_then(|o| o.remove(id)) {
            self.superseded.entry(seg).or_default().insert(id.clone());
        }
    }

    fn check_poisoned(&self) -> PersistenceResult<()> {
        if self.poisoned {
            return Err(PersistenceError::InvalidState(
                "store is poisoned after a failed manifest write; reopen to recover".into(),
            ));
        }
        Ok(())
    }

    /// Make the just-appended WAL record durable per the [`SyncPolicy`].
    fn sync_wal(&mut self) -> PersistenceResult<()> {
        match self.sync {
            SyncPolicy::Flush => self.wal.flush(),
            SyncPolicy::Fsync => self.wal.flush_and_sync(),
        }
    }

    /// Drain the buffer into a fresh immutable segment (no-op when empty).
    fn flush_buffer(&mut self) {
        if self.buffer.is_empty() {
            return;
        }
        let seg = self.store.build_segment(&self.buffer);
        let id = self.alloc_id();
        // `open` probes item_ids on the loaded segments; with none loaded, probe
        // the first one sealed, before any sealed copy is tracked.
        if self.segments.is_empty() && self.store.item_ids(&seg).is_none() {
            self.owners = None;
        }
        if let Some(owners) = self.owners.as_mut() {
            for (item_id, _) in &self.buffer {
                owners.insert(item_id.clone(), id);
            }
        }
        self.segments.push(Arc::new(seg));
        self.segment_ids.push(id);
        self.buffer.clear();
        self.buffer_ids.clear();
    }

    /// Allocate a fresh, never-reused segment id.
    fn alloc_id(&mut self) -> u64 {
        let id = self.next_seg_id;
        self.next_seg_id += 1;
        id
    }

    /// Delete every `segstore.seg.<k>` file whose id is not in `keep`, and forget
    /// those ids from `persisted_ids`. Called only after a manifest is durable, so
    /// a crash mid-GC just leaves orphans that the next open re-GCs.
    fn gc_orphan_segments(&mut self, keep: &HashSet<u64>, durable: bool, mut garbage: Vec<String>) {
        self.persisted_ids.retain(|id| keep.contains(id));
        if let Ok(names) = self.dir.list_dir("") {
            for name in names {
                if let Some(k) = name
                    .strip_prefix(SEG_PREFIX)
                    .and_then(|s| s.parse::<u64>().ok())
                {
                    if !keep.contains(&k) {
                        garbage.push(name);
                    }
                } else if let Some(k) = idx_seg_id(&name) {
                    // A consumer's index sidecar for a compacted-away segment.
                    if !keep.contains(&k) {
                        garbage.push(name);
                    }
                }
            }
        }
        delete_files_best_effort(&*self.dir, garbage, durable);
    }

    /// Merge ALL segments into one, dropping tombstoned ids and purging the
    /// tombstone set, then checkpoint. This is the full compaction; it is the only
    /// path that touches frozen (over-cap) segments and the only one that purges
    /// tombstones (a partial tier merge cannot, since a tombstoned id may live in a
    /// segment it did not merge).
    pub fn compact(&mut self) -> PersistenceResult<CompactionStats> {
        self.flush_buffer();
        let before = self.segments.len();
        let mut stats = CompactionStats {
            segments_before: before,
            ..Default::default()
        };
        // Nothing to do for 0/1 segments with no dead copies to purge.
        let has_dead = !self.tombstones.is_empty() || !self.superseded.is_empty();
        if before > 1 || (before == 1 && has_dead) {
            // merge_group drops a fully-dead merge result rather than keep an
            // empty segment.
            stats.items_merged = self.merge_group((0..before).collect())?;
            stats.merges = 1;
        }
        // After a full compaction no segment references a tombstoned id, so the set
        // is purged even if there was nothing to merge (stale tombstones for ids that
        // were only ever buffered).
        self.tombstones.clear();
        self.superseded.clear();
        self.checkpoint()?;
        stats.segments_after = self.segments.len();
        Ok(stats)
    }

    /// Run all currently-eligible size-tier merges (size-tiered compaction) per the
    /// [`TierConfig`], persisting the result if anything merged. Segments are grouped
    /// into size buckets (a Cassandra-style `bucket_low .. bucket_high` band around a
    /// running average, with a [`Options::flush_threshold`] floor); a bucket with at
    /// least `min_merge` segments is merged (smallest first, up to `max_merge` at once,
    /// never exceeding `max_merged_len` items), dropping tombstoned ids from the merged
    /// output. Segments above `max_merged_len / 2` are frozen out, so the largest segment
    /// is never rewritten here. The global tombstone set is NOT purged (only [`Self::compact`]
    /// can); a tombstoned id surviving in a frozen segment stays filtered by [`Self::is_live`].
    ///
    /// Scheduling is the consumer's: call this when convenient (e.g. on a background
    /// thread) so merge latency stays off the ingest path, or set [`Options::auto_compact`].
    pub fn compact_tiers(&mut self) -> PersistenceResult<CompactionStats> {
        self.flush_buffer();
        let mut stats = CompactionStats {
            segments_before: self.segments.len(),
            ..Default::default()
        };
        while let Some(group) = self.next_merge_group() {
            stats.items_merged += self.merge_group(group)?;
            stats.merges += 1;
        }
        if stats.merges > 0 {
            self.checkpoint()?;
        }
        stats.segments_after = self.segments.len();
        Ok(stats)
    }

    /// Consolidate on demand: merge segments until at most `max_segments` remain,
    /// ignoring the size band, the per-bucket minimum, and the [`TierConfig`] cap
    /// (this is explicit user intent, e.g. before a read-heavy phase, so it may
    /// produce a segment larger than `max_merged_len`). Merging to a single segment
    /// (`max_segments <= 1`) also purges the tombstone set, exactly like
    /// [`Self::compact`]; merging to more keeps the set (an id may live in a segment
    /// the call did not merge). Smallest segments are merged first to keep the work
    /// down. A no-op when already at or below `max_segments`.
    pub fn force_merge_to(&mut self, max_segments: usize) -> PersistenceResult<CompactionStats> {
        if max_segments <= 1 {
            return self.compact();
        }
        self.flush_buffer();
        let mut stats = CompactionStats {
            segments_before: self.segments.len(),
            ..Default::default()
        };
        while self.segments.len() > max_segments {
            let mut idx: Vec<usize> = (0..self.segments.len()).collect();
            idx.sort_by_key(|&i| self.store.segment_len(&self.segments[i]));
            // Merging k segments drops the count by k-1; to remove `over` segments we
            // merge `over + 1`, bounded by max_merge and what's available.
            let over = self.segments.len() - max_segments;
            let k = (over + 1)
                .min(self.tiering.max_merge.max(2))
                .min(self.segments.len());
            let group: Vec<usize> = idx.into_iter().take(k).collect();
            stats.items_merged += self.merge_group(group)?;
            stats.merges += 1;
        }
        if stats.merges > 0 {
            self.checkpoint()?;
        }
        stats.segments_after = self.segments.len();
        Ok(stats)
    }

    /// Merge the segments at `indices` into one (dropping tombstoned ids), replacing
    /// them in place with the single result. Returns the merged item count.
    ///
    /// The merged segment file is written before any in-memory state changes, so
    /// a refused write (an output over the per-blob byte cap, or an IO error)
    /// leaves the store exactly as it was. Otherwise the unpersistable result
    /// would sit in the segment list and fail every later checkpoint. Until a
    /// manifest names it, the file is an orphan that the next open or checkpoint
    /// garbage-collects.
    fn merge_group(&mut self, indices: Vec<usize>) -> PersistenceResult<usize> {
        let group: Vec<u64> = indices.iter().map(|&i| self.segment_ids[i]).collect();
        // Borrow the Arc-held segments rather than cloning their payloads to
        // satisfy merge_segments (&[&Segment]); the merge reads them in place.
        let segs: Vec<&S::Segment> = indices.iter().map(|&i| &*self.segments[i]).collect();
        let merged = {
            let tombstones = &self.tombstones;
            let superseded = &self.superseded;
            if group.iter().any(|g| superseded.contains_key(g)) {
                // One input can hold a superseded copy of an id whose live copy is
                // in another input, and an id-only predicate cannot tell the two
                // apart. Filter each input with its own predicate, then combine.
                let filtered: Vec<S::Segment> = segs
                    .iter()
                    .zip(&group)
                    .map(|(&seg, &g)| {
                        self.store.merge_segments(&[seg], &|id| {
                            copy_is_live(tombstones, superseded, g, id)
                        })
                    })
                    .collect();
                let refs: Vec<&S::Segment> = filtered.iter().collect();
                self.store.merge_segments(&refs, &|_| true)
            } else {
                self.store
                    .merge_segments(&segs, &|id| !tombstones.contains(id))
            }
        };
        let n = self.store.segment_len(&merged);
        let merged_id = if n > 0 {
            let id = self.alloc_id();
            self.persist_segment(id, &merged)?;
            Some(id)
        } else {
            None
        };
        // The merge dropped every superseded copy in the group.
        for g in &group {
            self.superseded.remove(g);
        }
        // Rebuild the segment list in one O(n) pass (filtering the merged indices)
        // instead of k O(n) `Vec::remove` calls, then append the result unless it is
        // empty (a fully-tombstoned group leaves no segment behind).
        let mut merged_idx = indices;
        merged_idx.sort_unstable();
        let old = std::mem::take(&mut self.segments);
        self.segments = old
            .into_iter()
            .enumerate()
            .filter(|(i, _)| merged_idx.binary_search(i).is_err())
            .map(|(_, seg)| seg)
            .collect();
        // Keep segment_ids aligned with segments: drop the same merged indices.
        let old_ids = std::mem::take(&mut self.segment_ids);
        self.segment_ids = old_ids
            .into_iter()
            .enumerate()
            .filter(|(i, _)| merged_idx.binary_search(i).is_err())
            .map(|(_, id)| id)
            .collect();
        if let Some(id) = merged_id {
            if self.owners.is_some() {
                // Every id in the merge output had its live copy in the group.
                match self.store.item_ids(&merged) {
                    Some(ids) => {
                        let owners = self.owners.get_or_insert_with(HashMap::new);
                        for item_id in ids {
                            owners.insert(item_id, id);
                        }
                    }
                    None => self.owners = None,
                }
            }
            self.segments.push(Arc::new(merged));
            self.segment_ids.push(id);
        }
        Ok(n)
    }

    /// Write segment `id` to its `segstore.seg.<id>` file (durably on a filesystem
    /// backend) and record it as persisted, so a checkpoint does not rewrite it.
    fn persist_segment(&mut self, id: u64, seg: &S::Segment) -> PersistenceResult<()> {
        let durable = self.dir.file_path(MANIFEST_PATH).is_some();
        let ckpt = CheckpointFile::new(self.dir.clone());
        let seg_write = if durable {
            ckpt.write_postcard_durable(&seg_path(id), 0, seg)
        } else {
            ckpt.write_postcard(&seg_path(id), 0, seg)
        };
        seg_write.map_err(|e| size_cap_context(e, &format!("segment {id}")))?;
        self.persisted_ids.insert(id);
        Ok(())
    }

    /// Whether at least one size bucket is eligible to merge right now.
    pub fn has_eligible_tier(&self) -> bool {
        self.next_merge_group().is_some()
    }

    /// Choose the next group of segment indices to merge (size-tiered selection), or
    /// `None` if no bucket is eligible. Smallest-average bucket first.
    fn next_merge_group(&self) -> Option<Vec<usize>> {
        let cfg = self.tiering;
        // A group of 1 would merge a segment into itself (no progress), so the loop
        // in `compact_tiers` would not terminate. 2 is the floor regardless of config.
        let min_merge = cfg.min_merge.max(2);
        let floor = self.flush_threshold.max(1);
        let cap_half = cfg.max_merged_len / 2;
        // (raw size, floored size, index) for segments not frozen by the cap.
        let mut elig: Vec<(usize, f64, usize)> = self
            .segments
            .iter()
            .enumerate()
            .map(|(i, s)| {
                let raw = self.store.segment_len(s);
                (raw, raw.max(floor) as f64, i)
            })
            .filter(|&(raw, _, _)| raw <= cap_half)
            .collect();
        if elig.len() < min_merge {
            return None;
        }
        elig.sort_by(|a, b| a.1.total_cmp(&b.1));

        // Cassandra-style bucketing: join the first bucket whose running average is
        // within the size band, else open a new bucket.
        let mut buckets: Vec<(f64, Vec<(usize, usize)>)> = Vec::new();
        'item: for &(raw, sz, idx) in &elig {
            for b in buckets.iter_mut() {
                if sz > b.0 * cfg.bucket_low && sz < b.0 * cfg.bucket_high {
                    let n = b.1.len() as f64;
                    b.0 = (b.0 * n + sz) / (n + 1.0);
                    b.1.push((raw, idx));
                    continue 'item;
                }
            }
            buckets.push((sz, vec![(raw, idx)]));
        }
        buckets.sort_by(|a, b| a.0.total_cmp(&b.0));

        for (_, mut members) in buckets {
            if members.len() < min_merge {
                continue;
            }
            members.sort_by_key(|&(raw, _)| raw); // smallest first
            let mut chosen = Vec::new();
            let mut total = 0usize;
            for &(raw, idx) in &members {
                if chosen.len() >= cfg.max_merge {
                    break;
                }
                if !chosen.is_empty() && total + raw > cfg.max_merged_len {
                    break;
                }
                total += raw;
                chosen.push(idx);
            }
            if chosen.len() >= min_merge {
                return Some(chosen);
            }
        }
        None
    }

    /// Total items physically stored across segments and the buffer. This counts
    /// tombstoned-but-not-yet-purged items (segstore cannot see inside an opaque
    /// segment to subtract them); pair with [`Self::tombstone_count`] to gauge
    /// space amplification.
    pub fn stored_len(&self) -> usize {
        let in_segments: usize = self
            .segments
            .iter()
            .map(|s| self.store.segment_len(s))
            .sum();
        in_segments + self.buffer.len()
    }

    /// The current WAL generation.
    pub fn epoch(&self) -> u64 {
        self.epoch
    }

    /// Space amplification = stored items / live items, or `None` if any segment's
    /// [`Store::live_len`] returns `None` (the default). A value near 1.0 means
    /// little dead data; a higher value means tombstoned/obsolete items are
    /// accumulating, reclaimable with [`Self::reclaim_tombstones`] or [`Self::compact`].
    pub fn space_amplification(&self) -> Option<f64> {
        let mut stored = 0usize;
        let mut live = 0usize;
        for (seg, &seg_id) in self.segments.iter().zip(&self.segment_ids) {
            let l = self
                .store
                .live_len(seg, &|id| self.is_live_in(seg_id, id))?;
            stored += self.store.segment_len(seg);
            live += l;
        }
        // Buffer items are always live (a delete or re-add removes the buffered copy).
        stored += self.buffer.len();
        live += self.buffer.len();
        if live == 0 {
            return Some(if stored == 0 { 1.0 } else { f64::INFINITY });
        }
        Some(stored as f64 / live as f64)
    }

    /// Merge segments whose live ratio (`live_len / segment_len`) is below
    /// `min_live_ratio`, reclaiming their dead (tombstoned) entries into one fresh
    /// segment. The cheap alternative to [`Self::compact`] when only a few segments
    /// are tombstone-heavy. Requires [`Store::live_len`]; a no-op if it returns
    /// `None` or nothing qualifies. Keeps the tombstone set (a reclaimed id may
    /// still live in a segment this did not touch); only `compact` purges it.
    pub fn reclaim_tombstones(
        &mut self,
        min_live_ratio: f64,
    ) -> PersistenceResult<CompactionStats> {
        self.flush_buffer();
        let mut stats = CompactionStats {
            segments_before: self.segments.len(),
            ..Default::default()
        };
        let mut targets = Vec::new();
        for (i, (seg, &seg_id)) in self.segments.iter().zip(&self.segment_ids).enumerate() {
            let total = self.store.segment_len(seg);
            if total == 0 {
                continue;
            }
            let live = match self.store.live_len(seg, &|id| self.is_live_in(seg_id, id)) {
                Some(l) => l,
                None => {
                    // Consumer can't report live counts; reclaim is unavailable.
                    stats.segments_after = self.segments.len();
                    return Ok(stats);
                }
            };
            if (live as f64) < min_live_ratio * total as f64 {
                targets.push(i);
            }
        }
        if targets.is_empty() {
            stats.segments_after = self.segments.len();
            return Ok(stats);
        }
        // Even a single tombstone-heavy segment is worth rewriting to drop dead data.
        stats.items_merged += self.merge_group(targets)?;
        stats.merges = 1;
        self.checkpoint()?;
        stats.segments_after = self.segments.len();
        Ok(stats)
    }

    /// Per-segment item counts, oldest segment first. The size distribution the
    /// consumer needs to watch the crossover signal (segment count + per-query
    /// fan-out vs corpus size) that says a multi-segment store is outgrowing the
    /// search-all-segments model.
    pub fn segment_sizes(&self) -> Vec<usize> {
        self.segments
            .iter()
            .map(|s| self.store.segment_len(s))
            .collect()
    }

    /// Snapshot the current segments + tombstones durably, then rotate the WAL:
    /// start a fresh epoch and delete the old log so it cannot grow unbounded.
    ///
    /// The checkpoint is the commit point. It records the *new* epoch, so once it
    /// is durable, recovery replays only the new (initially empty) WAL; the old
    /// WAL is superseded. A crash after the checkpoint but before the old WAL is
    /// deleted is safe: recovery never reads the old epoch, and the stale file is
    /// GC'd on the next open.
    ///
    /// If the manifest write fails, the new manifest may already be visible, so
    /// the store is poisoned: later writes and checkpoints return `InvalidState`.
    /// Reopen the store to recover.
    pub fn checkpoint(&mut self) -> PersistenceResult<()> {
        self.check_poisoned()?;
        self.flush_buffer();
        debug_assert_eq!(self.segments.len(), self.segment_ids.len());
        let new_epoch = self.epoch + 1;
        // On a filesystem backend, pass a power-loss barrier (fsync); in-memory
        // backends have no barrier and fall back to the atomic-only write.
        let durable = self.dir.file_path(MANIFEST_PATH).is_some();
        let ckpt = CheckpointFile::new(self.dir.clone());

        // 1. Persist every not-yet-written segment to its own file, durably, BEFORE
        //    the manifest names it. A crash here leaves an orphan seg file the
        //    manifest never references (GC'd on open); the old manifest still points
        //    at the old set, so nothing committed is lost.
        let to_write: Vec<(usize, u64)> = self
            .segment_ids
            .iter()
            .enumerate()
            .filter(|(_, id)| !self.persisted_ids.contains(id))
            .map(|(i, &id)| (i, id))
            .collect();
        for (idx, id) in to_write {
            let seg = Arc::clone(&self.segments[idx]);
            self.persist_segment(id, &seg)?;
        }

        // 2. Write the manifest: the commit point. It records the new epoch and
        //    names the current segment files, so once it is durable, recovery
        //    replays only the new (initially empty) WAL; the old WAL is superseded.
        let keep: HashSet<u64> = self.segment_ids.iter().copied().collect();
        self.superseded.retain(|seg, _| keep.contains(seg));
        let tomb_refs: Vec<&S::Id> = self.tombstones.iter().collect();
        let mut superseded_refs: Vec<(u64, Vec<&S::Id>)> = self
            .superseded
            .iter()
            .map(|(&seg, ids)| (seg, ids.iter().collect()))
            .collect();
        superseded_refs.sort_unstable_by_key(|&(seg, _)| seg);
        let manifest = ManifestRef {
            next_seg_id: self.next_seg_id,
            segment_ids: &self.segment_ids,
            tombstones: &tomb_refs,
            ext: ManifestExtRef {
                version: MANIFEST_EXT_VERSION,
                superseded: &superseded_refs,
            },
        };
        let manifest_write = if durable {
            ckpt.write_postcard_durable(MANIFEST_PATH, new_epoch, &manifest)
        } else {
            ckpt.write_postcard(MANIFEST_PATH, new_epoch, &manifest)
        };
        if let Err(e) = manifest_write {
            self.poisoned = true;
            return Err(size_cap_context(e, "manifest (segment ids + tombstones)"));
        }

        // 3. Past the commit point: start the new WAL generation and drop the old.
        let old_epoch = self.epoch;
        self.wal = RecordLogWriter::new(self.dir.clone(), wal_path(new_epoch));
        self.epoch = new_epoch;

        // 4. GC the segment files the new manifest no longer names (a merge's
        //    inputs). Safe only now that the manifest is durable.
        self.gc_orphan_segments(&keep, durable, vec![wal_path(old_epoch)]);

        // 5. Publish the post-checkpoint segment set to readers (the commit point).
        self.republish();
        Ok(())
    }

    /// The immutable segments, oldest first (each derefs to `S::Segment`). Query
    /// these plus [`Self::buffer`], filtering segment copies with [`Self::is_live_in`]. Segments are
    /// `Arc`-shared: an unchanged segment keeps its identity across mutations, so a
    /// consumer can cache per-segment state keyed by `Arc::as_ptr` and rebuild only
    /// new segments. For a consistent view while another thread mutates, use a
    /// [`Reader`] / [`View`] instead. For a cache key that *also* survives a restart,
    /// use [`Self::segment_ids`].
    pub fn segments(&self) -> &[Arc<S::Segment>] {
        &self.segments
    }

    /// The stable persistence id of each segment in [`Self::segments`], same order.
    /// Unlike the segment's `Arc` pointer (stable only within one process), this id
    /// names the segment's `segstore.seg.<id>` file and is stable across checkpoints
    /// *and* restarts, so a consumer can key a *persisted* per-segment built-index
    /// cache on it and reload across a process restart instead of rebuilding from the
    /// raw payload. An id is never reused after its segment is compacted away.
    pub fn segment_ids(&self) -> &[u64] {
        &self.segment_ids
    }

    /// The directory this store is backed by, so a consumer can persist a built
    /// per-segment index alongside the segments. Write the index into the reserved
    /// sidecar name from [`Self::index_name`], keyed by a stable [`Self::segment_ids`]
    /// id; segstore garbage-collects it when its segment is compacted away (on the
    /// same crash-safe schedule as the segment files). A missing or stale sidecar
    /// means "rebuild from the raw segment." This is the persist-the-built-index
    /// hook: recovery loads the sidecar instead of rebuilding every consumer index.
    pub fn dir(&self) -> &Arc<dyn Directory> {
        &self.dir
    }

    /// The reserved sidecar file name for a per-segment index of the given `kind`
    /// (e.g. `"hnsw"`), keyed by a stable [`Self::segment_ids`] id. `kind` must be
    /// non-empty ASCII alphanumeric plus `_` or `-`. It is a short namespace tag,
    /// not a compatibility proof; put full algorithm/config/input fingerprints in
    /// the sidecar bytes and rebuild from the raw segment when they mismatch. Use
    /// with [`Self::dir`] to persist/load a built index that segstore GCs in
    /// lockstep with the segment. Reader/searcher code that only has a [`View`]
    /// can use the module-level [`try_index_name`] helper with [`View::segment_ids`].
    pub fn try_index_name(&self, id: u64, kind: &str) -> PersistenceResult<String> {
        try_index_name(id, kind)
    }

    /// Infallible convenience wrapper around [`Self::try_index_name`].
    ///
    /// Panics if `kind` violates the documented sidecar-kind grammar.
    pub fn index_name(&self, id: u64, kind: &str) -> String {
        self.try_index_name(id, kind)
            .unwrap_or_else(|e| panic!("invalid segstore index kind: {e}"))
    }

    /// Live adds not yet flushed into a segment.
    pub fn buffer(&self) -> &[(S::Id, S::Item)] {
        &self.buffer
    }

    /// Whether `id` is not tombstoned.
    ///
    /// This is per-id: when a re-added id has copies in several segments, it is
    /// true for all of them. Filter a segment's contents with
    /// [`Self::is_live_in`] instead. Every buffered item is live.
    pub fn is_live(&self, id: &S::Id) -> bool {
        !self.tombstones.contains(id)
    }

    /// Whether the copy of `id` in segment `segment_id` (an entry of
    /// [`Self::segment_ids`]) is live: `id` is not tombstoned and was not
    /// re-added after that segment sealed. At most one copy of an id passes
    /// this check (see [`Self::add`]).
    pub fn is_live_in(&self, segment_id: u64, id: &S::Id) -> bool {
        copy_is_live(&self.tombstones, &self.superseded, segment_id, id)
    }

    /// The id of the segment holding `id`'s live sealed copy, or `None` if `id`
    /// is buffered, deleted, absent, or the store does not implement
    /// [`Store::item_ids`].
    ///
    /// A re-add or delete of `id` changes that segment's live set, so a consumer
    /// that caches a per-segment index can call this first and drop just that
    /// segment's cache entry, without scanning segments for the id.
    pub fn live_segment_of(&self, id: &S::Id) -> Option<u64> {
        self.owners.as_ref()?.get(id).copied()
    }

    /// Canonical live-id set of one sealed segment: the segment's ids filtered
    /// by [`Self::is_live_in`], sorted and deduped.
    ///
    /// This is the fingerprint a sidecar cache keys on. Returns `None` if
    /// `segment_id` is not a current segment or the store's [`Store`]
    /// implementation does not list ids ([`Store::item_ids`]). Buffered adds are
    /// not part of any segment's live-id set.
    pub fn live_ids(&self, segment_id: u64) -> Option<crate::sidecar::LiveIds<S::Id>>
    where
        S::Id: Ord,
    {
        let position = self.segment_ids.iter().position(|&id| id == segment_id)?;
        let ids = self.store.item_ids(&self.segments[position])?;
        Some(crate::sidecar::LiveIds::new(
            ids.into_iter().filter(|id| self.is_live_in(segment_id, id)),
        ))
    }

    /// Number of immutable segments.
    pub fn segment_count(&self) -> usize {
        self.segments.len()
    }

    /// Number of tombstoned ids.
    pub fn tombstone_count(&self) -> usize {
        self.tombstones.len()
    }
}

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

    #[test]
    fn size_cap_context_makes_the_blob_error_actionable() {
        // The raw durability error is opaque about what overflowed and how to
        // fix it; the wrapper names the artifact and the levers.
        let raw = PersistenceError::Format(
            "checkpoint payload too large: 300000000 bytes (max 268435456)".into(),
        );
        let wrapped = size_cap_context(raw, "segment 7");
        let msg = wrapped.to_string();
        assert!(msg.contains("segment 7"), "names the artifact: {msg}");
        assert!(
            msg.contains("max_merged_len"),
            "names the item-count lever: {msg}"
        );
        assert!(
            msg.contains("checkpoint payload too large"),
            "preserves the original detail: {msg}"
        );
    }

    #[test]
    fn size_cap_context_passes_unrelated_errors_through() {
        let before = PersistenceError::InvalidState("something else".into()).to_string();
        let after = size_cap_context(
            PersistenceError::InvalidState("something else".into()),
            "segment 1",
        )
        .to_string();
        assert_eq!(after, before, "non-cap errors are unchanged");
    }

    #[test]
    fn catalog_payload_reader_rejects_truncated_length_claim() {
        use std::io::Read;

        let dir = MemoryDirectory::arc();
        let seg_id = {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 1).unwrap();
            s.add(1, "a".into()).unwrap();
            s.checkpoint().unwrap();
            s.segment_ids()[0]
        };

        let name = seg_path(seg_id);
        let mut file = dir.open_file(&name).unwrap();
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes).unwrap();
        // Checkpoint envelope layout: magic(4), version(4), last_applied_id(8),
        // payload_len(8), crc32(4), then payload bytes.
        let len_offset = 4 + 4 + 8;
        let claimed = 4_u64 * 1024 * 1024;
        bytes[len_offset..len_offset + 8].copy_from_slice(&claimed.to_le_bytes());
        dir.atomic_write(&name, &bytes).unwrap();

        let catalog = SegmentCatalog::<u32>::open(dir).unwrap();
        let err = catalog
            .read_segment_payload(seg_id)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("truncated") || err.to_lowercase().contains("eof"),
            "expected truncation error, got: {err}"
        );
    }

    struct Kv;
    impl Store for Kv {
        type Id = u32;
        type Item = String;
        type Segment = Vec<(u32, String)>;
        fn build_segment(&self, batch: &[(u32, String)]) -> Vec<(u32, String)> {
            batch.to_vec()
        }
        fn merge_segments(
            &self,
            segs: &[&Vec<(u32, String)>],
            live: &dyn Fn(&u32) -> bool,
        ) -> Vec<(u32, String)> {
            segs.iter()
                .flat_map(|s| s.iter())
                .filter(|(id, _)| live(id))
                .cloned()
                .collect()
        }
        fn segment_len(&self, seg: &Vec<(u32, String)>) -> usize {
            seg.len()
        }
        fn live_len(&self, seg: &Vec<(u32, String)>, live: &dyn Fn(&u32) -> bool) -> Option<usize> {
            Some(seg.iter().filter(|(id, _)| live(id)).count())
        }
        fn item_ids(&self, seg: &Vec<(u32, String)>) -> Option<Vec<u32>> {
            Some(seg.iter().map(|(id, _)| *id).collect())
        }
    }

    /// A store that does NOT implement `live_len` or `item_ids` (uses the
    /// default `None`).
    struct OpaqueKv;
    impl Store for OpaqueKv {
        type Id = u32;
        type Item = String;
        type Segment = Vec<(u32, String)>;
        fn build_segment(&self, batch: &[(u32, String)]) -> Vec<(u32, String)> {
            batch.to_vec()
        }
        fn merge_segments(
            &self,
            segs: &[&Vec<(u32, String)>],
            live: &dyn Fn(&u32) -> bool,
        ) -> Vec<(u32, String)> {
            segs.iter()
                .flat_map(|s| s.iter())
                .filter(|(id, _)| live(id))
                .cloned()
                .collect()
        }
        fn segment_len(&self, seg: &Vec<(u32, String)>) -> usize {
            seg.len()
        }
    }

    /// A `Directory` that fails its Nth mutating operation (and every one after),
    /// to test IO-error propagation and crash atomicity. Reads always succeed.
    struct FaultDir {
        inner: Arc<dyn Directory>,
        countdown: std::sync::atomic::AtomicUsize,
    }
    impl FaultDir {
        fn arc(inner: Arc<dyn Directory>, fail_after: usize) -> Arc<dyn Directory> {
            Arc::new(FaultDir {
                inner,
                countdown: std::sync::atomic::AtomicUsize::new(fail_after),
            })
        }
        fn gate(&self) -> PersistenceResult<()> {
            use std::sync::atomic::Ordering::Relaxed;
            let n = self.countdown.load(Relaxed);
            if n == 0 {
                return Err(PersistenceError::InvalidState("injected IO fault".into()));
            }
            self.countdown.store(n - 1, Relaxed);
            Ok(())
        }
    }
    impl Directory for FaultDir {
        fn create_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.gate()?;
            self.inner.create_file(p)
        }
        fn open_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Read + Send>> {
            self.inner.open_file(p)
        }
        fn exists(&self, p: &str) -> bool {
            self.inner.exists(p)
        }
        fn delete(&self, p: &str) -> PersistenceResult<()> {
            self.gate()?;
            self.inner.delete(p)
        }
        fn atomic_rename(&self, a: &str, b: &str) -> PersistenceResult<()> {
            self.gate()?;
            self.inner.atomic_rename(a, b)
        }
        fn create_dir_all(&self, p: &str) -> PersistenceResult<()> {
            self.inner.create_dir_all(p)
        }
        fn list_dir(&self, p: &str) -> PersistenceResult<Vec<String>> {
            self.inner.list_dir(p)
        }
        fn append_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.gate()?;
            self.inner.append_file(p)
        }
        fn atomic_write(&self, p: &str, d: &[u8]) -> PersistenceResult<()> {
            self.gate()?;
            self.inner.atomic_write(p, d)
        }
        fn file_path(&self, p: &str) -> Option<std::path::PathBuf> {
            self.inner.file_path(p)
        }
    }

    /// Collect the live `(id, item)` set across segments + buffer.
    fn live_set(s: &SegmentedStore<Kv>) -> Vec<(u32, String)> {
        let mut out: Vec<(u32, String)> = Vec::new();
        for (seg, &seg_id) in s.segments().iter().zip(s.segment_ids()) {
            for (id, it) in seg.iter() {
                if s.is_live_in(seg_id, id) {
                    out.push((*id, it.clone()));
                }
            }
        }
        for (id, it) in s.buffer() {
            if s.is_live(id) {
                out.push((*id, it.clone()));
            }
        }
        out.sort();
        out
    }

    #[test]
    fn default_store_implements_the_vec_segment_pattern() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, DefaultStore::<u32, String>::new(), 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap();
        assert_eq!(s.segment_count(), 1);
        assert_eq!(
            s.segments()[0].as_ref(),
            &vec![(1, "a".into()), (2, "b".into())]
        );

        s.delete(2).unwrap();
        assert_eq!(
            s.space_amplification(),
            Some(2.0),
            "DefaultStore exposes live_len for tombstone policy"
        );

        s.compact().unwrap();
        assert_eq!(s.tombstone_count(), 0);
        assert_eq!(s.segments()[0].as_ref(), &vec![(1, "a".into())]);
    }

    #[test]
    fn sidecar_envelope_round_trips_payload() {
        let magic = b"SIDETST1";
        let recipe = b"demo-v1";
        let payload = b"payload bytes";

        let bytes = SidecarEnvelope::encode(magic, 2, 7, recipe, payload).unwrap();
        let decoded = SidecarEnvelope::decode(magic, 2, 7, recipe, &bytes).unwrap();

        assert_eq!(decoded, payload);
    }

    #[test]
    fn sidecar_envelope_reports_payload_info_without_full_decode() {
        let magic = b"SIDETST1";
        let recipe = b"demo-v1";
        let payload = b"payload bytes";
        let bytes = SidecarEnvelope::encode(magic, 2, 7, recipe, payload).unwrap();
        let mut reader = &bytes[..];

        let info =
            SidecarEnvelope::payload_info(magic, 2, 7, recipe, &mut reader, bytes.len() as u64)
                .unwrap();

        let expected_offset = (SIDECAR_ENVELOPE_HEADER_BYTES + recipe.len()) as u64;
        assert_eq!(info.payload_offset(), expected_offset);
        assert_eq!(info.payload_len(), payload.len() as u64);
        assert_eq!(
            info.crc32(),
            u32::from_le_bytes(bytes[24..28].try_into().unwrap())
        );
        assert_eq!(&bytes[info.payload_offset() as usize..], payload);
    }

    #[test]
    fn sidecar_envelope_rejects_corrupt_payload_by_crc() {
        let magic = b"SIDETST1";
        let recipe = b"demo-v1";
        let mut bytes = SidecarEnvelope::encode(magic, 2, 7, recipe, b"payload").unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 0xff;

        let err = SidecarEnvelope::decode(magic, 2, 7, recipe, &bytes).unwrap_err();
        assert!(
            matches!(err, PersistenceError::CrcMismatch { .. }),
            "corrupt sidecar bytes should fail CRC, got: {err}"
        );
    }

    #[test]
    fn sidecar_envelope_distinguishes_stale_recipe_from_corruption() {
        let magic = b"SIDETST1";
        let bytes = SidecarEnvelope::encode(magic, 2, 7, b"demo-v1", b"payload").unwrap();

        let err = SidecarEnvelope::decode(magic, 2, 7, b"demo-v2", &bytes).unwrap_err();
        assert!(
            err.to_string().contains("recipe mismatch"),
            "valid but stale sidecars should be rebuildable mismatches, got: {err}"
        );
    }

    #[test]
    fn sidecar_envelope_payload_info_distinguishes_stale_recipe() {
        let magic = b"SIDETST1";
        let bytes = SidecarEnvelope::encode(magic, 2, 7, b"demo-v1", b"payload").unwrap();
        let mut reader = &bytes[..];

        let err =
            SidecarEnvelope::payload_info(magic, 2, 7, b"demo-v2", &mut reader, bytes.len() as u64)
                .unwrap_err();
        assert!(
            err.to_string().contains("recipe mismatch"),
            "valid but stale sidecars should be rebuildable mismatches, got: {err}"
        );
    }

    #[test]
    fn sidecar_envelope_payload_info_rejects_corrupt_recipe_length() {
        let magic = b"SIDETST1";
        let mut bytes = SidecarEnvelope::encode(magic, 2, 7, b"demo-v1", b"payload").unwrap();
        bytes[20..24].copy_from_slice(&u32::MAX.to_le_bytes());
        let mut reader = &bytes[..];

        let err =
            SidecarEnvelope::payload_info(magic, 2, 7, b"demo-v1", &mut reader, bytes.len() as u64)
                .unwrap_err();
        assert!(
            err.to_string().contains("recipe is truncated"),
            "corrupt recipe lengths should fail before reading payload bytes, got: {err}"
        );
    }

    #[test]
    fn buffer_flushes_into_a_segment_at_threshold() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        assert_eq!(
            s.segment_count(),
            0,
            "one add stays buffered below threshold"
        );
        s.add(2, "b".into()).unwrap();
        assert_eq!(
            s.segment_count(),
            1,
            "second add hits threshold 2 and flushes"
        );
        assert!(s.buffer().is_empty());
    }

    #[test]
    fn wal_replay_preserves_flush_threshold() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Kv, 3).unwrap();
        for id in 0..65 {
            s.add(id, format!("v{id}")).unwrap();
        }
        drop(s);

        let mut reopened = SegmentedStore::open(dir, Kv, 3).unwrap();
        assert_eq!(reopened.segment_sizes(), vec![3; 21]);
        assert_eq!(reopened.buffer().len(), 2);

        reopened.add(65, "v65".into()).unwrap();
        assert_eq!(reopened.segment_sizes(), vec![3; 22]);
        assert!(reopened.buffer().is_empty());
        assert_eq!(live_set(&reopened).len(), 66);
    }

    #[test]
    fn wal_replay_preserves_checkpoint_visibility() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap();
        s.checkpoint().unwrap();

        s.add(3, "c".into()).unwrap();
        s.add(4, "d".into()).unwrap();
        s.delete(1).unwrap();
        drop(s);

        let mut reopened = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(
            live_set(&reopened),
            vec![(2, "b".into()), (3, "c".into()), (4, "d".into())]
        );

        let before_checkpoint = reopened.reader().view();
        assert_eq!(before_checkpoint.segment_count(), 1);
        assert!(before_checkpoint.is_live(&1));
        assert_eq!(before_checkpoint.segment_ids(), &[0]);

        reopened.checkpoint().unwrap();
        let after_checkpoint = reopened.reader().view();
        assert_eq!(after_checkpoint.segment_count(), 2);
        assert!(!after_checkpoint.is_live(&1));
        assert_eq!(after_checkpoint.segment_ids(), &[0, 1]);
    }

    #[test]
    fn delete_tombstones_and_hides_from_live_set() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap();
        s.delete(2).unwrap();
        assert!(s.is_live(&1) && !s.is_live(&2));
        assert_eq!(live_set(&s), vec![(1, "a".into())]);
    }

    #[test]
    fn re_add_of_a_live_id_replaces_the_sealed_copy() {
        // A re-add supersedes the sealed copy: per-copy liveness keeps only the
        // newest value, while per-id `is_live` stays true (the id is live).
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "x".into()).unwrap(); // flush=2 seals [(1,"a"),(2,"x")]
        s.add(1, "b".into()).unwrap(); // re-add 1: buffered; segment's (1,"a") is superseded
        assert!(s.is_live(&1));
        assert!(!s.is_live_in(s.segment_ids()[0], &1));
        assert_eq!(live_set(&s), vec![(1, "b".into()), (2, "x".into())]);

        // delete-then-add does not revive the old copy either.
        s.delete(1).unwrap();
        s.add(1, "c".into()).unwrap();
        assert_eq!(live_set(&s), vec![(1, "c".into()), (2, "x".into())]);
    }

    #[test]
    fn store_without_item_ids_replaces_only_the_buffered_copy() {
        // Without Store::item_ids segstore cannot tell which segment holds an
        // id, so a sealed copy stays live next to a re-add (the pre-tracking
        // behavior); a buffered copy is still replaced.
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), OpaqueKv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "x".into()).unwrap(); // seals [(1,"a"),(2,"x")]
        s.add(3, "y".into()).unwrap();
        s.add(3, "z".into()).unwrap(); // buffered re-add
        assert_eq!(s.buffer(), &[(3, "z".to_string())][..]);
        s.add(1, "b".into()).unwrap(); // seals [(3,"z"),(1,"b")]
        let seg0 = s.segment_ids()[0];
        assert!(s.is_live_in(seg0, &1), "untracked sealed copy stays live");
        s.checkpoint().unwrap();
        drop(s);
        let s = SegmentedStore::open(dir, OpaqueKv, 2).unwrap();
        assert!(s.is_live_in(seg0, &1), "same after reopen");
    }

    #[derive(Serialize)]
    struct LegacyTestManifest {
        next_seg_id: u64,
        segment_ids: Vec<u64>,
        tombstones: Vec<u32>,
    }

    #[test]
    fn writer_rejects_duplicate_live_ids_within_one_segment_without_changes() {
        let dir = MemoryDirectory::arc();
        let ckpt = CheckpointFile::new(dir.clone());
        ckpt.write_postcard(
            "segstore.seg.0",
            0,
            &vec![(7u32, "old".to_string()), (7, "new".to_string())],
        )
        .unwrap();
        let manifest = LegacyTestManifest {
            next_seg_id: 1,
            segment_ids: vec![0],
            tombstones: vec![],
        };
        ckpt.write_postcard(MANIFEST_PATH, 0, &manifest).unwrap();
        let snapshot = || {
            let mut names = dir.list_dir("").unwrap();
            names.sort();
            names
                .into_iter()
                .map(|name| {
                    let mut bytes = Vec::new();
                    dir.open_file(&name)
                        .unwrap()
                        .read_to_end(&mut bytes)
                        .unwrap();
                    (name, bytes)
                })
                .collect::<Vec<_>>()
        };
        let before = snapshot();
        let error = match SegmentedStore::open(dir.clone(), DefaultStore::<u32, String>::new(), 2) {
            Ok(_) => panic!("duplicate live ids within a segment cannot be safely reconstructed"),
            Err(error) => error,
        };
        assert!(matches!(error, PersistenceError::Format(_)), "{error}");
        assert!(error.to_string().contains("same segment"), "{error}");
        assert_eq!(snapshot(), before);
    }

    #[test]
    fn legacy_catalog_rejects_nonempty_manifest_without_reading_segments() {
        for segment_ids in [vec![0], vec![0, 1]] {
            let dir = MemoryDirectory::arc();
            let manifest = LegacyTestManifest {
                next_seg_id: segment_ids.len() as u64,
                segment_ids,
                tombstones: vec![],
            };
            CheckpointFile::new(dir.clone())
                .write_postcard(MANIFEST_PATH, 1, &manifest)
                .unwrap();
            let before = {
                let mut bytes = Vec::new();
                dir.open_file(MANIFEST_PATH)
                    .unwrap()
                    .read_to_end(&mut bytes)
                    .unwrap();
                bytes
            };
            let error = match SegmentCatalog::<u32>::open(dir.clone()) {
                Ok(_) => panic!("nonempty legacy ownership is ambiguous"),
                Err(error) => error,
            };
            assert!(matches!(error, PersistenceError::Format(_)), "{error}");
            assert!(error.to_string().contains("ownership"), "{error}");
            assert_eq!(
                {
                    let mut bytes = Vec::new();
                    dir.open_file(MANIFEST_PATH)
                        .unwrap()
                        .read_to_end(&mut bytes)
                        .unwrap();
                    bytes
                },
                before
            );
        }
    }

    #[test]
    fn legacy_catalog_allows_empty_and_modern_empty_ownership_metadata() {
        let dir = MemoryDirectory::arc();
        assert_eq!(
            SegmentCatalog::<u32>::open(dir.clone())
                .unwrap()
                .segment_count(),
            0
        );
        let empty = LegacyTestManifest {
            next_seg_id: 0,
            segment_ids: vec![],
            tombstones: vec![],
        };
        let ckpt = CheckpointFile::new(dir.clone());
        ckpt.write_postcard(MANIFEST_PATH, 0, &empty).unwrap();
        assert_eq!(
            SegmentCatalog::<u32>::open(dir.clone())
                .unwrap()
                .segment_count(),
            0
        );
        let modern = ManifestRef {
            next_seg_id: 2,
            segment_ids: &[0, 1],
            tombstones: &[],
            ext: ManifestExtRef::<u32> {
                version: MANIFEST_EXT_VERSION,
                superseded: &[],
            },
        };
        ckpt.write_postcard(MANIFEST_PATH, 1, &modern).unwrap();
        // There are deliberately no segment payload files: catalog open stays manifest-only.
        let catalog = SegmentCatalog::<u32>::open(dir.clone()).unwrap();
        assert_eq!(catalog.segment_count(), 2);
        assert!(catalog.is_live_in(0, &7));
        let single = ManifestRef {
            next_seg_id: 1,
            segment_ids: &[0],
            tombstones: &[],
            ext: ManifestExtRef::<u32> {
                version: MANIFEST_EXT_VERSION,
                superseded: &[],
            },
        };
        ckpt.write_postcard(MANIFEST_PATH, 1, &single).unwrap();
        assert_eq!(SegmentCatalog::<u32>::open(dir).unwrap().segment_count(), 1);
    }

    #[test]
    fn manifest_without_the_extension_still_opens() {
        // A manifest in the original layout (no superseded-copy extension), as
        // written by earlier segstore versions.
        #[derive(Serialize)]
        struct OriginalManifest<'a> {
            next_seg_id: u64,
            segment_ids: &'a [u64],
            tombstones: &'a [u32],
        }
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.checkpoint().unwrap();
        }
        let ckpt = CheckpointFile::new(dir.clone());
        let original = OriginalManifest {
            next_seg_id: 1,
            segment_ids: &[0],
            tombstones: &[2],
        };
        ckpt.write_postcard(MANIFEST_PATH, 1, &original).unwrap();

        assert!(matches!(
            SegmentCatalog::<u32>::open(dir.clone()),
            Err(PersistenceError::Format(_))
        ));
        let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
        assert_eq!(live_set(&s), vec![(1, "a".into())]);
        // The next checkpoint upgrades it, and a re-add is then tracked.
        s.add(1, "c".into()).unwrap();
        s.checkpoint().unwrap();
        let catalog = SegmentCatalog::<u32>::open(dir).unwrap();
        assert!(!catalog.is_live_in(0, &1));
    }

    #[test]
    fn original_layout_reader_still_decodes_a_current_manifest() {
        // An older segstore decodes the manifest as `Manifest`; postcard ignores
        // the trailing extension, so a downgrade still opens (without the
        // superseded-copy information).
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.add(1, "c".into()).unwrap();
            s.delete(2).unwrap();
            s.checkpoint().unwrap();
        }
        let ckpt = CheckpointFile::new(dir.clone());
        let (_, m): (u64, Manifest<u32>) = ckpt.read_postcard(MANIFEST_PATH).unwrap();
        assert_eq!(m.segment_ids, vec![0, 1]);
        assert_eq!(m.tombstones, vec![2]);
        let (_, v2): (u64, ManifestV2<u32>) = ckpt.read_postcard(MANIFEST_PATH).unwrap();
        assert_eq!(v2.ext.version, MANIFEST_EXT_VERSION);
        let mut superseded = v2.ext.superseded;
        for (_, ids) in &mut superseded {
            ids.sort_unstable();
        }
        assert_eq!(superseded, vec![(0, vec![1, 2])]);
    }

    #[test]
    fn open_keeps_the_newest_copy_when_an_old_manifest_has_duplicates() {
        // Before superseded copies were tracked, a re-add left two live copies
        // in sealed segments. Opening such a store keeps the newest one.
        #[derive(Serialize)]
        struct OriginalManifest<'a> {
            next_seg_id: u64,
            segment_ids: &'a [u64],
            tombstones: &'a [u32],
        }
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "x".into()).unwrap();
            s.add(1, "b".into()).unwrap();
            s.add(3, "y".into()).unwrap();
            s.checkpoint().unwrap();
        }
        let original = OriginalManifest {
            next_seg_id: 2,
            segment_ids: &[0, 1],
            tombstones: &[],
        };
        CheckpointFile::new(dir.clone())
            .write_postcard(MANIFEST_PATH, 1, &original)
            .unwrap();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        let want = vec![(1, "b".into()), (2, "x".into()), (3, "y".into())];
        assert_eq!(live_set(&s), want);
        s.compact().unwrap();
        assert_eq!(s.stored_len(), 3, "compaction dropped the older copy");
        assert_eq!(live_set(&s), want);
    }

    #[test]
    fn recovered_reader_uses_checkpoint_ownership_before_wal_replay() {
        // The original manifest layout is also exercised by the legacy writer
        // recovery tests above. Reader visibility must include its reconstructed
        // owners, but exclude replacements that only exist in the WAL.
        #[derive(Serialize)]
        struct OriginalManifest<'a> {
            next_seg_id: u64,
            segment_ids: &'a [u64],
            tombstones: &'a [u32],
        }
        for legacy in [true, false] {
            for wal_replacement in [false, true] {
                let dir = MemoryDirectory::arc();
                let mut s = SegmentedStore::open(dir.clone(), Dkv::new(), 1).unwrap();
                s.add(1, "old".into()).unwrap();
                s.add(1, "checkpoint".into()).unwrap();
                s.checkpoint().unwrap();
                if legacy {
                    CheckpointFile::new(dir.clone())
                        .write_postcard(
                            MANIFEST_PATH,
                            1,
                            &OriginalManifest {
                                next_seg_id: 2,
                                segment_ids: &[0, 1],
                                tombstones: &[],
                            },
                        )
                        .unwrap();
                }
                if wal_replacement {
                    s.add(1, "wal".into()).unwrap();
                }
                drop(s);

                let mut s = SegmentedStore::open(dir, Dkv::new(), 1).unwrap();
                let reader = s.reader();
                let held = reader.view();
                let checkpoint = vec![(1, "checkpoint".into())];
                assert_eq!(view_latest(&held), checkpoint);
                let current = if wal_replacement {
                    vec![(1, "wal".into())]
                } else {
                    checkpoint.clone()
                };
                assert_eq!(writer_latest(&s), current);
                s.checkpoint().unwrap();
                assert_eq!(view_latest(&reader.view()), current);
                assert_eq!(view_latest(&held), checkpoint, "held view is immutable");
            }
        }
    }

    #[test]
    fn unknown_manifest_extension_version_is_rejected() {
        #[derive(Serialize)]
        struct FutureManifest<'a> {
            next_seg_id: u64,
            segment_ids: &'a [u64],
            tombstones: &'a [u32],
            version: u32,
            superseded: &'a [(u64, Vec<u32>)],
        }
        let dir = MemoryDirectory::arc();
        let ckpt = CheckpointFile::new(dir.clone());
        let future = FutureManifest {
            next_seg_id: 0,
            segment_ids: &[],
            tombstones: &[],
            version: MANIFEST_EXT_VERSION + 1,
            superseded: &[],
        };
        ckpt.write_postcard(MANIFEST_PATH, 0, &future).unwrap();
        let err = SegmentCatalog::<u32>::open(dir.clone()).err().unwrap();
        assert!(err.to_string().contains("extension version"), "{err}");
        assert!(SegmentedStore::open(dir, Kv, 2).is_err());
    }

    #[test]
    fn compaction_physically_drops_tombstoned_ids() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap();
        s.add(3, "c".into()).unwrap();
        s.delete(2).unwrap();
        s.compact().unwrap();
        assert_eq!(s.segment_count(), 1, "compaction merges into one segment");
        assert_eq!(s.tombstone_count(), 0, "compaction purges tombstones");
        // The merged segment no longer carries id 2 at all.
        let flat: Vec<u32> = s.segments()[0].iter().map(|(id, _)| *id).collect();
        assert!(!flat.contains(&2));
        assert_eq!(live_set(&s), vec![(1, "a".into()), (3, "c".into())]);
    }

    #[test]
    fn recovers_from_checkpoint_plus_wal_replay() {
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap(); // flushes a segment
            s.checkpoint().unwrap(); // checkpoint covers ids 1,2
            s.add(3, "c".into()).unwrap(); // post-checkpoint, only in the WAL
            s.delete(2).unwrap(); // post-checkpoint tombstone
        } // drop without a second checkpoint: 3 and delete(2) live only in the WAL

        // Reopen: checkpoint gives {1,2}; WAL replay applies add(3) + delete(2).
        let s2 = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(live_set(&s2), vec![(1, "a".into()), (3, "c".into())]);
        assert!(!s2.is_live(&2));
    }

    /// A unique scratch directory under the OS temp dir (no tempfile dep).
    fn temp_root(tag: &str) -> std::path::PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!("segstore-test-{}-{}", std::process::id(), tag));
        let _ = std::fs::remove_dir_all(&p);
        p
    }

    #[test]
    fn recovers_on_real_disk_via_fs_directory() {
        let root = temp_root("fs-recover");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap(); // flushes a segment
            s.checkpoint().unwrap();
            s.add(3, "c".into()).unwrap(); // post-checkpoint, WAL only
            s.delete(2).unwrap();
        } // process-style drop: nothing in memory, only the on-disk WAL + checkpoint

        // A fresh FsDirectory on the same root must reconstruct the live set.
        let dir = durability::FsDirectory::arc(&root).unwrap();
        let s2 = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(live_set(&s2), vec![(1, "a".into()), (3, "c".into())]);
        assert!(!s2.is_live(&2));

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn second_writer_on_one_directory_is_refused() {
        // Two writers on one directory each checkpoint and GC the other's WAL
        // epoch, silently losing acknowledged adds. The store must take an
        // exclusive lock for its lifetime and release it on drop.
        let root = temp_root("single-writer");
        let first = SegmentedStore::open(durability::FsDirectory::arc(&root).unwrap(), Kv, 2)
            .expect("first open");
        let second = SegmentedStore::open(durability::FsDirectory::arc(&root).unwrap(), Kv, 2);
        assert!(second.is_err(), "a second live writer must be refused");
        drop(first);
        SegmentedStore::open(durability::FsDirectory::arc(&root).unwrap(), Kv, 2)
            .expect("the lock is released when the first store drops");
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn torn_wal_tail_is_dropped_not_fatal() {
        let root = temp_root("torn-wal");
        // Threshold high enough that every op stays in the WAL (no checkpoint,
        // no segment files), so the WAL is the single source of truth.
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 100).unwrap();
            s.add(1, "aaaa".into()).unwrap();
            s.add(2, "bbbb".into()).unwrap();
            s.add(3, "cccc".into()).unwrap();
            s.add(4, "dddd".into()).unwrap(); // this record's tail gets corrupted
        }

        // Corrupt the final WAL record by chopping bytes off the end of the file.
        // postcard records are length-prefixed, so a truncated final payload makes
        // the BestEffort reader stop before it rather than decode garbage.
        let wal = root.join(wal_path(0));
        let bytes = std::fs::read(&wal).unwrap();
        assert!(bytes.len() > 3, "WAL should hold four records");
        std::fs::write(&wal, &bytes[..bytes.len() - 3]).unwrap();

        // Recovery must succeed (no panic, no Err) and recover the intact prefix.
        let dir = durability::FsDirectory::arc(&root).unwrap();
        let s2 = SegmentedStore::open(dir, Kv, 100).unwrap();
        // id 4 never made it into the store: the torn final record was dropped,
        // so the live set is exactly the intact prefix. (`is_live` only reports
        // tombstone state, so it is not the right probe for "never added".)
        assert_eq!(
            live_set(&s2),
            vec![(1, "aaaa".into()), (2, "bbbb".into()), (3, "cccc".into())],
            "the torn final record is dropped; the prefix survives"
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    /// Writes acknowledged after a torn tail was recovered must survive the
    /// next reopen. Appending them behind the torn bytes made every later open
    /// fail with a CRC mismatch, so the whole store became unopenable.
    #[test]
    fn writes_after_torn_tail_recovery_survive_reopen() {
        let root = temp_root("torn-wal-then-write");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 100).unwrap();
            s.add(1, "aaaa".into()).unwrap();
            s.add(2, "bbbb".into()).unwrap(); // this record's tail gets torn
        }
        let wal = root.join(wal_path(0));
        let bytes = std::fs::read(&wal).unwrap();
        std::fs::write(&wal, &bytes[..bytes.len() - 3]).unwrap();

        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 100).unwrap();
            assert_eq!(live_set(&s), vec![(1, "aaaa".into())]);
            s.add(3, "cccc".into()).unwrap();
            s.add(4, "dddd".into()).unwrap();
        }

        let dir = durability::FsDirectory::arc(&root).unwrap();
        let s = SegmentedStore::open(dir, Kv, 100)
            .expect("writes acknowledged after recovery must not make the store unopenable");
        assert_eq!(
            live_set(&s),
            vec![(1, "aaaa".into()), (3, "cccc".into()), (4, "dddd".into())]
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Each checkpoint rotates the WAL, so at most one generation file exists.
    #[test]
    fn wal_is_bounded_to_one_generation_across_checkpoints() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Kv, 100).unwrap();
        for i in 0..10u32 {
            s.add(i, format!("v{i}")).unwrap();
            s.checkpoint().unwrap();
        }
        let wals: Vec<String> = dir
            .list_dir("")
            .unwrap()
            .into_iter()
            .filter(|n| n.starts_with(WAL_PREFIX))
            .collect();
        assert!(
            wals.len() <= 1,
            "rotation bounds the WAL to the current generation, got {wals:?}"
        );
    }

    /// A stale WAL from an earlier epoch (the crash-mid-rotation leftover) is
    /// never replayed and is garbage-collected on open.
    #[test]
    fn stale_wal_generation_is_ignored_and_gced() {
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 100).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.add(3, "c".into()).unwrap();
            s.checkpoint().unwrap(); // epoch 0 -> 1; snapshot holds {1,2,3}
        }
        // Forge a stale wal.0 (the generation a clean rotation deleted) carrying a
        // ghost op, as a crash mid-rotation would leave behind.
        {
            let mut ghost = RecordLogWriter::new(dir.clone(), wal_path(0));
            ghost
                .append_postcard(&Op::Add(99u32, "ghost".to_string()))
                .unwrap();
            ghost.flush().unwrap();
        }
        assert!(dir.exists(&wal_path(0)), "the stale WAL exists pre-open");

        let s2 = SegmentedStore::open(dir.clone(), Kv, 100).unwrap();
        assert_eq!(
            live_set(&s2),
            vec![(1, "a".into()), (2, "b".into()), (3, "c".into())],
            "the ghost op in the stale epoch is never replayed"
        );
        assert!(
            !dir.exists(&wal_path(0)),
            "the stale WAL generation is GC'd on open"
        );
    }

    #[test]
    fn fsync_policy_round_trips_on_filesystem() {
        let root = temp_root("fsync");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let opts = Options {
                sync: SyncPolicy::Fsync,
                ..Options::new(2)
            };
            let mut s = SegmentedStore::open_with_options(dir, Kv, opts).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap(); // flush
            s.checkpoint().unwrap();
            s.add(3, "c".into()).unwrap();
            s.delete(2).unwrap();
        }
        let dir = durability::FsDirectory::arc(&root).unwrap();
        let opts = Options {
            sync: SyncPolicy::Fsync,
            ..Options::new(2)
        };
        let s2 = SegmentedStore::open_with_options(dir, Kv, opts).unwrap();
        assert_eq!(live_set(&s2), vec![(1, "a".into()), (3, "c".into())]);
        assert!(!s2.is_live(&2));
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn fsync_policy_rejected_without_filesystem_backend() {
        let dir = MemoryDirectory::arc();
        let opts = Options {
            sync: SyncPolicy::Fsync,
            ..Options::new(2)
        };
        let err = SegmentedStore::open_with_options(dir, Kv, opts);
        assert!(
            matches!(err, Err(PersistenceError::InvalidConfig(_))),
            "Fsync on an in-memory directory is a config error"
        );
    }

    #[test]
    fn legacy_v01_unsuffixed_wal_is_rejected() {
        let dir = MemoryDirectory::arc();
        // Simulate a 0.1 store: a single unsuffixed WAL file.
        {
            let mut legacy = RecordLogWriter::new(dir.clone(), LEGACY_WAL_PATH);
            legacy
                .append_postcard(&Op::Add(1u32, "x".to_string()))
                .unwrap();
            legacy.flush().unwrap();
        }
        let err = SegmentedStore::open(dir, Kv, 2);
        assert!(
            matches!(err, Err(PersistenceError::InvalidConfig(_))),
            "a 0.1 on-disk store is rejected, not misread"
        );
    }

    // ---- size-tiered compaction ----

    /// The live `(id, item)` multiset, sorted, for invariant comparisons.
    fn live_multiset(s: &SegmentedStore<Kv>) -> Vec<(u32, String)> {
        live_set(s)
    }

    fn tier_opts(flush: usize, cfg: TierConfig, auto: bool) -> Options {
        Options {
            tiering: cfg,
            auto_compact: auto,
            ..Options::new(flush)
        }
    }

    #[test]
    fn compact_tiers_merges_a_full_bucket_and_is_idempotent() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig {
            min_merge: 4,
            ..Default::default()
        };
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(2, cfg, false)).unwrap();
        // 8 adds at flush=2 -> 4 segments of size 2: one full bucket.
        for i in 0..8u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        assert_eq!(
            s.segment_count(),
            4,
            "four size-2 segments before compaction"
        );
        let stats = s.compact_tiers().unwrap();
        assert_eq!(stats.merges, 1, "the full bucket merges once");
        assert_eq!(s.segment_count(), 1, "into a single segment");
        assert_eq!(stats.items_merged, 8);
        // Idempotent: nothing eligible now.
        assert!(!s.has_eligible_tier());
        let again = s.compact_tiers().unwrap();
        assert_eq!(again.merges, 0, "second call is a no-op");
    }

    #[test]
    fn tier_merge_respects_max_merged_len_cap() {
        let dir = MemoryDirectory::arc();
        // cap = 8 -> segments above 4 are frozen; 4 size-2 segments merge to exactly 8.
        let cfg = TierConfig {
            min_merge: 4,
            max_merged_len: 8,
            ..Default::default()
        };
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(2, cfg, true)).unwrap();
        for i in 0..64u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        s.compact_tiers().unwrap();
        for seg in s.segments() {
            assert!(
                seg.len() <= cfg.max_merged_len,
                "no segment exceeds the cap; got {}",
                seg.len()
            );
        }
    }

    #[test]
    fn auto_compact_bounds_segment_count() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig::default(); // min_merge 4, large cap
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(2, cfg, true)).unwrap();
        // 200 adds at flush=2 would be 100 segments without compaction.
        for i in 0..200u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        s.compact_tiers().unwrap();
        assert!(
            s.segment_count() <= 20,
            "tiering bounds segment count well below the uncompacted 100; got {}",
            s.segment_count()
        );
        // No data lost.
        assert_eq!(live_multiset(&s).len(), 200);
    }

    #[test]
    fn tier_merge_preserves_live_set_and_keeps_tombstones() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig {
            min_merge: 4,
            max_merged_len: 8, // force some frozen segments
            ..Default::default()
        };
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(2, cfg, false)).unwrap();
        let mut expect: std::collections::BTreeMap<u32, String> = Default::default();
        for i in 0..40u32 {
            s.add(i, format!("v{i}")).unwrap();
            expect.insert(i, format!("v{i}"));
        }
        // Delete a spread of ids (some land in soon-to-be-frozen segments).
        for i in (0..40u32).step_by(5) {
            s.delete(i).unwrap();
            expect.remove(&i);
        }
        s.compact_tiers().unwrap();
        let want: Vec<(u32, String)> = expect.into_iter().collect();
        assert_eq!(live_multiset(&s), want, "tier merge preserves the live set");
        assert!(
            s.tombstone_count() > 0,
            "partial tier merge keeps the tombstone set (ids may live in frozen segments)"
        );
        // Full compaction purges the tombstones.
        s.compact().unwrap();
        assert_eq!(s.tombstone_count(), 0, "full compact purges tombstones");
        assert_eq!(live_multiset(&s), want, "and preserves the live set");
    }

    #[test]
    fn min_merge_below_two_terminates() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig {
            min_merge: 1, // would group-of-1 forever without the clamp
            ..Default::default()
        };
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(1, cfg, false)).unwrap();
        for i in 0..8u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        // Must terminate (clamp forces min_merge >= 2).
        let stats = s.compact_tiers().unwrap();
        assert!(stats.segments_after <= stats.segments_before);
        assert_eq!(live_multiset(&s).len(), 8);
    }

    #[test]
    fn large_scale_random_simulation_holds_invariants() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig {
            min_merge: 4,
            max_merge: 8,
            max_merged_len: 64,
            ..Default::default()
        };
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(3, cfg, true)).unwrap();
        // Unique ids per add. A monotonic id keeps the reference model exact
        // while still exercising insert/delete/merge invariants; re-adds are
        // covered by `re_adds_are_last_write_wins_under_random_ops`.
        let mut expect: std::collections::BTreeMap<u32, String> = Default::default();
        let mut live_ids: Vec<u32> = Vec::new();
        let mut next_id = 0u32;
        // Deterministic LCG (no rand dep, no Math.random).
        let mut state: u64 = 0x9E3779B97F4A7C15;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (state >> 33) as u32
        };
        for _ in 0..2000 {
            if next() % 4 == 0 && !live_ids.is_empty() {
                let pos = (next() as usize) % live_ids.len();
                let id = live_ids.swap_remove(pos);
                s.delete(id).unwrap();
                expect.remove(&id);
            } else {
                let id = next_id;
                next_id += 1;
                let v = format!("v{id}");
                s.add(id, v.clone()).unwrap();
                expect.insert(id, v);
                live_ids.push(id);
            }
            if next() % 50 == 0 {
                s.compact_tiers().unwrap();
            }
            // Invariant: every segment is within the cap.
            for seg in s.segments() {
                assert!(
                    seg.len() <= cfg.max_merged_len,
                    "seg size {} exceeds cap {}",
                    seg.len(),
                    cfg.max_merged_len
                );
            }
        }
        s.compact().unwrap();
        let want: Vec<(u32, String)> = expect.into_iter().collect();
        assert_eq!(
            live_multiset(&s),
            want,
            "after a long random run, the live set matches the reference"
        );
    }

    #[test]
    fn segment_sizes_reports_per_segment_counts() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..6u32 {
            s.add(i, format!("v{i}")).unwrap(); // 3 segments of size 2
        }
        assert_eq!(s.segment_sizes(), vec![2, 2, 2]);
        assert_eq!(s.stored_len(), 6);
    }

    /// The store must be `Send` so the consumer can drive `compact_tiers` on a
    /// background thread (the whole point of consumer-driven scheduling).
    #[test]
    fn store_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<SegmentedStore<Kv>>();
    }

    // ---- checkpoint integrity (crash injection) ----

    #[test]
    fn corrupt_checkpoint_is_rejected_not_misread() {
        let root = temp_root("corrupt-ckpt");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.checkpoint().unwrap();
        }
        // Flip a byte in the middle of the manifest payload (past the header).
        let manifest = root.join(MANIFEST_PATH);
        let mut bytes = std::fs::read(&manifest).unwrap();
        let mid = bytes.len() / 2;
        bytes[mid] ^= 0xFF;
        std::fs::write(&manifest, &bytes).unwrap();

        let dir = durability::FsDirectory::arc(&root).unwrap();
        let res = SegmentedStore::open(dir, Kv, 2);
        assert!(
            res.is_err(),
            "a CRC-corrupt manifest is an error, not silently misread"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn stale_checkpoint_tmp_is_ignored() {
        let root = temp_root("stale-tmp");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.checkpoint().unwrap();
        }
        // A crash mid atomic_write can leave a `<manifest>.tmp` next to the real file.
        std::fs::write(root.join(format!("{MANIFEST_PATH}.tmp")), b"garbage").unwrap();

        let dir = durability::FsDirectory::arc(&root).unwrap();
        let s2 = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(live_set(&s2), vec![(1, "a".into()), (2, "b".into())]);
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn open_reclaims_a_segment_tmp_left_by_a_crash() {
        let root = temp_root("stale-seg-tmp");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.checkpoint().unwrap();
        }
        // A crash inside a segment's atomic write, before the rename, leaves
        // `<segment>.tmp`. Segment ids are never reused, so no later write
        // replaces it; open must delete it.
        let tmp = root.join(format!("{}.tmp", seg_path(9)));
        std::fs::write(&tmp, vec![0u8; 4096]).unwrap();

        let dir = durability::FsDirectory::arc(&root).unwrap();
        let s2 = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert!(!tmp.exists(), "segment tmp survived open");
        assert_eq!(live_set(&s2), vec![(1, "a".into()), (2, "b".into())]);
        let _ = std::fs::remove_dir_all(&root);
    }

    // ---- manifest format: incremental write, GC, version rejection ----

    /// A `Directory` that records the path of every mutating write (`atomic_write`
    /// + `create_file`), to assert which files a checkpoint actually rewrites.
    struct CountDir {
        inner: Arc<dyn Directory>,
        writes: Arc<std::sync::Mutex<Vec<String>>>,
    }
    impl CountDir {
        fn wrap(
            inner: Arc<dyn Directory>,
        ) -> (Arc<dyn Directory>, Arc<std::sync::Mutex<Vec<String>>>) {
            let writes = Arc::new(std::sync::Mutex::new(Vec::new()));
            let dir: Arc<dyn Directory> = Arc::new(CountDir {
                inner,
                writes: writes.clone(),
            });
            (dir, writes)
        }
    }
    impl Directory for CountDir {
        fn create_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.writes.lock().unwrap().push(p.to_string());
            self.inner.create_file(p)
        }
        fn atomic_write(&self, p: &str, d: &[u8]) -> PersistenceResult<()> {
            self.writes.lock().unwrap().push(p.to_string());
            self.inner.atomic_write(p, d)
        }
        fn open_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Read + Send>> {
            self.inner.open_file(p)
        }
        fn exists(&self, p: &str) -> bool {
            self.inner.exists(p)
        }
        fn delete(&self, p: &str) -> PersistenceResult<()> {
            self.inner.delete(p)
        }
        fn atomic_rename(&self, a: &str, b: &str) -> PersistenceResult<()> {
            self.inner.atomic_rename(a, b)
        }
        fn create_dir_all(&self, p: &str) -> PersistenceResult<()> {
            self.inner.create_dir_all(p)
        }
        fn list_dir(&self, p: &str) -> PersistenceResult<Vec<String>> {
            self.inner.list_dir(p)
        }
        fn append_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.inner.append_file(p)
        }
        fn file_path(&self, p: &str) -> Option<std::path::PathBuf> {
            self.inner.file_path(p)
        }
    }

    /// Count the `segstore.seg.*` files currently on disk.
    fn seg_file_count(dir: &Arc<dyn Directory>) -> usize {
        dir.list_dir("")
            .unwrap()
            .into_iter()
            .filter(|n| n.starts_with(SEG_PREFIX))
            .count()
    }

    #[test]
    fn checkpoint_writes_only_new_segment_files() {
        // The point of the manifest format: a checkpoint rewrites only the segments
        // sealed since the last one, not the whole corpus (O(delta), not O(total)).
        let (dir, writes) = CountDir::wrap(MemoryDirectory::arc());
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..4u32 {
            s.add(i, format!("v{i}")).unwrap(); // two sealed segments (ids 0, 1)
        }
        s.checkpoint().unwrap(); // writes seg.0, seg.1, manifest
        writes.lock().unwrap().clear();

        // One more segment, then checkpoint again.
        s.add(4, "e".into()).unwrap();
        s.add(5, "f".into()).unwrap(); // seals a third segment (id 2)
        s.checkpoint().unwrap();

        let w = writes.lock().unwrap();
        let seg_writes: Vec<&String> = w.iter().filter(|p| p.starts_with(SEG_PREFIX)).collect();
        assert_eq!(
            seg_writes.len(),
            1,
            "only the one new segment file is rewritten, not the unchanged two: {:?}",
            *w
        );
        assert!(
            seg_writes[0].ends_with(".2"),
            "and it is the new segment's file: {:?}",
            seg_writes
        );
    }

    #[test]
    fn compaction_gcs_superseded_segment_files() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
        for i in 0..8u32 {
            s.add(i, format!("v{i}")).unwrap(); // four segments
        }
        s.checkpoint().unwrap();
        assert_eq!(seg_file_count(&dir), 4, "one file per segment");
        s.compact().unwrap(); // merge to one; the four inputs are superseded
        assert_eq!(s.segment_count(), 1);
        assert_eq!(
            seg_file_count(&dir),
            1,
            "the merged-away segment files are GC'd; only the result remains"
        );
    }

    #[test]
    fn best_effort_delete_batch_syncs_parent_once() {
        struct SyncCountDir {
            inner: Arc<dyn Directory>,
            syncs: std::sync::atomic::AtomicUsize,
        }
        impl Directory for SyncCountDir {
            fn create_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
                self.inner.create_file(p)
            }
            fn open_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Read + Send>> {
                self.inner.open_file(p)
            }
            fn exists(&self, p: &str) -> bool {
                self.inner.exists(p)
            }
            fn delete(&self, p: &str) -> PersistenceResult<()> {
                self.inner.delete(p)
            }
            fn atomic_rename(&self, a: &str, b: &str) -> PersistenceResult<()> {
                self.inner.atomic_rename(a, b)
            }
            fn create_dir_all(&self, p: &str) -> PersistenceResult<()> {
                self.inner.create_dir_all(p)
            }
            fn list_dir(&self, p: &str) -> PersistenceResult<Vec<String>> {
                self.inner.list_dir(p)
            }
            fn append_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
                self.inner.append_file(p)
            }
            fn atomic_write(&self, p: &str, d: &[u8]) -> PersistenceResult<()> {
                self.inner.atomic_write(p, d)
            }
            fn file_path(&self, p: &str) -> Option<std::path::PathBuf> {
                Some(std::path::PathBuf::from("/tmp/segstore-sync-count").join(p))
            }
            fn durable_sync_parent_dir(&self, _path: &str) -> PersistenceResult<()> {
                self.syncs
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                Ok(())
            }
        }

        let dir = SyncCountDir {
            inner: MemoryDirectory::arc(),
            syncs: std::sync::atomic::AtomicUsize::new(0),
        };
        dir.atomic_write("a", b"a").unwrap();
        dir.atomic_write("b", b"b").unwrap();

        delete_files_best_effort(&dir, vec!["a".into(), "b".into(), "missing".into()], true);
        assert!(!dir.exists("a"));
        assert!(!dir.exists("b"));
        assert_eq!(
            dir.syncs.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "multiple GC deletes share one parent-directory sync"
        );

        delete_files_best_effort(&dir, vec!["missing".into()], true);
        assert_eq!(
            dir.syncs.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "missing files do not force a parent-directory sync"
        );

        dir.atomic_write("c", b"c").unwrap();
        delete_files_best_effort(&dir, vec!["c".into()], false);
        assert_eq!(
            dir.syncs.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "non-durable cleanup does not sync"
        );
    }

    #[test]
    fn index_sidecars_are_gced_with_their_segments() {
        // The persist-index hook: a consumer writes a per-segment index sidecar keyed
        // by a stable seg id; segstore GCs it when the segment is compacted away, and
        // sweeps orphans on open, on the same schedule as the segment files.
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
        for i in 0..8u32 {
            s.add(i, format!("v{i}")).unwrap(); // four segments
        }
        s.checkpoint().unwrap();
        // Simulate the consumer persisting one index sidecar per segment.
        for &id in s.segment_ids() {
            dir.atomic_write(&s.index_name(id, "toy"), b"built-index")
                .unwrap();
        }
        let idx_count = |d: &Arc<dyn Directory>| {
            d.list_dir("")
                .unwrap()
                .into_iter()
                .filter(|n| idx_seg_id(n).is_some())
                .count()
        };
        assert_eq!(idx_count(&dir), 4, "one sidecar per segment");

        // Compaction merges to one segment; the four inputs' sidecars are orphaned.
        s.compact().unwrap();
        assert_eq!(s.segment_count(), 1);
        assert_eq!(
            idx_count(&dir),
            0,
            "sidecars of compacted-away segments are GC'd"
        );

        // A sidecar for a segment that no longer exists is swept on open.
        dir.atomic_write(&s.index_name(9999, "toy"), b"orphan")
            .unwrap();
        drop(s);
        let _ = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
        assert_eq!(idx_count(&dir), 0, "orphan sidecar GC'd on open");
    }

    #[test]
    fn legacy_sidecar_names_are_still_gced() {
        // `try_index_name` rejects dotted kinds for new writes, but pre-grammar
        // releases allowed callers to write names such as `hnsw.v1`. Treat them
        // as sidecars for GC so upgrades do not strand stale derived artifacts.
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
        for i in 0..4u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        s.checkpoint().unwrap();
        let stale_id = s.segment_ids()[0];
        dir.atomic_write(&format!("{IDX_PREFIX}{stale_id}.hnsw.v1"), b"old-index")
            .unwrap();

        s.compact().unwrap();

        assert!(
            !dir.exists(&format!("{IDX_PREFIX}{stale_id}.hnsw.v1")),
            "legacy dotted-kind sidecar is removed when its segment is compacted away"
        );
    }

    #[test]
    fn index_sidecar_kind_is_checked() {
        let dir = MemoryDirectory::arc();
        let s = SegmentedStore::open(dir, Kv, 2).unwrap();

        assert_eq!(
            try_index_name(7, "hnsw_v1-fast").unwrap(),
            "segstore.idx.7.hnsw_v1-fast"
        );
        assert_eq!(
            s.try_index_name(7, "hnsw_v1-fast").unwrap(),
            try_index_name(7, "hnsw_v1-fast").unwrap()
        );
        assert_eq!(
            s.index_name(7, "hnsw_v1-fast"),
            index_name(7, "hnsw_v1-fast")
        );

        for kind in ["", "hnsw.v1", "hnsw/tmp", "../hnsw", ".tmp", "hnsw tmp"] {
            assert!(
                matches!(
                    try_index_name(7, kind),
                    Err(PersistenceError::InvalidConfig(_))
                ),
                "kind {kind:?} should be rejected by the free helper"
            );
            assert!(
                matches!(
                    s.try_index_name(7, kind),
                    Err(PersistenceError::InvalidConfig(_))
                ),
                "kind {kind:?} should be rejected"
            );
        }
    }

    #[test]
    #[should_panic(expected = "invalid segstore index kind")]
    fn index_name_panics_on_invalid_kind() {
        let _ = index_name(7, "hnsw.v1");
    }

    #[test]
    #[should_panic(expected = "invalid segstore index kind")]
    fn store_index_name_panics_on_invalid_kind() {
        let dir = MemoryDirectory::arc();
        let s = SegmentedStore::open(dir, Kv, 2).unwrap();
        let _ = s.index_name(7, "hnsw.v1");
    }

    #[test]
    fn index_sidecar_parser_recognizes_legacy_names_for_gc() {
        assert_eq!(idx_seg_id("segstore.idx.7.hnsw_v1-fast"), Some(7));
        assert_eq!(
            idx_seg_id("segstore.idx.7.hnsw.v1"),
            Some(7),
            "legacy dotted kind is still classified for cleanup"
        );

        for name in [
            "segstore.idx.7",
            "segstore.idx.7.",
            "segstore.idx.not-a-number.hnsw",
            "segstore.idx..hnsw",
            "not-segstore.idx.7.hnsw",
        ] {
            assert_eq!(idx_seg_id(name), None, "{name:?} should not parse");
        }
    }

    #[test]
    fn v02_ckpt_format_is_rejected() {
        let dir = MemoryDirectory::arc();
        // Simulate a 0.2 store: a monolithic checkpoint blob, no manifest.
        dir.atomic_write(LEGACY_CKPT_PATH, b"a 0.2 checkpoint blob")
            .unwrap();
        let err = SegmentedStore::open(dir, Kv, 2);
        assert!(
            matches!(err, Err(PersistenceError::InvalidConfig(_))),
            "a 0.2 on-disk store is rejected, not misread"
        );
    }

    #[test]
    fn corrupt_segment_file_is_rejected() {
        let root = temp_root("corrupt-seg");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
            s.add(1, "aaaaaaaa".into()).unwrap();
            s.add(2, "bbbbbbbb".into()).unwrap(); // seals segment id 0
            s.checkpoint().unwrap();
        }
        // Corrupt the one segment file (seg.0); recovery must reject, not misread.
        let seg = root.join(seg_path(0));
        let mut bytes = std::fs::read(&seg).unwrap();
        let mid = bytes.len() / 2;
        bytes[mid] ^= 0xFF;
        std::fs::write(&seg, &bytes).unwrap();

        let dir = durability::FsDirectory::arc(&root).unwrap();
        let res = SegmentedStore::open(dir, Kv, 2);
        assert!(
            res.is_err(),
            "a CRC-corrupt segment file is an error, not silently misread"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn segment_catalog_reads_manifest_without_decoding_segments() {
        let root = temp_root("segment-catalog");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.add(3, "c".into()).unwrap();
            s.add(4, "d".into()).unwrap();
            s.delete(2).unwrap();
            s.checkpoint().unwrap();
        }

        // Corrupt one segment file. Opening the full store must reject it, but
        // opening the catalog should still succeed because it reads only the
        // manifest. This is the narrow diagnostic/catalog step, not a query reader.
        let seg = root.join(seg_path(0));
        let mut bytes = std::fs::read(&seg).unwrap();
        let mid = bytes.len() / 2;
        bytes[mid] ^= 0xFF;
        std::fs::write(&seg, &bytes).unwrap();

        let dir = durability::FsDirectory::arc(&root).unwrap();
        let res = SegmentedStore::open(dir.clone(), Kv, 2);
        assert!(
            res.is_err(),
            "full store open decodes segment payloads and rejects corruption"
        );

        let catalog = SegmentCatalog::<u32>::open(dir.clone()).unwrap();
        assert_eq!(catalog.epoch(), 1);
        assert_eq!(catalog.segment_ids(), &[0, 1]);
        assert_eq!(catalog.segment_count(), 2);
        assert_eq!(catalog.tombstone_count(), 1);
        assert!(catalog.is_live(&1));
        assert!(!catalog.is_live(&2));
        assert_eq!(catalog.segment_name(1).unwrap(), seg_path(1));
        assert_eq!(
            catalog.try_index_name(1, "toy").unwrap(),
            "segstore.idx.1.toy"
        );
        assert!(matches!(
            catalog.segment_name(99),
            Err(PersistenceError::NotFound(_))
        ));
        assert!(catalog.open_segment_file(1).is_ok());
        let payload = catalog.read_segment_payload(1).unwrap();
        assert!(
            !payload.is_empty(),
            "payload bytes are available without decoding"
        );
        let seg1: Vec<(u32, String)> = catalog.read_segment(1).unwrap();
        assert_eq!(seg1, vec![(3, "c".into()), (4, "d".into())]);
        assert!(
            catalog.read_segment_payload(0).is_err(),
            "payload reads still validate the segment checkpoint CRC"
        );
        assert!(
            catalog.read_segment::<Vec<(u32, String)>>(0).is_err(),
            "reading the corrupt segment should fail when that segment is requested"
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn segment_catalog_payload_info_points_to_validated_payload_bytes() {
        use std::io::{Read, Seek};

        let root = temp_root("segment-payload-info");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.checkpoint().unwrap();
        }

        let dir = durability::FsDirectory::arc(&root).unwrap();
        let catalog = SegmentCatalog::<u32>::open(dir).unwrap();
        let seg_id = catalog.segment_ids()[0];
        let info = catalog.segment_payload_info(seg_id).unwrap();
        let payload = catalog.read_segment_payload(seg_id).unwrap();

        assert_eq!(info.payload_len, payload.len());
        assert_eq!(info.payload_crc32, crc32fast::hash(&payload));
        info.verify_payload(&payload).unwrap();

        let truncated = &payload[..payload.len() - 1];
        assert!(matches!(
            info.verify_payload(truncated),
            Err(PersistenceError::Format(_))
        ));

        let mut corrupt = payload.clone();
        corrupt[0] ^= 0xFF;
        assert!(matches!(
            info.verify_payload(&corrupt),
            Err(PersistenceError::CrcMismatch { .. })
        ));

        let path = catalog.segment_file_path(seg_id).unwrap().unwrap();
        let mut file = std::fs::File::open(path).unwrap();
        file.seek(std::io::SeekFrom::Start(info.payload_offset))
            .unwrap();
        let mut from_file = vec![0u8; info.payload_len];
        file.read_exact(&mut from_file).unwrap();
        assert_eq!(from_file, payload);

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn segment_catalog_reads_source_payloads_and_exposes_liveness_separately() {
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "b".into()).unwrap();
            s.delete(2).unwrap();
            s.checkpoint().unwrap();
        }

        let catalog = SegmentCatalog::<u32>::open(dir).unwrap();
        let segment_id = catalog.segment_ids()[0];
        let segment: Vec<(u32, String)> = catalog.read_segment(segment_id).unwrap();

        assert_eq!(segment, vec![(1, "a".into()), (2, "b".into())]);
        assert!(catalog.is_live(&1));
        assert!(!catalog.is_live(&2));
    }

    #[test]
    fn segment_catalog_payload_into_reuses_buffer_and_clears_on_error() {
        use std::io::Read;

        let dir = MemoryDirectory::arc();
        let seg_id = {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 1).unwrap();
            s.add(1, "a".into()).unwrap();
            s.checkpoint().unwrap();
            s.segment_ids()[0]
        };
        let catalog = SegmentCatalog::<u32>::open(dir.clone()).unwrap();

        let mut scratch = Vec::with_capacity(1024);
        let ptr = scratch.as_ptr();
        catalog
            .read_segment_payload_into(seg_id, &mut scratch)
            .unwrap();
        assert_eq!(
            scratch.as_ptr(),
            ptr,
            "a sufficiently large scratch buffer is reused"
        );
        let good_payload = scratch.clone();
        scratch.extend_from_slice(b"stale suffix");
        catalog
            .read_segment_payload_into(seg_id, &mut scratch)
            .unwrap();
        assert_eq!(scratch, good_payload, "the destination is cleared first");

        let name = seg_path(seg_id);
        let mut bytes = Vec::new();
        dir.open_file(&name)
            .unwrap()
            .read_to_end(&mut bytes)
            .unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 0xFF;
        dir.atomic_write(&name, &bytes).unwrap();

        let err = catalog
            .read_segment_payload_into(seg_id, &mut scratch)
            .unwrap_err();
        assert!(
            matches!(err, PersistenceError::CrcMismatch { .. }),
            "payload corruption is still detected: {err}"
        );
        assert!(
            scratch.is_empty(),
            "partial/corrupt reads do not leak bytes"
        );
    }

    #[test]
    fn segment_catalog_rejects_legacy_formats() {
        let dir = MemoryDirectory::arc();
        dir.atomic_write(LEGACY_CKPT_PATH, b"a 0.2 checkpoint blob")
            .unwrap();
        let err = SegmentCatalog::<u32>::open(dir);
        assert!(
            matches!(err, Err(PersistenceError::InvalidConfig(_))),
            "legacy monolithic checkpoints are rejected consistently"
        );
    }

    /// A `Directory` whose manifest write, once armed, publishes the new manifest
    /// and then fails, like a durable write whose fsync fails after the rename.
    struct ManifestPublishedThenFailsDir {
        inner: Arc<dyn Directory>,
        armed: std::sync::atomic::AtomicBool,
    }
    impl Directory for ManifestPublishedThenFailsDir {
        fn create_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.inner.create_file(p)
        }
        fn open_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Read + Send>> {
            self.inner.open_file(p)
        }
        fn exists(&self, p: &str) -> bool {
            self.inner.exists(p)
        }
        fn delete(&self, p: &str) -> PersistenceResult<()> {
            self.inner.delete(p)
        }
        fn atomic_rename(&self, a: &str, b: &str) -> PersistenceResult<()> {
            self.inner.atomic_rename(a, b)
        }
        fn create_dir_all(&self, p: &str) -> PersistenceResult<()> {
            self.inner.create_dir_all(p)
        }
        fn list_dir(&self, p: &str) -> PersistenceResult<Vec<String>> {
            self.inner.list_dir(p)
        }
        fn append_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.inner.append_file(p)
        }
        fn atomic_write(&self, p: &str, d: &[u8]) -> PersistenceResult<()> {
            self.inner.atomic_write(p, d)?;
            if p == MANIFEST_PATH && self.armed.load(std::sync::atomic::Ordering::Relaxed) {
                return Err(PersistenceError::InvalidState(
                    "injected fault after manifest publish".into(),
                ));
            }
            Ok(())
        }
        fn file_path(&self, p: &str) -> Option<std::path::PathBuf> {
            self.inner.file_path(p)
        }
    }

    #[test]
    fn failed_manifest_write_refuses_later_writes_instead_of_losing_them() {
        let mem = MemoryDirectory::arc();
        let faulty = Arc::new(ManifestPublishedThenFailsDir {
            inner: mem.clone(),
            armed: std::sync::atomic::AtomicBool::new(false),
        });
        let mut s = SegmentedStore::open(faulty.clone(), Kv, 100).unwrap();
        let mut acked = Vec::new();
        s.add(1, "v1".into()).unwrap();
        acked.push(1u32);
        s.checkpoint().unwrap();
        s.add(2, "v2".into()).unwrap();
        acked.push(2);

        faulty
            .armed
            .store(true, std::sync::atomic::Ordering::Relaxed);
        assert!(s.checkpoint().is_err(), "injected manifest fault surfaces");
        faulty
            .armed
            .store(false, std::sync::atomic::Ordering::Relaxed);

        // The new manifest is visible, so reopen GCs the store's current WAL
        // generation. A write appended there must be refused, not acknowledged.
        let after_add = s.add(3, "v3".into());
        if after_add.is_ok() {
            acked.push(3);
        }
        let after_delete = s.delete(1);
        if after_delete.is_ok() {
            acked.retain(|&id| id != 1);
        }

        // Reopen as a crash would (memory backends take no process lock).
        let s2 = SegmentedStore::open(mem, Kv, 100).unwrap();
        let live: Vec<u32> = live_set(&s2).into_iter().map(|(id, _)| id).collect();
        assert_eq!(live, acked, "every acknowledged write survives reopen");
        assert!(
            after_add.is_err(),
            "add after a failed checkpoint is refused"
        );
        assert!(
            after_delete.is_err(),
            "delete after a failed checkpoint is refused"
        );
        assert!(
            s.checkpoint().is_err(),
            "a poisoned store refuses checkpoint"
        );
    }

    /// A `Directory` that refuses segment files above `cap` bytes, as the
    /// checkpoint payload cap refuses an oversized segment, deterministically
    /// on every attempt.
    struct SegmentSizeCapDir {
        inner: Arc<dyn Directory>,
        cap: usize,
    }
    impl Directory for SegmentSizeCapDir {
        fn create_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.inner.create_file(p)
        }
        fn open_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Read + Send>> {
            self.inner.open_file(p)
        }
        fn exists(&self, p: &str) -> bool {
            self.inner.exists(p)
        }
        fn delete(&self, p: &str) -> PersistenceResult<()> {
            self.inner.delete(p)
        }
        fn atomic_rename(&self, a: &str, b: &str) -> PersistenceResult<()> {
            self.inner.atomic_rename(a, b)
        }
        fn create_dir_all(&self, p: &str) -> PersistenceResult<()> {
            self.inner.create_dir_all(p)
        }
        fn list_dir(&self, p: &str) -> PersistenceResult<Vec<String>> {
            self.inner.list_dir(p)
        }
        fn append_file(&self, p: &str) -> PersistenceResult<Box<dyn std::io::Write + Send>> {
            self.inner.append_file(p)
        }
        fn atomic_write(&self, p: &str, d: &[u8]) -> PersistenceResult<()> {
            if p.starts_with(SEG_PREFIX) && d.len() > self.cap {
                return Err(PersistenceError::Format(format!(
                    "injected size cap: {} bytes",
                    d.len()
                )));
            }
            self.inner.atomic_write(p, d)
        }
        fn file_path(&self, p: &str) -> Option<std::path::PathBuf> {
            self.inner.file_path(p)
        }
    }

    #[test]
    fn oversized_merge_fails_compaction_without_blocking_later_checkpoints() {
        let mem = MemoryDirectory::arc();
        let capped: Arc<dyn Directory> = Arc::new(SegmentSizeCapDir {
            inner: mem.clone(),
            cap: 600,
        });
        let mut s = SegmentedStore::open(capped, Kv, 2).unwrap();
        let item = |id: u32| format!("{id:0>100}");
        // Four two-item segments of about 200 bytes each: one size tier whose
        // merged output (about 800 bytes) exceeds the cap.
        for id in 0..8u32 {
            s.add(id, item(id)).unwrap();
        }
        s.checkpoint().unwrap();
        assert_eq!(s.segment_count(), 4);
        assert!(s.has_eligible_tier());
        let before = live_set(&s);

        assert!(
            s.compact_tiers().is_err(),
            "the oversized merge output is refused"
        );
        assert_eq!(
            s.segment_count(),
            4,
            "a refused merge leaves the segment set unchanged"
        );
        assert_eq!(live_set(&s), before);

        // The store keeps committing: a later checkpoint persists new writes
        // and publishes them to readers instead of retrying the refused merge.
        s.add(100, "after".into()).unwrap();
        s.checkpoint()
            .expect("checkpoint after a refused merge succeeds");
        let view = s.reader().view();
        assert!(
            view.segments()
                .iter()
                .any(|seg| seg.iter().any(|(id, _)| *id == 100)),
            "readers see writes committed after the refused merge"
        );

        drop(s);
        let s2 = SegmentedStore::open(mem, Kv, 2).unwrap();
        let mut expected = before;
        expected.push((100, "after".into()));
        expected.sort();
        assert_eq!(live_set(&s2), expected, "reopen recovers every write");
    }

    #[test]
    fn recovers_consistently_from_io_fault_at_every_step() {
        // FoundationDB-style fault injection: fail the Nth IO op, then reopen on
        // the underlying (un-faulted) directory and assert the recovered live set
        // is EXACTLY the durably-acked adds -- every Ok(add) survives, no failed add
        // appears, recovery never panics and never sees corruption. Sweeps the
        // fault point across the whole op sequence.
        for fail_after in 0..30usize {
            let mem = MemoryDirectory::arc();
            let dir = FaultDir::arc(mem.clone(), fail_after);
            let mut acked: Vec<u32> = Vec::new();
            if let Ok(mut s) = SegmentedStore::open(dir, Kv, 2) {
                for i in 0..10u32 {
                    if s.add(i, format!("v{i}")).is_err() {
                        break;
                    }
                    acked.push(i);
                    if i % 3 == 0 && s.compact_tiers().is_err() {
                        break;
                    }
                }
            }
            // Reopen on the clean underlying directory (the partial on-disk state).
            let s2 = SegmentedStore::open(mem, Kv, 2)
                .expect("recovery after an injected IO fault must not fail");
            let mut live: Vec<u32> = live_set(&s2).into_iter().map(|(id, _)| id).collect();
            live.sort_unstable();
            assert_eq!(
                live, acked,
                "fail_after={fail_after}: recovered set must be exactly the durably-acked adds"
            );
        }
    }

    #[test]
    fn no_space_leak_across_crash_recovery_cycles() {
        // After many crash+recover cycles, deleting everything and a full compaction
        // returns the store to baseline: no leaked segments, items, tombstones, or WAL
        // generations. This is redb's canonical invariant and the bug class targeted
        // crash tests structurally miss (a slow leak across recovery cycles).
        let mem = MemoryDirectory::arc();
        for cycle in 0..20u32 {
            // "Crash": run a few ops under an IO fault and drop the store mid-flight.
            let dir = FaultDir::arc(mem.clone(), (cycle as usize % 5) + 1);
            if let Ok(mut s) = SegmentedStore::open(dir, Kv, 2) {
                for j in 0..4u32 {
                    let id = cycle * 100 + j;
                    let _ = s.add(id, format!("v{id}"));
                    let _ = s.compact_tiers();
                }
            }
            // Recover on the clean directory between cycles.
            let _ = SegmentedStore::open(mem.clone(), Kv, 2).unwrap();
        }
        // Delete every surviving id, then full-compact.
        let mut s = SegmentedStore::open(mem.clone(), Kv, 2).unwrap();
        let live: Vec<u32> = live_set(&s).into_iter().map(|(id, _)| id).collect();
        for id in live {
            s.delete(id).unwrap();
        }
        s.compact().unwrap();
        assert_eq!(
            s.segment_count(),
            0,
            "no leaked segments after delete-all + compact"
        );
        assert_eq!(s.stored_len(), 0, "no leaked stored items");
        assert_eq!(s.tombstone_count(), 0, "compact purged the tombstone set");
        let wals: Vec<String> = mem
            .list_dir("")
            .unwrap()
            .into_iter()
            .filter(|n| n.starts_with(WAL_PREFIX))
            .collect();
        assert!(wals.len() <= 1, "no leaked WAL generations: {wals:?}");
        assert_eq!(
            seg_file_count(&mem),
            0,
            "no leaked segment files after delete-all + compact"
        );
    }
    // ---- tombstone reclamation (optional live_len) ----

    #[test]
    fn space_amplification_tracks_dead_data() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..10u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        assert_eq!(
            s.space_amplification(),
            Some(1.0),
            "no deletes, no dead data"
        );
        for i in 0..5u32 {
            s.delete(i).unwrap();
        }
        // 10 stored, 5 live -> amplification 2.0.
        assert_eq!(s.space_amplification(), Some(2.0));
        s.compact().unwrap();
        assert_eq!(s.space_amplification(), Some(1.0), "compaction reclaims it");
    }

    #[test]
    fn space_amplification_is_none_without_live_len() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, OpaqueKv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap();
        assert_eq!(
            s.space_amplification(),
            None,
            "a store without live_len cannot report it"
        );
    }

    #[test]
    fn reclaim_tombstones_rewrites_only_heavy_segments() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        // 5 segments of size 2 (ids 0..10).
        for i in 0..10u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        // Tombstone both items in the first two segments (ids 0,1,2,3) -> those
        // segments are fully dead; the rest are fully live.
        for i in 0..4u32 {
            s.delete(i).unwrap();
        }
        let before_stored = s.stored_len();
        let stats = s.reclaim_tombstones(0.5).unwrap();
        assert!(stats.merges > 0, "the dead segments were reclaimed");
        assert!(
            s.stored_len() < before_stored,
            "dead data dropped: {} < {}",
            s.stored_len(),
            before_stored
        );
        // Live set unchanged; tombstones kept (no full purge).
        let live: Vec<u32> = live_set(&s).into_iter().map(|(id, _)| id).collect();
        assert_eq!(live, (4..10).collect::<Vec<_>>());
    }

    #[test]
    fn reclaim_tombstones_is_noop_without_live_len() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, OpaqueKv, 2).unwrap();
        for i in 0..6u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        s.delete(0).unwrap();
        let before = s.segment_count();
        let stats = s.reclaim_tombstones(0.9).unwrap();
        assert_eq!(stats.merges, 0, "no live_len -> reclaim is a no-op");
        assert_eq!(s.segment_count(), before);
    }

    #[test]
    fn reclaim_drops_a_fully_dead_segment() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..4u32 {
            s.add(i, format!("v{i}")).unwrap(); // segment A=[0,1], B=[2,3]
        }
        assert_eq!(s.segment_count(), 2);
        s.delete(0).unwrap();
        s.delete(1).unwrap(); // segment A is now 0% live
        s.reclaim_tombstones(0.5).unwrap();
        // A's merge produces an empty segment, which is dropped (not kept as empty).
        assert_eq!(s.segment_count(), 1, "the fully-dead segment is dropped");
        assert_eq!(s.stored_len(), 2, "only the live segment remains");
    }

    // ---- force-merge / on-demand consolidation ----

    #[test]
    fn force_merge_to_consolidates_without_data_loss() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..20u32 {
            s.add(i, format!("v{i}")).unwrap(); // 10 segments of size 2
        }
        assert_eq!(s.segment_count(), 10);
        let stats = s.force_merge_to(3).unwrap();
        // Minimum work: consolidates to exactly 3 in a single merge (k = over+1 = 8
        // segments at once), like Lucene's least-number-of-merges force-merge.
        assert_eq!(s.segment_count(), 3, "consolidated to exactly 3");
        assert_eq!(stats.merges, 1, "one merge suffices (minimum work)");
        assert!(stats.items_merged > 0, "merged work is reported");
        assert_eq!(live_multiset(&s).len(), 20, "no data lost");
    }

    #[test]
    fn force_merge_to_one_purges_tombstones() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..10u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        for i in 0..5u32 {
            s.delete(i).unwrap();
        }
        s.force_merge_to(1).unwrap();
        assert_eq!(s.segment_count(), 1);
        assert_eq!(s.tombstone_count(), 0, "merge to one purges tombstones");
        let live: Vec<u32> = live_set(&s).into_iter().map(|(id, _)| id).collect();
        assert_eq!(live, (5..10).collect::<Vec<_>>());
    }

    #[test]
    fn force_merge_to_is_noop_when_already_small() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..4u32 {
            s.add(i, format!("v{i}")).unwrap(); // 2 segments
        }
        let e = s.epoch();
        let stats = s.force_merge_to(5).unwrap();
        assert_eq!(stats.merges, 0, "already at/below target, nothing to merge");
        assert_eq!(s.segment_count(), 2);
        assert_eq!(s.epoch(), e, "no merge -> no checkpoint");
    }

    #[test]
    fn force_merge_persists_across_reopen() {
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
            for i in 0..20u32 {
                s.add(i, format!("v{i}")).unwrap(); // 10 segments
            }
            s.force_merge_to(2).unwrap();
            assert_eq!(s.segment_count(), 2);
        }
        let s = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(s.segment_count(), 2, "force-merge result was checkpointed");
        assert_eq!(live_multiset(&s).len(), 20);
    }

    /// Tiering rewrites each item O(log) times, so the total merged work over N
    /// inserts is O(N log N) -- far below the O(N^2) of rebuilding everything on
    /// each compaction, which is the cliff the max_merged_len cap exists to avoid.
    #[test]
    fn tiered_write_amplification_is_subquadratic() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig::default(); // min_merge 4, large cap (no freezing here)
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(4, cfg, false)).unwrap();
        let n: u32 = 4000;
        let mut total_merged = 0usize;
        for i in 0..n {
            s.add(i, format!("v{i}")).unwrap();
            if i % 16 == 0 {
                total_merged += s.compact_tiers().unwrap().items_merged;
            }
        }
        total_merged += s.compact_tiers().unwrap().items_merged;
        let n = n as usize;
        assert!(total_merged > 0, "compaction actually ran");
        assert!(
            total_merged < 20 * n,
            "tiered merge work {total_merged} is ~O(N log N) (< 20*N = {}), not O(N^2={})",
            20 * n,
            n * n
        );
        assert_eq!(live_multiset(&s).len(), n, "no data lost");
    }

    // ---- mutation-driven: pin behavior the live-set tests left unobserved ----

    #[test]
    fn epoch_advances_per_checkpoint() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(s.epoch(), 0);
        s.add(1, "a".into()).unwrap();
        s.checkpoint().unwrap();
        assert_eq!(s.epoch(), 1);
        s.checkpoint().unwrap();
        assert_eq!(s.epoch(), 2);
    }

    #[test]
    fn stored_len_and_space_amp_count_the_buffer() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 100).unwrap(); // stays buffered
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap();
        assert_eq!(s.segment_count(), 0, "all buffered");
        assert_eq!(s.stored_len(), 2, "stored_len counts the buffer");
        assert_eq!(
            s.space_amplification(),
            Some(1.0),
            "buffered items are live"
        );
    }

    #[test]
    fn space_amp_of_empty_store_is_one() {
        let dir = MemoryDirectory::arc();
        let s = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(s.space_amplification(), Some(1.0));
    }

    #[test]
    fn space_amp_is_infinite_when_all_dead() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap(); // 1 segment, size 2
        s.delete(1).unwrap();
        s.delete(2).unwrap(); // stored 2, live 0
        assert!(
            s.space_amplification().unwrap().is_infinite(),
            "an all-dead segment is infinite amplification"
        );
    }

    #[test]
    fn has_eligible_tier_is_true_when_a_bucket_is_full() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig {
            min_merge: 4,
            ..Default::default()
        };
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(2, cfg, false)).unwrap();
        for i in 0..8u32 {
            s.add(i, format!("v{i}")).unwrap(); // 4 size-2 segments = one full bucket
        }
        assert!(s.has_eligible_tier());
    }

    #[test]
    fn compact_merges_only_when_there_is_work() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "b".into()).unwrap(); // 1 segment, no tombstones
        assert_eq!(
            s.compact().unwrap().merges,
            0,
            "a single clean segment: nothing to merge"
        );
        s.delete(1).unwrap();
        assert_eq!(
            s.compact().unwrap().merges,
            1,
            "a tombstone present: merge to purge it"
        );
    }

    #[test]
    fn reclaim_respects_the_live_ratio_threshold() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 4).unwrap();
        for i in 0..12u32 {
            s.add(i, format!("v{i}")).unwrap(); // 3 segments: [0-3] [4-7] [8-11]
        }
        // A: delete 0,1,2 -> 1/4 = 0.25 live. B: delete 4 -> 3/4 = 0.75. C: delete 8,9 -> 2/4 = 0.5.
        for i in [0u32, 1, 2, 4, 8, 9] {
            s.delete(i).unwrap();
        }
        let stats = s.reclaim_tombstones(0.5).unwrap();
        // Only A (0.25 < 0.5) qualifies; C (0.5) is at the threshold, not below; B (0.75) is above.
        assert_eq!(
            stats.merges, 1,
            "only the sub-threshold segment is reclaimed"
        );
        assert_eq!(stats.items_merged, 1, "A's single live item is rewritten");
        assert_eq!(
            s.segment_count(),
            3,
            "A rewritten in place; B and C untouched"
        );
        assert_eq!(s.stored_len(), 1 + 4 + 4, "only A's dead entries dropped");
    }

    #[test]
    fn compact_tiers_persists_across_reopen() {
        let dir = MemoryDirectory::arc();
        let cfg = TierConfig {
            min_merge: 4,
            ..Default::default()
        };
        {
            let mut s =
                SegmentedStore::open_with_options(dir.clone(), Kv, tier_opts(2, cfg, false))
                    .unwrap();
            for i in 0..8u32 {
                s.add(i, format!("v{i}")).unwrap();
            }
            assert_eq!(s.compact_tiers().unwrap().merges, 1);
            assert_eq!(s.segment_count(), 1);
        }
        let s = SegmentedStore::open_with_options(dir, Kv, tier_opts(2, cfg, false)).unwrap();
        assert_eq!(s.segment_count(), 1, "the tier merge was checkpointed");
        assert_eq!(live_multiset(&s).len(), 8);
    }

    #[test]
    fn compact_tiers_without_eligible_bucket_does_not_checkpoint() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 100).unwrap();
        s.add(1, "a".into()).unwrap();
        let e = s.epoch();
        assert_eq!(s.compact_tiers().unwrap().merges, 0);
        assert_eq!(s.epoch(), e, "no merge -> no checkpoint -> epoch unchanged");
    }

    // ---- research failure modes: the cap is the O(N^2) write-amp preventer ----

    #[test]
    fn cap_freezes_large_segments_from_tier_merges() {
        let dir = MemoryDirectory::arc();
        // cap = 8 -> a segment above cap/2 = 4 is frozen out of tier merges, so the
        // biggest segment is never rewritten by tiering (the O(N^2) cliff guard).
        let cfg = TierConfig {
            min_merge: 4,
            max_merged_len: 8,
            ..Default::default()
        };
        let mut s = SegmentedStore::open_with_options(dir, Kv, tier_opts(2, cfg, false)).unwrap();
        for i in 0..8u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        s.force_merge_to(1).unwrap(); // one size-8 segment, now frozen (> cap/2)
        assert_eq!(s.segment_sizes(), vec![8]);
        for i in 8..20u32 {
            s.add(i, format!("v{i}")).unwrap(); // 6 more size-2 segments
        }
        s.compact_tiers().unwrap();
        assert!(
            s.segment_sizes().contains(&8),
            "the frozen segment is never selected for a tier merge"
        );
        for sz in s.segment_sizes() {
            assert!(sz <= cfg.max_merged_len, "no segment exceeds the cap");
        }
        assert_eq!(live_multiset(&s).len(), 20, "no data lost");
    }

    #[test]
    fn without_compaction_fan_out_grows_then_collapses() {
        // The failure mode tiering exists to prevent: with no compaction every
        // flush adds a segment, and a query scans all segments, so fan-out grows
        // linearly with the corpus. Compaction collapses it.
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Kv, 2).unwrap();
        for i in 0..40u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        assert_eq!(
            s.segment_count(),
            20,
            "no compaction: 40 adds / flush 2 = 20 segments to scan per query"
        );
        s.compact_tiers().unwrap();
        assert!(
            s.segment_count() < 20,
            "tiered compaction collapses the fan-out, got {}",
            s.segment_count()
        );
        assert_eq!(live_multiset(&s).len(), 40, "without losing data");
    }

    // ---- concurrent snapshot reads ----

    #[test]
    fn view_reflects_segments_minus_tombstones() {
        let mut s = SegmentedStore::open(MemoryDirectory::arc(), Kv, 2).unwrap();
        for i in 0..6u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        s.delete(2).unwrap();
        s.checkpoint().unwrap(); // commit-visibility: publish to readers
        let v = s.reader().view();
        let mut live: Vec<u32> = Vec::new();
        for seg in v.segments() {
            for (id, _) in seg.iter() {
                if v.is_live(id) {
                    live.push(*id);
                }
            }
        }
        live.sort_unstable();
        assert_eq!(
            live,
            vec![0, 1, 3, 4, 5],
            "view = checkpointed segments minus tombstones"
        );
    }

    #[test]
    fn view_is_a_stable_snapshot_across_writes() {
        let mut s = SegmentedStore::open(MemoryDirectory::arc(), Kv, 2).unwrap();
        for i in 0..6u32 {
            s.add(i, format!("v{i}")).unwrap(); // 3 segments
        }
        s.checkpoint().unwrap(); // publish the 3 segments to readers
        let reader = s.reader();
        let v1 = reader.view();
        let before = v1.segment_count();
        assert_eq!(before, 3);
        // Mutate heavily while v1 is held.
        for i in 6..30u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        s.compact().unwrap();
        assert_eq!(v1.segment_count(), before, "the held view never changes");
        assert_eq!(
            reader.view().segment_count(),
            1,
            "a fresh view sees the compacted state"
        );
    }

    #[test]
    fn unchanged_segments_keep_arc_identity_across_checkpoints() {
        // The point of Arc-internal segments: an unchanged segment keeps its Arc
        // identity across mutations, so a consumer can cache per-segment state keyed
        // by it and rebuild only new segments.
        let mut s = SegmentedStore::open(MemoryDirectory::arc(), Kv, 2).unwrap();
        for i in 0..6u32 {
            s.add(i, format!("v{i}")).unwrap(); // 3 segments
        }
        s.checkpoint().unwrap();
        let r = s.reader();
        let ptrs1: Vec<*const _> = r.view().segments().iter().map(Arc::as_ptr).collect();
        assert_eq!(ptrs1.len(), 3);

        // A no-op checkpoint must keep every segment's identity.
        s.checkpoint().unwrap();
        let ptrs2: Vec<*const _> = r.view().segments().iter().map(Arc::as_ptr).collect();
        assert_eq!(
            ptrs1, ptrs2,
            "a no-op checkpoint keeps all segment identities"
        );

        // Sealing a new segment leaves the originals' identities intact.
        s.add(10, "x".into()).unwrap();
        s.add(11, "y".into()).unwrap(); // seals a 4th segment
        s.checkpoint().unwrap();
        let ptrs3: Vec<*const _> = r.view().segments().iter().map(Arc::as_ptr).collect();
        assert_eq!(ptrs3.len(), 4);
        assert_eq!(
            &ptrs3[..3],
            &ptrs1[..],
            "the original segments keep identity; only the new one is fresh"
        );
    }

    #[test]
    fn segment_ids_align_and_are_stable_across_checkpoint_and_reopen() {
        // The stable-id contract the persist-index hook rests on: ids align 1:1 with
        // segments, an unchanged segment keeps its id (so a persisted-index cache key
        // does not move), and ids survive a restart (unlike the Arc pointer).
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
        for i in 0..6u32 {
            s.add(i, format!("v{i}")).unwrap(); // 3 segments
        }
        s.checkpoint().unwrap();
        assert_eq!(s.segment_ids().len(), s.segments().len());
        assert_eq!(s.segment_ids().len(), 3);
        let ids0: Vec<u64> = s.segment_ids().to_vec();
        // The concurrent View exposes the same ids as the writer.
        assert_eq!(s.reader().view().segment_ids(), &ids0[..]);

        // A no-op checkpoint keeps every id (the cache key must not move on no change).
        s.checkpoint().unwrap();
        assert_eq!(s.segment_ids(), &ids0[..], "no-op checkpoint keeps ids");

        // Sealing a new segment keeps the originals' ids and appends a fresh one.
        s.add(10, "x".into()).unwrap();
        s.add(11, "y".into()).unwrap(); // seals a 4th segment
        s.checkpoint().unwrap();
        assert_eq!(&s.segment_ids()[..3], &ids0[..], "old ids unchanged");
        assert_eq!(s.segment_ids().len(), 4);
        assert!(
            !ids0.contains(&s.segment_ids()[3]),
            "the new segment got a fresh, never-reused id"
        );

        // Ids survive a restart: a consumer keying a persisted index cache on these
        // reloads it instead of rebuilding from the raw payload.
        let before: Vec<u64> = s.segment_ids().to_vec();
        drop(s);
        let s2 = SegmentedStore::open(dir, Kv, 2).unwrap();
        assert_eq!(
            s2.segment_ids(),
            &before[..],
            "segment ids are stable across a restart (persisted in the manifest)"
        );
    }

    #[test]
    fn concurrent_reader_during_writes_stays_consistent() {
        use std::sync::atomic::{AtomicBool, Ordering};
        let mut s = SegmentedStore::open_with_options(
            MemoryDirectory::arc(),
            Kv,
            Options {
                tiering: TierConfig {
                    min_merge: 4,
                    ..Default::default()
                },
                ..Options::new(4)
            },
        )
        .unwrap();
        for i in 0..40u32 {
            s.add(i, format!("v{i}")).unwrap();
        }
        let reader = s.reader();
        let stop = Arc::new(AtomicBool::new(false));
        let stop2 = stop.clone();
        // Reader thread: take views and fully scan them while the writer mutates.
        // Each view is an internally-consistent snapshot, so scanning never panics
        // and never sees a torn segment list.
        let handle = std::thread::spawn(move || {
            let mut iters = 0u64;
            while !stop2.load(Ordering::Relaxed) {
                let v = reader.view();
                let mut count = 0usize;
                for seg in v.segments() {
                    for (id, _) in seg.iter() {
                        if v.is_live(id) {
                            count += 1;
                        }
                    }
                }
                std::hint::black_box(count);
                iters += 1;
            }
            iters
        });
        // Writer: add + compact concurrently with the reader.
        for i in 40..400u32 {
            s.add(i, format!("v{i}")).unwrap();
            if i % 20 == 0 {
                s.compact_tiers().unwrap();
            }
        }
        s.compact().unwrap();
        stop.store(true, Ordering::Relaxed);
        handle.join().unwrap();
        // Final snapshot sees every live item.
        let v = s.reader().view();
        let mut live = 0usize;
        for seg in v.segments() {
            for (id, _) in seg.iter() {
                if v.is_live(id) {
                    live += 1;
                }
            }
        }
        assert_eq!(live, 400, "all 400 items live after the concurrent run");
    }

    // ---- bulk ingest (extend) + harder corruption ----

    #[test]
    fn extend_matches_individual_adds() {
        let mut s1 = SegmentedStore::open(MemoryDirectory::arc(), Kv, 2).unwrap();
        let mut s2 = SegmentedStore::open(MemoryDirectory::arc(), Kv, 2).unwrap();
        for i in 0..20u32 {
            s1.add(i, format!("v{i}")).unwrap();
        }
        s2.extend((0..20u32).map(|i| (i, format!("v{i}")))).unwrap();
        assert_eq!(live_set(&s1), live_set(&s2), "extend == individual adds");
        assert_eq!(s1.segment_count(), s2.segment_count());
    }

    #[test]
    fn extend_is_durable_across_reopen() {
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Kv, 4).unwrap();
            s.extend((0..20u32).map(|i| (i, format!("v{i}")))).unwrap();
        }
        let s = SegmentedStore::open(dir, Kv, 4).unwrap();
        assert_eq!(
            live_set(&s).len(),
            20,
            "the whole batch is durable after sync"
        );
    }

    #[test]
    fn garbled_wal_record_is_caught_by_crc() {
        // Harder than truncation: flip a byte inside a committed WAL record. Each
        // record carries a CRC, so recovery detects the bad record and (BestEffort)
        // stops there -- yielding a consistent PREFIX of the adds, never a panic or
        // a decoded-garbage record. This also documents the interior-corruption
        // behavior: records after the corruption are dropped (treated as a torn tail).
        let root = temp_root("garble-wal");
        {
            let dir = durability::FsDirectory::arc(&root).unwrap();
            let mut s = SegmentedStore::open(dir, Kv, 100).unwrap(); // all in one WAL
            for i in 1..=6u32 {
                s.add(i, format!("v{i}")).unwrap();
            }
        }
        let wal = root.join(wal_path(0));
        let mut bytes = std::fs::read(&wal).unwrap();
        let mid = bytes.len() / 2;
        bytes[mid] ^= 0xFF; // corrupt an interior record
        std::fs::write(&wal, &bytes).unwrap();

        // Recovery is SAFE either way: it returns a hard error (a corrupted length
        // field is not a clean torn tail) OR a consistent contiguous prefix of the
        // adds -- but NEVER a panic, a decoded-garbage id, or the corrupted record.
        // (Which of the two depends on where in the record the byte landed; the
        // safe-behavior invariant is what matters and is what we assert.)
        let dir = durability::FsDirectory::arc(&root).unwrap();
        match SegmentedStore::open(dir, Kv, 100) {
            Ok(s2) => {
                let mut live: Vec<u32> = live_set(&s2).into_iter().map(|(id, _)| id).collect();
                live.sort_unstable();
                assert!(
                    live.len() < 6,
                    "the corrupted record + tail are dropped: {live:?}"
                );
                assert_eq!(
                    live,
                    (1..=live.len() as u32).collect::<Vec<_>>(),
                    "survivors are the contiguous prefix before the corruption: {live:?}"
                );
            }
            Err(_) => { /* hard fault on corruption: acceptable, never garbage */ }
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    // ---- property-based: random op sequences vs a reference model ----

    use proptest::prelude::*;

    /// An op applied to both the store and a reference model. `Add` uses a fresh
    /// unique id (re-adds are covered by
    /// `re_adds_are_last_write_wins_under_random_ops`); `Delete` targets the k-th
    /// currently-live id.
    #[derive(Debug, Clone)]
    enum SimOp {
        Add,
        Delete(usize),
        Compact,
        CompactTiers,
        Reopen,
    }

    fn op_strategy() -> impl Strategy<Value = SimOp> {
        prop_oneof![
            3 => Just(SimOp::Add),
            2 => (0usize..100).prop_map(SimOp::Delete),
            1 => Just(SimOp::Compact),
            1 => Just(SimOp::CompactTiers),
            1 => Just(SimOp::Reopen),
        ]
    }

    #[derive(Debug, Clone)]
    enum CatalogOp {
        Add,
        Delete(usize),
        Checkpoint,
        Compact,
        CompactTiers,
        Reopen,
    }

    fn catalog_op_strategy() -> impl Strategy<Value = CatalogOp> {
        prop_oneof![
            3 => Just(CatalogOp::Add),
            2 => (0usize..100).prop_map(CatalogOp::Delete),
            2 => Just(CatalogOp::Checkpoint),
            1 => Just(CatalogOp::Compact),
            1 => Just(CatalogOp::CompactTiers),
            1 => Just(CatalogOp::Reopen),
        ]
    }

    fn catalog_expectation(
        s: &SegmentedStore<Kv>,
    ) -> (u64, u64, Vec<u64>, std::collections::HashSet<u32>) {
        (
            s.epoch,
            s.next_seg_id,
            s.segment_ids.clone(),
            s.tombstones.clone(),
        )
    }

    #[test]
    fn full_compaction_can_exceed_tier_cap_and_stays_frozen_after_reopen() {
        for count in [64u32, 65, 66] {
            let dir = MemoryDirectory::arc();
            let cfg = TierConfig {
                min_merge: 4,
                max_merge: 8,
                max_merged_len: 64,
                ..Default::default()
            };
            let options = || Options {
                tiering: cfg,
                ..Options::new(3)
            };
            let mut s = SegmentedStore::open_with_options(dir.clone(), Kv, options()).unwrap();
            let expected: Vec<_> = (0..count).map(|id| (id, format!("v{id}"))).collect();
            for (id, value) in &expected {
                s.add(*id, value.clone()).unwrap();
            }
            s.compact().unwrap();
            assert_eq!(s.segment_sizes(), vec![count as usize]);
            assert_eq!(live_set(&s), expected);
            let frozen_id = s.segment_ids()[0];
            assert_eq!(s.compact_tiers().unwrap().merges, 0);
            assert_eq!(s.segment_ids(), &[frozen_id]);
            assert_eq!(live_set(&s), expected);
            drop(s);
            let mut s = SegmentedStore::open_with_options(dir, Kv, options()).unwrap();
            assert_eq!(s.segment_sizes(), vec![count as usize]);
            assert_eq!(s.segment_ids(), &[frozen_id]);
            assert_eq!(live_set(&s), expected);
            assert_eq!(s.compact_tiers().unwrap().merges, 0);
            assert_eq!(s.segment_ids(), &[frozen_id]);
            assert_eq!(live_set(&s), expected);
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(512))]
        /// For any sequence of add/delete/compact/compact_tiers/reopen, the live set
        /// equals the reference model. Only full compaction may create over-cap
        /// segments; other operations may retain those frozen segments without growing them.
        #[test]
        fn live_set_matches_reference_under_random_ops(
            ops in proptest::collection::vec(op_strategy(), 0..200)
        ) {
            let dir = MemoryDirectory::arc();
            let cfg = TierConfig {
                min_merge: 4,
                max_merge: 8,
                max_merged_len: 64,
                ..Default::default()
            };
            let mk = || Options { tiering: cfg, ..Options::new(3) };
            let mut s = SegmentedStore::open_with_options(dir.clone(), Kv, mk()).unwrap();
            let mut model: std::collections::BTreeMap<u32, String> = Default::default();
            let mut live_ids: Vec<u32> = Vec::new();
            let mut next_id = 0u32;
            for op in ops {
                let oversized: std::collections::BTreeMap<_, _> = s.segment_ids().iter()
                    .copied().zip(s.segment_sizes())
                    .filter(|&(_, size)| size > cfg.max_merged_len).collect();
                let full_compaction = matches!(op, SimOp::Compact);
                match op {
                    SimOp::Add => {
                        let id = next_id;
                        next_id += 1;
                        let v = format!("v{id}");
                        s.add(id, v.clone()).unwrap();
                        model.insert(id, v);
                        live_ids.push(id);
                    }
                    SimOp::Delete(k) => {
                        if !live_ids.is_empty() {
                            let id = live_ids.swap_remove(k % live_ids.len());
                            s.delete(id).unwrap();
                            model.remove(&id);
                        }
                    }
                    SimOp::Compact => {
                        s.compact().unwrap();
                    }
                    SimOp::CompactTiers => {
                        s.compact_tiers().unwrap();
                    }
                    SimOp::Reopen => {
                        s = SegmentedStore::open_with_options(dir.clone(), Kv, mk()).unwrap();
                    }
                }
                if !full_compaction {
                    for (&id, size) in s.segment_ids().iter().zip(s.segment_sizes()) {
                        prop_assert!(size <= cfg.max_merged_len
                            || oversized.get(&id).is_some_and(|&before| size <= before));
                    }
                }
                // segment_ids must stay aligned 1:1 with segments under every op,
                // including across Reopen (the persist-index cache key invariant).
                prop_assert_eq!(s.segment_ids().len(), s.segment_count());
            }
            let want: Vec<(u32, String)> = model.into_iter().collect();
            prop_assert_eq!(live_set(&s), want);
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]
        /// The catalog is a manifest reader: it tracks the last checkpointed
        /// segment ids/tombstones exactly, while ignoring WAL-only suffix records.
        #[test]
        fn segment_catalog_matches_last_checkpoint_under_random_ops(
            ops in proptest::collection::vec(catalog_op_strategy(), 0..160)
        ) {
            let dir = MemoryDirectory::arc();
            let cfg = TierConfig {
                min_merge: 4,
                max_merge: 8,
                max_merged_len: 64,
                ..Default::default()
            };
            let mk = || Options { tiering: cfg, ..Options::new(3) };
            let mut s = SegmentedStore::open_with_options(dir.clone(), Kv, mk()).unwrap();
            let mut checkpointed = catalog_expectation(&s);
            let mut live_ids: Vec<u32> = Vec::new();
            let mut next_id = 0u32;

            for op in ops {
                match op {
                    CatalogOp::Add => {
                        let id = next_id;
                        next_id += 1;
                        s.add(id, format!("v{id}")).unwrap();
                        live_ids.push(id);
                    }
                    CatalogOp::Delete(k) => {
                        if !live_ids.is_empty() {
                            let id = live_ids.swap_remove(k % live_ids.len());
                            s.delete(id).unwrap();
                        }
                    }
                    CatalogOp::Checkpoint => {
                        s.checkpoint().unwrap();
                        checkpointed = catalog_expectation(&s);
                    }
                    CatalogOp::Compact => {
                        s.compact().unwrap();
                        checkpointed = catalog_expectation(&s);
                    }
                    CatalogOp::CompactTiers => {
                        if s.compact_tiers().unwrap().merges > 0 {
                            checkpointed = catalog_expectation(&s);
                        }
                    }
                    CatalogOp::Reopen => {
                        s = SegmentedStore::open_with_options(dir.clone(), Kv, mk()).unwrap();
                    }
                }

                let catalog = SegmentCatalog::<u32>::open(dir.clone()).unwrap();
                prop_assert_eq!(catalog.epoch(), checkpointed.0);
                prop_assert_eq!(catalog.next_segment_id(), checkpointed.1);
                prop_assert_eq!(catalog.segment_ids(), &checkpointed.2[..]);
                prop_assert_eq!(catalog.segment_count(), checkpointed.2.len());
                prop_assert_eq!(catalog.tombstone_count(), checkpointed.3.len());
                for id in 0..next_id {
                    prop_assert_eq!(catalog.is_live(&id), !checkpointed.3.contains(&id));
                }
                for &seg_id in catalog.segment_ids() {
                    prop_assert_eq!(catalog.segment_name(seg_id).unwrap(), seg_path(seg_id));
                    prop_assert!(catalog.open_segment_file(seg_id).is_ok());
                    let _: Vec<(u32, String)> = catalog.read_segment(seg_id).unwrap();
                }
                prop_assert!(matches!(
                    catalog.segment_name(u64::MAX),
                    Err(PersistenceError::NotFound(_))
                ));
            }
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(128))]
        /// Any single-byte manifest corruption must be detected before the
        /// catalog exposes segment ids or tombstones.
        #[test]
        fn segment_catalog_rejects_manifest_corruption_at_any_byte(offset in 0usize..256) {
            use std::io::Read;

            let dir = MemoryDirectory::arc();
            {
                let mut s = SegmentedStore::open(dir.clone(), Kv, 2).unwrap();
                s.add(1, "a".into()).unwrap();
                s.add(2, "b".into()).unwrap();
                s.delete(1).unwrap();
                s.checkpoint().unwrap();
            }

            let mut file = dir.open_file(MANIFEST_PATH).unwrap();
            let mut bytes = Vec::new();
            file.read_to_end(&mut bytes).unwrap();
            let header_len = durability::checkpoint::CheckpointHeader::SIZE;
            prop_assume!(bytes.len() > header_len);
            let i = header_len + (offset % (bytes.len() - header_len));
            bytes[i] ^= 0x80;
            dir.atomic_write(MANIFEST_PATH, &bytes).unwrap();

            prop_assert!(
                SegmentCatalog::<u32>::open(dir).is_err(),
                "corrupt manifest byte {i} was accepted"
            );
        }
    }

    // ---- re-add replaces: the newest copy of an id wins everywhere ----

    type Dkv = DefaultStore<u32, String>;

    // The per-copy liveness check a consumer applies while scanning one sealed
    // segment: tombstoned ids AND copies superseded by a newer add are dead.
    fn writer_copy_live(s: &SegmentedStore<Dkv>, seg: u64, id: &u32) -> bool {
        s.is_live_in(seg, id)
    }
    fn view_copy_live(v: &View<Dkv>, seg: u64, id: &u32) -> bool {
        v.is_live_in(seg, id)
    }
    fn catalog_copy_live(c: &SegmentCatalog<u32>, seg: u64, id: &u32) -> bool {
        c.is_live_in(seg, id)
    }

    /// Every live (id, value) a consumer sees through the writer: sealed
    /// segments filtered per copy, plus the buffer.
    fn writer_latest(s: &SegmentedStore<Dkv>) -> Vec<(u32, String)> {
        let mut out = Vec::new();
        for (seg, &seg_id) in s.segments().iter().zip(s.segment_ids()) {
            for (id, v) in seg.iter() {
                if writer_copy_live(s, seg_id, id) {
                    out.push((*id, v.clone()));
                }
            }
        }
        for (id, v) in s.buffer() {
            if s.is_live(id) {
                out.push((*id, v.clone()));
            }
        }
        out.sort();
        out
    }

    fn view_latest(v: &View<Dkv>) -> Vec<(u32, String)> {
        let mut out = Vec::new();
        for (seg, &seg_id) in v.segments().iter().zip(v.segment_ids()) {
            for (id, val) in seg.iter() {
                if view_copy_live(v, seg_id, id) {
                    out.push((*id, val.clone()));
                }
            }
        }
        out.sort();
        out
    }

    fn catalog_latest(dir: Arc<dyn Directory>) -> Vec<(u32, String)> {
        let c = SegmentCatalog::<u32>::open(dir).unwrap();
        let mut out = Vec::new();
        for &seg_id in c.segment_ids() {
            let seg: Vec<(u32, String)> = c.read_segment(seg_id).unwrap();
            for (id, val) in seg {
                if catalog_copy_live(&c, seg_id, &id) {
                    out.push((id, val));
                }
            }
        }
        out.sort();
        out
    }

    fn kv(pairs: &[(u32, &str)]) -> Vec<(u32, String)> {
        pairs.iter().map(|&(id, v)| (id, v.to_string())).collect()
    }

    /// Seal [(1,a),(2,x)], then re-add 1 and seal [(1,b),(3,y)].
    fn re_add_across_segments(dir: Arc<dyn Directory>) -> SegmentedStore<Dkv> {
        let mut s = SegmentedStore::open(dir, Dkv::new(), 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "x".into()).unwrap();
        s.add(1, "b".into()).unwrap();
        s.add(3, "y".into()).unwrap();
        assert_eq!(s.segment_count(), 2, "both batches sealed");
        s
    }

    #[test]
    fn re_add_after_flush_replaces_the_sealed_copy_in_a_view() {
        let dir = MemoryDirectory::arc();
        let mut s = re_add_across_segments(dir);
        let want = kv(&[(1, "b"), (2, "x"), (3, "y")]);
        assert_eq!(writer_latest(&s), want, "writer sees only the newest copy");
        s.checkpoint().unwrap();
        assert_eq!(view_latest(&s.reader().view()), want, "view too");
    }

    #[test]
    fn live_segment_of_names_the_segment_a_re_add_will_supersede() {
        let dir = MemoryDirectory::arc();
        let mut s = re_add_across_segments(dir);
        let (seg0, seg1) = (s.segment_ids()[0], s.segment_ids()[1]);
        assert_eq!(s.live_segment_of(&1), Some(seg1));
        assert_eq!(s.live_segment_of(&2), Some(seg0));
        s.add(2, "q".into()).unwrap();
        assert_eq!(s.live_segment_of(&2), None, "buffered");
        assert!(!s.is_live_in(seg0, &2));
        s.delete(3).unwrap();
        assert_eq!(s.live_segment_of(&3), None, "deleted");
        assert_eq!(s.live_segment_of(&9), None, "absent");
        s.compact().unwrap();
        let merged = s.segment_ids()[0];
        assert_eq!(s.live_segment_of(&1), Some(merged));
        assert_eq!(s.live_segment_of(&2), Some(merged));
        let s = SegmentedStore::open(MemoryDirectory::arc(), OpaqueKv, 1).unwrap();
        assert_eq!(s.live_segment_of(&1), None, "untracked store");
    }

    #[test]
    fn re_add_within_the_buffer_keeps_one_copy() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Dkv::new(), 100).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(1, "b".into()).unwrap();
        assert_eq!(s.buffer(), &kv(&[(1, "b")])[..]);
    }

    #[test]
    fn re_add_survives_checkpoint_and_reopen() {
        let dir = MemoryDirectory::arc();
        {
            let mut s = re_add_across_segments(dir.clone());
            s.checkpoint().unwrap();
        }
        let want = kv(&[(1, "b"), (2, "x"), (3, "y")]);
        assert_eq!(catalog_latest(dir.clone()), want, "manifest-only reader");
        let s = SegmentedStore::open(dir, Dkv::new(), 2).unwrap();
        assert_eq!(writer_latest(&s), want, "reopened writer");
        assert_eq!(view_latest(&s.reader().view()), want, "reopened view");
    }

    #[test]
    fn re_add_survives_wal_only_reopen() {
        let dir = MemoryDirectory::arc();
        {
            let mut s = SegmentedStore::open(dir.clone(), Dkv::new(), 2).unwrap();
            s.add(1, "a".into()).unwrap();
            s.add(2, "x".into()).unwrap();
            s.checkpoint().unwrap(); // (1,a) is in a persisted segment
            s.add(1, "b".into()).unwrap(); // the re-add lives only in the WAL
        }
        let mut s = SegmentedStore::open(dir.clone(), Dkv::new(), 2).unwrap();
        assert_eq!(writer_latest(&s), kv(&[(1, "b"), (2, "x")]));
        // Replay that seals the re-add into a segment behaves the same.
        s.add(3, "y".into()).unwrap();
        drop(s);
        let mut s = SegmentedStore::open(dir.clone(), Dkv::new(), 2).unwrap();
        let want = kv(&[(1, "b"), (2, "x"), (3, "y")]);
        assert_eq!(writer_latest(&s), want);
        s.checkpoint().unwrap();
        assert_eq!(view_latest(&s.reader().view()), want);
        assert_eq!(catalog_latest(dir), want);
    }

    #[test]
    fn delete_after_re_add_removes_every_copy_and_a_later_add_does_not_revive_them() {
        let dir = MemoryDirectory::arc();
        let mut s = re_add_across_segments(dir.clone());
        s.delete(1).unwrap();
        assert_eq!(writer_latest(&s), kv(&[(2, "x"), (3, "y")]));
        s.checkpoint().unwrap();
        // Re-adding after the delete must not bring back (1,a) or (1,b).
        s.add(1, "c".into()).unwrap();
        s.add(4, "z".into()).unwrap();
        let want = kv(&[(1, "c"), (2, "x"), (3, "y"), (4, "z")]);
        assert_eq!(writer_latest(&s), want);
        s.checkpoint().unwrap();
        assert_eq!(view_latest(&s.reader().view()), want);
        assert_eq!(catalog_latest(dir.clone()), want);
        drop(s);
        let s = SegmentedStore::open(dir, Dkv::new(), 2).unwrap();
        assert_eq!(writer_latest(&s), want);
    }

    #[test]
    fn full_compaction_keeps_only_the_newest_copy() {
        let dir = MemoryDirectory::arc();
        let mut s = re_add_across_segments(dir.clone());
        s.compact().unwrap();
        assert_eq!(s.segment_count(), 1);
        let mut physical: Vec<(u32, String)> = s.segments()[0].as_ref().clone();
        physical.sort();
        assert_eq!(physical, kv(&[(1, "b"), (2, "x"), (3, "y")]));
    }

    #[test]
    fn partial_merge_keeps_only_the_newest_copy() {
        let dir = MemoryDirectory::arc();
        let mut s = re_add_across_segments(dir.clone());
        s.add(4, "z".into()).unwrap();
        s.add(5, "w".into()).unwrap(); // third segment, left out of the merge below
                                       // Merge the two smallest-first segments: the old and the new copy of 1.
        s.force_merge_to(2).unwrap();
        assert_eq!(s.segment_count(), 2);
        let all: Vec<(u32, String)> = s
            .segments()
            .iter()
            .flat_map(|g| g.iter().cloned())
            .collect();
        let copies_of_1 = all.iter().filter(|(id, _)| *id == 1).count();
        assert_eq!(
            copies_of_1, 1,
            "merged output dropped the stale copy: {all:?}"
        );
        let want = kv(&[(1, "b"), (2, "x"), (3, "y"), (4, "z"), (5, "w")]);
        assert_eq!(writer_latest(&s), want);
        drop(s);
        let s = SegmentedStore::open(dir, Dkv::new(), 2).unwrap();
        assert_eq!(writer_latest(&s), want);
    }

    #[test]
    fn merge_that_skips_the_newest_copy_drops_the_stale_one() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir.clone(), Dkv::new(), 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "x".into()).unwrap(); // seg 0: stale (1,a)
        s.add(3, "y".into()).unwrap();
        s.add(4, "z".into()).unwrap(); // seg 1
        s.add(1, "b".into()).unwrap();
        s.add(5, "w".into()).unwrap(); // seg 2: newest (1,b)
        s.add(6, "v".into()).unwrap();
        s.add(7, "u".into()).unwrap();
        s.add(8, "t".into()).unwrap(); // seg 3, plus (8,t) sealed by the checkpoint
        s.checkpoint().unwrap();
        // Merge seg 0 with seg 1 only: the merged output (a NEWER segment id than
        // seg 2) must not carry the stale (1,a) forward.
        let merged = s.merge_group(vec![0, 1]).unwrap();
        assert_eq!(merged, 3);
        s.checkpoint().unwrap();
        let want = kv(&[
            (1, "b"),
            (2, "x"),
            (3, "y"),
            (4, "z"),
            (5, "w"),
            (6, "v"),
            (7, "u"),
            (8, "t"),
        ]);
        assert_eq!(writer_latest(&s), want);
        assert_eq!(catalog_latest(dir.clone()), want);
        drop(s);
        let s = SegmentedStore::open(dir, Dkv::new(), 2).unwrap();
        assert_eq!(writer_latest(&s), want);
    }

    #[test]
    fn reclaim_counts_superseded_copies_as_dead() {
        let dir = MemoryDirectory::arc();
        let mut s = SegmentedStore::open(dir, Dkv::new(), 2).unwrap();
        s.add(1, "a".into()).unwrap();
        s.add(2, "x".into()).unwrap();
        s.add(1, "b".into()).unwrap();
        s.add(2, "y".into()).unwrap(); // both copies in seg 0 are now stale
        let amp = s.space_amplification().unwrap();
        assert!((amp - 2.0).abs() < 1e-9, "4 stored / 2 live, got {amp}");
        s.reclaim_tombstones(0.5).unwrap();
        assert_eq!(s.stored_len(), 2, "the dead segment was rewritten away");
        assert_eq!(writer_latest(&s), kv(&[(1, "b"), (2, "y")]));
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]
        /// Last-write-wins under random re-adds, deletes, checkpoints, merges, and
        /// reopens: writer, view, and catalog all agree with a map model.
        #[test]
        fn re_adds_are_last_write_wins_under_random_ops(
            ops in proptest::collection::vec((0u8..6, 0u32..12), 0..160)
        ) {
            let dir = MemoryDirectory::arc();
            let cfg = TierConfig { min_merge: 2, max_merge: 4, max_merged_len: 64, ..Default::default() };
            let mk = || Options { tiering: cfg, ..Options::new(3) };
            let mut s = SegmentedStore::open_with_options(dir.clone(), Dkv::new(), mk()).unwrap();
            let mut model: std::collections::BTreeMap<u32, String> = Default::default();
            let mut committed = model.clone();
            for (step, (op, id)) in ops.into_iter().enumerate() {
                match op {
                    0 | 1 => {
                        let v = format!("v{step}");
                        s.add(id, v.clone()).unwrap();
                        model.insert(id, v);
                    }
                    2 => {
                        s.delete(id).unwrap();
                        model.remove(&id);
                    }
                    3 => {
                        s.checkpoint().unwrap();
                        committed = model.clone();
                    }
                    4 => {
                        if id % 2 == 0 {
                            s.compact().unwrap();
                        } else {
                            s.compact_tiers().unwrap();
                        }
                        s.checkpoint().unwrap();
                        committed = model.clone();
                    }
                    _ => {
                        s = SegmentedStore::open_with_options(dir.clone(), Dkv::new(), mk()).unwrap();
                    }
                }
                let want: Vec<(u32, String)> = model.clone().into_iter().collect();
                prop_assert_eq!(writer_latest(&s), want);
                let want_committed: Vec<(u32, String)> = committed.clone().into_iter().collect();
                prop_assert_eq!(view_latest(&s.reader().view()), want_committed.clone());
                prop_assert_eq!(catalog_latest(dir.clone()), want_committed);
            }
        }
    }
}