triblespace-core 0.47.1

The triblespace core implementation.
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
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
//! Persistent Adaptive Trie with Cuckoo-compression and
//! Hash-maintenance (PATCH).
//!
//! See the [PATCH](../book/src/deep-dive/patch.md) chapter of the Tribles Book
//! for the full design description and hashing scheme.
//!
//! Values stored in leaves are not part of hashing or equality comparisons.
//! Two [`PATCH`](crate::patch::PATCH)es are considered equal if they contain the same set of keys,
//! even if the associated values differ. This allows using the structure as an
//! idempotent blobstore where a value's hash determines its key.
//!
#![allow(unstable_name_collisions)]

mod branch;
/// Byte-indexed lookup tables used by PATCH branch nodes.
pub mod bytetable;
mod entry;
mod leaf;

use arrayvec::ArrayVec;

/// Re-export of [`Entry`](entry::Entry).
use branch::*;
pub use entry::{ArchiveEntry, Entry};
use leaf::*;

/// Re-export of all byte table utilities.
pub use bytetable::*;
use rand::thread_rng;
use rand::RngCore;
use std::cmp::{Ordering, Reverse};
use std::convert::TryInto;
use std::fmt;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::sync::{Arc, OnceLock};

/// Marker trait for opaque owners of bytes referenced by archive-backed
/// PATCH leaves. An owner exists solely to keep its allocation alive while a
/// [`HeadTag::LocalLeaf`] points into it.
pub trait ArchiveOwner: Send + Sync + 'static {}

impl<T: Send + Sync + 'static + ?Sized> ArchiveOwner for T {}

/// One node in the exact persistent set of retained archive allocations.
///
/// Owners are stored inline in their parent (or directly in [`OwnerCover`]);
/// only branches allocate an [`Arc`]. This is a binary Patricia trie over
/// owner allocation addresses. Masks strictly decrease on each root-to-leaf
/// path, so the shape is canonical for an address set and its height is at
/// most [`usize::BITS`]. Rebuilt paths share every untouched branch Arc with
/// older PATCH snapshots.
#[derive(Clone)]
enum OwnerNode {
    Owner(Arc<dyn ArchiveOwner>),
    Branch(Arc<OwnerBranch>),
}

struct OwnerBranch {
    mask: usize,
    zero: OwnerNode,
    one: OwnerNode,
}

/// Exact persistent set of archive allocations retained by one PATCH.
///
/// Membership is keyed by an allocation's data address. Each address remains
/// unavailable for reuse while its owner leaf is present. `latest_address`
/// keeps repeated archive ingestion O(1) without weakening exact membership
/// for older owners or repeated diamond unions.
#[derive(Clone)]
struct OwnerCover {
    latest_address: usize,
    len: usize,
    root: OwnerNode,
}

impl core::fmt::Debug for OwnerCover {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("OwnerCover")
            .field("len", &self.len)
            .finish()
    }
}

impl OwnerNode {
    #[inline]
    fn takes_one(address: usize, mask: usize) -> bool {
        address & mask != 0
    }

    #[inline]
    fn critical_mask(left: usize, right: usize) -> usize {
        let differing = left ^ right;
        debug_assert_ne!(differing, 0);
        1usize << (usize::BITS - 1 - differing.leading_zeros())
    }

    fn matching_owner(&self, address: usize) -> &Arc<dyn ArchiveOwner> {
        let mut node = self;
        loop {
            match node {
                Self::Owner(owner) => return owner,
                Self::Branch(branch) => {
                    node = if Self::takes_one(address, branch.mask) {
                        &branch.one
                    } else {
                        &branch.zero
                    };
                }
            }
        }
    }

    #[cfg(any(debug_assertions, test))]
    fn contains(&self, address: usize) -> bool {
        OwnerCover::address(self.matching_owner(address)) == address
    }

    #[cfg(test)]
    fn same_shape(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Owner(left), Self::Owner(right)) => {
                OwnerCover::address(left) == OwnerCover::address(right)
            }
            (Self::Branch(left), Self::Branch(right)) => {
                left.mask == right.mask
                    && left.zero.same_shape(&right.zero)
                    && left.one.same_shape(&right.one)
            }
            _ => false,
        }
    }

    /// Persistently insert one owner, returning the unchanged root on a hit.
    fn insert(&self, owner: &Arc<dyn ArchiveOwner>) -> (Self, bool) {
        let address = OwnerCover::address(owner);
        let matching = self.matching_owner(address);
        let existing_address = OwnerCover::address(matching);
        if existing_address == address {
            debug_assert!(Arc::ptr_eq(matching, owner));
            return (self.clone(), false);
        }

        let critical_mask = Self::critical_mask(address, existing_address);
        (
            Self::insert_at(
                self,
                Self::Owner(owner.clone()),
                address,
                existing_address,
                critical_mask,
            ),
            true,
        )
    }

    fn insert_at(
        root: &Self,
        inserted: Self,
        inserted_address: usize,
        existing_address: usize,
        critical_mask: usize,
    ) -> Self {
        if let Self::Branch(branch) = root {
            if branch.mask > critical_mask {
                if Self::takes_one(inserted_address, branch.mask) {
                    return Self::Branch(Arc::new(OwnerBranch {
                        mask: branch.mask,
                        zero: branch.zero.clone(),
                        one: Self::insert_at(
                            &branch.one,
                            inserted,
                            inserted_address,
                            existing_address,
                            critical_mask,
                        ),
                    }));
                }
                return Self::Branch(Arc::new(OwnerBranch {
                    mask: branch.mask,
                    zero: Self::insert_at(
                        &branch.zero,
                        inserted,
                        inserted_address,
                        existing_address,
                        critical_mask,
                    ),
                    one: branch.one.clone(),
                }));
            }
            debug_assert_ne!(branch.mask, critical_mask);
        }

        debug_assert_ne!(
            Self::takes_one(inserted_address, critical_mask),
            Self::takes_one(existing_address, critical_mask),
        );
        let (zero, one) = if Self::takes_one(inserted_address, critical_mask) {
            (root.clone(), inserted)
        } else {
            (inserted, root.clone())
        };
        Self::Branch(Arc::new(OwnerBranch {
            mask: critical_mask,
            zero,
            one,
        }))
    }

    fn for_each_owner<F>(&self, f: &mut F)
    where
        F: FnMut(&Arc<dyn ArchiveOwner>),
    {
        match self {
            Self::Owner(owner) => f(owner),
            Self::Branch(branch) => {
                branch.zero.for_each_owner(f);
                branch.one.for_each_owner(f);
            }
        }
    }
}

impl OwnerCover {
    #[inline]
    fn address(owner: &Arc<dyn ArchiveOwner>) -> usize {
        Arc::as_ptr(owner) as *const () as usize
    }

    fn singleton(owner: &Arc<dyn ArchiveOwner>) -> Arc<Self> {
        Arc::new(Self {
            latest_address: Self::address(owner),
            len: 1,
            root: OwnerNode::Owner(owner.clone()),
        })
    }

    fn retain(current: &mut Option<Arc<Self>>, owner: &Arc<dyn ArchiveOwner>) {
        let address = Self::address(owner);
        let Some(existing) = current.as_mut() else {
            *current = Some(Self::singleton(owner));
            return;
        };
        if existing.latest_address == address {
            return;
        }

        // Finish the persistent path before publishing it. A caught allocation
        // panic therefore leaves the installed lifetime receipt unchanged.
        let (root, inserted) = existing.root.insert(owner);
        let cover = Arc::make_mut(existing);
        cover.root = root;
        cover.len += usize::from(inserted);
        cover.latest_address = address;
    }

    /// Transactionally replace `current` with its exact union with `other`.
    fn merge_into(current: &mut Option<Arc<Self>>, other: &Option<Arc<Self>>) {
        *current = Self::union(current.clone(), other);
    }

    fn union(left: Option<Arc<Self>>, right: &Option<Arc<Self>>) -> Option<Arc<Self>> {
        let Some(right) = right.as_ref() else {
            return left;
        };
        let Some(left) = left else {
            return Some(right.clone());
        };
        if Arc::ptr_eq(&left, right) {
            return Some(left);
        }

        // Insert the smaller exact set into the larger. The canonical Patricia
        // shape makes the result independent of this directional choice.
        let (mut result, additions) = if left.len >= right.len {
            (left.clone(), right)
        } else {
            (right.clone(), &left)
        };
        additions.root.for_each_owner(&mut |owner| {
            let (root, inserted) = result.root.insert(owner);
            if inserted {
                let cover = Arc::make_mut(&mut result);
                cover.root = root;
                cover.len += 1;
            }
        });
        if result.latest_address != right.latest_address {
            Arc::make_mut(&mut result).latest_address = right.latest_address;
        }
        Some(result)
    }

    /// Exact subset check for auditing unsafe cover replacement in debug
    /// builds. Production callers rely on the construction proof documented
    /// at [`PATCH::set_owner_guard`].
    #[cfg(debug_assertions)]
    fn covers(&self, covered: &Self) -> bool {
        if self.len < covered.len {
            return false;
        }
        let mut covers = true;
        covered.root.for_each_owner(&mut |owner| {
            covers &= self.root.contains(Self::address(owner));
        });
        covers
    }
}

// Keep the intended structural cost visible. Owner leaves live inline; only
// Patricia branches and the outer cover allocate.
#[cfg(target_pointer_width = "64")]
const _: () = {
    assert!(std::mem::size_of::<OwnerNode>() == 2 * std::mem::size_of::<usize>());
    assert!(std::mem::size_of::<OwnerBranch>() == 5 * std::mem::size_of::<usize>());
    assert!(std::mem::size_of::<OwnerCover>() == 4 * std::mem::size_of::<usize>());
};

/// Opaque lifetime receipt for archive-backed PATCH leaves.
///
/// Aggregate structures can exactly deduplicate retained provenance, add one
/// archive owner, and install a proved conservative superset. Trie Heads and
/// concrete Patricia nodes remain private to PATCH.
#[derive(Clone, Debug, Default)]
pub(crate) struct PATCHOwnerGuard(Option<Arc<OwnerCover>>);

impl PATCHOwnerGuard {
    /// Retain the exact deduplicated union of owners in both receipts.
    pub(crate) fn join(self, other: Self) -> Self {
        Self(OwnerCover::union(self.0, &other.0))
    }

    /// Add one archive allocation before any LocalLeaf into it is installed.
    pub(crate) fn retain_archive_owner(&mut self, owner: &Arc<dyn ArchiveOwner>) {
        OwnerCover::retain(&mut self.0, owner);
    }

    #[cfg(debug_assertions)]
    fn covers(&self, current: &Option<Arc<OwnerCover>>) -> bool {
        let Some(current) = current else {
            return true;
        };
        let Some(replacement) = self.0.as_ref() else {
            return false;
        };
        Arc::ptr_eq(current, replacement) || replacement.covers(current)
    }

    #[cfg(test)]
    pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (None, None) => true,
            (Some(left), Some(right)) => Arc::ptr_eq(left, right),
            _ => false,
        }
    }

    #[cfg(test)]
    pub(crate) fn owner_count(&self) -> usize {
        self.0.as_ref().map_or(0, |cover| cover.len)
    }
}

#[cfg(not(target_pointer_width = "64"))]
compile_error!("PATCH tagged pointers require 64-bit targets");

struct HashKeys {
    leaf: [u8; 16],
    exported_fingerprint: [u8; 16],
}

static HASH_KEYS: OnceLock<HashKeys> = OnceLock::new();

mod sealed {
    pub trait Sealed {}
}

/// Hash-maintenance policy used by [`PATCH`].
///
/// Implementations are sealed because PATCH treats equal subtree summaries as
/// equal key sets in `Eq`, union, intersection, and difference. An invalid
/// implementation would therefore be a semantic data-loss bug rather than a
/// merely weak cache hint.
pub trait PatchHash: sealed::Sealed + Send + Sync + 'static {
    /// Cached summary stored in every heap leaf and branch.
    type Digest: Copy + core::fmt::Debug + Eq + Send + Sync + 'static;

    /// Incremental state used while summarizing one branch's children.
    type BranchState;

    /// Whether child summaries form a commutative branch aggregate.
    ///
    /// Commutative policies can scan the physical cuckoo table directly;
    /// ordered policies are fed children by ascending edge byte.
    const COMMUTATIVE_BRANCH: bool;

    /// Whether [`Self::edit_branch`] provides an exact updated digest.
    /// False lets PATCH compile the edit call out and rebuild once on editor
    /// drop; true keeps the default edit path identical to its direct
    /// algebraic update.
    const INCREMENTAL_BRANCH: bool;

    /// Initialize any process-local state required by this policy.
    fn init();

    /// Summarize one complete key. Associated values never participate.
    fn leaf(bytes: &[u8]) -> Self::Digest;

    /// Begin summarizing a canonical branch.
    ///
    /// `representative` is any descendant key. `tree_to_key` identifies the
    /// first `end_depth` bytes that form the branch's canonical compressed
    /// prefix; bytes after that prefix must not affect the summary.
    fn begin_branch(
        representative: &[u8],
        tree_to_key: &[usize],
        end_depth: usize,
        child_count: usize,
        leaf_count: u64,
    ) -> Self::BranchState;

    /// Add one child in ascending edge-byte order.
    fn push_child(state: &mut Self::BranchState, edge: u8, leaf_count: u64, digest: Self::Digest);

    /// Finish one branch summary.
    fn finish_branch(state: Self::BranchState) -> Self::Digest;

    /// Update a branch summary after one child edit.
    ///
    /// PATCH calls this only when [`Self::INCREMENTAL_BRANCH`] is true, which
    /// is a sealed-trait promise that this operation is exact.
    fn edit_branch(
        current: Self::Digest,
        edge: u8,
        old: Option<Self::Digest>,
        new: Option<Self::Digest>,
    ) -> Self::Digest;
}

/// PATCH's default process-private SipHash-leaf/XOR summary policy.
///
/// Its raw aggregates remain crate-private. [`TribleSetFingerprint`](
/// crate::trible::TribleSetFingerprint) exposes only the separately keyed,
/// nonlinear blinding of a root aggregate.
#[derive(Clone, Copy, Debug, Default)]
pub struct XorSip128;

impl sealed::Sealed for XorSip128 {}

impl PatchHash for XorSip128 {
    type Digest = u128;
    type BranchState = u128;
    const COMMUTATIVE_BRANCH: bool = true;
    const INCREMENTAL_BRANCH: bool = true;

    #[inline]
    fn init() {
        init_hash_keys();
    }

    #[inline]
    fn leaf(bytes: &[u8]) -> Self::Digest {
        xor_hash_leaf_bytes(bytes)
    }

    #[inline]
    fn begin_branch(
        _representative: &[u8],
        _tree_to_key: &[usize],
        _end_depth: usize,
        _child_count: usize,
        _leaf_count: u64,
    ) -> Self::BranchState {
        0
    }

    #[inline]
    fn push_child(
        state: &mut Self::BranchState,
        _edge: u8,
        _leaf_count: u64,
        digest: Self::Digest,
    ) {
        *state ^= digest;
    }

    #[inline]
    fn finish_branch(state: Self::BranchState) -> Self::Digest {
        state
    }

    #[inline]
    fn edit_branch(
        mut current: Self::Digest,
        _edge: u8,
        old: Option<Self::Digest>,
        new: Option<Self::Digest>,
    ) -> Self::Digest {
        if let Some(old) = old {
            current ^= old;
        }
        if let Some(new) = new {
            current ^= new;
        }
        current
    }
}

/// Canonical BLAKE3 Merkle summaries for durable or adversarial PATCH uses.
///
/// Unlike [`XorSip128`], this policy commits to the canonical Patricia-trie
/// structure: leaf keys are domain-separated from branches, and every branch
/// commits to its key width, compressed-path bytes, fanout, subtree leaf
/// count, and each ascending `(edge, child leaf count, child digest)` tuple.
/// PATCH's trie shape is a function of its key set, so insertion order and
/// cuckoo-table placement do not affect the result.
///
/// BLAKE3's native chunk tree is intentionally not reused here. Its tree
/// describes fixed-size chunks of one byte stream, whereas PATCH is a sparse
/// radix tree whose fanout and compressed depths change under edits. Branches
/// are therefore framed explicitly and hashed with the ordinary streaming
/// API.
#[derive(Clone, Copy, Debug, Default)]
pub struct Blake3Merkle;

impl sealed::Sealed for Blake3Merkle {}

impl PatchHash for Blake3Merkle {
    type Digest = [u8; 32];
    type BranchState = blake3::Hasher;
    const COMMUTATIVE_BRANCH: bool = false;
    const INCREMENTAL_BRANCH: bool = false;

    #[inline]
    fn init() {
        bytetable::init();
    }

    fn leaf(bytes: &[u8]) -> Self::Digest {
        let mut state = blake3::Hasher::new();
        state.update(b"triblespace.patch.leaf.v1\0");
        state.update(&(bytes.len() as u64).to_le_bytes());
        state.update(bytes);
        *state.finalize().as_bytes()
    }

    fn begin_branch(
        representative: &[u8],
        tree_to_key: &[usize],
        end_depth: usize,
        child_count: usize,
        leaf_count: u64,
    ) -> Self::BranchState {
        debug_assert_eq!(representative.len(), tree_to_key.len());
        debug_assert!(end_depth <= representative.len());
        let mut state = blake3::Hasher::new();
        state.update(b"triblespace.patch.branch.v2\0");
        state.update(&(representative.len() as u64).to_le_bytes());
        state.update(&(end_depth as u64).to_le_bytes());
        for &key_index in &tree_to_key[..end_depth] {
            state.update(&[representative[key_index]]);
        }
        state.update(&(child_count as u64).to_le_bytes());
        state.update(&leaf_count.to_le_bytes());
        state
    }

    #[inline]
    fn push_child(state: &mut Self::BranchState, edge: u8, leaf_count: u64, digest: Self::Digest) {
        state.update(&[edge]);
        state.update(&leaf_count.to_le_bytes());
        state.update(&digest);
    }

    #[inline]
    fn finish_branch(state: Self::BranchState) -> Self::Digest {
        *state.finalize().as_bytes()
    }

    #[inline]
    fn edit_branch(
        _current: Self::Digest,
        _edge: u8,
        _old: Option<Self::Digest>,
        _new: Option<Self::Digest>,
    ) -> Self::Digest {
        unreachable!("non-incremental PATCH hash policy was asked to edit a branch")
    }
}

/// Fixed input-domain marker for the public
/// [`TribleSetFingerprint`](crate::trible::TribleSetFingerprint)
/// blinding PRF.
///
/// A distinct random key already separates this use from PATCH leaf hashing;
/// the marker additionally prevents this output from being confused with a
/// future use of the same key over an untyped 128-bit value.
const EXPORTED_FINGERPRINT_DOMAIN: [u8; 16] = *b"TribleSet.fp.v1\0";

/// Minimum `other.leaf_count` at which [`Head::par_union`] takes the
/// scatter + bitset + rayon::scope-spawn path on the equal-depth-
/// branch arm. Below this, the per-key `modify_child` loop wins
/// because asymmetric merges only touch a handful of slots.
#[cfg(feature = "parallel")]
const PARALLEL_PATCH_UNION_THRESHOLD: usize = 4096;

/// Parallel-aware PATCH union, with a shared work-stealing budget
/// carried across the entire recursive descent.
///
/// Two-phase model per parallel call:
///   1. Spawn phase (collect sequentially, dispatch per child):
///      drain "both" pairs, for each: claim 1 unit from the
///      shared budget — if successful, spawn the child union as
///      a `rayon::scope` task; if budget is exhausted, run the
///      child serially via `Head::union`.
///   2. Install phase (purely serial): scatter-collected resolved
///      heads + single-side pass-throughs land in the parent
///      branch, then `recompute_aggregates` rebuilds the
///      hash/leaf_count/segment_count/childleaf in one pass.
///
/// The budget is a single shared atomic — `num_threads²` total
/// spawns across the entire descent, after which everything is
/// sequential. This caps overhead without restricting the depth
/// at which parallelism is reached: a heavy subtree near the
/// root claims many units; a balanced descent spreads them.
#[cfg(feature = "parallel")]
mod parallel_union {
    use core::sync::atomic::{AtomicUsize, Ordering};

    /// Carries the shared spawn budget across recursive
    /// `par_union_with_ctx` calls.
    pub(crate) struct ParUnionCtx {
        pub(crate) budget: AtomicUsize,
    }

    impl ParUnionCtx {
        pub(crate) fn new() -> Self {
            let n = rayon::current_num_threads();
            Self {
                budget: AtomicUsize::new(n.saturating_mul(n).max(2)),
            }
        }

        /// Try to claim one spawn unit. Returns `true` if a unit was
        /// claimed (caller should spawn), `false` if the budget was
        /// already exhausted (caller should run serially).
        ///
        /// A naive `fetch_sub(1)` would wrap `0 → usize::MAX` on
        /// over-subtract, briefly letting other threads see a huge
        /// budget — so we use compare-exchange to refuse the claim
        /// without ever observing the underflow.
        pub(crate) fn try_claim(&self) -> bool {
            let mut current = self.budget.load(Ordering::Relaxed);
            loop {
                if current == 0 {
                    return false;
                }
                match self.budget.compare_exchange_weak(
                    current,
                    current - 1,
                    Ordering::Relaxed,
                    Ordering::Relaxed,
                ) {
                    Ok(_) => return true,
                    Err(observed) => current = observed,
                }
            }
        }
    }

    /// Raw-pointer wrapper for the scatter-write target. Each
    /// spawned task writes to `resolved[k]` for its specific key
    /// byte `k`; keys are pairwise distinct by construction (each
    /// "both" bit in the partition uniquely identifies a slot), so
    /// the writes are non-aliasing despite sharing a `*mut` across
    /// threads.
    ///
    /// `write_at` exists as an inherent method (rather than callers
    /// reading the `*mut` field directly) so that move closures
    /// capture the whole wrapper — Rust 2021 precise-capture would
    /// otherwise grab the raw pointer field, dropping the manual
    /// `Send`/`Sync` impls and triggering a Send error.
    pub(crate) struct ScatterPtr<T>(pub *mut T);

    // Manual `Copy`/`Clone` impls so `T` doesn't get a spurious
    // `T: Copy` / `T: Clone` bound from derive — the wrapper holds a
    // raw pointer, which is always `Copy` regardless of `T`.
    impl<T> Clone for ScatterPtr<T> {
        fn clone(&self) -> Self {
            *self
        }
    }
    impl<T> Copy for ScatterPtr<T> {}

    // SAFETY: tasks only transfer owned `T` values into pairwise-disjoint
    // output slots. The wrapper never exposes a reference to a stored `T`, so
    // moving those values between threads requires `T: Send`, not `T: Sync`.
    unsafe impl<T: Send> Send for ScatterPtr<T> {}
    unsafe impl<T: Send> Sync for ScatterPtr<T> {}

    impl<T> ScatterPtr<T> {
        /// SAFETY: `i` must be in-bounds of the underlying buffer,
        /// and the caller must guarantee no other thread is writing
        /// to slot `i` concurrently.
        pub(crate) unsafe fn write_at(self, i: usize, v: T) {
            self.0.add(i).write(v);
        }
    }
}

/// Return the immutable process-local PATCH hash-key bundle, initializing all
/// randomness PATCH construction relies on exactly once.
fn hash_keys() -> &'static HashKeys {
    HASH_KEYS.get_or_init(|| {
        bytetable::init();

        let mut rng = thread_rng();
        let mut leaf = [0u8; 16];
        let mut exported_fingerprint = [0u8; 16];
        rng.fill_bytes(&mut leaf);
        // Make key separation exact rather than adding a second, avoidable
        // 2^-128 assumption to the public-boundary argument.
        loop {
            rng.fill_bytes(&mut exported_fingerprint);
            if exported_fingerprint != leaf {
                break;
            }
        }
        HashKeys {
            leaf,
            exported_fingerprint,
        }
    })
}

/// Initialize PATCH's process-local hash and byte-table randomness.
///
/// Hashing entry points also call [`hash_keys`] themselves, so safe `Entry`
/// construction before the first [`PATCH`] cannot observe an uninitialized
/// key.
pub(crate) fn init_hash_keys() {
    let _ = hash_keys();
}

/// Hash one PATCH leaf through the initialized process-local key accessor.
#[inline]
fn xor_hash_leaf_bytes(bytes: &[u8]) -> u128 {
    use siphasher::sip128::SipHasher24;

    SipHasher24::new_with_key(&hash_keys().leaf)
        .hash(bytes)
        .into()
}

/// Apply the public-fingerprint PRF under an explicit key.
///
/// Keeping this transformation separate makes the proof boundary visible:
/// PATCH's internal aggregate is linear, while values crossing the public API
/// pass through this nonlinear keyed function first.
#[inline]
fn blind_root_hash_with_key(root_hash: u128, key: &[u8; 16]) -> u128 {
    use siphasher::sip128::SipHasher24;

    let mut input = [0u8; 32];
    input[..16].copy_from_slice(&EXPORTED_FINGERPRINT_DOMAIN);
    input[16..].copy_from_slice(&root_hash.to_le_bytes());
    SipHasher24::new_with_key(key).hash(&input).into()
}

/// Blind PATCH's internal root aggregate for public, process-local cache keys.
///
/// The raw root is an XOR of keyed leaf hashes and must not be exposed: chosen
/// singleton outputs would reveal vectors from which a linear dependency can
/// be constructed. This distinct-key, domain-separated PRF preserves equality
/// within the process without exposing that algebra. `None` remains the unique
/// empty-set representation.
#[inline]
pub(crate) fn blind_root_hash(root_hash: Option<u128>) -> Option<u128> {
    let root_hash = root_hash?;
    Some(blind_root_hash_with_key(
        root_hash,
        &hash_keys().exported_fingerprint,
    ))
}

/// Hash one PATCH key with the process-local internal leaf key.
///
/// Bulk archive construction calls this once per source row and shares the
/// result across all six index builds. Initializing here is important because
/// that path hashes before it constructs its first [`PATCH`].
#[cfg(any(test, feature = "parallel"))]
#[inline]
pub(crate) fn hash_key(bytes: &[u8]) -> u128 {
    XorSip128::leaf(bytes)
}

/// Builds a per-byte segment map from the segment lengths.
///
/// The returned table maps each key byte to its segment index.
pub const fn build_segmentation<const N: usize, const M: usize>(lens: [usize; M]) -> [usize; N] {
    let mut res = [0; N];
    let mut seg = 0;
    let mut off = 0;
    while seg < M {
        let len = lens[seg];
        let mut i = 0;
        while i < len {
            res[off + i] = seg;
            i += 1;
        }
        off += len;
        seg += 1;
    }
    res
}

/// Builds an identity permutation table of length `N`.
pub const fn identity_map<const N: usize>() -> [usize; N] {
    let mut res = [0; N];
    let mut i = 0;
    while i < N {
        res[i] = i;
        i += 1;
    }
    res
}

/// Builds a table translating indices from key order to tree order.
///
/// `lens` describes the segment lengths in key order and `perm` is the
/// permutation of those segments in tree order.
pub const fn build_key_to_tree<const N: usize, const M: usize>(
    lens: [usize; M],
    perm: [usize; M],
) -> [usize; N] {
    let mut key_starts = [0; M];
    let mut off = 0;
    let mut i = 0;
    while i < M {
        key_starts[i] = off;
        off += lens[i];
        i += 1;
    }

    let mut tree_starts = [0; M];
    off = 0;
    i = 0;
    while i < M {
        let seg = perm[i];
        tree_starts[seg] = off;
        off += lens[seg];
        i += 1;
    }

    let mut res = [0; N];
    let mut seg = 0;
    while seg < M {
        let len = lens[seg];
        let ks = key_starts[seg];
        let ts = tree_starts[seg];
        let mut j = 0;
        while j < len {
            res[ks + j] = ts + j;
            j += 1;
        }
        seg += 1;
    }
    res
}

/// Inverts a permutation table.
pub const fn invert<const N: usize>(arr: [usize; N]) -> [usize; N] {
    let mut res = [0; N];
    let mut i = 0;
    while i < N {
        res[arr[i]] = i;
        i += 1;
    }
    res
}

/// For each tree-depth `d`, the end (exclusive) of the segment that contains
/// `d`, derived from a segmentation table (in key order) and a tree→key map.
///
/// Each logical segment is contiguous in tree order, so the boundary after a
/// depth is simply the first deeper depth whose segment id differs (or
/// `KEY_LEN`). Used by [`KeySchema::next_boundary`] / `SEGMENT_ENDS` to cap
/// variable-width branch spans so they never cross a segment checkpoint.
pub const fn build_segment_ends<const N: usize>(
    segments: [usize; N],
    tree_to_key: [usize; N],
) -> [usize; N] {
    let mut ends = [0usize; N];
    let mut d = 0;
    while d < N {
        let seg = segments[tree_to_key[d]];
        let mut e = d + 1;
        while e < N && segments[tree_to_key[e]] == seg {
            e += 1;
        }
        ends[d] = e;
        d += 1;
    }
    ends
}

