bazaar 3.5.2

Rust implementation of the Bazaar formats and protocols
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
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
//! Persistent maps from tuple_of_strings->string using CHK stores.
//!
//! Overview and current status:
//!
//! The CHKMap class implements a dict from tuple_of_strings->string by using a trie
//! with internal nodes of 8-bit fan out; The key tuples are mapped to strings by
//! joining them by \x00, and \x00 padding shorter keys out to the length of the
//! longest key. Leaf nodes are packed as densely as possible, and internal nodes
//! are all an additional 8-bits wide leading to a sparse upper tree.
//!
//! Updates to a CHKMap are done preferentially via the apply_delta method, to
//! allow optimisation of the update operation; but individual map/unmap calls are
//! possible and supported. Individual changes via map/unmap are buffered in memory
//! until the _save method is called to force serialisation of the tree.
//! apply_delta records its changes immediately by performing an implicit _save.
//!
//! # Todo
//!
//! Densely packed upper nodes.

use crc32fast::Hasher;

use std::fmt::Write;
use std::hash::Hash;
use std::iter::zip;

fn crc32(bit: &[u8]) -> u32 {
    let mut hasher = Hasher::new();
    hasher.update(bit);
    hasher.finalize()
}

pub type SerialisedKey = Vec<u8>;

/// If a ChildNode falls below this many bytes, we check for a remap.
/// Mirrors Python's `_INTERESTING_NEW_SIZE`.
pub const INTERESTING_NEW_SIZE: usize = 50;
/// If a ChildNode shrinks by more than this amount, we check for a remap.
/// Mirrors Python's `_INTERESTING_SHRINKAGE_LIMIT`.
pub const INTERESTING_SHRINKAGE_LIMIT: usize = 20;

/// Map the key tuple into a search string that just uses the key bytes.
pub fn search_key_plain(key: &Key) -> SerializedKey {
    key.0.join(&b'\x00')
}

pub fn search_key_16(key: &Key) -> SerializedKey {
    let mut result = String::new();
    for bit in key.iter() {
        write!(&mut result, "{:08X}\x00", crc32(bit)).unwrap();
    }
    result.pop();
    result.as_bytes().to_vec()
}

pub fn search_key_255(key: &Key) -> SerializedKey {
    let mut result = vec![];
    for bit in key.iter() {
        let crc = crc32(bit);
        let crc_bytes = crc.to_be_bytes();
        result.extend(crc_bytes);
        result.push(0x00);
    }
    result.pop();
    result
        .iter()
        .map(|b| if *b == 0x0A { b'_' } else { *b })
        .collect()
}

/// The set of search-key functions a CHKMap may be configured with.
///
/// `Plain` / `Hash16Way` / `Hash255Way` mirror the entries registered in
/// Python's `search_key_registry` for production use. `Custom` carries a
/// boxed closure for callers (most often test code) that register their
/// own — the pyo3 layer adapts a Python callable into a `Custom` variant.
#[derive(Clone)]
pub enum SearchKeyFunc {
    /// `b"plain"` — `b"\x00".join(key)`.
    Plain,
    /// `b"hash-16-way"` — 8-char uppercase hex of `crc32(part)` joined by NUL.
    Hash16Way,
    /// `b"hash-255-way"` — big-endian `crc32(part)` bytes joined by NUL,
    /// with any `\n` byte rewritten to `_`.
    Hash255Way,
    /// Any other callable, identified by a free-form name. The bytes
    /// returned by `name()` for a `Custom` variant come straight from
    /// the caller — they may not appear in `from_name`'s lookup table.
    Custom {
        name: Vec<u8>,
        func: std::sync::Arc<dyn Fn(&Key) -> SerializedKey + Send + Sync>,
    },
}

impl std::fmt::Debug for SearchKeyFunc {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SearchKeyFunc::Plain => f.write_str("Plain"),
            SearchKeyFunc::Hash16Way => f.write_str("Hash16Way"),
            SearchKeyFunc::Hash255Way => f.write_str("Hash255Way"),
            SearchKeyFunc::Custom { name, .. } => write!(f, "Custom({:?})", name),
        }
    }
}

impl PartialEq for SearchKeyFunc {
    /// Built-in variants compare equal by tag; `Custom` variants are
    /// only equal when their `Arc`s point at the same closure.
    fn eq(&self, other: &Self) -> bool {
        use SearchKeyFunc::*;
        match (self, other) {
            (Plain, Plain) | (Hash16Way, Hash16Way) | (Hash255Way, Hash255Way) => true,
            (Custom { func: a, .. }, Custom { func: b, .. }) => std::sync::Arc::ptr_eq(a, b),
            _ => false,
        }
    }
}

impl Eq for SearchKeyFunc {}

impl SearchKeyFunc {
    /// Resolve a registry name to a built-in variant. Unknown names
    /// return the raw bytes back; the caller may wrap them in a
    /// `Custom` variant with a closure of its own.
    pub fn from_name(name: &[u8]) -> Result<Self, Vec<u8>> {
        match name {
            b"plain" => Ok(SearchKeyFunc::Plain),
            b"hash-16-way" => Ok(SearchKeyFunc::Hash16Way),
            b"hash-255-way" => Ok(SearchKeyFunc::Hash255Way),
            other => Err(other.to_vec()),
        }
    }

    /// Wire name as it appears in serialised inventories.
    pub fn name(&self) -> &[u8] {
        match self {
            SearchKeyFunc::Plain => b"plain",
            SearchKeyFunc::Hash16Way => b"hash-16-way",
            SearchKeyFunc::Hash255Way => b"hash-255-way",
            SearchKeyFunc::Custom { name, .. } => name.as_slice(),
        }
    }

    /// Apply this variant's search-key transform to `key`.
    pub fn apply(&self, key: &Key) -> SerializedKey {
        match self {
            SearchKeyFunc::Plain => search_key_plain(key),
            SearchKeyFunc::Hash16Way => search_key_16(key),
            SearchKeyFunc::Hash255Way => search_key_255(key),
            SearchKeyFunc::Custom { func, .. } => func(key),
        }
    }
}

impl Default for SearchKeyFunc {
    fn default() -> Self {
        SearchKeyFunc::Plain
    }
}

pub fn bytes_to_text_key(data: &[u8]) -> Result<(&[u8], &[u8]), String> {
    let sections: Vec<&[u8]> = data.split(|&byte| byte == b'\n').collect();

    let delimiter_position = sections[0].windows(2).position(|window| window == b": ");

    if delimiter_position.is_none() {
        return Err("Invalid key file".to_string());
    }

    let (_kind, file_id) = sections[0].split_at(delimiter_position.unwrap() + 2);

    Ok((file_id, sections[3]))
}

#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct Key(Vec<Vec<u8>>);

impl From<Vec<Vec<u8>>> for Key {
    fn from(v: Vec<Vec<u8>>) -> Self {
        Key(v)
    }
}

impl Key {
    pub fn serialize(&self) -> SerializedKey {
        let mut result = vec![];
        for bit in self.0.iter() {
            result.extend(bit);
            result.push(0x00);
        }
        result.pop();
        result
    }

    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn iter(&self) -> impl Iterator<Item = &[u8]> {
        self.0.iter().map(|v| v.as_slice())
    }
}

impl std::ops::Index<usize> for Key {
    type Output = Vec<u8>;

    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl std::fmt::Display for Key {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let mut first = true;
        for bit in &self.0 {
            if !first {
                write!(f, "/")?;
            }
            first = false;
            write!(f, "{}", String::from_utf8_lossy(bit))?;
        }
        Ok(())
    }
}

pub type SerializedKey = Vec<u8>;

pub type Value = Vec<u8>;

#[derive(Debug)]
pub enum Error {
    InconsistentDeltaDelta(Vec<(Option<Key>, Option<Key>, Value)>, String),
    DeserializeError(String),
    /// A precondition or invariant was violated. Mirrors Python's
    /// `AssertionError` paths in chk_map.py — usually a bug in the
    /// caller, not a corrupt input.
    AssertionFailed(String),
}

impl From<std::num::ParseIntError> for Error {
    fn from(e: std::num::ParseIntError) -> Self {
        Error::DeserializeError(format!("Failed to parse int: {}", e))
    }
}

/// Given 2 strings, return the longest prefix common to both.
///
/// # Arguments
/// * `prefix` - This has been the common prefix for other keys, so it is more likely to be the common prefix in this case as well.
/// * `key` - Another string to compare to.
pub fn common_prefix_pair<'b>(prefix: &[u8], key: &'b [u8]) -> &'b [u8] {
    if key.starts_with(prefix) {
        return &key[..prefix.len()];
    }
    let mut p = 0;
    // Is there a better way to do this?
    for (left, right) in zip(prefix, key) {
        if left != right {
            break;
        }
        p += 1;
    }

    let p = p as usize;
    &key[..p]
}

#[test]
fn test_common_prefix_pair() {
    assert_eq!(common_prefix_pair(b"abc", b"abc"), b"abc");
    assert_eq!(common_prefix_pair(b"abc", b"abcd"), b"abc");
    assert_eq!(common_prefix_pair(b"abc", b"ab"), b"ab");
    assert_eq!(common_prefix_pair(b"abc", b"bbd"), b"");
    assert_eq!(common_prefix_pair(b"", b"bbc"), b"");
    assert_eq!(common_prefix_pair(b"abc", b""), b"");
}

/// Given a list of keys, find their common prefix.
///
/// # Arguments
/// * `keys`: An iterable of strings.
///
/// # Returns
/// The longest common prefix of all keys.
pub fn common_prefix_many<'a>(mut keys: impl Iterator<Item = &'a [u8]> + 'a) -> Option<&'a [u8]> {
    let mut cp = keys.next()?;
    for key in keys {
        cp = common_prefix_pair(cp, key);
        if cp.is_empty() {
            // if common_prefix is the empty string, then we know it won't
            // change further
            break;
        }
    }
    Some(cp)
}

/// Parsed contents of a serialised CHK leaf node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedLeafNode {
    pub maximum_size: usize,
    pub key_width: usize,
    pub length: usize,
    /// Common serialised prefix applied to every key line before splitting.
    /// Empty means there was no prefix line (or it was genuinely empty).
    pub common_serialised_prefix: Vec<u8>,
    /// (key_tuple, value) pairs in the order they appear in the serialised
    /// form — the caller is responsible for placing them in a dict.
    pub items: Vec<(Vec<Vec<u8>>, Vec<u8>)>,
    /// Matches `LeafNode._raw_size` as computed by the Python parser:
    /// `sum(len(l) for l in lines[5:]) + length*len(prefix) + (len(lines)-5)`.
    pub raw_size: usize,
}

/// Deserialise the serialised form of a CHK leaf node.
pub fn deserialise_leaf_node(data: &[u8]) -> Result<ParsedLeafNode, Error> {
    // Python does `data.split(b"\n")` which yields an empty trailing element
    // for a final newline; the parser insists on exactly that.
    let mut lines: Vec<&[u8]> = data.split(|&b| b == b'\n').collect();
    let trailing = lines
        .pop()
        .ok_or_else(|| Error::DeserializeError("empty leaf node body".into()))?;
    if !trailing.is_empty() {
        return Err(Error::DeserializeError(
            "leaf node did not end with final newline".into(),
        ));
    }
    if lines.len() < 5 {
        return Err(Error::DeserializeError(
            "leaf node truncated before item lines".into(),
        ));
    }
    if lines[0] != b"chkleaf:" {
        return Err(Error::DeserializeError("not a serialised leaf node".into()));
    }
    let maximum_size = parse_decimal(lines[1], "maximum_size")?;
    let width = parse_decimal(lines[2], "key_width")?;
    let length = parse_decimal(lines[3], "length")?;
    let prefix = lines[4];

    let mut items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = Vec::with_capacity(length);
    let mut pos = 5usize;
    while pos < lines.len() {
        // Reconstitute the full key line by prepending the common prefix,
        // then split on NUL to recover the key elements + final count.
        let mut full = Vec::with_capacity(prefix.len() + lines[pos].len());
        full.extend_from_slice(prefix);
        full.extend_from_slice(lines[pos]);
        pos += 1;

        let mut elements: Vec<Vec<u8>> = full.split(|&b| b == 0).map(|s| s.to_vec()).collect();
        if elements.len() != width + 1 {
            return Err(Error::DeserializeError(format!(
                "incorrect number of elements ({} vs {}) for leaf line",
                elements.len(),
                width + 1
            )));
        }
        let count_bytes = elements.pop().expect("just checked non-empty");
        let num_value_lines = parse_decimal(&count_bytes, "value line count")?;
        if pos + num_value_lines > lines.len() {
            return Err(Error::DeserializeError(
                "leaf node value line runs past end of body".into(),
            ));
        }
        let value_lines = &lines[pos..pos + num_value_lines];
        pos += num_value_lines;
        // Join the value lines with literal '\n' to reconstruct the value.
        let value_len =
            value_lines.iter().map(|l| l.len()).sum::<usize>() + num_value_lines.saturating_sub(1);
        let mut value = Vec::with_capacity(value_len);
        for (i, line) in value_lines.iter().enumerate() {
            if i > 0 {
                value.push(b'\n');
            }
            value.extend_from_slice(line);
        }
        items.push((elements, value));
    }
    if items.len() != length {
        return Err(Error::DeserializeError(format!(
            "item count ({}) mismatch: found {}",
            length,
            items.len()
        )));
    }

    // Reproduce LeafNode._raw_size exactly (see the Python implementation).
    let suffix_bytes: usize = lines[5..].iter().map(|l| l.len()).sum();
    let raw_size = suffix_bytes + length * prefix.len() + (lines.len() - 5);

    Ok(ParsedLeafNode {
        maximum_size,
        key_width: width,
        length,
        common_serialised_prefix: prefix.to_vec(),
        items,
        raw_size,
    })
}

/// Parsed contents of a serialised CHK internal node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedInternalNode {
    pub maximum_size: usize,
    pub key_width: usize,
    pub length: usize,
    pub search_prefix: Vec<u8>,
    /// (reconstructed_prefix, child_sha1_key) pairs in file order.
    pub items: Vec<(Vec<u8>, Vec<u8>)>,
    /// Length of the last parsed prefix — matches how Python's loop variable
    /// leaks out into `InternalNode._node_width`.
    pub node_width: usize,
}

/// Deserialise the serialised form of a CHK internal node.
pub fn deserialise_internal_node(data: &[u8]) -> Result<ParsedInternalNode, Error> {
    let mut lines: Vec<&[u8]> = data.split(|&b| b == b'\n').collect();
    let trailing = lines
        .pop()
        .ok_or_else(|| Error::DeserializeError("empty internal node body".into()))?;
    if !trailing.is_empty() {
        return Err(Error::DeserializeError("last line must be ''".into()));
    }
    if lines.len() < 5 {
        return Err(Error::DeserializeError(
            "internal node truncated before item lines".into(),
        ));
    }
    if lines[0] != b"chknode:" {
        return Err(Error::DeserializeError(
            "not a serialised internal node".into(),
        ));
    }
    let maximum_size = parse_decimal(lines[1], "maximum_size")?;
    let width = parse_decimal(lines[2], "key_width")?;
    let length = parse_decimal(lines[3], "length")?;
    let common_prefix = lines[4];

    let mut items: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
    let mut last_prefix_len = 0usize;
    for suffix in &lines[5..] {
        let mut full = Vec::with_capacity(common_prefix.len() + suffix.len());
        full.extend_from_slice(common_prefix);
        full.extend_from_slice(suffix);
        let split_at = full
            .iter()
            .rposition(|&b| b == 0)
            .ok_or_else(|| Error::DeserializeError("internal node line missing NUL".into()))?;
        let prefix = full[..split_at].to_vec();
        let flat_key = full[split_at + 1..].to_vec();
        last_prefix_len = prefix.len();
        items.push((prefix, flat_key));
    }
    if items.is_empty() {
        return Err(Error::DeserializeError(
            "internal node contained no items".into(),
        ));
    }

    Ok(ParsedInternalNode {
        maximum_size,
        key_width: width,
        length,
        search_prefix: common_prefix.to_vec(),
        items,
        node_width: last_prefix_len,
    })
}

fn parse_decimal(bytes: &[u8], what: &str) -> Result<usize, Error> {
    std::str::from_utf8(bytes)
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .ok_or_else(|| Error::DeserializeError(format!("invalid {}: {:?}", what, bytes)))
}

/// Split `value` into newline-terminated lines, as if a trailing `\n` had been
/// appended (so the final line is always terminated). Equivalent to
/// `split_lines_inclusive(value + b"\n")` but without copying `value` into a
/// padded buffer first: interior lines borrow nothing, and the last line is the
/// remaining tail with the synthetic `\n` appended.
fn value_to_lines(value: &[u8]) -> Vec<Vec<u8>> {
    let mut out = Vec::with_capacity(memchr::memchr_iter(b'\n', value).count() + 1);
    let mut start = 0;
    for nl in memchr::memchr_iter(b'\n', value) {
        out.push(value[start..=nl].to_vec());
        start = nl + 1;
    }
    // The tail after the last newline (or the whole value if it had none) plus
    // the appended trailing newline.
    let mut last = Vec::with_capacity(value.len() - start + 1);
    last.extend_from_slice(&value[start..]);
    last.push(b'\n');
    out.push(last);
    out
}

/// Build the byte chunks that [`LeafNode.serialise`] would emit before
/// adding them to a store. `items` must be presented in already-sorted
/// order (Python sorts `self._items.items()` before walking).
///
/// `common_prefix` is the longest common serialised prefix among all
/// items — pass `None` for an empty node. The output is split into one
/// `Vec<u8>` per line so the caller can hand it straight to
/// `store.add_lines(...)`.
///
/// Mirrors `LeafNode.serialise` minus the I/O side: the caller is still
/// responsible for `store.add_lines` and for updating `self._key` /
/// the in-memory cache from the resulting bytes.
pub fn serialise_leaf_node(
    maximum_size: usize,
    key_width: usize,
    items: &[(Vec<Vec<u8>>, Vec<u8>)],
    common_prefix: Option<&[u8]>,
) -> Result<Vec<Vec<u8>>, Error> {
    let mut out: Vec<Vec<u8>> = Vec::with_capacity(5 + items.len() * 2);
    out.push(b"chkleaf:\n".to_vec());
    out.push(format!("{}\n", maximum_size).into_bytes());
    out.push(format!("{}\n", key_width).into_bytes());
    out.push(format!("{}\n", items.len()).into_bytes());
    let prefix_bytes = match common_prefix {
        None => {
            if !items.is_empty() {
                return Err(Error::DeserializeError(
                    "common prefix is None but items is non-empty".into(),
                ));
            }
            out.push(b"\n".to_vec());
            return Ok(out);
        }
        Some(p) => {
            let mut line = p.to_vec();
            line.push(b'\n');
            out.push(line);
            p
        }
    };
    let prefix_len = prefix_bytes.len();
    for (key, value) in items {
        // Python's `osutils.chunks_to_lines([value + b"\n"])` splits the value
        // bytes on newlines so every output chunk is a single line terminated
        // by '\n' (the trailing b"\n" we append guarantees the last line is
        // terminated too). Downstream stores reject chunks with embedded
        // newlines, so the per-line split must be preserved. We split `value`
        // in place rather than copying it into a padded buffer first.
        let value_lines = value_to_lines(value);

        let mut header = key.join(&b'\x00');
        header.push(b'\x00');
        header.extend_from_slice(format!("{}\n", value_lines.len()).as_bytes());
        if !header.starts_with(prefix_bytes) {
            return Err(Error::DeserializeError(format!(
                "serialised key {:?} does not start with common prefix {:?}",
                header, prefix_bytes
            )));
        }
        out.push(header[prefix_len..].to_vec());
        out.extend(value_lines);
    }
    Ok(out)
}

/// One entry on an `InternalNode`'s serialised body: a prefix and the
/// flat sha1 key of the child it points at. The Python serialiser sorts
/// these by prefix before writing.
#[derive(Debug, Clone)]
pub struct InternalNodeChild {
    pub prefix: Vec<u8>,
    pub flat_key: Vec<u8>,
}

/// Build the byte chunks that [`InternalNode.serialise`] would emit
/// before adding them to a store. `items` must be sorted by `prefix`
/// (the Python loop does `sorted(self._items.items())`).
///
/// `length` is the InternalNode's `_len` — the total number of leaf
/// entries reachable through this node, **not** `items.len()` (which is
/// the direct fan-out count).
///
/// Mirrors `InternalNode.serialise` minus the I/O side and the
/// recursive walk that flushes child nodes first.
pub fn serialise_internal_node(
    maximum_size: usize,
    key_width: usize,
    length: usize,
    search_prefix: &[u8],
    items: &[InternalNodeChild],
) -> Result<Vec<Vec<u8>>, Error> {
    let mut out: Vec<Vec<u8>> = Vec::with_capacity(5 + items.len());
    out.push(b"chknode:\n".to_vec());
    out.push(format!("{}\n", maximum_size).into_bytes());
    out.push(format!("{}\n", key_width).into_bytes());
    out.push(format!("{}\n", length).into_bytes());
    let mut prefix_line = search_prefix.to_vec();
    prefix_line.push(b'\n');
    out.push(prefix_line);
    let prefix_len = search_prefix.len();
    for child in items {
        let mut serialised = child.prefix.clone();
        serialised.push(b'\x00');
        serialised.extend_from_slice(&child.flat_key);
        serialised.push(b'\n');
        if !serialised.starts_with(search_prefix) {
            return Err(Error::DeserializeError(format!(
                "internal node entry {:?} does not start with prefix {:?}",
                serialised, search_prefix
            )));
        }
        out.push(serialised[prefix_len..].to_vec());
    }
    Ok(out)
}

/// Serialised byte cost of one `(key, value)` pair inside a leaf node.
///
/// Mirrors `LeafNode._key_value_len` exactly: the key tuple's NUL-joined
/// bytes, the count of newlines in the value as a decimal string, the
/// value bytes themselves, and three separator bytes. The hot path for
/// every map/unmap is calling this to track `_raw_size`.
pub fn leaf_node_key_value_len(key: &[Vec<u8>], value: &[u8]) -> usize {
    let key_len: usize = if key.is_empty() {
        0
    } else {
        key.iter().map(Vec::len).sum::<usize>() + (key.len() - 1)
    };
    let newline_count = memchr::memchr_iter(b'\n', value).count();
    let newline_count_digits = if newline_count == 0 {
        1
    } else {
        let mut n = newline_count;
        let mut digits = 0;
        while n > 0 {
            n /= 10;
            digits += 1;
        }
        digits
    };
    key_len + 1 + newline_count_digits + 1 + value.len() + 1
}

/// Serialised byte cost of a leaf node, including its header.
///
/// Mirrors `LeafNode._current_size`. `bytes_for_items` is the sum of
/// per-entry serialised costs (i.e. the running `_raw_size`), with the
/// common-prefix-collapse applied: subtract `prefix_len * length` so
/// each entry doesn't pay for the prefix once stored once at the top
/// of the leaf.
pub fn leaf_node_current_size(
    maximum_size: usize,
    key_width: usize,
    length: usize,
    raw_size: usize,
    common_serialised_prefix: Option<&[u8]>,
) -> usize {
    let (bytes_for_items, prefix_len) = match common_serialised_prefix {
        None => (0, 0),
        Some(prefix) => {
            let prefix_len = prefix.len();
            (raw_size - prefix_len * length, prefix_len)
        }
    };
    // 9 = b"chkleaf:\n".len()
    9 + decimal_digits(maximum_size)
        + 1
        + decimal_digits(key_width)
        + 1
        + decimal_digits(length)
        + 1
        + prefix_len
        + 1
        + bytes_for_items
}

/// Serialised byte cost of an internal node header.
///
/// Mirrors `InternalNode._current_size`. The body bytes are tracked
/// separately in `_raw_size`; the header adds the four decimal-encoded
/// integers (maximum_size, key_width, length).
pub fn internal_node_current_size(
    maximum_size: usize,
    key_width: usize,
    length: usize,
    raw_size: usize,
) -> usize {
    raw_size + decimal_digits(length) + decimal_digits(key_width) + decimal_digits(maximum_size)
}

#[inline]
fn decimal_digits(n: usize) -> usize {
    if n == 0 {
        return 1;
    }
    let mut n = n;
    let mut digits = 0;
    while n > 0 {
        n /= 10;
        digits += 1;
    }
    digits
}

/// State of a `LeafNode`'s `_search_prefix` field.
///
/// Python uses an `_unknown` sentinel object to mark "items were
/// rebuilt without recomputing the prefix"; map / unmap then
/// demand-compute it. `None` means the node is empty, so there is no
/// prefix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SearchPrefix {
    /// The node was rebuilt and the prefix has not been recomputed.
    Unknown,
    /// The prefix is known to be `Some(p)` for a non-empty leaf, or
    /// `None` for an empty leaf.
    Computed(Option<Vec<u8>>),
}

