wabi_tree 0.1.2

Order-statistic B-tree map and set with O(log n) rank operations. Drop-in replacements for BTreeMap/BTreeSet.
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
use core::borrow::Borrow;

use smallvec::SmallVec;

use super::arena::Arena;
use super::handle::Handle;
use super::node::{InternalNode, LeafNode, MAX_KEYS, Node, SearchResult};
use super::size::Size;

/// The core B+Tree implementation backing `OSBTreeMap`.
pub(crate) struct RawOSBTreeMap<K, V> {
    /// Arena storing all tree nodes.
    nodes: Arena<Node<K>>,
    /// Arena storing all values (separate from nodes for cache efficiency).
    values: Arena<V>,
    /// Handle to the root node, if the tree is non-empty.
    root: Option<Handle>,
    /// Total number of key-value pairs in the tree.
    len: usize,
    /// Handle to the first (leftmost) leaf, for forward iteration.
    first_leaf: Option<Handle>,
    /// Handle to the last (rightmost) leaf, for backward iteration.
    last_leaf: Option<Handle>,
}

/// Result of an insertion attempt.
pub(crate) enum InsertResult<K> {
    /// Insertion completed without split.
    Done,
    /// Node split occurred; parent needs to insert this new child.
    Split {
        /// The separator key for the new child.
        separator: K,
        /// Handle to the new (right) child.
        new_child: Handle,
        /// Size of the new child subtree.
        new_child_size: Size,
    },
}

/// Path element for tracking traversal during mutations.
struct PathElement {
    /// Handle to the node at this level.
    node: Handle,
    /// Index of the child we descended into.
    child_index: usize,
}

/// Type alias for a path through the tree (stack of path elements).
type Path = SmallVec<[PathElement; 16]>;

impl<K, V> RawOSBTreeMap<K, V> {
    /// Creates a new, empty tree.
    pub(crate) const fn new() -> Self {
        Self {
            nodes: Arena::new(),
            values: Arena::new(),
            root: None,
            len: 0,
            first_leaf: None,
            last_leaf: None,
        }
    }

    /// Creates a new tree with the specified capacity.
    pub(crate) fn with_capacity(capacity: usize) -> Self {
        Self {
            nodes: Arena::with_capacity(capacity.div_ceil(MAX_KEYS)),
            values: Arena::with_capacity(capacity),
            root: None,
            len: 0,
            first_leaf: None,
            last_leaf: None,
        }
    }

    /// Returns the number of key-value pairs in the tree.
    pub(crate) const fn len(&self) -> usize {
        self.len
    }

    /// Returns true if the tree contains no elements.
    pub(crate) const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the capacity of the tree.
    pub(crate) fn capacity(&self) -> usize {
        self.values.capacity()
    }

    /// Clears all elements from the tree.
    pub(crate) fn clear(&mut self) {
        self.nodes.clear();
        self.values.clear();
        self.root = None;
        self.len = 0;
        self.first_leaf = None;
        self.last_leaf = None;
    }

    /// Drains all key-value pairs from the tree by walking the leaf chain.
    /// This is O(n) as it avoids rebalancing, unlike repeated `pop_first`/`pop_last`.
    pub(crate) fn drain_to_vec(&mut self) -> alloc::vec::Vec<(K, V)> {
        let len = self.len;
        if len == 0 {
            return alloc::vec::Vec::new();
        }

        let mut result = alloc::vec::Vec::with_capacity(len);
        let mut current_leaf = self.first_leaf;

        while let Some(leaf_handle) = current_leaf {
            let leaf = self.nodes.get_mut(leaf_handle).as_leaf_mut();
            let next = leaf.next();
            let (keys, value_handles) = leaf.take_all();

            for (key, vh) in keys.into_iter().zip(value_handles) {
                let value = self.values.take(vh);
                result.push((key, value));
            }

            current_leaf = next;
        }

        // Clear the tree structure (nodes arena still holds empty leaves and internals)
        self.nodes.clear();
        self.root = None;
        self.len = 0;
        self.first_leaf = None;
        self.last_leaf = None;

        result
    }

    /// Returns a reference to the first leaf, if any.
    pub(crate) fn first_leaf(&self) -> Option<Handle> {
        self.first_leaf
    }

    /// Returns a reference to the last leaf, if any.
    pub(crate) fn last_leaf(&self) -> Option<Handle> {
        self.last_leaf
    }

    /// Returns a reference to the root node, if any.
    pub(crate) fn root(&self) -> Option<Handle> {
        self.root
    }

    /// Returns a reference to a node by handle.
    pub(crate) fn node(&self, handle: Handle) -> &Node<K> {
        self.nodes.get(handle)
    }

    /// Returns a reference to a node by handle from a raw pointer.
    ///
    /// # Safety
    /// - `ptr` must point to a valid, allocated `RawOSBTreeMap<K, V>`.
    pub(crate) unsafe fn node_ptr<'a>(ptr: *const Self, handle: Handle) -> &'a Node<K> {
        // SAFETY: We only access the `nodes` field through addr_of, avoiding aliasing with
        // the `values` field.
        unsafe { Arena::get_ptr(core::ptr::addr_of!((*ptr).nodes), handle) }
    }

    /// Returns a mutable reference to a node by handle.
    pub(crate) fn node_mut(&mut self, handle: Handle) -> &mut Node<K> {
        self.nodes.get_mut(handle)
    }

    /// Returns a reference to a value by handle.
    pub(crate) fn value(&self, handle: Handle) -> &V {
        self.values.get(handle)
    }

    /// Returns a mutable reference to a value by handle.
    pub(crate) fn value_mut(&mut self, handle: Handle) -> &mut V {
        self.values.get_mut(handle)
    }

    /// Returns a mutable reference to a value by handle from a raw pointer.
    ///
    /// # Safety
    /// - `ptr` must point to a valid, allocated `RawOSBTreeMap<K, V>`.
    /// - The caller must ensure no other mutable references to the values arena exist.
    /// - The caller must have logical exclusive access to the value at `handle`.
    pub(crate) unsafe fn value_mut_ptr<'a>(ptr: *mut Self, handle: Handle) -> &'a mut V {
        // SAFETY: We only access the `values` field, avoiding aliasing with the `nodes` field.
        unsafe { (*core::ptr::addr_of_mut!((*ptr).values)).get_mut(handle) }
    }

    /// Takes a value from the arena.
    pub(crate) fn take_value(&mut self, handle: Handle) -> V {
        self.values.take(handle)
    }
}

