nitrite_fjall_adapter 1.0.2

Fjall storage adapter for Nitrite database - persistent LSM-tree 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
use crate::config::FjallConfig;
use crate::store::FjallStore;
use crate::wrapper::FjallValue;
use fjall::SingleWriterTxKeyspace as TxPartitionHandle;
use nitrite::common::{async_task, AttributeAware, Attributes, Key, Value, META_MAP_NAME};
use nitrite::errors::{ErrorKind, NitriteError, NitriteResult};
use nitrite::store::{
    EntryIterator, KeyIterator, NitriteMap, NitriteMapProvider, NitriteStore,
    SingleMapEntryProvider, SingleMapKeyProvider, SingleMapValueProvider, ValueIterator,
};
use parking_lot::RwLock;
use std::collections::Bound::{Excluded, Included, Unbounded};
use std::iter::Rev;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

#[derive(Clone)]
/// Fjall-based key-value map implementation.
///
/// A persistent, thread-safe key-value store backed by Fjall LSM engine. Uses PIMPL pattern
/// with `Arc<FjallMapInner>` for efficient cloning and shared ownership. Implements the
/// NitriteMapProvider trait for integration with Nitrite's storage abstraction.
///
/// Purpose: Provides durable, transactional key-value operations with automatic persistence,
/// garbage collection, and attribute metadata storage.
///
/// Characteristics:
/// - Thread-safe (Arc-based, can be cloned across threads)
/// - Persistent (backed by Fjall LSM storage engine)
/// - Garbage collection (automatic cleanup with `collect_garbage()`)
/// - Attributes (supports metadata via AttributeAware trait)
/// - Iterator support (entries, keys, values with reverse iteration)
/// - Cloneable (cheap Arc clones)
/// - Trait delegation (no Deref, explicit method forwarding)
///
/// Usage: Created via FjallStore, used for collection data storage and indexes.
/// Accessed through NitriteMapProvider trait for iterator and CRUD operations.
pub struct FjallMap {
    inner: Arc<FjallMapInner>,
}

impl FjallMap {
    /// Creates a new FjallMap with the given partition.
    ///
    /// Arguments:
    /// - `name`: Name of this map (identifies the partition)
    /// - `partition`: Fjall partition backing this map
    /// - `store`: Parent FjallStore for lifecycle management
    /// - `fjall_config`: Configuration for this map's operations
    ///
    /// Returns: A new `FjallMap` instance ready for use
    #[inline]
    pub fn new(
        name: String,
        partition: TxPartitionHandle,
        store: FjallStore,
        fjall_config: FjallConfig,
    ) -> FjallMap {
        FjallMap {
            inner: Arc::new(FjallMapInner::new(name, partition, store, fjall_config)),
        }
    }
}

impl AttributeAware for FjallMap {
    /// Returns the attributes associated with this map.
    ///
    /// Returns: `Ok(Some(Attributes))` if attributes exist, `Ok(None)` otherwise
    fn attributes(&self) -> NitriteResult<Option<Attributes>> {
        self.inner.get_attributes()
    }

    /// Sets the attributes for this map.
    ///
    /// Arguments:
    /// - `attributes`: Metadata to store for this map
    ///
    /// Returns: `Ok(())` on success, error otherwise
    fn set_attributes(&self, attributes: Attributes) -> NitriteResult<()> {
        self.inner.set_attributes(attributes)
    }
}

impl NitriteMapProvider for FjallMap {
    /// Checks if a key exists in this map.
    ///
    /// Arguments:
    /// - `key`: Key to check for existence
    ///
    /// Returns: `Ok(true)` if key exists, `Ok(false)` otherwise
    #[inline]
    fn contains_key(&self, key: &Key) -> NitriteResult<bool> {
        self.inner.contains_key(key)
    }

    /// Retrieves a value by key.
    ///
    /// Arguments:
    /// - `key`: Key to retrieve
    ///
    /// Returns: `Ok(Some(Value))` if key exists, `Ok(None)` otherwise
    #[inline]
    fn get(&self, key: &Key) -> NitriteResult<Option<Value>> {
        self.inner.get(key)
    }

    /// Removes all entries from this map.
    ///
    /// Also triggers asynchronous cleanup (commit and garbage collection) in the background.
    ///
    /// Returns: `Ok(())` on success, error otherwise
    fn clear(&self) -> NitriteResult<()> {
        self.inner.clear()?;
        let clone = self.clone();
        async_task(move || {
            // Safe cleanup: handle all errors gracefully without panicking in async task
            match clone.get_store() {
                Ok(store) => {
                    match store.commit() {
                        Ok(_) => {
                            log::debug!("Successfully committed store after clear");
                        }
                        Err(e) => {
                            log::error!("Failed to commit store after clear: {}", e);
                            // Do not panic - log and continue
                        }
                    }
                }
                Err(e) => {
                    log::debug!("Failed to get store for cleanup after clear: {}", e);
                    // Do not panic - store may have been dropped or closed
                    return;
                }
            }

            // Attempt garbage collection but don't crash if it fails
            match clone.collect_garbage() {
                Ok(_) => {
                    log::debug!("Successfully collected garbage after clear");
                }
                Err(e) => {
                    log::warn!("Failed to collect garbage after clear: {}", e);
                    // Non-fatal - garbage collection is best-effort
                }
            }
        });
        Ok(())
    }

    /// Checks if this map is closed.
    ///
    /// Returns: `Ok(true)` if closed, `Ok(false)` otherwise
    fn is_closed(&self) -> NitriteResult<bool> {
        self.inner.is_closed()
    }

    /// Closes this map, preventing further operations.
    ///
    /// Returns: `Ok(())` on success, error otherwise
    fn close(&self) -> NitriteResult<()> {
        self.inner.close()
    }

    /// Returns an iterator over all values in this map.
    ///
    /// Returns: A `ValueIterator` for iteration
    fn values(&self) -> NitriteResult<ValueIterator> {
        let provider = SingleMapValueProvider::new(NitriteMap::new(self.clone()));
        Ok(ValueIterator::new(provider))
    }

    /// Returns an iterator over all keys in this map.
    ///
    /// Returns: A `KeyIterator` for iteration
    fn keys(&self) -> NitriteResult<KeyIterator> {
        let provider = SingleMapKeyProvider::new(NitriteMap::new(self.clone()));
        Ok(KeyIterator::new(provider))
    }

    /// Removes an entry by key, returning its previous value.
    ///
    /// Arguments:
    /// - `key`: Key to remove
    ///
    /// Returns: `Ok(Some(Value))` if key existed, `Ok(None)` otherwise
    fn remove(&self, key: &Key) -> NitriteResult<Option<Value>> {
        let result = self.inner.remove(key)?;
        Ok(result)
    }

    /// Inserts or updates a key-value pair.
    ///
    /// Arguments:
    /// - `key`: Key to insert/update
    /// - `value`: Value to store
    ///
    /// Returns: `Ok(())` on success, error otherwise
    fn put(&self, key: Key, value: Value) -> NitriteResult<()> {
        self.inner.put(key, value)?;
        Ok(())
    }

    /// Inserts or updates multiple key-value pairs atomically.
    ///
    /// Arguments:
    /// - `entries`: Vector of (key, value) pairs to insert
    ///
    /// Returns: `Ok(())` on success, error otherwise
    fn put_all(&self, entries: Vec<(Key, Value)>) -> NitriteResult<()> {
        self.inner.put_all(entries)
    }