impl SearchPrefix {
    /// Return the prefix bytes if computed, panicking on `Unknown`.
    /// Mirrors call sites where Python would have already demanded a
    /// recompute.
    pub fn expect_computed(&self) -> Option<&[u8]> {
        match self {
            SearchPrefix::Unknown => panic!("search prefix is Unknown"),
            SearchPrefix::Computed(p) => p.as_deref(),
        }
    }

    pub fn is_unknown(&self) -> bool {
        matches!(self, SearchPrefix::Unknown)
    }
}

/// In-memory state of a CHK leaf node.
///
/// Mirrors Python's `LeafNode` exactly, minus the store-touching
/// methods (`serialise`, `map`/`_split` recursion). Held by the
/// upcoming pyo3 `LeafNode` pyclass and used directly by pure-Rust
/// callers.
///
/// Iteration order of `items` follows insertion order so it matches
/// Python's `dict` semantics — tests and the `_split` algorithm both
/// observe items in that order when they don't sort first.
#[derive(Debug, Clone)]
pub struct LeafNode {
    /// `(b"sha1:...",)` once the node has been serialised to a store;
    /// `None` while it is still mutable.
    pub key: Option<Vec<u8>>,
    pub maximum_size: usize,
    pub key_width: usize,
    pub raw_size: usize,
    pub items: indexmap::IndexMap<Vec<Vec<u8>>, Vec<u8>>,
    pub search_prefix: SearchPrefix,
    pub common_serialised_prefix: Option<Vec<u8>>,
    pub search_key_func: SearchKeyFunc,
}

impl LeafNode {
    /// Empty node with the given search-key transform.
    pub fn new(search_key_func: SearchKeyFunc) -> Self {
        Self {
            key: None,
            maximum_size: 0,
            key_width: 1,
            raw_size: 0,
            items: indexmap::IndexMap::new(),
            search_prefix: SearchPrefix::Computed(None),
            common_serialised_prefix: None,
            search_key_func,
        }
    }

    /// Build a populated leaf from the output of [`deserialise_leaf_node`].
    ///
    /// Mirrors Python's `_deserialise_leaf_node` post-processing: the
    /// items become a dict, `search_prefix` is `Unknown` (Python uses
    /// `_unknown`) for non-empty nodes so the next mutator recomputes
    /// it on demand, and `common_serialised_prefix` is taken straight
    /// from the parsed prefix.
    pub fn from_parsed(parsed: ParsedLeafNode, search_key_func: SearchKeyFunc) -> Self {
        let items_empty = parsed.items.is_empty();
        let mut items = indexmap::IndexMap::with_capacity(parsed.items.len());
        for (k, v) in parsed.items {
            items.insert(k, v);
        }
        let (search_prefix, common_serialised_prefix) = if items_empty {
            (SearchPrefix::Computed(None), None)
        } else {
            (SearchPrefix::Unknown, Some(parsed.common_serialised_prefix))
        };
        Self {
            key: None,
            maximum_size: parsed.maximum_size,
            key_width: parsed.key_width,
            raw_size: parsed.raw_size,
            items,
            search_prefix,
            common_serialised_prefix,
            search_key_func,
        }
    }

    /// Number of entries in this leaf.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Wrapper around [`leaf_node_current_size`] using `self`'s state.
    pub fn current_size(&self) -> usize {
        leaf_node_current_size(
            self.maximum_size,
            self.key_width,
            self.len(),
            self.raw_size,
            self.common_serialised_prefix.as_deref(),
        )
    }

    /// Recompute `search_prefix` from scratch by hashing every key
    /// and reducing with [`common_prefix_many`]. Mirrors
    /// `LeafNode._compute_search_prefix`.
    pub fn compute_search_prefix(&mut self) -> Option<&[u8]> {
        let keys: Vec<SerializedKey> = self
            .items
            .keys()
            .map(|k| self.search_key_func.apply(&Key::from(k.clone())))
            .collect();
        let prefix = common_prefix_many(keys.iter().map(|k| k.as_slice())).map(|s| s.to_vec());
        self.search_prefix = SearchPrefix::Computed(prefix);
        match &self.search_prefix {
            SearchPrefix::Computed(p) => p.as_deref(),
            SearchPrefix::Unknown => unreachable!(),
        }
    }

    /// Recompute `common_serialised_prefix` from scratch. Mirrors
    /// `LeafNode._compute_serialised_prefix`.
    pub fn compute_serialised_prefix(&mut self) -> Option<&[u8]> {
        let keys: Vec<SerializedKey> = self
            .items
            .keys()
            .map(|k| Key::from(k.clone()).serialize())
            .collect();
        let prefix = common_prefix_many(keys.iter().map(|k| k.as_slice())).map(|s| s.to_vec());
        self.common_serialised_prefix = prefix;
        self.common_serialised_prefix.as_deref()
    }

    /// `LeafNode._are_search_keys_identical`: all entries hash to the
    /// same search key. Empty leaves return `true`.
    pub fn are_search_keys_identical(&self) -> bool {
        let keys = self
            .items
            .keys()
            .map(|k| self.search_key_func.apply(&Key::from(k.clone())));
        are_search_keys_identical(keys)
    }

    /// Insert `(key, value)` and update `raw_size`, `search_prefix`,
    /// `common_serialised_prefix`. Returns `true` if the leaf has
    /// overflowed `maximum_size` and the caller must split it.
    ///
    /// Mirrors `LeafNode._map_no_split`: the caller must have already
    /// removed any prior entry for `key` from `raw_size` / `len`. If
    /// `search_prefix` was `Unknown`, it is recomputed before applying
    /// the new key.
    pub fn map_no_split(&mut self, key: Vec<Vec<u8>>, value: Vec<u8>) -> bool {
        self.raw_size += leaf_node_key_value_len(&key, &value);
        // Build one Key view and reuse it for both derivations instead of
        // cloning `key` twice. This runs once per inventory entry on the CHK
        // write path (commit/fetch), so the saved clone adds up.
        let key_obj = Key::from(key.clone());
        let serialised_key = key_obj.serialize();
        let search_key = self.search_key_func.apply(&key_obj);
        self.items.insert(key, value);

        self.common_serialised_prefix = Some(match self.common_serialised_prefix.take() {
            None => serialised_key,
            Some(prefix) => common_prefix_pair(&prefix, &serialised_key).to_vec(),
        });

        if self.search_prefix.is_unknown() {
            self.compute_search_prefix();
        }
        let new_prefix = match &self.search_prefix {
            SearchPrefix::Computed(None) => search_key.clone(),
            SearchPrefix::Computed(Some(p)) => common_prefix_pair(p, &search_key).to_vec(),
            SearchPrefix::Unknown => unreachable!("just recomputed above"),
        };
        self.search_prefix = SearchPrefix::Computed(Some(new_prefix.clone()));

        if self.items.len() > 1
            && self.maximum_size > 0
            && self.current_size() > self.maximum_size
            && (search_key != new_prefix || !self.are_search_keys_identical())
        {
            return true;
        }
        false
    }

    /// Remove `key`, recomputing `search_prefix` and
    /// `common_serialised_prefix` from scratch. Returns the removed
    /// value, or `None` if `key` was not present (Python raises
    /// `KeyError`; here the caller decides how to react).
    ///
    /// Mirrors `LeafNode.unmap` minus the store argument (the store is
    /// unused on the leaf path).
    pub fn unmap(&mut self, key: &[Vec<u8>]) -> Option<Vec<u8>> {
        let removed = self.items.shift_remove(key)?;
        self.raw_size -= leaf_node_key_value_len(key, &removed);
        self.key = None;
        self.compute_search_prefix();
        self.compute_serialised_prefix();
        Some(removed)
    }

    /// Serialise to `store` and cache the resulting bytes in `cache`.
    ///
    /// Mirrors Python's `LeafNode.serialise`: sorts the items, builds
    /// the line list, calls `store.add_lines((None,), (), lines)`,
    /// stores the resulting sha1 key on `self.key`, and writes the
    /// concatenated bytes into the page cache. Returns the resulting
    /// sha1 key (without the `b"sha1:"` prefix stripped).
    ///
    /// The Python version returns a single-element list; native Rust
    /// callers want the key value alone.
    pub fn serialise<S>(&mut self, store: &S, cache: &dyn PageCache) -> Result<Vec<u8>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        // Python sorts items before serialising; mirror that exactly.
        let mut sorted_items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = self
            .items
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        sorted_items.sort();
        let lines = serialise_leaf_node(
            self.maximum_size,
            self.key_width,
            &sorted_items,
            self.common_serialised_prefix.as_deref(),
        )?;
        let (sha1, _size) = store
            .add_lines(
                &crate::versionedfile::Key::ContentAddressed(vec![]),
                Some(&[]),
                &lines,
            )
            .map_err(|e| Error::AssertionFailed(format!("add_lines failed: {:?}", e)))?;
        let mut full_key = Vec::with_capacity(5 + sha1.len());
        full_key.extend_from_slice(b"sha1:");
        full_key.extend_from_slice(&sha1);
        let data: Vec<u8> = lines.iter().flatten().copied().collect();
        if data.len() != self.current_size() {
            return Err(Error::AssertionFailed("Invalid _current_size".into()));
        }
        cache.insert(full_key.clone(), data);
        self.key = Some(full_key.clone());
        Ok(full_key)
    }

    /// Split this overflowing leaf into multiple child nodes.
    ///
    /// Mirrors Python's `LeafNode._split`: groups items by the
    /// `(search_prefix + 1)`-byte search-key prefix into fresh sub-leaves.
    /// If a sub-leaf overflows during its own `map`, the result is
    /// promoted into an InternalNode wrapping the further splits.
    ///
    /// Consumes the items in `self`. After `_split` returns, the
    /// caller should treat `self` as destroyed — Python returns new
    /// nodes up the stack and the caller wraps them in an
    /// InternalNode at the level above.
    pub fn split(&mut self) -> Result<(Vec<u8>, Vec<(Vec<u8>, Node)>), Error> {
        let common_prefix = match &self.search_prefix {
            SearchPrefix::Unknown => {
                return Err(Error::AssertionFailed("Search prefix must be known".into()))
            }
            SearchPrefix::Computed(None) => Vec::new(),
            SearchPrefix::Computed(Some(p)) => p.clone(),
        };
        let split_at = common_prefix.len() + 1;
        let mut result: indexmap::IndexMap<Vec<u8>, Node> = indexmap::IndexMap::new();
        let items = std::mem::take(&mut self.items);
        for (key, value) in items {
            let search_key = self.search_key_func.apply(&Key::from(key.clone()));
            let mut prefix: Vec<u8> = if search_key.len() >= split_at {
                search_key[..split_at].to_vec()
            } else {
                search_key.clone()
            };
            if prefix.len() < split_at {
                prefix.resize(split_at, 0);
            }
            // Take or create the per-prefix sub-node; mutate it via
            // map, then store back.
            let existing = result.shift_remove(&prefix);
            let mut sub_node = match existing {
                Some(Node::Leaf(b)) => Node::Leaf(b),
                Some(Node::Internal(b)) => Node::Internal(b),
                None => {
                    let mut leaf = LeafNode::new(self.search_key_func.clone());
                    leaf.maximum_size = self.maximum_size;
                    leaf.key_width = self.key_width;
                    Node::Leaf(Box::new(leaf))
                }
            };
            let map_res = sub_node.map(key, value)?;
            match map_res {
                MapResult::InPlace { .. } => {
                    result.insert(prefix, sub_node);
                }
                MapResult::Split {
                    common_serialised_prefix: sub_prefix,
                    children,
                } => {
                    let mut new_internal =
                        InternalNode::new(sub_prefix.clone(), self.search_key_func.clone());
                    new_internal.maximum_size = self.maximum_size;
                    new_internal.key_width = self.key_width;
                    for (split_prefix, child) in children {
                        new_internal.add_node(split_prefix, child)?;
                    }
                    result.insert(prefix, Node::Internal(Box::new(new_internal)));
                }
            }
        }
        Ok((common_prefix, result.into_iter().collect()))
    }

    /// In-place insert. Mirrors Python's `LeafNode.map`: subtract
    /// the old entry's cost if the key existed, then call
    /// `map_no_split`. If it signals overflow, split.
    pub fn map(&mut self, key: Vec<Vec<u8>>, value: Vec<u8>) -> Result<MapResult, Error> {
        if let Some(old_value) = self.items.get(&key) {
            self.raw_size -= leaf_node_key_value_len(&key, old_value);
        }
        self.key = None;
        if self.map_no_split(key, value) {
            let (common_prefix, children) = self.split()?;
            Ok(MapResult::Split {
                common_serialised_prefix: common_prefix,
                children,
            })
        } else {
            let prefix = match &self.search_prefix {
                SearchPrefix::Unknown => {
                    return Err(Error::AssertionFailed(
                        "search_prefix must be known after map".into(),
                    ));
                }
                SearchPrefix::Computed(None) => Vec::new(),
                SearchPrefix::Computed(Some(p)) => p.clone(),
            };
            Ok(MapResult::InPlace {
                search_prefix: prefix,
            })
        }
    }

    /// Yield `(key, value)` pairs matching `key_filter`. When `None`,
    /// yields every entry in insertion order. Otherwise:
    ///
    /// * Filter keys of length `key_width` are looked up directly and
    ///   yielded in filter order (matching Python's left-to-right
    ///   iteration before falling through to the prefix-match pass).
    /// * Shorter filter keys act as prefix filters across the items.
    ///   Items are checked in insertion order; the first matching
    ///   filter wins (matches Python's `break` after a yield).
    ///
    /// Mirrors `LeafNode.iteritems` exactly; the store argument is
    /// unused on the leaf path and is omitted from this pure-Rust
    /// signature.
    pub fn iteritems(&self, key_filter: Option<&[Vec<Vec<u8>>]>) -> Vec<(Vec<Vec<u8>>, Vec<u8>)> {
        let mut out: Vec<(Vec<Vec<u8>>, Vec<u8>)> = Vec::new();
        let filter = match key_filter {
            None => {
                for (k, v) in self.items.iter() {
                    out.push((k.clone(), v.clone()));
                }
                return out;
            }
            Some(f) => f,
        };
        // Group short filters by length; iterate exact-width matches in
        // filter order.
        let mut short_filters: std::collections::HashMap<usize, Vec<&[Vec<u8>]>> =
            std::collections::HashMap::new();
        for key in filter.iter() {
            if key.len() == self.key_width {
                if let Some(v) = self.items.get(key) {
                    out.push((key.clone(), v.clone()));
                }
            } else {
                short_filters.entry(key.len()).or_default().push(key);
            }
        }
        if !short_filters.is_empty() {
            for (k, v) in self.items.iter() {
                for (length, candidates) in short_filters.iter() {
                    if k.len() >= *length && candidates.iter().any(|c| *c == &k[..*length]) {
                        out.push((k.clone(), v.clone()));
                        break;
                    }
                }
            }
        }
        out
    }
}

/// Result of [`LeafNode::map`] / [`Node::map`] — either the node
/// absorbed the new entry in place, or it split into multiple
/// children that the caller must wrap in an InternalNode.
#[derive(Debug, Clone)]
pub enum MapResult {
    /// No structural change. The caller's existing reference still
    /// points at the up-to-date node. `search_prefix` is the search
    /// prefix of the node post-map (matches Python's first return).
    InPlace { search_prefix: Vec<u8> },
    /// The node overflowed and split. The caller replaces it with
    /// an InternalNode at `common_serialised_prefix` containing
    /// each `(sub_prefix, child)` pair.
    Split {
        common_serialised_prefix: Vec<u8>,
        children: Vec<(Vec<u8>, Node)>,
    },
}

/// In-memory CHK node — either a leaf with key/value entries or an
/// internal node referencing other nodes. Mirrors the Python
/// `Node` base class hierarchy (LeafNode | InternalNode).
#[derive(Debug, Clone)]
pub enum Node {
    Leaf(Box<LeafNode>),
    Internal(Box<InternalNode>),
}

impl Node {
    /// `(b"sha1:...",)` key once the node has been serialised, else
    /// `None`. Mirrors Python's `Node.key()`.
    pub fn key(&self) -> Option<&[u8]> {
        match self {
            Node::Leaf(l) => l.key.as_deref(),
            Node::Internal(n) => n.key.as_deref(),
        }
    }

    /// Total number of leaf entries reachable through this node.
    /// Mirrors Python's `Node.__len__`.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        match self {
            Node::Leaf(l) => l.len(),
            Node::Internal(n) => n.len,
        }
    }

    /// Maximum byte size allowed for this node when serialised, or
    /// `0` for unlimited.
    pub fn maximum_size(&self) -> usize {
        match self {
            Node::Leaf(l) => l.maximum_size,
            Node::Internal(n) => n.maximum_size,
        }
    }

    /// CHK references held by this node. Mirrors `Node.refs`:
    /// leaves never reference other pages (returns `[]`); internal
    /// nodes return their children's sha1 keys (delegates to
    /// `InternalNode::refs`, which requires the node to have been
    /// serialised).
    pub fn refs(&self) -> Result<Vec<Vec<u8>>, Error> {
        match self {
            Node::Leaf(_) => Ok(Vec::new()),
            Node::Internal(n) => n.refs(),
        }
    }

    /// Insert `(key, value)` into this subtree (pure in-memory path).
    ///
    /// For leaves, delegates to `LeafNode::map`. For internal nodes,
    /// returns AssertionFailed — the recursive InternalNode path
    /// needs the store and lives at `Node::map_with_store`. This
    /// signature exists so `LeafNode::split` (which only ever creates
    /// fresh in-memory sub-leaves) can recurse via `Node::map`
    /// without a store argument.
    pub fn map(&mut self, key: Vec<Vec<u8>>, value: Vec<u8>) -> Result<MapResult, Error> {
        match self {
            Node::Leaf(l) => l.map(key, value),
            Node::Internal(_) => Err(Error::AssertionFailed(
                "Node::map on InternalNode requires a store — \
                 use Node::map_with_store"
                    .into(),
            )),
        }
    }

    /// Serialise this subtree to the store, returning every sha1 key
    /// written (children first, then self). Mirrors Python's
    /// `Node.serialise`. Skips children that are unloaded (their
    /// sha1 key is already canonical) or already serialised (key set).
    pub fn serialise<S>(&mut self, store: &S, cache: &dyn PageCache) -> Result<Vec<Vec<u8>>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        match self {
            Node::Leaf(l) => {
                let k = l.serialise(store, cache)?;
                Ok(vec![k])
            }
            Node::Internal(n) => n.serialise(store, cache),
        }
    }

    /// Recursive remove that may demand-load child pages. Returns
    /// the replacement node (possibly the same one, possibly a
    /// collapsed leaf, possibly the single remaining child if the
    /// internal node lost all but one child).
    ///
    /// Mirrors Python's polymorphic `unmap(store, key, check_remap)`.
    /// Raises `KeyError`-equivalent (`AssertionFailed`) when the key
    /// is not present.
    pub fn unmap_with_store<S>(
        self,
        store: &S,
        cache: &dyn PageCache,
        key: &[Vec<u8>],
        check_remap: bool,
    ) -> Result<Node, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        match self {
            Node::Leaf(mut leaf) => {
                if leaf.unmap(key).is_none() {
                    return Err(Error::AssertionFailed(format!("key not found: {:?}", key)));
                }
                Ok(Node::Leaf(leaf))
            }
            Node::Internal(internal) => {
                internal_unmap_with_store(*internal, store, cache, key, check_remap)
            }
        }
    }

    /// Recursive insert that may demand-load child pages from the
    /// store. Mirrors Python's polymorphic dispatch:
    /// `LeafNode.map(store, key, value)` for leaves;
    /// `InternalNode.map(store, key, value)` for internal nodes
    /// (which descends into the matching child, possibly creating a
    /// new wrapping parent if the key falls outside the current
    /// search prefix).
    ///
    /// May replace `*self` with a new node (e.g. an internal node
    /// promoting itself into a larger parent, or a parent collapsing
    /// back into a leaf after `_check_remap`).
    pub fn map_with_store<S>(
        &mut self,
        store: &S,
        cache: &dyn PageCache,
        key: Vec<Vec<u8>>,
        value: Vec<u8>,
    ) -> Result<MapResult, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        match self {
            Node::Leaf(l) => l.map(key, value),
            Node::Internal(_) => {
                // We need to potentially replace `*self`. Take the
                // internal node out, run the algorithm against it,
                // and put the result (possibly wrapped or collapsed)
                // back into `*self`.
                let placeholder = Node::Internal(Box::new(InternalNode::new(
                    Vec::new(),
                    SearchKeyFunc::Plain,
                )));
                let owned = std::mem::replace(self, placeholder);
                let internal = match owned {
                    Node::Internal(b) => b,
                    Node::Leaf(_) => unreachable!("matched Internal above"),
                };
                let (new_self, result) =
                    internal_map_with_store(*internal, store, cache, key, value)?;
                *self = new_self;
                Ok(result)
            }
        }
    }

    /// Iterate `(key, value)` pairs in this subtree matching
    /// `key_filter`. Mirrors Python's polymorphic `iteritems`:
    /// leaves yield directly; internal nodes recurse through
    /// `iter_nodes`, demand-loading children as needed.
    pub fn iteritems<S>(
        &mut self,
        store: &S,
        cache: &dyn PageCache,
        key_filter: Option<&[Vec<Vec<u8>>]>,
    ) -> Result<Vec<(Vec<Vec<u8>>, Vec<u8>)>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        match self {
            Node::Leaf(l) => Ok(l.iteritems(key_filter)),
            Node::Internal(n) => {
                let mut out: Vec<(Vec<Vec<u8>>, Vec<u8>)> = Vec::new();
                let children = n.iter_nodes(store, cache, key_filter, None)?;
                for (mut child, filter) in children {
                    let sub_filter = filter.as_deref();
                    out.extend(child.iteritems(store, cache, sub_filter)?);
                }
                Ok(out)
            }
        }
    }
}

/// Reference to a child of an `InternalNode`. The dict either holds a
/// `(b"sha1:...",)` reference to an unloaded child page or, after
/// `_iter_nodes` populates it from the store, the loaded child Node
/// itself.
#[derive(Debug, Clone)]
pub enum NodeRef {
    /// Unloaded reference — the `b"sha1:..."` key handed to the store
    /// to fetch the child's bytes.
    Unloaded(Vec<u8>),
    /// In-memory child node.
    Loaded(Node),
}

impl NodeRef {
    /// Length contribution of this child for `InternalNode._len`.
    pub fn len(&self) -> usize {
        match self {
            NodeRef::Unloaded(_) => {
                // Mirrors Python's behaviour: a tuple has no `len(node)`
                // semantic in `_len`, but Python only writes Unloaded
                // references after the parent's `_len` was already set
                // from the parsed body, so the per-ref length isn't
                // queried for unloaded children.
                0
            }
            NodeRef::Loaded(n) => n.len(),
        }
    }
}

/// In-memory state of a CHK internal node — a fan-out of byte-prefix
/// to child (loaded Node or unloaded sha1 reference).
///
/// Iteration order over `items` follows insertion order to match
/// Python's `dict` semantics; serialisation paths sort first.
#[derive(Debug, Clone)]
pub struct InternalNode {
    pub key: Option<Vec<u8>>,
    pub maximum_size: usize,
    pub key_width: usize,
    /// Total leaf entries reachable through this subtree.
    pub len: usize,
    /// Width in bytes of each prefix in `items`. `0` for an
    /// empty internal node (Python's `_node_width` default).
    pub node_width: usize,
    /// Reserved for future prefix-compression accounting; the Python
    /// `InternalNode` sets `_raw_size = None` since internal nodes
    /// don't carry per-entry payload. We track an explicit `0` here
    /// and recompute byte costs from the items list at serialise
    /// time.
    pub raw_size: usize,
    pub items: indexmap::IndexMap<Vec<u8>, NodeRef>,
    /// Search-key prefix common to every child of this node. Always
    /// `Some` once initialised; `None` only on a default-constructed
    /// empty node before `from_parsed` populates it.
    pub search_prefix: Option<Vec<u8>>,
    pub search_key_func: SearchKeyFunc,
}

impl InternalNode {
    /// Empty internal node with the given search prefix and key
    /// function. Mirrors Python's `InternalNode(prefix, search_key_func)`.
    pub fn new(prefix: Vec<u8>, search_key_func: SearchKeyFunc) -> Self {
        Self {
            key: None,
            maximum_size: 0,
            key_width: 1,
            len: 0,
            node_width: 0,
            raw_size: 0,
            items: indexmap::IndexMap::new(),
            search_prefix: Some(prefix),
            search_key_func,
        }
    }

    /// Build a populated internal node from the output of
    /// [`deserialise_internal_node`]. All children start as
    /// `NodeRef::Unloaded`; the caller demand-loads them via the
    /// store as `_iter_nodes` runs.
    pub fn from_parsed(parsed: ParsedInternalNode, search_key_func: SearchKeyFunc) -> Self {
        let mut items: indexmap::IndexMap<Vec<u8>, NodeRef> =
            indexmap::IndexMap::with_capacity(parsed.items.len());
        for (prefix, flat_key) in parsed.items {
            items.insert(prefix, NodeRef::Unloaded(flat_key));
        }
        Self {
            key: None,
            maximum_size: parsed.maximum_size,
            key_width: parsed.key_width,
            len: parsed.length,
            node_width: parsed.node_width,
            raw_size: 0,
            items,
            search_prefix: Some(parsed.search_prefix),
            search_key_func,
        }
    }