impl<K: Clone + Ord, V> RawOSBTreeMap<K, V> {
    /// Searches for a key and returns the leaf handle and index if found.
    pub(crate) fn search<Q>(&self, key: &Q) -> Option<(Handle, usize)>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let root = self.root?;
        let mut current = root;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(key);
                    current = internal.child(child_idx);
                }
                Node::Leaf(leaf) => {
                    if let SearchResult::Found(idx) = leaf.search(key) {
                        return Some((current, idx));
                    }
                    return None;
                }
            }
        }
    }

    /// Returns a reference to the value corresponding to the key.
    pub(crate) fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let (leaf_handle, idx) = self.search(key)?;
        let leaf = self.nodes.get(leaf_handle).as_leaf();
        let value_handle = leaf.value(idx);
        Some(self.values.get(value_handle))
    }

    /// Returns a mutable reference to the value corresponding to the key.
    pub(crate) fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let (leaf_handle, idx) = self.search(key)?;
        let leaf = self.nodes.get(leaf_handle).as_leaf();
        let value_handle = leaf.value(idx);
        Some(self.values.get_mut(value_handle))
    }

    /// Returns the key-value pair corresponding to the key.
    pub(crate) fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let (leaf_handle, idx) = self.search(key)?;
        let leaf = self.nodes.get(leaf_handle).as_leaf();
        let k = leaf.key(idx);
        let value_handle = leaf.value(idx);
        Some((k, self.values.get(value_handle)))
    }

    /// Returns true if the tree contains the specified key.
    pub(crate) fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        self.search(key).is_some()
    }

    /// Returns the first key-value pair in the tree.
    pub(crate) fn first_key_value(&self) -> Option<(&K, &V)> {
        let first_leaf = self.first_leaf?;
        let leaf = self.nodes.get(first_leaf).as_leaf();
        if leaf.key_count() == 0 {
            return None;
        }
        let k = leaf.key(0);
        let value_handle = leaf.value(0);
        Some((k, self.values.get(value_handle)))
    }

    /// Returns the last key-value pair in the tree.
    pub(crate) fn last_key_value(&self) -> Option<(&K, &V)> {
        let last_leaf = self.last_leaf?;
        let leaf = self.nodes.get(last_leaf).as_leaf();
        let count = leaf.key_count();
        if count == 0 {
            return None;
        }
        let k = leaf.key(count - 1);
        let value_handle = leaf.value(count - 1);
        Some((k, self.values.get(value_handle)))
    }

    /// Inserts a key-value pair into the tree.
    /// Returns the old value if the key was already present.
    pub(crate) fn insert(&mut self, key: K, value: V) -> Option<V> {
        // Handle empty tree case
        if self.root.is_none() {
            let value_handle = self.values.alloc(value);
            let mut leaf = LeafNode::new();
            leaf.push(key, value_handle);
            let leaf_handle = self.nodes.alloc(Node::Leaf(leaf));
            self.root = Some(leaf_handle);
            self.first_leaf = Some(leaf_handle);
            self.last_leaf = Some(leaf_handle);
            self.len = 1;
            return None;
        }

        let root = self.root.unwrap();

        // Build path from root to leaf
        let mut path: Path = SmallVec::new();
        let mut current = root;

        // Traverse to leaf
        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(&key);
                    path.push(PathElement {
                        node: current,
                        child_index: child_idx,
                    });
                    current = internal.child(child_idx);
                }
                Node::Leaf(_) => break,
            }
        }

        // Insert into leaf
        let leaf = self.nodes.get_mut(current).as_leaf_mut();
        match leaf.search(&key) {
            SearchResult::Found(idx) => {
                // Key exists, replace value in-place to avoid alloc/free churn
                let value_handle = leaf.value(idx);
                let old_value = core::mem::replace(self.values.get_mut(value_handle), value);
                Some(old_value)
            }
            SearchResult::NotFound(idx) => {
                // Insert new key-value
                let value_handle = self.values.alloc(value);
                leaf.insert(idx, key, value_handle);
                self.len += 1;

                // Check if we need to split
                if leaf.key_count() > MAX_KEYS {
                    self.split_leaf_and_propagate(current, &mut path);
                } else {
                    // Update sizes along the path
                    self.increment_sizes_along_path(&path);
                }

                None
            }
        }
    }

    /// Splits a leaf and propagates splits up the tree as needed.
    fn split_leaf_and_propagate(&mut self, leaf_handle: Handle, path: &mut Path) {
        let leaf = self.nodes.get_mut(leaf_handle).as_leaf_mut();
        let (separator, mut right_leaf) = leaf.split();

        // Get the sizes
        let left_size = Size::from_usize(leaf.key_count());
        let right_size = Size::from_usize(right_leaf.key_count());

        // Set up leaf links
        let old_next = leaf.next();
        right_leaf.set_prev(Some(leaf_handle));
        right_leaf.set_next(old_next);
        leaf.set_next(None); // Will be set after we allocate right_leaf

        // Allocate the right leaf
        let right_handle = self.nodes.alloc(Node::Leaf(right_leaf));

        // Fix up the links
        let leaf = self.nodes.get_mut(leaf_handle).as_leaf_mut();
        leaf.set_next(Some(right_handle));

        if let Some(old_next) = old_next {
            self.nodes.get_mut(old_next).as_leaf_mut().set_prev(Some(right_handle));
        }

        // Update last_leaf if needed
        if self.last_leaf == Some(leaf_handle) {
            self.last_leaf = Some(right_handle);
        }

        // Propagate the split up
        self.propagate_split(path, separator, right_handle, left_size, right_size);
    }

    /// Propagates a split up the tree.
    fn propagate_split(
        &mut self,
        path: &mut Path,
        mut separator: K,
        mut new_child: Handle,
        mut left_size: Size,
        mut right_size: Size,
    ) {
        while let Some(elem) = path.pop() {
            let parent = self.nodes.get_mut(elem.node).as_internal_mut();

            // Update the size of the child we descended into
            parent.set_child_size(elem.child_index, left_size);

            // Insert the new child
            parent.insert_child(elem.child_index, separator.clone(), new_child, right_size);
            parent.update_size();

            // Check if parent needs to split
            if parent.key_count() <= MAX_KEYS {
                // No more splits needed, just update sizes along remaining path
                self.update_sizes_along_path(path);
                return;
            }

            // Split this internal node
            let (median, right_internal) = parent.split();
            left_size = parent.size();
            right_size = right_internal.size();

            let right_handle = self.nodes.alloc(Node::Internal(right_internal));

            separator = median;
            new_child = right_handle;
        }

        // Need a new root
        let old_root = self.root.unwrap();
        let old_root_size = match self.nodes.get(old_root) {
            Node::Internal(internal) => internal.size(),
            Node::Leaf(leaf) => Size::from_usize(leaf.key_count()),
        };

        let mut new_root = InternalNode::new();
        new_root.set_first_child(old_root, old_root_size);
        new_root.push_child(separator, new_child, right_size);
        new_root.update_size();

        let new_root_handle = self.nodes.alloc(Node::Internal(new_root));
        self.root = Some(new_root_handle);
    }

    /// Updates sizes along the remaining path after a split that didn't propagate further.
    /// Recomputes each ancestor's `child_size` for the child we descended through,
    /// then recomputes the ancestor's total size.
    fn update_sizes_along_path(&mut self, path: &Path) {
        for elem in path.iter().rev() {
            let parent = self.nodes.get(elem.node).as_internal();
            let child_handle = parent.child(elem.child_index);
            let child_size = match self.nodes.get(child_handle) {
                Node::Internal(internal) => internal.size(),
                Node::Leaf(leaf) => Size::from_usize(leaf.key_count()),
            };
            let parent = self.nodes.get_mut(elem.node).as_internal_mut();
            parent.set_child_size(elem.child_index, child_size);
            parent.update_size();
        }
    }

    /// Increments sizes along the path after a simple insertion (no split).
    fn increment_sizes_along_path(&mut self, path: &Path) {
        for elem in path.iter().rev() {
            let node = self.nodes.get_mut(elem.node).as_internal_mut();
            // Increment the overall node size
            let new_size = node.size().to_usize() + 1;
            node.set_size(Size::from_usize(new_size));
            // Also increment the specific child's size
            let child_size = node.child_size(elem.child_index).to_usize() + 1;
            node.set_child_size(elem.child_index, Size::from_usize(child_size));
        }
    }

    /// Removes a key from the tree and returns the value.
    pub(crate) fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        self.remove_entry(key).map(|(_, v)| v)
    }

    /// Removes a key from the tree and returns the key-value pair.
    pub(crate) fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let root = self.root?;

        // Build path from root to leaf
        let mut path: Path = SmallVec::new();
        let mut current = root;

        // Traverse to leaf
        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(key);
                    path.push(PathElement {
                        node: current,
                        child_index: child_idx,
                    });
                    current = internal.child(child_idx);
                }
                Node::Leaf(_) => break,
            }
        }

        // Find and remove from leaf
        let leaf = self.nodes.get_mut(current).as_leaf_mut();
        let idx = match leaf.search(key) {
            SearchResult::Found(idx) => idx,
            SearchResult::NotFound(_) => return None,
        };

        let (removed_key, value_handle) = leaf.remove(idx);
        let removed_value = self.values.take(value_handle);
        self.len -= 1;

        // Handle empty tree
        if self.len == 0 {
            self.nodes.clear();
            self.root = None;
            self.first_leaf = None;
            self.last_leaf = None;
            return Some((removed_key, removed_value));
        }

        // Check if we need to rebalance
        let leaf = self.nodes.get(current).as_leaf();
        if !leaf.is_at_minimum() || path.is_empty() {
            // Update separator keys if needed
            self.update_separators_after_remove(current, &path);
            // Update sizes
            self.update_sizes_after_remove(current, &path);
            return Some((removed_key, removed_value));
        }

        // Need to rebalance
        self.rebalance_leaf(current, &mut path);

        Some((removed_key, removed_value))
    }

    /// Updates separator keys after a removal.
    fn update_separators_after_remove(&mut self, leaf_handle: Handle, path: &Path) {
        if path.is_empty() {
            return;
        }

        let leaf = self.nodes.get(leaf_handle).as_leaf();
        if leaf.key_count() == 0 {
            return;
        }

        // Update the separator in the parent if this was a rightmost key
        let last_key = leaf.last_key().unwrap().clone();

        for elem in path.iter().rev() {
            let parent = self.nodes.get_mut(elem.node).as_internal_mut();
            if elem.child_index < parent.key_count() {
                parent.set_key(elem.child_index, last_key);
                break;
            }
        }
    }

    /// Updates sizes along the path after a removal by recomputing from children.
    fn update_sizes_after_remove(&mut self, leaf_handle: Handle, path: &Path) {
        // First update the immediate parent's child size for this leaf
        if let Some(elem) = path.last() {
            let leaf = self.nodes.get(leaf_handle).as_leaf();
            let leaf_size = Size::from_usize(leaf.key_count());
            let parent = self.nodes.get_mut(elem.node).as_internal_mut();
            parent.set_child_size(elem.child_index, leaf_size);
            parent.update_size();
        }

        // Then update all ancestor sizes (recomputing child_sizes from actual children)
        for elem in path.iter().rev().skip(1) {
            let parent = self.nodes.get(elem.node).as_internal();
            let child_handle = parent.child(elem.child_index);
            let child_size = match self.nodes.get(child_handle) {
                Node::Internal(internal) => internal.size(),
                Node::Leaf(leaf) => Size::from_usize(leaf.key_count()),
            };
            let parent = self.nodes.get_mut(elem.node).as_internal_mut();
            parent.set_child_size(elem.child_index, child_size);
            parent.update_size();
        }
    }

    /// Rebalances a leaf after a removal caused it to underflow.
    fn rebalance_leaf(&mut self, leaf_handle: Handle, path: &mut Path) {
        let parent_elem = path.last().unwrap();
        let parent_handle = parent_elem.node;
        let child_idx = parent_elem.child_index;

        let parent = self.nodes.get(parent_handle).as_internal();

        // Try to borrow from left sibling
        if child_idx > 0 {
            let left_sibling_handle = parent.child(child_idx - 1);
            let left_sibling = self.nodes.get(left_sibling_handle).as_leaf();
            if left_sibling.can_lend() {
                self.borrow_from_left_leaf(leaf_handle, left_sibling_handle, parent_handle, child_idx);
                // Update overall sizes along path (child sizes already updated in borrow)
                self.update_sizes_from_path(path);
                return;
            }
        }

        // Try to borrow from right sibling
        if child_idx < parent.child_count() - 1 {
            let right_sibling_handle = parent.child(child_idx + 1);
            let right_sibling = self.nodes.get(right_sibling_handle).as_leaf();
            if right_sibling.can_lend() {
                self.borrow_from_right_leaf(leaf_handle, right_sibling_handle, parent_handle, child_idx);
                // Update overall sizes along path (child sizes already updated in borrow)
                self.update_sizes_from_path(path);
                return;
            }
        }

        // Must merge
        if child_idx > 0 {
            // Merge with left sibling
            let left_sibling_handle = parent.child(child_idx - 1);
            self.merge_leaves(left_sibling_handle, leaf_handle, path, child_idx - 1);
        } else {
            // Merge with right sibling
            let right_sibling_handle = parent.child(child_idx + 1);
            self.merge_leaves(leaf_handle, right_sibling_handle, path, child_idx);
        }
    }

    /// Borrows a key-value from the left leaf sibling.
    fn borrow_from_left_leaf(
        &mut self,
        leaf_handle: Handle,
        left_handle: Handle,
        parent_handle: Handle,
        child_idx: usize,
    ) {
        // Pop from left sibling
        let left = self.nodes.get_mut(left_handle).as_leaf_mut();
        let (key, value) = left.pop().unwrap();
        let left_new_size = left.key_count();
        let left_new_last_key = left.last_key().unwrap().clone();

        // Push to front of current leaf
        let leaf = self.nodes.get_mut(leaf_handle).as_leaf_mut();
        leaf.push_front(key, value);
        let current_new_size = leaf.key_count();

        // Update parent separator and child sizes
        let parent = self.nodes.get_mut(parent_handle).as_internal_mut();
        parent.set_key(child_idx - 1, left_new_last_key);
        parent.set_child_size(child_idx - 1, Size::from_usize(left_new_size));
        parent.set_child_size(child_idx, Size::from_usize(current_new_size));
    }

    /// Borrows a key-value from the right leaf sibling.
    fn borrow_from_right_leaf(
        &mut self,
        leaf_handle: Handle,
        right_handle: Handle,
        parent_handle: Handle,
        child_idx: usize,
    ) {
        // Pop from front of right sibling
        let right = self.nodes.get_mut(right_handle).as_leaf_mut();
        let (key, value) = right.pop_front().unwrap();
        let right_new_size = right.key_count();

        // Push to end of current leaf
        let leaf = self.nodes.get_mut(leaf_handle).as_leaf_mut();
        leaf.push(key.clone(), value);
        let current_new_size = leaf.key_count();

        // Update parent separator and child sizes.
        // The borrowed key becomes the new max key of the current node,
        // so it's the correct separator for child_idx.
        let parent = self.nodes.get_mut(parent_handle).as_internal_mut();
        parent.set_key(child_idx, key);
        parent.set_child_size(child_idx, Size::from_usize(current_new_size));
        parent.set_child_size(child_idx + 1, Size::from_usize(right_new_size));
    }

    /// Merges two leaf nodes.
    fn merge_leaves(&mut self, left_handle: Handle, right_handle: Handle, path: &mut Path, separator_idx: usize) {
        // Take the right leaf
        let right = match self.nodes.take(right_handle) {
            Node::Leaf(leaf) => leaf,
            Node::Internal(_) => panic!("expected leaf"),
        };

        // Merge into left
        let left = self.nodes.get_mut(left_handle).as_leaf_mut();
        left.merge_with_right(right);

        // Update next pointer of node after right (if any)
        if let Some(next_handle) = left.next() {
            self.nodes.get_mut(next_handle).as_leaf_mut().set_prev(Some(left_handle));
        }

        // Update last_leaf if needed
        if self.last_leaf == Some(right_handle) {
            self.last_leaf = Some(left_handle);
        }

        // Update first_leaf if needed
        if self.first_leaf == Some(right_handle) {
            self.first_leaf = Some(left_handle);
        }

        // Remove separator from parent and propagate
        self.remove_from_parent_and_propagate(path, separator_idx);
    }

    /// Removes a separator from a parent node and propagates rebalancing up.
    fn remove_from_parent_and_propagate(&mut self, path: &mut Path, separator_idx: usize) {
        let parent_elem = path.pop().unwrap();
        let parent_handle = parent_elem.node;

        let parent = self.nodes.get_mut(parent_handle).as_internal_mut();
        let (_sep_key, removed_child, _removed_size) = parent.remove_child(separator_idx);

        // Free the removed child handle (already taken during merge)
        // Note: The node was already taken in merge_leaves, so we don't free here
        let _ = removed_child;

        // Update the merged child's size in the parent (the left child absorbed the right)
        let merged_child_handle = parent.child(separator_idx);
        let merged_child_size = match self.nodes.get(merged_child_handle) {
            Node::Internal(internal) => internal.size(),
            Node::Leaf(leaf) => Size::from_usize(leaf.key_count()),
        };
        let parent = self.nodes.get_mut(parent_handle).as_internal_mut();
        parent.set_child_size(separator_idx, merged_child_size);
        parent.update_size();

        // Check if parent needs rebalancing
        if path.is_empty() {
            // This is the root
            if parent.child_count() == 1 {
                // Root has only one child, make that child the new root
                let new_root = parent.child(0);
                self.nodes.free(parent_handle);
                self.root = Some(new_root);
            }
            return;
        }

        if !parent.is_at_minimum() {
            // Update sizes along remaining path
            for elem in path.iter().rev() {
                let parent = self.nodes.get(elem.node).as_internal();
                let child_handle = parent.child(elem.child_index);
                let child_size = match self.nodes.get(child_handle) {
                    Node::Internal(internal) => internal.size(),
                    Node::Leaf(leaf) => Size::from_usize(leaf.key_count()),
                };
                let parent = self.nodes.get_mut(elem.node).as_internal_mut();
                parent.set_child_size(elem.child_index, child_size);
                parent.update_size();
            }
            return;
        }

        // Need to rebalance internal node
        self.rebalance_internal(parent_handle, path);
    }

    /// Rebalances an internal node after a child was removed.
    fn rebalance_internal(&mut self, node_handle: Handle, path: &mut Path) {
        let parent_elem = path.last().unwrap();
        let parent_handle = parent_elem.node;
        let child_idx = parent_elem.child_index;

        let parent = self.nodes.get(parent_handle).as_internal();

        // Try to borrow from left sibling
        if child_idx > 0 {
            let left_sibling_handle = parent.child(child_idx - 1);
            let left_sibling = self.nodes.get(left_sibling_handle).as_internal();
            if left_sibling.can_lend() {
                self.borrow_from_left_internal(node_handle, left_sibling_handle, parent_handle, child_idx);
                self.update_sizes_from_path(path);
                return;
            }
        }

        // Try to borrow from right sibling
        if child_idx < parent.child_count() - 1 {
            let right_sibling_handle = parent.child(child_idx + 1);
            let right_sibling = self.nodes.get(right_sibling_handle).as_internal();
            if right_sibling.can_lend() {
                self.borrow_from_right_internal(node_handle, right_sibling_handle, parent_handle, child_idx);
                self.update_sizes_from_path(path);
                return;
            }
        }

        // Must merge
        if child_idx > 0 {
            // Merge with left sibling
            let left_sibling_handle = parent.child(child_idx - 1);
            self.merge_internals(left_sibling_handle, node_handle, path, child_idx - 1);
        } else {
            // Merge with right sibling
            let right_sibling_handle = parent.child(child_idx + 1);
            self.merge_internals(node_handle, right_sibling_handle, path, child_idx);
        }
    }

    /// Borrows from left internal sibling.
    fn borrow_from_left_internal(
        &mut self,
        node_handle: Handle,
        left_handle: Handle,
        parent_handle: Handle,
        child_idx: usize,
    ) {
        // Get parent separator
        let parent = self.nodes.get(parent_handle).as_internal();
        let parent_sep = parent.key(child_idx - 1).clone();

        // Pop from left sibling
        let left = self.nodes.get_mut(left_handle).as_internal_mut();
        let (left_key, left_child, left_child_size) = left.pop_child().unwrap();
        left.update_size();
        let left_new_size = left.size();

        // Push to front of current node with parent separator
        let node = self.nodes.get_mut(node_handle).as_internal_mut();
        node.push_child_front(parent_sep, node.child(0), node.child_size(0));
        node.set_first_child(left_child, left_child_size);
        node.update_size();
        let node_new_size = node.size();

        // Update parent separator and child sizes
        let parent = self.nodes.get_mut(parent_handle).as_internal_mut();
        parent.set_key(child_idx - 1, left_key);
        parent.set_child_size(child_idx - 1, left_new_size);
        parent.set_child_size(child_idx, node_new_size);
    }

    /// Borrows from right internal sibling.
    fn borrow_from_right_internal(
        &mut self,
        node_handle: Handle,
        right_handle: Handle,
        parent_handle: Handle,
        child_idx: usize,
    ) {
        // Get parent separator
        let parent = self.nodes.get(parent_handle).as_internal();
        let parent_sep = parent.key(child_idx).clone();

        // Pop from front of right sibling
        let right = self.nodes.get_mut(right_handle).as_internal_mut();
        let (right_key, right_child, right_child_size) = right.pop_child_front().unwrap();
        right.update_size();
        let right_new_size = right.size();

        // Push to end of current node with parent separator
        let node = self.nodes.get_mut(node_handle).as_internal_mut();
        node.push_child(parent_sep, right_child, right_child_size);
        node.update_size();
        let node_new_size = node.size();

        // Update parent separator and child sizes
        let parent = self.nodes.get_mut(parent_handle).as_internal_mut();
        parent.set_key(child_idx, right_key);
        parent.set_child_size(child_idx, node_new_size);
        parent.set_child_size(child_idx + 1, right_new_size);
    }

    /// Merges two internal nodes.
    fn merge_internals(&mut self, left_handle: Handle, right_handle: Handle, path: &mut Path, separator_idx: usize) {
        let parent_elem = path.last().unwrap();
        let parent_handle = parent_elem.node;

        // Get separator from parent
        let parent = self.nodes.get(parent_handle).as_internal();
        let separator = parent.key(separator_idx).clone();

        // Take the right node
        let right = match self.nodes.take(right_handle) {
            Node::Internal(internal) => internal,
            Node::Leaf(_) => panic!("expected internal"),
        };

        // Merge into left
        let left = self.nodes.get_mut(left_handle).as_internal_mut();
        left.merge_with_right(separator, right);

        // Remove separator from parent and propagate
        self.remove_from_parent_and_propagate(path, separator_idx);
    }

    /// Updates sizes from a path.
    fn update_sizes_from_path(&mut self, path: &Path) {
        for elem in path.iter().rev() {
            let parent = self.nodes.get(elem.node).as_internal();
            let child_handle = parent.child(elem.child_index);
            let child_size = match self.nodes.get(child_handle) {
                Node::Internal(internal) => internal.size(),
                Node::Leaf(leaf) => Size::from_usize(leaf.key_count()),
            };
            let parent = self.nodes.get_mut(elem.node).as_internal_mut();
            parent.set_child_size(elem.child_index, child_size);
            parent.update_size();
        }
    }

    /// Removes and returns the first key-value pair.
    pub(crate) fn pop_first(&mut self) -> Option<(K, V)> {
        let root = self.root?;

        // Build path to first leaf (always go to child 0)
        let mut path: Path = SmallVec::new();
        let mut current = root;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    path.push(PathElement {
                        node: current,
                        child_index: 0,
                    });
                    current = internal.child(0);
                }
                Node::Leaf(_) => break,
            }
        }

        // Remove first element from leaf
        let leaf = self.nodes.get_mut(current).as_leaf_mut();
        let (removed_key, value_handle) = leaf.remove(0);
        let removed_value = self.values.take(value_handle);
        self.len -= 1;

        // Handle empty tree
        if self.len == 0 {
            self.nodes.clear();
            self.root = None;
            self.first_leaf = None;
            self.last_leaf = None;
            return Some((removed_key, removed_value));
        }

        // Check if we need to rebalance
        let leaf = self.nodes.get(current).as_leaf();
        if !leaf.is_at_minimum() || path.is_empty() {
            // Update separator keys if needed
            self.update_separators_after_remove(current, &path);
            // Update sizes
            self.update_sizes_after_remove(current, &path);
            return Some((removed_key, removed_value));
        }

        // Need to rebalance
        self.rebalance_leaf(current, &mut path);

        Some((removed_key, removed_value))
    }

    /// Removes and returns the last key-value pair.
    pub(crate) fn pop_last(&mut self) -> Option<(K, V)> {
        let root = self.root?;

        // Build path to last leaf (always go to last child)
        let mut path: Path = SmallVec::new();
        let mut current = root;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let last_child_idx = internal.child_count() - 1;
                    path.push(PathElement {
                        node: current,
                        child_index: last_child_idx,
                    });
                    current = internal.child(last_child_idx);
                }
                Node::Leaf(_) => break,
            }
        }

        // Remove last element from leaf
        let leaf = self.nodes.get_mut(current).as_leaf_mut();
        let last_idx = leaf.key_count() - 1;
        let (removed_key, value_handle) = leaf.remove(last_idx);
        let removed_value = self.values.take(value_handle);
        self.len -= 1;

        // Handle empty tree
        if self.len == 0 {
            self.nodes.clear();
            self.root = None;
            self.first_leaf = None;
            self.last_leaf = None;
            return Some((removed_key, removed_value));
        }

        // Check if we need to rebalance
        let leaf = self.nodes.get(current).as_leaf();
        if !leaf.is_at_minimum() || path.is_empty() {
            // Update separator keys if needed
            self.update_separators_after_remove(current, &path);
            // Update sizes
            self.update_sizes_after_remove(current, &path);
            return Some((removed_key, removed_value));
        }

        // Need to rebalance
        self.rebalance_leaf(current, &mut path);

        Some((removed_key, removed_value))
    }

    /// Gets an element by its rank (0-indexed position in sorted order).
    pub(crate) fn get_by_rank(&self, rank: usize) -> Option<(&K, &V)> {
        if rank >= self.len {
            return None;
        }

        let root = self.root?;
        let mut current = root;
        let mut remaining = rank;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    // Find which child contains the rank
                    let mut found = false;
                    for i in 0..internal.child_count() {
                        let child_size = internal.child_size(i).to_usize();
                        if remaining < child_size {
                            current = internal.child(i);
                            found = true;
                            break;
                        }
                        remaining -= child_size;
                    }
                    debug_assert!(
                        found,
                        "get_by_rank: tree size invariant violated - rank {} not found in children (node size: {})",
                        rank,
                        internal.size().to_usize()
                    );
                }
                Node::Leaf(leaf) => {
                    let key = leaf.key(remaining);
                    let value_handle = leaf.value(remaining);
                    return Some((key, self.values.get(value_handle)));
                }
            }
        }
    }

    /// Gets a mutable element by its rank.
    pub(crate) fn get_by_rank_mut(&mut self, rank: usize) -> Option<(&K, &mut V)> {
        if rank >= self.len {
            return None;
        }

        let root = self.root?;
        let mut current = root;
        let mut remaining = rank;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    // Find which child contains the rank
                    let mut found = false;
                    for i in 0..internal.child_count() {
                        let child_size = internal.child_size(i).to_usize();
                        if remaining < child_size {
                            current = internal.child(i);
                            found = true;
                            break;
                        }
                        remaining -= child_size;
                    }
                    debug_assert!(
                        found,
                        "get_by_rank_mut: tree size invariant violated - rank {} not found in children (node size: {})",
                        rank,
                        internal.size().to_usize()
                    );
                }
                Node::Leaf(leaf) => {
                    let key = leaf.key(remaining);
                    let value_handle = leaf.value(remaining);
                    // We need to return both a reference to the key and a mutable reference
                    // to the value. The borrow checker sees `self` as borrowed twice, but
                    // this is actually safe because keys and values are stored in separate
                    // arenas (self.nodes vs self.values) that don't alias.
                    //
                    // SAFETY:
                    // - `key` points into `self.nodes` arena (via the leaf node)
                    // - `value` points into `self.values` arena
                    // - These arenas are disjoint memory regions
                    // - We only mutate `self.values`, never `self.nodes`
                    // - The key reference remains valid because we don't modify the nodes arena
                    let key_ptr = key as *const K;
                    let value = self.values.get_mut(value_handle);
                    return Some((unsafe { &*key_ptr }, value));
                }
            }
        }
    }

    /// Returns the rank (0-indexed position) of a key.
    pub(crate) fn rank_of<Q>(&self, key: &Q) -> Option<usize>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let root = self.root?;
        let mut current = root;
        let mut rank = 0;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(key);
                    // Add sizes of all children before the one we're descending into
                    for i in 0..child_idx {
                        rank += internal.child_size(i).to_usize();
                    }
                    current = internal.child(child_idx);
                }
                Node::Leaf(leaf) => match leaf.search(key) {
                    SearchResult::Found(idx) => return Some(rank + idx),
                    SearchResult::NotFound(_) => return None,
                },
            }
        }
    }

    /// Finds the lower bound position (first key >= given key).
    /// Returns (`leaf_handle`, index) or None if all keys are less than the given key.
    pub(crate) fn lower_bound<Q>(&self, key: &Q) -> Option<(Handle, usize)>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let root = self.root?;
        let mut current = root;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(key);
                    current = internal.child(child_idx);
                }
                Node::Leaf(leaf) => {
                    // Find first key >= target
                    match leaf.search(key) {
                        SearchResult::Found(idx) => return Some((current, idx)),
                        SearchResult::NotFound(idx) => {
                            if idx < leaf.key_count() {
                                return Some((current, idx));
                            }
                            // All keys in this leaf are < target, check next leaf
                            if let Some(next) = leaf.next() {
                                let next_leaf = self.nodes.get(next).as_leaf();
                                if next_leaf.key_count() > 0 {
                                    return Some((next, 0));
                                }
                            }
                            return None;
                        }
                    }
                }
            }
        }
    }

    /// Finds the upper bound position (first key > given key).
    /// Returns (`leaf_handle`, index) or None if all keys are <= the given key.
    pub(crate) fn upper_bound<Q>(&self, key: &Q) -> Option<(Handle, usize)>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let root = self.root?;
        let mut current = root;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(key);
                    current = internal.child(child_idx);
                }
                Node::Leaf(leaf) => {
                    // Find first key > target
                    match leaf.search(key) {
                        SearchResult::Found(idx) => {
                            // Key found, upper bound is the next position
                            let next_idx = idx + 1;
                            if next_idx < leaf.key_count() {
                                return Some((current, next_idx));
                            }
                            // Check next leaf
                            if let Some(next) = leaf.next() {
                                let next_leaf = self.nodes.get(next).as_leaf();
                                if next_leaf.key_count() > 0 {
                                    return Some((next, 0));
                                }
                            }
                            return None;
                        }
                        SearchResult::NotFound(idx) => {
                            // idx is where key would be inserted, so it's also the first key > target
                            if idx < leaf.key_count() {
                                return Some((current, idx));
                            }
                            // All keys in this leaf are <= target, check next leaf
                            if let Some(next) = leaf.next() {
                                let next_leaf = self.nodes.get(next).as_leaf();
                                if next_leaf.key_count() > 0 {
                                    return Some((next, 0));
                                }
                            }
                            return None;
                        }
                    }
                }
            }
        }
    }

    /// Finds the last position <= given key.
    /// Returns (`leaf_handle`, index) or None if all keys are > the given key.
    pub(crate) fn upper_bound_inclusive<Q>(&self, key: &Q) -> Option<(Handle, usize)>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        // Find lower_bound and then step back if needed
        let root = self.root?;
        let mut current = root;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(key);
                    current = internal.child(child_idx);
                }
                Node::Leaf(leaf) => {
                    match leaf.search(key) {
                        SearchResult::Found(idx) => return Some((current, idx)),
                        SearchResult::NotFound(idx) => {
                            // idx is insertion point; last key <= target is at idx - 1
                            if idx > 0 {
                                return Some((current, idx - 1));
                            }
                            // Need to check previous leaf
                            if let Some(prev) = leaf.prev() {
                                let prev_leaf = self.nodes.get(prev).as_leaf();
                                if prev_leaf.key_count() > 0 {
                                    return Some((prev, prev_leaf.key_count() - 1));
                                }
                            }
                            return None;
                        }
                    }
                }
            }
        }
    }

    /// Finds the last position < given key.
    /// Returns (`leaf_handle`, index) or None if all keys are >= the given key.
    pub(crate) fn lower_bound_exclusive<Q>(&self, key: &Q) -> Option<(Handle, usize)>
    where
        K: Borrow<Q>,
        Q: ?Sized + Ord,
    {
        let root = self.root?;
        let mut current = root;

        loop {
            let node = self.nodes.get(current);
            match node {
                Node::Internal(internal) => {
                    let child_idx = internal.search_child(key);
                    current = internal.child(child_idx);
                }
                Node::Leaf(leaf) => {
                    match leaf.search(key) {
                        SearchResult::Found(idx) => {
                            // Key found, exclusive upper bound is idx - 1
                            if idx > 0 {
                                return Some((current, idx - 1));
                            }
                            // Need to check previous leaf
                            if let Some(prev) = leaf.prev() {
                                let prev_leaf = self.nodes.get(prev).as_leaf();
                                if prev_leaf.key_count() > 0 {
                                    return Some((prev, prev_leaf.key_count() - 1));
                                }
                            }
                            return None;
                        }
                        SearchResult::NotFound(idx) => {
                            // idx is insertion point; last key < target is at idx - 1
                            if idx > 0 {
                                return Some((current, idx - 1));
                            }
                            // Need to check previous leaf
                            if let Some(prev) = leaf.prev() {
                                let prev_leaf = self.nodes.get(prev).as_leaf();
                                if prev_leaf.key_count() > 0 {
                                    return Some((prev, prev_leaf.key_count() - 1));
                                }
                            }
                            return None;
                        }
                    }
                }
            }
        }
    }
}

