surrealkv 0.21.0

A low-level, versioned, embedded, ACID-compliant, key-value database for Rust
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
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
use std::path::PathBuf;
use std::sync::Arc;

use tempdir::TempDir;
use test_log::test;

use crate::compaction::leveled::Strategy;
use crate::levels::{validate_wal_log_number, LevelManifest};
use crate::lsm::{CompactionOperations, Core, CoreInner};
use crate::test::collect_transaction_all;
use crate::wal::list_segment_ids;
use crate::{
	Error,
	InternalKeyKind,
	Key,
	LSMIterator,
	Options,
	Tree,
	TreeBuilder,
	Value,
	WalRecoveryMode,
};

fn create_temp_directory() -> TempDir {
	TempDir::new("test").unwrap()
}

/// Creates test options with common defaults, allowing customization of
/// specific fields
fn create_test_options(path: PathBuf, customizations: impl FnOnce(&mut Options)) -> Arc<Options> {
	let mut opts = Options {
		path,
		vlog_value_threshold: 0,
		..Default::default()
	};
	customizations(&mut opts);
	Arc::new(opts)
}

/// Creates test options optimized for small memtable testing (triggers
/// frequent flushes)
fn create_small_memtable_options(path: PathBuf) -> Arc<Options> {
	create_test_options(path, |opts| {
		opts.max_memtable_size = 64 * 1024; // 64KB
	})
}

/// Creates test options optimized for VLog testing
fn create_vlog_test_options(path: PathBuf) -> Arc<Options> {
	create_test_options(path, |opts| {
		opts.max_memtable_size = 64 * 1024; // 64KB
		opts.vlog_max_file_size = 1024 * 1024; // 1MB
	})
}

/// Creates test options optimized for VLog compaction testing
fn create_vlog_compaction_options(path: PathBuf) -> Arc<Options> {
	create_test_options(path, |opts| {
		opts.max_memtable_size = 64 * 1024; // 64KB
		opts.vlog_max_file_size = 950; // Small size to force frequent rotations
		opts.level_count = 2; // Two levels for compaction strategy
	})
}

#[test(tokio::test)]
async fn test_tree_basic() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let tree = Tree::new(create_test_options(path.clone(), |_| {})).unwrap();

	// Insert a key-value pair
	let key = "hello";
	let value = "world";
	let mut txn = tree.begin().unwrap();
	txn.set(key.as_bytes(), value.as_bytes()).unwrap();
	txn.commit().await.unwrap();

	// Read back the key-value pair
	let txn = tree.begin().unwrap();
	let result = txn.get(key.as_bytes()).unwrap().unwrap();
	assert_eq!(result, value.as_bytes().to_vec());
}

#[test(tokio::test)]
async fn test_memtable_flush() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |_| {});

	let key = "hello";
	let values = ["world", "universe", "everyone", "planet"];

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert the same key multiple times with different values
	for value in values.iter() {
		// Insert key-value pair in a new transaction
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Ensure the active memtable is flushed to disk
	tree.flush().unwrap();

	{
		// Read back the key-value pair
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap().unwrap();
		let expected_value = values.last().unwrap();
		assert_eq!(result, expected_value.as_bytes().to_vec());
	}
}

#[test(tokio::test)]
async fn test_memtable_flush_with_delete() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |_| {});

	let key = "hello";
	let values = ["world", "universe", "everyone"];

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert the same key multiple times with different values
	for value in values.iter() {
		// Insert key-value pair in a new transaction
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Delete the key
	{
		let mut txn = tree.begin().unwrap();
		txn.delete(key.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Ensure the active memtable is flushed to disk
	tree.flush().unwrap();

	{
		// Read back the key-value pair
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();
		assert!(result.is_none(), "Expected key to be deleted");
	}
}

#[test(tokio::test)]
async fn test_memtable_flush_with_multiple_keys_and_updates() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Set a reasonable memtable size to trigger multiple flushes
	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Number of keys to insert
	const KEY_COUNT: usize = 10001;
	// Number of updates per key
	const UPDATES_PER_KEY: usize = 2;

	// Track the latest value for each key for verification
	let mut expected_values = Vec::with_capacity(KEY_COUNT);

	// Insert each key with multiple updates
	for i in 0..KEY_COUNT {
		let key = format!("key_{i:05}");
		for update in 0..UPDATES_PER_KEY {
			let value = format!("value_{i:05}_update_{update}");

			// Save the final value for verification
			if update == UPDATES_PER_KEY - 1 {
				expected_values.push((key.clone(), value.clone()));
			}

			// Insert in a new transaction
			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}
	}

	// Final flush to ensure all data is on disk
	tree.flush().unwrap();

	// Verify all keys have their final values
	for (key, expected_value) in expected_values {
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap().unwrap();
		assert_eq!(
			result,
			expected_value.as_bytes().to_vec(),
			"Key '{key}' should have final value '{expected_value}'"
		);
	}

	// Verify the LSM state: we should have multiple SSTables
	let l0_size = tree.core.level_manifest.read().unwrap().levels.get_levels()[0].tables.len();
	assert!(l0_size > 0, "Expected SSTables in L0, got {l0_size}");
}

#[test(tokio::test)]
async fn test_persistence() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Set a reasonable memtable size to trigger multiple flushes
	let opts = create_test_options(path.clone(), |opts| {
		opts.vlog_max_file_size = 10;
	});

	// Number of keys to insert
	const KEY_COUNT: usize = 100;
	// Number of updates per key
	const UPDATES_PER_KEY: usize = 1;

	// Track the latest value for each key for verification
	let expected_values: Vec<(String, String)>;

	// Step 1: Insert data and close the store
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut values = Vec::with_capacity(KEY_COUNT);

		// Insert each key with multiple updates
		for i in 0..KEY_COUNT {
			let key = format!("key_{i:05}");
			for update in 0..UPDATES_PER_KEY {
				let value = format!("value_{i:05}_update_{update}");

				// Save the final value for verification
				if update == UPDATES_PER_KEY - 1 {
					values.push((key.clone(), value.clone()));
				}

				// Insert in a new transaction
				let mut txn = tree.begin().unwrap();
				txn.set(key.as_bytes(), value.as_bytes()).unwrap();
				txn.commit().await.unwrap();
			}
		}

		// Final flush to ensure all data is on disk
		tree.flush().unwrap();

		// Store values for later verification
		expected_values = values;

		// Verify L0 has tables before closing
		let l0_size = tree.core.level_manifest.read().unwrap().levels.get_levels()[0].tables.len();
		assert!(l0_size > 0, "Expected SSTables in L0 before closing, got {l0_size}");

		// Tree will be dropped here, closing the store
		tree.close().await.unwrap();
	}

	// Step 2: Reopen the store and verify data
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify L0 has tables after reopening
		let l0_size = tree.core.level_manifest.read().unwrap().levels.get_levels()[0].tables.len();
		assert!(l0_size > 0, "Expected SSTables in L0 after reopening, got {l0_size}");

		// Verify all keys have their final values
		for (key, expected_value) in expected_values.iter() {
			let txn = tree.begin().unwrap();
			let result = txn.get(key.as_bytes()).unwrap();

			assert!(result.is_some(), "Key '{key}' not found after reopening store");

			let value = result.unwrap();
			assert_eq!(
				value,
				expected_value.as_bytes().to_vec(),
				"Key '{}' has incorrect value after reopening. Expected '{}', got '{:?}'",
				key,
				expected_value,
				std::str::from_utf8(value.as_ref()).unwrap_or("<invalid utf8>")
			);
		}
	}
}

#[test(tokio::test)]
async fn test_checkpoint_functionality() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	// Create initial data
	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert some test data
	for i in 0..10 {
		let key = format!("key_{i:03}");
		let value = format!("value_{i:03}");

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush to ensure data is on disk
	tree.flush().unwrap();

	// Create checkpoint
	let checkpoint_dir = temp_dir.path().join("checkpoint");
	let metadata = tree.create_checkpoint(&checkpoint_dir).unwrap();

	// Verify checkpoint metadata and structure
	assert!(metadata.timestamp > 0);
	assert_eq!(metadata.sequence_number, 10);
	assert_eq!(metadata.sstable_count, 1);
	assert!(metadata.total_size > 0);

	assert!(checkpoint_dir.exists());
	assert!(checkpoint_dir.join("sstables").exists());
	assert!(checkpoint_dir.join("wal").exists());
	assert!(checkpoint_dir.join("manifest").exists());
	assert!(checkpoint_dir.join("CHECKPOINT_METADATA").exists());

	// Insert more data after checkpoint
	for i in 10..15 {
		let key = format!("key_{i:03}");
		let value = format!("value_{i:03}");

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush to ensure the new data is also on disk
	tree.flush().unwrap();

	// Verify all data exists before restore
	for i in 0..15 {
		let key = format!("key_{i:03}");
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key '{key}' should exist before restore");
	}

	// Restore from checkpoint
	tree.restore_from_checkpoint(&checkpoint_dir).unwrap();

	// Verify data is restored to checkpoint state (keys 0-9 exist, 10-14 don't)
	for i in 0..10 {
		let key = format!("key_{i:03}");
		let expected_value = format!("value_{i:03}");

		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key '{key}' should exist after restore");
		assert_eq!(result.unwrap(), expected_value.as_bytes().to_vec());
	}

	// Verify the newer keys don't exist after restore
	for i in 10..15 {
		let key = format!("key_{i:03}");

		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();
		assert!(result.is_none(), "Key '{key}' should not exist after restore");
	}
}

#[test(tokio::test)]
async fn test_checkpoint_restore_discards_pending_writes() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	// Create initial data and checkpoint
	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert initial data
	for i in 0..5 {
		let key = format!("key_{i:03}");
		let value = format!("checkpoint_value_{i:03}");

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush to ensure data is on disk
	tree.flush().unwrap();

	// Create checkpoint
	let checkpoint_dir = temp_dir.path().join("checkpoint");
	let metadata = tree.create_checkpoint(&checkpoint_dir).unwrap();
	assert_eq!(metadata.sequence_number, 5);

	// Insert NEW data that should be discarded during restore
	for i in 0..5 {
		let key = format!("key_{i:03}");
		let value = format!("pending_value_{i:03}"); // Different values

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Verify the pending writes are in memory but not yet flushed
	for i in 0..5 {
		let key = format!("key_{i:03}");
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap().unwrap();
		assert_eq!(
			result,
			format!("pending_value_{i:03}").as_bytes().to_vec(),
			"Expected pending value before restore"
		);
	}

	// Restore from checkpoint - this should discard pending writes
	tree.restore_from_checkpoint(&checkpoint_dir).unwrap();

	// Verify data is restored to checkpoint state (NOT the pending writes)
	for i in 0..5 {
		let key = format!("key_{i:03}");
		let expected_value = format!("checkpoint_value_{i:03}");

		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap().unwrap();
		assert_eq!(
			result,
			expected_value.as_bytes().to_vec(),
			"Key '{key}' should have checkpoint value '{expected_value}', not pending value"
		);
	}
}

#[test(tokio::test)]
async fn test_simple_range_seek() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert simple keys
	let keys = ["a", "b", "c", "d", "e"];
	for key in keys.iter() {
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), key.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Test range scan BEFORE flushing (should work from memtables)
	let txn = tree.begin().unwrap();
	let range_before_flush = collect_transaction_all(&mut txn.range(b"a", b"d").unwrap()).unwrap();

	// Should return keys "a", "b", "c" ([a, d) range)
	assert_eq!(range_before_flush.len(), 3, "Range scan before flush should return 3 items");

	// Verify the keys and values are correct
	let expected_before = [("a", "a"), ("b", "b"), ("c", "c")];
	for (idx, (key, value)) in range_before_flush.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();
		assert_eq!(key_str, expected_before[idx].0, "Key mismatch at index {idx} before flush");
		assert_eq!(value_str, expected_before[idx].1, "Value mismatch at index {idx} before flush");
	}

	// Force flush to ensure data is on disk
	tree.flush().unwrap();

	// Test range scan AFTER flushing (should work from SSTables)
	let txn = tree.begin().unwrap();
	let range_after_flush = collect_transaction_all(&mut txn.range(b"a", b"d").unwrap()).unwrap();

	// Should return the same keys after flush
	assert_eq!(range_after_flush.len(), 3, "Range scan after flush should return 3 items");

	// Verify the keys and values are still correct after flush
	let expected_after = [("a", "a"), ("b", "b"), ("c", "c")];
	for (idx, (key, value)) in range_after_flush.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();
		assert_eq!(key_str, expected_after[idx].0, "Key mismatch at index {idx} after flush");
		assert_eq!(value_str, expected_after[idx].1, "Value mismatch at index {idx} after flush");
	}

	// Test individual gets
	for key in ["a", "b", "c"].iter() {
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();

		assert!(result.is_some(), "Key '{key}' should be found");
		let value = result.unwrap();
		let value_str = std::str::from_utf8(value.as_ref()).unwrap();
		assert_eq!(value_str, *key, "Value for key '{key}' should match the key");
	}

	// Verify that the results are identical before and after flush
	assert_eq!(
		range_before_flush, range_after_flush,
		"Range scan results should be identical before and after flush"
	);
}

#[test(tokio::test)]
async fn test_large_range_scan() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert 10,000 items with zero-padded keys for consistent ordering
	const TOTAL_ITEMS: usize = 10_000;
	let mut expected_items = Vec::with_capacity(TOTAL_ITEMS);

	for i in 0..TOTAL_ITEMS {
		let key = format!("key_{i:06}");
		let value = format!("value_{:06}_content_data_{}", i, i * 2);

		expected_items.push((key.clone(), value.clone()));

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush to ensure all data is on disk
	tree.flush().unwrap();

	// Test 1: Full range scan - should return all 10k items in order
	let start_key = "key_000000".as_bytes();
	let end_key = "key_999999".as_bytes();

	let txn = tree.begin().unwrap();
	let range_result =
		collect_transaction_all(&mut txn.range(start_key, end_key).unwrap()).unwrap();

	assert_eq!(
		range_result.len(),
		TOTAL_ITEMS,
		"Full range scan should return all {TOTAL_ITEMS} items"
	);

	// Verify each item is correct and in order
	for (idx, (key, value)) in range_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_key = &expected_items[idx].0;
		let expected_value = &expected_items[idx].1;

		assert_eq!(
			key_str, expected_key,
			"Key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
		);
		assert_eq!(
			value_str, expected_value,
			"Value mismatch at index {idx}: expected '{expected_value}', found '{value_str}'"
		);
	}

	// Test 2: Partial range scan - first 100 items ([key_000000, key_000100) range)
	let partial_start = "key_000000".as_bytes();
	let partial_end = "key_000100".as_bytes();

	let txn = tree.begin().unwrap();
	let partial_result =
		collect_transaction_all(&mut txn.range(partial_start, partial_end).unwrap()).unwrap();

	assert_eq!(partial_result.len(), 100, "Partial range scan should return 100 items");

	// Verify each item in partial range
	for (idx, (key, value)) in partial_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_key = &expected_items[idx].0;
		let expected_value = &expected_items[idx].1;

		assert_eq!(
                key_str, expected_key,
                "Partial range key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
            );
		assert_eq!(
                value_str, expected_value,
                "Partial range value mismatch at index {idx}: expected '{expected_value}', found '{value_str}'"
            );
	}

	// Test 3: Middle range scan - items 5000-5099
	let middle_start = "key_005000".as_bytes();
	let middle_end = "key_005100".as_bytes();

	let txn = tree.begin().unwrap();
	let middle_result =
		collect_transaction_all(&mut txn.range(middle_start, middle_end).unwrap()).unwrap();

	assert_eq!(middle_result.len(), 100, "Middle range scan should return 100 items");

	// Verify each item in middle range
	for (idx, (key, value)) in middle_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_idx = 5000 + idx;
		let expected_key = &expected_items[expected_idx].0;
		let expected_value = &expected_items[expected_idx].1;

		assert_eq!(
                key_str, expected_key,
                "Middle range key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
            );
		assert_eq!(
                value_str, expected_value,
                "Middle range value mismatch at index {idx}: expected '{expected_value}', found '{value_str}'"
            );
	}

	// Test 4: End range scan - last 100 items
	let end_start = "key_009900".as_bytes();
	let end_end = "key_010000".as_bytes();

	let txn = tree.begin().unwrap();
	let end_result = collect_transaction_all(&mut txn.range(end_start, end_end).unwrap()).unwrap();

	assert_eq!(end_result.len(), 100, "End range scan should return 100 items");

	// Verify each item in end range
	for (idx, (key, value)) in end_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_idx = 9900 + idx;
		let expected_key = &expected_items[expected_idx].0;
		let expected_value = &expected_items[expected_idx].1;

		assert_eq!(
			key_str, expected_key,
			"End range key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
		);
		assert_eq!(
                value_str, expected_value,
                "End range value mismatch at index {idx}: expected '{expected_value}', found '{value_str}'"
            );
	}

	// Test 5: Single item range scan
	let single_start = "key_004567".as_bytes();
	let single_end = "key_004568".as_bytes();

	let txn = tree.begin().unwrap();
	let single_result =
		collect_transaction_all(&mut txn.range(single_start, single_end).unwrap()).unwrap();

	assert_eq!(single_result.len(), 1, "Single item range scan should return 1 item");

	let (key, value) = &single_result[0];
	let key_str = std::str::from_utf8(key).unwrap();
	let value_str = std::str::from_utf8(value).unwrap();

	assert_eq!(key_str, "key_004567");
	assert_eq!(value_str, "value_004567_content_data_9134");

	// Test 6: Empty range scan (non-existent range)
	let empty_start = "key_999999".as_bytes();
	let empty_end = "key_888888".as_bytes(); // end < start, should be empty

	let txn = tree.begin().unwrap();
	let empty_result =
		collect_transaction_all(&mut txn.range(empty_start, empty_end).unwrap()).unwrap();

	assert_eq!(empty_result.len(), 0, "Empty range scan should return 0 items");
}

#[test(tokio::test)]
async fn test_range_skip_take() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	const TOTAL_ITEMS: usize = 10_000;
	let mut expected_items = Vec::with_capacity(TOTAL_ITEMS);

	for i in 0..TOTAL_ITEMS {
		let key = format!("key_{i:06}");
		let value = format!("value_{:06}_content_data_{}", i, i * 2);

		expected_items.push((key.clone(), value.clone()));

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	tree.flush().unwrap();

	let start_key = "key_000000".as_bytes();
	let end_key = "key_999999".as_bytes();

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(start_key, end_key).unwrap();
	iter.seek_first().unwrap();
	// Skip 5000 items
	for _ in 0..5000 {
		if !iter.valid() {
			break;
		}
		iter.next().unwrap();
	}
	// Take 100 items
	let mut range_result = Vec::new();
	for _ in 0..100 {
		if !iter.valid() {
			break;
		}
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		range_result.push((key, value));
		iter.next().unwrap();
	}

	assert_eq!(
		range_result.len(),
		100,
		"Range scan with skip(5000).take(100) should return 100 items"
	);

	for (idx, (key, value)) in range_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_idx = 5000 + idx;
		let expected_key = &expected_items[expected_idx].0;
		let expected_value = &expected_items[expected_idx].1;

		assert_eq!(
			key_str, expected_key,
			"Key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
		);
		assert_eq!(
			value_str, expected_value,
			"Value mismatch at index {idx}: expected '{expected_value}', found '{value_str}'"
		);
	}
}

#[test(tokio::test)]
async fn test_range_skip_take_alphabetical() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	fn generate_alphabetical_key(index: usize) -> String {
		let mut result = String::new();
		let mut remaining = index + 1;

		while remaining > 0 {
			let digit = (remaining - 1) % 26;
			result.push((b'a' + digit as u8) as char);
			remaining = (remaining - 1) / 26;
		}

		result.chars().rev().collect()
	}

	const TOTAL_ITEMS: usize = 10_000;
	let mut expected_items = Vec::with_capacity(TOTAL_ITEMS);

	for i in 0..TOTAL_ITEMS {
		let key = generate_alphabetical_key(i);
		let value = format!("value_{}_content_data_{}", key, i * 2);

		expected_items.push((key.clone(), value.clone()));

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	tree.flush().unwrap();

	expected_items.sort_by(|a, b| a.0.cmp(&b.0));

	let beg = [0u8].to_vec();
	let end = [255u8].to_vec();

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Skip 5000 items
	for _ in 0..5000 {
		if !iter.valid() {
			break;
		}
		iter.next().unwrap();
	}
	// Take 100 items
	let mut range_result = Vec::new();
	for _ in 0..100 {
		if !iter.valid() {
			break;
		}
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		range_result.push((key, value));
		iter.next().unwrap();
	}

	assert_eq!(
		range_result.len(),
		100,
		"Range scan with skip(5000).take(100) should return 100 items"
	);

	for (idx, (key, value)) in range_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_idx = 5000 + idx;
		let expected_key = &expected_items[expected_idx].0;
		let expected_value = &expected_items[expected_idx].1;

		assert_eq!(
			key_str, expected_key,
			"Key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
		);
		assert_eq!(
			value_str, expected_value,
			"Value mismatch at index {idx}: expected '{expected_value}', found '{value_str}'"
		);
	}
}