    /// Serialised byte cost of this node (header + body). Wraps
    /// [`internal_node_current_size`].
    pub fn current_size(&self) -> usize {
        internal_node_current_size(self.maximum_size, self.key_width, self.len, self.raw_size)
    }

    /// Add a loaded child node under `prefix`. Mirrors Python's
    /// `InternalNode.add_node`: validates that `prefix` extends
    /// `search_prefix` by exactly one byte, updates `len` and
    /// `node_width`, clears `key` (this node is now dirty).
    pub fn add_node(&mut self, prefix: Vec<u8>, node: Node) -> Result<(), Error> {
        let search_prefix = self.search_prefix.as_deref().ok_or_else(|| {
            Error::AssertionFailed("InternalNode.add_node: search_prefix is None".into())
        })?;
        if !prefix.starts_with(search_prefix) {
            return Err(Error::AssertionFailed(format!(
                "prefixes mismatch: {:?} must start with {:?}",
                prefix, search_prefix
            )));
        }
        if prefix.len() != search_prefix.len() + 1 {
            return Err(Error::AssertionFailed(format!(
                "prefix wrong length: len({:?}) is not {}",
                prefix,
                search_prefix.len() + 1
            )));
        }
        self.len += node.len();
        if self.items.is_empty() {
            self.node_width = prefix.len();
        }
        if self.node_width != search_prefix.len() + 1 {
            return Err(Error::AssertionFailed(format!(
                "node width mismatch: {} is not {}",
                self.node_width,
                search_prefix.len() + 1
            )));
        }
        self.items.insert(prefix, NodeRef::Loaded(node));
        self.key = None;
        Ok(())
    }

    /// Pad or truncate `key`'s search-key bytes to fit `node_width`,
    /// padding with NUL. Mirrors `InternalNode._search_key`.
    pub fn search_key(&self, key: &Key) -> SerializedKey {
        let base = self.search_key_func.apply(key);
        if base.len() >= self.node_width {
            base[..self.node_width].to_vec()
        } else {
            let mut padded = Vec::with_capacity(self.node_width);
            padded.extend_from_slice(&base);
            padded.resize(self.node_width, 0);
            padded
        }
    }

    /// Truncate `key`'s search-key bytes to `node_width` without
    /// padding (used as a prefix when filtering iteritems). Mirrors
    /// `InternalNode._search_prefix_filter`.
    pub fn search_prefix_filter(&self, key: &Key) -> SerializedKey {
        let base = self.search_key_func.apply(key);
        if base.len() >= self.node_width {
            base[..self.node_width].to_vec()
        } else {
            base
        }
    }

    /// Recompute `search_prefix` as the longest common prefix of all
    /// child prefixes. Mirrors `InternalNode._compute_search_prefix`.
    pub fn compute_search_prefix(&mut self) -> Option<&[u8]> {
        let prefix =
            common_prefix_many(self.items.keys().map(|k| k.as_slice())).map(|s| s.to_vec());
        self.search_prefix = prefix;
        self.search_prefix.as_deref()
    }

    /// Serialise this internal node (and any dirty descendants) to
    /// the store. Returns every newly-written sha1 key in
    /// children-first / self-last order. Mirrors
    /// `InternalNode.serialise`.
    pub fn serialise<S>(&mut self, store: &S, cache: &dyn PageCache) -> Result<Vec<Vec<u8>>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let mut out: Vec<Vec<u8>> = Vec::new();
        // Walk children: serialise any loaded child whose `key` is
        // unset. Unloaded children and already-serialised loaded
        // children are skipped.
        let prefixes: Vec<Vec<u8>> = self.items.keys().cloned().collect();
        for prefix in &prefixes {
            // Take, mutate, replace — avoids holding a `&mut`
            // borrow on self.items across recursion.
            let entry = self.items.shift_remove(prefix).unwrap();
            let entry = match entry {
                NodeRef::Unloaded(k) => NodeRef::Unloaded(k),
                NodeRef::Loaded(mut node) => {
                    if node.key().is_none() {
                        let keys = node.serialise(store, cache)?;
                        out.extend(keys);
                    }
                    NodeRef::Loaded(node)
                }
            };
            self.items.insert(prefix.clone(), entry);
        }
        let search_prefix = self
            .search_prefix
            .clone()
            .ok_or_else(|| Error::AssertionFailed("search_prefix is None".into()))?;
        // Build sorted (prefix, flat_key) list — mirrors
        // `sorted_items = [(prefix, node[0] or node._key[0]) for ...]`.
        let mut sorted_items: Vec<InternalNodeChild> = self
            .items
            .iter()
            .map(|(prefix, child)| {
                let flat_key = match child {
                    NodeRef::Unloaded(k) => k.clone(),
                    NodeRef::Loaded(n) => n
                        .key()
                        .map(|s| s.to_vec())
                        .ok_or_else(|| {
                            Error::AssertionFailed("loaded child has no key after serialise".into())
                        })
                        .unwrap_or_default(),
                };
                InternalNodeChild {
                    prefix: prefix.clone(),
                    flat_key,
                }
            })
            .collect();
        sorted_items.sort_by(|a, b| a.prefix.cmp(&b.prefix));
        let lines = serialise_internal_node(
            self.maximum_size,
            self.key_width,
            self.len,
            &search_prefix,
            &sorted_items,
        )?;
        let (sha1, _size) = store
            .add_lines(
                &crate::versionedfile::Key::ContentAddressed(vec![]),
                Some(&[]),
                &lines,
            )
            .map_err(|e| Error::AssertionFailed(format!("add_lines failed: {:?}", e)))?;
        let mut full_key = Vec::with_capacity(5 + sha1.len());
        full_key.extend_from_slice(b"sha1:");
        full_key.extend_from_slice(&sha1);
        let data: Vec<u8> = lines.iter().flatten().copied().collect();
        cache.insert(full_key.clone(), data);
        self.key = Some(full_key.clone());
        out.push(full_key);
        Ok(out)
    }

    /// Check whether this node's children can collapse back into a
    /// single LeafNode. Returns either `self` (wrapped as
    /// `Node::Internal`) when collapse isn't possible, or a freshly-
    /// built `Node::Leaf` holding everything from this subtree.
    ///
    /// Mirrors Python's `InternalNode._check_remap`: walks children
    /// in batches of 16, adding their entries into a candidate
    /// LeafNode; if any child is itself an InternalNode, abort
    /// (cheaper than walking further); if any insertion would overflow
    /// the candidate, abort.
    ///
    /// Consumes `self` to allow returning either variant.
    pub fn check_remap<S>(mut self, store: &S, cache: &dyn PageCache) -> Result<Node, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let mut new_leaf = LeafNode::new(self.search_key_func.clone());
        new_leaf.maximum_size = self.maximum_size;
        new_leaf.key_width = self.key_width;
        let children = self.iter_nodes(store, cache, None, Some(16))?;
        for (node, _) in children {
            if let Node::Internal(_) = node {
                // Any internal child means collapse is impossible.
                return Ok(Node::Internal(Box::new(self)));
            }
            let leaf = match node {
                Node::Leaf(l) => l,
                Node::Internal(_) => unreachable!(),
            };
            for (k, v) in leaf.items {
                if new_leaf.map_no_split(k, v) {
                    // Overflow during accumulation — abort.
                    return Ok(Node::Internal(Box::new(self)));
                }
            }
        }
        Ok(Node::Leaf(Box::new(new_leaf)))
    }

    /// Yield child nodes that match `key_filter`, demand-loading
    /// unloaded references via `cache` then `store`.
    ///
    /// Mirrors Python's `InternalNode._iter_nodes`: returns
    /// `(child_node, optional_filter)` pairs. Already-loaded children
    /// come first (in `self.items` order), then page-cache hits,
    /// then freshly fetched batches from the store.
    ///
    /// When loading from the store, this method also flips the
    /// matching `NodeRef::Unloaded` entries in `self.items` to
    /// `NodeRef::Loaded`, so subsequent calls hit the in-memory
    /// fast path.
    ///
    /// Note: returns owned `Node` clones rather than references —
    /// the caller can recurse into them without lifetime
    /// entanglement with `&mut self`.
    pub fn iter_nodes<S>(
        &mut self,
        store: &S,
        cache: &dyn PageCache,
        key_filter: Option<&[Vec<Vec<u8>>]>,
        batch_size: Option<usize>,
    ) -> Result<Vec<(Node, Option<Vec<Vec<Vec<u8>>>>)>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let mut out: Vec<(Node, Option<Vec<Vec<Vec<u8>>>>)> = Vec::new();
        // sha1_key -> (prefix, key_filter_for_that_child) for unloaded
        // refs we need to demand-load. Uses an IndexMap so the batch
        // ordering reflects `self.items` insertion order.
        let mut to_load: indexmap::IndexMap<Vec<u8>, (Vec<u8>, Option<Vec<Vec<Vec<u8>>>>)> =
            indexmap::IndexMap::new();

        match key_filter {
            None => {
                // Yield every loaded child; queue every unloaded child
                // with a `None` filter.
                for (prefix, child) in self.items.iter() {
                    match child {
                        NodeRef::Loaded(node) => out.push((node.clone(), None)),
                        NodeRef::Unloaded(sha1_key) => {
                            to_load.insert(sha1_key.clone(), (prefix.clone(), None));
                        }
                    }
                }
            }
            Some(filter) if filter.len() == 1 => {
                // Single-key fast path: compute its full-width search
                // prefix, do a dict lookup on items.
                let only_key = Key::from(filter[0].clone());
                let search_prefix = self.search_prefix_filter(&only_key);
                if search_prefix.len() == self.node_width {
                    match self.items.get(&search_prefix) {
                        None => return Ok(out),
                        Some(NodeRef::Loaded(node)) => {
                            out.push((node.clone(), Some(vec![filter[0].clone()])));
                            return Ok(out);
                        }
                        Some(NodeRef::Unloaded(sha1_key)) => {
                            to_load.insert(
                                sha1_key.clone(),
                                (search_prefix, Some(vec![filter[0].clone()])),
                            );
                        }
                    }
                } else {
                    // Fall through to the general filter path.
                    self.iter_nodes_general_filter(filter, &mut out, &mut to_load);
                }
            }
            Some(filter) => {
                self.iter_nodes_general_filter(filter, &mut out, &mut to_load);
            }
        }

        if to_load.is_empty() {
            return Ok(out);
        }

        // Look in the page cache first.
        let mut still_missing: indexmap::IndexMap<Vec<u8>, (Vec<u8>, Option<Vec<Vec<Vec<u8>>>>)> =
            indexmap::IndexMap::new();
        for (sha1_key, (prefix, filter)) in to_load.drain(..) {
            if let Some(bytes) = cache.get(&sha1_key) {
                let node =
                    deserialise_node(&bytes, sha1_key.clone(), self.search_key_func.clone())?;
                self.items
                    .insert(prefix.clone(), NodeRef::Loaded(node.clone()));
                out.push((node, filter));
            } else {
                still_missing.insert(sha1_key, (prefix, filter));
            }
        }
        if still_missing.is_empty() {
            return Ok(out);
        }

        // Demand-load remaining keys from the store, batched.
        let batch_size = batch_size.unwrap_or(still_missing.len());
        let key_order: Vec<Vec<u8>> = still_missing.keys().cloned().collect();
        for batch_start in (0..key_order.len()).step_by(batch_size.max(1)) {
            let batch_end = (batch_start + batch_size).min(key_order.len());
            let batch_keys: Vec<crate::versionedfile::Key> = key_order[batch_start..batch_end]
                .iter()
                .map(|k| crate::versionedfile::Key::Fixed(vec![k.clone()]))
                .collect();
            let stream = store
                .get_record_stream(&batch_keys, "unordered", true)
                .map_err(|e| {
                    Error::AssertionFailed(format!("get_record_stream failed: {:?}", e))
                })?;
            for record in stream {
                let record =
                    record.map_err(|e| Error::AssertionFailed(format!("record error: {:?}", e)))?;
                let rec_key = record.key();
                let sha1_key = rec_key
                    .segments()
                    .first()
                    .ok_or_else(|| Error::AssertionFailed("record key has no segments".into()))?
                    .clone();
                let bytes = record.to_fulltext().into_owned();
                let (prefix, filter) = still_missing.shift_remove(&sha1_key).ok_or_else(|| {
                    Error::AssertionFailed(format!("store returned unexpected key {:?}", sha1_key))
                })?;
                let node =
                    deserialise_node(&bytes, sha1_key.clone(), self.search_key_func.clone())?;
                cache.insert(sha1_key, bytes);
                self.items.insert(prefix, NodeRef::Loaded(node.clone()));
                out.push((node, filter));
            }
        }

        Ok(out)
    }

    /// General-case filter dispatch shared between the multi-key path
    /// and the single-key-but-not-full-width fallback. Walks every
    /// item in `self.items` against the length-keyed prefix filters.
    fn iter_nodes_general_filter(
        &self,
        filter: &[Vec<Vec<u8>>],
        out: &mut Vec<(Node, Option<Vec<Vec<Vec<u8>>>>)>,
        to_load: &mut indexmap::IndexMap<Vec<u8>, (Vec<u8>, Option<Vec<Vec<Vec<u8>>>>)>,
    ) {
        // Group filter keys by search-prefix length.
        let mut prefix_to_keys: indexmap::IndexMap<Vec<u8>, Vec<Vec<Vec<u8>>>> =
            indexmap::IndexMap::new();
        let mut length_filters: std::collections::HashMap<usize, indexmap::IndexSet<Vec<u8>>> =
            std::collections::HashMap::new();
        for key in filter.iter() {
            let search_prefix = self.search_prefix_filter(&Key::from(key.clone()));
            length_filters
                .entry(search_prefix.len())
                .or_default()
                .insert(search_prefix.clone());
            prefix_to_keys
                .entry(search_prefix)
                .or_default()
                .push(key.clone());
        }

        if length_filters.len() == 1 && length_filters.contains_key(&self.node_width) {
            // All filter keys map to full-width prefixes — do direct
            // dict lookups in filter-prefix order.
            let prefixes = &length_filters[&self.node_width];
            for prefix in prefixes.iter() {
                let Some(child) = self.items.get(prefix) else {
                    continue;
                };
                let node_filter = prefix_to_keys.get(prefix).cloned();
                match child {
                    NodeRef::Loaded(node) => out.push((node.clone(), node_filter)),
                    NodeRef::Unloaded(sha1_key) => {
                        to_load.insert(sha1_key.clone(), (prefix.clone(), node_filter));
                    }
                }
            }
        } else {
            // The slow path: walk every item, check each length filter.
            for (prefix, child) in self.items.iter() {
                let mut node_keys: Vec<Vec<Vec<u8>>> = Vec::new();
                for (length, length_filter) in length_filters.iter() {
                    if prefix.len() >= *length {
                        let sub_prefix = &prefix[..*length];
                        if length_filter.contains(sub_prefix) {
                            if let Some(keys) = prefix_to_keys.get(sub_prefix) {
                                node_keys.extend(keys.iter().cloned());
                            }
                        }
                    }
                }
                if !node_keys.is_empty() {
                    match child {
                        NodeRef::Loaded(node) => out.push((node.clone(), Some(node_keys))),
                        NodeRef::Unloaded(sha1_key) => {
                            to_load.insert(sha1_key.clone(), (prefix.clone(), Some(node_keys)));
                        }
                    }
                }
            }
        }
    }

    /// Read-only references to the children. Mirrors `InternalNode.refs`:
    /// returns the sha1 key of each unloaded child plus the
    /// `.key()` of each loaded child. Returns an `AssertionFailed`
    /// error when `self.key` is unset — the Python equivalent
    /// raises an `AssertionError`.
    pub fn refs(&self) -> Result<Vec<Vec<u8>>, Error> {
        if self.key.is_none() {
            return Err(Error::AssertionFailed(
                "unserialised nodes have no refs".into(),
            ));
        }
        let mut out: Vec<Vec<u8>> = Vec::with_capacity(self.items.len());
        for value in self.items.values() {
            match value {
                NodeRef::Unloaded(k) => out.push(k.clone()),
                NodeRef::Loaded(n) => {
                    let k = n.key().ok_or_else(|| {
                        Error::AssertionFailed("InternalNode.refs: loaded child has no key".into())
                    })?;
                    out.push(k.to_vec());
                }
            }
        }
        Ok(out)
    }
}

/// The CHK page cache: a sha1-keyed bytes store the deserialiser
/// consults before fetching from the underlying store.
///
/// Decoupled into a trait so the pyo3 layer can back it with
/// Python's per-thread `LRUSizeCache` (size-bounded) while pure-Rust
/// callers get a simple count-bounded LRU. Mirrors the per-thread
/// `_get_cache()` in `bzrformats/chk_map.py`.
pub trait PageCache: Send + Sync {
    /// Fetch the cached bytes for `sha1_key` (e.g. `b"sha1:abcd"`).
    fn get(&self, sha1_key: &[u8]) -> Option<Vec<u8>>;
    /// Cache `bytes` under `sha1_key`.
    fn insert(&self, sha1_key: Vec<u8>, bytes: Vec<u8>);
    /// Drop every cached entry.
    fn clear(&self);
}

/// Default in-memory `PageCache`: a `Mutex<LruCache>` shared across
/// CHKMap instances. Count-bounded (Python's `LRUSizeCache` is
/// byte-bounded; we approximate with a fixed entry count).
pub struct InMemoryPageCache {
    inner: std::sync::Mutex<lru::LruCache<Vec<u8>, Vec<u8>>>,
}

impl InMemoryPageCache {
    /// At ~4 KiB per CHK page, 1024 entries gives ~4 MiB of cache —
    /// the same nominal budget Python's `LRUSizeCache(4 * 1024 * 1024)`
    /// uses.
    pub const DEFAULT_CAPACITY: usize = 1024;

    pub fn new() -> Self {
        Self::with_capacity(Self::DEFAULT_CAPACITY)
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            inner: std::sync::Mutex::new(lru::LruCache::new(
                std::num::NonZeroUsize::new(capacity)
                    .expect("InMemoryPageCache capacity must be > 0"),
            )),
        }
    }
}

impl Default for InMemoryPageCache {
    fn default() -> Self {
        Self::new()
    }
}

impl PageCache for InMemoryPageCache {
    fn get(&self, sha1_key: &[u8]) -> Option<Vec<u8>> {
        let mut g = self.inner.lock().expect("page cache mutex poisoned");
        g.get(sha1_key).cloned()
    }

    fn insert(&self, sha1_key: Vec<u8>, bytes: Vec<u8>) {
        let mut g = self.inner.lock().expect("page cache mutex poisoned");
        g.put(sha1_key, bytes);
    }

    fn clear(&self) {
        let mut g = self.inner.lock().expect("page cache mutex poisoned");
        g.clear();
    }
}

/// Deserialise a CHK page from `data`, dispatching on the magic
/// prefix. Returns a fully populated `Node` with `key` set to the
/// supplied sha1 key.
///
/// Mirrors Python's `_deserialise(data, key, search_key_func)` plus
/// the small post-processing wrappers that follow each parse.
pub fn deserialise_node(
    data: &[u8],
    key: Vec<u8>,
    search_key_func: SearchKeyFunc,
) -> Result<Node, Error> {
    if data.starts_with(b"chkleaf:\n") {
        let parsed = deserialise_leaf_node(data)?;
        let mut leaf = LeafNode::from_parsed(parsed, search_key_func);
        if data.len() != leaf.current_size() {
            return Err(Error::AssertionFailed(
                "_current_size computed incorrectly".into(),
            ));
        }
        leaf.key = Some(key);
        Ok(Node::Leaf(Box::new(leaf)))
    } else if data.starts_with(b"chknode:\n") {
        let parsed = deserialise_internal_node(data)?;
        let mut internal = InternalNode::from_parsed(parsed, search_key_func);
        internal.key = Some(key);
        Ok(Node::Internal(Box::new(internal)))
    } else {
        Err(Error::AssertionFailed("Unknown node type.".into()))
    }
}

/// Core of `InternalNode.map` — takes the node by value so it can
/// optionally wrap itself in a new parent.
///
/// Returns `(replacement_node, MapResult)` where:
/// * `replacement_node` is what should occupy the original parent
///   slot. Usually the (mutated) self; may be a new wrapping parent
///   when the inserted key falls outside `self.search_prefix`.
/// * `MapResult` describes whether the *replacement* needs further
///   wrapping at the level above.
fn internal_map_with_store<S>(
    mut node: InternalNode,
    store: &S,
    cache: &dyn PageCache,
    key: Vec<Vec<u8>>,
    value: Vec<u8>,
) -> Result<(Node, MapResult), Error>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    if node.items.is_empty() {
        return Err(Error::AssertionFailed(
            "can't map in an empty InternalNode".into(),
        ));
    }
    let key_obj = Key::from(key.clone());
    let search_key = node.search_key(&key_obj);
    let search_prefix = node
        .search_prefix
        .clone()
        .ok_or_else(|| Error::AssertionFailed("search_prefix is None".into()))?;
    if node.node_width != search_prefix.len() + 1 {
        return Err(Error::AssertionFailed(format!(
            "node width mismatch: {} is not {}",
            node.node_width,
            search_prefix.len() + 1
        )));
    }
    if !search_key.starts_with(&search_prefix) {
        // Inserted key falls outside our search prefix: wrap self in
        // a new parent that has the broader prefix and recurse.
        let new_prefix = common_prefix_pair(&search_prefix, &search_key).to_vec();
        let mut new_parent = InternalNode::new(new_prefix.clone(), node.search_key_func.clone());
        new_parent.maximum_size = node.maximum_size;
        new_parent.key_width = node.key_width;
        // The wrapping parent's only child (initially) is `node`, at
        // its current search prefix extended by one byte.
        let wrap_prefix = search_prefix[..new_prefix.len() + 1].to_vec();
        new_parent.add_node(wrap_prefix, Node::Internal(Box::new(node)))?;
        // Recurse into the new parent.
        return internal_map_with_store(new_parent, store, cache, key, value);
    }
    // Find the matching child via iter_nodes (which demand-loads).
    let mut children = node.iter_nodes(store, cache, Some(&[key.clone()]), None)?;
    let (mut child_node, _filter) = if children.is_empty() {
        // No matching child — create a fresh LeafNode under
        // `search_key`. Mirrors `_new_child(search_key, LeafNode)`.
        let mut leaf = LeafNode::new(node.search_key_func.clone());
        leaf.maximum_size = node.maximum_size;
        leaf.key_width = node.key_width;
        let new_leaf = Node::Leaf(Box::new(leaf));
        node.items
            .insert(search_key.clone(), NodeRef::Loaded(new_leaf.clone()));
        (new_leaf, None)
    } else {
        children.remove(0)
    };
    let old_len = child_node.len();
    let old_size = match &child_node {
        Node::Leaf(l) => Some(l.current_size()),
        Node::Internal(_) => None,
    };
    let map_res = child_node.map_with_store(store, cache, key, value)?;
    match map_res {
        MapResult::InPlace { .. } => {
            // Child absorbed in place. Update items, len, and run
            // _check_remap if applicable.
            let new_len = child_node.len();
            node.len = node.len + new_len - old_len;
            node.items
                .insert(search_key.clone(), NodeRef::Loaded(child_node.clone()));
            node.key = None;
            // _check_remap heuristics.
            let new_self = match &child_node {
                Node::Leaf(child_leaf) => {
                    if old_size.is_none() {
                        // Child was previously an internal that
                        // collapsed to a leaf — definitely remap.
                        node.check_remap(store, cache)?
                    } else {
                        let new_size = child_leaf.current_size();
                        let shrinkage = old_size.unwrap().saturating_sub(new_size);
                        if (shrinkage > 0 && new_size < INTERESTING_NEW_SIZE)
                            || shrinkage > INTERESTING_SHRINKAGE_LIMIT
                        {
                            node.check_remap(store, cache)?
                        } else {
                            Node::Internal(Box::new(node))
                        }
                    }
                }
                Node::Internal(_) => Node::Internal(Box::new(node)),
            };
            let prefix = match &new_self {
                Node::Leaf(l) => match &l.search_prefix {
                    SearchPrefix::Computed(Some(p)) => p.clone(),
                    SearchPrefix::Computed(None) => Vec::new(),
                    SearchPrefix::Unknown => {
                        return Err(Error::AssertionFailed(
                            "search_prefix unknown after map".into(),
                        ))
                    }
                },
                Node::Internal(n) => n
                    .search_prefix
                    .clone()
                    .ok_or_else(|| Error::AssertionFailed("search_prefix is None".into()))?,
            };
            Ok((
                new_self,
                MapResult::InPlace {
                    search_prefix: prefix,
                },
            ))
        }
        MapResult::Split {
            common_serialised_prefix: child_prefix,
            children: split_children,
        } => {
            // Child overflowed: build a new intermediate InternalNode
            // at the split prefix and add all the split children.
            let mut intermediate =
                InternalNode::new(child_prefix.clone(), node.search_key_func.clone());
            intermediate.maximum_size = node.maximum_size;
            intermediate.key_width = node.key_width;
            for (sp, ch) in split_children {
                intermediate.add_node(sp, ch)?;
            }
            let new_child = Node::Internal(Box::new(intermediate));
            let new_len = new_child.len();
            node.items.insert(search_key, NodeRef::Loaded(new_child));
            node.len = node.len + new_len - old_len;
            node.key = None;
            let prefix = node.search_prefix.clone().unwrap_or_default();
            Ok((
                Node::Internal(Box::new(node)),
                MapResult::InPlace {
                    search_prefix: prefix,
                },
            ))
        }
    }
}