impl<K: Clone, V: Clone> Clone for RawOSBTreeMap<K, V> {
    fn clone(&self) -> Self {
        use alloc::collections::VecDeque;

        fn clone_node<K: Clone, V: Clone>(
            old_nodes: &Arena<Node<K>>,
            old_values: &Arena<V>,
            new_nodes: &mut Arena<Node<K>>,
            new_values: &mut Arena<V>,
            old_handle: Handle,
        ) -> Handle {
            let old_node = old_nodes.get(old_handle);
            match old_node {
                Node::Leaf(leaf) => {
                    let mut new_leaf = LeafNode::new();
                    for i in 0..leaf.key_count() {
                        let key = leaf.key(i).clone();
                        let old_value_handle = leaf.value(i);
                        let new_value_handle = new_values.alloc(old_values.get(old_value_handle).clone());
                        new_leaf.push(key, new_value_handle);
                    }
                    // prev/next will be fixed up later
                    new_nodes.alloc(Node::Leaf(new_leaf))
                }
                Node::Internal(internal) => {
                    // Recursively clone children
                    let mut new_internal = InternalNode::new();

                    // Clone first child
                    let first_child = internal.child(0);
                    let new_first = clone_node(old_nodes, old_values, new_nodes, new_values, first_child);
                    let first_size = internal.child_size(0);
                    new_internal.set_first_child(new_first, first_size);

                    // Clone remaining children
                    for i in 0..internal.key_count() {
                        let key = internal.key(i).clone();
                        let child = internal.child(i + 1);
                        let new_child = clone_node(old_nodes, old_values, new_nodes, new_values, child);
                        let child_size = internal.child_size(i + 1);
                        new_internal.push_child(key, new_child, child_size);
                    }

                    new_internal.set_size(internal.size());
                    new_nodes.alloc(Node::Internal(new_internal))
                }
            }
        }

        fn find_leaves<K>(nodes: &Arena<Node<K>>, root: Handle) -> alloc::vec::Vec<Handle> {
            let mut leaves = alloc::vec::Vec::new();
            let mut stack = alloc::vec![root];
            while let Some(handle) = stack.pop() {
                match nodes.get(handle) {
                    Node::Leaf(_) => leaves.push(handle),
                    Node::Internal(internal) => {
                        // Push children in reverse order so we process left-to-right
                        for i in (0..internal.child_count()).rev() {
                            stack.push(internal.child(i));
                        }
                    }
                }
            }
            leaves
        }

        // Clone values arena
        let mut new_values: Arena<V> = Arena::with_capacity(self.values.capacity());
        let mut new_nodes: Arena<Node<K>> = Arena::with_capacity(self.nodes.capacity());

        // If empty, return empty tree
        if self.root.is_none() {
            return Self {
                nodes: new_nodes,
                values: new_values,
                root: None,
                len: 0,
                first_leaf: None,
                last_leaf: None,
            };
        }

        // Clone all nodes using depth-first traversal
        let new_root = clone_node(&self.nodes, &self.values, &mut new_nodes, &mut new_values, self.root.unwrap());

        // Fix up leaf prev/next pointers by traversing the leaf chain
        // Find all leaves and build the chain
        let new_leaves = find_leaves(&new_nodes, new_root);

        // Set up prev/next links
        for i in 0..new_leaves.len() {
            let handle = new_leaves[i];
            let prev = if i > 0 {
                Some(new_leaves[i - 1])
            } else {
                None
            };
            let next = if i < new_leaves.len() - 1 {
                Some(new_leaves[i + 1])
            } else {
                None
            };
            let leaf = new_nodes.get_mut(handle).as_leaf_mut();
            leaf.set_prev(prev);
            leaf.set_next(next);
        }

        let first_leaf = new_leaves.first().copied();
        let last_leaf = new_leaves.last().copied();

        Self {
            nodes: new_nodes,
            values: new_values,
            root: Some(new_root),
            len: self.len,
            first_leaf,
            last_leaf,
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
#[allow(
    clippy::collapsible_if,
    clippy::manual_assert,
    clippy::uninlined_format_args,
    clippy::stable_sort_primitive,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap
)]
mod tests {
    use super::*;
    use alloc::string::String;
    use alloc::vec::Vec;
    use proptest::prelude::*;

