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
//! Tests for the versioned iterator functionality.
//!
//! Each test runs with both `versioned_index=false` (LSM-only iteration) and
//! `versioned_index=true` (merged B+tree + memtable iteration) to ensure both
//! paths produce identical results.

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

use crate::transaction::{HistoryOptions, Mode};
use crate::{Key, LSMIterator, Options, Result, TreeBuilder, Value};

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

/// Create a store with versioning enabled and configurable B+tree index
fn create_versioned_store(with_index: bool) -> (crate::lsm::Tree, TempDir) {
	let temp_dir = create_temp_directory();
	let opts = Options::new()
		.with_path(temp_dir.path().to_path_buf())
		.with_versioning(true, 0)
		.with_versioned_index(with_index);
	let tree = TreeBuilder::with_options(opts).build().unwrap();
	(tree, temp_dir)
}

/// Create a store without versioning enabled
fn create_store_no_versioning() -> (crate::lsm::Tree, TempDir) {
	let temp_dir = create_temp_directory();
	let opts = Options::new().with_path(temp_dir.path().to_path_buf());
	let tree = TreeBuilder::with_options(opts).build().unwrap();
	(tree, temp_dir)
}

/// Collects all entries from a history iterator
fn collect_history_all(iter: &mut impl LSMIterator) -> Result<Vec<(Key, Value, u64, bool)>> {
	iter.seek_first()?;
	let mut result = Vec::new();
	while iter.valid() {
		let key_ref = iter.key();
		let is_tombstone = key_ref.is_tombstone();
		// Tombstones have no value, so use empty vec
		let value = if is_tombstone {
			Vec::new()
		} else {
			iter.value()?
		};
		result.push((key_ref.user_key().to_vec(), value, key_ref.timestamp(), is_tombstone));
		iter.next()?;
	}
	Ok(result)
}

/// Collects all entries from a history iterator in reverse
fn collect_history_reverse(iter: &mut impl LSMIterator) -> Result<Vec<(Key, Value, u64, bool)>> {
	iter.seek_last()?;
	let mut result = Vec::new();
	while iter.valid() {
		let key_ref = iter.key();
		let is_tombstone = key_ref.is_tombstone();
		// Tombstones have no value, so use empty vec
		let value = if is_tombstone {
			Vec::new()
		} else {
			iter.value()?
		};
		result.push((key_ref.user_key().to_vec(), value, key_ref.timestamp(), is_tombstone));
		if !iter.prev()? {
			break;
		}
	}
	Ok(result)
}

// ============================================================================
// Test 1: Multiple Versions Per Key
// ============================================================================

#[test(tokio::test)]
async fn test_history_multiple_versions_single_key() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 three times with different values
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value1_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value1_v2", 200).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value1_v3", 300).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Query versioned range
		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key1", b"key2").unwrap();
		let results = collect_history_all(&mut iter).unwrap();

		// Should have all 3 versions, ordered by seq_num descending (newest first)
		assert_eq!(results.len(), 3, "with_index={with_index}: Should have 3 versions");
		assert_eq!(results[0].0, b"key1");
		assert_eq!(results[0].1, b"value1_v3");
		assert_eq!(results[0].2, 300);
		assert_eq!(results[1].0, b"key1");
		assert_eq!(results[1].1, b"value1_v2");
		assert_eq!(results[1].2, 200);
		assert_eq!(results[2].0, b"key1");
		assert_eq!(results[2].1, b"value1_v1");
		assert_eq!(results[2].2, 100);
	}
}

// ============================================================================
// Test 2: Multiple Keys with Multiple Versions
// ============================================================================

#[test(tokio::test)]
async fn test_history_multiple_keys_multiple_versions() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 (2 versions)
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		// Insert key2 (1 version)
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"key2_v1", 150).unwrap();
			tx.commit().await.unwrap();
		}

		// Insert key3 (3 versions)
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key3", b"key3_v1", 50).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key3", b"key3_v2", 250).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key3", b"key3_v3", 350).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Query all keys
		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key0", b"key9").unwrap();
		let results = collect_history_all(&mut iter).unwrap();

		// Should have 6 total versions
		assert_eq!(results.len(), 6, "with_index={with_index}: Should have 6 total versions");

		// Verify ordering: grouped by key, newest first within each key
		assert_eq!(results[0].0, b"key1");
		assert_eq!(results[0].1, b"key1_v2");
		assert_eq!(results[1].0, b"key1");
		assert_eq!(results[1].1, b"key1_v1");
		assert_eq!(results[2].0, b"key2");
		assert_eq!(results[2].1, b"key2_v1");
		assert_eq!(results[3].0, b"key3");
		assert_eq!(results[3].1, b"key3_v3");
		assert_eq!(results[4].0, b"key3");
		assert_eq!(results[4].1, b"key3_v2");
		assert_eq!(results[5].0, b"key3");
		assert_eq!(results[5].1, b"key3_v1");
	}
}

// ============================================================================
// Test 3: Tombstones - Without Include Tombstones
// ============================================================================

#[test(tokio::test)]
async fn test_history_excludes_tombstones() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 v1
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Delete key1
		{
			let mut tx = store.begin().unwrap();
			tx.delete(b"key1").unwrap();
			tx.commit().await.unwrap();
		}

		// Insert key2
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"value2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Query with history (excludes tombstones by default)
		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key0", b"key9").unwrap();
		let results = collect_history_all(&mut iter).unwrap();

		// Hard delete hides ALL versions of key1, only key2 visible
		assert_eq!(results.len(), 1, "with_index={with_index}: Only key2 visible");

		for result in &results {
			assert!(!result.3, "No entry should be a tombstone");
		}

		assert_eq!(results[0].0, b"key2");
		assert_eq!(results[0].1, b"value2");
	}
}

// ============================================================================
// Test 4: Tombstones - With Include Tombstones
// ============================================================================

#[test(tokio::test)]
async fn test_history_with_tombstones() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 v1
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Delete key1 (creates tombstone)
		{
			let mut tx = store.begin().unwrap();
			tx.delete(b"key1").unwrap();
			tx.commit().await.unwrap();
		}

		// Insert key2
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"value2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Query with history_with_options (includes tombstones)
		let tx = store.begin().unwrap();
		let opts = HistoryOptions {
			include_tombstones: true,
			..Default::default()
		};
		let mut iter = tx.history_with_options(b"key0", b"key9", &opts).unwrap();
		let results = collect_history_all(&mut iter).unwrap();

		// Hard delete hides ALL versions of key1, even with include_tombstones=true
		assert_eq!(results.len(), 1, "with_index={with_index}: Only key2 visible");
		assert_eq!(results[0].0, b"key2");
		assert!(!results[0].3, "key2 should not be a tombstone");
	}
}

// ============================================================================
// Test 5: Replace Operations
// ============================================================================

#[test(tokio::test)]
async fn test_history_replace_shows_all_versions() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1=v1
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Replace key1=v2
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		// Replace key1=v3
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v3", 300).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Query all versions
		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key1", b"key2").unwrap();
		let results = collect_history_all(&mut iter).unwrap();

		assert_eq!(results.len(), 3, "with_index={with_index}: All 3 versions visible");
		assert_eq!(results[0].1, b"v3");
		assert_eq!(results[1].1, b"v2");
		assert_eq!(results[2].1, b"v1");
	}
}

// ============================================================================
// Test 6: Soft Delete vs Hard Delete
// ============================================================================