/// Core of `InternalNode.unmap` — takes the node by value so it can
/// optionally return a different replacement (single remaining
/// child, collapsed leaf).
fn internal_unmap_with_store<S>(
    mut node: InternalNode,
    store: &S,
    cache: &dyn PageCache,
    key: &[Vec<u8>],
    check_remap: bool,
) -> Result<Node, Error>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    if node.items.is_empty() {
        return Err(Error::AssertionFailed(
            "can't unmap in an empty InternalNode".into(),
        ));
    }
    let key_obj = Key::from(key.to_vec());
    let children = node.iter_nodes(store, cache, Some(&[key.to_vec()]), None)?;
    let (child, _filter) = children.into_iter().next().ok_or_else(|| {
        Error::AssertionFailed(format!("key not found in internal node: {:?}", key))
    })?;
    node.len -= 1;
    let unmapped = child.unmap_with_store(store, cache, key, true)?;
    node.key = None;
    let search_key = node.search_key(&key_obj);
    let was_internal_after = matches!(unmapped, Node::Internal(_));
    if unmapped.len() == 0 {
        // Drop the child entirely.
        node.items.shift_remove(&search_key);
    } else {
        node.items.insert(search_key, NodeRef::Loaded(unmapped));
    }
    if node.items.len() == 1 {
        // Only one child left — collapse this internal node out of
        // the chain entirely.
        let only = node
            .items
            .into_iter()
            .next()
            .expect("just checked len == 1")
            .1;
        return Ok(match only {
            NodeRef::Loaded(n) => n,
            NodeRef::Unloaded(sha1_key) => {
                // Need to load it from cache or store.
                let bytes = match cache.get(&sha1_key) {
                    Some(b) => b,
                    None => {
                        let stream = store
                            .get_record_stream(
                                &[crate::versionedfile::Key::Fixed(vec![sha1_key.clone()])],
                                "unordered",
                                true,
                            )
                            .map_err(|e| {
                                Error::AssertionFailed(format!("get_record_stream: {:?}", e))
                            })?;
                        let record = stream
                            .into_iter()
                            .next()
                            .ok_or_else(|| {
                                Error::AssertionFailed(
                                    "store returned no record for collapse child".into(),
                                )
                            })?
                            .map_err(|e| Error::AssertionFailed(format!("record: {:?}", e)))?;
                        let data = record.to_fulltext().into_owned();
                        cache.insert(sha1_key.clone(), data.clone());
                        data
                    }
                };
                deserialise_node(&bytes, sha1_key, node.search_key_func.clone())?
            }
        });
    }
    if was_internal_after {
        // The replaced child is itself an internal node; per the
        // Python heuristic, we know there's no chance of further
        // collapse at this level.
        return Ok(Node::Internal(Box::new(node)));
    }
    if check_remap {
        node.check_remap(store, cache)
    } else {
        Ok(Node::Internal(Box::new(node)))
    }
}

/// Check whether every search key in `search_keys` is identical.
///
/// Mirrors `LeafNode._are_search_keys_identical`: this is the safety check
/// that lets a LeafNode grow past `_maximum_size` when its keys all hash to
/// the same search key (a collision under hash-based search funcs). An
/// empty iterator returns `true` (no two keys disagree).
pub fn are_search_keys_identical<I, S>(search_keys: I) -> bool
where
    I: IntoIterator<Item = S>,
    S: AsRef<[u8]>,
{
    let mut iter = search_keys.into_iter();
    let first = match iter.next() {
        Some(k) => k,
        None => return true,
    };
    let first = first.as_ref();
    iter.all(|k| k.as_ref() == first)
}

#[test]
fn test_common_prefix_many() {
    assert_eq!(
        common_prefix_many(vec![&b"abc"[..], &b"abc"[..]].into_iter()),
        Some(&b"abc"[..])
    );
    assert_eq!(
        common_prefix_many(vec![&b"abc"[..], &b"abcd"[..]].into_iter()),
        Some(&b"abc"[..])
    );
    assert_eq!(
        common_prefix_many(vec![&b"abc"[..], &b"ab"[..]].into_iter()),
        Some(&b"ab"[..])
    );
    assert_eq!(
        common_prefix_many(vec![&b"abc"[..], &b"bbd"[..]].into_iter()),
        Some(&b""[..])
    );
    assert_eq!(
        common_prefix_many(vec![&b"abcd"[..], &b"abc"[..], &b"abc"[..]].into_iter()),
        Some(&b"abc"[..])
    );
    assert_eq!(common_prefix_many(vec![].into_iter()), None);
}

/// A persistent map from key-tuple to value-bytes backed by a CHK
/// store.
///
/// Mirrors Python's `CHKMap`. The `store` is a `VersionedFiles`
/// instance that holds the serialised page bytes; the `cache` is a
/// `PageCache` (typically `InMemoryPageCache`) consulted before
/// fetching from the store. The `root` is the root node — either an
/// `Unloaded` sha1 reference (lazy-loaded on first access) or a
/// `Loaded` in-memory `Node`.
pub struct CHKMap<S>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    pub store: std::sync::Arc<S>,
    pub cache: std::sync::Arc<dyn PageCache>,
    pub search_key_func: SearchKeyFunc,
    pub root: NodeRef,
}

impl<S> CHKMap<S>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    /// Create a new CHKMap.
    ///
    /// `root_key` is the sha1 of the existing root node, or `None`
    /// to start with an empty in-memory LeafNode.
    pub fn new(
        store: std::sync::Arc<S>,
        cache: std::sync::Arc<dyn PageCache>,
        root_key: Option<Vec<u8>>,
        search_key_func: SearchKeyFunc,
    ) -> Self {
        let root = match root_key {
            None => NodeRef::Loaded(Node::Leaf(Box::new(LeafNode::new(search_key_func.clone())))),
            Some(k) => NodeRef::Unloaded(k),
        };
        Self {
            store,
            cache,
            search_key_func,
            root,
        }
    }

    /// Number of entries in this map. Demand-loads the root if
    /// needed.
    pub fn len(&mut self) -> Result<usize, Error> {
        self.ensure_root()?;
        Ok(match &self.root {
            NodeRef::Loaded(n) => n.len(),
            NodeRef::Unloaded(_) => unreachable!("just ensured root"),
        })
    }

    pub fn is_empty(&mut self) -> Result<bool, Error> {
        Ok(self.len()? == 0)
    }

    /// Return the sha1 key of the root node, or `None` if the root
    /// is in memory and has not yet been serialised.
    pub fn key(&self) -> Option<Vec<u8>> {
        match &self.root {
            NodeRef::Unloaded(k) => Some(k.clone()),
            NodeRef::Loaded(n) => n.key().map(|s| s.to_vec()),
        }
    }

    /// Ensure the root node is `Loaded`. If it was `Unloaded`, fetch
    /// and deserialise it. Mirrors `CHKMap._ensure_root`.
    pub fn ensure_root(&mut self) -> Result<(), Error> {
        if let NodeRef::Unloaded(sha1_key) = &self.root {
            let key = sha1_key.clone();
            let bytes = read_node_bytes(&*self.store, &*self.cache, &key)?;
            let node = deserialise_node(&bytes, key, self.search_key_func.clone())?;
            self.root = NodeRef::Loaded(node);
        }
        Ok(())
    }

    /// Insert `(key, value)`. Mirrors Python's `CHKMap.map`.
    pub fn map(&mut self, key: Vec<Vec<u8>>, value: Vec<u8>) -> Result<(), Error> {
        self.ensure_root()?;
        let root = match &mut self.root {
            NodeRef::Loaded(n) => n,
            NodeRef::Unloaded(_) => unreachable!("just ensured root"),
        };
        let res = root.map_with_store(&*self.store, &*self.cache, key, value)?;
        if let MapResult::Split {
            common_serialised_prefix,
            children,
        } = res
        {
            // Build a new InternalNode wrapping the split children
            // and use it as the new root.
            let (mxs, kw) = match children.first() {
                Some((_, n)) => (
                    n.maximum_size(),
                    match n {
                        Node::Leaf(l) => l.key_width,
                        Node::Internal(i) => i.key_width,
                    },
                ),
                None => (0, 1),
            };
            let mut new_root =
                InternalNode::new(common_serialised_prefix, self.search_key_func.clone());
            new_root.maximum_size = mxs;
            new_root.key_width = kw;
            for (prefix, child) in children {
                new_root.add_node(prefix, child)?;
            }
            self.root = NodeRef::Loaded(Node::Internal(Box::new(new_root)));
        }
        Ok(())
    }

    /// Remove `key`. Mirrors Python's `CHKMap.unmap(key, check_remap)`.
    pub fn unmap(&mut self, key: &[Vec<u8>], check_remap: bool) -> Result<(), Error> {
        self.ensure_root()?;
        // For LeafNode root, check_remap is ignored (LeafNode.unmap
        // doesn't accept it); for InternalNode root, it threads through.
        let placeholder = Node::Leaf(Box::new(LeafNode::new(self.search_key_func.clone())));
        let old_root = std::mem::replace(&mut self.root, NodeRef::Loaded(placeholder));
        let old_node = match old_root {
            NodeRef::Loaded(n) => n,
            NodeRef::Unloaded(_) => unreachable!("just ensured root"),
        };
        let new_root = old_node.unmap_with_store(&*self.store, &*self.cache, key, check_remap)?;
        self.root = NodeRef::Loaded(new_root);
        Ok(())
    }

    /// Iterate `(key, value)` pairs in the map. Mirrors
    /// `CHKMap.iteritems`.
    pub fn iteritems(
        &mut self,
        key_filter: Option<&[Vec<Vec<u8>>]>,
    ) -> Result<Vec<(Vec<Vec<u8>>, Vec<u8>)>, Error> {
        self.ensure_root()?;
        let root = match &mut self.root {
            NodeRef::Loaded(n) => n,
            NodeRef::Unloaded(_) => unreachable!("just ensured root"),
        };
        root.iteritems(&*self.store, &*self.cache, key_filter)
    }

    /// Run a `check_remap` pass at the root. Mirrors Python's
    /// `CHKMap._check_remap`.
    pub fn check_remap(&mut self) -> Result<(), Error> {
        self.ensure_root()?;
        let placeholder = Node::Leaf(Box::new(LeafNode::new(self.search_key_func.clone())));
        let old_root = std::mem::replace(&mut self.root, NodeRef::Loaded(placeholder));
        let old_node = match old_root {
            NodeRef::Loaded(n) => n,
            NodeRef::Unloaded(_) => unreachable!("just ensured root"),
        };
        let new_root = match old_node {
            Node::Internal(b) => b.check_remap(&*self.store, &*self.cache)?,
            other @ Node::Leaf(_) => other,
        };
        self.root = NodeRef::Loaded(new_root);
        Ok(())
    }

    /// Bulk-populate a fresh CHKMap from `initial_value` and serialise
    /// it. Returns the root sha1 key. Mirrors Python's
    /// `CHKMap.from_dict` / `_create_directly`.
    pub fn from_dict(
        store: std::sync::Arc<S>,
        cache: std::sync::Arc<dyn PageCache>,
        initial_value: indexmap::IndexMap<Vec<Vec<u8>>, Vec<u8>>,
        maximum_size: usize,
        key_width: usize,
        search_key_func: SearchKeyFunc,
    ) -> Result<Vec<u8>, Error> {
        let mut leaf = LeafNode::new(search_key_func.clone());
        leaf.maximum_size = maximum_size;
        leaf.key_width = key_width;
        // Compute raw_size from the items.
        leaf.raw_size = initial_value
            .iter()
            .map(|(k, v)| leaf_node_key_value_len(k, v))
            .sum();
        leaf.items = initial_value;
        leaf.compute_search_prefix();
        leaf.compute_serialised_prefix();
        // Split if the bulk-populated leaf is oversize.
        let mut node =
            if leaf.items.len() > 1 && maximum_size > 0 && leaf.current_size() > maximum_size {
                let (prefix, children) = leaf.split()?;
                if children.len() == 1 {
                    return Err(Error::AssertionFailed(
                        "Failed to split using node._split".into(),
                    ));
                }
                let mut internal = InternalNode::new(prefix, search_key_func);
                internal.maximum_size = maximum_size;
                internal.key_width = key_width;
                for (split_prefix, child) in children {
                    internal.add_node(split_prefix, child)?;
                }
                Node::Internal(Box::new(internal))
            } else {
                Node::Leaf(Box::new(leaf))
            };
        let keys = node.serialise(&*store, &*cache)?;
        Ok(keys
            .last()
            .cloned()
            .ok_or_else(|| Error::AssertionFailed("from_dict produced no keys".into()))?)
    }

    /// Iterate the differences between this map and `basis`.
    ///
    /// Mirrors Python's `CHKMap.iter_changes`: yields
    /// `(key, basis_value, self_value)` tuples for keys that differ
    /// (one side may carry `None` for "absent here"). Identical
    /// subtrees are skipped wholesale by sha1-key comparison.
    pub fn iter_changes(
        &mut self,
        basis: &mut CHKMap<S>,
    ) -> Result<Vec<(Vec<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)>, Error> {
        let mut out: Vec<(Vec<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)> = Vec::new();
        // Fast path: identical root keys means no changes.
        if let (Some(a), Some(b)) = (self.key(), basis.key()) {
            if a == b {
                return Ok(out);
            }
        }
        self.ensure_root()?;
        basis.ensure_root()?;

        // We work with three stores: self.store, basis.store, and
        // the page caches per side. The iter_changes algorithm
        // demand-loads via either side's store.
        let mut self_pending: std::collections::BinaryHeap<std::cmp::Reverse<PendingItem>> =
            std::collections::BinaryHeap::new();
        let mut basis_pending: std::collections::BinaryHeap<std::cmp::Reverse<PendingItem>> =
            std::collections::BinaryHeap::new();

        // Seed the pending heaps from the roots. Mirrors
        // `process_common_prefix_nodes(self_root, None, basis_root, None)`.
        let self_root_ref = match &self.root {
            NodeRef::Loaded(n) => n.clone(),
            NodeRef::Unloaded(_) => unreachable!("just ensured root"),
        };
        let basis_root_ref = match &basis.root {
            NodeRef::Loaded(n) => n.clone(),
            NodeRef::Unloaded(_) => unreachable!("just ensured root"),
        };
        process_common_prefix_nodes(
            &self_root_ref,
            None,
            &basis_root_ref,
            None,
            &mut self_pending,
            &mut basis_pending,
            self.search_key_func.clone(),
        );

        let excluded_keys: std::collections::HashSet<Vec<u8>> = std::collections::HashSet::new();

        loop {
            if self_pending.is_empty() && basis_pending.is_empty() {
                break;
            }
            if self_pending.is_empty() {
                // Drain basis side as deletes.
                for std::cmp::Reverse(item) in basis_pending.drain() {
                    if path_excluded(&item.path, &excluded_keys) {
                        continue;
                    }
                    drain_pending_item(
                        item,
                        true,
                        &mut basis.root,
                        &*basis.store,
                        &*basis.cache,
                        basis.search_key_func.clone(),
                        &mut out,
                    )?;
                }
                break;
            }
            if basis_pending.is_empty() {
                for std::cmp::Reverse(item) in self_pending.drain() {
                    if path_excluded(&item.path, &excluded_keys) {
                        continue;
                    }
                    drain_pending_item(
                        item,
                        false,
                        &mut self.root,
                        &*self.store,
                        &*self.cache,
                        self.search_key_func.clone(),
                        &mut out,
                    )?;
                }
                break;
            }
            let self_top = &self_pending.peek().unwrap().0;
            let basis_top = &basis_pending.peek().unwrap().0;
            match self_top.prefix.cmp(&basis_top.prefix) {
                std::cmp::Ordering::Less => {
                    let item = self_pending.pop().unwrap().0;
                    if path_excluded(&item.path, &excluded_keys) {
                        continue;
                    }
                    match item.payload {
                        Payload::Value { key, value } => {
                            out.push((key, None, Some(value)));
                        }
                        Payload::Subtree(child) => {
                            let node = resolve_noderef(
                                child,
                                &*self.store,
                                &*self.cache,
                                self.search_key_func.clone(),
                            )?;
                            expand_node(
                                node,
                                item.path,
                                self.search_key_func.clone(),
                                &mut self_pending,
                            );
                        }
                    }
                }
                std::cmp::Ordering::Greater => {
                    let item = basis_pending.pop().unwrap().0;
                    if path_excluded(&item.path, &excluded_keys) {
                        continue;
                    }
                    match item.payload {
                        Payload::Value { key, value } => {
                            out.push((key, Some(value), None));
                        }
                        Payload::Subtree(child) => {
                            let node = resolve_noderef(
                                child,
                                &*basis.store,
                                &*basis.cache,
                                basis.search_key_func.clone(),
                            )?;
                            expand_node(
                                node,
                                item.path,
                                basis.search_key_func.clone(),
                                &mut basis_pending,
                            );
                        }
                    }
                }
                std::cmp::Ordering::Equal => {
                    let self_is_value = matches!(self_top.payload, Payload::Value { .. });
                    let basis_is_value = matches!(basis_top.payload, Payload::Value { .. });
                    if self_is_value && basis_is_value {
                        let self_item = self_pending.pop().unwrap().0;
                        let basis_item = basis_pending.pop().unwrap().0;
                        match (self_item.payload, basis_item.payload) {
                            (
                                Payload::Value { key: sk, value: sv },
                                Payload::Value {
                                    key: _bk,
                                    value: bv,
                                },
                            ) => {
                                if sv != bv {
                                    out.push((sk, Some(bv), Some(sv)));
                                }
                            }
                            _ => unreachable!("just checked Value/Value"),
                        }
                        continue;
                    }
                    // At least one is a subtree. Check sha1 identity
                    // first — identical pointers skip entirely.
                    let self_child_key = subtree_child_sha1(&self_top.payload);
                    let basis_child_key = subtree_child_sha1(&basis_top.payload);
                    if self_child_key.is_some() && self_child_key == basis_child_key {
                        self_pending.pop();
                        basis_pending.pop();
                        continue;
                    }
                    if !self_is_value && !basis_is_value {
                        // Both subtrees, same prefix — process in parallel.
                        let self_item = self_pending.pop().unwrap().0;
                        let basis_item = basis_pending.pop().unwrap().0;
                        let self_child = match self_item.payload {
                            Payload::Subtree(c) => c,
                            _ => unreachable!(),
                        };
                        let basis_child = match basis_item.payload {
                            Payload::Subtree(c) => c,
                            _ => unreachable!(),
                        };
                        let self_node = resolve_noderef(
                            self_child,
                            &*self.store,
                            &*self.cache,
                            self.search_key_func.clone(),
                        )?;
                        let basis_node = resolve_noderef(
                            basis_child,
                            &*basis.store,
                            &*basis.cache,
                            basis.search_key_func.clone(),
                        )?;
                        process_common_prefix_nodes(
                            &self_node,
                            Some(item_path_extend(&self_item.path, &self_node)),
                            &basis_node,
                            Some(item_path_extend(&basis_item.path, &basis_node)),
                            &mut self_pending,
                            &mut basis_pending,
                            self.search_key_func.clone(),
                        );
                        continue;
                    }
                    if !self_is_value {
                        let item = self_pending.pop().unwrap().0;
                        if path_excluded(&item.path, &excluded_keys) {
                            continue;
                        }
                        let child = match item.payload {
                            Payload::Subtree(c) => c,
                            _ => unreachable!(),
                        };
                        let node = resolve_noderef(
                            child,
                            &*self.store,
                            &*self.cache,
                            self.search_key_func.clone(),
                        )?;
                        expand_node(
                            node,
                            item.path,
                            self.search_key_func.clone(),
                            &mut self_pending,
                        );
                    }
                    if !basis_is_value {
                        let item = basis_pending.pop().unwrap().0;
                        if path_excluded(&item.path, &excluded_keys) {
                            continue;
                        }
                        let child = match item.payload {
                            Payload::Subtree(c) => c,
                            _ => unreachable!(),
                        };
                        let node = resolve_noderef(
                            child,
                            &*basis.store,
                            &*basis.cache,
                            basis.search_key_func.clone(),
                        )?;
                        expand_node(
                            node,
                            item.path,
                            basis.search_key_func.clone(),
                            &mut basis_pending,
                        );
                    }
                }
            }
        }
        Ok(out)
    }

    /// Apply a sequence of `(old_key, new_key, new_value)` changes,
    /// returning the new root sha1 key.
    ///
    /// Mirrors Python's `CHKMap.apply_delta`:
    /// * pre-check that none of the new keys already exist (insert,
    ///   not update) — raises InconsistentDeltaDelta otherwise;
    /// * apply all deletes (`old != None and old != new`);
    /// * apply all inserts (`new != None`);
    /// * `check_remap` if any deletes happened;
    /// * `save` and return the new root.
    pub fn apply_delta(
        &mut self,
        delta: Vec<(Option<Vec<Vec<u8>>>, Option<Vec<Vec<u8>>>, Vec<u8>)>,
    ) -> Result<Vec<u8>, Error> {
        // Pre-check: every (None, Some(k), v) entry's k must not
        // already be in the map.
        let new_only: Vec<Vec<Vec<u8>>> = delta
            .iter()
            .filter_map(|(old, new, _v)| match (old, new) {
                (None, Some(k)) => Some(k.clone()),
                _ => None,
            })
            .collect();
        if !new_only.is_empty() {
            let existing = self.iteritems(Some(&new_only))?;
            if !existing.is_empty() {
                return Err(Error::InconsistentDeltaDelta(
                    delta
                        .iter()
                        .map(|(o, n, v)| {
                            (
                                o.as_ref().map(|k| Key::from(k.clone())),
                                n.as_ref().map(|k| Key::from(k.clone())),
                                v.clone(),
                            )
                        })
                        .collect(),
                    format!("New items are already in the map {:?}.", existing),
                ));
            }
        }
        // Apply deletes.
        let mut has_deletes = false;
        for (old, new, _value) in &delta {
            if let Some(old_k) = old {
                if Some(old_k) != new.as_ref() {
                    self.unmap(old_k, false)?;
                    has_deletes = true;
                }
            }
        }
        // Apply inserts.
        for (_old, new, value) in &delta {
            if let Some(new_k) = new {
                self.map(new_k.clone(), value.clone())?;
            }
        }
        if has_deletes {
            self.check_remap()?;
        }
        self.save()
    }

    /// Serialise everything to the store and return the root sha1
    /// key. Mirrors `CHKMap._save`.
    pub fn save(&mut self) -> Result<Vec<u8>, Error> {
        match &self.root {
            NodeRef::Unloaded(k) => return Ok(k.clone()),
            NodeRef::Loaded(_) => {}
        }
        let root = match &mut self.root {
            NodeRef::Loaded(n) => n,
            NodeRef::Unloaded(_) => unreachable!(),
        };
        let keys = root.serialise(&*self.store, &*self.cache)?;
        Ok(keys
            .last()
            .cloned()
            .ok_or_else(|| Error::AssertionFailed("save returned no keys".into()))?)
    }
}

/// One yielded record from the `iter_interesting_nodes` walk.
///
/// Mirrors Python's `(record, items)` yield pairs: a record holds a
/// CHK page's sha1 key and bytes (or `None`s for the
/// initial-from-queue items-only emission), plus any new
/// `(key, value)` items found on that page.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DifferenceRecord {
    /// sha1 key of the page that was read, or `None` for the
    /// initial items-only flush.
    pub page_key: Option<Vec<u8>>,
    /// page bytes; `None` when `page_key` is `None`.
    pub page_bytes: Option<Vec<u8>>,
    /// new `(key, value)` items from this page or queue, in
    /// store-read order (matching Python's no-uniqueness guarantee).
    pub items: Vec<(Vec<Vec<u8>>, Vec<u8>)>,
}