    impl<K: Ord + Clone, V> RawOSBTreeMap<K, V> {
        /// Validates all B+Tree invariants. Panics with a descriptive message if any are violated.
        /// This is intended for use in tests to catch tree corruption.
        pub(crate) fn validate_invariants(&self) {
            if self.root.is_none() {
                // Empty tree
                assert_eq!(self.len, 0, "Empty tree should have len 0");
                assert!(self.first_leaf.is_none(), "Empty tree should have no first_leaf");
                assert!(self.last_leaf.is_none(), "Empty tree should have no last_leaf");
                return;
            }

            let root = self.root.unwrap();
            let mut errors: Vec<String> = Vec::new();

            // 1. Validate tree structure and collect all leaves
            let mut all_leaves: Vec<Handle> = Vec::new();
            let mut leaf_depth: Option<usize> = None;
            self.validate_node(root, 0, &mut leaf_depth, &mut all_leaves, &mut errors);

            // 2. Validate leaf chain matches collected leaves
            self.validate_leaf_chain(&all_leaves, &mut errors);

            // 3. Validate len matches actual count
            let actual_count: usize = all_leaves.iter().map(|&h| self.nodes.get(h).as_leaf().key_count()).sum();
            if self.len != actual_count {
                errors.push(alloc::format!("len mismatch: self.len={}, actual count={}", self.len, actual_count));
            }

            // 4. Validate root size equals len (if root is internal)
            if let Node::Internal(internal) = self.nodes.get(root) {
                if internal.size().to_usize() != self.len {
                    let root_size = internal.size().to_usize();
                    let len = self.len;
                    errors.push(alloc::format!("Root size mismatch: root.size={root_size}, self.len={len}"));
                }
            }

            assert!(errors.is_empty(), "Tree invariant violations:\n{}", errors.join("\n"));
        }

