slatedb 0.12.1

A cloud native embedded storage engine built on object storage.
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
use async_trait::async_trait;
use bytes::Bytes;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::Bound::{Excluded, Included, Unbounded};
use std::ops::{Bound, Range, RangeBounds};
use std::sync::Arc;
use tokio::task::JoinHandle;

use crate::block_iterator::BlockLike;
use crate::block_iterator_v2::BlockIteratorV2;
use crate::bytes_range::BytesRange;
use crate::db_state::{SsTableId, SsTableView};
use crate::db_stats::DbStats;
use crate::error::SlateDBError;
use crate::filter::{self, BloomFilter};
use crate::flatbuffer_types::{SsTableIndex, SsTableIndexOwned};
use crate::format::block::Block;
use crate::format::sst::{SST_FORMAT_VERSION, SST_FORMAT_VERSION_V2};
use crate::{
    block_iterator::BlockIterator,
    iter::{init_optional_iterator, IterationOrder, RowEntryIterator},
    partitioned_keyspace,
    tablestore::TableStore,
    types::RowEntry,
};

enum FetchTask {
    InFlight(JoinHandle<Result<VecDeque<Arc<Block>>, SlateDBError>>),
    Finished(VecDeque<Arc<Block>>),
}

enum DataBlockIterator<B: BlockLike> {
    V1(BlockIterator<B>),
    V2(BlockIteratorV2<B>),
}

impl<B: BlockLike> DataBlockIterator<B> {
    fn new(block: B, sst_version: u16, order: IterationOrder) -> Result<Self, SlateDBError> {
        match sst_version {
            SST_FORMAT_VERSION => Ok(Self::V1(BlockIterator::new(block, order))),
            SST_FORMAT_VERSION_V2 => Ok(Self::V2(BlockIteratorV2::new(block, order))),
            _ => Err(SlateDBError::InvalidVersion {
                format_name: "SST",
                supported_versions: vec![SST_FORMAT_VERSION, SST_FORMAT_VERSION_V2],
                actual_version: sst_version,
            }),
        }
    }

    async fn next(&mut self) -> Result<Option<RowEntry>, SlateDBError> {
        match self {
            Self::V1(iter) => iter.next().await,
            Self::V2(iter) => iter.next().await,
        }
    }

    async fn seek(&mut self, next_key: &[u8]) -> Result<(), SlateDBError> {
        match self {
            Self::V1(iter) => iter.seek(next_key).await,
            Self::V2(iter) => iter.seek(next_key).await,
        }
    }