#[doc(hidden)]
#[macro_export]
macro_rules! key_segmentation {
    (@count $($e:expr),* $(,)?) => {
        <[()]>::len(&[$($crate::key_segmentation!(@sub $e)),*])
    };
    (@sub $e:expr) => { () };
    ($(#[$meta:meta])* $name:ident, $len:expr, [$($seg_len:expr),+ $(,)?]) => {
        $(#[$meta])*
        #[derive(Copy, Clone, Debug)]
        pub struct $name;
        impl $name {
            pub const SEG_LENS: [usize; $crate::key_segmentation!(@count $($seg_len),*)] = [$($seg_len),*];
        }
        impl $crate::patch::KeySegmentation<$len> for $name {
            const SEGMENTS: [usize; $len] = $crate::patch::build_segmentation::<$len, {$crate::key_segmentation!(@count $($seg_len),*)}>(Self::SEG_LENS);
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! key_schema {
    (@count $($e:expr),* $(,)?) => {
        <[()]>::len(&[$($crate::key_schema!(@sub $e)),*])
    };
    (@sub $e:expr) => { () };
    ($(#[$meta:meta])* $name:ident, $seg:ty, $len:expr, [$($perm:expr),+ $(,)?]) => {
        $(#[$meta])*
        #[derive(Copy, Clone, Debug)]
        pub struct $name;
        impl $crate::patch::KeySchema<$len> for $name {
            type Segmentation = $seg;
            const SEGMENT_PERM: &'static [usize] = &[$($perm),*];
            const KEY_TO_TREE: [usize; $len] = $crate::patch::build_key_to_tree::<$len, {$crate::key_schema!(@count $($perm),*)}>(<$seg>::SEG_LENS, [$($perm),*]);
            const TREE_TO_KEY: [usize; $len] = $crate::patch::invert(Self::KEY_TO_TREE);
        }
    };
}

/// A trait is used to provide a re-ordered view of the keys stored in the PATCH.
/// This allows for different PATCH instances share the same leaf nodes,
/// independent of the key ordering used in the tree.
pub trait KeySchema<const KEY_LEN: usize>: Copy + Clone + Debug {
    /// The segmentation this ordering operates over.
    type Segmentation: KeySegmentation<KEY_LEN>;
    /// Order of segments from key layout to tree layout.
    const SEGMENT_PERM: &'static [usize];
    /// Maps each key index to its position in the tree view.
    const KEY_TO_TREE: [usize; KEY_LEN];
    /// Maps each tree index to its position in the key view.
    const TREE_TO_KEY: [usize; KEY_LEN];

    /// For each tree-depth, the exclusive end of the segment containing it.
    ///
    /// Purely additive (a provided default derived from `Segmentation` +
    /// `TREE_TO_KEY`); it does not affect single-byte PATCH behaviour. A
    /// variable-width trie would use it to start branch spans segment-wide and
    /// guarantee a span never crosses a checkpoint. For EAV over a 64-byte
    /// trible this yields ends `{16,32,64}`; for VEA `{32,48,64}`.
    const SEGMENT_ENDS: [usize; KEY_LEN] = build_segment_ends::<KEY_LEN>(
        <Self::Segmentation as KeySegmentation<KEY_LEN>>::SEGMENTS,
        Self::TREE_TO_KEY,
    );

    /// The exclusive end of the segment containing tree-depth `tree_depth`.
    ///
    /// A variable-width branch starting at `span_start` may widen its span up
    /// to `next_boundary(span_start)` but no further, so each branch stays
    /// within a single segment.
    fn next_boundary(tree_depth: usize) -> usize {
        Self::SEGMENT_ENDS[tree_depth]
    }

    /// Reorders the key from the shared key ordering to the tree ordering.
    fn tree_ordered(key: &[u8; KEY_LEN]) -> [u8; KEY_LEN] {
        let mut new_key = [0; KEY_LEN];
        let mut i = 0;
        while i < KEY_LEN {
            new_key[Self::KEY_TO_TREE[i]] = key[i];
            i += 1;
        }
        new_key
    }

    /// Reorders the key from the tree ordering to the shared key ordering.
    fn key_ordered(tree_key: &[u8; KEY_LEN]) -> [u8; KEY_LEN] {
        let mut new_key = [0; KEY_LEN];
        let mut i = 0;
        while i < KEY_LEN {
            new_key[Self::TREE_TO_KEY[i]] = tree_key[i];
            i += 1;
        }
        new_key
    }

    /// Return the segment index for the byte at `at_depth` in tree ordering.
    ///
    /// Default implementation reads the static segmentation table and the
    /// tree->key mapping. Having this as a method makes call sites clearer and
    /// reduces the verbosity of expressions that access the segmentation table.
    fn segment_of_tree_depth(at_depth: usize) -> usize {
        <Self::Segmentation as KeySegmentation<KEY_LEN>>::SEGMENTS[Self::TREE_TO_KEY[at_depth]]
    }

    /// Return true if the tree-ordered bytes at `a` and `b` belong to the same
    /// logical segment.
    fn same_segment_tree(a: usize, b: usize) -> bool {
        <Self::Segmentation as KeySegmentation<KEY_LEN>>::SEGMENTS[Self::TREE_TO_KEY[a]]
            == <Self::Segmentation as KeySegmentation<KEY_LEN>>::SEGMENTS[Self::TREE_TO_KEY[b]]
    }
}

/// This trait is used to segment keys stored in the PATCH.
/// The segmentation is used to determine sub-fields of the key,
/// allowing for segment based operations, like counting the number
/// of elements in a segment with a given prefix without traversing the tree.
///
/// Note that the segmentation is defined on the shared key ordering,
/// and should thus be only implemented once, independent of additional key orderings.
///
/// See [TribleSegmentation](crate::trible::TribleSegmentation) for an example that segments keys into entity,
/// attribute, and value segments.
pub trait KeySegmentation<const KEY_LEN: usize>: Copy + Clone + Debug {
    /// Segment index for each position in the key.
    const SEGMENTS: [usize; KEY_LEN];
}

/// A `KeySchema` that does not reorder the keys.
/// This is useful for keys that are already ordered in the desired way.
/// This is the default ordering.
#[derive(Copy, Clone, Debug)]
pub struct IdentitySchema {}

/// A `KeySegmentation` that does not segment the keys.
/// This is useful for keys that do not have a segment structure.
/// This is the default segmentation.
#[derive(Copy, Clone, Debug)]
pub struct SingleSegmentation {}
impl<const KEY_LEN: usize> KeySchema<KEY_LEN> for IdentitySchema {
    type Segmentation = SingleSegmentation;
    const SEGMENT_PERM: &'static [usize] = &[0];
    const KEY_TO_TREE: [usize; KEY_LEN] = identity_map::<KEY_LEN>();
    const TREE_TO_KEY: [usize; KEY_LEN] = identity_map::<KEY_LEN>();
}

impl<const KEY_LEN: usize> KeySegmentation<KEY_LEN> for SingleSegmentation {
    const SEGMENTS: [usize; KEY_LEN] = [0; KEY_LEN];
}

#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
#[repr(u8)]
pub(crate) enum HeadTag {
    // Stored in the low 4 bits of `Head::tptr` (see Head::new).
    //
    // Branch values encode log2(branch_size) (i.e. `Branch2 == 1`, `Branch256
    // == 8`). `0` is reserved for leaf nodes, which lets us compute the branch
    // size as `1 << tag` without any offset. The derived `Ord` therefore
    // compares branch sizes — `tag_a > tag_b` ⟺ `size_a > size_b`, and the
    // 2× swap threshold reduces to a single tag-byte compare.
    //
    // `LocalLeaf` (9) is appended at the end so the Branch widths' `1 << tag`
    // arithmetic and the Leaf-vs-Branch threshold comparisons are unaffected.
    // It represents a leaf whose key bytes live in an archive's mmap'd buffer,
    // referenced via a thin pointer in the Head body slot rather than via a
    // heap-allocated `Leaf<KEY_LEN, V>`. Lifetime is guaranteed by the exact
    // owner set on the enclosing PATCH value.
    Leaf = 0,
    Branch2 = 1,
    Branch4 = 2,
    Branch8 = 3,
    Branch16 = 4,
    Branch32 = 5,
    Branch64 = 6,
    Branch128 = 7,
    Branch256 = 8,
    LocalLeaf = 9,
}

impl HeadTag {
    #[inline]
    fn from_raw(raw: u8) -> Self {
        debug_assert!(raw <= HeadTag::LocalLeaf as u8);
        // SAFETY: `HeadTag` is `#[repr(u8)]` with a contiguous discriminant
        // range 0..=9. The tag bits are written by Head::new/set_body and
        // Branch::tag, which only emit valid discriminants.
        unsafe { std::mem::transmute(raw) }
    }
}

pub(crate) enum BodyPtr<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> {
    Leaf(NonNull<Leaf<KEY_LEN, V, H>>),
    /// Thin pointer to a `[u8; KEY_LEN]` trible living in an archive's
    /// mmap'd buffer. Lifetime is implicit — guaranteed by the enclosing
    /// PATCH's owner set.
    LocalLeaf(NonNull<[u8; KEY_LEN]>),
    Branch(branch::BranchNN<KEY_LEN, O, V, H>),
}

/// Immutable borrow view of a Head body.
/// Returned by `body_ref()` and tied to the lifetime of the `&Head`.
pub(crate) enum BodyRef<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> {
    Leaf(&'a Leaf<KEY_LEN, V, H>),
    /// Reference to a trible's bytes within an archive. The slice's
    /// lifetime is bound to `&'a Head` via the body pointer; the actual
    /// underlying allocation is kept alive by the enclosing PATCH.
    LocalLeaf(&'a [u8; KEY_LEN]),
    Branch(&'a Branch<KEY_LEN, O, [Option<Head<KEY_LEN, O, V, H>>], V, H>),
}

/// Mutation-capable borrow view of a Head body.
/// Returned by `body_mut()` and tied to the lifetime of the `&mut Head`.
///
/// Branches are copy-on-write and therefore unique before this view exposes
/// them mutably. Heap leaves, like archive-local leaves, may still be shared
/// by another PATCH snapshot, so both leaf variants are exposed read-only.
pub(crate) enum BodyMut<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> {
    Leaf(&'a Leaf<KEY_LEN, V, H>),
    /// `LocalLeaf` is read-only by construction (it points into immutable
    /// archive bytes), so the mutable view yields a shared reference.
    /// Structural operations may move the Head while its PATCH owner guard
    /// remains live.
    LocalLeaf(&'a [u8; KEY_LEN]),
    Branch(&'a mut Branch<KEY_LEN, O, [Option<Head<KEY_LEN, O, V, H>>], V, H>),
}

pub(crate) trait Body {
    fn tag(body: NonNull<Self>) -> HeadTag;
}

#[repr(C)]
pub(crate) struct Head<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash = XorSip128> {
    tptr: std::ptr::NonNull<u8>,
    key_ordering: PhantomData<O>,
    key_segments: PhantomData<O::Segmentation>,
    value: PhantomData<V>,
    hash_policy: PhantomData<H>,
}

// SAFETY: a Head owns a persistent, atomically reference-counted node. Cloned
// Heads may expose the same Leaf<V> on different threads, and the final owner
// may drop V on either thread, so both auto traits require V: Send + Sync.
// O and O::Segmentation are ignored deliberately: they are type-level schemas
// used only through associated constants and functions; no value or reference
// of either type is stored in, or accessed through, a Head.
unsafe impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V: Send + Sync, H: PatchHash> Send
    for Head<KEY_LEN, O, V, H>
{
}

// SAFETY: the same shared-leaf and type-level-schema argument above applies.
unsafe impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V: Send + Sync, H: PatchHash> Sync
    for Head<KEY_LEN, O, V, H>
{
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Head<KEY_LEN, O, V, H> {
    // Tagged pointer layout (64-bit only):
    // - bits 0..=3:   HeadTag (requires 16-byte aligned bodies)
    // - bits 4..=55:  body pointer bits (52 bits)
    // - bits 56..=63: key byte for cuckoo table lookup
    const TAG_MASK: u64 = 0x0f;
    const BODY_MASK: u64 = 0x00_ff_ff_ff_ff_ff_ff_f0;
    const KEY_MASK: u64 = 0xff_00_00_00_00_00_00_00;

    pub(crate) fn new<T: Body + ?Sized>(key: u8, body: NonNull<T>) -> Self {
        unsafe {
            let tptr =
                std::ptr::NonNull::new_unchecked((body.as_ptr() as *mut u8).map_addr(|addr| {
                    debug_assert_eq!(addr as u64 & Self::TAG_MASK, 0);
                    ((addr as u64 & Self::BODY_MASK)
                        | ((key as u64) << 56)
                        | (<T as Body>::tag(body) as u64)) as usize
                }));
            Self {
                tptr,
                key_ordering: PhantomData,
                key_segments: PhantomData,
                value: PhantomData,
                hash_policy: PhantomData,
            }
        }
    }

    /// Constructs a `LocalLeaf` Head pointing directly at a `[u8; KEY_LEN]`
    /// trible inside an archive's mmap'd buffer. The pointer's address must
    /// be 16-byte aligned (so the low 4 bits are free for the `HeadTag`);
    /// for `SimpleArchive` buffers this holds whenever the base allocation
    /// is 16-byte aligned and tribles are 64 bytes wide (every offset is a
    /// multiple of 16).
    ///
    /// # Safety
    /// - `trible_ptr` must remain valid for at least as long as this Head
    ///   exists, which is the caller's responsibility to arrange — typically
    ///   by retaining its `Arc<dyn ArchiveOwner>` in the enclosing PATCH's
    ///   root owner set.
    /// - The pointed-to bytes must remain fully initialized and immutable for
    ///   that lifetime, including through concurrent aliases or interior
    ///   mutability. LocalLeaf routing and fingerprints read them through
    ///   shared references.
    /// - The pointer must be 16-byte aligned; this is debug-asserted.
    pub(crate) unsafe fn new_local_leaf(key: u8, trible_ptr: NonNull<[u8; KEY_LEN]>) -> Self {
        unsafe {
            let tptr = std::ptr::NonNull::new_unchecked((trible_ptr.as_ptr() as *mut u8).map_addr(
                |addr| {
                    debug_assert_eq!(
                        addr as u64 & Self::TAG_MASK,
                        0,
                        "LocalLeaf trible pointer must be 16-byte aligned"
                    );
                    ((addr as u64 & Self::BODY_MASK)
                        | ((key as u64) << 56)
                        | (HeadTag::LocalLeaf as u64)) as usize
                },
            ));
            Self {
                tptr,
                key_ordering: PhantomData,
                key_segments: PhantomData,
                value: PhantomData,
                hash_policy: PhantomData,
            }
        }
    }

    #[inline]
    pub(crate) fn tag(&self) -> HeadTag {
        HeadTag::from_raw((self.tptr.as_ptr() as u64 & Self::TAG_MASK) as u8)
    }

    #[inline]
    pub(crate) fn key(&self) -> u8 {
        (self.tptr.as_ptr() as u64 >> 56) as u8
    }

    #[inline]
    pub(crate) fn with_key(mut self, key: u8) -> Self {
        self.tptr =
            std::ptr::NonNull::new(self.tptr.as_ptr().map_addr(|addr| {
                ((addr as u64 & !Self::KEY_MASK) | ((key as u64) << 56)) as usize
            }))
            .unwrap();
        self
    }

    #[inline]
    pub(crate) fn set_body<T: Body + ?Sized>(&mut self, body: NonNull<T>) {
        unsafe {
            self.tptr = NonNull::new_unchecked((body.as_ptr() as *mut u8).map_addr(|addr| {
                debug_assert_eq!(addr as u64 & Self::TAG_MASK, 0);
                ((addr as u64 & Self::BODY_MASK)
                    | (self.tptr.as_ptr() as u64 & Self::KEY_MASK)
                    | (<T as Body>::tag(body) as u64)) as usize
            }))
        }
    }

    pub(crate) fn with_start(self, new_start_depth: usize) -> Head<KEY_LEN, O, V, H> {
        let leaf_key = self.childleaf_key();
        let i = O::TREE_TO_KEY[new_start_depth];
        let key = leaf_key[i];
        self.with_key(key)
    }

    // Removed childleaf_matches_key_from in favor of composing the existing
    // has_prefix primitives directly at call sites. Use
    // `self.has_prefix::<KEY_LEN>(at_depth, key)` or for partial checks
    // `self.childleaf().has_prefix::<O>(at_depth, &key[..limit])` instead.

    pub(crate) fn body(&self) -> BodyPtr<KEY_LEN, O, V, H> {
        unsafe {
            let ptr = NonNull::new_unchecked(self.tptr.as_ptr().map_addr(|addr| {
                let masked = (addr as u64) & Self::BODY_MASK;
                masked as usize
            }));
            match self.tag() {
                HeadTag::Leaf => BodyPtr::Leaf(ptr.cast()),
                HeadTag::LocalLeaf => BodyPtr::LocalLeaf(ptr.cast()),
                branch_tag => {
                    let count = 1 << (branch_tag as usize);
                    BodyPtr::Branch(NonNull::new_unchecked(std::ptr::slice_from_raw_parts(
                        ptr.as_ptr(),
                        count,
                    )
                        as *mut Branch<KEY_LEN, O, [Option<Head<KEY_LEN, O, V, H>>], V, H>))
                }
            }
        }
    }

    pub(crate) fn body_mut(&mut self) -> BodyMut<'_, KEY_LEN, O, V, H> {
        unsafe {
            match self.body() {
                BodyPtr::Leaf(leaf) => BodyMut::Leaf(leaf.as_ref()),
                BodyPtr::LocalLeaf(ptr) => BodyMut::LocalLeaf(ptr.as_ref()),
                BodyPtr::Branch(mut branch) => {
                    // Ensure ownership: try copy-on-write and update local pointer if needed.
                    let mut branch_nn = branch;
                    if Branch::rc_cow(&mut branch_nn).is_some() {
                        self.set_body(branch_nn);
                        BodyMut::Branch(branch_nn.as_mut())
                    } else {
                        BodyMut::Branch(branch.as_mut())
                    }
                }
            }
        }
    }

    /// Returns an immutable borrow of the body (Leaf, LocalLeaf, or Branch)
    /// tied to &self.
    pub(crate) fn body_ref(&self) -> BodyRef<'_, KEY_LEN, O, V, H> {
        match self.body() {
            BodyPtr::Leaf(nn) => BodyRef::Leaf(unsafe { nn.as_ref() }),
            BodyPtr::LocalLeaf(nn) => BodyRef::LocalLeaf(unsafe { nn.as_ref() }),
            BodyPtr::Branch(nn) => BodyRef::Branch(unsafe { nn.as_ref() }),
        }
    }

    pub(crate) fn count(&self) -> u64 {
        match self.body_ref() {
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => 1,
            BodyRef::Branch(branch) => branch.leaf_count,
        }
    }

    #[inline]
    fn is_archive_singleton_pair(&self, other: &Self) -> bool {
        matches!(
            (self.tag(), other.tag()),
            (HeadTag::LocalLeaf, HeadTag::Leaf | HeadTag::LocalLeaf)
                | (HeadTag::Leaf, HeadTag::LocalLeaf)
        )
    }

    /// Returns whether cardinality still permits equal fingerprints when an
    /// archive-backed leaf is involved. A `LocalLeaf` represents exactly one
    /// key, while a Branch's count is cached; all pairs without a `LocalLeaf`
    /// retain the existing fingerprint path unchanged.
    #[inline]
    fn local_leaf_cardinality_allows_equality(&self, other: &Self) -> bool {
        match (self.tag(), other.tag()) {
            (HeadTag::LocalLeaf, _) => other.count() == 1,
            (_, HeadTag::LocalLeaf) => self.count() == 1,
            _ => true,
        }
    }

    pub(crate) fn count_segment(&self, at_depth: usize) -> u64 {
        match self.body_ref() {
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => 1,
            BodyRef::Branch(branch) => branch.count_segment(at_depth),
        }
    }

    pub(crate) fn hash(&self) -> H::Digest {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => leaf.hash,
            BodyRef::LocalLeaf(bytes) => H::leaf(&bytes[..]),
            BodyRef::Branch(branch) => branch.hash,
        }
    }

    pub(crate) fn end_depth(&self) -> usize {
        match self.body_ref() {
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => KEY_LEN,
            BodyRef::Branch(branch) => branch.end_depth as usize,
        }
    }

    /// Returns the raw key-bytes pointer of the representative child
    /// leaf for use in low-level operations (Branch construction,
    /// invariant checks). For heap `Leaf`, that's `&leaf.key`; for
    /// `LocalLeaf`, the archive-resident bytes pointer; for `Branch`,
    /// the branch's already-computed childleaf pointer.
    pub(crate) fn childleaf_ptr(&self) -> *const [u8; KEY_LEN] {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => &leaf.key as *const [u8; KEY_LEN],
            BodyRef::LocalLeaf(bytes) => bytes as *const [u8; KEY_LEN],
            BodyRef::Branch(branch) => branch.childleaf_ptr(),
        }
    }

    pub(crate) fn childleaf_key(&self) -> &[u8; KEY_LEN] {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => &leaf.key,
            BodyRef::LocalLeaf(bytes) => bytes,
            BodyRef::Branch(branch) => branch.childleaf_key(),
        }
    }

    // Slot wrapper defined at module level (moved to below the impl block)

    /// Find the first depth in [start_depth, limit) where the tree-ordered
    /// bytes of `self` and `other` differ. The comparison limit is computed
    /// as min(self.end_depth(), other.end_depth(), KEY_LEN) which is the
    /// natural bound for comparing two heads. Returns `Some((depth, a, b))`
    /// where `a` and `b` are the differing bytes at that depth, or `None`
    /// if no divergence is found in the range.
    pub(crate) fn first_divergence(
        &self,
        other: &Self,
        start_depth: usize,
    ) -> Option<(usize, u8, u8)> {
        let limit = std::cmp::min(std::cmp::min(self.end_depth(), other.end_depth()), KEY_LEN);
        debug_assert!(limit <= KEY_LEN);
        let this_key = self.childleaf_key();
        let other_key = other.childleaf_key();
        let mut depth = start_depth;
        while depth < limit {
            let i = O::TREE_TO_KEY[depth];
            let a = this_key[i];
            let b = other_key[i];
            if a != b {
                return Some((depth, a, b));
            }
            depth += 1;
        }
        None
    }

    // Mutable access to the child slots for this head. If the head is a
    // branch, returns a mutable slice referencing the underlying child table
    // (each element is Option<Head>). If the head is a leaf an empty slice
    // is returned.
    //
    // The caller receives a &mut slice tied to the borrow of `self` and may
    // reorder entries in-place (e.g., sort_unstable) and then take them using
    // `Option::take()` to extract Head values. The call uses `body_mut()` so
    // COW semantics are preserved and callers have exclusive access to the
    // branch storage while the mutable borrow lasts.
    // NOTE: mut_children removed — prefer matching on BodyRef returned by
    // `body_mut()` and operating directly on the `&mut Branch` reference.

    /// Remove a matching leaf. A detached heap leaf is returned without being
    /// dropped; archive-local leaves are dropped immediately while the enclosing
    /// PATCH owner cover is still installed. Their backing owner is retired
    /// separately at the public mutation boundary if the root empties.
    #[must_use = "drop the retired heap leaf only after the replacement root is committed"]
    pub(crate) fn remove_leaf(
        slot: &mut Option<Self>,
        leaf_key: &[u8; KEY_LEN],
        start_depth: usize,
    ) -> Option<Self> {
        if let Some(this) = slot {
            let end_depth = std::cmp::min(this.end_depth(), KEY_LEN);
            // Check reachable equality by asking the head to test the prefix
            // up to its end_depth. Using the head/leaf primitive centralises the
            // unsafe deref into Branch::childleaf()/Leaf::has_prefix.
            if !this.has_prefix::<KEY_LEN>(start_depth, leaf_key) {
                return None;
            }
            match this.tag() {
                HeadTag::Leaf => {
                    // Keep the removed value alive until every ancestor has
                    // repaired its aggregates and collapsed any unary branch.
                    slot.take()
                }
                HeadTag::LocalLeaf => {
                    // A LocalLeaf owns no allocation itself. Remove its Head
                    // while the PATCH-level owner cover still guards the raw
                    // bytes; never let a naked LocalLeaf escape as retirement.
                    drop(slot.take());
                    None
                }
                _ => {
                    let mut retired_leaf = None;
                    let mut ed = crate::patch::branch::BranchMut::from_head(this);
                    let key = leaf_key[end_depth];
                    ed.modify_child(key, |mut opt| {
                        retired_leaf = Self::remove_leaf(&mut opt, leaf_key, end_depth);
                        opt
                    });

                    // If the branch now contains a single remaining child we
                    // collapse the branch upward into that child. We must pull
                    // the remaining child out while `ed` is still borrowed,
                    // then drop `ed` before writing back into `slot` to avoid
                    // double mutable borrows of the slot.
                    let occupied_children = ed.child_table.iter().flatten().take(2).count();
                    if occupied_children == 0 {
                        drop(ed);
                        drop(slot.take());
                    } else if occupied_children == 1 {
                        let mut remaining: Option<Head<KEY_LEN, O, V, H>> = None;
                        for slot_child in &mut ed.child_table {
                            if let Some(child) = slot_child.take() {
                                remaining = Some(child.with_start(start_depth));
                                break;
                            }
                        }
                        drop(ed);
                        if let Some(child) = remaining {
                            slot.replace(child);
                        }
                    } else {
                        // Ensure the editor commits the final pointer into the
                        // head when the branch does not collapse.
                        drop(ed);
                    }
                    retired_leaf
                }
            }
        } else {
            None
        }
    }

    // NOTE: slot-level wrappers removed; callers should take the slot and call
    // the owned helpers (insert_leaf / replace_leaf / union)
    // directly. This reduces the indirection and keeps ownership semantics
    // explicit at the call site.

    // Owned variants of the slot-based helpers. These accept the existing
    // Head by value and return the new Head after performing the
    // modification. They are used with the split `insert_child` /
    // `update_child` APIs so we no longer need `Branch::upsert_child`.
    pub(crate) fn insert_leaf(mut this: Self, leaf: Self, start_depth: usize) -> Self {
        if let Some((depth, this_byte_key, leaf_byte_key)) =
            this.first_divergence(&leaf, start_depth)
        {
            let old_key = this.key();
            let new_body = crate::patch::branch::Branch::new(
                depth,
                this.with_key(this_byte_key),
                leaf.with_key(leaf_byte_key),
            );
            return Head::new(old_key, new_body);
        }

        let end_depth = this.end_depth();
        if end_depth != KEY_LEN {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut this);
            let inserted = leaf.with_start(ed.end_depth as usize);
            let key = inserted.key();
            ed.modify_child(key, |opt| match opt {
                Some(old) => Some(Head::insert_leaf(old, inserted, end_depth)),
                None => Some(inserted),
            });
        }
        this
    }
}

// Archive-aware insertion path, available only when V = ().
impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, H: PatchHash> Head<KEY_LEN, O, (), H> {
    /// Inserts a LocalLeaf whose hash was already computed by ArchiveEntry.
    /// The enclosing PATCH retains the leaf's owner independently of trie
    /// shape, so LocalLeaves can use the ordinary structural operations.
    pub(crate) fn insert_archive_leaf(
        mut this: Self,
        leaf: Self,
        leaf_hash: H::Digest,
        start_depth: usize,
    ) -> Self {
        if let Some((depth, this_byte_key, leaf_byte_key)) =
            this.first_divergence(&leaf, start_depth)
        {
            let old_key = this.key();
            let new_body = crate::patch::branch::Branch::new_with_rchild_hash(
                depth,
                this.with_key(this_byte_key),
                leaf.with_key(leaf_byte_key),
                leaf_hash,
            );
            return Head::new(old_key, new_body);
        }

        let end_depth = this.end_depth();
        if end_depth != KEY_LEN {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut this);
            let inserted = leaf.with_start(ed.end_depth as usize);
            let key = inserted.key();
            ed.modify_child_with_inserted_hint(key, leaf_hash, |opt| match opt {
                None => Some(inserted),
                Some(old) => Some(Head::insert_archive_leaf(
                    old, inserted, leaf_hash, end_depth,
                )),
            });
        }
        this
    }
}

// Resume generic-V `Head` impl for the remaining methods (replace_leaf,
// union, intersect, query operations, etc.) which don't care about V
// shape and so remain in the V-generic impl block.
impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Head<KEY_LEN, O, V, H> {
    /// Replace the matching leaf while deferring reclamation of the old leaf.
    ///
    /// The returned retirement slot must be dropped only after the caller has
    /// published the returned head. `V::drop` is arbitrary user code and may
    /// panic; running it from inside a [`BranchMut`] edit would expose a taken
    /// child slot and stale aggregates if the panic were caught.
    pub(crate) fn replace_leaf(
        mut this: Self,
        leaf: Self,
        start_depth: usize,
    ) -> (Self, Option<Self>) {
        if let Some((depth, this_byte_key, leaf_byte_key)) =
            this.first_divergence(&leaf, start_depth)
        {
            let old_key = this.key();
            let new_body = Branch::new(
                depth,
                this.with_key(this_byte_key),
                leaf.with_key(leaf_byte_key),
            );

            return (Head::new(old_key, new_body), None);
        }

        let end_depth = this.end_depth();
        if end_depth == KEY_LEN {
            let old_key = this.key();
            return (leaf.with_key(old_key), Some(this));
        } else {
            // Use the editor view for branch mutation instead of raw pointer ops.
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut this);
            let inserted = leaf.with_start(ed.end_depth as usize);
            let key = inserted.key();
            let mut retired = None;
            ed.modify_child(key, |opt| match opt {
                Some(old) => {
                    let (replacement, old_leaf) = Head::replace_leaf(old, inserted, end_depth);
                    retired = old_leaf;
                    Some(replacement)
                }
                None => Some(inserted),
            });
            drop(ed);
            return (this, retired);
        }
    }

    /// Sequential PATCH-trie union. Always serial; the parallel
    /// dispatch lives in [`Self::par_union`] which calls back into
    /// `union` once budget is exhausted.
    pub(crate) fn union(mut this: Self, mut other: Self, at_depth: usize) -> Self {
        // An archive-backed singleton has no cached fingerprint. Decide its
        // exact identity first; a distinct union then hashes each child once
        // and carries those hashes into the new Branch.
        if this.is_archive_singleton_pair(&other) {
            if let Some((depth, this_byte_key, other_byte_key)) =
                this.first_divergence(&other, at_depth)
            {
                let this_hash = this.hash();
                let other_hash = other.hash();
                let old_key = this.key();
                let new_body = Branch::new_with_child_hashes(
                    depth,
                    this.with_key(this_byte_key),
                    other.with_key(other_byte_key),
                    this_hash,
                    other_hash,
                );
                return Head::new(old_key, new_body);
            }
            return this;
        }

        if this.local_leaf_cardinality_allows_equality(&other) && this.hash() == other.hash() {
            return this;
        }

        if let Some((depth, this_byte_key, other_byte_key)) =
            this.first_divergence(&other, at_depth)
        {
            let old_key = this.key();
            let new_body = Branch::new(
                depth,
                this.with_key(this_byte_key),
                other.with_key(other_byte_key),
            );

            return Head::new(old_key, new_body);
        }

        let this_depth = this.end_depth();
        let other_depth = other.end_depth();
        if this_depth < other_depth {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut this);
            let inserted = other.with_start(ed.end_depth as usize);
            let key = inserted.key();
            ed.modify_child(key, |opt| match opt {
                Some(old) => Some(Head::union(old, inserted, this_depth)),
                None => Some(inserted),
            });
            drop(ed);
            return this;
        }

        if other_depth < this_depth {
            let old_key = this.key();
            let this_head = this;
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut other);
            let inserted = this_head.with_start(ed.end_depth as usize);
            let key = inserted.key();
            ed.modify_child(key, |opt| match opt {
                Some(old) => Some(Head::union(old, inserted, other_depth)),
                None => Some(inserted),
            });
            drop(ed);
            return other.with_key(old_key);
        }

        // Equal depth, hashes differ → walk `other`'s children,
        // resolving collisions via recursive `Head::union` and the
        // `modify_child`'s per-call accounting.
        //
        // Union is commutative; mutating either side in place is
        // semantically equivalent. Swap when `other`'s child_table
        // is at least 2× larger than `this`'s — start with the
        // bigger capacity so cuckoo grows are mostly avoided during
        // insert. Branch tags encode `log2(child_table_size)`, so
        // the 2× ratio reduces to `other_tag > this_tag` (no body
        // deref needed; the tag bits live in the head's pointer).
        if other.tag() > this.tag() {
            std::mem::swap(&mut this, &mut other);
        }
        let BodyMut::Branch(other_branch_ref) = other.body_mut() else {
            unreachable!();
        };
        let mut ed = crate::patch::branch::BranchMut::from_head(&mut this);
        for other_child in other_branch_ref
            .child_table
            .iter_mut()
            .filter_map(Option::take)
        {
            let inserted = other_child.with_start(ed.end_depth as usize);
            let key = inserted.key();
            ed.modify_child(key, |opt| match opt {
                Some(old) => Some(Head::union(old, inserted, this_depth)),
                None => Some(inserted),
            });
        }
        drop(ed);
        this
    }

    /// Parallel-aware top-level union entry. Allocates a fresh
    /// [`parallel_union::ParUnionCtx`] with a budget of
    /// `num_threads²` shared spawns, then delegates to
    /// [`Self::par_union_with_ctx`]. The budget persists across the
    /// entire recursive descent — once exhausted, the rest is
    /// sequential.
    #[cfg(feature = "parallel")]
    pub(crate) fn par_union(this: Self, other: Self, at_depth: usize) -> Self
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        let ctx = parallel_union::ParUnionCtx::new();
        Self::par_union_with_ctx(this, other, at_depth, &ctx)
    }

    /// Recursive parallel-aware union: at the equal-depth-branch
    /// arm, drains the "both" pairs and, for each pair, either
    /// claims a budget unit and spawns a parallel task or falls
    /// back to serial `Self::union`. All other arms (hash-equal,
    /// divergence, asymmetric depth) delegate to `Self::union` —
    /// they don't generate fan-out work for the budget to spend.
    #[cfg(feature = "parallel")]
    pub(crate) fn par_union_with_ctx(
        mut this: Self,
        mut other: Self,
        at_depth: usize,
        ctx: &parallel_union::ParUnionCtx,
    ) -> Self
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        // Singleton pairs have no fan-out work for Rayon.
        if this.is_archive_singleton_pair(&other) {
            return Self::union(this, other, at_depth);
        }

        if this.local_leaf_cardinality_allows_equality(&other) && this.hash() == other.hash() {
            return this;
        }

        if let Some((depth, this_byte_key, other_byte_key)) =
            this.first_divergence(&other, at_depth)
        {
            let old_key = this.key();
            let new_body = Branch::new(
                depth,
                this.with_key(this_byte_key),
                other.with_key(other_byte_key),
            );
            return Head::new(old_key, new_body);
        }

        let this_depth = this.end_depth();
        let other_depth = other.end_depth();
        if this_depth != other_depth {
            // Asymmetric — no fan-out opportunity, serial path wins.
            return Self::union(this, other, at_depth);
        }

        // Equal depth, hashes differ → branch merge. Swap when
        // `other`'s child_table is ≥2× `this`'s so the in-place
        // target starts with the bigger capacity (fewer cuckoo
        // grows when scattering children back via
        // `install_child_growing`). Branch tags encode
        // `log2(child_table_size)`, so the 2× ratio reduces to
        // `other_tag > this_tag` — single byte compare from the
        // head pointer, no body deref / CoW risk.
        if other.tag() > this.tag() {
            std::mem::swap(&mut this, &mut other);
        }

        // Threshold check via `body_ref` (no CoW); fall back to
        // serial when the source side is too small to amortise the
        // scatter machinery.
        let small = match other.body_ref() {
            BodyRef::Branch(b) => (b.leaf_count as usize) < PARALLEL_PATCH_UNION_THRESHOLD,
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => unreachable!(),
        };
        if small {
            return Self::union(this, other, at_depth);
        }

        let BodyMut::Branch(other_branch_ref) = other.body_mut() else {
            unreachable!();
        };

        {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut this);
            let end_depth = ed.end_depth as usize;

            // Scatter both child tables into key-indexed 256-slot
            // arrays + present bitsets. The bitset partition tells us
            // which keys need a recursive union ("both") vs which are
            // simple pass-throughs ("only").
            let mut this_arr: [Option<Head<KEY_LEN, O, V, H>>; 256] = std::array::from_fn(|_| None);
            let mut other_arr: [Option<Head<KEY_LEN, O, V, H>>; 256] =
                std::array::from_fn(|_| None);
            let mut this_present = crate::patch::bytetable::ByteSet::new_empty();
            let mut other_present = crate::patch::bytetable::ByteSet::new_empty();

            for slot in ed.child_table.iter_mut() {
                if let Some(head) = slot.take() {
                    let key = head.key();
                    this_present.insert(key);
                    this_arr[key as usize] = Some(head);
                }
            }
            for slot in other_branch_ref.child_table.iter_mut() {
                if let Some(head) = slot.take() {
                    let head = head.with_start(end_depth);
                    let key = head.key();
                    other_present.insert(key);
                    other_arr[key as usize] = Some(head);
                }
            }

            let mut both = this_present.intersect(&other_present);
            let mut only = this_present.symmetric_difference(&other_present);

            // Pre-allocated scatter-write target. Each spawned task
            // writes to `resolved[k]` for its specific key byte —
            // disjoint by construction. The raw pointer wrapper
            // (`ScatterPtr`) makes the cross-thread sharing explicit.
            let mut resolved: [Option<Head<KEY_LEN, O, V, H>>; 256] = std::array::from_fn(|_| None);
            let resolved_ptr = parallel_union::ScatterPtr(resolved.as_mut_ptr());

            rayon::scope(|s| {
                // Drain `both` pairs serially in the parent; per
                // pair, either claim a spawn unit and dispatch as a
                // task, or run serially via `Head::union` here on
                // the parent thread. The atomic budget is shared
                // with all nested `par_union_with_ctx` calls.
                while let Some(k) = both.drain_next_ascending() {
                    let i = k as usize;
                    let t = this_arr[i].take().expect("both ⇒ this");
                    let o = other_arr[i].take().expect("both ⇒ other");
                    if ctx.try_claim() {
                        s.spawn(move |_| {
                            let head = Self::par_union_with_ctx(t, o, this_depth, ctx);
                            // SAFETY: each task has a distinct
                            // key `k`, so the writes to
                            // `resolved[i]` are non-aliasing.
                            unsafe {
                                resolved_ptr.write_at(i, Some(head));
                            }
                        });
                    } else {
                        // Budget exhausted — fall back to fully
                        // serial union on this pair, then scatter
                        // the result. SAFETY: same disjointness
                        // invariant; the parent thread races only
                        // with tasks targeting distinct keys.
                        let head = Self::union(t, o, this_depth);
                        unsafe {
                            resolved_ptr.write_at(i, Some(head));
                        }
                    }
                }
            });
            // After scope: all spawned tasks have completed; the
            // scatter writes to `resolved` are all sequenced-before
            // here by rayon's join semantics.

            for slot in resolved.iter_mut() {
                if let Some(head) = slot.take() {
                    ed.install_child_growing(head);
                }
            }
            while let Some(k) = only.drain_next_ascending() {
                let i = k as usize;
                let head = this_arr[i]
                    .take()
                    .or_else(|| other_arr[i].take())
                    .expect("only ⇒ exactly one side");
                ed.install_child_growing(head);
            }

            ed.recompute_aggregates();
        }
        this
    }

    /// Parallel-aware top-level intersect entry. Allocates a fresh
    /// [`parallel_union::ParUnionCtx`] (shared budget across the
    /// descent) and delegates to [`Self::par_intersect_with_ctx`].
    /// Intersect builds a fresh tree, so there is no in-place
    /// target — the parallel work is purely "compute per-pair
    /// intersections in parallel, then collect into a new Branch."
    #[cfg(feature = "parallel")]
    pub(crate) fn par_intersect(&self, other: &Self, at_depth: usize) -> Option<Self>
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        let ctx = parallel_union::ParUnionCtx::new();
        self.par_intersect_with_ctx(other, at_depth, &ctx)
    }

    /// Recursive parallel-aware intersect. At the equal-depth-branch
    /// arm, scatter-spawns one task per matching `(self_child,
    /// other_child)` pair (under budget), then collects results
    /// into a fresh `Branch`. Hash-equal / divergence / asymmetric-
    /// depth arms delegate to serial [`Self::intersect`] — they
    /// don't generate fan-out work.
    #[cfg(feature = "parallel")]
    pub(crate) fn par_intersect_with_ctx(
        &self,
        other: &Self,
        at_depth: usize,
        ctx: &parallel_union::ParUnionCtx,
    ) -> Option<Self>
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        if self.is_archive_singleton_pair(other) {
            return self.intersect(other, at_depth);
        }
        if self.local_leaf_cardinality_allows_equality(other) && self.hash() == other.hash() {
            return Some(self.clone());
        }
        if self.first_divergence(other, at_depth).is_some() {
            return None;
        }
        let self_depth = self.end_depth();
        let other_depth = other.end_depth();
        if self_depth != other_depth {
            return self.intersect(other, at_depth);
        }

        let BodyRef::Branch(self_branch) = self.body_ref() else {
            unreachable!();
        };
        let BodyRef::Branch(other_branch) = other.body_ref() else {
            unreachable!();
        };

        // Intersect work is bounded by the smaller side — pairs only
        // exist where keys appear in both branches.
        let min_leaves = self_branch.leaf_count.min(other_branch.leaf_count) as usize;
        if min_leaves < PARALLEL_PATCH_UNION_THRESHOLD {
            return self.intersect(other, at_depth);
        }

        let mut resolved: [Option<Head<KEY_LEN, O, V, H>>; 256] = std::array::from_fn(|_| None);
        let resolved_ptr = parallel_union::ScatterPtr(resolved.as_mut_ptr());

        // `in_place_scope` runs the outer closure on the calling
        // thread (no `Send` bound), which lets us hold `&Branch`
        // borrows across the spawn loop. `Branch` is `!Sync` due
        // to its raw `*const Leaf` pointer field, so a regular
        // `rayon::scope` would reject the captures.
        rayon::in_place_scope(|s| {
            for slot in self_branch.child_table.iter() {
                let Some(self_child) = slot.as_ref() else {
                    continue;
                };
                let key = self_child.key();
                let Some(other_child) = other_branch.child_table.table_get(key) else {
                    continue;
                };

                if ctx.try_claim() {
                    s.spawn(move |_| {
                        let result =
                            self_child.par_intersect_with_ctx(other_child, self_depth, ctx);
                        // SAFETY: distinct keys → disjoint slots.
                        unsafe {
                            resolved_ptr.write_at(key as usize, result);
                        }
                    });
                } else {
                    let result = self_child.intersect(other_child, self_depth);
                    unsafe {
                        resolved_ptr.write_at(key as usize, result);
                    }
                }
            }
        });

        // Collect non-None results into a fresh Branch. Stick with
        // per-key `modify_child` here — intersect's collection
        // phase typically has FEW children (heavy filtering kept
        // only the matching subset), so the per-call aggregate
        // updates beat the fixed `recompute_aggregates` cost. Bench
        // sanity-checked: install+recompute regressed intersect
        // +18% on the 4M/50%-overlap dataset.
        let mut iter = resolved.into_iter().flatten();
        let first = iter.next()?;
        let Some(second) = iter.next() else {
            return Some(first);
        };
        let new_branch = Branch::new(
            self_depth,
            first.with_start(self_depth),
            second.with_start(self_depth),
        );
        let mut head_for_branch = Head::new(0, new_branch);
        {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut head_for_branch);
            for child in iter {
                let inserted = child.with_start(self_depth);
                let k = inserted.key();
                ed.modify_child(k, |_opt| Some(inserted));
            }
        }
        Some(head_for_branch)
    }

    /// Parallel-aware top-level difference entry. Allocates a fresh
    /// [`parallel_union::ParUnionCtx`] and delegates to
    /// [`Self::par_difference_with_ctx`].
    #[cfg(feature = "parallel")]
    pub(crate) fn par_difference(&self, other: &Self, at_depth: usize) -> Option<Self>
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        let ctx = parallel_union::ParUnionCtx::new();
        self.par_difference_with_ctx(other, at_depth, &ctx)
    }

    /// Recursive parallel-aware difference. Same scatter-and-spawn
    /// shape as `par_intersect_with_ctx`, plus the "no match in
    /// other" branch where we clone `self_child` unchanged into
    /// the resolved array (no recursive work).
    #[cfg(feature = "parallel")]
    pub(crate) fn par_difference_with_ctx(
        &self,
        other: &Self,
        at_depth: usize,
        ctx: &parallel_union::ParUnionCtx,
    ) -> Option<Self>
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        if self.is_archive_singleton_pair(other) {
            return self.difference(other, at_depth);
        }
        if self.local_leaf_cardinality_allows_equality(other) && self.hash() == other.hash() {
            return None;
        }
        if self.first_divergence(other, at_depth).is_some() {
            return Some(self.clone());
        }
        let self_depth = self.end_depth();
        let other_depth = other.end_depth();
        if self_depth != other_depth {
            return self.difference(other, at_depth);
        }

        let BodyRef::Branch(self_branch) = self.body_ref() else {
            unreachable!();
        };
        let BodyRef::Branch(other_branch) = other.body_ref() else {
            unreachable!();
        };

        // Difference work is bounded by `self` (every key in self is
        // either kept or filtered against other).
        if (self_branch.leaf_count as usize) < PARALLEL_PATCH_UNION_THRESHOLD {
            return self.difference(other, at_depth);
        }

        let mut resolved: [Option<Head<KEY_LEN, O, V, H>>; 256] = std::array::from_fn(|_| None);
        let resolved_ptr = parallel_union::ScatterPtr(resolved.as_mut_ptr());

        // See `par_intersect_with_ctx` for why this is
        // `in_place_scope` rather than `scope`.
        rayon::in_place_scope(|s| {
            for slot in self_branch.child_table.iter() {
                let Some(self_child) = slot.as_ref() else {
                    continue;
                };
                let key = self_child.key();

                match other_branch.child_table.table_get(key) {
                    Some(other_child) => {
                        if ctx.try_claim() {
                            s.spawn(move |_| {
                                let result = self_child.par_difference_with_ctx(
                                    other_child,
                                    self_depth,
                                    ctx,
                                );
                                unsafe {
                                    resolved_ptr.write_at(key as usize, result);
                                }
                            });
                        } else {
                            let result = self_child.difference(other_child, self_depth);
                            unsafe {
                                resolved_ptr.write_at(key as usize, result);
                            }
                        }
                    }
                    None => {
                        // No match in other ⇒ keep `self_child`
                        // unchanged. Clone is cheap (Arc-style rc
                        // bump on Branch, leaf is small).
                        let cloned = self_child.clone();
                        unsafe {
                            resolved_ptr.write_at(key as usize, Some(cloned));
                        }
                    }
                }
            }
        });

        // Collect non-None results into a fresh Branch. Difference's
        // collection phase typically has MANY children (most keys
        // in `self` survive — only matching+empty subtrees get
        // filtered), so `install_child_growing` + one
        // `recompute_aggregates` pass wins handily over per-call
        // `modify_child`. Mirror of the union pattern; intersect
        // uses `modify_child` because its collection phase has
        // far fewer children (heavy filtering).
        let mut iter = resolved.into_iter().flatten();
        let first = iter.next()?;
        let Some(second) = iter.next() else {
            return Some(first);
        };
        let new_branch = Branch::new(
            self_depth,
            first.with_start(self_depth),
            second.with_start(self_depth),
        );
        let mut head_for_branch = Head::new(0, new_branch);
        {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut head_for_branch);
            for child in iter {
                ed.install_child_growing(child.with_start(self_depth));
            }
            ed.recompute_aggregates();
        }
        Some(head_for_branch)
    }

    pub(crate) fn infixes<const PREFIX_LEN: usize, const INFIX_LEN: usize, F>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        at_depth: usize,
        f: &mut F,
    ) where
        F: FnMut(&[u8; INFIX_LEN]),
    {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => leaf.infixes::<PREFIX_LEN, INFIX_LEN, O, F>(prefix, at_depth, f),
            BodyRef::LocalLeaf(bytes) => {
                leaf::key_ops::infixes::<KEY_LEN, PREFIX_LEN, INFIX_LEN, O, F>(
                    bytes, prefix, at_depth, f,
                )
            }
            BodyRef::Branch(branch) => {
                branch.infixes::<PREFIX_LEN, INFIX_LEN, F>(prefix, at_depth, f)
            }
        }
    }

    pub(crate) fn infixes_range<const PREFIX_LEN: usize, const INFIX_LEN: usize, F>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        at_depth: usize,
        min_infix: &[u8; INFIX_LEN],
        max_infix: &[u8; INFIX_LEN],
        f: &mut F,
    ) where
        F: FnMut(&[u8; INFIX_LEN]),
    {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => leaf.infixes_range::<PREFIX_LEN, INFIX_LEN, O, F>(
                prefix, at_depth, min_infix, max_infix, f,
            ),
            BodyRef::LocalLeaf(bytes) => {
                leaf::key_ops::infixes_range::<KEY_LEN, PREFIX_LEN, INFIX_LEN, O, F>(
                    bytes, prefix, at_depth, min_infix, max_infix, f,
                )
            }
            BodyRef::Branch(branch) => branch.infixes_range::<PREFIX_LEN, INFIX_LEN, F>(
                prefix, at_depth, min_infix, max_infix, f,
            ),
        }
    }

    pub(crate) fn first_infix_range<const PREFIX_LEN: usize, const INFIX_LEN: usize>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        at_depth: usize,
        min_infix: &[u8; INFIX_LEN],
        max_infix: &[u8; INFIX_LEN],
    ) -> Option<[u8; INFIX_LEN]> {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => leaf.first_infix_range::<PREFIX_LEN, INFIX_LEN, O>(
                prefix, at_depth, min_infix, max_infix,
            ),
            BodyRef::LocalLeaf(bytes) => {
                leaf::key_ops::first_infix_range::<KEY_LEN, PREFIX_LEN, INFIX_LEN, O>(
                    bytes, prefix, at_depth, min_infix, max_infix,
                )
            }
            BodyRef::Branch(branch) => branch
                .first_infix_range::<PREFIX_LEN, INFIX_LEN>(prefix, at_depth, min_infix, max_infix),
        }
    }

    pub(crate) fn count_range<const PREFIX_LEN: usize, const INFIX_LEN: usize>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        at_depth: usize,
        min_infix: &[u8; INFIX_LEN],
        max_infix: &[u8; INFIX_LEN],
    ) -> u64 {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => {
                leaf.count_range::<PREFIX_LEN, INFIX_LEN, O>(prefix, at_depth, min_infix, max_infix)
            }
            BodyRef::LocalLeaf(bytes) => {
                leaf::key_ops::count_range::<KEY_LEN, PREFIX_LEN, INFIX_LEN, O>(
                    bytes, prefix, at_depth, min_infix, max_infix,
                )
            }
            BodyRef::Branch(branch) => {
                branch.count_range::<PREFIX_LEN, INFIX_LEN>(prefix, at_depth, min_infix, max_infix)
            }
        }
    }

    pub(crate) fn has_prefix<const PREFIX_LEN: usize>(
        &self,
        at_depth: usize,
        prefix: &[u8; PREFIX_LEN],
    ) -> bool {
        const {
            assert!(PREFIX_LEN <= KEY_LEN);
        }
        match self.body_ref() {
            BodyRef::Leaf(leaf) => leaf.has_prefix::<O>(at_depth, prefix),
            BodyRef::LocalLeaf(bytes) => {
                leaf::key_ops::has_prefix::<KEY_LEN, O>(bytes, at_depth, prefix)
            }
            BodyRef::Branch(branch) => branch.has_prefix::<PREFIX_LEN>(at_depth, prefix),
        }
    }

    pub(crate) fn traversal_depth<const PREFIX_LEN: usize>(
        &self,
        at_depth: usize,
        prefix: &[u8; PREFIX_LEN],
    ) -> usize {
        const {
            assert!(PREFIX_LEN <= KEY_LEN);
        }
        match self.body_ref() {
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => 1,
            BodyRef::Branch(branch) => branch.traversal_depth::<PREFIX_LEN>(at_depth, prefix),
        }
    }

    pub(crate) fn get<'a>(&'a self, at_depth: usize, key: &[u8; KEY_LEN]) -> Option<&'a V>
    where
        O: 'a,
    {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => leaf.get::<O>(at_depth, key),
            BodyRef::LocalLeaf(bytes) => {
                if !leaf::key_ops::matches::<KEY_LEN, O>(bytes, at_depth, key) {
                    return None;
                }
                // SAFETY: LocalLeaf is only constructed by the SimpleArchive
                // ingestion path (step 3), which constrains the PATCH to
                // `V = ()`. The `Option<&V>` here therefore points at a
                // zero-sized value; a static `()` provides the address.
                // For non-`()` V this branch is unreachable today, and
                // construction will refuse such PATCHes once step 3 lands.
                // The type-system invariant will eventually be enforced
                // via a `LocalLeafSupported: V` trait constraint at
                // `Head::new_local_leaf` callers.
                static UNIT: () = ();
                let unit_ref: &V = unsafe {
                    debug_assert_eq!(std::mem::size_of::<V>(), 0, "LocalLeaf requires V = ()");
                    &*(&UNIT as *const () as *const V)
                };
                Some(unit_ref)
            }
            BodyRef::Branch(branch) => branch.get(at_depth, key),
        }
    }

    pub(crate) fn segmented_len<const PREFIX_LEN: usize>(
        &self,
        at_depth: usize,
        prefix: &[u8; PREFIX_LEN],
    ) -> u64 {
        match self.body_ref() {
            BodyRef::Leaf(leaf) => leaf.segmented_len::<O, PREFIX_LEN>(at_depth, prefix),
            BodyRef::LocalLeaf(bytes) => {
                leaf::key_ops::segmented_len::<KEY_LEN, PREFIX_LEN, O>(bytes, at_depth, prefix)
            }
            BodyRef::Branch(branch) => branch.segmented_len::<PREFIX_LEN>(at_depth, prefix),
        }
    }

    /// Locate the shallowest subtree whose keys all share `prefix`.
    ///
    /// Unlike composing [`Self::segmented_len`] with [`Self::infixes`], this
    /// returns the already-located head so a caller can inspect its cached
    /// segment count and then enumerate that same subtree without descending
    /// the fixed prefix a second time.
    fn locate_prefix<const PREFIX_LEN: usize>(
        &self,
        at_depth: usize,
        prefix: &[u8; PREFIX_LEN],
    ) -> Option<&Self> {
        let node_end_depth = self.end_depth();
        let limit = std::cmp::min(PREFIX_LEN, node_end_depth);
        if !leaf::key_ops::has_prefix::<KEY_LEN, O>(
            self.childleaf_key(),
            at_depth,
            &prefix[..limit],
        ) {
            return None;
        }
        if PREFIX_LEN <= node_end_depth {
            return Some(self);
        }
        let BodyRef::Branch(branch) = self.body_ref() else {
            unreachable!("a leaf always covers the complete key");
        };
        branch
            .child_table
            .table_get(prefix[node_end_depth])
            .and_then(|child| child.locate_prefix(node_end_depth, prefix))
    }

    /// Enumerate a whole infix segment after `prefix` has already been
    /// matched for every key below this head.
    fn infixes_from_matched_prefix<const PREFIX_LEN: usize, const INFIX_LEN: usize, F>(
        &self,
        for_each: &mut F,
    ) where
        F: FnMut(&[u8; INFIX_LEN]),
    {
        if PREFIX_LEN + INFIX_LEN <= self.end_depth() {
            let infix: [u8; INFIX_LEN] =
                core::array::from_fn(|i| self.childleaf_key()[O::TREE_TO_KEY[PREFIX_LEN + i]]);
            for_each(&infix);
            return;
        }

        let BodyRef::Branch(branch) = self.body_ref() else {
            unreachable!("a leaf always covers the complete key");
        };
        for child in branch.child_table.iter().flatten() {
            child.infixes_from_matched_prefix::<PREFIX_LEN, INFIX_LEN, F>(for_each);
        }
    }

    /// Diagnostic: accumulate (branch nodes, total child-table slots,
    /// heap-`Leaf` nodes, `LocalLeaf` slots) over the subtree. Used to
    /// decompose a PATCH's *structural* byte size (vs resident RSS).
    /// `branches` × the policy-specific branch header + `slots` × 8 is the
    /// branch allocation total; heap leaves add one `Leaf` node each.
    pub(crate) fn node_stats(&self, acc: &mut (u64, u64, u64, u64)) {
        match self.body_ref() {
            BodyRef::Leaf(_) => acc.2 += 1,
            BodyRef::LocalLeaf(_) => acc.3 += 1,
            BodyRef::Branch(branch) => {
                acc.0 += 1;
                acc.1 += branch.child_table.len() as u64;
                for child in branch.child_table.iter().flatten() {
                    child.node_stats(acc);
                }
            }
        }
    }

    /// Per-end-depth branch census: `hist[d] = (branch_count, filled_children)`
    /// for branches whose branching point is at byte-depth `d`. Reveals where
    /// the branches sit and their fanout — the input to the HOT/variable-width
    /// densification question.
    pub(crate) fn branch_hist(&self, hist: &mut [(u64, u64); 65]) {
        if let BodyRef::Branch(branch) = self.body_ref() {
            let d = self.end_depth().min(64);
            let fanout = branch.child_table.iter().flatten().count() as u64;
            hist[d].0 += 1;
            hist[d].1 += fanout;
            for child in branch.child_table.iter().flatten() {
                child.branch_hist(hist);
            }
        }
    }

    /// Per-fanout branch census: `hist[f] = branch_count` for branches with
    /// exactly `f` filled children.
    pub(crate) fn branch_fanout_hist(&self, hist: &mut [u64; 257]) {
        if let BodyRef::Branch(branch) = self.body_ref() {
            let fanout = branch.child_table.iter().flatten().count();
            hist[fanout.min(256)] += 1;
            for child in branch.child_table.iter().flatten() {
                child.branch_fanout_hist(hist);
            }
        }
    }

    // NOTE: slot-level union wrapper removed; callers should take the slot and
    // call the owned helper `union` directly.

    pub(crate) fn intersect(&self, other: &Self, at_depth: usize) -> Option<Self> {
        if self.is_archive_singleton_pair(other) {
            return if self.first_divergence(other, at_depth).is_none() {
                Some(self.clone())
            } else {
                None
            };
        }

        if self.local_leaf_cardinality_allows_equality(other) && self.hash() == other.hash() {
            return Some(self.clone());
        }

        if self.first_divergence(other, at_depth).is_some() {
            return None;
        }

        let self_depth = self.end_depth();
        let other_depth = other.end_depth();
        if self_depth < other_depth {
            // This means that there can be at most one child in self
            // that might intersect with other.
            let BodyRef::Branch(branch) = self.body_ref() else {
                unreachable!();
            };
            return branch
                .child_table
                .table_get(other.childleaf_key()[O::TREE_TO_KEY[self_depth]])
                .and_then(|self_child| other.intersect(self_child, self_depth));
        }

        if other_depth < self_depth {
            // This means that there can be at most one child in other
            // that might intersect with self.
            // If the depth of other is less than the depth of self, then it can't be a leaf.
            let BodyRef::Branch(other_branch) = other.body_ref() else {
                unreachable!();
            };
            return other_branch
                .child_table
                .table_get(self.childleaf_key()[O::TREE_TO_KEY[other_depth]])
                .and_then(|other_child| self.intersect(other_child, other_depth));
        }

        // If we reached this point then the depths are equal. The only way to have a leaf
        // is if the other is a leaf as well, which is already handled by the hash check if they are equal,
        // and by the key check if they are not equal.
        // If one of them is a leaf and the other is a branch, then they would also have different depths,
        // which is already handled by the above code.
        let BodyRef::Branch(self_branch) = self.body_ref() else {
            unreachable!();
        };
        let BodyRef::Branch(other_branch) = other.body_ref() else {
            unreachable!();
        };

        let mut intersected_children = self_branch
            .child_table
            .iter()
            .filter_map(Option::as_ref)
            .filter_map(|self_child| {
                let other_child = other_branch.child_table.table_get(self_child.key())?;
                self_child.intersect(other_child, self_depth)
            });
        let first_child = intersected_children.next()?;
        let Some(second_child) = intersected_children.next() else {
            return Some(first_child);
        };
        let new_branch = Branch::new(
            self_depth,
            first_child.with_start(self_depth),
            second_child.with_start(self_depth),
        );
        // Use a BranchMut editor to perform all child insertions via the
        // safe editor API instead of manipulating the NonNull pointer
        // directly. The editor will perform COW and commit the final
        // pointer into the Head when it is dropped.
        let mut head_for_branch = Head::new(0, new_branch);
        {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut head_for_branch);
            for child in intersected_children {
                let inserted = child.with_start(self_depth);
                let k = inserted.key();
                ed.modify_child(k, |_opt| Some(inserted));
            }
            // ed dropped here commits the final branch pointer into head_for_branch
        }
        Some(head_for_branch)
    }

    /// Returns the difference between self and other.
    /// This is the set of elements that are in self but not in other.
    /// If the difference is empty, None is returned.
    pub(crate) fn difference(&self, other: &Self, at_depth: usize) -> Option<Self> {
        if self.is_archive_singleton_pair(other) {
            return if self.first_divergence(other, at_depth).is_none() {
                None
            } else {
                Some(self.clone())
            };
        }

        if self.local_leaf_cardinality_allows_equality(other) && self.hash() == other.hash() {
            return None;
        }

        if self.first_divergence(other, at_depth).is_some() {
            return Some(self.clone());
        }

        let self_depth = self.end_depth();
        let other_depth = other.end_depth();
        if self_depth < other_depth {
            // This means that there can be at most one child in self
            // that might intersect with other. It's the only child that may not be in the difference.
            // The other children are definitely in the difference, as they have no corresponding byte in other.
            // Thus the cheapest way to compute the difference is compute the difference of the only child
            // that might intersect with other, copy self with it's correctly filled byte table, then
            // remove the old child, and insert the new child.
            let mut new_branch = self.clone();
            let other_byte_key = other.childleaf_key()[O::TREE_TO_KEY[self_depth]];
            {
                let mut ed = crate::patch::branch::BranchMut::from_head(&mut new_branch);
                ed.modify_child(other_byte_key, |opt| {
                    opt.and_then(|child| child.difference(other, self_depth))
                });

                // The asymmetric edit can delete the only matching child
                // subtree. Preserve the compressed-trie invariant instead of
                // returning a Branch with zero or one child.
                let child_count = ed
                    .child_table
                    .iter()
                    .filter(|child| child.is_some())
                    .take(2)
                    .count();
                if child_count <= 1 {
                    let mut remaining = None;
                    for slot in &mut ed.child_table {
                        if let Some(child) = slot.take() {
                            remaining = Some(child.with_start(at_depth));
                            break;
                        }
                    }
                    drop(ed);
                    return remaining;
                }
            }
            return Some(new_branch);
        }

        if other_depth < self_depth {
            // This means that we need to check if there is a child in other
            // that matches the path at the current depth of self.
            // There is no such child, then then self must be in the difference.
            // If there is such a child, then we have to compute the difference
            // between self and that child.
            // We know that other must be a branch.
            let BodyRef::Branch(other_branch) = other.body_ref() else {
                unreachable!();
            };
            let self_byte_key = self.childleaf_key()[O::TREE_TO_KEY[other_depth]];
            if let Some(other_child) = other_branch.child_table.table_get(self_byte_key) {
                return self.difference(other_child, at_depth);
            } else {
                return Some(self.clone());
            }
        }

        // If we reached this point then the depths are equal. The only way to have a leaf
        // is if the other is a leaf as well, which is already handled by the hash check if they are equal,
        // and by the key check if they are not equal.
        // If one of them is a leaf and the other is a branch, then they would also have different depths,
        // which is already handled by the above code.
        let BodyRef::Branch(self_branch) = self.body_ref() else {
            unreachable!();
        };
        let BodyRef::Branch(other_branch) = other.body_ref() else {
            unreachable!();
        };

        let mut differenced_children = self_branch
            .child_table
            .iter()
            .filter_map(Option::as_ref)
            .filter_map(|self_child| {
                if let Some(other_child) = other_branch.child_table.table_get(self_child.key()) {
                    self_child.difference(other_child, self_depth)
                } else {
                    Some(self_child.clone())
                }
            });

        let first_child = differenced_children.next()?;
        let second_child = match differenced_children.next() {
            Some(sc) => sc,
            None => return Some(first_child),
        };

        let new_branch = Branch::new(
            self_depth,
            first_child.with_start(self_depth),
            second_child.with_start(self_depth),
        );
        let mut head_for_branch = Head::new(0, new_branch);
        {
            let mut ed = crate::patch::branch::BranchMut::from_head(&mut head_for_branch);
            for child in differenced_children {
                let inserted = child.with_start(self_depth);
                let k = inserted.key();
                ed.modify_child(k, |_opt| Some(inserted));
            }
            // ed dropped here commits the final branch pointer into head_for_branch
        }
        // The key will be set later, because we don't know it yet.
        // The difference might remove multiple levels of branches,
        // so we can't just take the key from self or other.
        Some(head_for_branch)
    }

    /// Set inclusion between the keys under this head and under `other`:
    /// `Equal` for the same keys, `Less` for a strict subset, `Greater` for a
    /// strict superset, `None` when neither contains the other.
    ///
    /// The same walk as [`Self::difference`], constructing nothing: a shared
    /// subtree is settled by its hash, and a key one side lacks decides the
    /// direction the moment it is met.
    pub(crate) fn inclusion(&self, other: &Self, at_depth: usize) -> Option<Ordering> {
        if self.is_archive_singleton_pair(other) {
            return self
                .first_divergence(other, at_depth)
                .is_none()
                .then_some(Ordering::Equal);
        }

        if self.local_leaf_cardinality_allows_equality(other) && self.hash() == other.hash() {
            return Some(Ordering::Equal);
        }

        if self.first_divergence(other, at_depth).is_some() {
            // Two non-empty sets on divergent prefixes share no key.
            return None;
        }

        let self_depth = self.end_depth();
        let other_depth = other.end_depth();
        if self_depth < other_depth {
            // Self branches at a byte every key of other shares, so other
            // lies under one child of self, if anywhere, and self has more.
            let BodyRef::Branch(self_branch) = self.body_ref() else {
                unreachable!();
            };
            let other_byte_key = other.childleaf_key()[O::TREE_TO_KEY[self_depth]];
            return match self_branch.child_table.table_get(other_byte_key) {
                Some(self_child) => match self_child.inclusion(other, at_depth) {
                    Some(Ordering::Equal | Ordering::Greater) => Some(Ordering::Greater),
                    _ => None,
                },
                None => None,
            };
        }

        if other_depth < self_depth {
            let BodyRef::Branch(other_branch) = other.body_ref() else {
                unreachable!();
            };
            let self_byte_key = self.childleaf_key()[O::TREE_TO_KEY[other_depth]];
            return match other_branch.child_table.table_get(self_byte_key) {
                Some(other_child) => match self.inclusion(other_child, at_depth) {
                    Some(Ordering::Equal | Ordering::Less) => Some(Ordering::Less),
                    _ => None,
                },
                None => None,
            };
        }

        // Equal depths: both are branches, because a leaf pair is settled
        // above by the hash when equal and by the divergence when not. The
        // order is the meet over the children at each byte: a child only
        // self has says Greater, one only other has says Less, and a shared
        // byte says what its subtrees say.
        let BodyRef::Branch(self_branch) = self.body_ref() else {
            unreachable!();
        };
        let BodyRef::Branch(other_branch) = other.body_ref() else {
            unreachable!();
        };
        let mut order = Some(Ordering::Equal);
        for self_child in self_branch.child_table.iter().filter_map(Option::as_ref) {
            let child_order = match other_branch.child_table.table_get(self_child.key()) {
                Some(other_child) => self_child.inclusion(other_child, self_depth),
                None => Some(Ordering::Greater),
            };
            order = meet(order, child_order)?;
        }
        for other_child in other_branch.child_table.iter().filter_map(Option::as_ref) {
            if self_branch.child_table.table_get(other_child.key()).is_none() {
                order = meet(order, Some(Ordering::Less))?;
            }
        }
        order
    }
}