        fn validate_node(
            &self,
            handle: Handle,
            depth: usize,
            leaf_depth: &mut Option<usize>,
            all_leaves: &mut Vec<Handle>,
            errors: &mut Vec<String>,
        ) -> (Option<K>, usize) {
            // Returns (max_key, subtree_size)
            let node = self.nodes.get(handle);
            match node {
                Node::Leaf(leaf) => {
                    // Check leaf depth consistency
                    match *leaf_depth {
                        None => *leaf_depth = Some(depth),
                        Some(expected) => {
                            if depth != expected {
                                errors.push(alloc::format!(
                                    "Leaf depth mismatch: expected {}, got {} at handle {:?}",
                                    expected,
                                    depth,
                                    handle
                                ));
                            }
                        }
                    }

                    // Check keys are sorted
                    for i in 1..leaf.key_count() {
                        if leaf.key(i - 1) >= leaf.key(i) {
                            errors.push(alloc::format!(
                                "Leaf keys not sorted at handle {:?}, indices {} and {}",
                                handle,
                                i - 1,
                                i
                            ));
                        }
                    }

                    all_leaves.push(handle);

                    let max_key = leaf.last_key().cloned();
                    (max_key, leaf.key_count())
                }
                Node::Internal(internal) => {
                    // Check keys are sorted
                    for i in 1..internal.key_count() {
                        if internal.key(i - 1) >= internal.key(i) {
                            errors.push(alloc::format!(
                                "Internal keys not sorted at handle {:?}, indices {} and {}",
                                handle,
                                i - 1,
                                i
                            ));
                        }
                    }

                    // Validate children
                    // Note: child_count = key_count + 1 in B+tree
                    // keys[i] = max key of children[i] for i < key_count
                    // children[key_count] is the rightmost child with no corresponding key
                    let mut total_size = 0usize;
                    let mut last_child_max: Option<K> = None;
                    for i in 0..internal.child_count() {
                        let child = internal.child(i);
                        let (child_max, child_size) =
                            self.validate_node(child, depth + 1, leaf_depth, all_leaves, errors);

                        // Check child_size matches stored size
                        let stored_size = internal.child_size(i).to_usize();
                        if stored_size != child_size {
                            errors.push(alloc::format!(
                                "Child size mismatch at handle {:?} child {}: stored={}, actual={}",
                                handle,
                                i,
                                stored_size,
                                child_size
                            ));
                        }
                        total_size += child_size;

                        // Note: We don't strictly validate that separator[i] == max key of child[i]
                        // because after rebalancing operations (borrow/merge), separators may become
                        // "stale" but the tree still works correctly for searches. The important
                        // invariant is that keys are sorted and separators correctly partition
                        // the key space (child[i]'s keys <= separator[i] < child[i+1]'s keys).

                        last_child_max = child_max;
                    }

                    // Check internal node size equals sum of child sizes
                    if internal.size().to_usize() != total_size {
                        errors.push(alloc::format!(
                            "Internal size mismatch at handle {:?}: stored={}, computed={}",
                            handle,
                            internal.size().to_usize(),
                            total_size
                        ));
                    }

                    // The max key of this internal node is the max key of its rightmost child
                    // (last_child_max), or fall back to the last separator key if rightmost child is empty
                    (last_child_max, total_size)
                }
            }
        }