    /// Returns the number of entries in this map.
    ///
    /// Returns: Number of key-value pairs
    fn size(&self) -> NitriteResult<u64> {
        self.inner.size()
    }

    /// Inserts a key-value pair if the key is not already present.
    ///
    /// Arguments:
    /// - `key`: Key to check/insert
    /// - `value`: Value to store if key is absent
    ///
    /// Returns: `Ok(Some(Value))` if key existed, `Ok(None)` if inserted
    fn put_if_absent(&self, key: Key, value: Value) -> NitriteResult<Option<Value>> {
        let result = self.inner.put_if_absent(key, value)?;
        Ok(result)
    }

    /// Returns the first key in this map.
    ///
    /// Returns: `Ok(Some(Key))` if map is non-empty, `Ok(None)` otherwise
    fn first_key(&self) -> NitriteResult<Option<Key>> {
        self.inner.first_key()
    }

    /// Returns the last key in this map.
    ///
    /// Returns: `Ok(Some(Key))` if map is non-empty, `Ok(None)` otherwise
    fn last_key(&self) -> NitriteResult<Option<Key>> {
        self.inner.last_key()
    }

    /// Returns the smallest key strictly greater than the given key.
    ///
    /// Arguments:
    /// - `key`: Reference key
    ///
    /// Returns: `Ok(Some(Key))` if such key exists, `Ok(None)` otherwise
    fn higher_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.inner.higher_key(key)
    }

    /// Returns the smallest key greater than or equal to the given key.
    ///
    /// Arguments:
    /// - `key`: Reference key
    ///
    /// Returns: `Ok(Some(Key))` if such key exists, `Ok(None)` otherwise
    fn ceiling_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.inner.ceiling_key(key)
    }

    /// Returns the largest key strictly less than the given key.
    ///
    /// Arguments:
    /// - `key`: Reference key
    ///
    /// Returns: `Ok(Some(Key))` if such key exists, `Ok(None)` otherwise
    fn lower_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.inner.lower_key(key)
    }

    /// Returns the largest key less than or equal to the given key.
    ///
    /// Arguments:
    /// - `key`: Reference key
    ///
    /// Returns: `Ok(Some(Key))` if such key exists, `Ok(None)` otherwise
    fn floor_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.inner.floor_key(key)
    }

    /// Checks if this map is empty.
    ///
    /// Returns: `Ok(true)` if no entries, `Ok(false)` otherwise
    fn is_empty(&self) -> NitriteResult<bool> {
        self.inner.is_empty()
    }

    /// Returns the parent store of this map.
    ///
    /// Returns: A `NitriteStore` instance
    fn get_store(&self) -> NitriteResult<NitriteStore> {
        self.inner.get_store()
    }

    /// Returns the name of this map.
    ///
    /// Returns: String name of the map
    fn get_name(&self) -> NitriteResult<String> {
        self.inner.get_name()
    }

    /// Returns an iterator over all entries in this map.
    ///
    /// Returns: An `EntryIterator` for iteration
    /// Steps the partition's key iterator, which reads keys without their values.
    ///
    /// The walk this replaces asks the LSM tree for the next key from scratch each time - a
    /// range seek per row - and it is paid again from zero on every page. Stepping one key
    /// iterator is a move within the block it is already positioned on.
    ///
    /// Declined while a transaction is in scope: the keys there have to include the scope's
    /// own uncommitted inserts and exclude its tombstones, which is what `visible_entry_raw`
    /// merges. A count over the committed partition alone would land on the wrong row.
    fn skip_keys_from_start(&self, count: u64) -> NitriteResult<Option<(u64, Option<Key>)>> {
        self.inner.skip_keys_from_start(count)
    }

    fn entries(&self) -> NitriteResult<EntryIterator> {
        let provider = SingleMapEntryProvider::new(NitriteMap::new(self.clone()));
        Ok(EntryIterator::new(provider))
    }

    /// Returns a reverse iterator over all entries in this map.
    ///
    /// Returns: A reverse `EntryIterator` for iteration
    fn reverse_entries(&self) -> NitriteResult<Rev<EntryIterator>> {
        let provider = SingleMapEntryProvider::new(NitriteMap::new(self.clone()));
        Ok(EntryIterator::new(provider).rev())
    }

    /// Marks this map as disposed, freeing resources.
    ///
    /// Returns: `Ok(())` on success, error otherwise
    fn dispose(&self) -> NitriteResult<()> {
        self.inner.dispose()
    }

    /// Checks if this map is dropped.
    ///
    /// Returns: `Ok(true)` if dropped, `Ok(false)` otherwise
    fn is_dropped(&self) -> NitriteResult<bool> {
        self.inner.is_dropped()
    }
}

impl FjallMap {
    /// Performs garbage collection on this map.
    ///
    /// Reclaims space by removing deleted/unused data through compaction.
    ///
    /// Returns: `Ok(())` on success, error otherwise
    pub fn collect_garbage(&self) -> NitriteResult<()> {
        self.inner.collect_garbage()
    }

    /// Initializes this map.
    ///
    /// Returns: `Ok(())` on success, error otherwise
    pub fn initialize(&self) -> NitriteResult<()> {
        self.inner.initialize()
    }

    /// Returns the attributes associated with this map.
    ///
    /// Returns: `Ok(Some(Attributes))` if attributes exist, `Ok(None)` otherwise
    #[allow(dead_code)]
    pub fn get_attributes(&self) -> NitriteResult<Option<Attributes>> {
        self.inner.get_attributes()
    }

    /// Sets the attributes for this map.
    ///
    /// Arguments:
    /// - `attributes`: Metadata to store for this map
    ///
    /// Returns: `Ok(())` on success, error otherwise
    #[allow(dead_code)]
    pub fn set_attributes(&self, attributes: Attributes) -> NitriteResult<()> {
        self.inner.set_attributes(attributes)
    }
}

/// Internal Fjall map implementation.
///
/// Encapsulates the actual Fjall partition and manages state (open/closed/dropped).
/// Provides atomic access to partition operations with lifecycle tracking.
///
/// Thread-safe: Uses AtomicBool for state flags with Relaxed ordering for performance.
struct FjallMapInner {
    name: String,
    overlay_key: Arc<str>,
    /// `Option` (not a bare handle) so `close`/`dispose` can *release* it. A fjall 3
    /// `SingleWriterTxKeyspace` carries a clone of the database it belongs to, and fjall 3 holds
    /// an exclusive lock file over the database directory — so a map handle that outlives
    /// `close()` (nitrite's core keeps `NitriteMap`s for every collection and index) would keep
    /// the database open and make a reopen of the same path fail with `Locked`.
    partition: RwLock<Option<TxPartitionHandle>>,
    closed: AtomicBool,
    dropped: AtomicBool,
    store: FjallStore,
    fjall_config: FjallConfig,
}

#[derive(Clone, Copy)]
enum SeekDirection {
    Forward,
    Reverse,
}

impl FjallMapInner {
    /// Creates a new FjallMapInner wrapping the given partition.
    ///
    /// Arguments:
    /// - `name`: Map identifier
    /// - `partition`: Fjall partition backend
    /// - `store`: Parent store reference
    /// - `fjall_config`: Configuration for operations
    ///
    /// Returns: A new `FjallMapInner` with closed=false, dropped=false
    fn new(
        name: String,
        partition: TxPartitionHandle,
        store: FjallStore,
        fjall_config: FjallConfig,
    ) -> FjallMapInner {
        let overlay_key = Arc::<str>::from(name.as_str());
        FjallMapInner {
            name,
            overlay_key,
            partition: RwLock::new(Some(partition)),
            store,
            closed: AtomicBool::new(false),
            dropped: AtomicBool::new(false),
            fjall_config,
        }
    }