    fn is_empty(&self) -> bool {
        match self {
            Self::V1(iter) => iter.is_empty(),
            Self::V2(iter) => iter.is_empty(),
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct SstIteratorOptions {
    pub(crate) max_fetch_tasks: usize,
    pub(crate) blocks_to_fetch: usize,
    pub(crate) cache_blocks: bool,
    pub(crate) eager_spawn: bool,
    pub(crate) order: IterationOrder,
}

impl Default for SstIteratorOptions {
    fn default() -> Self {
        SstIteratorOptions {
            max_fetch_tasks: 1,
            blocks_to_fetch: 1,
            cache_blocks: true,
            eager_spawn: false,
            order: IterationOrder::Ascending,
        }
    }
}

/// This enum encapsulates access to an SST and corresponding ownership requirements.
/// For example, [`SstView::Owned`] allows the table view to be owned, which is
/// needed for [`crate::db::Db::scan`] since it returns the iterator, while [`SstView::Borrowed`]
/// accommodates access by reference which is useful for [`crate::db::Db::get`].
pub(crate) enum SstView<'a> {
    Owned(Box<SsTableView>, BytesRange),
    Borrowed(&'a SsTableView, BytesRange),
}

impl SstView<'_> {
    fn start_key(&self) -> Bound<&[u8]> {
        match self {
            SstView::Owned(_, r) | SstView::Borrowed(_, r) => r.start_bound().map(|b| b.as_ref()),
        }
    }

    fn end_key(&self) -> Bound<&[u8]> {
        match self {
            SstView::Owned(_, r) | SstView::Borrowed(_, r) => r.end_bound().map(|b| b.as_ref()),
        }
    }

    fn point_key(&self) -> Option<&[u8]> {
        match (self.start_key(), self.end_key()) {
            (Bound::Included(start), Bound::Included(end)) if start == end => Some(start),
            _ => None,
        }
    }

    fn table_as_ref(&self) -> &SsTableView {
        match self {
            SstView::Owned(t, _) => t,
            SstView::Borrowed(t, _) => t,
        }
    }

    /// Check whether a key is contained within this view.
    fn contains(&self, key: &[u8]) -> bool {
        match self {
            SstView::Owned(_, r) => r.contains(key),
            SstView::Borrowed(_, r) => r.contains(key),
        }
    }

    /// Check whether a key exceeds the range of this view.
    fn key_exceeds(&self, key: &[u8]) -> bool {
        match self.end_key() {
            Included(end) => key > end,
            Excluded(end) => key >= end,
            Unbounded => false,
        }
    }

    /// Check whether a key is below the range of this view.
    fn key_precedes(&self, key: &[u8]) -> bool {
        match self.start_key() {
            Included(start) => key < start,
            Excluded(start) => key <= start,
            Unbounded => false,
        }
    }
}

struct IteratorState {
    initialized: bool,
    current_iter: Option<DataBlockIterator<Arc<Block>>>,
}

impl IteratorState {
    fn new() -> Self {
        Self {
            initialized: false,
            current_iter: None,
        }
    }

    fn is_finished(&self) -> bool {
        self.initialized && self.current_iter.is_none()
    }

    fn is_initialized(&self) -> bool {
        self.initialized
    }

    fn advance(&mut self, iterator: DataBlockIterator<Arc<Block>>) {
        self.initialized = true;
        self.current_iter = Some(iterator);
    }

    fn stop(&mut self) {
        self.initialized = true;
        self.current_iter = None;
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum FilterState {
    NotChecked,
    NoFilter,
    Positive,
    Negative,
}

struct BloomFilterEvaluator {
    key: Bytes,
    db_stats: Option<DbStats>,
    state: FilterState,
    found_key: bool,
    false_positive_recorded: bool,
}

impl BloomFilterEvaluator {
    fn new(key: Bytes, db_stats: Option<DbStats>) -> Self {
        Self {
            key,
            db_stats,
            state: FilterState::NotChecked,
            found_key: false,
            false_positive_recorded: false,
        }
    }
}

impl BloomFilterEvaluator {
    /// Evaluate the bloom filter against the key.
    ///
    /// ## Arguments
    /// - `maybe_filter`: An optional bloom filter to evaluate against.
    async fn evaluate(&mut self, maybe_filter: Option<Arc<BloomFilter>>) {
        if self.state != FilterState::NotChecked {
            return;
        }

        let key_hash = filter::filter_hash(self.key.as_ref());

        match maybe_filter {
            Some(filter) => {
                if filter.might_contain(key_hash) {
                    if let Some(stats) = &self.db_stats {
                        stats.sst_filter_positives.increment(1);
                    }
                    self.state = FilterState::Positive;
                } else {
                    if let Some(stats) = &self.db_stats {
                        stats.sst_filter_negatives.increment(1);
                    }
                    self.state = FilterState::Negative;
                }
            }
            None => {
                self.state = FilterState::NoFilter;
            }
        }
    }

    fn is_filtered_out(&self) -> bool {
        self.state == FilterState::Negative
    }

    fn notify_key_found(&mut self, key: &[u8]) {
        if key == self.key.as_ref() {
            self.found_key = true;
        }
    }

    fn notify_finished_iteration(&mut self) {
        if self.state == FilterState::Positive && !self.found_key && !self.false_positive_recorded {
            if let Some(stats) = &self.db_stats {
                stats.sst_filter_false_positives.increment(1);
            }
            self.false_positive_recorded = true;
        }
    }
}

pub(crate) struct InternalSstIterator<'a> {
    view: SstView<'a>,
    index: Option<Arc<SsTableIndexOwned>>,
    state: IteratorState,
    next_block_idx_to_fetch: usize,
    block_idx_range: Range<usize>,
    fetch_tasks: VecDeque<FetchTask>,
    table_store: Arc<TableStore>,
    options: SstIteratorOptions,
    /// Buffer for descending iteration to maintain correct sequence order within keys.
    descending_buffer: Option<VecDeque<RowEntry>>,
    /// Pending entry that was read ahead but belongs to the next key group.
    /// Only used in descending mode.
    pending_entry: Option<RowEntry>,
}

impl<'a> InternalSstIterator<'a> {
    fn new(
        view: SstView<'a>,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Self, SlateDBError> {
        assert!(options.max_fetch_tasks > 0);
        assert!(options.blocks_to_fetch > 0);

        let descending_buffer = match options.order {
            IterationOrder::Descending => Some(VecDeque::new()),
            IterationOrder::Ascending => None,
        };

        Ok(Self {
            view,
            index: None,
            state: IteratorState::new(),
            next_block_idx_to_fetch: 0,
            block_idx_range: 0..0,
            fetch_tasks: VecDeque::new(),
            table_store,
            options,
            descending_buffer,
            pending_entry: None,
        })
    }

    fn table_id(&self) -> SsTableId {
        self.view.table_as_ref().sst.id
    }

    fn view(&self) -> &SstView<'a> {
        &self.view
    }

    fn table_store(&self) -> &Arc<TableStore> {
        &self.table_store
    }

    fn new_owned<T: RangeBounds<Bytes>>(
        range: T,
        table: SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        let Some(view_range) = table.calculate_view_range(BytesRange::from(range)) else {
            return Ok(None);
        };
        let view = SstView::Owned(Box::new(table), view_range);
        Self::new(view, table_store, options).map(Some)
    }

    async fn new_owned_initialized<T: RangeBounds<Bytes>>(
        range: T,
        table: SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        let iter = Self::new_owned(range, table, table_store, options)?;
        init_optional_iterator(iter).await
    }

    fn new_borrowed<T: RangeBounds<Bytes>>(
        range: T,
        table: &'a SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        let Some(view_range) = table.calculate_view_range(BytesRange::from(range)) else {
            return Ok(None);
        };
        let view = SstView::Borrowed(table, view_range);
        Self::new(view, table_store, options).map(Some)
    }

    async fn new_borrowed_initialized<T: RangeBounds<Bytes>>(
        range: T,
        table: &'a SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        let iter = Self::new_borrowed(range, table, table_store, options)?;
        init_optional_iterator(iter).await
    }

    fn for_key(
        table: &'a SsTableView,
        key: &'a [u8],
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        Self::new_borrowed(
            BytesRange::from_slice(key..=key),
            table,
            table_store,
            options,
        )
    }

    async fn for_key_initialized(
        table: &'a SsTableView,
        key: &'a [u8],
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        let iter = Self::for_key(table, key, table_store, options)?;
        init_optional_iterator(iter).await
    }

    fn last_block_with_data_including_key(index: &SsTableIndex, key: &[u8]) -> Option<usize> {
        partitioned_keyspace::last_partition_including_key(index, key)
    }

    fn first_block_with_data_including_or_after_key(index: &SsTableIndex, key: &[u8]) -> usize {
        partitioned_keyspace::first_partition_including_or_after_key(index, key)
    }

    fn blocks_covering_view(index: &SsTableIndex, view: &SstView) -> Range<usize> {
        let start_block_id = match view.start_key() {
            Included(k) | Excluded(k) => {
                Self::first_block_with_data_including_or_after_key(index, k)
            }
            Unbounded => 0,
        };

        let end_block_id_exclusive = match view.end_key() {
            Included(k) => Self::last_block_with_data_including_key(index, k)
                .map(|b| b + 1)
                .unwrap_or(start_block_id),
            Excluded(k) => {
                let block_index = Self::last_block_with_data_including_key(index, k);
                match block_index {
                    None => start_block_id,
                    Some(block_index) => {
                        let block = index.block_meta().get(block_index);
                        if k == block.first_key().bytes() {
                            block_index
                        } else {
                            block_index + 1
                        }
                    }
                }
            }
            Unbounded => index.block_meta().len(),
        };

        start_block_id..end_block_id_exclusive
    }

    /// Spawns fetch tasks for blocks based on iteration order.
    ///
    /// For ascending order: Fetches blocks forward from `next_block_idx_to_fetch`, incrementing it
    /// as blocks are scheduled. Stops when reaching `block_idx_range.end`.
    ///
    /// For descending order: Fetches blocks backward from `next_block_idx_to_fetch - 1`,
    /// decrementing `next_block_idx_to_fetch` as blocks are scheduled. Stops when reaching
    /// `block_idx_range.start`.
    fn spawn_fetches(&mut self) {
        let Some(index) = self.index.as_ref() else {
            return;
        };

        match self.options.order {
            IterationOrder::Ascending => {
                // Fetch blocks forward: next_block_idx_to_fetch advances toward block_idx_range.end
                while self.fetch_tasks.len() < self.options.max_fetch_tasks
                    && self.block_idx_range.contains(&self.next_block_idx_to_fetch)
                {
                    let blocks_to_fetch = min(
                        self.options.blocks_to_fetch,
                        self.block_idx_range.end - self.next_block_idx_to_fetch,
                    );
                    let table = self.view.table_as_ref().sst.clone();
                    let table_store = self.table_store.clone();
                    let blocks_start = self.next_block_idx_to_fetch;
                    let blocks_end = self.next_block_idx_to_fetch + blocks_to_fetch;
                    let index = index.clone();
                    let cache_blocks = self.options.cache_blocks;
                    self.fetch_tasks
                        .push_back(FetchTask::InFlight(tokio::spawn(async move {
                            table_store
                                .read_blocks_using_index(
                                    &table,
                                    index,
                                    blocks_start..blocks_end,
                                    cache_blocks,
                                )
                                .await
                        })));
                    self.next_block_idx_to_fetch = blocks_end;
                }
            }
            IterationOrder::Descending => {
                // Fetch blocks backward: next_block_idx_to_fetch retreats toward block_idx_range.start
                while self.fetch_tasks.len() < self.options.max_fetch_tasks
                    && self.next_block_idx_to_fetch > self.block_idx_range.start
                {
                    let blocks_to_fetch = min(
                        self.options.blocks_to_fetch,
                        self.next_block_idx_to_fetch - self.block_idx_range.start,
                    );
                    let table = self.view.table_as_ref().sst.clone();
                    let table_store = self.table_store.clone();
                    let blocks_end = self.next_block_idx_to_fetch;
                    let blocks_start = blocks_end - blocks_to_fetch;
                    let index = index.clone();
                    let cache_blocks = self.options.cache_blocks;
                    self.fetch_tasks
                        .push_back(FetchTask::InFlight(tokio::spawn(async move {
                            table_store
                                .read_blocks_using_index(
                                    &table,
                                    index,
                                    blocks_start..blocks_end,
                                    cache_blocks,
                                )
                                .await
                        })));
                    self.next_block_idx_to_fetch = blocks_start;
                }
            }
        }
    }

    async fn next_iter(
        &mut self,
        spawn_fetches: bool,
    ) -> Result<Option<DataBlockIterator<Arc<Block>>>, SlateDBError> {
        if self.index.is_none() {
            return Ok(None);
        }
        let sst_version = self.view.table_as_ref().sst.format_version;
        loop {
            if spawn_fetches {
                self.spawn_fetches();
            }
            if let Some(fetch_task) = self.fetch_tasks.front_mut() {
                match fetch_task {
                    FetchTask::InFlight(jh) => {
                        let blocks = jh.await.expect("join task failed")?;
                        *fetch_task = FetchTask::Finished(blocks);
                    }
                    FetchTask::Finished(blocks) => {
                        // For descending order, pop from back; for ascending, pop from front
                        let block = match self.options.order {
                            IterationOrder::Ascending => blocks.pop_front(),
                            IterationOrder::Descending => blocks.pop_back(),
                        };

                        if let Some(block) = block {
                            return Ok(Some(DataBlockIterator::new(
                                block,
                                sst_version,
                                self.options.order,
                            )?));
                        } else {
                            self.fetch_tasks.pop_front();
                        }
                    }
                }
            } else {
                assert!(self.fetch_tasks.is_empty());
                // With spawn_fetches=true, running out of tasks means we've
                // exhausted the entire range.
                // With spawn_fetches=false, it only means the prefetch buffer
                // is drained, but there may still be blocks in the range, and
                // the caller is responsible for scheduling more fetches if
                // needed.
                if spawn_fetches {
                    match self.options.order {
                        IterationOrder::Ascending => {
                            assert_eq!(self.next_block_idx_to_fetch, self.block_idx_range.end);
                        }
                        IterationOrder::Descending => {
                            assert_eq!(self.next_block_idx_to_fetch, self.block_idx_range.start);
                        }
                    }
                }
                return Ok(None);
            }
        }
    }

    async fn advance_block(&mut self) -> Result<(), SlateDBError> {
        self.ensure_metadata_loaded().await?;
        if !self.state.is_finished() {
            if let Some(mut iter) = self.next_iter(true).await? {
                // Only seek on the first block to position at the range boundary.
                // For subsequent blocks, iterate through the entire block in the specified order.
                if !self.state.is_initialized() {
                    match self.options.order {
                        IterationOrder::Ascending => match self.view.start_key() {
                            Included(start_key) | Excluded(start_key) => {
                                iter.seek(start_key).await?
                            }
                            Unbounded => (),
                        },
                        IterationOrder::Descending => match self.view.end_key() {
                            Included(end_key) | Excluded(end_key) => iter.seek(end_key).await?,
                            Unbounded => (),
                        },
                    }
                }
                self.state.advance(iter);
            } else {
                self.state.stop();
            }
        }
        Ok(())
    }

    fn stop(&mut self) {
        if let Some(index) = self.index.as_ref() {
            // For ascending order, stopping means we've gone to the end
            // For descending order, stopping means we've gone to the beginning
            match self.options.order {
                IterationOrder::Ascending => {
                    let num_blocks = index.borrow().block_meta().len();
                    self.next_block_idx_to_fetch = num_blocks;
                }
                IterationOrder::Descending => {
                    self.next_block_idx_to_fetch = 0;
                }
            }
        }
        self.state.stop();
    }

    async fn ensure_metadata_loaded(&mut self) -> Result<(), SlateDBError> {
        if self.index.is_none() {
            let index = self
                .table_store
                .read_index(&self.view.table_as_ref().sst, self.options.cache_blocks)
                .await?;
            let block_idx_range =
                InternalSstIterator::blocks_covering_view(&index.borrow(), &self.view);
            self.block_idx_range = block_idx_range.clone();
            // For descending order, start from the end and work backwards
            self.next_block_idx_to_fetch = match self.options.order {
                IterationOrder::Ascending => block_idx_range.start,
                IterationOrder::Descending => block_idx_range.end,
            };
            self.index = Some(index);
            if self.options.eager_spawn {
                self.spawn_fetches();
            }
        }
        Ok(())
    }

    async fn fill_descending_buffer(&mut self) -> Result<(), SlateDBError> {
        let mut temp_buffer = Vec::new();
        let mut target_key: Option<Bytes> = None;

        if let Some(pending) = self.pending_entry.take() {
            target_key = Some(pending.key.clone());
            temp_buffer.push(pending);
        }

        loop {
            let next = if let Some(iter) = self.state.current_iter.as_mut() {
                iter.next().await?
            } else {
                None
            };

            match next {
                Some(kv) => {
                    if !self.view.contains(&kv.key) {
                        if self.view.key_precedes(&kv.key) {
                            self.stop();
                            break;
                        }
                        continue;
                    }

                    if target_key.is_none() {
                        target_key = Some(kv.key.clone());
                        temp_buffer.push(kv);
                    } else if Some(&kv.key) == target_key.as_ref() {
                        temp_buffer.push(kv);
                    } else {
                        self.pending_entry = Some(kv);
                        break;
                    }
                }
                None => {
                    self.advance_block().await?;
                    if self.state.is_finished() {
                        break;
                    }
                }
            }
        }

        temp_buffer.reverse();
        self.descending_buffer
            .as_mut()
            .expect("descending_buffer must exist in descending mode")
            .extend(temp_buffer);

        Ok(())
    }
}

#[async_trait]
impl RowEntryIterator for InternalSstIterator<'_> {
    async fn init(&mut self) -> Result<(), SlateDBError> {
        if !self.state.is_initialized() {
            self.advance_block().await?;
        }
        Ok(())
    }