/// Combine the inclusion of two disjoint parts: equal parts do not move it,
/// two parts leaning the same way keep leaning, and two parts leaning
/// opposite ways make the wholes incomparable.
fn meet(left: Option<Ordering>, right: Option<Ordering>) -> Option<Option<Ordering>> {
    match (left?, right?) {
        (Ordering::Equal, order) | (order, Ordering::Equal) => Some(Some(order)),
        (Ordering::Less, Ordering::Less) => Some(Some(Ordering::Less)),
        (Ordering::Greater, Ordering::Greater) => Some(Some(Ordering::Greater)),
        _ => None,
    }
}

unsafe impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> ByteEntry
    for Head<KEY_LEN, O, V, H>
{
    fn key(&self) -> u8 {
        self.key()
    }
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> fmt::Debug
    for Head<KEY_LEN, O, V, H>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.tag().fmt(f)
    }
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Clone
    for Head<KEY_LEN, O, V, H>
{
    fn clone(&self) -> Self {
        unsafe {
            match self.body() {
                BodyPtr::Leaf(leaf) => Self::new(self.key(), Leaf::rc_inc(leaf)),
                BodyPtr::LocalLeaf(ptr) => {
                    // LocalLeaf has no refcount. Its enclosing PATCH snapshots
                    // clone the root owner set alongside the tagged pointer.
                    Self::new_local_leaf(self.key(), ptr)
                }
                BodyPtr::Branch(branch) => Self::new(self.key(), Branch::rc_inc(branch)),
            }
        }
    }
}

// The Slot wrapper was removed in favor of using BranchMut::from_slot(&mut
// Option<Head<...>>) directly. This keeps the API surface smaller and
// avoids an extra helper type that simply forwarded to BranchMut.

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Drop for Head<KEY_LEN, O, V, H> {
    fn drop(&mut self) {
        unsafe {
            match self.body() {
                BodyPtr::Leaf(leaf) => Leaf::rc_dec(leaf),
                BodyPtr::LocalLeaf(_) => {
                    // No-op: LocalLeaf bytes are retained by the enclosing
                    // PATCH's root owner set, not refcounted per leaf.
                }
                BodyPtr::Branch(branch) => Branch::rc_dec(branch),
            }
        }
    }
}

/// A PATCH is a persistent data structure that stores a set of keys.
/// Each key can be reordered and segmented, based on the provided key ordering and segmentation.
///
/// The patch supports efficient set operations, like union, intersection, and difference,
/// because it efficiently maintains a hash for all keys that are part of a sub-tree.
///
/// The tree itself is a path- and node-compressed a 256-ary trie.
/// Each nodes stores its children in a byte oriented cuckoo hash table,
/// allowing for O(1) access to children, while keeping the memory overhead low.
/// Table sizes are powers of two, starting at 2.
///
/// Having a single node type for all branching factors simplifies the implementation,
/// compared to other adaptive trie implementations, like ARTs or Judy Arrays
///
/// The PATCH allows for cheap copy-on-write operations, with `clone` being O(1).
/// Its persistent snapshots can share leaves, so a PATCH is `Send + Sync` only
/// when its associated value is also both `Send` and `Sync`.
///
/// A value that is neither thread-safe cannot make a PATCH thread-safe:
///
/// ```compile_fail
/// use std::rc::Rc;
/// use triblespace_core::patch::{IdentitySchema, PATCH};
///
/// fn assert_send_sync<T: Send + Sync>() {}
/// assert_send_sync::<PATCH<1, IdentitySchema, Rc<()>>>();
/// ```
///
/// `Cell<u64>` is `Send` but not `Sync`. Rejecting this case is important:
/// moving one PATCH snapshot can leave another snapshot reading the same leaf
/// on its original thread.
///
/// ```compile_fail
/// use std::cell::Cell;
/// use triblespace_core::patch::{IdentitySchema, PATCH};
///
/// fn assert_send<T: Send>() {}
/// assert_send::<PATCH<1, IdentitySchema, Cell<u64>>>();
/// ```
#[derive(Debug)]
pub struct PATCH<const KEY_LEN: usize, O = IdentitySchema, V = (), H = XorSip128>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    // Field order is deliberate: Heads drop before the owner cover.
    root: Option<Head<KEY_LEN, O, V, H>>,
    /// Deduplicated conservative lifetime cover for every LocalLeaf anywhere
    /// below `root`. Set operations may retain provenance no longer reachable
    /// from the result, but never duplicate an owner or omit a reachable one.
    /// This thin Arc adds eight bytes per PATCH while removing sixteen bytes
    /// from every Branch.
    owners: Option<Arc<OwnerCover>>,
}

/// A prefix-located PATCH infix traversal whose exact cardinality has already
/// been proved to fit a caller-supplied bound.
///
/// The view borrows the located trie head, so [`Self::for_each`] starts at that
/// same subtree and never repeats the fixed-prefix descent.
#[must_use = "call for_each to enumerate the bounded infixes"]
pub struct PATCHBoundedInfixes<
    'a,
    const KEY_LEN: usize,
    const PREFIX_LEN: usize,
    const INFIX_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    located: Option<&'a Head<KEY_LEN, O, V, H>>,
    count: u64,
}

/// Opaque borrow of one logical node in a canonical BLAKE3 PATCH trie.
///
/// The view exposes reconciliation data, never PATCH's tagged pointers,
/// branches, or physical cuckoo-table layout. It is available only for
/// [`IdentitySchema`], so [`Self::prefix`] and [`Self::representative`] are
/// canonical raw-key bytes rather than a schema-specific tree permutation.
/// Values do not participate in PATCH identity and are intentionally absent.
pub struct PATCHMerkleNode<'a, const KEY_LEN: usize, V> {
    head: &'a Head<KEY_LEN, IdentitySchema, V, Blake3Merkle>,
}

impl<const KEY_LEN: usize, V> Copy for PATCHMerkleNode<'_, KEY_LEN, V> {}

impl<const KEY_LEN: usize, V> Clone for PATCHMerkleNode<'_, KEY_LEN, V> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, const KEY_LEN: usize, V> PATCHMerkleNode<'a, KEY_LEN, V> {
    fn new(head: &'a Head<KEY_LEN, IdentitySchema, V, Blake3Merkle>) -> Self {
        Self { head }
    }

    /// Canonical digest of this logical subtree.
    pub fn digest(&self) -> [u8; 32] {
        self.head.hash()
    }

    /// Exact number of leaves below this node.
    ///
    /// Branch digests commit to this count. A leaf digest canonically denotes
    /// one complete key, so its count is necessarily one.
    pub fn leaf_count(&self) -> u64 {
        self.head.count()
    }

    /// First raw-key depth not shared by every key below this node.
    ///
    /// Leaves return `KEY_LEN`. For branches, the byte at `end_depth` selects
    /// one of [`Self::children`].
    pub fn end_depth(&self) -> usize {
        self.head.end_depth()
    }