    /// Initializes this map (currently a no-op).
    ///
    /// Returns: `Ok(())`
    pub fn initialize(&self) -> NitriteResult<()> {
        Ok(())
    }

    fn check_opened(&self) -> NitriteResult<()> {
        if self.closed.load(Ordering::Relaxed) {
            log::debug!("Map {} is closed", self.name);
            return Err(NitriteError::new(
                &format!("Map {} is closed", self.name),
                ErrorKind::StoreAlreadyClosed,
            ));
        }

        if self.dropped.load(Ordering::Relaxed) {
            log::debug!("Map {} is dropped", self.name);
            return Err(NitriteError::new(
                &format!("Map {} is dropped", self.name),
                ErrorKind::StoreNotInitialized,
            ));
        }

        Ok(())
    }

    /// Returns the map's partition handle, or an error if `close`/`dispose` already released it.
    ///
    /// The clone is cheap (fjall's handle is `Arc`-backed) and the read lock is held only long
    /// enough to take it.
    #[inline]
    fn partition_handle(&self) -> NitriteResult<TxPartitionHandle> {
        self.partition.read().clone().ok_or_else(|| {
            NitriteError::new(
                &format!("Map {} is closed", self.name),
                ErrorKind::StoreAlreadyClosed,
            )
        })
    }

    /// Builds a `BackendError` for a failed Fjall operation, logging it as well.
    fn backend_err(op: &str, err: impl std::fmt::Display) -> NitriteError {
        log::debug!("Failed to {} FjallMap: {}", op, err);
        NitriteError::new(
            &format!("Failed to {} FjallMap: {}", op, err),
            ErrorKind::BackendError,
        )
    }

    /// Deserializes a stored Fjall **key** back into a `Value`, using the order-preserving key
    /// codec (the counterpart of [`FjallValue::try_from_key`]).
    ///
    /// Corrupted or format-incompatible on-disk bytes are surfaced as a `NitriteError` rather
    /// than panicking, so a damaged or foreign database degrades to a recoverable read error
    /// instead of crashing the process.
    #[inline]
    fn decode_value(raw: FjallValue) -> NitriteResult<Value> {
        raw.try_into_key().map_err(NitriteError::from)
    }

    #[inline]
    fn decode_bytes(raw: &[u8]) -> NitriteResult<Value> {
        bincode::serde::decode_from_slice(raw, bincode::config::legacy())
            .map(|(value, _)| value)
            .map_err(|err| {
                NitriteError::from(crate::wrapper::FjallValueError::DeserializationError(
                    err.to_string(),
                ))
            })
    }

    fn insert_in_tx(&self, key: FjallValue, value: FjallValue) -> NitriteResult<()> {
        let raw_key = key.as_ref().to_vec();
        let raw_value = Box::<[u8]>::from(value.as_ref());
        let partition = self.partition_handle()?;
        crate::tx_scope::with_active(|tx| {
            let tx = tx.expect("write_in_tx requires an active transaction");
            tx.insert(&partition, key, value);
        });
        crate::tx_scope::record_insert(&self.overlay_key, raw_key, raw_value);
        Ok(())
    }

    fn remove_in_tx(&self, raw_key: Vec<u8>) -> NitriteResult<()> {
        let partition = self.partition_handle()?;
        crate::tx_scope::with_active(|tx| {
            let tx = tx.expect("write_in_tx requires an active transaction");
            tx.remove(&partition, raw_key.clone());
        });
        crate::tx_scope::record_remove(&self.overlay_key, raw_key);
        Ok(())
    }

    fn visible_contains_key(&self, op: &str, key: &FjallValue) -> NitriteResult<bool> {
        let partition = self.partition_handle()?;
        if !crate::tx_scope::in_scope() {
            return partition
                .contains_key(key.clone())
                .map_err(|err| Self::backend_err(op, err));
        }

        crate::tx_scope::with_partition_overlay(&self.overlay_key, |overlay| {
            if let Some(value) = overlay.and_then(|entries| entries.entries.get(key.as_ref())) {
                return Ok(value.is_some());
            }

            partition
                .contains_key(key.clone())
                .map_err(|err| Self::backend_err(op, err))
        })
    }

    fn visible_value(&self, op: &str, key: &FjallValue) -> NitriteResult<Option<Value>> {
        let partition = self.partition_handle()?;
        if !crate::tx_scope::in_scope() {
            return partition
                .get(key.clone())
                .map_err(|err| Self::backend_err(op, err))?
                .as_deref()
                .map(Self::decode_bytes)
                .transpose();
        }

        crate::tx_scope::with_partition_overlay(&self.overlay_key, |overlay| {
            if let Some(value) = overlay.and_then(|entries| entries.entries.get(key.as_ref())) {
                return value.as_deref().map(Self::decode_bytes).transpose();
            }

            partition
                .get(key.clone())
                .map_err(|err| Self::backend_err(op, err))?
                .as_deref()
                .map(Self::decode_bytes)
                .transpose()
        })
    }

    fn skip_keys_from_start(&self, count: u64) -> NitriteResult<Option<(u64, Option<Key>)>> {
        self.check_opened()?;
        if crate::tx_scope::in_scope() {
            return Ok(None);
        }

        // `Guard::key()` resolves only the key: on a KV-separated keyspace the blob behind the
        // value is never fetched, which is the whole point of skipping by key.
        let partition = self.partition_handle()?;
        let mut keys = partition.inner().iter();
        let mut skipped = 0u64;
        let mut landed: Option<Vec<u8>> = None;
        while skipped < count {
            match keys.next() {
                Some(guard) => {
                    let key = guard
                        .key()
                        .map_err(|err| Self::backend_err("skip keys in", err))?;
                    landed = Some(key.to_vec());
                    skipped += 1;
                }
                None => break,
            }
        }

        // Only the key it stopped on is decoded - the ones stepped over never become Keys.
        let landed = landed
            .map(|key| Self::decode_value(FjallValue::from(key)))
            .transpose()?;
        Ok(Some((skipped, landed)))
    }

    fn committed_entry_raw(
        &self,
        op: &str,
        bound: Option<&[u8]>,
        inclusive: bool,
        direction: SeekDirection,
    ) -> NitriteResult<Option<(Vec<u8>, Vec<u8>)>> {
        let partition = self.partition_handle()?;
        let guard = match (direction, bound) {
            (SeekDirection::Forward, None) => partition.first_key_value(),
            (SeekDirection::Reverse, None) => partition.last_key_value(),
            (SeekDirection::Forward, Some(bound)) => partition
                .inner()
                .range::<Vec<u8>, _>(((if inclusive {
                    Included(bound.to_vec())
                } else {
                    Excluded(bound.to_vec())
                }), Unbounded))
                .next(),
            (SeekDirection::Reverse, Some(bound)) => partition
                .inner()
                .range::<Vec<u8>, _>((Unbounded, if inclusive {
                    Included(bound.to_vec())
                } else {
                    Excluded(bound.to_vec())
                }))
                .next_back(),
        };

        // Fjall 3 hands back a `Guard` and defers the read; `into_inner` is where the I/O (and
        // the blob resolution on a KV-separated keyspace) actually happens.
        guard
            .map(|guard| {
                let (key, value) = guard
                    .into_inner()
                    .map_err(|err| Self::backend_err(op, err))?;
                Ok((key.to_vec(), value.to_vec()))
            })
            .transpose()
    }

