stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Copy-on-Write B-tree for i64 keys
//!
//! Design:
//! - Each node is wrapped in CompactArc (8 bytes) for memory management
//! - Nodes maintain their own `drop_count` (AtomicU32) for thread-safe V drops
//! - Readers clone the root (atomic, ~1ns) and traverse without locks
//! - Writers check `drop_count` and deep-clone only if shared (COW)
//! - Structural sharing: unmodified subtrees are shared between versions
//!
//! Thread safety:
//! - `drop_count` uses atomic fetch_sub to coordinate drops across threads
//! - Exactly one thread (whoever sees old_count=1) drops V values
//! - This avoids race conditions that could cause memory leaks
//!
//! Performance characteristics:
//! - Reads: O(log n), completely lock-free
//! - Writes: O(log n) + O(B) per modified node for COW
//! - Clone: O(1) - just increments reference counts
//! - Memory: Shared nodes between snapshots

use super::CompactArc;
use std::marker::PhantomData;
use std::mem;
use std::ops::Bound;
use std::ptr;
use std::sync::atomic::{AtomicU32, Ordering};

/// Maximum keys per node. Smaller = more nodes but faster COW.
/// 128 gives good balance for database workloads.
///
/// CONSTRAINT: MAX_KEYS <= 255 because NodePath uses u8 for child indices.
/// Internal nodes have MAX_KEYS + 1 children, so index can be at most MAX_KEYS.
const MAX_KEYS: usize = 128;

// Compile-time assertion: MAX_KEYS must fit in u8 (NodePath uses [u8; MAX_TREE_DEPTH])
const _: () = assert!(
    MAX_KEYS <= 255,
    "MAX_KEYS must be <= 255 (NodePath uses u8 indices)"
);

/// Minimum keys per node (except root).
/// Must satisfy: 2 * MIN_KEYS + 1 <= MAX_KEYS (merge invariant).
const MIN_KEYS: usize = (MAX_KEYS - 1) / 2;

/// Header: 8 bytes
/// [ len (u16) | is_leaf (u8) | pad (1) | drop_count (4) ]
///
/// `drop_count` is a separate refcount that coordinates dropping V values.
/// This fixes a race condition where multiple threads could skip dropping
/// V values when relying solely on CompactArc's is_unique() check.
#[repr(C)]
struct NodeHeader {
    len: u16,
    is_leaf: u8,
    _pad1: u8,
    /// Refcount for coordinating V/children drops.
    /// Decremented atomically in NodePtr::drop; whoever sees old_count=1 drops contents.
    /// Using U32 to support up to ~4 billion concurrent snapshots.
    drop_count: AtomicU32,
}

/// A Ref-counted pointer to a Byte-Packed Node.
/// Memory Layout: [ Header | Keys (MAX_KEYS) | Values/Children ]
/// One contiguous allocation.
pub struct NodePtr<V: Clone> {
    ptr: CompactArc<[u8]>,
    _marker: PhantomData<V>,
}

impl<V: Clone> Clone for NodePtr<V> {
    fn clone(&self) -> Self {
        // Clone CompactArc first (keeps memory alive), then increment drop_count.
        // This ordering ensures drop_count is only incremented after the clone succeeds.
        let new_ptr = self.ptr.clone();

        // SAFETY: ptr points to a valid CompactArc allocation that starts with NodeHeader.
        // The header is read-only here (only accessing drop_count atomically).
        let header = unsafe { &*(self.ptr.data_ptr_mut() as *const NodeHeader) };
        header.drop_count.fetch_add(1, Ordering::Relaxed);

        Self {
            ptr: new_ptr,
            _marker: PhantomData,
        }
    }
}

impl<V: Clone> Drop for NodePtr<V> {
    fn drop(&mut self) {
        // Atomically decrement drop_count and check if we're the last reference.
        // This fixes a race condition where multiple threads using is_unique()
        // could all see refcount > 1 and skip dropping V values.
        //
        // With atomic fetch_sub, exactly one thread will see old_count == 1
        // and that thread is responsible for dropping the contents.
        // SAFETY: ptr points to a valid CompactArc allocation that starts with NodeHeader.
        let header = unsafe { &*(self.ptr.data_ptr_mut() as *const NodeHeader) };
        let old_count = header.drop_count.fetch_sub(1, Ordering::AcqRel);

        if old_count != 1 {
            // Not the last reference - don't drop contents
            return;
        }

        // We're the last reference - drop contents
        let len = self.len();
        if self.is_leaf() {
            // Drop values in valid range
            // SAFETY: We are the last reference (old_count == 1). The values at indices
            // 0..len are valid initialized V instances. After dropping, we don't access them.
            unsafe {
                let v_ptr = self.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
                for i in 0..len {
                    ptr::drop_in_place(v_ptr.add(i));
                }
            }
        } else {
            // Drop children (keys count + 1)
            // SAFETY: We are the last reference (old_count == 1). The children at indices
            // 0..=len are valid NodePtr instances. After dropping, we don't access them.
            unsafe {
                let c_ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
                for i in 0..=len {
                    ptr::drop_in_place(c_ptr.add(i));
                }
            }
        }
    }
}

impl<V: Clone> NodePtr<V> {
    /// Keys start immediately after the header
    const fn keys_offset() -> usize {
        mem::size_of::<NodeHeader>()
    }

    /// Offset to values array (leaf nodes only).
    /// Same as `children_offset` - this is union-style memory sharing:
    /// leaf nodes store values here, internal nodes store children here.
    /// A node is either leaf OR internal, never both.
    const fn values_offset() -> usize {
        Self::keys_offset() + ((MAX_KEYS + 1) * 8)
    }

    /// Offset to children array (internal nodes only).
    /// Same as `values_offset` - see comment above.
    const fn children_offset() -> usize {
        Self::keys_offset() + ((MAX_KEYS + 1) * 8)
    }

    fn new_leaf() -> Self {
        let size = Self::values_offset() + ((MAX_KEYS + 1) * mem::size_of::<V>());
        let vec = vec![0u8; size];

        let mut ptr = NodePtr {
            ptr: CompactArc::from_vec(vec),
            _marker: PhantomData,
        };

        let header = ptr.header_mut();
        header.len = 0;
        header.is_leaf = 1;
        header.drop_count = AtomicU32::new(1);

        ptr
    }

    fn new_internal() -> Self {
        let size = Self::children_offset() + ((MAX_KEYS + 2) * mem::size_of::<NodePtr<V>>());
        let vec = vec![0u8; size];

        let mut ptr = NodePtr {
            ptr: CompactArc::from_vec(vec),
            _marker: PhantomData,
        };

        let header = ptr.header_mut();
        header.len = 0;
        header.is_leaf = 0;
        header.drop_count = AtomicU32::new(1);

        ptr
    }

    fn make_mut(&mut self) -> &mut Self {
        // Check if this node is shared using our own drop_count.
        // If drop_count > 1, we need to deep clone to maintain COW semantics.
        // SAFETY: ptr points to a valid CompactArc allocation that starts with NodeHeader.
        let header = unsafe { &*(self.ptr.data_ptr_mut() as *const NodeHeader) };
        if header.drop_count.load(Ordering::Acquire) != 1 {
            // Shared - need proper deep clone (not just byte copy!)
            // Byte copy would cause double-free for non-Copy value types
            *self = self.deep_clone();
        }
        self
    }

    /// Create a deep clone of this node.
    /// For leaf nodes: clones all values using V::clone()
    /// For internal nodes: clones all children (incrementing their refcounts)
    fn deep_clone(&self) -> Self {
        let len = self.len();

        if self.is_leaf() {
            let mut new_node = NodePtr::new_leaf();
            // Do NOT set len yet to ensure exception safety!
            // If V::clone() panics, new_node.drop() will only drop 0 elements.

            // Copy keys (i64 is Copy, byte copy is fine)
            // SAFETY: Both src and dst are valid pointers within their respective node allocations.
            // Keys are i64 (Copy type), so byte copy is safe. len <= MAX_KEYS.
            unsafe {
                let k_src = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *const i64;
                let k_dst = new_node.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
                ptr::copy_nonoverlapping(k_src, k_dst, len);
            }

            // Clone values using V::clone() - critical for non-Copy types!
            // SAFETY: v_src points to len valid V instances. v_dst points to uninitialized memory.
            // We use ptr::write to initialize each slot, and increment len after each successful
            // clone to maintain exception safety (if clone panics, only initialized values are dropped).
            unsafe {
                let v_src = self.ptr.data_ptr_mut().add(Self::values_offset()) as *const V;
                let v_dst = new_node.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
                for i in 0..len {
                    ptr::write(v_dst.add(i), (*v_src.add(i)).clone());
                    // Increment len after successful write/clone
                    // If clone panics on next iteration, this node will correctly drop 'i' elements
                    new_node.set_len(i + 1);
                }
            }

            new_node
        } else {
            let mut new_node = NodePtr::new_internal();
            new_node.set_len(len);

            // Copy keys (i64 is Copy)
            // SAFETY: Both src and dst are valid pointers within their respective node allocations.
            // Keys are i64 (Copy type), so byte copy is safe. len <= MAX_KEYS.
            unsafe {
                let k_src = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *const i64;
                let k_dst = new_node.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
                ptr::copy_nonoverlapping(k_src, k_dst, len);
            }

            // Clone children (NodePtr::clone increments CompactArc refcount)
            // NodePtr::clone cannot panic, so strict exception safety sequence not needed here,
            // but setting len upfront is fine.
            // SAFETY: c_src points to len+1 valid NodePtr instances. c_dst points to uninitialized memory.
            // NodePtr::clone only does atomic operations and cannot panic.
            unsafe {
                let c_src =
                    self.ptr.data_ptr_mut().add(Self::children_offset()) as *const NodePtr<V>;
                let c_dst =
                    new_node.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
                for i in 0..=len {
                    // children count = keys count + 1
                    ptr::write(c_dst.add(i), (*c_src.add(i)).clone());
                }
            }

            new_node
        }
    }

    fn header(&self) -> &NodeHeader {
        // SAFETY: ptr points to a valid CompactArc allocation that starts with NodeHeader.
        // Use data_ptr_mut() to bypass Deref and avoid Stacked Borrows conflicts.
        unsafe { &*(self.ptr.data_ptr_mut() as *const NodeHeader) }
    }

    fn header_mut(&mut self) -> &mut NodeHeader {
        // Assumes we have unique access (called make_mut)
        // SAFETY: ptr points to a valid CompactArc allocation. Caller guarantees unique access.
        // Use data_ptr_mut() to bypass Deref and avoid Stacked Borrows conflicts:
        // going through <[u8]>::as_ptr() would create a SharedReadOnly tag that
        // prevents the &mut cast needed here.
        unsafe { &mut *(self.ptr.data_ptr_mut() as *mut NodeHeader) }
    }

    fn is_leaf(&self) -> bool {
        self.header().is_leaf == 1
    }

    fn len(&self) -> usize {
        self.header().len as usize
    }

    fn set_len(&mut self, len: usize) {
        self.header_mut().len = len as u16;
    }

    fn keys(&self) -> &[i64] {
        let len = self.len();
        // SAFETY: ptr + keys_offset points to an array of len initialized i64 keys.
        // The slice lifetime is tied to &self, ensuring validity.
        unsafe {
            let ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *const i64;
            std::slice::from_raw_parts(ptr, len)
        }
    }

    fn values(&self) -> &[V] {
        assert!(self.is_leaf());
        let len = self.len();
        // SAFETY: This is a leaf node (asserted). ptr + values_offset points to
        // an array of len initialized V values. The slice lifetime is tied to &self.
        unsafe {
            let ptr = self.ptr.data_ptr_mut().add(Self::values_offset()) as *const V;
            std::slice::from_raw_parts(ptr, len)
        }
    }

    fn values_mut_slice(&mut self) -> &mut [V] {
        assert!(self.is_leaf());
        let len = self.len();
        // SAFETY: This is a leaf node (asserted). ptr + values_offset points to
        // an array of len initialized V values. Caller has &mut self, ensuring unique access.
        unsafe {
            let ptr = self.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
            std::slice::from_raw_parts_mut(ptr, len)
        }
    }

    fn children(&self) -> &[NodePtr<V>] {
        assert!(!self.is_leaf());
        let len = self.len() + 1; // Children = keys + 1
                                  // SAFETY: This is an internal node (asserted). ptr + children_offset points to
                                  // an array of len initialized NodePtr children. The slice lifetime is tied to &self.
        unsafe {
            let ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *const NodePtr<V>;
            std::slice::from_raw_parts(ptr, len)
        }
    }

    fn children_mut_slice(&mut self) -> &mut [NodePtr<V>] {
        assert!(!self.is_leaf());
        let len = self.len() + 1;
        // SAFETY: This is an internal node (asserted). ptr + children_offset points to
        // an array of len initialized NodePtr children. Caller has &mut self, ensuring unique access.
        unsafe {
            let ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            std::slice::from_raw_parts_mut(ptr, len)
        }
    }

    fn child(&self, index: usize) -> &NodePtr<V> {
        &self.children()[index]
    }

    fn child_mut(&mut self, index: usize) -> &mut NodePtr<V> {
        &mut self.children_mut_slice()[index]
    }

    fn search(&self, key: i64) -> Result<usize, usize> {
        self.keys().binary_search(&key)
    }