/// Walk the new-root subtree and yield every page + new item not
/// reachable from the old-root subtree.
///
/// Mirrors Python's `CHKMapDifference.process` + `iter_interesting_nodes`:
/// reads old roots fully to populate the "uninteresting" sets, then
/// streams the new-root subtree yielding only references and items
/// that aren't in the old set.
///
/// Returns the full output (ordered: first the new-root records, then
/// the items-only flush, then descendant-page records). Native
/// generator-style streaming would require an iterator returning
/// `Result<DifferenceRecord, Error>` per `next()` — the Python
/// version is also called for its side effect of fetching every page
/// once, so materialising is acceptable.
pub fn iter_interesting_nodes<S>(
    store: &S,
    cache: &dyn PageCache,
    interesting_root_keys: &[Vec<u8>],
    uninteresting_root_keys: &[Vec<u8>],
    search_key_func: SearchKeyFunc,
) -> Result<Vec<DifferenceRecord>, Error>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    let mut diff = CHKMapDifferenceState::new(
        interesting_root_keys.to_vec(),
        uninteresting_root_keys.to_vec(),
        search_key_func,
    );
    diff.process(store, cache)
}

/// Internal state of the difference walk. Modelled as a struct so the
/// helper functions can borrow `&mut self` without clashing with the
/// store + cache references.
struct CHKMapDifferenceState {
    new_root_keys: Vec<Vec<u8>>,
    old_root_keys: Vec<Vec<u8>>,
    /// Every sha1 key reachable from the old roots (and thus to be
    /// suppressed in the output).
    all_old_chks: std::collections::HashSet<Vec<u8>>,
    /// Every (key, value) item reachable from the old roots.
    all_old_items: std::collections::HashSet<(Vec<Vec<u8>>, Vec<u8>)>,
    /// New-side refs we've already streamed (so we don't re-walk).
    processed_new_refs: std::collections::HashSet<Vec<u8>>,
    /// Old-side refs still to walk for the suppression set.
    old_queue: Vec<Vec<u8>>,
    /// New-side refs whose pages we still need to yield.
    new_queue: Vec<Vec<u8>>,
    /// Items found on root pages, deferred until after old-root walk
    /// finishes so we can deduplicate against `all_old_items`.
    new_item_queue: Vec<(Vec<Vec<u8>>, Vec<u8>)>,
    search_key_func: SearchKeyFunc,
}

impl CHKMapDifferenceState {
    fn new(
        new_root_keys: Vec<Vec<u8>>,
        old_root_keys: Vec<Vec<u8>>,
        search_key_func: SearchKeyFunc,
    ) -> Self {
        let mut all_old_chks: std::collections::HashSet<Vec<u8>> = std::collections::HashSet::new();
        for k in &old_root_keys {
            all_old_chks.insert(k.clone());
        }
        Self {
            new_root_keys,
            old_root_keys,
            all_old_chks,
            all_old_items: std::collections::HashSet::new(),
            processed_new_refs: std::collections::HashSet::new(),
            old_queue: Vec::new(),
            new_queue: Vec::new(),
            new_item_queue: Vec::new(),
            search_key_func: search_key_func.clone(),
        }
    }

    fn process<S>(
        &mut self,
        store: &S,
        cache: &dyn PageCache,
    ) -> Result<Vec<DifferenceRecord>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let mut out: Vec<DifferenceRecord> = Vec::new();
        // _read_all_roots: yields new-root records (no items per the
        // Python `yield record` + outer `yield record, []`).
        let root_records = self.read_all_roots(store, cache)?;
        for rec in root_records {
            out.push(rec);
        }
        // _process_queues: drain old queue, then flush new.
        while !self.old_queue.is_empty() {
            self.process_next_old(store, cache)?;
        }
        let flushed = self.flush_new_queue(store, cache)?;
        out.extend(flushed);
        Ok(out)
    }

    /// Read a batch of pages from `store`, returning each as
    /// `(sha1, bytes, prefix_refs, items)` where `prefix_refs` is
    /// non-empty only for internal nodes.
    #[allow(clippy::type_complexity)]
    fn read_nodes<S>(
        &self,
        store: &S,
        cache: &dyn PageCache,
        keys: &[Vec<u8>],
    ) -> Result<
        Vec<(
            Vec<u8>,
            Vec<u8>,
            Vec<(Vec<u8>, Vec<u8>)>,
            Vec<(Vec<Vec<u8>>, Vec<u8>)>,
        )>,
        Error,
    >
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let key_objs: Vec<crate::versionedfile::Key> = keys
            .iter()
            .map(|k| crate::versionedfile::Key::Fixed(vec![k.clone()]))
            .collect();
        let stream = store
            .get_record_stream(&key_objs, "unordered", true)
            .map_err(|e| Error::AssertionFailed(format!("get_record_stream: {:?}", e)))?;
        let mut out = Vec::new();
        for record in stream {
            let record = record.map_err(|e| Error::AssertionFailed(format!("record: {:?}", e)))?;
            if record.storage_kind() == "absent" {
                return Err(Error::AssertionFailed(format!(
                    "absent record: {:?}",
                    record.key()
                )));
            }
            let sha1 = record.key().segments().first().cloned().unwrap_or_default();
            let bytes = record.to_fulltext().into_owned();
            cache.insert(sha1.clone(), bytes.clone());
            let node = deserialise_node(&bytes, sha1.clone(), self.search_key_func.clone())?;
            let (prefix_refs, items) = match node {
                Node::Internal(internal) => {
                    let refs: Vec<(Vec<u8>, Vec<u8>)> = internal
                        .items
                        .into_iter()
                        .filter_map(|(prefix, child)| match child {
                            NodeRef::Unloaded(k) => Some((prefix, k)),
                            NodeRef::Loaded(n) => n.key().map(|s| (prefix, s.to_vec())),
                        })
                        .collect();
                    (refs, Vec::new())
                }
                Node::Leaf(leaf) => {
                    let items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = leaf.items.into_iter().collect();
                    (Vec::new(), items)
                }
            };
            out.push((sha1, bytes, prefix_refs, items));
        }
        Ok(out)
    }

    fn read_old_roots<S>(
        &mut self,
        store: &S,
        cache: &dyn PageCache,
    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let mut old_chks_to_enqueue: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
        let nodes = self.read_nodes(store, cache, &self.old_root_keys.clone())?;
        for (_sha1, _bytes, prefix_refs, items) in nodes {
            let filtered: Vec<(Vec<u8>, Vec<u8>)> = prefix_refs
                .into_iter()
                .filter(|(_p, r)| !self.all_old_chks.contains(r))
                .collect();
            for (_p, r) in &filtered {
                self.all_old_chks.insert(r.clone());
            }
            for item in items {
                self.all_old_items.insert(item);
            }
            old_chks_to_enqueue.extend(filtered);
        }
        Ok(old_chks_to_enqueue)
    }

    fn enqueue_old(
        &mut self,
        new_prefixes: &std::collections::HashSet<Vec<u8>>,
        old_chks_to_enqueue: Vec<(Vec<u8>, Vec<u8>)>,
    ) {
        for (prefix, refk) in old_chks_to_enqueue {
            let mut interesting = false;
            for i in (1..=prefix.len()).rev() {
                if new_prefixes.contains(&prefix[..i]) {
                    interesting = true;
                    break;
                }
            }
            if interesting {
                self.old_queue.push(refk);
            }
        }
    }

    fn read_all_roots<S>(
        &mut self,
        store: &S,
        cache: &dyn PageCache,
    ) -> Result<Vec<DifferenceRecord>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let mut out: Vec<DifferenceRecord> = Vec::new();
        if self.old_root_keys.is_empty() {
            // Shortcut: no old context, queue all new roots.
            self.new_queue = self.new_root_keys.clone();
            return Ok(out);
        }
        let old_chks_to_enqueue = self.read_old_roots(store, cache)?;
        let mut new_keys: Vec<Vec<u8>> = self
            .new_root_keys
            .iter()
            .filter(|k| !self.all_old_chks.contains(*k))
            .cloned()
            .collect();
        new_keys.sort();
        new_keys.dedup();
        let mut new_prefixes: std::collections::HashSet<Vec<u8>> = std::collections::HashSet::new();
        for k in &new_keys {
            self.processed_new_refs.insert(k.clone());
        }
        let nodes = self.read_nodes(store, cache, &new_keys)?;
        for (sha1, bytes, prefix_refs, items) in nodes {
            let filtered: Vec<(Vec<u8>, Vec<u8>)> = prefix_refs
                .into_iter()
                .filter(|(_p, r)| {
                    !self.all_old_chks.contains(r) && !self.processed_new_refs.contains(r)
                })
                .collect();
            let refs: Vec<Vec<u8>> = filtered.iter().map(|(_, r)| r.clone()).collect();
            for (p, _) in &filtered {
                new_prefixes.insert(p.clone());
            }
            self.new_queue.extend(refs.clone());
            let new_items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = items
                .into_iter()
                .filter(|it| !self.all_old_items.contains(it))
                .collect();
            for (k, _v) in &new_items {
                let prefix = self.search_key_func.apply(&Key::from(k.clone()));
                new_prefixes.insert(prefix);
            }
            self.new_item_queue.extend(new_items);
            for r in refs {
                self.processed_new_refs.insert(r);
            }
            out.push(DifferenceRecord {
                page_key: Some(sha1),
                page_bytes: Some(bytes),
                items: Vec::new(),
            });
        }
        // Expand new_prefixes to include all shorter prefixes.
        let snapshot: Vec<Vec<u8>> = new_prefixes.iter().cloned().collect();
        for p in snapshot {
            for i in 1..p.len() {
                new_prefixes.insert(p[..i].to_vec());
            }
        }
        self.enqueue_old(&new_prefixes, old_chks_to_enqueue);
        Ok(out)
    }

    fn flush_new_queue<S>(
        &mut self,
        store: &S,
        cache: &dyn PageCache,
    ) -> Result<Vec<DifferenceRecord>, Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let mut out: Vec<DifferenceRecord> = Vec::new();
        let mut refs: std::collections::HashSet<Vec<u8>> = self.new_queue.drain(..).collect();
        // Initial items-only flush.
        let queued = std::mem::take(&mut self.new_item_queue);
        let new_items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = queued
            .into_iter()
            .filter(|it| !self.all_old_items.contains(it))
            .collect();
        if !new_items.is_empty() {
            out.push(DifferenceRecord {
                page_key: None,
                page_bytes: None,
                items: new_items,
            });
        }
        for k in &self.all_old_chks {
            refs.remove(k);
        }
        for k in &refs {
            self.processed_new_refs.insert(k.clone());
        }
        while !refs.is_empty() {
            let mut next_refs: std::collections::HashSet<Vec<u8>> =
                std::collections::HashSet::new();
            let refs_vec: Vec<Vec<u8>> = refs.into_iter().collect();
            let nodes = self.read_nodes(store, cache, &refs_vec)?;
            for (sha1, bytes, prefix_refs, items) in nodes {
                let items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = if self.all_old_items.is_empty() {
                    items
                } else {
                    items
                        .into_iter()
                        .filter(|it| !self.all_old_items.contains(it))
                        .collect()
                };
                out.push(DifferenceRecord {
                    page_key: Some(sha1),
                    page_bytes: Some(bytes),
                    items,
                });
                for (_p, r) in prefix_refs {
                    next_refs.insert(r);
                }
            }
            for k in &self.all_old_chks {
                next_refs.remove(k);
            }
            for k in &self.processed_new_refs {
                next_refs.remove(k);
            }
            for k in &next_refs {
                self.processed_new_refs.insert(k.clone());
            }
            refs = next_refs;
        }
        Ok(out)
    }

    fn process_next_old<S>(&mut self, store: &S, cache: &dyn PageCache) -> Result<(), Error>
    where
        S: crate::versionedfile::VersionedFiles + ?Sized,
    {
        let refs: Vec<Vec<u8>> = std::mem::take(&mut self.old_queue);
        let nodes = self.read_nodes(store, cache, &refs)?;
        for (_sha1, _bytes, prefix_refs, items) in nodes {
            for item in items {
                self.all_old_items.insert(item);
            }
            let new_refs: Vec<Vec<u8>> = prefix_refs
                .into_iter()
                .filter_map(|(_p, r)| {
                    if self.all_old_chks.contains(&r) {
                        None
                    } else {
                        Some(r)
                    }
                })
                .collect();
            for r in &new_refs {
                self.all_old_chks.insert(r.clone());
            }
            self.old_queue.extend(new_refs);
        }
        Ok(())
    }
}

/// Heap-pending item for the `iter_changes` diff walk.
///
/// Items compare by `prefix` first (the search-key prefix for
/// internal-node children, or the search_key of a leaf value);
/// `payload` is the actual content waiting to be processed.
/// `path` is a tail-shared chain of sha1 keys of every node we
/// walked through to reach this item, used to bail when an entire
/// subtree gets excluded.
#[derive(Debug)]
struct PendingItem {
    prefix: Vec<u8>,
    payload: Payload,
    path: Vec<Vec<u8>>,
}

#[derive(Debug)]
enum Payload {
    /// An internal-node child reference waiting to be expanded.
    Subtree(NodeRef),
    /// A leaf entry that can be yielded directly.
    Value { key: Vec<Vec<u8>>, value: Vec<u8> },
}

impl PartialEq for PendingItem {
    fn eq(&self, other: &Self) -> bool {
        self.prefix == other.prefix
    }
}
impl Eq for PendingItem {}
impl PartialOrd for PendingItem {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for PendingItem {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.prefix.cmp(&other.prefix)
    }
}

/// True if any sha1 key on `path` is in `excluded_keys`.
fn path_excluded(path: &[Vec<u8>], excluded_keys: &std::collections::HashSet<Vec<u8>>) -> bool {
    path.iter().any(|k| excluded_keys.contains(k))
}

/// Convert a possibly-unloaded NodeRef into a loaded Node by
/// consulting the page cache then the store.
fn resolve_noderef<S>(
    nref: NodeRef,
    store: &S,
    cache: &dyn PageCache,
    search_key_func: SearchKeyFunc,
) -> Result<Node, Error>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    match nref {
        NodeRef::Loaded(n) => Ok(n),
        NodeRef::Unloaded(sha1_key) => {
            let bytes = read_node_bytes(store, cache, &sha1_key)?;
            deserialise_node(&bytes, sha1_key, search_key_func)
        }
    }
}

/// Append this node's sha1 key (if any) to `parent_path` to form a
/// fresh path used for items emitted from this node.
fn item_path_extend(parent_path: &[Vec<u8>], node: &Node) -> Vec<Vec<u8>> {
    let mut out = Vec::with_capacity(parent_path.len() + 1);
    out.extend_from_slice(parent_path);
    if let Some(k) = node.key() {
        out.push(k.to_vec());
    }
    out
}

/// Expand a single node: push its children (for InternalNode) or its
/// entries (for LeafNode) onto the pending heap.
fn expand_node(
    node: Node,
    parent_path: Vec<Vec<u8>>,
    _search_key_func: SearchKeyFunc,
    pending: &mut std::collections::BinaryHeap<std::cmp::Reverse<PendingItem>>,
) {
    let path = item_path_extend(&parent_path, &node);
    match node {
        Node::Leaf(leaf) => {
            for (k, v) in leaf.items {
                let search_key = leaf.search_key_func.apply(&Key::from(k.clone()));
                pending.push(std::cmp::Reverse(PendingItem {
                    prefix: search_key,
                    payload: Payload::Value { key: k, value: v },
                    path: path.clone(),
                }));
            }
        }
        Node::Internal(internal) => {
            for (prefix, child) in internal.items {
                pending.push(std::cmp::Reverse(PendingItem {
                    prefix,
                    payload: Payload::Subtree(child),
                    path: path.clone(),
                }));
            }
        }
    }
}

/// Extract the sha1 key of a Subtree payload's NodeRef if known
/// (either unloaded or a loaded node that's been serialised).
fn subtree_child_sha1(payload: &Payload) -> Option<Vec<u8>> {
    match payload {
        Payload::Subtree(NodeRef::Unloaded(k)) => Some(k.clone()),
        Payload::Subtree(NodeRef::Loaded(n)) => n.key().map(|s| s.to_vec()),
        Payload::Value { .. } => None,
    }
}

/// Seed the pending heaps with the contents of two nodes at the
/// same logical position. If both are InternalNodes, only emit the
/// symmetric difference (avoiding redundant traversal of identical
/// children). If both are LeafNodes, similarly emit only the
/// per-side differences. Otherwise, expand each side independently.
fn process_common_prefix_nodes(
    self_node: &Node,
    self_parent_path: Option<Vec<Vec<u8>>>,
    basis_node: &Node,
    basis_parent_path: Option<Vec<Vec<u8>>>,
    self_pending: &mut std::collections::BinaryHeap<std::cmp::Reverse<PendingItem>>,
    basis_pending: &mut std::collections::BinaryHeap<std::cmp::Reverse<PendingItem>>,
    search_key_func: SearchKeyFunc,
) {
    let self_path = self_parent_path.unwrap_or_else(|| {
        self_node
            .key()
            .map(|s| vec![s.to_vec()])
            .unwrap_or_default()
    });
    let basis_path = basis_parent_path.unwrap_or_else(|| {
        basis_node
            .key()
            .map(|s| vec![s.to_vec()])
            .unwrap_or_default()
    });
    match (self_node, basis_node) {
        (Node::Internal(s), Node::Internal(b)) => {
            // Symmetric difference by (prefix, child_sha1).
            let self_set: std::collections::HashMap<Vec<u8>, Option<Vec<u8>>> = s
                .items
                .iter()
                .map(|(p, c)| (p.clone(), node_ref_sha1(c)))
                .collect();
            let basis_set: std::collections::HashMap<Vec<u8>, Option<Vec<u8>>> = b
                .items
                .iter()
                .map(|(p, c)| (p.clone(), node_ref_sha1(c)))
                .collect();
            for (prefix, child) in s.items.iter() {
                let s_sha1 = node_ref_sha1(child);
                if basis_set.get(prefix) != Some(&s_sha1) {
                    self_pending.push(std::cmp::Reverse(PendingItem {
                        prefix: prefix.clone(),
                        payload: Payload::Subtree(child.clone()),
                        path: self_path.clone(),
                    }));
                }
            }
            for (prefix, child) in b.items.iter() {
                let b_sha1 = node_ref_sha1(child);
                if self_set.get(prefix) != Some(&b_sha1) {
                    basis_pending.push(std::cmp::Reverse(PendingItem {
                        prefix: prefix.clone(),
                        payload: Payload::Subtree(child.clone()),
                        path: basis_path.clone(),
                    }));
                }
            }
        }
        (Node::Leaf(s), Node::Leaf(b)) => {
            for (k, v) in s.items.iter() {
                if b.items.get(k) != Some(v) {
                    let prefix = search_key_func.apply(&Key::from(k.clone()));
                    self_pending.push(std::cmp::Reverse(PendingItem {
                        prefix,
                        payload: Payload::Value {
                            key: k.clone(),
                            value: v.clone(),
                        },
                        path: self_path.clone(),
                    }));
                }
            }
            for (k, v) in b.items.iter() {
                if s.items.get(k) != Some(v) {
                    let prefix = search_key_func.apply(&Key::from(k.clone()));
                    basis_pending.push(std::cmp::Reverse(PendingItem {
                        prefix,
                        payload: Payload::Value {
                            key: k.clone(),
                            value: v.clone(),
                        },
                        path: basis_path.clone(),
                    }));
                }
            }
        }
        _ => {
            // Mismatched shapes — expand each side independently.
            expand_node(
                self_node.clone(),
                self_path.clone(),
                search_key_func.clone(),
                self_pending,
            );
            expand_node(
                basis_node.clone(),
                basis_path,
                search_key_func,
                basis_pending,
            );
        }
    }
}

/// sha1 key of a NodeRef when known (unloaded always knows; loaded
/// only when serialised).
fn node_ref_sha1(nref: &NodeRef) -> Option<Vec<u8>> {
    match nref {
        NodeRef::Unloaded(k) => Some(k.clone()),
        NodeRef::Loaded(n) => n.key().map(|s| s.to_vec()),
    }
}

/// Drain a single pending item into the output as a one-sided
/// change (the other side is exhausted). `is_basis` chooses which
/// (value-or-None) slot the value lands in.
fn drain_pending_item<S>(
    item: PendingItem,
    is_basis: bool,
    other_root: &mut NodeRef,
    store: &S,
    cache: &dyn PageCache,
    search_key_func: SearchKeyFunc,
    out: &mut Vec<(Vec<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)>,
) -> Result<(), Error>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    let _ = other_root;
    match item.payload {
        Payload::Value { key, value } => {
            if is_basis {
                out.push((key, Some(value), None));
            } else {
                out.push((key, None, Some(value)));
            }
            Ok(())
        }
        Payload::Subtree(child) => {
            let mut node = resolve_noderef(child, store, cache, search_key_func)?;
            let items = node.iteritems(store, cache, None)?;
            for (k, v) in items {
                if is_basis {
                    out.push((k, Some(v), None));
                } else {
                    out.push((k, None, Some(v)));
                }
            }
            Ok(())
        }
    }
}

/// Fetch bytes for `sha1_key` from the page cache, falling back to
/// the store. Mirrors Python's `CHKMap._read_bytes`.
fn read_node_bytes<S>(store: &S, cache: &dyn PageCache, sha1_key: &[u8]) -> Result<Vec<u8>, Error>
where
    S: crate::versionedfile::VersionedFiles + ?Sized,
{
    if let Some(b) = cache.get(sha1_key) {
        return Ok(b);
    }
    let stream = store
        .get_record_stream(
            &[crate::versionedfile::Key::Fixed(vec![sha1_key.to_vec()])],
            "unordered",
            true,
        )
        .map_err(|e| Error::AssertionFailed(format!("get_record_stream: {:?}", e)))?;
    let record = stream
        .into_iter()
        .next()
        .ok_or_else(|| Error::AssertionFailed("store returned no record".into()))?
        .map_err(|e| Error::AssertionFailed(format!("record: {:?}", e)))?;
    let data = record.to_fulltext().into_owned();
    cache.insert(sha1_key.to_vec(), data.clone());
    Ok(data)
}

/// Test-only fixtures shared across the `chk_map` and
/// `chk_inventory` test modules. Behind `#[cfg(test)]` (and
/// `pub(crate)`) so it's invisible at link time.
#[cfg(test)]
pub(crate) mod testing {

    /// Minimal in-memory `VersionedFiles` for round-tripping pages.
    /// `add_lines` hashes content with sha1 and stores under the bare
    /// hex; `get_record_stream` strips the `b"sha1:"` prefix from
    /// query keys and returns the matching pages as
    /// `FulltextContentFactory` records.
    pub struct FakeChkStore {
        pub(crate) pages: std::sync::Mutex<std::collections::HashMap<Vec<u8>, Vec<u8>>>,
    }

    impl FakeChkStore {
        pub fn new() -> Self {
            Self {
                pages: std::sync::Mutex::new(std::collections::HashMap::new()),
            }
        }
    }

    impl crate::versionedfile::VersionedFiles for FakeChkStore {
        fn get_parent_map(
            &self,
            _keys: &[crate::versionedfile::Key],
        ) -> Result<
            std::collections::HashMap<crate::versionedfile::Key, Vec<crate::versionedfile::Key>>,
            crate::knit::KnitError,
        > {
            Ok(std::collections::HashMap::new())
        }

        fn get_record_stream(
            &self,
            keys: &[crate::versionedfile::Key],
            _ordering: &str,
            _include_delta_closure: bool,
        ) -> Result<
            Box<
                dyn Iterator<
                    Item = Result<
                        Box<dyn crate::versionedfile::ContentFactory>,
                        crate::knit::KnitError,
                    >,
                >,
            >,
            crate::knit::KnitError,
        > {
            let pages = self.pages.lock().unwrap();
            let mut records: Vec<
                Result<Box<dyn crate::versionedfile::ContentFactory>, crate::knit::KnitError>,
            > = Vec::with_capacity(keys.len());
            for key in keys {
                let full = key.segments().first().cloned().unwrap_or_default();
                let bare: &[u8] = if full.starts_with(b"sha1:") {
                    &full[5..]
                } else {
                    &full
                };
                if let Some(data) = pages.get(bare) {
                    records.push(Ok(
                        Box::new(crate::versionedfile::FulltextContentFactory::new(
                            Some(bare.to_vec()),
                            key.clone(),
                            Some(vec![]),
                            data.clone(),
                        )) as Box<dyn crate::versionedfile::ContentFactory>,
                    ));
                }
            }
            Ok(Box::new(records.into_iter()))
        }

        fn get_sha1s(
            &self,
            _keys: &[crate::versionedfile::Key],
        ) -> Result<
            std::collections::HashMap<crate::versionedfile::Key, Vec<u8>>,
            crate::knit::KnitError,
        > {
            Ok(std::collections::HashMap::new())
        }

        fn keys(&self) -> Result<Vec<crate::versionedfile::Key>, crate::knit::KnitError> {
            let p = self.pages.lock().unwrap();
            Ok(p.keys()
                .map(|k| crate::versionedfile::Key::Fixed(vec![k.clone()]))
                .collect())
        }