    fn overlay_entry_raw<'a>(
        overlay: Option<&'a crate::tx_scope::PartitionOverlay>,
        bound: Option<&[u8]>,
        inclusive: bool,
        direction: SeekDirection,
    ) -> Option<(&'a Vec<u8>, &'a [u8])> {
        let overlay = overlay?;

        match (direction, bound) {
            (SeekDirection::Forward, None) => overlay
                .entries
                .iter()
                .find_map(|(key, value)| value.as_deref().map(|value| (key, value))),
            (SeekDirection::Reverse, None) => overlay
                .entries
                .iter()
                .rev()
                .find_map(|(key, value)| value.as_deref().map(|value| (key, value))),
            (SeekDirection::Forward, Some(bound)) => overlay
                .entries
                .range((if inclusive {
                    Included(bound.to_vec())
                } else {
                    Excluded(bound.to_vec())
                }, Unbounded))
                .find_map(|(key, value)| value.as_deref().map(|value| (key, value))),
            (SeekDirection::Reverse, Some(bound)) => overlay
                .entries
                .range((Unbounded, if inclusive {
                    Included(bound.to_vec())
                } else {
                    Excluded(bound.to_vec())
                }))
                .rev()
                .find_map(|(key, value)| value.as_deref().map(|value| (key, value))),
        }
    }

    fn choose_entry(
        direction: SeekDirection,
        overlay_candidate: Option<(&Vec<u8>, &[u8])>,
        committed_candidate: Option<(Vec<u8>, Vec<u8>)>,
    ) -> Option<(Vec<u8>, Vec<u8>)> {
        match (overlay_candidate, committed_candidate) {
            (Some((overlay_key, overlay_value)), Some(committed_entry)) => match direction {
                SeekDirection::Forward => {
                    if overlay_key.as_slice() <= committed_entry.0.as_slice() {
                        Some((overlay_key.clone(), overlay_value.to_vec()))
                    } else {
                        Some(committed_entry)
                    }
                }
                SeekDirection::Reverse => {
                    if overlay_key.as_slice() >= committed_entry.0.as_slice() {
                        Some((overlay_key.clone(), overlay_value.to_vec()))
                    } else {
                        Some(committed_entry)
                    }
                }
            },
            (Some((overlay_key, overlay_value)), None) => {
                Some((overlay_key.clone(), overlay_value.to_vec()))
            }
            (None, Some(committed_entry)) => Some(committed_entry),
            (None, None) => None,
        }
    }

    fn committed_size(&self, op: &str) -> NitriteResult<u64> {
        // Counting is a full scan either way, but `Keyspace::len` walks key *and* value, so
        // counting a collection of fat documents used to read (and decode) every stored
        // document. Resolving only `Guard::key()` never touches the values.
        let mut count = 0u64;
        for guard in self.partition_handle()?.inner().iter() {
            guard.key().map_err(|err| Self::backend_err(op, err))?;
            count += 1;
        }
        Ok(count)
    }

    fn overlay_size_delta(&self, op: &str) -> NitriteResult<i64> {
        let partition = self.partition_handle()?;
        crate::tx_scope::with_partition_overlay_mut(&self.overlay_key, |overlay| {
            let Some(overlay) = overlay else {
                return Ok(0);
            };

            if let Some(delta) = overlay.cached_size_delta() {
                return Ok(delta);
            }

            let mut delta = 0i64;
            for (key, value) in &overlay.entries {
                let committed_present = partition
                    .contains_key(key.as_slice())
                    .map_err(|err| Self::backend_err(op, err))?;

                match (committed_present, value.is_some()) {
                    (false, true) => delta += 1,
                    (true, false) => delta -= 1,
                    _ => {}
                }
            }

            overlay.cache_size_delta(delta);
            Ok(delta)
        })
    }

    fn visible_size(&self, op: &str) -> NitriteResult<u64> {
        let committed = self.committed_size(op)? as i64;
        let visible = committed + self.overlay_size_delta(op)?;
        debug_assert!(visible >= 0, "transaction overlay size delta underflowed");
        Ok(visible.max(0) as u64)
    }

    fn visible_entry_raw(
        &self,
        op: &str,
        bound: Option<&[u8]>,
        inclusive: bool,
        direction: SeekDirection,
    ) -> NitriteResult<Option<(Vec<u8>, Vec<u8>)>> {
        if !crate::tx_scope::in_scope() {
            return self.committed_entry_raw(op, bound, inclusive, direction);
        }

        crate::tx_scope::with_partition_overlay(&self.overlay_key, |overlay| {
            let overlay_candidate = Self::overlay_entry_raw(overlay, bound, inclusive, direction);
            let mut committed_candidate = self.committed_entry_raw(op, bound, inclusive, direction)?;

            while let Some((key, value)) = committed_candidate.take() {
                match overlay.and_then(|entries| entries.entries.get(key.as_slice())) {
                    Some(None) => {
                        committed_candidate =
                            self.committed_entry_raw(op, Some(&key), false, direction)?;
                    }
                    Some(Some(overlay_value)) => {
                        committed_candidate = Some((key, overlay_value.to_vec()));
                        break;
                    }
                    None => {
                        committed_candidate = Some((key, value));
                        break;
                    }
                }
            }

            Ok(Self::choose_entry(
                direction,
                overlay_candidate,
                committed_candidate,
            ))
        })
    }

    fn get_attributes(&self) -> NitriteResult<Option<Attributes>> {
        if !self.is_dropped()? {
            let store = self.get_store()?;
            let meta_map = store.open_map(META_MAP_NAME)?;
            let name = self.get_name()?;

            if name.ne(META_MAP_NAME) {
                let attributes = meta_map.get(&Value::from(name.clone()))?;
                if let Some(attributes) = attributes {
                    // Check if value is actually a Document before unwrapping
                    return match attributes.as_document() {
                        Some(doc) => Ok(Some(Attributes::from_document(doc))),
                        None => {
                            log::warn!(
                                "Metadata for map '{}' is not a Document, skipping attributes",
                                name
                            );
                            Ok(None)
                        }
                    };
                }
            }
        }
        Ok(None)
    }

    fn set_attributes(&self, attributes: Attributes) -> NitriteResult<()> {
        if !self.is_dropped()? {
            let store = self.get_store()?;
            let meta_map = store.open_map(META_MAP_NAME)?;
            let name = self.get_name()?;

            if name.ne(META_MAP_NAME) {
                meta_map.put(Value::from(name), Value::from(attributes.to_document()))?;
            }
        }
        Ok(())
    }

    fn contains_key(&self, key: &Key) -> NitriteResult<bool> {
        self.check_opened()?;
        // Normalize numeric key types so this matches the encoding used by get/put/remove
        // (e.g. U64(5) and I64(5) map to the same stored key); otherwise contains_key could
        // miss a key that get() would find.
        let fjall_key = FjallValue::try_from_key(key)?;
        if !crate::tx_scope::in_scope() {
            return self
                .partition_handle()?
                .contains_key(fjall_key)
                .map_err(|err| Self::backend_err("check key in", err));
        }

        self.visible_contains_key("check key in", &fjall_key)
    }

    fn get(&self, key: &Key) -> NitriteResult<Option<Value>> {
        self.check_opened()?;

        // Use normalized numeric types for keys to ensure consistent index behavior
        let normalized_key = FjallValue::try_from_key(key)?;
        self.visible_value("get value from", &normalized_key)
    }

    fn clear(&self) -> NitriteResult<()> {
        self.check_opened()?;

        // Collect every visible key first, then delete them inside one atomic transaction.
        let mut keys = Vec::new();
        let mut next = self.visible_entry_raw("clear", None, true, SeekDirection::Forward)?;
        while let Some((key, _)) = next {
            keys.push(key.clone());
            next = self.visible_entry_raw("clear", Some(&key), false, SeekDirection::Forward)?;
        }

        self.store.write_in_tx(|| {
            for key in keys {
                self.remove_in_tx(key)?;
            }
            Ok(())
        })
    }

    fn is_closed(&self) -> NitriteResult<bool> {
        Ok(self.closed.load(Ordering::Relaxed))
    }

    fn close(&self) -> NitriteResult<()> {
        self.closed.store(true, Ordering::Relaxed);
        // Release the fjall handle: it carries a database clone, and fjall 3 will not let the
        // same path be reopened while any handle to it is alive.
        drop(self.partition.write().take());
        let store = self.get_store()?;
        store.close_map(&self.name)
    }

    fn remove(&self, key: &Key) -> NitriteResult<Option<Value>> {
        self.check_opened()?;
        // Read the current value first (through the active transaction if any), then delete it
        // within an atomic write transaction.
        let value = self.get(key)?;
        let normalized_key = FjallValue::try_from_key(key)?;
        self.store
            .write_in_tx(|| self.remove_in_tx(normalized_key.as_ref().to_vec()))?;
        Ok(value)
    }

    fn put(&self, key: Key, value: Value) -> NitriteResult<()> {
        self.check_opened()?;
        // Use normalized numeric types for keys to ensure consistent index behavior
        // across different numeric types (e.g., I64 vs U64)
        let normalized_key = FjallValue::try_from_key(&key)?;
        self.store.write_in_tx(|| {
            let fjall_value = FjallValue::try_from_value(&value)?;
            self.insert_in_tx(normalized_key, fjall_value)
        })
    }

    /// Inserts multiple key-value pairs as part of one atomic write transaction.
    ///
    /// Every entry lands in the same transaction as the rest of the enclosing atomic scope, so
    /// a batch document insert and all of its index updates are persisted together or not at
    /// all. When called outside a scope a one-shot transaction is used for the whole batch.
    fn put_all(&self, entries: Vec<(Key, Value)>) -> NitriteResult<()> {
        self.check_opened()?;

        if entries.is_empty() {
            return Ok(());
        }

        self.store.write_in_tx(|| {
            for (key, value) in entries {
                let normalized_key = FjallValue::try_from_key(&key)?;
                let fjall_value = FjallValue::try_from_value(&value)?;
                self.insert_in_tx(normalized_key, fjall_value)?;
            }
            Ok(())
        })
    }

    fn size(&self) -> NitriteResult<u64> {
        self.check_opened()?;
        if !crate::tx_scope::in_scope() {
            return self.committed_size("get size of");
        }

        self.visible_size("get size of")
    }

    fn put_if_absent(&self, key: Key, value: Value) -> NitriteResult<Option<Value>> {
        self.check_opened()?;
        // Use normalized numeric types for keys to ensure consistent index behavior
        let normalized_key = FjallValue::try_from_key(&key)?;
        // The read and the conditional insert run in one transaction so the check and the
        // write are atomic and read-your-writes consistent.
        self.store.write_in_tx(|| {
            let existing = self.visible_value("get item from", &normalized_key)?;
            if existing.is_none() {
                let fjall_value = FjallValue::try_from_value(&value)?;
                self.insert_in_tx(normalized_key.clone(), fjall_value)?;
            }
            Ok(existing)
        })
    }

    fn first_key(&self) -> NitriteResult<Option<Key>> {
        self.check_opened()?;
        let result = self.visible_entry_raw("get first key from", None, true, SeekDirection::Forward)?;
        result
            .map(|(key, _)| Self::decode_value(FjallValue::from(key)))
            .transpose()
    }

    fn last_key(&self) -> NitriteResult<Option<Key>> {
        self.check_opened()?;
        let result = self.visible_entry_raw("get last key from", None, true, SeekDirection::Reverse)?;
        result
            .map(|(key, _)| Self::decode_value(FjallValue::from(key)))
            .transpose()
    }

    fn higher_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.check_opened()?;
        let normalized_key = FjallValue::try_from_key(key)?;
        let next = self.visible_entry_raw(
            "get higher key from",
            Some(normalized_key.as_ref()),
            false,
            SeekDirection::Forward,
        )?;
        next.map(|(key, _)| Self::decode_value(FjallValue::from(key)))
            .transpose()
    }

    fn ceiling_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.check_opened()?;
        let normalized_key = FjallValue::try_from_key(key)?;
        let next = self.visible_entry_raw(
            "get ceiling key from",
            Some(normalized_key.as_ref()),
            true,
            SeekDirection::Forward,
        )?;
        next.map(|(key, _)| Self::decode_value(FjallValue::from(key)))
            .transpose()
    }

    fn lower_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.check_opened()?;
        let normalized_key = FjallValue::try_from_key(key)?;
        let prev = self.visible_entry_raw(
            "get lower key from",
            Some(normalized_key.as_ref()),
            false,
            SeekDirection::Reverse,
        )?;
        prev.map(|(key, _)| Self::decode_value(FjallValue::from(key)))
            .transpose()
    }

    fn floor_key(&self, key: &Key) -> NitriteResult<Option<Key>> {
        self.check_opened()?;
        let normalized_key = FjallValue::try_from_key(key)?;
        let prev = self.visible_entry_raw(
            "get floor key from",
            Some(normalized_key.as_ref()),
            true,
            SeekDirection::Reverse,
        )?;
        prev.map(|(key, _)| Self::decode_value(FjallValue::from(key)))
            .transpose()
    }

    fn is_empty(&self) -> NitriteResult<bool> {
        self.check_opened()?;
        if !crate::tx_scope::in_scope() {
            return self
                .partition_handle()?
                .inner()
                .is_empty()
                .map_err(|err| Self::backend_err("check if empty", err));
        }

        Ok(self.visible_size("check if empty")? == 0)
    }

    fn get_store(&self) -> NitriteResult<NitriteStore> {
        Ok(NitriteStore::new(self.store.clone()))
    }

    fn get_name(&self) -> NitriteResult<String> {
        let encoded_name = self.name.clone();
        let name = FjallStore::decode_name(&encoded_name);
        Ok(name)
    }

    fn dispose(&self) -> NitriteResult<()> {
        self.dropped.store(true, Ordering::Relaxed);
        self.closed.store(true, Ordering::Relaxed);
        drop(self.partition.write().take());

        let store = self.get_store()?;
        let name = self.get_name()?; // Get decoded name since remove_map will encode it
        store.remove_map(&name)?;

        Ok(())
    }

    fn is_dropped(&self) -> NitriteResult<bool> {
        Ok(self.dropped.load(Ordering::Relaxed))
    }

    // Helper function to avoid repeated error handling pattern
    fn handle_gc_error<E: std::fmt::Display>(err: E, operation: &str) -> NitriteResult<()> {
        log::debug!("Failed to {} from FjallMap: {}", operation, err);
        Err(NitriteError::new(
            &format!("Failed to {} from FjallMap: {}", operation, err),
            ErrorKind::BackendError,
        ))
    }

    pub fn collect_garbage(&self) -> NitriteResult<()> {
        if self.fjall_config.kv_separated() {
            // Fjall 3 removed the explicit `gc_scan` / `gc_with_*` calls: blob reclamation is
            // folded into compaction and driven by the keyspace's `staleness_threshold` (set in
            // `FjallConfig::partition_config`). A major compaction is what forces that pass now.
            if let Err(err) = self.partition_handle()?.inner().major_compact() {
                return Self::handle_gc_error(err, "collect garbage (major compact)");
            }
        } else {
            log::warn!("Cannot use GC for non-KV-separated tree");
        }
        Ok(())
    }
}