#[test(tokio::test)]
async fn test_history_soft_delete_vs_hard_delete() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 v1
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Soft delete key1
		{
			let mut tx = store.begin().unwrap();
			tx.soft_delete(b"key1").unwrap();
			tx.commit().await.unwrap();
		}

		// Insert key2
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"value2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		// Hard delete key2
		{
			let mut tx = store.begin().unwrap();
			tx.delete(b"key2").unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Query with tombstones
			let tx = store.begin().unwrap();
			let opts = HistoryOptions {
				include_tombstones: true,
				..Default::default()
			};
			let mut iter = tx.history_with_options(b"key0", b"key9", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			// key1 (soft delete): tombstone + value = 2 entries
			// key2 (hard delete): hidden = 0 entries
			assert_eq!(results.len(), 2, "with_index={with_index}: Only key1 visible");
			assert_eq!(results[0].0, b"key1");
			assert!(results[0].3, "key1 first should be tombstone");
			assert_eq!(results[1].0, b"key1");
			assert!(!results[1].3, "key1 second should be value");
		}

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

// ============================================================================
// Test 7: Bounds - Inclusive Start, Exclusive End
// ============================================================================

#[test(tokio::test)]
async fn test_history_bounds() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert keys a through e
		for key in [b"key_a", b"key_b", b"key_c", b"key_d", b"key_e"] {
			let mut tx = store.begin().unwrap();
			tx.set_at(key, b"value", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Query range [key_b, key_d) - should include key_b and key_c, NOT key_d
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key_b", b"key_d").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 2, "with_index={with_index}: Should have 2 entries");
			assert_eq!(results[0].0, b"key_b");
			assert_eq!(results[1].0, b"key_c");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test 8: Bounds - Empty Range
// ============================================================================

#[test(tokio::test)]
async fn test_history_empty_range() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key_a and key_b
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key_a", b"value_a", 100).unwrap();
			tx.set_at(b"key_b", b"value_b", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Query range [key_c, key_d) - no matching keys
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key_c", b"key_d").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert!(results.is_empty(), "with_index={with_index}: Should have no entries");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test 9: Bounds - Single Key Match
// ============================================================================

#[test(tokio::test)]
async fn test_history_single_key_match() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key_a (2 versions)
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key_a", b"v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key_a", b"v2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		// Insert key_b and key_c
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key_b", b"value_b", 150).unwrap();
			tx.set_at(b"key_c", b"value_c", 150).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Query range that only matches key_a
		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key_a", b"key_b").unwrap();
		let results = collect_history_all(&mut iter).unwrap();

		assert_eq!(results.len(), 2, "with_index={with_index}: Should have both versions");
		assert_eq!(results[0].0, b"key_a");
		assert_eq!(results[0].1, b"v2");
		assert_eq!(results[1].0, b"key_a");
		assert_eq!(results[1].1, b"v1");
	}
}

// ============================================================================
// Test 10: Interleaved Iteration - Forward/Backward
// ============================================================================

#[test(tokio::test)]
async fn test_history_interleaved_iteration() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 (2 versions) and key2 (2 versions)
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v2", 200).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"key2_v1", 150).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"key2_v2", 250).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key0", b"key9").unwrap();

		// Test forward iteration
		iter.seek_first().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key1");
		assert_eq!(iter.value().unwrap(), b"key1_v2".to_vec());

		iter.next().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key1");
		assert_eq!(iter.value().unwrap(), b"key1_v1".to_vec());

		iter.next().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key2");
		assert_eq!(iter.value().unwrap(), b"key2_v2".to_vec());

		iter.next().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key2");
		assert_eq!(iter.value().unwrap(), b"key2_v1".to_vec());

		// Test backward iteration starting from last
		iter.seek_last().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key2");
		assert_eq!(iter.value().unwrap(), b"key2_v1".to_vec());

		iter.prev().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key2");
		assert_eq!(iter.value().unwrap(), b"key2_v2".to_vec());

		iter.prev().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key1");
		assert_eq!(iter.value().unwrap(), b"key1_v1".to_vec());
	}
}

// ============================================================================
// Test 11: Interleaved Iteration - Seek in Middle
// ============================================================================

#[test(tokio::test)]
async fn test_history_seek_middle() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert 5 keys
		for i in 1..=5 {
			let mut tx = store.begin().unwrap();
			let key = format!("key{i}");
			let value = format!("value{i}");
			tx.set_at(key.as_bytes(), value.as_bytes(), i as u64 * 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key0", b"key9").unwrap();

		// Forward iteration should return keys in order
		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(results.len(), 5);
		assert_eq!(results[0].0, b"key1");
		assert_eq!(results[1].0, b"key2");
		assert_eq!(results[2].0, b"key3");
		assert_eq!(results[3].0, b"key4");
		assert_eq!(results[4].0, b"key5");

		// Test seek_first after collection
		iter.seek_first().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key1");

		// Navigate forward
		iter.next().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key2");

		iter.next().unwrap();
		assert!(iter.valid());
		assert_eq!(iter.key().user_key(), b"key3");
	}
}

// ============================================================================
// Test 12: Backward Iteration Only
// ============================================================================

#[test(tokio::test)]
async fn test_history_backward_iteration() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert multiple keys with multiple versions
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v2", 200).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"key2_v1", 150).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin().unwrap();
		let mut iter = tx.history(b"key0", b"key9").unwrap();
		let results = collect_history_reverse(&mut iter).unwrap();

		assert_eq!(results.len(), 3, "with_index={with_index}: Should have 3 entries");

		// Reverse order: key2_v1, key1_v1, key1_v2
		assert_eq!(results[0].0, b"key2");
		assert_eq!(results[0].1, b"key2_v1");
		assert_eq!(results[1].0, b"key1");
		assert_eq!(results[1].1, b"key1_v1");
		assert_eq!(results[2].0, b"key1");
		assert_eq!(results[2].1, b"key1_v2");
	}
}

// ============================================================================
// Test 13: Snapshot Isolation - Versions Not Visible to Old Snapshots
// ============================================================================

#[test(tokio::test)]
async fn test_history_snapshot_isolation() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 v1
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Take snapshot1
		let tx1 = store.begin().unwrap();

		// Insert key1 v2
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Take snapshot2
		let tx2 = store.begin().unwrap();

		// snapshot1 should only see v1
		{
			let mut iter = tx1.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();
			assert_eq!(results.len(), 1, "with_index={with_index}: snapshot1 should see 1 version");
			assert_eq!(results[0].1, b"v1");
		}

		// snapshot2 should see both v1 and v2
		{
			let mut iter = tx2.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();
			assert_eq!(
				results.len(),
				2,
				"with_index={with_index}: snapshot2 should see 2 versions"
			);
			assert_eq!(results[0].1, b"v2");
			assert_eq!(results[1].1, b"v1");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test 14: Large Number of Versions
// ============================================================================

#[test(tokio::test)]
async fn test_history_many_versions() {
	for with_index in [false, true] {
		println!("test_history_many_versions with_index={with_index}");
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert same key 100 times with different values
		for i in 1..=100 {
			let mut tx = store.begin().unwrap();
			let value = format!("value_{i:03}");
			tx.set_at(b"key1", value.as_bytes(), i as u64 * 10).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Query all versions
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 100, "with_index={with_index}: Should have all 100 versions");
			assert_eq!(results[0].1, b"value_100");
			assert_eq!(results[99].1, b"value_001");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test 15: Mixed Timestamps
// ============================================================================

#[test(tokio::test)]
async fn test_history_timestamps() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key with timestamp 50, then 100, then 200
		// Note: seq_num order != timestamp order
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"ts_50", 50).unwrap();
			tx.commit().await.unwrap();
		}

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"ts_100", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"ts_200", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Query versions
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 3, "with_index={with_index}: Should have 3 versions");

			// Verify ordering is by timestamp descending (B+tree uses TimestampComparator)
			assert_eq!(results[0].1, b"ts_200");
			assert_eq!(results[0].2, 200);
			assert_eq!(results[1].1, b"ts_100");
			assert_eq!(results[1].2, 100);
			assert_eq!(results[2].1, b"ts_50");
			assert_eq!(results[2].2, 50);
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test 16: Entry Convenience Method
// Uses soft_delete to test include_tombstones (hard delete hides all versions)
// ============================================================================

#[test(tokio::test)]
async fn test_history_entry_method() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert a key
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Soft delete the key (creates tombstone that can be shown with include_tombstones)
		{
			let mut tx = store.begin().unwrap();
			tx.soft_delete(b"key1").unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Query with tombstones
		let tx = store.begin().unwrap();
		let opts = HistoryOptions {
			include_tombstones: true,
			..Default::default()
		};
		let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();

		iter.seek_first().unwrap();
		assert!(iter.valid());

		let key_ref = iter.key();
		let is_tombstone = key_ref.is_tombstone();
		assert_eq!(key_ref.user_key(), b"key1");
		assert!(is_tombstone, "First entry should be tombstone");

		iter.next().unwrap();
		assert!(iter.valid());

		let key_ref = iter.key();
		let value = iter.value().unwrap();
		let timestamp = key_ref.timestamp();
		let is_tombstone = key_ref.is_tombstone();
		assert_eq!(key_ref.user_key(), b"key1");
		assert_eq!(value.as_slice(), b"value1");
		assert_eq!(timestamp, 100);
		assert!(!is_tombstone, "Second entry should not be tombstone");
	}
}

// ============================================================================
// Test 17: get_at Fallback
// ============================================================================