    /// Lexicographically first complete raw key below this node.
    ///
    /// PATCH's internal representative pointer is merely a routing witness
    /// and may depend on construction history. This accessor instead follows
    /// the smallest logical edge at each branch, making the public result
    /// canonical without exposing or changing that hot-path field.
    pub fn representative(&self) -> &'a [u8; KEY_LEN] {
        let mut node = self.head;
        loop {
            match node.body_ref() {
                BodyRef::Leaf(leaf) => return &leaf.key,
                BodyRef::LocalLeaf(key) => return key,
                BodyRef::Branch(branch) => {
                    node = branch
                        .child_table
                        .iter()
                        .flatten()
                        .min_by_key(|child| child.key())
                        .expect("a PATCH branch has at least two children");
                }
            }
        }
    }

    /// Canonical raw-key prefix naming this logical node.
    ///
    /// A lookup prefix may end inside a compressed path. In that case the
    /// returned node's canonical prefix is longer than the requested prefix.
    pub fn prefix(&self) -> &'a [u8] {
        &self.representative()[..self.end_depth()]
    }

    /// Whether this node is a single complete key.
    pub fn is_leaf(&self) -> bool {
        self.end_depth() == KEY_LEN
    }

    /// Iterate over logical children in ascending edge-byte order.
    pub fn children(&self) -> PATCHMerkleChildren<'a, KEY_LEN, V> {
        PATCHMerkleChildren::new(*self)
    }

    /// Iterate over at most `limit` keys in this subtree, strictly after
    /// `after`, in canonical raw-key order.
    ///
    /// The cursor is a complete key, not an implementation node token. It
    /// need not exist in the PATCH. Keys are copied out so neither associated
    /// values nor archive-backed leaf lifetimes escape this borrow. A zero
    /// limit is explicitly empty and performs no traversal.
    pub fn items_after(
        &self,
        after: Option<&[u8; KEY_LEN]>,
        limit: usize,
    ) -> PATCHMerkleItems<'a, KEY_LEN, V> {
        PATCHMerkleItems::new(*self, after.copied(), limit)
    }

    fn may_contain_after(&self, after: &[u8; KEY_LEN]) -> bool {
        let end_depth = self.end_depth();
        self.representative()[..end_depth] >= after[..end_depth]
    }
}

impl<const KEY_LEN: usize, V> core::fmt::Debug for PATCHMerkleNode<'_, KEY_LEN, V> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PATCHMerkleNode")
            .field("prefix", &self.prefix())
            .field("digest", &self.digest())
            .field("leaf_count", &self.leaf_count())
            .field("end_depth", &self.end_depth())
            .field("representative", self.representative())
            .finish()
    }
}

/// Ascending logical children of a [`PATCHMerkleNode`].
///
/// The iterator contains at most 256 edges regardless of the physical branch
/// allocation. Its fields are private so the cuckoo representation remains an
/// implementation detail.
pub struct PATCHMerkleChildren<'a, const KEY_LEN: usize, V> {
    node: Option<PATCHMerkleNode<'a, KEY_LEN, V>>,
    edges: ByteSet,
}

impl<'a, const KEY_LEN: usize, V> PATCHMerkleChildren<'a, KEY_LEN, V> {
    fn new(node: PATCHMerkleNode<'a, KEY_LEN, V>) -> Self {
        let mut edges = ByteSet::new_empty();
        if let BodyRef::Branch(branch) = node.head.body_ref() {
            for child in branch.child_table.iter().flatten() {
                edges.insert(child.key());
            }
        }
        Self {
            node: (!node.is_leaf()).then_some(node),
            edges,
        }
    }
}

impl<'a, const KEY_LEN: usize, V> Iterator for PATCHMerkleChildren<'a, KEY_LEN, V> {
    type Item = (u8, PATCHMerkleNode<'a, KEY_LEN, V>);

    fn next(&mut self) -> Option<Self::Item> {
        let edge = self.edges.drain_next_ascending()?;
        let node = self.node.expect("a child edge requires a branch node");
        let BodyRef::Branch(branch) = node.head.body_ref() else {
            unreachable!("a leaf cannot carry child edges");
        };
        let child = branch
            .child_table
            .table_get(edge)
            .expect("an enumerated PATCH child remains present");
        Some((edge, PATCHMerkleNode::new(child)))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.edges.popcount() as usize;
        (remaining, Some(remaining))
    }
}

impl<const KEY_LEN: usize, V> ExactSizeIterator for PATCHMerkleChildren<'_, KEY_LEN, V> {}
impl<const KEY_LEN: usize, V> std::iter::FusedIterator for PATCHMerkleChildren<'_, KEY_LEN, V> {}

/// Bounded canonical key page below one [`PATCHMerkleNode`].
///
/// Earlier subtrees are rejected from their compressed raw-key prefix rather
/// than scanned leaf-by-leaf. The traversal stack grows only with trie depth;
/// each frame contains a fixed 256-bit edge set.
pub struct PATCHMerkleItems<'a, const KEY_LEN: usize, V> {
    pending: Option<PATCHMerkleNode<'a, KEY_LEN, V>>,
    stack: Vec<PATCHMerkleChildren<'a, KEY_LEN, V>>,
    after: Option<[u8; KEY_LEN]>,
    remaining: usize,
}

impl<'a, const KEY_LEN: usize, V> PATCHMerkleItems<'a, KEY_LEN, V> {
    fn new(
        node: PATCHMerkleNode<'a, KEY_LEN, V>,
        after: Option<[u8; KEY_LEN]>,
        limit: usize,
    ) -> Self {
        Self {
            pending: (limit != 0).then_some(node),
            stack: Vec::new(),
            after,
            remaining: limit,
        }
    }

    fn next_node(&mut self) -> Option<PATCHMerkleNode<'a, KEY_LEN, V>> {
        if let Some(node) = self.pending.take() {
            return Some(node);
        }
        loop {
            let children = self.stack.last_mut()?;
            if let Some((_, node)) = children.next() {
                return Some(node);
            }
            self.stack.pop();
        }
    }
}

impl<'a, const KEY_LEN: usize, V> Iterator for PATCHMerkleItems<'a, KEY_LEN, V> {
    type Item = [u8; KEY_LEN];

    fn next(&mut self) -> Option<Self::Item> {
        while self.remaining != 0 {
            let node = self.next_node()?;
            if self
                .after
                .as_ref()
                .is_some_and(|after| !node.may_contain_after(after))
            {
                continue;
            }
            if node.is_leaf() {
                let key = *node.representative();
                if self.after.as_ref().is_some_and(|after| key <= *after) {
                    continue;
                }
                self.remaining -= 1;
                return Some(key);
            }
            self.stack.push(node.children());
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.remaining))
    }
}

impl<const KEY_LEN: usize, V> std::iter::FusedIterator for PATCHMerkleItems<'_, KEY_LEN, V> {}

impl<
        'a,
        const KEY_LEN: usize,
        const PREFIX_LEN: usize,
        const INFIX_LEN: usize,
        O: KeySchema<KEY_LEN>,
        V,
        H: PatchHash,
    > PATCHBoundedInfixes<'a, KEY_LEN, PREFIX_LEN, INFIX_LEN, O, V, H>
{
    /// Exact number of distinct infixes this view will emit.
    pub fn len(&self) -> u64 {
        self.count
    }

    /// Whether this bounded traversal has no matching infixes.
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Enumerate the already-located subtree in the same callback order as
    /// [`PATCH::infixes`].
    pub fn for_each<F>(self, mut for_each: F)
    where
        F: FnMut(&[u8; INFIX_LEN]),
    {
        if let Some(located) = self.located {
            located.infixes_from_matched_prefix::<PREFIX_LEN, INFIX_LEN, F>(&mut for_each);
        }
    }
}

impl<const KEY_LEN: usize, O, V, H> Clone for PATCH<KEY_LEN, O, V, H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    fn clone(&self) -> Self {
        Self {
            root: self.root.clone(),
            owners: self.owners.clone(),
        }
    }
}

impl<const KEY_LEN: usize, O, V, H> Default for PATCH<KEY_LEN, O, V, H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<const KEY_LEN: usize, O, V, H> PATCH<KEY_LEN, O, V, H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    /// Creates a new empty PATCH.
    pub fn new() -> Self {
        H::init();
        PATCH {
            root: None,
            owners: None,
        }
    }

    /// Inserts a shared key into the PATCH.
    ///
    /// Takes an [Entry] object that can be created from a key,
    /// and inserted into multiple PATCH instances.
    ///
    /// If the key is already present, this is a no-op.
    pub fn insert(&mut self, entry: &Entry<KEY_LEN, V, H>) {
        if self.root.is_some() {
            let this = self.root.take().expect("root should not be empty");
            let new_head = Head::insert_leaf(this, entry.leaf(), 0);
            self.root.replace(new_head);
        } else {
            self.root.replace(entry.leaf());
        }
        self.debug_check_owner_invariant();
    }

    /// Inserts a key into the PATCH, replacing the value if it already exists.
    ///
    /// If the replaced value's destructor panics, the replacement is already
    /// fully committed when the panic is raised.
    pub fn replace(&mut self, entry: &Entry<KEY_LEN, V, H>) {
        let retired_leaf = if self.root.is_some() {
            let this = self.root.take().expect("root should not be empty");
            let (new_head, retired_leaf) = Head::replace_leaf(this, entry.leaf(), 0);
            self.root.replace(new_head);
            retired_leaf
        } else {
            self.root.replace(entry.leaf());
            None
        };
        self.debug_check_owner_invariant();

        // Deliberately last: replacement may release the final shared
        // reference to user-owned `V`, whose destructor may panic.
        drop(retired_leaf);
    }

    /// Removes a key from the PATCH.
    ///
    /// `key` is expressed in this PATCH's tree ordering. A key in the shared
    /// key ordering must first be converted with [`KeySchema::tree_ordered`].
    ///
    /// If the key is not present, this is a no-op.
    /// If a removed value or final archive owner's destructor panics, the
    /// removal is already fully committed when the panic is raised.
    pub fn remove(&mut self, key: &[u8; KEY_LEN]) {
        let retired_leaf = Head::remove_leaf(&mut self.root, key, 0);
        let retired_owners = if self.root.is_none() {
            self.owners.take()
        } else {
            None
        };
        self.debug_check_owner_invariant();

        // Deliberately last: owner and value reclamation may execute arbitrary
        // user Drop implementations, so every observable PATCH field and
        // structural invariant must already describe the committed result.
        drop(retired_owners);
        drop(retired_leaf);
    }

    /// Returns the number of keys in the PATCH.
    pub fn len(&self) -> u64 {
        if let Some(root) = &self.root {
            root.count()
        } else {
            0
        }
    }

    /// Diagnostic structural census: returns
    /// `(branch_nodes, child_table_slots, heap_leaf_nodes, local_leaf_slots)`.
    /// Structural branch bytes ≈ `branches * Self::branch_header_bytes() + slots * 8`;
    /// heap leaves add a `Leaf` node each (the key is shared across the six
    /// orderings, so count it once per trible, not once per ordering).
    pub fn node_stats(&self) -> (u64, u64, u64, u64) {
        let mut acc = (0u64, 0u64, 0u64, 0u64);
        if let Some(root) = &self.root {
            root.node_stats(&mut acc);
        }
        acc
    }

    #[cfg(debug_assertions)]
    fn debug_check_owner_invariant(&self) {
        debug_assert!(
            self.root.as_ref().map(|root| root.tag()) != Some(HeadTag::LocalLeaf)
                || self.owners.is_some(),
            "a root LocalLeaf must retain its archive owner",
        );
    }

    #[cfg(not(debug_assertions))]
    #[inline]
    fn debug_check_owner_invariant(&self) {}

    /// Returns the total capacity of all branch child tables.
    ///
    /// This counts allocated table slots (`child_table.len()`), not filled
    /// children.
    pub fn total_table_slots(&self) -> u64 {
        self.node_stats().1
    }

    /// Fixed branch header bytes, excluding the trailing child table.
    pub fn branch_header_bytes() -> usize {
        std::mem::size_of::<Branch<KEY_LEN, O, [Option<Head<KEY_LEN, O, V, H>>; 0], V, H>>()
    }

    /// Per-end-depth `(branch_count, filled_children)` histogram (65 buckets,
    /// byte-depths 0..=64), for analysing trie shape — where branches sit and
    /// their fanout distribution.
    pub fn branch_histogram(&self) -> [(u64, u64); 65] {
        let mut hist = [(0u64, 0u64); 65];
        if let Some(root) = &self.root {
            root.branch_hist(&mut hist);
        }
        hist
    }

    /// Per-fanout branch census: returns `hist[f] = branch_count` for each
    /// exact fanout `0..=256`.
    pub fn branch_fanout_histogram(&self) -> [u64; 257] {
        let mut hist = [0u64; 257];
        if let Some(root) = &self.root {
            root.branch_fanout_hist(&mut hist);
        }
        hist
    }

    /// Test-only root ownership receipt and LocalLeaf count.
    #[cfg(test)]
    pub(crate) fn archive_owner_guard_stats(&self) -> (bool, u64) {
        (self.owners.is_some(), self.node_stats().3)
    }

    /// Returns true if the PATCH contains no keys.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Return PATCH's internal root summary.
    ///
    /// The default policy's value is crate-private deliberately. Public cache
    /// keys must pass through [`blind_root_hash`] so callers cannot observe
    /// chosen leaf-hash vectors and exploit its XOR maintenance law.
    pub(crate) fn root_hash(&self) -> Option<H::Digest> {
        self.root.as_ref().map(|root| root.hash())
    }

    /// Whether two snapshots still share the same persistent root allocation.
    ///
    /// This is a lineage-local invalidation primitive, not semantic equality
    /// and not a portable version. Clones share the root; every key or attached
    /// value mutation copy-on-writes it, even when the key-only fingerprint is
    /// unchanged by replacing a value.
    pub(crate) fn shares_root(&self, other: &Self) -> bool {
        match (&self.root, &other.root) {
            (None, None) => true,
            (Some(left), Some(right)) => left.tptr == right.tptr,
            _ => false,
        }
    }

    /// Whether the complete subtree under `prefix` is structurally shared.
    ///
    /// The prefix is in tree order and may end inside a compressed path or a
    /// segment. Two absent prefixes are shared; present prefixes require the
    /// same node body and kind, not equal counts or key-set fingerprints. An
    /// unrelated insertion may re-key that body's incoming edge without
    /// changing its contents, so the edge byte is not part of this comparison.
    ///
    /// Like [`Self::shares_root`], this is conservative, lineage-local
    /// invalidation evidence, not semantic equality or a portable version.
    /// Key changes and attached-value replacements through PATCH are observed;
    /// interior mutations of an attached value are outside this contract.
    pub(crate) fn shares_prefix<const PREFIX_LEN: usize>(
        &self,
        other: &Self,
        prefix: &[u8; PREFIX_LEN],
    ) -> bool {
        const {
            assert!(PREFIX_LEN <= KEY_LEN);
        }
        let left = self
            .root
            .as_ref()
            .and_then(|root| root.locate_prefix(0, prefix));
        let right = other
            .root
            .as_ref()
            .and_then(|root| root.locate_prefix(0, prefix));
        match (left, right) {
            (None, None) => true,
            (Some(left), Some(right)) => {
                let mask = !(Head::<KEY_LEN, O, V, H>::KEY_MASK as usize);
                (left.tptr.as_ptr().addr() & mask) == (right.tptr.as_ptr().addr() & mask)
            }
            _ => false,
        }
    }

    /// Clone the opaque archive-owner receipt without exposing the root Head.
    pub(crate) fn owner_guard(&self) -> PATCHOwnerGuard {
        PATCHOwnerGuard(self.owners.clone())
    }

    /// Whether this PATCH and another PATCH share one owner-cover Arc.
    pub(crate) fn shares_owner_guard<OO, VV, HH>(&self, other: &PATCH<KEY_LEN, OO, VV, HH>) -> bool
    where
        OO: KeySchema<KEY_LEN>,
        HH: PatchHash,
    {
        match (&self.owners, &other.owners) {
            (None, None) => true,
            (Some(left), Some(right)) => Arc::ptr_eq(left, right),
            _ => false,
        }
    }

    /// Whether `owner` is the most recently adopted member of this cover.
    pub(crate) fn owner_guard_latest_is(&self, owner: &Arc<dyn ArchiveOwner>) -> bool {
        self.owners
            .as_ref()
            .is_some_and(|cover| cover.latest_address == OwnerCover::address(owner))
    }

    /// Install an owner cover proved to be a conservative superset of this
    /// PATCH's current receipt. Empty PATCHes may retain a receipt so all
    /// indexes of an aggregate can share one Arc.
    ///
    /// # Safety
    ///
    /// `guard` must retain every archive allocation retained by the current
    /// owner cover. Violating this can leave a LocalLeaf dangling.
    pub(crate) unsafe fn set_owner_guard(&mut self, guard: &PATCHOwnerGuard) {
        #[cfg(debug_assertions)]
        debug_assert!(
            guard.covers(&self.owners),
            "a PATCH owner guard may only be replaced by an owner-cover superset",
        );
        let already_installed = match (&self.owners, &guard.0) {
            (None, None) => true,
            (Some(current), Some(replacement)) => Arc::ptr_eq(current, replacement),
            _ => false,
        };
        if !already_installed {
            self.owners = guard.0.clone();
        }
        self.debug_check_owner_invariant();
    }

    /// Returns the value associated with `key` if present.
    pub fn get(&self, key: &[u8; KEY_LEN]) -> Option<&V> {
        self.root.as_ref().and_then(|root| root.get(0, key))
    }

    /// Allows iteratig over all infixes of a given length with a given prefix.
    /// Each infix is passed to the provided closure.
    ///
    /// The entire operation is performed over the tree view ordering of the keys.
    ///
    /// The length of the prefix and the infix is provided as type parameters,
    /// but will usually inferred from the arguments.
    ///
    /// The sum of `PREFIX_LEN` and `INFIX_LEN` must be less than or equal to `KEY_LEN`
    /// or a compile-time assertion will fail.
    ///
    /// Because all infixes are iterated in one go, less bookkeeping is required,
    /// than when using an Iterator, allowing for better performance.
    pub fn infixes<const PREFIX_LEN: usize, const INFIX_LEN: usize, F>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        mut for_each: F,
    ) where
        F: FnMut(&[u8; INFIX_LEN]),
    {
        const {
            assert!(PREFIX_LEN + INFIX_LEN <= KEY_LEN);
        }
        assert!(
            O::same_segment_tree(PREFIX_LEN, PREFIX_LEN + INFIX_LEN - 1)
                && (PREFIX_LEN + INFIX_LEN == KEY_LEN
                    || !O::same_segment_tree(PREFIX_LEN + INFIX_LEN - 1, PREFIX_LEN + INFIX_LEN)),
            "INFIX_LEN must cover a whole segment"
        );
        if let Some(root) = &self.root {
            root.infixes(prefix, 0, &mut for_each);
        }
    }

    /// Locate all distinct infixes for `prefix` only when their exact count is
    /// at most `limit`.
    ///
    /// `Some(view)` is an all-or-nothing proof that [`PATCHBoundedInfixes::len`]
    /// infixes fit the bound; [`PATCHBoundedInfixes::for_each`] then enumerates
    /// every one from the already-located subtree. `None` means the cached
    /// segment count exceeded `limit`. A missing prefix is a successful empty
    /// view.
    ///
    /// Locating the view costs `O(prefix depth)`. Visiting it costs
    /// `O(count)`, where `count <= limit`, so paged callers retain a hard
    /// geometric work bound while reserving output storage from the exact
    /// count before enumeration.
    pub fn bounded_infixes<const PREFIX_LEN: usize, const INFIX_LEN: usize>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        limit: u64,
    ) -> Option<PATCHBoundedInfixes<'_, KEY_LEN, PREFIX_LEN, INFIX_LEN, O, V, H>> {
        const {
            assert!(PREFIX_LEN + INFIX_LEN <= KEY_LEN);
        }
        assert!(
            O::same_segment_tree(PREFIX_LEN, PREFIX_LEN + INFIX_LEN - 1)
                && (PREFIX_LEN + INFIX_LEN == KEY_LEN
                    || !O::same_segment_tree(PREFIX_LEN + INFIX_LEN - 1, PREFIX_LEN + INFIX_LEN)),
            "INFIX_LEN must cover a whole segment"
        );
        const {
            if PREFIX_LEN > 0 && PREFIX_LEN < KEY_LEN {
                assert!(
                    <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                        [O::TREE_TO_KEY[PREFIX_LEN - 1]]
                        != <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                            [O::TREE_TO_KEY[PREFIX_LEN]],
                    "PREFIX_LEN must align to segment boundary",
                );
            }
        }

        let Some(root) = &self.root else {
            return Some(PATCHBoundedInfixes {
                located: None,
                count: 0,
            });
        };
        let Some(located) = root.locate_prefix(0, prefix) else {
            return Some(PATCHBoundedInfixes {
                located: None,
                count: 0,
            });
        };
        let count = located.count_segment(PREFIX_LEN);
        if count > limit {
            return None;
        }
        Some(PATCHBoundedInfixes {
            located: Some(located),
            count,
        })
    }

    /// Like [`infixes`](Self::infixes) but only yields infixes in the
    /// byte range `[min_infix, max_infix]` (inclusive).
    ///
    /// The trie is pruned at each depth: branches whose byte key falls
    /// outside the range at the current infix position are skipped
    /// entirely, avoiding traversal of irrelevant subtrees.
    pub fn infixes_range<const PREFIX_LEN: usize, const INFIX_LEN: usize, F>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        min_infix: &[u8; INFIX_LEN],
        max_infix: &[u8; INFIX_LEN],
        mut for_each: F,
    ) where
        F: FnMut(&[u8; INFIX_LEN]),
    {
        const {
            assert!(PREFIX_LEN + INFIX_LEN <= KEY_LEN);
        }
        assert!(
            O::same_segment_tree(PREFIX_LEN, PREFIX_LEN + INFIX_LEN - 1)
                && (PREFIX_LEN + INFIX_LEN == KEY_LEN
                    || !O::same_segment_tree(PREFIX_LEN + INFIX_LEN - 1, PREFIX_LEN + INFIX_LEN)),
            "INFIX_LEN must cover a whole segment"
        );
        if let Some(root) = &self.root {
            root.infixes_range(prefix, 0, min_infix, max_infix, &mut for_each);
        }
    }

    /// Return the lexicographically first distinct infix in the inclusive
    /// range `[min_infix, max_infix]` for `prefix`.
    ///
    /// This performs ordered lower-bound descent through the PATCH trie. It
    /// does not depend on the physical cuckoo-table order and does not
    /// materialize or sort the matching infixes.
    pub fn first_infix_range<const PREFIX_LEN: usize, const INFIX_LEN: usize>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        min_infix: &[u8; INFIX_LEN],
        max_infix: &[u8; INFIX_LEN],
    ) -> Option<[u8; INFIX_LEN]> {
        const {
            assert!(PREFIX_LEN + INFIX_LEN <= KEY_LEN);
        }
        assert!(
            O::same_segment_tree(PREFIX_LEN, PREFIX_LEN + INFIX_LEN - 1)
                && (PREFIX_LEN + INFIX_LEN == KEY_LEN
                    || !O::same_segment_tree(PREFIX_LEN + INFIX_LEN - 1, PREFIX_LEN + INFIX_LEN)),
            "INFIX_LEN must cover a whole segment"
        );
        if min_infix > max_infix {
            return None;
        }
        self.root
            .as_ref()
            .and_then(|root| root.first_infix_range(prefix, 0, min_infix, max_infix))
    }

    /// Return the first distinct infix strictly after `after`, bounded above
    /// by `max_infix` (inclusive).
    ///
    /// The successor is computed in lexicographic byte order and then passed
    /// to [`Self::first_infix_range`]. `None` is returned when `after` is the
    /// all-`0xff` value or when no later infix exists.
    pub fn next_infix_after<const PREFIX_LEN: usize, const INFIX_LEN: usize>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        after: &[u8; INFIX_LEN],
        max_infix: &[u8; INFIX_LEN],
    ) -> Option<[u8; INFIX_LEN]> {
        let mut lower = *after;
        let mut cursor = INFIX_LEN;
        loop {
            if cursor == 0 {
                return None;
            }
            cursor -= 1;
            if lower[cursor] != u8::MAX {
                lower[cursor] += 1;
                for byte in &mut lower[cursor + 1..] {
                    *byte = u8::MIN;
                }
                break;
            }
        }
        self.first_infix_range(prefix, &lower, max_infix)
    }

    /// Count entries whose infix falls within [min_infix, max_infix].
    ///
    /// Uses cached `leaf_count` on branches to skip entire subtrees that
    /// are fully inside the range, making the count O(boundary_nodes)
    /// rather than O(matching_leaves).
    pub fn count_range<const PREFIX_LEN: usize, const INFIX_LEN: usize>(
        &self,
        prefix: &[u8; PREFIX_LEN],
        min_infix: &[u8; INFIX_LEN],
        max_infix: &[u8; INFIX_LEN],
    ) -> u64 {
        const {
            assert!(PREFIX_LEN + INFIX_LEN <= KEY_LEN);
        }
        match &self.root {
            Some(root) => root.count_range(prefix, 0, min_infix, max_infix),
            None => 0,
        }
    }

    /// Returns true if the PATCH has a key with the given prefix.
    ///
    /// `PREFIX_LEN` must be less than or equal to `KEY_LEN` or a compile-time
    /// assertion will fail.
    pub fn has_prefix<const PREFIX_LEN: usize>(&self, prefix: &[u8; PREFIX_LEN]) -> bool {
        const {
            assert!(PREFIX_LEN <= KEY_LEN);
        }
        if let Some(root) = &self.root {
            root.has_prefix(0, prefix)
        } else {
            PREFIX_LEN == 0
        }
    }

    /// Returns the number of PATCH nodes inspected by a prefix lookup.
    ///
    /// This is a diagnostic companion to [`PATCH::has_prefix`]. A miss counts
    /// the node where the mismatch or missing child is discovered; an empty
    /// PATCH reports zero.
    pub fn traversal_depth<const PREFIX_LEN: usize>(&self, prefix: &[u8; PREFIX_LEN]) -> usize {
        const {
            assert!(PREFIX_LEN <= KEY_LEN);
        }
        self.root
            .as_ref()
            .map(|root| root.traversal_depth(0, prefix))
            .unwrap_or(0)
    }

    /// Returns the number of unique segments in keys with the given prefix.
    pub fn segmented_len<const PREFIX_LEN: usize>(&self, prefix: &[u8; PREFIX_LEN]) -> u64 {
        const {
            assert!(PREFIX_LEN <= KEY_LEN);
            if PREFIX_LEN > 0 && PREFIX_LEN < KEY_LEN {
                assert!(
                    <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                        [O::TREE_TO_KEY[PREFIX_LEN - 1]]
                        != <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                            [O::TREE_TO_KEY[PREFIX_LEN]],
                    "PREFIX_LEN must align to segment boundary",
                );
            }
        }
        if let Some(root) = &self.root {
            root.segmented_len(0, prefix)
        } else {
            0
        }
    }

    /// Iterates over all keys in the PATCH.
    /// The keys are returned in key ordering but random order.
    pub fn iter<'a>(&'a self) -> PATCHIterator<'a, KEY_LEN, O, V, H> {
        PATCHIterator::new(self)
    }

    /// Iterates over all keys in the PATCH in key order.
    ///
    /// The traversal visits every key in lexicographic key order, without
    /// accepting a prefix filter. For prefix-aware iteration, see
    /// [`PATCH::iter_prefix_count`].
    pub fn iter_ordered<'a>(&'a self) -> PATCHOrderedIterator<'a, KEY_LEN, O, V, H> {
        PATCHOrderedIterator::new(self)
    }

    /// Iterate over all prefixes of the given length in the PATCH.
    /// The prefixes are naturally returned in tree ordering and tree order.
    /// A count of the number of elements for the given prefix is also returned.
    pub fn iter_prefix_count<'a, const PREFIX_LEN: usize>(
        &'a self,
    ) -> PATCHPrefixIterator<'a, KEY_LEN, PREFIX_LEN, O, V, H> {
        PATCHPrefixIterator::new(self)
    }

    /// View every distinct tree-ordered prefix as one member of a set.
    ///
    /// `PREFIX_LEN` must end at a declared segment boundary. Bytes in later
    /// segments are deliberately projected away: adding or removing another
    /// suffix under an existing prefix does not change this view's membership.
    pub fn prefix_set<const PREFIX_LEN: usize>(
        &self,
    ) -> PATCHPrefixSet<'_, KEY_LEN, PREFIX_LEN, O, V, H> {
        PATCHPrefixSet::new(self)
    }

    /// Unions this PATCH with another PATCH.
    ///
    /// The other PATCH is consumed, and this PATCH is updated in place.
    /// If both PATCHes contain the same key, one associated value survives,
    /// but this operation does not specify which operand supplies it. Values
    /// do not participate in PATCH key-set identity, and the merge may swap
    /// operands internally.
    pub fn union(&mut self, mut other: Self)
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        if let Some(other_root) = other.root.take() {
            if self.root.is_some() {
                // Install the complete lifetime union before either Head can
                // detach or move LocalLeaves. `other` keeps its own cover
                // until the trie merge completes, including on unwind.
                OwnerCover::merge_into(&mut self.owners, &other.owners);
                let this = self.root.take().expect("root should not be empty");
                #[cfg(feature = "parallel")]
                let merged = Head::par_union(this, other_root, 0);
                #[cfg(not(feature = "parallel"))]
                let merged = Head::union(this, other_root, 0);
                self.root.replace(merged);
            } else {
                self.root.replace(other_root);
                self.owners = other.owners.take();
            }
        }
        self.debug_check_owner_invariant();
    }

    /// Intersects this PATCH with another PATCH.
    ///
    /// Returns a new PATCH that contains only the keys that are present in both PATCHes.
    pub fn intersect(&self, other: &Self) -> Self
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        let guard = self.owner_guard().join(other.owner_guard());
        // SAFETY: the exact union retains every owner held by either source.
        unsafe { self.intersect_with_guard(other, &guard) }
    }

    /// Intersect under an owner receipt already joined by an aggregate.
    ///
    /// # Safety
    ///
    /// `guard` must retain every archive allocation retained by either input.
    /// Intersection may reuse a LocalLeaf from either trie.
    pub(crate) unsafe fn intersect_with_guard(&self, other: &Self, guard: &PATCHOwnerGuard) -> Self
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        #[cfg(debug_assertions)]
        debug_assert!(
            guard.covers(&self.owners) && guard.covers(&other.owners),
            "an intersection guard must cover both source PATCHes",
        );
        let root = match (&self.root, &other.root) {
            (Some(root), Some(other_root)) => {
                #[cfg(feature = "parallel")]
                let result = root.par_intersect(other_root, 0);
                #[cfg(not(feature = "parallel"))]
                let result = root.intersect(other_root, 0);
                result.map(|root| root.with_start(0))
            }
            _ => None,
        };
        let owners = root.as_ref().and(guard.0.clone());
        let result = Self { root, owners };
        result.debug_check_owner_invariant();
        result
    }

    /// Returns the difference between this PATCH and another PATCH.
    ///
    /// Returns a new PATCH that contains only the keys that are present in this PATCH,
    /// but not in the other PATCH.
    pub fn difference(&self, other: &Self) -> Self
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        let guard = self.owner_guard();
        // SAFETY: difference can only reuse LocalLeaves from its left source.
        unsafe { self.difference_with_guard(other, &guard) }
    }


    /// Subtract under a left-owner receipt already combined by an aggregate.
    ///
    /// # Safety
    ///
    /// `guard` must retain every archive allocation retained by `self`.
    /// Difference never introduces a LocalLeaf from `other`.
    pub(crate) unsafe fn difference_with_guard(&self, other: &Self, guard: &PATCHOwnerGuard) -> Self
    where
        O: Send + Sync,
        V: Send + Sync,
    {
        #[cfg(debug_assertions)]
        debug_assert!(
            guard.covers(&self.owners),
            "a difference guard must cover its left source PATCH",
        );
        let root = match (&self.root, &other.root) {
            (Some(root), Some(other_root)) => {
                #[cfg(feature = "parallel")]
                let result = root.par_difference(other_root, 0);
                #[cfg(not(feature = "parallel"))]
                let result = root.difference(other_root, 0);
                result
            }
            (Some(root), None) => Some(root.clone()),
            (None, _) => None,
        };
        let owners = root.as_ref().and(guard.0.clone());
        let result = Self { root, owners };
        result.debug_check_owner_invariant();
        result
    }

    /// Calculates the average fill level for branch nodes grouped by their
    /// branching factor. The returned array contains eight entries for branch
    /// sizes `2`, `4`, `8`, `16`, `32`, `64`, `128` and `256` in that order.
    //#[cfg(debug_assertions)]
    pub fn debug_branch_fill(&self) -> [f32; 8] {
        let mut counts = [0u64; 8];
        let mut used = [0u64; 8];

        if let Some(root) = &self.root {
            let mut stack = Vec::new();
            stack.push(root);

            while let Some(head) = stack.pop() {
                match head.body_ref() {
                    BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => {}
                    BodyRef::Branch(b) => {
                        let size = b.child_table.len();
                        let idx = size.trailing_zeros() as usize - 1;
                        counts[idx] += 1;
                        used[idx] += b.child_table.iter().filter(|c| c.is_some()).count() as u64;
                        for child in b.child_table.iter().filter_map(|c| c.as_ref()) {
                            stack.push(child);
                        }
                    }
                }
            }
        }

        let mut avg = [0f32; 8];
        for i in 0..8 {
            if counts[i] > 0 {
                let size = 1u64 << (i + 1);
                avg[i] = used[i] as f32 / (counts[i] as f32 * size as f32);
            }
        }
        avg
    }
}

impl<const KEY_LEN: usize, O, V> PATCH<KEY_LEN, O, V, Blake3Merkle>
where
    O: KeySchema<KEY_LEN>,
{
    /// Return the canonical BLAKE3 Merkle root for this key set.
    ///
    /// `None` is the unique empty-set representation. The digest is stable
    /// across processes and construction histories; callers that need to
    /// scope anti-entropy to a team should key or domain-separate this root at
    /// that protocol boundary rather than changing PATCH's canonical identity.
    pub fn merkle_root(&self) -> Option<[u8; 32]> {
        self.root_hash()
    }
}

impl<const KEY_LEN: usize, V> PATCH<KEY_LEN, IdentitySchema, V, Blake3Merkle> {
    /// Locate the shallowest logical Merkle node whose compressed path covers
    /// `prefix`.
    ///
    /// Lookup walks raw key bytes from the root; PATCH maintains no
    /// digest-to-node side map. If `prefix` ends inside a compressed path, the
    /// returned node's [`PATCHMerkleNode::prefix`] extends beyond the request
    /// to that node's canonical `end_depth`. A prefix longer than `KEY_LEN`, a
    /// mismatching compressed path, or a missing child returns `None`.
    pub fn merkle_node(&self, prefix: &[u8]) -> Option<PATCHMerkleNode<'_, KEY_LEN, V>> {
        if prefix.len() > KEY_LEN {
            return None;
        }

        let mut node = self.root.as_ref()?;
        let mut at_depth = 0;
        loop {
            let end_depth = node.end_depth();
            let limit = prefix.len().min(end_depth);
            if node.childleaf_key()[at_depth..limit] != prefix[at_depth..limit] {
                return None;
            }
            if prefix.len() <= end_depth {
                return Some(PATCHMerkleNode::new(node));
            }

            let BodyRef::Branch(branch) = node.body_ref() else {
                unreachable!("a leaf covers every raw-key byte");
            };
            node = branch.child_table.table_get(prefix[end_depth])?;
            at_depth = end_depth;
        }
    }
}