        fn validate_leaf_chain(&self, all_leaves: &[Handle], errors: &mut Vec<String>) {
            if all_leaves.is_empty() {
                if self.first_leaf.is_some() || self.last_leaf.is_some() {
                    errors.push("first_leaf/last_leaf should be None for empty tree".into());
                }
                return;
            }

            // Check first_leaf
            if self.first_leaf != Some(all_leaves[0]) {
                errors.push(alloc::format!(
                    "first_leaf mismatch: expected {:?}, got {:?}",
                    Some(all_leaves[0]),
                    self.first_leaf
                ));
            }

            // Check last_leaf
            if self.last_leaf != Some(*all_leaves.last().unwrap()) {
                errors.push(alloc::format!(
                    "last_leaf mismatch: expected {:?}, got {:?}",
                    all_leaves.last().copied(),
                    self.last_leaf
                ));
            }

            // Check forward chain
            for i in 0..all_leaves.len() {
                let leaf = self.nodes.get(all_leaves[i]).as_leaf();
                let expected_next = if i + 1 < all_leaves.len() {
                    Some(all_leaves[i + 1])
                } else {
                    None
                };
                if leaf.next() != expected_next {
                    errors.push(alloc::format!(
                        "Leaf chain next mismatch at index {}: expected {:?}, got {:?}",
                        i,
                        expected_next,
                        leaf.next()
                    ));
                }
            }

            // Check backward chain
            for i in 0..all_leaves.len() {
                let leaf = self.nodes.get(all_leaves[i]).as_leaf();
                let expected_prev = if i > 0 {
                    Some(all_leaves[i - 1])
                } else {
                    None
                };
                if leaf.prev() != expected_prev {
                    errors.push(alloc::format!(
                        "Leaf chain prev mismatch at index {}: expected {:?}, got {:?}",
                        i,
                        expected_prev,
                        leaf.prev()
                    ));
                }
            }
        }
    }

    // Test operations enum for property testing
    #[derive(Clone, Debug)]
    enum Op {
        Insert(i32),
        Remove(i32),
    }

    fn op_strategy() -> impl Strategy<Value = Op> {
        prop_oneof![
            3 => (0i32..1000).prop_map(Op::Insert),
            1 => (0i32..1000).prop_map(Op::Remove),
        ]
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(50))]

        #[test]
        fn tree_invariants_maintained_after_operations(ops in prop::collection::vec(op_strategy(), 0..500)) {
            let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

            for op in ops {
                match op {
                    Op::Insert(key) => {
                        tree.insert(key, key * 2);
                    }
                    Op::Remove(key) => {
                        tree.remove(&key);
                    }
                }
                tree.validate_invariants();
            }
        }

        #[test]
        fn get_by_rank_correctness(ops in prop::collection::vec((0i32..500).prop_map(Op::Insert), 1..200)) {
            let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
            let mut expected: Vec<i32> = Vec::new();

            for op in ops {
                if let Op::Insert(key) = op {
                    if tree.insert(key, key * 2).is_none() {
                        expected.push(key);
                    }
                }
            }
            expected.sort();

            tree.validate_invariants();

            // Test get_by_rank for all valid ranks
            for (rank, &expected_key) in expected.iter().enumerate() {
                let result = tree.get_by_rank(rank);
                prop_assert!(result.is_some(), "get_by_rank({}) returned None", rank);
                let (key, value) = result.unwrap();
                prop_assert_eq!(*key, expected_key, "get_by_rank({}) returned wrong key", rank);
                prop_assert_eq!(*value, expected_key * 2, "get_by_rank({}) returned wrong value", rank);
            }

            // Test out of bounds
            prop_assert!(tree.get_by_rank(expected.len()).is_none());
        }

        #[test]
        fn rank_of_correctness(ops in prop::collection::vec((0i32..500).prop_map(Op::Insert), 1..200)) {
            let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
            let mut expected: Vec<i32> = Vec::new();

            for op in ops {
                if let Op::Insert(key) = op {
                    if tree.insert(key, key * 2).is_none() {
                        expected.push(key);
                    }
                }
            }
            expected.sort();

            tree.validate_invariants();

            // Test rank_of for all keys
            for (rank, &key) in expected.iter().enumerate() {
                let result = tree.rank_of(&key);
                prop_assert_eq!(result, Some(rank), "rank_of({}) returned wrong rank", key);
            }

            // Test non-existent key
            let max_key = expected.iter().max().copied().unwrap_or(0);
            prop_assert!(tree.rank_of(&(max_key + 1)).is_none());
        }

        #[test]
        fn rank_roundtrip(ops in prop::collection::vec((0i32..500).prop_map(Op::Insert), 1..200)) {
            let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

            for op in ops {
                if let Op::Insert(key) = op {
                    tree.insert(key, key * 2);
                }
            }

            tree.validate_invariants();

            // For every key, rank_of(key) should give a rank where get_by_rank returns the same key
            let mut current = tree.first_leaf;
            while let Some(leaf_handle) = current {
                let leaf = tree.nodes.get(leaf_handle).as_leaf();
                for i in 0..leaf.key_count() {
                    let key = leaf.key(i);
                    let rank = tree.rank_of(key).expect("rank_of should succeed for existing key");
                    let (retrieved_key, _) = tree.get_by_rank(rank).expect("get_by_rank should succeed");
                    prop_assert_eq!(key, retrieved_key, "rank roundtrip failed");
                }
                current = leaf.next();
            }
        }

        #[test]
        fn boundary_rank_operations(count in 1usize..100) {
            let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

            for i in 0..count as i32 {
                tree.insert(i, i * 2);
            }

            tree.validate_invariants();

            // Test Rank(0) - first element
            let (first_key, first_value) = tree.get_by_rank(0).expect("get_by_rank(0) should succeed");
            prop_assert_eq!(*first_key, 0, "First key should be 0");
            prop_assert_eq!(*first_value, 0, "First value should be 0");

            // Test Rank(len-1) - last element
            let last_rank = count - 1;
            let (last_key, last_value) = tree.get_by_rank(last_rank).expect("get_by_rank(last) should succeed");
            prop_assert_eq!(*last_key, (count - 1) as i32, "Last key should be count-1");
            prop_assert_eq!(*last_value, ((count - 1) * 2) as i32, "Last value should be (count-1)*2");

            // Test out of bounds
            prop_assert!(tree.get_by_rank(count).is_none(), "get_by_rank(len) should be None");
            prop_assert!(tree.get_by_rank(count + 100).is_none(), "get_by_rank(len+100) should be None");
        }