#[test(tokio::test)]
async fn test_get_at_fallback() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key at ts=100
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value_100", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Insert key at ts=200
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value_200", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin().unwrap();

		let result = tx.get_at(b"key1", 150).unwrap();
		assert!(result.is_some());
		assert_eq!(result.unwrap(), b"value_100");

		let result = tx.get_at(b"key1", 200).unwrap();
		assert!(result.is_some());
		assert_eq!(result.unwrap(), b"value_200");

		let result = tx.get_at(b"key1", 50).unwrap();
		assert!(result.is_none());

		let result = tx.get_at(b"key1", 250).unwrap();
		assert!(result.is_some());
		assert_eq!(result.unwrap(), b"value_200");
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test 18: get_at with Tombstone
// ============================================================================

#[test(tokio::test)]
async fn test_get_at_tombstone() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key at ts=100
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value_100", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Delete at ts=200 (creates tombstone)
		{
			let mut tx = store.begin().unwrap();
			tx.soft_delete(b"key1").unwrap();
			tx.commit().await.unwrap();
		}

		// Insert at ts=300
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"value_300", 300).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin().unwrap();

		let result = tx.get_at(b"key1", 150).unwrap();
		assert!(result.is_some());
		assert_eq!(result.unwrap(), b"value_100");

		let result = tx.get_at(b"key1", 350).unwrap();
		assert!(result.is_some());
		assert_eq!(result.unwrap(), b"value_300");
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test 19: Error Handling - Versioning Disabled
// ============================================================================

#[test(tokio::test)]
async fn test_history_requires_versioning() {
	// Create store WITHOUT versioning enabled
	let (store, _temp_dir) = create_store_no_versioning();

	// Insert some data
	{
		let mut tx = store.begin().unwrap();
		tx.set(b"key1", b"value1").unwrap();
		tx.commit().await.unwrap();
	}

	// Try to call history - should return error
	let tx = store.begin().unwrap();
	let result = tx.history(b"key0", b"key9");

	assert!(result.is_err(), "history should fail without versioning enabled");
}

// ============================================================================
// Test 20: Error Handling - Transaction States
// ============================================================================

#[test(tokio::test)]
async fn test_history_transaction_states() {
	let (store, _temp_dir) = create_versioned_store(false);

	// Insert some data
	{
		let mut tx = store.begin().unwrap();
		tx.set_at(b"key1", b"value1", 100).unwrap();
		tx.commit().await.unwrap();
	}

	// Test on closed transaction
	{
		let tx = store.begin().unwrap();
		drop(tx); // Transaction is dropped/closed

		// Cannot test closed transaction directly since drop consumes it
		// But we can test that a new transaction works fine
		let tx = store.begin().unwrap();
		let result = tx.history(b"key0", b"key9");
		assert!(result.is_ok(), "Fresh transaction should work");
	}

	// Test on write-only transaction
	{
		let tx = store.begin_with_mode(Mode::WriteOnly).unwrap();
		let result = tx.history(b"key0", b"key9");
		assert!(result.is_err(), "Write-only transaction should not allow history");
	}
}

// ============================================================================
// Test: Versions survive memtable flush (bug detector)
// ============================================================================

#[test(tokio::test)]
async fn test_history_survives_memtable_flush() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 three times with different values
		for i in 1..=3 {
			let mut tx = store.begin().unwrap();
			let value = format!("v{i}");
			tx.set_at(b"key1", value.as_bytes(), i as u64 * 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Verify all 3 versions exist in memtable BEFORE flush
		{
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();
			assert_eq!(
				results.len(),
				3,
				"with_index={with_index}: Should have 3 versions before flush"
			);
		}

		// FORCE MEMTABLE FLUSH
		store.flush().unwrap();

		{
			// Query versions AFTER flush
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(
				results.len(),
				3,
				"with_index={with_index}: All 3 versions should survive flush"
			);
			assert_eq!(results[0].1, b"v3");
			assert_eq!(results[1].1, b"v2");
			assert_eq!(results[2].1, b"v1");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: Replace operation cuts off older versions (even with versioning)
// ============================================================================

#[test(tokio::test)]
async fn test_replace_cuts_off_history_with_versioning() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 with SET operations
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"set_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"set_v2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		// Now use REPLACE - this should cut off the history
		{
			let mut tx = store.begin().unwrap();
			tx.replace(b"key1", b"replace_v3").unwrap();
			tx.commit().await.unwrap();
		}

		// Before flush - REPLACE filters immediately during iteration
		{
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();
			assert_eq!(
				results.len(),
				1,
				"with_index={with_index}: Before flush: REPLACE filters immediately"
			);
			assert_eq!(results[0].1, b"replace_v3");
		}

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

		{
			// After flush - same result
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(
				results.len(),
				1,
				"with_index={with_index}: After flush: only Replace survives"
			);
			assert_eq!(results[0].1, b"replace_v3");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: Multiple Replace operations are all preserved with versioning
// ============================================================================

#[test(tokio::test)]
async fn test_multiple_replaces_preserved_with_versioning() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert with SET first
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"set_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Multiple Replace operations
		{
			let mut tx = store.begin().unwrap();
			tx.replace(b"key1", b"replace_v2").unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.replace(b"key1", b"replace_v3").unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.replace(b"key1", b"replace_v4").unwrap();
			tx.commit().await.unwrap();
		}

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

		{
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 1, "with_index={with_index}: Latest Replace should survive");
			assert_eq!(results[0].1, b"replace_v4");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: Replace after Delete with versioning
// ============================================================================

#[test(tokio::test)]
async fn test_replace_after_delete_with_versioning() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"set_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Delete key1
		{
			let mut tx = store.begin().unwrap();
			tx.delete(b"key1").unwrap();
			tx.commit().await.unwrap();
		}

		// Replace key1 (after delete)
		{
			let mut tx = store.begin().unwrap();
			tx.replace(b"key1", b"replace_v3").unwrap();
			tx.commit().await.unwrap();
		}

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

		{
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 1, "with_index={with_index}: Replace should survive");
			assert_eq!(results[0].1, b"replace_v3");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: Versions survive compaction (L0 -> L1)
// ============================================================================

#[test(tokio::test)]
async fn test_versions_survive_compaction() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert key1 with multiple versions
		for i in 1..=5 {
			let mut tx = store.begin().unwrap();
			let value = format!("v{i}");
			tx.set_at(b"key1", value.as_bytes(), i as u64 * 100).unwrap();
			tx.commit().await.unwrap();
		}

		// First flush (memtable -> L0)
		store.flush().unwrap();

		// Verify versions after first flush
		{
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();
			assert_eq!(
				results.len(),
				5,
				"with_index={with_index}: All 5 versions should survive L0 flush"
			);
		}

		// Insert more versions to trigger another flush
		for i in 6..=10 {
			let mut tx = store.begin().unwrap();
			let value = format!("v{i}");
			tx.set_at(b"key1", value.as_bytes(), i as u64 * 100).unwrap();
			tx.commit().await.unwrap();
		}

		// Second flush
		store.flush().unwrap();

		{
			// Verify all 10 versions exist across L0 files
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key1", b"key2").unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(
				results.len(),
				10,
				"with_index={with_index}: All 10 versions should survive"
			);
			assert_eq!(results[0].1, b"v10");
			assert_eq!(results[9].1, b"v1");
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: history() forward and backward iteration
// ============================================================================

#[test(tokio::test)]
async fn test_history_bidirectional_iteration() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Insert multiple keys with multiple versions
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"key1_v2", 200).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"key2_v1", 150).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let tx = store.begin().unwrap();
			let mut iter = tx.history(b"key0", b"key9").unwrap();

			let forward_results = collect_history_all(&mut iter).unwrap();
			assert_eq!(forward_results.len(), 3);

			let reverse_results = collect_history_reverse(&mut iter).unwrap();
			assert_eq!(reverse_results.len(), 3);

			assert_eq!(forward_results[0].0, reverse_results[2].0);
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: ts_range filtering
// ============================================================================

#[test(tokio::test)]
async fn test_history_ts_range_forward() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v100", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v200", 200).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v300", 300).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v400", 400).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Query with ts_range [150, 350] - should only return v200 and v300
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_ts_range(150, 350);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(
				results.len(),
				2,
				"with_index={with_index}: Should have 2 versions in range"
			);
			assert_eq!(results[0].2, 300);
			assert_eq!(results[1].2, 200);
		}
		store.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_history_ts_range_backward() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v100", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v200", 200).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v300", 300).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Query with ts_range [150, 250] - should only return v200
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_ts_range(150, 250);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_reverse(&mut iter).unwrap();

			assert_eq!(results.len(), 1, "with_index={with_index}: Should have 1 version in range");
			assert_eq!(results[0].2, 200);
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: limit filtering
// ============================================================================