#[test(tokio::test)]
async fn test_range_limit_functionality() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	const TOTAL_ITEMS: usize = 10_000;
	let mut expected_items = Vec::with_capacity(TOTAL_ITEMS);

	for i in 0..TOTAL_ITEMS {
		let key = format!("key_{i:06}");
		let value = format!("value_{:06}_content_data_{}", i, i * 2);

		expected_items.push((key.clone(), value.clone()));

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	tree.flush().unwrap();

	let beg = [0u8].to_vec();
	let end = [255u8].to_vec();

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Take 100 items
	let mut limited_result = Vec::new();
	for _ in 0..100 {
		if !iter.valid() {
			break;
		}
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		limited_result.push((key, value));
		iter.next().unwrap();
	}

	assert_eq!(
		limited_result.len(),
		100,
		"Range scan with .take(100) should return exactly 100 items"
	);

	for (idx, (key, value)) in limited_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_key = &expected_items[idx].0;
		let expected_value = &expected_items[idx].1;

		assert_eq!(
                key_str, expected_key,
                "Key mismatch at index {idx} with limit 100: expected '{expected_key}', found '{key_str}'"
            );
		assert_eq!(
                value_str, expected_value,
                "Value mismatch at index {idx} with limit 100: expected '{expected_value}', found '{value_str}'"
            );
	}

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Take 1000 items
	let mut limited_result_1000 = Vec::new();
	for _ in 0..1000 {
		if !iter.valid() {
			break;
		}
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		limited_result_1000.push((key, value));
		iter.next().unwrap();
	}

	assert_eq!(
		limited_result_1000.len(),
		1000,
		"Range scan with .take(1000) should return exactly 1000 items"
	);

	for (idx, (key, value)) in limited_result_1000.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_key = &expected_items[idx].0;
		let expected_value = &expected_items[idx].1;

		assert_eq!(
                key_str, expected_key,
                "Key mismatch at index {idx} with limit 1000: expected '{expected_key}', found '{key_str}'"
            );
		assert_eq!(
                value_str, expected_value,
                "Value mismatch at index {idx} with limit 1000: expected '{expected_value}', found '{value_str}'"
            );
	}

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Take 15000 items
	let mut limited_result_large = Vec::new();
	for _ in 0..15000 {
		if !iter.valid() {
			break;
		}
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		limited_result_large.push((key, value));
		iter.next().unwrap();
	}

	assert_eq!(
		limited_result_large.len(),
		TOTAL_ITEMS,
		"Range scan with .take(15000) should return all {TOTAL_ITEMS} items"
	);

	let txn = tree.begin().unwrap();
	let unlimited_result = collect_transaction_all(&mut txn.range(&beg, &end).unwrap()).unwrap();

	assert_eq!(
		unlimited_result.len(),
		TOTAL_ITEMS,
		"Range scan with no limit should return all {TOTAL_ITEMS} items"
	);

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Take 1 item
	let mut single_result = Vec::new();
	if iter.valid() {
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		single_result.push((key, value));
	}

	assert_eq!(single_result.len(), 1, "Range scan with .take(1) should return exactly 1 item");

	let (key, value) = &single_result[0];
	let key_str = std::str::from_utf8(key).unwrap();
	let value_str = std::str::from_utf8(value).unwrap();

	assert_eq!(key_str, "key_000000");
	assert_eq!(value_str, "value_000000_content_data_0");

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Take 0 items (don't collect anything)
	let zero_result: Vec<(Key, Option<Value>)> = Vec::new();

	assert_eq!(zero_result.len(), 0, "Range scan with .take(0) should return no items");
}

#[test(tokio::test)]
async fn test_range_limit_with_skip_take() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	const TOTAL_ITEMS: usize = 20_000;
	let mut expected_items = Vec::with_capacity(TOTAL_ITEMS);

	for i in 0..TOTAL_ITEMS {
		let key = format!("key_{i:06}");
		let value = format!("value_{:06}_content_data_{}", i, i * 2);

		expected_items.push((key.clone(), value.clone()));

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	tree.flush().unwrap();

	let beg = [0u8].to_vec();
	let end = [255u8].to_vec();

	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Skip 5000 items
	for _ in 0..5000 {
		if !iter.valid() {
			break;
		}
		iter.next().unwrap();
	}
	// Take 100 items
	let mut unlimited_range_result = Vec::new();
	for _ in 0..100 {
		if !iter.valid() {
			break;
		}
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		unlimited_range_result.push((key, value));
		iter.next().unwrap();
	}

	assert_eq!(
		unlimited_range_result.len(),
		100,
		"Range scan followed by skip(5000).take(100) should return 100 items"
	);

	for (idx, (key, value)) in unlimited_range_result.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_idx = 5000 + idx;
		let expected_key = &expected_items[expected_idx].0;
		let expected_value = &expected_items[expected_idx].1;

		assert_eq!(
                key_str, expected_key,
                "Key mismatch at index {idx} with unlimited range: expected '{expected_key}', found '{key_str}'"
            );
		assert_eq!(
                value_str, expected_value,
                "Value mismatch at index {idx} with unlimited range: expected '{expected_value}', found '{value_str}'"
            );
	}

	// Case: Test another skip position with take
	let txn = tree.begin().unwrap();
	let mut iter = txn.range(&beg, &end).unwrap();
	iter.seek_first().unwrap();
	// Skip 5000 items
	for _ in 0..5000 {
		if !iter.valid() {
			break;
		}
		iter.next().unwrap();
	}
	// Take 50 items
	let mut res = Vec::new();
	for _ in 0..50 {
		if !iter.valid() {
			break;
		}
		let key = iter.key().user_key().to_vec();
		let value = iter.value().unwrap();
		res.push((key, value));
		iter.next().unwrap();
	}

	assert_eq!(res.len(), 50, "Range scan followed by skip(5000).take(50) should return 50 items");

	for (idx, (key, value)) in res.iter().enumerate() {
		let key_str = std::str::from_utf8(key).unwrap();
		let value_str = std::str::from_utf8(value).unwrap();

		let expected_idx = 5000 + idx;
		let expected_key = &expected_items[expected_idx].0;
		let expected_value = &expected_items[expected_idx].1;

		assert_eq!(
                key_str, expected_key,
                "Key mismatch at index {idx} with limit 5050: expected '{expected_key}', found '{key_str}'"
            );
		assert_eq!(
                value_str, expected_value,
                "Value mismatch at index {idx} with limit 5050: expected '{expected_value}', found '{value_str}'"
            );
	}
}

#[test(tokio::test)]
async fn test_vlog_basic() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_vlog_test_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Test 1: Values should be stored in VLog
	let small_key = "small_key";
	let small_value = "small_value"; // < 100 bytes

	let mut txn = tree.begin().unwrap();
	txn.set(small_key.as_bytes(), small_value.as_bytes()).unwrap();
	txn.commit().await.unwrap();

	// Test 2: Large values should be stored in VLog
	let large_key = "large_key";
	let large_value = "X".repeat(200); // >= 100 bytes

	let mut txn = tree.begin().unwrap();
	txn.set(large_key.as_bytes(), large_value.as_bytes()).unwrap();
	txn.commit().await.unwrap();

	// Force memtable flush to persist to SSTables
	tree.flush().unwrap();

	// Verify both values can be read correctly
	let txn = tree.begin().unwrap();

	let retrieved_small = txn.get(small_key.as_bytes()).unwrap().unwrap();
	assert_eq!(retrieved_small, small_value.as_bytes().to_vec());

	let retrieved_large = txn.get(large_key.as_bytes()).unwrap().unwrap();
	assert_eq!(retrieved_large, large_value.as_bytes().to_vec());
}

#[test(tokio::test(flavor = "multi_thread"))]
async fn test_vlog_concurrent_operations() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.vlog_max_file_size = 512 * 1024;
		opts.max_memtable_size = 32 * 1024;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	let mut expected_values = Vec::new();

	for i in 0..1000 {
		let key = format!("key_{i:04}");
		let value = if i % 2 == 0 {
			format!("small_value_{i}")
		} else {
			format!("large_value_{}_with_padding_{}", i, "X".repeat(100))
		};

		expected_values.push((key.clone(), value.clone()));

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush to ensure all data is persisted
	tree.close().await.unwrap();

	let tree = Arc::new(tree);

	// Concurrent reads
	let read_handles: Vec<_> = (0..5)
		.map(|reader_id| {
			let tree = Arc::clone(&tree);
			let expected_values = expected_values.clone();
			tokio::spawn(async move {
				for (key, expected_value) in expected_values {
					let txn = tree.begin().unwrap();
					let retrieved = txn.get(key.as_bytes()).unwrap().unwrap();
					assert_eq!(
						retrieved,
						expected_value.as_bytes().to_vec(),
						"Reader {reader_id} failed to get correct value for key {key}"
					);
				}
			})
		})
		.collect();

	// Wait for all reads to complete
	for handle in read_handles {
		handle.await.unwrap();
	}

	// Explicitly close the tree to ensure proper cleanup
	tree.close().await.unwrap();
}

#[test(tokio::test)]
async fn test_vlog_file_rotation() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.vlog_max_file_size = 2048; // 2KB files to force frequent rotation
		opts.enable_vlog = true;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert enough data to force multiple file rotations
	let mut keys_and_values = Vec::new();
	for i in 0..50 {
		let key = format!("rotation_key_{i:03}");
		let value = format!("rotation_value_{}_with_lots_of_padding_{}", i, "Z".repeat(200));
		keys_and_values.push((key.clone(), value.clone()));

		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush
	tree.flush().unwrap();

	// Check that multiple VLog files were created
	let vlog_dir = path.join("vlog");
	let entries = std::fs::read_dir(&vlog_dir).unwrap();
	let vlog_files: Vec<_> = entries
		.filter_map(|e| {
			let entry = e.ok()?;
			let name = entry.file_name().to_string_lossy().to_string();
			if opts.is_vlog_filename(&name) {
				Some(name)
			} else {
				None
			}
		})
		.collect();

	assert!(vlog_files.len() > 1, "Expected multiple VLog files due to rotation");

	// Verify all data is still accessible across multiple files
	for (key, expected_value) in keys_and_values {
		let txn = tree.begin().unwrap();
		let retrieved = txn.get(key.as_bytes()).unwrap().unwrap();
		assert_eq!(
			retrieved,
			expected_value.as_bytes().to_vec(),
			"Key {key} has incorrect value across file rotation"
		);
	}
}