        #[test]
        fn interleaved_rank_and_mutations(ops in prop::collection::vec(op_strategy(), 0..300)) {
            let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
            let mut expected: alloc::collections::BTreeMap<i32, i32> = alloc::collections::BTreeMap::new();

            for op in ops {
                match op {
                    Op::Insert(key) => {
                        tree.insert(key, key * 2);
                        expected.insert(key, key * 2);
                    }
                    Op::Remove(key) => {
                        tree.remove(&key);
                        expected.remove(&key);
                    }
                }

                tree.validate_invariants();

                // After each operation, verify rank operations are consistent
                if !expected.is_empty() {
                    let expected_keys: Vec<_> = expected.keys().copied().collect();

                    // Check a few random ranks
                    for rank in [0, expected.len() / 2, expected.len() - 1] {
                        if rank < expected.len() {
                            let (key, _) = tree.get_by_rank(rank).expect("get_by_rank should succeed");
                            prop_assert_eq!(*key, expected_keys[rank], "Key at rank {} mismatch", rank);
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn empty_tree_rank_operations() {
        let tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        tree.validate_invariants();

        assert!(tree.get_by_rank(0).is_none());
        assert!(tree.get_by_rank(100).is_none());
        assert!(tree.rank_of(&0).is_none());
        assert!(tree.rank_of(&100).is_none());
    }

    #[test]
    fn single_element_rank_operations() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        tree.insert(42, 84);
        tree.validate_invariants();

        // get_by_rank
        let (key, value) = tree.get_by_rank(0).expect("should have rank 0");
        assert_eq!(*key, 42);
        assert_eq!(*value, 84);
        assert!(tree.get_by_rank(1).is_none());

        // rank_of
        assert_eq!(tree.rank_of(&42), Some(0));
        assert!(tree.rank_of(&0).is_none());
        assert!(tree.rank_of(&100).is_none());
    }

    #[test]
    fn get_by_rank_mut_modifies_value() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        for i in 0..10 {
            tree.insert(i, i * 2);
        }
        tree.validate_invariants();

        // Modify value at rank 5
        {
            let (key, value) = tree.get_by_rank_mut(5).expect("should have rank 5");
            assert_eq!(*key, 5);
            assert_eq!(*value, 10);
            *value = 999;
        }

        tree.validate_invariants();

        // Verify modification persisted
        let (_, value) = tree.get_by_rank(5).expect("should still have rank 5");
        assert_eq!(*value, 999);

        // Verify other values unchanged
        let (_, value) = tree.get_by_rank(4).expect("should have rank 4");
        assert_eq!(*value, 8);
    }

    #[test]
    fn ranks_stable_after_rebalancing() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

        // Insert enough elements to create multiple levels
        for i in 0..100 {
            tree.insert(i, i * 2);
            tree.validate_invariants();
        }

        // Record all (key, rank) pairs
        let key_ranks: Vec<(i32, usize)> = (0..100).map(|i| (i, tree.rank_of(&i).expect("key should exist"))).collect();

        // Remove some elements (this may trigger rebalancing)
        for i in (0..100).step_by(3) {
            tree.remove(&i);
            tree.validate_invariants();
        }

        // Verify remaining keys have correct relative ordering
        let remaining: Vec<i32> = (0..100).filter(|i| i % 3 != 0).collect();
        for (expected_rank, &key) in remaining.iter().enumerate() {
            let actual_rank = tree.rank_of(&key).expect("remaining key should exist");
            assert_eq!(actual_rank, expected_rank, "Rank of {} should be {}", key, expected_rank);
        }
    }

    #[test]
    fn accessors_and_pointer_helpers_work() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        tree.insert(1, 10);
        tree.insert(2, 20);

        let root = tree.root().expect("root exists after inserts");
        let first_leaf = tree.first_leaf().expect("first leaf exists after inserts");
        let last_leaf = tree.last_leaf().expect("last leaf exists after inserts");
        assert_eq!(first_leaf, last_leaf);

        // Access mutable node reference.
        let leaf_count = tree.node_mut(first_leaf).as_leaf_mut().key_count();
        assert!(leaf_count > 0);

        // SAFETY: `tree_ptr` points to a valid tree and `first_leaf` is a valid handle.
        unsafe {
            let tree_ptr: *const RawOSBTreeMap<i32, i32> = &raw const tree;
            let node = RawOSBTreeMap::node_ptr(tree_ptr, first_leaf);
            assert!(node.is_leaf());
        }

        // Mutate a value through the raw pointer helper.
        let value_handle = tree.node(first_leaf).as_leaf().value(0);
        // SAFETY: `tree_ptr` points to a valid tree and `value_handle` is a valid handle.
        unsafe {
            let tree_ptr: *mut RawOSBTreeMap<i32, i32> = &raw mut tree;
            let value = RawOSBTreeMap::value_mut_ptr(tree_ptr, value_handle);
            *value += 1;
        }
        assert_eq!(tree.get(&1), Some(&11));

        // Root accessor is used in several iterators; ensure it is reachable.
        assert!(tree.node(root).key_count() > 0);
        tree.validate_invariants();
    }

    #[test]
    fn empty_leaf_neighbors_cause_bounds_to_return_none() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        // Use many keys to ensure multiple leaves.
        for i in 0..4000 {
            tree.insert(i * 2, i);
        }
        tree.validate_invariants();

        // Collect the leaf chain.
        let mut leaves: Vec<Handle> = Vec::new();
        let mut current = tree.first_leaf().expect("non-empty tree has a first leaf");
        loop {
            leaves.push(current);
            let leaf = tree.node(current).as_leaf();
            match leaf.next() {
                Some(next) => current = next,
                None => break,
            }
        }
        assert!(leaves.len() >= 5, "expected multiple leaves");

        let mid_index = leaves.len() / 2;
        let mid = leaves[mid_index];
        let prev = leaves[mid_index - 1];
        let next = leaves[mid_index + 1];

        let mid_key = *tree.node(mid).as_leaf().key(0);

        // Create empty neighbors around `mid` to exercise empty-leaf fallbacks.
        let _ = tree.node_mut(prev).as_leaf_mut().take_all();
        let _ = tree.node_mut(mid).as_leaf_mut().take_all();
        let _ = tree.node_mut(next).as_leaf_mut().take_all();

        // With an empty next leaf, lower/upper bounds should return None here.
        assert_eq!(tree.lower_bound(&mid_key), None);
        assert_eq!(tree.upper_bound(&mid_key), None);
        assert_eq!(tree.upper_bound_inclusive(&mid_key), None);
        assert_eq!(tree.lower_bound_exclusive(&mid_key), None);

        // Exercise the early return when the leaf is empty but the path is non-empty.
        let root = tree.root().expect("root exists");
        let mut synthetic_path: Path = SmallVec::new();
        synthetic_path.push(PathElement {
            node: root,
            child_index: 0,
        });
        tree.update_separators_after_remove(mid, &synthetic_path);
    }

    #[test]
    fn update_sizes_helpers_cover_leaf_children() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        for i in 0..64 {
            tree.insert(i, i);
        }
        tree.validate_invariants();

        let root = tree.root().expect("root exists");
        let root_internal = match tree.node(root) {
            Node::Internal(internal) => internal,
            Node::Leaf(_) => panic!("expected internal root for this test"),
        };
        let first_child = root_internal.child(0);
        assert!(matches!(tree.node(first_child), Node::Leaf(_)));

        let mut path: Path = SmallVec::new();
        path.push(PathElement {
            node: root,
            child_index: 0,
        });
        tree.update_sizes_along_path(&path);

        // Use a synthetic duplicate-root path to exercise the ancestor recompute leaf branch.
        let mut duplicate_root_path: Path = SmallVec::new();
        duplicate_root_path.push(PathElement {
            node: root,
            child_index: 0,
        });
        duplicate_root_path.push(PathElement {
            node: root,
            child_index: 0,
        });
        tree.update_sizes_after_remove(first_child, &duplicate_root_path);