        fn add_lines(
            &self,
            _key: &crate::versionedfile::Key,
            _parents: Option<&[crate::versionedfile::Key]>,
            lines: &[Vec<u8>],
        ) -> Result<(Vec<u8>, usize), crate::knit::KnitError> {
            use sha1::{Digest, Sha1};
            let data: Vec<u8> = lines.iter().flatten().copied().collect();
            let mut hasher = Sha1::new();
            hasher.update(&data);
            let digest = hasher.finalize();
            let sha1_hex: String = digest.iter().map(|b| format!("{:02x}", b)).collect();
            let sha1_bytes = sha1_hex.into_bytes();
            let size = data.len();
            self.pages.lock().unwrap().insert(sha1_bytes.clone(), data);
            Ok((sha1_bytes, size))
        }

        fn insert_record_stream(
            &self,
            _stream: Box<dyn Iterator<Item = Box<dyn crate::versionedfile::ContentFactory>>>,
        ) -> Result<(), crate::knit::KnitError> {
            Err(crate::knit::KnitError::NotImplemented(
                "insert_record_stream",
            ))
        }

        fn iter_lines_added_or_present_in_keys(
            &self,
            _keys: &[crate::versionedfile::Key],
        ) -> Result<Vec<(Vec<u8>, crate::versionedfile::Key)>, crate::knit::KnitError> {
            Err(crate::knit::KnitError::NotImplemented(
                "iter_lines_added_or_present_in_keys",
            ))
        }