#[test(tokio::test)]
async fn test_compaction_with_updates_and_delete() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.level_count = 2;
		opts.vlog_max_file_size = 20;
		opts.enable_vlog = true;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Create 2 keys in ascending order
	let keys = ["key-1".as_bytes(), "key-2".as_bytes()];

	// Insert first version of each key
	for (i, key) in keys.iter().enumerate() {
		let value = format!("value-{}-v1", i + 1);
		let mut tx = tree.begin().unwrap();
		tx.set(*key, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// Insert second version of each key
	for (i, key) in keys.iter().enumerate() {
		let value = format!("value-{}-v2", i + 1);
		let mut tx = tree.begin().unwrap();
		tx.set(*key, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// Verify the latest values before delete
	for (i, key) in keys.iter().enumerate() {
		let tx = tree.begin().unwrap();
		let result = tx.get(*key).unwrap();
		let expected = format!("value-{}-v2", i + 1);
		assert_eq!(result, Some(expected.as_bytes().to_vec()));
	}

	// Delete all keys
	for key in keys.iter() {
		let mut tx = tree.begin().unwrap();
		tx.delete(*key).unwrap();
		tx.commit().await.unwrap();
	}

	// Flush memtable
	tree.flush().unwrap();

	// Force compaction - this triggers automatic VLog cleanup via global-min approach
	let strategy = Arc::new(Strategy::default());
	tree.compact(strategy).unwrap();

	// Verify all keys are gone after compaction
	for key in keys.iter() {
		let tx = tree.begin().unwrap();
		let result = tx.get(*key).unwrap();
		assert_eq!(result, None);
	}
}

#[test(tokio::test)]
async fn test_compaction_with_updates_and_delete_on_same_key() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.level_count = 2;
		opts.vlog_max_file_size = 20;
		opts.enable_vlog = true;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Create single key
	let keys = ["key-1".as_bytes()];

	// Insert first version of each key
	for (i, key) in keys.iter().enumerate() {
		let value = format!("value-{}-v1", i + 1);
		let mut tx = tree.begin().unwrap();
		tx.set(*key, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// Insert second version of each key
	for (i, key) in keys.iter().enumerate() {
		let value = format!("value-{}-v2", i + 1);
		let mut tx = tree.begin().unwrap();
		tx.set(*key, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// Insert third version of each key
	for (i, key) in keys.iter().enumerate() {
		let value = format!("value-{}-v3", i + 1);
		let mut tx = tree.begin().unwrap();
		tx.set(*key, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// Insert fourth version of each key
	for (i, key) in keys.iter().enumerate() {
		let value = format!("value-{}-v4", i + 1);
		let mut tx = tree.begin().unwrap();
		tx.set(*key, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// Verify the latest values before delete
	for (i, key) in keys.iter().enumerate() {
		let tx = tree.begin().unwrap();
		let result = tx.get(*key).unwrap();
		assert_eq!(result, Some(format!("value-{}-v4", i + 1).as_bytes().to_vec()));
	}

	// Delete all keys
	for key in keys.iter() {
		let mut tx = tree.begin().unwrap();
		tx.delete(*key).unwrap();
		tx.commit().await.unwrap();
	}

	// Flush memtable
	tree.flush().unwrap();

	// Force compaction - this triggers automatic VLog cleanup via global-min approach
	let strategy = Arc::new(Strategy::default());
	tree.compact(strategy).unwrap();

	// Verify all keys are gone after compaction
	for key in keys.iter() {
		let tx = tree.begin().unwrap();
		let result = tx.get(*key).unwrap();
		assert_eq!(result, None);
	}
}

#[test(tokio::test)]
async fn test_vlog_compaction_preserves_sequence_numbers() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_vlog_compaction_options(path.clone());

	// Open the Tree (database instance)
	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Define keys used throughout the test
	let key1 = b"test_key_1".to_vec();
	let key2 = b"test_key_2".to_vec();
	let key3 = b"test_key_3".to_vec();

	// --- Step 1: Insert multiple versions of key1 to fill the first VLog file ---
	for i in 0..3 {
		let value = format!("value1_version_{i}").repeat(10); // Large value to fill VLog
		let mut tx = tree.begin().unwrap();
		tx.set(&key1, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// --- Step 2: Insert and delete key2 ---
	// We are doing this to make sure there are deleted keys in the VLog file
	{
		// Insert key2
		let mut tx = tree.begin().unwrap();
		tx.set(&key2, b"value2").unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();

		// Delete key2
		let mut tx = tree.begin().unwrap();
		tx.delete(&key2).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// --- Step 3: Validate current value of key1 (should be last inserted version)
	// ---
	{
		let tx = tree.begin().unwrap();
		let current_value = tx.get(&key1).unwrap().unwrap();
		assert_eq!(&current_value, "value1_version_2".to_string().repeat(10).as_bytes());
	}

	// --- Step 4: Insert key3 values which will rotate VLog file ---
	for i in 0..2 {
		let value = format!("value2_version_{i}").repeat(10); // Large values
		let mut tx = tree.begin().unwrap();
		tx.set(&key3, value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
		tree.flush().unwrap();
	}

	// --- Step 5: Update key1 with a final value ---
	{
		let mut tx = tree.begin().unwrap();
		tx.set(&key1, "final_value_key1".repeat(10).as_bytes()).unwrap();
		tx.commit().await.unwrap();
	}
	tree.flush().unwrap();

	// --- Step 6: Verify latest value of key1 before compaction ---
	{
		let tx = tree.begin().unwrap();
		let value = tx.get(&key1).unwrap().unwrap();
		assert_eq!(&value, "final_value_key1".repeat(10).as_bytes());
	}

	// --- Step 7: Trigger manual compaction of the LSM tree (also triggers VLog cleanup via
	// global-min approach) ---
	let strategy = Arc::new(Strategy::default());
	tree.compact(strategy).unwrap();

	// --- Step 8: Verify key1 still returns the correct latest value after compaction ---
	{
		let tx = tree.begin().unwrap();
		let value = tx.get(&key1).unwrap().unwrap();
		assert_eq!(
			&value,
			"final_value_key1".repeat(10).as_bytes(),
			"After compaction, key1 returned incorrect value. The sequence number was not preserved during compaction."
		);
	}

	// --- Step 9: Clean shutdown ---
	tree.close().await.unwrap();
}

#[test(tokio::test)]
async fn test_sstable_lsn_bug() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
		opts.level_count = 2;
	});

	// Step 1: Create database and write data for first table
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write data for first table
		for i in 0..6 {
			let key = format!("batch_0_key_{:03}", i);
			let value = format!("batch_0_value_{:03}", i);

			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		// Force first flush
		tree.flush().unwrap();

		// Write data for second table
		for i in 0..6 {
			let key = format!("batch_1_key_{:03}", i);
			let value = format!("batch_1_value_{:03}", i);

			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		// Force second flush
		tree.flush().unwrap();

		// Verify all keys exist immediately after flush
		for batch in 0..2 {
			for i in 0..6 {
				let key = format!("batch_{}_key_{:03}", batch, i);
				let expected_value = format!("batch_{}_value_{:03}", batch, i);

				let txn = tree.begin().unwrap();
				let result = txn.get(key.as_bytes()).unwrap();
				assert!(result.is_some(), "Key '{}' should exist immediately after flush", key);
				assert_eq!(&result.unwrap(), expected_value.as_bytes());
			}
		}

		// Close the database
		tree.close().await.unwrap();
	}

	// Step 2: Reopen database and verify data persistence
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify all keys still exist after restart
		for batch in 0..2 {
			for i in 0..6 {
				let key = format!("batch_{}_key_{:03}", batch, i);
				let expected_value = format!("batch_{}_value_{:03}", batch, i);

				let txn = tree.begin().unwrap();
				let result = txn.get(key.as_bytes()).unwrap();
				assert!(result.is_some(), "Key '{}' should exist after restart", key);
				assert_eq!(&result.unwrap(), expected_value.as_bytes());
			}
		}

		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_table_id_assignment_across_restart() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Create options with very small memtable to force frequent flushes
	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 4 * 1024;
		opts.level_count = 2;
	});

	// Step 1: Create initial database and write data for 2 memtables
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write data for first table
		for i in 0..6 {
			let key = format!("batch_0_key_{:03}", i);
			let value = format!("batch_0_value_{:03}", i);

			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		// Force first flush to create first table
		tree.flush().unwrap();

		// Write data for second table
		for i in 0..6 {
			let key = format!("batch_1_key_{:03}", i);
			let value = format!("batch_1_value_{:03}", i);

			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		// Force second flush to create second table
		tree.flush().unwrap();

		// Verify we have 2 tables in L0
		let l0_size = tree.core.level_manifest.read().unwrap().levels.get_levels()[0].tables.len();
		assert_eq!(l0_size, 2, "Expected 2 tables in L0 after initial writes, got {l0_size}");

		// Get the table IDs from the first session
		let (table1_id, table2_id, next_table_id) = {
			let manifest = tree.core.level_manifest.read().unwrap();
			let table1_id = manifest.levels.get_levels()[0].tables[0].id;
			let table2_id = manifest.levels.get_levels()[0].tables[1].id;
			let next_table_id = manifest.next_table_id();
			(table1_id, table2_id, next_table_id)
		};

		// Verify table IDs are increasing (note: tables are stored in reverse order by
		// sequence number) So the first table in the vector has the higher ID
		assert!(
			table1_id > table2_id,
			"Table 1 ID should be greater than table 2 ID (newer table first)"
		);
		assert!(
			table1_id < next_table_id,
			"Next table ID should be greater than existing table IDs"
		);

		// Close the database
		tree.close().await.unwrap();
	}

	// Step 2: Reopen the database
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		{
			// Verify we still have 2 tables in L0 after reopening
			let l0_size =
				tree.core.level_manifest.read().unwrap().levels.get_levels()[0].tables.len();
			assert_eq!(l0_size, 2, "Expected 2 tables in L0 after reopening, got {l0_size}");
			// Get the table IDs after reopening
			let manifest = tree.core.level_manifest.read().unwrap();
			let table1_id = manifest.levels.get_levels()[0].tables[0].id;
			let table2_id = manifest.levels.get_levels()[0].tables[1].id;
			let next_table_id = manifest.next_table_id();

			// Verify table IDs are still in correct order (newer table first)
			assert!(
				table1_id > table2_id,
				"Table 1 ID should be greater than table 2 ID (newer table first)"
			);
			assert!(
				table1_id < next_table_id,
				"Next table ID should be greater than existing table IDs after reopen"
			);
		}

		// Step 3: Add more data to create a 3rd table
		for i in 0..6 {
			let key = format!("batch_2_key_{:03}", i);
			let value = format!("batch_2_value_{:03}", i);

			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		// Force flush to create the 3rd table
		tree.flush().unwrap();

		{
			// Verify we now have 3 tables in L0
			let l0_size =
				tree.core.level_manifest.read().unwrap().levels.get_levels()[0].tables.len();
			assert_eq!(l0_size, 3, "Expected 3 tables in L0 after adding more data, got {l0_size}");

			// Get the table IDs from all 3 tables
			let manifest = tree.core.level_manifest.read().unwrap();
			let table1_id = manifest.levels.get_levels()[0].tables[0].id;
			let table2_id = manifest.levels.get_levels()[0].tables[1].id;
			let table3_id = manifest.levels.get_levels()[0].tables[2].id;
			let next_table_id = manifest.next_table_id();

			// Verify table IDs are in correct order (newer tables first)
			assert!(
				table1_id > table2_id,
				"Table 1 ID should be greater than table 2 ID (newer table first)"
			);
			assert!(
				table2_id > table3_id,
				"Table 2 ID should be greater than table 3 ID (newer table first)"
			);
			assert!(
				table1_id < next_table_id,
				"Next table ID should be greater than all existing table IDs"
			);
		}

		// Verify we can read data from all tables
		for batch in 0..3 {
			for i in 0..6 {
				let key = format!("batch_{}_key_{:03}", batch, i);
				let expected_value = format!("batch_{}_value_{:03}", batch, i);

				let txn = tree.begin().unwrap();
				let result = txn.get(key.as_bytes()).unwrap();
				assert!(result.is_some(), "Key '{}' should exist after restart", key);
				assert_eq!(&result.unwrap(), expected_value.as_bytes());
			}
		}

		// Close the database
		tree.close().await.unwrap();
	}

	// Step 4: Final verification - reopen and check everything is still correct
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify we still have 3 tables
		let l0_size = tree.core.level_manifest.read().unwrap().levels.get_levels()[0].tables.len();
		assert_eq!(l0_size, 3, "Expected 3 tables in L0 after final reopen, got {l0_size}");

		// Verify table IDs are still in correct order (newer tables first)
		let manifest = tree.core.level_manifest.read().unwrap();
		let table1_id = manifest.levels.get_levels()[0].tables[0].id;
		let table2_id = manifest.levels.get_levels()[0].tables[1].id;
		let table3_id = manifest.levels.get_levels()[0].tables[2].id;
		let next_table_id = manifest.next_table_id();

		assert!(
			table1_id > table2_id,
			"Final check: Table 1 ID should be greater than table 2 ID (newer table first)"
		);
		assert!(
			table2_id > table3_id,
			"Final check: Table 2 ID should be greater than table 3 ID (newer table first)"
		);
		assert!(
			table1_id < next_table_id,
			"Final check: Next table ID should be greater than all existing table IDs"
		);

		// Verify that we can read some data (simplified check)
		let txn = tree.begin().unwrap();
		let result = txn.get("batch_0_key_000".as_bytes()).unwrap();
		assert!(result.is_some(), "Should be able to read at least one key");
	}
}

#[test(tokio::test(flavor = "multi_thread"))]
async fn test_vlog_prefill_on_reopen() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.vlog_max_file_size = 10; // Very small to force multiple files
		opts.enable_vlog = true;
	});

	// Create initial database and add data to create multiple VLog files
	let tree1 = Tree::new(Arc::clone(&opts)).unwrap();

	// Verify VLog is enabled
	assert!(tree1.core.vlog.is_some(), "VLog should be enabled");

	// Add data to create multiple VLog files
	for i in 0..10 {
		let key = format!("key_{i}");
		let value = format!("value_{i}_large_data_that_should_force_vlog_storage");

		let mut tx = tree1.begin().unwrap();
		tx.set(key.as_bytes(), value.as_bytes()).unwrap();
		tx.commit().await.unwrap();

		// Verify the data was written immediately
		let tx = tree1.begin().unwrap();
		let result = tx.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key '{key}' should exist immediately after write");
	}

	// Verify all data exists in the first database
	for i in 0..10 {
		let key = format!("key_{i}");
		let expected_value = format!("value_{i}_large_data_that_should_force_vlog_storage");

		let tx = tree1.begin().unwrap();
		let result = tx.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key '{key}' should exist in first database");
		assert_eq!(&result.unwrap(), expected_value.as_bytes());
	}

	// Drop the first database (this will close it)
	tree1.close().await.unwrap();

	// Create a new database instance - this should trigger VLog prefill
	let tree2 = Tree::new(Arc::clone(&opts)).unwrap();
	assert!(tree2.core.vlog.is_some(), "VLog should be enabled in second database");

	// Verify that all existing data can still be read
	for i in 0..10 {
		let key = format!("key_{i}");
		let expected_value = format!("value_{i}_large_data_that_should_force_vlog_storage");

		let tx = tree2.begin().unwrap();
		let result = tx.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key '{key}' should exist after reopen");
		assert_eq!(&result.unwrap(), expected_value.as_bytes());
	}

	// Add new data and verify it goes to the correct active file
	let new_key = "new_key";
	let new_value = "new_value_large_data_that_should_force_vlog_storage";

	let mut tx = tree2.begin().unwrap();
	tx.set(new_key.as_bytes(), new_value.as_bytes()).unwrap();
	tx.commit().await.unwrap();

	// Verify the new data can be read
	let tx = tree2.begin().unwrap();
	let result = tx.get(new_key.as_bytes()).unwrap();
	assert!(result.is_some(), "New key should exist after write");
	assert_eq!(&result.unwrap(), new_value.as_bytes());

	// Verify we can still read from old data after adding new data
	for i in 0..10 {
		let key = format!("key_{i}");
		let expected_value = format!("value_{i}_large_data_that_should_force_vlog_storage");

		let tx = tree2.begin().unwrap();
		let result = tx.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Old key '{key}' should still exist");
		assert_eq!(&result.unwrap(), expected_value.as_bytes());
	}

	// Clean shutdown (drop will close it)
	tree2.close().await.unwrap();
}

#[test(tokio::test)]
async fn test_tree_builder() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Test TreeBuilder with default key type (InternalKey)
	let tree = TreeBuilder::new()
		.with_path(path.clone())
		.with_max_memtable_size(64 * 1024)
		.with_enable_vlog(true)
		.with_vlog_max_file_size(1024 * 1024)
		.build()
		.unwrap();

	// Test basic operations
	let mut txn = tree.begin().unwrap();
	txn.set(b"test_key", b"test_value").unwrap();
	txn.commit().await.unwrap();

	let txn = tree.begin().unwrap();
	let result = txn.get(b"test_key").unwrap().unwrap();
	assert_eq!(result, b"test_value".to_vec());

	// Test build_with_options
	let (tree2, opts) =
		TreeBuilder::new().with_path(temp_dir.path().join("tree2")).build_with_options().unwrap();

	// Verify the options are accessible
	assert_eq!(opts.path, temp_dir.path().join("tree2"));

	// Test basic operations on the second tree
	let mut txn = tree2.begin().unwrap();
	txn.set(b"key2", b"value2").unwrap();
	txn.commit().await.unwrap();

	let txn = tree2.begin().unwrap();
	let result = txn.get(b"key2").unwrap().unwrap();
	assert_eq!(result, b"value2".to_vec());
}

#[test(tokio::test)]
async fn test_soft_delete() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 64 * 1024; // Small memtable to force flushes
	});

	// Step 1: Create multiple versions of a key across separate transactions
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Create 5 different versions of the same key
		for version in 1..=5 {
			let value = format!("value_v{}", version);
			let mut txn = tree.begin().unwrap();
			txn.set(b"test_key", value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		// Verify the latest version exists
		let txn = tree.begin().unwrap();
		let result = txn.get(b"test_key").unwrap().unwrap();
		assert_eq!(&result, b"value_v5");

		// Soft delete the key
		let mut txn = tree.begin().unwrap();
		txn.soft_delete(b"test_key").unwrap();
		txn.commit().await.unwrap();

		// Verify the key is now invisible (soft deleted)
		let txn = tree.begin().unwrap();
		let result = txn.get(b"test_key").unwrap();
		assert!(result.is_none(), "Soft deleted key should not be visible");

		// Add a new different key
		let mut txn = tree.begin().unwrap();
		txn.set(b"other_key", b"other_value").unwrap();
		txn.commit().await.unwrap();

		// Verify the new key exists
		let txn = tree.begin().unwrap();
		let result = txn.get(b"other_key").unwrap().unwrap();
		assert_eq!(&result, b"other_value");

		// Force flush to persist all changes to disk
		tree.flush().unwrap();

		// Close the database
		tree.close().await.unwrap();
	}

	// Step 2: Reopen the database and verify soft deleted key is still invisible
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify the soft deleted key is still invisible after restart
		let txn = tree.begin().unwrap();
		let result = txn.get(b"test_key").unwrap();
		assert!(
			result.is_none(),
			"Soft deleted key should remain invisible after database restart"
		);

		// Verify the other key still exists
		let txn = tree.begin().unwrap();
		let result = txn.get(b"other_key").unwrap().unwrap();
		assert_eq!(&result, b"other_value");

		// Test range scan to ensure soft deleted key doesn't appear
		let txn = tree.begin().unwrap();
		let range_result = collect_transaction_all(
			&mut txn.range(b"test".as_slice(), b"testz".as_slice()).unwrap(),
		)
		.unwrap();

		// Should be empty since test_key is soft deleted
		assert!(range_result.is_empty(), "Range scan should not include soft deleted keys");

		// Test range scan that includes the other key
		let txn = tree.begin().unwrap();
		let range_result = collect_transaction_all(
			&mut txn.range(b"other".as_slice(), b"otherz".as_slice()).unwrap(),
		)
		.unwrap();

		// Should contain the other key
		assert_eq!(range_result.len(), 1);
		assert_eq!(&range_result[0].0, b"other_key");
		assert_eq!(range_result[0].1.as_slice(), b"other_value");

		// Test that we can reinsert the same key after soft delete
		let mut txn = tree.begin().unwrap();
		txn.set(b"test_key", b"new_value_after_soft_delete").unwrap();
		txn.commit().await.unwrap();

		// Verify the new value is visible
		let txn = tree.begin().unwrap();
		let result = txn.get(b"test_key").unwrap().unwrap();
		assert_eq!(&result, b"new_value_after_soft_delete");

		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_checkpoint_with_vlog() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.vlog_max_file_size = 1024;
		opts.max_memtable_size = 1024;
		opts.enable_vlog = true;
	});

	// Create initial data with VLog enabled
	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert some data to ensure VLog files are created
	let large_value = vec![1u8; 200]; // Large enough for VLog
	for i in 0..5 {
		let key = format!("key_{i}");
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), &large_value).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush to create VLog files
	tree.flush().unwrap();

	// Create checkpoint
	let checkpoint_dir = temp_dir.path().join("checkpoint");
	let metadata = tree.create_checkpoint(&checkpoint_dir).unwrap();

	// Verify checkpoint metadata
	assert!(metadata.timestamp > 0);
	assert!(metadata.total_size > 0);

	// Verify all expected directories exist in checkpoint
	assert!(checkpoint_dir.exists());
	assert!(checkpoint_dir.join("sstables").exists());
	assert!(checkpoint_dir.join("wal").exists());
	assert!(checkpoint_dir.join("manifest").exists());
	assert!(checkpoint_dir.join("vlog").exists());
	assert!(checkpoint_dir.join("CHECKPOINT_METADATA").exists());

	// Verify VLog files are in the checkpoint
	let vlog_checkpoint_dir = checkpoint_dir.join("vlog");
	let vlog_entries = std::fs::read_dir(&vlog_checkpoint_dir).unwrap();
	let vlog_files: Vec<_> = vlog_entries
		.filter_map(|entry| {
			let entry = entry.ok()?;
			let name = entry.file_name().to_string_lossy().to_string();
			if opts.is_vlog_filename(&name) {
				Some(name)
			} else {
				None
			}
		})
		.collect();

	assert!(!vlog_files.is_empty(), "Should have VLog files in the checkpoint");

	// Insert more data after checkpoint
	for i in 5..10 {
		let key = format!("key_{i}");
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), &large_value).unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush to ensure the new data is also on disk
	tree.flush().unwrap();

	// Verify all data exists before restore
	for i in 0..10 {
		let key = format!("key_{i}");
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key '{key}' should exist before restore");
	}

	// Restore from checkpoint
	tree.restore_from_checkpoint(&checkpoint_dir).unwrap();

	// Verify data is restored to checkpoint state (keys 0-4 exist, 5-9 don't)
	for i in 0..5 {
		let key = format!("key_{i}");
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key '{key}' should exist after restore");
		assert_eq!(&result.unwrap(), &large_value);
	}

	// Verify the newer keys don't exist after restore
	for i in 5..10 {
		let key = format!("key_{i}");
		let txn = tree.begin().unwrap();
		let result = txn.get(key.as_bytes()).unwrap();
		assert!(result.is_none(), "Key '{key}' should not exist after restore");
	}

	// Verify VLog directory is restored
	let vlog_dir = opts.vlog_dir();

	assert!(vlog_dir.exists(), "VLog directory should exist after restore");

	// Verify VLog files are restored
	let vlog_entries = std::fs::read_dir(&vlog_dir).unwrap();
	let vlog_files: Vec<_> = vlog_entries
		.filter_map(|entry| {
			let entry = entry.ok()?;
			let name = entry.file_name().to_string_lossy().to_string();
			if opts.is_vlog_filename(&name) {
				Some(name)
			} else {
				None
			}
		})
		.collect();

	assert!(!vlog_files.is_empty(), "Should have VLog files after restore");
}

#[test_log::test(tokio::test)]
async fn test_clean_shutdown_actually_skips_wal() {
	// This test explicitly validates that WAL is NOT replayed after clean shutdown
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
		opts.flush_on_close = true;
	});

	// Phase 1: Write data and clean shutdown
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let mut txn = tree.begin().unwrap();
		txn.set(b"test_key", b"test_value").unwrap();
		txn.commit().await.unwrap();

		// Clean shutdown - should flush to SST
		tree.close().await.unwrap();
	}

	// Phase 2: Check manifest state after shutdown
	let manifest = LevelManifest::new(Arc::clone(&opts)).expect("Failed to load manifest");
	let log_number = manifest.get_log_number();

	// CRITICAL CHECK: log_number should be > 0 to skip WAL #0
	assert!(
		log_number > 0,
		"BUG: log_number should be > 0 after flush to indicate WAL #0 is flushed, got {}",
		log_number
	);

	// Phase 3: Restart and verify WAL was actually skipped
	{
		// Create a custom Core to inspect if WAL was replayed
		let inner = Arc::new(CoreInner::new(Arc::clone(&opts)).unwrap());

		// Before WAL replay, memtable should be empty
		let memtable_before = inner.active_memtable.read().unwrap().clone();
		assert!(memtable_before.is_empty(), "Memtable should be empty before WAL replay");

		// Now do WAL replay
		let wal_path = opts.wal_dir();
		let min_wal_number = log_number;

		let (wal_seq_opt, _memtable_opt) = Core::replay_wal_with_repair(
			&wal_path,
			min_wal_number,
			"Test",
			WalRecoveryMode::default(),
			opts.max_memtable_size,
			|_memtable, _wal_number| Ok(()),
		)
		.unwrap();

		// CRITICAL: WAL should have been skipped (return None)
		assert_eq!(
			wal_seq_opt, None,
			"BUG: WAL should have been skipped but was replayed! min_wal={}, returned={:?}",
			min_wal_number, wal_seq_opt
		);
	}
}

#[tokio::test]
async fn test_crash_before_flush_replays_wal() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large memtable to prevent
		                                     // auto-flush
	});

	// Phase 1: Write data and simulate crash (no clean shutdown)
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"crash_key", b"crash_value").unwrap();
		txn.commit().await.unwrap();

		// Simulate crash: drop tree without calling close()
		// This leaves data in WAL but not flushed to SST
		// Release lock manually to allow reopen
		{
			let mut lockfile = tree.core.inner.lockfile.lock().unwrap();
			lockfile.release().unwrap();
		}
		drop(tree);
	}

	// Phase 2: Restart and verify WAL was replayed
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Data should be available (recovered from WAL)
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"crash_key").unwrap(), Some(b"crash_value".to_vec()));

		tree.close().await.unwrap();
	}
}

#[tokio::test]
async fn test_log_number_advances_with_flushes() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Initial log_number
	let log_number_0 = tree.core.inner.level_manifest.read().unwrap().get_log_number();

	// Write data to trigger flush #1
	for i in 0..100 {
		let mut txn = tree.begin().unwrap();
		txn.set(format!("key_{i}").as_bytes(), b"value").unwrap();
		txn.commit().await.unwrap();
	}

	// Force flush
	tree.flush().unwrap();
	let log_number_1 = tree.core.inner.level_manifest.read().unwrap().get_log_number();
	assert!(log_number_1 > log_number_0, "log_number should advance after flush");

	// Write more data, trigger flush #2
	for i in 100..200 {
		let mut txn = tree.begin().unwrap();
		txn.set(format!("key_{i}").as_bytes(), b"value").unwrap();
		txn.commit().await.unwrap();
	}

	tree.flush().unwrap();
	let log_number_2 = tree.core.inner.level_manifest.read().unwrap().get_log_number();
	assert!(log_number_2 > log_number_1, "log_number should advance after second flush");

	tree.close().await.unwrap();
}

#[tokio::test]
async fn test_last_sequence_persists_across_restart() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	let expected_last_seq;

	// Phase 1: Create database, write, flush
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write data
		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key_{i}").as_bytes(), b"value").unwrap();
			txn.commit().await.unwrap();
		}

		// Force flush to persist
		tree.flush().unwrap();

		// Get last_sequence from manifest
		expected_last_seq = tree.core.inner.level_manifest.read().unwrap().get_last_sequence();
		assert!(expected_last_seq > 0, "last_sequence should be > 0 after flush");

		tree.close().await.unwrap();
	}

	// Phase 2: Reopen and verify last_sequence persisted
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let loaded_last_seq = tree.core.inner.level_manifest.read().unwrap().get_last_sequence();

		assert_eq!(
			loaded_last_seq, expected_last_seq,
			"last_sequence should persist across restart"
		);

		tree.close().await.unwrap();
	}
}

#[test_log::test(tokio::test)]
async fn test_wal_recovery_updates_last_sequence_in_memory() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
	});

	let manifest_seq_initial;

	// Phase 1: Write data and clean shutdown (no flush, just close)
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1").unwrap();
		txn.commit().await.unwrap();

		// Don't flush, just close - this will flush memtable on shutdown
		tree.close().await.unwrap();

		// Get the manifest sequence after shutdown flush
		let manifest = LevelManifest::new(Arc::clone(&opts)).unwrap();
		manifest_seq_initial = manifest.get_last_sequence();
	}

	// Phase 2: Write more data but crash (no flush, no close)
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key2", b"value2").unwrap();
		txn.commit().await.unwrap();

		// Crash: drop without close, release lock manually
		{
			let mut lockfile = tree.core.inner.lockfile.lock().unwrap();
			lockfile.release().unwrap();
		}
		drop(tree);
	}

	// Phase 3: Recover and verify in-memory sequence > manifest sequence
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// In-memory sequence should be updated from WAL (key2 recovery)
		let in_memory_seq = tree.core.seq_num();

		// Manifest sequence should still be from Phase 1
		let manifest_seq = tree.core.inner.level_manifest.read().unwrap().get_last_sequence();
		assert_eq!(
			manifest_seq, manifest_seq_initial,
			"Manifest last_sequence should not be updated until flush (from Phase 2 crash)"
		);

		// In-memory should be higher (includes recovered WAL data)
		assert!(
			in_memory_seq > manifest_seq,
			"In-memory sequence ({}) should be > manifest ({}) after WAL recovery",
			in_memory_seq,
			manifest_seq
		);

		// Now flush and verify manifest gets updated
		tree.flush().unwrap();
		let manifest_seq_after_flush =
			tree.core.inner.level_manifest.read().unwrap().get_last_sequence();
		assert!(
			manifest_seq_after_flush >= in_memory_seq,
			"Manifest last_sequence should update after flush"
		);

		tree.close().await.unwrap();
	}
}

#[tokio::test]
async fn test_clean_shutdown_no_empty_wal() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	let wal_dir = opts.wal_dir();

	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write data and trigger flush
		// make_room_for_write rotates WAL, creating a new WAL for subsequent writes
		for i in 0..100 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key_{i}").as_bytes(), b"value").unwrap();
			txn.commit().await.unwrap();
		}
		tree.flush().unwrap();

		// Write a bit more data to the new WAL
		let mut txn = tree.begin().unwrap();
		txn.set(b"extra", b"data").unwrap();
		txn.commit().await.unwrap();

		// Clean shutdown (should flush the extra data, update log_number, close WAL)
		tree.close().await.unwrap();

		// Give async cleanup time to complete
		tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

		// Count WAL files after shutdown
		let wals_after = crate::wal::list_segment_ids(&wal_dir, Some("wal")).unwrap();

		// Validate: shutdown should NOT create additional WAL files
		// WAL count may decrease due to cleanup, but should never increase
		// This confirms no empty WAL is created on shutdown
		assert!(
			wals_after.len() <= 2,
			"Clean shutdown should not create new WAL files (found {} WAL files after shutdown)",
			wals_after.len()
		);
	}

	// Verify restart works and data is accessible
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"key_0").unwrap(), Some(b"value".to_vec()));
		assert_eq!(txn.get(b"extra").unwrap(), Some(b"data".to_vec()));
		tree.close().await.unwrap();
	}
}

#[tokio::test]
async fn test_multiple_flush_cycles_log_number_sequence() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Flush cycle 1
		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("batch1_key_{i}").as_bytes(), b"value1").unwrap();
			txn.commit().await.unwrap();
		}
		tree.flush().unwrap();
		let log_num_1 = tree.core.inner.level_manifest.read().unwrap().get_log_number();

		// Flush cycle 2
		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("batch2_key_{i}").as_bytes(), b"value2").unwrap();
			txn.commit().await.unwrap();
		}
		tree.flush().unwrap();
		let log_num_2 = tree.core.inner.level_manifest.read().unwrap().get_log_number();

		// Flush cycle 3
		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("batch3_key_{i}").as_bytes(), b"value3").unwrap();
			txn.commit().await.unwrap();
		}
		tree.flush().unwrap();
		let log_num_3 = tree.core.inner.level_manifest.read().unwrap().get_log_number();

		assert!(log_num_2 > log_num_1, "log_number should advance");
		assert!(log_num_3 > log_num_2, "log_number should advance");

		tree.close().await.unwrap();
	}

	// Restart and verify all data accessible from SSTables
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let txn = tree.begin().unwrap();

		// All batches should be accessible (reading doesn't need mut)
		assert_eq!(txn.get(b"batch1_key_0").unwrap(), Some(b"value1".to_vec()));
		assert_eq!(txn.get(b"batch2_key_0").unwrap(), Some(b"value2".to_vec()));
		assert_eq!(txn.get(b"batch3_key_0").unwrap(), Some(b"value3".to_vec()));

		tree.close().await.unwrap();
	}
}