    fn push_leaf(&mut self, key: i64, value: V) {
        assert!(self.is_leaf());
        let len = self.len();
        assert!(len <= MAX_KEYS); // Allow temporary overflow

        // SAFETY: This is a leaf node (asserted). len <= MAX_KEYS, so index len is within
        // the allocated array bounds (size MAX_KEYS + 1). We write to uninitialized slots.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::write(k_ptr.add(len), key);

            let v_ptr = self.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
            ptr::write(v_ptr.add(len), value);
        }
        self.set_len(len + 1);
    }

    fn remove_leaf(&mut self, index: usize) -> V {
        assert!(self.is_leaf());
        let len = self.len();
        assert!(index < len);

        // SAFETY: This is a leaf node (asserted). index < len, so all accesses are in bounds.
        // We read the value at index (moving it out), then shift remaining elements left.
        // The last position becomes logically invalid and is excluded by set_len.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::copy(k_ptr.add(index + 1), k_ptr.add(index), len - index - 1);

            let v_ptr = self.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
            let val = ptr::read(v_ptr.add(index));
            ptr::copy(v_ptr.add(index + 1), v_ptr.add(index), len - index - 1);

            self.set_len(len - 1);
            val
        }
    }

    fn insert_leaf(&mut self, index: usize, key: i64, value: V) {
        assert!(self.is_leaf());
        let len = self.len();
        assert!(len <= MAX_KEYS);
        assert!(
            index <= len,
            "insert_leaf: index {} > len {} for key {}",
            index,
            len,
            key
        );

        // SAFETY: This is a leaf node (asserted). len <= MAX_KEYS, so we have room for one more.
        // We shift elements at [index..len] to [index+1..len+1], then write the new key/value at index.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            let p_key = k_ptr.add(index);
            ptr::copy(p_key, p_key.add(1), len - index);
            ptr::write(p_key, key);

            let v_ptr = self.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
            let p_val = v_ptr.add(index);
            ptr::copy(p_val, p_val.add(1), len - index);
            ptr::write(p_val, value);
        }
        self.set_len(len + 1);
    }

    fn push_internal(&mut self, key: i64, child: NodePtr<V>) {
        assert!(!self.is_leaf());
        let len = self.len();
        assert!(len <= MAX_KEYS);

        // SAFETY: This is an internal node (asserted). len <= MAX_KEYS, so indices len (for key)
        // and len+1 (for child) are within allocated bounds. We write to uninitialized slots.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::write(k_ptr.add(len), key);

            let c_ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            ptr::write(c_ptr.add(len + 1), child);
        }
        self.set_len(len + 1);
    }

    fn split_internal(&mut self) -> (i64, NodePtr<V>) {
        let len = self.len();
        let mid = len / 2;
        let med_key = self.keys()[mid];
        let mut right = NodePtr::new_internal();
        let right_keys_count = len - mid - 1;
        let right_children_count = right_keys_count + 1;

        // SAFETY: Both self and right are internal nodes. We copy keys from indices [mid+1..len)
        // and children from indices [mid+1..len+1) of self into the start of right. The source
        // and destination do not overlap (different allocations). Keys are Copy (i64). Children
        // (NodePtr<V>) are bitwise copied - this is safe because we set self.len = mid afterwards,
        // so those slots become logically uninitialized (won't be dropped when self is dropped).
        unsafe {
            let k_src = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            let k_dst = right.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::copy_nonoverlapping(k_src.add(mid + 1), k_dst, right_keys_count);

            let c_src = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            let c_dst = right.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            ptr::copy_nonoverlapping(c_src.add(mid + 1), c_dst, right_children_count);
        }

        right.set_len(right_keys_count);
        self.set_len(mid);
        (med_key, right)
    }

    /// Optimized split for rightmost (sequential) inserts on internal nodes.
    /// Keeps MAX_KEYS keys in left node, moves only the last child to right.
    /// The median key (last key) goes to parent. Right node has 0 keys, 1 child.
    fn split_internal_rightmost(&mut self) -> (i64, NodePtr<V>) {
        let len = self.len();
        debug_assert!(
            len == MAX_KEYS + 1,
            "split_internal_rightmost expects overflow node"
        );

        // Median is the last key - it goes to parent
        let med_key = self.keys()[len - 1];

        let mut right = NodePtr::new_internal();

        // SAFETY: self is an internal node with MAX_KEYS + 1 keys (MAX_KEYS + 2 children).
        // We move only the last child to right. Children are moved via ptr::read then ptr::write.
        // After set_len(len-1), the source slots are logically uninitialized.
        unsafe {
            let c_src = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            let c_dst = right.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;

            // Move last child (index len, since we have len+1 children)
            ptr::write(c_dst, ptr::read(c_src.add(len)));
        }

        right.set_len(0); // 0 keys, but 1 child
        self.set_len(len - 1); // MAX_KEYS keys, MAX_KEYS + 1 children

        (med_key, right)
    }

    fn borrow_from_left(&mut self, index: usize) {
        assert!(!self.is_leaf());
        let is_left_leaf = self.child(index - 1).is_leaf();

        if is_left_leaf {
            let (key, val) = {
                let left = self.child_mut(index - 1).make_mut();
                let left_len = left.len();
                let key = left.keys()[left_len - 1];
                // SAFETY: left is a leaf node (verified by is_left_leaf). left_len > 0 because
                // we only borrow from siblings with spare keys. Index left_len - 1 is valid.
                // We move the value out via ptr::read, then set_len(left_len - 1) marks it
                // as logically removed so it won't be double-dropped.
                let val = unsafe {
                    let val_ptr = left.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
                    ptr::read(val_ptr.add(left_len - 1))
                };
                left.set_len(left_len - 1);
                (key, val)
            };

            let current = self.child_mut(index).make_mut();
            current.insert_leaf(0, key, val);

            // SAFETY: self is an internal node (asserted). index > 0 (we're borrowing from left).
            // index - 1 is a valid key index in self (parent of left and current).
            // Writing i64 which is Copy, overwriting existing separator key.
            unsafe {
                let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
                ptr::write(k_ptr.add(index - 1), key);
            }
        } else {
            let (child, key) = {
                let left = self.child_mut(index - 1).make_mut();
                let left_len = left.len();
                let key = left.keys()[left_len - 1];
                // SAFETY: left is an internal node (is_left_leaf is false). left_len > 0.
                // Index left_len is valid for children array (internal nodes have len+1 children).
                // We move the child out via ptr::read, then set_len(left_len - 1) ensures it
                // won't be double-dropped.
                let child = unsafe {
                    let c_ptr =
                        left.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
                    ptr::read(c_ptr.add(left_len))
                };
                left.set_len(left_len - 1);
                (child, key)
            };

            let separator_idx = index - 1;
            let separator = self.keys()[separator_idx];

            let current = self.child_mut(index).make_mut();
            current.insert_internal_at_start(separator, child);

            // SAFETY: self is an internal node (asserted). separator_idx is valid key index.
            // Writing i64 which is Copy, overwriting existing separator key.
            unsafe {
                let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
                ptr::write(k_ptr.add(separator_idx), key);
            }
        }
    }

    fn insert_internal(&mut self, index: usize, key: i64, child: NodePtr<V>) {
        assert!(!self.is_leaf());
        let len = self.len();
        assert!(len <= MAX_KEYS);

        // SAFETY: This is an internal node (asserted). len <= MAX_KEYS, so there's space.
        // index <= len. We shift keys [index..len) right by 1 to make room, then write key
        // at index. We shift children [index+1..len+1) right by 1, then write new child at
        // index+1. ptr::copy handles overlapping regions correctly. Keys are Copy (i64).
        // The new child is moved in (not cloned) via ptr::write.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::copy(k_ptr.add(index), k_ptr.add(index + 1), len - index);
            ptr::write(k_ptr.add(index), key);

            let c_ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            ptr::copy(c_ptr.add(index + 1), c_ptr.add(index + 2), len - index);
            ptr::write(c_ptr.add(index + 1), child);
        }
        self.set_len(len + 1);
    }

    fn insert_internal_at_start(&mut self, key: i64, child: NodePtr<V>) {
        let len = self.len();
        // SAFETY: This is an internal node (only called from internal node contexts).
        // We shift all keys [0..len) right by 1 and write new key at index 0.
        // We shift all children [0..len+1) right by 1 and write new child at index 0.
        // ptr::copy handles overlapping regions correctly. Keys are Copy (i64).
        // The new child is moved in via ptr::write. len + 1 <= MAX_KEYS + 1 by B-tree invariants.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::copy(k_ptr, k_ptr.add(1), len);
            ptr::write(k_ptr, key);

            let c_ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            ptr::copy(c_ptr, c_ptr.add(1), len + 1);
            ptr::write(c_ptr, child);
        }
        self.set_len(len + 1);
    }

    fn borrow_from_right(&mut self, index: usize) {
        assert!(!self.is_leaf());
        let is_right_leaf = self.child(index + 1).is_leaf();

        if is_right_leaf {
            let (key, val) = {
                let right = self.child_mut(index + 1).make_mut();
                let key = right.keys()[0];
                let val = right.remove_leaf(0);
                (key, val)
            };

            let current = self.child_mut(index).make_mut();
            current.push_leaf(key, val);

            let right = self.child(index + 1);
            let new_sep = right.keys()[0];
            // SAFETY: self is an internal node (asserted). index is valid key index in self
            // (it's the separator between children at index and index+1).
            // Writing i64 which is Copy, overwriting existing separator key.
            unsafe {
                let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
                ptr::write(k_ptr.add(index), new_sep);
            }
        } else {
            let (child, key) = {
                let right = self.child_mut(index + 1).make_mut();
                let key = right.keys()[0];
                // SAFETY: right is an internal node (is_right_leaf is false). right.len() > 0.
                // Index 0 is valid for children array. We move the first child out via ptr::read,
                // then remove_internal_at_start() shifts remaining elements left and decrements len.
                let child = unsafe {
                    let c_ptr =
                        right.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
                    ptr::read(c_ptr)
                };
                right.remove_internal_at_start();
                (child, key)
            };

            let separator = self.keys()[index];

            let current = self.child_mut(index).make_mut();
            current.push_internal(separator, child);

            // SAFETY: self is an internal node (asserted). index is valid key index.
            // Writing i64 which is Copy, overwriting existing separator key.
            unsafe {
                let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
                ptr::write(k_ptr.add(index), key);
            }
        }
    }

    fn remove_internal_at_start(&mut self) {
        let len = self.len();
        // SAFETY: This is an internal node (only called from internal node contexts). len > 0.
        // We shift keys [1..len) left by 1 (overwriting key at index 0).
        // We shift children [1..len+1) left by 1 (overwriting child at index 0, which was
        // already moved out by caller via ptr::read). Keys are Copy (i64). Children are
        // bitwise copied (ptr::copy handles overlap correctly). The child at the end becomes
        // logically uninitialized after set_len decrements the count.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::copy(k_ptr.add(1), k_ptr, len - 1);

            let c_ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            ptr::copy(c_ptr.add(1), c_ptr, len);
        }
        self.set_len(len - 1);
    }

    fn merge_with_left(&mut self, index: usize) {
        let separator = self.keys()[index - 1];

        // Make right uniquely owned so we can move data out of it
        let right_raw = self.child_mut(index) as *mut NodePtr<V>;
        // SAFETY: right_raw points to a valid NodePtr<V> in self's children array at index.
        // We need a raw pointer here to avoid borrow checker issues: we'll access left sibling
        // later, but Rust sees child_mut(index) and child_mut(index-1) as conflicting borrows.
        // The raw pointer lets us work around this while maintaining actual safety since we
        // only access right through right_raw, and later access left through child_mut.
        let right = unsafe { (*right_raw).make_mut() };
        let is_leaf = right.is_leaf();
        let r_len = right.len();

        if is_leaf {
            // Move keys and values out of right using ptr::read (no clone!)
            let mut keys_vals: Vec<(i64, V)> = Vec::with_capacity(r_len);
            // SAFETY: right is a leaf node (verified by is_leaf). We read all keys and values
            // from indices [0..r_len). Keys are Copy (i64). Values are moved via ptr::read.
            // We set_len(0) immediately after to mark them as logically removed, preventing
            // double-free when right's NodePtr is eventually dropped.
            unsafe {
                let k_ptr = right.ptr.data_ptr_mut().add(Self::keys_offset()) as *const i64;
                let v_ptr = right.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
                for i in 0..r_len {
                    let key = *k_ptr.add(i);
                    let val = ptr::read(v_ptr.add(i)); // Move, not clone!
                    keys_vals.push((key, val));
                }
            }
            // Set len=0 BEFORE any other operation to prevent double-free when right is dropped
            right.set_len(0);

            // Now we can safely mutably borrow left
            let left = self.child_mut(index - 1).make_mut();
            for (k, v) in keys_vals {
                left.push_leaf(k, v);
            }
        } else {
            // Move keys and children out of right using ptr::read (not clone!)
            // After make_mut(), we have unique ownership of the node structure,
            // so we can safely move the children out.
            let keys: Vec<i64> = right.keys().to_vec();
            // SAFETY: right is an internal node. We read all children from indices [0..r_len+1).
            // Children are moved via ptr::read.
            let children: Vec<NodePtr<V>> = unsafe {
                let c_ptr =
                    right.ptr.data_ptr_mut().add(Self::children_offset()) as *const NodePtr<V>;
                (0..=r_len).map(|i| ptr::read(c_ptr.add(i))).collect()
            };

            // CRITICAL: Set drop_count to 2 to prevent NodePtr::drop from dropping
            // the children again (they've been moved to the children Vec).
            // For internal nodes, Drop iterates 0..=len, so with len=0 it would still
            // try to drop child 0. By setting drop_count > 1, Drop thinks this isn't
            // the last reference and skips content dropping entirely.
            // SAFETY: We have unique access to right via make_mut(). Setting drop_count
            // to 2 is safe because we're about to drop this node in remove_key_and_child,
            // and we want Drop to skip the children (they've been moved out).
            unsafe {
                let header = &*(right.ptr.data_ptr_mut() as *const NodeHeader);
                header.drop_count.store(2, Ordering::Release);
            }
            right.set_len(0);

            let left = self.child_mut(index - 1).make_mut();

            // Move children to left using into_iter (no cloning needed)
            let mut children_iter = children.into_iter();
            left.push_internal(separator, children_iter.next().unwrap());
            for (key, child) in keys.into_iter().zip(children_iter) {
                left.push_internal(key, child);
            }
        }

        self.remove_key_and_child(index - 1, index);
    }

    fn merge_with_right(&mut self, index: usize) {
        self.merge_with_left(index + 1)
    }

    fn remove_key_and_child(&mut self, key_idx: usize, child_idx: usize) {
        let len = self.len();
        // SAFETY: This is an internal node (only called from internal node contexts).
        // key_idx < len and child_idx <= len (valid indices). We shift keys [key_idx+1..len)
        // left by 1 to fill the gap. For children, we first drop_in_place the child being
        // removed (it's a NodePtr that needs cleanup), then shift children [child_idx+1..len+1)
        // left by 1. ptr::copy handles overlapping regions. Keys are Copy (i64). The slots
        // at the end become logically uninitialized after set_len decrements the count.
        unsafe {
            let k_ptr = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::copy(
                k_ptr.add(key_idx + 1),
                k_ptr.add(key_idx),
                len - key_idx - 1,
            );

            let c_ptr = self.ptr.data_ptr_mut().add(Self::children_offset()) as *mut NodePtr<V>;
            // Drop the child being removed before overwriting it
            ptr::drop_in_place(c_ptr.add(child_idx));
            ptr::copy(
                c_ptr.add(child_idx + 1),
                c_ptr.add(child_idx),
                len - child_idx,
            );
        }
        self.set_len(len - 1);
    }

    fn split_leaf(&mut self) -> (i64, NodePtr<V>) {
        let mid = self.len() / 2;
        let right_count = self.len() - mid;

        let mut right = NodePtr::new_leaf();

        // SAFETY: Both self and right are leaf nodes. We copy keys from indices [mid..len)
        // and values from indices [mid..len) of self into the start of right. The source
        // and destination do not overlap (different allocations). Keys are Copy (i64). Values
        // are bitwise copied - this is safe because we set self.len = mid afterwards, so those
        // slots become logically uninitialized (won't be dropped when self is dropped).
        unsafe {
            let k_src = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            let k_dst = right.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;
            ptr::copy_nonoverlapping(k_src.add(mid), k_dst, right_count);

            let v_src = self.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
            let v_dst = right.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
            ptr::copy_nonoverlapping(v_src.add(mid), v_dst, right_count);
        }

        right.set_len(right_count);
        self.set_len(mid);

        let median = right.keys()[0];
        (median, right)
    }

    /// Optimized split for rightmost (sequential) inserts.
    /// Keeps MAX_KEYS in left node, moves only 1 key to right.
    /// This achieves ~100% fill factor for sequential insert workloads
    /// instead of the standard 50% from midpoint splits.
    fn split_leaf_rightmost(&mut self) -> (i64, NodePtr<V>) {
        let len = self.len();
        debug_assert!(
            len == MAX_KEYS + 1,
            "split_leaf_rightmost expects overflow node"
        );

        let mut right = NodePtr::new_leaf();

        // SAFETY: self is a leaf with MAX_KEYS + 1 elements. We move only the last
        // key/value to right. The key is Copy (i64). The value is moved via ptr::read
        // then ptr::write. After set_len(len-1), the source slot is logically uninitialized.
        unsafe {
            let k_src = self.ptr.data_ptr_mut().add(Self::keys_offset()) as *const i64;
            let k_dst = right.ptr.data_ptr_mut().add(Self::keys_offset()) as *mut i64;

            let v_src = self.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;
            let v_dst = right.ptr.data_ptr_mut().add(Self::values_offset()) as *mut V;

            // Copy last key
            ptr::write(k_dst, *k_src.add(len - 1));

            // Move last value (ptr::read moves ownership out)
            ptr::write(v_dst, ptr::read(v_src.add(len - 1)));
        }

        right.set_len(1);
        self.set_len(len - 1); // MAX_KEYS

        let median = right.keys()[0];
        (median, right)
    }
}