    async fn next(&mut self) -> Result<Option<RowEntry>, SlateDBError> {
        if !self.state.is_initialized() {
            return Err(SlateDBError::IteratorNotInitialized);
        }

        match self.options.order {
            IterationOrder::Descending => {
                if let Some(buffer) = &mut self.descending_buffer {
                    if let Some(entry) = buffer.pop_front() {
                        return Ok(Some(entry));
                    }
                }

                self.fill_descending_buffer().await?;

                return Ok(self
                    .descending_buffer
                    .as_mut()
                    .expect("descending_buffer must exist in descending mode")
                    .pop_front());
            }
            IterationOrder::Ascending => {}
        }

        while !self.state.is_finished() {
            let next = if let Some(iter) = self.state.current_iter.as_mut() {
                iter.next().await?
            } else {
                None
            };

            match next {
                Some(kv) => {
                    if self.view.contains(&kv.key) {
                        return Ok(Some(kv));
                    } else if self.view.key_exceeds(&kv.key) {
                        self.stop();
                    }
                }
                None => self.advance_block().await?,
            }
        }
        Ok(None)
    }

    async fn seek(&mut self, next_key: &[u8]) -> Result<(), SlateDBError> {
        if !self.state.is_initialized() {
            return Err(SlateDBError::IteratorNotInitialized);
        }
        if !self.view.contains(next_key) {
            if self.view.key_exceeds(next_key) {
                match self.options.order {
                    IterationOrder::Ascending => {
                        // Seeking beyond the end of the view range in ascending order
                        // means there are no more results.
                        self.stop();
                        return Ok(());
                    }
                    IterationOrder::Descending => {
                        // Seeking beyond the end in descending order means "start
                        // from the last key and go backwards" — fall through to
                        // the normal seek logic.
                    }
                }
            } else {
                return Err(SlateDBError::SeekKeyOutOfKeyRange {
                    key: next_key.to_vec(),
                    start_key: self.view.start_key().map(|b| b.to_vec()),
                    end_key: self.view.end_key().map(|b| b.to_vec()),
                });
            }
        }
        if !self.state.is_finished() {
            if let Some(iter) = self.state.current_iter.as_mut() {
                iter.seek(next_key).await?;
                if !iter.is_empty() {
                    return Ok(());
                }
            }

            let index = self
                .index
                .as_ref()
                .expect("metadata must be initialized")
                .clone();

            // For descending order, find the last block with the key
            // For ascending order, find the first block with or after the key
            let block_idx = match self.options.order {
                IterationOrder::Ascending => {
                    Self::first_block_with_data_including_or_after_key(&index.borrow(), next_key)
                }
                IterationOrder::Descending => {
                    Self::last_block_with_data_including_key(&index.borrow(), next_key)
                        .unwrap_or(self.block_idx_range.start)
                }
            };

            // Check if block is in the already-fetched direction
            let already_fetched = match self.options.order {
                IterationOrder::Ascending => block_idx < self.next_block_idx_to_fetch,
                IterationOrder::Descending => block_idx >= self.next_block_idx_to_fetch,
            };

            if already_fetched {
                while let Some(mut block_iter) = self.next_iter(false).await? {
                    block_iter.seek(next_key).await?;
                    if !block_iter.is_empty() {
                        self.state.advance(block_iter);
                        return Ok(());
                    }
                }
            }

            self.fetch_tasks.clear();
            self.next_block_idx_to_fetch = match self.options.order {
                IterationOrder::Ascending => block_idx,
                IterationOrder::Descending => block_idx + 1,
            };

            if let Some(mut block_iter) = self.next_iter(true).await? {
                block_iter.seek(next_key).await?;
                self.state.advance(block_iter);
            } else {
                self.state.stop();
            }
        }
        Ok(())
    }
}

struct BloomFilterIterator<'a> {
    inner: InternalSstIterator<'a>,
    filter: BloomFilterEvaluator,
    initialized: bool,
}

impl<'a> BloomFilterIterator<'a> {
    fn new(inner: InternalSstIterator<'a>, filter: BloomFilterEvaluator) -> Self {
        Self {
            inner,
            filter,
            initialized: false,
        }
    }

    fn table_id(&self) -> SsTableId {
        self.inner.table_id()
    }

    fn is_filtered_out(&self) -> bool {
        self.filter.is_filtered_out()
    }
}

#[async_trait]
impl RowEntryIterator for BloomFilterIterator<'_> {
    async fn init(&mut self) -> Result<(), SlateDBError> {
        if !self.initialized {
            let maybe_filter = self
                .inner
                .table_store()
                .read_filter(
                    &self.inner.view().table_as_ref().sst,
                    self.inner.options.cache_blocks,
                )
                .await?;
            self.filter.evaluate(maybe_filter).await;

            if self.is_filtered_out() {
                return Ok(());
            }

            // make sure initializing the inner iterator only happens after
            // the filter is evaluated to avoid unnecessary work
            self.inner.init().await?;
            self.initialized = true;
        }

        Ok(())
    }

    async fn next(&mut self) -> Result<Option<RowEntry>, SlateDBError> {
        if self.is_filtered_out() {
            self.filter.notify_finished_iteration();
            return Ok(None);
        }

        let next = self.inner.next().await?;
        if let Some(entry) = next.as_ref() {
            self.filter.notify_key_found(entry.key.as_ref());
        } else {
            self.filter.notify_finished_iteration();
        }

        Ok(next)
    }

    async fn seek(&mut self, next_key: &[u8]) -> Result<(), SlateDBError> {
        if self.is_filtered_out() {
            return Ok(());
        }

        self.inner.seek(next_key).await
    }
}

#[allow(clippy::large_enum_variant)]
enum SstIteratorDelegate<'a> {
    Direct(InternalSstIterator<'a>),
    Bloom(BloomFilterIterator<'a>),
}

pub(crate) struct SstIterator<'a> {
    delegate: SstIteratorDelegate<'a>,
}

impl<'a> SstIterator<'a> {
    fn from_internal(internal: InternalSstIterator<'a>, db_stats: Option<DbStats>) -> Self {
        let point_key = internal.view().point_key().map(Bytes::copy_from_slice);
        let delegate = match point_key {
            Some(key) => {
                let filter = BloomFilterEvaluator::new(key, db_stats);
                SstIteratorDelegate::Bloom(BloomFilterIterator::new(internal, filter))
            }
            None => SstIteratorDelegate::Direct(internal),
        };
        Self { delegate }
    }

    #[allow(dead_code)]
    pub(crate) fn new(
        view: SstView<'a>,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Self, SlateDBError> {
        Self::new_with_stats(view, table_store, options, None)
    }

    pub(crate) fn new_with_stats(
        view: SstView<'a>,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
        db_stats: Option<DbStats>,
    ) -> Result<Self, SlateDBError> {
        let internal = InternalSstIterator::new(view, table_store, options)?;
        Ok(Self::from_internal(internal, db_stats))
    }

    #[allow(dead_code)]
    pub(crate) fn new_owned_with_stats<T: RangeBounds<Bytes>>(
        range: T,
        table: SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
        db_stats: Option<DbStats>,
    ) -> Result<Option<Self>, SlateDBError> {
        let internal = InternalSstIterator::new_owned(range, table, table_store, options)?;
        Ok(internal.map(|iter| Self::from_internal(iter, db_stats.clone())))
    }

    #[allow(dead_code)]
    pub(crate) fn new_owned<T: RangeBounds<Bytes>>(
        range: T,
        table: SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        Self::new_owned_with_stats(range, table, table_store, options, None)
    }