#[tokio::test]
async fn test_shutdown_with_empty_memtable() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |_opts| {});

	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write and flush everything
		let mut txn = tree.begin().unwrap();
		txn.set(b"key", b"value").unwrap();
		txn.commit().await.unwrap();
		tree.flush().unwrap();

		// Get manifest state
		let log_number_before = tree.core.inner.level_manifest.read().unwrap().get_log_number();
		let last_seq_before = tree.core.inner.level_manifest.read().unwrap().get_last_sequence();

		// Shutdown with empty memtable
		tree.close().await.unwrap();

		// Verify manifest unchanged (no unnecessary updates)
		let manifest = LevelManifest::new(Arc::clone(&opts)).unwrap();
		assert_eq!(manifest.get_log_number(), log_number_before);
		assert_eq!(manifest.get_last_sequence(), last_seq_before);
	}

	// Restart successfully
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"key").unwrap(), Some(b"value".to_vec()));
		tree.close().await.unwrap();
	}
}

#[test_log::test(tokio::test)]
async fn test_full_crash_recovery_scenario() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	// Phase 1: Write batch A, flush
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("batch_a_{i}").as_bytes(), b"value_a").unwrap();
			txn.commit().await.unwrap();
		}
		tree.flush().unwrap();
		tree.close().await.unwrap();
	}

	// Phase 2: Write batch B, flush
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("batch_b_{i}").as_bytes(), b"value_b").unwrap();
			txn.commit().await.unwrap();
		}
		tree.flush().unwrap();

		// Get log_number after second flush
		let log_number_after_b = tree.core.inner.level_manifest.read().unwrap().get_log_number();
		assert!(log_number_after_b >= 2, "Should have rotated WAL at least twice");

		tree.close().await.unwrap();
	}

	// Give async cleanup time to finish from Phase 2
	tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

	// Phase 3: Write batch C, crash before flush
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		for i in 0..20 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("batch_c_{i}").as_bytes(), b"value_c").unwrap();
			txn.commit().await.unwrap();
		}

		// Simulate crash: drop without close
		// Release lock manually to allow reopen
		{
			let mut lockfile = tree.core.inner.lockfile.lock().unwrap();
			lockfile.release().unwrap();
		}
		drop(tree);
	}

	// Phase 4: Restart and verify
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// All data should be accessible
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"batch_a_0").unwrap(), Some(b"value_a".to_vec()));
		assert_eq!(txn.get(b"batch_b_0").unwrap(), Some(b"value_b".to_vec()));
		assert_eq!(
			txn.get(b"batch_c_0").unwrap(),
			Some(b"value_c".to_vec()),
			"Batch C should be recovered from WAL"
		);

		tree.close().await.unwrap();
	}
}

#[tokio::test]
async fn test_concurrent_flush_after_rotation() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Write data
	for i in 0..100 {
		let mut txn = tree.begin().unwrap();
		txn.set(format!("key_{i}").as_bytes(), b"value").unwrap();
		txn.commit().await.unwrap();
	}

	// Verify data is accessible before flush
	{
		let txn = tree.begin().unwrap();
		assert_eq!(
			txn.get(b"key_0").unwrap(),
			Some(b"value".to_vec()),
			"Data should be accessible before flush"
		);
	}

	// Call flush which will:
	// 1. Rotate WAL
	// 2. Call flush_memtable_and_update_manifest
	// The function should handle empty memtable gracefully
	tree.flush().unwrap();

	// Verify data is still accessible after flush
	{
		let txn = tree.begin().unwrap();
		assert_eq!(
			txn.get(b"key_0").unwrap(),
			Some(b"value".to_vec()),
			"Data should be accessible after flush"
		);
	}

	// Verify no errors and system continues
	let mut txn = tree.begin().unwrap();
	txn.set(b"after_flush", b"value").unwrap();
	txn.commit().await.unwrap();
	drop(txn);

	// Verify both old and new data are accessible
	{
		let txn = tree.begin().unwrap();
		assert_eq!(
			txn.get(b"key_0").unwrap(),
			Some(b"value".to_vec()),
			"Old data should still be accessible"
		);
		assert_eq!(
			txn.get(b"after_flush").unwrap(),
			Some(b"value".to_vec()),
			"New data after flush should be accessible"
		);
		drop(txn);
	}

	tree.close().await.unwrap();
}

#[test_log::test(tokio::test)]
async fn test_wal_file_reuse_across_restarts() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
	});

	// Phase 1: Open database, write one transaction, close
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1").unwrap();
		txn.commit().await.unwrap();

		tree.close().await.unwrap();
	}

	// Phase 2: Reopen database, check if WAL is reused
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write another transaction
		let mut txn = tree.begin().unwrap();
		txn.set(b"key2", b"value2").unwrap();
		txn.commit().await.unwrap();

		tree.close().await.unwrap();
	}

	// Phase 3: Verify recovery
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let txn = tree.begin().unwrap();

		// Both keys should be accessible
		let key1_present = txn.get(b"key1").unwrap().is_some();
		let key2_present = txn.get(b"key2").unwrap().is_some();

		assert!(key1_present && key2_present, "Both keys should be recovered");

		tree.close().await.unwrap();
	}
}

#[test_log::test(tokio::test)]
async fn test_wal_append_after_crash_recovery() {
	// This test verifies that after a crash (no flush), WAL is reused and appended
	// to
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
	});

	// Phase 1: Write data and simulate crash (no clean shutdown)
	let manifest_log = {
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1").unwrap();
		txn.commit().await.unwrap();

		let manifest_log = tree.core.inner.level_manifest.read().unwrap().get_log_number();

		// Simulate crash: drop without close (but release lock)
		{
			let mut lockfile = tree.core.inner.lockfile.lock().unwrap();
			lockfile.release().unwrap();
		}
		drop(tree);

		manifest_log
	};

	// Verify manifest didn't change (no flush happened)
	let manifest = LevelManifest::new(Arc::clone(&opts)).unwrap();
	assert_eq!(manifest.get_log_number(), manifest_log, "Manifest should not change on crash");

	// Phase 2: Reopen and verify WAL is reused (SAME number)
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let wal_num_after_reopen = tree.core.inner.wal.read().get_active_log_number();

		// CRITICAL: WAL number should be SAME as before (appending to existing)
		assert_eq!(wal_num_after_reopen, 0, "WAL should reuse existing file #0 since log_number=0");

		// Write another transaction to same WAL
		let mut txn = tree.begin().unwrap();
		txn.set(b"key2", b"value2").unwrap();
		txn.commit().await.unwrap();

		let wal_num_after_write = tree.core.inner.wal.read().get_active_log_number();

		// Should still be same WAL
		assert_eq!(
			wal_num_after_write, wal_num_after_reopen,
			"Should still be using same WAL file"
		);

		tree.close().await.unwrap();
	}
}

#[test_log::test(tokio::test)]
async fn test_flush_on_close_creates_sst() {
	// This test verifies that close() flushes active memtable to SST
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
		opts.flush_on_close = true;
	});

	let sst_dir = opts.sstable_dir();

	// Count SST files before
	let count_ssts = || {
		std::fs::read_dir(&sst_dir)
			.ok()
			.map(|entries| {
				entries
					.filter_map(|e| e.ok())
					.filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("sst"))
					.count()
			})
			.unwrap_or(0)
	};

	// Phase 1: Write data and close
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write data to memtable (no manual flush)
		let mut txn = tree.begin().unwrap();
		txn.set(b"test_key", b"test_value").unwrap();
		txn.commit().await.unwrap();

		let sst_count_before_close = count_ssts();

		// Close (should trigger flush)
		tree.close().await.unwrap();

		let sst_count_after_close = count_ssts();

		// CRITICAL: SST count should increase by 1 (memtable flushed)
		assert_eq!(
			sst_count_after_close,
			sst_count_before_close + 1,
			"SST count should increase by 1 after close (flush on shutdown)"
		);
	}

	// Phase 2: Reopen and verify data is in SST (not WAL)
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Memtable should be empty (data in SST)
		// Data should still be accessible
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"test_key").unwrap(), Some(b"test_value".to_vec()));

		tree.close().await.unwrap();
	}
}

#[test_log::test(tokio::test)]
async fn test_multiple_flush_cycles_with_sst_and_wal_verification() {
	// Comprehensive test: multiple write-flush-close cycles
	// Verifies SST creation, WAL rotation, log_number tracking, and recovery
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	let sst_dir = opts.sstable_dir();

	let count_ssts = || {
		std::fs::read_dir(&sst_dir)
			.ok()
			.map(|entries| {
				entries
					.filter_map(|e| e.ok())
					.filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("sst"))
					.count()
			})
			.unwrap_or(0)
	};

	// Cycle 1: Write data, trigger flush, close
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("cycle1_key_{}", i).as_bytes(), b"value1").unwrap();
			txn.commit().await.unwrap();
		}

		let sst_before = count_ssts();
		tree.flush().unwrap(); // Explicit flush
		let sst_after = count_ssts();

		{
			let manifest = tree.core.inner.level_manifest.read().unwrap();
			drop(manifest);
		}

		assert!(sst_after > sst_before, "Flush should create many SST");

		tree.close().await.unwrap();
	}

	// Cycle 2: Reopen, verify recovery, write more, flush, close
	{
		let manifest_before = LevelManifest::new(Arc::clone(&opts)).unwrap();
		let log_num_before = manifest_before.get_log_number();

		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify cycle 1 data is accessible
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"cycle1_key_0").unwrap(), Some(b"value1".to_vec()));
		drop(txn);

		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("cycle2_key_{}", i).as_bytes(), b"value2").unwrap();
			txn.commit().await.unwrap();
		}

		let sst_before = count_ssts();
		tree.flush().unwrap();
		let sst_after = count_ssts();

		{
			let manifest = tree.core.inner.level_manifest.read().unwrap();

			assert!(sst_after > sst_before, "Second flush should create more SST");
			assert!(manifest.get_log_number() > log_num_before, "log_number should advance");
			drop(manifest);
		}

		tree.close().await.unwrap();
	}

	// Cycle 3: Reopen, write but DON'T flush, close (tests shutdown flush)
	{
		// Enable flush_on_close to test shutdown flush behavior
		let opts_with_flush = Arc::new(Options {
			flush_on_close: true,
			..(*opts).clone()
		});
		let tree = Tree::new(opts_with_flush).unwrap();

		// Verify both previous cycles' data
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"cycle1_key_0").unwrap(), Some(b"value1".to_vec()));
		assert_eq!(txn.get(b"cycle2_key_0").unwrap(), Some(b"value2".to_vec()));
		drop(txn);

		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("cycle3_key_{}", i).as_bytes(), b"value3").unwrap();
			txn.commit().await.unwrap();
		}

		let sst_before_close = count_ssts();

		// Close WITHOUT explicit flush (shutdown should flush because
		// flush_on_close=true)
		tree.close().await.unwrap();

		let sst_after_close = count_ssts();

		assert!(
			sst_after_close > sst_before_close,
			"Shutdown should flush and create SST when flush_on_close=true"
		);
	}

	// Final verification: All data accessible from SSTs
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"cycle1_key_0").unwrap(), Some(b"value1".to_vec()));
		assert_eq!(txn.get(b"cycle2_key_0").unwrap(), Some(b"value2".to_vec()));
		assert_eq!(txn.get(b"cycle3_key_0").unwrap(), Some(b"value3".to_vec()));

		tree.close().await.unwrap();
	}
}

#[tokio::test]
async fn test_close_without_flush() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.flush_on_close = false; // Default behavior
		opts.max_memtable_size = 1024 * 1024;
	});

	let sst_count_before;
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write some data that won't trigger auto-flush
		for i in 0..10 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key_{}", i).as_bytes(), b"value").unwrap();
			txn.commit().await.unwrap();
		}

		// Count SSTs before close
		sst_count_before = tree.core.inner.level_manifest.read().as_ref().iter().count();

		// Close without flush (flush_on_close=false)
		tree.close().await.unwrap();
	}

	// Reopen and verify SST count hasn't changed
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let sst_count_after = tree.core.inner.level_manifest.read().as_ref().iter().count();

		assert_eq!(
			sst_count_after, sst_count_before,
			"SST count should not increase when flush_on_close=false"
		);

		// Data should still be accessible via WAL recovery
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"key_0").unwrap(), Some(b"value".to_vec()));

		tree.close().await.unwrap();
	}
}

#[tokio::test]
async fn test_flush_on_close_option_comparison() {
	// Test with flush_on_close = true
	{
		let temp_dir = TempDir::new("test").unwrap();
		let opts = create_test_options(temp_dir.path().to_path_buf(), |opts| {
			opts.flush_on_close = true;
		});

		let sst_before;
		{
			let tree = Tree::new(Arc::clone(&opts)).unwrap();
			let mut txn = tree.begin().unwrap();
			txn.set(b"test", b"data").unwrap();
			txn.commit().await.unwrap();

			sst_before = tree.core.inner.level_manifest.read().unwrap().iter().count();

			tree.close().await.unwrap();
		}

		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let sst_after = tree.core.inner.level_manifest.read().unwrap().iter().count();

		assert_eq!(sst_after, sst_before + 1, "flush_on_close=true should create SST");
		tree.close().await.unwrap();
	}

	// Test with flush_on_close = false
	{
		let temp_dir = TempDir::new("test").unwrap();
		let opts = create_test_options(temp_dir.path().to_path_buf(), |opts| {
			opts.flush_on_close = false;
		});

		let sst_before;
		{
			let tree = Tree::new(Arc::clone(&opts)).unwrap();
			let mut txn = tree.begin().unwrap();
			txn.set(b"test", b"data").unwrap();
			txn.commit().await.unwrap();

			sst_before = tree.core.inner.level_manifest.read().unwrap().iter().count();

			tree.close().await.unwrap();
		}

		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let sst_after = tree.core.inner.level_manifest.read().unwrap().iter().count();

		assert_eq!(sst_after, sst_before, "flush_on_close=false should NOT create SST");

		// But data should still be accessible via WAL
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"test").unwrap(), Some(b"data".to_vec()));

		tree.close().await.unwrap();
	}
}

/// Tests that flush_all_memtables_for_shutdown flushes both immutable and
/// active memtables in the correct order (immutables first, then active)
/// to preserve SSTable ordering.
#[test_log::test(tokio::test)]
async fn test_flush_all_memtables_on_close_ordering() {
	// This test verifies that close() flushes ALL memtables (immutable + active)
	// and that SSTable table_ids are in correct temporal order
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
		opts.flush_on_close = true;
	});

	let sst_dir = opts.sstable_dir();

	// Helper to count SST files
	let count_ssts = || -> usize {
		std::fs::read_dir(&sst_dir)
			.ok()
			.map(|entries| {
				entries
					.filter_map(|e| e.ok())
					.filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("sst"))
					.count()
			})
			.unwrap_or(0)
	};

	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write enough data to trigger multiple memtable flushes
		// This creates immutable memtables in the background
		for i in 0..50 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key_{:04}", i).as_bytes(), b"value_data_here").unwrap();
			txn.commit().await.unwrap();
		}

		// Wait a bit for background flushes to start
		tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

		let sst_count_before_close = count_ssts();
		log::info!("SST count before close: {}", sst_count_before_close);

		// Write one more entry to ensure active memtable has data
		let mut txn = tree.begin().unwrap();
		txn.set(b"final_key", b"final_value").unwrap();
		txn.commit().await.unwrap();

		// Close - should flush all remaining memtables
		tree.close().await.unwrap();

		let sst_count_after_close = count_ssts();
		log::info!("SST count after close: {}", sst_count_after_close);

		// Should have at least one more SST from the close flush
		assert!(
			sst_count_after_close >= sst_count_before_close,
			"SST count should not decrease after close"
		);
	}

	// Reopen and verify all data is accessible
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify data from all writes
		for i in 0..50 {
			let txn = tree.begin().unwrap();
			let key = format!("key_{:04}", i);
			let value = txn.get(key.as_bytes()).unwrap();
			assert!(value.is_some(), "Key {} should exist after close/reopen", key);
		}

		// Verify final key
		let txn = tree.begin().unwrap();
		assert_eq!(
			txn.get(b"final_key").unwrap(),
			Some(b"final_value".to_vec()),
			"Final key should exist after close/reopen"
		);

		tree.close().await.unwrap();
	}
}

/// Tests that pending immutable memtables are flushed during close even
/// when the active memtable is empty.
#[test_log::test(tokio::test)]
async fn test_flush_immutable_memtables_with_empty_active() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
		opts.flush_on_close = true;
	});

	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write data to trigger a memtable flush (creates immutable memtable)
		for i in 0..20 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key_{}", i).as_bytes(), b"value_data").unwrap();
			txn.commit().await.unwrap();
		}

		// Wait for background flush to complete
		tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

		// After flush, active memtable should be empty
		// Close should handle this correctly
		tree.close().await.unwrap();
	}

	// Reopen and verify data
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		for i in 0..20 {
			let txn = tree.begin().unwrap();
			let key = format!("key_{}", i);
			assert!(txn.get(key.as_bytes()).unwrap().is_some(), "Key {} should exist", key);
		}

		tree.close().await.unwrap();
	}
}

/// Tests that SSTable table_ids are in correct ascending order after
/// flushing immutable memtables followed by active memtable.
#[test_log::test(tokio::test)]
async fn test_sst_table_ids_ordered_correctly_on_close() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
		opts.flush_on_close = true;
	});

	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write data - will be flushed on close
		for i in 0..5 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key_{}", i).as_bytes(), b"value").unwrap();
			txn.commit().await.unwrap();
		}

		// Get initial table count
		let initial_count = tree.core.inner.level_manifest.read().unwrap().iter().count();

		// Close triggers flush
		tree.close().await.unwrap();

		// Reopen and verify table count increased
		let tree2 = Tree::new(Arc::clone(&opts)).unwrap();
		let after_count = tree2.core.inner.level_manifest.read().unwrap().iter().count();

		assert_eq!(after_count, initial_count + 1, "Should have one more SST after close flush");

		// Verify table_ids are in ascending order
		{
			let manifest = tree2.core.inner.level_manifest.read().unwrap();
			let mut prev_id = 0u64;
			for table in manifest.iter() {
				assert!(
					table.id > prev_id || prev_id == 0,
					"Table IDs should be in ascending order: prev={}, current={}",
					prev_id,
					table.id
				);
				prev_id = table.id;
			}
		} // Drop manifest before await

		tree2.close().await.unwrap();
	}
}

/// Tests that WAL numbers are correctly tracked with memtables and that
/// log_number is updated incrementally as each memtable is flushed.
#[test_log::test(tokio::test)]
async fn test_wal_number_tracking_on_flush() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large - prevent auto flush
		opts.flush_on_close = true;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Get initial state
	let initial_log_number = tree.core.inner.level_manifest.read().unwrap().get_log_number();
	let initial_wal_number = tree.core.inner.active_memtable.read().unwrap().get_wal_number();
	log::info!(
		"Initial state: log_number={}, wal_number={}",
		initial_log_number,
		initial_wal_number
	);

	// Write some data
	let mut txn = tree.begin().unwrap();
	txn.set(b"key1", b"value1").unwrap();
	txn.commit().await.unwrap();

	// Explicitly flush
	tree.flush().unwrap();

	// Verify log_number increased to wal_number + 1
	let after_flush_log = tree.core.inner.level_manifest.read().unwrap().get_log_number();
	assert_eq!(
		after_flush_log,
		initial_wal_number + 1,
		"log_number should be initial_wal + 1 after flush"
	);

	// Verify new memtable has new WAL number
	let new_wal_number = tree.core.inner.active_memtable.read().unwrap().get_wal_number();
	assert!(
		new_wal_number > initial_wal_number,
		"New memtable should have higher WAL number: {} > {}",
		new_wal_number,
		initial_wal_number
	);
	log::info!(
		"After first flush: log_number={}, new_wal_number={}",
		after_flush_log,
		new_wal_number
	);

	// Second write + flush cycle
	let mut txn = tree.begin().unwrap();
	txn.set(b"key2", b"value2").unwrap();
	txn.commit().await.unwrap();

	tree.flush().unwrap();

	let after_second_flush_log = tree.core.inner.level_manifest.read().unwrap().get_log_number();
	assert_eq!(
		after_second_flush_log,
		new_wal_number + 1,
		"log_number should be new_wal + 1 after second flush"
	);
	log::info!("After second flush: log_number={}", after_second_flush_log);

	// Verify data survives close/reopen
	tree.close().await.unwrap();

	let tree2 = Tree::new(Arc::clone(&opts)).unwrap();

	let txn = tree2.begin().unwrap();
	assert_eq!(
		txn.get(b"key1").unwrap(),
		Some(b"value1".to_vec()),
		"key1 should exist after reopen"
	);
	assert_eq!(
		txn.get(b"key2").unwrap(),
		Some(b"value2".to_vec()),
		"key2 should exist after reopen"
	);

	tree2.close().await.unwrap();
}