/// Copy-on-Write B+ tree for i64 keys
///
/// Provides lock-free reads through structural sharing.
/// Clone is O(1) - just increments root's reference count.
///
/// # Thread Safety
///
/// - **Readers**: Multiple readers can safely access the tree concurrently via cloned
///   snapshots. Each snapshot is immutable from the reader's perspective.
/// - **Writers**: Write operations (`insert`, `remove`, `get_mut`, `entry`) require
///   exclusive access (`&mut self`). External synchronization (e.g., `Mutex`, `RwLock`)
///   is required if multiple threads need write access.
/// - **Pattern**: Clone the tree to create a snapshot, then readers use the snapshot
///   while writers mutate the original. This is the standard MVCC pattern.
const MAX_TREE_DEPTH: usize = 16;

/// Stack-based path to avoid allocations
#[derive(Clone, Copy)]
pub struct NodePath {
    indices: [u8; MAX_TREE_DEPTH],
    len: u8,
}

impl Default for NodePath {
    fn default() -> Self {
        Self {
            indices: [0; MAX_TREE_DEPTH],
            len: 0,
        }
    }
}

impl NodePath {
    pub fn new() -> Self {
        Self::default()
    }

    #[cold]
    #[inline(never)]
    fn depth_overflow() -> ! {
        panic!("B-Tree depth exceeded maximum")
    }

    pub fn push(&mut self, idx: usize) {
        if (self.len as usize) < MAX_TREE_DEPTH {
            self.indices[self.len as usize] = idx as u8;
            self.len += 1;
        } else {
            Self::depth_overflow();
        }
    }

    fn get(&self, depth: usize) -> usize {
        self.indices[depth] as usize
    }

    fn iter(&self) -> impl Iterator<Item = usize> + '_ {
        (0..self.len as usize).map(|i| self.indices[i] as usize)
    }
}

pub struct CowBTree<V: Clone> {
    root: Option<NodePtr<V>>,
    /// Cached maximum key in the tree. Valid if root.is_some().
    max_key: i64,
    /// Number of elements in the tree
    len: usize,
}

impl<V: Clone> Default for CowBTree<V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<V: Clone> Clone for CowBTree<V> {
    /// O(1) clone - just increments root's reference count
    #[inline]
    fn clone(&self) -> Self {
        Self {
            root: self.root.clone(),
            max_key: self.max_key,
            len: self.len,
        }
    }
}

impl<V: Clone> CowBTree<V> {
    #[inline]
    pub fn new() -> Self {
        assert!(
            mem::align_of::<V>() <= 8,
            "CowBTree value type alignment must be <= 8"
        );
        Self {
            root: None,
            max_key: 0,
            len: 0,
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.root.is_none()
    }

    /// Get a value by key. Lock-free, O(log n).
    #[inline]
    pub fn get(&self, key: i64) -> Option<&V> {
        let mut node = self.root.as_ref()?;
        loop {
            match node.search(key) {
                Ok(i) => {
                    if node.is_leaf() {
                        return Some(&node.values()[i]);
                    }
                    node = node.child(i + 1);
                }
                Err(i) => {
                    if node.is_leaf() {
                        return None;
                    }
                    node = node.child(i);
                }
            }
        }
    }

    /// Get a mutable reference to a value. Triggers COW if needed.
    #[inline]
    pub fn get_mut(&mut self, key: i64) -> Option<&mut V> {
        let (path, leaf_idx) = self.search_path(key);
        let leaf_idx = leaf_idx.ok()?;

        self.get_mut_with_path(key, &path, leaf_idx)
    }

    fn get_mut_with_path(&mut self, _key: i64, path: &NodePath, leaf_idx: usize) -> Option<&mut V> {
        let root = self.root.as_mut()?;
        let mut node = root.make_mut();

        for idx in path.iter() {
            let child = node.child_mut(idx);
            node = child.make_mut();
        }

        if leaf_idx < node.len() {
            Some(&mut node.values_mut_slice()[leaf_idx])
        } else {
            None
        }
    }

    /// Check if key exists. Lock-free, O(log n).
    #[inline]
    pub fn contains_key(&self, key: i64) -> bool {
        self.get(key).is_some()
    }

    /// Insert a key-value pair. Returns old value if key existed.
    pub fn insert(&mut self, key: i64, value: V) -> Option<V> {
        if self.root.is_none() {
            let mut node = NodePtr::new_leaf();
            node.push_leaf(key, value);
            self.root = Some(node);
            self.max_key = key;
            self.len = 1;
            return None;
        }

        // Fast path for sequential inserts: if key > max key, append to rightmost leaf
        if self.is_key_greater_than_max(key) {
            let root = self.root.as_mut().unwrap();
            let result = Self::insert_rightmost(root, key, value);
            self.max_key = key;

            return match result {
                InsertResult::Done(old) => {
                    if old.is_none() {
                        self.len += 1;
                    }
                    old
                }
                InsertResult::Split(median, right) => {
                    let old_root = self.root.take().unwrap();
                    let mut new_root = NodePtr::new_internal();

                    // SAFETY: new_root is a freshly created internal node with len=0.
                    // We write old_root to children[0]. Internal nodes have len+1 children,
                    // so with len=0 we have space for 1 child at index 0. old_root is moved
                    // (not cloned) into the slot. push_internal will add children[1] and set len=1.
                    unsafe {
                        let c_ptr = new_root
                            .ptr
                            .data_ptr_mut()
                            .add(NodePtr::<V>::children_offset())
                            as *mut NodePtr<V>;
                        ptr::write(c_ptr, old_root);
                    }

                    new_root.push_internal(median, right);
                    self.root = Some(new_root);
                    self.len += 1;
                    None
                }
            };
        }

        let root = self.root.as_mut().unwrap();
        let result = Self::insert_recursive(root, key, value);

        if key > self.max_key {
            self.max_key = key;
        }

        match result {
            InsertResult::Done(old) => {
                if old.is_none() {
                    self.len += 1;
                }
                old
            }
            InsertResult::Split(median, right) => {
                let old_root = self.root.take().unwrap();
                let mut new_root = NodePtr::new_internal();
                // SAFETY: new_root is a freshly created internal node with len=0.
                // We write old_root to children[0]. Internal nodes have len+1 children,
                // so with len=0 we have space for 1 child at index 0. old_root is moved
                // (not cloned) into the slot. push_internal will add children[1] and set len=1.
                unsafe {
                    let c_ptr = new_root
                        .ptr
                        .data_ptr_mut()
                        .add(NodePtr::<V>::children_offset())
                        as *mut NodePtr<V>;
                    ptr::write(c_ptr, old_root);
                }
                new_root.push_internal(median, right);
                self.root = Some(new_root);
                self.len += 1;
                None
            }
        }
    }

    /// Check if key is greater than maximum key in tree (O(1) with caching)
    #[inline]
    fn is_key_greater_than_max(&self, key: i64) -> bool {
        self.root.is_some() && key > self.max_key
    }

    /// Fast path: insert into rightmost leaf (for sequential inserts)
    fn insert_rightmost(node: &mut NodePtr<V>, key: i64, value: V) -> InsertResult<V> {
        let (res, _) = Self::insert_rightmost_return_ptr(node, key, value);
        res
    }

    fn insert_rightmost_return_ptr(
        node: &mut NodePtr<V>,
        key: i64,
        value: V,
    ) -> (InsertResult<V>, *mut V) {
        let node = node.make_mut();

        if node.is_leaf() {
            node.push_leaf(key, value);

            // SAFETY: node is a leaf (verified above). We just pushed a value, so len >= 1.
            // We compute a pointer to the newly inserted value (at index len - 1).
            // If the node overflows (len > MAX_KEYS), we use rightmost split which moves
            // only the last element to the new right node, so the pointer is at right[0].
            // All pointer arithmetic stays within allocated bounds.
            unsafe {
                let len = node.len();
                let v_ptr = node.ptr.data_ptr_mut().add(NodePtr::<V>::values_offset()) as *mut V;
                let ptr = v_ptr.add(len - 1);

                if node.len() > MAX_KEYS {
                    // Use rightmost split: keeps MAX_KEYS in left, moves 1 to right
                    let (median, right) = node.split_leaf_rightmost();
                    // After rightmost split, the inserted value is at right[0]
                    let v_ptr_new =
                        right.ptr.data_ptr_mut().add(NodePtr::<V>::values_offset()) as *mut V;
                    (InsertResult::Split(median, right), v_ptr_new)
                } else {
                    (InsertResult::Done(None), ptr)
                }
            }
        } else {
            let last_idx = node.len();
            let child = node.child_mut(last_idx);
            let (result, ptr) = Self::insert_rightmost_return_ptr(child, key, value);

            match result {
                InsertResult::Done(old) => (InsertResult::Done(old), ptr),
                InsertResult::Split(median, right) => {
                    node.push_internal(median, right);

                    if node.len() > MAX_KEYS {
                        // Use rightmost split for internal nodes too
                        let (m, r) = node.split_internal_rightmost();
                        (InsertResult::Split(m, r), ptr)
                    } else {
                        (InsertResult::Done(None), ptr)
                    }
                }
            }
        }
    }

    fn insert_recursive(node: &mut NodePtr<V>, key: i64, value: V) -> InsertResult<V> {
        let node = node.make_mut();

        if node.is_leaf() {
            match node.search(key) {
                // SAFETY: node is a leaf (verified above). search returned Ok(i), meaning
                // key exists at index i (where i < node.len()). We read the old value via
                // ptr::read and write the new value via ptr::write. This is a replacement
                // of an existing value, so no len change is needed.
                Ok(i) => unsafe {
                    let v_ptr =
                        node.ptr.data_ptr_mut().add(NodePtr::<V>::values_offset()) as *mut V;
                    let old = ptr::read(v_ptr.add(i));
                    ptr::write(v_ptr.add(i), value);
                    InsertResult::Done(Some(old))
                },
                Err(i) => {
                    node.insert_leaf(i, key, value);

                    if node.len() > MAX_KEYS {
                        // Optimization: if we inserted at the end, use rightmost split
                        // This handles interleaved sequential inserts that miss the global fast path
                        let (median, right) = if i == node.len() - 1 {
                            node.split_leaf_rightmost()
                        } else {
                            node.split_leaf()
                        };
                        InsertResult::Split(median, right)
                    } else {
                        InsertResult::Done(None)
                    }
                }
            }
        } else {
            let i = match node.search(key) {
                Ok(i) => i + 1,
                Err(i) => i,
            };

            let result = Self::insert_recursive(node.child_mut(i), key, value);

            match result {
                InsertResult::Done(old) => InsertResult::Done(old),
                InsertResult::Split(median, right) => {
                    node.insert_internal(i, median, right);

                    if node.len() > MAX_KEYS {
                        // Optimization: if we inserted at the end, use rightmost split
                        let (m, r) = if i == node.len() - 1 {
                            node.split_internal_rightmost()
                        } else {
                            node.split_internal()
                        };
                        InsertResult::Split(m, r)
                    } else {
                        InsertResult::Done(None)
                    }
                }
            }
        }
    }

    /// Remove a key. Returns the value if it existed.
    pub fn remove(&mut self, key: i64) -> Option<V> {
        let root = self.root.as_mut()?;
        let result = Self::remove_recursive(root, key);

        if result.is_some() {
            self.len -= 1;

            if self.len == 0 {
                self.root = None;
                self.max_key = 0;
            } else if self.max_key == key {
                self.refresh_max_key();
            }

            if let Some(ref mut root) = self.root {
                let root = root.make_mut();
                if !root.is_leaf() && root.len() == 0 {
                    let child_node = root.child_mut(0).clone();
                    self.root = Some(child_node);
                } else if root.is_leaf() && root.len() == 0 {
                    self.root = None;
                    self.max_key = 0;
                }
            }
        }

        result
    }

    /// Search and return path to the leaf.
    /// Returns (path_indices, leaf_search_result)
    /// path_indices: indices of children taken to reach the leaf
    fn search_path(&self, key: i64) -> (NodePath, Result<usize, usize>) {
        let mut path = NodePath::new();
        if self.root.is_none() {
            return (path, Err(0));
        }

        let mut node = self.root.as_ref().unwrap();
        loop {
            match node.search(key) {
                Ok(i) => {
                    if node.is_leaf() {
                        return (path, Ok(i));
                    }
                    path.push(i + 1);
                    node = node.child(i + 1);
                }
                Err(i) => {
                    if node.is_leaf() {
                        return (path, Err(i));
                    }
                    path.push(i);
                    node = node.child(i);
                }
            }
        }
    }

    /// Insert using pre-computed path and leaf index (avoids redundant search).
    /// `leaf_idx` is the index in the leaf where the key should be inserted.
    fn insert_with_path(
        node_ptr: &mut NodePtr<V>,
        key: i64,
        value: V,
        path: &NodePath,
        depth: usize,
        leaf_idx: usize,
    ) -> (InsertResult<V>, *mut V) {
        let node = node_ptr.make_mut();

        if node.is_leaf() {
            // Use pre-computed leaf_idx directly - no search needed
            let i = leaf_idx;
            node.insert_leaf(i, key, value);

            if node.len() > MAX_KEYS {
                let (median, right_node) = node.split_leaf();
                // Must match split_leaf's mid calculation: self.len() / 2
                // Before split, len was MAX_KEYS + 1, so mid = (MAX_KEYS + 1) / 2 = MAX_KEYS.div_ceil(2)
                let mid = MAX_KEYS.div_ceil(2);

                let ptr = if i < mid {
                    // SAFETY: After split, i < mid means the inserted value stayed in node.
                    // node is a valid leaf with i < node.len() after the split. We compute a
                    // pointer to the inserted value at index i.
                    unsafe {
                        let v_ptr =
                            node.ptr.data_ptr_mut().add(NodePtr::<V>::values_offset()) as *mut V;
                        v_ptr.add(i)
                    }
                } else {
                    let right_idx = i - mid;
                    // SAFETY: After split, i >= mid means the inserted value moved to right_node.
                    // right_node is a valid leaf with right_idx < right_node.len() after the split.
                    // We compute a pointer to the inserted value at index right_idx.
                    unsafe {
                        let v_ptr = right_node
                            .ptr
                            .data_ptr_mut()
                            .add(NodePtr::<V>::values_offset())
                            as *mut V;
                        v_ptr.add(right_idx)
                    }
                };

                (InsertResult::Split(median, right_node), ptr)
            } else {
                // SAFETY: node is a leaf, we just inserted at index i (where i < node.len()).
                // We compute a pointer to the newly inserted value.
                unsafe {
                    let v_ptr =
                        node.ptr.data_ptr_mut().add(NodePtr::<V>::values_offset()) as *mut V;
                    let ptr = v_ptr.add(i);
                    (InsertResult::Done(None), ptr)
                }
            }
        } else {
            let i = path.get(depth);

            let (result, ptr) =
                Self::insert_with_path(node.child_mut(i), key, value, path, depth + 1, leaf_idx);

            match result {
                InsertResult::Done(old) => (InsertResult::Done(old), ptr),
                InsertResult::Split(median, right) => {
                    node.insert_internal(i, median, right);

                    if node.len() > MAX_KEYS {
                        // Optimization: if we inserted at the end, use rightmost split
                        let (m, r) = if i == node.len() - 1 {
                            node.split_internal_rightmost()
                        } else {
                            node.split_internal()
                        };
                        (InsertResult::Split(m, r), ptr)
                    } else {
                        (InsertResult::Done(None), ptr)
                    }
                }
            }
        }
    }

    fn refresh_max_key(&mut self) {
        if let Some(root) = &self.root {
            let mut node = root;
            loop {
                if node.is_leaf() {
                    self.max_key = node.keys().last().copied().unwrap_or(0);
                    break;
                }
                node = node.children().last().unwrap();
            }
        } else {
            self.max_key = 0;
        }
    }

    fn remove_recursive(node: &mut NodePtr<V>, key: i64) -> Option<V> {
        let node = node.make_mut();

        if node.is_leaf() {
            match node.search(key) {
                Ok(i) => Some(node.remove_leaf(i)),
                Err(_) => None,
            }
        } else {
            let i = match node.search(key) {
                Ok(i) => i + 1,
                Err(i) => i,
            };

            if node.child(i).len() <= MIN_KEYS {
                Self::ensure_child_can_lose_key(node, i);
            }

            let new_i = match node.search(key) {
                Ok(i) => i + 1,
                Err(i) => i,
            };

            let i = new_i.min(node.len()); // Children len is len+1. Max index len.
            Self::remove_recursive(node.child_mut(i), key)
        }
    }

    fn ensure_child_can_lose_key(node: &mut NodePtr<V>, i: usize) {
        let can_borrow_left = i > 0 && node.child(i - 1).len() > MIN_KEYS;
        let can_borrow_right = i < node.len() && node.child(i + 1).len() > MIN_KEYS;

        if can_borrow_left {
            node.borrow_from_left(i);
        } else if can_borrow_right {
            node.borrow_from_right(i);
        } else if i > 0 {
            node.merge_with_left(i);
        } else if i < node.len() {
            node.merge_with_right(i);
        }
    }

    /// Iterate over chunks of keys and values (O(1) amortized traversal)
    /// Yields `(&[i64], &[V])` slices directly from leaf nodes.
    pub fn iter_chunks(&self) -> impl Iterator<Item = (&[i64], &[V])> {
        CowBTreeChunkIter::new(self.root.as_ref())
    }

    /// Iterate over all key-value pairs in sorted order
    pub fn iter(&self) -> impl Iterator<Item = (&i64, &V)> {
        self.iter_chunks()
            .flat_map(|(keys, values)| keys.iter().zip(values.iter()))
    }

    /// Iterate over keys in sorted order
    pub fn keys(&self) -> impl Iterator<Item = i64> + '_ {
        self.iter().map(|(k, _)| *k)
    }