#[test(tokio::test)]
async fn test_history_limit_forward() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		for i in 1..=5 {
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", format!("v{}", i).as_bytes(), i * 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_limit(3);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 3, "with_index={with_index}: Should have 3 entries");
			assert_eq!(results[0].2, 500);
			assert_eq!(results[1].2, 400);
			assert_eq!(results[2].2, 300);
		}
		store.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_history_limit_backward() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		for i in 1..=5 {
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", format!("v{}", i).as_bytes(), i * 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_limit(2);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_reverse(&mut iter).unwrap();

			assert_eq!(results.len(), 2, "with_index={with_index}: Should have 2 entries");
			assert_eq!(results[0].2, 100);
			assert_eq!(results[1].2, 200);
		}
		store.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_history_limit_multiple_keys() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v1", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v2", 200).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"v1", 150).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key2", b"v2", 250).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_limit(3);
			let mut iter = tx.history_with_options(b"key0", b"key9", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(
				results.len(),
				3,
				"with_index={with_index}: Should have 3 entries across keys"
			);
		}
		store.close().await.unwrap();
	}
}

// ============================================================================
// Test: ts_range + limit combination
// ============================================================================

#[test(tokio::test)]
async fn test_history_ts_range_with_limit() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		for i in 1..=10 {
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", format!("v{}", i).as_bytes(), i * 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_ts_range(300, 800).with_limit(3);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(
				results.len(),
				3,
				"with_index={with_index}: Should have 3 entries (limited)"
			);
			assert_eq!(results[0].2, 800);
			assert_eq!(results[1].2, 700);
			assert_eq!(results[2].2, 600);
		}
		store.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_history_limit_zero() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_limit(0);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 0, "with_index={with_index}: Should have 0 entries");
		}
		store.close().await.unwrap();
	}
}

#[test(tokio::test)]
async fn test_history_ts_range_empty_result() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v100", 100).unwrap();
			tx.commit().await.unwrap();
		}
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v200", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let tx = store.begin().unwrap();
			let opts = HistoryOptions::new().with_ts_range(500, 600);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 0, "with_index={with_index}: Should have 0 entries");
		}

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

// ==================== RYOW (Read Your Own Writes) Tests ====================

/// Test get_at RYOW: uncommitted writes should be visible
#[test(tokio::test)]
async fn test_get_at_ryow() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Commit some initial data
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"committed_v1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Start a new transaction and write uncommitted data
		let mut tx = store.begin().unwrap();
		tx.set_at(b"key1", b"uncommitted_v2", 200).unwrap();
		tx.set_at(b"key2", b"uncommitted_new", 150).unwrap();

		let value = tx.get_at(b"key1", 200).unwrap();
		assert_eq!(value, Some(b"uncommitted_v2".to_vec()), "with_index={with_index}");

		let value = tx.get_at(b"key2", 150).unwrap();
		assert_eq!(value, Some(b"uncommitted_new".to_vec()), "with_index={with_index}");

		let value = tx.get_at(b"key1", 100).unwrap();
		assert_eq!(value, Some(b"committed_v1".to_vec()), "with_index={with_index}");
	}
}

/// Test get_at RYOW: future timestamp writes should not be visible
#[test(tokio::test)]
async fn test_get_at_ryow_future_timestamp() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		let mut tx = store.begin().unwrap();
		tx.set_at(b"key1", b"future_value", 500).unwrap();

		let value = tx.get_at(b"key1", 400).unwrap();
		assert_eq!(value, None, "with_index={with_index}: Should not see future write");

		let value = tx.get_at(b"key1", 500).unwrap();
		assert_eq!(value, Some(b"future_value".to_vec()), "with_index={with_index}");

		let value = tx.get_at(b"key1", 600).unwrap();
		assert_eq!(value, Some(b"future_value".to_vec()), "with_index={with_index}");
		store.close().await.unwrap();
	}
}

/// Test get_at RYOW with tombstone
#[test(tokio::test)]
async fn test_get_at_ryow_tombstone() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Commit initial data
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"initial", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		// Delete the key in a new transaction (uncommitted)
		let mut tx = store.begin().unwrap();
		tx.delete(b"key1").unwrap();

		let value = tx.get_at(b"key1", u64::MAX).unwrap();
		assert_eq!(value, None, "with_index={with_index}: Should see tombstone as None");
		store.close().await.unwrap();
	}
}

/// Test history iterator RYOW: uncommitted writes appear in history
#[test(tokio::test)]
async fn test_history_ryow() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Commit some initial data
		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"committed_v1", 100).unwrap();
			tx.set_at(b"key1", b"committed_v2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Start a new transaction and write uncommitted data
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"uncommitted_v3", 300).unwrap();
			tx.set_at(b"key2", b"uncommitted_new", 150).unwrap();

			let opts = HistoryOptions::new();
			let mut iter = tx.history_with_options(b"key1", b"key3", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 4, "with_index={with_index}: Should have 4 history entries");

			assert_eq!(results[0].0, b"key1".to_vec());
			assert_eq!(results[0].1, b"uncommitted_v3".to_vec());
			assert_eq!(results[0].2, 300);

			assert_eq!(results[1].0, b"key1".to_vec());
			assert_eq!(results[1].1, b"committed_v2".to_vec());
			assert_eq!(results[1].2, 200);

			assert_eq!(results[2].0, b"key1".to_vec());
			assert_eq!(results[2].1, b"committed_v1".to_vec());
			assert_eq!(results[2].2, 100);

			assert_eq!(results[3].0, b"key2".to_vec());
			assert_eq!(results[3].1, b"uncommitted_new".to_vec());
			assert_eq!(results[3].2, 150);
		}
		store.close().await.unwrap();
	}
}

/// Test history RYOW with timestamp collision: write set wins
#[test(tokio::test)]
async fn test_history_ryow_timestamp_collision() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"committed_at_100", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Write uncommitted data with the SAME timestamp
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"uncommitted_at_100", 100).unwrap();

			let opts = HistoryOptions::new();
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 1, "with_index={with_index}: Uncommitted shadows committed");
			assert_eq!(results[0].0, b"key1".to_vec());
			assert_eq!(results[0].1, b"uncommitted_at_100".to_vec());
			assert_eq!(results[0].2, 100);
		}
		store.close().await.unwrap();
	}
}

/// Test history RYOW with timestamp range filtering
#[test(tokio::test)]
async fn test_history_ryow_with_ts_range() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"committed_100", 100).unwrap();
			tx.set_at(b"key1", b"committed_200", 200).unwrap();
			tx.set_at(b"key1", b"committed_300", 300).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"uncommitted_150", 150).unwrap();

			let opts = HistoryOptions::new().with_ts_range(100, 200);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 3, "with_index={with_index}: Should have 3 entries in range");
			assert_eq!(results[0].2, 200);
			assert_eq!(results[1].2, 150);
			assert_eq!(results[1].1, b"uncommitted_150".to_vec());
			assert_eq!(results[2].2, 100);
		}

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

/// Test history RYOW soft delete (tombstone) handling
#[test(tokio::test)]
async fn test_history_ryow_soft_delete() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v1", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Soft delete key in new transaction (uncommitted)
			let mut tx = store.begin().unwrap();
			let write_opts = crate::transaction::WriteOptions {
				timestamp: Some(200),
			};
			tx.soft_delete_with_options(b"key1", &write_opts).unwrap();

			// Query without tombstones
			let opts = HistoryOptions::new();
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 1, "with_index={with_index}: Soft delete filtered");
			assert_eq!(results[0].1, b"v1".to_vec());
			assert_eq!(results[0].2, 100);

			// Query with tombstones included
			let opts = HistoryOptions::new().with_tombstones(true);
			let mut iter = tx.history_with_options(b"key1", b"key2", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 2, "with_index={with_index}: Should have 2 with tombstones");
			assert_eq!(results[0].2, 200);
			assert!(results[0].3, "First entry should be tombstone");
			assert_eq!(results[1].2, 100);
			assert!(!results[1].3, "Second entry should not be tombstone");
		}
		store.close().await.unwrap();
	}
}