    pub(crate) async fn new_owned_initialized<T: RangeBounds<Bytes>>(
        range: T,
        table: SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        let internal =
            InternalSstIterator::new_owned_initialized(range, table, table_store, options).await?;
        match internal {
            Some(inner) => {
                let mut iterator = Self::from_internal(inner, None);
                if let SstIteratorDelegate::Bloom(inner) = &mut iterator.delegate {
                    inner.init().await?;
                    if inner.is_filtered_out() {
                        return Ok(None);
                    }
                }
                Ok(Some(iterator))
            }
            None => Ok(None),
        }
    }

    #[allow(dead_code)]
    fn new_borrowed_with_stats<T: RangeBounds<Bytes>>(
        range: T,
        table: &'a SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
        db_stats: Option<DbStats>,
    ) -> Result<Option<Self>, SlateDBError> {
        let internal = InternalSstIterator::new_borrowed(range, table, table_store, options)?;
        Ok(internal.map(|iter| Self::from_internal(iter, db_stats.clone())))
    }

    #[allow(dead_code)]
    pub(crate) fn new_borrowed<T: RangeBounds<Bytes>>(
        range: T,
        table: &'a SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        Self::new_borrowed_with_stats(range, table, table_store, options, None)
    }

    pub(crate) async fn new_borrowed_initialized<T: RangeBounds<Bytes>>(
        range: T,
        table: &'a SsTableView,
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
    ) -> Result<Option<Self>, SlateDBError> {
        let internal =
            InternalSstIterator::new_borrowed_initialized(range, table, table_store, options)
                .await?;
        match internal {
            Some(inner) => {
                let mut iterator = Self::from_internal(inner, None);
                if let SstIteratorDelegate::Bloom(inner) = &mut iterator.delegate {
                    inner.init().await?;
                    if inner.is_filtered_out() {
                        return Ok(None);
                    }
                }
                Ok(Some(iterator))
            }
            None => Ok(None),
        }
    }

    #[allow(dead_code)]
    pub(crate) fn for_key_with_stats(
        table: &'a SsTableView,
        key: &'a [u8],
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
        db_stats: Option<DbStats>,
    ) -> Result<Option<Self>, SlateDBError> {
        let internal = InternalSstIterator::for_key(table, key, table_store, options)?;
        Ok(internal.map(|iter| Self::from_internal(iter, db_stats.clone())))
    }

    #[allow(dead_code)]
    pub(crate) async fn for_key_with_stats_initialized(
        table: &'a SsTableView,
        key: &'a [u8],
        table_store: Arc<TableStore>,
        options: SstIteratorOptions,
        db_stats: Option<DbStats>,
    ) -> Result<Option<Self>, SlateDBError> {
        let internal =
            InternalSstIterator::for_key_initialized(table, key, table_store, options).await?;
        match internal {
            Some(inner) => {
                let mut iterator = Self::from_internal(inner, db_stats);
                if let SstIteratorDelegate::Bloom(inner) = &mut iterator.delegate {
                    inner.init().await?;
                    if inner.is_filtered_out() {
                        return Ok(None);
                    }
                }
                Ok(Some(iterator))
            }
            None => Ok(None),
        }
    }

    pub(crate) fn table_id(&self) -> SsTableId {
        match &self.delegate {
            SstIteratorDelegate::Direct(inner) => inner.table_id(),
            SstIteratorDelegate::Bloom(inner) => inner.table_id(),
        }
    }

    #[allow(dead_code)]
    pub(crate) fn is_filtered_out(&self) -> bool {
        match &self.delegate {
            SstIteratorDelegate::Direct(_) => false,
            SstIteratorDelegate::Bloom(inner) => inner.is_filtered_out(),
        }
    }
}