    /// Iterate over values in sorted order
    pub fn values(&self) -> impl Iterator<Item = &V> {
        self.iter().map(|(_, v)| v)
    }

    /// Yields chunks of keys and values within the range.
    /// Each chunk is a slice from a single leaf node.
    pub fn range_chunks<R>(&self, range: R) -> impl Iterator<Item = (&[i64], &[V])>
    where
        R: std::ops::RangeBounds<i64>,
    {
        CowBTreeRangeChunkIter::new(self.root.as_ref(), range)
    }

    /// Iterator over a sub-range of elements in the B-tree.
    pub fn range<R>(&self, range: R) -> impl Iterator<Item = (&i64, &V)>
    where
        R: std::ops::RangeBounds<i64>,
    {
        self.range_chunks(range)
            .flat_map(|(keys, values)| keys.iter().zip(values.iter()))
    }

    /// Iterate over chunks in reverse order (rightmost leaf to leftmost)
    pub fn iter_rev_chunks(&self) -> impl Iterator<Item = (&[i64], &[V])> {
        CowBTreeRevChunkIter::new(self.root.as_ref())
    }

    /// Iterate over all key-value pairs in reverse sorted order (largest to smallest)
    pub fn iter_rev(&self) -> impl Iterator<Item = (&i64, &V)> {
        self.iter_rev_chunks()
            .flat_map(|(keys, values)| keys.iter().zip(values.iter()).rev())
    }

    /// Yields chunks within the range in reverse order (rightmost matching leaf first).
    /// Each chunk is a slice from a single leaf node, keys in ascending order within the chunk.
    pub fn range_rev_chunks<R>(&self, range: R) -> impl Iterator<Item = (&[i64], &[V])>
    where
        R: std::ops::RangeBounds<i64>,
    {
        CowBTreeRevRangeChunkIter::new(self.root.as_ref(), range)
    }

    /// Iterator over a sub-range in reverse order (largest to smallest within range).
    pub fn range_rev<R>(&self, range: R) -> impl Iterator<Item = (&i64, &V)>
    where
        R: std::ops::RangeBounds<i64>,
    {
        self.range_rev_chunks(range)
            .flat_map(|(keys, values)| keys.iter().zip(values.iter()).rev())
    }

    /// Clear all entries
    pub fn clear(&mut self) {
        self.root = None;
        self.max_key = 0;
        self.len = 0;
    }

    /// Returns the cached maximum key, or None if the tree is empty.
    #[inline]
    pub fn max_key(&self) -> Option<i64> {
        if self.root.is_some() {
            Some(self.max_key)
        } else {
            None
        }
    }

    fn insert_rightmost_entry(&mut self, key: i64, value: V) -> *mut V {
        let root = self.root.as_mut().unwrap();
        let (result, ptr) = Self::insert_rightmost_return_ptr(root, key, value);
        self.max_key = key;

        match result {
            InsertResult::Done(old) => {
                if old.is_none() {
                    self.len += 1;
                }
            }
            InsertResult::Split(median, right) => {
                let old_root = self.root.take().unwrap();
                let mut new_root = NodePtr::new_internal();
                // SAFETY: new_root is a freshly created internal node with len=0.
                // We write old_root to children[0]. Internal nodes have len+1 children,
                // so with len=0 we have space for 1 child at index 0. old_root is moved
                // (not cloned) into the slot. push_internal will add children[1] and set len=1.
                unsafe {
                    let c_ptr = new_root
                        .ptr
                        .data_ptr_mut()
                        .add(NodePtr::<V>::children_offset())
                        as *mut NodePtr<V>;
                    ptr::write(c_ptr, old_root);
                }
                new_root.push_internal(median, right);
                self.root = Some(new_root);
                self.len += 1;
            }
        }

        ptr
    }

    /// Entry API for in-place updates.
    /// Optimized: single traversal, O(1) get().
    /// - entry(): 1 traversal
    /// - OccupiedEntry::get(): O(1) via cached pointer
    /// - OccupiedEntry::get_mut()/insert(): 1 traversal with COW
    pub fn entry(&mut self, key: i64) -> Entry<'_, V> {
        // Fast path for sequential append
        if self.is_key_greater_than_max(key) {
            return Entry::Vacant(VacantEntry {
                tree: self,
                key,
                path: NodePath::new(), // Dummy, not used for rightmost
                leaf_idx: 0,           // Dummy, not used for rightmost
                is_rightmost: true,
            });
        }

        let (path, leaf_result) = self.search_path(key);
        match leaf_result {
            Ok(idx) => Entry::Occupied(OccupiedEntry {
                tree: self,
                key,
                path,
                leaf_idx: idx,
            }),
            Err(idx) => Entry::Vacant(VacantEntry {
                tree: self,
                key,
                path,
                leaf_idx: idx,
                is_rightmost: false,
            }),
        }
    }

    fn insert_using_path(
        &mut self,
        key: i64,
        value: V,
        path: &NodePath,
        leaf_idx: usize,
    ) -> *mut V {
        if self.root.is_none() {
            self.insert(key, value);
            return self.get_mut(key).unwrap() as *mut V;
        }

        let root = self.root.as_mut().unwrap();
        let (result, ptr) = Self::insert_with_path(root, key, value, path, 0, leaf_idx);

        if key > self.max_key {
            self.max_key = key;
        }

        match result {
            InsertResult::Done(old) => {
                if old.is_none() {
                    self.len += 1;
                }
            }
            InsertResult::Split(median, right) => {
                let old_root = self.root.take().unwrap();
                let mut new_root = NodePtr::new_internal();
                // SAFETY: new_root is a freshly created internal node with len=0.
                // We write old_root to children[0]. Internal nodes have len+1 children,
                // so with len=0 we have space for 1 child at index 0. old_root is moved
                // (not cloned) into the slot. push_internal will add children[1] and set len=1.
                unsafe {
                    let c_ptr = new_root
                        .ptr
                        .data_ptr_mut()
                        .add(NodePtr::<V>::children_offset())
                        as *mut NodePtr<V>;
                    ptr::write(c_ptr, old_root);
                }
                new_root.push_internal(median, right);
                self.root = Some(new_root);
                self.len += 1;
            }
        }

        ptr
    }
}

/// Entry API for CowBTree
pub enum Entry<'a, V: Clone> {
    Occupied(OccupiedEntry<'a, V>),
    Vacant(VacantEntry<'a, V>),
}

impl<'a, V: Clone> Entry<'a, V> {
    pub fn or_insert(self, default: V) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default),
        }
    }

    pub fn and_modify<F>(self, f: F) -> Self
    where
        F: FnOnce(&mut V),
    {
        match self {
            Entry::Occupied(mut entry) => {
                f(entry.get_mut());
                Entry::Occupied(entry)
            }
            Entry::Vacant(entry) => Entry::Vacant(entry),
        }
    }

    pub fn key(&self) -> i64 {
        match self {
            Entry::Occupied(entry) => entry.key(),
            Entry::Vacant(entry) => entry.key(),
        }
    }
}

/// An occupied entry in the CowBTree
pub struct OccupiedEntry<'a, V: Clone> {
    tree: &'a mut CowBTree<V>,
    key: i64,
    path: NodePath,
    leaf_idx: usize,
}

impl<'a, V: Clone> OccupiedEntry<'a, V> {
    #[inline]
    pub fn key(&self) -> i64 {
        self.key
    }

    /// O(log n) - traverses the cached path to reach the leaf
    #[inline]
    pub fn get(&self) -> &V {
        let mut node = self.tree.root.as_ref().unwrap();
        for idx in self.path.iter() {
            node = node.child(idx);
        }
        &node.values()[self.leaf_idx]
    }

    pub fn get_mut(&mut self) -> &mut V {
        self.tree
            .get_mut_with_path(self.key, &self.path, self.leaf_idx)
            .unwrap()
    }

    pub fn into_mut(self) -> &'a mut V {
        self.tree
            .get_mut_with_path(self.key, &self.path, self.leaf_idx)
            .unwrap()
    }

    pub fn insert(&mut self, value: V) -> V {
        let node = self.tree.root.as_mut().unwrap();
        let mut node = node.make_mut();

        for idx in self.path.iter() {
            let child = node.child_mut(idx);
            node = child.make_mut();
        }

        // SAFETY: node is a leaf (we followed the path to a leaf). self.leaf_idx is the
        // index where the key was found during entry lookup, so it's valid (< node.len()).
        // We read the old value via ptr::read and write the new value via ptr::write.
        // This is a replacement of an existing value, so no len change is needed.
        unsafe {
            let v_ptr = node.ptr.data_ptr_mut().add(NodePtr::<V>::values_offset()) as *mut V;
            let ptr = v_ptr.add(self.leaf_idx);
            let old = ptr::read(ptr);
            ptr::write(ptr, value);
            old
        }
    }
}

/// A vacant entry in the CowBTree
pub struct VacantEntry<'a, V: Clone> {
    tree: &'a mut CowBTree<V>,
    key: i64,
    path: NodePath,
    /// Index in the leaf node where the key should be inserted
    leaf_idx: usize,
    /// Optimization: true if this entry represents a sequential insert (key > max_key)
    is_rightmost: bool,
}

impl<'a, V: Clone> VacantEntry<'a, V> {
    #[inline]
    pub fn key(&self) -> i64 {
        self.key
    }