impl<const KEY_LEN: usize> PATCH<KEY_LEN, IdentitySchema, (), Blake3Merkle> {
    /// Build an immutable key-only PATCH bottom-up.
    ///
    /// Input order and duplicates are ignored. Already sorted, unique input
    /// takes a linear fast path; all other input is sorted and deduplicated
    /// before construction. Every retained key becomes one owned leaf, and
    /// every final Merkle node is hashed exactly once during construction
    /// while recursion carries child digests upward. Debug builds additionally
    /// recompute branch digests as an invariant audit.
    ///
    /// This is the construction path for canonical inventory snapshots. Use
    /// [`Self::insert`] instead when preserving an existing PATCH and editing
    /// only a small number of keys is more important than whole-set build
    /// throughput.
    pub fn from_keys(keys: impl IntoIterator<Item = [u8; KEY_LEN]>) -> Self {
        Self::from_owned_keys(keys.into_iter().collect())
    }
}

impl<const KEY_LEN: usize, H: PatchHash> PATCH<KEY_LEN, IdentitySchema, (), H> {
    fn from_owned_keys(mut keys: Vec<[u8; KEY_LEN]>) -> Self {
        H::init();
        if !keys.windows(2).all(|pair| pair[0] < pair[1]) {
            #[cfg(feature = "parallel")]
            {
                use rayon::prelude::*;
                keys.par_sort_unstable();
            }
            #[cfg(not(feature = "parallel"))]
            keys.sort_unstable();
            keys.dedup();
        }

        let root = (!keys.is_empty()).then(|| Self::build_owned_sorted_head(&keys, 0).0);
        let result = Self { root, owners: None };
        result.debug_check_owner_invariant();
        result
    }

    /// Build one logical node from a nonempty sorted, duplicate-free key run.
    /// The returned digest is carried by the returned Head and is returned
    /// separately so its parent never has to re-read or recompute it.
    fn build_owned_sorted_head(
        keys: &[[u8; KEY_LEN]],
        depth: usize,
    ) -> (Head<KEY_LEN, IdentitySchema, (), H>, H::Digest) {
        debug_assert!(!keys.is_empty());
        if keys.len() == 1 {
            // SAFETY: Leaf::new returns one initialized, 16-byte-aligned,
            // refcount-one allocation. This Head becomes its sole owner.
            let leaf = unsafe { Leaf::<KEY_LEN, (), H>::new(&keys[0], ()) };
            let digest = unsafe { leaf.as_ref().hash };
            return (Head::new(0, leaf), digest);
        }

        // Lexicographic ordering means the first and last keys determine the
        // common prefix of the entire run.
        let first = &keys[0];
        let last = &keys[keys.len() - 1];
        let mut end_depth = depth;
        while end_depth < KEY_LEN && first[end_depth] == last[end_depth] {
            end_depth += 1;
        }
        debug_assert!(
            end_depth < KEY_LEN,
            "deduplicated keys must diverge before their end"
        );

        let mut groups = Vec::with_capacity(256.min(keys.len()));
        let mut start = 0;
        while start < keys.len() {
            let edge = keys[start][end_depth];
            let width = keys[start..].partition_point(|key| key[end_depth] == edge);
            let end = start + width;
            groups.push((edge, &keys[start..end]));
            start = end;
        }
        debug_assert!(groups.len() >= 2);
        let initial_slots = if groups.len() == 2 {
            2
        } else {
            groups.len().next_power_of_two()
        };

        #[cfg(feature = "parallel")]
        let children = if keys.len() >= Self::PARALLEL_PARTITION_THRESHOLD {
            use rayon::prelude::*;
            groups
                .into_par_iter()
                .map(|(edge, child_keys)| {
                    let (head, digest) = Self::build_owned_sorted_head(child_keys, end_depth + 1);
                    (edge, head, digest)
                })
                .collect()
        } else {
            groups
                .into_iter()
                .map(|(edge, child_keys)| {
                    let (head, digest) = Self::build_owned_sorted_head(child_keys, end_depth + 1);
                    (edge, head, digest)
                })
                .collect()
        };
        #[cfg(not(feature = "parallel"))]
        let children = groups
            .into_iter()
            .map(|(edge, child_keys)| {
                let (head, digest) = Self::build_owned_sorted_head(child_keys, end_depth + 1);
                (edge, head, digest)
            })
            .collect();

        Self::assemble_partition_branch(end_depth, initial_slots, children)
    }
}

/// Archive-backed insertion path, available only for `V = ()` because
/// [`ArchiveEntry`] does not carry a value. Newly inserted archive keys remain
/// LocalLeaves while the PATCH's deduplicated root cover retains their
/// allocations.
impl<const KEY_LEN: usize, O, H> PATCH<KEY_LEN, O, (), H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    /// Inserts an archive-backed key and retains its allocation before the
    /// LocalLeaf becomes reachable from the root.
    pub fn insert_archive(&mut self, entry: &ArchiveEntry<'_, KEY_LEN, H>) {
        let (leaf_head, leaf_owner, leaf_hash) = entry.leaf::<O>();
        OwnerCover::retain(&mut self.owners, leaf_owner);
        if let Some(this) = self.root.take() {
            let new_head = Head::insert_archive_leaf(this, leaf_head, leaf_hash, 0);
            self.root.replace(new_head);
        } else {
            self.root.replace(leaf_head);
        }
        self.debug_check_owner_invariant();
    }

    /// Builds a canonical PATCH directly from an unordered row permutation by
    /// partitioning that one buffer in place at each trie depth.
    ///
    /// Archive construction fuses ordering and trie construction: no sorted
    /// pointer array or per-row leaf descriptor is retained. `hashes[row]` is
    /// the one transient key hash shared by every TribleSet index build.
    ///
    /// # Safety
    ///
    /// - `rows` must contain every valid index into `keys` and `hashes` exactly
    ///   once.
    /// - Every key pointer must be 16-byte aligned, immutable, and kept alive
    ///   by `owner`.
    /// - `keys` must contain no duplicates.
    /// - `hashes[row]` must be the PATCH key hash of `keys[row]`.
    #[cfg(test)]
    pub(crate) unsafe fn from_archive_partition(
        keys: &[[u8; KEY_LEN]],
        hashes: &[H::Digest],
        rows: &mut [u32],
        owner: &std::sync::Arc<dyn ArchiveOwner>,
    ) -> Self {
        unsafe {
            Self::from_archive_partition_with_guard(
                keys,
                hashes,
                rows,
                owner,
                &PATCHOwnerGuard::default(),
            )
        }
    }

    /// Build an archive partition under a receipt already shared by an
    /// aggregate. Retaining `owner` is idempotent when it is already the
    /// receipt's latest member, preserving the shared cover Arc.
    #[cfg(any(test, feature = "parallel"))]
    pub(crate) unsafe fn from_archive_partition_with_guard(
        keys: &[[u8; KEY_LEN]],
        hashes: &[H::Digest],
        rows: &mut [u32],
        owner: &std::sync::Arc<dyn ArchiveOwner>,
        guard: &PATCHOwnerGuard,
    ) -> Self {
        // Branch child tables use randomness initialized alongside the
        // hash-key bundle. A pre-hashed caller may reach this constructor
        // before PATCH::new.
        H::init();
        assert_eq!(keys.len(), hashes.len());
        assert_eq!(keys.len(), rows.len());
        assert!(
            u32::try_from(rows.len()).is_ok(),
            "archive row ordinals must fit the partition metadata",
        );
        if rows.is_empty() {
            return Self::new();
        }
        let mut guard = guard.clone();
        guard.retain_archive_owner(owner);
        let owners = guard.0;
        if rows.len() == 1 {
            let row = rows[0] as usize;
            let ptr = NonNull::from(&keys[row]);
            // SAFETY: the caller proves alignment and `owners` retains the
            // archive allocation for the returned PATCH's lifetime.
            let root = unsafe { Head::new_local_leaf(0, ptr) };
            let result = Self {
                root: Some(root),
                owners,
            };
            result.debug_check_owner_invariant();
            return result;
        }

        let (root, _) = unsafe { Self::build_archive_partition_head(keys, hashes, rows, 0) };
        let result = Self {
            root: Some(root.with_start(0)),
            owners,
        };
        result.debug_check_owner_invariant();
        result
    }

    /// Row count at or above which one trie node builds its children on
    /// separate workers instead of recursing into them in order.
    ///
    /// The MSD partition already hands each child a disjoint, contiguous
    /// interval of the one permutation buffer, so the fan-out costs no copy
    /// and no synchronisation — only the task overhead this threshold pays
    /// for. Below it a node is cheaper to walk than to schedule.
    #[cfg(feature = "parallel")]
    pub(crate) const PARALLEL_PARTITION_THRESHOLD: usize = 1 << 12;

    /// Rows one worker is given before a partition pass is worth splitting.
    ///
    /// A counting pass is a sequential read and a scatter is a random write,
    /// so a worker needs enough rows to amortise the histogram reduction and
    /// the second buffer. Below two workers' worth, the in-place American-flag
    /// pass is both cheaper and allocation-free.
    #[cfg(feature = "parallel")]
    pub(crate) const PARTITION_ROWS_PER_WORKER: usize = 1 << 13;

    /// How many workers an out-of-place partition of `rows` should use, and
    /// therefore whether it beats the in-place pass at all.
    #[cfg(feature = "parallel")]
    pub(crate) fn partition_workers(rows: usize) -> usize {
        (rows / Self::PARTITION_ROWS_PER_WORKER)
            .min(rayon::current_num_threads().max(1))
            .max(1)
    }

    /// Representative-LCP plus in-place MSD-radix worker for
    /// [`Self::from_archive_partition`].
    ///
    /// Trie construction is ownership-neutral. One deduplicated conservative
    /// owner cover on the returned PATCH guards every LocalLeaf regardless of
    /// later reshaping.
    ///
    /// With the `parallel` feature a node meets one of three regimes, by
    /// size: wide enough for [`Self::partition_workers`] to want more than one
    /// worker, it is split by the out-of-place counting pass and its children
    /// are built concurrently; merely at or above
    /// [`Self::PARALLEL_PARTITION_THRESHOLD`], it keeps the in-place pass and
    /// only its children go concurrent; below that it is walked in order.
    ///
    /// All three build the same trie. Children own disjoint intervals of the
    /// permutation and disjoint subtrees of the result, the child heads are
    /// reassembled in ascending key order either way, and the node hash is a
    /// canonical summary over edge-sorted children — so neither the order
    /// children are built in nor the order rows sit in within a bucket can
    /// reach the answer.
    #[cfg(any(test, feature = "parallel"))]
    unsafe fn build_archive_partition_head(
        keys: &[[u8; KEY_LEN]],
        hashes: &[H::Digest],
        rows: &mut [u32],
        depth: usize,
    ) -> (Head<KEY_LEN, O, (), H>, H::Digest) {
        debug_assert!(!rows.is_empty());
        if rows.len() == 1 {
            let row = rows[0] as usize;
            let ptr = NonNull::from(&keys[row]);
            // SAFETY: the outer constructor installs its owner cover before
            // returning this LocalLeaf to safe code.
            let head = unsafe { Head::new_local_leaf(0, ptr) };
            return (head, hashes[row]);
        }

        // A node big enough to be worth the extra buffer counts and scatters
        // its children across workers instead of walking them in place; a
        // node merely big enough to be worth a task keeps the in-place pass
        // and only recurses concurrently.
        #[cfg(feature = "parallel")]
        if Self::partition_workers(rows.len()) > 1 {
            let (plan, mut permuted) = Self::partition_archive_rows_parallel(keys, rows, depth);
            // SAFETY: `permuted` is the same multiset of row ordinals as
            // `rows`, grouped by the same key byte.
            return unsafe {
                Self::build_archive_partition_children(keys, hashes, &mut permuted, &plan)
            };
        }

        let plan = Self::partition_archive_rows(keys, rows, depth);
        let end_depth = plan.end_depth;

        #[cfg(feature = "parallel")]
        if rows.len() >= Self::PARALLEL_PARTITION_THRESHOLD {
            // SAFETY: same contract, on the in-place permutation.
            return unsafe { Self::build_archive_partition_children(keys, hashes, rows, &plan) };
        }

        let first_bucket = plan.buckets[0];
        let second_bucket = plan.buckets[1];
        let first_end = plan.ends[first_bucket as usize] as usize;
        let (first_head, first_hash) = unsafe {
            Self::build_archive_partition_head(keys, hashes, &mut rows[..first_end], end_depth + 1)
        };
        let second_end = plan.ends[second_bucket as usize] as usize;
        let (second_head, second_hash) = unsafe {
            Self::build_archive_partition_head(
                keys,
                hashes,
                &mut rows[first_end..second_end],
                end_depth + 1,
            )
        };
        let first_count = first_head.count();
        let second_count = second_head.count();

        let body = if plan.initial_slots == 2 {
            Branch::new_with_child_hashes(
                end_depth,
                first_head.with_key(first_bucket),
                second_head.with_key(second_bucket),
                first_hash,
                second_hash,
            )
        } else {
            Branch::new_with_child_hashes_capacity(
                end_depth,
                first_head.with_key(first_bucket),
                second_head.with_key(second_bucket),
                first_hash,
                second_hash,
                plan.initial_slots,
            )
        };
        let mut root = Head::new(0, body);
        let representative = &keys[rows[0] as usize];
        let mut hash_state = H::begin_branch(
            representative,
            &O::TREE_TO_KEY,
            end_depth,
            plan.fanout,
            rows.len() as u64,
        );
        H::push_child(&mut hash_state, first_bucket, first_count, first_hash);
        H::push_child(&mut hash_state, second_bucket, second_count, second_hash);
        if plan.fanout == 2 {
            debug_assert_eq!(second_end, rows.len());
            return (root, H::finish_branch(hash_state));
        }

        let mut editor = BranchMut::from_head(&mut root);
        let mut range_start = second_end;
        for &byte in &plan.buckets[2..plan.fanout] {
            let range_end = plan.ends[byte as usize] as usize;
            let (child, child_hash) = unsafe {
                Self::build_archive_partition_head(
                    keys,
                    hashes,
                    &mut rows[range_start..range_end],
                    end_depth + 1,
                )
            };
            let child_count = child.count();
            H::push_child(&mut hash_state, byte, child_count, child_hash);
            editor.install_child_growing(child.with_key(byte));
            range_start = range_end;
        }
        debug_assert_eq!(range_start, rows.len());

        // Rebuild structural aggregates once and install the exact canonical
        // summary carried by recursion, avoiding another hash read from direct
        // LocalLeaves.
        let hash = H::finish_branch(hash_state);
        editor.finish_bulk_aggregates(hash);
        drop(editor);
        (root, hash)
    }

    /// Build every child of one already-partitioned node concurrently.
    ///
    /// The partition hands each child a disjoint, contiguous interval of the
    /// permutation, so `split_at_mut` is the whole proof that the concurrent
    /// recursion cannot alias: disjoint rows, disjoint subtrees, and a node
    /// hash summarized over children in canonical edge order.
    ///
    /// # Safety
    ///
    /// The caller's `keys`/`hashes` contract must hold, and `rows` must be
    /// grouped by `plan` as [`Self::partition_archive_rows`] leaves it.
    #[cfg(feature = "parallel")]
    unsafe fn build_archive_partition_children(
        keys: &[[u8; KEY_LEN]],
        hashes: &[H::Digest],
        rows: &mut [u32],
        plan: &ArchivePartitionPlan,
    ) -> (Head<KEY_LEN, O, (), H>, H::Digest) {
        use rayon::prelude::*;

        let end_depth = plan.end_depth;
        let mut remaining: &mut [u32] = rows;
        let mut intervals: Vec<(u8, &mut [u32])> = Vec::with_capacity(plan.fanout);
        let mut previous_end = 0usize;
        for &byte in &plan.buckets[..plan.fanout] {
            let end = plan.ends[byte as usize] as usize;
            let (child, rest) = remaining.split_at_mut(end - previous_end);
            intervals.push((byte, child));
            remaining = rest;
            previous_end = end;
        }
        debug_assert!(remaining.is_empty());

        let children: Vec<(u8, Head<KEY_LEN, O, (), H>, H::Digest)> = intervals
            .into_par_iter()
            .map(|(byte, child_rows)| {
                // SAFETY: the caller's contract holds for every subinterval,
                // and the intervals are pairwise disjoint.
                let (head, hash) = unsafe {
                    Self::build_archive_partition_head(keys, hashes, child_rows, end_depth + 1)
                };
                (byte, head, hash)
            })
            .collect();

        Self::assemble_partition_branch(end_depth, plan.initial_slots, children)
    }

    /// Out-of-place counting-sort twin of [`Self::partition_archive_rows`].
    ///
    /// The in-place American-flag pass is a chain of dependent swaps and can
    /// only ever run on one worker, which is exactly what caps a whole-archive
    /// build: six root passes over every row, each a serial storm of cache
    /// misses. Counting into per-worker histograms and scattering into a
    /// second buffer costs one extra `u32` per row and runs on every worker.
    ///
    /// The result groups the same rows under the same key bytes. It does not
    /// preserve their relative order within a bucket, and does not need to:
    /// keys are distinct, so the trie a bucket produces is a function of its
    /// key set alone, and children are installed in ascending byte order
    /// either way.
    #[cfg(feature = "parallel")]
    fn partition_archive_rows_parallel(
        keys: &[[u8; KEY_LEN]],
        rows: &[u32],
        depth: usize,
    ) -> (ArchivePartitionPlan, Vec<u32>) {
        use rayon::prelude::*;

        let workers = Self::partition_workers(rows.len());
        let stride = rows.len().div_ceil(workers).max(1);

        // Every worker narrows the representative's prefix over its own run;
        // the shortest agreement wins, which is the same minimum the ordered
        // scan converges to.
        let representative = &keys[rows[0] as usize];
        let end_depth = rows[1..]
            .par_chunks(stride)
            .map(|chunk| {
                let mut shortest = KEY_LEN;
                for &row in chunk {
                    let key = &keys[row as usize];
                    let mut candidate_depth = depth;
                    while candidate_depth < shortest {
                        let key_index = O::TREE_TO_KEY[candidate_depth];
                        if representative[key_index] != key[key_index] {
                            shortest = candidate_depth;
                            break;
                        }
                        candidate_depth += 1;
                    }
                    if shortest == depth {
                        break;
                    }
                }
                shortest
            })
            .min()
            .unwrap_or(KEY_LEN);
        assert!(
            end_depth < KEY_LEN,
            "duplicate archive keys cannot form a finite trie",
        );

        let key_index = O::TREE_TO_KEY[end_depth];
        let histograms: Vec<[u32; 256]> = rows
            .par_chunks(stride)
            .map(|chunk| {
                let mut counts = [0u32; 256];
                for &row in chunk {
                    counts[keys[row as usize][key_index] as usize] += 1;
                }
                counts
            })
            .collect();

        let mut totals = [0u32; 256];
        for counts in &histograms {
            for (total, count) in totals.iter_mut().zip(counts.iter()) {
                *total += count;
            }
        }

        let mut buckets = [0u8; 256];
        let mut fanout = 0usize;
        let mut ends = [0u32; 256];
        let mut bases = [0u32; 256];
        let mut offset = 0u32;
        for (byte, &total) in totals.iter().enumerate() {
            if total == 0 {
                continue;
            }
            buckets[fanout] = byte as u8;
            fanout += 1;
            bases[byte] = offset;
            offset += total;
            ends[byte] = offset;
        }
        debug_assert_eq!(offset as usize, rows.len());
        debug_assert!((2..=256).contains(&fanout));
        let initial_slots = if fanout == 2 {
            2
        } else {
            fanout.next_power_of_two()
        };

        // Each worker's rows for a bucket land after every earlier worker's,
        // so the per-worker cursors carve the bucket into disjoint windows.
        let mut cursors: Vec<[u32; 256]> = vec![[0u32; 256]; histograms.len()];
        let mut running = bases;
        for (cursor, counts) in cursors.iter_mut().zip(histograms.iter()) {
            for &byte in &buckets[..fanout] {
                let byte = byte as usize;
                cursor[byte] = running[byte];
                running[byte] += counts[byte];
            }
        }

        let mut permuted: Vec<u32> = Vec::with_capacity(rows.len());
        let scatter = parallel_union::ScatterPtr(permuted.as_mut_ptr());
        rows.par_chunks(stride)
            .zip(cursors.into_par_iter())
            .for_each(|(chunk, mut cursor)| {
                for &row in chunk {
                    let byte = keys[row as usize][key_index] as usize;
                    let slot = cursor[byte] as usize;
                    // SAFETY: slot is inside the buffer and inside this
                    // worker's window of this bucket, so no other worker
                    // writes it.
                    unsafe { scatter.write_at(slot, row) };
                    cursor[byte] += 1;
                }
            });
        // SAFETY: the cursors partition `0..rows.len()`, so every slot was
        // written exactly once above.
        unsafe { permuted.set_len(rows.len()) };

        (
            ArchivePartitionPlan {
                end_depth,
                ends,
                buckets,
                fanout,
                initial_slots,
            },
            permuted,
        )
    }

    /// Install already-built children, in ascending key order, under one
    /// branch at `end_depth`.
    ///
    /// Children arrive as values, so whether they came from archive
    /// partitioning, a sorted owned-key build, or parallel recursion is
    /// invisible here. The final digest is computed before allocation and
    /// installed directly, so no temporary two-child BLAKE node is hashed.
    fn assemble_partition_branch(
        end_depth: usize,
        initial_slots: usize,
        children: Vec<(u8, Head<KEY_LEN, O, (), H>, H::Digest)>,
    ) -> (Head<KEY_LEN, O, (), H>, H::Digest) {
        debug_assert!(children.len() >= 2);
        debug_assert!(children.windows(2).all(|pair| pair[0].0 < pair[1].0));
        let child_count = children.len();
        let leaf_count = children.iter().map(|(_, child, _)| child.count()).sum();
        let mut hash_state = H::begin_branch(
            children[0].1.childleaf_key(),
            &O::TREE_TO_KEY,
            end_depth,
            child_count,
            leaf_count,
        );
        for &(edge, ref child, digest) in &children {
            H::push_child(&mut hash_state, edge, child.count(), digest);
        }
        let hash = H::finish_branch(hash_state);

        let mut drain = children.into_iter();
        let (first_bucket, first_head, _) = drain.next().expect("two children");
        let (second_bucket, second_head, _) = drain.next().expect("two children");
        let body = if initial_slots == 2 {
            Branch::new_with_known_hash(
                end_depth,
                first_head.with_key(first_bucket),
                second_head.with_key(second_bucket),
                hash,
            )
        } else {
            Branch::new_with_known_hash_capacity(
                end_depth,
                first_head.with_key(first_bucket),
                second_head.with_key(second_bucket),
                hash,
                initial_slots,
            )
        };
        let mut root = Head::new(0, body);
        let mut extra = drain.peekable();
        if extra.peek().is_none() {
            return (root, hash);
        }
        let mut editor = BranchMut::from_head(&mut root);
        for (byte, child, _) in extra {
            editor.install_child_growing(child.with_key(byte));
        }
        editor.finish_bulk_aggregates(hash);
        drop(editor);
        (root, hash)
    }

    /// One trie node's split: where its children diverge, which key bytes are
    /// occupied, and where each child's rows now sit inside `rows`.
    ///
    /// The rows are permuted in place by an American-flag pass, so on return
    /// bucket `buckets[i]` owns `rows[ends[buckets[i-1]]..ends[buckets[i]]]`.
    #[cfg(any(test, feature = "parallel"))]
    fn partition_archive_rows(
        keys: &[[u8; KEY_LEN]],
        rows: &mut [u32],
        depth: usize,
    ) -> ArchivePartitionPlan {
        // Tighten the representative's common prefix row-by-row. Once the
        // candidate reaches the incoming depth, no later row can shorten it.
        let representative = &keys[rows[0] as usize];
        let mut end_depth = KEY_LEN;
        for &row in &rows[1..] {
            let key = &keys[row as usize];
            let mut candidate_depth = depth;
            while candidate_depth < end_depth {
                let key_index = O::TREE_TO_KEY[candidate_depth];
                if representative[key_index] != key[key_index] {
                    end_depth = candidate_depth;
                    break;
                }
                candidate_depth += 1;
            }
            if end_depth == depth {
                break;
            }
        }
        assert!(
            end_depth < KEY_LEN,
            "duplicate archive keys cannot form a finite trie",
        );

        let key_index = O::TREE_TO_KEY[end_depth];
        let mut ends = [0u32; 256];
        let mut occupied = ByteSet::new_empty();
        for &row in rows.iter() {
            let byte = keys[row as usize][key_index];
            let count = &mut ends[byte as usize];
            if *count == 0 {
                occupied.insert(byte);
            }
            *count += 1;
        }

        let mut buckets = [0u8; 256];
        let mut fanout = 0usize;
        let mut listing = occupied;
        while let Some(byte) = listing.drain_next_ascending() {
            buckets[fanout] = byte;
            fanout += 1;
        }
        debug_assert!((2..=256).contains(&fanout));
        let initial_slots = if fanout == 2 {
            2
        } else {
            fanout.next_power_of_two()
        };

        // Convert counts into cumulative exclusive ends. `next` tracks the
        // first unfilled position in each occupied interval.
        let mut next = [0u32; 256];
        let mut offset = 0u32;
        for &byte in &buckets[..fanout] {
            let count = ends[byte as usize];
            next[byte as usize] = offset;
            offset += count;
            ends[byte as usize] = offset;
        }
        debug_assert_eq!(offset as usize, rows.len());

        // American-flag partition. Every swap permanently fills one
        // destination position, so this is linear and needs no second buffer.
        for &byte in &buckets[..fanout] {
            let bucket = byte as usize;
            while next[bucket] < ends[bucket] {
                let position = next[bucket] as usize;
                let row = rows[position] as usize;
                let destination = keys[row][key_index] as usize;
                if destination == bucket {
                    next[bucket] += 1;
                } else {
                    let destination_slot = next[destination] as usize;
                    debug_assert!(destination_slot < ends[destination] as usize);
                    rows.swap(position, destination_slot);
                    next[destination] += 1;
                }
            }
        }

        ArchivePartitionPlan {
            end_depth,
            ends,
            buckets,
            fanout,
            initial_slots,
        }
    }
}

/// Where one trie node's children start and end inside the shared permutation.
#[cfg(any(test, feature = "parallel"))]
struct ArchivePartitionPlan {
    /// Tree depth at which this node's children diverge.
    end_depth: usize,
    /// Exclusive end offset of each occupied bucket, indexed by key byte.
    ends: [u32; 256],
    /// The occupied key bytes, ascending, in `buckets[..fanout]`.
    buckets: [u8; 256],
    fanout: usize,
    /// Child-table capacity the branch is born with.
    initial_slots: usize,
}

/// A PATCH is a set with payload: equality (and the root hash) cover the keys
/// only, never the values; a type whose identity includes the values must
/// compare them itself.
impl<const KEY_LEN: usize, O, V, H> PartialEq for PATCH<KEY_LEN, O, V, H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    fn eq(&self, other: &Self) -> bool {
        self.root.as_ref().map(|root| root.hash()) == other.root.as_ref().map(|root| root.hash())
    }
}

/// Set inclusion over keys: `a <= b` says every key of `a` is in `b`, and
/// `partial_cmp` is `None` when neither contains the other.
///
/// An early-exit walk over both tries with the shape of
/// [`PATCH::difference`] that builds nothing: a shared subtree is settled by
/// its hash, and a key one side lacks decides the direction the moment it is
/// met. Prefer `a <= b` to `a.difference(&b).is_empty()`, which materializes
/// the keys it then discards.
impl<const KEY_LEN: usize, O, V, H> PartialOrd for PATCH<KEY_LEN, O, V, H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (&self.root, &other.root) {
            (None, None) => Some(Ordering::Equal),
            (None, Some(_)) => Some(Ordering::Less),
            (Some(_), None) => Some(Ordering::Greater),
            (Some(root), Some(other_root)) => root.inclusion(other_root, 0),
        }
    }
}

impl<const KEY_LEN: usize, O, V, H> Eq for PATCH<KEY_LEN, O, V, H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
}

impl<'a, const KEY_LEN: usize, O, V, H> IntoIterator for &'a PATCH<KEY_LEN, O, V, H>
where
    O: KeySchema<KEY_LEN>,
    H: PatchHash,
{
    type Item = &'a [u8; KEY_LEN];
    type IntoIter = PATCHIterator<'a, KEY_LEN, O, V, H>;

    fn into_iter(self) -> Self::IntoIter {
        PATCHIterator::new(self)
    }
}