/// Tests that the active memtable's WAL number is correctly updated after
/// each memtable swap during flush.
#[test_log::test(tokio::test)]
async fn test_memtable_wal_number_after_swap() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large - prevent auto flush
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Track WAL numbers through explicit flush cycles
	let wal_1 = tree.core.inner.active_memtable.read().unwrap().get_wal_number();
	log::info!("Initial WAL number: {}", wal_1);

	// Write data and flush
	let mut txn = tree.begin().unwrap();
	txn.set(b"key1", b"value1").unwrap();
	txn.commit().await.unwrap();

	tree.flush().unwrap();

	let wal_2 = tree.core.inner.active_memtable.read().unwrap().get_wal_number();
	log::info!("WAL number after first flush: {}", wal_2);
	assert!(wal_2 > wal_1, "WAL number should increase after flush: {} > {}", wal_2, wal_1);

	// Write more and flush again
	let mut txn = tree.begin().unwrap();
	txn.set(b"key2", b"value2").unwrap();
	txn.commit().await.unwrap();

	tree.flush().unwrap();

	let wal_3 = tree.core.inner.active_memtable.read().unwrap().get_wal_number();
	log::info!("WAL number after second flush: {}", wal_3);
	assert!(wal_3 > wal_2, "WAL number should increase after second flush: {} > {}", wal_3, wal_2);

	// Verify data survives close/reopen
	tree.close().await.unwrap();

	let tree2 = Tree::new(Arc::clone(&opts)).unwrap();

	let txn = tree2.begin().unwrap();
	assert_eq!(
		txn.get(b"key1").unwrap(),
		Some(b"value1".to_vec()),
		"key1 should exist after reopen"
	);
	assert_eq!(
		txn.get(b"key2").unwrap(),
		Some(b"value2".to_vec()),
		"key2 should exist after reopen"
	);

	tree2.close().await.unwrap();
}

/// Tests that after multiple flushes and reopen, the new active memtable
/// has the correct WAL number assigned.
#[test_log::test(tokio::test)]
async fn test_wal_number_correct_after_reopen() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large - prevent auto flush
		opts.flush_on_close = true;
	});

	// Phase 1: Multiple flushes, track WAL numbers
	let final_log_number;
	let last_flushed_wal;
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Do 3 write+flush cycles, tracking the last WAL that gets flushed
		let mut current_wal;
		for i in 0..3 {
			// Get the WAL number before flush - this WAL will be flushed
			current_wal = tree.core.inner.active_memtable.read().unwrap().get_wal_number();

			let mut txn = tree.begin().unwrap();
			txn.set(format!("key{}", i).as_bytes(), b"value").unwrap();
			txn.commit().await.unwrap();
			tree.flush().unwrap();

			log::info!(
				"After flush {}: flushed WAL {}, new log_number={}",
				i,
				current_wal,
				tree.core.inner.level_manifest.read().unwrap().get_log_number()
			);
		}

		// The last WAL that was flushed is the one before the final flush
		last_flushed_wal = tree.core.inner.level_manifest.read().unwrap().get_log_number() - 1;
		final_log_number = tree.core.inner.level_manifest.read().unwrap().get_log_number();

		log::info!(
			"Before close: last_flushed_wal={}, final_log_number={}",
			last_flushed_wal,
			final_log_number
		);

		tree.close().await.unwrap();
	}

	// Phase 2: Reopen and verify active memtable's WAL number
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let reopened_log_number = tree.core.inner.level_manifest.read().unwrap().get_log_number();
		let active_wal_number = tree.core.inner.active_memtable.read().unwrap().get_wal_number();

		log::info!(
			"After reopen: log_number={}, active_wal_number={}, last_flushed_wal={}",
			reopened_log_number,
			active_wal_number,
			last_flushed_wal
		);

		// log_number should be preserved from before close
		assert_eq!(
			reopened_log_number, final_log_number,
			"log_number should be preserved after reopen"
		);

		// Active memtable's WAL number should be exactly log_number
		// because WAL opens starting from log_number
		assert_eq!(
			active_wal_number, reopened_log_number,
			"Active memtable WAL number should equal log_number on fresh open"
		);

		// Active WAL number should be greater than the last flushed WAL
		// (log_number = last_flushed_wal + 1)
		assert!(
			active_wal_number > last_flushed_wal,
			"Active WAL number should be > last flushed WAL: {} > {}",
			active_wal_number,
			last_flushed_wal
		);

		// More specifically, it should be exactly last_flushed_wal + 1
		assert_eq!(
			active_wal_number,
			last_flushed_wal + 1,
			"Active WAL number should be last_flushed_wal + 1"
		);

		tree.close().await.unwrap();
	}
}

#[test_log::test(tokio::test)]
async fn test_wal_files_after_multiple_open_close_cycles() {
	// Simulates: open -> write 100 entries -> close, repeated multiple times
	// Tests that data is recoverable and manifest state is correct after each cycle
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
	});

	let mut previous_log_numbers = Vec::new();

	for cycle in 1..=3 {
		{
			let tree = Tree::new(Arc::clone(&opts)).unwrap();

			// Write 100 entries
			for i in 0..100 {
				let mut txn = tree.begin().unwrap();
				txn.set(format!("cycle{}_key_{}", cycle, i).as_bytes(), b"value").unwrap();
				txn.commit().await.unwrap();
			}

			// Close (should flush)
			tree.close().await.unwrap();

			// Give async cleanup time to run
			tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
		}

		// Check manifest state after close
		let manifest = LevelManifest::new(Arc::clone(&opts)).unwrap();
		let log_number_after_close = manifest.get_log_number();
		previous_log_numbers.push(log_number_after_close);

		// Verify data from this cycle is accessible
		{
			let tree = Tree::new(Arc::clone(&opts)).unwrap();
			let txn = tree.begin().unwrap();

			// Check data from current cycle
			assert_eq!(
				txn.get(format!("cycle{}_key_0", cycle).as_bytes()).unwrap(),
				Some(b"value".to_vec()),
				"Data from cycle {} should be recoverable",
				cycle
			);

			// Check data from all previous cycles is still accessible
			for prev_cycle in 1..cycle {
				assert_eq!(
					txn.get(format!("cycle{}_key_0", prev_cycle).as_bytes()).unwrap(),
					Some(b"value".to_vec()),
					"Data from previous cycle {} should still be accessible",
					prev_cycle
				);
			}

			drop(txn);
			tree.close().await.unwrap();
		}
	}

	// Final verification: Manifest log_number should have advanced across cycles
	assert!(previous_log_numbers.len() == 3, "Should have collected log numbers from all 3 cycles");

	// Verify all data is still accessible after all cycles
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let txn = tree.begin().unwrap();

		for cycle in 1..=3 {
			assert_eq!(
				txn.get(format!("cycle{}_key_0", cycle).as_bytes()).unwrap(),
				Some(b"value".to_vec()),
				"Data from cycle {} should be accessible in final check",
				cycle
			);
		}

		drop(txn);
		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_cleanup_orphaned_sst_files() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();
	let opts = create_test_options(path.clone(), |_| {});

	// Create initial tree and add some data
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1").unwrap();
		txn.commit().await.unwrap();
		tree.flush().unwrap();
		tree.close().await.unwrap();
	}

	// Manually create an orphaned SST file (simulating incomplete flush)
	let orphaned_table_id = 9999;
	let orphaned_path = opts.sstable_file_path(orphaned_table_id);
	std::fs::write(&orphaned_path, b"fake sst data").unwrap();

	// Verify orphaned file exists
	assert!(orphaned_path.exists(), "Orphaned SST should exist before cleanup");

	// Reopen database - should trigger cleanup
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify orphaned file was deleted
		assert!(!orphaned_path.exists(), "Orphaned SST should be cleaned up");

		// Verify real data still accessible
		let txn = tree.begin().unwrap();
		let result = txn.get(b"key1").unwrap().unwrap();
		assert_eq!(result, b"value1".to_vec());

		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_manifest_atomic_sst_and_log_number() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Use tiny threshold to ensure flush happens
	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Get initial log_number
	let initial_log_number = {
		let manifest = tree.core.inner.level_manifest.read().unwrap();
		manifest.get_log_number()
	};

	// Add data
	for i in 0..100 {
		let mut txn = tree.begin().unwrap();
		txn.set(format!("key{}", i).as_bytes(), b"value").unwrap();
		txn.commit().await.unwrap();
	}

	// Explicitly trigger flush to ensure test reliability
	tree.flush().unwrap();

	// Verify that when SST is added, log_number is also updated
	{
		let manifest = tree.core.inner.level_manifest.read().unwrap();
		let new_log_number = manifest.get_log_number();
		let level0_tables = &manifest.levels.get_levels()[0].tables;

		// SST should be flushed now
		assert!(!level0_tables.is_empty(), "SST should be flushed");
		// And log_number MUST have been updated atomically
		assert!(
			new_log_number > initial_log_number,
			"log_number should be updated atomically with SST addition"
		);
		drop(manifest);
	}

	tree.close().await.unwrap();
}

#[test(tokio::test)]
async fn test_no_spurious_small_flush() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 100 * 1024; // 100KB threshold
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Add small amount of data (way below threshold)
	let mut txn = tree.begin().unwrap();
	txn.set(b"key1", b"value1").unwrap();
	txn.commit().await.unwrap();

	// Manually trigger wake_up (simulating spurious notification)
	if let Some(ref task_manager) = *tree.core.task_manager.lock().unwrap() {
		task_manager.wake_up_memtable();
	}

	// Wait a bit
	tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

	// Verify no flush occurred (data still in active memtable, not in L0)
	{
		let manifest = tree.core.inner.level_manifest.read().unwrap();
		assert!(
			manifest.levels.get_levels()[0].tables.is_empty(),
			"Should not flush small memtable due to spurious notification"
		);
		drop(manifest);
	}

	tree.close().await.unwrap();
}

#[test(tokio::test)]
async fn test_crash_recovery_with_orphaned_sst() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();
	let opts = create_test_options(path.clone(), |_| {});

	// Phase 1: Write data and flush
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"committed_key", b"committed_value").unwrap();
		txn.commit().await.unwrap();
		tree.flush().unwrap();
		tree.close().await.unwrap();
	}

	// Phase 2: Simulate incomplete flush (create orphaned SST + keep WAL)
	let orphaned_table_id = 9998;
	let orphaned_sst_path = opts.sstable_file_path(orphaned_table_id);
	std::fs::write(&orphaned_sst_path, b"orphaned SST content").unwrap();

	// Add more data that would be in WAL
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"wal_key", b"wal_value").unwrap();
		txn.commit().await.unwrap();
		// Don't flush - keep in WAL
		tree.close().await.unwrap();
	}

	// Phase 3: Reopen - should cleanup orphaned SST and recover from WAL
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify orphaned SST was cleaned up
		assert!(!orphaned_sst_path.exists(), "Orphaned SST should be removed");

		// Verify WAL data was recovered
		let txn = tree.begin().unwrap();
		let result = txn.get(b"wal_key").unwrap().unwrap();
		assert_eq!(result, b"wal_value".to_vec());

		// Verify committed data still accessible
		let result = txn.get(b"committed_key").unwrap().unwrap();
		assert_eq!(result, b"committed_value".to_vec());

		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_cleanup_multiple_orphaned_ssts() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();
	let opts = create_test_options(path.clone(), |_| {});

	// Create initial database
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1").unwrap();
		txn.commit().await.unwrap();
		tree.close().await.unwrap();
	}

	// Create multiple orphaned SST files
	let orphaned_ids = vec![8888, 9999, 10000];
	for table_id in &orphaned_ids {
		let orphaned_path = opts.sstable_file_path(*table_id);
		std::fs::write(&orphaned_path, format!("orphaned {}", table_id)).unwrap();
	}

	// Verify all exist
	for table_id in &orphaned_ids {
		assert!(opts.sstable_file_path(*table_id).exists());
	}

	// Reopen - should cleanup all orphaned files
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify all orphaned files deleted
		for table_id in &orphaned_ids {
			assert!(
				!opts.sstable_file_path(*table_id).exists(),
				"Orphaned SST {} should be cleaned up",
				table_id
			);
		}

		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_valid_ssts_not_deleted_during_cleanup() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();
	let opts = create_small_memtable_options(path.clone());

	// Create database and flush some data
	let valid_table_ids = {
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		for i in 0..200 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key{}", i).as_bytes(), b"value").unwrap();
			txn.commit().await.unwrap();
		}

		tree.flush().unwrap();

		// Get list of valid table IDs
		let ids = {
			let manifest = tree.core.inner.level_manifest.read().unwrap();
			let ids: Vec<u64> = manifest.iter().map(|t| t.id).collect();
			drop(manifest);
			ids
		};

		tree.close().await.unwrap();
		ids
	};

	// Create orphaned SST
	let orphaned_id = 9999;
	std::fs::write(opts.sstable_file_path(orphaned_id), b"orphaned").unwrap();

	// Reopen
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify orphaned deleted
		assert!(!opts.sstable_file_path(orphaned_id).exists());

		// Verify all valid SSTs still exist
		for table_id in &valid_table_ids {
			assert!(
				opts.sstable_file_path(*table_id).exists(),
				"Valid SST {} should not be deleted",
				table_id
			);
		}

		// Verify data still accessible
		let txn = tree.begin().unwrap();
		let result = txn.get(b"key1").unwrap().unwrap();
		assert_eq!(result, b"value".to_vec());

		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_comprehensive_orphaned_cleanup_with_multiple_ssts() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024; // Small to create multiple SSTs
	});

	// Phase 1: Create multiple valid SSTs with real data
	let mut expected_keys = Vec::new();
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write multiple batches to create multiple SSTs
		for batch_num in 0..5 {
			for i in 0..50 {
				let key = format!("batch{}_key{}", batch_num, i);
				let value = format!("batch{}_value{}", batch_num, i);
				expected_keys.push(key.clone());

				let mut txn = tree.begin().unwrap();
				txn.set(key.as_bytes(), value.as_bytes()).unwrap();
				txn.commit().await.unwrap();
			}
			// Force flush after each batch
			tree.flush().unwrap();
		}

		tree.close().await.unwrap();
	}

	// Phase 2: Get valid SST IDs and create orphaned SSTs
	let valid_sst_ids = {
		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let ids = {
			let manifest = tree.core.inner.level_manifest.read().unwrap();
			let ids: Vec<u64> = manifest.iter().map(|t| t.id).collect();
			drop(manifest);
			ids
		};
		tree.close().await.unwrap();
		ids
	};

	// Create multiple orphaned SST files
	let orphaned_ids = vec![8888, 9999, 10000, 10001];
	for table_id in &orphaned_ids {
		let orphaned_path = opts.sstable_file_path(*table_id);
		std::fs::write(&orphaned_path, format!("orphaned SST {}", table_id)).unwrap();
	}

	// Verify all files exist (both valid and orphaned)
	for table_id in &valid_sst_ids {
		assert!(
			opts.sstable_file_path(*table_id).exists(),
			"Valid SST {} should exist before reopen",
			table_id
		);
	}
	for table_id in &orphaned_ids {
		assert!(
			opts.sstable_file_path(*table_id).exists(),
			"Orphaned SST {} should exist before cleanup",
			table_id
		);
	}

	// Phase 3: Reopen - should cleanup orphaned but keep valid
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify all orphaned files deleted
		for table_id in &orphaned_ids {
			assert!(
				!opts.sstable_file_path(*table_id).exists(),
				"Orphaned SST {} should be cleaned up",
				table_id
			);
		}

		// Verify all valid SST files still exist
		for table_id in &valid_sst_ids {
			assert!(
				opts.sstable_file_path(*table_id).exists(),
				"Valid SST {} should not be deleted",
				table_id
			);
		}

		// Verify ALL data is still accessible
		for key in &expected_keys {
			let txn = tree.begin().unwrap();
			let result = txn.get(key.as_bytes()).unwrap();
			assert!(result.is_some(), "Key {} should be accessible", key);
		}

		// Spot check a few specific values
		let txn = tree.begin().unwrap();
		let result = txn.get(b"batch0_key0").unwrap().unwrap();
		assert_eq!(result, b"batch0_value0".to_vec());

		let result = txn.get(b"batch4_key49").unwrap().unwrap();
		assert_eq!(result, b"batch4_value49".to_vec());

		tree.close().await.unwrap();
	}
}

#[test_log::test(tokio::test)]
async fn test_wal_recovery_mode_absolute_consistency_fails_on_corruption() {
	use std::io::Write;

	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	// Phase 1: Create a valid WAL with some data
	{
		let opts = create_test_options(path.clone(), |opts| {
			opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
			opts.flush_on_close = false; // Don't flush on close - keep data in WAL
		});

		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1").unwrap();
		txn.set(b"key2", b"value2").unwrap();
		txn.commit().await.unwrap();

		// Close without flush - data only in WAL
		tree.close().await.unwrap();
	}

	// Phase 2: Corrupt the WAL file
	let wal_dir = path.join("wal");
	let segment_path = wal_dir.join("00000000000000000000.wal");
	{
		let mut file = std::fs::OpenOptions::new().append(true).open(&segment_path).unwrap();
		file.write_all(b"CORRUPTED_DATA_AT_END").unwrap();
	}

	// Phase 3: Try to open with AbsoluteConsistency mode - should FAIL
	{
		let opts = create_test_options(path.clone(), |opts| {
			opts.wal_recovery_mode = WalRecoveryMode::AbsoluteConsistency;
		});

		let result = Tree::new(opts);

		// Should fail due to corruption
		match result {
			Err(Error::WalCorruption {
				..
			}) => {
				// Expected - AbsoluteConsistency correctly fails on
				// corruption
			}
			Err(e) => panic!("Expected WalCorruption error, got: {}", e),
			Ok(_) => {
				panic!("AbsoluteConsistency should fail on WAL corruption, but it succeeded")
			}
		}
	}
}

#[test_log::test(tokio::test)]
async fn test_wal_recovery_mode_tolerate_with_repair_succeeds_on_corruption() {
	use std::io::Write;

	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	// Phase 1: Create a valid WAL with some data
	{
		let opts = create_test_options(path.clone(), |opts| {
			opts.max_memtable_size = 10 * 1024 * 1024; // Large to prevent auto-flush
			opts.flush_on_close = false; // Don't flush on close - keep data in WAL
		});

		let tree = Tree::new(Arc::clone(&opts)).unwrap();
		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1").unwrap();
		txn.set(b"key2", b"value2").unwrap();
		txn.commit().await.unwrap();

		// Close without flush - data only in WAL
		tree.close().await.unwrap();
	}

	// Phase 2: Corrupt the WAL file at the end
	let wal_dir = path.join("wal");
	let segment_path = wal_dir.join("00000000000000000000.wal");
	{
		let mut file = std::fs::OpenOptions::new().append(true).open(&segment_path).unwrap();
		file.write_all(b"CORRUPTED_DATA_AT_END").unwrap();
	}

	// Phase 3: Open with default TolerateCorruptedWithRepair mode - should SUCCEED
	{
		let opts = create_test_options(path.clone(), |opts| {
			opts.wal_recovery_mode = WalRecoveryMode::TolerateCorruptedWithRepair;
		});

		let result = Tree::new(opts);

		// Should succeed (repair the WAL and recover data)
		let tree = match result {
			Ok(t) => t,
			Err(e) => {
				panic!("TolerateCorruptedWithRepair should succeed after repairing WAL: {}", e)
			}
		};

		// Verify data was recovered
		let txn = tree.begin().unwrap();
		assert_eq!(txn.get(b"key1").unwrap(), Some(b"value1".to_vec()));
		assert_eq!(txn.get(b"key2").unwrap(), Some(b"value2".to_vec()));

		tree.close().await.unwrap();
	}
}

#[test]
fn test_wal_recovery_mode_default_is_tolerate_with_repair() {
	// Verify that the default recovery mode is TolerateCorruptedWithRepair
	let opts = Options::default();
	assert_eq!(
		opts.wal_recovery_mode,
		WalRecoveryMode::TolerateCorruptedWithRepair,
		"Default recovery mode should be TolerateCorruptedWithRepair"
	);
}

#[test_log::test(tokio::test)]
async fn test_wal_incremental_number_after_flush_and_reopen() {
	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 1024;
		opts.flush_on_close = true;
	});

	// Phase 1: Write data and clean shutdown (triggers flush)
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let wal_num_before = tree.core.inner.wal.read().get_active_log_number();
		assert_eq!(wal_num_before, 0, "Fresh database should start at WAL #0");

		let mut txn = tree.begin().unwrap();
		txn.set(b"test_key", b"test_value").unwrap();
		txn.commit().await.unwrap();

		tree.close().await.unwrap();
	}

	// Phase 2: Reopen and verify WAL has incremental number
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let wal_num_after_reopen = tree.core.inner.wal.read().get_active_log_number();

		// CRITICAL: WAL number should be > 0 since WAL #0 was flushed
		assert!(
			wal_num_after_reopen > 0,
			"BUG: After flush and reopen, WAL should start at incremental number, not 0. Got {}",
			wal_num_after_reopen
		);

		tree.close().await.unwrap();
	}
}