    #[inline]
    pub fn insert(self, value: V) -> &'a mut V {
        if self.is_rightmost {
            let ptr = self.tree.insert_rightmost_entry(self.key, value);
            // SAFETY: insert_rightmost_entry returns a valid pointer to the newly inserted
            // value. The pointer remains valid for the lifetime 'a because we have exclusive
            // access to the tree (&'a mut). The insert functions guarantee the pointer points
            // to initialized, properly aligned memory within a leaf node.
            unsafe { &mut *ptr }
        } else {
            let ptr = self
                .tree
                .insert_using_path(self.key, value, &self.path, self.leaf_idx);
            // SAFETY: insert_using_path returns a valid pointer to the newly inserted value.
            // The pointer remains valid for the lifetime 'a because we have exclusive access
            // to the tree (&'a mut). The insert functions guarantee the pointer points to
            // initialized, properly aligned memory within a leaf node.
            unsafe { &mut *ptr }
        }
    }
}

enum InsertResult<V: Clone> {
    Done(Option<V>),
    Split(i64, NodePtr<V>),
}

/// Iterator over chunks of a CowBTree (leaf slices)
struct CowBTreeChunkIter<'a, V: Clone> {
    /// Stack of (node, next_child_index) for traversal
    /// Only holds internal nodes.
    stack: Vec<(&'a NodePtr<V>, usize)>,
    /// Current leaf node being yielded (if any)
    current_leaf: Option<&'a NodePtr<V>>,
}

impl<'a, V: Clone> CowBTreeChunkIter<'a, V> {
    fn new(root: Option<&'a NodePtr<V>>) -> Self {
        let mut iter = Self {
            stack: Vec::new(),
            current_leaf: None,
        };
        if let Some(root) = root {
            iter.descend_to_leftmost(root);
        }
        iter
    }

    /// Descend to the leftmost leaf, pushing internal nodes onto the stack
    fn descend_to_leftmost(&mut self, mut node: &'a NodePtr<V>) {
        while !node.is_leaf() {
            self.stack.push((node, 1));
            node = node.child(0);
        }
        self.current_leaf = Some(node);
    }
}

impl<'a, V: Clone> Iterator for CowBTreeChunkIter<'a, V> {
    type Item = (&'a [i64], &'a [V]);

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(leaf) = self.current_leaf.take() {
            return Some((leaf.keys(), leaf.values()));
        }

        loop {
            let (node, idx) = self.stack.last_mut()?;

            if *idx < node.len() + 1 {
                let child_idx = *idx;
                *idx += 1;
                let child = node.child(child_idx);
                self.descend_to_leftmost(child);

                if let Some(leaf) = self.current_leaf.take() {
                    return Some((leaf.keys(), leaf.values()));
                }
            } else {
                self.stack.pop();
            }
        }
    }
}

/// Range iterator over a CowBTree yielding chunks
/// Optimized: Seeks directly to start bound and yields slices
struct CowBTreeRangeChunkIter<'a, V: Clone, R> {
    stack: Vec<(&'a NodePtr<V>, usize)>,
    range: R,
    current_leaf: Option<&'a NodePtr<V>>,
    current_idx: usize,
    finished: bool,
}

impl<'a, V: Clone, R: std::ops::RangeBounds<i64>> CowBTreeRangeChunkIter<'a, V, R> {
    fn new(root: Option<&'a NodePtr<V>>, range: R) -> Self {
        let mut iter = Self {
            stack: Vec::new(),
            range,
            current_leaf: None,
            current_idx: 0,
            finished: false,
        };
        if let Some(root) = root {
            iter.seek_to_start(root);
        } else {
            iter.finished = true;
        }
        iter
    }

    fn seek_to_start(&mut self, mut node: &'a NodePtr<V>) {
        let start_key = match self.range.start_bound() {
            Bound::Included(&k) => Some(k),
            Bound::Excluded(&k) => Some(k),
            Bound::Unbounded => None,
        };

        loop {
            if node.is_leaf() {
                let keys = node.keys();
                let mut idx = if let Some(k) = start_key {
                    match keys.binary_search(&k) {
                        Ok(i) => i,
                        Err(i) => i,
                    }
                } else {
                    0
                };

                if let Bound::Excluded(&k) = self.range.start_bound() {
                    if idx < keys.len() && keys[idx] == k {
                        idx += 1;
                    }
                }

                self.current_leaf = Some(node);
                self.current_idx = idx;
                break;
            } else {
                let idx = if let Some(k) = start_key {
                    match node.search(k) {
                        Ok(i) => i + 1,
                        Err(i) => i,
                    }
                } else {
                    0
                };

                self.stack.push((node, idx + 1));
                node = node.child(idx);
            }
        }
    }
}

impl<'a, V: Clone, R: std::ops::RangeBounds<i64>> Iterator for CowBTreeRangeChunkIter<'a, V, R> {
    type Item = (&'a [i64], &'a [V]);

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        loop {
            if let Some(leaf) = self.current_leaf {
                let keys = leaf.keys();
                let values = leaf.values();
                if self.current_idx < keys.len() {
                    let start = self.current_idx;
                    let end = match self.range.end_bound() {
                        Bound::Unbounded => keys.len(),
                        Bound::Included(&k) => {
                            if keys.last().unwrap() <= &k {
                                keys.len()
                            } else {
                                let pos = keys[start..].partition_point(|&x| x <= k);
                                self.finished = true;
                                start + pos
                            }
                        }
                        Bound::Excluded(&k) => {
                            if keys.last().unwrap() < &k {
                                keys.len()
                            } else {
                                let pos = keys[start..].partition_point(|&x| x < k);
                                self.finished = true;
                                start + pos
                            }
                        }
                    };

                    if start >= end {
                        self.finished = true;
                        self.current_leaf = None;
                        return None;
                    }

                    self.current_idx = end;
                    let result = (&keys[start..end], &values[start..end]);

                    if end == keys.len() && !self.finished {
                        self.current_leaf = None;
                    } else {
                        self.finished = true;
                        self.current_leaf = None;
                    }

                    return Some(result);
                } else {
                    self.current_leaf = None;
                }
            }

            if self.finished {
                return None;
            }

            if let Some((node, idx)) = self.stack.last_mut() {
                if *idx < node.len() + 1 {
                    let child_idx = *idx;
                    *idx += 1;
                    let mut child = node.child(child_idx);

                    loop {
                        if child.is_leaf() {
                            self.current_leaf = Some(child);
                            self.current_idx = 0;
                            break;
                        } else {
                            self.stack.push((child, 1));
                            child = child.child(0);
                        }
                    }
                } else {
                    self.stack.pop();
                    if self.stack.is_empty() {
                        self.finished = true;
                        return None;
                    }
                }
            } else {
                self.finished = true;
                return None;
            }
        }
    }
}

impl<V: Clone + std::fmt::Debug> std::fmt::Debug for CowBTree<V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

/// Reverse iterator over a CowBTree yielding chunks from rightmost leaf to leftmost
struct CowBTreeRevChunkIter<'a, V: Clone> {
    /// Stack of (node, next_child_plus_one) for reverse traversal.
    /// next_child_plus_one == 0 means no more children to visit at this level.
    stack: Vec<(&'a NodePtr<V>, usize)>,
    /// Current leaf node being yielded
    current_leaf: Option<&'a NodePtr<V>>,
}

impl<'a, V: Clone> CowBTreeRevChunkIter<'a, V> {
    fn new(root: Option<&'a NodePtr<V>>) -> Self {
        let mut iter = Self {
            stack: Vec::new(),
            current_leaf: None,
        };
        if let Some(root) = root {
            iter.descend_to_rightmost(root);
        }
        iter
    }

    /// Descend to the rightmost leaf, pushing internal nodes onto the stack
    fn descend_to_rightmost(&mut self, mut node: &'a NodePtr<V>) {
        while !node.is_leaf() {
            let last_child = node.len(); // children indices: 0..=len
                                         // After visiting child(last_child), next to visit going left is child(last_child-1)
                                         // Store last_child as next_child_plus_one
            self.stack.push((node, last_child));
            node = node.child(last_child);
        }
        self.current_leaf = Some(node);
    }
}

impl<'a, V: Clone> Iterator for CowBTreeRevChunkIter<'a, V> {
    type Item = (&'a [i64], &'a [V]);

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(leaf) = self.current_leaf.take() {
            return Some((leaf.keys(), leaf.values()));
        }

        loop {
            let (node, next_plus_one) = self.stack.last_mut()?;

            if *next_plus_one > 0 {
                let child_idx = *next_plus_one - 1;
                *next_plus_one = child_idx;
                let child = node.child(child_idx);
                self.descend_to_rightmost(child);

                if let Some(leaf) = self.current_leaf.take() {
                    return Some((leaf.keys(), leaf.values()));
                }
            } else {
                self.stack.pop();
            }
        }
    }
}

/// Reverse range iterator over a CowBTree yielding chunks from end bound to start bound.
/// Each chunk contains keys in ascending order; the consumer should reverse within each chunk.
struct CowBTreeRevRangeChunkIter<'a, V: Clone, R> {
    stack: Vec<(&'a NodePtr<V>, usize)>,
    range: R,
    current_leaf: Option<&'a NodePtr<V>>,
    /// End index (exclusive) within current leaf
    current_end_idx: usize,
    finished: bool,
}

impl<'a, V: Clone, R: std::ops::RangeBounds<i64>> CowBTreeRevRangeChunkIter<'a, V, R> {
    fn new(root: Option<&'a NodePtr<V>>, range: R) -> Self {
        let mut iter = Self {
            stack: Vec::new(),
            range,
            current_leaf: None,
            current_end_idx: 0,
            finished: false,
        };
        if let Some(root) = root {
            iter.seek_to_end(root);
        } else {
            iter.finished = true;
        }
        iter
    }

    /// Descend to the rightmost leaf, setting current_end_idx to the full leaf length
    fn descend_to_rightmost(&mut self, mut node: &'a NodePtr<V>) {
        while !node.is_leaf() {
            let last_child = node.len();
            self.stack.push((node, last_child));
            node = node.child(last_child);
        }
        self.current_leaf = Some(node);
        self.current_end_idx = node.len();
    }

    /// Seek to the end bound of the range (the starting point for reverse iteration)
    fn seek_to_end(&mut self, mut node: &'a NodePtr<V>) {
        let end_key = match self.range.end_bound() {
            Bound::Included(&k) | Bound::Excluded(&k) => Some(k),
            Bound::Unbounded => None,
        };

        if end_key.is_none() {
            // Unbounded upper: start from rightmost leaf
            self.descend_to_rightmost(node);
            return;
        }

        let k = end_key.unwrap();

        loop {
            if node.is_leaf() {
                let keys = node.keys();
                let idx = match keys.binary_search(&k) {
                    Ok(i) => match self.range.end_bound() {
                        Bound::Included(_) => i + 1,
                        _ => i,
                    },
                    Err(i) => i,
                };

                if idx > 0 {
                    self.current_leaf = Some(node);
                    self.current_end_idx = idx;
                }
                // If idx == 0, no valid entries in this leaf for our range.
                // The first next() call will navigate to the previous leaf.
                break;
            } else {
                let child_idx = match node.search(k) {
                    Ok(i) => i + 1,
                    Err(i) => i,
                };
                // Store child_idx as next_child_plus_one: children before child_idx
                self.stack.push((node, child_idx));
                node = node.child(child_idx);
            }
        }
    }
}

impl<'a, V: Clone, R: std::ops::RangeBounds<i64>> Iterator for CowBTreeRevRangeChunkIter<'a, V, R> {
    type Item = (&'a [i64], &'a [V]);

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        loop {
            if let Some(leaf) = self.current_leaf {
                let keys = leaf.keys();
                let values = leaf.values();
                let end = self.current_end_idx;

                // Check start bound (lower bound) - trim from the left
                let start = if end == 0 {
                    end // Empty chunk, will be skipped
                } else {
                    match self.range.start_bound() {
                        Bound::Unbounded => 0,
                        Bound::Included(&k) => {
                            if keys[0] >= k {
                                0 // Entire chunk is within range
                            } else {
                                self.finished = true;
                                keys[..end].partition_point(|&x| x < k)
                            }
                        }
                        Bound::Excluded(&k) => {
                            if keys[0] > k {
                                0
                            } else {
                                self.finished = true;
                                keys[..end].partition_point(|&x| x <= k)
                            }
                        }
                    }
                };

                self.current_leaf = None;

                if start < end {
                    return Some((&keys[start..end], &values[start..end]));
                }

                if self.finished {
                    return None;
                }
            }

            // Navigate to previous leaf
            let (node, next_plus_one) = self.stack.last_mut()?;

            if *next_plus_one > 0 {
                let child_idx = *next_plus_one - 1;
                *next_plus_one = child_idx;
                let child = node.child(child_idx);
                self.descend_to_rightmost(child);
            } else {
                self.stack.pop();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_operations() {
        let mut tree: CowBTree<String> = CowBTree::new();

        assert!(tree.insert(5, "five".to_string()).is_none());
        assert!(tree.insert(3, "three".to_string()).is_none());
        assert!(tree.insert(7, "seven".to_string()).is_none());

        assert_eq!(tree.get(5), Some(&"five".to_string()));
        assert_eq!(tree.get(3), Some(&"three".to_string()));
        assert_eq!(tree.get(7), Some(&"seven".to_string()));
        assert_eq!(tree.get(1), None);

        assert_eq!(tree.len(), 3);
    }

    #[test]
    fn test_update() {
        let mut tree: CowBTree<String> = CowBTree::new();

        assert!(tree.insert(5, "five".to_string()).is_none());
        assert_eq!(tree.insert(5, "FIVE".to_string()), Some("five".to_string()));
        assert_eq!(tree.get(5), Some(&"FIVE".to_string()));
        assert_eq!(tree.len(), 1);
    }

    #[test]
    fn test_cow_semantics() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i, i * 10);
        }

        let snapshot = tree.clone();

        tree.insert(50, 999);
        tree.insert(200, 2000);

        assert_eq!(snapshot.get(50), Some(&500));
        assert_eq!(snapshot.get(200), None);

