lix 0.16.0

Embeddable version control for apps and AI agents.
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
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
//! Repository-wide sync publication and read model.
//!
//! The mutable protocol state is deliberately tiny: one monotonically
//! increasing repository sequence and one replica receipt. Branch heads stay
//! in Lix's ordinary branch controls and commits stay in the changelog.

#[cfg(test)]
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet, VecDeque};

use base64::Engine as _;
use bytes::Bytes;
use serde::{Deserialize, Serialize};

use crate::branch::{
    BRANCH_REF_SCHEMA_KEY, BranchHeadControl, BranchHeadControlContext,
    branch_head_control_precondition, stage_branch_head_control, stage_delete_branch_head_control,
};
use crate::changelog::{
    COMMIT_RECORD_FORMAT_VERSION, COMMIT_SPACE, ChangeId, ChangeLoadRequest, ChangeRecord,
    ChangeRecordProjection, ChangelogAppend, ChangelogContext, ChangelogReader, ChangelogWriter,
    CommitId, CommitLoadRequest, CommitRecord, CommitTouchedScopeDigest, commit_key,
    materialize_known_change_payloads_in_order, next_first_parent_jump,
};
use crate::commit_graph::CommitGraphContext;
use crate::common::LixTimestamp;
use crate::hot_state::{
    CompleteWorkingDiffMode, CurrentStateDeltaRef, HotTrackedSnapshot, TrackedHeadContext,
    TrackedWorkingDiffEpoch, WorkingDiffIndexCoverage, stage_tracked_working_diff_epoch,
};
use crate::row_pk::RowPk;
use crate::storage_adapter::{
    Storage, StorageAdapter, StorageAdapterRead, StorageBeginScanOptions, StorageCoreProjection,
    StorageGetManyRequest, StorageGetOptions, StorageKey, StoragePrecondition, StoragePrefix,
    StorageProjectedValue, StorageReadOptions, StorageSpace, StorageSpaceId, StorageWriteOptions,
    StorageWriteSet, ValueSemantics, exact_get_many,
};
use crate::tracked_state::{
    CertifiedCommitStateTopologyParent, CommitDeltaChangeLocator, CommitStateManifest,
    CommitStateMutationInventory, CommitStateReplayDebt, MaterializedTrackedStateRow,
    StagedCommitStateManifest, TRACKED_STATE_CHANGE_LOCATOR_SPACE, TrackedStateChunkOverlay,
    TrackedStateCommitDeltaRef, TrackedStateContext, TrackedStateDeltaRef, TrackedStateDiffRequest,
    TrackedStateFilter, TrackedStateKey, TrackedStateKeyRef, TrackedStateReadColumns,
    TrackedStateRootId, TrackedStateScanRequest, commit_delta_member_scopes,
    commit_history_is_deferred, deferred_commit_global_scope, direct_change_locator,
    encode_key_ref, incomplete_touched_scope_filter, load_change_record_by_id,
    load_commit_state_manifest, load_published_commit_state_topology,
    stage_certified_commit_state_manifest_with_handle, stage_change_locators,
    stage_commit_history_available, stage_commit_history_deferred_with_scope,
    stage_commit_state_manifest_with_handle,
    stage_current_state_scoped_ranges_from_complete_state_source,
    stage_current_state_scoped_ranges_from_topology, stage_imported_addressable_commit_deltas,
    stage_row_pk_index_from_deltas, stage_row_pk_index_from_members, staged_commit_delta_members,
    staged_commit_delta_segment_bytes,
};
use crate::{Lix, LixError};

use super::commit::{
    SyncCommit, SyncCommitMember, export_sync_commit, load_sync_commit,
    load_sync_commit_state_alias, stage_materialized_sync_state_alias,
};
use super::protocol::{
    SyncBlobManifest, SyncBranchHead, SyncCommitHeader, SyncEvent, SyncHistoryBoundary,
    SyncHistoryResponse, SyncPushRequest, SyncPushResponse, SyncRefUpdate,
    SyncRepositoryPullResponse, SyncSnapshotRow, SyncSnapshotRowPage,
};

fn immutable_object_mismatch(kind: &str, id: impl ToString) -> LixError {
    let id = id.to_string();
    LixError::new(
        super::SYNC_IMMUTABLE_OBJECT_MISMATCH_CODE,
        format!("sync {kind} '{id}' already exists with different content"),
    )
    .with_details(serde_json::json!({
        "objectKind": kind,
        "objectId": id,
    }))
}

pub(super) fn sync_commit_blob_ids(commits: &[SyncCommit]) -> Result<BTreeSet<String>, LixError> {
    let mut ids = BTreeSet::new();
    for member in commits
        .iter()
        .flat_map(|commit| &commit.members)
        .filter(|member| member.schema_key == "lix_binary_blob_ref" && !member.deleted)
    {
        let blob_id = member
            .snapshot
            .as_ref()
            .and_then(|snapshot| snapshot.get("blob_hash"))
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "live sync binary blob ref has no blob_hash",
                )
            })?;
        super::validate_blake3_id(blob_id, "sync binary blob ref blob_hash")?;
        ids.insert(blob_id.to_owned());
    }
    Ok(ids)
}

fn append_bounded_inline_blob(
    inline_blobs: &mut Vec<SyncBlobManifest>,
    encoded_len: &mut usize,
    manifest: SyncBlobManifest,
    context: &str,
) -> Result<bool, LixError> {
    let manifest_len = serde_json::to_vec(&manifest)
        .map_err(|error| {
            LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                format!("encode {context}: {error}"),
            )
        })?
        .len();
    let addition = manifest_len.saturating_add(usize::from(!inline_blobs.is_empty()));
    if encoded_len.saturating_add(addition) > super::MAX_SYNC_PULL_RESPONSE_BYTES {
        return Ok(false);
    }
    *encoded_len += addition;
    inline_blobs.push(manifest);
    Ok(true)
}

/// Loads either representation that can own a canonical change payload.
///
/// Snapshot bootstrap stores every currently-live change in the standalone
/// changelog namespace, including changes whose deferred commit body has not
/// arrived yet. Ordinary commit import may instead address the same payload
/// through its commit delta. History hydration must recognize both forms as
/// one logical change, otherwise filling a deferred body collides with the
/// already-readable hot snapshot row.
async fn load_existing_sync_change(
    read: &(impl StorageAdapterRead + ?Sized),
    change_id: ChangeId,
) -> Result<Option<ChangeRecord>, LixError> {
    let change_ids = [change_id];
    let mut changelog = ChangelogContext::new().reader(read);
    let stored = changelog
        .load_changes(ChangeLoadRequest {
            change_ids: &change_ids,
        })
        .await?
        .into_iter()
        .next()
        .expect("one changelog change was requested")
        .1;
    match stored {
        Some(change) => Ok(Some(change)),
        None => load_change_record_by_id(read, change_id).await,
    }
}

fn sync_change_records_equal(
    existing: &ChangeRecord,
    incoming: &ChangeRecord,
) -> Result<bool, LixError> {
    if existing.format_version != incoming.format_version
        || existing.change_id != incoming.change_id
        || existing.account_id != incoming.account_id
        || existing.schema_key != incoming.schema_key
        || existing.row_pk != incoming.row_pk
        || existing.file_id != incoming.file_id
        || existing.metadata != incoming.metadata
        || existing.created_at != incoming.created_at
        || existing.origin_key != incoming.origin_key
    {
        return Ok(false);
    }
    match (&existing.snapshot, &incoming.snapshot) {
        (None, None) => Ok(true),
        (Some(left), Some(right)) if left == right => Ok(true),
        (Some(left), Some(right)) => {
            let left = crate::plugin::runtime::WasmTypedRow::decode_durable_payload(
                left.clone().into(),
                &existing.schema_key,
                &existing.row_pk,
            )?;
            let right = crate::plugin::runtime::WasmTypedRow::decode_durable_payload(
                right.clone().into(),
                &incoming.schema_key,
                &incoming.row_pk,
            )?;
            Ok(left == right)
        }
        (None, Some(_)) | (Some(_), None) => Ok(false),
    }
}

fn stage_imported_commit_body(
    writes: &mut StorageWriteSet,
    commit: &ParsedCommit,
    imported_authored_change_ids: &mut BTreeSet<ChangeId>,
    selected_fallbacks: &mut BTreeMap<ChangeId, CommitDeltaChangeLocator>,
    authored: &mut BTreeMap<ChangeId, CommitDeltaChangeLocator>,
) -> Result<CommitStateMutationInventory, LixError> {
    let deltas = commit
        .members
        .iter()
        .map(|member| member.as_commit_delta(commit.commit_id))
        .collect::<Vec<_>>();
    let mut authored_change_ids = BTreeSet::new();
    let addressable = commit
        .members
        .iter()
        .map(|member| {
            if !member.authored {
                return false;
            }
            authored_change_ids.insert(member.change_id);
            direct_change_locator(member.change_id)
                .is_some_and(|locator| locator.commit_id == commit.commit_id)
        })
        .collect::<Vec<_>>();
    let staged = stage_imported_addressable_commit_deltas(writes, &deltas, &addressable)?;
    for ((member, assigned), addressable) in commit
        .members
        .iter()
        .zip(&staged.assigned_change_ids)
        .zip(&addressable)
    {
        if *addressable && member.change_id != *assigned {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync commit contains a noncanonical authored change id",
            ));
        }
    }
    imported_authored_change_ids.extend(authored_change_ids.iter().copied());
    for locator in staged.locators.iter().cloned() {
        if authored_change_ids.contains(&locator.change_id) {
            authored.insert(locator.change_id, locator);
        } else {
            selected_fallbacks
                .entry(locator.change_id)
                .or_insert(locator);
        }
    }
    Ok(staged.mutation_inventory().clone())
}

async fn stage_missing_selected_change_locators(
    read: &(impl StorageAdapterRead + ?Sized),
    writes: &mut StorageWriteSet,
    preconditions: &mut Vec<StoragePrecondition>,
    selected_fallbacks: BTreeMap<ChangeId, CommitDeltaChangeLocator>,
) -> Result<(), LixError> {
    if selected_fallbacks.is_empty() {
        return Ok(());
    }
    let locators = selected_fallbacks.into_values().collect::<Vec<_>>();
    let keys = locators
        .iter()
        .map(|locator| {
            StorageKey(Bytes::copy_from_slice(
                locator.change_id.as_uuid().as_bytes(),
            ))
        })
        .collect::<Vec<_>>();
    let existing = exact_get_many(
        read,
        &[StorageGetManyRequest {
            space: TRACKED_STATE_CHANGE_LOCATOR_SPACE,
            keys: &keys,
            opts: StorageGetOptions::default(),
        }],
    )
    .await?;
    let missing = locators
        .into_iter()
        .zip(keys)
        .zip(existing.values)
        .filter_map(|((locator, key), existing)| {
            existing.is_none().then(|| {
                preconditions.push(StoragePrecondition::KeyAbsent {
                    space: TRACKED_STATE_CHANGE_LOCATOR_SPACE,
                    key,
                });
                locator
            })
        })
        .collect::<Vec<_>>();
    stage_change_locators(writes, &missing);
    Ok(())
}

fn format_sync_state_root_id(root_id: &TrackedStateRootId) -> String {
    blake3::Hash::from_bytes(*root_id.as_bytes())
        .to_hex()
        .to_string()
}

fn parse_sync_state_root_id(value: &str) -> Result<TrackedStateRootId, LixError> {
    let hash = blake3::Hash::from_hex(value).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("sync stateRootId must be 64 lowercase hexadecimal characters: {error}"),
        )
    })?;
    if hash.to_hex().as_str() != value {
        return Err(LixError::new(
            LixError::CODE_INVALID_PARAM,
            "sync stateRootId must use canonical lowercase hexadecimal",
        ));
    }
    Ok(TrackedStateRootId::new(*hash.as_bytes()))
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct SyncLiveValueRootId([u8; 32]);

fn format_sync_live_value_root_id(root_id: &SyncLiveValueRootId) -> String {
    blake3::Hash::from_bytes(root_id.0).to_hex().to_string()
}

fn parse_sync_live_value_root_id(value: &str) -> Result<SyncLiveValueRootId, LixError> {
    let hash = blake3::Hash::from_hex(value).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("sync live value root must be 64 lowercase hexadecimal characters: {error}"),
        )
    })?;
    if hash.to_hex().as_str() != value {
        return Err(LixError::new(
            LixError::CODE_INVALID_PARAM,
            "sync live value root must use canonical lowercase hexadecimal",
        ));
    }
    Ok(SyncLiveValueRootId(*hash.as_bytes()))
}

struct SyncLiveValueRowRef<'a> {
    schema_key: &'a str,
    file_id: Option<&'a str>,
    row_pk: &'a RowPk,
    change_id: ChangeId,
    commit_id: CommitId,
    created_at: LixTimestamp,
    updated_at: LixTimestamp,
    snapshot_json: &'a str,
    metadata_json: Option<&'a str>,
    change_account_id: &'a str,
    change_created_at: LixTimestamp,
    origin_key: Option<&'a str>,
}

#[derive(Clone)]
struct SyncLiveValueRow {
    schema_key: String,
    file_id: Option<String>,
    row_pk: RowPk,
    change_id: ChangeId,
    commit_id: CommitId,
    created_at: LixTimestamp,
    updated_at: LixTimestamp,
    snapshot_json: String,
    metadata_json: Option<String>,
    change_account_id: String,
    change_created_at: LixTimestamp,
    origin_key: Option<String>,
}

impl SyncLiveValueRow {
    fn as_ref(&self) -> SyncLiveValueRowRef<'_> {
        SyncLiveValueRowRef {
            schema_key: &self.schema_key,
            file_id: self.file_id.as_deref(),
            row_pk: &self.row_pk,
            change_id: self.change_id,
            commit_id: self.commit_id,
            created_at: self.created_at,
            updated_at: self.updated_at,
            snapshot_json: &self.snapshot_json,
            metadata_json: self.metadata_json.as_deref(),
            change_account_id: &self.change_account_id,
            change_created_at: self.change_created_at,
            origin_key: self.origin_key.as_deref(),
        }
    }
}

#[derive(Debug)]
pub(super) struct SyncDeltaHotBlobPlan {
    pub(super) live_blob_ids: BTreeSet<String>,
    /// Final-live payloads whose owning row comes from outside this delta.
    ///
    /// This is deliberately row provenance rather than target provenance. A
    /// final head/checkpoint can be carried by the page while inheriting a blob
    /// from an older external parent. Such a payload may have only cold manifest
    /// metadata locally and must be hydrated before the new ref is certified.
    pub(super) external_survivor_blob_ids: BTreeSet<String>,
}

fn sync_live_value_blob_ids<'a>(
    rows: impl IntoIterator<Item = &'a SyncLiveValueRow>,
) -> Result<BTreeSet<String>, LixError> {
    let mut ids = BTreeSet::new();
    for row in rows {
        if row.schema_key != "lix_binary_blob_ref" {
            continue;
        }
        let blob_id = serde_json::from_str::<serde_json::Value>(&row.snapshot_json)
            .ok()
            .and_then(|snapshot| {
                snapshot
                    .get("blob_hash")
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_owned)
            })
            .ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "live sync binary blob ref has no blob_hash",
                )
            })?;
        super::validate_blake3_id(&blob_id, "sync binary blob ref blob_hash")?;
        ids.insert(blob_id);
    }
    Ok(ids)
}

fn canonical_sync_jsonb(value: &str, context: &str) -> Result<Vec<u8>, LixError> {
    let value = serde_json::from_str(value).map_err(|error| {
        LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            format!("decode {context} while certifying sync live state: {error}"),
        )
    })?;
    lix_schema::Jsonb::from_value(value)
        .binary()
        .map(|bytes| bytes.into_owned())
        .map_err(|error| {
            LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                format!("encode {context} while certifying sync live state: {error}"),
            )
        })
}

fn hash_len_prefixed(hasher: &mut blake3::Hasher, bytes: &[u8]) {
    hasher.update(&u64::try_from(bytes.len()).unwrap_or(u64::MAX).to_be_bytes());
    hasher.update(bytes);
}

fn sync_live_value_root<'a>(
    rows: impl IntoIterator<Item = SyncLiveValueRowRef<'a>>,
) -> Result<SyncLiveValueRootId, LixError> {
    let mut members = BTreeMap::<Vec<u8>, [u8; 32]>::new();
    for row in rows {
        let key = encode_key_ref(TrackedStateKeyRef {
            schema_key: row.schema_key,
            file_id: row.file_id,
            row_pk: row.row_pk,
        });
        let snapshot = canonical_sync_jsonb(row.snapshot_json, "row snapshot")?;
        let metadata = row
            .metadata_json
            .map(|metadata| canonical_sync_jsonb(metadata, "row metadata"))
            .transpose()?;
        let mut member = blake3::Hasher::new();
        member.update(b"lix.sync.live-value.row.v2\0");
        hash_len_prefixed(&mut member, &key);
        member.update(row.change_id.as_uuid().as_bytes());
        member.update(row.commit_id.as_uuid().as_bytes());
        member.update(&row.created_at.packed().to_be_bytes());
        member.update(&row.updated_at.packed().to_be_bytes());
        hash_len_prefixed(&mut member, &snapshot);
        match metadata {
            Some(metadata) => {
                member.update(&[1]);
                hash_len_prefixed(&mut member, &metadata);
            }
            None => {
                member.update(&[0]);
            }
        };
        hash_len_prefixed(&mut member, row.change_account_id.as_bytes());
        member.update(&row.change_created_at.packed().to_be_bytes());
        match row.origin_key {
            Some(origin_key) => {
                member.update(&[1]);
                hash_len_prefixed(&mut member, origin_key.as_bytes());
            }
            None => {
                member.update(&[0]);
            }
        }
        if members.insert(key, *member.finalize().as_bytes()).is_some() {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync live value certificate contains a duplicate row identity",
            ));
        }
    }
    let mut root = blake3::Hasher::new();
    root.update(b"lix.sync.live-value.root.v2\0");
    root.update(
        &u64::try_from(members.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    for (key, digest) in members {
        hash_len_prefixed(&mut root, &key);
        root.update(&digest);
    }
    Ok(SyncLiveValueRootId(*root.finalize().as_bytes()))
}

fn sync_header_from_record(record: &CommitRecord, global_scope: bool) -> SyncCommitHeader {
    SyncCommitHeader {
        is_checkpoint: record.is_checkpoint,
        commit_id: record.commit_id.to_string(),
        parent_commit_ids: record
            .parent_commit_ids
            .iter()
            .map(ToString::to_string)
            .collect(),
        base_commit_id: record.base_commit_id.map(|id| id.to_string()),
        account_id: record.account_id.clone(),
        created_at: record.created_at.to_string(),
        global_scope,
        generation: record.generation,
        first_parent_jump_commit_id: (record.first_parent_jump_span > 0)
            .then(|| record.first_parent_jump_commit_id.to_string()),
        first_parent_jump_span: (record.first_parent_jump_span > 0)
            .then_some(record.first_parent_jump_span),
    }
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SnapshotRowCursor {
    schema_key: String,
    file_id: Option<String>,
    row_pk: serde_json::Value,
}

fn encode_snapshot_row_cursor(
    schema_key: &str,
    file_id: Option<&str>,
    row_pk: &RowPk,
) -> Result<String, LixError> {
    let wire = SnapshotRowCursor {
        schema_key: schema_key.to_owned(),
        file_id: file_id.map(str::to_owned),
        row_pk: row_pk.as_typed_json_array_value()?,
    };
    let bytes = serde_json::to_vec(&wire).map_err(|error| {
        LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            format!("encode sync snapshot continuation: {error}"),
        )
    })?;
    Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
}

fn decode_snapshot_row_cursor(value: &str) -> Result<(String, Option<String>, RowPk), LixError> {
    if value.len() > 4096 {
        return Err(LixError::new(
            LixError::CODE_INVALID_PARAM,
            "sync snapshot continuation is too large",
        ));
    }
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(value)
        .map_err(|error| {
            LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!("decode sync snapshot continuation: {error}"),
            )
        })?;
    let wire: SnapshotRowCursor = serde_json::from_slice(&bytes).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("decode sync snapshot continuation: {error}"),
        )
    })?;
    let row_pk = RowPk::from_typed_json_array_value(&wire.row_pk).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("decode sync snapshot continuation row identity: {error}"),
        )
    })?;
    Ok((wire.schema_key, wire.file_id, row_pk))
}

pub(crate) const SYNC_SEQUENCE_SPACE: StorageSpace = StorageSpace::declare(
    StorageSpaceId(0x0007_0010),
    "sync.repository_sequence.v1",
    ValueSemantics::Mutable,
);

pub(crate) const SYNC_REPOSITORY_EVENT_SPACE: StorageSpace = StorageSpace::declare(
    StorageSpaceId(0x0007_0011),
    "sync.repository_event.v1",
    ValueSemantics::Immutable,
);

pub(crate) const SYNC_REPLICA_STATE_SPACE: StorageSpace = StorageSpace::declare(
    StorageSpaceId(0x0007_0014),
    "sync.replica_state.v3",
    ValueSemantics::Mutable,
);

// Authority admission and replica receipts are mutually exclusive repository
// roles, so their distinct keys share the existing private sync-control space.
// Keeping the marker here avoids expanding the public registered-space list.
pub(crate) const SYNC_AUTHORITY_STATE_SPACE: StorageSpace = SYNC_REPLICA_STATE_SPACE;

const SEQUENCE_KEY: &[u8] = b"repository";
const REPLICA_STATE_KEY: &[u8] = b"repository";
const AUTHORITY_STATE_KEY: &[u8] = b"authority";
pub(crate) const AUTHORITY_STATE_VALUE: &[u8] = b"certified-authority-v4";
const AMBIGUOUS_REPLICA_STATE_CODE: &str = "LIX_ERROR_SYNC_REPLICA_STATE_AMBIGUOUS";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RepositoryEventRecord {
    cursor: u64,
    commit_ids: Vec<String>,
    ref_updates: Vec<SyncRefUpdate>,
}

/// Runtime-owned immutable upload wave; never persisted as a second outbox.
#[derive(Debug)]
pub(crate) struct CachedSyncUploadPlan {
    plan: super::upload_plan::UploadPlan,
    authoritative_branches: BTreeMap<String, AuthoritativeBranchCoordinate>,
    prepared_page: Option<super::upload_plan::UploadPlanPage>,
}

impl CachedSyncUploadPlan {
    pub(crate) fn is_complete(&self) -> bool {
        self.plan.is_complete()
    }

    /// The runtime calls this only after durably importing the push receipt.
    pub(crate) fn acknowledge(&mut self) -> Result<(), LixError> {
        let page = self.prepared_page.as_ref().ok_or_else(|| {
            LixError::new(
                LixError::CODE_INVALID_PARAM,
                "upload wave has no prepared acknowledgment",
            )
        })?;
        let coordinates = page
            .ref_updates
            .iter()
            .map(|update| {
                Ok((
                    update.branch_id.clone(),
                    AuthoritativeBranchCoordinate::from_wire(
                        update.head_commit_id.clone(),
                        update.checkpoint_commit_id.clone(),
                        "acknowledged upload ref",
                    )?,
                ))
            })
            .collect::<Result<Vec<_>, LixError>>()?;
        self.plan.acknowledge(page)?;
        for (branch, coordinate) in coordinates {
            self.authoritative_branches.insert(branch, coordinate);
        }
        self.prepared_page = None;
        Ok(())
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SyncReplicaState {
    active_account_id: String,
    cursor: u64,
    authoritative_branches: BTreeMap<String, AuthoritativeBranchCoordinate>,
    /// Locally computed complete-value roots at each installed authority ref.
    /// This is private cache metadata, never part of the sync wire.
    #[serde(default)]
    certified_branch_roots: BTreeMap<String, CertifiedBranchRoots>,
    /// Last cursor whose locally computed roots were compared with an
    /// authority Snapshot response.
    #[serde(default)]
    snapshot_certified_cursor: Option<u64>,
    /// Restore operations are branch intent, not graph-shape inference. They
    /// are recorded in the same atomic commit as `lix_restore` so reconnect,
    /// crash recovery, and post-restore local commits preserve the exact CAS
    /// coordinate that the user intended to reset.
    #[serde(default)]
    pending_resets: BTreeMap<String, PendingSyncReset>,
    /// Commit objects observed from the authority but not yet made reachable
    /// from a fully converged set of authority refs.
    ///
    /// Large offline outboxes publish dependency-closed commit batches before
    /// their final ref update. Remembering those acknowledgements makes the
    /// next batch advance instead of rebuilding the same first 512 commits.
    authority_known_commit_ids: BTreeSet<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CertifiedBranchRoots {
    head_state_root_id: String,
    checkpoint_state_root_id: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PendingSyncReset {
    expected_authority_head_commit_id: String,
    expected_authority_checkpoint_commit_id: String,
    restore_target_commit_id: String,
    /// A commit on the restored local chain that the authority is already
    /// known to have. This is computed once, when restore is rare, rather than
    /// rescanning history on every ordinary sync push.
    authority_known_ancestor_commit_id: Option<String>,
    /// The actual ref head included in the latest prepared reset request. It
    /// can differ from the restore target when local commits follow restore.
    #[serde(default)]
    prepared_reset_head_commit_id: Option<String>,
    #[serde(default)]
    prepared_reset_checkpoint_commit_id: Option<String>,
    /// Legacy head-only tokens retained for receipt decoding. They cannot
    /// establish the exact target coordinate of an acknowledgment.
    #[serde(default)]
    superseded_prepared_reset_head_commit_ids: BTreeSet<String>,
    /// Exact superseded targets prepared against this intent's expected
    /// authority coordinate. Legacy head-only tokens never prove acceptance.
    #[serde(default)]
    superseded_prepared_reset_coordinates: BTreeSet<(String, String)>,
}

const MAX_SUPERSEDED_RESET_COORDINATES: usize = 64;

fn retain_prepared_reset_coordinate(
    coordinates: &mut BTreeSet<(String, String)>,
    head: Option<&String>,
    checkpoint: Option<&String>,
) -> bool {
    let (Some(head), Some(checkpoint)) = (head, checkpoint) else {
        return false;
    };
    if coordinates.len() >= MAX_SUPERSEDED_RESET_COORDINATES {
        return false;
    }
    coordinates.insert((head.clone(), checkpoint.clone()))
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum SyncReplicaBinding {
    Unbound,
    Bound { account_id: String },
    Ambiguous,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InitialSyncSnapshotInstall {
    Installed,
    ExistingRepository,
    Ambiguous,
}

/// The authority's complete coordinate for one known branch.
///
/// Absence from `SyncReplicaState::authoritative_branches` means the branch has
/// never been observed. A present `Deleted` value is a durable deletion. A
/// headed branch always carries its checkpoint, making the invalid split-map
/// state "head without checkpoint" unrepresentable.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    rename_all = "camelCase",
    rename_all_fields = "camelCase",
    tag = "state"
)]
enum AuthoritativeBranchCoordinate {
    Deleted,
    Headed {
        head_commit_id: String,
        checkpoint_commit_id: String,
    },
}

impl AuthoritativeBranchCoordinate {
    fn from_wire(
        head_commit_id: Option<String>,
        checkpoint_commit_id: Option<String>,
        context: &str,
    ) -> Result<Self, LixError> {
        match (head_commit_id, checkpoint_commit_id) {
            (None, None) => Ok(Self::Deleted),
            (Some(head_commit_id), Some(checkpoint_commit_id)) => Ok(Self::Headed {
                head_commit_id,
                checkpoint_commit_id,
            }),
            _ => Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!("{context} head and checkpoint must be paired"),
            )),
        }
    }

    fn head_commit_id(&self) -> Option<&str> {
        match self {
            Self::Deleted => None,
            Self::Headed { head_commit_id, .. } => Some(head_commit_id),
        }
    }

    fn checkpoint_commit_id(&self) -> Option<&str> {
        match self {
            Self::Deleted => None,
            Self::Headed {
                checkpoint_commit_id,
                ..
            } => Some(checkpoint_commit_id),
        }
    }
}

struct ReplicaStatePublication<'a> {
    retired_upload_proof_branches: &'a [String],
    reset_pending: bool,
    expected_cursor: u64,
    expected_state_raw: &'a Bytes,
    state: &'a SyncReplicaState,
}

pub(crate) fn replica_state_key() -> StorageKey {
    StorageKey(Bytes::from_static(REPLICA_STATE_KEY))
}

pub(crate) fn authority_state_key() -> StorageKey {
    StorageKey(Bytes::from_static(AUTHORITY_STATE_KEY))
}

async fn load_authority_state(
    read: &(impl StorageAdapterRead + ?Sized),
) -> Result<Option<Bytes>, LixError> {
    let key = authority_state_key();
    let values = exact_get_many(
        read,
        &[StorageGetManyRequest {
            space: SYNC_AUTHORITY_STATE_SPACE,
            keys: std::slice::from_ref(&key),
            opts: StorageGetOptions::default(),
        }],
    )
    .await?;
    values
        .values
        .into_iter()
        .next()
        .flatten()
        .map(|value| match value {
            StorageProjectedValue::FullValue(value) => Ok(value),
            StorageProjectedValue::KeyOnly => Err(LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "sync authority state read omitted its value",
            )),
        })
        .transpose()
}

/// Durably fences a repository into authority ownership before server
/// sessions can publish writes. Reopening a server accepts the exact marker;
/// a plain engine over the same storage never receives the process-local
/// adapter admission and therefore fails its atomic marker-absence fence.
pub(crate) async fn admit_sync_authority_storage<StorageImpl>(
    adapter: &StorageAdapter<StorageImpl>,
    expected_mutation_revision: Option<Bytes>,
) -> Result<(), LixError>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    for _ in 0..2 {
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        if load_replica_state(&read).await?.0.is_some() {
            return Err(LixError::new(
                super::SYNC_PROTOCOL_MISMATCH_CODE,
                "a certified replica cache cannot be opened as repository authority",
            ));
        }
        match load_authority_state(&read).await? {
            Some(value) if value.as_ref() == AUTHORITY_STATE_VALUE => {
                adapter.admit_sync_authority_writer();
                return Ok(());
            }
            Some(_) => {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "sync authority state marker is corrupt or unsupported",
                ));
            }
            None => {}
        }
        drop(read);
        let mut writes = adapter.new_write_set();
        writes.put(
            SYNC_AUTHORITY_STATE_SPACE,
            authority_state_key(),
            AUTHORITY_STATE_VALUE.to_vec(),
        );
        match adapter
            .commit_write_set(
                writes,
                StorageWriteOptions {
                    preconditions: vec![
                        crate::storage_adapter::repository_mutation_revision_precondition(
                            expected_mutation_revision.clone(),
                        ),
                    ],
                    await_durable: true,
                    ..StorageWriteOptions::default()
                },
            )
            .await
        {
            Ok(_) => {
                adapter.admit_sync_authority_writer();
                return Ok(());
            }
            Err(_) => {
                // Another server admission may have installed the same marker.
                // Re-read once and accept only its exact protocol value.
            }
        }
    }
    Err(LixError::new(
        LixError::CODE_TRANSACTION_CONFLICT,
        "repository authority ownership changed during server admission",
    ))
}

async fn load_replica_state(
    read: &(impl StorageAdapterRead + ?Sized),
) -> Result<(Option<SyncReplicaState>, Option<Bytes>), LixError> {
    let key = replica_state_key();
    let values = exact_get_many(
        read,
        &[StorageGetManyRequest {
            space: SYNC_REPLICA_STATE_SPACE,
            keys: std::slice::from_ref(&key),
            opts: StorageGetOptions::default(),
        }],
    )
    .await?;
    let raw = values
        .values
        .into_iter()
        .next()
        .flatten()
        .map(|value| match value {
            StorageProjectedValue::FullValue(value) => Ok(value),
            StorageProjectedValue::KeyOnly => Err(LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "sync replica state read omitted its value",
            )),
        })
        .transpose()?;
    let state = raw
        .as_ref()
        .filter(|raw| raw.as_ref() != AUTHORITY_STATE_VALUE)
        .map(|raw| {
            serde_json::from_slice(raw).map_err(|error| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!("decode sync replica state: {error}"),
                )
            })
        })
        .transpose()?;
    Ok((state, raw))
}

pub(crate) async fn load_sync_replica_account(
    read: &(impl StorageAdapterRead + ?Sized),
) -> Result<Option<String>, LixError> {
    Ok(load_replica_state(read)
        .await?
        .0
        .map(|state| state.active_account_id))
}

pub(super) async fn inspect_sync_replica_binding(
    read: &(impl StorageAdapterRead + ?Sized),
) -> Result<SyncReplicaBinding, LixError> {
    let exact = load_replica_state(read).await?.0;
    let range = StoragePrefix {
        bytes: Bytes::new(),
    }
    .to_range()?;
    let mut cursor = read
        .begin_scan(
            SYNC_REPLICA_STATE_SPACE,
            range,
            StorageBeginScanOptions {
                projection: StorageCoreProjection::KeyOnly,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    let keys = cursor.next_page(2).await?;
    match (exact, keys.len()) {
        (None, 0) => Ok(SyncReplicaBinding::Unbound),
        (None, _) => Ok(SyncReplicaBinding::Ambiguous),
        (Some(state), 1) => Ok(SyncReplicaBinding::Bound {
            account_id: state.active_account_id,
        }),
        (Some(_), _) => Ok(SyncReplicaBinding::Ambiguous),
    }
}

/// Moves the one legacy URL-keyed sync receipt to the repository-scoped key.
///
/// The raw bytes are preserved so repository admission cannot alter cursor or
/// outbox acknowledgement state. Lix supports exactly one sync authority per
/// local store, so more than one receipt is ambiguous and must fail closed.
pub(crate) async fn migrate_legacy_sync_replica_state<StorageImpl>(
    adapter: &StorageAdapter<StorageImpl>,
) -> Result<(), LixError>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    let read = adapter.begin_read(StorageReadOptions::default()).await?;
    let range = StoragePrefix {
        bytes: Bytes::new(),
    }
    .to_range()?;
    let mut cursor = read
        .begin_scan(
            SYNC_REPLICA_STATE_SPACE,
            range,
            StorageBeginScanOptions {
                projection: StorageCoreProjection::FullValue,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    let (entries, _) = cursor.next_page(2).await?.into_parts();
    if entries.is_empty() {
        return Ok(());
    }
    if entries.len() != 1 {
        return Err(ambiguous_replica_state_error());
    }
    let entry = entries.into_iter().next().expect("one replica-state row");
    drop(cursor);
    if entry.key == replica_state_key() {
        return Ok(());
    }
    let StorageProjectedValue::FullValue(raw) = entry.value else {
        return Err(LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            "legacy sync replica-state scan omitted its value",
        ));
    };
    serde_json::from_slice::<SyncReplicaState>(&raw).map_err(|error| {
        LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            format!("decode sync replica state: {error}"),
        )
    })?;

    let canonical_key = replica_state_key();
    let mut writes = adapter.new_write_set();
    writes.put(
        SYNC_REPLICA_STATE_SPACE,
        canonical_key.clone(),
        raw.to_vec(),
    );
    writes.delete(SYNC_REPLICA_STATE_SPACE, entry.key.clone());
    drop(read);
    let commit = adapter
        .commit_certified_replica_write_set(
            super::certified_replica_write_capability(),
            writes,
            StorageWriteOptions {
                preconditions: vec![
                    StoragePrecondition::KeyAbsent {
                        space: SYNC_REPLICA_STATE_SPACE,
                        key: canonical_key,
                    },
                    StoragePrecondition::KeyValueEquals {
                        space: SYNC_REPLICA_STATE_SPACE,
                        key: entry.key,
                        expected: raw,
                    },
                ],
                await_durable: true,
                ..StorageWriteOptions::default()
            },
        )
        .await;
    match commit {
        Ok(_) => Ok(()),
        Err(error) => {
            let error = LixError::from(error);
            if error.code != LixError::CODE_TRANSACTION_CONFLICT
                && error.code != LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN
            {
                return Err(error);
            }
            let read = adapter.begin_read(StorageReadOptions::default()).await?;
            match inspect_sync_replica_binding(&read).await? {
                SyncReplicaBinding::Bound { .. } => Ok(()),
                SyncReplicaBinding::Unbound | SyncReplicaBinding::Ambiguous => Err(error),
            }
        }
    }
}

fn ambiguous_replica_state_error() -> LixError {
    LixError::new(
        AMBIGUOUS_REPLICA_STATE_CODE,
        "sync replica contains multiple durable authority receipts",
    )
}

pub(crate) async fn has_any_sync_replica_state(
    read: &(impl StorageAdapterRead + ?Sized),
) -> Result<bool, LixError> {
    let range = StoragePrefix {
        bytes: Bytes::new(),
    }
    .to_range()?;
    let mut cursor = read
        .begin_scan(
            SYNC_REPLICA_STATE_SPACE,
            range,
            StorageBeginScanOptions {
                projection: StorageCoreProjection::FullValue,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    while let Some(entries) = cursor.next_chunk().await? {
        for entry in entries {
            let StorageProjectedValue::FullValue(value) = entry.value else {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "sync replica-state scan omitted its value",
                ));
            };
            if entry.key != authority_state_key() || value.as_ref() != AUTHORITY_STATE_VALUE {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

/// Commit bodies named by retained repository events remain part of the
/// authority's replay contract until those events expire.
pub(crate) async fn load_replayable_repository_event_commit_ids(
    read: &(impl StorageAdapterRead + ?Sized),
) -> Result<BTreeSet<CommitId>, LixError> {
    let range = StoragePrefix {
        bytes: Bytes::new(),
    }
    .to_range()?;
    let mut cursor = read
        .begin_scan(
            SYNC_REPOSITORY_EVENT_SPACE,
            range,
            StorageBeginScanOptions {
                projection: StorageCoreProjection::FullValue,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    let mut commit_ids = BTreeSet::new();
    while let Some(entries) = cursor.next_chunk().await? {
        for entry in entries {
            let StorageProjectedValue::FullValue(value) = entry.value else {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "repository sync event scan omitted its value",
                ));
            };
            let record: RepositoryEventRecord =
                serde_json::from_slice(&value).map_err(|error| {
                    LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!("decode repository sync event for GC retention: {error}"),
                    )
                })?;
            for commit_id in record.commit_ids {
                commit_ids.insert(CommitId::parse_lix(
                    &commit_id,
                    "repository sync event commit id",
                )?);
            }
        }
    }
    Ok(commit_ids)
}

/// Commits that must remain exportable until every configured authority has
/// acknowledged them. Compact checkpoints add a physical-state source edge
/// outside canonical parent ancestry, so the pending outbox closure follows
/// both edge kinds. Only confirmed ref coordinates stop provenance traversal;
/// body-only acknowledgments must not permit collection of pending source proofs.
pub(crate) async fn load_pending_sync_export_commit_ids(
    read: &(impl StorageAdapterRead + ?Sized),
    controls: &[(String, BranchHeadControl)],
) -> Result<BTreeSet<CommitId>, LixError> {
    let range = StoragePrefix {
        bytes: Bytes::new(),
    }
    .to_range()?;
    let mut cursor = read
        .begin_scan(
            SYNC_REPLICA_STATE_SPACE,
            range,
            StorageBeginScanOptions {
                projection: StorageCoreProjection::FullValue,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    let mut states = Vec::new();
    while let Some(entries) = cursor.next_chunk().await? {
        for entry in entries {
            let StorageProjectedValue::FullValue(value) = entry.value else {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "sync replica-state retention scan omitted its value",
                ));
            };
            if entry.key == authority_state_key() && value.as_ref() == AUTHORITY_STATE_VALUE {
                continue;
            }
            states.push(
                serde_json::from_slice::<SyncReplicaState>(&value).map_err(|error| {
                    LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!("decode sync replica state for GC retention: {error}"),
                    )
                })?,
            );
        }
    }

    let mut retained = BTreeSet::new();
    for state in states {
        let mut known = BTreeSet::new();
        for coordinate in state.authoritative_branches.values() {
            if let AuthoritativeBranchCoordinate::Headed {
                head_commit_id,
                checkpoint_commit_id,
            } = coordinate
            {
                known.insert(CommitId::parse_lix(
                    head_commit_id,
                    "sync GC authority head",
                )?);
                known.insert(CommitId::parse_lix(
                    checkpoint_commit_id,
                    "sync GC authority checkpoint",
                )?);
            }
        }
        // Rejection resets need the confirmed baseline even after an offline
        // compact checkpoint removes it from the visible branch ancestry.
        retained.extend(known.iter().copied());
        // Body acknowledgments do not retire local provenance: only a ref
        // acknowledgment makes its captured source interval unnecessary.

        let mut pending = controls
            .iter()
            .flat_map(|(_, control)| {
                [
                    Some(control.head_commit_id),
                    control.working_diff_checkpoint_commit_id,
                ]
            })
            .flatten()
            .map(|id| (id, true))
            .collect::<Vec<_>>();
        let mut seen_required = BTreeSet::new();
        let mut seen_provenance = BTreeSet::new();
        while let Some((commit_id, required)) = pending.pop() {
            if known.contains(&commit_id)
                || seen_required.contains(&commit_id)
                || (!required && !seen_provenance.insert(commit_id))
            {
                continue;
            }
            if required {
                seen_required.insert(commit_id);
            }
            let Some(record) = load_commit_record(read, commit_id).await? else {
                if required {
                    return Err(LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!("pending sync export commit '{commit_id}' has no commit record"),
                    ));
                }
                // A historical checkpoint may outlive its captured interval.
                // Restoring it does not turn its old local provenance into a
                // mandatory wire dependency or require re-fetching cold history.
                continue;
            };
            retained.insert(commit_id);
            if let Some((_, source)) =
                super::commit::load_sync_checkpoint_source(read, commit_id).await?
            {
                pending.push((source, false));
            }
            pending.extend(record.parent_commit_ids.iter().map(|id| (*id, required)));
            pending.extend(record.base_commit_id.map(|id| (id, required)));
            if let Some(alias) = load_sync_commit_state_alias(read, commit_id).await? {
                pending.push((
                    CommitId::parse_lix(
                        &alias.source_commit_id,
                        "pending sync export complete-state source",
                    )?,
                    required,
                ));
            }
        }
    }
    Ok(retained)
}

fn stage_replica_state(
    writes: &mut StorageWriteSet,
    preconditions: &mut Vec<StoragePrecondition>,
    state: &SyncReplicaState,
    previous: Option<Bytes>,
) -> Result<(), LixError> {
    let key = replica_state_key();
    writes.put(
        SYNC_REPLICA_STATE_SPACE,
        key.clone(),
        serde_json::to_vec(state).map_err(|error| {
            LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                format!("encode sync replica state: {error}"),
            )
        })?,
    );
    preconditions.push(match previous {
        Some(expected) => StoragePrecondition::KeyValueEquals {
            space: SYNC_REPLICA_STATE_SPACE,
            key,
            expected,
        },
        None => StoragePrecondition::KeyAbsent {
            space: SYNC_REPLICA_STATE_SPACE,
            key,
        },
    });
    Ok(())
}

/// Records the active replica's exact authority coordinate for an ancestor restore.
/// The caller commits these writes atomically with the restored branch ref.
pub(crate) async fn stage_sync_restore_intents(
    read: &(impl StorageAdapterRead + ?Sized),
    writes: &mut StorageWriteSet,
    preconditions: &mut Vec<StoragePrecondition>,
    remote_id: &str,
    restore_targets: &BTreeMap<String, CommitId>,
) -> Result<(), LixError> {
    if restore_targets.is_empty() {
        return Ok(());
    }
    super::upload_plan::stage_invalidate(writes);
    let (state, previous) = load_replica_state(read).await?;
    let Some(mut state) = state else {
        return Err(LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            format!("sync replica restore has no state for remote '{remote_id}'"),
        ));
    };
    let mut changed = false;
    for (branch_id, restore_target) in restore_targets {
        let Some(AuthoritativeBranchCoordinate::Headed {
            head_commit_id,
            checkpoint_commit_id,
        }) = state.authoritative_branches.get(branch_id).cloned()
        else {
            continue;
        };
        let restore_target = restore_target.to_string();
        let previous_intent = state
            .pending_resets
            .get(branch_id)
            .cloned()
            .filter(|pending| {
                pending.expected_authority_head_commit_id == head_commit_id
                    && pending.expected_authority_checkpoint_commit_id == checkpoint_commit_id
            });
        let target = CommitId::parse_lix(&restore_target, "pending sync restore target")?;
        let authority_known_ancestor_commit_id = find_restore_authority_boundary(
            read,
            &state,
            previous_intent.as_ref(),
            &head_commit_id,
            &checkpoint_commit_id,
            target,
        )
        .await?
        .map(|commit_id| commit_id.to_string());
        let superseded_prepared_reset_head_commit_ids = previous_intent
            .as_ref()
            .map(|pending| pending.superseded_prepared_reset_head_commit_ids.clone())
            .unwrap_or_default();
        let mut superseded_prepared_reset_coordinates = previous_intent
            .as_ref()
            .map(|pending| pending.superseded_prepared_reset_coordinates.clone())
            .unwrap_or_default();
        if let Some(previous) = previous_intent.as_ref() {
            retain_prepared_reset_coordinate(
                &mut superseded_prepared_reset_coordinates,
                previous.prepared_reset_head_commit_id.as_ref(),
                previous.prepared_reset_checkpoint_commit_id.as_ref(),
            );
        }
        let prepared_uploads = super::upload_proof::load_copy_targets(
            read,
            preconditions,
            branch_id,
            &head_commit_id,
            &checkpoint_commit_id,
        )
        .await?;
        superseded_prepared_reset_coordinates.extend(prepared_uploads);
        if superseded_prepared_reset_coordinates.len() > MAX_SUPERSEDED_RESET_COORDINATES {
            return Err(LixError::new(
                LixError::CODE_TRANSACTION_CONFLICT,
                "restore must wait for outstanding upload acknowledgments",
            ));
        }
        let intent = PendingSyncReset {
            expected_authority_head_commit_id: head_commit_id,
            expected_authority_checkpoint_commit_id: checkpoint_commit_id,
            restore_target_commit_id: restore_target,
            authority_known_ancestor_commit_id,
            prepared_reset_head_commit_id: None,
            prepared_reset_checkpoint_commit_id: None,
            superseded_prepared_reset_head_commit_ids,
            superseded_prepared_reset_coordinates,
        };
        if state.pending_resets.get(branch_id) != Some(&intent) {
            state.pending_resets.insert(branch_id.clone(), intent);
            changed = true;
        }
    }
    if changed {
        stage_replica_state(writes, preconditions, &state, previous)?;
    }
    Ok(())
}

async fn find_restore_authority_boundary(
    read: &(impl StorageAdapterRead + ?Sized),
    state: &SyncReplicaState,
    previous_intent: Option<&PendingSyncReset>,
    current_authority_head: &str,
    current_authority_checkpoint: &str,
    target: CommitId,
) -> Result<Option<CommitId>, LixError> {
    let mut authority_seen = BTreeSet::new();
    let mut primary_authority_pending = VecDeque::new();
    let mut fallback_authority_pending = VecDeque::new();
    {
        let mut enqueue_primary_authority = |commit_id: CommitId| {
            if authority_seen.insert(commit_id) {
                primary_authority_pending.push_back(commit_id);
            }
        };
        enqueue_primary_authority(CommitId::parse_lix(
            current_authority_head,
            "sync authoritative head",
        )?);
        enqueue_primary_authority(CommitId::parse_lix(
            current_authority_checkpoint,
            "sync authoritative checkpoint",
        )?);
        if let Some(previous_boundary) = previous_intent
            .and_then(|pending| pending.authority_known_ancestor_commit_id.as_deref())
        {
            enqueue_primary_authority(CommitId::parse_lix(
                previous_boundary,
                "pending sync restore authority-known ancestor",
            )?);
        }
    }
    {
        let mut enqueue_fallback_authority = |commit_id: CommitId| {
            if authority_seen.insert(commit_id) {
                fallback_authority_pending.push_back(commit_id);
            }
        };
        for coordinate in state.authoritative_branches.values() {
            if let AuthoritativeBranchCoordinate::Headed {
                head_commit_id,
                checkpoint_commit_id,
            } = coordinate
            {
                enqueue_fallback_authority(CommitId::parse_lix(
                    head_commit_id,
                    "sync authoritative head",
                )?);
                enqueue_fallback_authority(CommitId::parse_lix(
                    checkpoint_commit_id,
                    "sync authoritative checkpoint",
                )?);
            }
        }
        for commit_id in &state.authority_known_commit_ids {
            enqueue_fallback_authority(CommitId::parse_lix(
                commit_id,
                "sync authority-known commit",
            )?);
        }
    }

    if authority_seen.contains(&target) {
        return Ok(Some(target));
    }
    let mut target_seen = BTreeSet::from([target]);
    let mut target_pending = VecDeque::from([target]);
    while !target_pending.is_empty()
        || !primary_authority_pending.is_empty()
        || !fallback_authority_pending.is_empty()
    {
        let (authority_commit_id, primary) = primary_authority_pending
            .pop_front()
            .map(|commit_id| (Some(commit_id), true))
            .unwrap_or_else(|| (fallback_authority_pending.pop_front(), false));
        if let Some(commit_id) = authority_commit_id
            && let Some(record) = load_commit_record(read, commit_id).await?
        {
            for parent in record.parent_commit_ids {
                if target_seen.contains(&parent) {
                    return Ok(Some(parent));
                }
                if authority_seen.insert(parent) {
                    if primary {
                        primary_authority_pending.push_back(parent);
                    } else {
                        fallback_authority_pending.push_back(parent);
                    }
                }
            }
        }
        if let Some(commit_id) = target_pending.pop_front()
            && let Some(record) = load_commit_record(read, commit_id).await?
        {
            for parent in record.parent_commit_ids {
                if authority_seen.contains(&parent) {
                    return Ok(Some(parent));
                }
                if target_seen.insert(parent) {
                    target_pending.push_back(parent);
                }
            }
        }
    }
    Ok(None)
}

fn sequence_key() -> StorageKey {
    StorageKey(Bytes::from_static(SEQUENCE_KEY))
}

fn event_key(cursor: u64) -> StorageKey {
    StorageKey(Bytes::copy_from_slice(&cursor.to_be_bytes()))
}

async fn load_sequence(
    read: &(impl StorageAdapterRead + ?Sized),
) -> Result<(u64, Option<Bytes>), LixError> {
    let key = sequence_key();
    let values = exact_get_many(
        read,
        &[StorageGetManyRequest {
            space: SYNC_SEQUENCE_SPACE,
            keys: std::slice::from_ref(&key),
            opts: StorageGetOptions::default(),
        }],
    )
    .await?;
    let raw = values
        .values
        .into_iter()
        .next()
        .flatten()
        .map(|value| match value {
            StorageProjectedValue::FullValue(value) => Ok(value),
            StorageProjectedValue::KeyOnly => Err(LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "repository sync sequence read omitted its value",
            )),
        })
        .transpose()?;
    let cursor = match raw.as_ref() {
        None => 0,
        Some(raw) if raw.len() == 8 => u64::from_be_bytes(
            raw.as_ref()
                .try_into()
                .expect("repository sequence length was checked"),
        ),
        Some(_) => {
            return Err(LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "repository sync sequence is corrupt",
            ));
        }
    };
    Ok((cursor, raw))
}

struct ParsedMember {
    change_id: ChangeId,
    authored: bool,
    schema_key: String,
    file_id: Option<String>,
    row_pk: RowPk,
    deleted: bool,
    snapshot_json: Option<String>,
    metadata_json: Option<String>,
    snapshot: Option<Vec<u8>>,
    metadata: Option<lix_schema::Jsonb>,
    row_created_at: LixTimestamp,
    row_updated_at: LixTimestamp,
    change_created_at: LixTimestamp,
    change_account_id: String,
    origin_key: Option<String>,
}

struct ParsedSnapshotRow {
    branch_id: String,
    schema_key: String,
    file_id: Option<String>,
    row_pk: RowPk,
    change_id: ChangeId,
    commit_id: CommitId,
    created_at: LixTimestamp,
    updated_at: LixTimestamp,
    change_account_id: String,
    change_created_at: LixTimestamp,
    origin_key: Option<String>,
    snapshot_json: String,
    metadata_json: Option<String>,
    snapshot: Vec<u8>,
    metadata: Option<lix_schema::Jsonb>,
}

impl ParsedSnapshotRow {
    fn change_record(&self) -> ChangeRecord {
        ChangeRecord {
            format_version: 2,
            change_id: self.change_id,
            account_id: self.change_account_id.clone(),
            schema_key: self.schema_key.clone(),
            row_pk: self.row_pk.clone(),
            file_id: self.file_id.clone(),
            snapshot: Some(self.snapshot.clone()),
            metadata: self.metadata.clone(),
            created_at: self.change_created_at,
            origin_key: self.origin_key.clone(),
        }
    }

    fn as_root_delta(&self) -> TrackedStateDeltaRef<'_> {
        TrackedStateDeltaRef {
            schema_key: &self.schema_key,
            file_id: self.file_id.as_deref(),
            row_pk: &self.row_pk,
            change_id: self.change_id,
            commit_id: self.commit_id,
            deleted: false,
            created_at: self.created_at,
            updated_at: self.updated_at,
        }
    }
}

fn sync_live_value_root_from_snapshot_rows<'a>(
    rows: impl IntoIterator<Item = &'a ParsedSnapshotRow>,
) -> Result<SyncLiveValueRootId, LixError> {
    sync_live_value_root(rows.into_iter().map(|row| SyncLiveValueRowRef {
        schema_key: &row.schema_key,
        file_id: row.file_id.as_deref(),
        row_pk: &row.row_pk,
        change_id: row.change_id,
        commit_id: row.commit_id,
        created_at: row.created_at,
        updated_at: row.updated_at,
        snapshot_json: &row.snapshot_json,
        metadata_json: row.metadata_json.as_deref(),
        change_account_id: &row.change_account_id,
        change_created_at: row.change_created_at,
        origin_key: row.origin_key.as_deref(),
    }))
}

fn snapshot_rows_hot_snapshot<'a>(
    branch_id: &str,
    rows: impl IntoIterator<Item = &'a ParsedSnapshotRow>,
) -> Result<HotTrackedSnapshot, LixError> {
    HotTrackedSnapshot::from_materialized_rows(
        rows.into_iter()
            .filter(|row| {
                branch_id == crate::GLOBAL_BRANCH_ID
                    || row.schema_key != crate::checkpoint::CHECKPOINT_SCHEMA_KEY
            })
            .map(|row| {
                Ok(MaterializedTrackedStateRow {
                    row_pk: row.row_pk.clone(),
                    schema_key: row.schema_key.clone(),
                    file_id: row.file_id.clone(),
                    snapshot_content: Some(row.snapshot_json.clone().into()),
                    decoded_snapshot: Some(std::sync::Arc::new(
                        crate::plugin::runtime::WasmTypedRow::decode_durable_payload(
                            std::sync::Arc::from(row.snapshot.clone()),
                            &row.schema_key,
                            &row.row_pk,
                        )?,
                    )),
                    metadata: row.metadata_json.clone().map(Into::into),
                    deleted: false,
                    created_at: row.created_at.to_string(),
                    updated_at: row.updated_at.to_string(),
                    change_id: row.change_id,
                    commit_id: row.commit_id,
                })
            })
            .collect::<Result<Vec<_>, LixError>>()?,
    )
}

fn snapshot_rows_with_inherited_catalog<'a>(
    branch_id: &str,
    all_rows: &'a [ParsedSnapshotRow],
    local_rows: &[&'a ParsedSnapshotRow],
) -> BTreeMap<(String, Option<String>, RowPk), &'a ParsedSnapshotRow> {
    let mut rows = BTreeMap::new();
    if branch_id != crate::GLOBAL_BRANCH_ID {
        for row in all_rows.iter().filter(|row| {
            row.branch_id == crate::GLOBAL_BRANCH_ID && row.schema_key == "lix_registered_schema"
        }) {
            rows.insert(
                (
                    row.schema_key.clone(),
                    row.file_id.clone(),
                    row.row_pk.clone(),
                ),
                row,
            );
        }
    }
    for &row in local_rows {
        rows.insert(
            (
                row.schema_key.clone(),
                row.file_id.clone(),
                row.row_pk.clone(),
            ),
            row,
        );
    }
    rows
}

impl ParsedMember {
    fn change_record(&self) -> ChangeRecord {
        ChangeRecord {
            format_version: 2,
            change_id: self.change_id,
            account_id: self.change_account_id.clone(),
            schema_key: self.schema_key.clone(),
            row_pk: self.row_pk.clone(),
            file_id: self.file_id.clone(),
            snapshot: self.snapshot.clone(),
            metadata: self.metadata.clone(),
            created_at: self.change_created_at,
            origin_key: self.origin_key.clone(),
        }
    }

    fn as_root_delta(&self, commit_id: CommitId) -> TrackedStateDeltaRef<'_> {
        TrackedStateDeltaRef {
            schema_key: &self.schema_key,
            file_id: self.file_id.as_deref(),
            row_pk: &self.row_pk,
            change_id: self.change_id,
            commit_id,
            deleted: self.deleted,
            created_at: self.row_created_at,
            updated_at: self.row_updated_at,
        }
    }

    fn as_commit_delta(&self, commit_id: CommitId) -> TrackedStateCommitDeltaRef<'_> {
        TrackedStateCommitDeltaRef {
            delta: TrackedStateDeltaRef {
                schema_key: &self.schema_key,
                file_id: self.file_id.as_deref(),
                row_pk: &self.row_pk,
                change_id: self.change_id,
                commit_id,
                deleted: self.deleted,
                created_at: self.row_created_at,
                updated_at: self.row_updated_at,
            },
            snapshot: self.snapshot.as_deref(),
            metadata: self.metadata.as_ref(),
            origin_key: self.origin_key.as_deref(),
            base_coordinate: None,
            authored: self.authored,
        }
    }

    fn as_current_delta(&self, commit_id: CommitId) -> CurrentStateDeltaRef<'_> {
        CurrentStateDeltaRef {
            schema_key: &self.schema_key,
            file_id: self.file_id.as_deref(),
            row_pk: &self.row_pk,
            change_id: Some(self.change_id),
            commit_id: Some(commit_id),
            untracked: false,
            deleted: self.deleted,
            created_at: self.row_created_at,
            updated_at: self.row_updated_at,
            snapshot: self.snapshot.as_deref(),
            metadata: self.metadata.as_ref(),
            columnar_base_coordinate: None,
        }
    }
}

fn selected_payload_matches_authored(selected: &ParsedMember, authored: &ParsedMember) -> bool {
    authored.authored
        && selected.change_id == authored.change_id
        && selected.schema_key == authored.schema_key
        && selected.file_id == authored.file_id
        && selected.row_pk == authored.row_pk
        && selected.deleted == authored.deleted
        && selected.snapshot_json == authored.snapshot_json
        && selected.snapshot == authored.snapshot
        && selected.metadata_json == authored.metadata_json
        && selected.change_account_id == authored.change_account_id
        && selected.change_created_at == authored.change_created_at
        && selected.origin_key == authored.origin_key
}

struct ParsedCommit {
    wire: SyncCommit,
    commit_id: CommitId,
    parent_commit_ids: Vec<CommitId>,
    base_commit_id: Option<CommitId>,
    account_id: String,
    created_at: LixTimestamp,
    selected_source_commit_id: Option<CommitId>,
    state_alias: Option<(CommitId, TrackedStateRootId)>,
    members: Vec<ParsedMember>,
}

#[derive(Clone)]
struct ParsedSyncHeader {
    is_checkpoint: bool,
    commit_id: CommitId,
    parent_commit_ids: Vec<CommitId>,
    base_commit_id: Option<CommitId>,
    account_id: String,
    created_at: LixTimestamp,
    global_scope: bool,
    generation: u64,
    first_parent_jump_commit_id: CommitId,
    first_parent_jump_span: u64,
}

impl ParsedSyncHeader {
    fn parse(header: &SyncCommitHeader) -> Result<Self, LixError> {
        let commit_id = CommitId::parse_lix(&header.commit_id, "sync commit header")?;
        if header.account_id.is_empty() {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync commit header accountId must not be empty",
            ));
        }
        let mut unique_parents = BTreeSet::new();
        let parent_commit_ids = header
            .parent_commit_ids
            .iter()
            .map(|parent| CommitId::parse_lix(parent, "sync parent header"))
            .map(|parent| {
                let parent = parent?;
                if parent == commit_id {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync commit header cannot be its own parent",
                    ));
                }
                if !unique_parents.insert(parent) {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync commit header parent ids must be unique",
                    ));
                }
                Ok(parent)
            })
            .collect::<Result<Vec<_>, LixError>>()?;
        let (first_parent_jump_commit_id, first_parent_jump_span) = match (
            &header.first_parent_jump_commit_id,
            header.first_parent_jump_span,
        ) {
            (None, None) if parent_commit_ids.len() != 1 => (commit_id, 0),
            (Some(jump), Some(span)) if parent_commit_ids.len() == 1 && span > 0 => (
                CommitId::parse_lix(jump, "sync first-parent jump header")?,
                span,
            ),
            _ => {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync header jump id/span must be paired for linear commits and absent for root/merge commits",
                ));
            }
        };
        let base_commit_id = header
            .base_commit_id
            .as_deref()
            .map(|base| CommitId::parse_lix(base, "sync base commit header"))
            .transpose()?;
        if base_commit_id == Some(commit_id) {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync commit header cannot use itself as its base",
            ));
        }
        if header.global_scope && base_commit_id.is_some() {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "global sync commit header must not have a base",
            ));
        }
        if !header.global_scope && base_commit_id.is_none() {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "local sync commit header must have a base",
            ));
        }
        Ok(Self {
            is_checkpoint: header.is_checkpoint,
            commit_id,
            parent_commit_ids,
            base_commit_id,
            account_id: header.account_id.clone(),
            created_at: parse_sync_timestamp("sync header createdAt", &header.created_at)?,
            global_scope: header.global_scope,
            generation: header.generation,
            first_parent_jump_commit_id,
            first_parent_jump_span,
        })
    }

    fn matches_record(&self, existing: &CommitRecord) -> bool {
        // Headers do not transmit the locally derived touched-scope digest.
        // Preserve that stronger local metadata while checking every field
        // actually carried by the immutable wire header.
        let mut expected = self.record();
        expected.touched_scope_digest = existing.touched_scope_digest.clone();
        *existing == expected
    }

    fn record(&self) -> CommitRecord {
        CommitRecord {
            is_checkpoint: self.is_checkpoint,
            format_version: COMMIT_RECORD_FORMAT_VERSION,
            commit_id: self.commit_id,
            generation: self.generation,
            parent_commit_ids: self.parent_commit_ids.clone(),
            base_commit_id: self.base_commit_id,
            first_parent_jump_commit_id: self.first_parent_jump_commit_id,
            first_parent_jump_span: self.first_parent_jump_span,
            account_id: self.account_id.clone(),
            created_at: self.created_at,
            touched_scope_digest: CommitTouchedScopeDigest::opaque(),
        }
    }
}

fn validate_sync_header_set(
    headers: &BTreeMap<CommitId, ParsedSyncHeader>,
    context: &str,
    sparse_inventory_ids: &BTreeSet<CommitId>,
) -> Result<(), LixError> {
    if sparse_inventory_ids
        .iter()
        .any(|id| !headers.get(id).is_some_and(|h| h.is_checkpoint))
    {
        return Err(LixError::new(
            LixError::CODE_INVALID_PARAM,
            "sparse inventory must reference checkpoint headers",
        ));
    }
    // Kahn traversal visits each header and known parent edge once, avoiding
    // repeated scans of the entire retained inventory for the next ready node.
    let mut unresolved = BTreeMap::new();
    let mut children = BTreeMap::<CommitId, Vec<CommitId>>::new();
    let mut ready = Vec::new();
    for (id, header) in headers {
        let mut count = 0usize;
        for parent in &header.parent_commit_ids {
            if headers.contains_key(parent) {
                count += 1;
                children.entry(*parent).or_default().push(*id);
            }
        }
        unresolved.insert(*id, count);
        if count == 0 {
            ready.push(*id);
        }
    }
    let mut resolved = 0usize;
    while let Some(id) = ready.pop() {
        resolved += 1;
        for child in children.get(&id).into_iter().flatten() {
            let count = unresolved.get_mut(child).expect("known child");
            *count -= 1;
            if *count == 0 {
                ready.push(*child);
            }
        }
    }
    if resolved != headers.len() {
        return Err(LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("{context} commit header graph contains a cycle"),
        ));
    }

    for header in headers.values() {
        if let Some(base_commit_id) = header.base_commit_id
            && let Some(base) = headers.get(&base_commit_id)
            && !base.global_scope
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "{context} header '{}' uses non-global base '{}'",
                    header.commit_id, base_commit_id
                ),
            ));
        }
        let known_parent_generations = header
            .parent_commit_ids
            .iter()
            .filter_map(|parent| headers.get(parent).map(|parent| parent.generation))
            .collect::<Vec<_>>();
        if header.parent_commit_ids.is_empty() && header.generation != 0 {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "{context} root header '{}' has invalid generation",
                    header.commit_id
                ),
            ));
        }
        if !header.parent_commit_ids.is_empty() && header.generation == 0 {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "{context} non-root header '{}' has invalid generation",
                    header.commit_id
                ),
            ));
        }
        if let Some(max_known_parent) = known_parent_generations.iter().copied().max() {
            let exact = max_known_parent
                .checked_add(1)
                .ok_or_else(|| LixError::unknown("sync history generation overflow"))?;
            let all_parents_known =
                known_parent_generations.len() == header.parent_commit_ids.len();
            if (all_parents_known && header.generation != exact)
                || (!all_parents_known && header.generation <= max_known_parent)
            {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "{context} header '{}' has invalid generation",
                        header.commit_id
                    ),
                ));
            }
        }
        if header.first_parent_jump_span > 0 {
            let expected_generation = header.generation.checked_sub(header.first_parent_jump_span);
            if header.first_parent_jump_commit_id == header.commit_id
                || expected_generation.is_none()
            {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "{context} header '{}' has an invalid jump span",
                        header.commit_id
                    ),
                ));
            }
            match headers.get(&header.first_parent_jump_commit_id) {
                Some(jump) if expected_generation != Some(jump.generation) => {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!(
                            "{context} header '{}' has an invalid jump span",
                            header.commit_id
                        ),
                    ));
                }
                None if !sparse_inventory_ids.contains(&header.commit_id) => {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!(
                            "{context} header '{}' is missing jump boundary '{}'",
                            header.commit_id, header.first_parent_jump_commit_id
                        ),
                    ));
                }
                // Only inventory-only checkpoint headers may omit topology.
                // Graph readers demand the missing history before following it;
                // ordinary history imports must still supply the full closure.
                _ => {}
            }
        }
    }
    Ok(())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SyncImportPurpose {
    AuthorityPush,
    ReplicaDelta,
    History,
}

impl ParsedCommit {
    fn parse(wire: &SyncCommit) -> Result<Self, LixError> {
        wire.validate()?;
        let commit_id = CommitId::parse_lix(&wire.commit_id, "sync commit id")?;
        let parent_commit_ids = wire
            .parent_commit_ids
            .iter()
            .map(|parent| CommitId::parse_lix(parent, "sync parent commit id"))
            .collect::<Result<Vec<_>, _>>()?;
        let created_at = parse_sync_timestamp("sync commit createdAt", &wire.created_at)?;
        let base_commit_id = wire
            .base_commit_id
            .as_deref()
            .map(|base| CommitId::parse_lix(base, "sync base commit id"))
            .transpose()?;
        if base_commit_id == Some(commit_id) {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync commit cannot use itself as its base",
            ));
        }
        let selected_source_commit_id = wire
            .selected_source_commit_id
            .as_deref()
            .map(|source| CommitId::parse_lix(source, "sync selected source commit id"))
            .transpose()?;
        let state_alias = wire
            .state_alias
            .as_ref()
            .map(|alias| {
                let source = CommitId::parse_lix(
                    &alias.source_commit_id,
                    "sync complete-state source commit id",
                )?;
                let root = blake3::Hash::from_hex(&alias.state_root_id).map_err(|_| {
                    LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync complete-state alias has an invalid stateRootId",
                    )
                })?;
                Ok::<_, LixError>((source, TrackedStateRootId::new(*root.as_bytes())))
            })
            .transpose()?;
        let members = wire
            .members
            .iter()
            .map(parse_sync_member)
            .collect::<Result<Vec<_>, LixError>>()?;
        Ok(Self {
            wire: wire.clone(),
            commit_id,
            parent_commit_ids,
            base_commit_id,
            account_id: wire.account_id.clone(),
            created_at,
            selected_source_commit_id,
            state_alias,
            members,
        })
    }

    fn dependencies(&self) -> impl Iterator<Item = CommitId> + '_ {
        self.parent_commit_ids
            .iter()
            .copied()
            .chain(self.base_commit_id)
            .chain(self.state_alias.iter().map(|(source, _)| *source))
    }
}

fn parse_sync_member(member: &SyncCommitMember) -> Result<ParsedMember, LixError> {
    let snapshot_json = member
        .snapshot
        .as_ref()
        .map(serde_json::to_string)
        .transpose()
        .map_err(|error| LixError::unknown(format!("encode sync member snapshot: {error}")))?;
    let metadata_json = member
        .metadata
        .as_ref()
        .map(serde_json::to_string)
        .transpose()
        .map_err(|error| LixError::unknown(format!("encode sync member metadata: {error}")))?;
    let row_pk = RowPk::from_typed_json_array_value(&member.row_pk).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("sync member rowPk is invalid: {error}"),
        )
    })?;
    let snapshot = member
        .snapshot
        .as_ref()
        .map(|value| {
            super::commit::decode_sync_row_payload(
                &member.schema_key,
                &row_pk,
                value,
                member.snapshot_payload.as_deref(),
            )
        })
        .transpose()?;
    let metadata = member.metadata.clone().map(lix_schema::Jsonb::from_value);
    Ok(ParsedMember {
        change_id: ChangeId::parse_lix(&member.change_id, "sync member change id")?,
        authored: member.authored,
        schema_key: member.schema_key.clone(),
        file_id: member.file_id.clone(),
        row_pk,
        deleted: member.deleted,
        snapshot,
        metadata,
        snapshot_json,
        metadata_json,
        row_created_at: parse_sync_timestamp("sync member rowCreatedAt", &member.row_created_at)?,
        row_updated_at: parse_sync_timestamp("sync member rowUpdatedAt", &member.row_updated_at)?,
        change_created_at: parse_sync_timestamp(
            "sync member changeCreatedAt",
            &member.change_created_at,
        )?,
        change_account_id: member.change_account_id.clone(),
        origin_key: member.origin_key.clone(),
    })
}

fn parse_sync_timestamp(context: &str, value: &str) -> Result<LixTimestamp, LixError> {
    LixTimestamp::parse(value).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("{context} is invalid: {error}"),
        )
    })
}

async fn materialize_sync_live_value_rows_with_imports(
    read: &(impl StorageAdapterRead + ?Sized),
    parsed: &BTreeMap<CommitId, ParsedCommit>,
    target: CommitId,
) -> Result<BTreeMap<Vec<u8>, SyncLiveValueRow>, LixError> {
    let mut pending = Vec::new();
    let mut cursor = target;
    let mut rows = loop {
        let Some(commit) = parsed.get(&cursor) else {
            break load_sync_live_value_rows_at_commit(read, cursor).await?;
        };
        pending.push(cursor);
        if let Some((source, _)) = commit.state_alias {
            cursor = source;
        } else if let Some(parent) = commit.parent_commit_ids.first() {
            cursor = *parent;
        } else {
            break BTreeMap::new();
        }
    };

    for commit_id in pending.into_iter().rev() {
        let commit = &parsed[&commit_id];
        for member in &commit.members {
            let key = encode_key_ref(TrackedStateKeyRef {
                schema_key: &member.schema_key,
                file_id: member.file_id.as_deref(),
                row_pk: &member.row_pk,
            });
            if member.deleted {
                rows.remove(&key);
                continue;
            }
            let snapshot_json = member.snapshot_json.clone().ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "live sync member has no snapshot while certifying imported state",
                )
            })?;
            // Commit deltas carry the mutation timestamp as rowCreatedAt even
            // for updates. Materialized lifecycle semantics preserve the
            // original creation timestamp while the coordinate remains live.
            let created_at = rows
                .get(&key)
                .map_or(member.row_created_at, |row| row.created_at);
            rows.insert(
                key,
                SyncLiveValueRow {
                    schema_key: member.schema_key.clone(),
                    file_id: member.file_id.clone(),
                    row_pk: member.row_pk.clone(),
                    change_id: member.change_id,
                    commit_id,
                    created_at,
                    updated_at: member.row_updated_at,
                    snapshot_json,
                    metadata_json: member.metadata_json.clone(),
                    change_account_id: member.change_account_id.clone(),
                    change_created_at: member.change_created_at,
                    origin_key: member.origin_key.clone(),
                },
            );
        }
    }
    Ok(rows)
}

async fn certified_sync_live_value_root_with_imports(
    read: &(impl StorageAdapterRead + ?Sized),
    parsed: &BTreeMap<CommitId, ParsedCommit>,
    target: CommitId,
) -> Result<SyncLiveValueRootId, LixError> {
    let rows = materialize_sync_live_value_rows_with_imports(read, parsed, target).await?;
    sync_live_value_root(rows.values().map(SyncLiveValueRow::as_ref))
}

async fn load_sync_live_value_rows_at_commit(
    read: &(impl StorageAdapterRead + ?Sized),
    commit_id: CommitId,
) -> Result<BTreeMap<Vec<u8>, SyncLiveValueRow>, LixError> {
    let mut tracked = TrackedStateContext::new().reader(read);
    let tracked_rows = tracked
        .scan_batch_at_commit(&commit_id.to_string(), &TrackedStateScanRequest::default())
        .await?;
    let mut rows = BTreeMap::new();
    for row in tracked_rows.iter() {
        let change = load_existing_sync_change(read, row.change_id())
            .await?
            .ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!(
                        "sync live-value row change '{}' is missing",
                        row.change_id()
                    ),
                )
            })?;
        let key = encode_key_ref(TrackedStateKeyRef {
            schema_key: row.schema_key(),
            file_id: row.file_id(),
            row_pk: row.row_pk(),
        });
        rows.insert(
            key,
            SyncLiveValueRow {
                schema_key: row.schema_key().to_owned(),
                file_id: row.file_id().map(str::to_owned),
                row_pk: row.row_pk().clone(),
                change_id: row.change_id(),
                commit_id: row.commit_id(),
                created_at: row.created_at(),
                updated_at: row.updated_at(),
                snapshot_json: row
                    .snapshot_content()
                    .expect("a live tracked row has snapshot content")
                    .to_string(),
                metadata_json: row.metadata().map(ToString::to_string),
                change_account_id: change.account_id,
                change_created_at: change.created_at,
                origin_key: change.origin_key,
            },
        );
    }
    Ok(rows)
}

fn encode_sync_snapshot_row(
    branch_id: &str,
    row: crate::tracked_state::MaterializedTrackedStateRowRef<'_>,
    change: ChangeRecord,
) -> Result<SyncSnapshotRow, LixError> {
    Ok(SyncSnapshotRow {
        branch_id: branch_id.to_owned(),
        // The by-ID record supplies provenance, not the row payload:
        // eager plugin rows may share a source change ID while having
        // distinct identities and typed snapshots.
        snapshot_payload: Some(super::commit::encode_sync_row_payload(
            row.decoded_snapshot().ok_or_else(|| {
                LixError::unknown("live sync row lacks a materialized typed snapshot")
            })?,
        )?),
        schema_key: row.schema_key().to_owned(),
        file_id: row.file_id().map(str::to_owned),
        row_pk: row.row_pk().as_typed_json_array_value()?,
        snapshot: row
            .snapshot_content()
            .map(|value| serde_json::from_str(value.as_str()))
            .transpose()
            .map_err(|error| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!("decode sync snapshot row: {error}"),
                )
            })?,
        metadata: row
            .metadata()
            .map(|value| serde_json::from_str(value.as_str()))
            .transpose()
            .map_err(|error| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!("decode sync snapshot metadata: {error}"),
                )
            })?,
        change_id: row.change_id().to_string(),
        commit_id: row.commit_id().to_string(),
        created_at: row.created_at().to_string(),
        updated_at: row.updated_at().to_string(),
        change_account_id: change.account_id,
        change_created_at: change.created_at.to_string(),
        origin_key: change.origin_key,
    })
}

fn parse_snapshot_row(row: &SyncSnapshotRow) -> Result<ParsedSnapshotRow, LixError> {
    let snapshot = row
        .snapshot
        .as_ref()
        .map(serde_json::to_string)
        .transpose()
        .map_err(|error| LixError::unknown(format!("encode sync snapshot row: {error}")))?
        .ok_or_else(|| {
            LixError::new(
                LixError::CODE_INVALID_PARAM,
                "live sync snapshot row has no snapshot",
            )
        })?;
    let metadata = row
        .metadata
        .as_ref()
        .map(serde_json::to_string)
        .transpose()
        .map_err(|error| LixError::unknown(format!("encode sync snapshot metadata: {error}")))?;
    let row_pk = RowPk::from_typed_json_array_value(&row.row_pk).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("sync snapshot rowPk is invalid: {error}"),
        )
    })?;
    let snapshot_value = row
        .snapshot
        .as_ref()
        .expect("live sync snapshot was checked above");
    let typed_snapshot = super::commit::decode_sync_row_payload(
        &row.schema_key,
        &row_pk,
        snapshot_value,
        row.snapshot_payload.as_deref(),
    )?;
    Ok(ParsedSnapshotRow {
        branch_id: row.branch_id.clone(),
        schema_key: row.schema_key.clone(),
        file_id: row.file_id.clone(),
        row_pk,
        change_id: ChangeId::parse_lix(&row.change_id, "sync snapshot change id")?,
        commit_id: CommitId::parse_lix(&row.commit_id, "sync snapshot row commit id")?,
        created_at: parse_sync_timestamp("sync snapshot createdAt", &row.created_at)?,
        updated_at: parse_sync_timestamp("sync snapshot updatedAt", &row.updated_at)?,
        change_account_id: row.change_account_id.clone(),
        change_created_at: parse_sync_timestamp(
            "sync snapshot changeCreatedAt",
            &row.change_created_at,
        )?,
        origin_key: row.origin_key.clone(),
        snapshot_json: snapshot.clone(),
        metadata_json: metadata.clone(),
        snapshot: typed_snapshot,
        metadata: row.metadata.clone().map(lix_schema::Jsonb::from_value),
    })
}

fn encode_sync_typed_snapshot(
    schema_key: &str,
    row_pk: &RowPk,
    snapshot: &serde_json::Value,
) -> Result<Vec<u8>, LixError> {
    crate::plugin::runtime::WasmTypedRow::from_builtin_json(schema_key, row_pk, snapshot)
        .map_err(|error| {
            LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "sync row for schema '{schema_key}' has different content than its declared Schema v1 identity: {}",
                    error.message
                ),
            )
        })?
        .durable_payload()
        .map(|payload| payload.to_vec())
        .map_err(|error| {
            LixError::new(
                LixError::CODE_SCHEMA_VALIDATION,
                format!("sync row for schema '{schema_key}' is not durably encodable: {error:?}"),
            )
        })
}

async fn load_commit_record(
    read: &(impl StorageAdapterRead + ?Sized),
    commit_id: CommitId,
) -> Result<Option<CommitRecord>, LixError> {
    let ids = [commit_id];
    Ok(ChangelogContext::new()
        .reader(read)
        .load_commits(CommitLoadRequest { commit_ids: &ids })
        .await?
        .into_iter()
        .next()
        .and_then(|(_, record)| record))
}

async fn commit_reaches_ancestor(
    read: &(impl StorageAdapterRead + ?Sized),
    descendant: CommitId,
    ancestor: CommitId,
) -> Result<bool, LixError> {
    let mut pending = vec![descendant];
    let mut seen = BTreeSet::new();
    while let Some(commit_id) = pending.pop() {
        if commit_id == ancestor {
            return Ok(true);
        }
        if !seen.insert(commit_id) {
            continue;
        }
        let Some(record) = load_commit_record(read, commit_id).await? else {
            // Snapshot sync deliberately omits cold history bodies. Equality
            // with the requested ancestor is checked before this load, so an
            // absent older body is an unknown ancestry boundary, not local
            // corruption. Another merge parent can still prove reachability,
            // so keep walking every locally-known path before classifying the
            // relation as unknown/non-reachable.
            continue;
        };
        pending.extend(record.parent_commit_ids);
    }
    Ok(false)
}

/// Search only unacknowledged branch work. A compact checkpoint's physical
/// source is an outbox dependency even though it is not a canonical parent.
async fn pending_commit_reaches(
    read: &(impl StorageAdapterRead + ?Sized),
    descendant: CommitId,
    target: CommitId,
    confirmed: &BTreeSet<CommitId>,
    branch_id: &str,
) -> Result<bool, LixError> {
    let mut pending = vec![descendant];
    let mut seen = BTreeSet::new();
    while let Some(id) = pending.pop() {
        if id == target {
            return Ok(true);
        }
        if confirmed.contains(&id) || !seen.insert(id) {
            continue;
        }
        let Some(record) = load_commit_record(read, id).await? else {
            continue;
        };
        pending.extend(record.parent_commit_ids);
        if let Some((source_branch, source)) =
            super::commit::load_sync_checkpoint_source(read, id).await?
            && source_branch == branch_id
        {
            pending.push(source);
        }
        if let Some(alias) = load_sync_commit_state_alias(read, id).await? {
            pending.push(CommitId::parse_lix(
                &alias.source_commit_id,
                "pending checkpoint source",
            )?);
        }
    }
    Ok(false)
}

/// Proves ancestry through incoming immutable headers and existing local history.
/// Missing cold history is not proof; traversal must actually reach the local head.
async fn snapshot_head_contains_local_head(
    read: &(impl StorageAdapterRead + ?Sized),
    incoming_head: CommitId,
    local_head: CommitId,
    incoming_headers: &BTreeMap<CommitId, ParsedSyncHeader>,
) -> Result<bool, LixError> {
    let mut pending = vec![incoming_head];
    let mut seen = BTreeSet::new();
    while let Some(commit_id) = pending.pop() {
        if commit_id == local_head {
            return Ok(true);
        }
        if !seen.insert(commit_id) {
            continue;
        }
        if let Some(header) = incoming_headers.get(&commit_id) {
            pending.extend(header.parent_commit_ids.iter().copied());
        } else if let Some(record) = load_commit_record(read, commit_id).await? {
            pending.extend(record.parent_commit_ids);
        }
    }
    Ok(false)
}

fn sync_ref_change_id(branch_id: &str, head_commit_id: Option<CommitId>) -> ChangeId {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"lix.sync.repository_ref_change.v1");
    hasher.update(&(branch_id.len() as u64).to_be_bytes());
    hasher.update(branch_id.as_bytes());
    match head_commit_id {
        Some(commit_id) => hasher.update(commit_id.as_uuid().as_bytes()),
        None => hasher.update(&[0; 16]),
    };
    let mut bytes = [0; 16];
    bytes.copy_from_slice(&hasher.finalize().as_bytes()[..16]);
    // Keep the derived standalone change outside the commit-address sentinel
    // and direct member address zero.
    if bytes[12..] == [0; 4] {
        bytes[15] = 1;
    }
    ChangeId::new(uuid::Uuid::from_bytes(bytes))
}

fn sync_ref_change_record(
    branch_id: &str,
    head: CommitId,
    account_id: &str,
    created_at: LixTimestamp,
) -> Result<ChangeRecord, LixError> {
    let snapshot = serde_json::json!({
        "id": branch_id,
        "commit_id": head.to_string(),
    });
    let row_pk = RowPk::uuid_from_canonical(branch_id).map_err(|error| {
        LixError::new(
            LixError::CODE_INVALID_PARAM,
            format!("sync branch id is not a canonical UUID: {error}"),
        )
    })?;
    let snapshot = encode_sync_typed_snapshot(BRANCH_REF_SCHEMA_KEY, &row_pk, &snapshot)?;
    Ok(ChangeRecord {
        format_version: 2,
        change_id: sync_ref_change_id(branch_id, Some(head)),
        account_id: account_id.to_owned(),
        schema_key: BRANCH_REF_SCHEMA_KEY.to_owned(),
        row_pk,
        file_id: None,
        snapshot: Some(snapshot),
        metadata: None,
        created_at,
        origin_key: None,
    })
}

async fn load_sync_hot_snapshot(
    read: &(impl StorageAdapterRead + ?Sized),
    branch_id: &str,
    commit_id: CommitId,
) -> Result<HotTrackedSnapshot, LixError> {
    let mut rows: Vec<MaterializedTrackedStateRow> = TrackedStateContext::new()
        .reader(read)
        .scan_batch_at_commit(
            &commit_id.to_string(),
            &TrackedStateScanRequest {
                filter: TrackedStateFilter {
                    include_tombstones: true,
                    ..TrackedStateFilter::default()
                },
                read_columns: TrackedStateReadColumns::default(),
                limit: None,
            },
        )
        .await?
        .into_rows()
        .into_iter()
        .filter(|row| {
            branch_id == crate::GLOBAL_BRANCH_ID
                || row.schema_key != crate::checkpoint::CHECKPOINT_SCHEMA_KEY
        })
        .collect();
    if branch_id != crate::GLOBAL_BRANCH_ID {
        let node = CommitGraphContext::new()
            .reader(read)
            .load_node(&commit_id)
            .await?
            .ok_or_else(|| LixError::commit_not_found(commit_id.to_string(), "sync", "hot head"))?;
        if let Some(base_commit_id) = node.base_commit_id {
            let inherited_catalog = TrackedStateContext::new()
                .reader(read)
                .scan_batch_at_commit(
                    &base_commit_id.to_string(),
                    &TrackedStateScanRequest {
                        filter: TrackedStateFilter {
                            schema_keys: vec!["lix_registered_schema".to_owned()],
                            include_tombstones: true,
                            ..TrackedStateFilter::default()
                        },
                        read_columns: TrackedStateReadColumns::default(),
                        limit: None,
                    },
                )
                .await?
                .into_rows();
            for inherited in inherited_catalog {
                if !rows.iter().any(|local| {
                    local.schema_key == inherited.schema_key
                        && local.file_id == inherited.file_id
                        && local.row_pk == inherited.row_pk
                }) {
                    rows.push(inherited);
                }
            }
        }
    }
    HotTrackedSnapshot::from_materialized_rows(rows)
}

#[allow(clippy::too_many_arguments)]
async fn stage_sync_hot_delta(
    read: &(impl StorageAdapterRead + ?Sized),
    writes: &mut StorageWriteSet,
    branch_id: &str,
    previous_generation: CommitId,
    head: CommitId,
    deltas: &[CurrentStateDeltaRef<'_>],
    absence_guards: &BTreeSet<TrackedStateKey>,
    checkpoint: CommitId,
    coverage: &mut WorkingDiffIndexCoverage,
) -> Result<CommitId, LixError> {
    TrackedHeadContext::new()
        .writer(read, writes)
        .stage_current_state_with_working_diff(
            branch_id,
            Some(previous_generation),
            head,
            deltas,
            absence_guards,
            None,
            Some(checkpoint),
            coverage,
        )
        .await
}

/// Stages the only authority-side sync metadata needed by an ordinary Lix
/// transaction. Commit bodies remain in their native immutable stores.
pub(crate) async fn stage_repository_transaction_event<R>(
    read: &R,
    writes: &mut StorageWriteSet,
    preconditions: &mut Vec<StoragePrecondition>,
    commits: &[SyncCommit],
    published_controls: &BTreeMap<String, Option<BranchHeadControl>>,
) -> Result<Option<RepositoryEventRecord>, LixError>
where
    R: StorageAdapterRead + ?Sized,
{
    let mut commit_ids = commits
        .iter()
        .map(|commit| commit.commit_id.clone())
        .collect::<Vec<_>>();
    let branch_ids = published_controls.keys().cloned().collect::<Vec<_>>();
    let observed = BranchHeadControlContext::new()
        .reader(read)
        .load_many(&branch_ids)
        .await?;
    let mut ref_updates = branch_ids
        .into_iter()
        .zip(observed)
        .filter_map(|(branch_id, before)| {
            let after = published_controls[&branch_id];
            let checkpoint_commit_id = after
                .map(|control| {
                    control.working_diff_checkpoint_commit_id.ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INTERNAL_ERROR,
                            format!("published sync branch '{branch_id}' has no checkpoint cursor"),
                        )
                    })
                })
                .transpose();
            let checkpoint_commit_id = match checkpoint_commit_id {
                Ok(checkpoint_commit_id) => checkpoint_commit_id,
                Err(error) => return Some(Err(error)),
            };
            let before_coordinate = before.map(|control| {
                (
                    control.head_commit_id,
                    control.working_diff_checkpoint_commit_id,
                )
            });
            let after_coordinate = after.map(|control| {
                (
                    control.head_commit_id,
                    control.working_diff_checkpoint_commit_id,
                )
            });
            if before_coordinate == after_coordinate {
                return None;
            }
            Some(Ok(SyncRefUpdate {
                branch_id,
                expected_head_commit_id: before.map(|control| control.head_commit_id.to_string()),
                expected_checkpoint_commit_id: before
                    .and_then(|control| control.working_diff_checkpoint_commit_id)
                    .map(|checkpoint| checkpoint.to_string()),
                head_commit_id: after.map(|control| control.head_commit_id.to_string()),
                checkpoint_commit_id: checkpoint_commit_id.map(|checkpoint| checkpoint.to_string()),
            }))
        })
        .collect::<Result<Vec<_>, LixError>>()?;
    if commit_ids.is_empty() && ref_updates.is_empty() {
        return Ok(None);
    }
    commit_ids.sort();
    commit_ids.dedup();
    ref_updates.sort_by(|left, right| left.branch_id.cmp(&right.branch_id));

    Ok(Some(
        stage_repository_event(read, writes, preconditions, commit_ids, ref_updates).await?,
    ))
}

/// Rejects an Authority transaction before its atomic storage commit when the
/// event it would publish cannot be fetched within the protocol response cap.
/// The borrowed projection is byte-for-byte the public JSON shape without
/// cloning large member payloads merely to measure it.
pub(crate) fn validate_repository_transaction_event_transfer(
    event: &RepositoryEventRecord,
    materialized_commits: &[SyncCommit],
) -> Result<(), LixError> {
    let commits_by_id = materialized_commits
        .iter()
        .map(|commit| (commit.commit_id.as_str(), commit))
        .collect::<BTreeMap<_, _>>();
    let commits = event
        .commit_ids
        .iter()
        .map(|commit_id| {
            commits_by_id.get(commit_id.as_str()).copied().ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!(
                        "authority sync event references unstaged commit '{commit_id}' during preflight"
                    ),
                )
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    if commits.len() != materialized_commits.len() {
        return Err(LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            "authority sync preflight materialized a commit outside its repository event",
        ));
    }
    let encoded_len = super::encoded_delta_event_len(event.cursor, &commits, &event.ref_updates)?;
    let transfer_limit = repository_transaction_event_transfer_limit();
    if encoded_len > transfer_limit {
        return Err(LixError::new(
            "LIX_ERROR_SYNC_ITEM_TOO_LARGE",
            format!(
                "authority transaction would publish a {} byte sync event, exceeding the {} byte transfer limit",
                encoded_len, transfer_limit,
            ),
        ));
    }
    Ok(())
}

fn repository_transaction_event_transfer_limit() -> usize {
    #[cfg(test)]
    if let Some(limit) = TEST_REPOSITORY_TRANSACTION_EVENT_TRANSFER_LIMIT.with(Cell::get) {
        return limit;
    }
    super::MAX_SYNC_PULL_RESPONSE_BYTES
}

#[cfg(test)]
thread_local! {
    static TEST_REPOSITORY_TRANSACTION_EVENT_TRANSFER_LIMIT: Cell<Option<usize>> = const { Cell::new(None) };
}

#[cfg(test)]
struct TestRepositoryTransactionEventTransferLimit(Option<usize>);

#[cfg(test)]
impl TestRepositoryTransactionEventTransferLimit {
    fn install(limit: usize) -> Self {
        let previous = TEST_REPOSITORY_TRANSACTION_EVENT_TRANSFER_LIMIT
            .with(|current| current.replace(Some(limit)));
        Self(previous)
    }
}

#[cfg(test)]
impl Drop for TestRepositoryTransactionEventTransferLimit {
    fn drop(&mut self) {
        TEST_REPOSITORY_TRANSACTION_EVENT_TRANSFER_LIMIT.with(|current| current.set(self.0));
    }
}

async fn stage_repository_event<R>(
    read: &R,
    writes: &mut StorageWriteSet,
    preconditions: &mut Vec<StoragePrecondition>,
    mut commit_ids: Vec<String>,
    mut ref_updates: Vec<SyncRefUpdate>,
) -> Result<RepositoryEventRecord, LixError>
where
    R: StorageAdapterRead + ?Sized,
{
    commit_ids.sort();
    ref_updates.sort_by(|left, right| left.branch_id.cmp(&right.branch_id));
    let (cursor, raw_sequence) = load_sequence(read).await?;
    let cursor = cursor
        .checked_add(1)
        .ok_or_else(|| LixError::unknown("repository sync cursor overflow"))?;
    let record = RepositoryEventRecord {
        cursor,
        commit_ids,
        ref_updates,
    };
    let encoded = serde_json::to_vec(&record).map_err(|error| {
        LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            format!("encode repository sync event: {error}"),
        )
    })?;
    writes.put(SYNC_REPOSITORY_EVENT_SPACE, event_key(cursor), encoded);
    preconditions.push(StoragePrecondition::KeyAbsent {
        space: SYNC_REPOSITORY_EVENT_SPACE,
        key: event_key(cursor),
    });
    let key = sequence_key();
    writes.put(
        SYNC_SEQUENCE_SPACE,
        key.clone(),
        cursor.to_be_bytes().to_vec(),
    );
    preconditions.push(match raw_sequence {
        Some(expected) => StoragePrecondition::KeyValueEquals {
            space: SYNC_SEQUENCE_SPACE,
            key,
            expected,
        },
        None => StoragePrecondition::KeyAbsent {
            space: SYNC_SEQUENCE_SPACE,
            key,
        },
    });
    Ok(record)
}

impl<StorageImpl> Lix<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    pub(crate) async fn load_sync_repository_cursor(
        &self,
        _remote_id: &str,
    ) -> Result<Option<u64>, LixError> {
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        Ok(load_replica_state(&read).await?.0.map(|state| state.cursor))
    }

    #[cfg(test)]
    pub(crate) async fn sync_repository_cursor_is_certified(
        &self,
        cursor: u64,
    ) -> Result<bool, LixError> {
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        Ok(load_replica_state(&read).await?.0.is_some_and(|state| {
            state.cursor == cursor && state.snapshot_certified_cursor == Some(cursor)
        }))
    }

    pub(crate) async fn validate_sync_repository_account(
        &self,
        _remote_id: &str,
        active_account_id: &str,
    ) -> Result<(), LixError> {
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let expected = load_sync_replica_account(&read).await?;
        if expected
            .as_deref()
            .is_some_and(|expected| expected != active_account_id)
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync authority active account changed for this replica",
            ));
        }
        Ok(())
    }

    /// Validate the confirmed receipt independently of pending local controls.
    /// Immutable commits and branch controls are the durable upload outbox.
    pub(crate) async fn validate_sync_hot_state_authoritative(&self) -> Result<(), LixError> {
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let Some(state) = load_replica_state(&read).await?.0 else {
            return Err(LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "sync replica is missing its authoritative receipt",
            ));
        };
        let headed_count = state
            .authoritative_branches
            .values()
            .filter(|coordinate| matches!(coordinate, AuthoritativeBranchCoordinate::Headed { .. }))
            .count();
        if state.certified_branch_roots.len() != headed_count {
            return Err(LixError::new(
                super::SYNC_PROTOCOL_MISMATCH_CODE,
                "persisted sync replica predates certified HOT receipts",
            ));
        }
        Ok(())
    }

    /// Verifies the installed replica receipt against one immutable authority
    /// snapshot. Complete-value roots were computed when each delta was
    /// installed, so an already-caught-up fence reads only O(branches)
    /// metadata and never rescans current rows.
    pub(crate) async fn validate_sync_publication_snapshot(
        &self,
        snapshot: &SyncRepositoryPullResponse,
    ) -> Result<(), LixError> {
        let SyncRepositoryPullResponse::Snapshot {
            cursor, branches, ..
        } = snapshot
        else {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync publication fence requires snapshot metadata",
            ));
        };
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let (state, previous) = load_replica_state(&read).await?;
        let Some(mut state) = state else {
            return Err(LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "sync publication fence lost its replica receipt",
            ));
        };
        if state.cursor != *cursor {
            return Err(LixError::new(
                LixError::CODE_TRANSACTION_CONFLICT,
                "sync publication fence cursor changed before certification",
            ));
        }
        let headed_branch_count = state
            .authoritative_branches
            .values()
            .filter(|coordinate| matches!(coordinate, AuthoritativeBranchCoordinate::Headed { .. }))
            .count();
        if branches.len() != headed_branch_count
            || branches.len() != state.certified_branch_roots.len()
        {
            return Err(LixError::new(
                super::SYNC_IMMUTABLE_OBJECT_MISMATCH_CODE,
                "sync publication fence branch set differs from its local certificate",
            ));
        }
        for branch in branches {
            let expected = AuthoritativeBranchCoordinate::from_wire(
                branch.head_commit_id.clone(),
                branch.checkpoint_commit_id.clone(),
                "sync publication snapshot branch",
            )?;
            if state.authoritative_branches.get(&branch.branch_id) != Some(&expected) {
                return Err(LixError::new(
                    super::SYNC_IMMUTABLE_OBJECT_MISMATCH_CODE,
                    format!(
                        "sync publication fence branch '{}' coordinate is not installed",
                        branch.branch_id
                    ),
                ));
            }
            let expected_roots = CertifiedBranchRoots {
                head_state_root_id: branch.hot_state_root_id.clone(),
                checkpoint_state_root_id: branch.checkpoint_state_root_id.clone(),
            };
            if state.certified_branch_roots.get(&branch.branch_id) != Some(&expected_roots) {
                return Err(LixError::new(
                    super::SYNC_IMMUTABLE_OBJECT_MISMATCH_CODE,
                    format!(
                        "sync publication fence branch '{}' live-state roots diverged",
                        branch.branch_id
                    ),
                ));
            }
        }
        let previous = previous.expect("decoded sync replica state has source bytes");
        state.snapshot_certified_cursor = Some(*cursor);
        let mut writes = adapter.new_write_set();
        let mut preconditions = Vec::new();
        stage_replica_state(&mut writes, &mut preconditions, &state, Some(previous))?;
        drop(read);
        adapter
            .commit_certified_replica_write_set(
                super::certified_replica_write_capability(),
                writes,
                StorageWriteOptions {
                    preconditions,
                    await_durable: true,
                    ..StorageWriteOptions::default()
                },
            )
            .await?;
        Ok(())
    }

    #[cfg(test)]
    pub(crate) async fn build_sync_push(
        &self,
        remote_id: &str,
        max_items: usize,
    ) -> Result<Option<SyncPushRequest>, LixError> {
        self.build_sync_push_with_plan(remote_id, max_items, &mut None)
            .await
    }

    pub(crate) async fn build_sync_push_with_plan(
        &self,
        remote_id: &str,
        max_items: usize,
        cached: &mut Option<CachedSyncUploadPlan>,
    ) -> Result<Option<SyncPushRequest>, LixError> {
        let result = self
            .build_sync_push_with_plan_inner(remote_id, max_items, cached)
            .await;
        if result.is_err() {
            // An expired coherent read or unavailable body cannot certify this
            // plan. Rebuild from durable state on the next runtime attempt.
            *cached = None;
        }
        result
    }

    async fn build_sync_push_with_plan_inner(
        &self,
        _remote_id: &str,
        max_items: usize,
        cached: &mut Option<CachedSyncUploadPlan>,
    ) -> Result<Option<SyncPushRequest>, LixError> {
        if max_items == 0 || max_items > super::MAX_SYNC_REQUEST_ITEMS {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "sync push item limit must be between 1 and {}",
                    super::MAX_SYNC_REQUEST_ITEMS
                ),
            ));
        }
        let adapter = self.storage_adapter();
        let mut attempted_reconciliations = BTreeSet::new();
        let mut remaining_reconciliations = None;
        let mut rebuilt_missing_body = false;
        'planning: loop {
            let read = adapter.begin_read(StorageReadOptions::default()).await?;
            let Some(state) = load_replica_state(&read).await?.0 else {
                *cached = None;
                return Ok(None);
            };
            let generation = super::upload_plan::load_generation(&read).await?;
            if cached.as_ref().is_some_and(|cached| {
                cached.plan.is_complete()
                    || cached.plan.generation() != generation
                    || cached.authoritative_branches != state.authoritative_branches
            }) {
                *cached = None;
            }
            if cached.is_none() {
                let local_controls = BranchHeadControlContext::new()
                    .reader(&read)
                    .scan()
                    .await?
                    .into_iter()
                    .collect::<BTreeMap<_, _>>();
                let mut known = BTreeSet::new();
                for coordinate in state.authoritative_branches.values() {
                    if let AuthoritativeBranchCoordinate::Headed {
                        head_commit_id,
                        checkpoint_commit_id,
                    } = coordinate
                    {
                        known.insert(CommitId::parse_lix(
                            head_commit_id,
                            "sync authoritative head",
                        )?);
                        known.insert(CommitId::parse_lix(
                            checkpoint_commit_id,
                            "sync authoritative checkpoint",
                        )?);
                    }
                }
                let confirmed_boundaries = known.clone();
                for commit_id in &state.authority_known_commit_ids {
                    known.insert(CommitId::parse_lix(
                        commit_id,
                        "sync authority-known commit",
                    )?);
                }
                let mut commit_ids = BTreeSet::new();
                let mut dependencies = BTreeMap::<CommitId, BTreeSet<CommitId>>::new();
                let mut reset_known_commit_ids = BTreeSet::new();
                let mut ref_updates = Vec::new();
                let branch_ids = local_controls
                    .keys()
                    .chain(state.authoritative_branches.keys())
                    .cloned()
                    .collect::<BTreeSet<_>>();
                remaining_reconciliations.get_or_insert(branch_ids.len());
                // Divergence can be created locally without a new remote event (for
                // example reset to an old commit followed by a write). Remember one
                // reconciliation candidate, but first construct every independent
                // dependency-ready push. One conflicted branch must not hold the
                // repository's other refs behind its reset.
                let mut pending_reconciliation = None;
                for branch_id in branch_ids {
                    let local_control = local_controls.get(&branch_id).copied();
                    let local = local_control.map(|control| control.head_commit_id);
                    let local_checkpoint =
                        local_control
                            .map(|control| {
                                control.working_diff_checkpoint_commit_id.ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                format!("local sync branch '{branch_id}' has no checkpoint cursor"),
                            )
                        })
                            })
                            .transpose()?;
                    let authoritative_coordinate = state.authoritative_branches.get(&branch_id);
                    let authoritative = authoritative_coordinate
                        .and_then(AuthoritativeBranchCoordinate::head_commit_id)
                        .map(|head| CommitId::parse_lix(head, "sync authoritative head"))
                        .transpose()?;
                    let authoritative_checkpoint = authoritative_coordinate
                        .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id)
                        .map(|checkpoint| {
                            CommitId::parse_lix(checkpoint, "sync authoritative checkpoint")
                        })
                        .transpose()?;
                    let active_reset = match (
                        state.pending_resets.get(&branch_id),
                        local,
                        authoritative,
                        authoritative_checkpoint,
                    ) {
                        (Some(intent), Some(_local), Some(authority), Some(checkpoint))
                            if intent.expected_authority_head_commit_id == authority
                                && intent.expected_authority_checkpoint_commit_id == checkpoint =>
                        {
                            let target = CommitId::parse_lix(
                                &intent.restore_target_commit_id,
                                "pending sync restore target",
                            )?;
                            let boundary = intent
                                .authority_known_ancestor_commit_id
                                .as_deref()
                                .map(|boundary| {
                                    CommitId::parse_lix(
                                        boundary,
                                        "pending sync restore authority-known ancestor",
                                    )
                                })
                                .transpose()?;
                            Some((target, boundary))
                        }
                        _ => None,
                    };
                    let active_reset_target = active_reset.map(|(target, _)| target);
                    let active_reset_boundary = active_reset.and_then(|(_, boundary)| boundary);
                    if let Some(boundary) = active_reset_boundary {
                        reset_known_commit_ids.insert(boundary);
                    }
                    if local == authoritative && local_checkpoint == authoritative_checkpoint {
                        continue;
                    }
                    // Authority-known ancestry is enough to make a commit payload
                    // dependency-complete, but it does not make a stale ref update
                    // safe. Reconciliation owns every truly divergent ref.
                    if active_reset_target.is_none()
                        && let (Some(local_head), Some(authority_head)) = (local, authoritative)
                        && (local_head == authority_head
                            || !pending_commit_reaches(
                                &read,
                                local_head,
                                authority_head,
                                &confirmed_boundaries,
                                &branch_id,
                            )
                            .await?)
                    {
                        // A stale local control is corrected to the receipt. This
                        // check stops at known boundaries, never scans cold history.
                        pending_reconciliation.get_or_insert((
                            branch_id.clone(),
                            local_head,
                            authority_head,
                        ));
                        continue;
                    }
                    if let Some(local_head) = local {
                        let mut reached_authority = authoritative.is_none()
                            || (active_reset.is_some() && active_reset_boundary.is_none());
                        let mut pending = vec![local_head];
                        let mut branch_commit_ids = BTreeSet::new();
                        while let Some(cursor) = pending.pop() {
                            if Some(cursor) == authoritative
                                || Some(cursor) == active_reset_boundary
                                || known.contains(&cursor)
                            {
                                reached_authority = true;
                                continue;
                            }
                            if !branch_commit_ids.insert(cursor) {
                                continue;
                            }
                            if let std::collections::btree_map::Entry::Vacant(entry) =
                                dependencies.entry(cursor)
                            {
                                let record =
                                    load_commit_record(&read, cursor).await?.ok_or_else(|| {
                                        LixError::new(
                                            LixError::CODE_COMMIT_NOT_FOUND,
                                            format!(
                                                "local sync head '{cursor}' has no commit record"
                                            ),
                                        )
                                    })?;
                                let mut cursor_dependencies = record
                                    .parent_commit_ids
                                    .into_iter()
                                    .chain(record.base_commit_id)
                                    .collect::<BTreeSet<_>>();
                                if let Some(alias) =
                                    load_sync_commit_state_alias(&read, cursor).await?
                                {
                                    cursor_dependencies.insert(CommitId::parse_lix(
                                        &alias.source_commit_id,
                                        "local sync complete-state source",
                                    )?);
                                }
                                entry.insert(cursor_dependencies);
                            }
                            pending.extend(
                                dependencies
                                    .get(&cursor)
                                    .expect("loaded commit dependencies")
                                    .iter()
                                    .copied(),
                            );
                        }
                        if authoritative.is_some() && !reached_authority {
                            // Pull/apply owns divergence reconciliation. Never publish
                            // a stale expected head or overwrite pending local work.
                            // One divergent branch must not stall independent refs.
                            continue;
                        }
                        commit_ids.extend(branch_commit_ids);
                    }
                    ref_updates.push(SyncRefUpdate {
                        branch_id: branch_id.clone(),
                        expected_head_commit_id: authoritative.map(|head| head.to_string()),
                        expected_checkpoint_commit_id: authoritative_coordinate
                            .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id)
                            .map(str::to_owned),
                        head_commit_id: local.map(|head| head.to_string()),
                        checkpoint_commit_id: local_checkpoint
                            .map(|checkpoint| checkpoint.to_string()),
                    });
                }
                if ref_updates.is_empty() {
                    let Some((branch_id, local_head, authoritative_head)) = pending_reconciliation
                    else {
                        drop(read);
                        self.clear_converged_sync_frontier().await?;
                        return Ok(None);
                    };
                    let remaining = remaining_reconciliations
                        .as_mut()
                        .expect("reconciliation budget initializes with branch ids");
                    if *remaining == 0 {
                        return Err(LixError::new(
                            LixError::CODE_INTERNAL_ERROR,
                            "sync reconciliation exceeded the initial branch count",
                        ));
                    }
                    *remaining -= 1;
                    if !attempted_reconciliations.insert((
                        branch_id.clone(),
                        local_head,
                        authoritative_head,
                    )) {
                        return Err(LixError::new(
                            LixError::CODE_INTERNAL_ERROR,
                            format!(
                                "sync reconciliation for branch '{branch_id}' did not advance its head"
                            ),
                        ));
                    }
                    drop(read);
                    let authoritative_checkpoint = state
                        .authoritative_branches
                        .get(&branch_id)
                        .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id)
                        .ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                format!("sync authority branch '{branch_id}' has no checkpoint"),
                            )
                        })?;
                    Box::pin(self.import_sync_repository(
                        &SyncPushRequest {
                            commits: Vec::new(),
                            inline_blobs: Vec::new(),
                            ref_updates: vec![SyncRefUpdate {
                            branch_id: branch_id.clone(),
                            expected_head_commit_id: Some(local_head.to_string()),
                            expected_checkpoint_commit_id: local_controls.get(&branch_id)
                                .and_then(|control| control.working_diff_checkpoint_commit_id)
                                .map(|checkpoint| checkpoint.to_string()),
                            head_commit_id: Some(authoritative_head.to_string()),
                            checkpoint_commit_id: Some(authoritative_checkpoint.to_owned()),
                        }],
                        },
                        SyncImportPurpose::ReplicaDelta,
                        None,
                        None,
                    ))
                    .await?;
                    continue;
                }
                known.extend(reset_known_commit_ids);
                dependencies.retain(|id, _| commit_ids.contains(id));
                let plan = super::upload_plan::UploadPlan::new(
                    generation,
                    dependencies,
                    &known,
                    ref_updates,
                )?;
                *cached = Some(CachedSyncUploadPlan {
                    plan,
                    authoritative_branches: state.authoritative_branches.clone(),
                    prepared_page: None,
                });
            }
            let page = cached
                .as_ref()
                .expect("upload wave prepared")
                .plan
                .page(max_items)?
                .ok_or_else(|| {
                    LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        "upload wave has no pending page",
                    )
                })?;
            // Only this bounded page materializes immutable members. Planning
            // above reads headers/dependencies and never retains payload bytes.
            let mut commits = Vec::with_capacity(page.commit_ids.len());
            for commit_id in &page.commit_ids {
                let Some(commit) = load_sync_commit(&read, *commit_id).await? else {
                    *cached = None;
                    if rebuilt_missing_body {
                        return Err(LixError::new(
                            LixError::CODE_COMMIT_NOT_FOUND,
                            format!(
                                "local sync commit '{commit_id}' is missing after rebuilding its upload wave"
                            ),
                        ));
                    }
                    rebuilt_missing_body = true;
                    drop(read);
                    continue 'planning;
                };
                commits.push(commit);
            }
            let mut request = SyncPushRequest {
                commits,
                ref_updates: page.ref_updates.clone(),
                inline_blobs: Vec::new(),
            };
            let prepared_reset_heads = request
                .ref_updates
                .iter()
                .filter_map(|update| {
                    let intent = state.pending_resets.get(&update.branch_id)?;
                    let head = update.head_commit_id.as_ref()?;
                    let checkpoint = update.checkpoint_commit_id.as_ref()?;
                    Some((
                        update.branch_id.clone(),
                        (intent.clone(), head.clone(), checkpoint.clone()),
                    ))
                })
                .collect::<BTreeMap<_, _>>();
            let blob_ids = sync_commit_blob_ids(&request.commits)?;
            drop(read);
            let commit_refs = request.commits.iter().collect::<Vec<_>>();
            let mut encoded_len =
                super::encoded_delta_event_len(u64::MAX, &commit_refs, &request.ref_updates)?;
            for blob_id in blob_ids {
                let manifest = self.get_sync_inline_blob_manifest(&blob_id).await?;
                if let Some(manifest) = manifest {
                    if !append_bounded_inline_blob(
                        &mut request.inline_blobs,
                        &mut encoded_len,
                        manifest,
                        "inline sync blob",
                    )? {
                        // Inline transfer is optional. Keep the largest
                        // bounded prefix and let the ordinary manifest/chunk
                        // lane carry this and all later blobs.
                        break;
                    }
                }
            }
            if !request.ref_updates.is_empty()
                && !self
                    .mark_prepared_upload_refs(
                        generation,
                        &state.authoritative_branches,
                        &request.ref_updates,
                        &prepared_reset_heads,
                    )
                    .await?
            {
                // A destructive local action or remote publication raced
                // page construction. Its atomic guard invalidates the wave.
                *cached = None;
                continue;
            }
            cached.as_mut().expect("prepared upload wave").prepared_page = Some(page);
            return Ok(Some(request));
        }
    }

    /// Retires acknowledgment boundaries only when no local upload remains.
    /// Call after a wave drains, never for each body-only acknowledgment page.
    /// A concurrent publication merely postpones this optional cleanup.
    pub(crate) async fn clear_converged_sync_frontier(&self) -> Result<bool, LixError> {
        let _collaboration_guard = self.lock_collaboration_writes().await;
        let adapter = self.storage_adapter();
        for _ in 0..3 {
            let attempt = async {
                let read = adapter.begin_read(StorageReadOptions::default()).await?;
                let (Some(mut state), previous) = load_replica_state(&read).await? else {
                    return Ok(false);
                };
                if state.authority_known_commit_ids.is_empty() || !state.pending_resets.is_empty() {
                    return Ok(false);
                }
                // Point preconditions cannot fence a branch created after the
                // scan. The repository revision also guards that phantom row.
                let revision =
                    crate::storage_adapter::load_repository_mutation_revision(&read).await?;
                let controls = BranchHeadControlContext::new().reader(&read).scan().await?;
                let branch_ids = controls
                    .iter()
                    .map(|(branch, _)| branch.clone())
                    .chain(state.authoritative_branches.keys().cloned())
                    .collect::<BTreeSet<_>>()
                    .into_iter()
                    .collect::<Vec<_>>();
                let observations = BranchHeadControlContext::new()
                    .reader(&read)
                    .load_observed(&branch_ids)
                    .await?;
                let mut preconditions = vec![
                    crate::storage_adapter::repository_mutation_revision_precondition(revision),
                ];
                for (branch_id, observation) in branch_ids.iter().zip(&observations) {
                    let authority = state.authoritative_branches.get(branch_id);
                    let local_head = observation
                        .control
                        .map(|control| control.head_commit_id.to_string());
                    let local_checkpoint = observation
                        .control
                        .and_then(|control| control.working_diff_checkpoint_commit_id)
                        .map(|checkpoint| checkpoint.to_string());
                    if local_head.as_deref()
                        != authority.and_then(AuthoritativeBranchCoordinate::head_commit_id)
                        || local_checkpoint.as_deref()
                            != authority
                                .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id)
                    {
                        return Ok(false);
                    }
                    preconditions.push(branch_head_control_precondition(
                        branch_id,
                        observation.raw_token.clone(),
                    )?);
                }
                state.authority_known_commit_ids.clear();
                let mut writes = adapter.new_write_set();
                stage_replica_state(&mut writes, &mut preconditions, &state, previous)?;
                drop(read);
                adapter
                    .commit_certified_replica_write_set(
                        super::certified_replica_write_capability(),
                        writes,
                        StorageWriteOptions {
                            preconditions,
                            await_durable: true,
                            ..StorageWriteOptions::default()
                        },
                    )
                    .await?;
                Ok::<_, LixError>(true)
            }
            .await;
            match attempt {
                Err(error)
                    if matches!(
                        error.code.as_str(),
                        LixError::CODE_TRANSACTION_CONFLICT
                            | LixError::CODE_STORAGE_READ_EXPIRED
                            | LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN
                    ) =>
                {
                    tokio::task::yield_now().await;
                }
                result => return result,
            }
        }
        Ok(false)
    }

    async fn mark_prepared_upload_refs(
        &self,
        expected_generation: u128,
        expected_authority: &BTreeMap<String, AuthoritativeBranchCoordinate>,
        refs: &[SyncRefUpdate],
        prepared: &BTreeMap<String, (PendingSyncReset, String, String)>,
    ) -> Result<bool, LixError> {
        let _collaboration_guard = self.lock_collaboration_writes().await;
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let (Some(mut state), previous) = load_replica_state(&read).await? else {
            return Ok(false);
        };
        if super::upload_plan::load_generation(&read).await? != expected_generation
            || &state.authoritative_branches != expected_authority
        {
            return Ok(false);
        }
        for (branch_id, (expected, prepared_head, prepared_checkpoint)) in prepared {
            let Some(current) = state.pending_resets.get_mut(branch_id) else {
                return Ok(false);
            };
            if current != expected {
                return Ok(false);
            }
            if current.prepared_reset_head_commit_id.as_deref() != Some(prepared_head)
                || current.prepared_reset_checkpoint_commit_id.as_deref()
                    != Some(prepared_checkpoint)
            {
                // Another worker may still have the previous request in
                // flight, even when only an ordinary local child changed H.
                retain_prepared_reset_coordinate(
                    &mut current.superseded_prepared_reset_coordinates,
                    current.prepared_reset_head_commit_id.as_ref(),
                    current.prepared_reset_checkpoint_commit_id.as_ref(),
                );
                current.prepared_reset_head_commit_id = Some(prepared_head.clone());
                current.prepared_reset_checkpoint_commit_id = Some(prepared_checkpoint.clone());
            }
            current
                .superseded_prepared_reset_coordinates
                .remove(&(prepared_head.clone(), prepared_checkpoint.clone()));
        }
        let mut writes = adapter.new_write_set();
        let mut preconditions = vec![super::upload_plan::generation_precondition(
            expected_generation,
        )];
        for update in refs {
            super::upload_proof::stage_merge_proof(&read, &mut writes, &mut preconditions, update)
                .await?;
        }
        // The receipt CAS binds every prepared proof to the authority
        // coordinate inspected above, including ordinary (non-reset) refs.
        stage_replica_state(&mut writes, &mut preconditions, &state, previous)?;
        drop(read);
        let result = adapter
            .commit_certified_replica_write_set(
                super::certified_replica_write_capability(),
                writes,
                StorageWriteOptions {
                    preconditions,
                    await_durable: true,
                    ..StorageWriteOptions::default()
                },
            )
            .await
            .map_err(LixError::from);
        match result {
            Ok(_) => Ok(true),
            Err(error) if error.code == LixError::CODE_TRANSACTION_CONFLICT => Ok(false),
            Err(error) => Err(error),
        }
    }

    /// Computes binary payload reachability at the final authoritative
    /// coordinates named by one delta page without publishing those refs.
    ///
    /// The same imported-state overlay used by root certification is reused
    /// here so intermediate values and values deleted later in the page never
    /// become eager chunk downloads.
    pub(super) async fn sync_delta_hot_blob_plan(
        &self,
        response: &SyncRepositoryPullResponse,
    ) -> Result<SyncDeltaHotBlobPlan, LixError> {
        let SyncRepositoryPullResponse::Delta { events, .. } = response else {
            return Ok(SyncDeltaHotBlobPlan {
                live_blob_ids: BTreeSet::new(),
                external_survivor_blob_ids: BTreeSet::new(),
            });
        };
        let mut final_targets = BTreeMap::<String, (Option<String>, Option<String>)>::new();
        for event in events {
            for update in &event.ref_updates {
                final_targets.insert(
                    update.branch_id.clone(),
                    (
                        update.head_commit_id.clone(),
                        update.checkpoint_commit_id.clone(),
                    ),
                );
            }
        }
        if final_targets.is_empty() {
            return Ok(SyncDeltaHotBlobPlan {
                live_blob_ids: BTreeSet::new(),
                external_survivor_blob_ids: BTreeSet::new(),
            });
        }
        let mut parsed = BTreeMap::<CommitId, ParsedCommit>::new();
        for wire in events.iter().flat_map(|event| &event.commits) {
            let commit = ParsedCommit::parse(wire)?;
            if let Some(existing) = parsed.get(&commit.commit_id) {
                if existing.wire != commit.wire {
                    return Err(immutable_object_mismatch("commit", commit.commit_id));
                }
            } else {
                parsed.insert(commit.commit_id, commit);
            }
        }

        // A final row owned by an external commit is not necessarily cold. If
        // the touched branch's currently certified head/checkpoint already
        // reaches that payload, its chunks are complete by construction. Keep
        // those IDs out of the eager lane so an ordinary child commit neither
        // rereads payloads nor refetches manifests merely because the owning row
        // predates this delta page.
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let mut previously_live_blob_ids = BTreeSet::new();
        let no_imports = BTreeMap::new();
        for branch_id in final_targets.keys() {
            let Some(control) = BranchHeadControlContext::new()
                .reader(&read)
                .load(branch_id)
                .await?
            else {
                continue;
            };
            let previous_targets = [
                Some(control.head_commit_id),
                control.working_diff_checkpoint_commit_id,
            ]
            .into_iter()
            .flatten()
            .collect::<BTreeSet<_>>();
            for target in previous_targets {
                let rows =
                    materialize_sync_live_value_rows_with_imports(&read, &no_imports, target)
                        .await?;
                previously_live_blob_ids.extend(sync_live_value_blob_ids(rows.values())?);
            }
        }

        let target_ids = final_targets
            .into_values()
            .flat_map(|(head, checkpoint)| [head, checkpoint])
            .flatten()
            .map(|target| CommitId::parse_lix(&target, "sync delta final HOT target"))
            .collect::<Result<BTreeSet<_>, _>>()?;
        let mut live_blob_ids = BTreeSet::new();
        let mut external_survivor_blob_ids = BTreeSet::new();
        for target in target_ids {
            let rows =
                materialize_sync_live_value_rows_with_imports(&read, &parsed, target).await?;
            live_blob_ids.extend(sync_live_value_blob_ids(rows.values())?);
            external_survivor_blob_ids.extend(sync_live_value_blob_ids(
                rows.values()
                    .filter(|row| !parsed.contains_key(&row.commit_id)),
            )?);
        }
        external_survivor_blob_ids.retain(|blob_id| !previously_live_blob_ids.contains(blob_id));
        Ok(SyncDeltaHotBlobPlan {
            live_blob_ids,
            external_survivor_blob_ids,
        })
    }

    /// Correct permanently rejected local work without pretending it was
    /// accepted. Keep the confirmed cursor and immutable caches unchanged.
    pub(crate) async fn discard_sync_pending_changes(&self) -> Result<(), LixError> {
        loop {
            let adapter = self.storage_adapter();
            let read = adapter.begin_read(StorageReadOptions::default()).await?;
            let (Some(mut state), Some(raw)) = load_replica_state(&read).await? else {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "pending reset requires a replica receipt",
                ));
            };
            let controls = BranchHeadControlContext::new()
                .reader(&read)
                .scan()
                .await?
                .into_iter()
                .collect::<BTreeMap<_, _>>();
            let branch_ids = controls
                .keys()
                .chain(state.authoritative_branches.keys())
                .cloned()
                .collect::<BTreeSet<_>>();
            let mut ref_updates = Vec::with_capacity(branch_ids.len());
            for branch_id in branch_ids {
                let local = controls.get(&branch_id);
                let authority = state.authoritative_branches.get(&branch_id);
                ref_updates.push(SyncRefUpdate {
                    branch_id: branch_id.clone(),
                    expected_head_commit_id: local
                        .map(|control| control.head_commit_id.to_string()),
                    expected_checkpoint_commit_id: local
                        .and_then(|control| control.working_diff_checkpoint_commit_id)
                        .map(|id| id.to_string()),
                    head_commit_id: authority
                        .and_then(AuthoritativeBranchCoordinate::head_commit_id)
                        .map(str::to_owned),
                    checkpoint_commit_id: authority
                        .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id)
                        .map(str::to_owned),
                });
            }
            let cursor = state.cursor;
            state.pending_resets.clear();
            drop(read);
            let result = Box::pin(self.import_sync_repository(
                &SyncPushRequest {
                    commits: Vec::new(),
                    ref_updates,
                    inline_blobs: Vec::new(),
                },
                SyncImportPurpose::ReplicaDelta,
                None,
                Some(ReplicaStatePublication {
                    retired_upload_proof_branches: &[],
                    expected_cursor: cursor,
                    expected_state_raw: &raw,
                    state: &state,
                    reset_pending: true,
                }),
            ))
            .await;
            match result {
                Ok(_) => return Ok(()),
                Err(error) if error.code == LixError::CODE_TRANSACTION_CONFLICT => continue,
                Err(error) => return Err(error),
            }
        }
    }

    pub(crate) async fn apply_sync_repository_pull(
        &self,
        _remote_id: &str,
        response: &SyncRepositoryPullResponse,
    ) -> Result<(), LixError> {
        match response {
            SyncRepositoryPullResponse::Snapshot { .. } => Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync snapshot metadata must be completed with commit bodies, headers, and row pages",
            )),
            SyncRepositoryPullResponse::Delta { cursor, events } => 'admit: loop {
                let (mut state, expected_state_raw) = {
                    let adapter = self.storage_adapter();
                    let read = adapter.begin_read(StorageReadOptions::default()).await?;
                    let (state, raw) = load_replica_state(&read).await?;
                    let state = state.ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            "sync delta requires an initialized replica cursor",
                        )
                    })?;
                    let raw = raw.expect("decoded sync replica state has source bytes");
                    (state, raw)
                };
                // A long-poll timeout carries no new repository state. The
                // persisted cursor already proves this heartbeat was applied,
                // so do not rescan branches or durably rewrite identical
                // replica state every time an idle poll expires.
                if events.is_empty() {
                    if *cursor > state.cursor {
                        return Err(LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            "sync delta cursor does not match its final event",
                        ));
                    }
                    return Ok(());
                }

                if events
                    .windows(2)
                    .any(|pair| pair[0].cursor.checked_add(1) != Some(pair[1].cursor))
                    || events.last().is_none_or(|event| event.cursor != *cursor)
                {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync delta event cursor is not contiguous",
                    ));
                }

                // More than one live handle can momentarily share a durable
                // browser replica while an old page is closing. Their pulls
                // can overlap even though each individual worker serializes
                // its own long poll and publication barriers. Drop the prefix
                // another worker already published; never replay it against a
                // newer certified coordinate or move the durable cursor back.
                let events =
                    &events[events.partition_point(|event| event.cursor <= state.cursor)..];
                if events.is_empty() {
                    return Ok(());
                }

                let expected_cursor = state.cursor;
                let branch_ids = events
                    .iter()
                    .flat_map(|event| event.ref_updates.iter())
                    .map(|update| update.branch_id.clone())
                    .collect::<BTreeSet<_>>()
                    .into_iter()
                    .collect::<Vec<_>>();
                let previous_authoritative = state.authoritative_branches.clone();
                let mut local_coordinates = {
                    let adapter = self.storage_adapter();
                    let read = adapter.begin_read(StorageReadOptions::default()).await?;
                    BranchHeadControlContext::new()
                        .reader(&read)
                        .load_observed(&branch_ids)
                        .await?
                        .into_iter()
                        .zip(&branch_ids)
                        .map(|(observation, branch_id)| {
                            let head = observation
                                .control
                                .map(|control| control.head_commit_id.to_string());
                            let checkpoint = observation
                                .control
                                .and_then(|control| control.working_diff_checkpoint_commit_id)
                                .map(|checkpoint| checkpoint.to_string());
                            (branch_id.clone(), (head, checkpoint))
                        })
                        .collect::<BTreeMap<_, _>>()
                };
                // Confirmed coordinates belong to the durable receipt. Visible
                // controls may contain locally durable, unacknowledged work.
                let confirmed_boundaries = state
                    .authoritative_branches
                    .values()
                    .flat_map(|coordinate| {
                        [
                            coordinate.head_commit_id(),
                            coordinate.checkpoint_commit_id(),
                        ]
                    })
                    .flatten()
                    .map(|id| CommitId::parse_lix(id, "confirmed outbox boundary"))
                    .collect::<Result<BTreeSet<_>, _>>()?;
                let mut commits = BTreeMap::new();
                let mut inline_blobs = BTreeMap::new();
                let mut branch_chains = BTreeMap::<String, (Option<String>, Option<String>)>::new();
                let mut preserved_reset_branches = BTreeSet::new();
                let mut retired_upload_proof_branches = BTreeSet::new();
                for event in events {
                    let next_cursor = state
                        .cursor
                        .checked_add(1)
                        .ok_or_else(|| LixError::unknown("sync replica cursor overflow"))?;
                    if event.cursor != next_cursor {
                        return Err(LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            "sync delta event cursor is not contiguous",
                        ));
                    }
                    for commit in &event.commits {
                        if let Some(existing) =
                            commits.insert(commit.commit_id.clone(), commit.clone())
                            && existing != *commit
                        {
                            return Err(immutable_object_mismatch("commit", &commit.commit_id));
                        }
                    }
                    for manifest in &event.inline_blobs {
                        if let Some(existing) =
                            inline_blobs.insert(manifest.blob_id.clone(), manifest.clone())
                            && existing != *manifest
                        {
                            return Err(immutable_object_mismatch(
                                "blob manifest",
                                &manifest.blob_id,
                            ));
                        }
                    }
                    state
                        .authority_known_commit_ids
                        .extend(event.commits.iter().map(|commit| commit.commit_id.clone()));
                    // Retain only the unattached dependency frontier, not an
                    // ever-growing set of all historical acknowledgements.
                    for commit in &event.commits {
                        for parent in &commit.parent_commit_ids {
                            state.authority_known_commit_ids.remove(parent);
                        }
                    }
                    for update in &event.ref_updates {
                        let authoritative_coordinate =
                            state.authoritative_branches.get(&update.branch_id);
                        let authoritative = authoritative_coordinate
                            .and_then(AuthoritativeBranchCoordinate::head_commit_id);
                        let authoritative_checkpoint = authoritative_coordinate
                            .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id);
                        if update.expected_head_commit_id.as_deref() != authoritative
                            || update.expected_checkpoint_commit_id.as_deref()
                                != authoritative_checkpoint
                        {
                            return Err(LixError::new(
                                LixError::CODE_INVALID_PARAM,
                                format!(
                                    "sync delta ref '{}' does not continue its authoritative coordinate",
                                    update.branch_id
                                ),
                            ));
                        }
                        let next_authoritative = AuthoritativeBranchCoordinate::from_wire(
                            update.head_commit_id.clone(),
                            update.checkpoint_commit_id.clone(),
                            "sync delta ref",
                        )?;
                        if update.head_commit_id != update.expected_head_commit_id
                            || update.checkpoint_commit_id != update.expected_checkpoint_commit_id
                        {
                            retired_upload_proof_branches.insert(update.branch_id.clone());
                        }
                        // A newer restore is not necessarily a descendant of
                        // an older in-flight restore. Its durable prepared-head
                        // token proves this is our acknowledgment, not another
                        // writer's incompatible ref. Rebase the newer intent's
                        // CAS coordinate without changing its target or baseline.
                        let superseded_reset_ack = state
                            .pending_resets
                            .get_mut(&update.branch_id)
                            .is_some_and(|intent| {
                                let Some(head) = update.head_commit_id.as_ref() else {
                                    return false;
                                };
                                let Some(checkpoint) = update.checkpoint_commit_id.as_ref() else {
                                    return false;
                                };
                                if Some(intent.expected_authority_head_commit_id.as_str())
                                    != update.expected_head_commit_id.as_deref()
                                    || Some(intent.expected_authority_checkpoint_commit_id.as_str())
                                        != update.expected_checkpoint_commit_id.as_deref()
                                    || !intent
                                        .superseded_prepared_reset_coordinates
                                        .contains(&(head.clone(), checkpoint.clone()))
                                {
                                    return false;
                                }
                                // All recorded requests used the old expected
                                // source. Once it advances none can CAS again;
                                // retaining them would misidentify a foreign
                                // write from the new source as our acknowledgment.
                                intent.superseded_prepared_reset_coordinates.clear();
                                intent.superseded_prepared_reset_head_commit_ids.clear();
                                intent.expected_authority_head_commit_id = head.clone();
                                intent.expected_authority_checkpoint_commit_id = update
                                    .checkpoint_commit_id
                                    .clone()
                                    .expect("headed ref has a checkpoint");
                                intent.prepared_reset_head_commit_id = None;
                                intent.prepared_reset_checkpoint_commit_id = None;
                                true
                            });
                        if superseded_reset_ack {
                            preserved_reset_branches.insert(update.branch_id.clone());
                        } else {
                            // A later unrelated ref in the same delta page
                            // still wins over the pending restore.
                            preserved_reset_branches.remove(&update.branch_id);
                        }
                        let chain = branch_chains
                            .entry(update.branch_id.clone())
                            .or_insert_with(|| {
                                (
                                    update.head_commit_id.clone(),
                                    update.checkpoint_commit_id.clone(),
                                )
                            });
                        chain.0 = update.head_commit_id.clone();
                        chain.1 = update.checkpoint_commit_id.clone();
                        state
                            .authoritative_branches
                            .insert(update.branch_id.clone(), next_authoritative);
                        if let Some(head) = &update.head_commit_id {
                            state.authority_known_commit_ids.remove(head);
                        }
                    }
                    state.cursor = event.cursor;
                }
                if state.cursor != *cursor {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync delta cursor does not match its final event",
                    ));
                }

                let mut applicable_refs = Vec::new();
                let mut reset_pending_dependents = false;
                let adapter = self.storage_adapter();
                let read = adapter.begin_read(StorageReadOptions::default()).await?;
                for (branch_id, (head, checkpoint)) in &branch_chains {
                    let local = local_coordinates
                        .get(branch_id)
                        .expect("folded delta branch was loaded once");
                    // Own acknowledged prefixes must never roll back a newer
                    // local transaction. A competing server branch wins. Walk
                    // only the local chain; no historical network demand.
                    let preserve_local = preserved_reset_branches.contains(branch_id)
                        || match (local.0.as_deref(), head.as_deref()) {
                            (Some(local_head), Some(server_head)) if local_head != server_head => {
                                let server_head =
                                    CommitId::parse_lix(server_head, "acknowledged head")?;
                                !confirmed_boundaries.contains(&server_head)
                                    && pending_commit_reaches(
                                        &read,
                                        CommitId::parse_lix(local_head, "local pending head")?,
                                        server_head,
                                        &confirmed_boundaries,
                                        branch_id,
                                    )
                                    .await?
                            }
                            _ => false,
                        };
                    if !preserve_local
                        && (local.0.as_deref(), local.1.as_deref())
                            != (head.as_deref(), checkpoint.as_deref())
                    {
                        let previous = previous_authoritative.get(branch_id);
                        reset_pending_dependents |= (local.0.as_deref(), local.1.as_deref())
                            != (
                                previous.and_then(AuthoritativeBranchCoordinate::head_commit_id),
                                previous
                                    .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id),
                            );
                    }
                    if !preserve_local {
                        state.pending_resets.remove(branch_id);
                    }
                    // Keep the pending coordinate visible. If a local writer
                    // advanced it meanwhile, importer admission retries before
                    // it can replace that newer coordinate.
                    applicable_refs.push(SyncRefUpdate {
                        branch_id: branch_id.clone(),
                        expected_head_commit_id: local.0.clone(),
                        expected_checkpoint_commit_id: local.1.clone(),
                        head_commit_id: if preserve_local {
                            local.0.clone()
                        } else {
                            head.clone()
                        },
                        checkpoint_commit_id: if preserve_local {
                            local.1.clone()
                        } else {
                            checkpoint.clone()
                        },
                    });
                }
                if reset_pending_dependents {
                    // A pending checkpoint spans its branch and the global
                    // catalog; schema edits can be bases of other branches.
                    // Conservatively discard the entire pending client state
                    // atomically on incompatibility, including these reverse
                    // dependencies, instead of uploading orphan checkpoints.
                    for (branch_id, control) in
                        BranchHeadControlContext::new().reader(&read).scan().await?
                    {
                        local_coordinates.entry(branch_id).or_insert_with(|| {
                            (
                                Some(control.head_commit_id.to_string()),
                                control
                                    .working_diff_checkpoint_commit_id
                                    .map(|id| id.to_string()),
                            )
                        });
                    }
                    for branch_id in state.authoritative_branches.keys() {
                        local_coordinates
                            .entry(branch_id.clone())
                            .or_insert((None, None));
                    }
                    applicable_refs = local_coordinates
                        .iter()
                        .map(|(branch_id, local)| {
                            let coordinate = state.authoritative_branches.get(branch_id);
                            SyncRefUpdate {
                                branch_id: branch_id.clone(),
                                expected_head_commit_id: local.0.clone(),
                                expected_checkpoint_commit_id: local.1.clone(),
                                head_commit_id: coordinate
                                    .and_then(AuthoritativeBranchCoordinate::head_commit_id)
                                    .map(str::to_owned),
                                checkpoint_commit_id: coordinate
                                    .and_then(AuthoritativeBranchCoordinate::checkpoint_commit_id)
                                    .map(str::to_owned),
                            }
                        })
                        .collect();
                    state.pending_resets.clear();
                }
                drop(read);
                let commits = commits.into_values().collect::<Vec<_>>();
                let inline_blobs = inline_blobs.into_values().collect::<Vec<_>>();
                let parsed = commits
                    .iter()
                    .map(ParsedCommit::parse)
                    .map(|result| result.map(|commit| (commit.commit_id, commit)))
                    .collect::<Result<BTreeMap<_, _>, _>>()?;
                let adapter = self.storage_adapter();
                let read = adapter.begin_read(StorageReadOptions::default()).await?;
                let mut roots = BTreeMap::<CommitId, SyncLiveValueRootId>::new();
                for (branch_id, (head, checkpoint)) in &branch_chains {
                    match (head.as_deref(), checkpoint.as_deref()) {
                        (Some(head), Some(checkpoint)) => {
                            let head = CommitId::parse_lix(head, "sync delta branch head")?;
                            let checkpoint =
                                CommitId::parse_lix(checkpoint, "sync delta branch checkpoint")?;
                            let head_root = if let Some(root) = roots.get(&head) {
                                root.clone()
                            } else {
                                let root = certified_sync_live_value_root_with_imports(
                                    &read, &parsed, head,
                                )
                                .await?;
                                roots.insert(head, root.clone());
                                root
                            };
                            let checkpoint_root = if let Some(root) = roots.get(&checkpoint) {
                                root.clone()
                            } else {
                                let root = certified_sync_live_value_root_with_imports(
                                    &read, &parsed, checkpoint,
                                )
                                .await?;
                                roots.insert(checkpoint, root.clone());
                                root
                            };
                            state.certified_branch_roots.insert(
                                branch_id.clone(),
                                CertifiedBranchRoots {
                                    head_state_root_id: format_sync_live_value_root_id(&head_root),
                                    checkpoint_state_root_id: format_sync_live_value_root_id(
                                        &checkpoint_root,
                                    ),
                                },
                            );
                        }
                        (None, None) => {
                            state.certified_branch_roots.remove(branch_id);
                        }
                        _ => unreachable!(
                            "sync coordinate validation already paired head/checkpoint"
                        ),
                    }
                }
                drop(read);
                let retired_upload_proof_branches = retired_upload_proof_branches
                    .into_iter()
                    .collect::<Vec<_>>();
                let publication = Box::pin(self.import_sync_repository(
                    &SyncPushRequest {
                        commits,
                        ref_updates: applicable_refs,
                        inline_blobs,
                    },
                    SyncImportPurpose::ReplicaDelta,
                    None,
                    Some(ReplicaStatePublication {
                        retired_upload_proof_branches: &retired_upload_proof_branches,
                        reset_pending: reset_pending_dependents,
                        expected_cursor,
                        expected_state_raw: &expected_state_raw,
                        state: &state,
                    }),
                ))
                .await;
                match publication {
                    Ok(_) => return Ok(()),
                    // A sibling worker may have won the durable receipt CAS
                    // after this iteration loaded it. Re-read the receipt and
                    // trim the now-redundant prefix instead of terminating the
                    // sync runtime with a false cursor-gap error.
                    Err(error) if error.code == LixError::CODE_TRANSACTION_CONFLICT => {
                        let adapter = self.storage_adapter();
                        let read = adapter.begin_read(StorageReadOptions::default()).await?;
                        let (latest_state, latest_raw) = load_replica_state(&read).await?;
                        if latest_raw.as_ref() == Some(&expected_state_raw) {
                            return Err(error);
                        }
                        let latest_state = latest_state.ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                "sync replica state disappeared after publication conflict",
                            )
                        })?;
                        if latest_state.cursor < expected_cursor {
                            return Err(LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                "sync replica cursor regressed after publication conflict",
                            ));
                        }
                        continue 'admit;
                    }
                    Err(error) => return Err(error),
                }
            },
        }
    }

    #[cfg(test)]
    pub(crate) async fn try_install_initial_sync_snapshot(
        &self,
        remote_id: &str,
        active_account_id: &str,
        metadata: &SyncRepositoryPullResponse,
        head_commits: &[SyncCommit],
        commit_headers: &[SyncCommitHeader],
        rows: &[SyncSnapshotRow],
        checkpoint_roots: &BTreeMap<String, String>,
    ) -> Result<InitialSyncSnapshotInstall, LixError> {
        self.try_install_initial_sync_snapshot_with_inventory(
            remote_id,
            active_account_id,
            metadata,
            head_commits,
            commit_headers,
            rows,
            checkpoint_roots,
            &BTreeSet::new(),
        )
        .await
    }

    pub(crate) async fn try_install_initial_sync_snapshot_with_inventory(
        &self,
        remote_id: &str,
        active_account_id: &str,
        metadata: &SyncRepositoryPullResponse,
        head_commits: &[SyncCommit],
        commit_headers: &[SyncCommitHeader],
        rows: &[SyncSnapshotRow],
        checkpoint_roots: &BTreeMap<String, String>,
        sparse_inventory_commit_ids: &BTreeSet<String>,
    ) -> Result<InitialSyncSnapshotInstall, LixError> {
        self.set_sync_replica_remote_id(remote_id)?;
        let _collaboration_guard = self.lock_collaboration_writes().await;
        let SyncRepositoryPullResponse::Snapshot {
            cursor,
            lix_id,
            default_branch_id,
            branches,
        } = metadata
        else {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync repository snapshot installer requires snapshot metadata",
            ));
        };
        self.install_sync_snapshot(
            remote_id,
            active_account_id,
            *cursor,
            lix_id,
            default_branch_id,
            branches,
            head_commits,
            commit_headers,
            rows,
            checkpoint_roots,
            sparse_inventory_commit_ids,
        )
        .await
    }

    #[cfg(test)]
    async fn store_replica_state(
        &self,
        remote_id: &str,
        state: SyncReplicaState,
    ) -> Result<(), LixError> {
        self.set_sync_replica_remote_id(remote_id)?;
        let _collaboration_guard = self.lock_collaboration_writes().await;
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let (_, previous) = load_replica_state(&read).await?;
        let mut writes = adapter.new_write_set();
        let mut preconditions = Vec::new();
        stage_replica_state(&mut writes, &mut preconditions, &state, previous)?;
        drop(read);
        adapter
            .commit_certified_replica_write_set(
                super::certified_replica_write_capability(),
                writes,
                StorageWriteOptions {
                    preconditions,
                    await_durable: true,
                    ..StorageWriteOptions::default()
                },
            )
            .await?;
        Ok(())
    }

    async fn install_sync_snapshot(
        &self,
        remote_id: &str,
        active_account_id: &str,
        cursor: u64,
        lix_id: &str,
        default_branch_id: &str,
        branches: &[SyncBranchHead],
        head_commits: &[SyncCommit],
        commit_headers: &[SyncCommitHeader],
        rows: &[SyncSnapshotRow],
        checkpoint_roots: &BTreeMap<String, String>,
        sparse_inventory_commit_ids: &BTreeSet<String>,
    ) -> Result<InitialSyncSnapshotInstall, LixError> {
        super::validate_sync_remote_id(remote_id)?;
        let mut parsed_heads = BTreeMap::new();
        for commit in head_commits {
            let commit = ParsedCommit::parse(commit)?;
            if parsed_heads.insert(commit.commit_id, commit).is_some() {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync snapshot contains duplicate commit bodies",
                ));
            }
        }
        let parsed_rows = rows
            .iter()
            .map(parse_snapshot_row)
            .collect::<Result<Vec<_>, _>>()?;
        let default_branch_row_pk = RowPk::single(crate::init::DEFAULT_BRANCH_KEY);
        let lix_id_row_pk = RowPk::single(crate::init::LIX_ID_KEY);
        let mut tracked_lix_ids = parsed_rows
            .iter()
            .filter(|row| {
                row.branch_id == crate::GLOBAL_BRANCH_ID
                    && row.schema_key == "lix_key_value"
                    && row.file_id.is_none()
                    && row.row_pk == lix_id_row_pk
            })
            .map(|row| {
                serde_json::from_str::<serde_json::Value>(&row.snapshot_json)
                    .ok()
                    .and_then(|snapshot| {
                        snapshot
                            .get("value")
                            .and_then(serde_json::Value::as_str)
                            .map(str::to_owned)
                    })
            });
        if tracked_lix_ids.next().flatten().as_deref() != Some(lix_id)
            || tracked_lix_ids.next().is_some()
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync snapshot lixId disagrees with its canonical tracked row",
            ));
        }
        let mut tracked_default_branch_ids = parsed_rows
            .iter()
            .filter(|row| {
                row.branch_id == crate::GLOBAL_BRANCH_ID
                    && row.schema_key == "lix_key_value"
                    && row.file_id.is_none()
                    && row.row_pk == default_branch_row_pk
            })
            .map(|row| {
                serde_json::from_str::<serde_json::Value>(&row.snapshot_json)
                    .ok()
                    .and_then(|snapshot| {
                        snapshot
                            .get("value")
                            .and_then(serde_json::Value::as_str)
                            .map(str::to_owned)
                    })
            });
        if tracked_default_branch_ids.next().flatten().as_deref() != Some(default_branch_id)
            || tracked_default_branch_ids.next().is_some()
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync snapshot defaultBranchId disagrees with its canonical tracked row",
            ));
        }
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        match inspect_sync_replica_binding(&read).await? {
            SyncReplicaBinding::Unbound => {}
            SyncReplicaBinding::Bound { .. } => {
                return Ok(InitialSyncSnapshotInstall::ExistingRepository);
            }
            SyncReplicaBinding::Ambiguous => {
                return Ok(InitialSyncSnapshotInstall::Ambiguous);
            }
        }
        let branch_ids = branches
            .iter()
            .map(|branch| branch.branch_id.clone())
            .collect::<Vec<_>>();
        if branch_ids
            .iter()
            .map(String::as_str)
            .collect::<BTreeSet<_>>()
            .len()
            != branch_ids.len()
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync snapshot contains duplicate branch ids",
            ));
        }
        if branches
            .iter()
            .filter(|branch| branch.branch_id == default_branch_id)
            .count()
            != 1
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync snapshot must contain exactly one headed default branch",
            ));
        }
        let mut header_by_id = BTreeMap::new();
        for header in commit_headers {
            let parsed = ParsedSyncHeader::parse(header)?;
            if header_by_id.insert(parsed.commit_id, parsed).is_some() {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync snapshot contains duplicate commit headers",
                ));
            }
        }
        let sparse_inventory_ids = sparse_inventory_commit_ids
            .iter()
            .map(|id| CommitId::parse_lix(id, "sparse checkpoint inventory"))
            .collect::<Result<BTreeSet<_>, _>>()?;
        if sparse_inventory_ids
            .iter()
            .any(|id| parsed_heads.contains_key(id))
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "materialized snapshot headers cannot use sparse inventory validation",
            ));
        }
        validate_sync_header_set(&header_by_id, "sync snapshot", &sparse_inventory_ids)?;
        let observed = BranchHeadControlContext::new()
            .reader(&read)
            .load_observed(&branch_ids)
            .await?;
        let local_global_head = BranchHeadControlContext::new()
            .reader(&read)
            .load(crate::GLOBAL_BRANCH_ID)
            .await?
            .map(|control| control.head_commit_id);
        for (branch, observation) in branches.iter().zip(&observed) {
            let incoming_head = branch
                .head_commit_id
                .as_deref()
                .ok_or_else(|| {
                    LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync snapshot branch has no head",
                    )
                })
                .and_then(|head| CommitId::parse_lix(head, "sync snapshot branch head"))?;
            let Some(local) = observation.control else {
                continue;
            };
            if snapshot_head_contains_local_head(
                &read,
                incoming_head,
                local.head_commit_id,
                &header_by_id,
            )
            .await?
            {
                // A newly hosted copy may already include server-side account
                // initialization or other commits. Accept its proven extension
                // of our local history, but never discard a diverged local head.
                continue;
            }
            let record = load_commit_record(&read, local.head_commit_id)
                .await?
                .ok_or_else(|| {
                    LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!(
                            "local sync branch '{}' lost head commit '{}'",
                            branch.branch_id, local.head_commit_id
                        ),
                    )
                })?;
            let pristine_topology = if branch.branch_id == crate::GLOBAL_BRANCH_ID {
                record.parent_commit_ids.is_empty() && record.base_commit_id.is_none()
            } else {
                record.base_commit_id == local_global_head
                    && record
                        .base_commit_id
                        .is_some_and(|base| record.parent_commit_ids.as_slice() == [base])
            };
            let pristine_initialization = pristine_topology
                && record.account_id == crate::SYSTEM_ACCOUNT_ID
                && local.head_commit_id == local.tracked_generation
                && local.working_diff_checkpoint_commit_id == Some(local.head_commit_id)
                && local.current_state_revision == 0
                && local.created_at == local.updated_at;
            if !pristine_initialization {
                return Err(LixError::new(
                    LixError::CODE_TRANSACTION_CONFLICT,
                    format!(
                        "sync snapshot cannot replace locally advanced branch '{}' at '{}'",
                        branch.branch_id, local.head_commit_id
                    ),
                ));
            }
        }
        let mut records = BTreeMap::<CommitId, CommitRecord>::new();
        let mut existing_complete = BTreeSet::new();
        let mut appended_records = Vec::with_capacity(header_by_id.len());
        for header in header_by_id.values() {
            if let Some(existing) = load_commit_record(&read, header.commit_id).await? {
                if !header.matches_record(&existing) {
                    return Err(immutable_object_mismatch("commit", header.commit_id));
                }
                let existing_scope =
                    match load_published_commit_state_topology(&read, header.commit_id).await? {
                        Some(topology) => Some(topology.global_scope()),
                        None => deferred_commit_global_scope(&read, header.commit_id).await?,
                    };
                if existing_scope.is_some_and(|scope| scope != header.global_scope) {
                    return Err(immutable_object_mismatch("commit", header.commit_id));
                }
                if existing_scope.is_some()
                    && !commit_history_is_deferred(&read, header.commit_id).await?
                {
                    existing_complete.insert(header.commit_id);
                }
                records.insert(header.commit_id, existing);
            } else {
                let record = header.record();
                records.insert(header.commit_id, record.clone());
                appended_records.push(record);
            }
        }
        for (commit_id, commit) in &parsed_heads {
            let header = header_by_id.get(commit_id).ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!("sync snapshot head '{commit_id}' has no certified header"),
                )
            })?;
            if header.is_checkpoint != commit.wire.is_checkpoint
                || header.parent_commit_ids != commit.parent_commit_ids
                || header.base_commit_id != commit.base_commit_id
                || header.account_id != commit.account_id
                || header.created_at != commit.created_at
                || header.global_scope != commit.wire.global_scope
            {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!("sync snapshot head '{commit_id}' body disagrees with its header"),
                ));
            }
        }
        for (commit_id, commit) in &parsed_heads {
            if existing_complete.contains(commit_id) {
                let stored = load_sync_commit(&read, *commit_id)
                    .await?
                    .ok_or_else(|| LixError::unknown("complete local commit body is missing"))?;
                if stored != commit.wire {
                    return Err(immutable_object_mismatch("commit", commit_id));
                }
            }
        }
        let mut head_ids = BTreeSet::new();
        let mut checkpoint_ids = BTreeSet::new();
        for branch in branches {
            let head = branch
                .head_commit_id
                .as_deref()
                .ok_or_else(|| {
                    LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync snapshot branch has no head",
                    )
                })
                .and_then(|head| CommitId::parse_lix(head, "sync snapshot branch head"))?;
            if !parsed_heads.contains_key(&head) {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!("sync snapshot head '{head}' has no exact commit body"),
                ));
            }
            head_ids.insert(head);
            checkpoint_ids.insert(CommitId::parse_lix(
                branch
                    .checkpoint_commit_id
                    .as_deref()
                    .expect("validated checkpoint"),
                "sync snapshot branch checkpoint",
            )?);
        }
        checkpoint_ids.extend(
            header_by_id
                .values()
                .filter(|header| {
                    header.is_checkpoint && parsed_heads.contains_key(&header.commit_id)
                })
                .map(|header| header.commit_id),
        );
        let mut snapshot_body_ids = head_ids
            .union(&checkpoint_ids)
            .copied()
            .collect::<BTreeSet<_>>();
        // A local head or checkpoint is not a complete state authority
        // without its pinned global base, so the snapshot ships that base's
        // body inline. Accept exactly the bases the accepted bodies name;
        // bases are global commits and carry no base of their own.
        let inline_base_ids = snapshot_body_ids
            .iter()
            .filter_map(|commit_id| parsed_heads.get(commit_id))
            .filter_map(|commit| commit.base_commit_id)
            .collect::<BTreeSet<_>>();
        snapshot_body_ids.extend(inline_base_ids);
        let required_checkpoint_roots = checkpoint_ids
            .difference(&head_ids)
            .map(ToString::to_string)
            .collect::<BTreeSet<_>>();
        let advertised_roots = checkpoint_roots.keys().cloned().collect::<BTreeSet<_>>();
        if !required_checkpoint_roots.is_subset(&advertised_roots)
            || advertised_roots.iter().any(|id| {
                CommitId::parse_lix(id, "snapshot boundary")
                    .map_or(true, |id| !snapshot_body_ids.contains(&id))
            })
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync snapshot checkpoint roots do not match its authenticated boundaries",
            ));
        }
        for body_id in parsed_heads.keys() {
            if !snapshot_body_ids.contains(body_id) {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync snapshot body '{body_id}' is neither a branch head nor checkpoint"
                    ),
                ));
            }
        }

        let advertised_branches = branch_ids
            .iter()
            .map(String::as_str)
            .collect::<BTreeSet<_>>();
        let mut row_coordinates = BTreeSet::new();
        for row in &parsed_rows {
            let checkpoint_row_owner =
                CommitId::parse_lix(&row.branch_id, "sync snapshot checkpoint row owner")
                    .ok()
                    .is_some_and(|commit_id| snapshot_body_ids.contains(&commit_id));
            if !advertised_branches.contains(row.branch_id.as_str()) && !checkpoint_row_owner {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync snapshot row references unadvertised branch '{}'",
                        row.branch_id
                    ),
                ));
            }
            if !row_coordinates.insert((
                row.branch_id.clone(),
                row.schema_key.clone(),
                row.file_id.clone(),
                row.row_pk.clone(),
            )) {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync snapshot repeats a row coordinate",
                ));
            }
        }
        // A page sequence is complete only if its reconstructed canonical root
        // equals the head certificate. This turns an omitted/truncated page
        // into an atomic bootstrap failure instead of silently deleting rows.
        for branch in branches {
            let head = CommitId::parse_lix(
                branch.head_commit_id.as_deref().expect("validated head"),
                "sync snapshot branch head",
            )?;
            let expected_root = parse_sync_live_value_root_id(&branch.hot_state_root_id)?;
            let actual_root = sync_live_value_root_from_snapshot_rows(
                parsed_rows
                    .iter()
                    .filter(|row| row.branch_id == branch.branch_id),
            )?;
            if actual_root != expected_root {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync snapshot rows for branch '{}' do not match head '{}' stateRootId",
                        branch.branch_id, head
                    ),
                ));
            }
        }
        for (checkpoint_id, root_id) in checkpoint_roots {
            CommitId::parse_lix(checkpoint_id, "sync snapshot checkpoint root")?;
            let expected_root = parse_sync_live_value_root_id(root_id)?;
            let actual_root = sync_live_value_root_from_snapshot_rows(
                parsed_rows
                    .iter()
                    .filter(|row| row.branch_id == *checkpoint_id),
            )?;
            if actual_root != expected_root {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync snapshot rows for checkpoint '{checkpoint_id}' do not match its liveStateRootId"
                    ),
                ));
            }
        }

        let mut writes = adapter.new_write_set();
        let mut preconditions = Vec::new();
        for commit_id in header_by_id.keys().copied() {
            if parsed_heads.contains_key(&commit_id) || existing_complete.contains(&commit_id) {
                stage_commit_history_available(&mut writes, commit_id);
            } else {
                stage_commit_history_deferred_with_scope(
                    &mut writes,
                    commit_id,
                    header_by_id[&commit_id].global_scope,
                );
            }
        }
        for (commit_id, commit) in &parsed_heads {
            if !existing_complete.contains(commit_id)
                && let Some(alias) = &commit.wire.state_alias
            {
                stage_materialized_sync_state_alias(&mut writes, *commit_id, alias)?;
            }
        }
        let mut changes = BTreeMap::<ChangeId, ChangeRecord>::new();
        for row in &parsed_rows {
            let change = row.change_record();
            if changes
                .insert(change.change_id, change.clone())
                .is_some_and(|existing| existing != change)
            {
                return Err(immutable_object_mismatch("change", change.change_id));
            }
        }
        for branch in branches {
            let head = CommitId::parse_lix(
                branch.head_commit_id.as_deref().expect("validated head"),
                "sync snapshot branch head",
            )?;
            let record = &records[&head];
            let change = sync_ref_change_record(
                &branch.branch_id,
                head,
                &record.account_id,
                record.created_at,
            )?;
            if changes
                .insert(change.change_id, change.clone())
                .is_some_and(|existing| existing != change)
            {
                return Err(immutable_object_mismatch(
                    "branch ref change",
                    change.change_id,
                ));
            }
        }
        let mut head_mutations = BTreeMap::new();
        // A sparse bootstrap can include a checkpoint/head selection while the
        // commit that originally authored one of its changes remains deferred.
        // The selected payload is self-contained, so let it temporarily own
        // the canonical locator. If an authored body is present in the same
        // snapshot it wins; later history hydration replaces the fallback with
        // the original authored locator.
        let mut selected_fallback_locators = BTreeMap::new();
        let mut authored_locators = BTreeMap::new();
        let mut imported_authored_change_ids = BTreeSet::new();
        for commit in parsed_heads
            .iter()
            .filter(|(commit_id, _)| {
                snapshot_body_ids.contains(commit_id) && !existing_complete.contains(commit_id)
            })
            .map(|(_, commit)| commit)
        {
            let mutations = stage_imported_commit_body(
                &mut writes,
                commit,
                &mut imported_authored_change_ids,
                &mut selected_fallback_locators,
                &mut authored_locators,
            )?;
            for member in &commit.members {
                let change = member.change_record();
                if changes
                    .insert(change.change_id, change.clone())
                    .is_some_and(|existing| existing != change)
                {
                    return Err(immutable_object_mismatch("change", change.change_id));
                }
            }
            head_mutations.insert(commit.commit_id, mutations);
        }
        selected_fallback_locators
            .retain(|change_id, _| !imported_authored_change_ids.contains(change_id));
        stage_missing_selected_change_locators(
            &read,
            &mut writes,
            &mut preconditions,
            selected_fallback_locators,
        )
        .await?;
        stage_change_locators(
            &mut writes,
            &authored_locators.into_values().collect::<Vec<_>>(),
        );
        ChangelogContext::new()
            .writer(&mut &read, &mut writes)
            .stage_certified_sparse_append(ChangelogAppend {
                commits: appended_records,
                changes: changes.into_values().collect(),
            })
            .await?;

        let mut row_pk_index_overlay = TrackedStateChunkOverlay::new();
        for head in snapshot_body_ids.iter().copied() {
            if existing_complete.contains(&head) {
                // The source already owns the complete immutable body and
                // state representation. Sparse bootstrap must not rewrite it
                // under the same identities with a different physical encoding.
                continue;
            }
            // A sparse snapshot may advertise a checkpoint coordinate whose
            // header/body is intentionally deferred. Its rows still seed the
            // hot checkpoint baseline; immutable state authority is installed
            // later through the structured history-demand path.
            let (Some(record), Some(header)) = (records.get(&head), header_by_id.get(&head)) else {
                continue;
            };
            let row_owner = branches
                .iter()
                .find(|branch| branch.head_commit_id.as_deref() == Some(head.to_string().as_str()))
                .map(|branch| branch.branch_id.clone())
                .unwrap_or_else(|| head.to_string());
            let head_rows = parsed_rows
                .iter()
                .filter(|row| row.branch_id == row_owner)
                .collect::<Vec<_>>();
            let root_deltas = head_rows
                .iter()
                .map(|row| row.as_root_delta())
                .collect::<Vec<_>>();
            let tracked_context = TrackedStateContext::new();
            let mut tracked_writer = tracked_context.writer(&read, &mut writes);
            tracked_writer
                .stage_commit_root(&head.to_string(), None, root_deltas)
                .await?;
            let mut snapshot_root = tracked_writer
                .staged_commit_roots()
                .find(|root| root.commit_id == head)
                .cloned()
                .ok_or_else(|| LixError::unknown("sync snapshot did not stage its root"))?;
            drop(tracked_writer);
            snapshot_root.changed_key_count = u64::try_from(
                parsed_heads
                    .get(&head)
                    .map_or(head_rows.len(), |commit| commit.members.len()),
            )
            .map_err(|_| LixError::unknown("sync head mutation count exceeds u64"))?;
            snapshot_root.complete_state_fence = true;
            let row_pk_index_root_id = stage_row_pk_index_from_deltas(
                &read,
                &mut writes,
                &mut row_pk_index_overlay,
                head_rows.iter().map(|row| row.as_root_delta()),
                head,
            )
            .await?;
            let mutations = head_mutations.remove(&head).unwrap_or_default();
            stage_commit_state_manifest_with_handle(
                &mut writes,
                &CommitStateManifest {
                    commit_id: head,
                    change_account_id: record.account_id.clone(),
                    replay_debt: CommitStateReplayDebt::default(),
                    mutations,
                    touched_scope_filter: incomplete_touched_scope_filter(),
                    global_scope: header.global_scope,
                    current_state_scoped_ranges: None,
                    row_pk_index_root_id,
                    snapshot_root: Some(Box::new(snapshot_root)),
                },
            )?;
        }

        for ((branch, observation), head) in
            branches
                .iter()
                .zip(observed)
                .zip(branches.iter().map(|branch| {
                    CommitId::parse_lix(
                        branch.head_commit_id.as_deref().expect("validated head"),
                        "sync snapshot branch head",
                    )
                    .expect("validated head")
                }))
        {
            preconditions.push(branch_head_control_precondition(
                &branch.branch_id,
                observation.raw_token,
            )?);
            let branch_rows = parsed_rows
                .iter()
                .filter(|row| row.branch_id == branch.branch_id)
                .collect::<Vec<_>>();
            let checkpoint = CommitId::parse_lix(
                branch
                    .checkpoint_commit_id
                    .as_deref()
                    .expect("validated checkpoint"),
                "sync snapshot branch checkpoint",
            )?;
            let checkpoint_rows = if checkpoint == head {
                branch_rows.clone()
            } else {
                parsed_rows
                    .iter()
                    .filter(|row| row.branch_id == checkpoint)
                    .collect::<Vec<_>>()
            };
            let current_rows =
                snapshot_rows_with_inherited_catalog(&branch.branch_id, &parsed_rows, &branch_rows);
            let checkpoint_rows = snapshot_rows_with_inherited_catalog(
                &branch.branch_id,
                &parsed_rows,
                &checkpoint_rows,
            );
            let current_snapshot =
                snapshot_rows_hot_snapshot(&branch.branch_id, current_rows.into_values())?;
            let checkpoint_snapshot =
                snapshot_rows_hot_snapshot(&branch.branch_id, checkpoint_rows.into_values())?;
            let mut coverage = WorkingDiffIndexCoverage::default();
            let (_, schemas) = TrackedHeadContext::new()
                .writer(&read, &mut writes)
                .stage_complete_current_state_with_working_diff(
                    &branch.branch_id,
                    head,
                    current_snapshot,
                    observation
                        .control
                        .map(|control| control.tracked_generation),
                    &[],
                    &[],
                    &BTreeSet::new(),
                    if checkpoint == head {
                        CompleteWorkingDiffMode::ResetClean
                    } else {
                        CompleteWorkingDiffMode::Rebase {
                            checkpoint_commit_id: checkpoint,
                            checkpoint: checkpoint_snapshot,
                        }
                    },
                    &mut coverage,
                )
                .await?;
            stage_tracked_working_diff_epoch(
                &mut writes,
                &branch.branch_id,
                TrackedWorkingDiffEpoch {
                    checkpoint_commit_id: checkpoint,
                    generation: head,
                    coverage,
                },
            )?;
            let record = &records[&head];
            let mut control = BranchHeadControl {
                head_commit_id: head,
                tracked_generation: head,
                current_state_revision: observation.control.map_or(0, |control| {
                    control.current_state_revision.saturating_add(1)
                }),
                working_diff_checkpoint_commit_id: Some(checkpoint),
                created_at: observation
                    .control
                    .map_or(record.created_at, |control| control.created_at),
                updated_at: record.created_at,
                ref_change_id: sync_ref_change_id(&branch.branch_id, Some(head)),
                schema_presence_bloom: [0; 4],
            };
            control.note_schemas(schemas.iter().map(String::as_str));
            stage_branch_head_control(&mut writes, &branch.branch_id, control)?;
        }
        let authoritative_branches = branches
            .iter()
            .map(|branch| {
                Ok((
                    branch.branch_id.clone(),
                    AuthoritativeBranchCoordinate::from_wire(
                        branch.head_commit_id.clone(),
                        branch.checkpoint_commit_id.clone(),
                        "sync snapshot branch",
                    )?,
                ))
            })
            .collect::<Result<BTreeMap<_, _>, LixError>>()?;
        let certified_branch_roots = branches
            .iter()
            .map(|branch| {
                (
                    branch.branch_id.clone(),
                    CertifiedBranchRoots {
                        head_state_root_id: branch.hot_state_root_id.clone(),
                        checkpoint_state_root_id: branch.checkpoint_state_root_id.clone(),
                    },
                )
            })
            .collect();
        stage_replica_state(
            &mut writes,
            &mut preconditions,
            &SyncReplicaState {
                active_account_id: active_account_id.to_owned(),
                cursor,
                authoritative_branches,
                certified_branch_roots,
                snapshot_certified_cursor: Some(cursor),
                pending_resets: BTreeMap::new(),
                authority_known_commit_ids: BTreeSet::new(),
            },
            None,
        )?;
        preconditions.push(StoragePrecondition::RangeEmpty {
            space: SYNC_REPLICA_STATE_SPACE,
            range: StoragePrefix {
                bytes: Bytes::new(),
            }
            .to_range()?,
        });
        crate::json_store::stage_json_publication_fence(&read, &mut writes, &mut preconditions)
            .await?;
        drop(read);
        adapter
            .commit_certified_replica_write_set(
                super::certified_replica_write_capability(),
                writes,
                StorageWriteOptions {
                    preconditions,
                    await_durable: true,
                    ..StorageWriteOptions::default()
                },
            )
            .await?;
        self.notify_observers_for_sync();
        self.sync_mode_state().notify_sync_change();
        Ok(InitialSyncSnapshotInstall::Installed)
    }

    pub(crate) async fn push_sync_repository(
        &self,
        request: &SyncPushRequest,
    ) -> Result<SyncPushResponse, LixError> {
        Box::pin(self.import_sync_repository(request, SyncImportPurpose::AuthorityPush, None, None))
            .await
    }

    pub(crate) async fn import_sync_history_boundaries(
        &self,
        commits: &[SyncCommit],
        boundaries: &[SyncHistoryBoundary],
        rows: &[SyncSnapshotRow],
    ) -> Result<(), LixError> {
        Box::pin(self.import_sync_repository(
            &SyncPushRequest {
                commits: commits.to_vec(),
                ref_updates: Vec::new(),
                inline_blobs: Vec::new(),
            },
            SyncImportPurpose::History,
            Some((boundaries, rows)),
            None,
        ))
        .await?;
        Ok(())
    }

    pub(crate) async fn import_sync_history_headers(
        &self,
        headers: &[SyncCommitHeader],
    ) -> Result<(), LixError> {
        let mut parsed = BTreeMap::new();
        for header in headers {
            let header = ParsedSyncHeader::parse(header)?;
            if parsed.insert(header.commit_id, header).is_some() {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync history contains duplicate commit headers",
                ));
            }
        }
        validate_sync_header_set(&parsed, "sync history", &BTreeSet::new())?;
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let mut new_records = Vec::new();
        let mut writes = adapter.new_write_set();
        for header in parsed.values() {
            if let Some(existing) = load_commit_record(&read, header.commit_id).await? {
                if !header.matches_record(&existing) {
                    return Err(immutable_object_mismatch("commit", header.commit_id));
                }
                let existing_scope =
                    match load_published_commit_state_topology(&read, header.commit_id).await? {
                        Some(topology) => Some(topology.global_scope()),
                        None => deferred_commit_global_scope(&read, header.commit_id).await?,
                    };
                if existing_scope.is_some_and(|scope| scope != header.global_scope) {
                    return Err(immutable_object_mismatch("commit", header.commit_id));
                }
            } else {
                new_records.push(header.record());
                stage_commit_history_deferred_with_scope(
                    &mut writes,
                    header.commit_id,
                    header.global_scope,
                );
            }
        }
        if new_records.is_empty() {
            return Ok(());
        }
        ChangelogContext::new()
            .writer(&mut &read, &mut writes)
            .stage_certified_sparse_append(ChangelogAppend {
                commits: new_records,
                changes: Vec::new(),
            })
            .await?;
        let mut preconditions = Vec::new();
        crate::json_store::stage_json_publication_fence(&read, &mut writes, &mut preconditions)
            .await?;
        drop(read);
        adapter
            .commit_certified_replica_write_set(
                super::certified_replica_write_capability(),
                writes,
                StorageWriteOptions {
                    preconditions,
                    await_durable: true,
                    ..StorageWriteOptions::default()
                },
            )
            .await?;
        Ok(())
    }

    /// Authenticated authority admission: historical dependency objects may
    /// retain their original author only when their canonical body is known.
    pub async fn push_sync_repository_for_account(
        &self,
        request: &SyncPushRequest,
        account_id: &str,
    ) -> Result<SyncPushResponse, LixError> {
        Box::pin(self.import_sync_repository_for_account(
            request,
            SyncImportPurpose::AuthorityPush,
            None,
            None,
            Some(account_id),
        ))
        .await
    }

    async fn import_sync_repository(
        &self,
        request: &SyncPushRequest,
        purpose: SyncImportPurpose,
        history_boundaries: Option<(&[SyncHistoryBoundary], &[SyncSnapshotRow])>,
        replica_publication: Option<ReplicaStatePublication<'_>>,
    ) -> Result<SyncPushResponse, LixError> {
        self.import_sync_repository_for_account(
            request,
            purpose,
            history_boundaries,
            replica_publication,
            None,
        )
        .await
    }

    async fn import_sync_repository_for_account(
        &self,
        request: &SyncPushRequest,
        purpose: SyncImportPurpose,
        history_boundaries: Option<(&[SyncHistoryBoundary], &[SyncSnapshotRow])>,
        replica_publication: Option<ReplicaStatePublication<'_>>,
        expected_account_id: Option<&str>,
    ) -> Result<SyncPushResponse, LixError> {
        // Sync imports publish the same repository state that foreground
        // auto-commit and checkpoint transactions read. Serialize at this
        // direct writer boundary so a read that has entered its quiescent
        // retry cannot be expired repeatedly by the sync worker. Do not hold
        // this guard across network preparation or outbox construction.
        let _collaboration_guard = self.lock_collaboration_writes().await;
        if purpose == SyncImportPurpose::History && !request.ref_updates.is_empty() {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync history import cannot update refs",
            ));
        }
        let referenced_blob_ids = sync_commit_blob_ids(&request.commits)?;
        let mut inline_blob_ids = BTreeSet::new();
        for manifest in &request.inline_blobs {
            if !inline_blob_ids.insert(manifest.blob_id.clone()) {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!("sync request repeats inline blob '{}'", manifest.blob_id),
                ));
            }
            if !referenced_blob_ids.contains(&manifest.blob_id) {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync request includes unreferenced inline blob '{}'",
                        manifest.blob_id
                    ),
                ));
            }
            if manifest.inline_bytes_base64.is_none() {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync hot-path blob '{}' has no inline payload",
                        manifest.blob_id
                    ),
                ));
            }
        }
        let mut parsed = BTreeMap::new();
        for wire in &request.commits {
            let commit = ParsedCommit::parse(wire)?;
            if parsed.insert(commit.commit_id, commit).is_some() {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync push contains duplicate commit ids",
                ));
            }
        }
        let mut boundary_roots = BTreeMap::new();
        let mut boundary_rows = BTreeMap::<CommitId, Vec<ParsedSnapshotRow>>::new();
        let mut boundary_coordinates = BTreeSet::new();
        if let Some((boundaries, rows)) = history_boundaries {
            if purpose != SyncImportPurpose::History {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync snapshot boundaries are only valid for history import",
                ));
            }
            for boundary in boundaries {
                let commit_id =
                    CommitId::parse_lix(&boundary.commit_id, "sync history boundary commit id")?;
                let root = parse_sync_state_root_id(&boundary.live_state_root_id)?;
                if boundary_roots.insert(commit_id, root).is_some() {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync history contains duplicate boundaries",
                    ));
                }
            }
            for commit_id in boundary_roots.keys() {
                if !parsed.contains_key(commit_id) {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!("sync history boundary '{commit_id}' has no canonical commit body"),
                    ));
                }
                boundary_rows.insert(*commit_id, Vec::new());
            }
            for commit in parsed.values() {
                let external_parent = commit
                    .parent_commit_ids
                    .iter()
                    .any(|parent| !parsed.contains_key(parent));
                if external_parent && !boundary_roots.contains_key(&commit.commit_id) {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!(
                            "sync history commit '{}' has external topology but no boundary",
                            commit.commit_id
                        ),
                    ));
                }
            }
            for row in rows {
                let commit_id =
                    CommitId::parse_lix(&row.branch_id, "sync history boundary snapshot branch")?;
                let parsed_row = parse_snapshot_row(row)?;
                if !boundary_coordinates.insert((
                    commit_id,
                    parsed_row.schema_key.clone(),
                    parsed_row.file_id.clone(),
                    parsed_row.row_pk.clone(),
                )) {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "sync history boundary repeats a row coordinate",
                    ));
                }
                boundary_rows
                    .get_mut(&commit_id)
                    .ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            format!(
                                "sync history snapshot rows reference unrelated boundary '{commit_id}'"
                            ),
                        )
                    })?
                    .push(parsed_row);
            }
        }
        let mut parsed_refs = Vec::with_capacity(request.ref_updates.len());
        let mut branch_ids = Vec::with_capacity(request.ref_updates.len());
        let mut seen_branches = BTreeSet::new();
        for update in &request.ref_updates {
            RowPk::uuid_from_canonical(&update.branch_id).map_err(|error| {
                LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!("sync ref branchId is invalid: {error}"),
                )
            })?;
            if !seen_branches.insert(update.branch_id.clone()) {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync push contains duplicate branch ref updates",
                ));
            }
            let expected = update
                .expected_head_commit_id
                .as_deref()
                .map(|id| CommitId::parse_lix(id, "sync expected ref head"))
                .transpose()?;
            let expected_checkpoint = update
                .expected_checkpoint_commit_id
                .as_deref()
                .map(|id| CommitId::parse_lix(id, "sync expected checkpoint"))
                .transpose()?;
            let head = update
                .head_commit_id
                .as_deref()
                .map(|id| CommitId::parse_lix(id, "sync ref head"))
                .transpose()?;
            let checkpoint = update
                .checkpoint_commit_id
                .as_deref()
                .map(|id| CommitId::parse_lix(id, "sync ref checkpoint"))
                .transpose()?;
            if expected.is_some() != expected_checkpoint.is_some()
                || head.is_some() != checkpoint.is_some()
            {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync ref head and checkpoint coordinates must be paired",
                ));
            }
            branch_ids.push(update.branch_id.clone());
            parsed_refs.push((
                update.clone(),
                expected,
                expected_checkpoint,
                head,
                checkpoint,
            ));
        }

        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let default_branch_id = self.repository_default_branch_id_for_sync(&read).await?;
        if parsed_refs.iter().any(|(update, _, _, head, _)| {
            (update.branch_id == default_branch_id || update.branch_id == crate::GLOBAL_BRANCH_ID)
                && head.is_none()
        }) {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync push cannot delete the repository default or global branch",
            ));
        }
        if replica_publication
            .as_ref()
            .is_some_and(|publication| publication.reset_pending)
        {
            let admitted = branch_ids
                .iter()
                .map(String::as_str)
                .collect::<BTreeSet<_>>();
            if BranchHeadControlContext::new()
                .reader(&read)
                .scan()
                .await?
                .iter()
                .any(|(id, _)| !admitted.contains(id.as_str()))
            {
                return Err(LixError::new(
                    LixError::CODE_TRANSACTION_CONFLICT,
                    "local branch set changed during pending-state reset",
                ));
            }
        }
        let observations = BranchHeadControlContext::new()
            .reader(&read)
            .load_observed(&branch_ids)
            .await?;
        let mut changed_refs = Vec::new();
        for ((update, expected, expected_checkpoint, head, checkpoint), observation) in
            parsed_refs.iter().zip(&observations)
        {
            let current = observation.control.map(|control| control.head_commit_id);
            let current_checkpoint = observation
                .control
                .and_then(|control| control.working_diff_checkpoint_commit_id);
            if current == *head && current_checkpoint == *checkpoint {
                continue;
            }
            if current != *expected || current_checkpoint != *expected_checkpoint {
                return Err(LixError::new(
                    LixError::CODE_TRANSACTION_CONFLICT,
                    format!(
                        "sync ref '{}' expected coordinate ({:?}, {:?}), found ({:?}, {:?})",
                        update.branch_id,
                        expected.map(|id| id.to_string()),
                        expected_checkpoint.map(|id| id.to_string()),
                        current.map(|id| id.to_string()),
                        current_checkpoint.map(|id| id.to_string()),
                    ),
                ));
            }
            changed_refs.push((update.clone(), *head, *checkpoint));
        }

        // Ref CAS is the cheap, side-effect-free gate. Authority admission
        // requires complete local blob content; replica/history import only
        // requires the manifest registered by the transport's lazy-CAS lane.
        for commit in parsed.values() {
            for member in commit
                .members
                .iter()
                .filter(|member| member.schema_key == "lix_binary_blob_ref" && !member.deleted)
            {
                let blob_hash = member
                    .snapshot_json
                    .as_deref()
                    .and_then(|snapshot| serde_json::from_str::<serde_json::Value>(snapshot).ok())
                    .and_then(|snapshot| {
                        snapshot
                            .get("blob_hash")
                            .and_then(serde_json::Value::as_str)
                            .map(str::to_owned)
                    })
                    .ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            "live sync binary blob ref has no blob_hash",
                        )
                    })?;
                let available = inline_blob_ids.contains(&blob_hash)
                    || match purpose {
                        SyncImportPurpose::AuthorityPush => self
                            .get_sync_blob_manifest_with_collaboration_guard(&blob_hash)
                            .await?
                            .is_some(),
                        SyncImportPurpose::ReplicaDelta | SyncImportPurpose::History => {
                            self.has_sync_blob_manifest(&blob_hash).await?
                        }
                    };
                if !available {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!("sync commit references unavailable binary blob '{blob_hash}'"),
                    ));
                }
            }
        }

        let mut existing = BTreeSet::new();
        let mut deferred_existing = BTreeSet::new();
        let mut records = BTreeMap::<CommitId, CommitRecord>::new();
        let mut published_topologies = BTreeMap::new();
        for (commit_id, commit) in &parsed {
            match load_sync_commit(&read, *commit_id).await {
                Ok(Some(stored)) => {
                    let materialized_external_boundary =
                        boundary_rows.contains_key(commit_id) && commit.members.is_empty();
                    if stored != commit.wire && !materialized_external_boundary {
                        return Err(immutable_object_mismatch("commit", commit_id));
                    }
                    existing.insert(*commit_id);
                    records.insert(
                        *commit_id,
                        load_commit_record(&read, *commit_id)
                            .await?
                            .ok_or_else(|| {
                                LixError::new(
                                    LixError::CODE_INTERNAL_ERROR,
                                    format!("existing sync commit '{commit_id}' lost its record"),
                                )
                            })?,
                    );
                    published_topologies.insert(
                        *commit_id,
                        load_published_commit_state_topology(&read, *commit_id)
                            .await?
                            .ok_or_else(|| {
                                LixError::new(
                                    LixError::CODE_INTERNAL_ERROR,
                                    format!(
                                        "existing sync commit '{commit_id}' has no state authority"
                                    ),
                                )
                            })?,
                    );
                }
                Ok(None) => {
                    if expected_account_id.is_some_and(|account| account != commit.wire.account_id)
                    {
                        return Err(LixError::new(
                            "LIX_SYNC_ACCOUNT_MISMATCH",
                            "new sync commits must belong to the authenticated account",
                        ));
                    }
                }
                Err(error) if error.code == "LIX_SYNC_HISTORY_REQUIRED" => {
                    if expected_account_id.is_some_and(|account| account != commit.wire.account_id)
                    {
                        return Err(LixError::new(
                            "LIX_SYNC_ACCOUNT_MISMATCH",
                            "unknown sync commit bodies must belong to the authenticated account",
                        ));
                    }
                    let record = load_commit_record(&read, *commit_id)
                        .await?
                        .ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                format!("deferred sync commit '{commit_id}' lost its header"),
                            )
                        })?;
                    if record.is_checkpoint != commit.wire.is_checkpoint
                        || record.parent_commit_ids != commit.parent_commit_ids
                        || record.base_commit_id != commit.base_commit_id
                        || record.account_id != commit.account_id
                        || record.created_at != commit.created_at
                        || deferred_commit_global_scope(&read, *commit_id)
                            .await?
                            .is_some_and(|scope| scope != commit.wire.global_scope)
                    {
                        return Err(LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            format!(
                                "deferred sync commit '{commit_id}' body disagrees with its header"
                            ),
                        ));
                    }
                    records.insert(*commit_id, record);
                    deferred_existing.insert(*commit_id);
                }
                Err(error) => return Err(error),
            }
        }
        if purpose == SyncImportPurpose::History
            && parsed.keys().any(|commit_id| {
                !existing.contains(commit_id) && !deferred_existing.contains(commit_id)
            })
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "sync history hydration can only fill known deferred commit headers",
            ));
        }

        // Resolve every dependency outside this push before constructing the
        // write set. Internal dependencies are supplied by the staged maps.
        let dependencies = parsed
            .iter()
            .flat_map(|(commit_id, commit)| {
                commit
                    .parent_commit_ids
                    .iter()
                    .copied()
                    .chain(commit.base_commit_id)
                    .chain(
                        (!boundary_rows.contains_key(commit_id))
                            .then_some(commit.state_alias.as_ref())
                            .flatten()
                            .map(|(source, _)| *source),
                    )
            })
            .filter(|dependency| !parsed.contains_key(dependency))
            .collect::<BTreeSet<_>>();
        let required_external_topologies = parsed
            .iter()
            .filter(|(commit_id, _)| !boundary_rows.contains_key(commit_id))
            .flat_map(|(_, commit)| commit.dependencies())
            .filter(|dependency| !parsed.contains_key(dependency))
            .collect::<BTreeSet<_>>();
        for dependency in dependencies {
            records.insert(
                dependency,
                load_commit_record(&read, dependency)
                    .await?
                    .ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_COMMIT_NOT_FOUND,
                            format!("sync commit dependency '{dependency}' does not exist"),
                        )
                    })?,
            );
            if required_external_topologies.contains(&dependency) {
                published_topologies.insert(
                    dependency,
                    load_published_commit_state_topology(&read, dependency)
                        .await?
                        .ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                format!("sync dependency '{dependency}' has no state authority"),
                            )
                        })?,
                );
            }
        }
        for commit in parsed.values() {
            let Some(base_commit_id) = commit.base_commit_id else {
                continue;
            };
            let base_is_global = parsed
                .get(&base_commit_id)
                .map(|base| base.wire.global_scope)
                .or_else(|| {
                    published_topologies
                        .get(&base_commit_id)
                        .map(|topology| topology.global_scope())
                })
                .ok_or_else(|| {
                    LixError::new(
                        LixError::CODE_COMMIT_NOT_FOUND,
                        format!("sync base commit '{base_commit_id}' has no state authority"),
                    )
                })?;
            if !base_is_global {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!("sync base commit '{base_commit_id}' is not global"),
                ));
            }
        }
        for (_, _, _, head, checkpoint) in &parsed_refs {
            if let Some(head) = head
                && !parsed.contains_key(head)
                && !records.contains_key(head)
            {
                records.insert(
                    *head,
                    load_commit_record(&read, *head).await?.ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_COMMIT_NOT_FOUND,
                            format!("sync ref target '{head}' does not exist"),
                        )
                    })?,
                );
            }
            if let Some(checkpoint) = checkpoint
                && !parsed.contains_key(checkpoint)
                && !records.contains_key(checkpoint)
            {
                records.insert(
                    *checkpoint,
                    load_commit_record(&read, *checkpoint)
                        .await?
                        .ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_COMMIT_NOT_FOUND,
                                format!("sync ref checkpoint '{checkpoint}' does not exist"),
                            )
                        })?,
                );
            }
        }
        for (update, _, _, head, checkpoint) in &parsed_refs {
            if update.branch_id != crate::GLOBAL_BRANCH_ID {
                continue;
            }
            for target in [head, checkpoint].into_iter().flatten() {
                let (global_scope, base_commit_id) = if let Some(commit) = parsed.get(target) {
                    (commit.wire.global_scope, commit.base_commit_id)
                } else {
                    let record = records.get(target).ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_COMMIT_NOT_FOUND,
                            format!("sync global ref target '{target}' does not exist"),
                        )
                    })?;
                    let global_scope = load_published_commit_state_topology(&read, *target)
                        .await?
                        .map(|topology| topology.global_scope())
                        .or(deferred_commit_global_scope(&read, *target).await?)
                        .unwrap_or(false);
                    (global_scope, record.base_commit_id)
                };
                if !global_scope || base_commit_id.is_some() {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!(
                            "sync global branch target '{target}' is not a base-native global commit"
                        ),
                    ));
                }
            }
        }

        let mut writes = adapter.new_write_set();
        let mut preconditions = Vec::new();
        for (commit_id, commit) in &parsed {
            if !existing.contains(commit_id)
                && let Some(alias) = &commit.wire.state_alias
            {
                stage_materialized_sync_state_alias(&mut writes, *commit_id, alias)?;
            }
        }
        for manifest in &request.inline_blobs {
            super::blob::stage_inline_sync_blob(&mut writes, manifest)?;
        }
        if !request.inline_blobs.is_empty() {
            crate::binary_cas::stage_transfer_publication_fence(
                &read,
                &mut writes,
                &mut preconditions,
            )
            .await?;
        }
        for commit_id in parsed.keys().copied() {
            stage_commit_history_available(&mut writes, commit_id);
        }

        // Every protocol commit is a root fence. Build roots first with one
        // writer so children can use parents staged earlier in this request.
        // Ordinary and merge membership is the complete logical delta relative
        // to the first parent. A metadata-only checkpoint instead carries an
        // authenticated complete-state alias and no members; its semantic
        // parent and physical source are distinct dependency edges.
        let mut imported_roots = BTreeMap::new();
        let mut root_remaining = parsed
            .keys()
            .filter(|commit_id| !existing.contains(commit_id))
            .copied()
            .collect::<BTreeSet<_>>();
        let external_first_parents = root_remaining
            .iter()
            .filter(|commit_id| !boundary_rows.contains_key(commit_id))
            .filter_map(|commit_id| parsed[commit_id].parent_commit_ids.first().copied())
            .filter(|parent| !root_remaining.contains(parent))
            .collect::<BTreeSet<_>>();
        let mut materialized_parent_roots = BTreeMap::new();
        for parent in external_first_parents {
            let rooted = load_commit_state_manifest(&read, parent)
                .await?
                .is_some_and(|manifest| manifest.snapshot_root.is_some());
            if !rooted {
                let mut tracked = TrackedStateContext::new().reader(&read);
                let rows = tracked
                    .scan_batch_at_commit(&parent.to_string(), &TrackedStateScanRequest::default())
                    .await?;
                materialized_parent_roots.insert(parent, rows);
            }
        }
        let tracked_context = TrackedStateContext::new();
        let mut tracked_writer = tracked_context.writer(&read, &mut writes);
        for (parent, rows) in &materialized_parent_roots {
            let deltas = rows.iter().map(|row| TrackedStateDeltaRef {
                schema_key: row.schema_key(),
                file_id: row.file_id(),
                row_pk: row.row_pk(),
                change_id: row.change_id(),
                commit_id: row.commit_id(),
                deleted: row.deleted(),
                created_at: row.created_at(),
                updated_at: row.updated_at(),
            });
            tracked_writer
                .stage_commit_root(&parent.to_string(), None, deltas)
                .await?;
        }
        while !root_remaining.is_empty() {
            let ready = root_remaining.iter().copied().find(|commit_id| {
                if boundary_rows.contains_key(commit_id) {
                    return true;
                }
                let commit = &parsed[commit_id];
                let first_parent_ready = commit.parent_commit_ids.first().is_none_or(|parent| {
                    !root_remaining.contains(parent) || imported_roots.contains_key(parent)
                });
                let alias_source_ready = commit.state_alias.as_ref().is_none_or(|(source, _)| {
                    !root_remaining.contains(source) || imported_roots.contains_key(source)
                });
                first_parent_ready && alias_source_ready
            });
            let Some(commit_id) = ready else {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync root dependency graph contains a cycle",
                ));
            };
            let commit = &parsed[&commit_id];
            let state_parent_commit_id =
                commit.parent_commit_ids.first().copied().filter(|parent| {
                    commit.wire.global_scope
                        || !parsed
                            .get(parent)
                            .map(|parent| parent.wire.global_scope)
                            .or_else(|| {
                                published_topologies
                                    .get(parent)
                                    .map(|topology| topology.global_scope())
                            })
                            .or_else(|| {
                                records
                                    .get(parent)
                                    .map(|record| record.base_commit_id.is_none())
                            })
                            .unwrap_or(false)
                });
            let parent = if boundary_rows.contains_key(&commit_id) {
                None
            } else {
                state_parent_commit_id.map(|parent| parent.to_string())
            };
            let root_deltas = if let Some(rows) = boundary_rows.get(&commit_id) {
                rows.iter()
                    .map(ParsedSnapshotRow::as_root_delta)
                    .collect::<Vec<_>>()
            } else {
                commit
                    .members
                    .iter()
                    .map(|member| member.as_root_delta(commit_id))
                    .collect::<Vec<_>>()
            };
            if boundary_rows.contains_key(&commit_id) {
                tracked_writer
                    .stage_commit_root(&commit_id.to_string(), None, root_deltas)
                    .await?;
            } else if let Some((source_commit_id, _)) = &commit.state_alias {
                tracked_writer
                    .stage_complete_state_alias(commit_id, *source_commit_id)
                    .await?;
            } else {
                tracked_writer
                    .stage_commit_root(&commit_id.to_string(), parent.as_deref(), root_deltas)
                    .await?;
            }
            let mut root = tracked_writer
                .staged_commit_roots()
                .find(|root| root.commit_id == commit_id)
                .cloned()
                .ok_or_else(|| LixError::unknown("sync import did not stage its commit root"))?;
            if !boundary_rows.contains_key(&commit_id)
                && let Some((_, expected_root)) = &commit.state_alias
                && &root.root_id != expected_root
            {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync complete-state alias for '{commit_id}' does not match its source root"
                    ),
                ));
            }
            if commit.state_alias.is_none()
                && !boundary_rows.contains_key(&commit_id)
                && root.parent_roots.first().map(|root| root.commit_id) != state_parent_commit_id
            {
                return Err(LixError::unknown(format!(
                    "sync import root '{commit_id}' did not retain physical overlay parent '{state_parent_commit_id:?}'",
                )));
            }
            if boundary_rows.contains_key(&commit_id) {
                let expected_root = &boundary_roots[&commit_id];
                if &root.root_id != expected_root {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!(
                            "sync history boundary rows for '{commit_id}' do not match liveStateRootId"
                        ),
                    ));
                }
                root.changed_key_count = u64::try_from(commit.members.len())
                    .map_err(|_| LixError::unknown("sync history mutation count exceeds u64"))?;
                root.complete_state_fence = true;
                debug_assert!(root.parent_roots.is_empty());
            }
            imported_roots.insert(commit_id, root);
            root_remaining.remove(&commit_id);
        }
        if purpose == SyncImportPurpose::AuthorityPush {
            let authored_by_change = parsed
                .values()
                .flat_map(|commit| commit.members.iter())
                .filter(|member| member.authored)
                .map(|member| (member.change_id, member))
                .collect::<BTreeMap<_, _>>();
            for commit in parsed.values() {
                let selected = commit
                    .members
                    .iter()
                    .filter(|member| !member.authored)
                    .collect::<Vec<_>>();
                if selected.is_empty() {
                    continue;
                }
                let source = if commit.parent_commit_ids.len() > 1 {
                    let source_id = commit.selected_source_commit_id.ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            format!("sync merge '{}' has no selected source", commit.commit_id),
                        )
                    })?;
                    let keys = selected
                        .iter()
                        .map(|member| TrackedStateKey {
                            schema_key: member.schema_key.clone(),
                            file_id: member.file_id.clone(),
                            row_pk: member.row_pk.clone(),
                        })
                        .collect::<Vec<_>>();
                    let values =
                        if parsed.contains_key(&source_id) && !existing.contains(&source_id) {
                            tracked_writer
                                .root_values_at_commit(source_id, &keys)
                                .await?
                        } else {
                            TrackedStateContext::new()
                                .reader(&read)
                                .index_values_at_commit(&source_id.to_string(), &keys)
                                .await?
                        };
                    Some((source_id, values))
                } else {
                    None
                };
                for (index, member) in selected.iter().enumerate() {
                    if let Some((source_id, source_values)) = &source {
                        let source_value = source_values[index].as_ref().ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INVALID_PARAM,
                                format!(
                                    "sync merge '{}' selects a row absent from source '{}'",
                                    commit.commit_id, source_id
                                ),
                            )
                        })?;
                        if source_value.change_id != member.change_id
                            || source_value.deleted != member.deleted
                            || source_value.created_at != member.row_created_at
                            || source_value.updated_at != member.row_updated_at
                        {
                            return Err(LixError::new(
                                LixError::CODE_INVALID_PARAM,
                                format!(
                                    "sync merge '{}' selected row disagrees with source '{}'",
                                    commit.commit_id, source_id
                                ),
                            ));
                        }
                    }
                    // A non-merge checkpoint is a complete, source-less state
                    // selection. Its member payload is the protocol authority;
                    // requiring every selected change body to have arrived in
                    // an earlier push recreates an ordering-only side channel.
                    if source.is_none() {
                        continue;
                    }
                    if let Some(authored) = authored_by_change.get(&member.change_id) {
                        if !selected_payload_matches_authored(member, authored) {
                            return Err(LixError::new(
                                LixError::CODE_INVALID_PARAM,
                                format!(
                                    "sync commit '{}' selected payload disagrees with its authored change",
                                    commit.commit_id
                                ),
                            ));
                        }
                        continue;
                    }
                    let change = load_existing_sync_change(&read, member.change_id)
                        .await?
                        .ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INVALID_PARAM,
                                format!(
                                    "sync commit '{}' selected change '{}' is unavailable",
                                    commit.commit_id, member.change_id
                                ),
                            )
                        })?;
                    if change.account_id != member.change_account_id
                        || change.created_at != member.change_created_at
                        || change.origin_key != member.origin_key
                    {
                        return Err(LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            format!(
                                "sync commit '{}' selected change metadata disagrees with its source",
                                commit.commit_id
                            ),
                        ));
                    }
                    let (_, payload) = materialize_known_change_payloads_in_order(
                        std::iter::once(change),
                        ChangeRecordProjection::full(),
                    )?
                    .into_iter()
                    .next()
                    .expect("one selected change materializes once");
                    let identity = payload.identity.expect("full projection has identity");
                    if identity.schema_key != member.schema_key
                        || identity.file_id != member.file_id
                        || identity.row_pk != member.row_pk
                        || payload.snapshot_content.as_deref() != member.snapshot_json.as_deref()
                        || payload.metadata.as_deref() != member.metadata_json.as_deref()
                    {
                        return Err(LixError::new(
                            LixError::CODE_INVALID_PARAM,
                            format!(
                                "sync commit '{}' selected payload disagrees with source change '{}'",
                                commit.commit_id, member.change_id
                            ),
                        ));
                    }
                }
            }
        }
        drop(tracked_writer);

        let mut staged_manifests = BTreeMap::<CommitId, StagedCommitStateManifest>::new();
        let mut row_pk_index_overlay = TrackedStateChunkOverlay::new();
        let mut appended_records = Vec::new();
        let mut appended_changes = BTreeMap::<ChangeId, ChangeRecord>::new();
        for row in boundary_rows.values().flatten() {
            let change = row.change_record();
            match load_existing_sync_change(&read, change.change_id).await? {
                Some(existing) if existing != change => {
                    return Err(immutable_object_mismatch("change", change.change_id));
                }
                Some(_) => {}
                None => match appended_changes.entry(change.change_id) {
                    std::collections::btree_map::Entry::Vacant(entry) => {
                        entry.insert(change);
                    }
                    std::collections::btree_map::Entry::Occupied(entry)
                        if entry.get() == &change => {}
                    std::collections::btree_map::Entry::Occupied(_) => {
                        return Err(immutable_object_mismatch("change", change.change_id));
                    }
                },
            }
        }
        let mut newly_imported = Vec::new();
        let mut selected_fallback_locators = BTreeMap::new();
        let mut authored_locators = BTreeMap::new();
        let mut imported_authored_change_ids = BTreeSet::new();
        let mut remaining = parsed
            .keys()
            .filter(|commit_id| !existing.contains(commit_id))
            .copied()
            .collect::<BTreeSet<_>>();
        while !remaining.is_empty() {
            let ready = remaining.iter().copied().find(|commit_id| {
                if boundary_rows.contains_key(commit_id) {
                    return true;
                }
                parsed[commit_id].dependencies().all(|dependency| {
                    if parsed.contains_key(&dependency) && !existing.contains(&dependency) {
                        staged_manifests.contains_key(&dependency)
                    } else {
                        records.contains_key(&dependency)
                    }
                })
            });
            let Some(commit_id) = ready else {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "sync commit graph contains a cycle",
                ));
            };
            let commit = &parsed[&commit_id];
            // Commit membership comes only from the canonical body. Boundary
            // rows certify a complete state root but never redefine a delta.
            let mutations = stage_imported_commit_body(
                &mut writes,
                commit,
                &mut imported_authored_change_ids,
                &mut selected_fallback_locators,
                &mut authored_locators,
            )?;
            for member in &commit.members {
                let change = member.change_record();
                match load_existing_sync_change(&read, change.change_id).await? {
                    Some(existing) if !sync_change_records_equal(&existing, &change)? => {
                        return Err(immutable_object_mismatch("change", change.change_id));
                    }
                    Some(_) => {}
                    None => match appended_changes.entry(change.change_id) {
                        std::collections::btree_map::Entry::Vacant(entry) => {
                            entry.insert(change);
                        }
                        std::collections::btree_map::Entry::Occupied(entry)
                            if entry.get() == &change => {}
                        std::collections::btree_map::Entry::Occupied(_) => {
                            return Err(immutable_object_mismatch("change", change.change_id));
                        }
                    },
                }
            }
            let touched_scope_digest = if commit.state_alias.is_some() {
                CommitTouchedScopeDigest::opaque()
            } else {
                match commit_delta_member_scopes(commit_id, &mutations)? {
                    Some(scopes) => CommitTouchedScopeDigest::exact(scopes.iter()),
                    None => CommitTouchedScopeDigest::opaque(),
                }
            };
            let row_pk_base_commit_id = if boundary_rows.contains_key(&commit_id) {
                None
            } else {
                commit
                    .state_alias
                    .as_ref()
                    .map(|(source_commit_id, _)| *source_commit_id)
                    .or_else(|| {
                        commit.parent_commit_ids.first().copied().filter(|parent| {
                            commit.wire.global_scope
                                || !parsed
                                    .get(parent)
                                    .map(|parent| parent.wire.global_scope)
                                    .or_else(|| {
                                        published_topologies
                                            .get(parent)
                                            .map(|topology| topology.global_scope())
                                    })
                                    .or_else(|| {
                                        records
                                            .get(parent)
                                            .map(|record| record.base_commit_id.is_none())
                                    })
                                    .unwrap_or(false)
                        })
                    })
            };
            let row_pk_base_root = row_pk_base_commit_id.and_then(|base_id| {
                staged_manifests
                    .get(&base_id)
                    .and_then(|manifest| manifest.row_pk_index_root_id.as_ref())
                    .or_else(|| {
                        published_topologies
                            .get(&base_id)
                            .and_then(|manifest| manifest.row_pk_index_root_id())
                    })
            });
            if row_pk_base_commit_id.is_some() && row_pk_base_root.is_none() {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!(
                        "sync commit '{commit_id}' has no row-PK index for serving base '{}'",
                        row_pk_base_commit_id.expect("checked above")
                    ),
                ));
            }
            let row_pk_index_root_id = if let Some(rows) = boundary_rows.get(&commit_id) {
                stage_row_pk_index_from_deltas(
                    &read,
                    &mut writes,
                    &mut row_pk_index_overlay,
                    rows.iter().map(ParsedSnapshotRow::as_root_delta),
                    commit_id,
                )
                .await?
            } else {
                let staged_segments =
                    staged_commit_delta_segment_bytes(&writes, commit_id, &mutations)?;
                let row_pk_members = staged_commit_delta_members(
                    &read,
                    commit_id,
                    &commit.account_id,
                    &mutations,
                    staged_segments,
                )
                .await?;
                stage_row_pk_index_from_members(
                    &read,
                    &mut writes,
                    &mut row_pk_index_overlay,
                    row_pk_base_root,
                    &row_pk_members,
                    commit_id,
                )
                .await?
            };
            let staged_manifest = if boundary_rows.contains_key(&commit_id) {
                stage_commit_state_manifest_with_handle(
                    &mut writes,
                    &CommitStateManifest {
                        commit_id,
                        change_account_id: commit.account_id.clone(),
                        replay_debt: CommitStateReplayDebt::default(),
                        mutations,
                        touched_scope_filter: incomplete_touched_scope_filter(),
                        global_scope: commit.wire.global_scope,
                        current_state_scoped_ranges: None,
                        row_pk_index_root_id,
                        snapshot_root: Some(Box::new(
                            imported_roots
                                .remove(&commit_id)
                                .expect("every history boundary staged a root"),
                        )),
                    },
                )?
            } else {
                let parent_inputs = commit
                    .parent_commit_ids
                    .iter()
                    .map(|parent| {
                        staged_manifests
                            .get(parent)
                            .map(CertifiedCommitStateTopologyParent::Staged)
                            .or_else(|| {
                                published_topologies
                                    .get(parent)
                                    .map(CertifiedCommitStateTopologyParent::PublishedTopology)
                            })
                            .ok_or_else(|| {
                                LixError::new(
                                    LixError::CODE_INTERNAL_ERROR,
                                    format!("sync parent '{parent}' lost its state authority"),
                                )
                            })
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                let publication = if let Some((source_commit_id, _)) = commit.state_alias {
                    let source = staged_manifests
                        .get(&source_commit_id)
                        .map(CertifiedCommitStateTopologyParent::Staged)
                        .or_else(|| {
                            published_topologies
                                .get(&source_commit_id)
                                .map(CertifiedCommitStateTopologyParent::PublishedTopology)
                        })
                        .ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                format!(
                                    "sync complete-state source '{source_commit_id}' lost its state authority"
                                ),
                            )
                        })?;
                    stage_current_state_scoped_ranges_from_complete_state_source(
                        &read,
                        &mut writes,
                        &parent_inputs,
                        source,
                        commit_id,
                        &commit.account_id,
                        &mutations,
                    )
                    .await?
                } else {
                    stage_current_state_scoped_ranges_from_topology(
                        &read,
                        &mut writes,
                        &parent_inputs,
                        None,
                        commit_id,
                        &commit.account_id,
                        &mutations,
                    )
                    .await?
                };
                let manifest = CommitStateManifest {
                    commit_id,
                    change_account_id: commit.account_id.clone(),
                    replay_debt: CommitStateReplayDebt::default(),
                    mutations,
                    touched_scope_filter: publication.touched_scope_filter().clone(),
                    global_scope: commit.wire.global_scope,
                    current_state_scoped_ranges: publication.root(),
                    row_pk_index_root_id,
                    snapshot_root: Some(Box::new(
                        imported_roots
                            .remove(&commit_id)
                            .expect("every new sync commit staged a root"),
                    )),
                };
                stage_certified_commit_state_manifest_with_handle(
                    &mut writes,
                    &manifest,
                    &publication,
                )?
            };

            let generation = commit
                .parent_commit_ids
                .iter()
                .map(|parent| records[parent].generation)
                .max()
                .map_or(Ok(0), |generation| {
                    generation
                        .checked_add(1)
                        .ok_or_else(|| LixError::unknown("sync commit generation overflow"))
                })?;
            if let Some(parent) = commit.parent_commit_ids.first()
                && commit.parent_commit_ids.len() == 1
            {
                let jump = records[parent].first_parent_jump_commit_id;
                let missing_jump_record = match records.get(&jump) {
                    Some(_) => None,
                    None => Some(load_commit_record(&read, jump).await?.ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INTERNAL_ERROR,
                            format!("sync parent jump target '{jump}' is missing"),
                        )
                    })?),
                };
                if let Some(jump_record) = missing_jump_record {
                    records.insert(jump, jump_record);
                }
            }
            let parent_record = match commit.parent_commit_ids.as_slice() {
                [parent] => Some(&records[parent]),
                _ => None,
            };
            let parent_jump =
                parent_record.map(|parent| &records[&parent.first_parent_jump_commit_id]);
            let first_parent_jump = next_first_parent_jump(
                commit_id,
                &commit.parent_commit_ids,
                parent_record,
                parent_jump,
            )?;
            let record = CommitRecord {
                is_checkpoint: commit.wire.is_checkpoint,
                format_version: COMMIT_RECORD_FORMAT_VERSION,
                commit_id,
                generation,
                parent_commit_ids: commit.parent_commit_ids.clone(),
                base_commit_id: commit.base_commit_id,
                first_parent_jump_commit_id: first_parent_jump.0,
                first_parent_jump_span: first_parent_jump.1,
                account_id: commit.account_id.clone(),
                created_at: commit.created_at,
                touched_scope_digest,
            };
            if deferred_existing.contains(&commit_id) {
                let certified = records
                    .get(&commit_id)
                    .expect("deferred body retained its certified header");
                if certified.is_checkpoint != record.is_checkpoint
                    || certified.generation != record.generation
                    || certified.parent_commit_ids != record.parent_commit_ids
                    || certified.first_parent_jump_commit_id != record.first_parent_jump_commit_id
                    || certified.first_parent_jump_span != record.first_parent_jump_span
                    || certified.account_id != record.account_id
                    || certified.created_at != record.created_at
                {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        format!(
                            "sync history body '{commit_id}' disagrees with its certified topology"
                        ),
                    ));
                }
            }
            if !deferred_existing.contains(&commit_id) {
                preconditions.push(StoragePrecondition::KeyAbsent {
                    space: COMMIT_SPACE,
                    key: StorageKey(Bytes::from(commit_key(commit_id))),
                });
            }
            records.insert(commit_id, record.clone());
            staged_manifests.insert(commit_id, staged_manifest);
            if !deferred_existing.contains(&commit_id) {
                appended_records.push(record);
                newly_imported.push(commit_id.to_string());
            }
            remaining.remove(&commit_id);
        }

        selected_fallback_locators
            .retain(|change_id, _| !imported_authored_change_ids.contains(change_id));
        stage_missing_selected_change_locators(
            &read,
            &mut writes,
            &mut preconditions,
            selected_fallback_locators,
        )
        .await?;
        stage_change_locators(
            &mut writes,
            &authored_locators.into_values().collect::<Vec<_>>(),
        );

        for (update, head, _) in &changed_refs {
            let Some(head) = head else {
                continue;
            };
            let record = &records[head];
            let change = sync_ref_change_record(
                &update.branch_id,
                *head,
                &record.account_id,
                record.created_at,
            )?;
            match load_existing_sync_change(&read, change.change_id).await? {
                Some(existing) if !sync_change_records_equal(&existing, &change)? => {
                    return Err(immutable_object_mismatch(
                        "branch ref change",
                        change.change_id,
                    ));
                }
                Some(_) => {}
                None => {
                    appended_changes.insert(change.change_id, change);
                }
            }
        }

        if !appended_records.is_empty() || !appended_changes.is_empty() {
            ChangelogContext::new()
                .writer(&mut &read, &mut writes)
                .stage_append(ChangelogAppend {
                    commits: appended_records,
                    changes: appended_changes.into_values().collect(),
                })
                .await?;
        }

        let hydrated_history = !deferred_existing.is_empty();
        // A direct, authored fast-forward already has every immutable object,
        // payload, and root staged in this write set. Publishing those objects
        // merely so the hot-head writer can read them back in a second durable
        // transaction adds a crash boundary without adding validation. Derive
        // the hot delta from the authenticated child commit and let the branch
        // control CAS publish commit, head, and replica receipt atomically.
        let certified_replica_delta =
            purpose == SyncImportPurpose::ReplicaDelta && replica_publication.is_some();
        let atomic_fast_forward = !certified_replica_delta
            && !changed_refs.is_empty()
            && changed_refs.iter().all(|(update, head, checkpoint)| {
                let observation_index = branch_ids
                    .iter()
                    .position(|branch_id| branch_id == &update.branch_id)
                    .expect("changed ref came from request");
                let Some(previous) = observations[observation_index].control else {
                    return false;
                };
                let Some(head) = head else {
                    return false;
                };
                let Some(commit) = parsed.get(head) else {
                    return false;
                };
                !existing.contains(head)
                    && commit.parent_commit_ids.as_slice() == [previous.head_commit_id]
                    && commit.members.iter().all(|member| member.authored)
                    && previous.working_diff_checkpoint_commit_id == *checkpoint
            });
        // Immutable commits and roots are safe to publish before a ref. This
        // makes the second transaction a small atomic `(head, checkpoint)`
        // publication whose hash-guided hot-state diff can read both roots.
        // A failed CAS can leave only unreachable immutable objects.
        let (read, mut writes, mut preconditions, observations) = if !atomic_fast_forward
            && !changed_refs.is_empty()
            && (!newly_imported.is_empty() || hydrated_history)
        {
            crate::json_store::stage_json_publication_fence(&read, &mut writes, &mut preconditions)
                .await?;
            drop(read);
            let options = StorageWriteOptions {
                preconditions,
                await_durable: true,
                ..StorageWriteOptions::default()
            };
            if self.sync_mode_state().role() == super::SyncRole::Replica
                && purpose != SyncImportPurpose::AuthorityPush
            {
                adapter
                    .commit_certified_replica_write_set(
                        super::certified_replica_write_capability(),
                        writes,
                        options,
                    )
                    .await?;
            } else {
                adapter.commit_write_set(writes, options).await?;
            }
            let read = adapter.begin_read(StorageReadOptions::default()).await?;
            let observations = BranchHeadControlContext::new()
                .reader(&read)
                .load_observed(&branch_ids)
                .await?;
            (read, adapter.new_write_set(), Vec::new(), observations)
        } else {
            (read, writes, preconditions, observations)
        };

        let mut published_ref_updates = Vec::new();
        for (update, head, checkpoint) in &changed_refs {
            let observation_index = branch_ids
                .iter()
                .position(|branch_id| branch_id == &update.branch_id)
                .expect("changed ref came from request");
            let observation = &observations[observation_index];
            let current_head = observation.control.map(|control| control.head_commit_id);
            let current_checkpoint = observation
                .control
                .and_then(|control| control.working_diff_checkpoint_commit_id);
            if current_head == *head && current_checkpoint == *checkpoint {
                continue;
            }
            let expected_head = update
                .expected_head_commit_id
                .as_deref()
                .map(|id| CommitId::parse_lix(id, "sync expected ref head"))
                .transpose()?;
            let expected_checkpoint = update
                .expected_checkpoint_commit_id
                .as_deref()
                .map(|id| CommitId::parse_lix(id, "sync expected checkpoint"))
                .transpose()?;
            if current_head != expected_head || current_checkpoint != expected_checkpoint {
                return Err(LixError::new(
                    LixError::CODE_TRANSACTION_CONFLICT,
                    format!(
                        "sync ref '{}' changed while immutable commits were admitted",
                        update.branch_id
                    ),
                ));
            }
            preconditions.push(branch_head_control_precondition(
                &update.branch_id,
                observation.raw_token.clone(),
            )?);
            let Some(head) = head else {
                stage_delete_branch_head_control(&mut writes, &update.branch_id)?;
                published_ref_updates.push(update.clone());
                continue;
            };
            let checkpoint = checkpoint.ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    format!(
                        "sync ref '{}' has a head but no checkpoint",
                        update.branch_id
                    ),
                )
            })?;
            let previous = observation.control;
            let current_diff = if let Some(previous) = previous
                && previous.working_diff_checkpoint_commit_id == Some(checkpoint)
                && !atomic_fast_forward
            {
                Some(
                    TrackedStateContext::new()
                        .reader(&read)
                        .diff_commits(
                            &previous.head_commit_id.to_string(),
                            &head.to_string(),
                            &TrackedStateDiffRequest::default(),
                        )
                        .await?,
                )
            } else {
                None
            };
            // A server-wins reset can remove a locally created row entirely.
            // Such absence has no authoritative tombstone/change identity to
            // patch into the old generation. Rebuild the target generation on
            // this exceptional path so no discarded local row remains visible.
            let requires_complete_reset = current_diff
                .as_ref()
                .is_some_and(|diff| diff.entries.iter().any(|entry| entry.after.is_none()));
            let (generation, coverage) = if let Some(previous) = previous
                && previous.working_diff_checkpoint_commit_id == Some(checkpoint)
                && !requires_complete_reset
            {
                let epoch = TrackedHeadContext::new()
                    .reader(&read)
                    .working_diff_epoch(&update.branch_id)
                    .await?
                    .ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INTERNAL_ERROR,
                            format!(
                                "sync branch '{}' has a checkpoint cursor but no working-diff epoch",
                                update.branch_id
                            ),
                        )
                    })?;
                if epoch.checkpoint_commit_id != checkpoint
                    || epoch.generation != previous.tracked_generation
                {
                    return Err(LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!(
                            "sync branch '{}' has a stale working-diff epoch",
                            update.branch_id
                        ),
                    ));
                }
                let mut coverage = epoch.coverage;
                let generation = if atomic_fast_forward {
                    let commit = parsed
                        .get(head)
                        .expect("atomic fast-forward target was validated");
                    let keys = commit
                        .members
                        .iter()
                        .map(|member| TrackedStateKey {
                            schema_key: member.schema_key.clone(),
                            file_id: member.file_id.clone(),
                            row_pk: member.row_pk.clone(),
                        })
                        .collect::<Vec<_>>();
                    let before = TrackedStateContext::new()
                        .reader(&read)
                        .index_values_at_commit(&previous.head_commit_id.to_string(), &keys)
                        .await?;
                    let absence_guards = keys
                        .iter()
                        .zip(before)
                        .filter_map(|(key, before)| {
                            before
                                .as_ref()
                                .is_none_or(|before| before.deleted)
                                .then(|| key.clone())
                        })
                        .collect::<BTreeSet<_>>();
                    let deltas = commit
                        .members
                        .iter()
                        .map(|member| member.as_current_delta(*head))
                        .collect::<Vec<_>>();
                    stage_sync_hot_delta(
                        &read,
                        &mut writes,
                        &update.branch_id,
                        previous.tracked_generation,
                        *head,
                        &deltas,
                        &absence_guards,
                        checkpoint,
                        &mut coverage,
                    )
                    .await?
                } else {
                    let diff = current_diff
                        .as_ref()
                        .expect("incremental replica diff was loaded");
                    let mut deltas = Vec::with_capacity(diff.entries.len());
                    let mut absence_guards = BTreeSet::new();
                    for entry in &diff.entries {
                        let after = entry.after.as_ref().ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                "sync tracked-state diff removed a row without a tombstone",
                            )
                        })?;
                        let payload = diff.payloads().get(after.change_id).ok_or_else(|| {
                            LixError::new(
                                LixError::CODE_INTERNAL_ERROR,
                                format!("sync diff lost payload for change '{}'", after.change_id),
                            )
                        })?;
                        if entry.visible_before().is_none() {
                            absence_guards.insert(TrackedStateKey {
                                schema_key: entry.identity.schema_key().to_owned(),
                                file_id: entry.identity.file_id().map(str::to_owned),
                                row_pk: entry.identity.row_pk().clone(),
                            });
                        }
                        deltas.push(CurrentStateDeltaRef {
                            schema_key: entry.identity.schema_key(),
                            file_id: entry.identity.file_id(),
                            row_pk: entry.identity.row_pk(),
                            change_id: Some(after.change_id),
                            commit_id: Some(after.commit_id),
                            untracked: false,
                            deleted: after.deleted,
                            created_at: after.created_at,
                            updated_at: after.updated_at,
                            // A collection marker and its cascade removals
                            // can share a payload key; deleted rows never copy
                            // the live marker's snapshot or metadata.
                            snapshot: if after.deleted {
                                None
                            } else {
                                payload.snapshot
                            },
                            metadata: if after.deleted {
                                None
                            } else {
                                payload.metadata
                            },
                            columnar_base_coordinate: None,
                        });
                    }
                    stage_sync_hot_delta(
                        &read,
                        &mut writes,
                        &update.branch_id,
                        previous.tracked_generation,
                        *head,
                        &deltas,
                        &absence_guards,
                        checkpoint,
                        &mut coverage,
                    )
                    .await?
                };
                (generation, coverage)
            } else {
                let current = load_sync_hot_snapshot(&read, &update.branch_id, *head).await?;
                let checkpoint_snapshot =
                    load_sync_hot_snapshot(&read, &update.branch_id, checkpoint).await?;
                let generation = CommitId::with_change_address_space(uuid::Uuid::now_v7());
                let mut coverage = WorkingDiffIndexCoverage::default();
                TrackedHeadContext::new()
                    .writer(&read, &mut writes)
                    .stage_complete_current_state_with_working_diff(
                        &update.branch_id,
                        generation,
                        current,
                        previous.map(|control| control.tracked_generation),
                        &[],
                        &[],
                        &BTreeSet::new(),
                        if *head == checkpoint {
                            CompleteWorkingDiffMode::ResetClean
                        } else {
                            CompleteWorkingDiffMode::Rebase {
                                checkpoint_commit_id: checkpoint,
                                checkpoint: checkpoint_snapshot,
                            }
                        },
                        &mut coverage,
                    )
                    .await?;
                (generation, coverage)
            };
            stage_tracked_working_diff_epoch(
                &mut writes,
                &update.branch_id,
                TrackedWorkingDiffEpoch {
                    checkpoint_commit_id: checkpoint,
                    generation,
                    coverage,
                },
            )?;
            let head_record = records.get(head).ok_or_else(|| {
                LixError::new(
                    LixError::CODE_COMMIT_NOT_FOUND,
                    format!("sync ref target '{head}' does not exist"),
                )
            })?;
            let mut control = BranchHeadControl {
                head_commit_id: *head,
                tracked_generation: generation,
                current_state_revision: observation.control.map_or(Ok(0), |control| {
                    control
                        .current_state_revision
                        .checked_add(1)
                        .ok_or_else(|| LixError::unknown("branch current-state revision overflow"))
                })?,
                working_diff_checkpoint_commit_id: Some(checkpoint),
                created_at: observation
                    .control
                    .map_or(head_record.created_at, |control| control.created_at),
                updated_at: head_record.created_at,
                ref_change_id: sync_ref_change_id(&update.branch_id, Some(*head)),
                schema_presence_bloom: [0; 4],
            };
            control.schema_presence_bloom = [u64::MAX; 4];
            stage_branch_head_control(&mut writes, &update.branch_id, control)?;
            published_ref_updates.push(update.clone());
        }

        if replica_publication.is_some() {
            // Even an unchanged visible ref participates in receipt admission:
            // a concurrent local writer must not escape a global-dependent reset.
            for (branch_id, observation) in branch_ids.iter().zip(&observations) {
                preconditions.push(branch_head_control_precondition(
                    branch_id,
                    observation.raw_token.clone(),
                )?);
            }
        }
        if let Some(publication) = &replica_publication {
            if publication.state.cursor < publication.expected_cursor
                || (publication.state.cursor == publication.expected_cursor
                    && !publication.reset_pending)
            {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "sync replica publication must advance its event cursor",
                ));
            }
            let (_stored_state, previous) = load_replica_state(&read).await?;
            if previous.as_ref() != Some(publication.expected_state_raw) {
                return Err(LixError::new(
                    LixError::CODE_TRANSACTION_CONFLICT,
                    "sync replica state changed while its repository event was admitted",
                ));
            }
            for branch_id in publication.retired_upload_proof_branches {
                super::upload_proof::stage_retire_proof(
                    &read,
                    &mut writes,
                    &mut preconditions,
                    branch_id,
                )
                .await?;
            }
            stage_replica_state(&mut writes, &mut preconditions, publication.state, previous)?;
        }
        if purpose == SyncImportPurpose::ReplicaDelta
            && (replica_publication
                .as_ref()
                .is_some_and(|publication| publication.reset_pending)
                || (replica_publication.is_none() && !changed_refs.is_empty()))
        {
            super::upload_plan::stage_invalidate(&mut writes);
        }
        crate::json_store::stage_json_publication_fence(&read, &mut writes, &mut preconditions)
            .await?;
        let (current_cursor, _) = load_sequence(&read).await?;
        if newly_imported.is_empty()
            && published_ref_updates.is_empty()
            && !hydrated_history
            && replica_publication.is_none()
        {
            return Ok(SyncPushResponse {
                cursor: current_cursor,
            });
        }
        if !published_ref_updates.is_empty() {
            // A remote head movement can reveal filesystem and account rows
            // selected from older commits even when the pushed tip authored
            // neither schema. Invalidate the same derived read caches as a
            // local transaction before publishing the ref atomically.
            crate::filesystem::stage_path_index_revision(&mut writes);
            crate::account::stage_account_revision(&mut writes);
        }
        let cursor = if purpose == SyncImportPurpose::AuthorityPush
            && (!newly_imported.is_empty() || !published_ref_updates.is_empty())
        {
            let event_commit_ids = if published_ref_updates.is_empty() {
                newly_imported
            } else {
                request
                    .commits
                    .iter()
                    .map(|commit| commit.commit_id.clone())
                    .collect()
            };
            stage_repository_event(
                &read,
                &mut writes,
                &mut preconditions,
                event_commit_ids,
                published_ref_updates,
            )
            .await?
            .cursor
        } else {
            current_cursor
        };
        drop(read);
        let options = StorageWriteOptions {
            preconditions,
            await_durable: true,
            ..StorageWriteOptions::default()
        };
        if self.sync_mode_state().role() == super::SyncRole::Replica
            && purpose != SyncImportPurpose::AuthorityPush
        {
            adapter
                .commit_certified_replica_write_set(
                    super::certified_replica_write_capability(),
                    writes,
                    options,
                )
                .await?;
        } else {
            adapter.commit_write_set(writes, options).await?;
        }
        self.notify_observers_for_sync();
        self.sync_mode_state().notify_sync_change();
        Ok(SyncPushResponse { cursor })
    }

    pub(crate) async fn sync_history_demand_ids(
        &self,
        commit_ids: BTreeSet<String>,
    ) -> Result<BTreeSet<String>, LixError> {
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let mut pending = BTreeSet::new();
        for commit_id in commit_ids {
            let parsed = CommitId::parse_lix(&commit_id, "sync history demand commit id")?;
            if load_commit_record(&read, parsed).await?.is_none()
                || commit_history_is_deferred(&read, parsed).await?
            {
                pending.insert(commit_id);
            }
        }
        Ok(pending)
    }

    pub(crate) async fn sync_checkpoint_history_demand_ids(
        &self,
        commit_ids: &BTreeSet<String>,
    ) -> Result<BTreeSet<String>, LixError> {
        if commit_ids.is_empty() {
            return Ok(BTreeSet::new());
        }
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let mut checkpoints = BTreeSet::new();
        for commit_id in commit_ids {
            let id = CommitId::parse_lix(commit_id, "sync checkpoint history demand commit id")?;
            if load_commit_record(&read, id)
                .await?
                .is_some_and(|record| record.is_checkpoint)
            {
                checkpoints.insert(commit_id.clone());
            }
        }
        Ok(checkpoints)
    }

    async fn complete_history_live_root_at_commit(
        &self,
        read: &(impl StorageAdapterRead + ?Sized),
        commit_id: CommitId,
    ) -> Result<TrackedStateRootId, LixError> {
        let mut tracked = TrackedStateContext::new().reader(read);
        let rows = tracked
            .scan_batch_at_commit(&commit_id.to_string(), &TrackedStateScanRequest::default())
            .await?;
        let deltas = rows.iter().map(|row| TrackedStateDeltaRef {
            schema_key: row.schema_key(),
            file_id: row.file_id(),
            row_pk: row.row_pk(),
            change_id: row.change_id(),
            commit_id: row.commit_id(),
            deleted: false,
            created_at: row.created_at(),
            updated_at: row.updated_at(),
        });
        let mut transient_writes = self.storage_adapter().new_write_set();
        let tracked_context = TrackedStateContext::new();
        let mut writer = tracked_context.writer(read, &mut transient_writes);
        writer
            .stage_commit_root(&commit_id.to_string(), None, deltas)
            .await?;
        Ok(writer
            .staged_commit_roots()
            .find(|root| root.commit_id == commit_id)
            .expect("complete live root was staged")
            .root_id
            .clone())
    }

    async fn complete_sync_live_value_root_at_commit(
        &self,
        read: &(impl StorageAdapterRead + ?Sized),
        commit_id: CommitId,
    ) -> Result<SyncLiveValueRootId, LixError> {
        let rows = load_sync_live_value_rows_at_commit(read, commit_id).await?;
        sync_live_value_root(rows.values().map(SyncLiveValueRow::as_ref))
    }

    pub(crate) async fn sync_history(
        &self,
        head: &str,
        limit: usize,
    ) -> Result<SyncHistoryResponse, LixError> {
        if limit == 0 || limit > super::MAX_SYNC_HISTORY_PAGE_SIZE {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "sync history limit must be between 1 and {}",
                    super::MAX_SYNC_HISTORY_PAGE_SIZE
                ),
            ));
        }
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let head = CommitId::parse_lix(head, "sync history head")?;
        load_commit_record(&read, head)
            .await?
            .ok_or_else(|| LixError::commit_not_found(head.to_string(), "sync_history", "head"))?;
        let mut next = Some(head);
        let mut newest_first = Vec::with_capacity(limit);
        while let Some(commit_id) = next
            && newest_first.len() < limit
        {
            let record = load_commit_record(&read, commit_id).await?.ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!("sync history chain is missing commit '{commit_id}'"),
                )
            })?;
            next = record.parent_commit_ids.first().copied();
            newest_first.push(record);
        }
        let body_ids = newest_first
            .iter()
            .map(|record| record.commit_id)
            .collect::<BTreeSet<_>>();
        let external_base_ids = newest_first
            .iter()
            .filter_map(|record| record.base_commit_id)
            .filter(|base| !body_ids.contains(base))
            .collect::<BTreeSet<_>>();
        let mut boundary_ids = newest_first
            .iter()
            .filter(|record| {
                record
                    .parent_commit_ids
                    .iter()
                    .any(|parent| !body_ids.contains(parent))
            })
            .map(|record| record.commit_id)
            .collect::<BTreeSet<_>>();
        // A local commit is not a complete state authority without its pinned
        // global base. When that base is outside the bounded body page, ship
        // it as a materialized boundary just like an external causal parent.
        // Its canonical body travels as an out-of-page dependency below.
        boundary_ids.extend(external_base_ids.iter().copied());
        let mut commits = Vec::with_capacity(newest_first.len() + external_base_ids.len());
        for record in newest_first.iter().rev() {
            commits.push(
                load_sync_commit(&read, record.commit_id)
                    .await?
                    .ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_INTERNAL_ERROR,
                            format!(
                                "sync history commit '{}' has no complete body",
                                record.commit_id
                            ),
                        )
                    })?,
            );
        }
        // Dependency bodies do not consume causal history-page slots. Ship
        // external pinned global bases in the same response so the receiver
        // can publish each immutable commit authority exactly once without an
        // additional request per local commit.
        for commit_id in &external_base_ids {
            commits.push(load_sync_commit(&read, *commit_id).await?.ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!("sync history base dependency '{commit_id}' has no complete body"),
                )
            })?);
        }
        // A complete-state alias is O(1) only when the receiver already owns
        // its physical source (the normal ordered-delta case). History demand
        // cannot assume that, and GC may have retired the source's semantic
        // commit record while retaining its chunks. Mark the checkpoint itself
        // as a paginated state boundary so history remains self-contained
        // without expanding one commit body past the response cap.
        boundary_ids.extend(
            commits
                .iter()
                .filter_map(|commit| {
                    commit
                        .state_alias
                        .as_ref()
                        .map(|_| CommitId::parse_lix(&commit.commit_id, "sync checkpoint boundary"))
                })
                .collect::<Result<Vec<_>, _>>()?,
        );
        let mut header_ids = body_ids.clone();
        for record in &newest_first {
            header_ids.extend(record.parent_commit_ids.iter().copied());
            header_ids.extend(record.base_commit_id);
            if record.first_parent_jump_span > 0 {
                header_ids.insert(record.first_parent_jump_commit_id);
            }
        }
        let mut pending_header_ids = header_ids.iter().copied().collect::<Vec<_>>();
        while let Some(commit_id) = pending_header_ids.pop() {
            let record = load_commit_record(&read, commit_id).await?.ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!("sync history boundary '{commit_id}' is missing"),
                )
            })?;
            if record.first_parent_jump_span > 0
                && header_ids.insert(record.first_parent_jump_commit_id)
            {
                pending_header_ids.push(record.first_parent_jump_commit_id);
            }
            if let Some(base_commit_id) = record.base_commit_id
                && header_ids.insert(base_commit_id)
            {
                pending_header_ids.push(base_commit_id);
            }
        }
        let mut commit_headers = Vec::with_capacity(header_ids.len());
        for commit_id in header_ids {
            let record = load_commit_record(&read, commit_id)
                .await?
                .expect("validated history boundary remains present");
            let global_scope =
                match load_published_commit_state_topology(&read, record.commit_id).await? {
                    Some(topology) => topology.global_scope(),
                    None => deferred_commit_global_scope(&read, record.commit_id)
                        .await?
                        .unwrap_or(false),
                };
            commit_headers.push(sync_header_from_record(&record, global_scope));
        }
        let mut boundaries = Vec::with_capacity(boundary_ids.len());
        for commit_id in boundary_ids {
            let live_state_root_id = self
                .complete_history_live_root_at_commit(&read, commit_id)
                .await?;
            boundaries.push(SyncHistoryBoundary {
                commit_id: commit_id.to_string(),
                live_state_root_id: format_sync_state_root_id(&live_state_root_id),
            });
        }
        Ok(SyncHistoryResponse {
            commits,
            commit_headers,
            boundaries,
        })
    }

    pub(crate) async fn pull_sync_snapshot_rows(
        &self,
        branch_id: &str,
        head_commit_id: &str,
        continuation: Option<&str>,
        limit: usize,
    ) -> Result<SyncSnapshotRowPage, LixError> {
        super::validate_sync_branch_id(branch_id)?;
        if limit == 0 || limit > super::MAX_SYNC_REQUEST_ITEMS {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "sync snapshot row limit must be between 1 and {}",
                    super::MAX_SYNC_REQUEST_ITEMS
                ),
            ));
        }
        let head = CommitId::parse_lix(head_commit_id, "sync snapshot row head")?;
        let after = continuation
            .map(decode_snapshot_row_cursor)
            .transpose()?
            .map(|(schema_key, file_id, row_pk)| TrackedStateKey {
                schema_key,
                file_id,
                row_pk,
            });
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        if load_commit_record(&read, head).await?.is_none() {
            return Err(LixError::new(
                LixError::CODE_COMMIT_NOT_FOUND,
                format!("sync snapshot row head '{head}' does not exist"),
            ));
        }
        let mut tracked = TrackedStateContext::new().reader(&read);
        let request = TrackedStateScanRequest {
            limit: Some(limit.saturating_add(1)),
            ..TrackedStateScanRequest::default()
        };
        let batch = tracked
            .scan_batch_at_commit_page(head_commit_id, &request, after.as_ref())
            .await?;
        let mut selected = batch.iter().collect::<Vec<_>>();
        let has_more = selected.len() > limit;
        if has_more {
            selected.pop();
        }
        let next = if has_more {
            let row = selected.last().expect("positive page limit emitted a row");
            Some(encode_snapshot_row_cursor(
                row.schema_key(),
                row.file_id(),
                row.row_pk(),
            )?)
        } else {
            None
        };
        let mut rows = Vec::with_capacity(selected.len());
        for row in selected {
            let change = load_change_record_by_id(&read, row.change_id())
                .await?
                .ok_or_else(|| {
                    LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!("sync snapshot row change '{}' is missing", row.change_id()),
                    )
                })?;
            rows.push(encode_sync_snapshot_row(branch_id, row, change)?);
        }
        Ok(SyncSnapshotRowPage {
            branch_id: branch_id.to_owned(),
            head_commit_id: head_commit_id.to_owned(),
            rows,
            continuation: next,
        })
    }

    pub(crate) async fn pull_sync_repository(
        &self,
        after: Option<u64>,
        limit: usize,
    ) -> Result<SyncRepositoryPullResponse, LixError> {
        if limit == 0 || limit > super::MAX_SYNC_REQUEST_ITEMS {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!(
                    "sync pull limit must be between 1 and {}",
                    super::MAX_SYNC_REQUEST_ITEMS
                ),
            ));
        }
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let (head_cursor, _) = load_sequence(&read).await?;

        let Some(after) = after else {
            drop(read);
            return self.build_sync_snapshot().await;
        };
        if after > head_cursor {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                format!("sync cursor {after} is ahead of repository cursor {head_cursor}"),
            ));
        }
        let count = usize::try_from(head_cursor - after)
            .unwrap_or(usize::MAX)
            .min(limit);
        let keys = (1..=count)
            .map(|offset| event_key(after + u64::try_from(offset).expect("pull limit fits u64")))
            .collect::<Vec<_>>();
        let values = exact_get_many(
            &read,
            &[StorageGetManyRequest {
                space: SYNC_REPOSITORY_EVENT_SPACE,
                keys: &keys,
                opts: StorageGetOptions::default(),
            }],
        )
        .await?;
        let mut events = Vec::with_capacity(count);
        for value in values.values {
            let Some(StorageProjectedValue::FullValue(value)) = value else {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "repository sync event is missing below its sequence head",
                ));
            };
            let record: RepositoryEventRecord =
                serde_json::from_slice(&value).map_err(|error| {
                    LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!("decode repository sync event: {error}"),
                    )
                })?;
            let mut commits = Vec::with_capacity(record.commit_ids.len());
            for commit_id in &record.commit_ids {
                commits.push(export_sync_commit(self, commit_id).await?.ok_or_else(|| {
                    LixError::new(
                        LixError::CODE_INTERNAL_ERROR,
                        format!("repository sync event references missing commit '{commit_id}'"),
                    )
                })?);
            }
            let ref_updates = record.ref_updates;
            events.push(SyncEvent {
                cursor: record.cursor,
                commits,
                ref_updates,
                inline_blobs: Vec::new(),
            });
        }
        let cursor = events.last().map_or(after, |event| event.cursor);
        let mut response = SyncRepositoryPullResponse::Delta { cursor, events };
        let hot_blob_ids = self
            .sync_delta_hot_blob_plan(&response)
            .await?
            .live_blob_ids;
        let SyncRepositoryPullResponse::Delta { events, .. } = &mut response else {
            unreachable!("delta response was just constructed")
        };
        let mut emitted = BTreeSet::new();
        for event in events {
            let commit_refs = event.commits.iter().collect::<Vec<_>>();
            let mut encoded_len =
                super::encoded_delta_event_len(event.cursor, &commit_refs, &event.ref_updates)?;
            for blob_id in sync_commit_blob_ids(&event.commits)? {
                if !hot_blob_ids.contains(&blob_id) || !emitted.insert(blob_id.clone()) {
                    continue;
                }
                let manifest = self.get_sync_inline_blob_manifest(&blob_id).await?;
                if let Some(manifest) = manifest
                    && !append_bounded_inline_blob(
                        &mut event.inline_blobs,
                        &mut encoded_len,
                        manifest,
                        "inline sync event blob",
                    )?
                {
                    break;
                }
            }
        }
        Ok(response)
    }

    pub(crate) async fn sync_checkpoint_inventory(
        &self,
        cursor: u64,
        after: Option<&str>,
        limit: usize,
    ) -> Result<super::SyncCheckpointInventoryPage, LixError> {
        if limit == 0 || limit > super::MAX_SYNC_REQUEST_ITEMS {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "checkpoint inventory limit is out of range",
            ));
        }
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let (actual, _) = load_sequence(&read).await?;
        if actual != cursor {
            return Err(LixError::new(
                LixError::CODE_TRANSACTION_CONFLICT,
                "checkpoint inventory changed; restart repository snapshot",
            ));
        }
        let after = after
            .map(|id| CommitId::parse_lix(id, "checkpoint inventory cursor"))
            .transpose()?;
        let (records, next) =
            crate::checkpoint::checkpoint_commit_page(&read, after, limit).await?;
        Ok(super::SyncCheckpointInventoryPage {
            cursor,
            commit_headers: records
                .into_iter()
                .map(|record| sync_header_from_record(&record, record.base_commit_id.is_none()))
                .collect(),
            continuation: next.map(|id| id.to_string()),
        })
    }

    async fn build_sync_snapshot(&self) -> Result<SyncRepositoryPullResponse, LixError> {
        let adapter = self.storage_adapter();
        let read = adapter.begin_read(StorageReadOptions::default()).await?;
        let (cursor, _) = load_sequence(&read).await?;
        let default_branch_id = self.repository_default_branch_id_for_sync(&read).await?;
        let controls = BranchHeadControlContext::default()
            .reader(&read)
            .scan()
            .await?;
        let mut branches = Vec::with_capacity(controls.len());
        for (branch_id, control) in &controls {
            let hot_state_root_id = self
                .complete_sync_live_value_root_at_commit(&read, control.head_commit_id)
                .await?;
            let checkpoint = control.working_diff_checkpoint_commit_id.ok_or_else(|| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    format!("sync branch '{branch_id}' has no checkpoint cursor"),
                )
            })?;
            let checkpoint_state_root_id = self
                .complete_sync_live_value_root_at_commit(&read, checkpoint)
                .await?;
            branches.push(SyncBranchHead {
                branch_id: branch_id.clone(),
                head_commit_id: Some(control.head_commit_id.to_string()),
                checkpoint_commit_id: Some(checkpoint.to_string()),
                checkpoint_state_root_id: format_sync_live_value_root_id(&checkpoint_state_root_id),
                hot_state_root_id: format_sync_live_value_root_id(&hot_state_root_id),
            });
        }
        let metadata = SyncRepositoryPullResponse::Snapshot {
            cursor,
            lix_id: self.lix_id().to_owned(),
            default_branch_id,
            branches,
        };
        Ok(metadata)
    }
}

#[cfg(test)]
mod tests {
    include!("upload_plan_profile_tests.rs");
    include!("upload_frontier_tests.rs");
    include!("upload_proof_tests.rs");
    include!("upload_cache_tests.rs");
    use super::*;
    use crate::engine::Engine;
    use crate::hot_state::{HotStateContext, HotStateRowRequest};
    use crate::storage::{
        BeginScanOptions, CommitResult, GetManyRequest, GetManyResult, Key, KeyRange, Memory,
        MemoryRead, MemoryWrite, PutBatch, ReadOptions, ScanCursor, Storage, StorageError,
        StorageRead, StorageSpace, StorageWrite, WriteOptions,
    };
    use crate::storage_adapter::SharedStorageAdapterRead;
    use crate::{
        CreateBranchOptions, GLOBAL_BRANCH_ID, Lix, MergeBranchOptions, NullableKeyFilter,
        SwitchBranchOptions, Value, open_lix,
    };
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    const TEST_REMOTE: &str = "https://sync.example/lix/01936f4e-7b6c-7c3d-8f9a-000000000001";

    #[derive(Clone, Default)]
    struct SyncAccountingStorage {
        inner: Memory,
        forbidden_operations: Arc<AtomicU64>,
        branch_control_scans: Arc<AtomicU64>,
        write_transactions: Arc<AtomicU64>,
        atomic_ref_receipts: Arc<AtomicU64>,
        branch_publications_without_receipt: Arc<AtomicU64>,
        fail_next_replica_receipt: Arc<AtomicU64>,
        bootstrap_commit_barrier: Arc<Mutex<Option<Arc<tokio::sync::Barrier>>>>,
    }

    struct SyncAccountingRead {
        inner: MemoryRead,
        forbidden_operations: Arc<AtomicU64>,
        branch_control_scans: Arc<AtomicU64>,
    }

    struct SyncAccountingWrite {
        inner: MemoryWrite,
        write_transactions: Arc<AtomicU64>,
        atomic_ref_receipts: Arc<AtomicU64>,
        branch_publications_without_receipt: Arc<AtomicU64>,
        fail_next_replica_receipt: Arc<AtomicU64>,
        bootstrap_commit_barrier: Arc<Mutex<Option<Arc<tokio::sync::Barrier>>>>,
        touches_branch_control: bool,
        touches_replica_state: bool,
    }

    fn is_logical_space(space: StorageSpace, logical: StorageSpace) -> bool {
        space.id.0 & 0x3fff_ffff == logical.id.0
    }

    impl SyncAccountingStorage {
        fn reset(&self) {
            self.forbidden_operations.store(0, Ordering::Relaxed);
            self.branch_control_scans.store(0, Ordering::Relaxed);
            self.write_transactions.store(0, Ordering::Relaxed);
            self.atomic_ref_receipts.store(0, Ordering::Relaxed);
            self.branch_publications_without_receipt
                .store(0, Ordering::Relaxed);
        }

        fn forbidden_operation_count(&self) -> u64 {
            self.forbidden_operations.load(Ordering::Relaxed)
        }

        fn branch_control_scan_count(&self) -> u64 {
            self.branch_control_scans.load(Ordering::Relaxed)
        }

        fn write_transaction_count(&self) -> u64 {
            self.write_transactions.load(Ordering::Relaxed)
        }

        fn atomic_ref_receipt_count(&self) -> u64 {
            self.atomic_ref_receipts.load(Ordering::Relaxed)
        }

        fn branch_publication_without_receipt_count(&self) -> u64 {
            self.branch_publications_without_receipt
                .load(Ordering::Relaxed)
        }

        fn fail_next_replica_receipt(&self) {
            self.fail_next_replica_receipt.store(1, Ordering::Relaxed);
        }

        fn gate_bootstrap_commits(&self, participants: usize) {
            *self
                .bootstrap_commit_barrier
                .lock()
                .expect("bootstrap gate should lock") =
                Some(Arc::new(tokio::sync::Barrier::new(participants)));
        }
    }

    impl Storage for SyncAccountingStorage {
        type Read<'a>
            = SyncAccountingRead
        where
            Self: 'a;
        type Write<'a>
            = SyncAccountingWrite
        where
            Self: 'a;

        async fn acquire_session(
            &self,
        ) -> Result<crate::storage::StorageSessionToken, StorageError> {
            self.inner.acquire_session().await
        }

        async fn begin_read(&self, options: ReadOptions) -> Result<Self::Read<'_>, StorageError> {
            Ok(SyncAccountingRead {
                inner: self.inner.begin_read(options).await?,
                forbidden_operations: Arc::clone(&self.forbidden_operations),
                branch_control_scans: Arc::clone(&self.branch_control_scans),
            })
        }

        async fn begin_write(
            &self,
            options: WriteOptions,
        ) -> Result<Self::Write<'_>, StorageError> {
            self.forbidden_operations.fetch_add(1, Ordering::Relaxed);
            Ok(SyncAccountingWrite {
                inner: self.inner.begin_write(options).await?,
                write_transactions: Arc::clone(&self.write_transactions),
                atomic_ref_receipts: Arc::clone(&self.atomic_ref_receipts),
                branch_publications_without_receipt: Arc::clone(
                    &self.branch_publications_without_receipt,
                ),
                fail_next_replica_receipt: Arc::clone(&self.fail_next_replica_receipt),
                bootstrap_commit_barrier: Arc::clone(&self.bootstrap_commit_barrier),
                touches_branch_control: false,
                touches_replica_state: false,
            })
        }
    }

    impl StorageWrite for SyncAccountingWrite {
        async fn replace_many(
            &mut self,
            space: StorageSpace,
            entries: PutBatch,
        ) -> Result<(), StorageError> {
            self.touches_branch_control |=
                is_logical_space(space, crate::branch::BRANCH_HEAD_CONTROL_SPACE);
            self.touches_replica_state |= is_logical_space(space, SYNC_REPLICA_STATE_SPACE);
            self.inner.replace_many(space, entries).await
        }

        async fn put_many(
            &mut self,
            space: StorageSpace,
            entries: PutBatch,
        ) -> Result<(), StorageError> {
            self.touches_branch_control |=
                is_logical_space(space, crate::branch::BRANCH_HEAD_CONTROL_SPACE);
            self.touches_replica_state |= is_logical_space(space, SYNC_REPLICA_STATE_SPACE);
            self.inner.put_many(space, entries).await
        }

        async fn delete_many(
            &mut self,
            space: StorageSpace,
            keys: &[Key],
        ) -> Result<(), StorageError> {
            self.touches_branch_control |=
                is_logical_space(space, crate::branch::BRANCH_HEAD_CONTROL_SPACE);
            self.touches_replica_state |= is_logical_space(space, SYNC_REPLICA_STATE_SPACE);
            self.inner.delete_many(space, keys).await
        }

        async fn delete_range(
            &mut self,
            space: StorageSpace,
            range: KeyRange,
        ) -> Result<(), StorageError> {
            self.touches_branch_control |=
                is_logical_space(space, crate::branch::BRANCH_HEAD_CONTROL_SPACE);
            self.touches_replica_state |= is_logical_space(space, SYNC_REPLICA_STATE_SPACE);
            self.inner.delete_range(space, range).await
        }

        async fn commit(self) -> Result<CommitResult, StorageError> {
            self.write_transactions.fetch_add(1, Ordering::Relaxed);
            let bootstrap_commit_barrier = if self.touches_replica_state {
                self.bootstrap_commit_barrier
                    .lock()
                    .expect("bootstrap gate should lock")
                    .clone()
            } else {
                None
            };
            if let Some(barrier) = bootstrap_commit_barrier {
                barrier.wait().await;
                let mut configured = self
                    .bootstrap_commit_barrier
                    .lock()
                    .expect("bootstrap gate should lock");
                if configured
                    .as_ref()
                    .is_some_and(|candidate| Arc::ptr_eq(candidate, &barrier))
                {
                    *configured = None;
                }
            }
            if self.touches_replica_state
                && self.fail_next_replica_receipt.swap(0, Ordering::Relaxed) != 0
            {
                return Err(StorageError::Io(
                    "injected replica receipt failure".to_owned(),
                ));
            }
            if self.touches_branch_control && self.touches_replica_state {
                self.atomic_ref_receipts.fetch_add(1, Ordering::Relaxed);
            } else if self.touches_branch_control {
                self.branch_publications_without_receipt
                    .fetch_add(1, Ordering::Relaxed);
            }
            self.inner.commit().await
        }

        async fn rollback(self) -> Result<(), StorageError> {
            self.inner.rollback().await
        }
    }

    impl StorageRead for SyncAccountingRead {
        async fn get_many(
            &self,
            requests: &[GetManyRequest<'_>],
        ) -> Result<GetManyResult, StorageError> {
            self.inner.get_many(requests).await
        }

        async fn begin_scan(
            &self,
            space: StorageSpace,
            range: KeyRange,
            options: BeginScanOptions,
        ) -> Result<ScanCursor<'_>, StorageError> {
            self.forbidden_operations.fetch_add(1, Ordering::Relaxed);
            if is_logical_space(space, crate::branch::BRANCH_HEAD_CONTROL_SPACE) {
                self.branch_control_scans.fetch_add(1, Ordering::Relaxed);
            }
            self.inner.begin_scan(space, range, options).await
        }
    }

    async fn close_history_boundary_bodies(authority: &Lix, history: &mut SyncHistoryResponse) {
        let missing = history
            .boundaries
            .iter()
            .filter(|boundary| {
                !history
                    .commits
                    .iter()
                    .any(|commit| commit.commit_id == boundary.commit_id)
            })
            .map(|boundary| boundary.commit_id.clone())
            .collect::<Vec<_>>();
        let mut headers = history
            .commit_headers
            .drain(..)
            .map(|header| (header.commit_id.clone(), header))
            .collect::<BTreeMap<_, _>>();
        for commit_id in missing {
            let dependency = authority
                .sync_history(&commit_id, 1)
                .await
                .expect("external history boundary body should load");
            for commit in dependency.commits {
                if !history
                    .commits
                    .iter()
                    .any(|existing| existing.commit_id == commit.commit_id)
                {
                    history.commits.push(commit);
                }
            }
            headers.extend(
                dependency
                    .commit_headers
                    .into_iter()
                    .map(|header| (header.commit_id.clone(), header)),
            );
        }
        history.commit_headers = headers.into_values().collect();
    }

    #[tokio::test]
    async fn ancestry_walk_stops_at_an_absent_lazy_history_boundary() {
        let lix = open_lix().await.expect("open Lix");
        let adapter = lix.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("open ancestry read");
        let absent = CommitId::parse_lix(
            "01920000-0000-7000-8000-000000000501",
            "absent history commit",
        )
        .expect("test commit ID parses");
        let other = CommitId::parse_lix(
            "01920000-0000-7000-8000-000000000502",
            "other history commit",
        )
        .expect("test commit ID parses");

        assert!(
            !commit_reaches_ancestor(&read, absent, other)
                .await
                .expect("absent lazy history is an unknown boundary"),
            "an omitted cold commit cannot prove reachability",
        );
    }

    #[tokio::test]
    async fn ancestry_walk_explores_other_merge_parents_after_a_sparse_boundary() {
        let lix = open_lix().await.expect("open Lix");
        let snapshot = lix
            .pull_sync_repository(None, 1)
            .await
            .expect("load initial snapshot");
        let (_, ancestor) = default_head(&snapshot);
        let ancestor =
            CommitId::parse_lix(&ancestor, "known merge ancestor").expect("ancestor id parses");
        let absent = CommitId::for_test_label("absent-secondary-merge-parent");
        let merge = CommitId::for_test_label("sparse-merge-descendant");

        let adapter = lix.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("open ancestor read");
        let ancestor_record = load_commit_record(&read, ancestor)
            .await
            .expect("load ancestor")
            .expect("ancestor exists");
        drop(read);
        let mut merge_header = sync_header_from_record(&ancestor_record, false);
        merge_header.commit_id = merge.to_string();
        // The walker is LIFO. Put the absent parent last so it is visited
        // before the known ancestor and cannot mask the reachable path.
        merge_header.parent_commit_ids = vec![ancestor.to_string(), absent.to_string()];
        merge_header.generation = ancestor_record.generation.saturating_add(1);
        merge_header.first_parent_jump_commit_id = None;
        merge_header.first_parent_jump_span = None;
        lix.import_sync_history_headers(&[merge_header])
            .await
            .expect("install sparse merge header");

        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("open ancestry read");
        assert!(
            commit_reaches_ancestor(&read, merge, ancestor)
                .await
                .expect("known merge parent proves reachability"),
            "an absent sibling parent must not hide a known ancestor path",
        );
    }

    #[tokio::test]
    async fn applying_a_sync_delta_invalidates_observers_without_waiting_for_storage_polling() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        write_key_value(&authority, "observed-sync-value", "before").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let params = [Value::Text("observed-sync-value".to_owned())];
        replica
            .set_sync_role(super::super::SyncRole::Disabled)
            .expect("local observer fixture should bypass public replica routing");
        let mut events = replica
            .observe("SELECT value FROM lix_key_value WHERE key = $1", &params)
            .expect("observe replica value");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should be restored before applying the delta");
        events
            .next()
            .await
            .expect("initial observer evaluation succeeds")
            .expect("initial observer event exists");

        write_key_value(&authority, "observed-sync-value", "after").await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("authority delta should load");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("replica should apply remote delta");

        let event = tokio::time::timeout(Duration::from_millis(100), events.next())
            .await
            .expect("direct sync apply should wake observers before the 250 ms storage poll")
            .expect("remote observer evaluation succeeds")
            .expect("remote observer event exists");
        assert_eq!(
            event.rows.rows()[0]
                .get::<serde_json::Value>("value")
                .expect("observed value decodes"),
            serde_json::json!("after"),
        );
    }

    #[tokio::test]
    async fn overlapping_sync_pulls_trim_an_already_published_prefix() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let replica = replica_from_snapshot(&authority, &snapshot).await;

        write_key_value(&authority, "overlapping-pull", "first").await;
        let first = authority
            .pull_sync_repository(Some(cursor), 1)
            .await
            .expect("first authority delta should load");
        write_key_value(&authority, "overlapping-pull", "second").await;
        let overlapping = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("overlapping authority delta should load");

        replica
            .apply_sync_repository_pull(TEST_REMOTE, &first)
            .await
            .expect("first worker should publish its delta");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &overlapping)
            .await
            .expect("second worker should trim the published prefix");
        // A fully redundant response is the other ordering of the same race.
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &overlapping)
            .await
            .expect("an already published delta should be idempotent");
        replica
            .apply_sync_repository_pull(
                TEST_REMOTE,
                &SyncRepositoryPullResponse::Delta {
                    cursor,
                    events: Vec::new(),
                },
            )
            .await
            .expect("a stale heartbeat should not move the receipt backwards");

        let mut malformed = overlapping.clone();
        let SyncRepositoryPullResponse::Delta { cursor, events } = &mut malformed else {
            panic!("incremental pull should be a delta");
        };
        events[1].cursor = events[1]
            .cursor
            .checked_add(1)
            .expect("test cursor should not overflow");
        *cursor = events[1].cursor;
        let error = replica
            .apply_sync_repository_pull(TEST_REMOTE, &malformed)
            .await
            .expect_err("a gapped overlap must still be rejected");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);

        assert_eq!(read_key_value(&replica, "overlapping-pull").await, "second");
        let SyncRepositoryPullResponse::Delta {
            cursor: final_cursor,
            ..
        } = overlapping
        else {
            panic!("incremental pull should be a delta");
        };
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("replica cursor should load"),
            Some(final_cursor),
            "a stale pull must never move the durable receipt backwards",
        );
    }

    #[tokio::test]
    async fn concurrent_overlapping_sync_pulls_converge_after_the_receipt_cas() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let storage = SyncAccountingStorage::default();
        let replica =
            accounting_replica_from_snapshot(&authority, &snapshot, storage.clone()).await;
        let sibling = open_lix()
            .with_storage(storage.clone())
            .await
            .expect("sibling replica handle should open");
        sibling
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("sibling replica role should install");
        sibling
            .set_sync_replica_remote_id(TEST_REMOTE)
            .expect("sibling should bind to the same authority");

        write_key_value(&authority, "concurrent-overlap", "first").await;
        let first = authority
            .pull_sync_repository(Some(cursor), 1)
            .await
            .expect("first authority delta should load");
        write_key_value(&authority, "concurrent-overlap", "second").await;
        let overlapping = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("overlapping authority delta should load");

        storage.reset();
        storage.gate_bootstrap_commits(2);
        let (first_result, overlapping_result) = tokio::join!(
            replica.apply_sync_repository_pull(TEST_REMOTE, &first),
            sibling.apply_sync_repository_pull(TEST_REMOTE, &overlapping),
        );
        first_result.expect("short overlapping worker should converge");
        overlapping_result.expect("long overlapping worker should converge");

        assert_eq!(
            read_key_value(&replica, "concurrent-overlap").await,
            "second"
        );
        let SyncRepositoryPullResponse::Delta {
            cursor: final_cursor,
            ..
        } = overlapping
        else {
            panic!("incremental pull should be a delta");
        };
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("replica cursor should load"),
            Some(final_cursor),
        );
        assert_eq!(
            storage.branch_publication_without_receipt_count(),
            0,
            "every winning ref publication must include its durable receipt",
        );
    }

    #[tokio::test]
    async fn authority_preserves_untracked_current_state_without_history() {
        let authority = open_lix().await.unwrap();
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .unwrap();
        let head = authority
            .execute("SELECT id FROM lix_commit ORDER BY id", &[])
            .await
            .unwrap();
        authority.execute("INSERT INTO lix_key_value (key,value,lixcol_untracked) VALUES ('authority-local-only','preserved',true)", &[]).await.unwrap();
        assert_eq!(
            authority
                .execute(
                    "SELECT value FROM lix_key_value WHERE key = 'authority-local-only'",
                    &[]
                )
                .await
                .unwrap()
                .rows()
                .len(),
            1
        );
        let after = authority
            .execute("SELECT id FROM lix_commit ORDER BY id", &[])
            .await
            .unwrap();
        assert_eq!(
            head.rows(),
            after.rows(),
            "untracked mutations must not create history"
        );
    }

    #[tokio::test]
    async fn consecutive_file_deltas_reach_an_active_joined_content_observer() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let replica = replica_from_snapshot(&authority, &snapshot).await;

        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/remote.md".to_owned()),
                    Value::Text(String::new()),
                ],
            )
            .await
            .expect("remote file create should commit");
        let created = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("file-create delta should load");
        let SyncRepositoryPullResponse::Delta {
            cursor: created_cursor,
            events: _,
        } = &created
        else {
            panic!("file-create pull should be a delta");
        };
        hydrate_delta_blobs(&authority, &replica, &created).await;
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &created)
            .await
            .expect("replica should apply file create");

        let file_id = authority
            .execute(
                "SELECT id FROM lix_file WHERE path = $1",
                &[Value::Text("/remote.md".to_owned())],
            )
            .await
            .expect("remote file id should load")
            .rows()[0]
            .get::<String>("id")
            .expect("remote file id should decode");
        let params = [
            Value::Text(file_id.clone()),
            Value::Text(default_head(&snapshot).0),
        ];
        let mut observed = replica
            .observe(
                "SELECT file.id AS id, file.content AS content, file.path AS path, \
                 file.lixcol_change_id AS change_id, change.origin_key AS origin_key, \
                 $2 AS active_branch_id FROM lix_file AS file \
                 LEFT JOIN lix_change AS change ON change.id = file.lixcol_change_id \
                 AND change.file_id = file.id WHERE file.id = $1",
                &params,
            )
            .expect("joined Atelier file observer should open");
        let initial = observed
            .next()
            .await
            .expect("initial file observation should succeed")
            .expect("initial file observation should exist");
        assert_eq!(
            initial.rows.rows()[0]
                .get::<Vec<u8>>("content")
                .expect("initial content should decode"),
            Vec::<u8>::new(),
        );

        authority
            .execute(
                "UPDATE lix_file SET content = CAST($1 AS BYTEA) WHERE id = $2",
                &[
                    Value::Text("# right-marker\n".to_owned()),
                    Value::Text(file_id),
                ],
            )
            .await
            .expect("remote editor write should commit");
        let edited = authority
            .pull_sync_repository(Some(*created_cursor), 128)
            .await
            .expect("file-edit delta should load");
        hydrate_delta_blobs(&authority, &replica, &edited).await;
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &edited)
            .await
            .expect("replica should apply file edit");

        let next = tokio::time::timeout(Duration::from_millis(100), observed.next())
            .await
            .expect("file edit should wake the active observer")
            .expect("file edit observation should succeed")
            .expect("file edit observation should exist");
        assert_eq!(
            next.rows.rows()[0]
                .get::<Vec<u8>>("content")
                .expect("updated content should decode"),
            b"# right-marker\n",
        );
    }

    #[tokio::test]
    async fn empty_sync_delta_does_not_scan_or_open_a_write_transaction() {
        let storage = SyncAccountingStorage::default();
        let receipt = Engine::initialize(storage.clone())
            .await
            .expect("replica storage should initialize");
        let replica = open_lix()
            .with_storage(storage.clone())
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        replica
            .store_replica_state(
                TEST_REMOTE,
                SyncReplicaState {
                    active_account_id: crate::ANONYMOUS_ACCOUNT_ID.to_owned(),
                    cursor: 0,
                    authoritative_branches: BTreeMap::from([(
                        receipt.main_branch_id,
                        AuthoritativeBranchCoordinate::Headed {
                            head_commit_id: receipt.initial_commit_id.clone(),
                            checkpoint_commit_id: receipt.initial_commit_id,
                        },
                    )]),
                    certified_branch_roots: BTreeMap::new(),
                    snapshot_certified_cursor: None,
                    pending_resets: BTreeMap::new(),
                    authority_known_commit_ids: BTreeSet::new(),
                },
            )
            .await
            .expect("replica cursor should initialize");
        storage.reset();

        replica
            .apply_sync_repository_pull(
                TEST_REMOTE,
                &SyncRepositoryPullResponse::Delta {
                    cursor: 0,
                    events: Vec::new(),
                },
            )
            .await
            .expect("an unchanged heartbeat should be accepted");

        assert_eq!(
            storage.forbidden_operation_count(),
            0,
            "an unchanged heartbeat must not scan branches or open a write transaction",
        );
    }

    #[tokio::test]
    async fn delta_ref_and_cursor_publish_atomically_without_post_scan() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let (branch_id, _) = default_head(&snapshot);
        let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        let storage = SyncAccountingStorage::default();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .expect("replica storage should initialize");
        let replica = open_lix()
            .with_storage(storage.clone())
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect("snapshot should initialize replica");

        write_key_value(&authority, "scan-free-delta", "after").await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("authority delta should load");
        let SyncRepositoryPullResponse::Delta {
            cursor: delta_cursor,
            events,
        } = &delta
        else {
            panic!("incremental pull should return a delta");
        };
        let [event] = events.as_slice() else {
            panic!("one authority transaction should publish one event");
        };
        let [update] = event.ref_updates.as_slice() else {
            panic!("the authority write should publish one ref update");
        };
        let expected_head = update
            .head_commit_id
            .clone()
            .expect("the updated branch should remain headed");
        replica
            .import_sync_repository(
                &SyncPushRequest {
                    commits: event.commits.clone(),
                    ref_updates: Vec::new(),
                    inline_blobs: event.inline_blobs.clone(),
                },
                SyncImportPurpose::ReplicaDelta,
                None,
                None,
            )
            .await
            .expect("fixture should preload immutable commit bodies");
        storage.reset();
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("replica should apply remote delta");

        assert_eq!(
            storage.branch_control_scan_count(),
            0,
            "the atomic event receipt needs no post-publication convergence scan",
        );
        assert_eq!(
            storage.write_transaction_count(),
            1,
            "a ready ref event should need one storage publication",
        );
        assert_eq!(
            storage.atomic_ref_receipt_count(),
            1,
            "the branch ref and replica receipt must share that publication",
        );
        assert_eq!(
            storage.branch_publication_without_receipt_count(),
            0,
            "the imported ref must never become visible without its cursor",
        );
        let adapter = replica.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("atomic publication read should open");
        let control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("published branch should load")
            .expect("published branch should exist");
        let stored_state = load_replica_state(&read)
            .await
            .expect("published receipt should load")
            .0
            .expect("published receipt should exist");
        assert_eq!(control.head_commit_id.to_string(), expected_head);
        assert_eq!(stored_state.cursor, *delta_cursor);
    }

    #[tokio::test]
    async fn storage_session_writes_through_replica_fence_with_owner_account_and_branch() {
        const ACCOUNT: &str = "01920000-0000-7000-8000-000000000611";
        let authority = open_lix().await.unwrap();
        authority
            .ensure_account(ACCOUNT, "Filesystem author", "human")
            .await
            .unwrap();
        let draft = authority
            .create_branch(CreateBranchOptions {
                id: None,
                name: "Filesystem draft".to_owned(),
                from_commit_id: None,
            })
            .await
            .unwrap();
        let snapshot = authority.pull_sync_repository(None, 128).await.unwrap();
        let (branch_id, _) = default_head(&snapshot);
        let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        let storage = Memory::new();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .unwrap();
        let mut replica = open_lix().with_storage(storage.clone()).await.unwrap();
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .unwrap();
        replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                ACCOUNT,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .unwrap();
        // Match bootstrap's cached identity alignment after installing authority state.
        replica
            .align_repository_identity_for_sync(authority.lix_id().to_owned())
            .unwrap();
        replica
            .align_primary_account_for_sync(ACCOUNT)
            .await
            .unwrap();
        install_publication_fence_responder_for_test(&mut replica);
        replica
            .switch_branch(SwitchBranchOptions {
                branch_id: draft.id.clone(),
            })
            .await
            .unwrap();

        let plain = open_lix().with_storage(storage.clone()).await.unwrap();
        let error = plain
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ('/forbidden.txt', $1)",
                &[Value::Blob(b"forbidden".to_vec().into())],
            )
            .await
            .expect_err("a plain engine must remain fenced by the durable replica receipt");
        assert_eq!(error.code, "LIX_REPLICA_CACHE_READ_ONLY");

        let backing = replica.open_storage_session(storage).await.unwrap();
        assert_eq!(backing.active_account_id(), ACCOUNT);
        assert_eq!(backing.active_branch_id().await.unwrap(), draft.id);
        let changed = replica.sync_mode_state().change_watcher();
        backing
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ('/watched.txt', $1)",
                &[Value::Blob(b"filesystem edit".to_vec().into())],
            )
            .await
            .expect("the inherited adapter must admit a real replica write");
        assert!(
            changed.has_changed().unwrap(),
            "filesystem commits must wake the owning sync runtime"
        );
        assert_eq!(
            read_file_content(&replica, "/watched.txt").await,
            Value::Blob(b"filesystem edit".to_vec().into())
        );
        let push = replica
            .build_sync_push(TEST_REMOTE, 128)
            .await
            .unwrap()
            .expect("filesystem edit must enter the owner's outbox");
        assert!(push.commits.iter().any(|commit| {
            commit
                .members
                .iter()
                .any(|member| member.change_account_id == ACCOUNT)
        }));

        backing.close().await.unwrap();
        plain.close().await.unwrap();
        replica.close().await.unwrap();
        authority.close().await.unwrap();
    }

    #[tokio::test]
    async fn admitted_replica_writes_locally_while_plain_engines_remain_fenced() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "authority-only", "before").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let (_, initial_head) = default_head(&snapshot);

        let second_engine = open_lix()
            .with_storage(replica.storage_adapter().storage().clone())
            .await
            .expect("a second plain engine should open the same replica storage");
        let second_error = second_engine
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('second-engine', 'forbidden')",
                &[],
            )
            .await
            .expect_err("the durable receipt must fence a process-local disabled role");
        assert_eq!(second_error.code, "LIX_REPLICA_CACHE_READ_ONLY");
        assert!(
            second_engine
                .execute(
                    "SELECT * FROM lix_key_value WHERE key = 'second-engine'",
                    &[]
                )
                .await
                .expect("fenced row absence should query")
                .rows()
                .is_empty()
        );

        replica
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('local-only', 'durable')",
                &[],
            )
            .await
            .expect("admitted replica writes locally");
        replica
            .create_checkpoint()
            .await
            .expect("checkpoint commits locally");
        assert_ne!(
            current_branch_head(&replica).await,
            CommitId::parse_lix(&initial_head, "initial replica head").expect("head parses")
        );
        assert_eq!(read_key_value(&replica, "local-only").await, "durable");
        assert!(
            replica
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("outbox builds")
                .is_some()
        );
    }

    #[tokio::test]
    async fn one_delta_page_folds_a_same_branch_chain_into_one_receipt_publication() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("initial snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let storage = SyncAccountingStorage::default();
        let replica =
            accounting_replica_from_snapshot(&authority, &snapshot, storage.clone()).await;
        let params = [Value::Text("folded-chain".to_owned())];
        replica
            .set_sync_role(super::super::SyncRole::Disabled)
            .expect("local observer fixture should bypass public replica routing");
        let mut observed = replica
            .observe("SELECT value FROM lix_key_value WHERE key = $1", &params)
            .expect("observe folded value");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should be restored before applying the delta");
        observed
            .next()
            .await
            .expect("initial observer evaluation succeeds")
            .expect("initial observer event exists");

        write_key_value(&authority, "folded-chain", "first").await;
        write_key_value(&authority, "folded-chain", "final").await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("two-event delta should load");
        let SyncRepositoryPullResponse::Delta { events, cursor, .. } = &delta else {
            panic!("incremental pull should be a delta");
        };
        assert_eq!(events.len(), 2, "fixture must cross two authority events");
        storage.reset();

        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("folded page should apply");

        assert_eq!(
            storage.write_transaction_count(),
            2,
            "all immutable bodies share one publication and the final ref/receipt share one publication",
        );
        assert_eq!(storage.atomic_ref_receipt_count(), 1);
        assert_eq!(storage.branch_publication_without_receipt_count(), 0);
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("cursor should load"),
            Some(*cursor),
        );
        assert_eq!(read_key_value(&replica, "folded-chain").await, "final");
        let event = observed
            .next()
            .await
            .expect("folded observer evaluation succeeds")
            .expect("folded observer event exists");
        assert_eq!(
            event.rows.rows()[0]
                .get::<serde_json::Value>("value")
                .expect("observed value decodes"),
            serde_json::json!("final"),
        );
        assert!(
            tokio::time::timeout(Duration::from_millis(25), observed.next())
                .await
                .is_err(),
            "one folded page should emit one observer delivery",
        );
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica outbox semantics were removed"]
    async fn direct_file_fast_forwards_publish_once_and_fail_atomically() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("initial snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let (branch_id, _) = default_head(&snapshot);
        let storage = SyncAccountingStorage::default();
        let replica =
            accounting_replica_from_snapshot(&authority, &snapshot, storage.clone()).await;
        let params = [Value::Text("/atomic-fast-forward.md".to_owned())];
        let mut observed = replica
            .observe("SELECT content FROM lix_file WHERE path = $1", &params)
            .expect("file observer should open");
        assert!(
            observed
                .next()
                .await
                .expect("initial observation should succeed")
                .expect("initial observation should exist")
                .rows
                .rows()
                .is_empty()
        );

        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/atomic-fast-forward.md".to_owned()),
                    Value::Text("created".to_owned()),
                ],
            )
            .await
            .expect("authority file create should commit");
        let created = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("file create delta should load");
        assert!(matches!(
            &created,
            SyncRepositoryPullResponse::Delta { events, .. }
                if !events[0].inline_blobs.is_empty()
        ));
        storage.reset();
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &created)
            .await
            .expect("file create should apply");
        assert_eq!(storage.write_transaction_count(), 1);
        assert_eq!(storage.atomic_ref_receipt_count(), 1);
        let created_event = observed
            .next()
            .await
            .expect("created file observation should succeed")
            .expect("created file observation should exist");
        assert_eq!(
            created_event.rows.rows()[0]
                .get::<Vec<u8>>("content")
                .expect("created content should decode"),
            b"created",
        );
        let SyncRepositoryPullResponse::Delta {
            cursor: created_cursor,
            events: created_events,
            ..
        } = &created
        else {
            panic!("file create should produce a delta");
        };
        let created_head = created_events[0].ref_updates[0]
            .head_commit_id
            .clone()
            .expect("created branch should remain headed");

        authority
            .execute(
                "UPDATE lix_file SET content = CAST($1 AS BYTEA) WHERE path = $2",
                &[
                    Value::Text("edited".to_owned()),
                    Value::Text("/atomic-fast-forward.md".to_owned()),
                ],
            )
            .await
            .expect("authority file edit should commit");
        let edited = authority
            .pull_sync_repository(Some(*created_cursor), 128)
            .await
            .expect("file edit delta should load");
        storage.reset();
        storage.fail_next_replica_receipt();
        let SyncRepositoryPullResponse::Delta {
            cursor: edited_cursor,
            events,
        } = &edited
        else {
            panic!("file edit should produce a delta");
        };
        let edited_commit_id =
            CommitId::parse_lix(&events[0].commits[0].commit_id, "edited fixture commit")
                .expect("edited commit id should parse");
        let edited_blob_id = events[0].inline_blobs[0].blob_id.clone();
        let error = replica
            .apply_sync_repository_pull(TEST_REMOTE, &edited)
            .await
            .expect_err("injected publication failure should reject the whole fast-forward");
        assert!(error.message.contains("injected replica receipt failure"));
        assert_eq!(storage.write_transaction_count(), 1);
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("old cursor should remain readable"),
            Some(*created_cursor),
        );
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("atomicity read should open");
        assert!(
            load_commit_record(&read, edited_commit_id)
                .await
                .expect("failed commit lookup should succeed")
                .is_none(),
            "a failed atomic publication must not leak the immutable commit",
        );
        drop(read);
        assert!(
            !replica
                .has_sync_blob_manifest(&edited_blob_id)
                .await
                .expect("failed inline manifest lookup should succeed"),
            "a failed atomic publication must not leak the inline blob",
        );
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("atomicity control read should reopen");
        let control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("branch control should load")
            .expect("branch control should exist");
        assert_eq!(control.head_commit_id.to_string(), created_head);
        drop(read);
        assert!(
            tokio::time::timeout(Duration::from_millis(25), observed.next())
                .await
                .is_err(),
            "a failed atomic publication must not notify the warm observer",
        );

        storage.reset();
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &edited)
            .await
            .expect("replaying the file edit should apply");
        assert_eq!(storage.write_transaction_count(), 1);
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("edited cursor should load"),
            Some(*edited_cursor),
        );
        let edited_event = observed
            .next()
            .await
            .expect("edited file observation should succeed")
            .expect("edited file observation should exist");
        assert_eq!(
            edited_event.rows.rows()[0]
                .get::<Vec<u8>>("content")
                .expect("edited content should decode"),
            b"edited",
        );

        authority
            .execute(
                "DELETE FROM lix_file WHERE path = $1",
                &[Value::Text("/atomic-fast-forward.md".to_owned())],
            )
            .await
            .expect("authority file delete should commit");
        let deleted = authority
            .pull_sync_repository(Some(*edited_cursor), 128)
            .await
            .expect("file delete delta should load");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &deleted)
            .await
            .expect("file delete should apply atomically");
        assert!(
            observed
                .next()
                .await
                .expect("deleted file observation should succeed")
                .expect("deleted file observation should exist")
                .rows
                .rows()
                .is_empty()
        );
        let SyncRepositoryPullResponse::Delta {
            cursor: deleted_cursor,
            ..
        } = &deleted
        else {
            panic!("file delete should produce a delta");
        };

        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/atomic-fast-forward.md".to_owned()),
                    Value::Text("recreated".to_owned()),
                ],
            )
            .await
            .expect("authority file recreate should commit");
        let recreated = authority
            .pull_sync_repository(Some(*deleted_cursor), 128)
            .await
            .expect("file recreate delta should load");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &recreated)
            .await
            .expect("tombstoned file recreate should apply atomically");
        let recreated_event = observed
            .next()
            .await
            .expect("recreated file observation should succeed")
            .expect("recreated file observation should exist");
        assert_eq!(
            recreated_event.rows.rows()[0]
                .get::<Vec<u8>>("content")
                .expect("recreated content should decode"),
            b"recreated",
        );
        let SyncRepositoryPullResponse::Delta {
            cursor: recreated_cursor,
            ..
        } = &recreated
        else {
            panic!("file recreate should produce a delta");
        };
        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST('' AS BYTEA))",
                &[Value::Text("/empty-fast-forward.md".to_owned())],
            )
            .await
            .expect("empty authority file should commit");
        let empty = authority
            .pull_sync_repository(Some(*recreated_cursor), 128)
            .await
            .expect("empty file delta should load");
        let SyncRepositoryPullResponse::Delta { events, .. } = &empty else {
            panic!("empty file should produce a delta");
        };
        assert!(
            events[0].inline_blobs.is_empty(),
            "an intrinsic empty file references no CAS blob",
        );
        storage.reset();
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &empty)
            .await
            .expect("empty inline file should apply atomically");
        assert_eq!(
            storage.write_transaction_count(),
            1,
            "empty file commit, head, and receipt publish once without a blob lane",
        );
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica outbox semantics were removed"]
    async fn inline_blob_admission_is_referenced_authenticated_and_atomic() {
        let authority_storage = SyncAccountingStorage::default();
        Engine::initialize(authority_storage.clone())
            .await
            .expect("authority storage should initialize");
        let authority = open_lix()
            .with_storage(authority_storage.clone())
            .await
            .expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot else {
            panic!("fixture should start from a snapshot");
        };
        let replica = replica_from_snapshot(
            &authority,
            &authority
                .pull_sync_repository(None, 1)
                .await
                .expect("replica snapshot should load"),
        )
        .await;
        replica
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/inline-admission.md".to_owned()),
                    Value::Text("authenticated inline payload".to_owned()),
                ],
            )
            .await
            .expect("replica file write should commit");
        let request = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("inline push should build")
            .expect("file write should be pending");
        assert_eq!(request.inline_blobs.len(), 1);
        let commit_id = CommitId::parse_lix(&request.commits[0].commit_id, "inline fixture commit")
            .expect("fixture commit id should parse");

        let mut unreferenced = request.clone();
        let unrelated = crate::binary_cas::CanonicalBlobManifest::from_bytes(b"unrelated");
        unreferenced.inline_blobs[0] = SyncBlobManifest {
            blob_id: unrelated.blob_id.to_hex(),
            size_bytes: unrelated.size_bytes,
            chunks: unrelated
                .chunks
                .iter()
                .map(|chunk| super::super::SyncBlobChunk {
                    chunk_id: chunk.hash.to_hex(),
                    size_bytes: chunk.size_bytes,
                })
                .collect(),
            inline_bytes_base64: Some(
                base64::engine::general_purpose::STANDARD.encode(b"unrelated"),
            ),
        };
        let error = authority
            .push_sync_repository(&unreferenced)
            .await
            .expect_err("unreferenced inline blob must be rejected");
        assert!(error.message.contains("unreferenced inline blob"));

        let mut tampered = request.clone();
        tampered.inline_blobs[0].inline_bytes_base64 =
            Some(base64::engine::general_purpose::STANDARD.encode(b"tampered inline payload"));
        authority
            .push_sync_repository(&tampered)
            .await
            .expect_err("tampered inline blob must be rejected");
        assert_eq!(
            authority
                .pull_sync_repository(Some(cursor), 1)
                .await
                .expect("unchanged authority delta should load"),
            SyncRepositoryPullResponse::Delta {
                cursor,
                events: Vec::new(),
            },
        );
        let read = authority
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("atomicity read should open");
        assert!(
            load_commit_record(&read, commit_id)
                .await
                .expect("rejected commit lookup should succeed")
                .is_none()
        );
        drop(read);

        authority_storage.reset();
        authority
            .push_sync_repository(&request)
            .await
            .expect("authenticated referenced inline blob should publish");
        assert_eq!(
            authority_storage.write_transaction_count(),
            1,
            "authority must publish inline CAS, commit, ref, and event once",
        );
        let delta = authority
            .pull_sync_repository(Some(cursor), 1)
            .await
            .expect("published inline delta should load");
        let SyncRepositoryPullResponse::Delta { events, .. } = delta else {
            panic!("published response should be a delta");
        };
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].inline_blobs, request.inline_blobs);
        let history = authority
            .execute(
                "SELECT lixcol_to_commit_id FROM lix_history('lix_file') WHERE to_path = $1 ORDER BY lixcol_position LIMIT 1",
                &[Value::Text("/inline-admission.md".to_owned())],
            )
            .await
            .expect("public file history query should remain readable after inline sync");
        let history = authority
            .execute(
                "SELECT content FROM lix_as_of('lix_file', $1) WHERE path = $2",
                &[
                    Value::Text(
                        history.rows()[0]
                            .get::<String>("lixcol_to_commit_id")
                            .unwrap(),
                    ),
                    Value::Text("/inline-admission.md".to_owned()),
                ],
            )
            .await
            .expect("synced history endpoint snapshot");
        assert!(
            history.rows().iter().any(|row| {
                row.get::<Vec<u8>>("content")
                    .is_ok_and(|content| content == b"authenticated inline payload")
            }),
            "public file history should expose the synced commit",
        );
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica outbox semantics were removed"]
    async fn large_blob_inline_discovery_is_metadata_only_for_push_and_pull() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("replica snapshot should load");
        let replica_storage = SyncAccountingStorage::default();
        let replica =
            accounting_replica_from_snapshot(&authority, &snapshot, replica_storage.clone()).await;
        replica
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, $2)",
                &[
                    Value::Text("/large-local.bin".to_owned()),
                    Value::Blob(vec![7_u8; 65 * 1024].into()),
                ],
            )
            .await
            .expect("large local file should commit");
        replica_storage.reset();
        let push = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("large push should build")
            .expect("large file should be pending");
        assert!(push.inline_blobs.is_empty());
        assert_eq!(
            replica_storage.write_transaction_count(),
            0,
            "large outbound discovery must not canonicalize or publish transfer chunks",
        );

        let authority_storage = SyncAccountingStorage::default();
        let receipt = Engine::initialize(authority_storage.clone())
            .await
            .expect("accounted authority storage should initialize");
        let accounted_authority = open_lix()
            .with_storage(authority_storage.clone())
            .await
            .expect("accounted authority should open");
        accounted_authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("accounted authority role should install");
        accounted_authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, $2)",
                &[
                    Value::Text("/large-authority.bin".to_owned()),
                    Value::Blob(vec![9_u8; 65 * 1024].into()),
                ],
            )
            .await
            .expect("large authority file should commit");
        authority_storage.reset();
        let delta = accounted_authority
            .pull_sync_repository(Some(0), 1)
            .await
            .expect("large authority event should load");
        let SyncRepositoryPullResponse::Delta { events, .. } = delta else {
            panic!("large authority pull should be a delta");
        };
        assert_eq!(events.len(), 1);
        assert!(events[0].inline_blobs.is_empty());
        assert_eq!(
            authority_storage.write_transaction_count(),
            0,
            "large inbound discovery must not canonicalize or publish transfer chunks",
        );
        assert_eq!(
            receipt.main_branch_id,
            accounted_authority
                .active_branch_id()
                .await
                .expect("accounted authority branch should load"),
        );
    }

    #[tokio::test]
    async fn one_delta_page_folds_independent_branch_updates() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let main_branch_id = authority
            .active_branch_id()
            .await
            .expect("main branch should load");
        let secondary = authority
            .create_branch(CreateBranchOptions {
                id: Some("01920000-0000-7000-8000-000000001777".to_owned()),
                name: "folded-secondary".to_owned(),
                from_commit_id: None,
            })
            .await
            .expect("secondary branch should be created");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("branch-complete snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let storage = SyncAccountingStorage::default();
        let replica =
            accounting_replica_from_snapshot(&authority, &snapshot, storage.clone()).await;

        authority
            .switch_branch(SwitchBranchOptions {
                branch_id: secondary.id.clone(),
            })
            .await
            .expect("authority should select secondary branch");
        write_key_value(&authority, "secondary-fold", "secondary").await;
        authority
            .switch_branch(SwitchBranchOptions {
                branch_id: main_branch_id.clone(),
            })
            .await
            .expect("authority should restore main branch");
        write_key_value(&authority, "main-fold", "main").await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("independent branch delta should load");
        let SyncRepositoryPullResponse::Delta { events, .. } = &delta else {
            panic!("incremental pull should be a delta");
        };
        assert_eq!(
            events.len(),
            3,
            "fixture contains the stale secondary checkout refresh plus one user event per branch"
        );
        storage.reset();

        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("independent branch page should apply");

        assert_eq!(
            storage.write_transaction_count(),
            2,
            "the atomic page publication is followed by one local composite-base refresh",
        );
        assert_eq!(storage.atomic_ref_receipt_count(), 1);
        assert_eq!(read_key_value(&replica, "main-fold").await, "main");
        replica
            .switch_branch(SwitchBranchOptions {
                branch_id: secondary.id,
            })
            .await
            .expect("replica should select synchronized secondary branch");
        assert_eq!(
            read_key_value(&replica, "secondary-fold").await,
            "secondary",
        );
    }

    #[tokio::test]
    async fn durable_replica_fence_rejects_nonadmitted_engines() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        write_key_value(&authority, "divergent-base", "base").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("initial snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let storage = SyncAccountingStorage::default();
        let replica =
            accounting_replica_from_snapshot(&authority, &snapshot, storage.clone()).await;
        let plain = open_lix()
            .with_storage(storage.clone())
            .await
            .expect("plain engine can read the receipt-bound storage");
        let error = plain
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('local-divergent', 'local')",
                &[],
            )
            .await
            .expect_err("a durable authority receipt must make local divergence impossible");
        assert_eq!(error.code, "LIX_REPLICA_CACHE_READ_ONLY");
        write_key_value(&authority, "remote-divergent-a", "remote-a").await;
        write_key_value(&authority, "remote-divergent-b", "remote-b").await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("divergent page should load");
        let SyncRepositoryPullResponse::Delta { events, .. } = &delta else {
            panic!("incremental pull should be a delta");
        };
        assert_eq!(events.len(), 2);

        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("the still-certified replica should accept authority state");
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("new cursor should be readable"),
            Some(match delta {
                SyncRepositoryPullResponse::Delta { cursor, .. } => cursor,
                SyncRepositoryPullResponse::Snapshot { .. } => unreachable!(),
            }),
            "the authority receipt advances only with the certified page",
        );
        assert!(
            replica
                .execute(
                    "SELECT * FROM lix_key_value WHERE key = 'local-divergent'",
                    &[],
                )
                .await
                .expect("the rejected row absence should query")
                .rows()
                .is_empty()
        );
        assert_eq!(
            read_key_value(&replica, "remote-divergent-b").await,
            "remote-b"
        );
    }

    fn default_head(snapshot: &SyncRepositoryPullResponse) -> (String, String) {
        let SyncRepositoryPullResponse::Snapshot {
            default_branch_id,
            branches,
            ..
        } = snapshot
        else {
            panic!("initial pull must be a snapshot");
        };
        let head = branches
            .iter()
            .find(|branch| &branch.branch_id == default_branch_id)
            .and_then(|branch| branch.head_commit_id.clone())
            .expect("default branch must have a head");
        (default_branch_id.clone(), head)
    }

    fn authoritative_coordinates(
        branches: &[SyncBranchHead],
    ) -> BTreeMap<String, AuthoritativeBranchCoordinate> {
        branches
            .iter()
            .map(|branch| {
                (
                    branch.branch_id.clone(),
                    AuthoritativeBranchCoordinate::from_wire(
                        branch.head_commit_id.clone(),
                        branch.checkpoint_commit_id.clone(),
                        "test snapshot branch",
                    )
                    .expect("snapshot branch coordinate should be complete"),
                )
            })
            .collect()
    }

    async fn snapshot_parts<AuthorityStorage>(
        authority: &Lix<AuthorityStorage>,
        snapshot: &SyncRepositoryPullResponse,
    ) -> (
        SyncHistoryResponse,
        Vec<SyncSnapshotRow>,
        BTreeMap<String, String>,
    )
    where
        AuthorityStorage: Storage + Clone + Send + Sync + 'static,
    {
        let SyncRepositoryPullResponse::Snapshot { branches, .. } = snapshot else {
            unreachable!("initial pull is a snapshot");
        };
        let mut commits = BTreeMap::new();
        let mut headers = BTreeMap::new();
        let mut boundaries = BTreeMap::new();
        let snapshot_commits = branches
            .iter()
            .flat_map(|branch| {
                [
                    branch.head_commit_id.as_deref(),
                    branch.checkpoint_commit_id.as_deref(),
                ]
            })
            .flatten()
            .collect::<BTreeSet<_>>();
        for head in snapshot_commits {
            let page = authority
                .sync_history(head, 1)
                .await
                .expect("snapshot head history should load");
            commits.extend(
                page.commits
                    .into_iter()
                    .map(|commit| (commit.commit_id.clone(), commit)),
            );
            headers.extend(
                page.commit_headers
                    .into_iter()
                    .map(|header| (header.commit_id.clone(), header)),
            );
            boundaries.extend(
                page.boundaries
                    .into_iter()
                    .map(|boundary| (boundary.commit_id.clone(), boundary)),
            );
        }
        let checkpoint_roots = branches
            .iter()
            .filter_map(|branch| {
                let head = branch.head_commit_id.as_deref()?;
                let checkpoint = branch.checkpoint_commit_id.as_deref()?;
                if head == checkpoint {
                    return None;
                }
                Some((
                    checkpoint.to_owned(),
                    branch.checkpoint_state_root_id.clone(),
                ))
            })
            .collect::<BTreeMap<_, _>>();
        let history = SyncHistoryResponse {
            commits: commits.into_values().collect(),
            commit_headers: headers.into_values().collect(),
            boundaries: boundaries.into_values().collect(),
        };
        let mut rows = Vec::new();
        for branch in branches {
            let Some(head) = branch.head_commit_id.as_deref() else {
                continue;
            };
            let mut continuation = None;
            loop {
                let page = authority
                    .pull_sync_snapshot_rows(
                        &branch.branch_id,
                        head,
                        continuation.as_deref(),
                        super::super::MAX_SYNC_REQUEST_ITEMS,
                    )
                    .await
                    .expect("snapshot row page should load");
                rows.extend(page.rows);
                let Some(next) = page.continuation else {
                    break;
                };
                continuation = Some(next);
            }
        }
        let checkpoint_targets = branches
            .iter()
            .filter_map(|branch| {
                let head = branch.head_commit_id.as_deref()?;
                let checkpoint = branch.checkpoint_commit_id.as_deref()?;
                (head != checkpoint).then_some(checkpoint)
            })
            .collect::<BTreeSet<_>>();
        for checkpoint in checkpoint_targets {
            let mut continuation = None;
            loop {
                let page = authority
                    .pull_sync_snapshot_rows(
                        checkpoint,
                        checkpoint,
                        continuation.as_deref(),
                        super::super::MAX_SYNC_REQUEST_ITEMS,
                    )
                    .await
                    .expect("checkpoint snapshot row page should load");
                rows.extend(page.rows);
                let Some(next) = page.continuation else {
                    break;
                };
                continuation = Some(next);
            }
        }
        (history, rows, checkpoint_roots)
    }

    fn install_publication_fence_responder_for_test<StorageImpl>(lix: &mut Lix<StorageImpl>)
    where
        StorageImpl: Storage + Clone + Send + Sync + 'static,
    {
        let (demand_tx, mut demand_rx) = tokio::sync::mpsc::channel(8);
        lix.set_sync_demand_sender_for_test(demand_tx);
        tokio::spawn(async move {
            while let Some(demand) = demand_rx.recv().await {
                assert!(
                    demand.is_publication_barrier_for_test(),
                    "the synthetic replica fixture only answers publication barriers",
                );
                demand.succeed_for_test();
            }
        });
    }

    #[test]
    fn snapshot_encoding_preserves_distinct_rows_sharing_a_source_change() {
        let source_pk = RowPk::single("source-row");
        let source_payload = crate::plugin::runtime::WasmTypedRow::from_test_json_unchecked(
            &source_pk,
            &serde_json::json!({"value": "source"}),
        )
        .unwrap()
        .durable_payload()
        .unwrap();
        let source = ChangeRecord {
            format_version: 2,
            change_id: ChangeId::for_test_label("shared-source-change"),
            account_id: crate::ANONYMOUS_ACCOUNT_ID.to_owned(),
            schema_key: "source_row".to_owned(),
            row_pk: source_pk,
            file_id: None,
            snapshot: Some(source_payload.to_vec()),
            metadata: None,
            created_at: LixTimestamp::expect_parse("created_at", "2026-05-12T00:00:00Z"),
            origin_key: None,
        };
        let commit_id = CommitId::for_test_label("shared-source-snapshot");
        let materialized = crate::tracked_state::MaterializedTrackedStateBatch::from_rows(
            ["derived-one", "derived-two"]
                .into_iter()
                .map(|identity| {
                    let row_pk = RowPk::single(identity);
                    let json = serde_json::json!({"id": identity});
                    let typed = crate::plugin::runtime::WasmTypedRow::from_test_json_unchecked(
                        &row_pk, &json,
                    )
                    .unwrap();
                    MaterializedTrackedStateRow {
                        row_pk,
                        schema_key: "derived_row".into(),
                        file_id: None,
                        snapshot_content: Some(typed.to_json_shared().unwrap()),
                        decoded_snapshot: Some(Arc::new(typed)),
                        metadata: None,
                        deleted: false,
                        created_at: source.created_at.to_string(),
                        updated_at: source.created_at.to_string(),
                        change_id: source.change_id,
                        commit_id,
                    }
                })
                .collect(),
        )
        .unwrap();
        let mut payloads = Vec::new();
        for row in materialized.iter() {
            // The source record has another schema/PK and payload entirely;
            // only its account, timestamp, and origin apply to the derived row.
            let wire = encode_sync_snapshot_row(GLOBAL_BRANCH_ID, row, source.clone()).unwrap();
            let parsed = parse_snapshot_row(&wire).unwrap();
            assert_eq!(parsed.row_pk, *row.row_pk());
            assert_eq!(
                wire.snapshot.unwrap(),
                serde_json::from_str::<serde_json::Value>(row.snapshot_content().unwrap().as_str())
                    .unwrap()
            );
            assert_eq!(wire.change_account_id, source.account_id);
            assert_eq!(wire.change_id, source.change_id.to_string());
            payloads.push(wire.snapshot_payload.unwrap());
        }
        assert_ne!(
            payloads[0], payloads[1],
            "shared source IDs must not collapse identity-specific payloads"
        );
    }

    #[tokio::test]
    async fn custom_schema_snapshot_retains_rows_from_before_schema_amendment() {
        let authority = open_lix().await.unwrap();
        let mut schema = serde_json::json!({
            "$schema": "https://lix.dev/schema-v1.json", "key": "amended_sync_row",
            "columns": [{"name":"id","type":"text","nullable":false}],
            "primary_key": ["id"]
        });
        authority
            .execute(
                "INSERT INTO lix_registered_schema (value) VALUES (CAST($1 AS JSONB))",
                &[Value::Text(schema.to_string())],
            )
            .await
            .unwrap();
        authority
            .execute("INSERT INTO amended_sync_row (id) VALUES ('old')", &[])
            .await
            .unwrap();
        let (_, old_head) = default_head(&authority.pull_sync_repository(None, 128).await.unwrap());
        schema["columns"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::json!({"name":"extra","type":"text","nullable":true}));
        authority.execute("UPDATE lix_registered_schema SET value = CAST($1 AS JSONB) WHERE schema_key = 'amended_sync_row'", &[Value::Text(schema.to_string())]).await.unwrap();
        authority
            .execute(
                "INSERT INTO amended_sync_row (id, extra) VALUES ('new', 'value')",
                &[],
            )
            .await
            .unwrap();
        let snapshot = authority.pull_sync_repository(None, 128).await.unwrap();
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let query = "SELECT id FROM amended_sync_row ORDER BY id";
        assert_eq!(
            replica.execute(query, &[]).await.unwrap().rows(),
            authority.execute(query, &[]).await.unwrap().rows()
        );
        hydrate_history_commit(&authority, &replica, &old_head).await;
        assert_eq!(
            export_sync_commit(&replica, &old_head).await.unwrap(),
            export_sync_commit(&authority, &old_head).await.unwrap(),
            "lazy history preserves the immutable row's original schema fingerprint"
        );
        replica.close().await.unwrap();
        authority.close().await.unwrap();
    }

    #[tokio::test]
    async fn custom_schema_rows_sync_bootstrap_and_bidirectional_edits() {
        let authority = open_lix().await.unwrap();
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .unwrap();
        let schema = serde_json::json!({
            "$schema": "https://lix.dev/schema-v1.json", "key": "sync_custom_row",
            "columns": [{"name":"id","type":"text","nullable":false}, {"name":"value","type":"text","nullable":false}],
            "primary_key": ["id"]
        });
        authority.execute("INSERT INTO lix_registered_schema (schema_key, value, lixcol_global) VALUES ('sync_custom_row', CAST($1 AS JSONB), false)", &[Value::Text(schema.to_string())]).await.unwrap();
        authority
            .execute(
                "INSERT INTO sync_custom_row (id, value) VALUES ('row', 'initial')",
                &[],
            )
            .await
            .unwrap();
        let initial = authority.pull_sync_repository(None, 128).await.unwrap();
        let replica = replica_from_snapshot(&authority, &initial).await;
        let query = "SELECT value FROM sync_custom_row WHERE id = 'row'";
        assert_eq!(
            replica.execute(query, &[]).await.unwrap().rows(),
            authority.execute(query, &[]).await.unwrap().rows()
        );
        authority
            .execute(
                "UPDATE sync_custom_row SET value = 'server-edit' WHERE id = 'row'",
                &[],
            )
            .await
            .unwrap();
        let cursor = replica
            .load_sync_repository_cursor(TEST_REMOTE)
            .await
            .unwrap();
        let delta = authority.pull_sync_repository(cursor, 128).await.unwrap();
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .unwrap();
        assert_eq!(
            replica.execute(query, &[]).await.unwrap().rows(),
            authority.execute(query, &[]).await.unwrap().rows()
        );
        replica
            .execute(
                "UPDATE sync_custom_row SET value = 'local-edit' WHERE id = 'row'",
                &[],
            )
            .await
            .unwrap();
        let push = replica
            .build_sync_push(TEST_REMOTE, 128)
            .await
            .unwrap()
            .unwrap();
        authority.push_sync_repository(&push).await.unwrap();
        assert_eq!(
            replica.execute(query, &[]).await.unwrap().rows(),
            authority.execute(query, &[]).await.unwrap().rows()
        );
        replica.close().await.unwrap();
        authority.close().await.unwrap();
    }

    async fn replica_from_snapshot<AuthorityStorage>(
        authority: &Lix<AuthorityStorage>,
        snapshot: &SyncRepositoryPullResponse,
    ) -> Lix<Memory>
    where
        AuthorityStorage: Storage + Clone + Send + Sync + 'static,
    {
        let (branch_id, _) = default_head(snapshot);
        let (history, rows, checkpoint_roots) = snapshot_parts(authority, snapshot).await;
        let storage = Memory::new();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .expect("replica storage should initialize");
        let mut replica = open_lix()
            .with_storage(storage)
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect("snapshot should initialize replica");
        install_publication_fence_responder_for_test(&mut replica);
        replica
    }

    #[tokio::test]
    async fn concurrent_initial_snapshots_publish_one_repository_binding() {
        let authority = open_lix().await.expect("authority should open");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (branch_id, _) = default_head(&snapshot);
        let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        let storage = SyncAccountingStorage::default();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .expect("replica storage should initialize");
        let first = open_lix()
            .with_storage(storage.clone())
            .await
            .expect("first opener should open");
        let second = open_lix()
            .with_storage(storage.clone())
            .await
            .expect("second opener should open");
        for opener in [&first, &second] {
            opener
                .set_sync_role(super::super::SyncRole::Replica)
                .expect("replica role should install");
        }

        storage.gate_bootstrap_commits(2);
        let (first_result, second_result) = tokio::join!(
            first.try_install_initial_sync_snapshot(
                "https://sync.example/lix/01936f4e-7b6c-7c3d-8f9a-000000000003",
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            ),
            second.try_install_initial_sync_snapshot(
                "https://sync.example/lix/01936f4e-7b6c-7c3d-8f9a-000000000004",
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            ),
        );

        let results = [first_result, second_result];
        assert_eq!(
            results
                .iter()
                .filter(|result| matches!(result, Ok(InitialSyncSnapshotInstall::Installed)))
                .count(),
            1,
            "exactly one bootstrap may claim an unbound replica"
        );
        let loser = results
            .iter()
            .find_map(|result| result.as_ref().err())
            .expect("the competing bootstrap should lose atomically");
        assert_eq!(loser.code, LixError::CODE_TRANSACTION_CONFLICT);

        let serialized_loser = if matches!(results[0], Ok(InitialSyncSnapshotInstall::Installed)) {
            second
                .try_install_initial_sync_snapshot(
                    "https://sync.example/lix/01936f4e-7b6c-7c3d-8f9a-000000000004",
                    crate::ANONYMOUS_ACCOUNT_ID,
                    &snapshot,
                    &history.commits,
                    &history.commit_headers,
                    &rows,
                    &checkpoint_roots,
                )
                .await
        } else {
            first
                .try_install_initial_sync_snapshot(
                    "https://sync.example/lix/01936f4e-7b6c-7c3d-8f9a-000000000003",
                    crate::ANONYMOUS_ACCOUNT_ID,
                    &snapshot,
                    &history.commits,
                    &history.commit_headers,
                    &rows,
                    &checkpoint_roots,
                )
                .await
        }
        .expect("the coherent binding scan should recognize the same repository");
        assert_eq!(
            serialized_loser,
            InitialSyncSnapshotInstall::ExistingRepository
        );

        let adapter = first.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("published replica state should be readable");
        let mut cursor = read
            .begin_scan(
                SYNC_REPLICA_STATE_SPACE,
                StoragePrefix {
                    bytes: Bytes::new(),
                }
                .to_range()
                .expect("full replica-state range should be valid"),
                StorageBeginScanOptions::default(),
            )
            .await
            .expect("replica-state scan should open");
        assert_eq!(
            cursor
                .next_page(2)
                .await
                .expect("replica-state scan should complete")
                .len(),
            1,
            "the repository must have one binding owner"
        );
    }

    async fn hydrate_delta_blobs<AuthorityStorage, ReplicaStorage>(
        authority: &Lix<AuthorityStorage>,
        replica: &Lix<ReplicaStorage>,
        response: &SyncRepositoryPullResponse,
    ) where
        AuthorityStorage: Storage + Clone + Send + Sync + 'static,
        ReplicaStorage: Storage + Clone + Send + Sync + 'static,
    {
        let SyncRepositoryPullResponse::Delta { events, .. } = response else {
            panic!("blob hydration requires a delta");
        };
        let blob_ids = events
            .iter()
            .flat_map(|event| &event.commits)
            .flat_map(|commit| &commit.members)
            .filter(|member| member.schema_key == "lix_binary_blob_ref" && !member.deleted)
            .filter_map(|member| {
                member
                    .snapshot
                    .as_ref()
                    .and_then(|snapshot| snapshot.get("blob_hash"))
                    .and_then(serde_json::Value::as_str)
            })
            .collect::<BTreeSet<_>>();
        for blob_id in blob_ids {
            let manifest = authority
                .get_sync_blob_manifest(blob_id)
                .await
                .expect("delta blob manifest should load")
                .expect("delta blob manifest should exist");
            replica
                .register_deferred_sync_blob_manifest(&manifest)
                .await
                .expect("delta blob should hydrate inline");
        }
    }

    async fn accounting_replica_from_snapshot(
        authority: &Lix<Memory>,
        snapshot: &SyncRepositoryPullResponse,
        storage: SyncAccountingStorage,
    ) -> Lix<SyncAccountingStorage> {
        let (branch_id, _) = default_head(snapshot);
        let (history, rows, checkpoint_roots) = snapshot_parts(authority, snapshot).await;
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .expect("replica storage should initialize");
        let mut replica = open_lix()
            .with_storage(storage)
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect("snapshot should initialize replica");
        install_publication_fence_responder_for_test(&mut replica);
        replica
    }

    #[tokio::test]
    async fn local_first_acknowledgement_preserves_newer_pending_checkpoint_after_reopen() {
        let authority = open_lix().await.expect("authority opens");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot");
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        write_key_value(&replica, "pending", "first").await;
        let request = replica
            .build_sync_push(TEST_REMOTE, 128)
            .await
            .expect("outbox")
            .expect("pending write");
        authority
            .push_sync_repository(&request)
            .await
            .expect("accept first write");
        // Simulate user work racing the upload acknowledgment, including a
        // compact checkpoint whose source edge differs from parent ancestry.
        write_key_value(&replica, "pending", "second").await;
        replica.create_checkpoint().await.expect("local checkpoint");
        let (branch_id, _) = default_head(&snapshot);
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read");
        let expected = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("control")
            .expect("branch");
        drop(read);
        let storage = replica.storage_adapter().storage().clone();
        replica.close().await.expect("close without upload");
        let mut replica = open_lix()
            .with_storage(storage)
            .await
            .expect("reopen offline");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role");
        replica
            .set_sync_replica_remote_id(TEST_REMOTE)
            .expect("remote");
        install_publication_fence_responder_for_test(&mut replica);
        replica
            .validate_sync_hot_state_authoritative()
            .await
            .expect("pending work is valid after reopen");
        let cursor = replica
            .load_sync_repository_cursor(TEST_REMOTE)
            .await
            .expect("cursor")
            .expect("receipt");
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("acknowledgment");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("apply acknowledgment");
        assert_eq!(read_key_value(&replica, "pending").await, "second");
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read");
        let actual = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("control")
            .expect("branch");
        assert_eq!(actual.head_commit_id, expected.head_commit_id);
        assert_eq!(
            actual.working_diff_checkpoint_commit_id,
            expected.working_diff_checkpoint_commit_id
        );
        drop(read);
        assert!(
            replica
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("remaining outbox")
                .is_some()
        );
    }

    #[tokio::test]
    async fn scoped_checkpoint_chain_preserves_older_ack_after_reopen() {
        let authority = open_lix().await.expect("authority opens");
        write_key_value(&authority, "authority-working", "uncheckpointed").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot");
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        write_key_value(&replica, "pending", "first").await;
        let request = replica
            .build_sync_push(TEST_REMOTE, 128)
            .await
            .expect("outbox")
            .expect("pending write");
        authority
            .push_sync_repository(&request)
            .await
            .expect("accept first write");
        // Simulate user work racing the upload acknowledgment, including a
        // compact checkpoint whose source edge differs from parent ancestry.
        write_key_value(&replica, "pending", "second").await;
        for value in ["intermediate", "second"] {
            write_key_value(&replica, "pending", value).await;
            replica.execute(
                "SELECT commit_id FROM lix_create_checkpoint(ARRAY(SELECT row_ref FROM lix_diff('lix_key_value')))",
                &[],
            ).await.expect("scoped checkpoint");
        }
        let (branch_id, _) = default_head(&snapshot);
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read");
        let expected = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("control")
            .expect("branch");
        drop(read);
        let mut bodies = replica
            .build_sync_push(TEST_REMOTE, 128)
            .await
            .expect("scoped bodies")
            .expect("scoped pending outbox");
        bodies.ref_updates.clear();
        authority
            .push_sync_repository(&bodies)
            .await
            .expect("body-only acceptance");
        let storage = replica.storage_adapter().storage().clone();
        replica.close().await.expect("close without upload");
        let mut replica = open_lix()
            .with_storage(storage)
            .await
            .expect("reopen offline");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role");
        replica
            .set_sync_replica_remote_id(TEST_REMOTE)
            .expect("remote");
        install_publication_fence_responder_for_test(&mut replica);
        replica
            .validate_sync_hot_state_authoritative()
            .await
            .expect("pending work is valid after reopen");
        let cursor = replica
            .load_sync_repository_cursor(TEST_REMOTE)
            .await
            .expect("cursor")
            .expect("receipt");
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("acknowledgment");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("apply acknowledgment");
        assert_eq!(read_key_value(&replica, "pending").await, "second");
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read");
        let actual = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("control")
            .expect("branch");
        assert_eq!(actual.head_commit_id, expected.head_commit_id);
        assert_eq!(
            actual.working_diff_checkpoint_commit_id,
            expected.working_diff_checkpoint_commit_id
        );
        let state = load_replica_state(&read)
            .await
            .expect("receipt")
            .0
            .expect("state");
        assert!(
            !state.authority_known_commit_ids.is_empty(),
            "body-only ack retained"
        );
        let retained = load_pending_sync_export_commit_ids(&read, &[(branch_id.clone(), actual)])
            .await
            .expect("GC pending retention");
        let (_, source) =
            super::super::commit::load_sync_checkpoint_source(&read, actual.head_commit_id)
                .await
                .expect("source proof")
                .expect("scoped provenance");
        assert!(
            retained.contains(&source),
            "body-only acknowledgment must retain provenance source"
        );
        drop(read);
        assert!(
            replica
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("remaining outbox")
                .is_some()
        );
    }

    #[tokio::test]
    async fn local_first_incompatible_server_write_resets_without_merge() {
        for checkpoint in [false, true] {
            let authority = open_lix().await.expect("authority opens");
            let secondary = authority
                .create_branch(CreateBranchOptions {
                    id: None,
                    name: "independent-pending".to_owned(),
                    from_commit_id: None,
                })
                .await
                .expect("server secondary branch");
            let snapshot = authority
                .pull_sync_repository(None, 1)
                .await
                .expect("snapshot");
            let left = replica_from_snapshot(&authority, &snapshot).await;
            let right = replica_from_snapshot(&authority, &snapshot).await;
            write_key_value(&left, "winner", "server").await;
            write_key_value(&right, "winner", "discarded").await;
            write_key_value(&right, "local-only", "discarded").await;
            if checkpoint {
                right
                    .create_checkpoint()
                    .await
                    .expect("pending global checkpoint catalog");
            }
            right
                .switch_branch(SwitchBranchOptions {
                    branch_id: secondary.id.clone(),
                })
                .await
                .expect("secondary branch");
            write_key_value(&right, "unrelated-pending", "discarded").await;
            right
                .switch_branch(SwitchBranchOptions {
                    branch_id: default_head(&snapshot).0,
                })
                .await
                .expect("main branch");
            let request = left
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("outbox")
                .expect("write");
            authority
                .push_sync_repository(&request)
                .await
                .expect("accept winner");
            let cursor = right
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("cursor")
                .expect("receipt");
            let delta = authority
                .pull_sync_repository(Some(cursor), 128)
                .await
                .expect("delta");
            right
                .apply_sync_repository_pull(TEST_REMOTE, &delta)
                .await
                .expect("server correction");
            assert_eq!(read_key_value(&right, "winner").await, "server");
            assert!(
                right
                    .execute(
                        "SELECT value FROM lix_key_value WHERE key = 'local-only'",
                        &[]
                    )
                    .await
                    .expect("discarded local row is absent")
                    .rows()
                    .is_empty()
            );
            assert!(
                right
                    .build_sync_push(TEST_REMOTE, 128)
                    .await
                    .expect("outbox drains")
                    .is_none()
            );
            right
                .switch_branch(SwitchBranchOptions {
                    branch_id: secondary.id,
                })
                .await
                .expect("secondary after reset");
            assert!(
                right
                    .execute(
                        "SELECT value FROM lix_key_value WHERE key = 'unrelated-pending'",
                        &[]
                    )
                    .await
                    .expect("other branch pending work is reset")
                    .rows()
                    .is_empty()
            );
            let snapshot = authority
                .pull_sync_repository(None, 1)
                .await
                .expect("server snapshot");
            right
                .validate_sync_publication_snapshot(&snapshot)
                .await
                .expect("server roots match");
        }
    }

    #[tokio::test]
    async fn local_first_global_divergence_discards_dependent_pending_checkpoint() {
        let authority = open_lix().await.expect("authority opens");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot");
        let left = replica_from_snapshot(&authority, &snapshot).await;
        let right = replica_from_snapshot(&authority, &snapshot).await;
        for (replica, key) in [(&left, "accepted_schema"), (&right, "discarded_schema")] {
            let schema = serde_json::json!({
                "$schema": "https://lix.dev/schema-v1.json", "key": key,
                "columns": [{ "name": "id", "type": "text", "nullable": false }],
                "primary_key": ["id"]
            });
            replica.execute(
                "INSERT INTO lix_registered_schema (schema_key, value, lixcol_global) VALUES (CAST($1 AS JSONB) ->> 'key', CAST($1 AS JSONB), true)",
                &[Value::Text(schema.to_string())]).await.expect("local global/schema mutation");
        }
        write_key_value(&right, "dependent", "discarded").await;
        right
            .create_checkpoint()
            .await
            .expect("dependent checkpoint");
        let request = left
            .build_sync_push(TEST_REMOTE, 128)
            .await
            .expect("outbox")
            .expect("schema write");
        assert!(
            request
                .ref_updates
                .iter()
                .any(|update| update.branch_id == GLOBAL_BRANCH_ID)
        );
        authority
            .push_sync_repository(&request)
            .await
            .expect("accept global winner");
        let cursor = right
            .load_sync_repository_cursor(TEST_REMOTE)
            .await
            .expect("cursor")
            .expect("receipt");
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("global correction");
        right
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("atomic dependent reset");
        assert!(
            right
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("discarded dependencies stay discarded")
                .is_none()
        );
        let result = right
            .execute(
                "SELECT value FROM lix_key_value WHERE key = 'dependent'",
                &[],
            )
            .await
            .expect("current state readable");
        assert!(result.rows().is_empty());
    }

    #[tokio::test]
    async fn local_first_permanent_rejection_resets_pending_without_advancing_receipt() {
        let authority = open_lix().await.expect("authority opens");
        write_key_value(&authority, "rejected", "confirmed").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot");
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let cursor = replica
            .load_sync_repository_cursor(TEST_REMOTE)
            .await
            .expect("cursor");
        write_key_value(&replica, "rejected", "local").await;
        replica
            .create_checkpoint()
            .await
            .expect("pending checkpoint");
        replica
            .discard_sync_pending_changes()
            .await
            .expect("server correction");
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("cursor"),
            cursor
        );
        assert!(
            replica
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("outbox")
                .is_none()
        );
        assert_eq!(read_key_value(&replica, "rejected").await, "confirmed");
        replica
            .discard_sync_pending_changes()
            .await
            .expect("reset is idempotent");
    }

    async fn write_key_value<StorageImpl>(lix: &Lix<StorageImpl>, key: &str, value: &str)
    where
        StorageImpl: Storage + Clone + Send + Sync + 'static,
    {
        lix.execute(
            "INSERT INTO lix_key_value (key, value) VALUES ($1, $2) \
             ON CONFLICT (key) DO UPDATE SET value = excluded.value",
            &[Value::Text(key.to_owned()), Value::Text(value.to_owned())],
        )
        .await
        .expect("key-value write should commit");
    }

    async fn read_key_value<StorageImpl>(lix: &Lix<StorageImpl>, key: &str) -> String
    where
        StorageImpl: Storage + Clone + Send + Sync + 'static,
    {
        let value = lix
            .execute(
                "SELECT value FROM lix_key_value WHERE key = $1",
                &[Value::Text(key.to_owned())],
            )
            .await
            .expect("key-value read should succeed")
            .rows()
            .first()
            .expect("key-value row should exist")
            .get::<Value>("value")
            .expect("key-value value should decode");
        match value {
            Value::Jsonb(value) => value
                .as_json_string()
                .expect("key-value JSON should contain a string"),
            Value::Text(value) => value,
            other => panic!("unexpected key-value representation: {other:?}"),
        }
    }

    async fn current_branch_head<StorageImpl>(lix: &Lix<StorageImpl>) -> String
    where
        StorageImpl: Storage + Clone + Send + Sync + 'static,
    {
        lix.execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("active branch head should load")
            .rows()[0]
            .get::<String>("id")
            .expect("active branch head should decode")
    }

    async fn working_diff_count(lix: &Lix<Memory>) -> i64 {
        let branch_id = lix
            .active_branch_id()
            .await
            .expect("active branch should remain readable");
        let adapter = lix.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("branch control read should open");
        let control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("active branch control should remain readable")
            .expect("active branch control should exist");
        TrackedHeadContext::new()
            .reader(&read)
            .working_diff_for_control(
                &branch_id,
                control,
                &TrackedStateDiffRequest {
                    retain_payloads: false,
                    ..TrackedStateDiffRequest::default()
                },
            )
            .await
            .expect("working diff should remain readable")
            .expect("certified working diff should be installed")
            .diff
            .entries
            .len() as i64
    }

    async fn read_file_content(lix: &Lix<Memory>, path: &str) -> Value {
        lix.execute(
            "SELECT content FROM lix_file WHERE path = $1",
            &[Value::Text(path.to_owned())],
        )
        .await
        .expect("file content should remain readable")
        .rows()[0]
            .get::<Value>("content")
            .expect("file content should decode")
    }

    async fn publish_pending(replica: &Lix<Memory>, authority: &Lix<Memory>) -> SyncPushRequest {
        let request = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("pending push should build")
            .expect("replica should have pending work");
        authority
            .push_sync_repository(&request)
            .await
            .expect("authority should accept pending work");
        request
    }

    async fn hydrate_history_commit(
        authority: &Lix<Memory>,
        replica: &Lix<Memory>,
        commit_id: &str,
    ) {
        let page = authority
            .sync_history(commit_id, 1)
            .await
            .expect("history page should load");
        let mut boundary_rows = Vec::new();
        for boundary in &page.boundaries {
            let rows = authority
                .pull_sync_snapshot_rows(
                    &boundary.commit_id,
                    &boundary.commit_id,
                    None,
                    super::super::MAX_SYNC_REQUEST_ITEMS,
                )
                .await
                .expect("history boundary rows should load");
            assert_eq!(rows.continuation, None);
            boundary_rows.extend(rows.rows);
        }
        replica
            .import_sync_history_headers(&page.commit_headers)
            .await
            .expect("history headers should import");
        replica
            .import_sync_history_boundaries(&page.commits, &page.boundaries, &boundary_rows)
            .await
            .expect("history bodies should import");
    }

    async fn transfer_commit_blobs(
        source: &Lix<Memory>,
        target: &Lix<Memory>,
        commits: &[SyncCommit],
    ) {
        let blob_ids = commits
            .iter()
            .flat_map(|commit| commit.members.iter())
            .filter(|member| member.schema_key == "lix_binary_blob_ref" && !member.deleted)
            .filter_map(|member| member.snapshot.as_ref())
            .filter_map(|snapshot| snapshot["blob_hash"].as_str().map(str::to_owned))
            .collect::<BTreeSet<_>>();
        for blob_id in blob_ids {
            let manifest = source
                .get_sync_blob_manifest(&blob_id)
                .await
                .expect("outbound manifest should load")
                .expect("outbound manifest should exist");
            for chunk in &manifest.chunks {
                let bytes = source
                    .get_sync_chunk(&chunk.chunk_id)
                    .await
                    .expect("outbound chunk should load")
                    .expect("outbound chunk should exist");
                target
                    .put_sync_chunk(&chunk.chunk_id, &bytes)
                    .await
                    .expect("authority should accept chunk");
            }
            target
                .register_sync_blob_manifest(&manifest)
                .await
                .expect("authority should accept manifest");
        }
    }

    async fn publish_pending_with_blobs(
        replica: &Lix<Memory>,
        authority: &Lix<Memory>,
    ) -> SyncPushRequest {
        let request = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("pending push should build")
            .expect("replica should have pending work");
        transfer_commit_blobs(replica, authority, &request.commits).await;
        authority
            .push_sync_repository(&request)
            .await
            .expect("authority should accept pending work");
        request
    }

    async fn assert_root_parent_is_complete(lix: &Lix<Memory>, commit_id: &str) {
        let commit_id = CommitId::parse_lix(commit_id, "test commit").expect("valid commit id");
        let read = lix
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("test read should open");
        let record = load_commit_record(&read, commit_id)
            .await
            .expect("record should load")
            .expect("record should exist");
        let manifest = load_commit_state_manifest(&read, commit_id)
            .await
            .expect("manifest should load")
            .expect("manifest should exist");
        if let Some(root) = manifest.snapshot_root {
            assert_eq!(
                root.parent_roots.first().map(|parent| parent.commit_id),
                record.parent_commit_ids.first().copied(),
                "root metadata must retain the changelog first parent for {commit_id}",
            );
        }
    }

    #[tokio::test]
    async fn ordinary_authority_transaction_publishes_the_canonical_stored_commit() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let before = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("initial snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = before else {
            panic!("initial pull should be a snapshot");
        };

        write_key_value(&authority, "authority-preflight", "canonical").await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 1)
            .await
            .expect("ordinary authority event should be pullable");
        let SyncRepositoryPullResponse::Delta { events, .. } = delta else {
            panic!("cursor pull should be a delta");
        };
        let event = events
            .first()
            .expect("ordinary transaction should emit one event");
        assert_eq!(event.commits.len(), 1);
        let stored = export_sync_commit(&authority, &event.commits[0].commit_id)
            .await
            .expect("stored commit should export")
            .expect("event commit should exist");
        assert_eq!(
            event.commits[0], stored,
            "preflight and post-commit export must share one canonical codec",
        );
    }

    #[tokio::test]
    async fn authority_restore_publishes_a_ref_event_and_converges_a_replica() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        write_key_value(&authority, "restore-sync", "target").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("target snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let (branch_id, target_head) = default_head(&snapshot);
        let replica = replica_from_snapshot(&authority, &snapshot).await;

        write_key_value(&authority, "restore-sync", "abandoned").await;
        let abandoned_head = authority
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("abandoned head should read")
            .rows()[0]
            .get::<String>("id")
            .expect("abandoned head should decode");
        authority
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(target_head.clone())],
            )
            .await
            .expect("ancestor restore should succeed");

        let delta = authority
            .pull_sync_repository(Some(cursor), 16)
            .await
            .expect("write and restore events should be pullable");
        let SyncRepositoryPullResponse::Delta { events, .. } = &delta else {
            panic!("cursor pull should be a delta");
        };
        assert!(events.iter().any(|event| {
            event.ref_updates.iter().any(|update| {
                update.branch_id == branch_id
                    && update.expected_head_commit_id.as_deref() == Some(abandoned_head.as_str())
                    && update.head_commit_id.as_deref() == Some(target_head.as_str())
            })
        }));

        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("replica should apply restore delta");
        assert_eq!(read_key_value(&replica, "restore-sync").await, "target");
        assert_eq!(working_diff_count(&replica).await, 0);
    }

    #[tokio::test]
    async fn oversized_ordinary_authority_event_is_rejected_atomically() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let before = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("initial snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = before else {
            panic!("initial pull should be a snapshot");
        };
        let _limit = TestRepositoryTransactionEventTransferLimit::install(128);

        let error = authority
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ($1, $2)",
                &[
                    Value::Text("rejected-authority-event".to_owned()),
                    Value::Text("must-not-commit".to_owned()),
                ],
            )
            .await
            .expect_err("an unpullable authority event must fail before commit");
        assert_eq!(error.code, "LIX_ERROR_SYNC_ITEM_TOO_LARGE");

        let result = authority
            .execute(
                "SELECT COUNT(*) AS count FROM lix_key_value WHERE key = $1",
                &[Value::Text("rejected-authority-event".to_owned())],
            )
            .await
            .expect("rejected row count should remain readable");
        assert_eq!(
            result.rows()[0]
                .get::<i64>("count")
                .expect("count should decode"),
            0,
        );
        let after = authority
            .pull_sync_repository(Some(cursor), 1)
            .await
            .expect("rejected transaction must not advance the cursor");
        assert_eq!(
            after,
            SyncRepositoryPullResponse::Delta {
                cursor,
                events: Vec::new(),
            },
        );
    }

    #[tokio::test]
    #[ignore = "v3 replicas are read-only serving caches"]
    async fn snapshot_bootstraps_non_root_head_without_parent_bodies_and_is_immediately_writable() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "bootstrap-seed", "parent-body-omitted").await;
        write_key_value(&authority, "bootstrap", "visible").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("non-root snapshot should load");
        let (_, head) = default_head(&snapshot);
        let history = authority
            .sync_history(&head, 128)
            .await
            .expect("head history should load");
        let head_commits = &history.commits;
        let commit_headers = &history.commit_headers;
        let head_header = commit_headers
            .iter()
            .find(|header| header.commit_id == head)
            .expect("head topology should be present");
        assert!(
            !head_header.parent_commit_ids.is_empty(),
            "the regression requires a non-root head",
        );
        let deferred_parent = head_header.parent_commit_ids[0].clone();
        assert_eq!(
            head_commits
                .iter()
                .filter(|commit| commit.commit_id == head)
                .count(),
            1,
            "the exact head body should be included once",
        );
        assert!(
            head_header.parent_commit_ids.iter().all(|parent| {
                head_commits
                    .iter()
                    .all(|commit| &commit.commit_id != parent)
            }),
            "snapshot bootstrap must not depend on parent commit bodies",
        );
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        assert_eq!(read_key_value(&replica, "bootstrap").await, "visible");
        let history_error = replica
            .sync_history(&deferred_parent, 1)
            .await
            .expect_err("a header-only ancestor must demand lazy history");
        assert_eq!(history_error.code, "LIX_SYNC_HISTORY_REQUIRED");
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("replica read should open");
        let global_control = BranchHeadControlContext::new()
            .reader(&read)
            .load(GLOBAL_BRANCH_ID)
            .await
            .expect("global branch control should load")
            .expect("global branch control should exist");
        let account_pk = RowPk::uuid_from_canonical(crate::ANONYMOUS_ACCOUNT_ID)
            .expect("anonymous account id is canonical");
        let physical_key = crate::hot_state::encode_hot_row_key_for_test(
            GLOBAL_BRANCH_ID,
            global_control.tracked_generation,
            "lix_account",
            &account_pk,
            None,
        );
        let physical_account = exact_get_many(
            &read,
            &[StorageGetManyRequest {
                space: crate::hot_state::ROW_SPACE,
                keys: &[StorageKey(Bytes::from(physical_key))],
                opts: StorageGetOptions::default(),
            }],
        )
        .await
        .expect("physical global account lookup should succeed")
        .values
        .into_iter()
        .next()
        .flatten();
        let account = HotStateContext::new(TrackedStateContext::new(), CommitGraphContext::new())
            .reader(SharedStorageAdapterRead::new(read))
            .load_row(&HotStateRowRequest {
                schema_key: "lix_account".to_owned(),
                branch_id: GLOBAL_BRANCH_ID.to_owned(),
                row_pk: account_pk,
                file_id: NullableKeyFilter::Null,
            })
            .await
            .expect("global account lookup should succeed");
        assert!(
            account.is_some(),
            "snapshot global generation {} must publish the active account (physical row present: {})",
            global_control.tracked_generation,
            physical_account.is_some(),
        );
        replica
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/after-bootstrap.txt".to_owned()),
                    Value::Text("works".to_owned()),
                ],
            )
            .await
            .expect("the first file write after bootstrap should succeed");
        replica
            .create_checkpoint()
            .await
            .expect("the first checkpoint after bootstrap should succeed");
        let files = replica
            .execute(
                "SELECT path FROM lix_file WHERE path = '/after-bootstrap.txt'",
                &[],
            )
            .await
            .expect("the new file should be readable");
        assert_eq!(files.rows().len(), 1);
    }

    #[tokio::test]
    async fn deep_snapshot_imports_a_bounded_sparse_jump_header_closure() {
        let authority = open_lix().await.expect("authority should open");
        for generation in 0..32 {
            write_key_value(
                &authority,
                "deep-history",
                &format!("generation-{generation}"),
            )
            .await;
        }
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("deep snapshot metadata should load");
        let (_, head) = default_head(&snapshot);
        let history = authority
            .sync_history(&head, 1)
            .await
            .expect("deep head history should load");
        let header_ids = history
            .commit_headers
            .iter()
            .map(|header| header.commit_id.as_str())
            .collect::<BTreeSet<_>>();
        assert!(
            header_ids.len() <= 6,
            "bootstrap topology must stay bounded independently of history depth",
        );
        for header in &history.commit_headers {
            if let Some(jump) = header.first_parent_jump_commit_id.as_deref() {
                assert!(
                    header_ids.contains(jump),
                    "jump target {jump} for {} must be present",
                    header.commit_id,
                );
            }
        }
        replica_from_snapshot(&authority, &snapshot).await;
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica-authored checkpoint semantics were removed"]
    async fn checkpoint_head_roundtrips_through_snapshot_import() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "checkpoint-roundtrip", "selected").await;
        authority
            .create_checkpoint()
            .await
            .expect("authority checkpoint should succeed");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("checkpoint snapshot should load");
        let (_, head) = default_head(&snapshot);
        let authority_history = authority
            .sync_history(&head, 1)
            .await
            .expect("authority checkpoint history should load");
        let authority_commit = authority_history
            .commits
            .first()
            .cloned()
            .expect("authority checkpoint body exists");
        assert!(authority_commit.state_alias.is_some());
        assert!(authority_commit.members.is_empty());
        let mut checkpoint_rows = Vec::new();
        for boundary in &authority_history.boundaries {
            let page = authority
                .pull_sync_snapshot_rows(
                    &boundary.commit_id,
                    &boundary.commit_id,
                    None,
                    super::super::MAX_SYNC_REQUEST_ITEMS,
                )
                .await
                .expect("checkpoint boundary rows should load");
            assert_eq!(page.continuation, None);
            checkpoint_rows.extend(page.rows);
        }
        let mut expanded_checkpoint = authority_commit.clone();
        expanded_checkpoint.state_alias = None;
        expanded_checkpoint.members = checkpoint_rows
            .iter()
            .filter(|row| {
                row.schema_key == "lix_key_value"
                    && row.row_pk
                        == serde_json::json!([{"type": "string", "value": "checkpoint-roundtrip"}])
            })
            .map(|row| SyncCommitMember {
                change_id: row.change_id.clone(),
                authored: false,
                schema_key: row.schema_key.clone(),
                file_id: row.file_id.clone(),
                row_pk: row.row_pk.clone(),
                deleted: false,
                snapshot: row.snapshot.clone(),
                snapshot_payload: row.snapshot_payload.clone(),
                metadata: row.metadata.clone(),
                row_created_at: row.created_at.clone(),
                row_updated_at: row.updated_at.clone(),
                change_account_id: row.change_account_id.clone(),
                change_created_at: row.change_created_at.clone(),
                origin_key: row.origin_key.clone(),
            })
            .collect();
        let mut forged_checkpoint = expanded_checkpoint.clone();
        forged_checkpoint.commit_id =
            CommitId::for_test_label("forged-checkpoint-selected-change").to_string();
        forged_checkpoint.parent_commit_ids = vec![head.clone()];
        let forged_member = forged_checkpoint
            .members
            .iter_mut()
            .find(|member| !member.authored)
            .expect("checkpoint should contain a selected member");
        forged_member.change_id = ChangeId::for_test_label("unknown-checkpoint-change").to_string();
        let forged_id = forged_checkpoint.commit_id.clone();
        authority
            .push_sync_repository(&SyncPushRequest {
                commits: vec![forged_checkpoint.clone()],
                ref_updates: Vec::new(),
                inline_blobs: Vec::new(),
            })
            .await
            .expect("a source-less complete checkpoint owns its selected payloads");
        let forged_history = authority
            .sync_history(&forged_id, 1)
            .await
            .expect("complete checkpoint history should load");
        assert_eq!(
            forged_history.commits[0].commit_id,
            forged_checkpoint.commit_id
        );
        let mut repeated_checkpoint = expanded_checkpoint.clone();
        repeated_checkpoint.commit_id =
            CommitId::for_test_label("repeated-checkpoint-selected-change").to_string();
        repeated_checkpoint.parent_commit_ids = vec![head.clone()];
        let repeated_id = repeated_checkpoint.commit_id.clone();
        authority
            .push_sync_repository(&SyncPushRequest {
                commits: vec![repeated_checkpoint.clone()],
                ref_updates: Vec::new(),
                inline_blobs: Vec::new(),
            })
            .await
            .expect("a repeated selected checkpoint should import");
        let selected_ids = expanded_checkpoint
            .members
            .iter()
            .filter(|member| !member.authored)
            .map(|member| {
                ChangeId::parse_lix(&member.change_id, "checkpoint selected test change")
                    .expect("selected change id should parse")
            })
            .collect::<Vec<_>>();
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let mut deleted_locators = StorageWriteSet::default();
        crate::tracked_state::stage_delete_change_locators(
            &mut deleted_locators,
            selected_ids.iter().copied(),
        );
        replica
            .storage_adapter()
            .commit_certified_replica_write_set(
                crate::sync::certified_replica_write_capability(),
                deleted_locators,
                StorageWriteOptions::default(),
            )
            .await
            .expect("test should emulate a sparse replica missing selected locators");
        let mut repeated_history = authority
            .sync_history(&repeated_id, 1)
            .await
            .expect("detached selected history should load");
        close_history_boundary_bodies(&authority, &mut repeated_history).await;
        let mut repeated_boundary_rows = Vec::new();
        for boundary in &repeated_history.boundaries {
            let page = authority
                .pull_sync_snapshot_rows(
                    &boundary.commit_id,
                    &boundary.commit_id,
                    None,
                    super::super::MAX_SYNC_REQUEST_ITEMS,
                )
                .await
                .expect("detached selected boundary rows should load");
            assert_eq!(page.continuation, None);
            repeated_boundary_rows.extend(page.rows);
        }
        replica
            .import_sync_history_headers(&repeated_history.commit_headers)
            .await
            .expect("detached selected headers should import");
        replica
            .import_sync_history_boundaries(
                &repeated_history.commits,
                &repeated_history.boundaries,
                &repeated_boundary_rows,
            )
            .await
            .expect("detached selected body should import");
        assert_eq!(
            working_diff_count(&replica).await,
            0,
            "checkpoint metadata is not a user-visible working change",
        );
        write_key_value(&replica, "checkpoint-roundtrip-dirty", "one change").await;
        assert_eq!(
            working_diff_count(&replica).await,
            1,
            "only the post-checkpoint user row should be dirty",
        );
        let adapter = replica.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("replica change read should open");
        let locator_keys = selected_ids
            .iter()
            .map(|change_id| StorageKey(Bytes::copy_from_slice(change_id.as_uuid().as_bytes())))
            .collect::<Vec<_>>();
        let restored_locators = exact_get_many(
            &read,
            &[StorageGetManyRequest {
                space: TRACKED_STATE_CHANGE_LOCATOR_SPACE,
                keys: &locator_keys,
                opts: StorageGetOptions::default(),
            }],
        )
        .await
        .expect("selected locator rows should load");
        assert!(
            restored_locators.values.iter().all(Option::is_some),
            "ordinary history import must restore every missing selected locator",
        );
        let selected_records = ChangelogContext::new()
            .reader(&read)
            .load_changes(ChangeLoadRequest {
                change_ids: &selected_ids,
            })
            .await
            .expect("selected checkpoint changes should load");
        assert!(
            selected_records.iter().all(|(_, record)| record.is_some()),
            "checkpoint snapshot must persist selected change payloads"
        );
        let packed_changes = crate::tracked_state::scan_change_records_from_commit_deltas(&read)
            .await
            .expect("sparse checkpoint selections must remain readable by lix_change scans");
        assert!(
            selected_ids.iter().all(|change_id| packed_changes
                .iter()
                .any(|change| change.change_id == *change_id)),
            "a later history import must publish selected locator fallbacks too",
        );
        let packed_change_ids = packed_changes
            .iter()
            .map(|change| change.change_id)
            .collect::<BTreeSet<_>>();
        assert!(
            selected_ids
                .iter()
                .all(|change_id| packed_change_ids.contains(change_id)),
            "deferred authored bodies must use the selected checkpoint payload as a locator fallback",
        );
        let authored_commits = selected_ids
            .iter()
            .map(|change_id| {
                direct_change_locator(*change_id)
                    .expect("test change should encode its authored commit")
                    .commit_id
            })
            .collect::<BTreeSet<_>>();
        drop(read);
        let replica_commit = loop {
            match replica.sync_history(&head, 1).await {
                Ok(history) => {
                    break history
                        .commits
                        .into_iter()
                        .next()
                        .expect("replica checkpoint body exists");
                }
                Err(error) if error.code == "LIX_SYNC_HISTORY_REQUIRED" => {
                    let commit_ids = error
                        .details
                        .as_ref()
                        .and_then(|details| details["commitIds"].as_array())
                        .expect("history demand ids")
                        .iter()
                        .map(|id| id.as_str().expect("history demand id").to_owned())
                        .collect::<Vec<_>>();
                    for commit_id in commit_ids {
                        let history = authority
                            .sync_history(&commit_id, 1)
                            .await
                            .expect("deferred checkpoint dependency should load");
                        replica
                            .import_sync_history_headers(&history.commit_headers)
                            .await
                            .expect("checkpoint dependency headers should import");
                        replica
                            .import_sync_history_boundaries(&history.commits, &[], &[])
                            .await
                            .expect("checkpoint dependency bodies should import");
                    }
                }
                Err(error) => panic!("replica checkpoint history should load: {error:?}"),
            }
        };
        assert_eq!(replica_commit.commit_id, authority_commit.commit_id);
        assert_eq!(
            replica_commit.parent_commit_ids,
            authority_commit.parent_commit_ids
        );
        assert_eq!(replica_commit.members, authority_commit.members);

        for authored_commit in authored_commits {
            let mut history = authority
                .sync_history(&authored_commit.to_string(), 1)
                .await
                .expect("authored history should load");
            close_history_boundary_bodies(&authority, &mut history).await;
            let mut boundary_rows = Vec::new();
            for boundary in &history.boundaries {
                let mut continuation = None;
                loop {
                    let page = authority
                        .pull_sync_snapshot_rows(
                            &boundary.commit_id,
                            &boundary.commit_id,
                            continuation.as_deref(),
                            super::super::MAX_SYNC_REQUEST_ITEMS,
                        )
                        .await
                        .expect("authored history boundary rows should load");
                    boundary_rows.extend(page.rows);
                    let Some(next) = page.continuation else {
                        break;
                    };
                    continuation = Some(next);
                }
            }
            replica
                .import_sync_history_headers(&history.commit_headers)
                .await
                .expect("authored headers should import");
            replica
                .import_sync_history_boundaries(
                    &history.commits,
                    &history.boundaries,
                    &boundary_rows,
                )
                .await
                .expect("authored body should replace the selected locator fallback");
        }
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("hydrated replica change read should open");
        let hydrated_changes = crate::tracked_state::scan_change_records_from_commit_deltas(&read)
            .await
            .expect("hydrating authored bodies must preserve canonical change scans");
        for change_id in &selected_ids {
            assert_eq!(
                hydrated_changes
                    .iter()
                    .filter(|change| change.change_id == *change_id)
                    .count(),
                1,
                "history hydration must replace, not duplicate, the selected locator fallback",
            );
            assert_eq!(
                hydrated_changes
                    .iter()
                    .find(|change| change.change_id == *change_id),
                packed_changes
                    .iter()
                    .find(|change| change.change_id == *change_id),
                "history hydration must preserve the checkpoint-certified selected payload",
            );
        }
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica outbox semantics were removed"]
    async fn checkpoint_push_includes_its_distinct_state_alias_source() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "checkpoint-source-base", "authority").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("initial snapshot should load");
        let replica = replica_from_snapshot(&authority, &snapshot).await;

        write_key_value(&replica, "checkpoint-source-local-1", "replica-1a").await;
        let first_source_parent_id = replica
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("first checkpoint source parent should load")
            .rows()[0]
            .get::<String>("id")
            .expect("first checkpoint source parent should decode");
        write_key_value(&replica, "checkpoint-source-local-1", "replica-1b").await;
        let first_source_id = replica
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("checkpoint source head should load")
            .rows()[0]
            .get::<String>("id")
            .expect("checkpoint source head should decode");
        replica
            .create_checkpoint()
            .await
            .expect("first replica checkpoint should succeed");
        let first_checkpoint_id = replica
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("first checkpoint head should load")
            .rows()[0]
            .get::<String>("id")
            .expect("first checkpoint head should decode");

        write_key_value(&replica, "checkpoint-source-local-2", "replica-2").await;
        let second_source_id = replica
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("second checkpoint source head should load")
            .rows()[0]
            .get::<String>("id")
            .expect("second checkpoint source head should decode");
        replica
            .create_checkpoint()
            .await
            .expect("second replica checkpoint should succeed");
        let second_checkpoint_id = replica
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("checkpoint head should load")
            .rows()[0]
            .get::<String>("id")
            .expect("checkpoint head should decode");
        let canonical_checkpoint = export_sync_commit(&replica, &second_checkpoint_id)
            .await
            .expect("checkpoint should export before GC")
            .expect("checkpoint body should exist before GC");

        let adapter = replica.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("GC read should open");
        let mut gc_writes = adapter.new_write_set();
        crate::gc::stage_repository_gc(SharedStorageAdapterRead::new(read), &mut gc_writes)
            .await
            .expect("pre-push GC should stage");
        adapter
            .commit_certified_replica_write_set(
                crate::sync::certified_replica_write_capability(),
                gc_writes,
                StorageWriteOptions::default(),
            )
            .await
            .expect("pre-push GC should commit");

        let request = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("checkpoint push should build")
            .expect("checkpoint push should be pending");
        let first_checkpoint_index = request
            .commits
            .iter()
            .position(|commit| commit.commit_id == first_checkpoint_id)
            .expect("push should contain the first checkpoint body");
        let first_checkpoint = &request.commits[first_checkpoint_index];
        assert_eq!(
            first_checkpoint
                .state_alias
                .as_ref()
                .expect("first checkpoint alias exists")
                .source_commit_id,
            first_source_id,
        );
        assert!(
            !first_checkpoint
                .parent_commit_ids
                .contains(&first_source_id),
            "the fixture must exercise a state source distinct from semantic ancestry",
        );
        let first_source_index = request
            .commits
            .iter()
            .position(|commit| commit.commit_id == first_source_id)
            .expect("push must retain the first alias source through pre-push GC");
        let first_source_parent_index = request
            .commits
            .iter()
            .position(|commit| commit.commit_id == first_source_parent_id)
            .expect("push must retain the alias source parent through pre-push GC");
        let second_source_index = request
            .commits
            .iter()
            .position(|commit| commit.commit_id == second_source_id)
            .expect("push must include the second alias source body");
        let second_checkpoint_index = request
            .commits
            .iter()
            .position(|commit| commit.commit_id == second_checkpoint_id)
            .expect("push should contain the second checkpoint body");
        assert!(first_source_parent_index < first_source_index);
        assert!(first_source_index < first_checkpoint_index);
        assert!(first_checkpoint_index < second_source_index);
        assert!(second_source_index < second_checkpoint_index);
        authority
            .push_sync_repository(&request)
            .await
            .expect("dependency-complete checkpoint push should import");
        assert_eq!(
            export_sync_commit(&authority, &second_checkpoint_id)
                .await
                .expect("imported checkpoint should export")
                .expect("imported checkpoint body should exist"),
            canonical_checkpoint,
            "materialized checkpoint export must preserve canonical wire authority",
        );
    }

    #[tokio::test]
    async fn history_batch_prefers_authored_locator_over_selected_fallback() {
        let authority = open_lix().await.expect("authority should open");
        let baseline = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("baseline snapshot should load");
        let replica = replica_from_snapshot(&authority, &baseline).await;

        write_key_value(&authority, "same-batch-locator", "authored").await;
        authority
            .create_checkpoint()
            .await
            .expect("authority checkpoint should succeed");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("checkpoint snapshot should load");
        let (_, head) = default_head(&snapshot);
        let mut checkpoint_history = authority
            .sync_history(&head, 1)
            .await
            .expect("checkpoint body should load");
        close_history_boundary_bodies(&authority, &mut checkpoint_history).await;
        let mut checkpoint_rows = Vec::new();
        for boundary in &checkpoint_history.boundaries {
            let page = authority
                .pull_sync_snapshot_rows(
                    &boundary.commit_id,
                    &boundary.commit_id,
                    None,
                    super::super::MAX_SYNC_REQUEST_ITEMS,
                )
                .await
                .expect("checkpoint boundary rows should load");
            assert_eq!(page.continuation, None);
            checkpoint_rows.extend(page.rows);
        }
        let shared_change_id = checkpoint_rows
            .iter()
            .find(|row| {
                row.schema_key == "lix_key_value"
                    && row.row_pk
                        == serde_json::json!([{"type": "string", "value": "same-batch-locator"}])
            })
            .map(|row| row.change_id.clone())
            .expect("checkpoint should select the authored working change");
        let shared_change_id_parsed =
            ChangeId::parse_lix(&shared_change_id, "same-batch shared change")
                .expect("shared change id should parse");
        let authored_commit_id = direct_change_locator(shared_change_id_parsed)
            .expect("locally authored change should encode its commit address")
            .commit_id;
        let mut authored_history = authority
            .sync_history(&authored_commit_id.to_string(), 1)
            .await
            .expect("selected change's authored body should load");
        close_history_boundary_bodies(&authority, &mut authored_history).await;
        assert!(
            authored_history.commits[0]
                .members
                .iter()
                .any(|member| { member.authored && member.change_id == shared_change_id })
        );
        replica
            .import_sync_history_headers(&authored_history.commit_headers)
            .await
            .expect("authored headers should import");
        replica
            .import_sync_history_headers(&checkpoint_history.commit_headers)
            .await
            .expect("checkpoint headers should import");
        let commits = authored_history
            .commits
            .into_iter()
            .chain(checkpoint_history.commits)
            .map(|commit| (commit.commit_id.clone(), commit))
            .collect::<BTreeMap<_, _>>()
            .into_values()
            .collect::<Vec<_>>();
        let boundaries = authored_history
            .boundaries
            .into_iter()
            .chain(checkpoint_history.boundaries)
            .map(|boundary| (boundary.commit_id.clone(), boundary))
            .collect::<BTreeMap<_, _>>()
            .into_values()
            .collect::<Vec<_>>();
        let mut boundary_rows = Vec::new();
        for boundary in &boundaries {
            let page = authority
                .pull_sync_snapshot_rows(
                    &boundary.commit_id,
                    &boundary.commit_id,
                    None,
                    super::super::MAX_SYNC_REQUEST_ITEMS,
                )
                .await
                .expect("history boundary rows should load");
            assert_eq!(page.continuation, None);
            boundary_rows.extend(page.rows);
        }

        replica
            .import_sync_history_boundaries(&commits, &boundaries, &boundary_rows)
            .await
            .expect("one batch may contain selected and authored copies of one change");

        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("replica change scan should open");
        let changes = crate::tracked_state::scan_change_records_from_commit_deltas(&read)
            .await
            .expect("imported changes should scan");
        assert_eq!(
            changes
                .iter()
                .filter(|change| change.change_id == shared_change_id_parsed)
                .count(),
            1,
            "selected fallback must not duplicate an authored change imported in the same batch",
        );
        drop(read);

        // Reproduce the sparse-replica failure: the selected checkpoint has a
        // canonical standalone payload, but its packed locator is absent.
        let adapter = replica.storage_adapter();
        let mut missing_locator = adapter.new_write_set();
        crate::tracked_state::stage_delete_change_locators(
            &mut missing_locator,
            [shared_change_id_parsed],
        );
        adapter
            .commit_certified_replica_write_set(
                crate::sync::certified_replica_write_capability(),
                missing_locator,
                StorageWriteOptions::default(),
            )
            .await
            .expect("missing-locator fixture should commit");
        let missing_locator_read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("missing-locator scan should open");
        let changes =
            crate::tracked_state::scan_change_records_from_commit_deltas(&missing_locator_read)
                .await
                .expect("standalone canonical payload should recover a missing locator");
        assert_eq!(
            changes
                .iter()
                .filter(|change| change.change_id == shared_change_id_parsed)
                .count(),
            1,
            "authored and selected packed copies must remain deduplicated without a locator",
        );
        drop(missing_locator_read);

        let retirement_read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("authored retirement read should open");
        let authored_manifest = load_commit_state_manifest(&retirement_read, authored_commit_id)
            .await
            .expect("authored manifest lookup should succeed")
            .expect("authored manifest should exist before reclamation");
        let mut retirement = adapter.new_write_set();
        crate::tracked_state::stage_delete_commit_state_manifest_for_gc(
            &retirement_read,
            &mut retirement,
            authored_commit_id,
            &authored_manifest,
        )
        .await
        .expect("authored physical authority should retire");
        drop(retirement_read);
        adapter
            .commit_certified_replica_write_set(
                crate::sync::certified_replica_write_capability(),
                retirement,
                StorageWriteOptions::default(),
            )
            .await
            .expect("authored retirement should commit");

        let warm = replica
            .open_another_session()
            .await
            .expect("warm sparse replica should reopen");
        let warm_read = warm
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("warm sparse change scan should open");
        let changes = crate::tracked_state::scan_change_records_from_commit_deltas(&warm_read)
            .await
            .expect("selected checkpoint should use its standalone canonical fallback");
        assert_eq!(
            changes
                .iter()
                .filter(|change| change.change_id == shared_change_id_parsed)
                .count(),
            0,
            "manually retiring the final physical commit authority removes it from history scans",
        );
    }

    #[tokio::test]
    #[ignore = "v3 replicas are read-only serving caches"]
    async fn snapshot_live_state_omits_tombstones_and_remains_writable() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/deleted-before-snapshot.txt".to_owned()),
                    Value::Text("old".to_owned()),
                ],
            )
            .await
            .expect("file create should succeed");
        authority
            .create_checkpoint()
            .await
            .expect("create checkpoint should succeed");
        authority
            .execute(
                "DELETE FROM lix_file WHERE path = $1",
                &[Value::Text("/deleted-before-snapshot.txt".to_owned())],
            )
            .await
            .expect("file delete should succeed");
        authority
            .create_checkpoint()
            .await
            .expect("delete checkpoint should succeed");

        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let absent = replica
            .execute(
                "SELECT path FROM lix_file WHERE path = $1",
                &[Value::Text("/deleted-before-snapshot.txt".to_owned())],
            )
            .await
            .expect("live-state read should succeed");
        assert!(
            absent.rows().is_empty(),
            "snapshot must not revive tombstones"
        );

        replica
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/deleted-before-snapshot.txt".to_owned()),
                    Value::Text("new".to_owned()),
                ],
            )
            .await
            .expect("recreating a deleted file after bootstrap should succeed");
        replica
            .create_checkpoint()
            .await
            .expect("checkpoint after tombstone-free bootstrap should succeed");
    }

    #[tokio::test]
    async fn exact_push_is_atomic_idempotent_and_creates_a_writable_checkpoint_epoch() {
        let source = open_lix().await.expect("source should open");
        write_key_value(&source, "immutable-collision", "original").await;
        let source_snapshot = source
            .pull_sync_repository(None, 1)
            .await
            .expect("source snapshot should load");
        let (_, source_head) = default_head(&source_snapshot);
        let source_history = source
            .sync_history(&source_head, 100)
            .await
            .expect("source history should load");
        let source_commit = source_history
            .commits
            .iter()
            .find(|commit| commit.commit_id == source_head)
            .cloned()
            .expect("source head commit should exist");
        let source_commits = source_history.commits.clone();
        if let Some(base) = source_commit.base_commit_id.as_deref() {
            assert!(
                source_commits.iter().any(|commit| commit.commit_id == base),
                "history inlines the pinned base dependency",
            );
        }

        let target = open_lix().await.expect("target should open");
        let branch_id = "01920000-0000-7000-8000-000000001499".to_string();
        let request = SyncPushRequest {
            commits: source_commits,
            ref_updates: vec![SyncRefUpdate {
                branch_id: branch_id.clone(),
                expected_head_commit_id: None,
                expected_checkpoint_commit_id: None,
                head_commit_id: Some(source_head.clone()),
                checkpoint_commit_id: Some(source_head.clone()),
            }],
            inline_blobs: Vec::new(),
        };
        let first = target
            .push_sync_repository(&request)
            .await
            .expect("exact push should succeed");
        let second = target
            .push_sync_repository(&request)
            .await
            .expect("exact replay should be idempotent");
        assert_eq!(second.cursor, first.cursor);
        let mut conflicting = request.clone();
        let member = conflicting
            .commits
            .iter_mut()
            .flat_map(|commit| &mut commit.members)
            .find(|member| member.schema_key == "lix_key_value")
            .unwrap();
        member
            .snapshot
            .as_mut()
            .unwrap()
            .as_object_mut()
            .unwrap()
            .insert("value".to_owned(), serde_json::json!("different"));
        let pk = RowPk::from_typed_json_array_value(&member.row_pk).unwrap();
        let row = crate::plugin::runtime::WasmTypedRow::from_builtin_json(
            &member.schema_key,
            &pk,
            member.snapshot.as_ref().unwrap(),
        )
        .unwrap();
        member.snapshot_payload =
            Some(super::super::commit::encode_sync_row_payload(&row).unwrap());
        let error = target
            .push_sync_repository(&conflicting)
            .await
            .expect_err("same commit id with different content must fail");
        assert_eq!(
            error.code,
            super::super::SYNC_IMMUTABLE_OBJECT_MISMATCH_CODE
        );
        assert!(error.message.contains("different content"));
        assert_eq!(
            target
                .sync_history(&source_head, 1)
                .await
                .expect("imported history should load")
                .commits
                .into_iter()
                .find(|commit| commit.commit_id == source_head),
            Some(source_commit)
        );

        target
            .switch_branch(SwitchBranchOptions {
                branch_id: branch_id.clone(),
            })
            .await
            .expect("imported branch should be switchable");
        target
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/after-sync.txt".to_string()),
                    Value::Text("works".to_string()),
                ],
            )
            .await
            .expect("first file write after sync must have a checkpoint cursor");

        let adapter = target.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read should open");
        let control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("control should load")
            .expect("control should exist");
        assert!(control.working_diff_checkpoint_commit_id.is_some());
    }

    #[tokio::test]
    async fn more_than_one_push_window_of_offline_commits_drains_without_repeating_a_batch() {
        let authority = open_lix().await.expect("authority should open");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let replica = replica_from_snapshot(&authority, &snapshot).await;

        for index in 0..=super::super::MAX_SYNC_REQUEST_ITEMS {
            write_key_value(&replica, "offline-window", &format!("value-{index}")).await;
        }

        let mut pushed_commit_ids = BTreeSet::new();
        let mut push_count = 0usize;
        loop {
            let Some(request) = replica
                .build_sync_push(TEST_REMOTE, super::super::MAX_SYNC_REQUEST_ITEMS)
                .await
                .expect("bounded offline push should build")
            else {
                break;
            };
            assert!(
                request.commits.len() + request.ref_updates.len()
                    <= super::super::MAX_SYNC_REQUEST_ITEMS,
                "every request must obey the shared item limit",
            );
            for commit in &request.commits {
                assert!(
                    pushed_commit_ids.insert(commit.commit_id.clone()),
                    "an acknowledged commit batch must not be rebuilt",
                );
            }
            let receipt = authority
                .push_sync_repository(&request)
                .await
                .expect("authority should accept bounded push");
            let cursor = replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("replica cursor should load")
                .expect("replica should be initialized");
            let delta = authority
                .pull_sync_repository(Some(cursor), super::super::MAX_SYNC_REQUEST_ITEMS)
                .await
                .expect("authority acknowledgement delta should load");
            assert!(
                match &delta {
                    SyncRepositoryPullResponse::Delta { cursor, .. } => *cursor >= receipt.cursor,
                    SyncRepositoryPullResponse::Snapshot { .. } => false,
                },
                "delta should cover the accepted push",
            );
            replica
                .apply_sync_repository_pull(TEST_REMOTE, &delta)
                .await
                .expect("replica should persist the authority acknowledgement");
            let read = replica
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("acknowledgement state read should open");
            let acknowledged = load_replica_state(&read)
                .await
                .expect("acknowledgement state should load")
                .0
                .expect("replica state should exist");
            assert!(
                acknowledged.authority_known_commit_ids.len() <= 1,
                "a linear multi-page upload retains only its unattached frontier",
            );
            push_count += 1;
        }

        assert!(push_count >= 2, "the fixture must cross one push window");
        assert_eq!(
            pushed_commit_ids.len(),
            super::super::MAX_SYNC_REQUEST_ITEMS + 1,
        );
        assert_eq!(
            read_key_value(&authority, "offline-window").await,
            format!("value-{}", super::super::MAX_SYNC_REQUEST_ITEMS),
        );
    }

    #[tokio::test]
    async fn ref_conflict_does_not_import_commit() {
        let source = open_lix().await.expect("source should open");
        source
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/conflict.txt".to_string()),
                    Value::Text("content".to_string()),
                ],
            )
            .await
            .expect("source write should succeed");
        let source_snapshot = source
            .pull_sync_repository(None, 1)
            .await
            .expect("source snapshot should load");
        let (_, source_head) = default_head(&source_snapshot);
        let source_commit = source
            .sync_history(&source_head, 1)
            .await
            .expect("source history should load")
            .commits
            .into_iter()
            .next()
            .expect("source head commit should exist");

        let target = open_lix().await.expect("target should open");
        let target_snapshot = target
            .pull_sync_repository(None, 1)
            .await
            .expect("target snapshot should load");
        let (target_branch, _) = default_head(&target_snapshot);
        let error = target
            .push_sync_repository(&SyncPushRequest {
                commits: vec![source_commit],
                ref_updates: vec![SyncRefUpdate {
                    branch_id: target_branch,
                    expected_head_commit_id: None,
                    expected_checkpoint_commit_id: None,
                    head_commit_id: Some(source_head.clone()),
                    checkpoint_commit_id: Some(source_head.clone()),
                }],
                inline_blobs: Vec::new(),
            })
            .await
            .expect_err("stale ref CAS must fail");
        assert_eq!(
            error.code,
            LixError::CODE_TRANSACTION_CONFLICT,
            "unexpected pre-CAS failure: {error:?}",
        );
        let error = target
            .sync_history(&source_head, 1)
            .await
            .expect_err("missing history head must fail");
        assert_eq!(error.code, LixError::CODE_COMMIT_NOT_FOUND);
    }

    #[tokio::test]
    async fn authority_rejects_deleting_the_repository_default_branch() {
        let authority = open_lix().await.expect("authority should open");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (default_branch_id, default_head_id) = default_head(&snapshot);

        let error = authority
            .push_sync_repository(&SyncPushRequest {
                commits: Vec::new(),
                ref_updates: vec![SyncRefUpdate {
                    branch_id: default_branch_id.clone(),
                    expected_head_commit_id: Some(default_head_id.clone()),
                    expected_checkpoint_commit_id: Some(default_head_id.clone()),
                    head_commit_id: None,
                    checkpoint_commit_id: None,
                }],
                inline_blobs: Vec::new(),
            })
            .await
            .expect_err("the repository default branch cannot be deleted");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);

        let after = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should remain readable");
        assert_eq!(default_head(&after), (default_branch_id, default_head_id));
    }

    #[tokio::test]
    async fn repository_events_keep_deleted_branch_commit_bodies_replayable_after_gc() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .set_sync_role(super::super::SyncRole::Authority)
            .expect("authority role should install");
        let main_branch_id = authority
            .active_branch_id()
            .await
            .expect("main branch should load");
        let branch = authority
            .create_branch(CreateBranchOptions {
                id: Some("01920000-0000-7000-8000-000000001778".to_owned()),
                name: "event-retention".to_owned(),
                from_commit_id: None,
            })
            .await
            .expect("disposable branch should be created");
        authority
            .switch_branch(SwitchBranchOptions {
                branch_id: branch.id.clone(),
            })
            .await
            .expect("disposable branch should become active");
        write_key_value(&authority, "event-retention", "must-survive-gc").await;
        authority
            .switch_branch(SwitchBranchOptions {
                branch_id: main_branch_id,
            })
            .await
            .expect("main branch should become active again");
        authority
            .execute(
                "DELETE FROM lix_branch WHERE id = $1",
                &[Value::Text(branch.id)],
            )
            .await
            .expect("disposable branch should be deleted");

        let adapter = authority.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("GC read should open");
        let mut writes = adapter.new_write_set();
        crate::gc::stage_repository_gc(SharedStorageAdapterRead::new(read), &mut writes)
            .await
            .expect("repository GC should stage");
        adapter
            .commit_certified_replica_write_set(
                crate::sync::certified_replica_write_capability(),
                writes,
                StorageWriteOptions::default(),
            )
            .await
            .expect("repository GC should commit");

        let replay = authority
            .pull_sync_repository(Some(0), super::super::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("every retained event must still export its commit bodies");
        let SyncRepositoryPullResponse::Delta { events, .. } = replay else {
            panic!("cursor pull should return a delta");
        };
        assert!(
            events.iter().any(|event| {
                event.commits.iter().any(|commit| {
                    commit.members.iter().any(|member| {
                        member.schema_key == "lix_key_value"
                            && member
                                .snapshot
                                .as_ref()
                                .and_then(|snapshot| snapshot.get("key"))
                                .and_then(serde_json::Value::as_str)
                                == Some("event-retention")
                    })
                })
            }),
            "the deleted branch's replayable event body disappeared",
        );
    }

    #[tokio::test]
    async fn authority_preserves_a_noncanonical_looking_change_via_locator_fallback() {
        let source = open_lix().await.expect("source should open");
        write_key_value(&source, "forged-address", "payload").await;
        let snapshot = source
            .pull_sync_repository(None, 1)
            .await
            .expect("source snapshot should load");
        let (_, head) = default_head(&snapshot);
        let mut commits = source
            .sync_history(&head, super::super::MAX_SYNC_HISTORY_PAGE_SIZE)
            .await
            .expect("source history should load")
            .commits;
        let commit = commits
            .iter_mut()
            .find(|commit| commit.commit_id == head)
            .expect("source head should have a body");
        let member = commit
            .members
            .iter_mut()
            .find(|member| member.authored)
            .expect("written commit should have an authored member");
        let mut forged = *CommitId::parse_lix(&head, "forged commit")
            .expect("head should parse")
            .as_uuid()
            .as_bytes();
        forged[12..].copy_from_slice(&50_u32.to_be_bytes());
        member.change_id = ChangeId::new(uuid::Uuid::from_bytes(forged)).to_string();

        let target = open_lix().await.expect("target authority should open");

        target
            .push_sync_repository(&SyncPushRequest {
                commits: commits.clone(),
                ref_updates: Vec::new(),
                inline_blobs: Vec::new(),
            })
            .await
            .expect("the complete commit's authoritative id should use locator fallback");
        assert_eq!(
            target
                .sync_history(&head, 1)
                .await
                .expect("imported history should load")
                .commits
                .into_iter()
                .find(|candidate| candidate.commit_id == head),
            commits.into_iter().find(|commit| commit.commit_id == head),
        );
    }

    #[tokio::test]
    async fn snapshot_rejects_metadata_without_the_default_branch() {
        let authority = open_lix().await.expect("authority should open");
        let mut snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        let (default_branch_id, _) = default_head(&snapshot);
        let SyncRepositoryPullResponse::Snapshot { branches, .. } = &mut snapshot else {
            unreachable!("initial pull is a snapshot");
        };
        branches.retain(|branch| branch.branch_id != default_branch_id);

        let storage = Memory::new();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&default_branch_id))
            .await
            .expect("replica storage should initialize");
        let replica = open_lix()
            .with_storage(storage)
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        let error = replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect_err("default-less metadata must be rejected");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("headed default branch"));
    }

    #[tokio::test]
    async fn snapshot_rejects_a_default_branch_that_disagrees_with_tracked_state() {
        let authority = open_lix().await.expect("authority should open");
        let secondary = authority
            .create_branch(CreateBranchOptions {
                id: Some("01920000-0000-7000-8000-000000001501".to_owned()),
                name: "secondary".to_owned(),
                from_commit_id: None,
            })
            .await
            .expect("secondary branch should be created");
        let mut snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        let SyncRepositoryPullResponse::Snapshot {
            default_branch_id, ..
        } = &mut snapshot
        else {
            unreachable!("initial pull is a snapshot");
        };
        *default_branch_id = secondary.id.clone();

        let storage = Memory::new();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&secondary.id))
            .await
            .expect("replica storage should initialize");
        let replica = open_lix()
            .with_storage(storage)
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        let error = replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect_err("metadata cannot redefine the tracked repository default");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("canonical tracked row"));
    }

    fn sparse_checkpoint_header() -> ParsedSyncHeader {
        ParsedSyncHeader {
            is_checkpoint: true,
            commit_id: CommitId::for_test_label("sparse-inventory-checkpoint"),
            parent_commit_ids: vec![CommitId::for_test_label("sparse-inventory-parent")],
            base_commit_id: None,
            account_id: crate::SYSTEM_ACCOUNT_ID.to_owned(),
            created_at: LixTimestamp::expect_parse("created_at", "2026-05-12T00:00:00Z"),
            global_scope: true,
            generation: 4,
            first_parent_jump_commit_id: CommitId::for_test_label("sparse-inventory-jump"),
            first_parent_jump_span: 3,
        }
    }

    #[test]
    fn sparse_checkpoint_jump_requires_explicit_inventory_permission() {
        let header = sparse_checkpoint_header();
        let inventory_ids = BTreeSet::from([header.commit_id]);
        let headers = BTreeMap::from([(header.commit_id, header)]);
        let error = validate_sync_header_set(&headers, "test snapshot", &BTreeSet::new())
            .expect_err("ordinary history must include jump boundaries");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("missing jump boundary"));
        validate_sync_header_set(&headers, "test snapshot", &inventory_ids)
            .expect("explicit sparse inventory may defer an absent jump boundary");
    }

    #[test]
    fn sparse_checkpoint_jump_rejects_invalid_metadata() {
        for mutation in ["self jump", "oversized span", "unmarked"] {
            let mut header = sparse_checkpoint_header();
            match mutation {
                "self jump" => header.first_parent_jump_commit_id = header.commit_id,
                "oversized span" => header.first_parent_jump_span = header.generation + 1,
                "unmarked" => header.is_checkpoint = false,
                _ => unreachable!(),
            }
            let inventory_ids = BTreeSet::from([header.commit_id]);
            let headers = BTreeMap::from([(header.commit_id, header)]);
            let error = validate_sync_header_set(&headers, "test snapshot", &inventory_ids)
                .expect_err(mutation);
            assert_eq!(error.code, LixError::CODE_INVALID_PARAM, "{mutation}");
        }
    }

    #[test]
    fn sparse_checkpoint_jump_still_validates_present_boundary_generation() {
        let header = sparse_checkpoint_header();
        let inventory_ids = BTreeSet::from([header.commit_id]);
        let mut jump = header.clone();
        jump.commit_id = header.first_parent_jump_commit_id;
        jump.is_checkpoint = false;
        jump.parent_commit_ids.clear();
        jump.generation = 0;
        jump.first_parent_jump_commit_id = jump.commit_id;
        jump.first_parent_jump_span = 0;
        let headers = BTreeMap::from([(header.commit_id, header), (jump.commit_id, jump)]);
        let error = validate_sync_header_set(&headers, "test snapshot", &inventory_ids)
            .expect_err("present jump boundary must match the declared span");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("invalid jump span"));
    }

    #[tokio::test]
    async fn incoming_header_preserves_local_scope_digest_but_checks_identity() {
        let local = open_lix().await.unwrap();
        write_key_value(&local, "digest-proof", "local").await;
        let head = CommitId::parse_lix(&current_branch_head(&local).await, "test head").unwrap();
        let storage = local.storage_adapter();
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .unwrap();
        let record = load_commit_record(&read, head).await.unwrap().unwrap();
        let mut wire = sync_header_from_record(&record, false);
        let header = ParsedSyncHeader::parse(&wire).unwrap();
        assert!(header.matches_record(&record));
        wire.account_id = "0197bf96-8733-7000-8000-000000000099".to_owned();
        assert!(
            !ParsedSyncHeader::parse(&wire)
                .unwrap()
                .matches_record(&record)
        );
    }

    #[tokio::test]
    async fn snapshot_accepts_hosted_copy_with_new_authority_commits() {
        for advance_main in [false, true] {
            let local = open_lix().await.unwrap();
            write_key_value(&local, "before-publication", "preserved").await;
            let mut bytes = Vec::new();
            local.export_snapshot().write_to(&mut bytes).await.unwrap();
            let authority = open_lix()
                .from_snapshot(futures_lite::io::Cursor::new(bytes))
                .await
                .unwrap();
            authority
                .ensure_account(
                    "0197bf96-8733-7000-8000-000000000001",
                    "Hosted user",
                    "human",
                )
                .await
                .unwrap();
            if advance_main {
                write_key_value(&authority, "after-publication", "server").await;
            }
            let snapshot = authority.pull_sync_repository(None, 1).await.unwrap();
            let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
            local
                .set_sync_role(super::super::SyncRole::Replica)
                .unwrap();
            let result = local
                .try_install_initial_sync_snapshot(
                    TEST_REMOTE,
                    crate::ANONYMOUS_ACCOUNT_ID,
                    &snapshot,
                    &history.commits,
                    &history.commit_headers,
                    &rows,
                    &checkpoint_roots,
                )
                .await
                .expect("hosted copy extends the source without losing local commits");
            assert!(matches!(result, InitialSyncSnapshotInstall::Installed));
            // This fixture constructs no connected authority. Read the installed cache
            // directly instead of entering the public execution/session machinery.
            let storage = local.storage_adapter();
            let read = storage
                .begin_read(StorageReadOptions::default())
                .await
                .unwrap();
            let reader =
                HotStateContext::new(TrackedStateContext::new(), CommitGraphContext::new())
                    .reader(SharedStorageAdapterRead::new(read));
            let (branch_id, _) = default_head(&snapshot);
            for (key, expected) in [
                ("before-publication", "preserved"),
                ("after-publication", "server"),
            ] {
                if key == "after-publication" && !advance_main {
                    continue;
                }
                let row = reader
                    .load_row(&HotStateRowRequest {
                        schema_key: "lix_key_value".to_owned(),
                        branch_id: branch_id.clone(),
                        row_pk: RowPk::single(key),
                        file_id: NullableKeyFilter::Null,
                    })
                    .await
                    .unwrap()
                    .expect("published row remains available");
                let content: serde_json::Value = serde_json::from_str(
                    row.snapshot_content.as_deref().expect("live row content"),
                )
                .unwrap();
                assert_eq!(content["value"], expected);
            }
        }
    }

    #[tokio::test]
    async fn snapshot_rejects_local_edits_after_hosted_copy_without_losing_them() {
        let local = open_lix().await.unwrap();
        write_key_value(&local, "before-publication", "shared").await;
        let mut bytes = Vec::new();
        local.export_snapshot().write_to(&mut bytes).await.unwrap();
        let authority = open_lix()
            .from_snapshot(futures_lite::io::Cursor::new(bytes))
            .await
            .unwrap();
        write_key_value(&local, "after-copy", "local").await;
        write_key_value(&authority, "after-copy", "server").await;
        let snapshot = authority.pull_sync_repository(None, 1).await.unwrap();
        let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        local
            .set_sync_role(super::super::SyncRole::Replica)
            .unwrap();
        let error = local
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect_err("diverged local commits must not be replaced");
        assert_eq!(error.code, LixError::CODE_TRANSACTION_CONFLICT);
        local
            .set_sync_role(super::super::SyncRole::Disabled)
            .unwrap();
        assert_eq!(read_key_value(&local, "after-copy").await, "local");
        assert_eq!(
            local
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .unwrap(),
            None
        );
    }

    #[tokio::test]
    async fn snapshot_rejects_and_preserves_a_locally_advanced_same_id_branch() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "authority-only", "remote").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("authority snapshot should load");
        let (branch_id, _) = default_head(&snapshot);

        let storage = Memory::new();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .expect("local storage should initialize with the same branch id");
        let local = open_lix()
            .with_storage(storage)
            .await
            .expect("local repository should open");
        write_key_value(&local, "local-only", "must-survive").await;
        let local_head_before = local
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("local head should load")
            .rows()[0]
            .get::<String>("id")
            .expect("local head should be text");
        local
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        let (history, rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;

        let error = local
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect_err("snapshot must not orphan a locally advanced same-id branch");
        assert_eq!(error.code, LixError::CODE_TRANSACTION_CONFLICT);
        assert!(error.message.contains("locally advanced branch"));
        local
            .set_sync_role(super::super::SyncRole::Disabled)
            .expect("a rejected bootstrap should return the fixture to standalone mode");
        assert_eq!(read_key_value(&local, "local-only").await, "must-survive");
        let local_head_after = local
            .execute("SELECT lix_active_branch_commit_id() AS id", &[])
            .await
            .expect("local head should remain readable")
            .rows()[0]
            .get::<String>("id")
            .expect("local head should be text");
        assert_eq!(local_head_after, local_head_before);
        assert_eq!(
            local
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("cursor query should succeed"),
            None,
            "failed snapshot must remain atomic",
        );
    }

    #[tokio::test]
    async fn snapshot_rejects_an_incomplete_row_sequence_without_advancing_cursor() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "complete-a", "one").await;
        write_key_value(&authority, "complete-b", "two").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot metadata should load");
        let (branch_id, _) = default_head(&snapshot);
        let (history, mut rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        assert!(rows.len() > 1, "fixture must have more than one live row");
        let omitted = rows
            .iter()
            .position(|row| {
                row.schema_key == "lix_key_value"
                    && row
                        .snapshot
                        .as_ref()
                        .and_then(|snapshot| snapshot.get("key"))
                        .and_then(serde_json::Value::as_str)
                        == Some("complete-a")
            })
            .expect("fixture row should exist");
        rows.remove(omitted);

        let storage = Memory::new();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .expect("replica storage should initialize");
        let replica = open_lix()
            .with_storage(storage)
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        let error = replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect_err("an incomplete row sequence must fail root verification");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("do not match head"));
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("cursor query should succeed"),
            None,
            "failed root verification must not advance the replica cursor",
        );
    }

    #[tokio::test]
    async fn snapshot_live_value_root_rejects_tampered_content_without_advancing_cursor() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "certified-content", "authority").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot metadata should load");
        let (branch_id, _) = default_head(&snapshot);
        let (history, mut rows, checkpoint_roots) = snapshot_parts(&authority, &snapshot).await;
        let row = rows
            .iter_mut()
            .find(|row| {
                row.schema_key == "lix_key_value"
                    && row
                        .snapshot
                        .as_ref()
                        .and_then(|snapshot| snapshot.get("key"))
                        .and_then(serde_json::Value::as_str)
                        == Some("certified-content")
            })
            .expect("fixture row should exist");
        row.snapshot.as_mut().expect("live row has content")["value"] =
            serde_json::json!("tampered");

        let storage = Memory::new();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .expect("replica storage should initialize");
        let replica = open_lix()
            .with_storage(storage)
            .await
            .expect("replica should open");
        replica
            .set_sync_role(super::super::SyncRole::Replica)
            .expect("replica role should install");
        let error = replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .expect_err("tampered content must fail live-value verification");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert_eq!(
            replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("cursor query should succeed"),
            None,
        );
    }

    #[tokio::test]
    async fn snapshot_row_pages_are_complete_ordered_and_exclusive() {
        let authority = open_lix().await.expect("authority should open");
        for index in 0..8 {
            write_key_value(&authority, &format!("page-{index:02}"), "value").await;
        }
        for index in 0..6 {
            authority
                .execute(
                    "DELETE FROM lix_key_value WHERE key = $1",
                    &[Value::Text(format!("page-{index:02}"))],
                )
                .await
                .expect("tombstone-heavy page fixture should delete a row");
        }
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot metadata should load");
        let (branch_id, head) = default_head(&snapshot);
        let complete = authority
            .pull_sync_snapshot_rows(
                &branch_id,
                &head,
                None,
                super::super::MAX_SYNC_REQUEST_ITEMS,
            )
            .await
            .expect("complete page should load");
        assert!(complete.continuation.is_none());

        let mut paged = Vec::new();
        let mut continuation = None;
        loop {
            let page = authority
                .pull_sync_snapshot_rows(&branch_id, &head, continuation.as_deref(), 3)
                .await
                .expect("bounded page should load");
            paged.extend(page.rows);
            let Some(next) = page.continuation else {
                break;
            };
            assert_ne!(continuation.as_deref(), Some(next.as_str()));
            continuation = Some(next);
        }
        assert_eq!(paged, complete.rows);
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica outbox semantics were removed"]
    async fn cold_merge_history_page_boundaries_cover_every_external_parent() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "base", "shared").await;
        let base_snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("base snapshot should load");
        let cold = replica_from_snapshot(&authority, &base_snapshot).await;
        let left = replica_from_snapshot(&authority, &base_snapshot).await;
        let right = replica_from_snapshot(&authority, &base_snapshot).await;

        write_key_value(&left, "left", "authority-first").await;
        write_key_value(&right, "right", "secondary-parent").await;
        publish_pending(&left, &authority).await;
        let delta = authority
            .pull_sync_repository(Some(0), 128)
            .await
            .expect("authority delta should load");
        right
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("right replica should reconcile into a merge");
        let merge_push = publish_pending(&right, &authority).await;
        let merge_head = merge_push.ref_updates[0]
            .head_commit_id
            .clone()
            .expect("merge push should advance the branch");

        let mut page = authority
            .sync_history(&merge_head, 2)
            .await
            .expect("cold merge page should load");
        let body_ids = page
            .commits
            .iter()
            .map(|commit| commit.commit_id.as_str())
            .collect::<BTreeSet<_>>();
        let merge = page
            .commits
            .iter()
            .find(|commit| commit.commit_id == merge_head)
            .expect("page should contain its merge head");
        assert_eq!(merge.parent_commit_ids.len(), 2);
        assert!(
            body_ids.contains(merge.parent_commit_ids[0].as_str()),
            "the merge first parent should be in the page"
        );
        assert!(
            merge
                .parent_commit_ids
                .iter()
                .any(|parent| !body_ids.contains(parent.as_str())),
            "the merge secondary parent should be outside the page"
        );
        let boundary_ids = page
            .boundaries
            .iter()
            .map(|boundary| boundary.commit_id.as_str())
            .collect::<BTreeSet<_>>();
        assert!(
            boundary_ids.contains(merge_head.as_str()),
            "a merge with an external secondary parent must be a boundary"
        );
        assert_eq!(
            boundary_ids.len(),
            3,
            "the merge, oldest causal body, and external global base all need boundaries"
        );
        let expected_page_commits = page.commits.clone();
        close_history_boundary_bodies(&authority, &mut page).await;

        let mut rows = Vec::new();
        for boundary in &page.boundaries {
            let mut continuation = None;
            loop {
                let row_page = authority
                    .pull_sync_snapshot_rows(
                        &boundary.commit_id,
                        &boundary.commit_id,
                        continuation.as_deref(),
                        super::super::MAX_SYNC_REQUEST_ITEMS,
                    )
                    .await
                    .expect("boundary snapshot rows should load");
                rows.extend(row_page.rows);
                let Some(next) = row_page.continuation else {
                    break;
                };
                continuation = Some(next);
            }
        }
        cold.import_sync_history_headers(&page.commit_headers)
            .await
            .expect("cold replica should accept sparse topology");
        cold.import_sync_history_boundaries(&page.commits, &page.boundaries, &rows)
            .await
            .expect("cold replica should import a merge page with two boundaries");
        assert_eq!(
            cold.sync_history(&merge_head, 2)
                .await
                .expect("imported merge history should be readable")
                .commits,
            expected_page_commits,
        );
    }

    #[tokio::test]
    async fn history_headers_reject_a_forged_generation() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "generation", "parent").await;
        write_key_value(&authority, "generation", "child").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot metadata should load");
        let (_, head) = default_head(&snapshot);
        let mut history = authority
            .sync_history(&head, 1)
            .await
            .expect("history should load");
        history
            .commit_headers
            .iter_mut()
            .find(|header| header.commit_id == head)
            .expect("head header should exist")
            .generation += 7;
        let replica = open_lix().await.expect("replica should open");
        let error = replica
            .import_sync_history_headers(&history.commit_headers)
            .await
            .expect_err("forged generation must be rejected");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("invalid generation"));
    }

    #[tokio::test]
    async fn deferred_history_body_rejects_header_scope_mismatch() {
        let authority = open_lix().await.expect("authority should open");
        let base = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("base snapshot should load");
        let replica = replica_from_snapshot(&authority, &base).await;
        write_key_value(&authority, "scope-mismatch", "body").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("updated snapshot should load");
        let (_, head) = default_head(&snapshot);
        let history = authority
            .sync_history(&head, 1)
            .await
            .expect("history should load");
        replica
            .import_sync_history_headers(&history.commit_headers)
            .await
            .expect("certified headers should import");
        let mut rows = Vec::new();
        for boundary in &history.boundaries {
            let page = authority
                .pull_sync_snapshot_rows(
                    &boundary.commit_id,
                    &boundary.commit_id,
                    None,
                    super::super::MAX_SYNC_REQUEST_ITEMS,
                )
                .await
                .expect("boundary rows should load");
            assert!(page.continuation.is_none());
            rows.extend(page.rows);
        }

        let mut forged = history.commits.clone();
        forged[0].global_scope = !forged[0].global_scope;
        let error = replica
            .import_sync_history_boundaries(&forged, &history.boundaries, &rows)
            .await
            .expect_err("history body must retain the header's immutable scope");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(
            error
                .message
                .contains("global sync commit must not have a base"),
            "unexpected error: {}",
            error.message
        );
    }

    #[tokio::test]
    async fn history_headers_reject_self_and_duplicate_parents() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "header-parent", "child").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot metadata should load");
        let (_, head) = default_head(&snapshot);
        let history = authority
            .sync_history(&head, 1)
            .await
            .expect("history should load");
        let original = history
            .commit_headers
            .iter()
            .find(|header| header.commit_id == head)
            .expect("head header should exist")
            .clone();
        let replica = open_lix().await.expect("replica should open");

        let mut self_parent = original.clone();
        self_parent.parent_commit_ids = vec![self_parent.commit_id.clone()];
        let error = replica
            .import_sync_history_headers(&[self_parent])
            .await
            .expect_err("a header cannot be its own parent");
        assert!(error.message.contains("own parent"));

        let mut duplicate_parent = original;
        let parent = duplicate_parent
            .parent_commit_ids
            .first()
            .expect("written head should have a parent")
            .clone();
        duplicate_parent.parent_commit_ids = vec![parent.clone(), parent];
        let error = replica
            .import_sync_history_headers(&[duplicate_parent])
            .await
            .expect_err("header parents must be unique");
        assert!(error.message.contains("must be unique"));
    }

    #[tokio::test]
    async fn history_headers_reject_a_sparse_two_node_cycle() {
        let authority = open_lix().await.expect("authority should open");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (_, head) = default_head(&snapshot);
        let template = authority
            .sync_history(&head, 1)
            .await
            .expect("history should load")
            .commit_headers
            .into_iter()
            .next()
            .expect("a template header should exist");
        let first = CommitId::for_test_label("sparse-cycle-first").to_string();
        let second = CommitId::for_test_label("sparse-cycle-second").to_string();
        let omitted = CommitId::for_test_label("sparse-cycle-omitted").to_string();
        let mut first_header = template.clone();
        first_header.commit_id.clone_from(&first);
        first_header.parent_commit_ids = vec![second.clone(), omitted.clone()];
        first_header.generation = 2;
        first_header.first_parent_jump_commit_id = None;
        first_header.first_parent_jump_span = None;
        let mut second_header = template;
        second_header.commit_id = second;
        second_header.parent_commit_ids = vec![first, omitted];
        second_header.generation = 2;
        second_header.first_parent_jump_commit_id = None;
        second_header.first_parent_jump_span = None;

        let replica = open_lix().await.expect("replica should open");
        let error = replica
            .import_sync_history_headers(&[first_header, second_header])
            .await
            .expect_err("sparse boundaries cannot conceal an in-batch cycle");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("graph contains a cycle"));
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot create local restore children"]
    async fn durable_restore_with_a_local_child_does_not_stall_an_unrelated_branch_push() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "base", "one").await;
        write_key_value(&authority, "tip", "two").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (main_branch_id, authority_head) = default_head(&snapshot);
        let history = authority
            .sync_history(&authority_head, 1)
            .await
            .expect("authority head history should load");
        let historical_head = history
            .commits
            .iter()
            .find(|commit| commit.commit_id == authority_head)
            .and_then(|commit| commit.parent_commit_ids.first())
            .cloned()
            .expect("authority head should have a historical parent");
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let unrelated_branch_id = "01920000-0000-7000-8000-000000001500".to_owned();
        replica
            .create_branch(CreateBranchOptions {
                id: Some(unrelated_branch_id.clone()),
                name: "unrelated local branch".to_owned(),
                from_commit_id: Some(authority_head.clone()),
            })
            .await
            .expect("unrelated branch should be created");
        replica
            .switch_branch(SwitchBranchOptions {
                branch_id: main_branch_id.clone(),
            })
            .await
            .expect("fixture should restore the synchronized main branch");
        let historical = authority
            .sync_history(&historical_head, 1)
            .await
            .expect("restore target history should load");
        let mut boundary_rows = Vec::new();
        for boundary in &historical.boundaries {
            let rows = authority
                .pull_sync_snapshot_rows(
                    &boundary.commit_id,
                    &boundary.commit_id,
                    None,
                    super::super::MAX_SYNC_REQUEST_ITEMS,
                )
                .await
                .expect("restore boundary rows should load");
            boundary_rows.extend(rows.rows);
        }
        replica
            .import_sync_history_headers(&historical.commit_headers)
            .await
            .expect("restore history headers should import");
        replica
            .import_sync_history_boundaries(
                &historical.commits,
                &historical.boundaries,
                &boundary_rows,
            )
            .await
            .expect("restore history should import");
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(historical_head.clone())],
            )
            .await
            .expect("historical restore should succeed");
        write_key_value(&replica, "after-restore", "local-child").await;

        let push = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("push should build")
            .expect("reset and unrelated branch should both remain publishable");
        let reset = push
            .ref_updates
            .iter()
            .find(|update| update.branch_id == main_branch_id)
            .expect("historical reset must produce a ref CAS");
        assert_eq!(
            reset.expected_head_commit_id.as_deref(),
            Some(authority_head.as_str())
        );
        assert_ne!(
            reset.head_commit_id.as_deref(),
            Some(authority_head.as_str())
        );
        assert_ne!(
            reset.head_commit_id.as_deref(),
            Some(historical_head.as_str()),
            "the post-restore local child must be published with the reset"
        );
        assert!(
            !push.commits.is_empty(),
            "post-restore local commits must accompany the ref reset"
        );
        assert!(
            push.ref_updates
                .iter()
                .any(|update| update.branch_id == unrelated_branch_id),
            "one reset branch must not stall an independent new branch",
        );
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot author restore intents"]
    async fn restore_to_an_unpublished_local_ancestor_exports_the_target() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "published-base", "authority").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let replica = replica_from_snapshot(&authority, &snapshot).await;

        write_key_value(&replica, "offline-target", "kept").await;
        let unpublished_target = current_branch_head(&replica).await;
        write_key_value(&replica, "offline-abandoned", "removed").await;
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(unpublished_target.clone())],
            )
            .await
            .expect("restore to the first offline commit should succeed");

        let request = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("reset push should build")
            .expect("unpublished reset should have pending work");
        assert!(
            request
                .commits
                .iter()
                .any(|commit| commit.commit_id == unpublished_target),
            "the authority cannot accept the reset until its target is exported"
        );
        authority
            .push_sync_repository(&request)
            .await
            .expect("authority should accept a dependency-complete reset");
        assert_eq!(current_branch_head(&authority).await, unpublished_target);
        assert_eq!(read_key_value(&authority, "offline-target").await, "kept");
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot author restore intents"]
    async fn restore_losing_a_ref_cas_adopts_the_advanced_authority_without_retry() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "restore-race", "target").await;
        write_key_value(&authority, "restore-race", "abandoned").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (_, authority_before) = default_head(&snapshot);
        let target = authority
            .sync_history(&authority_before, 1)
            .await
            .expect("authority history should load")
            .commits[0]
            .parent_commit_ids[0]
            .clone();
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let remote_writer = replica_from_snapshot(&authority, &snapshot).await;
        hydrate_history_commit(&authority, &replica, &target).await;
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(target)],
            )
            .await
            .expect("offline restore should succeed");

        write_key_value(&remote_writer, "restore-race", "authority-wins").await;
        let published = publish_pending(&remote_writer, &authority).await;
        let authority_after = published.ref_updates[0]
            .head_commit_id
            .clone()
            .expect("authority should advance");
        let delta = authority
            .pull_sync_repository(Some(0), 128)
            .await
            .expect("authority delta should load");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("the failed reset coordinate should reconcile");

        assert_eq!(
            read_key_value(&replica, "restore-race").await,
            "authority-wins"
        );
        assert_eq!(
            current_branch_head(&replica).await,
            authority_after,
            "a pure restored ancestor adopts the authority without a merge"
        );
        assert!(
            replica
                .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
                .await
                .expect("post-race outbox should inspect")
                .is_none(),
            "the superseded reset must not be retried against the new authority"
        );
    }

    #[test]
    fn superseded_restore_coordinates_are_bounded_by_pairs() {
        let mut coordinates = BTreeSet::new();
        let head = "same-head".to_owned();
        for index in 0..=MAX_SUPERSEDED_RESET_COORDINATES {
            retain_prepared_reset_coordinate(
                &mut coordinates,
                Some(&head),
                Some(&format!("checkpoint-{index}")),
            );
        }
        assert_eq!(coordinates.len(), MAX_SUPERSEDED_RESET_COORDINATES);
        assert!(coordinates.contains(&(head, "checkpoint-0".to_owned())));
    }

    #[tokio::test]
    async fn multiple_prepared_restore_coordinates_preserve_the_oldest_in_flight_ack() {
        for (same_head, foreign_reuses_old_pair) in [(true, false), (false, false), (true, true)] {
            let authority = open_lix().await.expect("authority opens");
            write_key_value(&authority, "restore-chain", "oldest").await;
            let oldest = current_branch_head(&authority).await;
            write_key_value(&authority, "restore-chain", "middle").await;
            let middle = current_branch_head(&authority).await;
            write_key_value(&authority, "restore-chain", "tip").await;
            let snapshot = authority
                .pull_sync_repository(None, 1)
                .await
                .expect("snapshot");
            let replica = replica_from_snapshot(&authority, &snapshot).await;
            hydrate_history_commit(&authority, &replica, &middle).await;
            hydrate_history_commit(&authority, &replica, &oldest).await;
            replica
                .execute(
                    "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                    &[Value::Text(middle)],
                )
                .await
                .expect("restore A");
            write_key_value(&replica, "after-A", "child").await;
            let first = replica
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("prepare A")
                .expect("pending A");
            authority
                .push_sync_repository(&first)
                .await
                .expect("accept A before its delta arrives");
            if same_head {
                // Restoring CURRENT HEAD is a no-op. Make H an ancestor
                // before restoring it to establish the distinct (H,H) pair.
                write_key_value(&replica, "temporary-before-B", "discarded").await;
                replica
                    .execute(
                        "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                        &[Value::Text(
                            first.ref_updates[0].head_commit_id.clone().unwrap(),
                        )],
                    )
                    .await
                    .expect("restore B to same H with a new C");
            } else {
                write_key_value(&replica, "after-B", "ordinary child").await;
            }
            // A sibling sync worker can prepare another request while A's
            // acknowledgment is in flight. Preserve both exact coordinates.
            let second = replica
                .build_sync_push(TEST_REMOTE, 128)
                .await
                .expect("prepare B")
                .expect("pending B");
            replica
                .execute(
                    "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                    &[Value::Text(oldest)],
                )
                .await
                .expect("restore C");
            write_key_value(&replica, "after-C", "preserved").await;
            let local_head = current_branch_head(&replica).await;
            let read = replica
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("intent read");
            let state = load_replica_state(&read).await.expect("receipt").0.unwrap();
            let intent = state
                .pending_resets
                .get(&first.ref_updates[0].branch_id)
                .unwrap();
            for request in [&first, &second] {
                assert!(intent.superseded_prepared_reset_coordinates.contains(&(
                    request.ref_updates[0].head_commit_id.clone().unwrap(),
                    request.ref_updates[0].checkpoint_commit_id.clone().unwrap()
                )));
            }
            drop(read);
            if foreign_reuses_old_pair {
                let mut foreign = second.clone();
                foreign.ref_updates[0].expected_head_commit_id =
                    first.ref_updates[0].head_commit_id.clone();
                foreign.ref_updates[0].expected_checkpoint_commit_id =
                    first.ref_updates[0].checkpoint_commit_id.clone();
                authority
                    .push_sync_repository(&foreign)
                    .await
                    .expect("foreign write uses new source and B's old target pair");
            }
            let cursor = replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("cursor")
                .unwrap();
            let delta = authority
                .pull_sync_repository(Some(cursor), 128)
                .await
                .expect("acknowledgment page");
            replica
                .apply_sync_repository_pull(TEST_REMOTE, &delta)
                .await
                .expect("apply acknowledgment");
            if foreign_reuses_old_pair {
                assert_eq!(
                    current_branch_head(&replica).await,
                    second.ref_updates[0].head_commit_id.clone().unwrap()
                );
                assert!(
                    replica
                        .build_sync_push(TEST_REMOTE, 128)
                        .await
                        .expect("foreign source must not be mistaken for own ack")
                        .is_none()
                );
            } else {
                assert_eq!(current_branch_head(&replica).await, local_head);
                assert_eq!(read_key_value(&replica, "after-C").await, "preserved");
                let third = replica
                    .build_sync_push(TEST_REMOTE, 128)
                    .await
                    .expect("rebased C")
                    .expect("C remains pending");
                assert_eq!(
                    third.ref_updates[0].expected_head_commit_id,
                    first.ref_updates[0].head_commit_id
                );
                assert_eq!(
                    third.ref_updates[0].expected_checkpoint_commit_id,
                    first.ref_updates[0].checkpoint_commit_id
                );
                authority
                    .push_sync_repository(&third)
                    .await
                    .expect("accept C against A's coordinate");
                assert_eq!(read_key_value(&authority, "after-C").await, "preserved");
            }
        }
    }

    #[test]
    fn legacy_restore_tokens_decode_without_claiming_an_exact_checkpoint() {
        let pending: PendingSyncReset = serde_json::from_value(serde_json::json!({
            "expectedAuthorityHeadCommitId": "head",
            "expectedAuthorityCheckpointCommitId": "checkpoint",
            "restoreTargetCommitId": "target",
            "authorityKnownAncestorCommitId": null,
            "preparedResetHeadCommitId": "prepared",
            "supersededPreparedResetHeadCommitIds": ["older"]
        }))
        .expect("previous receipt format remains readable");
        assert!(pending.prepared_reset_checkpoint_commit_id.is_none());
        assert!(pending.superseded_prepared_reset_coordinates.is_empty());
    }

    #[tokio::test]
    async fn newer_restore_survives_an_older_reset_acknowledgement() {
        for (local_child, competing_server_write, different_checkpoint, same_head_restore) in [
            (false, false, false, false),
            (true, false, false, false),
            (true, true, false, false),
            (true, false, true, false),
            (false, false, false, true),
        ] {
            let authority = open_lix().await.expect("authority should open");
            write_key_value(&authority, "restore-chain", "oldest").await;
            write_key_value(&authority, "restore-chain", "middle").await;
            write_key_value(&authority, "restore-chain", "tip").await;
            let snapshot = authority
                .pull_sync_repository(None, 1)
                .await
                .expect("snapshot should load");
            let (_, authority_head) = default_head(&snapshot);
            let middle = authority
                .sync_history(&authority_head, 1)
                .await
                .expect("tip history should load")
                .commits[0]
                .parent_commit_ids[0]
                .clone();
            let oldest = authority
                .sync_history(&middle, 1)
                .await
                .expect("middle history should load")
                .commits[0]
                .parent_commit_ids[0]
                .clone();
            let replica = replica_from_snapshot(&authority, &snapshot).await;
            hydrate_history_commit(&authority, &replica, &middle).await;
            hydrate_history_commit(&authority, &replica, &oldest).await;

            replica
                .execute(
                    "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                    &[Value::Text(middle.clone())],
                )
                .await
                .expect("first restore should succeed");
            write_key_value(&replica, "after-first-restore", "local-child").await;
            let first_prepared_head = current_branch_head(&replica).await;
            let first = replica
                .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
                .await
                .expect("first reset should build")
                .expect("first reset should be pending");
            let mut accepted = first.clone();
            if different_checkpoint {
                accepted.ref_updates[0].checkpoint_commit_id = accepted.ref_updates[0]
                    .expected_checkpoint_commit_id
                    .clone();
                assert_ne!(
                    accepted.ref_updates[0].checkpoint_commit_id,
                    first.ref_updates[0].checkpoint_commit_id
                );
            }
            authority
                .push_sync_repository(&accepted)
                .await
                .expect("authority should accept the first reset");

            if same_head_restore {
                write_key_value(&replica, "temporary-before-newer-restore", "discarded").await;
            }
            replica
                .execute(
                    "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                    &[Value::Text(if same_head_restore {
                        first_prepared_head.clone()
                    } else {
                        oldest.clone()
                    })],
                )
                .await
                .expect("newer restore should replace the in-flight intent");
            if local_child {
                write_key_value(&replica, "after-second-restore", "preserved").await;
            }
            let newer_local_head = current_branch_head(&replica).await;
            if competing_server_write {
                authority
                    .set_sync_role(super::super::SyncRole::Authority)
                    .expect("publish competing server event");
                write_key_value(&authority, "restore-chain", "server-wins").await;
            }
            let acknowledgement = authority
                .pull_sync_repository(Some(0), 128)
                .await
                .expect("first reset acknowledgement should load");
            replica
                .apply_sync_repository_pull(TEST_REMOTE, &acknowledgement)
                .await
                .expect("older acknowledgement should preserve the newer restore");

            if different_checkpoint {
                assert_eq!(current_branch_head(&replica).await, first_prepared_head);
                let read = replica
                    .storage_adapter()
                    .begin_read(StorageReadOptions::default())
                    .await
                    .expect("corrected control read");
                let control = BranchHeadControlContext::new()
                    .reader(&read)
                    .load(&accepted.ref_updates[0].branch_id)
                    .await
                    .expect("corrected control")
                    .expect("branch exists");
                assert_eq!(
                    control
                        .working_diff_checkpoint_commit_id
                        .map(|id| id.to_string()),
                    accepted.ref_updates[0].checkpoint_commit_id
                );
                drop(read);
                assert!(
                    replica
                        .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
                        .await
                        .expect("same head with a different checkpoint is a server correction")
                        .is_none()
                );
                continue;
            }
            if competing_server_write {
                assert_eq!(
                    read_key_value(&replica, "restore-chain").await,
                    "server-wins"
                );
                assert!(
                    replica
                        .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
                        .await
                        .expect("competing server ref clears pending restore")
                        .is_none()
                );
                continue;
            }
            assert_eq!(current_branch_head(&replica).await, newer_local_head);
            assert_eq!(
                read_key_value(&replica, "restore-chain").await,
                if same_head_restore {
                    "middle"
                } else {
                    "oldest"
                }
            );
            if local_child {
                assert_eq!(
                    read_key_value(&replica, "after-second-restore").await,
                    "preserved"
                );
            }
            let second = replica
                .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
                .await
                .expect("rebased reset should build")
                .unwrap_or_else(|| panic!("newer restore must remain pending: child={local_child}, competing={competing_server_write}, different_checkpoint={different_checkpoint}, same_head_restore={same_head_restore}"));
            assert_eq!(second.ref_updates.len(), 1);
            assert_eq!(
                second.ref_updates[0].expected_head_commit_id.as_deref(),
                Some(first_prepared_head.as_str())
            );
            assert_eq!(
                second.ref_updates[0].expected_checkpoint_commit_id,
                first.ref_updates[0].checkpoint_commit_id,
                "newer restore must rebase both authority CAS coordinates"
            );
            assert_eq!(
                second.ref_updates[0].head_commit_id.as_deref(),
                Some(newer_local_head.as_str())
            );
            authority
                .push_sync_repository(&second)
                .await
                .expect("authority should accept the rebased newer reset");
            assert_eq!(current_branch_head(&authority).await, newer_local_head);
            let cursor = replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .expect("replica cursor")
                .expect("receipt");
            let final_ack = authority
                .pull_sync_repository(Some(cursor), 128)
                .await
                .expect("newer reset acknowledgment");
            replica
                .apply_sync_repository_pull(TEST_REMOTE, &final_ack)
                .await
                .expect("acknowledge newer restore");
            assert!(
                replica
                    .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
                    .await
                    .expect("both restores acknowledged")
                    .is_none()
            );
        }
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot author restore intents"]
    async fn newer_restore_to_unpublished_descendant_reuses_known_boundary() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "restore-boundary", "ancestor").await;
        write_key_value(&authority, "restore-boundary", "authority-tip").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (_, authority_head) = default_head(&snapshot);
        let ancestor = authority
            .sync_history(&authority_head, 1)
            .await
            .expect("authority history should load")
            .commits[0]
            .parent_commit_ids[0]
            .clone();
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        hydrate_history_commit(&authority, &replica, &ancestor).await;

        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(ancestor)],
            )
            .await
            .expect("first restore should succeed");
        write_key_value(&replica, "offline-chain", "keep").await;
        let desired_descendant = current_branch_head(&replica).await;
        write_key_value(&replica, "offline-chain", "discard").await;
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(desired_descendant.clone())],
            )
            .await
            .expect("second restore should succeed");

        let push = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("descendant reset should build")
            .expect("descendant reset should remain publishable");
        assert_eq!(push.ref_updates.len(), 1);
        assert_eq!(
            push.ref_updates[0].expected_head_commit_id.as_deref(),
            Some(authority_head.as_str())
        );
        assert_eq!(
            push.ref_updates[0].head_commit_id.as_deref(),
            Some(desired_descendant.as_str())
        );
        assert!(
            push.commits
                .iter()
                .any(|commit| commit.commit_id == desired_descendant),
            "the unpublished descendant must be included"
        );
        authority
            .push_sync_repository(&push)
            .await
            .expect("authority should accept the descendant reset");
        assert_eq!(current_branch_head(&authority).await, desired_descendant);
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot author restore intents"]
    async fn newer_restore_to_authority_ancestor_recomputes_known_boundary() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "restore-reboundary", "ancestor").await;
        write_key_value(&authority, "restore-reboundary", "authority-tip").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (_, authority_head) = default_head(&snapshot);
        let authority_ancestor = authority
            .sync_history(&authority_head, 1)
            .await
            .expect("authority history should load")
            .commits[0]
            .parent_commit_ids[0]
            .clone();
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        hydrate_history_commit(&authority, &replica, &authority_ancestor).await;

        write_key_value(&replica, "unpublished-chain", "first").await;
        let unpublished_ancestor = current_branch_head(&replica).await;
        write_key_value(&replica, "unpublished-chain", "second").await;
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(unpublished_ancestor)],
            )
            .await
            .expect("first restore should succeed");
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(authority_ancestor.clone())],
            )
            .await
            .expect("second restore should succeed");

        let push = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("rebased ancestor reset should build")
            .expect("authority ancestor reset should remain publishable");
        assert!(push.commits.is_empty());
        assert_eq!(push.ref_updates.len(), 1);
        assert_eq!(
            push.ref_updates[0].expected_head_commit_id.as_deref(),
            Some(authority_head.as_str())
        );
        assert_eq!(
            push.ref_updates[0].head_commit_id.as_deref(),
            Some(authority_ancestor.as_str())
        );
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot author restore intents"]
    async fn restore_to_second_parent_lineage_uses_common_authority_boundary() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "restore-merge-base", "shared").await;
        let shared_ancestor = current_branch_head(&authority).await;
        write_key_value(&authority, "authority-lineage", "tip").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (main_branch_id, authority_head) = default_head(&snapshot);
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        hydrate_history_commit(&authority, &replica, &shared_ancestor).await;

        let side = replica
            .create_branch(CreateBranchOptions {
                id: Some("01920000-0000-7000-8000-000000001991".to_owned()),
                name: "restore-side-lineage".to_owned(),
                from_commit_id: Some(shared_ancestor),
            })
            .await
            .expect("side branch should fork from the shared ancestor");
        replica
            .switch_branch(SwitchBranchOptions {
                branch_id: side.id.clone(),
            })
            .await
            .expect("side branch should become active");
        write_key_value(&replica, "side-lineage", "target").await;
        let side_target = current_branch_head(&replica).await;
        replica
            .switch_branch(SwitchBranchOptions {
                branch_id: main_branch_id.clone(),
            })
            .await
            .expect("main branch should become active");
        replica
            .merge_branch(MergeBranchOptions {
                source_branch_id: side.id,
            })
            .await
            .expect("side lineage should merge into main");
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(side_target.clone())],
            )
            .await
            .expect("restore to the second-parent lineage should succeed");

        let push = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("second-parent reset should build")
            .expect("second-parent reset should remain publishable");
        let main_update = push
            .ref_updates
            .iter()
            .find(|update| update.branch_id == main_branch_id)
            .expect("main reset ref should be included");
        assert_eq!(
            main_update.expected_head_commit_id.as_deref(),
            Some(authority_head.as_str())
        );
        assert_eq!(
            main_update.head_commit_id.as_deref(),
            Some(side_target.as_str())
        );
        assert!(
            push.commits
                .iter()
                .any(|commit| commit.commit_id == side_target),
            "the second-parent target must be exported from the shared boundary"
        );
    }

    #[tokio::test]
    async fn pull_publication_rejects_same_cursor_replica_state_change() {
        let replica = open_lix().await.expect("replica should open");
        let original = SyncReplicaState {
            active_account_id: "account-a".to_owned(),
            cursor: 7,
            authoritative_branches: BTreeMap::new(),
            certified_branch_roots: BTreeMap::new(),
            snapshot_certified_cursor: None,
            pending_resets: BTreeMap::new(),
            authority_known_commit_ids: BTreeSet::new(),
        };
        replica
            .store_replica_state(TEST_REMOTE, original.clone())
            .await
            .expect("initial replica state should store");
        let adapter = replica.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("replica state read should open");
        let (_, expected_state_raw) = load_replica_state(&read)
            .await
            .expect("replica state should load");
        let expected_state_raw = expected_state_raw.expect("replica state should have bytes");
        drop(read);

        let mut folded = original.clone();
        folded.cursor = 8;
        let mut concurrent = original;
        concurrent
            .authority_known_commit_ids
            .insert(CommitId::with_change_address_space(uuid::Uuid::now_v7()).to_string());
        replica
            .store_replica_state(TEST_REMOTE, concurrent.clone())
            .await
            .expect("same-cursor metadata update should store");

        let error = replica
            .import_sync_repository(
                &SyncPushRequest {
                    commits: Vec::new(),
                    ref_updates: Vec::new(),
                    inline_blobs: Vec::new(),
                },
                SyncImportPurpose::ReplicaDelta,
                None,
                Some(ReplicaStatePublication {
                    retired_upload_proof_branches: &[],
                    reset_pending: false,
                    expected_cursor: 7,
                    expected_state_raw: &expected_state_raw,
                    state: &folded,
                }),
            )
            .await
            .expect_err("stale full-state admission must conflict");
        assert_eq!(error.code, LixError::CODE_TRANSACTION_CONFLICT);

        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("replica state read should reopen");
        assert_eq!(
            load_replica_state(&read)
                .await
                .expect("replica state should load")
                .0,
            Some(concurrent),
            "the concurrent same-cursor state must remain intact"
        );
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot author restore intents"]
    async fn restore_child_racing_authority_keeps_local_first_parent() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "restore-base", "target").await;
        write_key_value(&authority, "restore-base", "abandoned").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (_, authority_before) = default_head(&snapshot);
        let target = authority
            .sync_history(&authority_before, 1)
            .await
            .expect("authority history should load")
            .commits[0]
            .parent_commit_ids[0]
            .clone();
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let remote_writer = replica_from_snapshot(&authority, &snapshot).await;
        hydrate_history_commit(&authority, &replica, &target).await;
        replica
            .execute(
                "INSERT INTO lix_restore (commit_id) VALUES ($1)",
                &[Value::Text(target)],
            )
            .await
            .expect("offline restore should succeed");
        write_key_value(&replica, "local-only", "survives").await;
        let local_head = current_branch_head(&replica).await;

        write_key_value(&remote_writer, "authority-only", "survives").await;
        let published = publish_pending(&remote_writer, &authority).await;
        let authority_head = published.ref_updates[0]
            .head_commit_id
            .clone()
            .expect("authority should advance");
        let delta = authority
            .pull_sync_repository(Some(0), 128)
            .await
            .expect("authority delta should load");
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("restore-child divergence should reconcile");
        assert_eq!(read_key_value(&replica, "local-only").await, "survives");
        assert_eq!(read_key_value(&replica, "authority-only").await, "survives");

        let push = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("merge push should build")
            .expect("server-winning merge should be pending");
        let merge_head = push.ref_updates[0]
            .head_commit_id
            .as_deref()
            .expect("merge ref should have a head");
        let merge = push
            .commits
            .iter()
            .find(|commit| commit.commit_id == merge_head)
            .expect("merge commit should be exported");
        assert_eq!(
            merge.parent_commit_ids,
            vec![local_head, authority_head],
            "the local state parent stays first and authority history stays as the merge parent"
        );
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot diverge or reconcile"]
    async fn divergent_child_reconciles_without_waiting_for_another_remote_event() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "base", "shared").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (branch_id, _) = default_head(&snapshot);
        let local = replica_from_snapshot(&authority, &snapshot).await;
        let remote_writer = replica_from_snapshot(&authority, &snapshot).await;
        write_key_value(&local, "after-old-head", "local").await;
        write_key_value(&remote_writer, "authority-advanced", "remote").await;
        let published = publish_pending(&remote_writer, &authority).await;
        let authority_head = published.ref_updates[0]
            .head_commit_id
            .clone()
            .expect("remote push should advance authority");
        local
            .import_sync_repository(
                &SyncPushRequest {
                    commits: published.commits.clone(),
                    ref_updates: Vec::new(),
                    inline_blobs: published.inline_blobs.clone(),
                },
                SyncImportPurpose::ReplicaDelta,
                None,
                None,
            )
            .await
            .expect("consumed delta commits should be locally available");

        // Model a consumed cursor whose authority receipt was persisted before
        // local reconciliation (the same graph shape as reset-to-old + write).
        let SyncRepositoryPullResponse::Snapshot { branches, .. } = &snapshot else {
            unreachable!("fixture response is a snapshot");
        };
        let mut authoritative_branches = authoritative_coordinates(branches);
        let checkpoint_commit_id = authoritative_branches[&branch_id]
            .checkpoint_commit_id()
            .expect("authority branch should have a checkpoint")
            .to_owned();
        authoritative_branches.insert(
            branch_id.clone(),
            AuthoritativeBranchCoordinate::Headed {
                head_commit_id: authority_head.clone(),
                checkpoint_commit_id,
            },
        );
        local
            .store_replica_state(
                TEST_REMOTE,
                SyncReplicaState {
                    active_account_id: local.active_account_id().to_owned(),
                    cursor: 1,
                    authoritative_branches,
                    certified_branch_roots: BTreeMap::new(),
                    snapshot_certified_cursor: None,
                    pending_resets: BTreeMap::new(),
                    authority_known_commit_ids: BTreeSet::new(),
                },
            )
            .await
            .expect("authority receipt should store");

        let push = local
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("build should proactively reconcile")
            .expect("reconciled merge should be publishable");
        let update = push
            .ref_updates
            .iter()
            .find(|update| update.branch_id == branch_id)
            .expect("reconciled branch should be present");
        assert_eq!(
            update.expected_head_commit_id.as_deref(),
            Some(authority_head.as_str()),
        );
        assert_ne!(
            update.head_commit_id.as_deref(),
            Some(authority_head.as_str())
        );
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot diverge or publish refs"]
    async fn divergent_branch_does_not_starve_an_independent_ready_ref() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "base", "shared").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (divergent_branch_id, base_head) = default_head(&snapshot);
        let local = replica_from_snapshot(&authority, &snapshot).await;
        let remote_writer = replica_from_snapshot(&authority, &snapshot).await;
        let independent_branch_id = "01920000-0000-7000-8000-000000001501".to_owned();
        local
            .create_branch(CreateBranchOptions {
                id: Some(independent_branch_id.clone()),
                name: "independent ready branch".to_owned(),
                from_commit_id: Some(base_head.clone()),
            })
            .await
            .expect("independent branch should be created");
        local
            .switch_branch(SwitchBranchOptions {
                branch_id: divergent_branch_id.clone(),
            })
            .await
            .expect("fixture should return to the branch that will diverge");

        write_key_value(&local, "local-divergence", "local").await;
        let local_head_before = {
            let read = local
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("local head read should open");
            BranchHeadControlContext::new()
                .reader(&read)
                .load(&divergent_branch_id)
                .await
                .expect("local head should load")
                .expect("local branch should exist")
                .head_commit_id
        };

        write_key_value(&remote_writer, "authority-divergence", "remote").await;
        let published = publish_pending(&remote_writer, &authority).await;
        let authority_head = published.ref_updates[0]
            .head_commit_id
            .clone()
            .expect("remote push should advance authority");
        local
            .import_sync_repository(
                &SyncPushRequest {
                    commits: published.commits,
                    ref_updates: Vec::new(),
                    inline_blobs: published.inline_blobs,
                },
                SyncImportPurpose::ReplicaDelta,
                None,
                None,
            )
            .await
            .expect("authority commits should import without moving local refs");

        let SyncRepositoryPullResponse::Snapshot { branches, .. } = &snapshot else {
            unreachable!("fixture response is a snapshot");
        };
        let mut authoritative_branches = authoritative_coordinates(branches);
        let checkpoint_commit_id = authoritative_branches[&divergent_branch_id]
            .checkpoint_commit_id()
            .expect("authority branch should have a checkpoint")
            .to_owned();
        authoritative_branches.insert(
            divergent_branch_id.clone(),
            AuthoritativeBranchCoordinate::Headed {
                head_commit_id: authority_head,
                checkpoint_commit_id,
            },
        );
        local
            .store_replica_state(
                TEST_REMOTE,
                SyncReplicaState {
                    active_account_id: local.active_account_id().to_owned(),
                    cursor: 1,
                    authoritative_branches,
                    certified_branch_roots: BTreeMap::new(),
                    snapshot_certified_cursor: None,
                    pending_resets: BTreeMap::new(),
                    authority_known_commit_ids: BTreeSet::new(),
                },
            )
            .await
            .expect("authority receipt should store");

        let push = local
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("independent push should build")
            .expect("independent branch ref should be ready");
        assert!(
            push.ref_updates
                .iter()
                .any(|update| update.branch_id == independent_branch_id),
            "the ready branch must publish before divergent reconciliation",
        );
        assert!(
            push.ref_updates
                .iter()
                .all(|update| update.branch_id != divergent_branch_id),
            "the stale expected head must not be published",
        );

        let local_head_after = {
            let read = local
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("post-build local head read should open");
            BranchHeadControlContext::new()
                .reader(&read)
                .load(&divergent_branch_id)
                .await
                .expect("post-build local head should load")
                .expect("post-build local branch should exist")
                .head_commit_id
        };
        assert_eq!(
            local_head_after, local_head_before,
            "building independent work must not reconcile the divergent branch first",
        );
    }

    #[test]
    fn authoritative_branch_coordinate_is_complete_and_round_trips() {
        let headed = AuthoritativeBranchCoordinate::from_wire(
            Some("head".to_owned()),
            Some("checkpoint".to_owned()),
            "test coordinate",
        )
        .expect("a complete headed coordinate should parse");
        assert_eq!(
            serde_json::to_value(&headed).expect("headed coordinate should encode"),
            serde_json::json!({
                "state": "headed",
                "headCommitId": "head",
                "checkpointCommitId": "checkpoint",
            }),
        );
        assert_eq!(
            serde_json::from_value::<AuthoritativeBranchCoordinate>(
                serde_json::to_value(&headed).expect("headed coordinate should encode"),
            )
            .expect("headed coordinate should decode"),
            headed,
        );
        assert_eq!(
            AuthoritativeBranchCoordinate::from_wire(None, None, "test coordinate")
                .expect("a deleted coordinate should parse"),
            AuthoritativeBranchCoordinate::Deleted,
        );
        for (head, checkpoint) in [
            (Some("head".to_owned()), None),
            (None, Some("checkpoint".to_owned())),
        ] {
            assert_eq!(
                AuthoritativeBranchCoordinate::from_wire(head, checkpoint, "test coordinate")
                    .expect_err("a partial coordinate must be rejected")
                    .code,
                LixError::CODE_INVALID_PARAM,
            );
        }
        assert!(
            serde_json::from_value::<AuthoritativeBranchCoordinate>(serde_json::json!({
                "state": "headed",
                "headCommitId": "head",
            }))
            .is_err(),
            "persisted headed coordinates require a checkpoint",
        );
    }

    #[tokio::test]
    async fn replica_state_persists_and_enforces_the_authority_account() {
        let replica = open_lix().await.expect("replica should open");
        replica
            .store_replica_state(
                TEST_REMOTE,
                SyncReplicaState {
                    active_account_id: crate::SYSTEM_ACCOUNT_ID.to_owned(),
                    cursor: 7,
                    authoritative_branches: BTreeMap::new(),
                    certified_branch_roots: BTreeMap::new(),
                    snapshot_certified_cursor: None,
                    pending_resets: BTreeMap::new(),
                    authority_known_commit_ids: BTreeSet::new(),
                },
            )
            .await
            .expect("replica identity should store durably");
        let adapter = replica.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("replica state read should open");
        assert_eq!(
            load_sync_replica_account(&read)
                .await
                .expect("replica account should decode")
                .as_deref(),
            Some(crate::SYSTEM_ACCOUNT_ID),
        );
        drop(read);
        replica
            .validate_sync_repository_account(TEST_REMOTE, crate::SYSTEM_ACCOUNT_ID)
            .await
            .expect("the same authority account should reconnect");
        let error = replica
            .validate_sync_repository_account(TEST_REMOTE, crate::ANONYMOUS_ACCOUNT_ID)
            .await
            .expect_err("a changed authority account must fail closed");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("account changed"));
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot diverge or reconcile"]
    async fn divergent_replicas_merge_different_rows_and_push_from_new_authority_head() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "base", "non-root").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let left = replica_from_snapshot(&authority, &snapshot).await;
        let right = replica_from_snapshot(&authority, &snapshot).await;

        write_key_value(&left, "left", "from-left").await;
        write_key_value(&right, "right", "from-right").await;
        let right_pending = right
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("right pending push should build")
            .expect("right should have pending work");
        for commit in &right_pending.commits {
            assert_root_parent_is_complete(&right, &commit.commit_id).await;
        }
        let left_push = publish_pending(&left, &authority).await;
        let left_head = left_push.ref_updates[0]
            .head_commit_id
            .clone()
            .expect("left push advances its ref");

        let delta = authority
            .pull_sync_repository(Some(0), 128)
            .await
            .expect("authority delta should load");
        right
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("right replica should reconcile divergence");
        let right_push = right
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("reconciled push should build")
            .expect("merge commit should remain pending");
        assert_eq!(
            right_push.ref_updates[0].expected_head_commit_id.as_deref(),
            Some(left_head.as_str()),
            "the retry CAS must start from the newly pulled authority head",
        );
        authority
            .push_sync_repository(&right_push)
            .await
            .expect("authority should accept reconciled merge");

        assert_eq!(read_key_value(&authority, "left").await, "from-left");
        assert_eq!(read_key_value(&authority, "right").await, "from-right");
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot diverge or reconcile"]
    async fn divergent_file_insert_and_edit_preserve_checkpoint_cursor_and_both_rows() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/existing.md".to_owned()),
                    Value::Text("base".to_owned()),
                ],
            )
            .await
            .expect("base file should commit");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (branch_id, _) = default_head(&snapshot);
        let inserting_replica = replica_from_snapshot(&authority, &snapshot).await;
        let editing_replica = replica_from_snapshot(&authority, &snapshot).await;
        let (snapshot_history, _, _) = snapshot_parts(&authority, &snapshot).await;
        transfer_commit_blobs(&authority, &inserting_replica, &snapshot_history.commits).await;
        transfer_commit_blobs(&authority, &editing_replica, &snapshot_history.commits).await;

        inserting_replica
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/created.md".to_owned()),
                    Value::Text("created".to_owned()),
                ],
            )
            .await
            .expect("new file should commit locally");
        editing_replica
            .execute(
                "UPDATE lix_file SET content = CAST($1 AS BYTEA) WHERE path = $2",
                &[
                    Value::Text("edited".to_owned()),
                    Value::Text("/existing.md".to_owned()),
                ],
            )
            .await
            .expect("existing file should edit locally");

        for replica in [&inserting_replica, &editing_replica] {
            let read = replica
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("pre-reconcile control read should open");
            let control = BranchHeadControlContext::new()
                .reader(&read)
                .load(&branch_id)
                .await
                .expect("pre-reconcile control should load")
                .expect("pre-reconcile control should exist");
            assert!(
                control.working_diff_checkpoint_commit_id.is_some(),
                "ordinary local file writes must preserve the checkpoint cursor",
            );
            assert!(
                working_diff_count(replica).await > 0,
                "ordinary local file writes must remain dirty against the checkpoint",
            );
        }

        publish_pending_with_blobs(&editing_replica, &authority).await;
        let delta = authority
            .pull_sync_repository(Some(0), 128)
            .await
            .expect("authority delta should load");
        let SyncRepositoryPullResponse::Delta { events, .. } = &delta else {
            panic!("a cursor pull should return a delta");
        };
        for event in events {
            transfer_commit_blobs(&authority, &inserting_replica, &event.commits).await;
        }
        inserting_replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("file divergence should reconcile");

        let adapter = inserting_replica.storage_adapter();
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("branch control read should open");
        let control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("branch control should load")
            .expect("branch control should exist");
        assert!(
            control.working_diff_checkpoint_commit_id.is_some(),
            "reconciliation must preserve the private checkpoint cursor",
        );
        drop(read);

        let paths = inserting_replica
            .execute(
                "SELECT path FROM lix_file WHERE path IN ('/created.md', '/existing.md') ORDER BY path",
                &[],
            )
            .await
            .expect("both reconciled files should remain queryable");
        assert_eq!(paths.rows().len(), 2);
        assert!(
            working_diff_count(&inserting_replica).await > 0,
            "reconciliation must retain the pending insert in working diff",
        );
        assert_eq!(
            read_file_content(&inserting_replica, "/existing.md").await,
            Value::Blob(b"edited".to_vec().into()),
        );

        let retry = inserting_replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("reconciled push should build")
            .expect("created file should remain pending");
        transfer_commit_blobs(&inserting_replica, &authority, &retry.commits).await;
        authority
            .push_sync_repository(&retry)
            .await
            .expect("authority should accept the reconciled file edit");
        let authority_paths = authority
            .execute(
                "SELECT path FROM lix_file WHERE path IN ('/created.md', '/existing.md') ORDER BY path",
                &[],
            )
            .await
            .expect("authority should expose both files");
        assert_eq!(authority_paths.rows().len(), 2);
        assert_eq!(
            read_file_content(&authority, "/existing.md").await,
            Value::Blob(b"edited".to_vec().into()),
        );
    }

    #[tokio::test]
    async fn fresh_snapshot_preserves_dirty_state_against_the_shared_checkpoint() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "dirty-bootstrap", "baseline").await;
        let checkpoint = authority
            .create_checkpoint()
            .await
            .expect("explicit checkpoint should commit");
        let checkpoint = CommitId::parse_lix(&checkpoint.commit_id, "bootstrap checkpoint")
            .expect("checkpoint id should parse");
        write_key_value(&authority, "dirty-bootstrap", "dirty after checkpoint").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("dirty snapshot should load");
        let (branch_id, head) = default_head(&snapshot);
        assert_ne!(head, checkpoint.to_string());

        let replica = replica_from_snapshot(&authority, &snapshot).await;
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("replica branch read should open");
        let control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("replica branch should load")
            .expect("replica branch should exist");
        assert_eq!(control.head_commit_id.to_string(), head);
        assert_eq!(control.working_diff_checkpoint_commit_id, Some(checkpoint),);
        drop(read);
        assert!(working_diff_count(&replica).await > 0);
        assert_eq!(
            read_key_value(&replica, "dirty-bootstrap").await,
            "dirty after checkpoint",
        );
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica-authored write semantics were removed"]
    async fn ordinary_remote_write_preserves_the_shared_checkpoint_baseline() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/shared.md".to_owned()),
                    Value::Text("baseline".to_owned()),
                ],
            )
            .await
            .expect("baseline file should commit");
        let checkpoint = authority
            .create_checkpoint()
            .await
            .expect("explicit checkpoint should commit");
        let checkpoint = CommitId::parse_lix(&checkpoint.commit_id, "baseline checkpoint")
            .expect("checkpoint id should parse");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = &snapshot else {
            panic!("initial pull should return a snapshot");
        };
        let cursor = *cursor;
        let (branch_id, _) = default_head(&snapshot);
        let origin = replica_from_snapshot(&authority, &snapshot).await;
        let peer = replica_from_snapshot(&authority, &snapshot).await;

        origin
            .execute(
                "UPDATE lix_file SET content = CAST($1 AS BYTEA) WHERE path = $2",
                &[
                    Value::Text("ordinary write".to_owned()),
                    Value::Text("/shared.md".to_owned()),
                ],
            )
            .await
            .expect("ordinary file write should commit locally");
        publish_pending_with_blobs(&origin, &authority).await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("published write should load as a delta");
        let SyncRepositoryPullResponse::Delta { events, .. } = &delta else {
            panic!("cursor pull should return a delta");
        };
        for event in events {
            transfer_commit_blobs(&authority, &origin, &event.commits).await;
            transfer_commit_blobs(&authority, &peer, &event.commits).await;
        }
        origin
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("origin should acknowledge its published write");
        peer.apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("peer should apply the published write");

        for (name, replica) in [("origin", &origin), ("peer", &peer)] {
            let adapter = replica.storage_adapter();
            let read = adapter
                .begin_read(StorageReadOptions::default())
                .await
                .expect("branch control read should open");
            let control = BranchHeadControlContext::new()
                .reader(&read)
                .load(&branch_id)
                .await
                .expect("branch control should load")
                .expect("branch control should exist");
            assert_eq!(
                control.working_diff_checkpoint_commit_id,
                Some(checkpoint),
                "{name} must retain the explicit checkpoint as its working-diff cursor",
            );
            drop(read);
            assert!(
                working_diff_count(replica).await > 0,
                "{name} must keep the ordinary write dirty against the explicit checkpoint",
            );
        }
    }

    #[tokio::test]
    async fn remote_checkpoint_advances_the_shared_baseline_and_clears_working_diff() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "checkpoint-sync", "baseline").await;
        authority
            .create_checkpoint()
            .await
            .expect("baseline checkpoint should commit");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (branch_id, _) = default_head(&snapshot);
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = &snapshot else {
            panic!("initial pull should return a snapshot");
        };
        let mut cursor = *cursor;
        let origin = replica_from_snapshot(&authority, &snapshot).await;
        let peer = replica_from_snapshot(&authority, &snapshot).await;

        origin
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/checkpoint-sync.md".to_owned()),
                    Value::Text("dirty".to_owned()),
                ],
            )
            .await
            .expect("replica file write should commit");
        publish_pending_with_blobs(&origin, &authority).await;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("ordinary delta should load");
        cursor = match &delta {
            SyncRepositoryPullResponse::Delta { cursor, .. } => *cursor,
            _ => panic!("cursor pull should return a delta"),
        };
        if let SyncRepositoryPullResponse::Delta { events, .. } = &delta {
            for event in events {
                transfer_commit_blobs(&authority, &peer, &event.commits).await;
                transfer_commit_blobs(&authority, &origin, &event.commits).await;
            }
        }
        peer.apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("peer should apply ordinary write");
        assert!(working_diff_count(&peer).await > 0);

        origin
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("origin should acknowledge ordinary write");
        let _checkpoint = origin
            .create_checkpoint()
            .await
            .expect("replica checkpoint should commit");
        assert_eq!(
            working_diff_count(&origin).await,
            0,
            "origin checkpoint should be locally clean",
        );
        let origin_read = origin
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("origin control read should open");
        let origin_control = BranchHeadControlContext::new()
            .reader(&origin_read)
            .load(&branch_id)
            .await
            .expect("origin control should load")
            .expect("origin control should exist");
        let origin_checkpoint_diff = TrackedStateContext::new()
            .reader(&origin_read)
            .diff_commits(
                &origin_control
                    .working_diff_checkpoint_commit_id
                    .expect("origin checkpoint")
                    .to_string(),
                &origin_control.head_commit_id.to_string(),
                &TrackedStateDiffRequest::default(),
            )
            .await
            .expect("origin checkpoint root diff should load");
        assert!(
            origin_checkpoint_diff.entries.iter().all(|entry| {
                entry.identity.schema_key() == crate::checkpoint::CHECKPOINT_SCHEMA_KEY
            }),
            "origin checkpoint child should differ only by checkpoint metadata: {:?}",
            origin_checkpoint_diff.entries,
        );
        let origin_checkpoint_id = origin_control
            .working_diff_checkpoint_commit_id
            .expect("origin checkpoint")
            .to_string();
        let scanned_checkpoint = BranchHeadControlContext::new()
            .reader(&origin_read)
            .scan()
            .await
            .expect("origin controls should scan")
            .into_iter()
            .find(|(id, _)| id == &branch_id)
            .and_then(|(_, control)| control.working_diff_checkpoint_commit_id)
            .expect("scanned origin checkpoint")
            .to_string();
        assert_eq!(scanned_checkpoint, origin_checkpoint_id);
        let preview_push = origin
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("checkpoint push should build")
            .expect("checkpoint push should exist");
        if let Some(update) = preview_push
            .ref_updates
            .iter()
            .find(|update| update.branch_id == branch_id)
        {
            assert_eq!(
                update.checkpoint_commit_id.as_deref(),
                Some(origin_checkpoint_id.as_str()),
                "first outbox build must use the exact local checkpoint coordinate",
            );
        }
        drop(origin_read);
        let mut checkpoint_ref = None;
        for _ in 0..8 {
            let before_push_read = origin
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("before push read");
            let before_push_checkpoint = BranchHeadControlContext::new()
                .reader(&before_push_read)
                .scan()
                .await
                .expect("before push controls")
                .into_iter()
                .find(|(id, _)| id == &branch_id)
                .and_then(|(_, control)| control.working_diff_checkpoint_commit_id)
                .expect("before push checkpoint")
                .to_string();
            assert_eq!(before_push_checkpoint, origin_checkpoint_id);
            drop(before_push_read);
            let checkpoint_push = publish_pending_with_blobs(&origin, &authority).await;
            let published_active = checkpoint_push
                .ref_updates
                .into_iter()
                .find(|update| update.branch_id == branch_id);
            if let Some(update) = &published_active {
                assert_eq!(
                    update.checkpoint_commit_id.as_deref(),
                    Some(origin_checkpoint_id.as_str()),
                    "bounded outbox ref must use the exact local checkpoint coordinate",
                );
            }
            let delta = authority
                .pull_sync_repository(Some(cursor), 128)
                .await
                .expect("checkpoint upload receipt should pull");
            if let SyncRepositoryPullResponse::Delta {
                cursor: next_cursor,
                events,
            } = &delta
            {
                for event in events {
                    transfer_commit_blobs(&authority, &origin, &event.commits).await;
                    transfer_commit_blobs(&authority, &peer, &event.commits).await;
                }
                cursor = *next_cursor;
            }
            origin
                .apply_sync_repository_pull(TEST_REMOTE, &delta)
                .await
                .expect("origin should acknowledge checkpoint upload page");
            peer.apply_sync_repository_pull(TEST_REMOTE, &delta)
                .await
                .expect("peer should apply checkpoint upload page");
            let loop_read = origin
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("loop origin read");
            let loop_control = BranchHeadControlContext::new()
                .reader(&loop_read)
                .load(&branch_id)
                .await
                .expect("loop origin control")
                .expect("loop origin branch");
            assert_eq!(
                loop_control
                    .working_diff_checkpoint_commit_id
                    .expect("loop checkpoint")
                    .to_string(),
                origin_checkpoint_id,
                "checkpoint upload acknowledgement must not rewrite local checkpoint",
            );
            drop(loop_read);
            if let Some(update) = published_active {
                checkpoint_ref = Some(update);
                break;
            }
        }
        let checkpoint_ref = checkpoint_ref
            .expect("bounded checkpoint upload should eventually publish the active branch");
        let pushed_head = checkpoint_ref
            .head_commit_id
            .as_deref()
            .expect("headed ref");
        let pushed_checkpoint = checkpoint_ref
            .checkpoint_commit_id
            .as_deref()
            .expect("headed ref checkpoint");
        assert_eq!(
            pushed_checkpoint, origin_checkpoint_id,
            "outbox must publish the exact local checkpoint coordinate",
        );
        let imported_checkpoint_history = authority
            .sync_history(pushed_checkpoint, 1)
            .await
            .expect("imported checkpoint history");
        assert!(
            imported_checkpoint_history
                .boundaries
                .iter()
                .any(|boundary| boundary.commit_id == pushed_checkpoint),
            "checkpoint history must paginate its aliased state as a self-contained boundary",
        );
        let imported_checkpoint = imported_checkpoint_history
            .commits
            .into_iter()
            .next()
            .expect("imported checkpoint body");
        assert!(
            imported_checkpoint.members.is_empty(),
            "checkpoint boundary should not expand selected file members on the wire: {:?}",
            imported_checkpoint.members,
        );
        assert!(
            imported_checkpoint.state_alias.is_some(),
            "checkpoint wire body must carry its authenticated complete-state alias",
        );
        let read = authority
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("authority diff read should open");
        let root_diff = TrackedStateContext::new()
            .reader(&read)
            .diff_commits(
                pushed_checkpoint,
                pushed_head,
                &TrackedStateDiffRequest::default(),
            )
            .await
            .expect("checkpoint-to-head diff should load");
        assert!(
            root_diff.entries.iter().all(
                |entry| entry.identity.schema_key() == crate::checkpoint::CHECKPOINT_SCHEMA_KEY
            ),
            "checkpoint child should differ only by checkpoint metadata: {:?}",
            root_diff.entries,
        );
        drop(read);
        let read = authority
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("authority control read should open");
        let authority_control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("authority control should load")
            .expect("authority control should exist");
        assert_eq!(authority_control.head_commit_id.to_string(), pushed_head);
        assert_eq!(
            authority_control
                .working_diff_checkpoint_commit_id
                .map(|commit| commit.to_string())
                .as_deref(),
            Some(pushed_checkpoint),
        );
        drop(read);
        assert_eq!(
            working_diff_count(&authority).await,
            0,
            "authority checkpoint should be clean",
        );
        let peer_diff = peer
            .execute(
                "SELECT id, diff_type \
                 FROM lix_diff('lix_file', $1, lix_active_branch_commit_id())",
                &[Value::Text(pushed_checkpoint.to_owned())],
            )
            .await
            .expect("peer working diff should load");
        assert_eq!(
            peer_diff.rows().len(),
            0,
            "peer checkpoint should be clean, found {:?}",
            peer_diff.rows(),
        );
        let peer_read = peer
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("peer change scan should open");
        let peer_changes = crate::tracked_state::scan_change_records_from_commit_deltas(&peer_read)
            .await
            .expect("peer must resolve every imported checkpoint member");
        assert!(
            peer_changes.iter().any(|change| {
                change.schema_key == "lix_file_descriptor" && change.file_id.is_some()
            }),
            "peer change scan should include the synchronized file",
        );
        drop(peer_read);
        let read = peer
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .expect("peer branch read should open");
        let control = BranchHeadControlContext::new()
            .reader(&read)
            .load(&branch_id)
            .await
            .expect("peer branch should load")
            .expect("peer branch should exist");
        assert_eq!(control.head_commit_id.to_string(), pushed_head);
        assert_eq!(
            control
                .working_diff_checkpoint_commit_id
                .map(|commit| commit.to_string())
                .as_deref(),
            Some(pushed_checkpoint),
        );
    }

    #[tokio::test]
    async fn sparse_snapshot_can_diff_from_checkpoint_without_authored_bodies() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/history.md".to_owned()),
                    Value::Text("before".to_owned()),
                ],
            )
            .await
            .expect("baseline file should commit");
        let checkpoint = authority
            .create_checkpoint()
            .await
            .expect("checkpoint should commit")
            .commit_id;
        authority
            .execute(
                "UPDATE lix_file SET content = CAST($1 AS BYTEA) WHERE path = $2",
                &[
                    Value::Text("after".to_owned()),
                    Value::Text("/history.md".to_owned()),
                ],
            )
            .await
            .expect("post-checkpoint file update should commit");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (_, head) = default_head(&snapshot);
        let replica = replica_from_snapshot(&authority, &snapshot).await;

        let diff = replica
            .execute(
                "SELECT diff_type FROM lix_diff('lix_file', $1, $2)",
                &[Value::Text(checkpoint), Value::Text(head)],
            )
            .await
            .expect("checkpoint diff should use its authenticated sparse snapshot");
        assert_eq!(diff.rows().len(), 1);
        assert_eq!(
            diff.rows()[0]
                .get::<String>("diff_type")
                .expect("diff type should decode"),
            "modified",
        );
    }

    #[tokio::test]
    async fn sparse_snapshot_history_reads_files_added_at_checkpoint_state() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/baseline.md".to_owned()),
                    Value::Text("baseline".to_owned()),
                ],
            )
            .await
            .expect("baseline file should commit");
        authority
            .create_checkpoint()
            .await
            .expect("baseline checkpoint should commit");
        let added_file = authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA)) RETURNING id",
                &[
                    Value::Text("/added.md".to_owned()),
                    Value::Text("added".to_owned()),
                ],
            )
            .await
            .expect("added file should commit");
        let added_file_id = added_file.rows()[0]
            .get::<String>("id")
            .expect("added file id should decode");
        let checkpoint = authority
            .create_checkpoint()
            .await
            .expect("latest checkpoint should commit")
            .commit_id;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let (_, snapshot_head) = default_head(&snapshot);
        assert_eq!(checkpoint, snapshot_head);
        let mut replica = replica_from_snapshot(&authority, &snapshot).await;
        // This test hydrates history explicitly below. Do not route a cold
        // bootstrap boundary through the publication-only fixture responder.
        replica.clear_sync_demand_sender_for_test();

        crate::sql2::take_mainline_work();

        let history = loop {
            match replica
                .execute(
                    "SELECT id, to_path AS path FROM lix_history('lix_file', $1) WHERE id = $2 AND lixcol_to_commit_id = $1 ORDER BY lixcol_position ASC LIMIT 1",
                    &[
                        Value::Text(checkpoint.clone()),
                        Value::Text(added_file_id.clone()),
                    ],
                )
                .await
            {
                Ok(history) => break history,
                Err(error) if error.code == "LIX_SYNC_HISTORY_REQUIRED" => {
                    let commit_ids = error
                        .details
                        .as_ref()
                        .and_then(|details| details["commitIds"].as_array())
                        .expect("history demand ids")
                        .iter()
                        .map(|id| id.as_str().expect("history demand id").to_owned())
                        .collect::<Vec<_>>();
                    for commit_id in commit_ids {
                        let page = authority
                            .sync_history(&commit_id, 1)
                            .await
                            .expect("deferred history should load from authority");
                        let mut boundary_rows = Vec::new();
                        for boundary in &page.boundaries {
                            let rows = authority
                                .pull_sync_snapshot_rows(
                                    &boundary.commit_id,
                                    &boundary.commit_id,
                                    None,
                                    super::super::MAX_SYNC_REQUEST_ITEMS,
                                )
                                .await
                                .expect("history boundary rows should load");
                            assert_eq!(rows.continuation, None);
                            boundary_rows.extend(rows.rows);
                        }
                        replica
                            .import_sync_history_headers(&page.commit_headers)
                            .await
                            .expect("history headers should import");
                        replica
                            .import_sync_history_boundaries(
                                &page.commits,
                                &page.boundaries,
                                &boundary_rows,
                            )
                            .await
                            .expect("history bodies should import");
                    }
                }
                Err(error) => panic!("checkpoint history should load: {error:?}"),
            }
        };
        let work = crate::sql2::take_mainline_work();
        assert!(
            work.1 >= 1,
            "selected checkpoint must evaluate an endpoint difference"
        );
        assert_eq!(history.rows().len(), 1);
        assert_eq!(
            history.rows()[0]
                .get::<String>("path")
                .expect("history path should decode"),
            "/added.md",
        );
    }

    #[tokio::test]
    async fn warm_replica_history_reads_files_added_by_a_later_checkpoint() {
        let authority = open_lix().await.expect("authority should open");
        authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA))",
                &[
                    Value::Text("/baseline.md".to_owned()),
                    Value::Text("baseline".to_owned()),
                ],
            )
            .await
            .expect("baseline file should commit");
        let previous_checkpoint = authority
            .create_checkpoint()
            .await
            .expect("baseline checkpoint should commit")
            .commit_id;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("baseline snapshot should load");
        let SyncRepositoryPullResponse::Snapshot { cursor, .. } = snapshot.clone() else {
            panic!("initial pull should be a snapshot");
        };
        let mut replica = replica_from_snapshot(&authority, &snapshot).await;
        // This fixture explicitly imports the missing history returned below;
        // it does not run a network hydration worker.
        replica.clear_sync_demand_sender_for_test();

        let added_file = authority
            .execute(
                "INSERT INTO lix_file (path, content) VALUES ($1, CAST($2 AS BYTEA)) RETURNING id",
                &[
                    Value::Text("/added-later.md".to_owned()),
                    Value::Text("added later".to_owned()),
                ],
            )
            .await
            .expect("later file should commit");
        let added_file_id = added_file.rows()[0]
            .get::<String>("id")
            .expect("later file id should decode");
        let latest_checkpoint = authority
            .create_checkpoint()
            .await
            .expect("later checkpoint should commit")
            .commit_id;
        let delta = authority
            .pull_sync_repository(Some(cursor), 128)
            .await
            .expect("later checkpoint delta should load");
        hydrate_delta_blobs(&authority, &replica, &delta).await;
        replica
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("warm replica should apply the checkpoint delta");

        let diff = loop {
            match replica
                .execute(
                    "SELECT id AS file_id FROM lix_diff('lix_file', $1, $2)",
                    &[
                        Value::Text(previous_checkpoint.clone()),
                        Value::Text(latest_checkpoint.clone()),
                    ],
                )
                .await
            {
                Ok(diff) => break diff,
                Err(error)
                    if error.code == "LIX_SYNC_HISTORY_REQUIRED"
                        || error.code == LixError::CODE_COMMIT_NOT_FOUND =>
                {
                    let details = error.details.as_ref().expect("history demand details");
                    let commit_ids = if error.code == "LIX_SYNC_HISTORY_REQUIRED" {
                        details["commitIds"]
                            .as_array()
                            .expect("history demand ids")
                            .iter()
                            .map(|id| id.as_str().expect("history demand id").to_owned())
                            .collect::<Vec<_>>()
                    } else {
                        vec![
                            details["commit_id"]
                                .as_str()
                                .expect("missing graph commit id")
                                .to_owned(),
                        ]
                    };
                    for commit_id in commit_ids {
                        let mut page = authority
                            .sync_history(&commit_id, 100)
                            .await
                            .expect("deferred diff history should load from authority");
                        close_history_boundary_bodies(&authority, &mut page).await;
                        let mut boundary_rows = Vec::new();
                        for boundary in &page.boundaries {
                            let rows = authority
                                .pull_sync_snapshot_rows(
                                    &boundary.commit_id,
                                    &boundary.commit_id,
                                    None,
                                    super::super::MAX_SYNC_REQUEST_ITEMS,
                                )
                                .await
                                .expect("history boundary rows should load");
                            assert_eq!(rows.continuation, None);
                            boundary_rows.extend(rows.rows);
                        }
                        replica
                            .import_sync_history_headers(&page.commit_headers)
                            .await
                            .expect("history headers should import");
                        replica
                            .import_sync_history_boundaries(
                                &page.commits,
                                &page.boundaries,
                                &boundary_rows,
                            )
                            .await
                            .expect("history bodies should import");
                    }
                }
                Err(error) => panic!("checkpoint diff should load: {error:?}"),
            }
        };
        assert!(
            diff.rows().iter().any(|row| {
                row.get::<String>("file_id")
                    .is_ok_and(|file_id| file_id == added_file_id)
            }),
            "checkpoint diff should expose the later file id",
        );

        let history = replica
            .execute(
                "SELECT id, to_path AS path FROM lix_history('lix_file', $1) WHERE id = $2 AND lixcol_to_commit_id = $1 ORDER BY lixcol_position ASC LIMIT 1",
                &[
                    Value::Text(latest_checkpoint),
                    Value::Text(added_file_id),
                ],
            )
            .await
            .expect("hydrated warm checkpoint history should be queryable");
        assert_eq!(history.rows().len(), 1);
        assert_eq!(
            history.rows()[0]
                .get::<String>("path")
                .expect("history path should decode"),
            "/added-later.md",
        );
    }

    #[tokio::test]
    #[ignore = "pre-v3 replica outbox semantics were removed"]
    async fn authority_rejects_a_stale_expected_checkpoint_coordinate() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "checkpoint-cas", "baseline").await;
        authority
            .create_checkpoint()
            .await
            .expect("baseline checkpoint should commit");
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let replica = replica_from_snapshot(&authority, &snapshot).await;
        write_key_value(&replica, "checkpoint-cas", "changed").await;
        let mut request = replica
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("push should build")
            .expect("write should be pending");
        let update = request
            .ref_updates
            .first_mut()
            .expect("pending write should update a ref");
        update.expected_checkpoint_commit_id =
            Some(CommitId::for_test_label("stale-expected-sync-checkpoint").to_string());
        let error = authority
            .push_sync_repository(&request)
            .await
            .expect_err("stale checkpoint CAS must fail");
        assert_eq!(error.code, LixError::CODE_TRANSACTION_CONFLICT);
        assert!(error.message.contains("expected coordinate"));
    }

    #[tokio::test]
    #[ignore = "v3 replicas cannot diverge or reconcile"]
    async fn divergent_same_row_deterministically_keeps_authority_value() {
        let authority = open_lix().await.expect("authority should open");
        write_key_value(&authority, "base", "non-root").await;
        let snapshot = authority
            .pull_sync_repository(None, 1)
            .await
            .expect("snapshot should load");
        let left = replica_from_snapshot(&authority, &snapshot).await;
        let right = replica_from_snapshot(&authority, &snapshot).await;

        write_key_value(&left, "shared", "authority-wins").await;
        write_key_value(&right, "shared", "local-pending").await;
        let right_pending = right
            .build_sync_push(TEST_REMOTE, crate::sync::MAX_SYNC_REQUEST_ITEMS)
            .await
            .expect("right pending push should build")
            .expect("right should have pending work");
        for commit in &right_pending.commits {
            assert_root_parent_is_complete(&right, &commit.commit_id).await;
        }
        publish_pending(&left, &authority).await;
        let delta = authority
            .pull_sync_repository(Some(0), 128)
            .await
            .expect("authority delta should load");
        right
            .apply_sync_repository_pull(TEST_REMOTE, &delta)
            .await
            .expect("same-row divergence should reconcile");
        assert_eq!(
            read_key_value(&right, "shared").await,
            "authority-wins",
            "the authority wins an unresolved same-row conflict",
        );

        {
            let read = right
                .storage_adapter()
                .begin_read(StorageReadOptions::default())
                .await
                .expect("reconciled controls should load");
            for (branch_id, control) in BranchHeadControlContext::new()
                .reader(&read)
                .scan()
                .await
                .expect("reconciled controls should scan")
            {
                assert!(
                    control.working_diff_checkpoint_commit_id.is_some(),
                    "reconciled branch '{branch_id}' must retain its checkpoint"
                );
            }
        }

        publish_pending(&right, &authority).await;
        assert_eq!(read_key_value(&authority, "shared").await, "authority-wins",);
    }
}