/// Tests that new writes after crash recovery are not lost.
///
/// BUG SCENARIO (without fix):
/// 1. Crash with segments 1, 2, 3 on disk, manifest log_number=1
/// 2. Recovery: replays all segments, WAL opens at segment 1 for new writes
/// 3. Write key4 → goes to segment 1
/// 4. Flush → log_number becomes 2
/// 5. Second crash and recovery
/// 6. WAL recovery skips segments < 2 (skips segment 1!)
/// 7. key4 is LOST
///
/// FIX: WAL opens at max(log_number, highest_segment_on_disk)
/// - With fix: WAL opens at segment 3, key4 goes to segment 3
/// - After flush log_number=4, nothing is skipped, no data loss
#[test_log::test(tokio::test)]
async fn test_recovery_with_manually_created_wal_segments() {
	use crate::batch::Batch;
	use crate::vlog::ValueLocation;
	use crate::wal::Wal;

	let temp_dir = TempDir::new("test").unwrap();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.max_memtable_size = 10 * 1024 * 1024; // Large - prevent auto flush
		opts.flush_on_close = false; // Don't auto-flush on close
	});

	let wal_path = opts.path.join("wal");

	// Phase 1: Establish baseline - write key1, flush, close
	// This creates: SST with key1, manifest log_number = 1
	let log_number_after_phase1;
	let last_seq_after_phase1;
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let mut txn = tree.begin().unwrap();
		txn.set(b"key1", b"value1_from_sst").unwrap();
		txn.commit().await.unwrap();
		tree.flush().unwrap();

		log_number_after_phase1 = tree.core.inner.level_manifest.read().unwrap().get_log_number();
		last_seq_after_phase1 = tree.core.inner.level_manifest.read().unwrap().get_last_sequence();
		log::info!(
			"Phase 1: After flush, log_number={}, last_seq={}",
			log_number_after_phase1,
			last_seq_after_phase1
		);

		tree.close().await.unwrap();
	}

	// Phase 2: Manually create WAL segments 2 and 3 with key2 and key3
	// This simulates a crash where WAL rotations happened but manifest wasn't
	// updated
	let highest_segment_created;
	{
		log::info!("Phase 2: Creating additional WAL segments");

		// Find the highest existing segment on disk
		let highest_existing: u64 = std::fs::read_dir(&wal_path)
			.unwrap()
			.filter_map(|e| e.ok())
			.filter_map(|e| {
				e.path()
					.file_name()
					.and_then(|n| n.to_str())
					.and_then(|n| n.strip_suffix(".wal"))
					.and_then(|n| n.parse::<u64>().ok())
			})
			.max()
			.unwrap_or(0);

		// Create segment for key2
		let segment_for_key2 = highest_existing + 1;
		let next_seq = last_seq_after_phase1 + 1;
		{
			let mut batch = Batch::new(next_seq);
			let encoded_value =
				ValueLocation::with_inline_value(b"value2_from_wal".to_vec()).encode();
			batch
				.add_record(InternalKeyKind::Set, b"key2".to_vec(), Some(encoded_value), 0)
				.unwrap();

			let mut wal = Wal::open_with_min_log_number(
				&wal_path,
				segment_for_key2,
				crate::wal::Options::default(),
			)
			.unwrap();
			wal.append(&batch.encode().unwrap()).unwrap();
			wal.sync().unwrap();
			wal.close().unwrap();
			log::info!("Phase 2: Created segment {} with key2", segment_for_key2);
		}

		// Create segment for key3
		let segment_for_key3 = segment_for_key2 + 1;
		{
			let mut batch = Batch::new(next_seq + 1);
			let encoded_value =
				ValueLocation::with_inline_value(b"value3_from_wal".to_vec()).encode();
			batch
				.add_record(InternalKeyKind::Set, b"key3".to_vec(), Some(encoded_value), 0)
				.unwrap();

			let mut wal = Wal::open_with_min_log_number(
				&wal_path,
				segment_for_key3,
				crate::wal::Options::default(),
			)
			.unwrap();
			wal.append(&batch.encode().unwrap()).unwrap();
			wal.sync().unwrap();
			wal.close().unwrap();
			log::info!("Phase 2: Created segment {} with key3", segment_for_key3);
		}

		highest_segment_created = segment_for_key3;
	}

	// Phase 3: First recovery - open Tree, verify key2/key3 recovered, then write
	// NEW data This is where the bug manifests:
	// - WITHOUT FIX: WAL opens at log_number (1), new writes go to segment 1
	// - WITH FIX: WAL opens at highest (3), new writes go to segment 3
	let active_wal_after_recovery;
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		active_wal_after_recovery = tree.core.inner.wal.read().get_active_log_number();
		let log_number = tree.core.inner.level_manifest.read().unwrap().get_log_number();
		log::info!(
			"Phase 3: active_wal={}, log_number={}, highest_created={}",
			active_wal_after_recovery,
			log_number,
			highest_segment_created
		);

		// KEY ASSERTION: WAL should open at highest segment, not log_number
		assert_eq!(
			active_wal_after_recovery, highest_segment_created,
			"BUG: WAL opened at {} but should open at highest segment {} to prevent data loss",
			active_wal_after_recovery, highest_segment_created
		);

		// Verify initial recovery worked
		let txn = tree.begin().unwrap();
		assert!(txn.get(b"key1").unwrap().is_some(), "key1 should exist");
		assert!(txn.get(b"key2").unwrap().is_some(), "key2 should exist");
		assert!(txn.get(b"key3").unwrap().is_some(), "key3 should exist");
		drop(txn);

		// Write NEW data after recovery - this is the data that could be lost
		let mut txn = tree.begin().unwrap();
		txn.set(b"key4_new_after_recovery", b"value4").unwrap();
		txn.commit().await.unwrap();
		log::info!("Phase 3: Wrote key4 to WAL segment {}", active_wal_after_recovery);

		// Flush - this updates log_number
		tree.flush().unwrap();
		let log_number_after_flush =
			tree.core.inner.level_manifest.read().unwrap().get_log_number();
		log::info!("Phase 3: After flush, log_number={}", log_number_after_flush);

		// Write more data that stays in WAL (not flushed)
		let mut txn = tree.begin().unwrap();
		txn.set(b"key5_unflushed", b"value5").unwrap();
		txn.commit().await.unwrap();
		log::info!("Phase 3: Wrote key5 (unflushed)");

		// Close without flush (simulating crash)
		tree.close().await.unwrap();
	}

	// Phase 4: Second recovery - verify NO data loss
	// Without the fix, key4 and key5 would be lost because they were written
	// to segment 1 (if WAL opened there), and segment 1 is now skipped
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		let txn = tree.begin().unwrap();

		// Original data should still exist
		assert!(txn.get(b"key1").unwrap().is_some(), "key1 should persist");
		assert!(txn.get(b"key2").unwrap().is_some(), "key2 should persist");
		assert!(txn.get(b"key3").unwrap().is_some(), "key3 should persist");

		// CRITICAL: New data written after recovery should NOT be lost
		let key4 = txn.get(b"key4_new_after_recovery").unwrap();
		assert_eq!(
			key4,
			Some(b"value4".to_vec()),
			"DATA LOSS BUG: key4 written after recovery was lost! \
				 This happens when WAL opens at log_number instead of highest segment."
		);

		let key5 = txn.get(b"key5_unflushed").unwrap();
		assert_eq!(key5, Some(b"value5".to_vec()), "DATA LOSS BUG: key5 (unflushed) was lost!");

		log::info!("Phase 4: All data verified - no data loss!");

		tree.close().await.unwrap();
	}
}

// Test if flush_wal is concurrent safe and does not block the commit pipeline.
#[test(tokio::test)]
async fn test_flush_wal_concurrent_commits() {
	use std::sync::atomic::{AtomicUsize, Ordering};

	use tokio::task::JoinSet;

	let temp_dir = create_temp_directory();
	let opts = create_test_options(temp_dir.path().to_path_buf(), |opts| {
		opts.enable_vlog = true;
		opts.vlog_value_threshold = 50; // Some values will go to VLog
	});

	let tree = Arc::new(Tree::new(opts).unwrap());
	let commit_count = Arc::new(AtomicUsize::new(0));
	let flush_count = Arc::new(AtomicUsize::new(0));

	let num_commit_tasks = 8;
	let commits_per_task = 25;
	let num_flush_tasks = 2;
	let flushes_per_task = 50;

	let mut join_set = JoinSet::new();

	// Spawn commit tasks
	for task_id in 0..num_commit_tasks {
		let tree = Arc::clone(&tree);
		let commit_count = Arc::clone(&commit_count);

		join_set.spawn(async move {
			for i in 0..commits_per_task {
				let key = format!("task{}_key{}", task_id, i);
				let value = if i % 2 == 0 {
					// Small value (inline)
					format!("value{}", i)
				} else {
					// Large value (VLog)
					"x".repeat(100)
				};

				let mut txn = tree.begin().unwrap();
				txn.set(key.as_bytes(), value.as_bytes()).unwrap();
				txn.commit().await.unwrap();
				commit_count.fetch_add(1, Ordering::SeqCst);
			}
		});
	}

	// Spawn flush tasks
	for _ in 0..num_flush_tasks {
		let tree = Arc::clone(&tree);
		let flush_count = Arc::clone(&flush_count);

		join_set.spawn(async move {
			for i in 0..flushes_per_task {
				// Alternate between flush and sync
				let sync = i % 2 == 0;
				let result = tree.flush_wal(sync);
				assert!(result.is_ok(), "flush_wal should succeed during concurrent commits");
				flush_count.fetch_add(1, Ordering::SeqCst);
				// Small yield to allow interleaving
				tokio::task::yield_now().await;
			}
		});
	}

	// Wait for all tasks to complete
	while let Some(result) = join_set.join_next().await {
		result.expect("Task should complete successfully");
	}

	// Verify counts
	assert_eq!(
		commit_count.load(Ordering::SeqCst),
		num_commit_tasks * commits_per_task,
		"All commits should complete"
	);
	assert_eq!(
		flush_count.load(Ordering::SeqCst),
		num_flush_tasks * flushes_per_task,
		"All flushes should complete"
	);

	// Verify all data is accessible
	{
		let txn = tree.begin().unwrap();
		for task_id in 0..num_commit_tasks {
			for i in 0..commits_per_task {
				let key = format!("task{}_key{}", task_id, i);
				let result = txn.get(key.as_bytes()).unwrap();
				assert!(result.is_some(), "Key {} should exist after concurrent operations", key);
			}
		}
	}

	tree.close().await.unwrap();
}

/// Test that verifies lexicographic byte ordering with keys of varying lengths.
/// This ensures that keys like "a" < "b" < "ba" < "baaa" < "baaaaaaaaaaaaaaaaaa1" < "c"
/// are correctly ordered during range scans, both before and after flush.
#[test(tokio::test)]
async fn test_range_key_ordering_correctness() {
	use crate::test::collect_transaction_reverse;

	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Keys in expected lexicographic sorted order
	let keys_in_order = ["a", "b", "ba", "baaa", "baaaaaaaaaaaaaaaaaa1", "c"];

	// Insert keys in random order to ensure sorting is done by the system
	let insert_order = ["baaa", "c", "a", "baaaaaaaaaaaaaaaaaa1", "b", "ba"];
	for key in insert_order.iter() {
		let mut txn = tree.begin().unwrap();
		let value = format!("value_for_{}", key);
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Test BEFORE flush (memtable path)
	{
		let txn = tree.begin().unwrap();

		// Forward iteration
		let range_result = collect_transaction_all(&mut txn.range(b"a", b"d").unwrap()).unwrap();

		assert_eq!(
			range_result.len(),
			keys_in_order.len(),
			"Should return all {} keys",
			keys_in_order.len()
		);

		// Verify forward order
		for (idx, (key, value)) in range_result.iter().enumerate() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			let expected_key = keys_in_order[idx];
			let expected_value = format!("value_for_{}", expected_key);

			assert_eq!(
				key_str, expected_key,
				"Forward iteration: Key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
			);
			assert_eq!(
				value.as_slice(),
				expected_value.as_bytes(),
				"Forward iteration: Value mismatch at index {idx}"
			);
		}

		// Reverse iteration
		let reverse_result =
			collect_transaction_reverse(&mut txn.range(b"a", b"d").unwrap()).unwrap();

		assert_eq!(
			reverse_result.len(),
			keys_in_order.len(),
			"Reverse should return all {} keys",
			keys_in_order.len()
		);

		// Verify reverse order
		for (idx, (key, _value)) in reverse_result.iter().enumerate() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			let expected_key = keys_in_order[keys_in_order.len() - 1 - idx];

			assert_eq!(
				key_str, expected_key,
				"Reverse iteration: Key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
			);
		}
	}

	// Flush to disk
	tree.flush().unwrap();

	// Test AFTER flush (SSTable path)
	{
		let txn = tree.begin().unwrap();

		// Forward iteration
		let range_result = collect_transaction_all(&mut txn.range(b"a", b"d").unwrap()).unwrap();

		assert_eq!(
			range_result.len(),
			keys_in_order.len(),
			"After flush: Should return all {} keys",
			keys_in_order.len()
		);

		// Verify forward order after flush
		for (idx, (key, value)) in range_result.iter().enumerate() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			let expected_key = keys_in_order[idx];
			let expected_value = format!("value_for_{}", expected_key);

			assert_eq!(
				key_str, expected_key,
				"After flush forward: Key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
			);
			assert_eq!(
				value.as_slice(),
				expected_value.as_bytes(),
				"After flush forward: Value mismatch at index {idx}"
			);
		}

		// Reverse iteration after flush
		let reverse_result =
			collect_transaction_reverse(&mut txn.range(b"a", b"d").unwrap()).unwrap();

		for (idx, (key, _value)) in reverse_result.iter().enumerate() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			let expected_key = keys_in_order[keys_in_order.len() - 1 - idx];

			assert_eq!(
				key_str, expected_key,
				"After flush reverse: Key mismatch at index {idx}: expected '{expected_key}', found '{key_str}'"
			);
		}
	}
}

/// Test that keys with common prefixes are correctly differentiated.
/// This tests SurrealDB-like namespace patterns where table records and index records
/// share a common prefix but should be distinguishable by range scans.
///
/// If partial prefix matching incorrectly includes wrong records, deserializing
/// an index record as a table record (or vice versa) would cause errors.
#[test(tokio::test)]
async fn test_range_prefix_differentiation() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Table records: /ns/db/tb/<id>
	// Index records: /ns/db/ix/<name>
	let table_records = [
		("/ns/db/tb/1", "TableRecord1"),
		("/ns/db/tb/2", "TableRecord2"),
		("/ns/db/tb/10", "TableRecord10"),
		("/ns/db/tb/100", "TableRecord100"),
	];

	let index_records =
		[("/ns/db/ix/a", "IndexA"), ("/ns/db/ix/b", "IndexB"), ("/ns/db/ix/name_idx", "IndexName")];

	// Insert all records
	for (key, value) in table_records.iter().chain(index_records.iter()) {
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), value.as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Test before flush
	{
		let txn = tree.begin().unwrap();

		// Range scan for table records only: [/ns/db/tb/, /ns/db/tb0)
		let table_range =
			collect_transaction_all(&mut txn.range(b"/ns/db/tb/", b"/ns/db/tb0").unwrap()).unwrap();

		assert_eq!(
			table_range.len(),
			table_records.len(),
			"Table range should return exactly {} table records, got {}",
			table_records.len(),
			table_range.len()
		);

		// Verify all returned keys are table records
		for (key, value) in table_range.iter() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			assert!(
				key_str.starts_with("/ns/db/tb/"),
				"Key '{}' should be a table record (start with /ns/db/tb/)",
				key_str
			);
			// Verify it's NOT an index record
			assert!(
				!key_str.starts_with("/ns/db/ix/"),
				"Table range should NOT contain index record '{}'",
				key_str
			);
			// Verify value is a table record value
			let value_str = std::str::from_utf8(value.as_ref()).unwrap();
			assert!(
				value_str.starts_with("TableRecord"),
				"Value '{}' should be a TableRecord",
				value_str
			);
		}

		// Range scan for index records only: [/ns/db/ix/, /ns/db/ix0)
		let index_range =
			collect_transaction_all(&mut txn.range(b"/ns/db/ix/", b"/ns/db/ix0").unwrap()).unwrap();

		assert_eq!(
			index_range.len(),
			index_records.len(),
			"Index range should return exactly {} index records, got {}",
			index_records.len(),
			index_range.len()
		);

		// Verify all returned keys are index records
		for (key, value) in index_range.iter() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			assert!(
				key_str.starts_with("/ns/db/ix/"),
				"Key '{}' should be an index record (start with /ns/db/ix/)",
				key_str
			);
			// Verify it's NOT a table record
			assert!(
				!key_str.starts_with("/ns/db/tb/"),
				"Index range should NOT contain table record '{}'",
				key_str
			);
			// Verify value is an index record value
			let value_str = std::str::from_utf8(value.as_ref()).unwrap();
			assert!(value_str.starts_with("Index"), "Value '{}' should be an Index", value_str);
		}
	}

	// Flush and test after flush
	tree.flush().unwrap();

	{
		let txn = tree.begin().unwrap();

		// Same tests after flush
		let table_range =
			collect_transaction_all(&mut txn.range(b"/ns/db/tb/", b"/ns/db/tb0").unwrap()).unwrap();

		assert_eq!(
			table_range.len(),
			table_records.len(),
			"After flush: Table range should return exactly {} table records",
			table_records.len()
		);

		for (key, _value) in table_range.iter() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			assert!(
				key_str.starts_with("/ns/db/tb/"),
				"After flush: Key '{}' should be a table record",
				key_str
			);
		}

		let index_range =
			collect_transaction_all(&mut txn.range(b"/ns/db/ix/", b"/ns/db/ix0").unwrap()).unwrap();

		assert_eq!(
			index_range.len(),
			index_records.len(),
			"After flush: Index range should return exactly {} index records",
			index_records.len()
		);

		for (key, _value) in index_range.iter() {
			let key_str = std::str::from_utf8(key.as_ref()).unwrap();
			assert!(
				key_str.starts_with("/ns/db/ix/"),
				"After flush: Key '{}' should be an index record",
				key_str
			);
		}
	}
}

/// Test that exclusive upper bounds work correctly.
/// The range API uses [start, end) semantics - inclusive start, exclusive end.
#[test(tokio::test)]
async fn test_range_exclusive_boundaries() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert keys: a, b, c, d
	let keys = ["a", "b", "c", "d"];
	for key in keys.iter() {
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), format!("value_{}", key).as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Test before flush
	{
		let txn = tree.begin().unwrap();

		// Range [a, c) should include a, b but NOT c
		let range_result = collect_transaction_all(&mut txn.range(b"a", b"c").unwrap()).unwrap();

		assert_eq!(range_result.len(), 2, "Range [a, c) should return 2 keys (a and b)");

		let result_keys: Vec<String> = range_result
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert!(result_keys.contains(&"a".to_string()), "Range [a, c) should include 'a'");
		assert!(result_keys.contains(&"b".to_string()), "Range [a, c) should include 'b'");
		assert!(!result_keys.contains(&"c".to_string()), "Range [a, c) should NOT include 'c'");
		assert!(!result_keys.contains(&"d".to_string()), "Range [a, c) should NOT include 'd'");

		// Range [b, d) should include b, c but NOT d
		let range_result2 = collect_transaction_all(&mut txn.range(b"b", b"d").unwrap()).unwrap();

		assert_eq!(range_result2.len(), 2, "Range [b, d) should return 2 keys (b and c)");

		let result_keys2: Vec<String> = range_result2
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert!(!result_keys2.contains(&"a".to_string()), "Range [b, d) should NOT include 'a'");
		assert!(result_keys2.contains(&"b".to_string()), "Range [b, d) should include 'b'");
		assert!(result_keys2.contains(&"c".to_string()), "Range [b, d) should include 'c'");
		assert!(!result_keys2.contains(&"d".to_string()), "Range [b, d) should NOT include 'd'");

		// Range starting at exact key boundary
		let range_result3 = collect_transaction_all(&mut txn.range(b"c", b"e").unwrap()).unwrap();

		assert_eq!(range_result3.len(), 2, "Range [c, e) should return 2 keys (c and d)");

		let result_keys3: Vec<String> = range_result3
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert!(result_keys3.contains(&"c".to_string()), "Range [c, e) should include 'c'");
		assert!(result_keys3.contains(&"d".to_string()), "Range [c, e) should include 'd'");
	}

	// Flush and test after flush
	tree.flush().unwrap();

	{
		let txn = tree.begin().unwrap();

		// Same tests after flush
		let range_result = collect_transaction_all(&mut txn.range(b"a", b"c").unwrap()).unwrap();

		assert_eq!(range_result.len(), 2, "After flush: Range [a, c) should return 2 keys");

		let result_keys: Vec<String> = range_result
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert!(
			result_keys.contains(&"a".to_string()),
			"After flush: Range [a, c) should include 'a'"
		);
		assert!(
			result_keys.contains(&"b".to_string()),
			"After flush: Range [a, c) should include 'b'"
		);
		assert!(
			!result_keys.contains(&"c".to_string()),
			"After flush: Range [a, c) should NOT include 'c'"
		);
	}
}