        assert_eq!(tree.get(50), Some(&999));
        assert_eq!(tree.get(200), Some(&2000));
    }

    #[test]
    fn test_many_inserts_sequential() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..10_000 {
            tree.insert(i, i * 2);
        }

        assert_eq!(tree.len(), 10_000);

        for i in 0..10_000 {
            assert_eq!(tree.get(i), Some(&(i * 2)), "Failed at key {}", i);
        }
    }

    #[test]
    fn test_random_inserts() {
        let mut tree: CowBTree<i64> = CowBTree::new();
        let keys: Vec<i64> = (0..1000).map(|i| (i * 7919 + 13) % 10000).collect();

        for &k in &keys {
            tree.insert(k, k * 2);
        }

        for &k in &keys {
            assert_eq!(tree.get(k), Some(&(k * 2)), "Failed at key {}", k);
        }
    }

    #[test]
    fn test_iteration() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in [5, 2, 8, 1, 9, 3, 7, 4, 6, 0] {
            tree.insert(i, i * 10);
        }

        let keys: Vec<i64> = tree.keys().collect();
        assert_eq!(keys, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
    }

    #[test]
    fn test_range() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i, i);
        }

        let range: Vec<i64> = tree.range(25..75).map(|(k, _)| *k).collect();
        assert_eq!(range.len(), 50);
        assert_eq!(range[0], 25);
        assert_eq!(range[49], 74);
    }

    #[test]
    fn test_remove_leaf() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20 {
            tree.insert(i, i * 10);
        }

        assert_eq!(tree.remove(10), Some(100));
        assert_eq!(tree.get(10), None);
        assert_eq!(tree.len(), 19);

        assert_eq!(tree.remove(10), None);
    }

    #[test]
    fn test_remove_many() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..1000 {
            tree.insert(i, i);
        }

        for i in (0..1000).step_by(2) {
            assert_eq!(tree.remove(i), Some(i));
        }

        assert_eq!(tree.len(), 500);

        for i in 0..1000 {
            if i % 2 == 0 {
                assert_eq!(tree.get(i), None);
            } else {
                assert_eq!(tree.get(i), Some(&i));
            }
        }
    }

    #[test]
    fn test_get_mut() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        tree.insert(5, 50);
        tree.insert(3, 30);
        tree.insert(7, 70);

        if let Some(v) = tree.get_mut(5) {
            *v = 500;
        }

        assert_eq!(tree.get(5), Some(&500));
        assert_eq!(tree.get(3), Some(&30));
    }

    #[test]
    fn test_cow_with_get_mut() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i, i);
        }

        let snapshot = tree.clone();

        if let Some(v) = tree.get_mut(50) {
            *v = 999;
        }

        assert_eq!(snapshot.get(50), Some(&50));
        assert_eq!(tree.get(50), Some(&999));
    }

    #[test]
    fn test_memory_size() {
        assert!(std::mem::size_of::<CowBTree<i64>>() <= 24);
    }

    #[test]
    fn test_entry_api() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        let v = tree.entry(1).or_insert(10);
        assert_eq!(*v, 10);
        assert_eq!(tree.get(1), Some(&10));

        let v = tree.entry(1).or_insert(20);
        assert_eq!(*v, 10);

        tree.entry(1).and_modify(|v| *v += 5);
        assert_eq!(tree.get(1), Some(&15));

        for i in 2..100 {
            tree.entry(i).or_insert(i * 10);
        }
        assert_eq!(tree.len(), 99);
        assert_eq!(tree.get(50), Some(&500));

        tree.entry(50).and_modify(|v| *v = 999);
        assert_eq!(tree.get(50), Some(&999));
    }

    #[test]
    fn test_entry_vacant() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        match tree.entry(42) {
            Entry::Occupied(_) => panic!("Expected vacant"),
            Entry::Vacant(v) => {
                assert_eq!(v.key(), 42);
                let val = v.insert(420);
                assert_eq!(*val, 420);
            }
        }
        assert_eq!(tree.get(42), Some(&420));
        assert_eq!(tree.len(), 1);

        tree.insert(10, 100);
        tree.insert(50, 500);

        match tree.entry(30) {
            Entry::Occupied(_) => panic!("Expected vacant"),
            Entry::Vacant(v) => {
                assert_eq!(v.key(), 30);
                v.insert(300);
            }
        }
        assert_eq!(tree.get(30), Some(&300));
        assert_eq!(tree.len(), 4);

        match tree.entry(5) {
            Entry::Occupied(_) => panic!("Expected vacant"),
            Entry::Vacant(v) => {
                v.insert(50);
            }
        }
        match tree.entry(100) {
            Entry::Occupied(_) => panic!("Expected vacant"),
            Entry::Vacant(v) => {
                v.insert(1000);
            }
        }
        assert_eq!(tree.get(5), Some(&50));
        assert_eq!(tree.get(100), Some(&1000));
    }

    #[test]
    fn test_entry_occupied() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i, i * 10);
        }

        match tree.entry(50) {
            Entry::Occupied(o) => {
                assert_eq!(o.key(), 50);
            }
            Entry::Vacant(_) => panic!("Expected occupied"),
        }

        match tree.entry(50) {
            Entry::Occupied(o) => {
                assert_eq!(*o.get(), 500);
            }
            Entry::Vacant(_) => panic!("Expected occupied"),
        }

        match tree.entry(50) {
            Entry::Occupied(mut o) => {
                *o.get_mut() = 5000;
            }
            Entry::Vacant(_) => panic!("Expected occupied"),
        }
        assert_eq!(tree.get(50), Some(&5000));

        match tree.entry(50) {
            Entry::Occupied(mut o) => {
                let old = o.insert(50000);
                assert_eq!(old, 5000);
            }
            Entry::Vacant(_) => panic!("Expected occupied"),
        }
        assert_eq!(tree.get(50), Some(&50000));

        let val_ref = match tree.entry(50) {
            Entry::Occupied(o) => o.into_mut(),
            Entry::Vacant(_) => panic!("Expected occupied"),
        };
        *val_ref = 500000;
        assert_eq!(tree.get(50), Some(&500000));
    }

    #[test]
    fn test_entry_cow_semantics() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i, i);
        }

        let snapshot = tree.clone();

        match tree.entry(50) {
            Entry::Occupied(mut o) => {
                o.insert(999);
            }
            Entry::Vacant(_) => panic!("Expected occupied"),
        }

        match tree.entry(200) {
            Entry::Occupied(_) => panic!("Expected vacant"),
            Entry::Vacant(v) => {
                v.insert(2000);
            }
        }

        assert_eq!(snapshot.get(50), Some(&50));
        assert_eq!(snapshot.get(200), None);
        assert_eq!(snapshot.len(), 100);

        assert_eq!(tree.get(50), Some(&999));
        assert_eq!(tree.get(200), Some(&2000));
        assert_eq!(tree.len(), 101);
    }

    #[test]
    fn test_entry_many_inserts() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..1000 {
            match tree.entry(i) {
                Entry::Occupied(_) => panic!("Should be vacant"),
                Entry::Vacant(v) => {
                    v.insert(i * 10);
                }
            }
        }

        assert_eq!(tree.len(), 1000);

        for i in 0..1000 {
            match tree.entry(i) {
                Entry::Occupied(mut o) => {
                    assert_eq!(*o.get(), i * 10);
                    o.insert(i * 20);
                }
                Entry::Vacant(_) => panic!("Should be occupied"),
            }
        }

        for i in 0..1000 {
            assert_eq!(tree.get(i), Some(&(i * 20)));
        }
    }

    #[test]
    fn test_node_path_limit() {
        let mut path = NodePath::new();
        for i in 0..MAX_TREE_DEPTH {
            path.push(i);
        }
        assert_eq!(path.len, MAX_TREE_DEPTH as u8);
    }

    #[test]
    fn test_entry_sequential_optimization() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        tree.insert(0, 0);

        for i in 1..1000 {
            tree.entry(i).or_insert(i * 10);
        }

        assert_eq!(tree.len(), 1000);
        assert_eq!(tree.get(999), Some(&9990));
        assert_eq!(tree.max_key, 999);
    }

    #[test]
    fn test_drop_is_called() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        #[derive(Clone)]
        #[allow(dead_code)]
        struct DropCounter(i64);

        impl Drop for DropCounter {
            fn drop(&mut self) {
                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        DROP_COUNT.store(0, Ordering::SeqCst);

        {
            let mut tree: CowBTree<DropCounter> = CowBTree::new();
            for i in 0..100 {
                tree.insert(i, DropCounter(i));
            }
            assert_eq!(tree.len(), 100);
        }

        let drops = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(drops, 100, "Expected 100 drops, got {}", drops);
    }

    #[test]
    fn test_drop_with_splits() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        #[derive(Clone)]
        #[allow(dead_code)]
        struct DropCounter(i64);

        impl Drop for DropCounter {
            fn drop(&mut self) {
                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        DROP_COUNT.store(0, Ordering::SeqCst);

        {
            let mut tree: CowBTree<DropCounter> = CowBTree::new();
            for i in 0..500 {
                tree.insert(i, DropCounter(i));
            }
            assert_eq!(tree.len(), 500);
        }

        let drops = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(drops, 500, "Expected 500 drops, got {}", drops);
    }

    #[test]
    fn test_drop_with_clone() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        #[derive(Clone)]
        #[allow(dead_code)]
        struct DropCounter(i64);

        impl Drop for DropCounter {
            fn drop(&mut self) {
                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        DROP_COUNT.store(0, Ordering::SeqCst);

        {
            let mut tree1: CowBTree<DropCounter> = CowBTree::new();
            for i in 0..100 {
                tree1.insert(i, DropCounter(i));
            }

            let tree2 = tree1.clone();
            assert_eq!(tree1.len(), 100);
            assert_eq!(tree2.len(), 100);

            drop(tree1);
            assert_eq!(
                DROP_COUNT.load(Ordering::SeqCst),
                0,
                "Data should not be dropped while clone exists"
            );
            drop(tree2);
        }

        let drops = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(
            drops, 100,
            "Expected 100 drops after both trees dropped, got {}",
            drops
        );
    }

    #[test]
    fn test_rightmost_split_optimization() {
        // Test that sequential inserts use rightmost split optimization
        // which achieves ~100% fill factor instead of 50%
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert enough to cause multiple splits
        // With MAX_KEYS=128, after 1000 inserts we should have ~8 leaf nodes
        // With standard 50% split: ~16 leaf nodes at 50% fill
        // With rightmost split: ~8 leaf nodes at ~100% fill
        for i in 0..1000 {
            tree.insert(i, i * 10);
        }

        assert_eq!(tree.len(), 1000);

        // Verify all values are correct
        for i in 0..1000 {
            assert_eq!(tree.get(i), Some(&(i * 10)), "Failed at key {}", i);
        }

        // Count leaf nodes and check fill factor
        let mut leaf_count = 0;
        let mut total_keys = 0;
        for (keys, _) in tree.iter_chunks() {
            leaf_count += 1;
            total_keys += keys.len();

            // All but the last (rightmost) leaf should be nearly full (MAX_KEYS)
            // The rightmost leaf can have 1..=MAX_KEYS keys
            // With rightmost split, non-rightmost leaves have exactly MAX_KEYS
        }

        assert_eq!(total_keys, 1000);

        // With rightmost split optimization:
        // - 1000 keys, MAX_KEYS=128
        // - First 7 leaves should have 128 keys each = 896 keys
        // - Last leaf should have 104 keys
        // - Total: 8 leaves
        //
        // Without optimization (50% split):
        // - Would have ~16 leaves at ~64 keys each

        // We expect 8 leaves (1000 / 128 = 7.8, rounded up)
        // Allow some variance, but should be much less than 16
        assert!(
            leaf_count <= 10,
            "Expected ~8 leaf nodes with rightmost split, got {} (suggests 50% split is being used)",
            leaf_count
        );

        // Verify fill factor: total_keys / (leaf_count * MAX_KEYS) should be > 75%
        let fill_factor = (total_keys as f64) / (leaf_count as f64 * MAX_KEYS as f64);
        assert!(
            fill_factor > 0.75,
            "Expected fill factor > 75%, got {:.1}%",
            fill_factor * 100.0
        );
    }

    #[test]
    fn test_rightmost_split_with_entry_api() {
        // Test that entry API also benefits from rightmost split
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..1000 {
            tree.entry(i).or_insert(i * 10);
        }

        assert_eq!(tree.len(), 1000);

        // Count leaves - should match the insert test
        let leaf_count = tree.iter_chunks().count();
        assert!(
            leaf_count <= 10,
            "Expected ~8 leaf nodes with rightmost split via entry API, got {}",
            leaf_count
        );
    }

    #[test]
    fn test_clear() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i, i * 10);
        }
        assert_eq!(tree.len(), 100);
        assert!(!tree.is_empty());

        tree.clear();
        assert_eq!(tree.len(), 0);
        assert!(tree.is_empty());
        assert_eq!(tree.get(50), None);

        // Can insert after clear
        tree.insert(1, 10);
        assert_eq!(tree.len(), 1);
        assert_eq!(tree.get(1), Some(&10));
    }

    #[test]
    fn test_values_iterator() {
        let mut tree: CowBTree<String> = CowBTree::new();

        tree.insert(3, "three".to_string());
        tree.insert(1, "one".to_string());
        tree.insert(2, "two".to_string());

        let values: Vec<&String> = tree.values().collect();
        // Values should be in key-sorted order
        assert_eq!(values, vec!["one", "two", "three"]);
    }

    #[test]
    fn test_range_unbounded() {
        use std::ops::Bound;

        let mut tree: CowBTree<i64> = CowBTree::new();
        for i in 0..100 {
            tree.insert(i, i);
        }

        // Unbounded start: ..50
        let range: Vec<i64> = tree.range(..50).map(|(k, _)| *k).collect();
        assert_eq!(range.len(), 50);
        assert_eq!(range[0], 0);
        assert_eq!(range[49], 49);

        // Unbounded end: 50..
        let range: Vec<i64> = tree.range(50..).map(|(k, _)| *k).collect();
        assert_eq!(range.len(), 50);
        assert_eq!(range[0], 50);
        assert_eq!(range[49], 99);

        // Fully unbounded: ..
        let range: Vec<i64> = tree.range(..).map(|(k, _)| *k).collect();
        assert_eq!(range.len(), 100);

        // RangeInclusive: 25..=75
        let range: Vec<i64> = tree.range(25..=75).map(|(k, _)| *k).collect();
        assert_eq!(range.len(), 51);
        assert_eq!(range[0], 25);
        assert_eq!(range[50], 75);

        // Custom bounds with Excluded start
        let range: Vec<i64> = tree
            .range((Bound::Excluded(25), Bound::Included(30)))
            .map(|(k, _)| *k)
            .collect();
        assert_eq!(range, vec![26, 27, 28, 29, 30]);
    }

    #[test]
    fn test_deletion_triggers_borrow_from_left() {
        // To trigger borrow_from_left, we need:
        // 1. A leaf node that falls below MIN_KEYS after deletion
        // 2. A left sibling with spare keys (more than MIN_KEYS)
        //
        // Strategy: Insert keys to create specific tree structure,
        // then delete from the right leaf to trigger borrowing from left.
        let mut tree: CowBTree<i64> = CowBTree::new();

        // With MAX_KEYS=128, MIN_KEYS=64
        // Insert 200 keys sequentially to get 2 leaves (128 + 72)
        for i in 0..200 {
            tree.insert(i, i);
        }

        // Now delete keys from the second leaf (keys 128-199) until it has < 64 keys
        // We need to delete more than 72 - 64 = 8 keys from the right leaf
        // to trigger underflow. Delete keys 190-199 (10 keys from end).
        for i in 190..200 {
            tree.remove(i);
        }

        // Should still have 190 keys
        assert_eq!(tree.len(), 190);

        // Continue deleting to trigger rebalancing
        // Delete more keys from the second leaf
        for i in 170..190 {
            tree.remove(i);
        }

        // Should have 170 keys
        assert_eq!(tree.len(), 170);

        // Verify tree integrity - all remaining keys should be accessible
        for i in 0..170 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_deletion_triggers_borrow_from_right() {
        // To trigger borrow_from_right, we need:
        // 1. A leaf node that falls below MIN_KEYS after deletion
        // 2. A right sibling with spare keys
        //
        // Strategy: Create tree, then delete from the LEFT leaf
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert 200 keys to get 2 leaves
        for i in 0..200 {
            tree.insert(i, i);
        }

        // Delete keys from the first leaf (keys 0-127) to trigger underflow
        // Delete keys 0-70 to make first leaf have < 64 keys
        for i in 0..71 {
            tree.remove(i);
        }

        // Should have 129 keys (200 - 71)
        assert_eq!(tree.len(), 129);

        // Verify tree integrity
        for i in 71..200 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_deletion_triggers_merge() {
        // To trigger merge, we need:
        // 1. A leaf node below MIN_KEYS
        // 2. A sibling also at or below MIN_KEYS (no spare keys to borrow)
        //
        // Strategy: Create minimal tree, delete until both siblings are at MIN_KEYS,
        // then delete one more to trigger merge.
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert 150 keys to create 2 leaves with ~75 each after split
        // Actually with rightmost split: first leaf has 128, second has 22
        // Let's insert more to have a more balanced scenario
        for i in 0..300 {
            tree.insert(i, i);
        }

        // Delete many keys to force merges
        // Delete all even keys first
        for i in (0..300).step_by(2) {
            tree.remove(i);
        }

        // Should have 150 keys
        assert_eq!(tree.len(), 150);

        // Delete more to trigger merges
        for i in (1..300).step_by(4) {
            tree.remove(i);
        }

        // Verify remaining keys
        let remaining: Vec<i64> = tree.keys().collect();
        for key in &remaining {
            assert_eq!(tree.get(*key), Some(key));
        }
    }

    #[test]
    fn test_heavy_deletion_rebalancing() {
        // Stress test for deletion rebalancing
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert 1000 keys
        for i in 0..1000 {
            tree.insert(i, i);
        }

        // Delete in a pattern that forces various rebalancing scenarios
        // Delete every 3rd key starting from 0
        for i in (0..1000).step_by(3) {
            tree.remove(i);
        }

        // Delete every 3rd key starting from 1
        for i in (1..1000).step_by(3) {
            tree.remove(i);
        }

        // Only keys where i % 3 == 2 remain (333 keys)
        let expected_count = (0..1000).filter(|i| i % 3 == 2).count();
        assert_eq!(tree.len(), expected_count);

        // Verify all remaining keys
        for i in 0..1000 {
            if i % 3 == 2 {
                assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
            } else {
                assert_eq!(tree.get(i), None, "Unexpected key {}", i);
            }
        }
    }

    #[test]
    fn test_delete_all_keys() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..500 {
            tree.insert(i, i);
        }

        // Delete all keys
        for i in 0..500 {
            assert_eq!(tree.remove(i), Some(i), "Failed to remove key {}", i);
        }

        assert!(tree.is_empty());
        assert_eq!(tree.len(), 0);

        // Can reuse the tree
        tree.insert(1, 1);
        assert_eq!(tree.get(1), Some(&1));
    }

    #[test]
    fn test_remove_from_internal_node() {
        // When removing a key that exists in an internal node (as separator),
        // the algorithm must replace it with predecessor/successor
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert enough to create internal nodes
        for i in 0..500 {
            tree.insert(i, i);
        }

        // Delete keys in the middle that might be internal node separators
        for i in 100..200 {
            assert_eq!(tree.remove(i), Some(i));
        }

        // Verify tree integrity
        for i in 0..100 {
            assert_eq!(tree.get(i), Some(&i));
        }
        for i in 100..200 {
            assert_eq!(tree.get(i), None);
        }
        for i in 200..500 {
            assert_eq!(tree.get(i), Some(&i));
        }
    }

    #[test]
    fn test_cow_with_deletion() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i, i);
        }

        let snapshot = tree.clone();

        // Delete from original
        for i in 0..50 {
            tree.remove(i);
        }

        // Snapshot should still have all keys
        assert_eq!(snapshot.len(), 100);
        for i in 0..100 {
            assert_eq!(snapshot.get(i), Some(&i));
        }

        // Original should have only keys 50-99
        assert_eq!(tree.len(), 50);
        for i in 0..50 {
            assert_eq!(tree.get(i), None);
        }
        for i in 50..100 {
            assert_eq!(tree.get(i), Some(&i));
        }
    }

    #[test]
    fn test_entry_key_method() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        tree.insert(10, 100);
        tree.insert(20, 200);

        // Test Entry::key() on occupied entry
        let key = tree.entry(10).key();
        assert_eq!(key, 10);

        // Test Entry::key() on vacant entry
        let key = tree.entry(15).key();
        assert_eq!(key, 15);

        // Verify tree wasn't modified by key() calls
        assert_eq!(tree.len(), 2);
    }

    #[test]
    fn test_and_modify_on_vacant() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        tree.insert(10, 100);

        // and_modify on vacant entry should return Vacant unchanged
        let entry = tree.entry(20).and_modify(|v| *v += 1);
        match entry {
            Entry::Vacant(v) => {
                assert_eq!(v.key(), 20);
                v.insert(200);
            }
            Entry::Occupied(_) => panic!("Expected Vacant after and_modify on non-existent key"),
        }

        assert_eq!(tree.get(20), Some(&200));

        // and_modify on occupied entry should modify the value
        tree.entry(10).and_modify(|v| *v += 1);
        assert_eq!(tree.get(10), Some(&101));
    }

    #[test]
    fn test_entry_api_root_split() {
        // Test that entry API correctly handles root splits
        // This happens when inserting via entry() causes the tree to grow a new level
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert enough keys to cause multiple splits via entry API
        // MAX_KEYS = 128, so after 128 inserts we get first split
        for i in 0..500 {
            tree.entry(i).or_insert(i * 10);
        }

        assert_eq!(tree.len(), 500);

        // Verify all values
        for i in 0..500 {
            assert_eq!(tree.get(i), Some(&(i * 10)));
        }
    }

    #[test]
    fn test_deep_tree_internal_node_split() {
        // Create a tree with 3+ levels to trigger internal node splitting
        // With MAX_KEYS=128, we need more than 128*128 = 16384 keys for 3 levels
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert 20000 keys to ensure 3-level tree
        for i in 0..20_000 {
            tree.insert(i, i);
        }

        assert_eq!(tree.len(), 20_000);

        // Verify random samples
        for i in (0..20_000).step_by(100) {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_deep_tree_internal_node_rebalancing() {
        // Create a deep tree and then delete keys to trigger internal node rebalancing
        // This tests borrow_from_left/right and merge operations on internal nodes
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert 20000 keys to create 3-level tree
        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Delete keys to trigger internal node underflow and rebalancing
        // Delete from the middle to maximize rebalancing
        for i in 5000..15000 {
            tree.remove(i);
        }

        assert_eq!(tree.len(), 10_000);

        // Verify remaining keys
        for i in 0..5000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
        for i in 5000..15000 {
            assert_eq!(tree.get(i), None, "Key {} should be deleted", i);
        }
        for i in 15000..20000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_deep_tree_random_deletion() {
        // Random deletion pattern to exercise various internal node operations
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Delete in a pattern that causes internal node rebalancing
        // Delete every 3rd key
        for i in (0..20_000).step_by(3) {
            tree.remove(i);
        }

        // Delete every 5th key of remaining
        for i in (1..20_000).step_by(5) {
            tree.remove(i);
        }

        // Verify integrity - remaining keys should still be accessible
        let remaining: Vec<i64> = tree.keys().collect();
        for key in &remaining {
            assert_eq!(tree.get(*key), Some(key));
        }
    }

    #[test]
    fn test_deep_tree_cow_semantics() {
        // Test COW semantics with deep tree
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20_000 {
            tree.insert(i, i);
        }

        let snapshot = tree.clone();

        // Modify original
        for i in 0..5000 {
            tree.remove(i);
        }
        tree.insert(25000, 25000);

        // Snapshot should be unchanged
        assert_eq!(snapshot.len(), 20_000);
        assert_eq!(snapshot.get(0), Some(&0));
        assert_eq!(snapshot.get(25000), None);

        // Original should have modifications
        assert_eq!(tree.len(), 15_001);
        assert_eq!(tree.get(0), None);
        assert_eq!(tree.get(25000), Some(&25000));
    }

    #[test]
    fn test_default_trait() {
        let tree: CowBTree<i64> = CowBTree::default();
        assert!(tree.is_empty());
        assert_eq!(tree.len(), 0);
    }

    #[test]
    fn test_empty_tree_range_iteration() {
        let tree: CowBTree<i64> = CowBTree::new();

        // Range on empty tree should return empty iterator
        let range: Vec<_> = tree.range(..).collect();
        assert!(range.is_empty());

        let range: Vec<_> = tree.range(0..100).collect();
        assert!(range.is_empty());

        let range: Vec<_> = tree.range(..50).collect();
        assert!(range.is_empty());

        // iter_chunks on empty tree
        let chunks: Vec<_> = tree.iter_chunks().collect();
        assert!(chunks.is_empty());

        // range_chunks on empty tree
        let chunks: Vec<_> = tree.range_chunks(0..100).collect();
        assert!(chunks.is_empty());
    }

    #[test]
    fn test_random_order_entry_api() {
        // Random order inserts via entry API triggers split_internal (non-rightmost path)
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Use a pseudo-random pattern to insert keys out of order
        let keys: Vec<i64> = (0..1000).map(|i| (i * 7919 + 13) % 10000).collect();

        for &k in &keys {
            tree.entry(k).or_insert(k * 10);
        }

        // Verify all inserted values
        for &k in &keys {
            assert_eq!(tree.get(k), Some(&(k * 10)), "Missing key {}", k);
        }
    }

    #[test]
    fn test_random_order_entry_api_large() {
        // Larger random order inserts to ensure internal node splits
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Generate keys in random order
        let keys: Vec<i64> = (0..5000).map(|i| (i * 7919 + 13) % 50000).collect();

        for &k in &keys {
            tree.entry(k).or_insert(k);
        }

        // Verify all keys are present
        for &k in &keys {
            assert!(tree.contains_key(k), "Missing key {}", k);
        }
    }

    #[test]
    fn test_range_on_deep_tree() {
        // Range iteration on a deep tree exercises seek_to_start internal node path
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Range in the middle of the tree
        let range: Vec<i64> = tree.range(5000..5100).map(|(k, _)| *k).collect();
        assert_eq!(range.len(), 100);
        assert_eq!(range[0], 5000);
        assert_eq!(range[99], 5099);

        // Range with excluded start bound
        use std::ops::Bound;
        let range: Vec<i64> = tree
            .range((Bound::Excluded(10000), Bound::Included(10010)))
            .map(|(k, _)| *k)
            .collect();
        assert_eq!(range.len(), 10);
        assert_eq!(range[0], 10001);
        assert_eq!(range[9], 10010);

        // Unbounded range on deep tree
        let count = tree.range(..).count();
        assert_eq!(count, 20_000);
    }

    #[test]
    fn test_range_chunks_on_deep_tree() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Range chunks in the middle
        let mut total = 0;
        for (keys, values) in tree.range_chunks(5000..6000) {
            assert_eq!(keys.len(), values.len());
            total += keys.len();
        }
        assert_eq!(total, 1000);
    }

    #[test]
    fn test_deep_tree_delete_from_left_internal() {
        // Delete pattern that triggers borrow_from_right on internal nodes
        // We need to delete from the LEFT side of a deep tree to make left internal
        // nodes underflow while right internal nodes have spare keys
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert 20K keys for 3-level tree
        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Delete the first 8000 keys - this should cause internal node rebalancing
        // where left internal nodes need to borrow from right siblings
        for i in 0..8000 {
            tree.remove(i);
        }

        assert_eq!(tree.len(), 12_000);

        // Verify remaining keys
        for i in 8000..20_000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_deep_tree_delete_alternating_pattern() {
        // Alternating delete pattern to exercise more internal node paths
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Delete in an alternating pattern across the tree
        // First delete from beginning
        for i in 0..3000 {
            tree.remove(i);
        }

        // Then delete from end
        for i in 17000..20_000 {
            tree.remove(i);
        }

        // Then delete from middle
        for i in 8000..12000 {
            tree.remove(i);
        }

        // Verify deleted keys are gone
        for i in 0..3000 {
            assert_eq!(tree.get(i), None, "Key {} should be deleted", i);
        }
        for i in 17000..20_000 {
            assert_eq!(tree.get(i), None, "Key {} should be deleted", i);
        }
        for i in 8000..12000 {
            assert_eq!(tree.get(i), None, "Key {} should be deleted", i);
        }

        // Verify remaining keys exist
        for i in 3000..8000 {
            assert_eq!(tree.get(i), Some(&i), "Key {} should exist", i);
        }
        for i in 12000..17000 {
            assert_eq!(tree.get(i), Some(&i), "Key {} should exist", i);
        }
    }

    #[test]
    fn test_entry_on_deep_tree_random() {
        // Entry API with random keys on deep tree
        let mut tree: CowBTree<i64> = CowBTree::new();

        // First build a deep tree sequentially
        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Now use entry API with random access patterns
        for i in (0..20_000).step_by(7) {
            tree.entry(i).and_modify(|v| *v *= 2);
        }

        // Verify modifications
        for i in 0..20_000 {
            if i % 7 == 0 {
                assert_eq!(tree.get(i), Some(&(i * 2)));
            } else {
                assert_eq!(tree.get(i), Some(&i));
            }
        }
    }

    #[test]
    fn test_iter_on_deep_tree() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // iter() should return all keys in order
        let keys: Vec<i64> = tree.keys().collect();
        assert_eq!(keys.len(), 20_000);
        for (i, k) in keys.iter().enumerate() {
            assert_eq!(*k, i as i64);
        }

        // values() should return all values in order
        let values: Vec<&i64> = tree.values().collect();
        assert_eq!(values.len(), 20_000);
        for (i, v) in values.iter().enumerate() {
            assert_eq!(**v, i as i64);
        }
    }

    #[test]
    fn test_get_mut_on_deep_tree() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // get_mut at various positions
        if let Some(v) = tree.get_mut(0) {
            *v = 999;
        }
        if let Some(v) = tree.get_mut(10000) {
            *v = 888;
        }
        if let Some(v) = tree.get_mut(19999) {
            *v = 777;
        }

        assert_eq!(tree.get(0), Some(&999));
        assert_eq!(tree.get(10000), Some(&888));
        assert_eq!(tree.get(19999), Some(&777));
    }

    #[test]
    fn test_contains_key() {
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..100 {
            tree.insert(i * 2, i);
        }

        // Even keys should exist
        for i in 0..100 {
            assert!(tree.contains_key(i * 2));
        }

        // Odd keys should not exist
        for i in 0..100 {
            assert!(!tree.contains_key(i * 2 + 1));
        }
    }

    #[test]
    fn test_reverse_order_inserts() {
        // Reverse order inserts force standard split_internal (not rightmost)
        // because we're always inserting at the leftmost position
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert in reverse order to trigger split_internal (midpoint split)
        for i in (0..5000).rev() {
            tree.insert(i, i);
        }

        assert_eq!(tree.len(), 5000);

        // Verify all keys
        for i in 0..5000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }

        // Verify iteration order
        let keys: Vec<i64> = tree.keys().collect();
        for (idx, &k) in keys.iter().enumerate() {
            assert_eq!(k, idx as i64);
        }
    }

    #[test]
    fn test_shuffled_inserts_large() {
        // Shuffled inserts to trigger standard split_internal paths
        // Using a shuffle pattern that avoids sequential rightmost inserts
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Generate shuffled keys - interleave from both ends
        let mut keys: Vec<i64> = Vec::with_capacity(10000);
        for i in 0..5000 {
            keys.push(i * 2); // Even: 0, 2, 4, ...
            keys.push(i * 2 + 1); // Odd: 1, 3, 5, ...
        }
        // Reverse half to make it more shuffled
        for i in 0..5000 {
            keys.swap(i, 9999 - i);
        }

        for &k in &keys {
            tree.insert(k, k);
        }

        assert_eq!(tree.len(), 10000);

        for i in 0..10000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_internal_node_borrow_from_right() {
        // This test triggers internal node borrow_from_right (the else branch)
        // by creating a 3-level tree and causing internal node underflow
        // where the right sibling is also an internal node (not a leaf)
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Use a shuffle pattern to ensure we don't get the rightmost-optimized splits
        // This creates a more balanced tree with internal nodes that can borrow from each other
        let mut keys: Vec<i64> = (0..50_000).collect();
        // Shuffle using a deterministic pattern
        for i in 0..keys.len() {
            let j = (i * 31337 + 17) % keys.len();
            keys.swap(i, j);
        }

        for &k in &keys {
            tree.insert(k, k);
        }

        assert_eq!(tree.len(), 50_000);

        // Delete a large contiguous region from the left side
        // This should cause leaf merges in that region, which cascade up
        // to cause internal node underflow and borrow/merge operations
        for i in 0..20_000 {
            tree.remove(i);
        }

        assert_eq!(tree.len(), 30_000);

        // Verify remaining keys
        for i in 0..20_000 {
            assert_eq!(tree.get(i), None, "Key {} should be deleted", i);
        }
        for i in 20_000..50_000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_internal_node_merge_cascade() {
        // Trigger internal node merge by deleting enough to cause cascade
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Use reverse interleaving for balanced structure
        for i in 0..30_000 {
            let key = if i % 2 == 0 {
                i / 2
            } else {
                30_000 - 1 - i / 2
            };
            tree.insert(key, key);
        }

        // Delete from multiple regions to trigger internal node merges
        // Delete first third
        for i in 0..10_000 {
            tree.remove(i);
        }

        // Delete last third
        for i in 20_000..30_000 {
            tree.remove(i);
        }

        // Verify remaining keys in middle third
        for i in 10_000..20_000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_massive_deletion_internal_rebalance() {
        // Create large tree and delete 90% of keys to heavily exercise internal node rebalancing
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Interleaved insert pattern
        for i in 0..60_000 {
            let key = (i * 7919) % 60_000;
            tree.insert(key, key);
        }

        // Delete 90% - keep only every 10th key
        for i in 0..60_000 {
            if i % 10 != 0 {
                tree.remove(i);
            }
        }

        assert_eq!(tree.len(), 6000);

        // Verify remaining keys
        for i in (0..60_000).step_by(10) {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_left_heavy_deletion() {
        // Delete heavily from left side to trigger internal node borrow from right
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Build tree with reverse order to create left-biased structure
        for i in (0..22_000).rev() {
            tree.insert(i, i);
        }

        // Delete 80% from left side
        for i in 0..17_600 {
            tree.remove(i);
        }

        assert_eq!(tree.len(), 4400);

        // Verify
        for i in 17_600..22_000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_right_heavy_deletion() {
        // Delete heavily from right side to trigger borrow from left
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Sequential insert for rightmost structure
        for i in 0..30_000 {
            tree.insert(i, i);
        }

        // Delete 80% from right side
        for i in 6000..30_000 {
            tree.remove(i);
        }

        assert_eq!(tree.len(), 6000);

        // Verify
        for i in 0..6000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_alternating_sides_deletion() {
        // Alternate between deleting from left and right to exercise both borrow directions
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..30_000 {
            tree.insert(i, i);
        }

        // Delete from ends alternating
        let mut left = 0;
        let mut right = 29_999;
        for _ in 0..20_000 {
            if left < right {
                tree.remove(left);
                left += 1;
            }
            if left < right {
                tree.remove(right);
                right -= 1;
            }
        }

        // Verify middle section
        for i in left..=right {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_entry_api_reverse_order() {
        // Entry API with reverse order to trigger split_internal (not rightmost)
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in (0..3000).rev() {
            tree.entry(i).or_insert(i * 10);
        }

        assert_eq!(tree.len(), 3000);

        for i in 0..3000 {
            assert_eq!(tree.get(i), Some(&(i * 10)));
        }
    }

    #[test]
    fn test_cow_during_internal_rebalancing() {
        // Test COW semantics are maintained during internal node rebalancing
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Create deep tree
        for i in 0..30_000 {
            tree.insert(i, i);
        }

        // Clone before deletions
        let snapshot = tree.clone();

        // Delete heavily to trigger internal rebalancing
        for i in 0..20_000 {
            tree.remove(i);
        }

        // Snapshot must be intact
        assert_eq!(snapshot.len(), 30_000);
        for i in 0..30_000 {
            assert_eq!(snapshot.get(i), Some(&i), "Snapshot missing key {}", i);
        }

        // Modified tree
        assert_eq!(tree.len(), 10_000);
        for i in 0..20_000 {
            assert_eq!(tree.get(i), None);
        }
        for i in 20_000..30_000 {
            assert_eq!(tree.get(i), Some(&i));
        }
    }

    #[test]
    fn test_zigzag_insert_pattern() {
        // Insert in zigzag pattern: 0, 9999, 1, 9998, 2, 9997, ...
        // This forces many internal node splits at non-rightmost positions
        let mut tree: CowBTree<i64> = CowBTree::new();

        for i in 0..5000 {
            tree.insert(i, i);
            tree.insert(9999 - i, 9999 - i);
        }

        assert_eq!(tree.len(), 10000);

        for i in 0..10000 {
            assert_eq!(tree.get(i), Some(&i), "Missing key {}", i);
        }
    }

    #[test]
    fn test_middle_insert_split() {
        // Insert at middle positions to force non-rightmost splits
        let mut tree: CowBTree<i64> = CowBTree::new();

        // First insert boundaries
        for i in (0..5000).step_by(100) {
            tree.insert(i, i);
        }

        // Then fill in midpoints repeatedly
        for gap in [50i64, 25, 12, 6, 3, 1] {
            let mut i = gap;
            while i < 5000 {
                if tree.get(i).is_none() {
                    tree.insert(i, i);
                }
                i += gap * 2;
            }
        }

        // Fill any remaining gaps
        for i in 0..5000 {
            if tree.get(i).is_none() {
                tree.insert(i, i);
            }
        }

        assert_eq!(tree.len(), 5000);

        for i in 0..5000 {
            assert_eq!(tree.get(i), Some(&i));
        }
    }

    #[test]
    fn test_update_separator_keys() {
        // This test triggers the Ok(i) => i + 1 path in insert_recursive
        // by updating keys that are separator keys in internal nodes.
        // Separator keys are promoted during splits.
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert in reverse order to use insert_recursive (not rightmost optimization)
        // This ensures splits go through split_internal, not split_internal_rightmost
        for i in (0..1000).rev() {
            tree.insert(i, i);
        }

        // Now update ALL keys - some of them are separator keys in internal nodes
        // When we update a separator key, search returns Ok(i) and we go to child i+1
        for i in 0..1000 {
            let old = tree.insert(i, i * 100);
            assert_eq!(old, Some(i), "Key {} should have existed", i);
        }

        // Verify updates
        for i in 0..1000 {
            assert_eq!(tree.get(i), Some(&(i * 100)));
        }
    }

    #[test]
    fn test_reverse_insert_internal_node_split() {
        // This test ensures split_internal() (not split_internal_rightmost) is called
        // by inserting in reverse order with enough keys to overflow internal nodes.
        // With MAX_KEYS=128, we need 128*128 = 16384+ keys for 3 levels.
        let mut tree: CowBTree<i64> = CowBTree::new();

        // Insert 20K keys in reverse order
        // All inserts go through insert_recursive since key < max_key
        for i in (0..20_000).rev() {
            tree.insert(i, i);
        }

        assert_eq!(tree.len(), 20_000);

        // Verify all keys
        for i in (0..20_000).step_by(100) {
            assert_eq!(tree.get(i), Some(&i));
        }
    }

    #[test]
    fn test_iter_rev() {
        let mut tree: CowBTree<i64> = CowBTree::new();
        for i in 0..500 {
            tree.insert(i, i * 10);
        }

        // iter_rev should yield all entries in descending key order
        let rev: Vec<(i64, i64)> = tree.iter_rev().map(|(&k, &v)| (k, v)).collect();
        assert_eq!(rev.len(), 500);
        for (i, &(k, v)) in rev.iter().enumerate() {
            assert_eq!(k, 499 - i as i64);
            assert_eq!(v, k * 10);
        }

        // iter_rev on empty tree
        let empty: CowBTree<i64> = CowBTree::new();
        assert_eq!(empty.iter_rev().count(), 0);
    }

    #[test]
    fn test_range_rev() {
        let mut tree: CowBTree<i64> = CowBTree::new();
        for i in 0..500 {
            tree.insert(i, i * 10);
        }

        // range_rev with Excluded start, Unbounded end (keyset pagination pattern)
        let result: Vec<(i64, i64)> = tree
            .range_rev((std::ops::Bound::Excluded(100), std::ops::Bound::Unbounded))
            .map(|(&k, &v)| (k, v))
            .collect();
        assert_eq!(result.len(), 399); // 101..499 inclusive
        assert_eq!(result[0], (499, 4990)); // Largest first
        assert_eq!(result[398], (101, 1010)); // Smallest last

        // range_rev with Included start, Unbounded end
        let result: Vec<(i64, i64)> = tree
            .range_rev((std::ops::Bound::Included(100), std::ops::Bound::Unbounded))
            .map(|(&k, &v)| (k, v))
            .collect();
        assert_eq!(result.len(), 400); // 100..499 inclusive
        assert_eq!(result[0], (499, 4990));
        assert_eq!(result[399], (100, 1000));

        // range_rev with both bounds
        let result: Vec<(i64, i64)> = tree
            .range_rev((
                std::ops::Bound::Included(200),
                std::ops::Bound::Excluded(300),
            ))
            .map(|(&k, &v)| (k, v))
            .collect();
        assert_eq!(result.len(), 100); // 200..299 inclusive
        assert_eq!(result[0], (299, 2990));
        assert_eq!(result[99], (200, 2000));

        // range_rev with Included end
        let result: Vec<(i64, i64)> = tree
            .range_rev((
                std::ops::Bound::Included(200),
                std::ops::Bound::Included(300),
            ))
            .map(|(&k, &v)| (k, v))
            .collect();
        assert_eq!(result.len(), 101); // 200..=300 inclusive
        assert_eq!(result[0], (300, 3000));
        assert_eq!(result[100], (200, 2000));

        // range_rev unbounded both sides = iter_rev
        let all_rev: Vec<i64> = tree
            .range_rev((
                std::ops::Bound::Unbounded,
                std::ops::Bound::Unbounded::<i64>,
            ))
            .map(|(&k, _)| k)
            .collect();
        let iter_rev: Vec<i64> = tree.iter_rev().map(|(&k, _)| k).collect();
        assert_eq!(all_rev, iter_rev);
    }

    #[test]
    fn test_iter_rev_on_deep_tree() {
        let mut tree: CowBTree<i64> = CowBTree::new();
        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // iter_rev should return all keys in reverse order
        let rev_keys: Vec<i64> = tree.iter_rev().map(|(&k, _)| k).collect();
        assert_eq!(rev_keys.len(), 20_000);
        for (i, &k) in rev_keys.iter().enumerate() {
            assert_eq!(k, 19_999 - i as i64);
        }

        // Taking a small prefix is O(limit), not O(n)
        let first_5: Vec<i64> = tree.iter_rev().map(|(&k, _)| k).take(5).collect();
        assert_eq!(first_5, vec![19_999, 19_998, 19_997, 19_996, 19_995]);
    }

    #[test]
    fn test_range_rev_on_deep_tree() {
        let mut tree: CowBTree<i64> = CowBTree::new();
        for i in 0..20_000 {
            tree.insert(i, i);
        }

        // Keyset pagination pattern: WHERE id > 15000 ORDER BY id DESC LIMIT 5
        let page: Vec<i64> = tree
            .range_rev((
                std::ops::Bound::Excluded(15_000),
                std::ops::Bound::Unbounded,
            ))
            .map(|(&k, _)| k)
            .take(5)
            .collect();
        assert_eq!(page, vec![19_999, 19_998, 19_997, 19_996, 19_995]);

        // Keyset pagination: WHERE id > 5000 ORDER BY id DESC LIMIT 5
        let page: Vec<i64> = tree
            .range_rev((std::ops::Bound::Excluded(5_000), std::ops::Bound::Unbounded))
            .map(|(&k, _)| k)
            .take(5)
            .collect();
        assert_eq!(page, vec![19_999, 19_998, 19_997, 19_996, 19_995]);

        // Bounded range in reverse
        let result: Vec<i64> = tree
            .range_rev((
                std::ops::Bound::Included(10_000),
                std::ops::Bound::Excluded(10_010),
            ))
            .map(|(&k, _)| k)
            .collect();
        assert_eq!(
            result,
            vec![10_009, 10_008, 10_007, 10_006, 10_005, 10_004, 10_003, 10_002, 10_001, 10_000]
        );
    }
}