#[cfg(test)]
#[allow(clippy::assertions_on_constants)] // tests use assert!(true) as "reached without panic" markers
mod tests {
    use super::*;
    use crate::tests::{run_test, Context};
    use nitrite::common::{Attributes, Key, NitritePluginProvider, Value};
    use nitrite::nitrite_config::NitriteConfig;
    use nitrite::store::NitriteStoreProvider;
    use std::path::PathBuf;
    use std::time::Duration;
    use std::{fs, thread};

    #[inline(never)]
    #[allow(dead_code)]
    fn black_box<T>(x: T) -> T {
        x
    }

    fn create_context() -> Context {
        let path = random_path();
        let nitrite_config = NitriteConfig::default();
        nitrite_config
            .auto_configure()
            .expect("Failed to auto configure");
        let fjall_config = FjallConfig::new();
        fjall_config.set_db_path(&path);
        fjall_config.set_kv_separated(true);

        // Create the store first - it will create and own the keyspace
        let store = FjallStore::new(fjall_config.clone());
        store.open_or_create().expect("Failed to open store");
        store
            .initialize(nitrite_config)
            .expect("Failed to initialize store");

        // Get the keyspace from the store and use it to create the test partition
        // This ensures the partition belongs to the same keyspace used by the store
        let keyspace = store
            .keyspace()
            .expect("Store keyspace should be initialized");
        let partition = keyspace
            .clone()
            .keyspace("test_partition", || fjall_config.partition_config())
            .expect("Failed to open partition");

        let fjall_map = FjallMap::new(
            "test_map".to_string(),
            partition.clone(),
            store.clone(),
            fjall_config,
        );

        Context::new(
            path,
            Some(keyspace),
            Some(partition),
            Some(store),
            Some(fjall_map),
        )
    }