/// Test edge cases with keys at boundaries, especially keys that are proper prefixes of each other.
/// This tests scenarios like: aa < aaa < aaaa < ab < b
/// Range [aa, ab) should return aa, aaa, aaaa but NOT ab
#[test(tokio::test)]
async fn test_range_boundary_edge_cases() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_small_memtable_options(path.clone());

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Keys where some are proper prefixes of others
	let keys = ["aa", "aaa", "aaaa", "aaaab", "ab", "b"];
	for key in keys.iter() {
		let mut txn = tree.begin().unwrap();
		txn.set(key.as_bytes(), format!("value_{}", key).as_bytes()).unwrap();
		txn.commit().await.unwrap();
	}

	// Test before flush
	{
		let txn = tree.begin().unwrap();

		// Range [aa, ab) should return aa, aaa, aaaa, aaaab but NOT ab, b
		let range_result = collect_transaction_all(&mut txn.range(b"aa", b"ab").unwrap()).unwrap();

		let result_keys: Vec<String> = range_result
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert_eq!(
			range_result.len(),
			4,
			"Range [aa, ab) should return 4 keys (aa, aaa, aaaa, aaaab), got: {:?}",
			result_keys
		);

		assert!(result_keys.contains(&"aa".to_string()), "Should include 'aa'");
		assert!(result_keys.contains(&"aaa".to_string()), "Should include 'aaa'");
		assert!(result_keys.contains(&"aaaa".to_string()), "Should include 'aaaa'");
		assert!(result_keys.contains(&"aaaab".to_string()), "Should include 'aaaab'");
		assert!(!result_keys.contains(&"ab".to_string()), "Should NOT include 'ab' (upper bound)");
		assert!(!result_keys.contains(&"b".to_string()), "Should NOT include 'b'");

		// Verify ordering within the result
		assert_eq!(result_keys[0], "aa", "First key should be 'aa'");
		assert_eq!(result_keys[1], "aaa", "Second key should be 'aaa'");
		assert_eq!(result_keys[2], "aaaa", "Third key should be 'aaaa'");
		assert_eq!(result_keys[3], "aaaab", "Fourth key should be 'aaaab'");

		// Range [aaa, aaaa) - very narrow range between prefixes
		let narrow_range =
			collect_transaction_all(&mut txn.range("aaa".as_bytes(), "aaaa".as_bytes()).unwrap())
				.unwrap();

		let narrow_keys: Vec<String> = narrow_range
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert_eq!(
			narrow_range.len(),
			1,
			"Range [aaa, aaaa) should return only 'aaa', got: {:?}",
			narrow_keys
		);
		assert_eq!(narrow_keys[0], "aaa", "Only key should be 'aaa'");

		// Range [aaaa, ab) - starts exactly at 'aaaa'
		let exact_start =
			collect_transaction_all(&mut txn.range("aaaa".as_bytes(), "ab".as_bytes()).unwrap())
				.unwrap();

		let exact_keys: Vec<String> = exact_start
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert_eq!(
			exact_start.len(),
			2,
			"Range [aaaa, ab) should return 'aaaa' and 'aaaab', got: {:?}",
			exact_keys
		);
		assert!(exact_keys.contains(&"aaaa".to_string()), "Should include 'aaaa'");
		assert!(exact_keys.contains(&"aaaab".to_string()), "Should include 'aaaab'");
	}

	// Flush and test after flush
	tree.flush().unwrap();

	{
		let txn = tree.begin().unwrap();

		// Same primary test after flush
		let range_result = collect_transaction_all(&mut txn.range(b"aa", b"ab").unwrap()).unwrap();

		let result_keys: Vec<String> = range_result
			.iter()
			.map(|(k, _)| std::str::from_utf8(k.as_ref()).unwrap().to_string())
			.collect();

		assert_eq!(
			range_result.len(),
			4,
			"After flush: Range [aa, ab) should return 4 keys, got: {:?}",
			result_keys
		);

		// Verify ordering is maintained after flush
		assert_eq!(result_keys[0], "aa", "After flush: First key should be 'aa'");
		assert_eq!(result_keys[1], "aaa", "After flush: Second key should be 'aaa'");
		assert_eq!(result_keys[2], "aaaa", "After flush: Third key should be 'aaaa'");
		assert_eq!(result_keys[3], "aaaab", "After flush: Fourth key should be 'aaaab'");
	}
}

/// Tests that versioned_index cleanup is triggered after VLog GC
/// and that data integrity is maintained.
#[test(tokio::test)]
async fn test_versioned_index_cleanup_after_vlog_gc() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Create tree with versioned_index AND vlog enabled
	// Note: versioned_index requires versioning to be enabled
	let opts = create_test_options(path.clone(), |opts| {
		opts.level_count = 2;
		opts.vlog_max_file_size = 50; // Very small to force multiple VLog files
		opts.enable_vlog = true;
		opts.enable_versioning = true;
		opts.versioned_history_retention_ns = 1_000_000_000_000; // 1000 seconds
		opts.enable_versioned_index = true;
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Insert multiple key-value pairs that will go to VLog
	let keys: Vec<String> = (0..10).map(|i| format!("key-{:04}", i)).collect();
	let value = "x".repeat(100); // Large value to force VLog storage

	// Insert first version of each key
	for key in &keys {
		let mut tx = tree.begin().unwrap();
		tx.set(key.as_bytes(), value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
	}
	tree.flush().unwrap();

	// Insert second version (updates) to create older versions
	let value2 = "y".repeat(100);
	for key in &keys {
		let mut tx = tree.begin().unwrap();
		tx.set(key.as_bytes(), value2.as_bytes()).unwrap();
		tx.commit().await.unwrap();
	}
	tree.flush().unwrap();

	// Force compaction to trigger VLog GC and versioned_index cleanup
	let strategy = Arc::new(Strategy::default());
	tree.compact(strategy).unwrap();

	// Verify that latest values are still accessible
	for key in &keys {
		let tx = tree.begin().unwrap();
		let result = tx.get(key.as_bytes()).unwrap();
		assert_eq!(
			result,
			Some(value2.as_bytes().to_vec()),
			"Key {} should have latest value",
			key
		);
	}
}

/// Tests that versioned_index cleanup is deadlock-free when running
/// concurrently with writes.
#[test(tokio::test)]
async fn test_versioned_index_cleanup_concurrent_with_writes() {
	use std::time::Duration;

	use tokio::time::timeout;

	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Create tree with versioned_index AND vlog enabled
	// Note: versioned_index requires versioning to be enabled
	let opts = create_test_options(path.clone(), |opts| {
		opts.level_count = 2;
		opts.vlog_max_file_size = 50; // Very small to force multiple VLog files
		opts.enable_vlog = true;
		opts.enable_versioning = true;
		opts.versioned_history_retention_ns = 1_000_000_000_000; // 1000 seconds
		opts.enable_versioned_index = true;
	});

	let tree = Arc::new(Tree::new(Arc::clone(&opts)).unwrap());

	// First, insert some data and flush to create SSTs with VLog references
	let value = "x".repeat(100);
	for i in 0..5 {
		let key = format!("setup-key-{:04}", i);
		let mut tx = tree.begin().unwrap();
		tx.set(key.as_bytes(), value.as_bytes()).unwrap();
		tx.commit().await.unwrap();
	}
	tree.flush().unwrap();

	// Now run concurrent writes and compactions with a timeout
	// If there's a deadlock, this will timeout
	let result = timeout(Duration::from_secs(30), async {
		let tree1 = Arc::clone(&tree);
		let tree2 = Arc::clone(&tree);

		// Spawn writer task
		let writer_handle = tokio::spawn(async move {
			let value = "y".repeat(100);
			for i in 0..50 {
				let key = format!("concurrent-key-{:04}", i);
				let mut tx = tree1.begin().unwrap();
				tx.set(key.as_bytes(), value.as_bytes()).unwrap();
				tx.commit().await.unwrap();

				// Flush periodically to trigger cleanup
				if i % 10 == 0 {
					tree1.flush().unwrap();
				}
			}
		});

		// Spawn compaction task
		let compactor_handle = tokio::spawn(async move {
			for _ in 0..5 {
				// Compact triggers versioned_index cleanup
				let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
					Arc::new(Strategy::default());
				let _ = tree2.core.compact(strategy);
				tokio::time::sleep(Duration::from_millis(10)).await;
			}
		});

		// Wait for both tasks to complete
		let (writer_result, compactor_result) = tokio::join!(writer_handle, compactor_handle);
		writer_result.expect("Writer task should complete");
		compactor_result.expect("Compactor task should complete");
	})
	.await;

	// Assert that we didn't timeout (no deadlock)
	assert!(result.is_ok(), "Test timed out - possible deadlock detected");

	// Verify data integrity - all concurrent keys should be readable
	for i in 0..50 {
		let key = format!("concurrent-key-{:04}", i);
		let tx = tree.begin().unwrap();
		let result = tx.get(key.as_bytes()).unwrap();
		assert!(result.is_some(), "Key {} should exist", key);
	}
}

/// Tests that stale entries are actually deleted from the versioned_index (B+ tree)
/// after VLog GC by directly inspecting the B+ tree contents.
#[test(tokio::test)]
async fn test_versioned_index_entries_deleted_after_gc() {
	use crate::vlog::{ValueLocation, ValuePointer};

	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Create tree with versioned_index AND vlog enabled
	// Use a very short retention period so old versions get dropped during compaction
	let opts = create_test_options(path.clone(), |opts| {
		opts.level_count = 2;
		opts.vlog_max_file_size = 50; // Very small to force multiple VLog files
		opts.enable_vlog = true;
		opts.enable_versioning = true;
		opts.versioned_history_retention_ns = 1; // 1 nanosecond - immediately expire old versions
		opts.enable_versioned_index = true;
		opts.level0_max_files = 1; // Trigger compaction after each flush
	});

	let tree = Tree::new(Arc::clone(&opts)).unwrap();

	// Phase 1: Insert initial data - these will go to VLog file 1
	let keys: Vec<String> = (0..5).map(|i| format!("gc-test-key-{:04}", i)).collect();
	let value1 = "x".repeat(100); // Large value to force VLog storage

	for key in &keys {
		let mut tx = tree.begin().unwrap();
		tx.set(key.as_bytes(), value1.as_bytes()).unwrap();
		tx.commit().await.unwrap();
	}
	tree.flush().unwrap();

	// Small delay to ensure timestamps differ
	tokio::time::sleep(std::time::Duration::from_millis(10)).await;

	// Phase 2: Update data - these will go to VLog file 2
	let value2 = "y".repeat(100);
	for key in &keys {
		let mut tx = tree.begin().unwrap();
		tx.set(key.as_bytes(), value2.as_bytes()).unwrap();
		tx.commit().await.unwrap();
	}
	tree.flush().unwrap();

	// Phase 3: Capture pre-GC state - count entries and VLog file IDs in B+ tree
	let (pre_gc_count, pre_gc_file_ids) = {
		let versioned_index = tree.core.inner.versioned_index.as_ref().unwrap();
		let guard = versioned_index.read();

		let empty: &[u8] = &[];
		let mut count = 0;
		let mut file_ids = std::collections::HashSet::new();

		for entry in guard.range(empty..).unwrap() {
			let (_, value) = entry.unwrap();
			count += 1;

			if let Ok(loc) = ValueLocation::decode(&value) {
				if loc.is_value_pointer() {
					if let Ok(ptr) = ValuePointer::decode(&loc.value) {
						file_ids.insert(ptr.file_id);
					}
				}
			}
		}

		(count, file_ids)
	};

	// Should have entries from multiple VLog files (at least 2)
	assert!(
		pre_gc_file_ids.len() >= 2,
		"Pre-GC should have entries from at least 2 VLog files, found: {:?}",
		pre_gc_file_ids
	);

	// Phase 4: Trigger GC via compaction - use strategy with our options
	let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
		Arc::new(Strategy::from_options(Arc::clone(&opts)));
	tree.compact(Arc::clone(&strategy)).unwrap();

	// Phase 5: Verify entries deleted - count should be less and no stale file IDs
	let (post_gc_count, post_gc_file_ids, min_file_id) = {
		let versioned_index = tree.core.inner.versioned_index.as_ref().unwrap();
		let guard = versioned_index.read();

		let empty: &[u8] = &[];
		let mut count = 0;
		let mut file_ids = std::collections::HashSet::new();
		let mut min_id = u32::MAX;

		for entry in guard.range(empty..).unwrap() {
			let (_, value) = entry.unwrap();
			count += 1;

			if let Ok(loc) = ValueLocation::decode(&value) {
				if loc.is_value_pointer() {
					if let Ok(ptr) = ValuePointer::decode(&loc.value) {
						file_ids.insert(ptr.file_id);
						min_id = min_id.min(ptr.file_id);
					}
				}
			}
		}

		(count, file_ids, min_id)
	};

	// Entry count should be reduced (stale entries deleted)
	assert!(
		post_gc_count < pre_gc_count,
		"Entry count should decrease after GC: pre={}, post={}",
		pre_gc_count,
		post_gc_count
	);

	// Should have fewer unique VLog file IDs (old files deleted)
	assert!(
		post_gc_file_ids.len() < pre_gc_file_ids.len(),
		"Should have fewer VLog file references after GC: pre={:?}, post={:?}",
		pre_gc_file_ids,
		post_gc_file_ids
	);

	// All remaining file IDs should be >= min valid (no stale references)
	for file_id in &post_gc_file_ids {
		assert!(
			*file_id >= min_file_id,
			"Found stale file_id {} < min_valid {}",
			file_id,
			min_file_id
		);
	}

	// Verify data integrity - latest values should still be accessible
	for key in &keys {
		let tx = tree.begin().unwrap();
		let result = tx.get(key.as_bytes()).unwrap();
		assert_eq!(
			result,
			Some(value2.as_bytes().to_vec()),
			"Key {} should have latest value after GC",
			key
		);
	}
}

/// Tests that VLog files persist correctly across shutdown/restart.
/// This validates that the VLog GC mechanism doesn't incorrectly delete
/// files that are still referenced by SSTs.
#[test(tokio::test)]
async fn test_vlog_files_persist_across_restart() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.vlog_max_file_size = 512; // Very small to force many file rotations
		opts.enable_vlog = true;
	});

	let num_records = 1000;
	let mut keys_and_values = Vec::with_capacity(num_records);

	// Phase 1: Insert data and verify VLog files are created
	let vlog_files_before_shutdown: Vec<String>;
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Insert 1000 records with ~100 byte values each
		for i in 0..num_records {
			let key = format!("persist_key_{i:04}");
			let value = format!("persist_value_{i}_padding_{}", "X".repeat(80));
			keys_and_values.push((key.clone(), value.clone()));

			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		// Flush to ensure data is persisted to SST (so VLog files are referenced)
		tree.flush().unwrap();

		// Count VLog files before shutdown
		let vlog_dir = path.join("vlog");
		let entries = std::fs::read_dir(&vlog_dir).unwrap();
		vlog_files_before_shutdown = entries
			.filter_map(|e| {
				let entry = e.ok()?;
				let name = entry.file_name().to_string_lossy().to_string();
				if opts.is_vlog_filename(&name) {
					Some(name)
				} else {
					None
				}
			})
			.collect();

		// Should have multiple VLog files due to small file size
		assert!(
			vlog_files_before_shutdown.len() > 10,
			"Expected more than 10 VLog files due to small file size, got {}",
			vlog_files_before_shutdown.len()
		);

		log::info!("VLog files before shutdown: {} files", vlog_files_before_shutdown.len());

		// Close the tree
		tree.close().await.unwrap();
	}

	// Phase 2: Reopen, add 10 new entries, flush, and verify all records (repeat 5 times)
	// Track VLog file count - should only grow or stay same, never decrease
	let mut previous_vlog_count = vlog_files_before_shutdown.len();

	for iteration in 1..=5 {
		log::info!("=== Restart iteration {}/5 ===", iteration);

		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Count VLog files after restart (before adding new entries)
		let vlog_dir = path.join("vlog");
		let entries = std::fs::read_dir(&vlog_dir).unwrap();
		let vlog_files_after_restart: Vec<String> = entries
			.filter_map(|e| {
				let entry = e.ok()?;
				let name = entry.file_name().to_string_lossy().to_string();
				if opts.is_vlog_filename(&name) {
					Some(name)
				} else {
					None
				}
			})
			.collect();

		log::info!(
			"VLog files after restart {}: {} files (previous: {})",
			iteration,
			vlog_files_after_restart.len(),
			previous_vlog_count
		);

		// VLog file count should not decrease (GC should not delete referenced files)
		assert!(
			vlog_files_after_restart.len() >= previous_vlog_count,
			"VLog file count decreased after restart {}: previous={}, after={}",
			iteration,
			previous_vlog_count,
			vlog_files_after_restart.len()
		);

		// Add 10 new entries
		let new_entries_start = num_records + (iteration - 1) * 10;
		for i in 0..10 {
			let idx = new_entries_start + i;
			let key = format!("persist_key_{idx:04}");
			let value = format!("persist_value_{idx}_padding_{}", "X".repeat(80));
			keys_and_values.push((key.clone(), value.clone()));

			let mut txn = tree.begin().unwrap();
			txn.set(key.as_bytes(), value.as_bytes()).unwrap();
			txn.commit().await.unwrap();
		}

		log::info!("Added 10 new entries (total records: {})", keys_and_values.len());

		// Flush to persist new entries
		tree.flush().unwrap();

		// Count VLog files after flush
		let entries = std::fs::read_dir(&vlog_dir).unwrap();
		let vlog_files_after_flush: Vec<String> = entries
			.filter_map(|e| {
				let entry = e.ok()?;
				let name = entry.file_name().to_string_lossy().to_string();
				if opts.is_vlog_filename(&name) {
					Some(name)
				} else {
					None
				}
			})
			.collect();

		log::info!("VLog files after flush {}: {} files", iteration, vlog_files_after_flush.len());

		// Update previous count for next iteration
		previous_vlog_count = vlog_files_after_flush.len();

		// Verify ALL records are readable (original 1000 + all newly added)
		for (key, expected_value) in &keys_and_values {
			let txn = tree.begin().unwrap();
			let result = txn.get(key.as_bytes()).unwrap();
			assert_eq!(
				result,
				Some(expected_value.as_bytes().to_vec()),
				"Key {} has incorrect value after restart {}",
				key,
				iteration
			);
		}

		log::info!("Verified all {} records after restart {}", keys_and_values.len(), iteration);

		tree.close().await.unwrap();
	}

	// Final verification: 1000 + 5*10 = 1050 records
	assert_eq!(
		keys_and_values.len(),
		1050,
		"Expected 1050 total records (1000 initial + 5*10 added)"
	);

	log::info!(
		"All 5 restart iterations passed successfully with {} total records",
		keys_and_values.len()
	);
}