#[async_trait]
impl RowEntryIterator for SstIterator<'_> {
    async fn init(&mut self) -> Result<(), SlateDBError> {
        match &mut self.delegate {
            SstIteratorDelegate::Direct(inner) => inner.init().await,
            SstIteratorDelegate::Bloom(inner) => inner.init().await,
        }
    }

    async fn next(&mut self) -> Result<Option<RowEntry>, SlateDBError> {
        match &mut self.delegate {
            SstIteratorDelegate::Direct(inner) => inner.next().await,
            SstIteratorDelegate::Bloom(inner) => inner.next().await,
        }
    }

    async fn seek(&mut self, next_key: &[u8]) -> Result<(), SlateDBError> {
        match &mut self.delegate {
            SstIteratorDelegate::Direct(inner) => inner.seek(next_key).await,
            SstIteratorDelegate::Bloom(inner) => inner.seek(next_key).await,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bytes_generator::OrderedBytesGenerator;
    use crate::db_cache::test_utils::TestCache;
    use crate::db_cache::DbCache;
    use crate::db_cache::SplitCache;
    use crate::db_state::{SsTableId, SsTableView};
    use crate::db_stats::DbStats;
    use crate::filter;
    use crate::format::sst::SsTableFormat;
    use crate::object_stores::ObjectStores;
    use crate::sst_builder::BlockFormat;
    use crate::test_utils::assert_kv;
    use crate::types::{KeyValue, ValueDeletable};
    use object_store::path::Path;
    use object_store::{memory::InMemory, ObjectStore};
    use slatedb_common::metrics::{
        lookup_metric, DefaultMetricsRecorder, MetricLevel, MetricsRecorderHelper,
    };
    use std::sync::Arc;

    #[tokio::test]
    async fn test_one_block_sst_iter() {
        test_one_block_sst_iter_with_order(IterationOrder::Ascending).await;
        test_one_block_sst_iter_with_order(IterationOrder::Descending).await;
    }

    async fn test_one_block_sst_iter_with_order(order: IterationOrder) {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            min_filter_keys: 3,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));
        let mut builder = table_store.table_builder();
        builder
            .add_value(b"key1", b"value1", Some(1), None)
            .await
            .unwrap();
        builder
            .add_value(b"key2", b"value2", Some(2), None)
            .await
            .unwrap();
        builder
            .add_value(b"key3", b"value3", Some(3), None)
            .await
            .unwrap();
        builder
            .add_value(b"key4", b"value4", Some(4), None)
            .await
            .unwrap();
        let encoded = builder.build().await.unwrap();
        table_store
            .write_sst(&SsTableId::Wal(0), encoded, false)
            .await
            .unwrap();
        let sst_handle = table_store.open_sst(&SsTableId::Wal(0)).await.unwrap();
        let index = table_store.read_index(&sst_handle, true).await.unwrap();
        assert_eq!(index.borrow().block_meta().len(), 1);

        let sst_iter_options = SstIteratorOptions {
            cache_blocks: true,
            order,
            ..SstIteratorOptions::default()
        };
        let mut iter = SstIterator::new_owned_initialized(
            ..,
            SsTableView::identity(sst_handle),
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // Expected keys based on order
        let expected_keys = match order {
            IterationOrder::Ascending => vec![b"key1", b"key2", b"key3", b"key4"],
            IterationOrder::Descending => vec![b"key4", b"key3", b"key2", b"key1"],
        };
        let expected_values = match order {
            IterationOrder::Ascending => vec![b"value1", b"value2", b"value3", b"value4"],
            IterationOrder::Descending => vec![b"value4", b"value3", b"value2", b"value1"],
        };

        for (expected_key, expected_value) in expected_keys.iter().zip(expected_values.iter()) {
            let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
            assert_eq!(kv.key, expected_key.as_slice());
            assert_eq!(kv.value, expected_value.as_slice());
        }
        let kv = iter.next().await.unwrap().map(KeyValue::from);
        assert!(kv.is_none());
    }

    #[tokio::test]
    async fn should_record_bloom_filter_positive_for_single_key() {
        // given
        let recorder = Arc::new(DefaultMetricsRecorder::new());
        let helper = MetricsRecorderHelper::new(recorder.clone(), MetricLevel::default());
        let db_stats = DbStats::new(&helper);
        let table_store = bloom_filter_enabled_table_store(10);
        let sst_handle = build_single_block_sst(&table_store, &[b"k1", b"k2"]).await;

        // when
        let mut iter = SstIterator::for_key_with_stats_initialized(
            &sst_handle,
            b"k1",
            table_store.clone(),
            SstIteratorOptions::default(),
            Some(db_stats.clone()),
        )
        .await
        .expect("iterator construction should succeed")
        .expect("expected iterator for present key");
        let entry = iter
            .next()
            .await
            .expect("iteration should succeed")
            .expect("expected entry for present key");

        // then
        assert_eq!(entry.key.as_ref(), b"k1");
        match entry.value {
            ValueDeletable::Value(value) => assert_eq!(value.as_ref(), b"v_k1"),
            other => panic!("expected value, found {other:?}"),
        }
        assert_eq!(
            lookup_metric(&recorder, crate::db_stats::SST_FILTER_POSITIVE_COUNT),
            Some(1)
        );
        assert_eq!(
            lookup_metric(&recorder, crate::db_stats::SST_FILTER_FALSE_POSITIVE_COUNT),
            Some(0)
        );
    }

    #[tokio::test]
    async fn should_record_bloom_filter_negative_for_missing_key() {
        // given
        let recorder = Arc::new(DefaultMetricsRecorder::new());
        let helper = MetricsRecorderHelper::new(recorder.clone(), MetricLevel::default());
        let db_stats = DbStats::new(&helper);
        let table_store = bloom_filter_enabled_table_store(10);
        let sst_handle = build_single_block_sst(&table_store, &[b"k1", b"k3"]).await;

        // when
        let iter = SstIterator::for_key_with_stats_initialized(
            &sst_handle,
            b"k2",
            table_store,
            SstIteratorOptions::default(),
            Some(db_stats.clone()),
        )
        .await
        .expect("iterator construction should succeed");

        // then
        assert!(iter.is_none(), "negative bloom result should skip iterator");
        assert_eq!(
            lookup_metric(&recorder, crate::db_stats::SST_FILTER_NEGATIVE_COUNT),
            Some(1)
        );
        assert_eq!(
            lookup_metric(&recorder, crate::db_stats::SST_FILTER_FALSE_POSITIVE_COUNT),
            Some(0)
        );
    }

    #[tokio::test]
    async fn should_record_bloom_filter_false_positive_for_single_key() {
        // given
        let recorder = Arc::new(DefaultMetricsRecorder::new());
        let helper = MetricsRecorderHelper::new(recorder.clone(), MetricLevel::default());
        let db_stats = DbStats::new(&helper);
        let table_store = bloom_filter_enabled_table_store(2);
        // these keys share the same bucket in the bloom filter (hard coded)
        // after testing with the SIP13 algorithm. The collision key must be
        // within the SST's key range [k1, k3] for range pruning.
        let existing_keys = [b"k1".as_slice(), b"k3".as_slice()];
        let sst_handle = build_single_block_sst(&table_store, &existing_keys).await;

        let filter = table_store
            .read_filter(&sst_handle.sst, true)
            .await
            .expect("filter read should succeed")
            .expect("filter should exist");

        let collision_key = b"k12";
        let hash = filter::filter_hash(collision_key);
        assert!(
            filter.might_contain(hash),
            "bloom filter should report collision for hard-coded key"
        );

        // when
        let mut iter = SstIterator::for_key_with_stats_initialized(
            &sst_handle,
            collision_key,
            table_store.clone(),
            SstIteratorOptions::default(),
            Some(db_stats.clone()),
        )
        .await
        .expect("iterator construction should succeed")
        .expect("filter positive should yield iterator");

        let entry = iter.next().await.expect("iteration should succeed");

        // then
        assert!(entry.is_none(), "false positive must return no entry");
        assert_eq!(
            lookup_metric(&recorder, crate::db_stats::SST_FILTER_POSITIVE_COUNT),
            Some(1)
        );
        assert_eq!(
            lookup_metric(&recorder, crate::db_stats::SST_FILTER_FALSE_POSITIVE_COUNT),
            Some(1)
        );
        assert_eq!(
            lookup_metric(&recorder, crate::db_stats::SST_FILTER_NEGATIVE_COUNT),
            Some(0)
        );
    }

    #[tokio::test]
    async fn test_bloom_filter_iterator_honors_cache_blocks() {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            min_filter_keys: 1,
            ..SsTableFormat::default()
        };
        let writer = TableStore::new(
            ObjectStores::new(object_store.clone(), None),
            format.clone(),
            root_path.clone(),
            None,
        );
        let mut builder = writer.table_builder();
        builder
            .add_value(b"key1", b"value1", Some(1), None)
            .await
            .unwrap();
        builder
            .add_value(b"key2", b"value2", Some(2), None)
            .await
            .unwrap();
        let sst = writer
            .write_sst(
                &SsTableId::Compacted(ulid::Ulid::new()),
                builder.build().await.unwrap(),
                false,
            )
            .await
            .unwrap();
        let handle = SsTableView::identity(sst);

        let meta_cache = Arc::new(TestCache::new());
        let cache = Arc::new(
            SplitCache::new()
                .with_meta_cache(Some(meta_cache.clone()))
                .build(),
        );
        let reader = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            Some(cache),
        ));

        let no_cache_options = SstIteratorOptions {
            cache_blocks: false,
            ..Default::default()
        };
        let mut iter = SstIterator::for_key_with_stats_initialized(
            &handle,
            b"key1",
            reader.clone(),
            no_cache_options,
            None,
        )
        .await
        .expect("iterator construction should succeed")
        .expect("expected iterator for present key");
        let _ = iter.next().await.unwrap();

        assert!(meta_cache
            .get_filter(&(handle.sst.id, handle.sst.info.filter_offset).into())
            .await
            .unwrap()
            .is_none());

        let cache_options = SstIteratorOptions {
            cache_blocks: true,
            ..Default::default()
        };
        let mut iter = SstIterator::for_key_with_stats_initialized(
            &handle,
            b"key1",
            reader,
            cache_options,
            None,
        )
        .await
        .expect("iterator construction should succeed")
        .expect("expected iterator for present key");
        let _ = iter.next().await.unwrap();

        assert!(meta_cache
            .get_filter(&(handle.sst.id, handle.sst.info.filter_offset).into())
            .await
            .unwrap()
            .is_some());
    }

    fn bloom_filter_enabled_table_store(filter_bits_per_key: u32) -> Arc<TableStore> {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            min_filter_keys: 1,
            filter_bits_per_key,
            ..SsTableFormat::default()
        };
        Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            None,
        ))
    }

    async fn build_single_block_sst(table_store: &Arc<TableStore>, keys: &[&[u8]]) -> SsTableView {
        let mut builder = table_store.table_builder();
        for key in keys {
            let value = format!("v_{}", String::from_utf8_lossy(key));
            builder
                .add_value(key, value.as_bytes(), Some(0), None)
                .await
                .unwrap();
        }
        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        SsTableView::identity(table_store.write_sst(&id, encoded, false).await.unwrap())
    }

    #[tokio::test]
    async fn test_many_block_sst_iter() {
        test_many_block_sst_iter_with_order(IterationOrder::Ascending).await;
        test_many_block_sst_iter_with_order(IterationOrder::Descending).await;
    }

    async fn test_many_block_sst_iter_with_order(order: IterationOrder) {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            min_filter_keys: 3,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));
        let mut builder = table_store.table_builder();

        for i in 0..1000 {
            builder
                .add_value(
                    format!("key{}", i).as_bytes(),
                    format!("value{}", i).as_bytes(),
                    Some(i),
                    None,
                )
                .await
                .unwrap();
        }

        let encoded = builder.build().await.unwrap();
        table_store
            .write_sst(&SsTableId::Wal(0), encoded, false)
            .await
            .unwrap();
        let sst_handle = table_store.open_sst(&SsTableId::Wal(0)).await.unwrap();
        let index = table_store.read_index(&sst_handle, true).await.unwrap();
        assert_eq!(index.borrow().block_meta().len(), 8);

        let sst_iter_options = SstIteratorOptions {
            max_fetch_tasks: 3,
            blocks_to_fetch: 3,
            cache_blocks: true,
            order,
            ..SstIteratorOptions::default()
        };
        let mut iter = SstIterator::new_owned_initialized(
            ..,
            SsTableView::identity(sst_handle),
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        match order {
            IterationOrder::Ascending => {
                for i in 0..1000 {
                    let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
                    assert_eq!(kv.key, format!("key{}", i));
                    assert_eq!(kv.value, format!("value{}", i));
                }
            }
            IterationOrder::Descending => {
                for i in (0..1000).rev() {
                    let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
                    assert_eq!(kv.key, format!("key{}", i));
                    assert_eq!(kv.value, format!("value{}", i));
                }
            }
        }

        let next = iter.next().await.unwrap().map(KeyValue::from);
        assert!(next.is_none());
    }

    #[tokio::test]
    async fn test_iter_from_key() {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128,
            min_filter_keys: 1,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));
        let first_key = [b'a'; 16];
        let key_gen = OrderedBytesGenerator::new_with_byte_range(&first_key, b'a', b'z');
        let mut test_case_key_gen = key_gen.clone();
        let first_val = [1u8; 16];
        let val_gen = OrderedBytesGenerator::new_with_byte_range(&first_val, 1u8, 26u8);
        let mut test_case_val_gen = val_gen.clone();
        let (sst, nkeys) = build_sst_with_n_blocks(3, table_store.clone(), key_gen, val_gen).await;

        // iterate over all keys and make sure we iterate from that key
        for i in 0..nkeys {
            let mut expected_key_gen = test_case_key_gen.clone();
            let mut expected_val_gen = test_case_val_gen.clone();
            let from_key = test_case_key_gen.next();
            let _ = test_case_val_gen.next();
            let mut iter = SstIterator::new_borrowed_initialized(
                BytesRange::from_slice(from_key.as_ref()..),
                &sst,
                table_store.clone(),
                SstIteratorOptions::default(),
            )
            .await
            .unwrap()
            .expect("Expected Some(iter) but got None");
            for _ in 0..nkeys - i {
                let e = iter.next().await.unwrap().unwrap().into();
                assert_kv(
                    &e,
                    expected_key_gen.next().as_ref(),
                    expected_val_gen.next().as_ref(),
                );
            }
            assert!(iter.next().await.unwrap().is_none());
        }
    }

    #[tokio::test]
    async fn test_iter_from_key_smaller_than_first() {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128,
            min_filter_keys: 1,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));
        let first_key = [b'b'; 16];
        let key_gen = OrderedBytesGenerator::new_with_byte_range(&first_key, b'a', b'y');
        let mut expected_key_gen = key_gen.clone();
        let first_val = [2u8; 16];
        let val_gen = OrderedBytesGenerator::new_with_byte_range(&first_val, 1u8, 26u8);
        let mut expected_val_gen = val_gen.clone();
        let (sst, nkeys) = build_sst_with_n_blocks(2, table_store.clone(), key_gen, val_gen).await;

        let mut iter = SstIterator::new_borrowed_initialized(
            BytesRange::from_slice([b'a'; 16].as_ref()..),
            &sst,
            table_store.clone(),
            SstIteratorOptions::default(),
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        for _ in 0..nkeys {
            let e = iter.next().await.unwrap().unwrap().into();
            assert_kv(
                &e,
                expected_key_gen.next().as_ref(),
                expected_val_gen.next().as_ref(),
            );
        }
        assert!(iter.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_iter_from_key_larger_than_last() {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128,
            min_filter_keys: 1,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));
        let first_key = [b'b'; 16];
        let key_gen = OrderedBytesGenerator::new_with_byte_range(&first_key, b'a', b'y');
        let first_val = [2u8; 16];
        let val_gen = OrderedBytesGenerator::new_with_byte_range(&first_val, 1u8, 26u8);
        let (sst, _) = build_sst_with_n_blocks(2, table_store.clone(), key_gen, val_gen).await;

        let iter = SstIterator::new_borrowed_initialized(
            BytesRange::from_slice([b'z'; 16].as_ref()..),
            &sst,
            table_store.clone(),
            SstIteratorOptions::default(),
        )
        .await
        .unwrap();

        // The SST's key range doesn't overlap with the query range starting at 'z',
        // so the iterator should be pruned (None).
        assert!(iter.is_none());
    }

    #[tokio::test]
    async fn test_descending_seek_beyond_last_key() {
        test_descending_seek_beyond_last_key_with_format(BlockFormat::V1).await;
        test_descending_seek_beyond_last_key_with_format(BlockFormat::V2).await;
        test_descending_seek_beyond_last_key_with_format(BlockFormat::Latest).await;
    }

    async fn test_descending_seek_beyond_last_key_with_format(block_format: BlockFormat) {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128,
            min_filter_keys: 3,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));

        // Build SST with specified format (keys 0-99)
        let builder = table_store.table_builder();
        let mut builder = match block_format {
            BlockFormat::V1 => builder,
            BlockFormat::V2 => builder.with_block_format(BlockFormat::V2),
            BlockFormat::Latest => builder.with_block_format(BlockFormat::Latest),
        };

        for i in 0..100 {
            builder
                .add_value(
                    format!("key{:03}", i).as_bytes(),
                    format!("value{:03}", i).as_bytes(),
                    Some(i),
                    None,
                )
                .await
                .unwrap();
        }

        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        let sst_handle =
            SsTableView::identity(table_store.write_sst(&id, encoded, false).await.unwrap());

        // Initialize iterator in descending order with full range
        let mut iter = SstIterator::new_borrowed_initialized(
            ..,
            &sst_handle,
            table_store.clone(),
            SstIteratorOptions {
                order: IterationOrder::Descending,
                ..SstIteratorOptions::default()
            },
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // Seek to key999 (beyond the last key which is key099)
        iter.seek(b"key999").await.unwrap();

        // Should iterate backwards from key099
        let kv1 = iter
            .next()
            .await
            .unwrap()
            .map(KeyValue::from)
            .expect("Expected first key but got None");
        let kv2 = iter
            .next()
            .await
            .unwrap()
            .map(KeyValue::from)
            .expect("Expected second key but got None");

        assert_eq!(kv1.key.as_ref(), b"key099");
        assert_eq!(kv2.key.as_ref(), b"key098");
    }

    #[tokio::test]
    async fn test_iter_seek_through_sst() {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128,
            min_filter_keys: 1,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));
        let first_key = [b'b'; 16];
        let key_gen = OrderedBytesGenerator::new_with_byte_range(&first_key, b'a', b'y');
        let first_val = [2u8; 16];
        let val_gen = OrderedBytesGenerator::new_with_byte_range(&first_val, 1u8, 26u8);
        let (sst, nkeys) =
            build_sst_with_n_blocks(256, table_store.clone(), key_gen, val_gen).await;

        let mut iter_large_fetch = SstIterator::new_borrowed_initialized(
            ..,
            &sst,
            table_store.clone(),
            SstIteratorOptions {
                max_fetch_tasks: 32,
                blocks_to_fetch: 256,
                cache_blocks: true,
                eager_spawn: false,
                order: IterationOrder::Ascending,
            },
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        let mut iter_small_fetch = SstIterator::new_borrowed_initialized(
            ..,
            &sst,
            table_store.clone(),
            SstIteratorOptions {
                max_fetch_tasks: 1,
                blocks_to_fetch: 1,
                cache_blocks: true,
                eager_spawn: false,
                order: IterationOrder::Ascending,
            },
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        let mut key_gen = OrderedBytesGenerator::new_with_byte_range(&first_key, b'a', b'y');
        let mut val_gen = OrderedBytesGenerator::new_with_byte_range(&first_val, 1u8, 26u8);
        let mut key_values = Vec::new();
        for _ in 0..nkeys {
            key_values.push((key_gen.next(), val_gen.next()));
        }

        for i in (0..nkeys).step_by(100) {
            iter_large_fetch.seek(&key_values[i].0).await.unwrap();
            let kv_large_fetch: KeyValue = iter_large_fetch.next().await.unwrap().unwrap().into();

            iter_small_fetch.seek(&key_values[i].0).await.unwrap();
            let kv_small_fetch: KeyValue = iter_small_fetch.next().await.unwrap().unwrap().into();

            assert_eq!(kv_large_fetch.key, key_values[i].0);
            assert_eq!(kv_large_fetch.value, key_values[i].1);
            assert_eq!(kv_small_fetch.key, key_values[i].0);
            assert_eq!(kv_small_fetch.value, key_values[i].1);
        }
    }

    async fn build_sst_with_n_blocks(
        n: usize,
        ts: Arc<TableStore>,
        mut key_gen: OrderedBytesGenerator,
        mut val_gen: OrderedBytesGenerator,
    ) -> (SsTableView, usize) {
        let mut writer = ts.table_writer(SsTableId::Wal(0));
        let mut nkeys = 0usize;
        while writer.blocks_written() < n {
            let entry = RowEntry::new_value(key_gen.next().as_ref(), val_gen.next().as_ref(), 0);
            writer.add(entry).await.unwrap();
            nkeys += 1;
        }
        let sst = writer.close().await.unwrap();
        (SsTableView::identity(sst), nkeys)
    }

    #[tokio::test]
    #[cfg(feature = "moka")]
    async fn test_sst_iter_cache_blocks() {
        use crate::db_cache::moka::MokaCache;
        use crate::db_cache::DbCache;
        use crate::db_cache::SplitCache;

        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            min_filter_keys: 3,
            ..SsTableFormat::default()
        };
        let block_cache = Arc::new(MokaCache::new());
        let meta_cache = Arc::new(MokaCache::new());
        let split_cache = Arc::new(
            SplitCache::new()
                .with_block_cache(Some(block_cache.clone()))
                .with_meta_cache(Some(meta_cache))
                .build(),
        );
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            Some(split_cache.clone()),
        ));

        let mut builder = table_store.table_builder();
        builder
            .add_value(b"key1", b"value1", Some(1), None)
            .await
            .unwrap();
        builder
            .add_value(b"key2", b"value2", Some(2), None)
            .await
            .unwrap();
        builder
            .add_value(b"key3", b"value3", Some(3), None)
            .await
            .unwrap();
        builder
            .add_value(b"key4", b"value4", Some(4), None)
            .await
            .unwrap();
        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        table_store.write_sst(&id, encoded, false).await.unwrap();
        let sst_handle = table_store.open_sst(&id).await.unwrap();

        let sst_iter_options = SstIteratorOptions {
            cache_blocks: true,
            ..SstIteratorOptions::default()
        };
        let mut iter = SstIterator::new_owned_initialized(
            ..,
            SsTableView::identity(sst_handle),
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        for i in 1..=4 {
            let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
            assert_eq!(kv.key, format!("key{}", i).as_bytes());
            assert_eq!(kv.value, format!("value{}", i).as_bytes());
        }

        let kv = iter.next().await.unwrap().map(KeyValue::from);
        assert!(kv.is_none());

        // verify that block was cached
        assert!(block_cache
            .get_block(&(id, 0).into())
            .await
            .unwrap_or(None)
            .is_some());

        // remove block from cache and verify that it is not cached when iterating with cache_blocks=false
        block_cache.remove(&(id, 0).into()).await;
        let sst_handle = table_store.open_sst(&id).await.unwrap();
        let sst_iter_options = SstIteratorOptions {
            cache_blocks: false,
            ..SstIteratorOptions::default()
        };
        let mut iter = SstIterator::new_owned_initialized(
            ..,
            SsTableView::identity(sst_handle),
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        for i in 1..=4 {
            let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
            assert_eq!(kv.key, format!("key{}", i).as_bytes());
            assert_eq!(kv.value, format!("value{}", i).as_bytes());
        }

        let kv = iter.next().await.unwrap().map(KeyValue::from);
        assert!(kv.is_none());

        // verify that block is not cached
        assert!(block_cache
            .get_block(&(id, 0).into())
            .await
            .unwrap()
            .is_none());
    }

    async fn build_v2_sst(
        table_store: &Arc<TableStore>,
        keys_and_values: &[(&[u8], &[u8])],
    ) -> SsTableView {
        let mut builder = table_store
            .table_builder()
            .with_block_format(BlockFormat::V2);
        for (key, value) in keys_and_values {
            builder.add_value(key, value, Some(0), None).await.unwrap();
        }
        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        SsTableView::identity(table_store.write_sst(&id, encoded, false).await.unwrap())
    }

    #[tokio::test]
    async fn should_iterate_v2_sst_scan() {
        // given: a V2 SST with multiple keys
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            min_filter_keys: 10,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            None,
        ));

        let keys_and_values = vec![
            (b"key1".as_slice(), b"value1".as_slice()),
            (b"key2".as_slice(), b"value2".as_slice()),
            (b"key3".as_slice(), b"value3".as_slice()),
            (b"key4".as_slice(), b"value4".as_slice()),
        ];
        let sst_handle = build_v2_sst(&table_store, &keys_and_values).await;

        // when: iterating over the SST
        let sst_iter_options = SstIteratorOptions {
            cache_blocks: true,
            ..SstIteratorOptions::default()
        };
        let mut iter = SstIterator::new_owned_initialized(
            ..,
            sst_handle,
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // then: all keys should be returned in order
        for (expected_key, expected_value) in &keys_and_values {
            let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
            assert_eq!(kv.key, *expected_key);
            assert_eq!(kv.value, *expected_value);
        }
        assert!(iter.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn should_iterate_v2_sst_for_key() {
        // given: a V2 SST with multiple keys
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            min_filter_keys: 10,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            None,
        ));

        let keys_and_values = vec![
            (b"key1".as_slice(), b"value1".as_slice()),
            (b"key2".as_slice(), b"value2".as_slice()),
            (b"key3".as_slice(), b"value3".as_slice()),
            (b"key4".as_slice(), b"value4".as_slice()),
        ];
        let sst_handle = build_v2_sst(&table_store, &keys_and_values).await;

        // when: searching for key2
        let mut iter = SstIterator::for_key_with_stats_initialized(
            &sst_handle,
            b"key2",
            table_store.clone(),
            SstIteratorOptions::default(),
            None,
        )
        .await
        .expect("iterator construction should succeed")
        .expect("expected iterator for present key");

        // then: key2 should be found
        let entry = iter
            .next()
            .await
            .expect("iteration should succeed")
            .expect("expected entry for present key");
        assert_eq!(entry.key.as_ref(), b"key2");
        match entry.value {
            ValueDeletable::Value(value) => assert_eq!(value.as_ref(), b"value2"),
            other => panic!("expected value, found {other:?}"),
        }
    }

    #[tokio::test]
    async fn should_iterate_v2_sst_with_many_keys() {
        // given: a V2 SST with many keys to test prefix compression
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 256,
            min_filter_keys: 1000,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            None,
        ));

        // Create keys with shared prefixes to exercise prefix compression
        let mut builder = table_store
            .table_builder()
            .with_block_format(BlockFormat::V2);

        let num_keys = 100;
        for i in 0..num_keys {
            let key = format!("prefix_{:04}", i);
            let value = format!("value_{:04}", i);
            builder
                .add_value(key.as_bytes(), value.as_bytes(), Some(i), None)
                .await
                .unwrap();
        }

        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        let sst_handle =
            SsTableView::identity(table_store.write_sst(&id, encoded, false).await.unwrap());

        // when: iterating over all keys
        let sst_iter_options = SstIteratorOptions {
            cache_blocks: true,
            ..SstIteratorOptions::default()
        };
        let mut iter = SstIterator::new_owned_initialized(
            ..,
            sst_handle,
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // then: all keys should be returned in order
        for i in 0..num_keys {
            let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
            let expected_key = format!("prefix_{:04}", i);
            let expected_value = format!("value_{:04}", i);
            assert_eq!(kv.key, expected_key.as_bytes());
            assert_eq!(kv.value, expected_value.as_bytes());
        }
        assert!(iter.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn should_seek_v2_sst_across_multiple_blocks() {
        // given: a V2 SST with small block_size to force multiple blocks
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128, // Small block size to force multiple blocks
            min_filter_keys: 1000,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            None,
        ));

        // Create keys that will span multiple blocks
        let mut builder = table_store
            .table_builder()
            .with_block_format(BlockFormat::V2);

        let num_keys = 50;
        for i in 0..num_keys {
            let key = format!("key_{:04}", i);
            let value = format!("value_{:04}", i);
            builder
                .add_value(key.as_bytes(), value.as_bytes(), Some(i), None)
                .await
                .unwrap();
        }

        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        let sst_handle = table_store.write_sst(&id, encoded, false).await.unwrap();

        // Verify we have multiple blocks
        let index = table_store.read_index(&sst_handle, true).await.unwrap();
        assert!(
            index.borrow().block_meta().len() > 1,
            "Expected multiple blocks but got {}",
            index.borrow().block_meta().len()
        );

        // when: seeking to a key in a later block (key_0030)
        let sst_view = SsTableView::identity(sst_handle);
        let seek_key = b"key_0030";
        let mut iter = SstIterator::new_borrowed_initialized(
            BytesRange::from_slice(seek_key.as_ref()..),
            &sst_view,
            table_store.clone(),
            SstIteratorOptions::default(),
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // then: should iterate from key_0030 onwards
        for i in 30..num_keys {
            let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
            let expected_key = format!("key_{:04}", i);
            let expected_value = format!("value_{:04}", i);
            assert_eq!(kv.key, expected_key.as_bytes());
            assert_eq!(kv.value, expected_value.as_bytes());
        }
        assert!(iter.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn should_return_none_for_missing_key_in_v2_sst() {
        // given: a V2 SST with multiple blocks
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128,
            min_filter_keys: 1000,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            None,
        ));

        let mut builder = table_store
            .table_builder()
            .with_block_format(BlockFormat::V2);

        // Add keys with gaps (only even numbers)
        for i in (0..50).step_by(2) {
            let key = format!("key_{:04}", i);
            let value = format!("value_{:04}", i);
            builder
                .add_value(key.as_bytes(), value.as_bytes(), Some(i), None)
                .await
                .unwrap();
        }

        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        let sst_handle =
            SsTableView::identity(table_store.write_sst(&id, encoded, false).await.unwrap());

        // when: searching for a non-existent key (odd number)
        let mut iter = SstIterator::for_key_with_stats_initialized(
            &sst_handle,
            b"key_0025", // This key doesn't exist
            table_store.clone(),
            SstIteratorOptions::default(),
            None,
        )
        .await
        .expect("iterator construction should succeed")
        .expect("expected iterator");

        // then: should return None since key doesn't exist
        let entry = iter.next().await.expect("iteration should succeed");
        assert!(entry.is_none(), "expected None for missing key");
    }

    #[tokio::test]
    async fn should_seek_past_last_key_in_v2_sst() {
        // given: a V2 SST
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128,
            min_filter_keys: 1000,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path,
            None,
        ));

        let mut builder = table_store
            .table_builder()
            .with_block_format(BlockFormat::V2);

        for i in 0..20 {
            let key = format!("key_{:04}", i);
            let value = format!("value_{:04}", i);
            builder
                .add_value(key.as_bytes(), value.as_bytes(), Some(i), None)
                .await
                .unwrap();
        }

        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        let sst_handle =
            SsTableView::identity(table_store.write_sst(&id, encoded, false).await.unwrap());

        // when: seeking past the last key
        let iter = SstIterator::new_borrowed_initialized(
            BytesRange::from_slice(b"zzz".as_ref()..),
            &sst_handle,
            table_store.clone(),
            SstIteratorOptions::default(),
        )
        .await
        .unwrap();

        // then: the SST should be pruned entirely since "zzz" is beyond the last key
        assert!(iter.is_none());
    }

    /// Test: iteration with both start and end bounds where the keys are in the middle of blocks
    /// and neither the first nor last block of the SST is included in the range.
    #[tokio::test]
    async fn test_range_iteration_middle_blocks_ascending() {
        test_range_iteration_middle_blocks_with_order(IterationOrder::Ascending).await;
    }

    #[tokio::test]
    async fn test_range_iteration_middle_blocks_descending() {
        test_range_iteration_middle_blocks_with_order(IterationOrder::Descending).await;
    }

    async fn test_range_iteration_middle_blocks_with_order(order: IterationOrder) {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128, // Small block size to ensure multiple blocks
            min_filter_keys: 100,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));

        // Build an SST with enough keys to span multiple blocks
        // Using key pattern: key000, key001, ..., key099
        let mut builder = table_store.table_builder();
        for i in 0..100 {
            builder
                .add_value(
                    format!("key{:03}", i).as_bytes(),
                    format!("value{:03}", i).as_bytes(),
                    Some(i),
                    None,
                )
                .await
                .unwrap();
        }
        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        table_store.write_sst(&id, encoded, false).await.unwrap();
        let sst_handle = table_store.open_sst(&id).await.unwrap();

        let index = table_store.read_index(&sst_handle, true).await.unwrap();
        let num_blocks = index.borrow().block_meta().len();
        assert!(
            num_blocks >= 4,
            "Test requires at least 4 blocks, got {}",
            num_blocks
        );

        // Use start and end keys that:
        // 1. Are not at the first key of any block (using middle range key020..key079)
        // 2. Exclude the first block entirely (start > first block's last key)
        // 3. Exclude the last block entirely (end < last block's first key)
        // 4. Are guaranteed to exist in the SST (key020 through key079)
        let start_key = b"key020";
        let end_key = b"key079";

        let sst_iter_options = SstIteratorOptions {
            max_fetch_tasks: 3,
            blocks_to_fetch: 3,
            cache_blocks: true,
            eager_spawn: false,
            order,
        };
        let mut iter = SstIterator::new_owned_initialized(
            BytesRange::from_slice(start_key.as_ref()..=end_key.as_ref()),
            SsTableView::identity(sst_handle),
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // Expected keys based on order
        let start_idx = 20;
        let end_idx = 79; // inclusive
        let expected_count = end_idx - start_idx + 1;

        let mut count = 0;
        match order {
            IterationOrder::Ascending => {
                for i in start_idx..=end_idx {
                    let kv = iter
                        .next()
                        .await
                        .unwrap()
                        .map(KeyValue::from)
                        .unwrap_or_else(|| {
                            panic!(
                                "Expected key{:03} in ascending order, but got None. Count so far: {}",
                                i, count
                            )
                        });
                    assert_eq!(
                        kv.key,
                        format!("key{:03}", i).as_bytes(),
                        "Key mismatch in ascending order at position {}",
                        count
                    );
                    assert_eq!(kv.value, format!("value{:03}", i).as_bytes());
                    count += 1;
                }
            }
            IterationOrder::Descending => {
                for i in (start_idx..=end_idx).rev() {
                    let kv = iter
                        .next()
                        .await
                        .unwrap()
                        .map(KeyValue::from)
                        .unwrap_or_else(|| {
                            panic!(
                                "Expected key{:03} in descending order, but got None. Count so far: {}",
                                i, count
                            )
                        });
                    assert_eq!(
                        kv.key,
                        format!("key{:03}", i).as_bytes(),
                        "Key mismatch in descending order at position {}, expected key{:03}",
                        count,
                        i
                    );
                    assert_eq!(kv.value, format!("value{:03}", i).as_bytes());
                    count += 1;
                }
            }
        }

        assert_eq!(
            count, expected_count,
            "Should iterate exactly {} keys",
            expected_count
        );
        assert!(
            iter.next().await.unwrap().is_none(),
            "Should have no more keys"
        );
    }

    #[tokio::test]
    async fn test_full_descending_iteration() {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat {
            block_size: 128, // Small block size to ensure multiple blocks
            min_filter_keys: 100,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));

        // Build an SST with enough data for multiple blocks
        let mut builder = table_store.table_builder();
        for i in 0..30 {
            builder
                .add_value(
                    format!("key{:03}", i).as_bytes(),
                    format!("value{:03}", i).as_bytes(),
                    Some(i),
                    None,
                )
                .await
                .unwrap();
        }
        let encoded = builder.build().await.unwrap();
        let id = SsTableId::Compacted(ulid::Ulid::new());
        table_store.write_sst(&id, encoded, false).await.unwrap();
        let sst_handle = table_store.open_sst(&id).await.unwrap();

        let index = table_store.read_index(&sst_handle, true).await.unwrap();
        let num_blocks = index.borrow().block_meta().len();
        assert!(
            num_blocks >= 2,
            "Test requires at least 2 blocks, got {}",
            num_blocks
        );

        // Full iteration in descending order
        let sst_iter_options = SstIteratorOptions {
            cache_blocks: true,
            order: IterationOrder::Descending,
            ..SstIteratorOptions::default()
        };
        let mut iter = SstIterator::new_owned_initialized(
            ..,
            SsTableView::identity(sst_handle),
            table_store.clone(),
            sst_iter_options,
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // Should iterate backwards from key029 to key000
        for i in (0..30).rev() {
            let kv: KeyValue = iter.next().await.unwrap().unwrap().into();
            assert_eq!(kv.key, format!("key{:03}", i).as_bytes());
            assert_eq!(kv.value, format!("value{:03}", i).as_bytes());
        }

        assert!(iter.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_duplicate_keys_iteration() {
        test_duplicate_keys_iteration_with_order(IterationOrder::Ascending).await;
        test_duplicate_keys_iteration_with_order(IterationOrder::Descending).await;
    }

    async fn test_duplicate_keys_iteration_with_order(order: IterationOrder) {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let format = SsTableFormat::default();
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));

        let mut writer = table_store.table_writer(SsTableId::Wal(0));
        writer
            .add(RowEntry::new_value(b"key_a", b"value_100", 100))
            .await
            .unwrap();
        writer
            .add(RowEntry::new_value(b"key_a", b"value_95", 95))
            .await
            .unwrap();
        writer
            .add(RowEntry::new_value(b"key_a", b"value_90", 90))
            .await
            .unwrap();
        writer
            .add(RowEntry::new_value(b"key_b", b"value_80", 80))
            .await
            .unwrap();
        writer
            .add(RowEntry::new_value(b"key_b", b"value_70", 70))
            .await
            .unwrap();
        writer
            .add(RowEntry::new_value(b"key_c", b"value_50", 50))
            .await
            .unwrap();
        let handle = writer.close().await.unwrap();

        let mut iter = SstIterator::new_owned_initialized(
            ..,
            SsTableView::identity(handle),
            table_store.clone(),
            SstIteratorOptions {
                order,
                ..SstIteratorOptions::default()
            },
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        let expected = match order {
            IterationOrder::Ascending => vec![
                (b"key_a".as_slice(), b"value_100".as_slice(), 100),
                (b"key_a".as_slice(), b"value_95".as_slice(), 95),
                (b"key_a".as_slice(), b"value_90".as_slice(), 90),
                (b"key_b".as_slice(), b"value_80".as_slice(), 80),
                (b"key_b".as_slice(), b"value_70".as_slice(), 70),
                (b"key_c".as_slice(), b"value_50".as_slice(), 50),
            ],
            IterationOrder::Descending => vec![
                (b"key_c".as_slice(), b"value_50".as_slice(), 50),
                (b"key_b".as_slice(), b"value_80".as_slice(), 80),
                (b"key_b".as_slice(), b"value_70".as_slice(), 70),
                (b"key_a".as_slice(), b"value_100".as_slice(), 100),
                (b"key_a".as_slice(), b"value_95".as_slice(), 95),
                (b"key_a".as_slice(), b"value_90".as_slice(), 90),
            ],
        };

        for (expected_key, expected_value, expected_seq) in expected {
            let entry = iter
                .next()
                .await
                .expect("iteration should succeed")
                .expect("expected entry");
            assert_eq!(entry.key.as_ref(), expected_key, "key mismatch");
            assert_eq!(entry.seq, expected_seq, "sequence number mismatch");
            match entry.value {
                ValueDeletable::Value(value) => {
                    assert_eq!(value.as_ref(), expected_value, "value mismatch")
                }
                other => panic!("expected value, found {other:?}"),
            }
        }

        let entry = iter.next().await.expect("iteration should succeed");
        assert!(entry.is_none(), "expected end of iteration");
    }

    #[tokio::test]
    async fn test_seek_forward_after_scan_already_fetched_block_consumed() {
        let root_path = Path::from("");
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        // Small block_size so we get ~2 keys per block.
        let format = SsTableFormat {
            block_size: 64,
            min_filter_keys: 1,
            ..SsTableFormat::default()
        };
        let table_store = Arc::new(TableStore::new(
            ObjectStores::new(object_store, None),
            format,
            root_path.clone(),
            None,
        ));

        // Keys spaced by 10: key_000, key_010, key_020, ..., key_190.
        // Gaps like key_035 don't exist.
        let mut writer = table_store.table_writer(SsTableId::Wal(0));
        for i in 0..20 {
            let key = format!("key_{:03}", i * 10);
            let val = format!("val_{:03}", i * 10);
            writer
                .add(RowEntry::new_value(key.as_bytes(), val.as_bytes(), 0))
                .await
                .unwrap();
        }
        let sst_handle = writer.close().await.unwrap();
        let sst = SsTableView::identity(sst_handle);

        // Minimal prefetch: 1 block at a time, 1 task max.
        let mut iter = SstIterator::new_borrowed_initialized(
            ..,
            &sst,
            table_store.clone(),
            SstIteratorOptions {
                max_fetch_tasks: 1,
                blocks_to_fetch: 1,
                cache_blocks: true,
                eager_spawn: false,
                order: IterationOrder::Ascending,
            },
        )
        .await
        .unwrap()
        .expect("Expected Some(iter) but got None");

        // Scan 3 entries: key_000, key_010, key_020.
        // After this, current block has key_020, key_030. fetch_tasks is empty.
        // next_block_idx_to_fetch = 2.
        for _ in 0..3 {
            iter.next().await.unwrap().expect("should have entries");
        }

        // Seek to key_035 (doesn't exist). The index maps it to block 1
        // (which contains key_020, key_030). block_idx=1 < next_block_idx=2,
        // so already_fetched=true. But fetch_tasks is empty (consumed during
        // scan). The already_fetched loop immediately calls next_iter(false)
        // on empty tasks, hitting the assertion.
        iter.seek(b"key_035").await.unwrap();

        // Should find key_040 (first key >= key_035).
        let entry = iter.next().await.unwrap().expect("should find key_040");
        let kv: KeyValue = entry.into();
        assert_eq!(kv.key.as_ref(), b"key_040");
    }
}