/// An iterator over all keys in a PATCH.
/// The keys are returned in key ordering but in random order.
pub struct PATCHIterator<
    'a,
    const KEY_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    // Root-to-leaf branch depths strictly increase within 0..KEY_LEN, so
    // seeding from the real root branch keeps the live stack within KEY_LEN.
    stack: ArrayVec<std::slice::Iter<'a, Option<Head<KEY_LEN, O, V, H>>>, KEY_LEN>,
    // A singleton root has no branch frame, including when KEY_LEN is zero.
    pending_leaf: Option<&'a [u8; KEY_LEN]>,
    remaining: usize,
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    PATCHIterator<'a, KEY_LEN, O, V, H>
{
    /// Creates an iterator over all keys in `patch`.
    pub fn new(patch: &'a PATCH<KEY_LEN, O, V, H>) -> Self {
        let mut r = PATCHIterator {
            stack: ArrayVec::new(),
            pending_leaf: None,
            remaining: patch.len().min(usize::MAX as u64) as usize,
        };
        if let Some(root) = &patch.root {
            match root.body_ref() {
                BodyRef::Leaf(leaf) => r.pending_leaf = Some(&leaf.key),
                BodyRef::LocalLeaf(key) => r.pending_leaf = Some(key),
                BodyRef::Branch(branch) => r.stack.push(branch.child_table.iter()),
            }
        }
        r
    }
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Iterator
    for PATCHIterator<'a, KEY_LEN, O, V, H>
{
    type Item = &'a [u8; KEY_LEN];

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(key) = self.pending_leaf.take() {
            self.remaining = self.remaining.saturating_sub(1);
            return Some(key);
        }
        let mut iter = self.stack.last_mut()?;
        loop {
            if let Some(child) = iter.next() {
                if let Some(child) = child {
                    match child.body_ref() {
                        BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => {
                            self.remaining = self.remaining.saturating_sub(1);
                            // Use the safe accessor on the child reference to obtain the leaf key bytes.
                            return Some(child.childleaf_key());
                        }
                        BodyRef::Branch(branch) => {
                            self.stack.push(branch.child_table.iter());
                            iter = self.stack.last_mut()?;
                        }
                    }
                }
            } else {
                self.stack.pop();
                iter = self.stack.last_mut()?;
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> ExactSizeIterator
    for PATCHIterator<'a, KEY_LEN, O, V, H>
{
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> std::iter::FusedIterator
    for PATCHIterator<'a, KEY_LEN, O, V, H>
{
}

/// An iterator over every key in a PATCH, returned in key order.
///
/// Keys are yielded in lexicographic key order regardless of their physical
/// layout in the underlying tree. This iterator walks the full tree and does
/// not accept a prefix filter. For prefix-aware iteration, use
/// [`PATCHPrefixIterator`], constructed via [`PATCH::iter_prefix_count`].
pub struct PATCHOrderedIterator<
    'a,
    const KEY_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    stack: Vec<ArrayVec<&'a Head<KEY_LEN, O, V, H>, 256>>,
    remaining: usize,
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    PATCHOrderedIterator<'a, KEY_LEN, O, V, H>
{
    pub fn new(patch: &'a PATCH<KEY_LEN, O, V, H>) -> Self {
        let mut r = PATCHOrderedIterator {
            stack: Vec::with_capacity(KEY_LEN),
            remaining: patch.len().min(usize::MAX as u64) as usize,
        };
        if let Some(root) = &patch.root {
            r.stack.push(ArrayVec::new());
            match root.body_ref() {
                BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => {
                    r.stack[0].push(root);
                }
                BodyRef::Branch(branch) => {
                    let first_level = &mut r.stack[0];
                    first_level.extend(branch.child_table.iter().filter_map(|c| c.as_ref()));
                    first_level.sort_unstable_by_key(|&k| Reverse(k.key())); // We need to reverse here because we pop from the vec.
                }
            }
        }
        r
    }
}

// --- Owned consuming iterators ---
/// Iterator that owns a PATCH and yields keys in key-order. The owner set is
/// retained until every queued LocalLeaf has been copied out.
pub struct PATCHIntoIterator<
    const KEY_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    // Field order is deliberate: queued Heads drop before the owner cover.
    queue: Vec<Head<KEY_LEN, O, V, H>>,
    remaining: usize,
    _owners: Option<Arc<OwnerCover>>,
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    PATCHIntoIterator<KEY_LEN, O, V, H>
{
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Iterator
    for PATCHIntoIterator<KEY_LEN, O, V, H>
{
    type Item = [u8; KEY_LEN];

    fn next(&mut self) -> Option<Self::Item> {
        let q = &mut self.queue;
        while let Some(mut head) = q.pop() {
            // Match on the mutable body directly. For leaves we can return the
            // stored key (the array is Copy), for branches we take children out
            // of the table and push them onto the stack so they are visited
            // depth-first.
            match head.body_mut() {
                BodyMut::Leaf(leaf) => {
                    self.remaining = self.remaining.saturating_sub(1);
                    return Some(leaf.key);
                }
                BodyMut::LocalLeaf(bytes) => {
                    self.remaining = self.remaining.saturating_sub(1);
                    return Some(*bytes);
                }
                BodyMut::Branch(branch) => {
                    for slot in branch.child_table.iter_mut().rev() {
                        if let Some(c) = slot.take() {
                            q.push(c);
                        }
                    }
                }
            }
        }
        None
    }
}

/// Iterator that owns a PATCH and yields keys in key order.
pub struct PATCHIntoOrderedIterator<
    const KEY_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    // Field order is deliberate: queued Heads drop before the owner cover.
    queue: Vec<Head<KEY_LEN, O, V, H>>,
    remaining: usize,
    _owners: Option<Arc<OwnerCover>>,
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Iterator
    for PATCHIntoOrderedIterator<KEY_LEN, O, V, H>
{
    type Item = [u8; KEY_LEN];

    fn next(&mut self) -> Option<Self::Item> {
        let q = &mut self.queue;
        while let Some(mut head) = q.pop() {
            // Match the mutable body directly — we own `head` so calling
            // `body_mut()` is safe and allows returning the copied leaf key
            // or mutating the branch child table in-place.
            match head.body_mut() {
                BodyMut::Leaf(leaf) => {
                    self.remaining = self.remaining.saturating_sub(1);
                    return Some(leaf.key);
                }
                BodyMut::LocalLeaf(bytes) => {
                    self.remaining = self.remaining.saturating_sub(1);
                    return Some(*bytes);
                }
                BodyMut::Branch(branch) => {
                    let slice: &mut [Option<Head<KEY_LEN, O, V, H>>] = &mut branch.child_table;
                    // Sort children by their byte-key, placing empty slots (None)
                    // after all occupied slots. Using `sort_unstable_by_key` with
                    // a simple key projection is clearer than a custom
                    // comparator; it also avoids allocating temporaries. The
                    // old comparator manually handled None/Some cases — we
                    // express that intent directly by sorting on the tuple
                    // (is_none, key_opt).
                    slice
                        .sort_unstable_by_key(|opt| (opt.is_none(), opt.as_ref().map(|h| h.key())));
                    for slot in slice.iter_mut().rev() {
                        if let Some(c) = slot.take() {
                            q.push(c);
                        }
                    }
                }
            }
        }
        None
    }
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> IntoIterator
    for PATCH<KEY_LEN, O, V, H>
{
    type Item = [u8; KEY_LEN];
    type IntoIter = PATCHIntoIterator<KEY_LEN, O, V, H>;

    fn into_iter(self) -> Self::IntoIter {
        let remaining = self.len().min(usize::MAX as u64) as usize;
        let PATCH { root, owners } = self;
        let mut q = Vec::new();
        if let Some(root) = root {
            q.push(root);
        }
        PATCHIntoIterator {
            queue: q,
            remaining,
            _owners: owners,
        }
    }
}

impl<const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> PATCH<KEY_LEN, O, V, H> {
    /// Consume and return an iterator that yields keys in key order.
    pub fn into_iter_ordered(self) -> PATCHIntoOrderedIterator<KEY_LEN, O, V, H> {
        let remaining = self.len().min(usize::MAX as u64) as usize;
        let PATCH { root, owners } = self;
        let mut q = Vec::new();
        if let Some(root) = root {
            q.push(root);
        }
        PATCHIntoOrderedIterator {
            queue: q,
            remaining,
            _owners: owners,
        }
    }

    /// Consume this PATCH and enumerate each distinct tree-ordered prefix once.
    ///
    /// Unlike mapping the full consuming iterator and deduplicating it, this
    /// traversal stops at `PREFIX_LEN`: suffix subtrees are dropped without
    /// visiting their leaves. `PREFIX_LEN` must end at a segment boundary.
    pub fn into_prefixes<const PREFIX_LEN: usize>(
        self,
    ) -> PATCHIntoPrefixSetIterator<KEY_LEN, PREFIX_LEN, O, V, H> {
        const {
            assert!(PREFIX_LEN > 0, "a prefix set needs at least one byte");
            assert!(PREFIX_LEN <= KEY_LEN);
            if PREFIX_LEN < KEY_LEN {
                assert!(
                    <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                        [O::TREE_TO_KEY[PREFIX_LEN - 1]]
                        != <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                            [O::TREE_TO_KEY[PREFIX_LEN]],
                    "PREFIX_LEN must align to a segment boundary",
                );
            }
        }

        let PATCH { root, owners } = self;
        let mut queue = Vec::new();
        if let Some(root) = root {
            queue.push(root);
        }
        PATCHIntoPrefixSetIterator {
            queue,
            _owners: owners,
        }
    }
}

/// Consuming iterator over the distinct prefixes at one PATCH segment boundary.
///
/// The iterator owns an immutable PATCH snapshot and drops every suffix subtree
/// as soon as its one projected member has been emitted. This is useful when an
/// iterator must outlive the snapshot value from which it was constructed.
pub struct PATCHIntoPrefixSetIterator<
    const KEY_LEN: usize,
    const PREFIX_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    // Field order is deliberate: queued Heads drop before the owner cover.
    queue: Vec<Head<KEY_LEN, O, V, H>>,
    _owners: Option<Arc<OwnerCover>>,
}

impl<const KEY_LEN: usize, const PREFIX_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Iterator
    for PATCHIntoPrefixSetIterator<KEY_LEN, PREFIX_LEN, O, V, H>
{
    type Item = [u8; PREFIX_LEN];

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(head) = self.queue.pop() {
            if head.end_depth() >= PREFIX_LEN {
                let key = O::tree_ordered(head.childleaf_key());
                return Some(key[..PREFIX_LEN].try_into().unwrap());
            }

            let BodyRef::Branch(branch) = head.body_ref() else {
                unreachable!("a leaf cannot end before a valid prefix boundary");
            };
            // Clone one-word persistent Heads from the immutable branch. Using
            // `body_mut` here would copy-on-write every shared branch merely
            // because the iterator owns a clone of the PATCH root.
            let mut children = ArrayVec::<&Head<KEY_LEN, O, V, H>, 256>::new();
            children.extend(branch.child_table.iter().filter_map(Option::as_ref));
            children.sort_unstable_by_key(|child| child.key());
            for child in children.into_iter().rev() {
                self.queue.push((*child).clone());
            }
        }
        None
    }
}

impl<const KEY_LEN: usize, const PREFIX_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    std::iter::FusedIterator for PATCHIntoPrefixSetIterator<KEY_LEN, PREFIX_LEN, O, V, H>
{
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> Iterator
    for PATCHOrderedIterator<'a, KEY_LEN, O, V, H>
{
    type Item = &'a [u8; KEY_LEN];

    fn next(&mut self) -> Option<Self::Item> {
        let mut level = self.stack.last_mut()?;
        loop {
            if let Some(child) = level.pop() {
                match child.body_ref() {
                    BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => {
                        self.remaining = self.remaining.saturating_sub(1);
                        return Some(child.childleaf_key());
                    }
                    BodyRef::Branch(branch) => {
                        self.stack.push(ArrayVec::new());
                        level = self.stack.last_mut()?;
                        level.extend(branch.child_table.iter().filter_map(|c| c.as_ref()));
                        level.sort_unstable_by_key(|&k| Reverse(k.key())); // We need to reverse here because we pop from the vec.
                    }
                }
            } else {
                self.stack.pop();
                level = self.stack.last_mut()?;
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> ExactSizeIterator
    for PATCHOrderedIterator<'a, KEY_LEN, O, V, H>
{
}

impl<'a, const KEY_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash> std::iter::FusedIterator
    for PATCHOrderedIterator<'a, KEY_LEN, O, V, H>
{
}

/// A zero-copy set view over distinct prefixes at one PATCH segment boundary.
///
/// The view borrows the physical trie. It neither allocates a second PATCH nor
/// gives suffix multiplicity semantic weight. Iteration collapses every suffix
/// subtree to its one shared prefix.
#[derive(Clone, Copy)]
pub struct PATCHPrefixSet<
    'a,
    const KEY_LEN: usize,
    const PREFIX_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    patch: &'a PATCH<KEY_LEN, O, V, H>,
}

impl<'a, const KEY_LEN: usize, const PREFIX_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    PATCHPrefixSet<'a, KEY_LEN, PREFIX_LEN, O, V, H>
{
    fn new(patch: &'a PATCH<KEY_LEN, O, V, H>) -> Self {
        const {
            assert!(PREFIX_LEN > 0, "a prefix set needs at least one byte");
            assert!(PREFIX_LEN <= KEY_LEN);
            if PREFIX_LEN < KEY_LEN {
                assert!(
                    <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                        [O::TREE_TO_KEY[PREFIX_LEN - 1]]
                        != <O as KeySchema<KEY_LEN>>::Segmentation::SEGMENTS
                            [O::TREE_TO_KEY[PREFIX_LEN]],
                    "PREFIX_LEN must align to a segment boundary",
                );
            }
        }
        Self { patch }
    }

    /// Whether at least one physical key has this projected prefix.
    pub fn contains(&self, prefix: &[u8; PREFIX_LEN]) -> bool {
        self.patch.has_prefix(prefix)
    }

    /// Enumerate each projected prefix once in tree order.
    pub fn iter(&self) -> PATCHPrefixSetIterator<'a, KEY_LEN, PREFIX_LEN, O, V, H> {
        PATCHPrefixSetIterator {
            inner: self.patch.iter_prefix_count(),
        }
    }

    /// Whether this projected set has no members.
    pub fn is_empty(&self) -> bool {
        self.patch.is_empty()
    }

    /// Intersect this projected set with an ordinary key-only PATCH.
    ///
    /// The returned PATCH retains `other`'s hash policy, making this suitable
    /// for filtering a typed semantic cover through a larger physical index.
    pub fn intersection<OH: PatchHash>(
        &self,
        other: &PATCH<PREFIX_LEN, IdentitySchema, (), OH>,
    ) -> PATCH<PREFIX_LEN, IdentitySchema, (), OH> {
        let keys = other
            .iter_ordered()
            .filter(|key| self.contains(key))
            .copied()
            .collect();
        PATCH::from_owned_keys(keys)
    }
}

/// Iterator over a [`PATCHPrefixSet`].
pub struct PATCHPrefixSetIterator<
    'a,
    const KEY_LEN: usize,
    const PREFIX_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    inner: PATCHPrefixIterator<'a, KEY_LEN, PREFIX_LEN, O, V, H>,
}

impl<'a, const KEY_LEN: usize, const PREFIX_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    Iterator for PATCHPrefixSetIterator<'a, KEY_LEN, PREFIX_LEN, O, V, H>
{
    type Item = [u8; PREFIX_LEN];

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(prefix, _count)| prefix)
    }
}

impl<'a, const KEY_LEN: usize, const PREFIX_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    std::iter::FusedIterator for PATCHPrefixSetIterator<'a, KEY_LEN, PREFIX_LEN, O, V, H>
{
}

/// An iterator over all keys in a PATCH that have a given prefix.
/// The keys are returned in tree ordering and in tree order.
pub struct PATCHPrefixIterator<
    'a,
    const KEY_LEN: usize,
    const PREFIX_LEN: usize,
    O: KeySchema<KEY_LEN>,
    V,
    H: PatchHash = XorSip128,
> {
    stack: Vec<ArrayVec<&'a Head<KEY_LEN, O, V, H>, 256>>,
}

impl<'a, const KEY_LEN: usize, const PREFIX_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    PATCHPrefixIterator<'a, KEY_LEN, PREFIX_LEN, O, V, H>
{
    fn new(patch: &'a PATCH<KEY_LEN, O, V, H>) -> Self {
        const {
            assert!(PREFIX_LEN <= KEY_LEN);
        }
        let mut r = PATCHPrefixIterator {
            stack: Vec::with_capacity(PREFIX_LEN),
        };
        if let Some(root) = &patch.root {
            r.stack.push(ArrayVec::new());
            if root.end_depth() >= PREFIX_LEN {
                r.stack[0].push(root);
            } else {
                let BodyRef::Branch(branch) = root.body_ref() else {
                    unreachable!();
                };
                let first_level = &mut r.stack[0];
                first_level.extend(branch.child_table.iter().filter_map(|c| c.as_ref()));
                first_level.sort_unstable_by_key(|&k| Reverse(k.key())); // We need to reverse here because we pop from the vec.
            }
        }
        r
    }
}

impl<'a, const KEY_LEN: usize, const PREFIX_LEN: usize, O: KeySchema<KEY_LEN>, V, H: PatchHash>
    Iterator for PATCHPrefixIterator<'a, KEY_LEN, PREFIX_LEN, O, V, H>
{
    type Item = ([u8; PREFIX_LEN], u64);

    fn next(&mut self) -> Option<Self::Item> {
        let mut level = self.stack.last_mut()?;
        loop {
            if let Some(child) = level.pop() {
                if child.end_depth() >= PREFIX_LEN {
                    let key = O::tree_ordered(child.childleaf_key());
                    let suffix_count = child.count();
                    return Some((key[0..PREFIX_LEN].try_into().unwrap(), suffix_count));
                } else {
                    let BodyRef::Branch(branch) = child.body_ref() else {
                        unreachable!();
                    };
                    self.stack.push(ArrayVec::new());
                    level = self.stack.last_mut()?;
                    level.extend(branch.child_table.iter().filter_map(|c| c.as_ref()));
                    level.sort_unstable_by_key(|&k| Reverse(k.key())); // We need to reverse here because we pop from the vec.
                }
            } else {
                self.stack.pop();
                level = self.stack.last_mut()?;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use itertools::Itertools;
    use proptest::prelude::*;
    use std::collections::HashSet;
    use std::convert::TryInto;
    use std::iter::FromIterator;
    use std::mem;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[repr(C, align(16))]
    struct AlignedArchivePair([[u8; 16]; 2]);

    #[repr(C, align(16))]
    struct AlignedArchiveKey<const KEY_LEN: usize>([u8; KEY_LEN]);

    fn blake_patch<const KEY_LEN: usize>(
        keys: &[[u8; KEY_LEN]],
    ) -> PATCH<KEY_LEN, IdentitySchema, (), Blake3Merkle> {
        let mut patch = PATCH::new();
        for key in keys {
            patch.insert(&Entry::<KEY_LEN, (), Blake3Merkle>::new(key));
        }
        patch
    }

    fn inventory_keys<const KEY_LEN: usize>(len: usize) -> Vec<[u8; KEY_LEN]> {
        assert!(KEY_LEN >= 8);
        (0..len)
            .map(|index| {
                let mut key = [0u8; KEY_LEN];
                key[..8].copy_from_slice(&(index as u64).to_be_bytes());
                let mut state = (index as u64) ^ 0x243f_6a88_85a3_08d3;
                for byte in &mut key[8..] {
                    state ^= state >> 12;
                    state ^= state << 25;
                    state ^= state >> 27;
                    *byte = state.wrapping_mul(0x2545_f491_4f6c_dd1d) as u8;
                }
                key
            })
            .collect()
    }

    #[test]
    fn bulk_owned_build_canonicalizes_order_duplicates_and_edit_history() {
        let keys = inventory_keys::<16>(4_097);
        let mut noisy = keys.clone();
        noisy.reverse();
        noisy.extend(keys.iter().step_by(7).copied());
        noisy.rotate_left(997);

        let bulk = PATCH::<16, IdentitySchema, (), Blake3Merkle>::from_keys(noisy.clone());
        let bulk_reversed =
            PATCH::<16, IdentitySchema, (), Blake3Merkle>::from_keys(noisy.into_iter().rev());
        let inserted = blake_patch(&keys);
        let mut edited = blake_patch(&keys.iter().rev().copied().collect::<Vec<_>>());
        for key in keys.iter().step_by(5) {
            edited.remove(key);
        }
        for key in keys.iter().step_by(5).rev() {
            edited.insert(&Entry::new(key));
        }

        let expected_root = inserted.merkle_root();
        assert_eq!(bulk.len(), keys.len() as u64);
        assert_eq!(bulk.merkle_root(), expected_root);
        assert_eq!(bulk_reversed.merkle_root(), expected_root);
        assert_eq!(edited.merkle_root(), expected_root);
        assert_eq!(bulk, inserted);
        assert_eq!(
            bulk.merkle_node(&[])
                .unwrap()
                .items_after(None, usize::MAX)
                .collect::<Vec<_>>(),
            keys
        );
    }

    #[test]
    fn bulk_owned_build_handles_empty_singleton_and_already_canonical_input() {
        let empty = PATCH::<16, IdentitySchema, (), Blake3Merkle>::from_keys([]);
        assert!(empty.is_empty());
        assert_eq!(empty.merkle_root(), None);

        let key = [42; 16];
        let singleton = PATCH::<16, IdentitySchema, (), Blake3Merkle>::from_keys([key]);
        assert_eq!(singleton.len(), 1);
        assert_eq!(singleton.merkle_node(&[]).unwrap().representative(), &key);

        let canonical = inventory_keys::<16>(1_024);
        let bulk = PATCH::<16, IdentitySchema, (), Blake3Merkle>::from_keys(canonical.clone());
        assert_eq!(
            bulk.merkle_node(&[])
                .unwrap()
                .items_after(None, usize::MAX)
                .collect::<Vec<_>>(),
            canonical
        );
    }

    static BULK_LEAF_HASHES: AtomicUsize = AtomicUsize::new(0);
    static BULK_BRANCH_HASHES: AtomicUsize = AtomicUsize::new(0);

    struct CountingBlake3;
    impl sealed::Sealed for CountingBlake3 {}
    impl PatchHash for CountingBlake3 {
        type Digest = [u8; 32];
        type BranchState = blake3::Hasher;
        const COMMUTATIVE_BRANCH: bool = false;
        const INCREMENTAL_BRANCH: bool = false;

        fn init() {
            Blake3Merkle::init();
        }

        fn leaf(bytes: &[u8]) -> Self::Digest {
            BULK_LEAF_HASHES.fetch_add(1, Ordering::Relaxed);
            Blake3Merkle::leaf(bytes)
        }

        fn begin_branch(
            representative: &[u8],
            tree_to_key: &[usize],
            end_depth: usize,
            child_count: usize,
            leaf_count: u64,
        ) -> Self::BranchState {
            Blake3Merkle::begin_branch(
                representative,
                tree_to_key,
                end_depth,
                child_count,
                leaf_count,
            )
        }

        fn push_child(
            state: &mut Self::BranchState,
            edge: u8,
            leaf_count: u64,
            digest: Self::Digest,
        ) {
            Blake3Merkle::push_child(state, edge, leaf_count, digest);
        }

        fn finish_branch(state: Self::BranchState) -> Self::Digest {
            BULK_BRANCH_HASHES.fetch_add(1, Ordering::Relaxed);
            Blake3Merkle::finish_branch(state)
        }

        fn edit_branch(
            _current: Self::Digest,
            _edge: u8,
            _old: Option<Self::Digest>,
            _new: Option<Self::Digest>,
        ) -> Self::Digest {
            unreachable!("the counting Merkle policy is not incremental")
        }
    }

    #[test]
    fn bulk_owned_build_hashes_each_final_node_once_plus_debug_audit() {
        BULK_LEAF_HASHES.store(0, Ordering::Relaxed);
        BULK_BRANCH_HASHES.store(0, Ordering::Relaxed);
        let keys = inventory_keys::<16>(10_000);
        let patch = PATCH::<16, IdentitySchema, (), CountingBlake3>::from_owned_keys(keys.clone());
        let (branches, _, heap_leaves, archive_leaves) = patch.node_stats();

        assert_eq!(patch.len(), keys.len() as u64);
        assert_eq!(heap_leaves, keys.len() as u64);
        assert_eq!(archive_leaves, 0);
        assert_eq!(BULK_LEAF_HASHES.load(Ordering::Relaxed), keys.len());
        // The build itself finishes each branch once. Debug builds then
        // deliberately recompute it once inside Branch's invariant audit;
        // optimized production builds compile that verification away.
        let expected_branch_hashes = branches as usize * if cfg!(debug_assertions) { 2 } else { 1 };
        assert_eq!(
            BULK_BRANCH_HASHES.load(Ordering::Relaxed),
            expected_branch_hashes
        );
    }

    struct BulkUnwindProbe(Arc<AtomicUsize>);

    impl Drop for BulkUnwindProbe {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn wider_known_hash_branch_owns_every_child_during_unwind() {
        let drops = Arc::new(AtomicUsize::new(0));
        let keys = [[1, 0], [2, 0], [3, 0]];
        let digests = keys.map(|key| Blake3Merkle::leaf(&key));
        let mut state = Blake3Merkle::begin_branch(
            &keys[0],
            &<IdentitySchema as KeySchema<2>>::TREE_TO_KEY,
            0,
            keys.len(),
            keys.len() as u64,
        );
        for (edge, digest) in [1, 2, 3].into_iter().zip(digests) {
            Blake3Merkle::push_child(&mut state, edge, 1, digest);
        }
        let final_hash = Blake3Merkle::finish_branch(state);

        let leaf = |key: &[u8; 2]| {
            // SAFETY: every returned allocation is immediately transferred
            // into exactly one owning Head.
            unsafe {
                Leaf::<2, BulkUnwindProbe, Blake3Merkle>::new(key, BulkUnwindProbe(drops.clone()))
            }
        };
        type ProbeHead = Head<2, IdentitySchema, BulkUnwindProbe, Blake3Merkle>;
        let first = ProbeHead::new(0, leaf(&keys[0])).with_key(1);
        let second = ProbeHead::new(0, leaf(&keys[1])).with_key(2);
        let third = ProbeHead::new(0, leaf(&keys[2])).with_key(3);
        let body = Branch::new_with_known_hash_capacity(0, first, second, final_hash, 4);
        let mut root = Head::new(0, body);

        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut editor = BranchMut::from_head(&mut root);
            editor.install_child_growing(third);
            // This is the only interval where the branch contains every
            // child but its structural counts still describe the initial
            // pair. BranchMut's Drop must nevertheless return the current
            // allocation to `root`, whose ordinary destructor owns all three.
            panic!("interrupt wider bottom-up assembly");
        }));
        assert!(panic.is_err());
        drop(root);
        assert_eq!(drops.load(Ordering::Relaxed), keys.len());
    }

    fn merkle_inventory<const KEY_LEN: usize, V>(
        node: PATCHMerkleNode<'_, KEY_LEN, V>,
        out: &mut Vec<(Vec<u8>, [u8; 32], u64, usize, [u8; KEY_LEN], Vec<u8>)>,
    ) {
        let child_edges = node.children().map(|(edge, _)| edge).collect::<Vec<_>>();
        out.push((
            node.prefix().to_vec(),
            node.digest(),
            node.leaf_count(),
            node.end_depth(),
            *node.representative(),
            child_edges,
        ));
        for (_, child) in node.children() {
            merkle_inventory(child, out);
        }
    }

    #[test]
    fn merkle_prefix_lookup_canonicalizes_compressed_paths_and_orders_children() {
        let patch = blake_patch(&[[1, 2, 3, 255], [1, 2, 3, 0]]);
        let root = patch.merkle_node(&[]).expect("nonempty PATCH");
        assert_eq!(root.end_depth(), 3);
        assert_eq!(root.prefix(), &[1, 2, 3]);
        assert_eq!(root.leaf_count(), 2);
        assert!(!root.is_leaf());

        for request in [&[][..], &[1][..], &[1, 2][..], &[1, 2, 3][..]] {
            let located = patch.merkle_node(request).expect("compressed prefix");
            assert_eq!(located.digest(), root.digest());
            assert_eq!(located.prefix(), &[1, 2, 3]);
        }
        assert!(patch.merkle_node(&[1, 2, 4]).is_none());
        assert!(patch.merkle_node(&[1, 2, 3, 0, 0]).is_none());

        let children = root.children().collect::<Vec<_>>();
        assert_eq!(
            children.iter().map(|(edge, _)| *edge).collect::<Vec<_>>(),
            [0, 255]
        );
        for (edge, child) in children {
            assert!(child.is_leaf());
            assert_eq!(child.leaf_count(), 1);
            assert_eq!(child.end_depth(), 4);
            assert_eq!(child.representative()[3], edge);
            assert_eq!(child.prefix(), child.representative());
            assert_eq!(child.children().len(), 0);
        }

        let debug = format!("{root:?}");
        assert!(debug.contains("PATCHMerkleNode"));
        assert!(!debug.contains("child_table"));
        assert!(!debug.contains("Branch"));
    }

    #[test]
    fn merkle_prefix_lookup_reports_compressed_shape_mismatches_without_aliasing_nodes() {
        let compressed = blake_patch(&[[1, 2, 3, 0], [1, 2, 3, 255]]);
        let split_earlier = blake_patch(&[[1, 2, 3, 0], [1, 2, 4, 0]]);

        let compressed_root = compressed.merkle_node(&[]).expect("root");
        assert_eq!(compressed_root.prefix(), &[1, 2, 3]);
        let corresponding = split_earlier
            .merkle_node(compressed_root.prefix())
            .expect("the shared key still exists");
        assert!(corresponding.is_leaf());
        assert_eq!(corresponding.prefix(), &[1, 2, 3, 0]);
        assert_ne!(corresponding.digest(), compressed_root.digest());
        assert_ne!(corresponding.leaf_count(), compressed_root.leaf_count());

        let earlier_root = split_earlier.merkle_node(&[]).expect("root");
        assert_eq!(earlier_root.prefix(), &[1, 2]);
        let covered = compressed
            .merkle_node(earlier_root.prefix())
            .expect("request ends inside compressed path");
        assert_eq!(covered.prefix(), &[1, 2, 3]);
        assert_eq!(covered.digest(), compressed_root.digest());
    }

    #[test]
    fn merkle_traversal_is_history_independent() {
        let keys: Vec<[u8; 4]> = (0u8..64)
            .map(|i| [i.wrapping_mul(73), i / 4, i.wrapping_mul(11), 255 - i])
            .collect();
        let forward = blake_patch(&keys);
        let mut reversed_keys = keys.clone();
        reversed_keys.reverse();
        let reversed = blake_patch(&reversed_keys);
        let mut edited = reversed.clone();
        for key in keys.iter().step_by(3) {
            edited.remove(key);
        }
        for key in keys.iter().step_by(3).rev() {
            edited.insert(&Entry::<4, (), Blake3Merkle>::new(key));
        }

        let inventory = |patch: &PATCH<4, IdentitySchema, (), Blake3Merkle>| {
            let mut out = Vec::new();
            merkle_inventory(patch.merkle_node(&[]).expect("root"), &mut out);
            out
        };
        assert_eq!(inventory(&forward), inventory(&reversed));
        assert_eq!(inventory(&forward), inventory(&edited));

        let mut expected = keys.clone();
        expected.sort_unstable();
        for patch in [&forward, &reversed, &edited] {
            let root = patch.merkle_node(&[]).expect("root");
            let mut paged = Vec::new();
            let mut after = None;
            loop {
                let page = root.items_after(after.as_ref(), 7).collect::<Vec<_>>();
                if page.is_empty() {
                    break;
                }
                after = page.last().copied();
                paged.extend(page);
            }
            assert_eq!(paged, expected);
        }
    }

    #[test]
    fn merkle_items_are_prefix_scoped_exclusive_and_hard_bounded() {
        let mut keys = Vec::new();
        for i in 0u8..32 {
            keys.push([7, i, i.wrapping_mul(17), 255 - i]);
            keys.push([8, i, 0, 0]);
        }
        let patch = blake_patch(&keys);
        let node = patch.merkle_node(&[7]).expect("prefix seven");

        let mut empty = node.items_after(None, 0);
        assert_eq!(empty.size_hint(), (0, Some(0)));
        assert_eq!(empty.next(), None);
        assert_eq!(empty.next(), None);

        let first_five = node.items_after(None, 5).collect::<Vec<_>>();
        assert_eq!(first_five.len(), 5);
        assert!(first_five.windows(2).all(|pair| pair[0] < pair[1]));
        assert!(first_five.iter().all(|key| key[0] == 7));

        let cursor = [7, 4, 128, 0];
        let after = node.items_after(Some(&cursor), 3).collect::<Vec<_>>();
        assert_eq!(after.len(), 3);
        assert!(after.iter().all(|key| key > &cursor && key[0] == 7));

        let exact = keys
            .iter()
            .copied()
            .filter(|key| key[0] == 7)
            .nth(12)
            .unwrap();
        let exclusive = node
            .items_after(Some(&exact), usize::MAX)
            .collect::<Vec<_>>();
        assert!(exclusive.iter().all(|key| key > &exact && key[0] == 7));
        assert!(!exclusive.contains(&exact));
        assert_eq!(exclusive.len(), 19);

        assert_eq!(node.items_after(Some(&[255; 4]), 10).next(), None);
        let mut one = node.items_after(None, 1);
        assert_eq!(one.size_hint(), (0, Some(1)));
        assert!(one.next().is_some());
        assert_eq!(one.size_hint(), (0, Some(0)));
        assert_eq!(one.next(), None);
    }

    #[test]
    fn merkle_views_do_not_require_or_expose_values() {
        struct NotDebug(u8);

        let key = [9, 8, 7, 6];
        let entry = Entry::<4, NotDebug, Blake3Merkle>::with_value(&key, NotDebug(42));
        let mut patch = PATCH::<4, IdentitySchema, NotDebug, Blake3Merkle>::new();
        patch.insert(&entry);
        let node = patch.merkle_node(&[]).expect("root");
        assert_eq!(node.items_after(None, 1).collect::<Vec<_>>(), [key]);
        assert!(format!("{node:?}").contains("PATCHMerkleNode"));
        assert_eq!(entry.value().0, 42);
    }

    #[test]
    fn blake3_merkle_authenticates_reconciliation_descriptor() {
        fn framed(representative: [u8; 16], leaf_count: u64, child_counts: [u64; 2]) -> [u8; 32] {
            let mut state = Blake3Merkle::begin_branch(
                &representative,
                &<IdentitySchema as KeySchema<16>>::TREE_TO_KEY,
                4,
                2,
                leaf_count,
            );
            Blake3Merkle::push_child(&mut state, 3, child_counts[0], [7; 32]);
            Blake3Merkle::push_child(&mut state, 9, child_counts[1], [11; 32]);
            Blake3Merkle::finish_branch(state)
        }

        let representative = [5; 16];
        let canonical = framed(representative, 4, [1, 3]);
        assert_ne!(canonical, framed(representative, 5, [1, 3]));
        assert_ne!(canonical, framed(representative, 4, [2, 2]));

        let mut different_prefix = representative;
        different_prefix[2] ^= 1;
        assert_ne!(canonical, framed(different_prefix, 4, [1, 3]));

        let mut different_suffix = representative;
        different_suffix[7] ^= 1;
        assert_eq!(canonical, framed(different_suffix, 4, [1, 3]));
    }

    #[test]
    fn blake3_merkle_is_history_independent_across_edits_and_set_operations() {
        let keys = [
            [0, 0, 0, 0],
            [0, 0, 1, 0],
            [0, 2, 0, 0],
            [3, 0, 0, 0],
            [3, 0, 0, 9],
            [255, 1, 2, 3],
        ];

        let forward = blake_patch(&keys);
        let mut reversed_keys = keys;
        reversed_keys.reverse();
        let reversed = blake_patch(&reversed_keys);
        assert_eq!(forward.merkle_root(), reversed.merkle_root());
        assert_eq!(forward, reversed);

        let mut edited = forward.clone();
        edited.remove(&keys[2]);
        edited.insert(&Entry::<4, (), Blake3Merkle>::new(&keys[2]));
        assert_eq!(edited.merkle_root(), forward.merkle_root());

        let left = blake_patch(&keys[..4]);
        let right = blake_patch(&keys[2..]);
        let mut union = left.clone();
        union.union(right.clone());
        assert_eq!(union.merkle_root(), forward.merkle_root());

        let expected_intersection = blake_patch(&keys[2..4]);
        assert_eq!(
            left.intersect(&right).merkle_root(),
            expected_intersection.merkle_root()
        );

        let expected_difference = blake_patch(&keys[..2]);
        assert_eq!(
            left.difference(&right).merkle_root(),
            expected_difference.merkle_root()
        );
    }

    #[test]
    fn blake3_merkle_heap_and_archive_construction_have_the_same_root() {
        #[repr(C, align(16))]
        struct AlignedBlakeArchive([[u8; 16]; 6]);

        let storage = Arc::new(AlignedBlakeArchive([
            [0; 16], [1; 16], [2; 16], [3; 16], [17; 16], [255; 16],
        ]));
        let owner: Arc<dyn ArchiveOwner> = storage.clone();
        let hashes = storage.0.map(|key| Blake3Merkle::leaf(&key));
        let mut rows = [5, 3, 1, 4, 0, 2];

        // SAFETY: the aligned wrapper makes every 16-byte row 16-byte
        // aligned, the rows are a permutation, the keys are distinct and
        // immutable, and `owner` retains the allocation.
        let archive = unsafe {
            PATCH::<16, IdentitySchema, (), Blake3Merkle>::from_archive_partition(
                &storage.0, &hashes, &mut rows, &owner,
            )
        };
        let heap = blake_patch(&storage.0);

        assert_eq!(archive.merkle_root(), heap.merkle_root());
        assert_eq!(archive, heap);
        let archive_root = archive.merkle_node(&[]).expect("archive root");
        assert_eq!(archive_root.leaf_count(), 6);
        assert_eq!(
            archive_root
                .items_after(None, usize::MAX)
                .collect::<Vec<_>>(),
            storage.0
        );
    }

    crate::key_segmentation!(PermutedInfixSegments, 12, [4, 4, 4]);
    crate::key_schema!(PermutedInfixSchema, PermutedInfixSegments, 12, [1, 2, 0]);
    crate::key_segmentation!(PrefixProjectionSegments, 6, [4, 2]);
    crate::key_schema!(PrefixProjectionSchema, PrefixProjectionSegments, 6, [0, 1]);
    crate::key_segmentation!(PrefixSharingBlobSegments, 40, [32, 8]);
    crate::key_schema!(
        PrefixSharingBlobSchema,
        PrefixSharingBlobSegments,
        40,
        [0, 1]
    );

    #[test]
    fn shares_prefix_handles_empty_and_full_prefixes() {
        let empty = PATCH::<4, IdentitySchema>::new();
        let key = [1, 2, 3, 4];
        assert!(empty.shares_prefix(&empty.clone(), &[]));
        assert!(empty.shares_prefix(&empty.clone(), &key));

        let mut populated = empty.clone();
        populated.insert(&Entry::new(&key));
        assert!(!empty.shares_prefix(&populated, &[]));
        assert!(!empty.shares_prefix(&populated, &key));
        assert!(!populated.shares_prefix(&empty, &[1, 2]));
        assert!(populated.shares_prefix(&empty, &[1, 9]));
        assert!(populated.shares_prefix(&populated.clone(), &[]));
        assert!(populated.shares_prefix(&populated.clone(), &key));

        let mut rebuilt = PATCH::<4, IdentitySchema>::new();
        rebuilt.insert(&Entry::new(&key));
        assert_eq!(populated, rebuilt);
        assert!(!populated.shares_prefix(&rebuilt, &[]));
        assert!(!populated.shares_prefix(&rebuilt, &key));
    }

    #[test]
    fn shares_prefix_retains_compressed_subtrees_after_unrelated_insertions() {
        let mut original = PATCH::<4, IdentitySchema>::new();
        original.insert(&Entry::new(&[1, 2, 3, 0]));
        original.insert(&Entry::new(&[1, 2, 3, 255]));
        assert_eq!(original.root.as_ref().unwrap().end_depth(), 3);

        let mut outside = original.clone();
        outside.insert(&Entry::new(&[9, 8, 7, 6]));
        // The old compressed root becomes a child with a different edge byte.
        assert!(!original.shares_prefix(&outside, &[]));
        assert!(original.shares_prefix(&outside, &[1]));
        assert!(original.shares_prefix(&outside, &[1, 2]));
        assert!(original.shares_prefix(&outside, &[1, 2, 3]));
        assert!(original.shares_prefix(&outside, &[1, 2, 3, 0]));
        assert!(original.shares_prefix(&outside, &[1, 2, 4]));

        let mut split = outside.clone();
        split.insert(&Entry::new(&[1, 2, 4, 0]));
        assert!(!outside.shares_prefix(&split, &[1]));
        assert!(!outside.shares_prefix(&split, &[1, 2]));
        assert!(!outside.shares_prefix(&split, &[1, 2, 4]));
        assert!(outside.shares_prefix(&split, &[1, 2, 3]));
        assert!(outside.shares_prefix(&split, &[9]));

        let mut inside = split.clone();
        inside.insert(&Entry::new(&[1, 2, 3, 127]));
        assert!(!split.shares_prefix(&inside, &[1, 2, 3]));
        assert!(split.shares_prefix(&inside, &[1, 2, 3, 0]));
        assert!(split.shares_prefix(&inside, &[1, 2, 4]));
    }

    #[test]
    fn shares_prefix_detects_an_additional_physical_blob_occurrence() {
        let physical_key = |hash: [u8; 32], offset: u64| {
            let mut key = [0; 40];
            key[..32].copy_from_slice(&hash);
            key[32..].copy_from_slice(&offset.to_be_bytes());
            key
        };
        let hash = [7; 32];
        let other_hash = [9; 32];
        let first = physical_key(hash, 512);
        let mut before = PATCH::<40, PrefixSharingBlobSchema>::new();
        before.insert(&Entry::new(&first));
        before.insert(&Entry::new(&physical_key(other_hash, 1024)));
        let mut after = before.clone();
        after.insert(&Entry::new(&physical_key(hash, 2048)));

        assert_eq!(
            before.prefix_set::<32>().iter().collect::<Vec<_>>(),
            after.prefix_set::<32>().iter().collect::<Vec<_>>()
        );
        assert!(!before.shares_prefix(&after, &hash));
        assert!(before.shares_prefix(&after, &first));
        assert!(before.shares_prefix(&after, &other_hash));
    }

    #[test]
    fn shares_prefix_observes_replaced_values_with_unchanged_keys() {
        let key = [1, 2, 3, 4];
        let sibling = [1, 2, 3, 9];
        let unrelated = [9, 8, 7, 6];
        let mut before = PATCH::<4, IdentitySchema, u64>::new();
        for key in [key, sibling, unrelated] {
            before.insert(&Entry::with_value(&key, 10));
        }
        let mut after = before.clone();
        after.replace(&Entry::with_value(&key, 11));

        assert_eq!(before, after);
        assert_eq!(before.get(&key), Some(&10));
        assert_eq!(after.get(&key), Some(&11));
        assert!(!before.shares_prefix(&after, &key));
        assert!(!before.shares_prefix(&after, &[1, 2, 3]));
        assert!(before.shares_prefix(&after, &sibling));
        assert!(before.shares_prefix(&after, &[9]));
    }

    #[test]
    fn shares_prefix_uses_tree_order_inside_permuted_segments() {
        let first = [30, 31, 32, 33, 1, 2, 3, 4, 5, 6, 7, 8];
        let mut sibling = first;
        sibling[0] = 40;
        let mut before = PATCH::<12, PermutedInfixSchema>::new();
        before.insert(&Entry::new(&first));
        before.insert(&Entry::new(&sibling));

        let mut unrelated = first;
        unrelated[4..8].copy_from_slice(&[9, 8, 7, 6]);
        let mut after = before.clone();
        after.insert(&Entry::new(&unrelated));
        assert!(before.shares_prefix(&after, &[1, 2]));
        assert!(before.shares_prefix(&after, &[1, 2, 3, 4]));
        assert!(before.shares_prefix(
            &after,
            &<PermutedInfixSchema as KeySchema<12>>::tree_ordered(&first)
        ));
        assert!(!before.shares_prefix(&after, &[9, 8]));

        let mut added = first;
        added[6] = 8;
        let mut split = after.clone();
        split.insert(&Entry::new(&added));
        assert!(!after.shares_prefix(&split, &[1, 2]));
        assert!(after.shares_prefix(&split, &[1, 2, 3, 4]));
    }

    #[test]
    fn prefix_set_projects_away_suffix_multiplicity_and_order() {
        let first = [1, 2, 3, 4];
        let second = [5, 6, 7, 8];
        let physical_key = |prefix: [u8; 4], suffix: [u8; 2]| {
            let mut key = [0; 6];
            key[..4].copy_from_slice(&prefix);
            key[4..].copy_from_slice(&suffix);
            key
        };

        let mut left = PATCH::<6, PrefixProjectionSchema>::new();
        for key in [
            physical_key(first, [0, 2]),
            physical_key(second, [0, 9]),
            physical_key(first, [0, 1]),
        ] {
            left.insert(&Entry::new(&key));
        }
        let mut right = PATCH::<6, PrefixProjectionSchema>::new();
        for key in [physical_key(second, [7, 7]), physical_key(first, [8, 8])] {
            right.insert(&Entry::new(&key));
        }

        assert_eq!(
            left.clone().into_prefixes::<4>().collect::<Vec<_>>(),
            vec![first, second]
        );
        let left = left.prefix_set::<4>();
        let right = right.prefix_set::<4>();
        assert_eq!(left.iter().collect::<Vec<_>>(), vec![first, second]);
        assert_eq!(right.iter().collect::<Vec<_>>(), vec![first, second]);
        assert!(left.contains(&first));
        assert!(left.contains(&second));
        assert!(!left.contains(&[9; 4]));
        assert_eq!(
            left.iter().collect::<Vec<_>>(),
            right.iter().collect::<Vec<_>>()
        );
    }

    #[test]
    fn prefix_set_intersection_retains_the_other_patch_policy() {
        let physical_key = |prefix: [u8; 4], suffix: [u8; 2]| {
            let mut key = [0; 6];
            key[..4].copy_from_slice(&prefix);
            key[4..].copy_from_slice(&suffix);
            key
        };
        let resident = [[1; 4], [3; 4], [5; 4]];
        let mut physical = PATCH::<6, PrefixProjectionSchema>::new();
        for (prefix, suffix) in [
            (resident[0], [0, 1]),
            (resident[0], [0, 2]),
            (resident[1], [0, 3]),
            (resident[2], [0, 4]),
        ] {
            physical.insert(&Entry::new(&physical_key(prefix, suffix)));
        }

        let requested = PATCH::<4, IdentitySchema, (), Blake3Merkle>::from_keys([
            [0; 4],
            resident[0],
            [2; 4],
            resident[1],
            [4; 4],
            resident[2],
            [6; 4],
        ]);
        let actual = physical.prefix_set::<4>().intersection(&requested);
        let expected = PATCH::<4, IdentitySchema, (), Blake3Merkle>::from_keys(resident);
        assert_eq!(actual, expected);
        assert_eq!(actual.merkle_root(), expected.merkle_root());
    }

    struct PanicOnDrop(bool);

    impl Drop for PanicOnDrop {
        fn drop(&mut self) {
            if self.0 {
                panic!("intentional value drop panic");
            }
        }
    }

    /// Build the smallest all-LocalLeaf PATCH and return a weak witness for
    /// its backing allocation. The returned PATCH is the allocation's only
    /// strong owner, so liveness assertions fail before a dangling pointer is
    /// ever dereferenced.
    fn owned_archive_pair(
        keys: [[u8; 16]; 2],
    ) -> (
        PATCH<16, IdentitySchema>,
        std::sync::Weak<AlignedArchivePair>,
    ) {
        let storage = std::sync::Arc::new(AlignedArchivePair(keys));
        let weak = std::sync::Arc::downgrade(&storage);
        let owner: std::sync::Arc<dyn ArchiveOwner> = storage.clone();
        let hashes = [hash_key(&storage.0[0]), hash_key(&storage.0[1])];
        let mut rows = [0, 1];
        // SAFETY: AlignedArchivePair is 16-byte aligned, each 16-byte row has
        // the same alignment, the two keys are distinct in every fixture, and
        // `owner` retains the immutable storage throughout construction.
        let patch =
            unsafe { PATCH::from_archive_partition(&storage.0, &hashes, &mut rows, &owner) };
        assert_eq!(patch.node_stats(), (1, 2, 0, 2));
        drop(owner);
        drop(storage);
        (patch, weak)
    }

    /// The out-of-place pass exists only to do what the in-place one does,
    /// on more than one worker. Pin that: same split depth, same occupied
    /// bytes, same interval per byte, same rows inside each interval.
    ///
    /// Order *within* an interval is deliberately unspecified — keys are
    /// distinct, so a bucket's subtrie is a function of its key set — and the
    /// assertion is written to say so rather than to accidentally depend on
    /// it.
    #[cfg(feature = "parallel")]
    #[test]
    fn parallel_partition_pass_agrees_with_the_in_place_pass() {
        type Subject = PATCH<16, IdentitySchema>;
        let len = 4 * Subject::PARTITION_ROWS_PER_WORKER;
        let mut keys: Vec<[u8; 16]> = Vec::with_capacity(len);
        let mut state = 0x243f_6a88_85a3_08d3u64;
        for index in 0..len {
            state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
            let mut mixed = state;
            mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
            mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
            mixed ^= mixed >> 31;
            let mut key = [0u8; 16];
            // Nine rows in ten share a first byte, and every row shares the
            // seven bytes after it, so the representative's prefix has to be
            // walked rather than rejected on the second row.
            key[0] = if index % 10 == 0 {
                (mixed & 0xff) as u8
            } else {
                0x5a
            };
            key[1..8].copy_from_slice(&[0x5a; 7]);
            key[8..16].copy_from_slice(&(index as u64).to_be_bytes());
            keys.push(key);
        }
        keys.sort_unstable();
        keys.dedup();
        assert!(
            keys.len() > 2 * Subject::PARTITION_ROWS_PER_WORKER,
            "the fixture must be wide enough for the out-of-place pass",
        );
        assert!(Subject::partition_workers(keys.len()) > 1);

        let rows: Vec<u32> = (0..keys.len() as u32).collect();
        let mut in_place = rows.clone();
        let ordered = Subject::partition_archive_rows(&keys, &mut in_place, 0);
        let (concurrent, permuted) = Subject::partition_archive_rows_parallel(&keys, &rows, 0);

        assert_eq!(ordered.end_depth, concurrent.end_depth);
        assert_eq!(ordered.fanout, concurrent.fanout);
        assert_eq!(ordered.initial_slots, concurrent.initial_slots);
        assert_eq!(
            ordered.buckets[..ordered.fanout],
            concurrent.buckets[..concurrent.fanout],
        );
        assert_eq!(ordered.ends, concurrent.ends);

        let mut start = 0usize;
        for &byte in &ordered.buckets[..ordered.fanout] {
            let end = ordered.ends[byte as usize] as usize;
            let mut ordered_rows: Vec<u32> = in_place[start..end].to_vec();
            let mut concurrent_rows: Vec<u32> = permuted[start..end].to_vec();
            ordered_rows.sort_unstable();
            concurrent_rows.sort_unstable();
            assert_eq!(ordered_rows, concurrent_rows, "bucket {byte:#04x}");
            start = end;
        }
        assert_eq!(start, keys.len());
    }

    fn key(byte: u8) -> [u8; 16] {
        [byte; 16]
    }

    fn singleton_patch(key: [u8; 16]) -> PATCH<16, IdentitySchema> {
        let mut patch = PATCH::new();
        let entry = Entry::new(&key);
        patch.insert(&entry);
        patch
    }

    #[test]
    fn exported_fingerprint_blinding_is_not_xor_homomorphic() {
        let key = [0x5au8; 16];
        let left = 0x0123_4567_89ab_cdef_fedc_ba98_7654_3210u128;
        let right = 0xfedc_ba98_7654_3210_0123_4567_89ab_cdefu128;
        let blind_left = blind_root_hash_with_key(left, &key);
        let blind_right = blind_root_hash_with_key(right, &key);

        assert_ne!(blind_left, left);
        assert_ne!(
            blind_root_hash_with_key(left ^ right, &key),
            blind_left ^ blind_right
        );
    }

    #[test]
    fn owner_cover_shape_is_canonical_and_membership_is_exact() {
        let owners: Vec<Arc<dyn ArchiveOwner>> = (0u8..8)
            .map(|byte| Arc::new([byte]) as Arc<dyn ArchiveOwner>)
            .collect();
        let build = |order: &[usize]| {
            let mut cover = None;
            for &index in order {
                OwnerCover::retain(&mut cover, &owners[index]);
            }
            cover.unwrap()
        };

        let forward = build(&[0, 1, 2, 3, 4, 5, 6, 7]);
        let shuffled = build(&[6, 2, 7, 0, 5, 1, 4, 3]);
        assert_eq!(forward.len, owners.len());
        assert_eq!(shuffled.len, owners.len());
        assert!(forward.root.same_shape(&shuffled.root));
        for owner in &owners {
            assert!(forward.root.contains(OwnerCover::address(owner)));
        }
        let unrelated: Arc<dyn ArchiveOwner> = Arc::new([0xff]);
        assert!(!forward.root.contains(OwnerCover::address(&unrelated)));
    }

    #[test]
    fn owner_cover_overlapping_diamond_does_not_accumulate_duplicates() {
        let first_backing = Arc::new([0x11]);
        let second_backing = Arc::new([0x22]);
        let first_weak = Arc::downgrade(&first_backing);
        let second_weak = Arc::downgrade(&second_backing);
        let first: Arc<dyn ArchiveOwner> = first_backing.clone();
        let second: Arc<dyn ArchiveOwner> = second_backing.clone();

        let mut left = Some(OwnerCover::singleton(&first));
        OwnerCover::retain(&mut left, &second);
        let mut right = Some(OwnerCover::singleton(&second));
        OwnerCover::retain(&mut right, &first);
        let left_root = match &left.as_ref().unwrap().root {
            OwnerNode::Branch(branch) => Arc::downgrade(branch),
            OwnerNode::Owner(_) => panic!("two owners require one Patricia branch"),
        };
        let right_root = match &right.as_ref().unwrap().root {
            OwnerNode::Branch(branch) => Arc::downgrade(branch),
            OwnerNode::Owner(_) => panic!("two owners require one Patricia branch"),
        };

        for _ in 0..4_096 {
            let next_left = OwnerCover::union(left.clone(), &right);
            let next_right = OwnerCover::union(right.clone(), &left);
            left = next_left;
            right = next_right;
            assert_eq!(left.as_ref().unwrap().len, 2);
            assert_eq!(right.as_ref().unwrap().len, 2);
            assert!(matches!(
                &left.as_ref().unwrap().root,
                OwnerNode::Branch(branch) if Arc::as_ptr(branch) == left_root.as_ptr()
            ));
            assert!(matches!(
                &right.as_ref().unwrap().root,
                OwnerNode::Branch(branch) if Arc::as_ptr(branch) == right_root.as_ptr()
            ));
        }

        drop(first);
        drop(second);
        drop(first_backing);
        drop(second_backing);
        assert!(first_weak.upgrade().is_some());
        assert!(second_weak.upgrade().is_some());
        drop(left);
        drop(right);
        assert!(first_weak.upgrade().is_none());
        assert!(second_weak.upgrade().is_none());
    }

    #[test]
    fn repeated_latest_owner_retention_reuses_the_cover() {
        let owner: Arc<dyn ArchiveOwner> = Arc::new([0x55]);
        let mut cover = None;
        OwnerCover::retain(&mut cover, &owner);
        let original = cover.as_ref().unwrap().clone();

        for _ in 0..4_096 {
            OwnerCover::retain(&mut cover, &owner);
        }

        let cover = cover.unwrap();
        assert!(Arc::ptr_eq(&cover, &original));
        assert_eq!(cover.len, 1);
        assert!(matches!(&cover.root, OwnerNode::Owner(_)));
    }

    proptest! {
        #[test]
        fn owner_cover_union_matches_address_set(
            left in prop::collection::btree_set(0usize..24, 0..24),
            right in prop::collection::btree_set(0usize..24, 0..24),
        ) {
            let owners: Vec<Arc<dyn ArchiveOwner>> = (0u8..24)
                .map(|byte| Arc::new([byte]) as Arc<dyn ArchiveOwner>)
                .collect();
            let build = |indices: Vec<usize>| {
                let mut cover = None;
                for index in indices {
                    OwnerCover::retain(&mut cover, &owners[index]);
                }
                cover
            };
            let left_cover = build(left.iter().copied().collect());
            let right_cover = build(right.iter().rev().copied().collect());
            let joined = OwnerCover::union(left_cover, &right_cover);
            let expected: std::collections::BTreeSet<_> =
                left.union(&right).copied().collect();

            if expected.is_empty() {
                prop_assert!(joined.is_none());
            } else {
                let joined = joined.unwrap();
                let mut actual = HashSet::new();
                joined.root.for_each_owner(&mut |owner| {
                    assert!(actual.insert(OwnerCover::address(owner)));
                });
                let expected_addresses: HashSet<_> = expected
                    .iter()
                    .map(|&index| OwnerCover::address(&owners[index]))
                    .collect();
                prop_assert_eq!(actual, expected_addresses);
                prop_assert_eq!(joined.len, expected.len());

                let canonical = build(expected.iter().copied().collect()).unwrap();
                prop_assert!(joined.root.same_shape(&canonical.root));
            }
        }
    }

    #[test]
    fn disjoint_cross_owner_union_retains_both_archives() {
        let (mut left, left_owner) = owned_archive_pair([key(0x10), key(0x20)]);
        let (right, right_owner) = owned_archive_pair([key(0x30), key(0x40)]);

        left.union(right);

        assert!(
            left_owner.upgrade().is_some(),
            "union dropped its left archive"
        );
        assert!(
            right_owner.upgrade().is_some(),
            "union dropped its consumed right archive"
        );
        assert_eq!(
            left.iter().copied().collect::<HashSet<_>>(),
            HashSet::from([key(0x10), key(0x20), key(0x30), key(0x40)])
        );
        drop(left);
        assert!(left_owner.upgrade().is_none());
        assert!(right_owner.upgrade().is_none());
    }

    #[test]
    fn one_key_intersection_retains_both_source_archives() {
        let (left, left_owner) = owned_archive_pair([key(0x10), key(0x20)]);
        let (right, right_owner) = owned_archive_pair([key(0x10), key(0x30)]);

        let intersection = left.intersect(&right);
        drop(left);
        drop(right);

        assert!(
            left_owner.upgrade().is_some(),
            "intersection dropped the archive backing its surviving LocalLeaf"
        );
        assert!(
            right_owner.upgrade().is_some(),
            "intersection must conservatively retain both source covers"
        );
        assert_eq!(intersection.iter().copied().collect_vec(), vec![key(0x10)]);
        drop(intersection);
        assert!(left_owner.upgrade().is_none());
        assert!(right_owner.upgrade().is_none());
    }

    #[test]
    fn one_key_difference_retains_its_left_archive() {
        let (left, left_owner) = owned_archive_pair([key(0x10), key(0x20)]);
        let (right, right_owner) = owned_archive_pair([key(0x10), key(0x30)]);

        let difference = left.difference(&right);
        drop(left);
        drop(right);

        assert!(
            left_owner.upgrade().is_some(),
            "difference dropped the archive backing its surviving LocalLeaf"
        );
        assert!(
            right_owner.upgrade().is_none(),
            "difference should not retain an archive used only for subtraction"
        );
        assert_eq!(difference.iter().copied().collect_vec(), vec![key(0x20)]);
        drop(difference);
        assert!(left_owner.upgrade().is_none());
        assert!(right_owner.upgrade().is_none());
    }

    #[test]
    fn asymmetric_difference_collapses_its_surviving_child() {
        let (left, owner) = owned_archive_pair([key(0x10), key(0x20)]);
        assert_eq!(left.root.as_ref().map(Head::tag), Some(HeadTag::Branch2));
        let removed = singleton_patch(key(0x10));

        let survivor = left.difference(&removed);
        drop(left);
        drop(removed);

        assert_eq!(survivor.len(), 1);
        assert_eq!(survivor.node_stats(), (0, 0, 0, 1));
        assert_eq!(
            survivor.root.as_ref().map(Head::tag),
            Some(HeadTag::LocalLeaf),
            "Branch-minus-Leaf left a unary Branch instead of its child",
        );
        assert_eq!(survivor.iter().copied().collect_vec(), vec![key(0x20)]);
        assert!(owner.upgrade().is_some());

        let final_key = singleton_patch(key(0x20));
        let empty = survivor.difference(&final_key);
        drop(survivor);
        drop(final_key);

        assert!(empty.root.is_none());
        assert!(empty.owners.is_none());
        assert!(owner.upgrade().is_none());
    }

    #[test]
    fn clone_and_consuming_iterator_retain_the_archive() {
        let (patch, owner) = owned_archive_pair([key(0x10), key(0x20)]);
        let clone = patch.clone();
        drop(patch);
        assert!(owner.upgrade().is_some(), "clone lost the archive owner");

        let mut iter = clone.into_iter();
        assert!(
            owner.upgrade().is_some(),
            "consuming iterator lost the archive owner"
        );
        assert!(matches!(iter.next(), Some(value) if value == key(0x10) || value == key(0x20)));
        drop(iter);
        assert!(owner.upgrade().is_none());
    }

    #[test]
    fn ordered_consuming_iterator_retains_the_archive() {
        let (patch, owner) = owned_archive_pair([key(0x10), key(0x20)]);

        let mut iter = patch.into_iter_ordered();
        assert!(
            owner.upgrade().is_some(),
            "ordered consuming iterator lost the archive owner"
        );
        assert_eq!(iter.next(), Some(key(0x10)));
        drop(iter);
        assert!(owner.upgrade().is_none());
    }

    #[test]
    fn removal_retains_collapsed_local_root_and_releases_empty_cover() {
        let (mut patch, owner) = owned_archive_pair([key(0x10), key(0x20)]);

        patch.remove(&key(0x10));
        assert!(
            owner.upgrade().is_some(),
            "removal lost the owner of the surviving LocalLeaf"
        );
        assert_eq!(patch.iter().copied().collect_vec(), vec![key(0x20)]);

        patch.remove(&key(0x20));
        assert!(patch.is_empty());
        assert!(owner.upgrade().is_none(), "empty PATCH retained its cover");
    }

    #[test]
    fn head_tag() {
        let head = Head::<64, IdentitySchema, ()>::new::<Leaf<64, ()>>(0, NonNull::dangling());
        assert_eq!(head.tag(), HeadTag::Leaf);
        mem::forget(head);
    }

    #[test]
    fn head_key() {
        for k in 0..=255 {
            let head = Head::<64, IdentitySchema, ()>::new::<Leaf<64, ()>>(k, NonNull::dangling());
            assert_eq!(head.key(), k);
            mem::forget(head);
        }
    }

    #[test]
    fn head_size() {
        assert_eq!(mem::size_of::<Head<64, IdentitySchema, ()>>(), 8);
    }

    #[test]
    fn option_head_size() {
        assert_eq!(mem::size_of::<Option<Head<64, IdentitySchema, ()>>>(), 8);
    }

    #[test]
    fn empty_tree() {
        let _tree = PATCH::<64, IdentitySchema, ()>::new();
    }

    #[test]
    fn tree_put_one() {
        const KEY_SIZE: usize = 64;
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
        let entry = Entry::new(&[0; KEY_SIZE]);
        tree.insert(&entry);
    }

    #[test]
    fn tree_clone_one() {
        const KEY_SIZE: usize = 64;
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
        let entry = Entry::new(&[0; KEY_SIZE]);
        tree.insert(&entry);
        let _clone = tree.clone();
    }

    #[test]
    fn consuming_shared_leaf_does_not_mutably_alias_value() {
        const KEY_SIZE: usize = 4;
        let key = [1u8; KEY_SIZE];
        let mut retained = PATCH::<KEY_SIZE, IdentitySchema, String>::new();
        let entry = Entry::with_value(&key, String::from("still borrowed"));
        retained.insert(&entry);
        drop(entry);

        let unordered = retained.clone();
        let value = retained.get(&key).expect("inserted value");
        assert_eq!(unordered.into_iter().collect::<Vec<_>>(), vec![key]);
        assert_eq!(value, "still borrowed");

        let ordered = retained.clone();
        let value = retained.get(&key).expect("inserted value");
        assert_eq!(ordered.into_iter_ordered().collect::<Vec<_>>(), vec![key]);
        assert_eq!(value, "still borrowed");
    }

    #[test]
    fn tree_put_same() {
        const KEY_SIZE: usize = 64;
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
        let entry = Entry::new(&[0; KEY_SIZE]);
        tree.insert(&entry);
        tree.insert(&entry);
    }

    #[test]
    fn ordered_infix_bounds_include_all_zero_and_all_ff() {
        let mut tree = PATCH::<4, IdentitySchema, ()>::new();
        tree.insert(&Entry::new(&[0x00; 4]));
        tree.insert(&Entry::new(&[0x80, 0x00, 0x00, 0x00]));
        tree.insert(&Entry::new(&[0xff; 4]));

        assert_eq!(
            tree.first_infix_range(&[], &[0x00; 4], &[0xff; 4]),
            Some([0x00; 4]),
        );
        assert_eq!(
            tree.next_infix_after(&[], &[0x00; 4], &[0xff; 4]),
            Some([0x80, 0x00, 0x00, 0x00]),
        );
        assert_eq!(
            tree.first_infix_range(&[], &[0xff; 4], &[0xff; 4]),
            Some([0xff; 4]),
        );
        assert_eq!(tree.next_infix_after(&[], &[0xff; 4], &[0xff; 4]), None,);
        assert_eq!(tree.first_infix_range(&[], &[0xff; 4], &[0x00; 4]), None,);
    }

    #[test]
    fn ordered_infix_descent_reads_local_leaves() {
        #[repr(C, align(16))]
        struct AlignedKey([u8; 16]);

        let storage = std::sync::Arc::new([
            AlignedKey([0x10; 16]),
            AlignedKey([0x20; 16]),
            AlignedKey([0xf0; 16]),
        ]);
        let owner: std::sync::Arc<dyn ArchiveOwner> = storage.clone();
        let mut tree = PATCH::<16, IdentitySchema, ()>::new();
        for key in storage.iter() {
            let entry = unsafe { ArchiveEntry::new(NonNull::from(&key.0), &owner) };
            tree.insert_archive(&entry);
        }

        assert!(tree.node_stats().3 > 0, "fixture must contain a LocalLeaf");
        assert_eq!(
            tree.first_infix_range(&[], &[0x11; 16], &[0xff; 16]),
            Some([0x20; 16]),
        );
        assert_eq!(
            tree.next_infix_after(&[], &[0x20; 16], &[0xff; 16]),
            Some([0xf0; 16]),
        );
    }

    #[test]
    fn ordered_infix_descent_honors_permuted_segments_in_local_leaves() {
        fn physical_key(prefix: [u8; 4], infix: [u8; 4], suffix: [u8; 4]) -> [u8; 12] {
            let mut key = [0; 12];
            key[..4].copy_from_slice(&suffix);
            key[4..8].copy_from_slice(&prefix);
            key[8..].copy_from_slice(&infix);
            key
        }

        let selected = [0x10; 4];
        let other = [0x20; 4];
        let first = [0x11; 4];
        let second = [0x22; 4];
        let storage = std::sync::Arc::new([
            AlignedArchiveKey(physical_key(other, [0x33; 4], [0x44; 4])),
            AlignedArchiveKey(physical_key(selected, second, [0x44; 4])),
            AlignedArchiveKey(physical_key(selected, first, [0x55; 4])),
            AlignedArchiveKey(physical_key(selected, first, [0x44; 4])),
        ]);
        let owner: std::sync::Arc<dyn ArchiveOwner> = storage.clone();
        let mut tree = PATCH::<12, PermutedInfixSchema, ()>::new();
        for key in storage.iter() {
            // SAFETY: every key is aligned and remains immutable and alive
            // through `owner` for the lifetime of the archive-backed PATCH.
            let entry = unsafe { ArchiveEntry::new(NonNull::from(&key.0), &owner) };
            tree.insert_archive(&entry);
        }

        assert!(tree.node_stats().3 > 0, "fixture must contain a LocalLeaf");
        assert_eq!(
            tree.first_infix_range(&selected, &[u8::MIN; 4], &[u8::MAX; 4]),
            Some(first),
        );
        assert_eq!(
            tree.next_infix_after(&selected, &first, &[u8::MAX; 4]),
            Some(second),
        );
        assert_eq!(
            tree.next_infix_after(&selected, &second, &[u8::MAX; 4]),
            None,
        );
    }

    #[test]
    fn bounded_infixes_are_atomic_over_archive_local_leaves() {
        #[repr(C, align(16))]
        struct AlignedKey([u8; 16]);

        let storage = std::sync::Arc::new([
            AlignedKey([0x10; 16]),
            AlignedKey([0x20; 16]),
            AlignedKey([0xf0; 16]),
        ]);
        let owner: std::sync::Arc<dyn ArchiveOwner> = storage.clone();
        let mut tree = PATCH::<16, IdentitySchema, ()>::new();
        for key in storage.iter() {
            let entry = unsafe { ArchiveEntry::new(NonNull::from(&key.0), &owner) };
            tree.insert_archive(&entry);
        }
        assert!(tree.node_stats().3 > 0, "fixture must contain a LocalLeaf");

        assert!(tree.bounded_infixes::<0, 16>(&[], 2).is_none());

        let mut expected = Vec::new();
        tree.infixes(&[], |value: &[u8; 16]| expected.push(*value));
        let mut accepted = Vec::new();
        let bounded = tree
            .bounded_infixes::<0, 16>(&[], 3)
            .expect("the exact count fits");
        assert_eq!(bounded.len(), 3);
        bounded.for_each(|value: &[u8; 16]| accepted.push(*value));
        assert_eq!(accepted, expected);
    }

    #[test]
    fn archive_singleton_pairs_follow_exact_key_identity() {
        const KEY_SIZE: usize = 64;
        #[repr(C, align(16))]
        struct AlignedKey([u8; KEY_SIZE]);

        let key_a = [0x44; KEY_SIZE];
        let mut key_b = key_a;
        key_b[KEY_SIZE - 1] = 0x55;
        let storage = std::sync::Arc::new([AlignedKey(key_a), AlignedKey(key_b)]);
        let _owner: std::sync::Arc<dyn ArchiveOwner> = storage.clone();

        let local_a = unsafe { Head::new_local_leaf(0, NonNull::from(&storage[0].0)) };
        let local_b = unsafe { Head::new_local_leaf(0, NonNull::from(&storage[1].0)) };
        let heap_a_entry = Entry::new(&key_a);
        let heap_b_entry = Entry::new(&key_b);
        let heap_a = heap_a_entry.leaf::<IdentitySchema>();
        let heap_b = heap_b_entry.leaf::<IdentitySchema>();

        fn assert_pair(
            left: &Head<64, IdentitySchema, ()>,
            right: &Head<64, IdentitySchema, ()>,
            equal: bool,
        ) {
            let union = Head::union(left.clone(), right.clone(), 0);
            assert_eq!(union.count(), if equal { 1 } else { 2 });
            assert_eq!(
                left.intersect(right, 0).as_ref().map(Head::count),
                equal.then_some(1)
            );
            assert_eq!(
                left.difference(right, 0).as_ref().map(Head::count),
                (!equal).then_some(1)
            );
        }

        assert_pair(&local_a, &local_a, true);
        assert_pair(&local_a, &local_b, false);
        assert_pair(&heap_a, &local_a, true);
        assert_pair(&local_a, &heap_a, true);
        assert_pair(&heap_a, &local_b, false);
        assert_pair(&local_a, &heap_b, false);
        assert_pair(&heap_a, &heap_a, true);
        assert_pair(&heap_a, &heap_b, false);
    }

    #[test]
    fn local_leaf_and_unary_branch_keep_equal_fingerprint_path() {
        const KEY_SIZE: usize = 16;
        #[repr(C, align(16))]
        struct AlignedKey([u8; KEY_SIZE]);

        let storage =
            std::sync::Arc::new([AlignedKey([0x10; KEY_SIZE]), AlignedKey([0x20; KEY_SIZE])]);
        let owner: std::sync::Arc<dyn ArchiveOwner> = storage.clone();
        let mut pair = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
        for key in storage.iter() {
            let entry = unsafe { ArchiveEntry::new(NonNull::from(&key.0), &owner) };
            pair.insert_archive(&entry);
        }

        // Deliberately retain a unary Branch representation. Cardinality one
        // is not enough to infer its tag or reject equality with a LocalLeaf.
        let mut unary = pair.root.as_ref().expect("pair has a root").clone();
        let removed_slot = match unary.body_ref() {
            BodyRef::Branch(branch) => branch
                .child_table
                .iter()
                .flatten()
                .find(|child| child.childleaf_key() == &storage[0].0)
                .expect("first archive key is present")
                .key(),
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => panic!("pair root must be a Branch"),
        };
        {
            let mut editor = crate::patch::branch::BranchMut::from_head(&mut unary);
            editor.modify_child(removed_slot, |_| None);
        }
        assert!(matches!(unary.body_ref(), BodyRef::Branch(_)));
        assert_eq!(unary.count(), 1);

        let local = match unary.body_ref() {
            BodyRef::Branch(branch) => branch
                .child_table
                .iter()
                .flatten()
                .next()
                .expect("unary Branch has one child")
                .clone(),
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => unreachable!(),
        };
        assert_eq!(local.tag(), HeadTag::LocalLeaf);
        assert_eq!(local.count(), 1);
        assert_eq!(local.hash(), unary.hash());

        // The equal-fingerprint shortcut returns its left operand unchanged.
        // These shape checks therefore prove that the count-one case reaches
        // fingerprints rather than taking the unequal-cardinality descent.
        let union = Head::union(local.clone(), unary.clone(), 0);
        assert_eq!(union.tag(), HeadTag::LocalLeaf);
        let intersection = unary
            .intersect(&local, 0)
            .expect("equal singleton sets intersect");
        assert!(matches!(intersection.body_ref(), BodyRef::Branch(_)));
        assert!(unary.difference(&local, 0).is_none());

        #[cfg(feature = "parallel")]
        {
            let union = Head::par_union(local.clone(), unary.clone(), 0);
            assert_eq!(union.tag(), HeadTag::LocalLeaf);
            let intersection = unary
                .par_intersect(&local, 0)
                .expect("equal singleton sets intersect");
            assert!(matches!(intersection.body_ref(), BodyRef::Branch(_)));
            assert!(unary.par_difference(&local, 0).is_none());
        }
    }

    #[test]
    fn archive_set_ops_retain_shared_backing() {
        const KEY_SIZE: usize = 16;
        #[repr(C, align(16))]
        struct AlignedKey([u8; KEY_SIZE]);

        let key_a = [0x10; KEY_SIZE];
        let key_b = [0x20; KEY_SIZE];
        let key_c = [0x30; KEY_SIZE];
        let (left, right) = {
            let storage =
                std::sync::Arc::new([AlignedKey(key_a), AlignedKey(key_b), AlignedKey(key_c)]);
            let owner: std::sync::Arc<dyn ArchiveOwner> = storage.clone();
            let mut left = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            let mut right = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            for index in [0, 1] {
                let entry = unsafe { ArchiveEntry::new(NonNull::from(&storage[index].0), &owner) };
                left.insert_archive(&entry);
            }
            for index in [1, 2] {
                let entry = unsafe { ArchiveEntry::new(NonNull::from(&storage[index].0), &owner) };
                right.insert_archive(&entry);
            }
            assert!(left.node_stats().3 > 0);
            assert!(right.node_stats().3 > 0);
            (left, right)
        };

        let mut union = left.clone();
        union.union(right.clone());
        assert_eq!(union.len(), 3);
        assert!(union.get(&key_a).is_some());
        assert!(union.get(&key_b).is_some());
        assert!(union.get(&key_c).is_some());

        let intersection = left.intersect(&right);
        assert_eq!(intersection.len(), 1);
        assert!(intersection.get(&key_b).is_some());

        let difference = left.difference(&right);
        assert_eq!(difference.len(), 1);
        assert!(difference.get(&key_a).is_some());
    }

    #[test]
    fn tree_replace_existing() {
        const KEY_SIZE: usize = 64;
        let key = [1u8; KEY_SIZE];
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let entry1 = Entry::with_value(&key, 1);
        tree.insert(&entry1);
        let entry2 = Entry::with_value(&key, 2);
        tree.replace(&entry2);
        assert_eq!(tree.get(&key), Some(&2));
    }

    #[test]
    fn tree_replace_childleaf_updates_branch() {
        const KEY_SIZE: usize = 64;
        let key1 = [0u8; KEY_SIZE];
        let key2 = [1u8; KEY_SIZE];
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let entry1 = Entry::with_value(&key1, 1);
        let entry2 = Entry::with_value(&key2, 2);
        tree.insert(&entry1);
        tree.insert(&entry2);
        let entry1b = Entry::with_value(&key1, 3);
        tree.replace(&entry1b);
        assert_eq!(tree.get(&key1), Some(&3));
        assert_eq!(tree.get(&key2), Some(&2));
    }

    #[test]
    fn update_child_refreshes_childleaf_on_replace() {
        const KEY_SIZE: usize = 4;
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();

        let key1 = [0u8; KEY_SIZE];
        let key2 = [1u8; KEY_SIZE];
        tree.insert(&Entry::with_value(&key1, 1));
        tree.insert(&Entry::with_value(&key2, 2));

        // Determine which child currently provides the branch childleaf.
        let root_ref = tree.root.as_ref().expect("root exists");
        let before_childleaf = *root_ref.childleaf_key();

        // Find the slot key (the byte index used in the branch table) for the child
        // that currently provides the childleaf.
        let slot_key = match root_ref.body_ref() {
            BodyRef::Branch(branch) => branch
                .child_table
                .iter()
                .filter_map(|c| c.as_ref())
                .find(|c| c.childleaf_key() == &before_childleaf)
                .expect("child exists")
                .key(),
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => panic!("root should be a branch"),
        };

        // Replace that child with a new leaf that has a different childleaf key.
        let new_key = [2u8; KEY_SIZE];
        {
            let mut ed = crate::patch::branch::BranchMut::from_slot(&mut tree.root);
            ed.modify_child(slot_key, |_| {
                Some(Entry::with_value(&new_key, 42).leaf::<IdentitySchema>())
            });
            // drop(ed) commits
        }

        let after = tree.root.as_ref().expect("root exists");
        assert_eq!(after.childleaf_key(), &new_key);
    }

    #[test]
    fn replace_commits_nested_structure_before_value_drop_panics() {
        use std::panic::{catch_unwind, AssertUnwindSafe};

        const KEY_LEN: usize = 4;
        let replaced = [0, 0, 0, 0];
        let nested_sibling = [0, 0, 0, 1];
        let root_sibling = [1, 0, 0, 0];
        let mut patch = PATCH::<KEY_LEN, IdentitySchema, PanicOnDrop>::new();

        for (key, should_panic) in [
            (replaced, true),
            (nested_sibling, false),
            (root_sibling, false),
        ] {
            let entry = Entry::with_value(&key, PanicOnDrop(should_panic));
            patch.insert(&entry);
            drop(entry);
        }
        let old_hash = patch.root_hash().expect("fixture hash");
        let old_nodes = patch.node_stats();

        let replacement = Entry::with_value(&replaced, PanicOnDrop(false));
        let result = catch_unwind(AssertUnwindSafe(|| patch.replace(&replacement)));
        assert!(result.is_err());

        assert_eq!(patch.len(), 3);
        assert_eq!(patch.get(&replaced).map(|value| value.0), Some(false));
        assert_eq!(patch.get(&nested_sibling).map(|value| value.0), Some(false));
        assert_eq!(patch.get(&root_sibling).map(|value| value.0), Some(false));
        assert_eq!(patch.root_hash(), Some(old_hash));
        assert_eq!(patch.node_stats(), old_nodes);
        assert_eq!(
            patch.iter_ordered().copied().collect::<Vec<_>>(),
            vec![replaced, nested_sibling, root_sibling],
        );
    }

    #[test]
    fn replace_commits_singleton_root_before_value_drop_panics() {
        use std::panic::{catch_unwind, AssertUnwindSafe};

        const KEY_LEN: usize = 4;
        let key = [7; KEY_LEN];
        let mut patch = PATCH::<KEY_LEN, IdentitySchema, PanicOnDrop>::new();
        let original = Entry::with_value(&key, PanicOnDrop(true));
        patch.insert(&original);
        drop(original);

        let replacement = Entry::with_value(&key, PanicOnDrop(false));
        let result = catch_unwind(AssertUnwindSafe(|| patch.replace(&replacement)));
        assert!(result.is_err());

        assert_eq!(patch.len(), 1);
        assert_eq!(patch.get(&key).map(|value| value.0), Some(false));
        assert_eq!(patch.root_hash(), Some(hash_key(&key)));
        assert!(matches!(
            patch.root.as_ref().expect("replacement root").body_ref(),
            BodyRef::Leaf(_),
        ));
    }

    #[test]
    fn remove_commits_nested_structure_before_value_drop_panics() {
        use std::panic::{catch_unwind, AssertUnwindSafe};

        const KEY_LEN: usize = 4;
        let removed = [0, 0, 0, 0];
        let nested_sibling = [0, 0, 0, 1];
        let root_sibling = [1, 0, 0, 0];
        let mut patch = PATCH::<KEY_LEN, IdentitySchema, PanicOnDrop>::new();

        for (key, should_panic) in [
            (removed, true),
            (nested_sibling, false),
            (root_sibling, false),
        ] {
            let entry = Entry::with_value(&key, PanicOnDrop(should_panic));
            patch.insert(&entry);
            drop(entry);
        }
        assert_eq!(patch.node_stats().0, 2, "fixture must contain two branches");
        assert_eq!(
            patch.root.as_ref().expect("root branch").childleaf_key(),
            &removed,
            "the removed leaf must back the ancestor representative pointer",
        );
        let old_hash = patch.root_hash().expect("fixture hash");

        let result = catch_unwind(AssertUnwindSafe(|| patch.remove(&removed)));
        assert!(result.is_err());

        assert_eq!(patch.len(), 2);
        assert!(patch.get(&removed).is_none());
        assert!(patch.get(&nested_sibling).is_some());
        assert!(patch.get(&root_sibling).is_some());
        assert_eq!(
            patch.iter_ordered().copied().collect::<Vec<_>>(),
            vec![nested_sibling, root_sibling],
        );
        assert_eq!(patch.node_stats().0, 1, "the nested unary branch collapsed");
        assert_ne!(
            patch.root.as_ref().expect("surviving root").childleaf_key(),
            &removed,
            "the surviving branch must not retain a dangling representative",
        );
        assert_eq!(patch.root_hash(), Some(old_hash ^ hash_key(&removed)));
        let fanout = patch.branch_fanout_histogram();
        assert_eq!(fanout[0], 0);
        assert_eq!(fanout[1], 0);
    }

    #[test]
    fn remove_collapses_root_before_value_drop_panics() {
        use std::panic::{catch_unwind, AssertUnwindSafe};

        const KEY_LEN: usize = 4;
        let removed = [0; KEY_LEN];
        let retained = [1; KEY_LEN];
        let mut patch = PATCH::<KEY_LEN, IdentitySchema, PanicOnDrop>::new();
        for (key, should_panic) in [(removed, true), (retained, false)] {
            let entry = Entry::with_value(&key, PanicOnDrop(should_panic));
            patch.insert(&entry);
            drop(entry);
        }

        let result = catch_unwind(AssertUnwindSafe(|| patch.remove(&removed)));
        assert!(result.is_err());
        assert_eq!(patch.len(), 1);
        assert!(patch.get(&removed).is_none());
        assert!(patch.get(&retained).is_some());
        assert_eq!(patch.root_hash(), Some(hash_key(&retained)));
        assert!(matches!(
            patch.root.as_ref().expect("retained root").body_ref(),
            BodyRef::Leaf(_),
        ));
    }

    #[test]
    fn remove_commits_cow_snapshot_before_deferred_value_drop_panics() {
        use std::panic::{catch_unwind, AssertUnwindSafe};

        const KEY_LEN: usize = 4;
        let removed = [0; KEY_LEN];
        let retained = [1; KEY_LEN];
        let mut edited = PATCH::<KEY_LEN, IdentitySchema, PanicOnDrop>::new();
        for (key, should_panic) in [(removed, true), (retained, false)] {
            let entry = Entry::with_value(&key, PanicOnDrop(should_panic));
            edited.insert(&entry);
            drop(entry);
        }
        let snapshot = edited.clone();

        // The untouched snapshot still owns the removed leaf, so this is not
        // yet its final release and the edit itself cannot run `V::drop`.
        edited.remove(&removed);
        assert!(edited.get(&removed).is_none());
        assert!(edited.get(&retained).is_some());
        assert_eq!(edited.root_hash(), Some(hash_key(&retained)));
        assert!(snapshot.get(&removed).is_some());

        let result = catch_unwind(AssertUnwindSafe(|| drop(snapshot)));
        assert!(result.is_err());
        assert_eq!(edited.len(), 1);
        assert!(edited.get(&retained).is_some());
    }

    #[test]
    fn remove_retains_archive_owner_until_empty_then_commits_before_drop_panics() {
        use std::panic::{catch_unwind, AssertUnwindSafe};

        const KEY_LEN: usize = 16;
        #[repr(C, align(16))]
        struct PanickingOwner {
            keys: [AlignedArchiveKey<KEY_LEN>; 2],
            drops: Arc<AtomicUsize>,
        }

        impl Drop for PanickingOwner {
            fn drop(&mut self) {
                self.drops.fetch_add(1, Ordering::Relaxed);
                panic!("intentional archive owner drop panic");
            }
        }

        let first = [7; KEY_LEN];
        let second = [8; KEY_LEN];
        let drops = Arc::new(AtomicUsize::new(0));
        let owner = Arc::new(PanickingOwner {
            keys: [AlignedArchiveKey(first), AlignedArchiveKey(second)],
            drops: drops.clone(),
        });
        let erased: Arc<dyn ArchiveOwner> = owner.clone();
        let mut patch = PATCH::<KEY_LEN, IdentitySchema>::new();
        for index in 0..2 {
            let entry = unsafe { ArchiveEntry::new(NonNull::from(&owner.keys[index].0), &erased) };
            patch.insert_archive(&entry);
        }
        drop(erased);
        drop(owner);

        // Removing one LocalLeaf may collapse its parent, but must retain the
        // owner cover for the promoted survivor.
        patch.remove(&first);
        assert_eq!(drops.load(Ordering::Relaxed), 0);
        assert!(patch.owners.is_some());
        assert_eq!(patch.iter().copied().collect::<Vec<_>>(), vec![second]);
        assert!(matches!(
            patch.root.as_ref().expect("archive root").body_ref(),
            BodyRef::LocalLeaf(_),
        ));

        let result = catch_unwind(AssertUnwindSafe(|| patch.remove(&second)));
        assert!(result.is_err());
        assert_eq!(drops.load(Ordering::Relaxed), 1);
        assert!(patch.root.is_none(), "the empty root was committed first");
        assert!(
            patch.owners.is_none(),
            "the owner cover was detached before reclamation"
        );
        assert!(patch.is_empty());
    }

    #[test]
    fn remove_promotes_a_multi_leaf_only_child_subtree() {
        const KEY_LEN: usize = 4;
        let removed = [0, 0, 0, 0];
        let retained_a = [1, 0, 0, 0];
        let retained_b = [1, 1, 0, 0];
        let mut patch = PATCH::<KEY_LEN, IdentitySchema>::new();
        for key in [removed, retained_a, retained_b] {
            patch.insert(&Entry::new(&key));
        }
        assert_eq!(patch.node_stats().0, 2, "fixture must contain two branches");

        patch.remove(&removed);

        assert_eq!(patch.len(), 2);
        assert_eq!(patch.node_stats().0, 1, "unary root must be removed");
        assert_eq!(patch.branch_fanout_histogram()[1], 0);
        assert!(patch.get(&retained_a).is_some());
        assert!(patch.get(&retained_b).is_some());
    }

    #[test]
    fn remove_childleaf_updates_branch() {
        const KEY_SIZE: usize = 4;
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();

        let key1 = [0u8; KEY_SIZE];
        let key2 = [1u8; KEY_SIZE];
        tree.insert(&Entry::with_value(&key1, 1));
        tree.insert(&Entry::with_value(&key2, 2));

        let childleaf_before = *tree.root.as_ref().unwrap().childleaf_key();
        // remove the leaf that currently provides the branch.childleaf
        tree.remove(&childleaf_before);

        // Ensure the removed key is gone and the other key remains and is now the childleaf.
        let other = if childleaf_before == key1 { key2 } else { key1 };
        assert_eq!(tree.get(&childleaf_before), None);
        assert_eq!(tree.get(&other), Some(&2u32));
        let after_childleaf = tree.root.as_ref().unwrap().childleaf_key();
        assert_eq!(after_childleaf, &other);
    }

    #[test]
    fn remove_collapses_branch_to_single_child() {
        const KEY_SIZE: usize = 4;
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();

        let key1 = [0u8; KEY_SIZE];
        let key2 = [1u8; KEY_SIZE];
        tree.insert(&Entry::with_value(&key1, 1));
        tree.insert(&Entry::with_value(&key2, 2));

        // Remove one key and ensure the root collapses to the remaining child.
        tree.remove(&key1);
        assert_eq!(tree.get(&key1), None);
        assert_eq!(tree.get(&key2), Some(&2u32));
        let root = tree.root.as_ref().expect("root exists");
        match root.body_ref() {
            BodyRef::Leaf(_) | BodyRef::LocalLeaf(_) => {}
            BodyRef::Branch(_) => panic!("root should have collapsed to a leaf"),
        }
    }

    #[test]
    fn branch_size() {
        // Ownership lives once on PATCH, leaving the original 48-byte Branch
        // header. Each child is an 8-byte tagged Head.
        assert_eq!(
            mem::size_of::<Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 2], ()>>(
            ),
            48 + 8 * 2
        );
        assert_eq!(
            mem::size_of::<Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 4], ()>>(
            ),
            48 + 8 * 4
        );
        assert_eq!(
            mem::size_of::<Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 8], ()>>(
            ),
            48 + 8 * 8
        );
        assert_eq!(
            mem::size_of::<
                Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 16], ()>,
            >(),
            48 + 8 * 16
        );
        assert_eq!(
            mem::size_of::<
                Branch<64, IdentitySchema, [Option<Head<32, IdentitySchema, ()>>; 32], ()>,
            >(),
            48 + 8 * 32
        );
        assert_eq!(
            mem::size_of::<
                Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 64], ()>,
            >(),
            48 + 8 * 64
        );
        assert_eq!(
            mem::size_of::<
                Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 128], ()>,
            >(),
            48 + 8 * 128
        );
        assert_eq!(
            mem::size_of::<
                Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 256], ()>,
            >(),
            48 + 8 * 256
        );
    }

    #[test]
    fn patch_root_owner_cover_is_one_thin_arc() {
        // Default-policy layout is a compatibility and performance contract:
        // making PATCH generic must not charge TribleSet for the stronger
        // digest it does not use.
        assert_eq!(mem::size_of::<Entry<64, ()>>(), 8);
        assert_eq!(mem::size_of::<Leaf<64, ()>>(), 96);
        assert_eq!(mem::size_of::<Head<64, IdentitySchema, ()>>(), 8);
        assert_eq!(
            mem::size_of::<Branch<64, IdentitySchema, [Option<Head<64, IdentitySchema, ()>>; 0], ()>>(
            ),
            48
        );
        assert_eq!(mem::size_of::<Option<Arc<OwnerCover>>>(), 8);
        assert_eq!(mem::size_of::<PATCH<64, IdentitySchema, ()>>(), 16);

        assert_eq!(mem::size_of::<Entry<64, (), Blake3Merkle>>(), 8);
        assert_eq!(mem::size_of::<Leaf<64, (), Blake3Merkle>>(), 112);
        assert_eq!(
            mem::size_of::<
                Branch<
                    64,
                    IdentitySchema,
                    [Option<Head<64, IdentitySchema, (), Blake3Merkle>>; 0],
                    (),
                    Blake3Merkle,
                >,
            >(),
            64
        );
        assert_eq!(
            mem::size_of::<PATCH<64, IdentitySchema, (), Blake3Merkle>>(),
            16
        );
    }

    /// Checks what happens if we join two PATCHes that
    /// only contain a single element each, that differs in the last byte.
    #[test]
    fn tree_union_single() {
        const KEY_SIZE: usize = 8;
        let mut left = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
        let mut right = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
        let left_entry = Entry::new(&[0, 0, 0, 0, 0, 0, 0, 0]);
        let right_entry = Entry::new(&[0, 0, 0, 0, 0, 0, 0, 1]);
        left.insert(&left_entry);
        right.insert(&right_entry);
        left.union(right);
        assert_eq!(left.len(), 2);
    }

    /// Both union arms must produce the same trie.
    ///
    /// `PATCH::union` dispatches to the work-stealing `Head::par_union`
    /// when the `parallel` feature is compiled, and to the serial
    /// `Head::union` when it is not, so no single build exercises both.
    /// This compares whichever arm the build selected against a
    /// reference that uses neither: the same key set inserted directly.
    /// Running it under both feature settings pins the two arms to the
    /// same trie without either of them being the other's oracle.
    ///
    /// It exists because `trible`'s manifest dropped the feature for
    /// months, so a rollout that restores it changes which arm the
    /// maintenance daemons run. That is only safe if the arms agree,
    /// and agreeing is a claim a test should make rather than a reader.
    #[test]
    fn union_matches_insertion_reference() {
        const KEY_SIZE: usize = 8;
        // Comfortably past PARALLEL_PATCH_UNION_THRESHOLD (4096) so the
        // parallel build takes its scatter-and-spawn arm rather than the
        // per-key fallback that a small asymmetric merge would take.
        const KEYS: u64 = 12_000;

        let build = |start: u64, step: u64| {
            let mut tree = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            for index in 0..KEYS {
                let key = (start + index * step).to_be_bytes();
                tree.insert(&Entry::new(&key));
            }
            tree
        };

        // The disjoint even/odd key sets have interleaved ranges and shared
        // byte prefixes, so the equal-depth branch arm has "both" pairs to
        // drain. Root-level scatter is exercised; child pairs are smaller.
        let mut united = build(0, 2);
        united.union(build(1, 2));

        let mut reference = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
        for index in 0..(2 * KEYS) {
            reference.insert(&Entry::new(&index.to_be_bytes()));
        }

        assert_eq!(united.len(), 2 * KEYS);
        assert_eq!(united.len(), reference.len());
        assert_eq!(united, reference);

        let mut united_keys = Vec::new();
        united.infixes(&[0u8; 0], &mut |&key: &[u8; KEY_SIZE]| {
            united_keys.push(key)
        });
        let mut reference_keys = Vec::new();
        reference.infixes(&[0u8; 0], &mut |&key: &[u8; KEY_SIZE]| {
            reference_keys.push(key)
        });
        united_keys.sort_unstable();
        reference_keys.sort_unstable();
        assert_eq!(united_keys, reference_keys);
    }

    // Small unit tests that ensure BranchMut-based editing is used by
    // the higher-level set operations like intersect/difference. These are
    // ordinary unit tests (not proptest) and must appear outside the
    // `proptest!` macro below.

    proptest! {
        #[test]
        fn tree_insert(keys in prop::collection::vec(prop::collection::vec(0u8..=255, 64), 1..1024)) {
            let mut tree = PATCH::<64, IdentitySchema, ()>::new();
            for key in keys {
                let key: [u8; 64] = key.try_into().unwrap();
                let entry = Entry::new(&key);
                tree.insert(&entry);
            }
        }

        #[test]
        fn tree_len(keys in prop::collection::vec(prop::collection::vec(0u8..=255, 64), 1..1024)) {
            let mut tree = PATCH::<64, IdentitySchema, ()>::new();
            let mut set = HashSet::new();
            for key in keys {
                let key: [u8; 64] = key.try_into().unwrap();
                let entry = Entry::new(&key);
                tree.insert(&entry);
                set.insert(key);
            }

            prop_assert_eq!(set.len() as u64, tree.len())
        }

        #[test]
        fn tree_infixes(keys in prop::collection::vec(prop::collection::vec(0u8..=255, 64), 1..1024)) {
            let mut tree = PATCH::<64, IdentitySchema, ()>::new();
            let mut set = HashSet::new();
            for key in keys {
                let key: [u8; 64] = key.try_into().unwrap();
                let entry = Entry::new(&key);
                tree.insert(&entry);
                set.insert(key);
            }
            let mut set_vec = Vec::from_iter(set.into_iter());
            let mut tree_vec = vec![];
            tree.infixes(&[0; 0], &mut |&x: &[u8; 64]| tree_vec.push(x));

            set_vec.sort();
            tree_vec.sort();

            prop_assert_eq!(set_vec, tree_vec);
        }

        #[test]
        fn tree_iter(keys in prop::collection::vec(prop::collection::vec(0u8..=255, 64), 1..1024)) {
            let mut tree = PATCH::<64, IdentitySchema, ()>::new();
            let mut set = HashSet::new();
            for key in keys {
                let key: [u8; 64] = key.try_into().unwrap();
                let entry = Entry::new(&key);
                tree.insert(&entry);
                set.insert(key);
            }
            let mut set_vec = Vec::from_iter(set.into_iter());
            let mut tree_vec = vec![];
            for key in &tree {
                tree_vec.push(*key);
            }

            set_vec.sort();
            tree_vec.sort();

            prop_assert_eq!(set_vec, tree_vec);
        }

        #[test]
        fn tree_union(left in prop::collection::vec(prop::collection::vec(0u8..=255, 64), 200),
                        right in prop::collection::vec(prop::collection::vec(0u8..=255, 64), 200)) {
            let mut set = HashSet::new();

            let mut left_tree = PATCH::<64, IdentitySchema, ()>::new();
            for entry in left {
                let mut key = [0; 64];
                key.iter_mut().set_from(entry.iter().cloned());
                let entry = Entry::new(&key);
                left_tree.insert(&entry);
                set.insert(key);
            }

            let mut right_tree = PATCH::<64, IdentitySchema, ()>::new();
            for entry in right {
                let mut key = [0; 64];
                key.iter_mut().set_from(entry.iter().cloned());
                let entry = Entry::new(&key);
                right_tree.insert(&entry);
                set.insert(key);
            }

            left_tree.union(right_tree);

            let mut set_vec = Vec::from_iter(set.into_iter());
            let mut tree_vec = vec![];
            left_tree.infixes(&[0; 0], &mut |&x: &[u8;64]| tree_vec.push(x));

            set_vec.sort();
            tree_vec.sort();

            prop_assert_eq!(set_vec, tree_vec);
            }

        #[test]
        fn tree_union_empty(left in prop::collection::vec(prop::collection::vec(0u8..=255, 64), 2)) {
            let mut set = HashSet::new();

            let mut left_tree = PATCH::<64, IdentitySchema, ()>::new();
            for entry in left {
                let mut key = [0; 64];
                key.iter_mut().set_from(entry.iter().cloned());
                let entry = Entry::new(&key);
                left_tree.insert(&entry);
                set.insert(key);
            }

            let right_tree = PATCH::<64, IdentitySchema, ()>::new();

            left_tree.union(right_tree);

            let mut set_vec = Vec::from_iter(set.into_iter());
            let mut tree_vec = vec![];
            left_tree.infixes(&[0; 0], &mut |&x: &[u8;64]| tree_vec.push(x));

            set_vec.sort();
            tree_vec.sort();

            prop_assert_eq!(set_vec, tree_vec);
            }

        // I got a feeling that we're not testing COW properly.
        // We should check if a tree remains the same after a clone of it
        // is modified by inserting new keys.

    #[test]
    fn cow_on_insert(base_keys in prop::collection::vec(prop::collection::vec(0u8..=255, 8), 1..1024),
                         new_keys in prop::collection::vec(prop::collection::vec(0u8..=255, 8), 1..1024)) {
            // Note that we can't compare the trees directly, as that uses the hash,
            // which might not be affected by nodes in lower levels being changed accidentally.
            // Instead we need to iterate over the keys and check if they are the same.

            let mut tree = PATCH::<8, IdentitySchema, ()>::new();
            for key in base_keys {
                let key: [u8; 8] = key[..].try_into().unwrap();
                let entry = Entry::new(&key);
                tree.insert(&entry);
            }
            let base_tree_content: Vec<[u8; 8]> = tree.iter().copied().collect();

            let mut tree_clone = tree.clone();
            for key in new_keys {
                let key: [u8; 8] = key[..].try_into().unwrap();
                let entry = Entry::new(&key);
                tree_clone.insert(&entry);
            }

            let new_tree_content: Vec<[u8; 8]> = tree.iter().copied().collect();
            prop_assert_eq!(base_tree_content, new_tree_content);
        }

        #[test]
    fn cow_on_union(base_keys in prop::collection::vec(prop::collection::vec(0u8..=255, 8), 1..1024),
                         new_keys in prop::collection::vec(prop::collection::vec(0u8..=255, 8), 1..1024)) {
            // Note that we can't compare the trees directly, as that uses the hash,
            // which might not be affected by nodes in lower levels being changed accidentally.
            // Instead we need to iterate over the keys and check if they are the same.

            let mut tree = PATCH::<8, IdentitySchema, ()>::new();
            for key in base_keys {
                let key: [u8; 8] = key[..].try_into().unwrap();
                let entry = Entry::new(&key);
                tree.insert(&entry);
            }
            let base_tree_content: Vec<[u8; 8]> = tree.iter().copied().collect();

            let mut tree_clone = tree.clone();
            let mut new_tree = PATCH::<8, IdentitySchema, ()>::new();
            for key in new_keys {
                let key: [u8; 8] = key[..].try_into().unwrap();
                let entry = Entry::new(&key);
                new_tree.insert(&entry);
            }
            tree_clone.union(new_tree);

            let new_tree_content: Vec<[u8; 8]> = tree.iter().copied().collect();
            prop_assert_eq!(base_tree_content, new_tree_content);
        }
    }

    #[test]
    fn intersect_multiple_common_children_commits_branchmut() {
        const KEY_SIZE: usize = 4;
        let mut left = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let mut right = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();

        let a = [0u8, 0u8, 0u8, 1u8];
        let b = [0u8, 0u8, 0u8, 2u8];
        let c = [0u8, 0u8, 0u8, 3u8];
        let d = [2u8, 0u8, 0u8, 0u8];
        let e = [3u8, 0u8, 0u8, 0u8];

        left.insert(&Entry::with_value(&a, 1));
        left.insert(&Entry::with_value(&b, 2));
        left.insert(&Entry::with_value(&c, 3));
        left.insert(&Entry::with_value(&d, 4));

        right.insert(&Entry::with_value(&a, 10));
        right.insert(&Entry::with_value(&b, 11));
        right.insert(&Entry::with_value(&c, 12));
        right.insert(&Entry::with_value(&e, 13));

        let res = left.intersect(&right);
        // A, B, C are common
        assert_eq!(res.len(), 3);
        assert!(res.get(&a).is_some());
        assert!(res.get(&b).is_some());
        assert!(res.get(&c).is_some());
    }

    #[test]
    fn difference_multiple_children_commits_branchmut() {
        const KEY_SIZE: usize = 4;
        let mut left = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let mut right = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();

        let a = [0u8, 0u8, 0u8, 1u8];
        let b = [0u8, 0u8, 0u8, 2u8];
        let c = [0u8, 0u8, 0u8, 3u8];
        let d = [2u8, 0u8, 0u8, 0u8];
        let e = [3u8, 0u8, 0u8, 0u8];

        left.insert(&Entry::with_value(&a, 1));
        left.insert(&Entry::with_value(&b, 2));
        left.insert(&Entry::with_value(&c, 3));
        left.insert(&Entry::with_value(&d, 4));

        right.insert(&Entry::with_value(&a, 10));
        right.insert(&Entry::with_value(&b, 11));
        right.insert(&Entry::with_value(&c, 12));
        right.insert(&Entry::with_value(&e, 13));

        let res = left.difference(&right);
        // left only has d
        assert_eq!(res.len(), 1);
        assert!(res.get(&d).is_some());
    }

    #[test]
    fn difference_equal_singleton_after_survivor_collapse_is_empty() {
        const KEY_SIZE: usize = 16;
        let removed_key = [0x10; KEY_SIZE];
        let survivor_key = [0x20; KEY_SIZE];

        let mut pair = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        pair.insert(&Entry::with_value(&removed_key, 1));
        pair.insert(&Entry::with_value(&survivor_key, 2));

        let mut removed = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        removed.insert(&Entry::with_value(&removed_key, 1));
        let collapsed_survivor = pair.difference(&removed);
        assert_eq!(collapsed_survivor.len(), 1);
        assert_eq!(
            collapsed_survivor.root.as_ref().map(Head::tag),
            Some(HeadTag::Leaf),
        );

        let mut survivor = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        survivor.insert(&Entry::with_value(&survivor_key, 2));
        assert_eq!(collapsed_survivor, survivor);
        assert!(collapsed_survivor.difference(&survivor).root.is_none());
    }

    #[test]
    fn difference_empty_left_is_empty() {
        const KEY_SIZE: usize = 4;
        let left = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let mut right = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let key = [1u8, 2u8, 3u8, 4u8];
        right.insert(&Entry::with_value(&key, 7));

        let res = left.difference(&right);
        assert_eq!(res.len(), 0);
    }

    fn inclusion_agrees_with_difference<const KEY_SIZE: usize>(
        left: &PATCH<KEY_SIZE, IdentitySchema, ()>,
        right: &PATCH<KEY_SIZE, IdentitySchema, ()>,
    ) {
        let left_inside = left.difference(right).is_empty();
        let right_inside = right.difference(left).is_empty();
        let expected = match (left_inside, right_inside) {
            (true, true) => Some(std::cmp::Ordering::Equal),
            (true, false) => Some(std::cmp::Ordering::Less),
            (false, true) => Some(std::cmp::Ordering::Greater),
            (false, false) => None,
        };
        assert_eq!(left.partial_cmp(right), expected);
        assert_eq!(right.partial_cmp(left), expected.map(std::cmp::Ordering::reverse));
        assert_eq!(left <= right, left_inside);
        assert_eq!(right <= left, right_inside);
    }

    #[test]
    fn inclusion_matches_the_difference_oracle_on_wide_random_keys() {
        use rand::RngCore;
        const KEY_SIZE: usize = 32;
        let mut rng = thread_rng();
        for _ in 0..64 {
            let mut left = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            let mut right = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            for _ in 0..(rng.next_u32() % 48) {
                let mut key = [0u8; KEY_SIZE];
                rng.fill_bytes(&mut key);
                // Shared, left-only, or right-only.
                match rng.next_u32() % 3 {
                    0 => {
                        left.insert(&Entry::new(&key));
                        right.insert(&Entry::new(&key));
                    }
                    1 => left.insert(&Entry::new(&key)),
                    _ => right.insert(&Entry::new(&key)),
                }
            }
            inclusion_agrees_with_difference(&left, &right);
            let mut union = left.clone();
            union.union(right.clone());
            assert!(left <= union);
            assert!(right <= union);
            assert_eq!(union <= left, right <= left);
            assert_eq!(union == left, right <= left);
        }
    }

    #[test]
    fn inclusion_matches_the_difference_oracle_on_narrow_alphabets() {
        use rand::RngCore;
        // Three symbols over eight bytes: keys collide on long prefixes, so
        // every depth case of the walk is exercised, including subtrees the
        // two tries hold with equal contents.
        const KEY_SIZE: usize = 8;
        let mut rng = thread_rng();
        for _ in 0..256 {
            let mut left = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            let mut right = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            for _ in 0..(rng.next_u32() % 24) {
                let mut key = [0u8; KEY_SIZE];
                for byte in &mut key {
                    *byte = (rng.next_u32() % 3) as u8;
                }
                match rng.next_u32() % 3 {
                    0 => {
                        left.insert(&Entry::new(&key));
                        right.insert(&Entry::new(&key));
                    }
                    1 => left.insert(&Entry::new(&key)),
                    _ => right.insert(&Entry::new(&key)),
                }
            }
            inclusion_agrees_with_difference(&left, &right);
            let empty = PATCH::<KEY_SIZE, IdentitySchema, ()>::new();
            assert!(empty <= left);
            assert_eq!(left <= empty, left.is_empty());
            assert_eq!(left.partial_cmp(&left), Some(std::cmp::Ordering::Equal));
        }
    }

    #[test]
    fn difference_empty_right_returns_left() {
        const KEY_SIZE: usize = 4;
        let mut left = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let right = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();
        let key = [1u8, 2u8, 3u8, 4u8];
        left.insert(&Entry::with_value(&key, 7));

        let res = left.difference(&right);
        assert_eq!(res.len(), 1);
        assert!(res.get(&key).is_some());
    }

    #[test]
    fn slot_edit_branchmut_insert_update() {
        // Small unit test demonstrating the Slot::edit -> BranchMut insert/update pattern.
        const KEY_SIZE: usize = 8;
        let mut tree = PATCH::<KEY_SIZE, IdentitySchema, u32>::new();

        let entry1 = Entry::with_value(&[0u8; KEY_SIZE], 1u32);
        let entry2 = Entry::with_value(&[1u8; KEY_SIZE], 2u32);
        tree.insert(&entry1);
        tree.insert(&entry2);
        assert_eq!(tree.len(), 2);

        // Edit the root slot in-place using the BranchMut editor.
        {
            let mut ed = crate::patch::branch::BranchMut::from_slot(&mut tree.root);

            // Compute the insertion start depth first to avoid borrowing `ed` inside the closure.
            let start_depth = ed.end_depth as usize;
            let inserted = Entry::with_value(&[2u8; KEY_SIZE], 3u32)
                .leaf::<IdentitySchema>()
                .with_start(start_depth);
            let key = inserted.key();

            ed.modify_child(key, |opt| match opt {
                Some(old) => Some(Head::insert_leaf(old, inserted, start_depth)),
                None => Some(inserted),
            });
            // BranchMut is dropped here and commits the updated branch pointer back into the head.
        }

        assert_eq!(tree.len(), 3);
        assert_eq!(tree.get(&[2u8; KEY_SIZE]), Some(&3u32));
    }
}