    fn random_path() -> String {
        let id = uuid::Uuid::new_v4();
        PathBuf::from("../test-data")
            .join(id.to_string())
            .to_str()
            .unwrap()
            .to_string()
    }

    fn cleanup(ctx: Context) {
        let path = ctx.path();
        let mut retry = 0;
        while fs::remove_dir_all(path.clone()).is_err() && retry < 2 {
            thread::sleep(Duration::from_millis(100));
            retry += 1;
        }
    }

    #[test]
    fn test_initialize() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.initialize().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_collect_garbage() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                map.put(Value::I8(1), Value::I8(1))
                    .expect("Failed to put item");
                map.remove(&Value::I8(1)).expect("Failed to remove item");
                assert!(map.collect_garbage().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_attributes() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let attributes = Attributes::new();
                assert!(map.set_attributes(attributes.clone()).is_ok());
                assert_eq!(map.attributes().unwrap(), Some(attributes));
            },
            cleanup,
        );
    }

    #[test]
    fn test_contains_key() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                assert!(map.contains_key(&key).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_contains_key_normalizes_numeric_types_like_get() {
        // Regression: contains_key must use the same normalized key encoding as get/put, so a
        // key stored as one numeric type is found regardless of the numeric type queried.
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                map.put(Key::U64(5), Value::from("five")).unwrap();

                // Found via the same and the cross numeric type, matching get().
                assert!(map.contains_key(&Key::U64(5)).unwrap());
                assert!(map.contains_key(&Key::I64(5)).unwrap());
                assert_eq!(map.get(&Key::I64(5)).unwrap(), Some(Value::from("five")));

                // A genuinely absent key is still reported absent.
                assert!(!map.contains_key(&Key::U64(6)).unwrap());
            },
            cleanup,
        );
    }

    #[test]
    fn test_get() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                assert!(map.get(&key).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.clear().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_is_closed() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.is_closed().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_close() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.close().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_values() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.values().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_keys() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.keys().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_remove() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                assert!(map.remove(&key).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_put() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                let value = Value::from("test_value");
                assert!(map.put(key, value).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_size() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.size().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_put_if_absent() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                let value = Value::from("test_value");
                assert!(map.put_if_absent(key, value).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_first_key() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.first_key().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_last_key() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.last_key().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_higher_key() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                assert!(map.higher_key(&key).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_ceiling_key() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                assert!(map.ceiling_key(&key).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_lower_key() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                assert!(map.lower_key(&key).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_floor_key() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                assert!(map.floor_key(&key).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_is_empty() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.is_empty().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_get_store() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.get_store().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_get_name() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert_eq!(map.get_name().unwrap(), "test_map");
            },
            cleanup,
        );
    }

    #[test]
    fn test_entries() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.entries().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_reverse_entries() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.reverse_entries().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_dispose_map() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                let value = Value::from("test_value");
                map.put(key, value).expect("Failed to put item");
                assert!(map.dispose().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_is_dropped() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                assert!(map.is_dropped().is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_with_async_cleanup_success() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add some data
                map.put(Key::from("key1"), Value::from("value1"))
                    .expect("Failed to put item");
                map.put(Key::from("key2"), Value::from("value2"))
                    .expect("Failed to put item");

                // Verify data exists
                assert_eq!(map.size().unwrap(), 2);

                // Clear should complete without panicking
                assert!(map.clear().is_ok());

                // Give async task time to complete
                thread::sleep(Duration::from_millis(200));

                // Verify cleared
                assert_eq!(map.size().unwrap(), 0);
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_async_cleanup_handles_commit_gracefully() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add data
                map.put(Key::from("test"), Value::from("data"))
                    .expect("Failed to put item");

                // Clear should NOT panic even if store cleanup fails
                // The async task should handle errors gracefully
                assert!(map.clear().is_ok());

                // Give async task time to complete
                thread::sleep(Duration::from_millis(200));

                // Map should still be usable after clear
                assert!(map.get(&Key::from("test")).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_on_closed_map() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Close the map
                assert!(map.close().is_ok());

                // Clear should fail since map is closed
                assert!(map.clear().is_err());
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_on_dropped_map() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Dispose (drop) the map
                assert!(map.dispose().is_ok());

                // Clear should fail since map is dropped
                assert!(map.clear().is_err());
            },
            cleanup,
        );
    }

    #[test]
    fn test_multiple_clears_in_succession() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // First clear
                map.put(Key::from("key1"), Value::from("value1"))
                    .expect("Failed to put item");
                assert!(map.clear().is_ok());
                thread::sleep(Duration::from_millis(200));
                assert_eq!(map.size().unwrap(), 0);

                // Second clear (on already empty map)
                map.put(Key::from("key2"), Value::from("value2"))
                    .expect("Failed to put item");
                assert!(map.clear().is_ok());
                thread::sleep(Duration::from_millis(200));
                assert_eq!(map.size().unwrap(), 0);

                // Third clear
                assert!(map.clear().is_ok());
                thread::sleep(Duration::from_millis(200));
                assert_eq!(map.size().unwrap(), 0);
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_does_not_panic_on_async_errors() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add data
                for i in 0..10 {
                    map.put(
                        Key::from(format!("key{}", i)),
                        Value::from(format!("value{}", i)),
                    )
                    .expect("Failed to put item");
                }

                // Clear should complete without panicking in async task
                // Even if store/garbage collection has issues
                assert!(map.clear().is_ok());

                // Give async task time to complete
                thread::sleep(Duration::from_millis(300));

                // Map should be usable and cleared
                assert_eq!(map.size().unwrap(), 0);
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_followed_by_put_operations() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add initial data
                map.put(Key::from("initial"), Value::from("data"))
                    .expect("Failed to put item");

                // Clear
                assert!(map.clear().is_ok());
                thread::sleep(Duration::from_millis(200));

                // Should be able to add new data after clear
                map.put(Key::from("new_key"), Value::from("new_value"))
                    .expect("Failed to put new item after clear");

                let result = map
                    .get(&Key::from("new_key"))
                    .expect("Failed to get new item");
                assert!(result.is_some());
                assert_eq!(result.unwrap(), Value::from("new_value"));
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_with_large_dataset() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add large amount of data
                for i in 0..100 {
                    map.put(
                        Key::from(format!("key_{:03}", i)),
                        Value::from(format!("value_{:03}", i)),
                    )
                    .expect("Failed to put item");
                }

                assert_eq!(map.size().unwrap(), 100);

                // Clear should handle large dataset without panicking
                assert!(map.clear().is_ok());
                thread::sleep(Duration::from_millis(500));

                assert_eq!(map.size().unwrap(), 0);
            },
            cleanup,
        );
    }

    #[test]
    fn test_clear_async_task_error_logging() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add data
                map.put(Key::from("key"), Value::from("value"))
                    .expect("Failed to put item");

                // Clear and let async task complete
                assert!(map.clear().is_ok());

                // Even if async task encounters errors,
                // they should be logged, not panicked
                thread::sleep(Duration::from_millis(200));

                // Map should still be functional
                assert!(map.is_closed().is_ok() || map.get(&Key::from("key")).is_ok());
            },
            cleanup,
        );
    }

    #[test]
    fn test_collect_garbage_error_handling() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add and remove items to create garbage
                for i in 0..20 {
                    let key = Key::from(format!("gc_key_{}", i));
                    map.put(key.clone(), Value::I64(i as i64))
                        .expect("Failed to put");
                    map.remove(&key).expect("Failed to remove");
                }

                // Garbage collection should succeed and handle errors gracefully
                match map.collect_garbage() {
                    Ok(_) => {
                        // Expected success
                        assert!(true);
                    }
                    Err(e) => {
                        // Even if it fails, it should return a proper error, not panic
                        log::info!("GC returned error (non-fatal): {}", e);
                        assert!(true);
                    }
                }
            },
            cleanup,
        );
    }

    #[test]
    fn test_attributes_handles_non_document_gracefully() {
        // Verify attributes doesn't panic on non-Document metadata
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Try to get attributes - should handle gracefully if metadata is corrupted
                let result = map.get_attributes();
                assert!(
                    result.is_ok(),
                    "get_attributes should not panic on non-Document metadata"
                );
            },
            cleanup,
        );
    }

    #[test]
    fn test_remove_uses_safe_error_pattern() {
        // Verify remove() uses safe error handling pattern
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");

                // Put and remove a value
                map.put(key.clone(), Value::from("test_value"))
                    .expect("Failed to put");

                // Remove should use safe error pattern (if let Err)
                let result = map.remove(&key);
                assert!(
                    result.is_ok(),
                    "Remove should succeed and use safe error handling"
                );
            },
            cleanup,
        );
    }

    #[test]
    fn test_put_if_absent_uses_safe_error_pattern() {
        // Verify put_if_absent() uses safe error handling pattern
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("unique_key");
                let value = Value::from("unique_value");

                // First put_if_absent should succeed
                let result1 = map.put_if_absent(key.clone(), value.clone());
                assert!(result1.is_ok(), "First put_if_absent should succeed");

                // Second put_if_absent should return Some (existing value)
                let result2 = map.put_if_absent(key.clone(), Value::from("new_value"));
                assert!(result2.is_ok(), "Second put_if_absent should succeed");
                let existing = result2.unwrap();
                assert!(existing.is_some(), "Should return existing value");
            },
            cleanup,
        );
    }

    #[test]
    fn test_collect_garbage_uses_safe_error_pattern() {
        // Verify collect_garbage() uses safe error pattern
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add and remove items to create garbage
                for i in 0..10 {
                    let key = Key::from(format!("gc_key_{}", i));
                    map.put(key.clone(), Value::I64(i as i64))
                        .expect("Failed to put");
                    map.remove(&key).expect("Failed to remove");
                }

                // Collect garbage should use safe error pattern
                let _result = map.collect_garbage();
                // Result may be Ok or Err, but should never panic
                assert!(true, "GC completed safely");
            },
            cleanup,
        );
    }

    #[test]
    fn test_error_handling_consistency_across_methods() {
        // Verify all methods use consistent error handling patterns
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("test_key");
                let value = Value::from("test_value");

                // Test remove with safe pattern
                map.put(key.clone(), value.clone()).ok();
                let remove_result = map.remove(&key);
                assert!(
                    remove_result.is_ok(),
                    "Remove should use safe error handling"
                );

                // Test put_if_absent with safe pattern
                let put_if_absent_result = map.put_if_absent(key.clone(), value.clone());
                assert!(
                    put_if_absent_result.is_ok(),
                    "put_if_absent should use safe error handling"
                );

                // Test collect_garbage with safe pattern
                let _gc_result = map.collect_garbage();
                // Should complete without panic regardless of success/failure
                assert!(true, "collect_garbage completed safely");
            },
            cleanup,
        );
    }

    #[test]
    fn test_multiple_garbage_collection_cycles() {
        // Verify refactored GC helper handles multiple cycles safely
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                for cycle in 0..5 {
                    // Add data
                    for i in 0..5 {
                        let key = Key::from(format!("cycle_{}_key_{}", cycle, i));
                        map.put(key.clone(), Value::from(format!("data_{}", i)))
                            .expect("Failed to put");
                        map.remove(&key).expect("Failed to remove");
                    }

                    // Collect garbage
                    map.collect_garbage().ok();
                }

                assert!(true, "Multiple GC cycles completed safely");
            },
            cleanup,
        );
    }

    #[test]
    fn test_attributes_empty_map_doesnt_panic() {
        // Verify attributes don't panic on empty map
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Empty map should not panic when getting attributes
                let result = map.get_attributes();
                assert!(result.is_ok(), "Empty map attributes should not panic");
            },
            cleanup,
        );
    }

    #[test]
    fn test_remove_after_put_safe_error_handling() {
        // Comprehensive remove test with safe error handling
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                for i in 0..10 {
                    let key = Key::from(format!("remove_test_{}", i));
                    let value = Value::from(format!("value_{}", i));

                    map.put(key.clone(), value.clone()).expect("Failed to put");

                    // Remove should handle errors safely
                    let remove_result = map.remove(&key);
                    assert!(
                        remove_result.is_ok(),
                        "Remove should use safe error pattern"
                    );

                    let retrieved = remove_result.unwrap();
                    assert_eq!(retrieved, Some(value), "Should retrieve correct value");
                }
            },
            cleanup,
        );
    }

    #[test]
    fn test_garbage_collection_with_various_data_types() {
        // Test GC helper with various data types
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Add various value types
                let values = vec![
                    Value::I64(42),
                    Value::F64(3.5),
                    Value::String("test".to_string()),
                    Value::Null,
                    Value::Array(vec![1.into(), 2.into()]),
                ];

                for (i, value) in values.into_iter().enumerate() {
                    let key = Key::from(format!("diverse_key_{}", i));
                    map.put(key.clone(), value).expect("Failed to put");
                    map.remove(&key).expect("Failed to remove");
                }

                // GC should handle diverse data safely
                let _gc_result = map.collect_garbage();
                assert!(true, "GC completed for diverse data without panicking");
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_fjall_map_contains_key_perf() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("perf_key");
                map.put(key.clone(), Value::I64(123))
                    .expect("Failed to put");

                for _ in 0..10000 {
                    let result = black_box(map.contains_key(&key));
                    black_box(result.is_ok());
                }
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_fjall_map_get_perf() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();
                let key = Key::from("perf_key");
                map.put(key.clone(), Value::I64(456))
                    .expect("Failed to put");

                for _ in 0..1000 {
                    let result = black_box(map.get(&key));
                    black_box(result.is_ok());
                }
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    // =================== put_all batch write tests ===================

    #[test]
    fn test_put_all_empty_batch() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Empty batch should succeed without error
                let result = map.put_all(vec![]);
                assert!(result.is_ok(), "Empty batch should succeed");

                // Map should still be empty
                assert_eq!(map.size().unwrap(), 0, "Map should be empty");
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_put_all_single_entry() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                let entries = vec![(Key::from("batch_key1"), Value::from("batch_value1"))];

                let result = map.put_all(entries);
                assert!(result.is_ok(), "Single entry batch should succeed");

                // Verify entry was inserted
                let value = map.get(&Key::from("batch_key1")).unwrap();
                assert_eq!(value, Some(Value::from("batch_value1")));
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_put_all_multiple_entries() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                let entries = vec![
                    (Key::from("batch_a"), Value::from("value_a")),
                    (Key::from("batch_b"), Value::I64(42)),
                    (Key::from("batch_c"), Value::F64(3.5)),
                    (Key::from("batch_d"), Value::Bool(true)),
                    (Key::from("batch_e"), Value::Null),
                ];

                let result = map.put_all(entries);
                assert!(result.is_ok(), "Multiple entry batch should succeed");

                // Verify all entries were inserted
                assert_eq!(map.size().unwrap(), 5, "All 5 entries should be inserted");
                assert_eq!(
                    map.get(&Key::from("batch_a")).unwrap(),
                    Some(Value::from("value_a"))
                );
                assert_eq!(
                    map.get(&Key::from("batch_b")).unwrap(),
                    Some(Value::I64(42))
                );
                assert_eq!(
                    map.get(&Key::from("batch_c")).unwrap(),
                    Some(Value::F64(3.5))
                );
                assert_eq!(
                    map.get(&Key::from("batch_d")).unwrap(),
                    Some(Value::Bool(true))
                );
                assert_eq!(map.get(&Key::from("batch_e")).unwrap(), Some(Value::Null));
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_put_all_overwrites_existing() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Insert initial value
                map.put(Key::from("overwrite_key"), Value::from("original"))
                    .unwrap();

                // Batch overwrite
                let entries = vec![(Key::from("overwrite_key"), Value::from("updated"))];

                let result = map.put_all(entries);
                assert!(result.is_ok(), "Batch overwrite should succeed");

                // Verify value was updated
                assert_eq!(
                    map.get(&Key::from("overwrite_key")).unwrap(),
                    Some(Value::from("updated"))
                );
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_put_all_large_batch() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Create a large batch of 1000 entries
                let entries: Vec<(Key, Value)> = (0..1000)
                    .map(|i| {
                        (
                            Key::from(format!("large_batch_{:04}", i)),
                            Value::I64(i as i64),
                        )
                    })
                    .collect();

                let result = map.put_all(entries);
                assert!(result.is_ok(), "Large batch should succeed");

                // Verify count
                assert_eq!(
                    map.size().unwrap(),
                    1000,
                    "All 1000 entries should be inserted"
                );

                // Spot check some values
                assert_eq!(
                    map.get(&Key::from("large_batch_0000")).unwrap(),
                    Some(Value::I64(0))
                );
                assert_eq!(
                    map.get(&Key::from("large_batch_0500")).unwrap(),
                    Some(Value::I64(500))
                );
                assert_eq!(
                    map.get(&Key::from("large_batch_0999")).unwrap(),
                    Some(Value::I64(999))
                );
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_put_all_with_numeric_keys() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Test batch with various numeric key types
                let entries = vec![
                    (Key::I64(100), Value::from("i64_key")),
                    (Key::I32(200), Value::from("i32_key")),
                    (Key::U64(300), Value::from("u64_key")),
                    (Key::F64(1.5), Value::from("f64_key")),
                ];

                let result = map.put_all(entries);
                assert!(result.is_ok(), "Batch with numeric keys should succeed");

                // Verify all entries
                assert_eq!(
                    map.get(&Key::I64(100)).unwrap(),
                    Some(Value::from("i64_key"))
                );
                assert_eq!(
                    map.get(&Key::I32(200)).unwrap(),
                    Some(Value::from("i32_key"))
                );
                assert_eq!(
                    map.get(&Key::U64(300)).unwrap(),
                    Some(Value::from("u64_key"))
                );
                assert_eq!(
                    map.get(&Key::F64(1.5)).unwrap(),
                    Some(Value::from("f64_key"))
                );
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_put_all_on_closed_map_fails() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Close the map
                map.close().unwrap();

                // put_all should fail on closed map
                let entries = vec![(Key::from("should_fail"), Value::from("value"))];

                let result = map.put_all(entries);
                assert!(result.is_err(), "put_all should fail on closed map");
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }

    #[test]
    fn test_put_all_perf_vs_individual_puts() {
        run_test(
            create_context,
            |ctx| {
                let map = ctx.fjall_map_unsafe();

                // Time individual puts
                let start = std::time::Instant::now();
                for i in 0..100 {
                    let key = Key::from(format!("individual_{:04}", i));
                    let value = Value::I64(i as i64);
                    map.put(key, value).unwrap();
                }
                let individual_time = start.elapsed();

                // Clear and time batch put
                map.clear().unwrap();

                let entries: Vec<(Key, Value)> = (0..100)
                    .map(|i| (Key::from(format!("batch_{:04}", i)), Value::I64(i as i64)))
                    .collect();

                let start = std::time::Instant::now();
                map.put_all(entries).unwrap();
                let batch_time = start.elapsed();

                // Batch should be faster (or at least not significantly slower)
                // Note: this is a relative test, not absolute performance
                log::info!(
                    "Performance: individual={:?}, batch={:?}",
                    individual_time,
                    batch_time
                );

                // Verify both methods resulted in correct count
                assert_eq!(map.size().unwrap(), 100);
            },
            |ctx| {
                cleanup(ctx);
            },
        );
    }
}