/// Test history RYOW hard delete handling - wipes all history
#[test(tokio::test)]
async fn test_history_ryow_hard_delete() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v1", 100).unwrap();
			tx.set_at(b"key2", b"v2", 100).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		{
			// Hard delete key1 in new transaction (uncommitted)
			let mut tx = store.begin().unwrap();
			tx.delete(b"key1").unwrap();

			let opts = HistoryOptions::new();
			let mut iter = tx.history_with_options(b"key1", b"key3", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(results.len(), 1, "with_index={with_index}: key1 wiped by hard delete");
			assert_eq!(results[0].0, b"key2".to_vec());
			assert_eq!(results[0].1, b"v2".to_vec());

			// Even with tombstones=true, hard delete wipes all
			let opts = HistoryOptions::new().with_tombstones(true);
			let mut iter = tx.history_with_options(b"key1", b"key3", &opts).unwrap();
			let results = collect_history_all(&mut iter).unwrap();

			assert_eq!(
				results.len(),
				1,
				"with_index={with_index}: Hard delete wipes even with tombstones"
			);
			assert_eq!(results[0].0, b"key2".to_vec());
		}

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

/// Test get_at RYOW with hard delete - returns None regardless of timestamp
#[test(tokio::test)]
async fn test_get_at_ryow_hard_delete() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin().unwrap();
			tx.set_at(b"key1", b"v1", 100).unwrap();
			tx.set_at(b"key1", b"v2", 200).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let mut tx = store.begin().unwrap();
		tx.delete(b"key1").unwrap();

		let value = tx.get_at(b"key1", 100).unwrap();
		assert_eq!(value, None, "with_index={with_index}: Hard delete should wipe ts=100");

		let value = tx.get_at(b"key1", 200).unwrap();
		assert_eq!(value, None, "with_index={with_index}: Hard delete should wipe ts=200");

		let value = tx.get_at(b"key1", u64::MAX).unwrap();
		assert_eq!(value, None, "with_index={with_index}: Hard delete should wipe all");
		store.close().await.unwrap();
	}
}

// ============================================================================
// History Iterator Bounds Tests
// ============================================================================

/// Test that forward iteration respects lower bound when keys exist before the range.
/// Regression test: keys with user_key lexicographically before lower bound should not be returned.
#[test(tokio::test)]
async fn test_history_forward_respects_lower_bound() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Key starting with '#' (ASCII 35) comes before '@' (ASCII 64)
		let sync_key = b"#@prefix:sync\x00\x00\x00\x00\x00\x00\x00\x02****************";
		let table_key = b"@prefix:tbentity\x00\x00\x00\x00\x00\x00\x00\x00\x10cccccccccccccccc";
		let before_key = b"@prefix:tbentity\x00\x00\x00\x00\x00\x00\x00\x00\x10kkkkkkkkkkkkkkkk";
		let after_key = b"@prefix:tbentity\x00\x00\x00\x00\x00\x00\x00\x00\x10MMMMMMMMMMMMMMMM";

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(before_key, b"value", 1).unwrap();
			tx.commit().await.unwrap();
		}

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(sync_key, b"value", 2).unwrap();
			tx.set_at(table_key, b"value", 2).unwrap();
			tx.commit().await.unwrap();
		}

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(after_key, b"value", 3).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();

		// Query range starting with '@' should NOT return '#@prefix:sync'
		let lower = b"@prefix:\x00";
		let upper = b"@prefix:\xFF";
		let opts = HistoryOptions::new().with_tombstones(true).with_ts_range(2, 2);
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();

		// Only table_key should be returned (it's the only key within range at ts=2)
		assert_eq!(
			results.len(),
			1,
			"with_index={with_index}: Only keys within range should be returned, got: {:?}",
			results.iter().map(|(k, _, _, _)| String::from_utf8_lossy(k)).collect::<Vec<_>>()
		);
		assert!(
			results[0].0.starts_with(b"@prefix:"),
			"with_index={with_index}: Key should start with @prefix:"
		);

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

/// Test that backward iteration respects upper bound when keys exist after the range.
/// Regression test: keys with user_key lexicographically after upper bound should not be returned.
#[test(tokio::test)]
async fn test_history_backward_respects_upper_bound() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Keys in range
		let key_a = b"key_a";
		let key_b = b"key_b";
		// Key after upper bound
		let key_z = b"key_z";

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(key_a, b"value_a", 1).unwrap();
			tx.set_at(key_b, b"value_b", 1).unwrap();
			tx.set_at(key_z, b"value_z", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();

		// Query range [key_a, key_c) should NOT return key_z
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"key_a", b"key_c", &opts).unwrap();

		// Iterate backward from the end
		iter.seek_last().unwrap();
		let mut results = Vec::new();
		while iter.valid() {
			let key_ref = iter.key();
			results.push(key_ref.user_key().to_vec());
			if !iter.prev().unwrap() {
				break;
			}
		}

		assert_eq!(
			results.len(),
			2,
			"with_index={with_index}: Only keys within range should be returned, got: {:?}",
			results.iter().map(|k| String::from_utf8_lossy(k)).collect::<Vec<_>>()
		);
		// Backward iteration returns newest first, so key_b then key_a
		assert_eq!(results[0], b"key_b".to_vec(), "with_index={with_index}: First should be key_b");
		assert_eq!(
			results[1],
			b"key_a".to_vec(),
			"with_index={with_index}: Second should be key_a"
		);

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

/// Test that both bounds are respected with keys outside both ends of the range.
#[test(tokio::test)]
async fn test_history_respects_both_bounds() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Keys before range
		let key_aa = b"aa_before";
		let key_ab = b"ab_before";
		// Keys in range
		let key_ma = b"ma_inside";
		let key_mb = b"mb_inside";
		let key_mc = b"mc_inside";
		// Keys after range
		let key_za = b"za_after";
		let key_zb = b"zb_after";

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(key_aa, b"v", 1).unwrap();
			tx.set_at(key_ab, b"v", 1).unwrap();
			tx.set_at(key_ma, b"v", 1).unwrap();
			tx.set_at(key_mb, b"v", 1).unwrap();
			tx.set_at(key_mc, b"v", 1).unwrap();
			tx.set_at(key_za, b"v", 1).unwrap();
			tx.set_at(key_zb, b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();

		// Query range [m, z) should only return keys starting with 'm'
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"m", b"z", &opts).unwrap();

		// Test forward iteration
		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(
			results.len(),
			3,
			"with_index={with_index}: Forward should return 3 keys in range, got: {:?}",
			results.iter().map(|(k, _, _, _)| String::from_utf8_lossy(k)).collect::<Vec<_>>()
		);
		for (key, _, _, _) in &results {
			assert!(
				key.as_slice() >= b"m".as_slice() && key.as_slice() < b"z".as_slice(),
				"with_index={with_index}: Key {:?} should be in range [m, z)",
				String::from_utf8_lossy(key)
			);
		}

		// Test backward iteration
		let mut iter = tx.history_with_options(b"m", b"z", &opts).unwrap();
		iter.seek_last().unwrap();
		let mut backward_results = Vec::new();
		while iter.valid() {
			backward_results.push(iter.key().user_key().to_vec());
			if !iter.prev().unwrap() {
				break;
			}
		}
		assert_eq!(
			backward_results.len(),
			3,
			"with_index={with_index}: Backward should return 3 keys in range, got: {:?}",
			backward_results.iter().map(|k| String::from_utf8_lossy(k)).collect::<Vec<_>>()
		);
		for key in &backward_results {
			assert!(
				key.as_slice() >= b"m".as_slice() && key.as_slice() < b"z".as_slice(),
				"with_index={with_index}: Key {:?} should be in range [m, z)",
				String::from_utf8_lossy(key)
			);
		}

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