        tree.validate_invariants();
    }

    fn make_two_leaf_tree(left_keys: &[i32], right_keys: &[i32]) -> (RawOSBTreeMap<i32, i32>, Handle, Handle, Handle) {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

        let left_handle = tree.nodes.alloc(Node::new_leaf());
        let right_handle = tree.nodes.alloc(Node::new_leaf());

        for &key in left_keys {
            let value_handle = tree.values.alloc(key * 10);
            tree.nodes.get_mut(left_handle).as_leaf_mut().push(key, value_handle);
        }
        for &key in right_keys {
            let value_handle = tree.values.alloc(key * 10);
            tree.nodes.get_mut(right_handle).as_leaf_mut().push(key, value_handle);
        }

        tree.nodes.get_mut(left_handle).as_leaf_mut().set_next(Some(right_handle));
        tree.nodes.get_mut(right_handle).as_leaf_mut().set_prev(Some(left_handle));

        let root_handle = tree.nodes.alloc(Node::new_internal());
        {
            let root = tree.nodes.get_mut(root_handle).as_internal_mut();
            root.set_first_child(left_handle, Size::from_usize(left_keys.len()));
            root.push_child(
                *left_keys.last().expect("left leaf must be non-empty"),
                right_handle,
                Size::from_usize(right_keys.len()),
            );
            root.update_size();
        }

        tree.root = Some(root_handle);
        tree.first_leaf = Some(left_handle);
        tree.last_leaf = Some(right_handle);
        tree.len = left_keys.len() + right_keys.len();

        (tree, root_handle, left_handle, right_handle)
    }

    #[test]
    fn take_value_and_empty_first_last_leaf_return_none() {
        // Cover the take_value accessor using a valid value handle.
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        tree.insert(1, 10);
        let leaf = tree.first_leaf().expect("leaf exists");
        let value_handle = tree.node(leaf).as_leaf().value(0);
        let taken = tree.take_value(value_handle);
        assert_eq!(taken, 10);

        // Create multiple leaves, then empty the first and last leaves while keeping their handles.
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        for i in 0..400 {
            tree.insert(i * 2, i);
        }

        let first = tree.first_leaf().expect("first leaf exists");
        let last = tree.last_leaf().expect("last leaf exists");
        let _ = tree.node_mut(first).as_leaf_mut().take_all();
        let _ = tree.node_mut(last).as_leaf_mut().take_all();

        assert_eq!(tree.first_key_value(), None);
        assert_eq!(tree.last_key_value(), None);
    }

    #[test]
    fn bounds_fallback_to_next_leaf_with_stale_separator() {
        let (mut tree, root_handle, _left, right) = make_two_leaf_tree(&[0, 2, 4], &[6, 8, 10]);

        // Make the separator far too large so search_child can choose the left leaf incorrectly.
        tree.nodes.get_mut(root_handle).as_internal_mut().set_key(0, i32::MAX);

        assert_eq!(tree.lower_bound(&7), Some((right, 0)));
        assert_eq!(tree.upper_bound(&7), Some((right, 0)));
        assert_eq!(tree.upper_bound(&4), Some((right, 0)));
    }

    #[test]
    fn lower_bound_exclusive_uses_previous_leaf_on_boundary() {
        let (tree, _root, left, _right) = make_two_leaf_tree(&[0, 2, 4], &[6, 8, 10]);
        tree.validate_invariants();

        // Exact boundary: key is the first key of the right leaf.
        assert_eq!(tree.lower_bound_exclusive(&6), Some((left, 2)));
        // Between leaves: not found in right leaf at index 0, so we step to the previous leaf.
        assert_eq!(tree.lower_bound_exclusive(&5), Some((left, 2)));
    }

    #[test]
    fn upper_bound_returns_none_when_next_leaf_is_empty() {
        let (mut tree, _root, _left, right) = make_two_leaf_tree(&[0, 2, 4], &[6, 8, 10]);
        let _ = tree.node_mut(right).as_leaf_mut().take_all();

        // Found at the last index with an empty next leaf should return None.
        assert_eq!(tree.upper_bound(&4), None);
    }

    #[test]
    fn lower_bound_exclusive_returns_none_when_prev_leaf_is_empty() {
        let (mut tree, _root, left, _right) = make_two_leaf_tree(&[0, 2, 4], &[6, 8, 10]);
        let _ = tree.node_mut(left).as_leaf_mut().take_all();

        // Found at index 0 with an empty previous leaf should return None.
        assert_eq!(tree.lower_bound_exclusive(&6), None);
    }

    #[test]
    fn upper_bound_returns_none_on_last_key_without_next_leaf() {
        let (tree, _root, _left, _right) = make_two_leaf_tree(&[0, 2, 4], &[6, 8, 10]);
        assert_eq!(tree.upper_bound(&10), None);
    }

    #[test]
    fn lower_bound_exclusive_returns_none_on_first_key_without_prev_leaf() {
        let (tree, _root, _left, _right) = make_two_leaf_tree(&[0, 2, 4], &[6, 8, 10]);
        assert_eq!(tree.lower_bound_exclusive(&0), None);
    }

    #[test]
    fn remove_from_parent_updates_sizes_when_path_child_is_leaf() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

        let leaf_count = crate::raw::node::MIN_INTERNAL_KEYS + 3;
        let mut leaves: Vec<Handle> = Vec::with_capacity(leaf_count);
        for i in 0..leaf_count {
            let handle = tree.nodes.alloc(Node::new_leaf());
            let key = (i as i32) * 2;
            let value_handle = tree.values.alloc(key * 10);
            tree.nodes.get_mut(handle).as_leaf_mut().push(key, value_handle);
            leaves.push(handle);
        }

        for (i, &handle) in leaves.iter().enumerate() {
            let prev = i.checked_sub(1).and_then(|j| leaves.get(j).copied());
            let next = leaves.get(i + 1).copied();
            let leaf = tree.nodes.get_mut(handle).as_leaf_mut();
            leaf.set_prev(prev);
            leaf.set_next(next);
        }

        let bottom_handle = tree.nodes.alloc(Node::new_internal());
        {
            let bottom = tree.nodes.get_mut(bottom_handle).as_internal_mut();
            bottom.set_first_child(leaves[0], Size::from_usize(1));
            for (i, &child) in leaves.iter().enumerate().skip(1) {
                let sep_key = ((i - 1) as i32) * 2;
                bottom.push_child(sep_key, child, Size::from_usize(1));
            }
            bottom.update_size();
        }

        let root_handle = tree.nodes.alloc(Node::new_internal());
        {
            let bottom_size = tree.nodes.get(bottom_handle).as_internal().size();
            let root = tree.nodes.get_mut(root_handle).as_internal_mut();
            root.set_first_child(bottom_handle, bottom_size);
            root.update_size();
        }

        tree.root = Some(root_handle);
        tree.first_leaf = Some(leaves[0]);
        tree.last_leaf = Some(leaves[leaf_count - 1]);
        tree.len = leaf_count;

        // Use a duplicate bottom element so the remaining path includes an internal whose child is a leaf.
        let mut path: Path = SmallVec::new();
        path.push(PathElement {
            node: root_handle,
            child_index: 0,
        });
        path.push(PathElement {
            node: bottom_handle,
            child_index: 0,
        });
        path.push(PathElement {
            node: bottom_handle,
            child_index: 0,
        });

        tree.remove_from_parent_and_propagate(&mut path, 1);

        let bottom_size = tree.nodes.get(bottom_handle).as_internal().size();
        let root_child_size = tree.nodes.get(root_handle).as_internal().child_size(0);
        assert_eq!(root_child_size, bottom_size);
    }

    #[test]
    fn merge_leaves_updates_first_leaf_when_right_was_first() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

        let left_handle = tree.nodes.alloc(Node::new_leaf());
        let right_handle = tree.nodes.alloc(Node::new_leaf());

        let left_value = tree.values.alloc(10);
        let right_value = tree.values.alloc(20);
        tree.nodes.get_mut(left_handle).as_leaf_mut().push(1, left_value);
        tree.nodes.get_mut(right_handle).as_leaf_mut().push(2, right_value);
        tree.nodes.get_mut(left_handle).as_leaf_mut().set_next(Some(right_handle));
        tree.nodes.get_mut(right_handle).as_leaf_mut().set_prev(Some(left_handle));

        let parent_handle = tree.nodes.alloc(Node::new_internal());
        {
            let parent = tree.nodes.get_mut(parent_handle).as_internal_mut();
            parent.set_first_child(left_handle, Size::from_usize(1));
            parent.push_child(1, right_handle, Size::from_usize(1));
            parent.update_size();
        }

        tree.root = Some(parent_handle);
        // Intentionally point first/last at the right leaf to exercise the update branches.
        tree.first_leaf = Some(right_handle);
        tree.last_leaf = Some(right_handle);
        tree.len = 2;

        let mut path: Path = SmallVec::new();
        path.push(PathElement {
            node: parent_handle,
            child_index: 0,
        });

        tree.merge_leaves(left_handle, right_handle, &mut path, 0);

        assert_eq!(tree.first_leaf, Some(left_handle));
        assert_eq!(tree.last_leaf, Some(left_handle));
        tree.validate_invariants();
    }

    #[test]
    #[should_panic(expected = "get_by_rank: tree size invariant violated")]
    fn get_by_rank_panics_when_internal_sizes_are_inconsistent() {
        let (mut tree, root_handle, _left, _right) = make_two_leaf_tree(&[0, 2], &[4, 6]);
        {
            let root = tree.nodes.get_mut(root_handle).as_internal_mut();
            root.set_size(Size::from_usize(5));
        }
        tree.len = 5;

        let _ = tree.get_by_rank(4);
    }

    #[test]
    #[should_panic(expected = "get_by_rank_mut: tree size invariant violated")]
    fn get_by_rank_mut_panics_when_internal_sizes_are_inconsistent() {
        let (mut tree, root_handle, _left, _right) = make_two_leaf_tree(&[0, 2], &[4, 6]);
        {
            let root = tree.nodes.get_mut(root_handle).as_internal_mut();
            root.set_size(Size::from_usize(5));
        }
        tree.len = 5;

        let _ = tree.get_by_rank_mut(4);
    }

    #[test]
    #[should_panic(expected = "expected leaf")]
    fn merge_leaves_panics_on_internal_right() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();
        tree.insert(1, 1);

        let left_leaf = tree.first_leaf().expect("leaf exists");
        let internal_handle = tree.nodes.alloc(Node::Internal(InternalNode::new()));
        let mut path: Path = SmallVec::new();
        tree.merge_leaves(left_leaf, internal_handle, &mut path, 0);
    }

    #[test]
    #[should_panic(expected = "expected internal")]
    fn merge_internals_panics_on_leaf_right() {
        let mut tree: RawOSBTreeMap<i32, i32> = RawOSBTreeMap::new();

        let parent_handle = tree.nodes.alloc(Node::Internal(InternalNode::new()));
        let left_handle = tree.nodes.alloc(Node::Internal(InternalNode::new()));
        let right_leaf_handle = tree.nodes.alloc(Node::Leaf(LeafNode::new()));

        {
            let parent = tree.nodes.get_mut(parent_handle).as_internal_mut();
            parent.set_first_child(left_handle, Size::from_usize(0));
            parent.push_child(1, right_leaf_handle, Size::from_usize(0));
        }

        let mut path: Path = SmallVec::new();
        path.push(PathElement {
            node: parent_handle,
            child_index: 0,
        });

        tree.merge_internals(left_handle, right_leaf_handle, &mut path, 0);
    }
}