        fn annotate(
            &self,
            _key: &crate::versionedfile::Key,
        ) -> Result<Vec<(crate::versionedfile::Key, Vec<u8>)>, crate::knit::KnitError> {
            Err(crate::knit::KnitError::NotImplemented("annotate"))
        }
    }
}

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

    fn key(parts: &[&[u8]]) -> Key {
        Key::from(parts.iter().map(|p| p.to_vec()).collect::<Vec<_>>())
    }

    #[test]
    fn search_key_plain_joins_with_nul() {
        assert_eq!(
            search_key_plain(&key(&[b"foo", b"bar"])),
            b"foo\x00bar".to_vec()
        );
        assert_eq!(search_key_plain(&key(&[b"only"])), b"only".to_vec());
    }

    #[test]
    fn search_key_16_is_uppercase_hex() {
        // For a single-element key, the result is `{crc32:08X}`.
        let out = search_key_16(&key(&[b"hello"]));
        let s = std::str::from_utf8(&out).unwrap();
        assert_eq!(s.len(), 8);
        assert!(s
            .chars()
            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_lowercase()));
    }

    #[test]
    fn search_key_16_joins_multi_element_keys_with_nul() {
        // Exact values, matching the Python test
        // test_iteritems_keys_prefixed_by_2_width_nodes_hashed.
        assert_eq!(search_key_16(&key(&[b"a", b"a"])), b"E8B7BE43\x00E8B7BE43");
        assert_eq!(search_key_16(&key(&[b"a", b"b"])), b"E8B7BE43\x0071BEEFF9");
        assert_eq!(search_key_16(&key(&[b"b", b""])), b"71BEEFF9\x0000000000");
    }

    #[test]
    fn search_key_255_uses_raw_be_bytes_with_lf_replaced() {
        let out = search_key_255(&key(&[b"hello"]));
        assert_eq!(out.len(), 4);
        assert!(!out.contains(&b'\n'));
    }

    #[test]
    fn search_key_255_replaces_lf_with_underscore() {
        // The implementation post-processes the raw CRC bytes to replace any
        // \n byte with `_` so the result can be safely embedded in a node
        // dump.
        for input in [b"abc".as_slice(), b"x", b"y"] {
            let out = search_key_255(&key(&[input]));
            assert!(!out.contains(&b'\n'));
        }
    }

    #[test]
    fn search_key_255_multi_element_keys_use_nul_separator() {
        // Raw big-endian CRC bytes of each element, nul-joined (the \n->_
        // post-processing does not affect these inputs).
        assert_eq!(
            search_key_255(&key(&[b"a", b"b"])),
            b"\xe8\xb7\xbeC\x00q\xbe\xef\xf9"
        );
    }

    #[test]
    fn bytes_to_text_key_parses_file_record() {
        let bytes = b"file: file-id\nparent-id\nname\nrevision-id\n\
da39a3ee5e6b4b0d3255bfef95601890afd80709\n100\nN";
        let (file_id, revision_id) = bytes_to_text_key(bytes).unwrap();
        assert_eq!(file_id, b"file-id");
        assert_eq!(revision_id, b"revision-id");
    }

    #[test]
    fn bytes_to_text_key_rejects_missing_separator() {
        // No `: ` between kind and file-id.
        let bytes = b"file:file-id\nparent-id\nname\nrevision-id\n\
da39a3ee5e6b4b0d3255bfef95601890afd80709\n100\nN";
        assert!(bytes_to_text_key(bytes).is_err());
    }

    #[test]
    fn key_serialize_joins_parts_with_nul() {
        assert_eq!(key(&[b"foo", b"bar"]).serialize(), b"foo\x00bar".to_vec());
        assert_eq!(key(&[b"alone"]).serialize(), b"alone".to_vec());
    }

    #[test]
    fn key_len_returns_part_count() {
        assert_eq!(key(&[b"foo", b"bar"]).len(), 2);
        assert_eq!(key(&[b"a"]).len(), 1);
    }

    // Fixture generated from the real Python serialiser: a leaf with
    // _maximum_size=100, key_width=1, and two items whose keys share
    // the common prefix "alph". Cross-checked in the session probe.
    const LEAF_FIXTURE: &[u8] = b"chkleaf:\n100\n1\n2\nalph\n2\x002\nv2\nv2line2\na\x001\nv1\n";

    #[test]
    fn deserialise_leaf_fixture_items_match() {
        let p = deserialise_leaf_node(LEAF_FIXTURE).unwrap();
        assert_eq!(p.maximum_size, 100);
        assert_eq!(p.key_width, 1);
        assert_eq!(p.length, 2);
        assert_eq!(p.common_serialised_prefix, b"alph");
        assert_eq!(p.items.len(), 2);
        // Order matches file order, not sorted order.
        assert_eq!(p.items[0].0, vec![b"alph2".to_vec()]);
        assert_eq!(p.items[0].1, b"v2\nv2line2");
        assert_eq!(p.items[1].0, vec![b"alpha".to_vec()]);
        assert_eq!(p.items[1].1, b"v1");
    }

    #[test]
    fn deserialise_leaf_raw_size_matches_python_formula() {
        // Cross-checked against LeafNode._raw_size: 30.
        let p = deserialise_leaf_node(LEAF_FIXTURE).unwrap();
        assert_eq!(p.raw_size, 30);
    }

    #[test]
    fn deserialise_leaf_empty_items() {
        // length=0, no item lines. Prefix line is empty.
        let data = b"chkleaf:\n100\n1\n0\n\n";
        let p = deserialise_leaf_node(data).unwrap();
        assert_eq!(p.length, 0);
        assert!(p.items.is_empty());
        assert_eq!(p.common_serialised_prefix, b"");
        // raw_size = 0 + 0*0 + 0 = 0 for this case.
        assert_eq!(p.raw_size, 0);
    }

    #[test]
    fn deserialise_leaf_multi_element_key() {
        // key_width=2 means each item line has 3 NUL-separated fields:
        // the two key elements plus the value-line count.
        let data = b"chkleaf:\n200\n2\n1\n\nkey1\x00sub\x001\nhello\n";
        let p = deserialise_leaf_node(data).unwrap();
        assert_eq!(p.key_width, 2);
        assert_eq!(p.items.len(), 1);
        assert_eq!(p.items[0].0, vec![b"key1".to_vec(), b"sub".to_vec()]);
        assert_eq!(p.items[0].1, b"hello");
    }

    #[test]
    fn deserialise_leaf_rejects_missing_trailing_newline() {
        let data = b"chkleaf:\n100\n1\n0\n";
        assert!(matches!(
            deserialise_leaf_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    #[test]
    fn deserialise_leaf_rejects_bad_magic() {
        let data = b"notaleaf:\n100\n1\n0\n\n";
        assert!(matches!(
            deserialise_leaf_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    #[test]
    fn deserialise_leaf_rejects_wrong_element_count() {
        // width=1 but the key line has three NUL-separated pieces.
        let data = b"chkleaf:\n100\n1\n1\n\nfoo\x00bar\x001\nval\n";
        assert!(matches!(
            deserialise_leaf_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    #[test]
    fn deserialise_leaf_rejects_length_mismatch() {
        // Claims length=2 but only one item is present.
        let data = b"chkleaf:\n100\n1\n2\n\nfoo\x001\nval\n";
        assert!(matches!(
            deserialise_leaf_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    // Fixture generated from the real Python serialiser for an internal
    // node: _maximum_size=200, key_width=1, _search_prefix=b"pre", two
    // children. Cross-checked in the session probe.
    const INTERNAL_FIXTURE: &[u8] = b"chknode:\n200\n1\n2\npre\nbar\x00sha1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\nfoo\x00sha1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n";

    #[test]
    fn deserialise_internal_fixture_items_match() {
        let p = deserialise_internal_node(INTERNAL_FIXTURE).unwrap();
        assert_eq!(p.maximum_size, 200);
        assert_eq!(p.key_width, 1);
        assert_eq!(p.length, 2);
        assert_eq!(p.search_prefix, b"pre");
        assert_eq!(p.items.len(), 2);
        assert_eq!(p.items[0].0, b"prebar");
        assert_eq!(
            p.items[0].1,
            b"sha1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
        );
        assert_eq!(p.items[1].0, b"prefoo");
        assert_eq!(
            p.items[1].1,
            b"sha1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        // _node_width mirrors Python's loop-variable leak: the length
        // of the final parsed prefix.
        assert_eq!(p.node_width, b"prefoo".len());
    }

    #[test]
    fn deserialise_internal_rejects_empty_items() {
        let data = b"chknode:\n100\n1\n0\n\n";
        assert!(matches!(
            deserialise_internal_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    #[test]
    fn deserialise_internal_rejects_bad_magic() {
        let data = b"notchk:\n100\n1\n1\n\nfoo\x00sha1:aaaa\n";
        assert!(matches!(
            deserialise_internal_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    #[test]
    fn deserialise_internal_rejects_missing_trailing_newline() {
        let data = b"chknode:\n100\n1\n1\n\nfoo\x00sha1:aaaa";
        assert!(matches!(
            deserialise_internal_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    #[test]
    fn deserialise_internal_rejects_line_without_nul() {
        let data = b"chknode:\n100\n1\n1\n\nfoobar\n";
        assert!(matches!(
            deserialise_internal_node(data),
            Err(Error::DeserializeError(_))
        ));
    }

    #[test]
    fn serialise_leaf_node_roundtrips_through_deserialise() {
        let items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = vec![
            (vec![b"a".to_vec()], b"v1".to_vec()),
            (vec![b"alpha".to_vec()], b"v2\nv2line2".to_vec()),
        ];
        // Common prefix of the serialised key lines `a\x001\n` and
        // `alpha\x002\n` is `a` (the first byte of "a" and "alpha").
        let out = serialise_leaf_node(100, 1, &items, Some(b"a")).unwrap();
        let blob: Vec<u8> = out.iter().flatten().copied().collect();
        let parsed = deserialise_leaf_node(&blob).unwrap();
        assert_eq!(parsed.maximum_size, 100);
        assert_eq!(parsed.key_width, 1);
        assert_eq!(parsed.length, 2);
        assert_eq!(parsed.common_serialised_prefix, b"a");
        assert_eq!(parsed.items.len(), 2);
        assert_eq!(parsed.items[0].0, vec![b"a".to_vec()]);
        assert_eq!(parsed.items[0].1, b"v1".to_vec());
        assert_eq!(parsed.items[1].0, vec![b"alpha".to_vec()]);
        assert_eq!(parsed.items[1].1, b"v2\nv2line2".to_vec());
    }

    #[test]
    fn serialise_empty_leaf_node_has_blank_prefix() {
        let out = serialise_leaf_node(100, 1, &[], None).unwrap();
        let blob: Vec<u8> = out.iter().flatten().copied().collect();
        assert_eq!(blob, b"chkleaf:\n100\n1\n0\n\n");
    }

    #[test]
    fn leaf_node_key_value_len_matches_python_layout() {
        // Single-segment key, value with one newline.
        let key = vec![b"foo".to_vec()];
        let value = b"hello\nworld";
        // Layout: key\0count\nvalue\n
        //         "foo" + "\0" + "1" + "\n" + "hello\nworld" + "\n"
        //          3      1     1     1       11               1   = 18
        // Note the function returns raw size (no trailing newline yet
        // collapsed into the value); count `\n` chars in value = 1
        let got = leaf_node_key_value_len(&key, value);
        // 3 + 1 (NUL after key) + 1 (digit "1") + 1 (NUL) + 11 (value) + 1 (NUL)
        assert_eq!(got, 3 + 1 + 1 + 1 + 11 + 1);
    }

    #[test]
    fn leaf_node_key_value_len_multi_segment_key_joins_with_nul() {
        let key = vec![b"a".to_vec(), b"bc".to_vec()];
        let value = b"x";
        // key joined: "a\0bc" = 4 bytes; value has 0 newlines so count="0" (1 digit).
        let got = leaf_node_key_value_len(&key, value);
        // 4 + 1 + 1 + 1 + 1 + 1
        assert_eq!(got, 9);
    }

    #[test]
    fn leaf_node_current_size_includes_header_and_drops_prefix() {
        // length=2 items, common prefix "ab" (2 bytes), raw_size=20.
        // bytes_for_items = 20 - 2*2 = 16.
        // Header: "chkleaf:\n100\n1\n2\nab\n" = 9 + 3+1 + 1+1 + 1+1 + 2+1 = 20
        // current = 20 + 16 = 36
        let got = leaf_node_current_size(100, 1, 2, 20, Some(b"ab"));
        assert_eq!(got, 36);
    }

    #[test]
    fn leaf_node_current_size_empty_prefix() {
        let got = leaf_node_current_size(15, 1, 0, 0, None);
        // "chkleaf:\n15\n1\n0\n\n" = 9 + 2+1 + 1+1 + 1+1 + 0+1 = 17
        assert_eq!(got, 17);
    }

    #[test]
    fn internal_node_current_size_adds_header_digits() {
        // raw_size=50, length=3 (1 digit), key_width=1 (1 digit),
        // maximum_size=100 (3 digits) → 50 + 1 + 1 + 3 = 55
        let got = internal_node_current_size(100, 1, 3, 50);
        assert_eq!(got, 55);
    }

    fn key_vec(parts: &[&[u8]]) -> Vec<Vec<u8>> {
        parts.iter().map(|p| p.to_vec()).collect()
    }

    /// Build and save a CHK map from `entries`, returning its root key.
    /// Mirrors the Python `TestCaseWithExampleMaps.get_map_key` /
    /// `_get_map` helper used by the iter_changes / iter_interesting tests.
    fn build_map_key(
        store: std::sync::Arc<FakeChkStore>,
        cache: std::sync::Arc<dyn PageCache>,
        entries: &[(&[&[u8]], &[u8])],
        maximum_size: usize,
    ) -> Vec<u8> {
        let mut initial: indexmap::IndexMap<Vec<Vec<u8>>, Vec<u8>> = indexmap::IndexMap::new();
        for (key, value) in entries {
            initial.insert(key_vec(key), value.to_vec());
        }
        CHKMap::from_dict(store, cache, initial, maximum_size, 1, SearchKeyFunc::Plain).unwrap()
    }

    /// Collect every `(key, value)` item yielded by `iter_interesting_nodes`,
    /// sorted. Mirrors the Python `assertIterInteresting` aggregation, which
    /// only cares about the union of items regardless of page order.
    fn collect_interesting_items(
        store: &FakeChkStore,
        cache: &dyn PageCache,
        interesting: &[Vec<u8>],
        old: &[Vec<u8>],
    ) -> Vec<(Vec<Vec<u8>>, Vec<u8>)> {
        let records =
            iter_interesting_nodes(store, cache, interesting, old, SearchKeyFunc::Plain).unwrap();
        let mut items: Vec<(Vec<Vec<u8>>, Vec<u8>)> =
            records.into_iter().flat_map(|r| r.items).collect();
        items.sort();
        items
    }

    #[test]
    fn leaf_node_new_starts_empty() {
        let n = LeafNode::new(SearchKeyFunc::Plain);
        assert_eq!(n.len(), 0);
        assert!(n.is_empty());
        assert_eq!(n.maximum_size, 0);
        assert_eq!(n.key_width, 1);
        assert_eq!(n.raw_size, 0);
        assert!(matches!(n.search_prefix, SearchPrefix::Computed(None)));
        assert!(n.common_serialised_prefix.is_none());
        assert!(n.key.is_none());
    }

    #[test]
    fn leaf_node_map_no_split_first_insert_sets_prefixes() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        let split = n.map_no_split(key_vec(&[b"foo"]), b"bar".to_vec());
        assert!(!split);
        assert_eq!(n.len(), 1);
        // With one entry, both prefixes equal the key bytes themselves.
        assert_eq!(n.common_serialised_prefix.as_deref(), Some(&b"foo"[..]));
        assert_eq!(
            n.search_prefix,
            SearchPrefix::Computed(Some(b"foo".to_vec()))
        );
        assert_eq!(
            n.raw_size,
            leaf_node_key_value_len(&[b"foo".to_vec()], b"bar")
        );
    }

    #[test]
    fn leaf_node_map_no_split_shrinks_prefix_on_divergent_key() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map_no_split(key_vec(&[b"alpha"]), b"v1".to_vec());
        n.map_no_split(key_vec(&[b"alphabet"]), b"v2".to_vec());
        // Common prefix of "alpha" and "alphabet" is "alpha".
        assert_eq!(n.common_serialised_prefix.as_deref(), Some(&b"alpha"[..]));
        assert_eq!(
            n.search_prefix,
            SearchPrefix::Computed(Some(b"alpha".to_vec()))
        );
    }

    #[test]
    fn leaf_node_map_no_split_signals_split_when_oversize() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.maximum_size = 10;
        let _ = n.map_no_split(key_vec(&[b"foo"]), b"v1".to_vec());
        // Second entry pushes us over and the keys disagree, so we must split.
        let split = n.map_no_split(key_vec(&[b"bar"]), b"v2".to_vec());
        assert!(split);
    }

    #[test]
    fn leaf_node_unmap_removes_entry_and_recomputes_prefixes() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map_no_split(key_vec(&[b"foo"]), b"v1".to_vec());
        n.map_no_split(key_vec(&[b"foobar"]), b"v2".to_vec());
        assert_eq!(n.common_serialised_prefix.as_deref(), Some(&b"foo"[..]));
        let removed = n.unmap(&key_vec(&[b"foobar"]));
        assert_eq!(removed, Some(b"v2".to_vec()));
        // After removing "foobar", the only key left is "foo" and the prefix
        // becomes its full bytes.
        assert_eq!(n.common_serialised_prefix.as_deref(), Some(&b"foo"[..]));
        assert_eq!(n.len(), 1);
        assert!(n.key.is_none());
    }

    #[test]
    fn leaf_node_unmap_returns_none_for_missing_key() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map_no_split(key_vec(&[b"foo"]), b"v1".to_vec());
        assert_eq!(n.unmap(&key_vec(&[b"missing"])), None);
        // Unchanged otherwise.
        assert_eq!(n.len(), 1);
    }

    #[test]
    fn leaf_node_compute_search_prefix_resolves_unknown_state() {
        let blob: &[u8] = b"chkleaf:\n100\n1\n2\nalph\n2\x002\nv2\nv2line2\na\x001\nv1\n";
        let parsed = deserialise_leaf_node(blob).unwrap();
        let mut n = LeafNode::from_parsed(parsed, SearchKeyFunc::Plain);
        assert!(n.search_prefix.is_unknown());
        let prefix = n.compute_search_prefix().map(|s| s.to_vec());
        // Under Plain, the search keys equal the serialised keys; for
        // "alph2" and "alpha" the common prefix is "alph".
        assert_eq!(prefix, Some(b"alph".to_vec()));
        assert!(!n.search_prefix.is_unknown());
    }

    #[test]
    fn leaf_node_from_parsed_marks_search_prefix_unknown() {
        let blob: &[u8] = b"chkleaf:\n100\n1\n2\nalph\n2\x002\nv2\nv2line2\na\x001\nv1\n";
        let parsed = deserialise_leaf_node(blob).unwrap();
        let n = LeafNode::from_parsed(parsed, SearchKeyFunc::Plain);
        assert_eq!(n.len(), 2);
        assert!(n.search_prefix.is_unknown());
        assert_eq!(n.common_serialised_prefix.as_deref(), Some(&b"alph"[..]));
        // current_size reads off the raw_size; reproducing it just sanity
        // checks the wiring against leaf_node_current_size.
        assert!(n.current_size() > 0);
    }

    #[test]
    fn leaf_node_from_parsed_empty_keeps_prefix_none() {
        let blob: &[u8] = b"chkleaf:\n100\n1\n0\n\n";
        let parsed = deserialise_leaf_node(blob).unwrap();
        let n = LeafNode::from_parsed(parsed, SearchKeyFunc::Plain);
        assert_eq!(n.len(), 0);
        assert!(matches!(n.search_prefix, SearchPrefix::Computed(None)));
        assert!(n.common_serialised_prefix.is_none());
    }

    #[test]
    fn internal_node_new_starts_empty_with_prefix() {
        let n = InternalNode::new(b"pre".to_vec(), SearchKeyFunc::Plain);
        assert_eq!(n.len, 0);
        assert_eq!(n.node_width, 0);
        assert_eq!(n.maximum_size, 0);
        assert_eq!(n.search_prefix.as_deref(), Some(&b"pre"[..]));
        assert!(n.items.is_empty());
        assert!(n.key.is_none());
    }

    #[test]
    fn internal_node_from_parsed_marks_children_unloaded() {
        let blob: &[u8] = b"chknode:\n200\n1\n2\npre\nbar\x00sha1:bbbb\nfoo\x00sha1:aaaa\n";
        let parsed = deserialise_internal_node(blob).unwrap();
        let n = InternalNode::from_parsed(parsed, SearchKeyFunc::Plain);
        assert_eq!(n.len, 2);
        assert_eq!(n.search_prefix.as_deref(), Some(&b"pre"[..]));
        assert_eq!(n.maximum_size, 200);
        assert_eq!(n.key_width, 1);
        assert_eq!(n.items.len(), 2);
        // Verify both are Unloaded with the right sha1 keys.
        match n.items.get(&b"prebar".to_vec()) {
            Some(NodeRef::Unloaded(k)) => assert_eq!(k, b"sha1:bbbb"),
            other => panic!("expected Unloaded for prebar, got {:?}", other),
        }
        match n.items.get(&b"prefoo".to_vec()) {
            Some(NodeRef::Unloaded(k)) => assert_eq!(k, b"sha1:aaaa"),
            other => panic!("expected Unloaded for prefoo, got {:?}", other),
        }
    }

    use super::testing::FakeChkStore;

    #[test]
    fn iter_interesting_nodes_no_old_yields_all_new() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        m.map(key_vec(&[b"a"]), b"v1".to_vec()).unwrap();
        m.map(key_vec(&[b"b"]), b"v2".to_vec()).unwrap();
        let root = m.save().unwrap();
        let records =
            iter_interesting_nodes(&*store, &*cache, &[root.clone()], &[], SearchKeyFunc::Plain)
                .unwrap();
        // With no old context the root page is reported and its items
        // are flushed as a None-keyed record.
        assert!(records.iter().any(|r| r.page_key.as_deref() == Some(&root)));
        let all_items: Vec<(Vec<Vec<u8>>, Vec<u8>)> =
            records.iter().flat_map(|r| r.items.clone()).collect();
        // Note: with no old roots, items aren't yielded — the new
        // root pages are queued for processing in flush_new_queue
        // which yields per-page items. Page count + items together
        // covers the full tree.
        if all_items.is_empty() {
            // Items live in the root page; root page was emitted.
            assert!(!records.is_empty());
        } else {
            let mut sorted_items: Vec<(Vec<Vec<u8>>, Vec<u8>)> = all_items;
            sorted_items.sort();
            assert_eq!(sorted_items.len(), 2);
        }
    }

    #[test]
    fn iter_interesting_nodes_identical_old_and_new_yields_root_only() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        m.map(key_vec(&[b"a"]), b"v1".to_vec()).unwrap();
        m.map(key_vec(&[b"b"]), b"v2".to_vec()).unwrap();
        let root = m.save().unwrap();
        let records = iter_interesting_nodes(
            &*store,
            &*cache,
            &[root.clone()],
            &[root.clone()],
            SearchKeyFunc::Plain,
        )
        .unwrap();
        // Old contains the same root, so nothing new should appear.
        let interesting_items: Vec<_> = records.iter().flat_map(|r| r.items.clone()).collect();
        assert!(interesting_items.is_empty());
    }

    // The following iter_interesting_nodes tests mirror Python's
    // `TestIterInterestingNodes` (bzrformats/tests/test_chk_map.py),
    // asserting the union of yielded items rather than page-walk order.

    #[test]
    fn iter_interesting_nodes_empty_to_one_key() {
        // test_empty_to_one_keys: one interesting root, no old roots.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let target = build_map_key(store.clone(), cache.clone(), &[(&[b"a"], b"content")], 10);
        let items = collect_interesting_items(&*store, &*cache, &[target], &[]);
        assert_eq!(items, vec![(key_vec(&[b"a"]), b"content".to_vec())]);
    }

    #[test]
    fn iter_interesting_nodes_none_to_one_key() {
        // test_none_to_one_key: empty old map, one-key new map.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let basis = build_map_key(store.clone(), cache.clone(), &[], 10);
        let target = build_map_key(store.clone(), cache.clone(), &[(&[b"a"], b"content")], 10);
        let items = collect_interesting_items(&*store, &*cache, &[target], &[basis]);
        assert_eq!(items, vec![(key_vec(&[b"a"]), b"content".to_vec())]);
    }

    #[test]
    fn iter_interesting_nodes_one_to_none_key() {
        // test_one_to_none_key: deleting the only key yields no items.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let basis = build_map_key(store.clone(), cache.clone(), &[(&[b"a"], b"content")], 10);
        let target = build_map_key(store.clone(), cache.clone(), &[], 10);
        let items = collect_interesting_items(&*store, &*cache, &[target], &[basis]);
        assert!(items.is_empty());
    }

    #[test]
    fn iter_interesting_nodes_common_pages() {
        // test_common_pages: only the changed leaf's item is interesting.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let basis = build_map_key(
            store.clone(),
            cache.clone(),
            &[
                (&[b"a"], b"content"),
                (&[b"b"], b"content"),
                (&[b"c"], b"content"),
            ],
            10,
        );
        let target = build_map_key(
            store.clone(),
            cache.clone(),
            &[
                (&[b"a"], b"content"),
                (&[b"b"], b"other content"),
                (&[b"c"], b"content"),
            ],
            10,
        );
        let items = collect_interesting_items(&*store, &*cache, &[target], &[basis]);
        assert_eq!(items, vec![(key_vec(&[b"b"]), b"other content".to_vec())]);
    }

    #[test]
    fn iter_interesting_nodes_common_sub_page() {
        // test_common_sub_page: a new key nested under a shared sub-page.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let basis = build_map_key(
            store.clone(),
            cache.clone(),
            &[(&[b"aaa"], b"common"), (&[b"c"], b"common")],
            10,
        );
        let target = build_map_key(
            store.clone(),
            cache.clone(),
            &[
                (&[b"aaa"], b"common"),
                (&[b"aab"], b"new"),
                (&[b"c"], b"common"),
            ],
            10,
        );
        let items = collect_interesting_items(&*store, &*cache, &[target], &[basis]);
        assert_eq!(items, vec![(key_vec(&[b"aab"]), b"new".to_vec())]);
    }

    #[test]
    fn iter_interesting_nodes_common_leaf_multiple_targets() {
        // test_common_leaf: the shared 'aaa' leaf occurs at three depths
        // across three interesting roots but its item appears once.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let basis = build_map_key(store.clone(), cache.clone(), &[], 10);
        let target1 = build_map_key(store.clone(), cache.clone(), &[(&[b"aaa"], b"common")], 10);
        let target2 = build_map_key(
            store.clone(),
            cache.clone(),
            &[(&[b"aaa"], b"common"), (&[b"bbb"], b"new")],
            10,
        );
        let target3 = build_map_key(
            store.clone(),
            cache.clone(),
            &[
                (&[b"aaa"], b"common"),
                (&[b"aac"], b"other"),
                (&[b"bbb"], b"new"),
            ],
            10,
        );
        let items =
            collect_interesting_items(&*store, &*cache, &[target1, target2, target3], &[basis]);
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"aaa"]), b"common".to_vec()),
                (key_vec(&[b"aac"]), b"other".to_vec()),
                (key_vec(&[b"bbb"]), b"new".to_vec()),
            ]
        );
    }

    // The following iter_changes tests mirror Python's `TestMap`
    // iter_changes scenarios (bzrformats/tests/test_chk_map.py).

    /// Build a saved map and reopen it from its root key, so iter_changes
    /// starts from an unloaded tuple root like the Python tests do.
    fn reopen_map(
        store: std::sync::Arc<FakeChkStore>,
        cache: std::sync::Arc<dyn PageCache>,
        entries: &[(&[&[u8]], &[u8])],
        maximum_size: usize,
    ) -> CHKMap<FakeChkStore> {
        let root = build_map_key(store.clone(), cache.clone(), entries, maximum_size);
        CHKMap::new(store, cache, Some(root), SearchKeyFunc::Plain)
    }

    #[test]
    fn chkmap_iter_changes_empty_to_ab() {
        // test_iter_changes_empty_ab: empty basis -> {a, b} target.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut basis = reopen_map(store.clone(), cache.clone(), &[], 10);
        let mut target = reopen_map(
            store.clone(),
            cache.clone(),
            &[(&[b"a"], b"content here"), (&[b"b"], b"more content")],
            10,
        );
        let mut changes = target.iter_changes(&mut basis).unwrap();
        changes.sort();
        assert_eq!(
            changes,
            vec![
                (key_vec(&[b"a"]), None, Some(b"content here".to_vec())),
                (key_vec(&[b"b"]), None, Some(b"more content".to_vec())),
            ]
        );
    }

    #[test]
    fn chkmap_iter_changes_ab_to_empty() {
        // test_iter_changes_ab_empty: {a, b} basis -> empty target.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut basis = reopen_map(
            store.clone(),
            cache.clone(),
            &[(&[b"a"], b"content here"), (&[b"b"], b"more content")],
            10,
        );
        let mut target = reopen_map(store.clone(), cache.clone(), &[], 10);
        let mut changes = target.iter_changes(&mut basis).unwrap();
        changes.sort();
        assert_eq!(
            changes,
            vec![
                (key_vec(&[b"a"]), Some(b"content here".to_vec()), None),
                (key_vec(&[b"b"]), Some(b"more content".to_vec()), None),
            ]
        );
    }

    #[test]
    fn chkmap_iter_changes_mixed_node_length() {
        // test_iter_changes_unchanged_keys_in_multi_key_leafs_ignored:
        // unchanged keys inside multi-value leaf nodes are not reported,
        // while altered/added/removed keys are.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut basis = reopen_map(
            store.clone(),
            cache.clone(),
            &[
                (&[b"aaa"], b"foo bar"),
                (&[b"aab"], b"common altered a"),
                (&[b"b"], b"foo bar b"),
            ],
            10,
        );
        let mut target = reopen_map(
            store.clone(),
            cache.clone(),
            &[
                (&[b"aaa"], b"foo bar"),
                (&[b"aab"], b"common altered b"),
                (&[b"at"], b"foo bar t"),
            ],
            10,
        );
        let mut changes = target.iter_changes(&mut basis).unwrap();
        changes.sort();
        assert_eq!(
            changes,
            vec![
                (
                    key_vec(&[b"aab"]),
                    Some(b"common altered a".to_vec()),
                    Some(b"common altered b".to_vec()),
                ),
                (key_vec(&[b"at"]), None, Some(b"foo bar t".to_vec())),
                (key_vec(&[b"b"]), Some(b"foo bar b".to_vec()), None),
            ]
        );
    }

    #[test]
    fn chkmap_iter_changes_ab_ab_is_empty() {
        // test_iter_changes_ab_ab_is_empty: identical multi-key maps.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut basis = reopen_map(
            store.clone(),
            cache.clone(),
            &[(&[b"a"], b"content here"), (&[b"b"], b"more content")],
            10,
        );
        let mut target = reopen_map(
            store.clone(),
            cache.clone(),
            &[(&[b"a"], b"content here"), (&[b"b"], b"more content")],
            10,
        );
        let changes = target.iter_changes(&mut basis).unwrap();
        assert!(changes.is_empty());
    }

    #[test]
    fn chkmap_iter_changes_identical_returns_empty() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut a = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        a.map(key_vec(&[b"k"]), b"v".to_vec()).unwrap();
        let root = a.save().unwrap();
        let mut a2 = CHKMap::new(
            store.clone(),
            cache.clone(),
            Some(root),
            SearchKeyFunc::Plain,
        );
        let changes = a.iter_changes(&mut a2).unwrap();
        assert!(changes.is_empty());
    }

    #[test]
    fn chkmap_iter_changes_detects_add_remove_modify() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        // basis: {a:1, b:2}
        let mut basis = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        basis.map(key_vec(&[b"a"]), b"1".to_vec()).unwrap();
        basis.map(key_vec(&[b"b"]), b"2".to_vec()).unwrap();
        // self: {a:1, c:3}
        let mut me = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        me.map(key_vec(&[b"a"]), b"1".to_vec()).unwrap();
        me.map(key_vec(&[b"c"]), b"3".to_vec()).unwrap();
        let mut changes = me.iter_changes(&mut basis).unwrap();
        changes.sort();
        // 'b' was removed (basis has it, self doesn't), 'c' was added.
        assert_eq!(
            changes,
            vec![
                (key_vec(&[b"b"]), Some(b"2".to_vec()), None),
                (key_vec(&[b"c"]), None, Some(b"3".to_vec())),
            ]
        );
    }

    #[test]
    fn chkmap_iter_changes_detects_modification() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut basis = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        basis.map(key_vec(&[b"a"]), b"old".to_vec()).unwrap();
        let mut me = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        me.map(key_vec(&[b"a"]), b"new".to_vec()).unwrap();
        let changes = me.iter_changes(&mut basis).unwrap();
        assert_eq!(
            changes,
            vec![(
                key_vec(&[b"a"]),
                Some(b"old".to_vec()),
                Some(b"new".to_vec())
            )]
        );
    }

    #[test]
    fn node_refs_leaf_returns_empty() {
        let leaf = LeafNode::new(SearchKeyFunc::Plain);
        let node = Node::Leaf(Box::new(leaf));
        assert!(node.refs().unwrap().is_empty());
    }

    #[test]
    fn chkmap_from_dict_returns_loadable_root_key() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut initial: indexmap::IndexMap<Vec<Vec<u8>>, Vec<u8>> = indexmap::IndexMap::new();
        initial.insert(key_vec(&[b"a"]), b"v1".to_vec());
        initial.insert(key_vec(&[b"b"]), b"v2".to_vec());
        let root_key = CHKMap::from_dict(
            store.clone(),
            cache.clone(),
            initial,
            0,
            1,
            SearchKeyFunc::Plain,
        )
        .unwrap();
        assert!(root_key.starts_with(b"sha1:"));
        let mut m = CHKMap::new(store, cache, Some(root_key), SearchKeyFunc::Plain);
        let items = m.iteritems(None).unwrap();
        assert_eq!(items.len(), 2);
    }

    #[test]
    fn chkmap_apply_delta_inserts_and_deletes() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        m.map(key_vec(&[b"a"]), b"v1".to_vec()).unwrap();
        m.map(key_vec(&[b"b"]), b"v2".to_vec()).unwrap();

        // Delete b, add c.
        let delta = vec![
            (Some(key_vec(&[b"b"])), None, Vec::new()),
            (None, Some(key_vec(&[b"c"])), b"v3".to_vec()),
        ];
        let new_root = m.apply_delta(delta).unwrap();
        assert!(new_root.starts_with(b"sha1:"));
        let mut items = m.iteritems(None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"a"]), b"v1".to_vec()),
                (key_vec(&[b"c"]), b"v3".to_vec()),
            ]
        );
    }

    #[test]
    fn chkmap_apply_delta_rejects_insert_collisions() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        m.map(key_vec(&[b"a"]), b"v1".to_vec()).unwrap();
        // Try to insert (None, Some("a"), v2) — "a" already exists.
        let delta = vec![(None, Some(key_vec(&[b"a"])), b"v2".to_vec())];
        let err = m.apply_delta(delta).unwrap_err();
        assert!(matches!(err, Error::InconsistentDeltaDelta(_, _)));
    }

    #[test]
    fn chkmap_empty_starts_with_leaf_root() {
        let store = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store, cache, None, SearchKeyFunc::Plain);
        assert!(m.is_empty().unwrap());
        assert!(m.key().is_none());
    }

    #[test]
    fn chkmap_map_and_iteritems_roundtrip() {
        let store = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store, cache, None, SearchKeyFunc::Plain);
        m.map(key_vec(&[b"foo"]), b"v1".to_vec()).unwrap();
        m.map(key_vec(&[b"bar"]), b"v2".to_vec()).unwrap();
        let mut items = m.iteritems(None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"bar"]), b"v2".to_vec()),
                (key_vec(&[b"foo"]), b"v1".to_vec()),
            ]
        );
        assert_eq!(m.len().unwrap(), 2);
    }

    #[test]
    fn chkmap_unmap_removes_entry() {
        let store = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store, cache, None, SearchKeyFunc::Plain);
        m.map(key_vec(&[b"foo"]), b"v1".to_vec()).unwrap();
        m.map(key_vec(&[b"bar"]), b"v2".to_vec()).unwrap();
        m.unmap(&key_vec(&[b"foo"]), true).unwrap();
        let items = m.iteritems(None).unwrap();
        assert_eq!(items, vec![(key_vec(&[b"bar"]), b"v2".to_vec())]);
    }

    #[test]
    fn chkmap_save_round_trips_through_demand_load() {
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        m.map(key_vec(&[b"foo"]), b"v1".to_vec()).unwrap();
        m.map(key_vec(&[b"bar"]), b"v2".to_vec()).unwrap();
        let root_key = m.save().unwrap();
        assert!(root_key.starts_with(b"sha1:"));

        // Reload from the stored root key.
        let mut m2 = CHKMap::new(
            store.clone(),
            cache.clone(),
            Some(root_key),
            SearchKeyFunc::Plain,
        );
        let mut items = m2.iteritems(None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"bar"]), b"v2".to_vec()),
                (key_vec(&[b"foo"]), b"v1".to_vec()),
            ]
        );
    }

    #[test]
    fn chkmap_map_split_promotes_root_to_internal() {
        let store = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store, cache, None, SearchKeyFunc::Plain);
        // Tight max_size forces a split on the second insert.
        if let NodeRef::Loaded(Node::Leaf(l)) = &mut m.root {
            l.maximum_size = 10;
        }
        m.map(key_vec(&[b"foo"]), b"v1".to_vec()).unwrap();
        m.map(key_vec(&[b"bar"]), b"v2".to_vec()).unwrap();
        // Root should now be an InternalNode.
        match &m.root {
            NodeRef::Loaded(Node::Internal(_)) => {}
            other => panic!("expected Internal root after split, got {:?}", other),
        }
        let mut items = m.iteritems(None).unwrap();
        items.sort();
        assert_eq!(items.len(), 2);
    }

    #[test]
    fn chkmap_apply_delta_is_deterministic_regardless_of_order() {
        // The same items applied in different orders must produce the same
        // canonical tree and root key. Mirrors test_apply_delta_is_deterministic.
        fn build(order: &[(&[u8], &[u8])]) -> Vec<u8> {
            let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
            let cache: std::sync::Arc<dyn PageCache> =
                std::sync::Arc::new(InMemoryPageCache::new());
            let mut m = CHKMap::new(store, cache, None, SearchKeyFunc::Plain);
            if let NodeRef::Loaded(Node::Leaf(l)) = &mut m.root {
                l.maximum_size = 10;
            }
            let delta: Vec<_> = order
                .iter()
                .map(|(k, v)| (None, Some(key_vec(&[k])), v.to_vec()))
                .collect();
            m.apply_delta(delta).unwrap();
            m.save().unwrap()
        }
        let root1 = build(&[
            (b"aaa", b"common"),
            (b"bba", b"target2"),
            (b"bbb", b"common"),
        ]);
        let root2 = build(&[
            (b"bbb", b"common"),
            (b"bba", b"target2"),
            (b"aaa", b"common"),
        ]);
        assert_eq!(root1, root2);
    }

    #[test]
    fn chkmap_multi_level_split_round_trips() {
        // A tiny maximum_size with several keys sharing prefixes forces a
        // tree more than one level deep; all items must still round-trip.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Plain);
        if let NodeRef::Loaded(Node::Leaf(l)) = &mut m.root {
            l.maximum_size = 10;
        }
        let keys: &[&[u8]] = &[b"aaa", b"aab", b"aac", b"aba", b"abb", b"baa", b"bbb"];
        for k in keys {
            m.map(key_vec(&[k]), b"v".to_vec()).unwrap();
        }
        // Root must be internal after all those splits.
        assert!(matches!(&m.root, NodeRef::Loaded(Node::Internal(_))));
        let mut items = m.iteritems(None).unwrap();
        items.sort();
        let mut expected: Vec<_> = keys
            .iter()
            .map(|k| (key_vec(&[k]), b"v".to_vec()))
            .collect();
        expected.sort();
        assert_eq!(items, expected);

        // And the tree round-trips through save/reload.
        let root_key = m.save().unwrap();
        let mut reloaded = CHKMap::new(
            store.clone(),
            cache.clone(),
            Some(root_key),
            SearchKeyFunc::Plain,
        );
        let mut items2 = reloaded.iteritems(None).unwrap();
        items2.sort();
        assert_eq!(items2, expected);
    }

    #[test]
    fn chkmap_collapses_internal_to_leaf_on_size_shrink() {
        // A long value splits the root into an internal node; replacing it
        // with a short value must collapse back to a single leaf.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store, cache, None, SearchKeyFunc::Plain);
        if let NodeRef::Loaded(Node::Leaf(l)) = &mut m.root {
            l.maximum_size = 35;
        }
        m.map(key_vec(&[b"aaa"]), b"v".to_vec()).unwrap();
        m.map(key_vec(&[b"aab"]), b"very long value that splits".to_vec())
            .unwrap();
        assert!(
            matches!(&m.root, NodeRef::Loaded(Node::Internal(_))),
            "expected split to internal node"
        );
        // Shrinking the value should rebuild back into a single leaf.
        m.map(key_vec(&[b"aab"]), b"v".to_vec()).unwrap();
        assert!(
            matches!(&m.root, NodeRef::Loaded(Node::Leaf(_))),
            "expected collapse back to leaf"
        );
        let mut items = m.iteritems(None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"aaa"]), b"v".to_vec()),
                (key_vec(&[b"aab"]), b"v".to_vec()),
            ]
        );
    }

    /// Collect the sorted child prefixes of an internal root node, asserting
    /// the root did split into an internal node.
    fn root_child_prefixes(root: &NodeRef) -> Vec<Vec<u8>> {
        match root {
            NodeRef::Loaded(Node::Internal(internal)) => {
                let mut prefixes: Vec<Vec<u8>> = internal.items.keys().cloned().collect();
                prefixes.sort();
                prefixes
            }
            other => panic!("expected internal root, got {:?}", other),
        }
    }

    #[test]
    fn chkmap_search_key_16_tree_layout() {
        // Port of TestMapSearchKeys.test_search_key_16: with a small max_size
        // and the hash-16 search key, three single-char keys land under the
        // hex prefixes '1'/'6'/'8'. (Python asserts this via _dump_tree.)
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(store.clone(), cache.clone(), None, SearchKeyFunc::Hash16Way);
        if let NodeRef::Loaded(Node::Leaf(l)) = &mut m.root {
            l.maximum_size = 10;
        }
        m.map(key_vec(&[b"1"]), b"foo".to_vec()).unwrap();
        m.map(key_vec(&[b"2"]), b"bar".to_vec()).unwrap();
        m.map(key_vec(&[b"3"]), b"baz".to_vec()).unwrap();

        assert_eq!(
            root_child_prefixes(&m.root),
            vec![b"1".to_vec(), b"6".to_vec(), b"8".to_vec()]
        );
        let mut items = m.iteritems(None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"1"]), b"foo".to_vec()),
                (key_vec(&[b"2"]), b"bar".to_vec()),
                (key_vec(&[b"3"]), b"baz".to_vec()),
            ]
        );

        // Round-trips through save/reload (Python re-opens from the root key).
        let root_key = m.save().unwrap();
        let mut reloaded = CHKMap::new(
            store.clone(),
            cache.clone(),
            Some(root_key),
            SearchKeyFunc::Hash16Way,
        );
        assert_eq!(
            reloaded.iteritems(Some(&[key_vec(&[b"1"])])).unwrap(),
            vec![(key_vec(&[b"1"]), b"foo".to_vec())]
        );
    }

    #[test]
    fn chkmap_search_key_255_tree_layout() {
        // Port of TestMapSearchKeys.test_search_key_255: the raw-byte search
        // key places the three keys under the byte prefixes 0x1a / 'm' / 0x83.
        let store: std::sync::Arc<FakeChkStore> = std::sync::Arc::new(FakeChkStore::new());
        let cache: std::sync::Arc<dyn PageCache> = std::sync::Arc::new(InMemoryPageCache::new());
        let mut m = CHKMap::new(
            store.clone(),
            cache.clone(),
            None,
            SearchKeyFunc::Hash255Way,
        );
        if let NodeRef::Loaded(Node::Leaf(l)) = &mut m.root {
            l.maximum_size = 10;
        }
        m.map(key_vec(&[b"1"]), b"foo".to_vec()).unwrap();
        m.map(key_vec(&[b"2"]), b"bar".to_vec()).unwrap();
        m.map(key_vec(&[b"3"]), b"baz".to_vec()).unwrap();

        assert_eq!(
            root_child_prefixes(&m.root),
            vec![vec![0x1a], b"m".to_vec(), vec![0x83]]
        );
        let mut items = m.iteritems(None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"1"]), b"foo".to_vec()),
                (key_vec(&[b"2"]), b"bar".to_vec()),
                (key_vec(&[b"3"]), b"baz".to_vec()),
            ]
        );
    }

    #[test]
    fn internal_node_serialise_writes_children_then_self() {
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let mut leaf_b = LeafNode::new(SearchKeyFunc::Plain);
        leaf_b.map_no_split(key_vec(&[b"b"]), b"vb".to_vec());
        let mut internal = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        internal
            .add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        internal
            .add_node(b"b".to_vec(), Node::Leaf(Box::new(leaf_b)))
            .unwrap();
        let written = internal.serialise(&store, &cache).unwrap();
        // Two children + self = 3 keys.
        assert_eq!(written.len(), 3);
        // The self key matches what's stored on the InternalNode.
        assert_eq!(
            internal.key.as_deref(),
            Some(written.last().unwrap().as_slice())
        );
        // All written keys should be present in the page cache.
        for k in &written {
            assert!(cache.get(k).is_some(), "missing {:?}", k);
        }
    }

    #[test]
    fn internal_node_serialise_skips_already_serialised_children() {
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let _child_key = leaf_a.serialise(&store, &cache).unwrap();
        let mut internal = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        internal
            .add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        let written = internal.serialise(&store, &cache).unwrap();
        // Child already serialised, so only self is in the written list.
        assert_eq!(written.len(), 1);
        assert!(written[0].starts_with(b"sha1:"));
    }

    #[test]
    fn node_unmap_with_store_removes_from_leaf() {
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf = LeafNode::new(SearchKeyFunc::Plain);
        leaf.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        leaf.map_no_split(key_vec(&[b"b"]), b"vb".to_vec());
        let node = Node::Leaf(Box::new(leaf));
        let new_node = node
            .unmap_with_store(&store, &cache, &key_vec(&[b"a"]), true)
            .unwrap();
        assert_eq!(new_node.len(), 1);
    }

    #[test]
    fn node_unmap_with_store_collapses_internal_to_only_child() {
        // Build an internal with two leaves; remove one — internal
        // should collapse to the remaining leaf.
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let mut leaf_b = LeafNode::new(SearchKeyFunc::Plain);
        leaf_b.map_no_split(key_vec(&[b"b"]), b"vb".to_vec());
        let mut internal = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        internal
            .add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        internal
            .add_node(b"b".to_vec(), Node::Leaf(Box::new(leaf_b)))
            .unwrap();
        let node = Node::Internal(Box::new(internal));
        let new_node = node
            .unmap_with_store(&store, &cache, &key_vec(&[b"a"]), true)
            .unwrap();
        // After removing the "a" leaf, only "b" remains — the
        // internal node collapses to the bare leaf.
        match &new_node {
            Node::Leaf(l) => {
                assert_eq!(l.len(), 1);
                assert!(l.items.contains_key(&key_vec(&[b"b"])));
            }
            Node::Internal(_) => panic!("expected collapse to leaf"),
        }
    }

    #[test]
    fn node_unmap_with_store_raises_for_missing_key() {
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf = LeafNode::new(SearchKeyFunc::Plain);
        leaf.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let node = Node::Leaf(Box::new(leaf));
        let err = node
            .unmap_with_store(&store, &cache, &key_vec(&[b"absent"]), true)
            .unwrap_err();
        assert!(matches!(err, Error::AssertionFailed(_)));
    }

    #[test]
    fn node_map_with_store_descends_into_internal_child() {
        // Build an InternalNode with two leaf children that have
        // distinct first-byte search keys; insert a new entry that
        // belongs in one of them.
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"alpha"]), b"va".to_vec());
        let mut leaf_b = LeafNode::new(SearchKeyFunc::Plain);
        leaf_b.map_no_split(key_vec(&[b"beta"]), b"vb".to_vec());
        let mut internal = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        internal
            .add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        internal
            .add_node(b"b".to_vec(), Node::Leaf(Box::new(leaf_b)))
            .unwrap();
        let mut node = Node::Internal(Box::new(internal));
        let r = node
            .map_with_store(&store, &cache, key_vec(&[b"apple"]), b"vap".to_vec())
            .unwrap();
        assert!(matches!(r, MapResult::InPlace { .. }));
        // The leaf under "a" should now have two entries.
        let mut all_items = node.iteritems(&store, &cache, None).unwrap();
        all_items.sort();
        assert_eq!(
            all_items,
            vec![
                (key_vec(&[b"alpha"]), b"va".to_vec()),
                (key_vec(&[b"apple"]), b"vap".to_vec()),
                (key_vec(&[b"beta"]), b"vb".to_vec()),
            ]
        );
        assert_eq!(node.len(), 3);
    }

    #[test]
    fn node_map_with_store_creates_new_child_if_no_match() {
        // Insert into a slot that doesn't have a child yet.
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let mut internal = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        internal
            .add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        let mut node = Node::Internal(Box::new(internal));
        let r = node
            .map_with_store(&store, &cache, key_vec(&[b"b"]), b"vb".to_vec())
            .unwrap();
        assert!(matches!(r, MapResult::InPlace { .. }));
        let mut items = node.iteritems(&store, &cache, None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"a"]), b"va".to_vec()),
                (key_vec(&[b"b"]), b"vb".to_vec()),
            ]
        );
    }

    #[test]
    fn leaf_node_map_in_place_no_split() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        let r = n.map(key_vec(&[b"foo"]), b"bar".to_vec()).unwrap();
        match r {
            MapResult::InPlace { search_prefix } => {
                assert_eq!(search_prefix, b"foo".to_vec());
            }
            MapResult::Split { .. } => panic!("did not expect split"),
        }
        assert_eq!(n.len(), 1);
    }

    #[test]
    fn leaf_node_map_replacing_existing_key_does_not_grow_len() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map(key_vec(&[b"foo"]), b"bar".to_vec()).unwrap();
        let r = n.map(key_vec(&[b"foo"]), b"BAZ".to_vec()).unwrap();
        assert!(matches!(r, MapResult::InPlace { .. }));
        assert_eq!(n.len(), 1);
        assert_eq!(n.items.get(&key_vec(&[b"foo"])), Some(&b"BAZ".to_vec()));
    }

    #[test]
    fn leaf_node_map_overflow_splits_into_internal_subtree() {
        // Two divergent keys with a tight maximum_size force a split.
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.maximum_size = 10;
        let r1 = n.map(key_vec(&[b"foo"]), b"v1".to_vec()).unwrap();
        assert!(matches!(r1, MapResult::InPlace { .. }));
        let r2 = n.map(key_vec(&[b"bar"]), b"v2".to_vec()).unwrap();
        match r2 {
            MapResult::Split {
                common_serialised_prefix,
                children,
            } => {
                // Search prefix of two divergent single-byte-prefix
                // keys is empty.
                assert!(common_serialised_prefix.is_empty());
                // Two sub-children for the split.
                assert_eq!(children.len(), 2);
                let prefixes: Vec<&[u8]> = children.iter().map(|(p, _)| p.as_slice()).collect();
                assert!(prefixes.contains(&&b"f"[..]));
                assert!(prefixes.contains(&&b"b"[..]));
            }
            MapResult::InPlace { .. } => panic!("expected split"),
        }
    }

    #[test]
    fn node_iteritems_recurses_into_internal_children() {
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        // Two leaves each with one entry, serialised into the store.
        let mut la = LeafNode::new(SearchKeyFunc::Plain);
        la.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let mut lb = LeafNode::new(SearchKeyFunc::Plain);
        lb.map_no_split(key_vec(&[b"b"]), b"vb".to_vec());
        let key_a = la.serialise(&store, &cache).unwrap();
        let key_b = lb.serialise(&store, &cache).unwrap();
        // Parent internal node referencing both as unloaded.
        let mut internal = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        internal.node_width = 1;
        internal
            .items
            .insert(b"a".to_vec(), NodeRef::Unloaded(key_a));
        internal
            .items
            .insert(b"b".to_vec(), NodeRef::Unloaded(key_b));
        internal.len = 2;
        let mut node = Node::Internal(Box::new(internal));
        let mut items = node.iteritems(&store, &cache, None).unwrap();
        items.sort();
        assert_eq!(
            items,
            vec![
                (key_vec(&[b"a"]), b"va".to_vec()),
                (key_vec(&[b"b"]), b"vb".to_vec()),
            ]
        );
    }

    #[test]
    fn node_iteritems_with_filter_only_yields_matching_keys() {
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut la = LeafNode::new(SearchKeyFunc::Plain);
        la.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let mut lb = LeafNode::new(SearchKeyFunc::Plain);
        lb.map_no_split(key_vec(&[b"b"]), b"vb".to_vec());
        let key_a = la.serialise(&store, &cache).unwrap();
        let key_b = lb.serialise(&store, &cache).unwrap();
        let mut internal = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        internal.node_width = 1;
        internal
            .items
            .insert(b"a".to_vec(), NodeRef::Unloaded(key_a));
        internal
            .items
            .insert(b"b".to_vec(), NodeRef::Unloaded(key_b));
        internal.len = 2;
        let mut node = Node::Internal(Box::new(internal));
        let items = node
            .iteritems(&store, &cache, Some(&[key_vec(&[b"a"])]))
            .unwrap();
        assert_eq!(items, vec![(key_vec(&[b"a"]), b"va".to_vec())]);
    }

    #[test]
    fn internal_node_iter_nodes_returns_loaded_children_in_order() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 1;
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let mut leaf_b = LeafNode::new(SearchKeyFunc::Plain);
        leaf_b.map_no_split(key_vec(&[b"b"]), b"vb".to_vec());
        n.add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        n.add_node(b"b".to_vec(), Node::Leaf(Box::new(leaf_b)))
            .unwrap();
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let yielded = n.iter_nodes(&store, &cache, None, None).unwrap();
        assert_eq!(yielded.len(), 2);
        // Filter is None for everything when no key_filter is given.
        assert!(yielded.iter().all(|(_, f)| f.is_none()));
        let lens: Vec<usize> = yielded.iter().map(|(n, _)| n.len()).collect();
        assert_eq!(lens, vec![1, 1]);
    }

    #[test]
    fn internal_node_iter_nodes_demand_loads_via_store() {
        // Serialise a leaf into the store first.
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf = LeafNode::new(SearchKeyFunc::Plain);
        leaf.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let child_key = leaf.serialise(&store, &cache).unwrap();

        // Build an InternalNode pointing at the unloaded child.
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 1;
        n.items
            .insert(b"a".to_vec(), NodeRef::Unloaded(child_key.clone()));
        n.len = 1;

        // Drop the cache to force a store read.
        cache.clear();

        let yielded = n.iter_nodes(&store, &cache, None, None).unwrap();
        assert_eq!(yielded.len(), 1);
        assert_eq!(yielded[0].0.len(), 1);
        // After loading, the items entry should be Loaded.
        match n.items.get(&b"a".to_vec()) {
            Some(NodeRef::Loaded(_)) => {}
            other => panic!("expected Loaded after iter_nodes, got {:?}", other),
        }
        // The page cache should now hold the bytes.
        assert!(cache.get(&child_key).is_some());
    }

    #[test]
    fn internal_node_iter_nodes_single_key_filter_dict_lookup() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 1;
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let mut leaf_b = LeafNode::new(SearchKeyFunc::Plain);
        leaf_b.map_no_split(key_vec(&[b"b"]), b"vb".to_vec());
        n.add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        n.add_node(b"b".to_vec(), Node::Leaf(Box::new(leaf_b)))
            .unwrap();
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let filter = [key_vec(&[b"a"])];
        let yielded = n.iter_nodes(&store, &cache, Some(&filter), None).unwrap();
        assert_eq!(yielded.len(), 1);
        assert_eq!(yielded[0].1.as_deref(), Some(&[key_vec(&[b"a"])][..]));
    }

    #[test]
    fn internal_node_iter_nodes_single_key_miss_yields_nothing() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 1;
        let mut leaf_a = LeafNode::new(SearchKeyFunc::Plain);
        leaf_a.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        n.add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf_a)))
            .unwrap();
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let filter = [key_vec(&[b"z"])];
        let yielded = n.iter_nodes(&store, &cache, Some(&filter), None).unwrap();
        assert!(yielded.is_empty());
    }

    #[test]
    fn internal_node_iter_nodes_hits_cache_before_store() {
        // First serialise leaf into store + cache.
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let mut leaf = LeafNode::new(SearchKeyFunc::Plain);
        leaf.map_no_split(key_vec(&[b"a"]), b"va".to_vec());
        let child_key = leaf.serialise(&store, &cache).unwrap();

        // Build an InternalNode pointing at the unloaded child.
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 1;
        n.items
            .insert(b"a".to_vec(), NodeRef::Unloaded(child_key.clone()));
        n.len = 1;

        // Now corrupt the store; if iter_nodes hits the store we'll
        // get back garbage. The cache hit should bypass the store.
        store
            .pages
            .lock()
            .unwrap()
            .insert(child_key[5..].to_vec(), b"corrupt".to_vec());

        let yielded = n.iter_nodes(&store, &cache, None, None).unwrap();
        assert_eq!(yielded.len(), 1);
        assert_eq!(yielded[0].0.len(), 1);
    }

    #[test]
    fn leaf_node_serialise_caches_and_sets_key() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map_no_split(key_vec(&[b"foo"]), b"bar".to_vec());
        let store = FakeChkStore::new();
        let cache = InMemoryPageCache::new();
        let sha1_key = n.serialise(&store, &cache).unwrap();
        assert!(sha1_key.starts_with(b"sha1:"));
        assert_eq!(n.key.as_deref(), Some(sha1_key.as_slice()));
        // Page cache holds the serialised bytes.
        let cached = cache.get(&sha1_key).expect("page cache miss");
        assert!(cached.starts_with(b"chkleaf:\n"));
        // Round-trip through deserialise.
        let node = deserialise_node(&cached, sha1_key, SearchKeyFunc::Plain).unwrap();
        match node {
            Node::Leaf(leaf) => {
                assert_eq!(leaf.len(), 1);
                assert_eq!(leaf.items.get(&key_vec(&[b"foo"])), Some(&b"bar".to_vec()));
            }
            Node::Internal(_) => panic!("expected leaf"),
        }
    }

    #[test]
    fn in_memory_page_cache_roundtrips() {
        let c = InMemoryPageCache::new();
        assert_eq!(c.get(b"sha1:absent"), None);
        c.insert(b"sha1:x".to_vec(), b"page-bytes".to_vec());
        assert_eq!(c.get(b"sha1:x").as_deref(), Some(&b"page-bytes"[..]));
    }

    #[test]
    fn in_memory_page_cache_clear_drops_all_entries() {
        let c = InMemoryPageCache::new();
        c.insert(b"sha1:x".to_vec(), b"v1".to_vec());
        c.insert(b"sha1:y".to_vec(), b"v2".to_vec());
        c.clear();
        assert_eq!(c.get(b"sha1:x"), None);
        assert_eq!(c.get(b"sha1:y"), None);
    }

    #[test]
    fn in_memory_page_cache_evicts_when_full() {
        let c = InMemoryPageCache::with_capacity(2);
        c.insert(b"k1".to_vec(), b"v1".to_vec());
        c.insert(b"k2".to_vec(), b"v2".to_vec());
        c.insert(b"k3".to_vec(), b"v3".to_vec()); // evicts k1
        assert_eq!(c.get(b"k1"), None);
        assert_eq!(c.get(b"k2").as_deref(), Some(&b"v2"[..]));
        assert_eq!(c.get(b"k3").as_deref(), Some(&b"v3"[..]));
    }

    #[test]
    fn deserialise_node_dispatches_to_leaf() {
        let blob: &[u8] = b"chkleaf:\n100\n1\n2\nalph\n2\x002\nv2\nv2line2\na\x001\nv1\n";
        let node = deserialise_node(blob, b"sha1:abcd".to_vec(), SearchKeyFunc::Plain).unwrap();
        match node {
            Node::Leaf(leaf) => {
                assert_eq!(leaf.key.as_deref(), Some(&b"sha1:abcd"[..]));
                assert_eq!(leaf.len(), 2);
            }
            Node::Internal(_) => panic!("expected leaf"),
        }
    }

    #[test]
    fn deserialise_node_dispatches_to_internal() {
        let blob: &[u8] = b"chknode:\n200\n1\n2\npre\nbar\x00sha1:bbbb\nfoo\x00sha1:aaaa\n";
        let node = deserialise_node(blob, b"sha1:root".to_vec(), SearchKeyFunc::Plain).unwrap();
        match node {
            Node::Internal(internal) => {
                assert_eq!(internal.key.as_deref(), Some(&b"sha1:root"[..]));
                assert_eq!(internal.len, 2);
            }
            Node::Leaf(_) => panic!("expected internal"),
        }
    }

    #[test]
    fn deserialise_node_rejects_unknown_magic() {
        let blob: &[u8] = b"unknown:\n";
        let err = deserialise_node(blob, b"sha1:x".to_vec(), SearchKeyFunc::Plain).unwrap_err();
        assert!(matches!(err, Error::AssertionFailed(_)));
    }

    #[test]
    fn internal_node_add_node_validates_prefix_length() {
        let mut n = InternalNode::new(b"pre".to_vec(), SearchKeyFunc::Plain);
        let leaf = Node::Leaf(Box::new(LeafNode::new(SearchKeyFunc::Plain)));
        // Prefix too long.
        let too_long = n.add_node(b"preXY".to_vec(), leaf.clone());
        assert!(matches!(too_long, Err(Error::AssertionFailed(_))));
        // Prefix not starting with search_prefix.
        let mismatch = n.add_node(b"qrZ".to_vec(), leaf.clone());
        assert!(matches!(mismatch, Err(Error::AssertionFailed(_))));
        // Correct: search_prefix + 1 byte.
        n.add_node(b"preX".to_vec(), leaf).unwrap();
        assert_eq!(n.items.len(), 1);
        assert_eq!(n.node_width, 4);
    }

    #[test]
    fn internal_node_add_node_clears_key_and_grows_len() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.key = Some(b"sha1:old".to_vec());
        let mut leaf = LeafNode::new(SearchKeyFunc::Plain);
        leaf.map_no_split(key_vec(&[b"k1"]), b"v1".to_vec());
        leaf.map_no_split(key_vec(&[b"k2"]), b"v2".to_vec());
        n.add_node(b"a".to_vec(), Node::Leaf(Box::new(leaf)))
            .unwrap();
        assert_eq!(n.len, 2);
        assert!(n.key.is_none());
    }

    #[test]
    fn internal_node_search_key_pads_with_nul() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 5;
        // Plain search key of `("k",)` is `b"k"`, length 1; pad to 5.
        assert_eq!(n.search_key(&Key::from(vec![b"k".to_vec()])), b"k\0\0\0\0");
    }

    #[test]
    fn internal_node_search_key_truncates_when_longer() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 3;
        assert_eq!(n.search_key(&Key::from(vec![b"longkey".to_vec()])), b"lon");
    }

    #[test]
    fn internal_node_search_prefix_filter_does_not_pad() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 5;
        // Shorter key returns as-is (no padding).
        assert_eq!(
            n.search_prefix_filter(&Key::from(vec![b"k".to_vec()])),
            b"k"
        );
        // Longer key gets truncated.
        n.node_width = 3;
        assert_eq!(
            n.search_prefix_filter(&Key::from(vec![b"longkey".to_vec()])),
            b"lon"
        );
    }

    #[test]
    fn internal_node_compute_search_prefix_from_children() {
        let mut n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        n.items
            .insert(b"abc".to_vec(), NodeRef::Unloaded(b"sha1:x".to_vec()));
        n.items
            .insert(b"abd".to_vec(), NodeRef::Unloaded(b"sha1:y".to_vec()));
        n.items
            .insert(b"abe".to_vec(), NodeRef::Unloaded(b"sha1:z".to_vec()));
        let prefix = n.compute_search_prefix().map(<[u8]>::to_vec);
        assert_eq!(prefix, Some(b"ab".to_vec()));
        assert_eq!(n.search_prefix.as_deref(), Some(&b"ab"[..]));
    }

    #[test]
    fn internal_node_refs_returns_child_keys() {
        let mut n = InternalNode::new(b"p".to_vec(), SearchKeyFunc::Plain);
        n.node_width = 2;
        n.items
            .insert(b"pa".to_vec(), NodeRef::Unloaded(b"sha1:a".to_vec()));
        let mut leaf = LeafNode::new(SearchKeyFunc::Plain);
        leaf.key = Some(b"sha1:b".to_vec());
        n.items
            .insert(b"pb".to_vec(), NodeRef::Loaded(Node::Leaf(Box::new(leaf))));
        n.key = Some(b"sha1:self".to_vec());
        let refs = n.refs().unwrap();
        assert_eq!(refs.len(), 2);
        assert!(refs.contains(&b"sha1:a".to_vec()));
        assert!(refs.contains(&b"sha1:b".to_vec()));
    }

    #[test]
    fn internal_node_refs_errors_when_unserialised() {
        let n = InternalNode::new(b"".to_vec(), SearchKeyFunc::Plain);
        assert!(matches!(n.refs(), Err(Error::AssertionFailed(_))));
    }

    #[test]
    fn node_wraps_leaf_and_internal() {
        let leaf = Node::Leaf(Box::new(LeafNode::new(SearchKeyFunc::Plain)));
        let internal = Node::Internal(Box::new(InternalNode::new(
            b"".to_vec(),
            SearchKeyFunc::Plain,
        )));
        assert_eq!(leaf.len(), 0);
        assert_eq!(internal.len(), 0);
        assert_eq!(leaf.maximum_size(), 0);
        assert_eq!(internal.maximum_size(), 0);
        assert_eq!(leaf.key(), None);
        assert_eq!(internal.key(), None);
    }

    #[test]
    fn node_len_reflects_inner_state() {
        let mut leaf = LeafNode::new(SearchKeyFunc::Plain);
        leaf.map_no_split(key_vec(&[b"foo"]), b"bar".to_vec());
        leaf.map_no_split(key_vec(&[b"baz"]), b"qux".to_vec());
        let node = Node::Leaf(Box::new(leaf));
        assert_eq!(node.len(), 2);
    }

    #[test]
    fn leaf_node_iteritems_returns_all_with_no_filter() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map_no_split(key_vec(&[b"foo"]), b"bar".to_vec());
        n.map_no_split(key_vec(&[b"baz"]), b"qux".to_vec());
        let items = n.iteritems(None);
        assert_eq!(items.len(), 2);
        let keys: Vec<&[Vec<u8>]> = items.iter().map(|(k, _)| k.as_slice()).collect();
        assert!(keys.contains(&key_vec(&[b"foo"]).as_slice()));
        assert!(keys.contains(&key_vec(&[b"baz"]).as_slice()));
    }

    #[test]
    fn leaf_node_iteritems_exact_match_filter() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map_no_split(key_vec(&[b"foo"]), b"bar".to_vec());
        n.map_no_split(key_vec(&[b"baz"]), b"qux".to_vec());
        let items = n.iteritems(Some(&[key_vec(&[b"foo"])]));
        assert_eq!(items, vec![(key_vec(&[b"foo"]), b"bar".to_vec())]);
    }

    #[test]
    fn leaf_node_iteritems_exact_miss_yields_nothing() {
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.map_no_split(key_vec(&[b"foo"]), b"bar".to_vec());
        let items = n.iteritems(Some(&[key_vec(&[b"absent"])]));
        assert!(items.is_empty());
    }

    #[test]
    fn leaf_node_iteritems_short_prefix_filter_matches_items() {
        // key_width=2, filter is a 1-element prefix that matches the
        // first element of one stored key.
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.key_width = 2;
        n.map_no_split(key_vec(&[b"foo", b"sub1"]), b"v1".to_vec());
        n.map_no_split(key_vec(&[b"bar", b"sub2"]), b"v2".to_vec());
        let items = n.iteritems(Some(&[key_vec(&[b"foo"])]));
        assert_eq!(items, vec![(key_vec(&[b"foo", b"sub1"]), b"v1".to_vec())]);
    }

    #[test]
    fn leaf_node_iteritems_mixed_filter_lengths() {
        // key_width=2, mix of exact (length 2) and prefix (length 1).
        let mut n = LeafNode::new(SearchKeyFunc::Plain);
        n.key_width = 2;
        n.map_no_split(key_vec(&[b"foo", b"sub"]), b"v1".to_vec());
        n.map_no_split(key_vec(&[b"bar", b"sub"]), b"v2".to_vec());
        n.map_no_split(key_vec(&[b"baz", b"sub"]), b"v3".to_vec());
        let items = n.iteritems(Some(&[
            key_vec(&[b"foo", b"sub"]), // exact, yielded first
            key_vec(&[b"bar"]),         // prefix
        ]));
        // Exact match first, then prefix match in items order.
        assert_eq!(items.len(), 2);
        assert_eq!(items[0], (key_vec(&[b"foo", b"sub"]), b"v1".to_vec()));
        assert_eq!(items[1], (key_vec(&[b"bar", b"sub"]), b"v2".to_vec()));
    }

    #[test]
    fn search_key_func_from_name_resolves_known_variants() {
        assert_eq!(
            SearchKeyFunc::from_name(b"plain").unwrap(),
            SearchKeyFunc::Plain
        );
        assert_eq!(
            SearchKeyFunc::from_name(b"hash-16-way").unwrap(),
            SearchKeyFunc::Hash16Way
        );
        assert_eq!(
            SearchKeyFunc::from_name(b"hash-255-way").unwrap(),
            SearchKeyFunc::Hash255Way
        );
    }

    #[test]
    fn search_key_func_from_name_returns_unknown_bytes() {
        let err = SearchKeyFunc::from_name(b"unrecognised").unwrap_err();
        assert_eq!(err, b"unrecognised".to_vec());
    }

    #[test]
    fn search_key_func_name_roundtrips() {
        for variant in [
            SearchKeyFunc::Plain,
            SearchKeyFunc::Hash16Way,
            SearchKeyFunc::Hash255Way,
        ] {
            let parsed = SearchKeyFunc::from_name(variant.name()).unwrap();
            assert_eq!(parsed, variant);
        }
    }

    #[test]
    fn search_key_func_apply_matches_free_functions() {
        let k = key(&[b"foo", b"bar"]);
        assert_eq!(SearchKeyFunc::Plain.apply(&k), search_key_plain(&k));
        assert_eq!(SearchKeyFunc::Hash16Way.apply(&k), search_key_16(&k));
        assert_eq!(SearchKeyFunc::Hash255Way.apply(&k), search_key_255(&k));
    }

    #[test]
    fn search_key_func_default_is_plain() {
        assert_eq!(SearchKeyFunc::default(), SearchKeyFunc::Plain);
    }

    #[test]
    fn are_search_keys_identical_returns_true_for_empty() {
        let empty: [&[u8]; 0] = [];
        assert!(are_search_keys_identical(empty));
    }

    #[test]
    fn are_search_keys_identical_returns_true_for_single() {
        assert!(are_search_keys_identical([b"hash".as_slice()]));
    }

    #[test]
    fn are_search_keys_identical_returns_true_when_all_match() {
        assert!(are_search_keys_identical([
            b"same".as_slice(),
            b"same",
            b"same"
        ]));
    }

    #[test]
    fn are_search_keys_identical_returns_false_when_one_differs() {
        assert!(!are_search_keys_identical([
            b"same".as_slice(),
            b"same",
            b"other"
        ]));
        assert!(!are_search_keys_identical([b"first".as_slice(), b"second"]));
    }

    #[test]
    fn serialise_internal_node_roundtrips_through_deserialise() {
        let items = vec![
            InternalNodeChild {
                prefix: b"prebar".to_vec(),
                flat_key: b"sha1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_vec(),
            },
            InternalNodeChild {
                prefix: b"prefoo".to_vec(),
                flat_key: b"sha1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_vec(),
            },
        ];
        // The fixture's `length=2` happens to match items.len() because
        // those two children are themselves leaves; for deeper trees
        // length is the total leaf count, which the caller passes in.
        let out = serialise_internal_node(200, 1, 2, b"pre", &items).unwrap();
        let blob: Vec<u8> = out.iter().flatten().copied().collect();
        assert_eq!(blob, INTERNAL_FIXTURE);
    }
}