/// Test bounds with timestamp ranges - keys outside range but within timestamp should be excluded.
#[test(tokio::test)]
async fn test_history_bounds_with_timestamp_range() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Key before range at target timestamp
		let key_before = b"aaa_before";
		// Key in range at target timestamp
		let key_inside = b"mmm_inside";
		// Key after range at target timestamp
		let key_after = b"zzz_after";

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			// All keys at timestamp 5
			tx.set_at(key_before, b"v", 5).unwrap();
			tx.set_at(key_inside, b"v", 5).unwrap();
			tx.set_at(key_after, b"v", 5).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();

		// Query with timestamp filter - should still respect bounds
		let opts = HistoryOptions::new().with_tombstones(true).with_ts_range(5, 5);
		let mut iter = tx.history_with_options(b"m", b"z", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(
			results.len(),
			1,
			"with_index={with_index}: Only key_inside should be returned, got: {:?}",
			results.iter().map(|(k, _, _, _)| String::from_utf8_lossy(k)).collect::<Vec<_>>()
		);
		assert_eq!(
			results[0].0,
			key_inside.to_vec(),
			"with_index={with_index}: Should return mmm_inside"
		);

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

/// Test direction switching (forward to backward) respects bounds.
#[test(tokio::test)]
async fn test_history_bounds_direction_switch_forward_to_backward() {
	for with_index in [false] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Keys: before range, in range (3 keys), after range
		let keys: [&[u8]; 5] = [b"aa_before", b"mm_in1", b"mm_in2", b"mm_in3", b"zz_after"];

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			for key in keys {
				tx.set_at(key, b"value", 1).unwrap();
			}
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let lower: &[u8] = b"m";
		let upper: &[u8] = b"z";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		// Forward: get first key
		iter.seek_first().unwrap();
		assert!(iter.valid(), "with_index={with_index}: Should be valid after seek_first");
		let first_key = iter.key().user_key().to_vec();
		assert_eq!(
			first_key,
			b"mm_in1".to_vec(),
			"with_index={with_index}: First key should be mm_in1"
		);

		// Move forward one more
		iter.next().unwrap();
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"mm_in2",
			"with_index={with_index}: Second should be mm_in2"
		);

		// Switch direction: go backward
		iter.prev().unwrap();
		assert!(iter.valid());
		let back_key = iter.key().user_key().to_vec();
		assert_eq!(
			back_key,
			b"mm_in1".to_vec(),
			"with_index={with_index}: After prev should be mm_in1"
		);

		// Continue backward - should become invalid (no more in-range keys)
		let has_more = iter.prev().unwrap();
		assert!(
			!has_more || !iter.valid(),
			"with_index={with_index}: Should have no more keys before mm_in1"
		);

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

/// Test direction switching (backward to forward) respects bounds.
#[test(tokio::test)]
async fn test_history_bounds_direction_switch_backward_to_forward() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		let keys: [&[u8]; 5] = [b"aa_before", b"mm_in1", b"mm_in2", b"mm_in3", b"zz_after"];

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			for key in keys {
				tx.set_at(key, b"value", 1).unwrap();
			}
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let lower: &[u8] = b"m";
		let upper: &[u8] = b"z";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		// Backward: get last key in range
		iter.seek_last().unwrap();
		assert!(iter.valid(), "with_index={with_index}: Should be valid after seek_last");
		let last_key = iter.key().user_key().to_vec();
		assert_eq!(
			last_key,
			b"mm_in3".to_vec(),
			"with_index={with_index}: Last key should be mm_in3"
		);

		// Move backward one
		iter.prev().unwrap();
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"mm_in2",
			"with_index={with_index}: Should be at mm_in2"
		);

		// Switch direction: go forward
		iter.next().unwrap();
		assert!(iter.valid());
		let fwd_key = iter.key().user_key().to_vec();
		assert_eq!(
			fwd_key,
			b"mm_in3".to_vec(),
			"with_index={with_index}: After next should be mm_in3"
		);

		// Continue forward - should become invalid (no more in-range keys)
		let has_more = iter.next().unwrap();
		assert!(
			!has_more || !iter.valid(),
			"with_index={with_index}: Should have no more keys after mm_in3"
		);

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

/// Test direction switching with keys that have many versions.
/// Verifies that prev/next correctly navigate across multi-version keys.
#[test(tokio::test)]
async fn test_history_direction_switch_multi_version_keys() {
	const VERSIONS_PER_KEY: u64 = 5;
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Create 3 keys, each with many versions
		for key in [b"key_a", b"key_b", b"key_c"] {
			for v in 1..=VERSIONS_PER_KEY {
				let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
				tx.set_at(
					key,
					format!("{}_v{}", std::str::from_utf8(key).unwrap(), v).as_bytes(),
					v * 100,
				)
				.unwrap();
				tx.commit().await.unwrap();
			}
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"key_a", b"key_d", &opts).unwrap();

		// --- Forward: advance past key_a (5 versions) to key_b
		iter.seek_first().unwrap();
		assert_eq!(
			iter.key().user_key(),
			b"key_a",
			"with_index={with_index}: First should be key_a"
		);
		for _ in 0..VERSIONS_PER_KEY {
			iter.next().unwrap();
		}
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"key_b",
			"with_index={with_index}: After key_a versions should be key_b"
		);

		// --- Switch backward: prev should go to last version of key_a
		iter.prev().unwrap();
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"key_a",
			"with_index={with_index}: After prev from key_b should be key_a"
		);
		assert_eq!(
			iter.value().unwrap(),
			b"key_a_v1",
			"with_index={with_index}: Should be oldest key_a"
		);

		// --- Switch forward: next advances one entry (key_a v1 -> v2). Advance through key_a to
		// key_b.
		for _ in 0..VERSIONS_PER_KEY {
			iter.next().unwrap();
		}
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"key_b",
			"with_index={with_index}: After advancing through key_a versions should be key_b"
		);

		// --- Forward: advance through key_b to key_c
		for _ in 0..VERSIONS_PER_KEY {
			iter.next().unwrap();
		}
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"key_c",
			"with_index={with_index}: After key_b versions should be key_c"
		);

		// --- Backward: seek_last, then prev through key_c to key_b
		iter.seek_last().unwrap();
		assert_eq!(
			iter.key().user_key(),
			b"key_c",
			"with_index={with_index}: Last should be key_c"
		);
		for _ in 0..VERSIONS_PER_KEY {
			iter.prev().unwrap();
		}
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"key_b",
			"with_index={with_index}: After key_c versions should be key_b"
		);

		// --- Switch forward: next advances one entry. Advance through key_b to key_c.
		for _ in 0..VERSIONS_PER_KEY {
			iter.next().unwrap();
		}
		assert!(iter.valid());
		assert_eq!(
			iter.key().user_key(),
			b"key_c",
			"with_index={with_index}: After advancing through key_b versions should be key_c"
		);

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

/// Test seeking to a key below lower_bound.
#[test(tokio::test)]
async fn test_history_seek_outside_lower_bound() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"aaa", b"v", 1).unwrap();
			tx.set_at(b"mmm", b"v", 1).unwrap();
			tx.set_at(b"zzz", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"m", b"z", &opts).unwrap();

		// Seek to key below lower_bound - should position at first in-range key or become invalid
		iter.seek(b"aaa").unwrap();
		if iter.valid() {
			let key = iter.key().user_key();
			assert!(
				key >= b"m".as_slice(),
				"with_index={with_index}: After seek below lower, key should be >= lower_bound, got: {:?}",
				String::from_utf8_lossy(key)
			);
		}

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

/// Test seeking to a key at or above upper_bound.
#[test(tokio::test)]
async fn test_history_seek_outside_upper_bound() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"aaa", b"v", 1).unwrap();
			tx.set_at(b"mmm", b"v", 1).unwrap();
			tx.set_at(b"zzz", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"m", b"z", &opts).unwrap();

		// Seek to key at upper_bound - should be invalid (upper is exclusive)
		iter.seek(b"z").unwrap();
		assert!(
			!iter.valid(),
			"with_index={with_index}: Seek to upper_bound should make iterator invalid"
		);

		// Seek to key above upper_bound
		let mut iter = tx.history_with_options(b"m", b"z", &opts).unwrap();
		iter.seek(b"zzz").unwrap();
		assert!(
			!iter.valid(),
			"with_index={with_index}: Seek above upper_bound should make iterator invalid"
		);

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

/// Test seeking to exact bound values.
#[test(tokio::test)]
async fn test_history_seek_to_exact_bounds() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_a", b"v", 1).unwrap();
			tx.set_at(b"key_m", b"v", 1).unwrap();
			tx.set_at(b"key_z", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);

		// Seek to exact lower_bound where key exists
		let mut iter = tx.history_with_options(b"key_m", b"key_z", &opts).unwrap();
		iter.seek(b"key_m").unwrap();
		assert!(iter.valid(), "with_index={with_index}: Seek to lower_bound should be valid");
		assert_eq!(iter.key().user_key(), b"key_m", "with_index={with_index}: Should be at key_m");

		// Seek to exact upper_bound - should be invalid (exclusive)
		iter.seek(b"key_z").unwrap();
		assert!(
			!iter.valid(),
			"with_index={with_index}: Seek to upper_bound should be invalid (exclusive)"
		);

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