#[test(tokio::test)]
async fn test_vlog_gc_non_versioned_surrealdb_style_keys() {
	// This test tries to mimics the SurrealDB bug scenario:
	//
	// https://github.com/surrealdb/surrealdb/issues/6872
	//
	//
	// Timeline from user report:
	// - Feb 11: Fresh import, everything working
	// - Feb 11-12: Normal daemon operation (~24h), no issues
	// - Feb 12 evening: macOS reboot → SIGTERM shutdown
	// - Feb 13 morning: Server restarts clean, corruption present
	// - Progressive corruption: queries that worked start failing as more data written
	//
	// Test structure:
	// 1. Phase 1: 500 update rounds + periodic GC (simulates ~24h operation)
	// 2. Close + reopen database (simulates SIGTERM + restart)
	// 3. Phase 2: 500 more update rounds + periodic GC (simulates post-restart)
	// 4. Verify ALL 200 keys accessible (catches progressive corruption)

	// Helper to print VLog files and SSTables
	fn print_storage_state(path: &std::path::Path, tree: &Tree, phase: &str, round: usize) {
		// List VLog files
		let vlog_dir = path.join("vlog");
		let vlog_files: Vec<String> = if vlog_dir.exists() {
			std::fs::read_dir(&vlog_dir)
				.unwrap()
				.filter_map(|e| {
					let entry = e.ok()?;
					let name = entry.file_name().to_string_lossy().to_string();
					if name.ends_with(".vlog") {
						Some(name)
					} else {
						None
					}
				})
				.collect()
		} else {
			vec![]
		};

		// List SSTable files
		let sstables_dir = path.join("sstables");
		let sstable_files: Vec<String> = if sstables_dir.exists() {
			std::fs::read_dir(&sstables_dir)
				.unwrap()
				.filter_map(|e| {
					let entry = e.ok()?;
					let name = entry.file_name().to_string_lossy().to_string();
					if name.ends_with(".sst") {
						Some(name)
					} else {
						None
					}
				})
				.collect()
		} else {
			vec![]
		};

		// Get SSTable counts per level from manifest
		let manifest = tree.core.level_manifest.read().unwrap();
		let levels = manifest.levels.get_levels();
		let level_counts: Vec<usize> = levels.iter().map(|l| l.tables.len()).collect();

		println!("[{} round {}] VLog files ({}): {:?}", phase, round, vlog_files.len(), vlog_files);
		println!(
			"[{} round {}] SSTable files ({}): {:?}",
			phase,
			round,
			sstable_files.len(),
			sstable_files
		);
		println!("[{} round {}] SSTables per level: {:?}", phase, round, level_counts);
		println!("---");
	}

	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.level_count = 1; // Only L0 - always bottom level for stale marking
		opts.enable_vlog = true;
		opts.vlog_max_file_size = 128 * 1024; // 128KB files - larger to reduce file count
	});

	// SurrealDB-style: 50 records, each with 4 fields
	// Key format: /ns/db/tb/record_NNN:fieldN
	const NUM_RECORDS: usize = 50;
	const FIELDS: [&str; 4] = ["field1", "field2", "field3", "field4"];
	const ROUNDS_PER_PHASE: usize = 100;
	const GC_INTERVAL: usize = 10;

	// ========== PHASE 1: Normal operation (simulates ~24h daemon) ==========
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		for round in 0..ROUNDS_PER_PHASE {
			// Update all 50 records
			let mut tx = tree.begin().unwrap();
			for record_id in 0..NUM_RECORDS {
				for field in &FIELDS {
					let key = format!("/ns/db/tb/record_{:03}:{}", record_id, field);
					let value =
						format!("phase1_record_{}_{}_{}", record_id, field, round).repeat(10);
					tx.set(key.as_bytes(), value.as_bytes()).unwrap();
				}
			}
			tx.commit().await.unwrap();
			tree.flush().unwrap();

			// Periodic compaction + VLog GC
			if round > 0 && round % GC_INTERVAL == 0 {
				let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
					Arc::new(Strategy::default());
				for _ in 0..6 {
					tree.compact(Arc::clone(&strategy)).unwrap();
				}
				print_storage_state(&path, &tree, "Phase1", round);
			}
		}

		// Final GC before "shutdown"
		let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
			Arc::new(Strategy::default());
		tree.compact(strategy).unwrap();
		print_storage_state(&path, &tree, "Phase1-Final", ROUNDS_PER_PHASE);

		// Simulate SIGTERM shutdown
		tree.close().await.unwrap();
	}

	// ========== PHASE 2: Post-restart operation ==========
	{
		// Reopen database (simulates server restart after SIGTERM)
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		for round in 0..ROUNDS_PER_PHASE {
			// Update all 50 records (post-restart)
			let mut tx = tree.begin().unwrap();
			for record_id in 0..NUM_RECORDS {
				for field in &FIELDS {
					let key = format!("/ns/db/tb/record_{:03}:{}", record_id, field);
					let value =
						format!("phase2_record_{}_{}_{}", record_id, field, round).repeat(10);
					tx.set(key.as_bytes(), value.as_bytes()).unwrap();
				}
			}
			tx.commit().await.unwrap();
			tree.flush().unwrap();

			// Periodic compaction + VLog GC (this is where progressive corruption would appear)
			if round > 0 && round % GC_INTERVAL == 0 {
				let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
					Arc::new(Strategy::default());
				for _ in 0..6 {
					tree.compact(Arc::clone(&strategy)).unwrap();
				}
				print_storage_state(&path, &tree, "Phase2", round);
			}
		}

		// Final GC pass
		let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
			Arc::new(Strategy::default());
		tree.compact(strategy).unwrap();
		print_storage_state(&path, &tree, "Phase2-Final", ROUNDS_PER_PHASE);

		// ========== VERIFY: All records accessible (no "file not found" errors) ==========
		// This catches the progressive corruption scenario where queries start failing
		// as more data accumulates post-restart
		// NOTE: We check ALL records, not LIMIT 1 (which would hide the bug)
		let tx = tree.begin().unwrap();
		for record_id in 0..NUM_RECORDS {
			for field in &FIELDS {
				let key = format!("/ns/db/tb/record_{:03}:{}", record_id, field);
				let result = tx.get(key.as_bytes()).unwrap();
				assert!(
					result.is_some(),
					"Record {} field {} should exist - got 'file not found' IO error",
					record_id,
					field
				);

				let expected =
					format!("phase2_record_{}_{}_{}", record_id, field, ROUNDS_PER_PHASE - 1)
						.repeat(10);
				assert_eq!(
					result.unwrap(),
					expected.as_bytes(),
					"Record {} field {} should have latest phase2 value",
					record_id,
					field
				);
			}
		}

		tree.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_vlog_gc_with_updates_deletes_and_reupdates() {
	// This test comprehensively tests VLog GC with a realistic workload pattern:
	//
	// Pattern: Updates → Deletes → Re-updates (same keys)
	//
	// This tests the critical scenarios:
	// 1. Values written to VLog, then updated (old versions become stale)
	// 2. Records deleted (tombstones written, values become stale)
	// 3. Same keys re-inserted (new values written, tombstones superseded)
	// 4. Compaction + VLog GC must correctly handle all these state transitions
	// 5. Restart and verify no corruption
	//
	// The bug scenario: VLog GC may incorrectly delete VLog files that still
	// contain live data if the delete_list or discard_stats are inconsistent.

	fn print_storage_state(path: &std::path::Path, tree: &Tree, phase: &str, round: usize) {
		let vlog_dir = path.join("vlog");
		let vlog_files: Vec<String> = if vlog_dir.exists() {
			std::fs::read_dir(&vlog_dir)
				.unwrap()
				.filter_map(|e| {
					let entry = e.ok()?;
					let name = entry.file_name().to_string_lossy().to_string();
					if name.ends_with(".vlog") {
						Some(name)
					} else {
						None
					}
				})
				.collect()
		} else {
			vec![]
		};

		let sstables_dir = path.join("sstables");
		let sstable_files: Vec<String> = if sstables_dir.exists() {
			std::fs::read_dir(&sstables_dir)
				.unwrap()
				.filter_map(|e| {
					let entry = e.ok()?;
					let name = entry.file_name().to_string_lossy().to_string();
					if name.ends_with(".sst") {
						Some(name)
					} else {
						None
					}
				})
				.collect()
		} else {
			vec![]
		};

		let manifest = tree.core.level_manifest.read().unwrap();
		let levels = manifest.levels.get_levels();
		let level_counts: Vec<usize> = levels.iter().map(|l| l.tables.len()).collect();

		println!("[{} round {}] VLog files ({}): {:?}", phase, round, vlog_files.len(), vlog_files);
		println!(
			"[{} round {}] SSTable files ({}): {:?}",
			phase,
			round,
			sstable_files.len(),
			sstable_files
		);
		println!("[{} round {}] SSTables per level: {:?}", phase, round, level_counts);
		println!("---");
	}

	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	let opts = create_test_options(path.clone(), |opts| {
		opts.level_count = 1; // Only L0 - always bottom level for stale marking
		opts.enable_vlog = true;
		opts.vlog_max_file_size = 128 * 1024; // 128KB files - smaller to create more files
	});

	const NUM_RECORDS: usize = 100;
	const FIELDS: [&str; 3] = ["data", "metadata", "content"];
	const ROUNDS: usize = 50;
	const GC_INTERVAL: usize = 5;

	// Track which records are currently "deleted" vs "live"
	// Even records (0, 2, 4, ...) will be deleted and re-inserted
	// Odd records (1, 3, 5, ...) will just be updated

	// ========== PHASE 1: Initial data + mixed updates/deletes ==========
	{
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Initial insert of all records
		println!("=== PHASE 1: Initial insert ===");
		{
			let mut tx = tree.begin().unwrap();
			for record_id in 0..NUM_RECORDS {
				for field in &FIELDS {
					let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
					let value = format!("initial_value_{}_{}", record_id, field).repeat(20);
					tx.set(key.as_bytes(), value.as_bytes()).unwrap();
				}
			}
			tx.commit().await.unwrap();
			tree.flush().unwrap();
		}

		// Run compaction + GC
		let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
			Arc::new(Strategy::default());
		for _ in 0..3 {
			tree.compact(Arc::clone(&strategy)).unwrap();
		}
		print_storage_state(&path, &tree, "Phase1-Initial", 0);

		// Mixed workload: updates + deletes + re-inserts
		for round in 0..ROUNDS {
			let mut tx = tree.begin().unwrap();

			for record_id in 0..NUM_RECORDS {
				let is_even = record_id % 2 == 0;
				let delete_this_round = is_even && (round % 3 == 0); // Delete every 3rd round
				let reinsert_this_round = is_even && (round % 3 == 1); // Re-insert next round

				if delete_this_round {
					// DELETE even records every 3rd round
					for field in &FIELDS {
						let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
						tx.delete(key.as_bytes()).unwrap();
					}
				} else if reinsert_this_round {
					// RE-INSERT previously deleted records
					for field in &FIELDS {
						let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
						let value =
							format!("reinserted_round{}_{}_{}", round, record_id, field).repeat(20);
						tx.set(key.as_bytes(), value.as_bytes()).unwrap();
					}
				} else {
					// UPDATE (both even and odd records when not deleting/reinserting)
					for field in &FIELDS {
						let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
						let value =
							format!("updated_round{}_{}_{}", round, record_id, field).repeat(20);
						tx.set(key.as_bytes(), value.as_bytes()).unwrap();
					}
				}
			}

			tx.commit().await.unwrap();
			tree.flush().unwrap();

			// Periodic compaction + VLog GC
			if round > 0 && round % GC_INTERVAL == 0 {
				let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
					Arc::new(Strategy::default());
				for _ in 0..4 {
					tree.compact(Arc::clone(&strategy)).unwrap();
				}
				print_storage_state(&path, &tree, "Phase1-Mixed", round);
			}
		}

		// Final compaction + GC before shutdown
		let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
			Arc::new(Strategy::default());
		for _ in 0..5 {
			tree.compact(Arc::clone(&strategy)).unwrap();
		}
		print_storage_state(&path, &tree, "Phase1-Final", ROUNDS);

		// Verify all records before shutdown
		println!("=== Verifying Phase 1 data before shutdown ===");
		let tx = tree.begin().unwrap();
		for record_id in 0..NUM_RECORDS {
			for field in &FIELDS {
				let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
				let result = tx.get(key.as_bytes());
				assert!(
					result.is_ok(),
					"Phase1: Record {} field {} get() should not error",
					record_id,
					field
				);
				// All records should exist (even ones were re-inserted)
				assert!(
					result.unwrap().is_some(),
					"Phase1: Record {} field {} should exist",
					record_id,
					field
				);
			}
		}

		// Simulate SIGTERM shutdown
		tree.close().await.unwrap();
	}

	// ========== PHASE 2: Post-restart - more mixed operations ==========
	{
		println!("=== PHASE 2: Post-restart ===");
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Verify all records accessible after restart (before any new writes)
		println!("=== Verifying data after restart ===");
		{
			let tx = tree.begin().unwrap();
			for record_id in 0..NUM_RECORDS {
				for field in &FIELDS {
					let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
					let result = tx.get(key.as_bytes());
					assert!(
						result.is_ok(),
						"Post-restart: Record {} field {} get() should not error - got {:?}",
						record_id,
						field,
						result.err()
					);
					assert!(
						result.unwrap().is_some(),
						"Post-restart: Record {} field {} should exist",
						record_id,
						field
					);
				}
			}
		}

		// More mixed operations post-restart
		for round in 0..ROUNDS {
			let mut tx = tree.begin().unwrap();

			for record_id in 0..NUM_RECORDS {
				let is_odd = record_id % 2 == 1;
				let delete_this_round = is_odd && (round % 4 == 0); // Delete odd records every 4th round
				let reinsert_this_round = is_odd && (round % 4 == 2); // Re-insert 2 rounds later

				if delete_this_round {
					// DELETE odd records
					for field in &FIELDS {
						let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
						tx.delete(key.as_bytes()).unwrap();
					}
				} else if reinsert_this_round {
					// RE-INSERT previously deleted odd records
					for field in &FIELDS {
						let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
						let value =
							format!("phase2_reinsert_round{}_{}_{}", round, record_id, field)
								.repeat(20);
						tx.set(key.as_bytes(), value.as_bytes()).unwrap();
					}
				} else {
					// UPDATE all records
					for field in &FIELDS {
						let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
						let value = format!("phase2_update_round{}_{}_{}", round, record_id, field)
							.repeat(20);
						tx.set(key.as_bytes(), value.as_bytes()).unwrap();
					}
				}
			}

			tx.commit().await.unwrap();
			tree.flush().unwrap();

			// Periodic compaction + VLog GC
			if round > 0 && round % GC_INTERVAL == 0 {
				let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
					Arc::new(Strategy::default());
				for _ in 0..4 {
					tree.compact(Arc::clone(&strategy)).unwrap();
				}
				print_storage_state(&path, &tree, "Phase2-Mixed", round);

				// Verify records accessible after each GC cycle (catches progressive corruption)
				let verify_tx = tree.begin().unwrap();
				for record_id in 0..NUM_RECORDS {
					// Determine expected state for this record at this round
					let is_odd = record_id % 2 == 1;
					let was_deleted_this_round = is_odd && (round % 4 == 0);
					let was_reinserted_this_round = is_odd && (round % 4 == 2);

					// Record should exist unless it was deleted this round and not reinserted
					let should_exist = !was_deleted_this_round || was_reinserted_this_round;
					// Note: even records are always updated (never deleted in phase 2)
					// Odd records: deleted at round%4==0, reinserted at round%4==2
					// At round 20: 20%4==0, so odd records are deleted → should NOT exist
					// At round 10: 10%4==2, so odd records are reinserted → should exist

					for field in &FIELDS {
						let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
						let result = verify_tx.get(key.as_bytes());
						assert!(
							result.is_ok(),
							"Phase2 round {}: Record {} field {} get() error: {:?}",
							round,
							record_id,
							field,
							result.err()
						);

						let value = result.unwrap();
						if should_exist {
							assert!(
								value.is_some(),
								"Phase2 round {}: Record {} field {} should exist but is None (VLog corruption?)",
								round,
								record_id,
								field
							);
						} else {
							assert!(
								value.is_none(),
								"Phase2 round {}: Record {} field {} should be deleted but still exists",
								round,
								record_id,
								field
							);
						}
					}
				}
			}
		}

		// Final compaction + GC
		let strategy: Arc<dyn crate::compaction::CompactionStrategy> =
			Arc::new(Strategy::default());
		tree.compact(strategy).unwrap();
		print_storage_state(&path, &tree, "Phase2-Final", ROUNDS);

		// Final verification
		println!("=== Final verification ===");
		let tx = tree.begin().unwrap();
		for record_id in 0..NUM_RECORDS {
			for field in &FIELDS {
				let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
				let result = tx.get(key.as_bytes());
				assert!(
					result.is_ok(),
					"Final: Record {} field {} get() error: {:?}",
					record_id,
					field,
					result.err()
				);
				let value = result.unwrap();
				assert!(
					value.is_some(),
					"Final: Record {} field {} missing - VLog file may have been incorrectly deleted",
					record_id,
					field
				);
			}
		}

		tree.close().await.unwrap();
	}

	// ========== PHASE 3: Another restart cycle to catch delayed corruption ==========
	{
		println!("=== PHASE 3: Second restart verification ===");
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Full scan of all records
		// After round 49 (last round), all records were updated, so all should exist
		// Last round: 49 % 4 == 1 → UPDATE all records (not delete/reinsert)
		let tx = tree.begin().unwrap();
		let mut accessible_count = 0;
		let mut io_error_count = 0;
		let mut none_count = 0;

		for record_id in 0..NUM_RECORDS {
			for field in &FIELDS {
				let key = format!("/app/db/table/record_{:04}:{}", record_id, field);
				match tx.get(key.as_bytes()) {
					Ok(Some(_)) => accessible_count += 1,
					Ok(None) => {
						// After round 49, all records should exist
						println!(
							"ERROR: Record {} field {} is None (should exist after round 49 update)",
							record_id, field
						);
						none_count += 1;
					}
					Err(e) => {
						println!(
							"ERROR: Record {} field {} - IO error (VLog corruption): {:?}",
							record_id, field, e
						);
						io_error_count += 1;
					}
				}
			}
		}

		println!(
			"=== Results: {} accessible, {} None, {} IO errors out of {} total ===",
			accessible_count,
			none_count,
			io_error_count,
			NUM_RECORDS * FIELDS.len()
		);

		assert_eq!(
			io_error_count, 0,
			"Found {} records with IO errors - VLog corruption detected!",
			io_error_count
		);
		assert_eq!(
			none_count, 0,
			"Found {} records unexpectedly None - data loss detected!",
			none_count
		);
		assert_eq!(accessible_count, NUM_RECORDS * FIELDS.len(), "Not all records accessible");

		tree.close().await.unwrap();
	}
}

/// Tests that recovery detects and rejects corrupted manifest log_number.
/// This prevents silent data loss when log_number exceeds actual WAL segments.
#[test_log::test(tokio::test)]
async fn test_recovery_detects_corrupt_log_number() {
	use byteorder::{BigEndian, WriteBytesExt};

	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Phase 1: Create a database with some data and WAL segments
	// Disable flush_on_close so WAL segments remain on disk
	{
		let opts = create_test_options(path.clone(), |opts| {
			opts.flush_on_close = false;
		});
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write some data (creates WAL entries)
		for i in 0..10 {
			let mut txn = tree.begin().unwrap();
			txn.set(format!("key{}", i).as_bytes(), b"value").unwrap();
			txn.commit().await.unwrap();
		}

		// Close without flushing (data is only in WAL)
		tree.close().await.unwrap();
	}

	// Phase 2: Corrupt the manifest by setting log_number to a very high value
	{
		// Manifest format is: {path}/manifest/{id:020}.manifest
		let manifest_path = path.join("manifest").join("00000000000000000000.manifest");

		// Read the existing manifest
		let data = std::fs::read(&manifest_path).expect("Failed to read manifest");

		// Create corrupted manifest with log_number = 999999 (way beyond any WAL)
		let mut corrupted = Vec::new();
		// Copy version (u16)
		corrupted.extend_from_slice(&data[0..2]);
		// Copy next_table_id (u64)
		corrupted.extend_from_slice(&data[2..10]);
		// Write corrupted log_number (u64) - set to 999999
		corrupted.write_u64::<BigEndian>(999999).unwrap();
		// Copy rest of the file (last_sequence and beyond)
		corrupted.extend_from_slice(&data[18..]);

		// Write corrupted manifest
		std::fs::write(&manifest_path, &corrupted).expect("Failed to write corrupted manifest");
	}

	// Phase 3: Try to open the database - should fail with ManifestCorruption
	{
		let opts = create_test_options(path.clone(), |_| {});
		let result = Tree::new(Arc::clone(&opts));

		match result {
			Ok(_) => panic!("Expected error when opening with corrupted manifest"),
			Err(Error::ManifestCorruption(msg)) => {
				println!("Error message: {}", msg);
				assert!(
					msg.contains("log_number") && msg.contains("exceeds WAL segments"),
					"Error message should mention log_number exceeds WAL segments, got: {}",
					msg
				);
			}
			Err(other) => panic!("Expected ManifestCorruption error, got: {}", other),
		}
	}
}

/// Unit test for validate_wal_log_number with multiple WAL segments.
/// Directly tests the validation function without actual file corruption.
#[test_log::test(tokio::test)]
async fn test_validate_wal_log_number_multiple_wals() {
	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Phase 1: Create database with multiple WAL segments
	{
		let opts = create_test_options(path.clone(), |opts| {
			opts.max_memtable_size = 1024; // 1KB - triggers frequent rotations
			opts.flush_on_close = false;
		});
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		// Write enough data to trigger multiple WAL rotations
		for i in 0..100 {
			let mut txn = tree.begin().unwrap();
			let value = vec![b'x'; 100]; // 100 bytes per entry
			txn.set(format!("key{:04}", i).as_bytes(), &value).unwrap();
			txn.commit().await.unwrap();
		}

		tree.close().await.unwrap();
	}

	// Phase 2: Verify multiple WAL segments exist
	let wal_path = path.join("wal");
	let segment_ids = list_segment_ids(&wal_path, Some("wal")).unwrap();
	assert!(!segment_ids.is_empty(), "Expected WAL segments, got {}", segment_ids.len());
	let max_wal = *segment_ids.last().unwrap();

	// Phase 3: Test validation detects corruption
	let result = validate_wal_log_number(&wal_path, max_wal + 10);
	match result {
		Ok(_) => panic!("Expected error for log_number exceeding max WAL segment"),
		Err(Error::ManifestCorruption(msg)) => {
			assert!(msg.contains("log_number") && msg.contains("exceeds WAL segments"));
		}
		Err(other) => panic!("Expected ManifestCorruption, got: {}", other),
	}

	// Phase 4: Verify valid log_number passes
	let valid_result = validate_wal_log_number(&wal_path, max_wal + 1);
	assert!(valid_result.is_ok(), "log_number = max_wal + 1 should be valid");
}

/// Integration test: corrupts manifest and verifies Tree::new() detects it.
/// Tests the full recovery flow with multiple WAL segments.
#[test_log::test(tokio::test)]
async fn test_recovery_detects_corrupt_log_number_multiple_wals() {
	use byteorder::{BigEndian, WriteBytesExt};

	let temp_dir = create_temp_directory();
	let path = temp_dir.path().to_path_buf();

	// Phase 1: Create database with multiple WAL segments
	{
		let opts = create_test_options(path.clone(), |opts| {
			opts.max_memtable_size = 1024; // 1KB - triggers frequent rotations
			opts.flush_on_close = false;
		});
		let tree = Tree::new(Arc::clone(&opts)).unwrap();

		for i in 0..100 {
			let mut txn = tree.begin().unwrap();
			let value = vec![b'x'; 100];
			txn.set(format!("key{:04}", i).as_bytes(), &value).unwrap();
			txn.commit().await.unwrap();
		}

		tree.close().await.unwrap();
	}

	// Phase 2: Verify multiple WAL segments exist
	let wal_path = path.join("wal");
	let segment_ids = list_segment_ids(&wal_path, Some("wal")).unwrap();
	assert!(!segment_ids.is_empty(), "Expected WAL segments, got {}", segment_ids.len());
	let max_wal = *segment_ids.last().unwrap();

	// Phase 3: Corrupt the manifest file
	{
		let manifest_path = path.join("manifest").join("00000000000000000000.manifest");
		let data = std::fs::read(&manifest_path).expect("Failed to read manifest");

		let mut corrupted = Vec::new();
		corrupted.extend_from_slice(&data[0..2]); // version (u16)
		corrupted.extend_from_slice(&data[2..10]); // next_table_id (u64)
		corrupted.write_u64::<BigEndian>(max_wal + 100).unwrap(); // corrupted log_number
		corrupted.extend_from_slice(&data[18..]); // rest of file

		std::fs::write(&manifest_path, &corrupted).expect("Failed to write corrupted manifest");
	}

	// Phase 4: Try to open - should fail with ManifestCorruption
	{
		let opts = create_test_options(path.clone(), |_| {});
		let result = Tree::new(Arc::clone(&opts));

		match result {
			Ok(_) => panic!("Expected error when opening with corrupted manifest"),
			Err(Error::ManifestCorruption(msg)) => {
				assert!(
					msg.contains("log_number") && msg.contains("exceeds WAL segments"),
					"Error message should mention log_number exceeds WAL segments, got: {}",
					msg
				);
			}
			Err(other) => panic!("Expected ManifestCorruption error, got: {}", other),
		}
	}
}