/// Test key exactly at lower_bound is included (inclusive).
#[test(tokio::test)]
async fn test_history_key_at_exact_lower_bound() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"lower", b"v", 1).unwrap();
			tx.set_at(b"middle", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"lower", b"upper", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		assert!(
			results.iter().any(|(k, _, _, _)| k == b"lower"),
			"with_index={with_index}: Key exactly at lower_bound should be included"
		);

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

/// Test key exactly at upper_bound is excluded (exclusive).
#[test(tokio::test)]
async fn test_history_key_at_exact_upper_bound() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"middle", b"v", 1).unwrap();
			tx.set_at(b"upper", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"lower", b"upper", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		assert!(
			!results.iter().any(|(k, _, _, _)| k == b"upper"),
			"with_index={with_index}: Key exactly at upper_bound should be excluded"
		);
		assert!(
			results.iter().any(|(k, _, _, _)| k == b"middle"),
			"with_index={with_index}: Key before upper_bound should be included"
		);

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

/// Test adjacent byte boundaries with special byte values.
#[test(tokio::test)]
async fn test_history_adjacent_byte_boundaries() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		// Keys with adjacent byte values
		let key_before = b"key";
		let key_at_lower = b"key\x00";
		let key_in_range = b"key\x01";
		let key_at_upper = b"key\x10";

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(key_before, b"v", 1).unwrap();
			tx.set_at(key_at_lower, b"v", 1).unwrap();
			tx.set_at(key_in_range, b"v", 1).unwrap();
			tx.set_at(key_at_upper, b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		// Range: [key\x00, key\x10)
		let mut iter = tx.history_with_options(b"key\x00", b"key\x10", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();

		// key\x00 should be included (at lower bound, inclusive)
		assert!(
			results.iter().any(|(k, _, _, _)| k == key_at_lower),
			"with_index={with_index}: Key at lower bound should be included"
		);
		// key\x01 should be included (in range)
		assert!(
			results.iter().any(|(k, _, _, _)| k == key_in_range),
			"with_index={with_index}: Key in range should be included"
		);
		// key (without suffix) should be excluded (before lower)
		assert!(
			!results.iter().any(|(k, _, _, _)| k == key_before),
			"with_index={with_index}: Key before lower bound should be excluded"
		);
		// key\x10 should be excluded (at upper, exclusive)
		assert!(
			!results.iter().any(|(k, _, _, _)| k == key_at_upper),
			"with_index={with_index}: Key at upper bound should be excluded"
		);

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

/// Test tombstone (soft delete) at lower bound.
#[test(tokio::test)]
async fn test_history_tombstone_at_lower_bound() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_a", b"v", 1).unwrap();
			tx.set_at(b"key_b", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			let write_opts = crate::transaction::WriteOptions {
				timestamp: Some(2),
			};
			tx.soft_delete_with_options(b"key_a", &write_opts).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();

		// Without tombstones - key_a's older version (ts=1) should still appear,
		// but the tombstone at ts=2 should NOT appear
		let opts = HistoryOptions::new().with_tombstones(false);
		let mut iter = tx.history_with_options(b"key_a", b"key_z", &opts).unwrap();
		let results = collect_history_all(&mut iter).unwrap();
		// The value at ts=1 should appear
		assert!(
			results.iter().any(|(k, _, ts, is_tomb)| k == b"key_a" && *ts == 1 && !is_tomb),
			"with_index={with_index}: Without tombstones flag, older value version should still appear"
		);
		// The tombstone at ts=2 should NOT appear
		assert!(
			!results.iter().any(|(k, _, ts, is_tomb)| k == b"key_a" && *ts == 2 && *is_tomb),
			"with_index={with_index}: Without tombstones flag, tombstone should be filtered out"
		);

		// With tombstones - both versions of key_a should appear
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"key_a", b"key_z", &opts).unwrap();
		let results = collect_history_all(&mut iter).unwrap();
		// The tombstone at ts=2 should appear
		assert!(
			results.iter().any(|(k, _, ts, is_tomb)| k == b"key_a" && *ts == 2 && *is_tomb),
			"with_index={with_index}: With tombstones flag, tombstone at lower bound should appear"
		);
		// The value at ts=1 should also appear
		assert!(
			results.iter().any(|(k, _, ts, is_tomb)| k == b"key_a" && *ts == 1 && !is_tomb),
			"with_index={with_index}: With tombstones flag, older value should also appear"
		);

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

/// Test hard delete at boundary.
#[test(tokio::test)]
async fn test_history_hard_delete_at_boundary() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_a", b"v1", 1).unwrap();
			tx.set_at(b"key_b", b"v1", 1).unwrap();
			tx.commit().await.unwrap();
		}

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			let write_opts = crate::transaction::WriteOptions {
				timestamp: Some(2),
			};
			tx.delete_with_options(b"key_a", &write_opts).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"key_a", b"key_z", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		// Hard delete should completely remove the key from history
		assert!(
			!results.iter().any(|(k, _, _, _)| k == b"key_a"),
			"with_index={with_index}: Hard deleted key at boundary should not appear"
		);
		assert!(
			results.iter().any(|(k, _, _, _)| k == b"key_b"),
			"with_index={with_index}: Other keys should still appear"
		);

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

/// Test replace operation at boundary.
#[test(tokio::test)]
async fn test_history_replace_at_boundary() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_a", b"v1", 1).unwrap();
			tx.set_at(b"key_a", b"v2", 2).unwrap();
			tx.commit().await.unwrap();
		}

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.replace(b"key_a", b"v3").unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let mut iter = tx.history_with_options(b"key_a", b"key_z", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		let key_a_versions: Vec<_> = results.iter().filter(|(k, _, _, _)| k == b"key_a").collect();

		// Replace cuts off history - should only see v3 (the replace)
		assert_eq!(
			key_a_versions.len(),
			1,
			"with_index={with_index}: Replace should cut off history, only showing the replace version"
		);

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

/// Test equal lower and upper bounds (empty range).
#[test(tokio::test)]
async fn test_history_bounds_equal_lower_upper() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_a", b"v", 1).unwrap();
			tx.set_at(b"key_b", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		// Range [key_a, key_a) is empty since upper is exclusive
		let mut iter = tx.history_with_options(b"key_a", b"key_a", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(
			results.len(),
			0,
			"with_index={with_index}: Equal lower and upper bounds should return empty"
		);

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

/// Test inverted bounds (lower > upper).
#[test(tokio::test)]
async fn test_history_bounds_inverted() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_a", b"v", 1).unwrap();
			tx.set_at(b"key_b", b"v", 1).unwrap();
			tx.set_at(b"key_c", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		// Range [key_z, key_a) is inverted
		let mut iter = tx.history_with_options(b"key_z", b"key_a", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(
			results.len(),
			0,
			"with_index={with_index}: Inverted bounds should return empty"
		);

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

/// Test single key in range.
#[test(tokio::test)]
async fn test_history_single_key_in_range() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"only_key", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		let lower: &[u8] = b"only";
		let upper: &[u8] = b"only_z";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		// Forward
		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(results.len(), 1, "with_index={with_index}: Should have exactly 1 key");
		assert_eq!(results[0].0, b"only_key".to_vec());

		// Backward
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();
		iter.seek_last().unwrap();
		assert!(iter.valid(), "with_index={with_index}: seek_last should be valid");
		assert_eq!(iter.key().user_key(), b"only_key");

		let has_more = iter.prev().unwrap();
		assert!(!has_more, "with_index={with_index}: Should have no more keys");

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

/// Test all keys outside range.
#[test(tokio::test)]
async fn test_history_all_keys_outside_range() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"aaa", b"v", 1).unwrap();
			tx.set_at(b"bbb", b"v", 1).unwrap();
			tx.set_at(b"zzz", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		// Range [m, n) has no keys
		let mut iter = tx.history_with_options(b"m", b"n", &opts).unwrap();

		// Forward
		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(results.len(), 0, "with_index={with_index}: Forward should return empty");

		// Backward
		let mut iter = tx.history_with_options(b"m", b"n", &opts).unwrap();
		iter.seek_last().unwrap();
		assert!(
			!iter.valid(),
			"with_index={with_index}: seek_last should be invalid for empty range"
		);

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

/// Test bounds with limit (forward).
#[test(tokio::test)]
async fn test_history_bounds_with_limit() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			// 5 keys in range
			tx.set_at(b"key_1", b"v", 1).unwrap();
			tx.set_at(b"key_2", b"v", 1).unwrap();
			tx.set_at(b"key_3", b"v", 1).unwrap();
			tx.set_at(b"key_4", b"v", 1).unwrap();
			tx.set_at(b"key_5", b"v", 1).unwrap();
			// Keys outside range
			tx.set_at(b"aaa", b"v", 1).unwrap();
			tx.set_at(b"zzz", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true).with_limit(3);
		let lower: &[u8] = b"key";
		let upper: &[u8] = b"key_z";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(results.len(), 3, "with_index={with_index}: Limit should cap results to 3");
		// Verify results are in range
		for (key, _, _, _) in &results {
			assert!(
				key.as_slice() >= lower && key.as_slice() < upper,
				"with_index={with_index}: All keys should be in range"
			);
		}

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

/// Test bounds with limit (backward).
#[test(tokio::test)]
async fn test_history_bounds_with_limit_backward() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_1", b"v", 1).unwrap();
			tx.set_at(b"key_2", b"v", 1).unwrap();
			tx.set_at(b"key_3", b"v", 1).unwrap();
			tx.set_at(b"key_4", b"v", 1).unwrap();
			tx.set_at(b"key_5", b"v", 1).unwrap();
			tx.set_at(b"zzz", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true).with_limit(3);
		let lower: &[u8] = b"key";
		let upper: &[u8] = b"key_z";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		// Backward iteration with limit
		iter.seek_last().unwrap();
		let mut results = Vec::new();
		while iter.valid() && results.len() < 3 {
			let key = iter.key().user_key().to_vec();
			assert!(
				key.as_slice() >= lower && key.as_slice() < upper,
				"with_index={with_index}: Key should be in range, got: {:?}",
				String::from_utf8_lossy(&key)
			);
			results.push(key);
			if !iter.prev().unwrap() {
				break;
			}
		}

		assert!(results.len() <= 3, "with_index={with_index}: Should respect limit");

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

/// Test bounds with timestamp range and limit combined.
#[test(tokio::test)]
async fn test_history_bounds_ts_range_and_limit() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			// Keys at different timestamps
			tx.set_at(b"key_a", b"v_ts1", 1).unwrap();
			tx.set_at(b"key_b", b"v_ts1", 1).unwrap();
			tx.set_at(b"key_c", b"v_ts1", 1).unwrap();
			tx.commit().await.unwrap();
		}

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key_a", b"v_ts5", 5).unwrap();
			tx.set_at(b"key_b", b"v_ts5", 5).unwrap();
			tx.set_at(b"key_c", b"v_ts5", 5).unwrap();
			tx.set_at(b"key_d", b"v_ts5", 5).unwrap();
			tx.set_at(b"key_e", b"v_ts5", 5).unwrap();
			tx.commit().await.unwrap();
		}

		// Key outside range
		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"zzz", b"v_ts5", 5).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		// All three constraints: key bounds [key, key_z), ts_range [5,5], limit 3
		let opts = HistoryOptions::new().with_tombstones(true).with_ts_range(5, 5).with_limit(3);
		let lower: &[u8] = b"key";
		let upper: &[u8] = b"key_z";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();

		// Should have at most 3 results
		assert!(
			results.len() <= 3,
			"with_index={with_index}: Limit should be respected, got {}",
			results.len()
		);

		// All results should be in key range and ts range
		for (key, _, ts, _) in &results {
			assert!(
				key.as_slice() >= lower && key.as_slice() < upper,
				"with_index={with_index}: Key should be in range"
			);
			assert_eq!(*ts, 5, "with_index={with_index}: Timestamp should be 5");
		}

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

/// Test prefix pattern iteration (common use case).
#[test(tokio::test)]
async fn test_history_bounds_prefix_pattern() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			// Keys with prefix "user:"
			tx.set_at(b"user:alice", b"v", 1).unwrap();
			tx.set_at(b"user:bob", b"v", 1).unwrap();
			tx.set_at(b"user:charlie", b"v", 1).unwrap();
			// Keys without prefix
			tx.set_at(b"admin:root", b"v", 1).unwrap();
			tx.set_at(b"users_count", b"v", 1).unwrap(); // starts with "user" but not "user:"
			tx.set_at(b"userz", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		// Range for prefix "user:" is [user:, user;) since ';' is byte after ':'
		let mut iter = tx.history_with_options(b"user:", b"user;", &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();
		assert_eq!(
			results.len(),
			3,
			"with_index={with_index}: Should have 3 keys with prefix 'user:'"
		);

		for (key, _, _, _) in &results {
			assert!(
				key.starts_with(b"user:"),
				"with_index={with_index}: All keys should start with 'user:', got: {:?}",
				String::from_utf8_lossy(key)
			);
		}

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

/// Test keys and bounds containing null bytes.
#[test(tokio::test)]
async fn test_history_bounds_null_bytes() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			// Keys with embedded null bytes
			tx.set_at(b"key\x00a", b"v", 1).unwrap();
			tx.set_at(b"key\x00b", b"v", 1).unwrap();
			tx.set_at(b"key\x00c", b"v", 1).unwrap();
			// Key without null byte
			tx.set_at(b"key", b"v", 1).unwrap();
			tx.set_at(b"key\x01", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		// Range with null byte bounds: [key\x00, key\x01)
		let lower: &[u8] = b"key\x00";
		let upper: &[u8] = b"key\x01";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();

		// Should include key\x00a, key\x00b, key\x00c but not "key" or "key\x01"
		assert_eq!(
			results.len(),
			3,
			"with_index={with_index}: Should have 3 keys in null byte range"
		);

		for (key, _, _, _) in &results {
			assert!(
				key.starts_with(b"key\x00"),
				"with_index={with_index}: All keys should start with 'key\\x00'"
			);
		}

		// Verify "key" (without null) is not included
		assert!(
			!results.iter().any(|(k, _, _, _)| k == b"key"),
			"with_index={with_index}: 'key' without null should not be included"
		);

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

/// Test bounds with maximum byte values (0xFF).
#[test(tokio::test)]
async fn test_history_bounds_max_byte_values() {
	for with_index in [false, true] {
		let (store, _temp_dir) = create_versioned_store(with_index);

		{
			let mut tx = store.begin_with_mode(Mode::ReadWrite).unwrap();
			tx.set_at(b"key\xfe", b"v", 1).unwrap();
			tx.set_at(b"key\xff", b"v", 1).unwrap();
			tx.set_at(b"key\xff\x00", b"v", 1).unwrap();
			tx.set_at(b"kez", b"v", 1).unwrap();
			tx.commit().await.unwrap();
		}

		store.flush().unwrap();

		let tx = store.begin_with_mode(Mode::ReadOnly).unwrap();
		let opts = HistoryOptions::new().with_tombstones(true);
		// Range [key\xff, key\xff\xff) - keys starting with key\xff
		let lower: &[u8] = b"key\xff";
		let upper: &[u8] = b"key\xff\xff";
		let mut iter = tx.history_with_options(lower, upper, &opts).unwrap();

		let results = collect_history_all(&mut iter).unwrap();

		// Should include key\xff and key\xff\x00
		assert_eq!(
			results.len(),
			2,
			"with_index={with_index}: Should have 2 keys starting with 0xFF"
		);

		// Verify key\xfe is not included
		assert!(
			!results.iter().any(|(k, _, _, _)| k == b"key\xfe"),
			"with_index={with_index}: key\\xfe should not be included"
		);

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

// Test for https://github.com/surrealdb/surrealkv/issues/364
#[tokio::test(flavor = "current_thread")]
async fn repro() {
	let tmp = tempfile::Builder::new().prefix("tc-").tempdir().unwrap();

	let dir = std::path::PathBuf::from(tmp.path());

	let opts = Options::new().with_path(dir).with_versioning(true, 0).with_l0_no_compression();

	let store = TreeBuilder::with_options(opts).build().unwrap();

	let sync_key = b"#@prefix:sync\x00\x00\x00\x00\x00\x00\x00\x02****************";
	let table_key = b"@prefix:tbentity\x00\x00\x00\x00\x00\x00\x00\x00\x10cccccccccccccccc";
	let before_key = b"@prefix:tbentity\x00\x00\x00\x00\x00\x00\x00\x00\x10kkkkkkkkkkkkkkkk";
	let after_key = b"@prefix:tbentity\x00\x00\x00\x00\x00\x00\x00\x00\x10MMMMMMMMMMMMMMMM";

	{
		let mut tx = store.begin().unwrap();
		tx.set_at(before_key, b"value", 1).unwrap();
		tx.commit().await.unwrap();
	}

	{
		let mut tx = store.begin().unwrap();
		tx.set_at(sync_key, b"value", 2).unwrap();
		tx.set_at(table_key, b"value", 2).unwrap();
		tx.commit().await.unwrap();
	}

	{
		let mut tx = store.begin().unwrap();
		tx.set_at(after_key, b"value", 3).unwrap();
		tx.commit().await.unwrap();
	}

	let tx = store.begin().unwrap();

	let lower = b"@prefix:\x00";
	let upper = b"@prefix:\xFF";
	let opts = HistoryOptions::new().with_tombstones(true).with_ts_range(2, 2);
	let mut it = tx.history_with_options(lower, upper, &opts).unwrap();

	let mut seen = vec![];

	if it.seek_first().unwrap() {
		while it.valid() {
			let key = it.key();
			let user_key = String::from_utf8_lossy(key.user_key()).to_string();
			eprintln!("\t{}: {}", key.timestamp(), user_key);
			seen.push(user_key);

			it.next().unwrap();
		}
	}

	// Expected: only the @prefix key should be returned for this range.
	// Current behavior: this also returns #@prefix:* and reproduces the bug.
	assert_eq!(seen.len(), 1, "unexpected keys at ts=2 in scope range: {seen:?}");
}