lix 0.17.1

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
mod partial;
mod partial_merge;

use lix::plugin::runtime::WasmRuntime;
use lix::storage::{Storage, StorageSession};
use lix::telemetry::TelemetrySink;
use lix::{
    Blob, CreateBranchOptions, CreateBranchReceipt, ExecuteBatchStatement, ExecuteIdempotency,
    ExecuteResult, ExecuteStatementMetadata, ExecutionDisposition, LixError, Memory,
    MergeBranchOptions, MergeBranchPreview, MergeBranchPreviewOptions, MergeBranchReceipt,
    ObserveEvent, RedoReceipt, SwitchBranchOptions, SwitchBranchReceipt, UndoReceipt, Value,
};
use std::{
    future::{Future, IntoFuture},
    pin::Pin,
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},
    },
};

use crate::authority_client::{
    ClientCore, ProtocolClient, ProtocolExecuteOptions, ProtocolObserveEvents, ProtocolTransaction,
    open_protocol_client,
};
use crate::common::ExpiredReadRetryState;
use crate::engine::{Engine, EngineOptions};
use crate::open_types::{
    OpenMigrationReport, OpenPhase, OpenProgress, OpenProgressSink, OpenReport, emit_open_progress,
};

use crate::session::SessionContext;
use crate::session::{CoherentReadBatch, ExecuteOptions};
#[cfg(test)]
use crate::transaction_types::TransactionWriteRow;

/// Adapts a Rust closure to [`OpenProgressSink`].
#[expect(missing_debug_implementations)]
pub struct CallbackOpenProgressSink<F> {
    callback: F,
}

impl<F> CallbackOpenProgressSink<F>
where
    F: Fn(OpenProgress) + Send + Sync,
{
    pub fn new(callback: F) -> Self {
        Self { callback }
    }
}

impl<F> OpenProgressSink for CallbackOpenProgressSink<F>
where
    F: Fn(OpenProgress) + Send + Sync,
{
    fn report(&self, progress: OpenProgress) {
        (self.callback)(progress);
    }
}

struct RetainingOpenProgressSink {
    downstream: Option<Arc<dyn OpenProgressSink>>,
    migrated_from: AtomicU32,
    initialized: AtomicBool,
}

impl RetainingOpenProgressSink {
    fn new(downstream: Option<Arc<dyn OpenProgressSink>>) -> Self {
        Self {
            downstream,
            migrated_from: AtomicU32::new(0),
            initialized: AtomicBool::new(false),
        }
    }

    fn migrated_from(&self) -> Option<u32> {
        match self.migrated_from.load(Ordering::Acquire) {
            0 => None,
            version => Some(version),
        }
    }

    fn initialized(&self) -> bool {
        self.initialized.load(Ordering::Acquire)
    }

    fn retain_initialized(&self, initialized: bool) {
        if initialized {
            self.initialized.store(true, Ordering::Release);
        }
    }
}

impl OpenProgressSink for RetainingOpenProgressSink {
    fn report(&self, mut progress: OpenProgress) {
        if let Some(from_format) = progress.from_format {
            self.migrated_from.store(from_format, Ordering::Release);
        } else if matches!(progress.phase, OpenPhase::Opening | OpenPhase::Complete) {
            progress.from_format = self.migrated_from();
        }
        if let Some(downstream) = &self.downstream {
            downstream.report(progress);
        }
    }
}

/// Connection information for a hosted Lix repository.
///
/// A server alone selects remote execution. Adding explicit local storage selects synchronization.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerOptions {
    pub url: String,
    /// HTTP headers included on server protocol requests.
    pub headers: Vec<(String, String)>,
}

impl ServerOptions {
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            headers: Vec::new(),
        }
    }

    /// Adds HTTP headers used by the server transport, such as Authorization.
    pub fn with_headers(mut self, headers: impl IntoIterator<Item = (String, String)>) -> Self {
        self.headers = headers.into_iter().collect();
        self
    }
}

/// Persistence boundary required before acknowledging repository writes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Durability {
    /// Wait for the backend's persistent boundary. Memory storage remains ephemeral.
    #[default]
    Durable,
    /// Acknowledge buffered writes. A crash or power loss may lose acknowledged writes.
    /// Internal publication and synchronization requirements still force durability.
    Buffered,
}

/// Configures a session after local storage has been explicitly selected.
///
/// Start with [`open_lix`] and select storage with `with_storage`. Adding a
/// server to this builder selects synchronization.
#[expect(missing_debug_implementations)]
pub struct OpenLixBuilder<StorageImpl = Memory> {
    durability: Durability,
    storage: StorageImpl,
    wasm_runtime: Option<Arc<dyn WasmRuntime>>,
    telemetry: Option<Arc<dyn TelemetrySink>>,
    server: Option<ServerOptions>,
    open_progress: Option<Arc<dyn OpenProgressSink>>,
}

impl OpenLixBuilder<Memory> {
    fn memory() -> Self {
        Self {
            storage: Memory::new(),
            durability: Durability::default(),
            wasm_runtime: None,
            telemetry: None,
            server: None,
            open_progress: None,
        }
    }
}

impl<StorageImpl> OpenLixBuilder<StorageImpl> {
    /// Sets acknowledgement policy for all writes and sessions opened by this handle.
    /// This controls local persistence, not remote synchronization completion.
    pub fn with_durability(mut self, durability: Durability) -> Self {
        self.durability = durability;
        self
    }

    /// Replaces the default in-memory storage with `storage`.
    pub fn with_storage<NewStorageImpl>(
        self,
        storage: NewStorageImpl,
    ) -> OpenLixBuilder<NewStorageImpl> {
        OpenLixBuilder {
            durability: self.durability,
            storage,
            wasm_runtime: self.wasm_runtime,
            telemetry: self.telemetry,
            server: self.server,
            open_progress: self.open_progress,
        }
    }

    /// Restores a verified snapshot into the selected fresh storage before
    /// opening it. This is a terminal builder step.
    pub fn from_snapshot<Source>(
        self,
        source: Source,
    ) -> OpenLixFromSnapshotBuilder<StorageImpl, Source> {
        OpenLixFromSnapshotBuilder { open: self, source }
    }

    /// Supplies the Component runtime used by plugins.
    pub fn with_wasm_runtime(mut self, wasm_runtime: Arc<dyn WasmRuntime>) -> Self {
        self.wasm_runtime = Some(wasm_runtime);
        self
    }

    /// Sends engine spans to `telemetry` for this Lix instance.
    pub fn with_telemetry(mut self, telemetry: Arc<dyn TelemetrySink>) -> Self {
        self.telemetry = Some(telemetry);
        self
    }

    /// Runs this repository as a local replica of `server`.
    ///
    /// Sync replicas require a storage adapter that implements durable reads.
    /// The default in-memory adapter is intentionally not supported because it
    /// cannot prove that a bootstrap snapshot survived its publication fence.
    pub fn with_server(mut self, server: ServerOptions) -> Self {
        self.server = Some(server);
        self
    }

    /// Observes current-format repository inspection and opening. Migration is explicit.
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), lix::LixError> {
    /// use std::sync::Arc;
    /// let sink = lix::CallbackOpenProgressSink::new(|progress| {
    ///     eprintln!("opening: {:?}", progress.phase);
    /// });
    /// let lix = lix::open_lix()
    ///     .with_open_progress_sink(Arc::new(sink))
    ///     .await?;
    /// # lix.close().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_open_progress_sink(mut self, sink: Arc<dyn OpenProgressSink>) -> Self {
        self.open_progress = Some(sink);
        self
    }

    /// Opens the repository as a canonical Lix Server Protocol session factory.
    ///
    /// Serving owns the repository engine directly and creates no application
    /// session. Each successful protocol handshake retains exactly one
    /// application session.
    #[cfg(feature = "server-protocol")]
    pub fn serve(self) -> crate::server_protocol::ServeLixBuilder<StorageImpl> {
        crate::server_protocol::ServeLixBuilder::new(self)
    }
}

#[cfg(feature = "server-protocol")]
impl<StorageImpl> OpenLixBuilder<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    pub(crate) async fn open_protocol_engine(
        self,
    ) -> Result<Engine<StorageSession<StorageImpl>>, LixError> {
        if self.server.is_some() {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "a Lix Server Protocol authority cannot also be a sync replica",
            ));
        }
        let storage = StorageSession::acquire(self.storage).await?;
        let retained_progress = Arc::new(RetainingOpenProgressSink::new(self.open_progress));
        let (engine, migrated_from) = retry_expired_read(|| {
            let storage = storage.clone();
            let open_progress: Arc<dyn OpenProgressSink> = retained_progress.clone();
            let wasm_runtime = self.wasm_runtime.clone();
            let telemetry = self.telemetry.clone();
            async move {
                let admission =
                    ensure_current_repository(&storage, Some(&open_progress), None).await?;
                let migrated_from = admission
                    .report
                    .migration
                    .map(|migration| migration.from_format);
                emit_open_progress(
                    Some(&open_progress),
                    OpenProgress {
                        phase: OpenPhase::Opening,
                        from_format: migrated_from,
                        to_format: crate::init::CURRENT_FORMAT_VERSION,
                        completed: None,
                        total: None,
                    },
                );
                let (engine, _) = open_or_initialize_engine_with_adapter(
                    admission.adapter.with_durability(self.durability),
                    wasm_runtime,
                    telemetry,
                    None,
                    None,
                )
                .await?;
                let engine_storage = engine.storage();
                let read = engine_storage
                    .begin_read(crate::storage_adapter::StorageReadOptions::default())
                    .await?;
                if crate::sync::has_any_sync_replica_state(&read).await? {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "a persisted sync replica cannot be served as a protocol authority",
                    ));
                }
                Ok((engine, migrated_from))
            }
        })
        .await?;
        let migrated_from = migrated_from.or_else(|| retained_progress.migrated_from());
        let open_progress: Arc<dyn OpenProgressSink> = retained_progress;
        emit_open_progress(
            Some(&open_progress),
            OpenProgress {
                phase: OpenPhase::Complete,
                from_format: migrated_from,
                to_format: crate::init::CURRENT_FORMAT_VERSION,
                completed: None,
                total: None,
            },
        );
        Ok(engine)
    }
}

/// Starts configuring the primary session for a Lix repository.
///
/// The primary session starts on the repository's tracked
/// `lix_default_branch_id`. Applications own window- or session-specific
/// branch selection and can switch explicitly after opening.
///
/// Await the returned builder to open a new in-memory Lix:
///
/// ```no_run
/// # async fn example() -> Result<(), lix::LixError> {
/// let lix = lix::open_lix().await?;
/// # Ok(())
/// # }
/// ```
pub fn open_lix() -> UnconfiguredOpenLixBuilder {
    UnconfiguredOpenLixBuilder(OpenLixBuilder::memory())
}

/// An open request without explicitly selected storage.
/// Supplying only a server opens remote execution; supplying storage opens locally.
#[expect(missing_debug_implementations)]
pub struct UnconfiguredOpenLixBuilder(OpenLixBuilder<Memory>);

impl UnconfiguredOpenLixBuilder {
    pub fn with_storage<S>(self, storage: S) -> OpenLixBuilder<S> {
        self.0.with_storage(storage)
    }
    pub fn with_server(self, server: ServerOptions) -> RemoteOpenLixBuilder {
        RemoteOpenLixBuilder {
            open: self.0,
            server,
        }
    }
    pub fn with_wasm_runtime(mut self, runtime: Arc<dyn WasmRuntime>) -> Self {
        self.0 = self.0.with_wasm_runtime(runtime);
        self
    }
    pub fn with_telemetry(mut self, telemetry: Arc<dyn TelemetrySink>) -> Self {
        self.0 = self.0.with_telemetry(telemetry);
        self
    }
    pub fn with_open_progress_sink(mut self, sink: Arc<dyn OpenProgressSink>) -> Self {
        self.0 = self.0.with_open_progress_sink(sink);
        self
    }
    pub fn from_snapshot<S>(self, source: S) -> OpenLixFromSnapshotBuilder<Memory, S> {
        self.0.from_snapshot(source)
    }
    #[cfg(feature = "server-protocol")]
    pub fn serve(self) -> crate::server_protocol::ServeLixBuilder<Memory> {
        self.0.serve()
    }
}

impl IntoFuture for UnconfiguredOpenLixBuilder {
    type Output = Result<Lix<Memory>, LixError>;
    type IntoFuture = <OpenLixBuilder<Memory> as IntoFuture>::IntoFuture;
    fn into_future(self) -> Self::IntoFuture {
        self.0.into_future()
    }
}

/// An open request with a server but no explicitly selected local storage.
#[expect(missing_debug_implementations)]
pub struct RemoteOpenLixBuilder {
    open: OpenLixBuilder<Memory>,
    server: ServerOptions,
}
impl RemoteOpenLixBuilder {
    /// Selects a local replica with durable local writes and background sync.
    pub fn with_storage<S>(self, storage: S) -> OpenLixBuilder<S> {
        self.open.with_storage(storage).with_server(self.server)
    }
}
impl IntoFuture for RemoteOpenLixBuilder {
    type Output = Result<RemoteLix, LixError>;
    type IntoFuture = crate::sync::SyncTransportFuture<'static, RemoteLix>;
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            if self.open.wasm_runtime.is_some()
                || self.open.telemetry.is_some()
                || self.open.open_progress.is_some()
            {
                return Err(LixError::new(
                    LixError::CODE_INVALID_PARAM,
                    "remote execution cannot configure a local runtime, telemetry sink, or storage progress sink",
                ));
            }
            let http = crate::sync::authority_http(&self.server.headers)?;
            let client = open_protocol_client(http, self.server.url, None).await?;
            let account_id = client.active_account_id().await?;
            Ok(RemoteLix { client, account_id })
        })
    }
}

/// A repository whose operations execute on its server.
#[derive(Debug, Clone)]
pub struct RemoteLix {
    account_id: String,
    client: ProtocolClient<crate::sync::AuthorityHttp>,
}
impl RemoteLix {
    /// Streams a complete snapshot from the server without allocating local storage.
    pub fn export_snapshot(&self) -> crate::snapshot::SnapshotExportBuilder<Memory> {
        crate::snapshot::SnapshotExportBuilder::remote(
            self.client.http().clone(),
            self.client
                .ensure_usable()
                .and_then(|_| self.client.join_path("snapshot")),
            self.client.session_id(),
        )
    }

    pub fn execute<'a>(&'a self, sql: &'a str, params: &'a [Value]) -> RemoteExecuteBuilder<'a> {
        RemoteExecuteBuilder {
            lix: self,
            sql,
            params,
            options: ProtocolExecuteOptions::default(),
        }
    }
    pub async fn create_branch(
        &self,
        options: CreateBranchOptions,
    ) -> Result<CreateBranchReceipt, LixError> {
        self.client.create_branch(options).await
    }
    pub async fn merge_branch(
        &self,
        options: MergeBranchOptions,
    ) -> Result<MergeBranchReceipt, LixError> {
        self.client.merge_branch(options).await
    }
    pub async fn merge_branch_preview(
        &self,
        options: MergeBranchPreviewOptions,
    ) -> Result<MergeBranchPreview, LixError> {
        self.client.merge_branch_preview(options).await
    }
    pub async fn switch_branch(
        &self,
        options: SwitchBranchOptions,
    ) -> Result<SwitchBranchReceipt, LixError> {
        self.client
            .switch_branch_and_restart(&options.branch_id)
            .await
    }
    pub async fn undo(&self) -> Result<UndoReceipt, LixError> {
        self.client.undo().await
    }
    pub async fn redo(&self) -> Result<RedoReceipt, LixError> {
        self.client.redo().await
    }
    pub async fn begin_transaction(&self) -> Result<RemoteLixTransaction, LixError> {
        let client = self
            .client
            .open_another_session(None, Some(self.account_id.clone()))
            .await?;
        // Own the session before awaiting begin so failure or cancellation
        // schedules closure of any transaction the server may have started.
        let mut opened = RemoteLixTransaction {
            transaction: None,
            client: Some(client),
        };
        opened.transaction = Some(
            opened
                .client
                .as_ref()
                .ok_or_else(closed_transaction_error)?
                .begin_transaction()
                .await?,
        );
        Ok(opened)
    }

    pub fn observe(&self, sql: &str, params: &[Value]) -> Result<RemoteObserveEvents, LixError> {
        self.client.ensure_usable()?;
        Ok(RemoteObserveEvents {
            client: self.client.clone(),
            sql: sql.to_owned(),
            params: params.to_vec(),
            events: None,
            closed: false,
        })
    }
    pub fn open_another_session(&self) -> RemoteOpenAnotherSessionBuilder<'_> {
        RemoteOpenAnotherSessionBuilder {
            lix: self,
            account_id: None,
            branch_id: None,
        }
    }
    pub fn execute_batch<'a>(
        &'a self,
        statements: &'a [ExecuteBatchStatement],
    ) -> RemoteExecuteBatchBuilder<'a> {
        RemoteExecuteBatchBuilder {
            lix: self,
            statements,
            options: ProtocolExecuteOptions::default(),
        }
    }
    pub async fn active_branch_id(&self) -> Result<String, LixError> {
        self.client.active_branch_id().await
    }
    pub fn active_account_id(&self) -> &str {
        &self.account_id
    }
    pub async fn close(&self) -> Result<(), LixError> {
        self.client.close().await
    }
}

/// A transaction executing on the remote repository.
///
/// Each transaction owns a dedicated server session. Dropping it schedules
/// best-effort session closure, which rolls back unfinished work without
/// blocking the parent session. Server session expiry bounds abandoned work.
/// Call [`Self::rollback`] to await rollback and session closure explicitly.
#[derive(Debug)]
pub struct RemoteLixTransaction {
    transaction: Option<ProtocolTransaction<crate::sync::AuthorityHttp>>,
    client: Option<ProtocolClient<crate::sync::AuthorityHttp>>,
}
impl RemoteLixTransaction {
    pub fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [Value],
    ) -> RemoteTransactionExecuteBuilder<'a> {
        RemoteTransactionExecuteBuilder {
            transaction: self,
            sql,
            params,
            options: ProtocolExecuteOptions::default(),
        }
    }
    pub async fn commit(mut self) -> Result<crate::CommitReceipt, LixError> {
        let result = self
            .transaction
            .as_ref()
            .ok_or_else(closed_transaction_error)?
            .commit()
            .await;
        let close_result = self
            .client
            .as_ref()
            .ok_or_else(closed_transaction_error)?
            .close()
            .await;
        self.client.take();
        let receipt = result?;
        close_result.map_err(|error| receipt.annotate_completion_error(error))?;
        Ok(receipt)
    }
    pub async fn rollback(mut self) -> Result<(), LixError> {
        let result = self
            .transaction
            .as_ref()
            .ok_or_else(closed_transaction_error)?
            .rollback()
            .await;
        let close_result = self
            .client
            .as_ref()
            .ok_or_else(closed_transaction_error)?
            .close()
            .await;
        self.client.take();
        result?;
        close_result
    }
}

impl Drop for RemoteLixTransaction {
    fn drop(&mut self) {
        let Some(client) = self.client.take() else {
            return;
        };
        let http = client.http().clone();
        crate::authority_client::ProtocolHttp::spawn(
            &http,
            Box::pin(async move {
                let _ = client.close().await;
            }),
        );
    }
}

/// Configures an independent remote session.
#[derive(Debug)]
pub struct RemoteOpenAnotherSessionBuilder<'a> {
    lix: &'a RemoteLix,
    account_id: Option<String>,
    branch_id: Option<String>,
}
impl RemoteOpenAnotherSessionBuilder<'_> {
    pub fn with_account(mut self, account_id: impl Into<String>) -> Self {
        self.account_id = Some(account_id.into());
        self
    }
    pub fn with_branch(mut self, branch_id: impl Into<String>) -> Self {
        self.branch_id = Some(branch_id.into());
        self
    }
}
impl<'a> IntoFuture for RemoteOpenAnotherSessionBuilder<'a> {
    type Output = Result<RemoteLix, LixError>;
    type IntoFuture = crate::sync::SyncTransportFuture<'a, RemoteLix>;
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let client = self
                .lix
                .client
                .open_another_session(self.branch_id, self.account_id)
                .await?;
            let account_id = client.active_account_id().await?;
            Ok(RemoteLix { client, account_id })
        })
    }
}

/// Configures SQL executed inside a remote transaction.
#[derive(Debug)]
pub struct RemoteTransactionExecuteBuilder<'a> {
    transaction: &'a RemoteLixTransaction,
    sql: &'a str,
    params: &'a [Value],
    options: ProtocolExecuteOptions,
}
impl RemoteTransactionExecuteBuilder<'_> {
    pub fn with_origin_key(mut self, origin_key: impl Into<String>) -> Self {
        self.options.origin_key = Some(origin_key.into());
        self
    }
}
impl<'a> IntoFuture for RemoteTransactionExecuteBuilder<'a> {
    type Output = Result<ExecuteResult, LixError>;
    type IntoFuture = crate::sync::SyncTransportFuture<'a, ExecuteResult>;
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            self.transaction
                .transaction
                .as_ref()
                .ok_or_else(closed_transaction_error)?
                .execute(self.sql, self.params, Some(self.options))
                .await
        })
    }
}

/// Observation events streamed from the remote repository.
#[expect(missing_debug_implementations)]
pub struct RemoteObserveEvents {
    client: ProtocolClient<crate::sync::AuthorityHttp>,
    sql: String,
    params: Vec<Value>,
    events: Option<ProtocolObserveEvents<ClientCore<crate::sync::AuthorityHttp>>>,
    closed: bool,
}
impl RemoteObserveEvents {
    pub async fn next(&mut self) -> Result<Option<ObserveEvent>, LixError> {
        if self.closed {
            return Ok(None);
        }
        if self.events.is_none() {
            self.events = Some(self.client.observe(&self.sql, self.params.clone()).await?);
        }
        self.events
            .as_ref()
            .expect("observation registered")
            .next()
            .await
    }
    pub fn close(&mut self) {
        self.closed = true;
        if let Some(events) = self.events.take() {
            events.close();
        }
    }
}

/// Configures an atomic SQL batch on the server.
#[derive(Debug)]
pub struct RemoteExecuteBatchBuilder<'a> {
    lix: &'a RemoteLix,
    statements: &'a [ExecuteBatchStatement],
    options: ProtocolExecuteOptions,
}
impl RemoteExecuteBatchBuilder<'_> {
    pub fn with_origin_key(mut self, origin_key: impl Into<String>) -> Self {
        self.options.origin_key = Some(origin_key.into());
        self
    }

    /// Caps whole automatic-transaction replays. Zero fails on the first failed attempt.
    /// Without an override, Lix retains its default conflict and snapshot-recovery budgets.
    pub fn with_max_auto_commit_retries(mut self, retries: u32) -> Self {
        self.options.max_auto_commit_retries = Some(retries);
        self
    }
}
impl<'a> IntoFuture for RemoteExecuteBatchBuilder<'a> {
    type Output = Result<crate::ExecuteBatchResult, LixError>;
    type IntoFuture = crate::sync::SyncTransportFuture<'a, crate::ExecuteBatchResult>;
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            self.lix
                .client
                .execute_batch(self.statements, Some(self.options))
                .await
        })
    }
}

/// Configures execution on a remote repository.
#[derive(Debug)]
pub struct RemoteExecuteBuilder<'a> {
    lix: &'a RemoteLix,
    sql: &'a str,
    params: &'a [Value],
    options: ProtocolExecuteOptions,
}
impl RemoteExecuteBuilder<'_> {
    pub fn with_origin_key(mut self, origin_key: impl Into<String>) -> Self {
        self.options.origin_key = Some(origin_key.into());
        self
    }

    /// Caps whole automatic-transaction replays. Zero fails on the first failed attempt.
    /// Without an override, Lix retains its default conflict and snapshot-recovery budgets.
    pub fn with_max_auto_commit_retries(mut self, retries: u32) -> Self {
        self.options.max_auto_commit_retries = Some(retries);
        self
    }
}
impl<'a> IntoFuture for RemoteExecuteBuilder<'a> {
    type Output = Result<ExecuteResult, LixError>;
    type IntoFuture = crate::sync::SyncTransportFuture<'a, ExecuteResult>;
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            self.lix
                .client
                .execute(self.sql, self.params, Some(self.options))
                .await
        })
    }
}

/// Restores a snapshot into fresh storage and then opens the resulting Lix.
#[expect(missing_debug_implementations)]
pub struct OpenLixFromSnapshotBuilder<StorageImpl, Source> {
    open: OpenLixBuilder<StorageImpl>,
    source: Source,
}

async fn finish_open<StorageImpl>(
    open: OpenLixBuilder<StorageImpl>,
    storage: StorageSession<StorageImpl>,
) -> Result<Lix<StorageImpl>, LixError>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    let retained_progress = Arc::new(RetainingOpenProgressSink::new(open.open_progress.clone()));
    // Opening is one restartable unit. In cross-context storage, a competing
    // tab may commit during any phase, including sync bootstrap after the
    // engine and primary session exist.
    let mut lix = retry_expired_read(|| {
        open_lix_inner(
            storage.clone(),
            open.wasm_runtime.clone(),
            open.telemetry.clone(),
            open.server.clone(),
            retained_progress.clone(),
            open.durability,
        )
    })
    .await?;
    let initialized = lix.open_report.initialized || retained_progress.initialized();
    let migration = lix.open_report.migration.or_else(|| {
        retained_progress
            .migrated_from()
            .map(|from_format| OpenMigrationReport {
                from_format,
                to_format: crate::init::CURRENT_FORMAT_VERSION,
            })
    });
    if initialized != lix.open_report.initialized || migration != lix.open_report.migration {
        lix.open_report = Arc::new(OpenReport {
            format: lix.open_report.format,
            initialized,
            migration,
        });
    }
    Ok(lix)
}

impl<StorageImpl> IntoFuture for OpenLixBuilder<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    type Output = Result<Lix<StorageImpl>, LixError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        // SAFETY: the builder owns Send storage/runtime/telemetry values, and
        // the returned Lix contains only Send synchronization primitives. The
        // compiler cannot prove all deeply nested SQL futures are Send.
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                // Acquire exactly once and retain this fenced generation across
                // every retry and for the complete lifetime of the returned Lix.
                let storage = StorageSession::acquire(self.storage.clone()).await?;
                finish_open(self, storage).await
            })
        })
    }
}

impl<StorageImpl, Source> IntoFuture for OpenLixFromSnapshotBuilder<StorageImpl, Source>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
    Source: futures_io::AsyncRead + Unpin + Send + 'static,
{
    type Output = Result<Lix<StorageImpl>, LixError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                if self.open.server.is_some() {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "snapshot restore cannot be combined with server mode",
                    ));
                }
                let storage = StorageSession::acquire(self.open.storage.clone()).await?;
                let storage = crate::snapshot::restore_snapshot(storage, self.source).await?;
                finish_open(self.open, storage).await
            })
        })
    }
}

/// Configures another independent session for an open Lix repository.
///
/// The new session starts on the current branch and inherits the current
/// account unless [`OpenAnotherSessionBuilder::with_account`] overrides it.
#[expect(missing_debug_implementations)]
pub struct OpenAnotherSessionBuilder<'a, StorageImpl = Memory>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    lix: &'a Lix<StorageImpl>,
    account_id: Option<String>,
    branch_id: Option<String>,
}

impl<'a, StorageImpl> OpenAnotherSessionBuilder<'a, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    /// Attributes changes from the new session to `account_id`.
    ///
    /// This selects an existing account; it does not create one.
    pub fn with_account(mut self, account_id: impl Into<String>) -> Self {
        self.account_id = Some(account_id.into());
        self
    }

    /// Opens the additional session on `branch_id` without changing the
    /// primary session or repository default.
    pub fn with_branch(mut self, branch_id: impl Into<String>) -> Self {
        self.branch_id = Some(branch_id.into());
        self
    }
}

impl<'a, StorageImpl> IntoFuture for OpenAnotherSessionBuilder<'a, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    type Output = Result<Lix<StorageImpl>, LixError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        // SAFETY: the future only borrows a Send + Sync Lix handle and owns the
        // optional account id. Storage handles satisfy the Storage Send
        // contract; the remaining compiler limitation is caused by nested
        // higher-ranked SQL futures.
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                self.lix
                    .open_another_session_inner(self.account_id, self.branch_id)
                    .await
            })
        })
    }
}

/// Configures one SQL statement execution.
#[expect(missing_debug_implementations)]
pub struct ExecuteBuilder<'a, StorageImpl = Memory>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    lix: &'a Lix<StorageImpl>,
    sql: String,
    params: Vec<Value>,
    options: ExecuteOptions,
}

impl<StorageImpl> ExecuteBuilder<'_, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    /// Identifies the caller-defined origin of this execution.
    pub fn with_origin_key(mut self, origin_key: impl Into<String>) -> Self {
        self.options.origin_key = Some(origin_key.into());
        self
    }

    /// Caps whole automatic-transaction replays. Zero fails on the first failed attempt.
    /// Without an override, Lix retains its default conflict and snapshot-recovery budgets.
    pub fn with_max_auto_commit_retries(mut self, retries: u32) -> Self {
        self.options.max_auto_commit_retries = Some(retries);
        self
    }
}

impl<'a, StorageImpl> IntoFuture for ExecuteBuilder<'a, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    type Output = Result<ExecuteResult, LixError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        // SAFETY: the builder owns the SQL, parameters, and options. The only
        // borrowed value retained across suspension is a shared reference to
        // the Sync session; storage handles are Send by the Storage contract.
        if !matches!(
            self.lix.engine.sync_mode().role(),
            crate::sync::SyncRole::Replica | crate::sync::SyncRole::PartialReplica
        ) {
            return Box::pin(unsafe {
                crate::session::AssumeSendFuture::new(async move {
                    self.lix
                        .session
                        .execute_with_options(&self.sql, &self.params, self.options)
                        .await
                })
            });
        }
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                let route = self.lix.session.execution_disposition(&self.sql)?;
                self.lix
                    .retry_replica_read(route, || {
                        self.lix.retry_sync_demands(|| {
                            self.lix.session.execute_with_options(
                                &self.sql,
                                &self.params,
                                self.options.clone(),
                            )
                        })
                    })
                    .await
            })
        })
    }
}

/// Configures one atomic SQL batch execution.
#[expect(missing_debug_implementations)]
pub struct ExecuteBatchBuilder<'a, StorageImpl = Memory>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    lix: &'a Lix<StorageImpl>,
    statements: Vec<ExecuteBatchStatement>,
    options: ExecuteOptions,
}

impl<StorageImpl> ExecuteBatchBuilder<'_, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    /// Identifies the caller-defined origin of this batch.
    pub fn with_origin_key(mut self, origin_key: impl Into<String>) -> Self {
        self.options.origin_key = Some(origin_key.into());
        self
    }

    /// Caps whole automatic-transaction replays. Zero fails on the first failed attempt.
    /// Without an override, Lix retains its default conflict and snapshot-recovery budgets.
    pub fn with_max_auto_commit_retries(mut self, retries: u32) -> Self {
        self.options.max_auto_commit_retries = Some(retries);
        self
    }
}

impl<'a, StorageImpl> IntoFuture for ExecuteBatchBuilder<'a, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    type Output = Result<crate::ExecuteBatchResult, LixError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        // SAFETY: as above, the builder owns every request value and borrows
        // only the Sync session across suspension.
        if !matches!(
            self.lix.engine.sync_mode().role(),
            crate::sync::SyncRole::Replica | crate::sync::SyncRole::PartialReplica
        ) {
            return Box::pin(unsafe {
                crate::session::AssumeSendFuture::new(async move {
                    self.lix
                        .session
                        .execute_batch_with_options(&self.statements, self.options)
                        .await
                        .map(crate::ExecuteBatchResult::from_results)
                })
            });
        }
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                let route = self
                    .lix
                    .session
                    .execute_batch_disposition(&self.statements)?;
                self.lix
                    .retry_replica_read(route, || {
                        self.lix.retry_sync_demands(|| {
                            self.lix
                                .session
                                .execute_batch_with_options(&self.statements, self.options.clone())
                        })
                    })
                    .await
                    .map(crate::ExecuteBatchResult::from_results)
            })
        })
    }
}

/// Clonable handle for a Lix repository.
///
/// Clones share the active branch, file-view state, and close lifecycle.
/// Explicit transactions use independent contexts on the captured branch.
///
/// Public operation builders erase their internal future type, so embedding
/// applications can spawn composed Lix flows without raising rustc's
/// recursion limit.
#[derive(Clone)]
#[expect(missing_debug_implementations)]
pub struct Lix<StorageImpl = Memory>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    engine: Arc<Engine<StorageSession<StorageImpl>>>,
    session: Arc<SessionContext<StorageSession<StorageImpl>>>,
    transaction_lifecycle: Arc<PublicTransactionLifecycle>,
    primary_switch_gate: Option<Arc<tokio::sync::Mutex<()>>>,
    sync_lease: Option<Arc<SyncSessionLease>>,
    sync_demand_tx: Option<tokio::sync::mpsc::Sender<crate::sync::SyncDemand>>,
    server: Option<ServerOptions>,
    open_report: Arc<OpenReport>,
}

/// Reserves only the handle's close lifecycle, not its SQL session.
#[derive(Debug, Default)]
struct PublicTransactionLifecycle {
    admission: tokio::sync::Mutex<()>,
    active: AtomicUsize,
}

#[derive(Debug)]
struct PublicTransactionLease(Arc<PublicTransactionLifecycle>);

impl PublicTransactionLease {
    fn acquire(lifecycle: Arc<PublicTransactionLifecycle>) -> Result<Self, LixError> {
        lifecycle
            .active
            .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
            .map_err(|_| {
                LixError::new(
                    "LIX_INVALID_TRANSACTION_STATE",
                    "Lix handle already has an active transaction",
                )
            })?;
        Ok(Self(lifecycle))
    }
}

impl Drop for PublicTransactionLease {
    fn drop(&mut self) {
        self.0.active.fetch_sub(1, Ordering::AcqRel);
    }
}

/// A live query observation bound to the local storage session.
#[expect(missing_debug_implementations)]
pub struct ObserveEvents<StorageImpl = Memory>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    events: crate::session::SessionObserveEvents<StorageSession<StorageImpl>>,
}

impl<StorageImpl> ObserveEvents<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    pub fn next(
        &mut self,
    ) -> impl Future<Output = Result<Option<ObserveEvent>, LixError>> + Send + '_ {
        self.events.next()
    }

    pub fn close(&mut self) {
        self.events.close();
    }
}

#[derive(Debug)]
struct SyncSessionLease {
    runtime: Arc<crate::sync::SyncRuntime>,
    active_sessions: Arc<AtomicUsize>,
    partial_owner: Option<crate::engine::PartialOwnerLifetime>,
    released: AtomicBool,
}

impl SyncSessionLease {
    fn root_with_owner(
        runtime: Arc<crate::sync::SyncRuntime>,
        owner: crate::engine::PartialOwnerLifetime,
    ) -> Arc<Self> {
        Arc::new(Self {
            runtime,
            active_sessions: Arc::new(AtomicUsize::new(1)),
            partial_owner: Some(owner),
            released: AtomicBool::new(false),
        })
    }

    fn child(&self) -> Arc<Self> {
        self.active_sessions.fetch_add(1, Ordering::AcqRel);
        Arc::new(Self {
            runtime: self.runtime.clone(),
            active_sessions: self.active_sessions.clone(),
            partial_owner: self.partial_owner.clone(),
            released: AtomicBool::new(false),
        })
    }

    async fn release(&self) -> Result<(), LixError> {
        if self.released.swap(true, Ordering::AcqRel) {
            return Ok(());
        }
        if self.active_sessions.fetch_sub(1, Ordering::AcqRel) == 1 {
            if let Some(owner) = &self.partial_owner {
                owner.close();
            }
            self.runtime.stop_and_join().await?;
        }
        Ok(())
    }
}

async fn open_lix_inner<StorageImpl>(
    storage: StorageSession<StorageImpl>,
    wasm_runtime: Option<Arc<dyn WasmRuntime>>,
    telemetry: Option<Arc<dyn TelemetrySink>>,
    server: Option<ServerOptions>,
    retained_progress: Arc<RetainingOpenProgressSink>,
    durability: Durability,
) -> Result<Lix<StorageImpl>, LixError>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    let server = match server {
        Some(mut server) => {
            server.url = crate::sync::normalize_sync_locator(&server.url)?.locator;
            Some(server)
        }
        None => None,
    };
    let open_progress: Arc<dyn OpenProgressSink> = retained_progress.clone();
    // Sync opening is a partial replica with on-demand sync. A metadata-only
    // default-read probe recognizes offline partial storage without requiring
    // Durable reads from ordinary standalone Memory repositories.
    if server.is_some() || crate::migration::has_partial_replica_marker(&storage).await? {
        emit_open_progress(
            Some(&open_progress),
            OpenProgress {
                phase: OpenPhase::Opening,
                from_format: None,
                to_format: crate::init::CURRENT_FORMAT_VERSION,
                completed: None,
                total: None,
            },
        );
        let lix =
            partial::open_partial_lix(storage, wasm_runtime, telemetry, server, durability).await?;
        retained_progress.retain_initialized(lix.open_report.initialized);
        emit_open_progress(
            Some(&open_progress),
            OpenProgress {
                phase: OpenPhase::Complete,
                from_format: None,
                to_format: crate::init::CURRENT_FORMAT_VERSION,
                completed: None,
                total: None,
            },
        );
        return Ok(lix);
    }
    let admission =
        ensure_current_repository(&storage, Some(&open_progress), server.as_ref()).await?;
    let mut open_report = admission.report;
    retained_progress.retain_initialized(open_report.initialized);
    let migrated_from = open_report.migration.map(|migration| migration.from_format);
    emit_open_progress(
        Some(&open_progress),
        OpenProgress {
            phase: OpenPhase::Opening,
            from_format: migrated_from,
            to_format: crate::init::CURRENT_FORMAT_VERSION,
            completed: None,
            total: None,
        },
    );
    let (engine, engine_initialized) = open_or_initialize_engine_with_adapter(
        admission.adapter.with_durability(durability),
        wasm_runtime,
        telemetry,
        None,
        None,
    )
    .await?;
    if engine_initialized {
        open_report.initialized = true;
        retained_progress.retain_initialized(true);
    }
    let session = engine.open_session().await?;
    let lix = Lix {
        engine: Arc::new(engine),
        session: Arc::new(session),
        transaction_lifecycle: Arc::default(),
        primary_switch_gate: Some(Arc::new(tokio::sync::Mutex::new(()))),
        sync_lease: None,
        sync_demand_tx: None,
        server: server.clone(),
        open_report: Arc::new(open_report),
    };
    lix.bind_session();
    emit_open_progress(
        Some(&open_progress),
        OpenProgress {
            phase: OpenPhase::Complete,
            from_format: migrated_from,
            to_format: crate::init::CURRENT_FORMAT_VERSION,
            completed: None,
            total: None,
        },
    );
    Ok(lix)
}

// Builds a private candidate without starting a sync worker or publishing an
// epoch. The migration owner validates and publishes only after this returns.
pub(crate) async fn new_replica_migration_candidate<S>(
    adapter: crate::storage_adapter::StorageAdapter<S>,
    default_branch_id: &str,
) -> Result<Lix<S>, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    let adapter = adapter.with_session().await?;
    let (engine, _) =
        open_or_initialize_engine_with_adapter(adapter, None, None, None, Some(default_branch_id))
            .await?;
    let session = engine.open_session().await?;
    Ok(Lix {
        engine: Arc::new(engine),
        session: Arc::new(session),
        transaction_lifecycle: Arc::default(),
        primary_switch_gate: Some(Arc::new(tokio::sync::Mutex::new(()))),
        sync_lease: None,
        sync_demand_tx: None,
        server: None,
        open_report: Arc::new(OpenReport {
            format: crate::init::CURRENT_FORMAT_VERSION,
            initialized: false,
            migration: None,
        }),
    })
}

/// Isolated writer admission for an explicit authenticated recovery operation.
/// No worker, pull loop or upload loop is installed on this context.
pub(crate) async fn new_replica_recovery_context<S>(
    adapter: crate::storage_adapter::StorageAdapter<S>,
    branch_id: &str,
    account_id: &str,
) -> Result<Lix<S>, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    let candidate = new_replica_migration_candidate(adapter, branch_id).await?;
    let opened = candidate.open_internal_session(branch_id, account_id).await;
    let recovery = match opened {
        Ok(recovery) => recovery,
        Err(error) => {
            let _ = candidate.close().await;
            return Err(error);
        }
    };
    recovery.set_sync_role(crate::sync::SyncRole::Replica)?;
    candidate.close().await?;
    Ok(recovery)
}

struct RepositoryAdmission<StorageImpl> {
    adapter: crate::storage_adapter::StorageAdapter<StorageImpl>,
    report: OpenReport,
}

async fn ensure_current_repository<StorageImpl>(
    storage: &StorageImpl,
    progress: Option<&Arc<dyn OpenProgressSink>>,
    _server: Option<&ServerOptions>,
) -> Result<RepositoryAdmission<StorageImpl>, LixError>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    let current = crate::init::CURRENT_FORMAT_VERSION;
    emit_open_progress(
        progress,
        OpenProgress {
            phase: OpenPhase::Inspecting,
            from_format: None,
            to_format: current,
            completed: None,
            total: None,
        },
    );
    let admission = crate::migration::admit_current_repository(storage, true).await?;
    Ok(RepositoryAdmission {
        adapter: admission.adapter,
        report: admission.report,
    })
}

impl<StorageImpl> Lix<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    /// Returns local synchronization health without issuing SQL or network requests.
    /// Available after close so a stopped worker can still be diagnosed.
    pub fn sync_health(&self) -> crate::SyncHealth {
        self.engine.sync_mode().health().snapshot()
    }

    /// Configures a deterministic, stream-first snapshot export.
    pub fn export_snapshot(&self) -> crate::snapshot::SnapshotExportBuilder<StorageImpl> {
        let export = crate::snapshot::SnapshotExportBuilder::new(self.engine.storage());
        if self.engine.sync_mode().role() == crate::sync::SyncRole::PartialReplica {
            // A local export must preserve the state the caller is diagnosing,
            // including unpublished edits and its exact resident working set.
            export.from_local_partial_replica()
        } else if let Some(server) = &self.server {
            export.from_sync_server(server.clone(), self.active_account_id().to_owned())
        } else if self.engine.sync_mode().role().is_replica() {
            export.reject_connected_replica()
        } else {
            export
        }
    }

    #[cfg(feature = "server-protocol")]
    pub(crate) async fn open_protocol_session(
        engine: Arc<Engine<StorageSession<StorageImpl>>>,
        active_branch_id: Option<String>,
        active_account_id: String,
    ) -> Result<Self, LixError> {
        let session = match active_branch_id {
            Some(active_branch_id) => {
                if engine
                    .load_branch_head_commit_id(&active_branch_id)
                    .await?
                    .is_none()
                {
                    return Err(LixError::branch_not_found(
                        active_branch_id,
                        "open_protocol_session",
                        "target",
                    ));
                }
                engine
                    .open_session_at_with_account(active_branch_id, active_account_id)
                    .await?
            }
            None => engine.open_session_with_account(active_account_id).await?,
        };
        Ok(Self {
            engine,
            session: Arc::new(session),
            transaction_lifecycle: Arc::default(),
            primary_switch_gate: None,
            sync_lease: None,
            sync_demand_tx: None,
            server: None,
            open_report: Arc::new(OpenReport {
                format: crate::init::CURRENT_FORMAT_VERSION,
                initialized: false,
                migration: None,
            }),
        })
    }

    async fn retry_sync_demands<T, Operation, OperationFuture>(
        &self,
        mut operation: Operation,
    ) -> Result<T, LixError>
    where
        Operation: FnMut() -> OperationFuture,
        OperationFuture: Future<Output = Result<T, LixError>>,
    {
        let mut retry = crate::sync::SyncDemandRetry::default();
        loop {
            match operation().await {
                Err(error) => {
                    retry
                        .hydrate_for_retry(self.sync_demand_tx.as_ref(), error)
                        .await?;
                }
                result => return result,
            }
        }
    }

    #[cfg(feature = "storage-benches")]
    #[doc(hidden)]
    pub fn storage_adapter(
        &self,
    ) -> crate::storage_adapter::StorageAdapter<StorageSession<StorageImpl>> {
        self.engine.storage()
    }

    #[cfg(not(feature = "storage-benches"))]
    pub(crate) fn storage_adapter(
        &self,
    ) -> crate::storage_adapter::StorageAdapter<StorageSession<StorageImpl>> {
        self.engine.storage()
    }

    pub(crate) fn sync_mode_state(&self) -> crate::sync::SyncModeState {
        self.engine.sync_mode()
    }

    pub(crate) fn notify_observers_for_sync(&self) {
        self.engine.notify_observers();
    }

    pub(crate) async fn repository_default_branch_id_for_sync(
        &self,
        read: &(impl crate::storage_adapter::StorageAdapterRead + ?Sized),
    ) -> Result<String, LixError> {
        self.engine.load_repository_default_branch_id(read).await
    }

    /// Starts configuring another independent session for this repository.
    ///
    /// Await the returned builder directly, or call
    /// [`OpenAnotherSessionBuilder::with_account`] first. The new session
    /// starts on this handle's current branch and otherwise inherits its
    /// account.
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), lix::LixError> {
    /// let lix = lix::open_lix().await?;
    /// let collaborator = lix.open_another_session().await?;
    /// # collaborator.close().await?;
    /// # lix.close().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn open_another_session(&self) -> OpenAnotherSessionBuilder<'_, StorageImpl> {
        OpenAnotherSessionBuilder {
            lix: self,
            account_id: None,
            branch_id: None,
        }
    }

    async fn open_another_session_inner(
        &self,
        account_id: Option<String>,
        branch_id: Option<String>,
    ) -> Result<Self, LixError> {
        if self.session.is_closed() {
            return Err(LixError::new(
                LixError::CODE_CLOSED,
                "cannot open another session from a closed Lix handle",
            ));
        }
        let active_branch_id = match branch_id {
            Some(branch_id) => branch_id,
            None => Arc::clone(&self.session).active_branch_id_owned().await?,
        };
        let active_account_id = account_id.unwrap_or_else(|| self.active_account_id().to_owned());
        if matches!(
            self.engine.sync_mode().role(),
            crate::sync::SyncRole::Replica | crate::sync::SyncRole::PartialReplica
        ) && active_account_id != self.active_account_id()
        {
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "connected sessions cannot override the authority-authenticated account",
            ));
        }
        let mut opened = self
            .open_internal_session(active_branch_id.clone(), active_account_id)
            .await?
            .with_session_telemetry(self.telemetry().cloned())?;
        opened.sync_lease = self.sync_lease.as_ref().map(|lease| lease.child());

        Ok(opened)
    }

    /// Storage-adapter integration: open a backing-storage session sharing this
    /// repository's replica sync admission and wakeups without retaining its storage wrapper.
    /// This integration hook supports standalone and connected-replica repositories;
    /// it does not grant authority-server write admission.
    /// The adapter must stop this session before stopping the owning sync runtime.
    #[doc(hidden)]
    pub async fn open_storage_session<Backing>(
        &self,
        storage: Backing,
    ) -> Result<Lix<Backing>, LixError>
    where
        Backing: Storage + Clone + Send + Sync + 'static,
    {
        let operation = self.open_storage_session_inner(storage);
        #[cfg(not(target_family = "wasm"))]
        {
            // SAFETY: like open_another_session, this operation borrows only a
            // Send + Sync Lix and owns Send backing storage. Storage read/write
            // handles satisfy the Storage contract; retained scan-scope and
            // admission references point to Sync state. The raw Memory future
            // and borrowing-adapter obligations are checked in partial tests.
            unsafe { crate::session::AssumeSendFuture::new(operation) }.await
        }
        #[cfg(target_family = "wasm")]
        {
            operation.await
        }
    }

    async fn open_storage_session_inner<Backing>(
        &self,
        storage: Backing,
    ) -> Result<Lix<Backing>, LixError>
    where
        Backing: Storage + Clone + Send + Sync + 'static,
    {
        if self.session.is_closed() {
            return Err(LixError::new(
                LixError::CODE_CLOSED,
                "cannot open a storage session from a closed handle",
            ));
        }
        if self.engine.sync_mode().role() == crate::sync::SyncRole::PartialReplica {
            return partial::open_partial_storage_session(self, storage).await;
        }
        let mut opened = open_lix()
            .with_storage(storage)
            .with_durability(self.engine.storage().durability())
            .await?;
        if opened.lix_id() != self.lix_id() {
            opened.close().await?;
            return Err(LixError::new(
                LixError::CODE_INVALID_PARAM,
                "storage session must use the same repository",
            ));
        }
        let engine = Arc::get_mut(&mut opened.engine).ok_or_else(|| {
            LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "new storage session engine is shared",
            )
        })?;
        engine.inherit_storage_runtime(&self.engine);
        engine.inherit_sync_mode(self.engine.sync_mode());
        let account = if matches!(
            self.engine.sync_mode().role(),
            crate::sync::SyncRole::Replica | crate::sync::SyncRole::PartialReplica
        ) {
            self.active_account_id()
        } else {
            crate::SYSTEM_ACCOUNT_ID
        };
        let session = opened
            .engine
            .open_session_at_with_account(self.active_branch_id().await?, account.to_owned())
            .await?;
        let previous = std::mem::replace(&mut opened.session, Arc::new(session));
        previous.close().await?;
        opened.sync_demand_tx = self.sync_demand_tx.clone();
        opened.server = self.server.clone();
        Ok(opened)
    }

    pub(crate) async fn open_internal_session(
        &self,
        active_branch_id: impl Into<String>,
        active_account_id: impl Into<String>,
    ) -> Result<Self, LixError> {
        let active_branch_id = active_branch_id.into();
        let active_account_id = active_account_id.into();
        // Admission reads can expire while another session or background sync
        // commits. Restart only this read/validation unit; the child handle and
        // sync lease are published once, after it succeeds.
        let session = retry_expired_read(|| async {
            if self.session.is_closed() {
                return Err(LixError::new(
                    LixError::CODE_CLOSED,
                    "cannot open a session from a closed Lix handle",
                ));
            }
            // Partial session admission owns its selected/GLOBAL scope policy.
            // Do not probe an unadmitted branch first: resolving absent controls
            // can require cold descriptor objects and hide the scope error.
            if self.engine.sync_mode().role() != crate::sync::SyncRole::PartialReplica
                && self
                    .engine
                    .load_branch_head_commit_id(&active_branch_id)
                    .await?
                    .is_none()
            {
                return Err(LixError::branch_not_found(
                    active_branch_id.clone(),
                    "open_another_session",
                    "target",
                ));
            }
            self.engine
                .open_session_at_with_account(active_branch_id.clone(), active_account_id.clone())
                .await
        })
        .await?;
        Ok(Self {
            engine: self.engine.clone(),
            session: Arc::new(session),
            transaction_lifecycle: Arc::default(),
            primary_switch_gate: None,
            sync_lease: None,
            sync_demand_tx: self.sync_demand_tx.clone(),
            server: self.server.clone(),
            open_report: Arc::clone(&self.open_report),
        })
    }

    /// Returns the immutable report produced while opening this repository.
    pub fn open_report(&self) -> &OpenReport {
        &self.open_report
    }

    /// Executes one PostgreSQL-dialect SQL statement against this Lix session.
    ///
    /// Lix supports a PostgreSQL-dialect subset executed by DataFusion.
    /// Positional placeholders use `$1`, `$2`, and so on. Parsing PostgreSQL
    /// syntax does not imply support for every PostgreSQL statement or runtime
    /// feature. Use `information_schema` for catalog inspection. Lix owns
    /// transaction boundaries for each statement.
    /// While a transaction is active, call `execute()` on the transaction
    /// handle instead.
    ///
    /// `sql` must be a single statement. To run several statements atomically,
    /// pass an array of statements to [`Self::execute_batch`]. Do not concatenate
    /// statements into one script string.
    pub fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [Value],
    ) -> ExecuteBuilder<'a, StorageImpl> {
        ExecuteBuilder {
            lix: self,
            sql: sql.to_string(),
            params: params.to_vec(),
            options: ExecuteOptions::default(),
        }
    }

    /// Classifies one SQL execution for a caller that owns its transport
    /// lifecycle.
    ///
    /// The result comes from Lix's parsed and bound statement route. It is
    /// safe for a transport to abandon [`ExecutionDisposition::CancellableRead`]
    /// work; [`ExecutionDisposition::Durable`] work must be allowed to finish.
    pub(crate) fn execution_disposition(
        &self,
        sql: &str,
    ) -> Result<ExecutionDisposition, LixError> {
        self.session.execution_disposition(sql)
    }

    /// Upserts one file's bytes by full logical path without parsing SQL.
    ///
    /// This structured path is intended for file transfer clients. It uses the
    /// engine's filesystem fast-write path and retains normal plugin and
    /// transaction behavior.
    pub(crate) async fn upsert_file_content(
        &self,
        path: impl Into<String>,
        content: impl Into<Blob>,
    ) -> Result<u64, LixError> {
        self.session
            .upsert_file_content(path.into(), content.into())
            .await
    }

    /// Sends one sequential resumable part through the same logical file
    /// upsert. The final part atomically publishes the ordinary file version.
    pub(crate) async fn upsert_file_content_part(
        &self,
        upload_id: impl Into<String>,
        path: impl Into<String>,
        start: u64,
        total_size: u64,
        content: impl Into<Blob>,
    ) -> Result<lix::FileUploadProgress, LixError> {
        self.session
            .upsert_file_content_part(
                upload_id.into(),
                path.into(),
                start,
                total_size,
                content.into(),
            )
            .await
    }

    /// Upserts a non-empty batch of files atomically without parsing SQL for
    /// normal filesystem layouts.
    ///
    /// Each item is a full logical file path and its bytes. Paths must be
    /// unique within the batch. This direct-only API rejects exceptional
    /// layouts that its path index cannot route unambiguously.
    pub(crate) async fn upsert_file_content_batch(
        &self,
        writes: Vec<(String, Blob)>,
    ) -> Result<u64, LixError> {
        self.session.upsert_file_content_batch(writes).await
    }

    /// Read exact retained blob identity through the ordinary authenticated chunk
    /// demand path, without rendering plugin-backed current file state.
    pub(crate) async fn read_recovery_blob(
        &self,
        hash: &str,
        expected_size: u64,
    ) -> Result<Option<Blob>, LixError> {
        let id = crate::binary_cas::BlobId::from_hex(hash)?;
        self.retry_sync_demands(|| async {
            let adapter = self.storage_adapter();
            let read = adapter
                .begin_read(crate::storage_adapter::StorageReadOptions::default())
                .await?;
            let metadata = crate::binary_cas::load_metadata_many(&read, &[id])
                .await?
                .into_vec()
                .into_iter()
                .next()
                .flatten();
            if metadata.is_none_or(|metadata| metadata.size_bytes != expected_size) {
                return Ok(None);
            }
            Ok(crate::binary_cas::load_bytes_many(&read, &[id])
                .await?
                .into_vec()
                .into_iter()
                .next()
                .flatten()
                .map(Blob::from))
        })
        .await
    }

    /// Reads one file's bytes by full logical path without parsing SQL.
    ///
    /// The returned `None` means the file is absent; `Some` with an empty
    /// [`Blob`] means a present empty file.
    pub(crate) async fn read_file_content(
        &self,
        path: impl Into<String>,
        range: Option<std::ops::Range<u64>>,
    ) -> Result<Option<lix::FileRead>, LixError> {
        let path = path.into();
        self.retry_replica_read(ExecutionDisposition::CancellableRead, || {
            self.retry_sync_demands(|| self.session.read_file_content(path.clone(), range.clone()))
        })
        .await
    }

    pub(crate) fn execute_with_idempotency_and_options_and_metadata(
        self: Arc<Self>,
        sql: String,
        params: Vec<Value>,
        options: ExecuteOptions,
        metadata: ExecuteStatementMetadata,
        idempotency: Option<ExecuteIdempotency>,
    ) -> Pin<Box<dyn Future<Output = Result<ExecuteResult, LixError>> + Send + 'static>> {
        if !matches!(
            self.engine.sync_mode().role(),
            crate::sync::SyncRole::Replica | crate::sync::SyncRole::PartialReplica
        ) {
            return Box::pin(
                Arc::clone(&self.session).execute_with_idempotency_and_options_and_metadata(
                    sql,
                    params,
                    options,
                    metadata,
                    idempotency,
                ),
            );
        }
        // SAFETY: the retry future owns the Lix handle and every request
        // value. Reusing the same idempotency identity on each attempt is the
        // required contract: a pre-commit history demand has no receipt, while
        // an already committed attempt replays its durable receipt.
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                let route = self.session.execution_disposition(&sql)?;
                self.retry_replica_read(route, || {
                    self.retry_sync_demands(|| {
                        Arc::clone(&self.session).execute_with_idempotency_and_options_and_metadata(
                            sql.clone(),
                            params.clone(),
                            options.clone(),
                            metadata.clone(),
                            idempotency.clone(),
                        )
                    })
                })
                .await
            })
        })
    }

    /// Executes statements sequentially against one atomic snapshot.
    /// Pure reads share one read snapshot; batches containing writes retain
    /// transactional read-after-write and rollback semantics.
    ///
    /// Each entry is one statement plus its own parameters. Callers assemble
    /// the array; Lix does not parse a multi-statement script on their behalf.
    pub fn execute_batch<'a>(
        &'a self,
        statements: &'a [ExecuteBatchStatement],
    ) -> ExecuteBatchBuilder<'a, StorageImpl> {
        ExecuteBatchBuilder {
            lix: self,
            statements: statements.to_vec(),
            options: ExecuteOptions::default(),
        }
    }

    /// Executes read statements against one coherent storage snapshot and
    /// returns the snapshot metadata required by official storage adapters.
    #[doc(hidden)]
    pub fn execute_coherent_read_batch(
        &self,
        statements: &[(&str, &[Value])],
    ) -> impl Future<Output = Result<CoherentReadBatch, LixError>> + Send + 'static {
        let statements = Arc::new(
            statements
                .iter()
                .map(|(sql, params)| ((*sql).to_owned(), (*params).to_vec()))
                .collect::<Vec<_>>(),
        );
        let routed = statements
            .iter()
            .map(|(sql, params)| ExecuteBatchStatement {
                sql: sql.clone(),
                params: params.clone(),
                label: None,
            })
            .collect::<Vec<_>>();
        let route = self.session.execute_batch_disposition(&routed);
        let session = Arc::clone(&self.session);
        let demand_tx = self.sync_demand_tx.clone();
        // SAFETY: the future owns its local session and statement values, as
        // do the ordinary execute builders. Each retry opens a complete new
        // coherent snapshot after hydration releases the old read scope.
        unsafe {
            crate::session::AssumeSendFuture::new(async move {
                if route? == ExecutionDisposition::Durable {
                    return Err(LixError::new(
                        LixError::CODE_INVALID_PARAM,
                        "execute_coherent_read_batch only accepts read statements without durable runtime functions",
                    ));
                }
                crate::common::with_read_deadline(async {
                    let mut retry = crate::sync::SyncDemandRetry::default();
                    loop {
                        let result = retry_expired_read(|| {
                            Arc::clone(&session)
                                .execute_coherent_read_batch_owned(Arc::clone(&statements))
                        })
                        .await;
                        match result {
                            Ok(result) => return Ok(result),
                            Err(error) => {
                                retry.hydrate_for_retry(demand_tx.as_ref(), error).await?
                            }
                        }
                    }
                })
                .await
            })
        }
    }

    /// Classifies an atomic SQL batch for a caller that owns its transport
    /// lifecycle.
    pub(crate) fn execute_batch_disposition(
        &self,
        statements: &[ExecuteBatchStatement],
    ) -> Result<ExecutionDisposition, LixError> {
        self.session.execute_batch_disposition(statements)
    }

    pub(crate) fn execute_batch_with_idempotency_and_options_and_metadata(
        self: Arc<Self>,
        statements: Vec<ExecuteBatchStatement>,
        options: ExecuteOptions,
        statement_metadata: Vec<ExecuteStatementMetadata>,
        idempotency: Option<ExecuteIdempotency>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<ExecuteResult>, LixError>> + Send + 'static>> {
        if !matches!(
            self.engine.sync_mode().role(),
            crate::sync::SyncRole::Replica | crate::sync::SyncRole::PartialReplica
        ) {
            return Box::pin(
                Arc::clone(&self.session).execute_batch_with_idempotency_and_options_and_metadata(
                    statements,
                    options,
                    statement_metadata,
                    idempotency,
                ),
            );
        }
        // Preserve the exact request identity across lazy-history retries so a
        // commit-outcome-unknown response can still be retried safely with the
        // caller's original key.
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                let route = self.session.execute_batch_disposition(&statements)?;
                self.retry_replica_read(route, || {
                    self.retry_sync_demands(|| {
                        Arc::clone(&self.session)
                            .execute_batch_with_idempotency_and_options_and_metadata(
                                statements.clone(),
                                options.clone(),
                                statement_metadata.clone(),
                                idempotency.clone(),
                            )
                    })
                })
                .await
            })
        })
    }

    #[cfg(test)]
    pub(crate) fn set_sync_demand_sender_for_test(
        &mut self,
        sender: tokio::sync::mpsc::Sender<crate::sync::SyncDemand>,
    ) {
        self.sync_demand_tx = Some(sender);
    }

    #[cfg(test)]
    pub(crate) fn clear_sync_demand_sender_for_test(&mut self) {
        self.sync_demand_tx = None;
    }

    pub fn observe(
        &self,
        sql: &str,
        params: &[Value],
    ) -> Result<ObserveEvents<StorageImpl>, LixError> {
        self.session
            .observe(sql, params)
            .map(|events| ObserveEvents {
                events: events.with_sync_demand_sender(self.sync_demand_tx.clone()),
            })
    }

    /// Starts an atomic transaction on the current branch and account.
    ///
    /// The transaction owns an independent context. Reads, observations, and
    /// writes through this handle remain outside it, and later branch switches
    /// do not retarget it. Finish or drop the transaction before closing this
    /// handle (or one of its clones).
    ///
    /// Partial replicas fetch missing immutable inputs while each SQL call
    /// awaits, without advancing this transaction's snapshot. If the authority
    /// no longer retains that snapshot, the operation returns a transaction
    /// conflict; previously returned reads are never silently rebased.
    pub async fn begin_transaction(&self) -> Result<LixTransaction<StorageImpl>, LixError> {
        // Reserve before awaiting admission so close also notices an opening
        // transaction. The mutex coordinates only begin/close, never SQL work.
        let lifecycle = PublicTransactionLease::acquire(Arc::clone(&self.transaction_lifecycle))?;
        let _admission = self.transaction_lifecycle.admission.lock().await;
        self.session.ensure_open()?;

        // Each attempt opens an adapter-specific session and transaction. Keep
        // that nested future on the heap so retry orchestration does not embed
        // its full storage-read state in every caller's stack frame.
        let inner = self
            .retry_sync_demands(|| {
                Box::pin(async {
                    let branch_id = Arc::clone(&self.session).active_branch_id_owned().await?;
                    let session = Arc::new(
                        self.engine
                            .open_session_at_with_account(
                                branch_id,
                                self.active_account_id().to_owned(),
                            )
                            .await?
                            .with_file_views_from(&self.session),
                    );
                    Ok(session
                        .begin_transaction()
                        .await?
                        .with_sync_demand_sender(self.sync_demand_tx.clone()))
                })
            })
            .await?;
        Ok(LixTransaction {
            _lifecycle: lifecycle,
            inner: Some(inner),
        })
    }

    pub fn active_branch_id(
        &self,
    ) -> impl Future<Output = Result<String, LixError>> + Send + 'static {
        Arc::clone(&self.session).active_branch_id_owned()
    }

    pub fn active_account_id(&self) -> &str {
        self.session.active_account_id()
    }

    /// Repository identity stored as `lix_key_value.lix_id`.
    pub fn lix_id(&self) -> &str {
        self.engine.lix_id()
    }

    /// Binding integration: replace the sink before exposing a new session.
    #[doc(hidden)]
    pub fn with_session_telemetry(
        mut self,
        telemetry: Option<Arc<dyn TelemetrySink>>,
    ) -> Result<Self, LixError> {
        let session = Arc::get_mut(&mut self.session).ok_or_else(|| {
            LixError::new(
                LixError::CODE_INVALID_PARAM,
                "session telemetry must be configured before sharing the session",
            )
        })?;
        session.set_telemetry(telemetry);
        Ok(self)
    }

    /// Telemetry sink for this session, if the host attached one.
    pub fn telemetry(&self) -> Option<&Arc<dyn TelemetrySink>> {
        self.session.telemetry()
    }

    /// Records that this handle's session has bound to the repository.
    ///
    /// In-process [`open_lix`] and protocol handshake session creation call
    /// this once. Hosts that mint a session against an already-open runtime
    /// should call the same helper instead of opening another engine.
    pub fn bind_session(&self) {
        let Ok(branch_id) = self.session.bound_branch_id() else {
            return;
        };
        crate::telemetry::bind_session(
            self.telemetry(),
            self.lix_id(),
            &branch_id,
            Some(self.active_account_id()),
        );
    }

    /// Creates an active global account if it does not exist. Existing mutable
    /// account fields are deliberately left unchanged.
    pub(crate) async fn ensure_account(
        &self,
        id: &str,
        name: &str,
        kind: &str,
    ) -> Result<(), LixError> {
        self.engine.ensure_account(id, name, kind).await
    }

    pub async fn create_branch(
        &self,
        options: CreateBranchOptions,
    ) -> Result<CreateBranchReceipt, LixError> {
        self.retry_sync_demands(|| self.session.create_branch(options.clone()))
            .await
    }

    /// Crate-internal test/support sugar. Public callers use the canonical SQL
    /// `lix_create_checkpoint(...)` function.
    pub(crate) async fn create_checkpoint(
        &self,
    ) -> Result<crate::session::CreateCheckpointReceipt, LixError> {
        self.session.create_checkpoint().await
    }

    /// Reverses the latest undoable tracked commit on this handle's active branch.
    pub async fn undo(&self) -> Result<UndoReceipt, LixError> {
        self.retry_sync_demands(|| self.session.undo()).await
    }

    /// Replays the latest tracked commit abandoned by undo on this handle's active branch.
    pub async fn redo(&self) -> Result<RedoReceipt, LixError> {
        self.retry_sync_demands(|| self.session.redo()).await
    }

    pub fn switch_branch(
        &self,
        options: SwitchBranchOptions,
    ) -> impl Future<Output = Result<SwitchBranchReceipt, LixError>> + Send + '_ {
        // SAFETY: the future borrows a Send + Sync Lix handle and owns its
        // switch options. The compiler cannot prove the nested switch SQL
        // future is Send for every storage read lifetime.
        unsafe {
            crate::session::AssumeSendFuture::new(async move {
                let _primary_switch_guard = match &self.primary_switch_gate {
                    Some(gate) => Some(gate.clone().lock_owned().await),
                    None => None,
                };

                if let Some(state) = self.engine.sync_mode().partial_admission() {
                    if options.branch_id != state.descriptor().selected_branch.branch_id
                        && options.branch_id != state.descriptor().global_branch.branch_id
                    {
                        let server = self.server.clone().ok_or_else(|| {
                            LixError::new(
                                "LIX_PARTIAL_REPLICA_OFFLINE",
                                "admitting another branch requires its authority",
                            )
                        })?;
                        let target = options.branch_id.clone();
                        let completion = self
                            .session
                            .partial_switch_completion(target.clone(), _primary_switch_guard)
                            .await?;
                        crate::sync::switch_existing_branch(
                            self.engine.clone(),
                            server,
                            completion,
                            self.sync_demand_tx.clone(),
                        )
                        .await?;
                        return Ok(SwitchBranchReceipt { branch_id: target });
                    }
                }
                self.retry_sync_demands(|| self.session.switch_branch(options.clone()))
                    .await
            })
        }
    }

    pub async fn merge_branch(
        &self,
        options: MergeBranchOptions,
    ) -> Result<MergeBranchReceipt, LixError> {
        self.retry_sync_demands(|| self.session.merge_branch(options.clone()))
            .await
    }

    pub async fn merge_branch_preview(
        &self,
        options: MergeBranchPreviewOptions,
    ) -> Result<MergeBranchPreview, LixError> {
        self.retry_sync_demands(|| self.session.merge_branch_preview(options.clone()))
            .await
    }

    /// Restarts the complete local serving attempt when a certified replica
    /// publication races its storage snapshot. Session reads already retry
    /// individual coherent scopes; this outer boundary covers expiry between
    /// sync-demand hydration and the final local read. Only classified reads
    /// enter it, so retrying cannot duplicate a mutation.
    async fn retry_replica_read<T, Operation, OperationFuture>(
        &self,
        route: ExecutionDisposition,
        mut operation: Operation,
    ) -> Result<T, LixError>
    where
        Operation: FnMut() -> OperationFuture,
        OperationFuture: Future<Output = Result<T, LixError>>,
    {
        if route == ExecutionDisposition::Durable {
            return operation().await;
        }
        // Includes typed input preparation/hydration between complete local
        // attempts. The deadline never wraps a durable operation.
        crate::common::with_read_deadline(async {
            if matches!(
                self.engine.sync_mode().role(),
                crate::sync::SyncRole::Replica | crate::sync::SyncRole::PartialReplica
            ) {
                retry_expired_read(operation).await
            } else {
                operation().await
            }
        })
        .await
    }

    pub async fn close(&self) -> Result<(), LixError> {
        // A begin awaiting network I/O must not make close wait for admission.
        if self.transaction_lifecycle.active.load(Ordering::Acquire) > 0 {
            return Err(LixError::new(
                "LIX_INVALID_TRANSACTION_STATE",
                "cannot close Lix while an explicit transaction is active",
            ));
        }
        let _admission = self.transaction_lifecycle.admission.lock().await;
        if self.transaction_lifecycle.active.load(Ordering::Acquire) > 0 {
            return Err(LixError::new(
                "LIX_INVALID_TRANSACTION_STATE",
                "cannot close Lix while an explicit transaction is active",
            ));
        }
        // Check the independent transactions before mutating any session or
        // remote lifecycle, including their shared publication worker.
        self.session.close().await?;

        if let Some(lease) = &self.sync_lease {
            lease.release().await?;
        }
        Ok(())
    }
    pub(crate) fn set_sync_role(&self, role: crate::sync::SyncRole) -> Result<(), LixError> {
        if role == crate::sync::SyncRole::Replica {
            self.engine.storage().admit_sync_replica_writer();
        }
        self.engine.sync_mode().set_role(role);
        Ok(())
    }

    pub(crate) fn set_sync_replica_remote_id(&self, remote_id: &str) -> Result<(), LixError> {
        crate::sync::validate_sync_remote_id(remote_id)?;
        self.engine
            .sync_mode()
            .set_replica_remote_id(Arc::<str>::from(remote_id));
        Ok(())
    }

    pub(crate) async fn align_primary_account_for_sync(
        &mut self,
        active_account_id: &str,
    ) -> Result<(), LixError> {
        if self.active_account_id() == active_account_id {
            return Ok(());
        }
        let replacement = self
            .engine
            .open_session_with_account(active_account_id.to_owned())
            .await?;
        let previous = std::mem::replace(&mut self.session, Arc::new(replacement));
        previous.close().await
    }

    pub(crate) fn align_repository_identity_for_sync(
        &mut self,
        lix_id: String,
    ) -> Result<(), LixError> {
        let engine = Arc::get_mut(&mut self.engine).ok_or_else(|| {
            LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "sync bootstrap cloned the engine before repository identity alignment",
            )
        })?;
        engine.set_lix_id_for_sync(lix_id);
        Ok(())
    }

    pub(crate) async fn lock_collaboration_writes(&self) -> tokio::sync::OwnedMutexGuard<()> {
        self.engine.collaboration_write_gate().lock_owned().await
    }
}

#[expect(missing_debug_implementations)]
pub struct LixTransaction<StorageImpl = Memory>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    inner: Option<lix::SessionTransaction<StorageSession<StorageImpl>>>,
    _lifecycle: PublicTransactionLease,
}

/// Configures one SQL statement inside an explicit transaction.
#[expect(missing_debug_implementations)]
pub struct TransactionExecuteBuilder<'a, StorageImpl = Memory>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    transaction: &'a mut LixTransaction<StorageImpl>,
    sql: &'a str,
    params: &'a [Value],
    options: ExecuteOptions,
}

impl<StorageImpl> TransactionExecuteBuilder<'_, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    /// Identifies the caller-defined origin of this execution.
    pub fn with_origin_key(mut self, origin_key: impl Into<String>) -> Self {
        self.options.origin_key = Some(origin_key.into());
        self
    }
}

impl<'a, StorageImpl> IntoFuture for TransactionExecuteBuilder<'a, StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    type Output = Result<ExecuteResult, LixError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(unsafe {
            crate::session::AssumeSendFuture::new(async move {
                {
                    self.transaction
                        .inner
                        .as_mut()
                        .ok_or_else(closed_transaction_error)?
                        .execute_with_options(
                            self.sql.to_owned(),
                            self.params.to_vec(),
                            self.options,
                        )
                        .await
                }
            })
        })
    }
}

impl<StorageImpl> LixTransaction<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    /// Executes one SQL statement inside this transaction.
    ///
    /// Writes are staged until `commit()`. Reads use the transaction overlay,
    /// so they can observe writes staged by earlier calls on this handle.
    pub fn execute<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> TransactionExecuteBuilder<'a, StorageImpl> {
        TransactionExecuteBuilder {
            transaction: self,
            sql,
            params,
            options: ExecuteOptions::default(),
        }
    }

    /// Executes one SQL statement inside this transaction with explicit options.
    ///
    /// Protocol handlers use this instead of the builder so they stay on the
    /// public transaction API without a raw `transaction.execute(` call site.
    pub(crate) fn execute_with_options(
        &mut self,
        sql: String,
        params: Vec<Value>,
        options: ExecuteOptions,
    ) -> impl Future<Output = Result<ExecuteResult, LixError>> + Send + '_ {
        unsafe {
            crate::session::AssumeSendFuture::new(async move {
                {
                    self.inner
                        .as_mut()
                        .ok_or_else(closed_transaction_error)?
                        .execute_with_options(sql, params, options)
                        .await
                }
            })
        }
    }

    #[cfg(test)]
    pub(crate) async fn stage_test_row(
        &mut self,
        row: TransactionWriteRow,
    ) -> Result<(), LixError> {
        self.inner
            .as_mut()
            .ok_or_else(closed_transaction_error)?
            .stage_test_row(row)
            .await
    }

    pub async fn commit(mut self) -> Result<crate::CommitReceipt, LixError> {
        self.inner
            .take()
            .ok_or_else(closed_transaction_error)?
            .commit()
            .await
    }

    pub async fn rollback(mut self) -> Result<(), LixError> {
        self.inner
            .take()
            .ok_or_else(closed_transaction_error)?
            .rollback()
            .await
    }
}

fn closed_transaction_error() -> LixError {
    LixError::new(
        LixError::CODE_INVALID_SESSION_STATE,
        "Lix transaction is closed",
    )
}

async fn open_or_initialize_engine_with_adapter<StorageImpl>(
    adapter: crate::storage_adapter::StorageAdapter<StorageImpl>,
    wasm_runtime: Option<Arc<dyn WasmRuntime>>,
    telemetry: Option<Arc<dyn TelemetrySink>>,
    plugin_resource_limits: Option<(u64, usize)>,
    initial_main_branch_id: Option<&str>,
) -> Result<(Engine<StorageImpl>, bool), LixError>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    match new_engine(
        adapter.clone(),
        wasm_runtime.clone(),
        telemetry.clone(),
        plugin_resource_limits,
    )
    .await
    {
        Ok(engine) => Ok((engine, false)),
        Err(error) if error.code == "LIX_ERROR_NOT_INITIALIZED" => {
            let initialized = match Engine::initialize_with_adapter(
                adapter.clone(),
                initial_main_branch_id,
            )
            .await
            {
                Ok(_) => true,
                // Another opener can publish the seed after our empty-state
                // check. Admit that winner below; never replay initialization.
                Err(error)
                    if error.code == "LIX_ERROR_ALREADY_INITIALIZED"
                        || error.code == LixError::CODE_TRANSACTION_CONFLICT =>
                {
                    false
                }
                Err(error) => return Err(error),
            };
            new_engine(adapter, wasm_runtime, telemetry, plugin_resource_limits)
                .await
                .map(|engine| (engine, initialized))
        }
        Err(error) => Err(error),
    }
}

pub(crate) async fn retry_expired_read<T, Operation, OperationFuture>(
    mut operation: Operation,
) -> Result<T, LixError>
where
    Operation: FnMut() -> OperationFuture,
    OperationFuture: Future<Output = Result<T, LixError>>,
{
    let mut retry = ExpiredReadRetryState::default();
    loop {
        match operation().await {
            Ok(value) => return Ok(value),
            Err(error) => {
                let Some(delay) = retry.next_delay(&error) else {
                    return Err(error);
                };
                tokio::task::yield_now().await;
                if !delay.is_zero() {
                    crate::sync::sleep(delay).await;
                }
            }
        }
    }
}

async fn new_engine<StorageImpl>(
    storage: crate::storage_adapter::StorageAdapter<StorageImpl>,
    wasm_runtime: Option<Arc<dyn WasmRuntime>>,
    telemetry: Option<Arc<dyn TelemetrySink>>,
    plugin_resource_limits: Option<(u64, usize)>,
) -> Result<Engine<StorageImpl>, LixError>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    #[cfg(feature = "default_wasm_runtime")]
    let wasm_runtime = match wasm_runtime {
        Some(wasm_runtime) => Some(wasm_runtime),
        None => Some(crate::plugin::runtime::default::runtime()?),
    };
    let mut options = EngineOptions::new();
    if let Some(wasm_runtime) = wasm_runtime {
        options = options.with_wasm_runtime(wasm_runtime);
    }
    if let Some(telemetry) = telemetry {
        options = options.with_telemetry(telemetry);
    }
    if let Some((max_memory_bytes, max_live_stores)) = plugin_resource_limits {
        options = options.with_plugin_resource_limits(max_memory_bytes, max_live_stores);
    }
    Engine::new_with_adapter(storage, options).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use lix::telemetry::{
        CallbackTelemetrySink, CompletedTelemetrySpan, TelemetrySink, TelemetrySpanDescriptor,
        TelemetrySpanEnd, TelemetrySpanHandle, TelemetrySpanStart,
    };
    use std::sync::{
        Mutex,
        atomic::{AtomicUsize, Ordering},
    };

    #[tokio::test]
    async fn storage_session_inherits_replica_admission_account_and_wakeups() {
        let storage = Memory::new();
        let source = open_lix().with_storage(storage.clone()).await.unwrap();
        source
            .set_sync_role(crate::sync::SyncRole::Replica)
            .unwrap();
        source
            .set_sync_replica_remote_id("http://localhost:8088/lix/test")
            .unwrap();
        let backing = source.open_storage_session(storage).await.unwrap();
        assert_eq!(
            backing.engine.sync_mode().role(),
            crate::sync::SyncRole::Replica
        );
        assert_eq!(backing.active_account_id(), source.active_account_id());
        assert_eq!(
            backing.active_branch_id().await.unwrap(),
            source.active_branch_id().await.unwrap()
        );
        let mut changed = source.engine.sync_mode().change_watcher();
        backing.engine.sync_mode().notify_sync_change();
        assert!(changed.has_changed().unwrap());
        changed.borrow_and_update();
        assert!(source.open_storage_session(Memory::new()).await.is_err());
        backing.close().await.unwrap();
        source.close().await.unwrap();
    }

    #[tokio::test]
    async fn opening_transaction_rejects_close_and_cancellation_releases_reservation() {
        let lix = open_lix().await.expect("open Lix");
        let admission = lix.transaction_lifecycle.admission.lock().await;
        let mut opening = Box::pin(lix.begin_transaction());
        std::future::poll_fn(|cx| {
            assert!(opening.as_mut().poll(cx).is_pending());
            std::task::Poll::Ready(())
        })
        .await;

        let mut closing = Box::pin(lix.close());
        std::future::poll_fn(|cx| {
            let std::task::Poll::Ready(Err(error)) = closing.as_mut().poll(cx) else {
                panic!("close must reject immediately while a transaction is opening");
            };
            assert_eq!(error.code, "LIX_INVALID_TRANSACTION_STATE");
            std::task::Poll::Ready(())
        })
        .await;
        drop(closing);
        lix.execute("SELECT 1", &[])
            .await
            .expect("opening reservation does not block parent SQL");

        drop(opening);
        assert_eq!(lix.transaction_lifecycle.active.load(Ordering::Acquire), 0);
        drop(admission);
        lix.begin_transaction()
            .await
            .expect("cancelled begin releases reservation")
            .rollback()
            .await
            .expect("replacement transaction rolls back");
        lix.close().await.expect("parent closes after cancellation");
    }

    #[tokio::test]
    async fn failed_transaction_begin_releases_lifecycle_reservation() {
        let lix = open_lix().await.expect("open Lix");
        lix.close().await.expect("close Lix");
        assert!(lix.begin_transaction().await.is_err());
        assert_eq!(lix.transaction_lifecycle.active.load(Ordering::Acquire), 0);
        assert!(lix.begin_transaction().await.is_err());
        assert_eq!(lix.transaction_lifecycle.active.load(Ordering::Acquire), 0);
    }

    fn opened_spans(spans: &[CompletedTelemetrySpan]) -> Vec<&CompletedTelemetrySpan> {
        spans
            .iter()
            .filter(|span| span.start.name == "lix.repository.opened")
            .collect()
    }

    fn attribute_string<'a>(span: &'a CompletedTelemetrySpan, key: &str) -> Option<&'a str> {
        span.start.attributes.iter().find_map(|attribute| {
            if attribute.key == key {
                match &attribute.value {
                    crate::telemetry::TelemetryValue::String(value) => Some(value.as_str()),
                    _ => None,
                }
            } else {
                None
            }
        })
    }

    #[cfg(not(target_family = "wasm"))]
    #[tokio::test]
    async fn server_without_storage_opens_remote_protocol_session() {
        use std::io::{Read, Write};
        let source = open_lix().await.unwrap();
        source
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('remote-snapshot', 'true'::jsonb)",
                &[],
            )
            .await
            .unwrap();
        let mut snapshot = Vec::new();
        source
            .export_snapshot()
            .write_to(&mut snapshot)
            .await
            .unwrap();
        let expected_snapshot = snapshot.clone();
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let thread = std::thread::spawn(move || {
            let (mut connection, _) = listener.accept().unwrap();
            connection
                .set_read_timeout(Some(std::time::Duration::from_secs(5)))
                .unwrap();
            let mut request = Vec::new();
            loop {
                let mut byte = [0];
                connection.read_exact(&mut byte).unwrap();
                request.push(byte[0]);
                if request.ends_with(b"\r\n\r\n") {
                    break;
                }
            }
            let request = String::from_utf8(request).unwrap();
            assert!(request.starts_with("GET /lix/v1/00000000-0000-4000-8000-000000000001/ "));
            assert!(
                request
                    .to_lowercase()
                    .contains("authorization: bearer test")
            );
            let body = serde_json::json!({
                "protocolVersion": crate::SERVER_PROTOCOL_VERSION,
                "sessionId": "remote-session", "activeBranchId": "main", "activeAccountId": "account"
            }).to_string();
            write!(connection, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body).unwrap();
            drop(connection);
            let (mut connection, _) = listener.accept().unwrap();
            connection
                .set_read_timeout(Some(std::time::Duration::from_secs(5)))
                .unwrap();
            let mut request = Vec::new();
            loop {
                let mut byte = [0];
                connection.read_exact(&mut byte).unwrap();
                request.push(byte[0]);
                if request.ends_with(b"\r\n\r\n") {
                    break;
                }
            }
            assert!(
                String::from_utf8(request)
                    .unwrap()
                    .starts_with("GET /lix/v1/00000000-0000-4000-8000-000000000001/snapshot")
            );
            write!(connection, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.lix.snapshot\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", snapshot.len()).unwrap();
            connection.write_all(&snapshot).unwrap();
        });
        let lix: RemoteLix = open_lix()
            .with_server(
                ServerOptions::new(format!(
                    "http://{address}/lix/00000000-0000-4000-8000-000000000001"
                ))
                .with_headers([("Authorization".to_owned(), "Bearer test".to_owned())]),
            )
            .await
            .expect("remote open");
        assert_eq!(lix.client.session_id().as_deref(), Some("remote-session"));
        let mut exported = Vec::new();
        lix.export_snapshot()
            .write_to(&mut exported)
            .await
            .expect("remote snapshot export");
        assert_eq!(exported, expected_snapshot);
        assert_eq!(lix.active_account_id(), "account");
        thread.join().unwrap();
    }

    #[cfg(not(target_family = "wasm"))]
    fn remote_request(
        listener: &std::net::TcpListener,
        method: &str,
        path: &str,
        session: Option<&str>,
    ) -> std::net::TcpStream {
        use std::io::Read;
        let (mut connection, _) = listener.accept().unwrap();
        connection
            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
            .unwrap();
        let mut request = Vec::new();
        loop {
            let mut byte = [0];
            connection.read_exact(&mut byte).unwrap();
            request.push(byte[0]);
            if request.ends_with(b"\r\n\r\n") {
                break;
            }
        }
        let request = String::from_utf8(request).unwrap();
        assert!(request.starts_with(&format!("{method} ")), "{request}");
        assert!(request.lines().next().unwrap().contains(path), "{request}");
        if let Some(session) = session {
            assert!(
                request
                    .to_lowercase()
                    .contains(&format!("lix-session-id: {session}\r\n")),
                "{request}"
            );
        }
        let size = request
            .lines()
            .find_map(|line| {
                line.to_lowercase()
                    .strip_prefix("content-length:")
                    .and_then(|n| n.trim().parse::<usize>().ok())
            })
            .unwrap_or(0);
        connection.read_exact(&mut vec![0; size]).unwrap();
        connection
    }

    #[cfg(not(target_family = "wasm"))]
    fn remote_response(mut connection: std::net::TcpStream, status: u16, body: serde_json::Value) {
        use std::io::Write;
        let body = if status == 204 {
            String::new()
        } else {
            body.to_string()
        };
        write!(connection, "HTTP/1.1 {status} Response\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
    }

    #[cfg(not(target_family = "wasm"))]
    fn remote_handshake(listener: &std::net::TcpListener, session: &str, child: bool) {
        let path = if child {
            "/?activeBranchId=feature"
        } else {
            "/ "
        };
        remote_response(
            remote_request(listener, "GET", path, None),
            200,
            serde_json::json!({
                "protocolVersion": crate::SERVER_PROTOCOL_VERSION,
                "sessionId": session, "activeBranchId": "feature", "activeAccountId": "account"
            }),
        );
    }

    #[cfg(not(target_family = "wasm"))]
    #[tokio::test]
    async fn remote_transactions_finish_and_close_their_dedicated_sessions() {
        for commit in [false, true] {
            for fail_finish in [false, true] {
                let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
                let address = listener.local_addr().unwrap();
                let thread = std::thread::spawn(move || {
                    remote_handshake(&listener, "parent", false);
                    remote_handshake(&listener, "child", true);
                    remote_response(
                        remote_request(&listener, "POST", "/transaction/begin ", Some("child")),
                        200,
                        serde_json::json!({ "transactionId": "transaction" }),
                    );
                    let path = if commit {
                        "/transaction/commit "
                    } else {
                        "/transaction/rollback "
                    };
                    remote_response(
                        remote_request(&listener, "POST", path, Some("child")),
                        if fail_finish { 500 } else { 204 },
                        serde_json::json!({"error": {"code": "TEST_FINISH_FAILED", "message": "finish failed"}}),
                    );
                    remote_response(
                        remote_request(&listener, "DELETE", "/session ", Some("child")),
                        204,
                        serde_json::Value::Null,
                    );
                    remote_response(
                        remote_request(&listener, "POST", "/execute ", Some("parent")),
                        200,
                        serde_json::json!({ "columns": [], "rows": [], "rowsAffected": 0 }),
                    );
                    remote_response(
                        remote_request(&listener, "DELETE", "/session ", Some("parent")),
                        204,
                        serde_json::Value::Null,
                    );
                });
                let lix = open_lix()
                    .with_server(ServerOptions::new(format!(
                        "http://{address}/lix/00000000-0000-4000-8000-000000000001"
                    )))
                    .await
                    .unwrap();
                let transaction = lix.begin_transaction().await.unwrap();
                let child = transaction.client.as_ref().unwrap();
                assert_eq!(
                    child.active_branch_id().await.unwrap(),
                    lix.active_branch_id().await.unwrap()
                );
                assert_eq!(
                    child.active_account_id().await.unwrap(),
                    lix.active_account_id()
                );
                assert_ne!(child.session_id(), lix.client.session_id());
                let result = if commit {
                    transaction.commit().await.map(|_| ())
                } else {
                    transaction.rollback().await
                };
                if fail_finish {
                    assert_eq!(result.unwrap_err().code, "TEST_FINISH_FAILED");
                } else {
                    result.unwrap();
                }
                lix.execute("SELECT 1", &[])
                    .await
                    .expect("parent remains usable after transaction finishes");
                lix.close().await.unwrap();
                thread.join().unwrap();
            }
        }
    }

    #[cfg(not(target_family = "wasm"))]
    #[tokio::test]
    async fn dropping_remote_transaction_does_not_block_parent_during_failed_session_cleanup() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (closing_tx, closing_rx) = tokio::sync::oneshot::channel();
        let (resume_tx, resume_rx) = std::sync::mpsc::channel();
        let thread = std::thread::spawn(move || {
            remote_handshake(&listener, "parent", false);
            remote_handshake(&listener, "abandoned", true);
            remote_response(
                remote_request(&listener, "POST", "/transaction/begin ", Some("abandoned")),
                200,
                serde_json::json!({ "transactionId": "abandoned-transaction" }),
            );
            let pending_close = remote_request(&listener, "DELETE", "/session ", Some("abandoned"));
            closing_tx.send(()).unwrap();
            // Keep cleanup unanswered while the same parent executes, opens another
            // transaction, and closes. No rollback request should be sent on drop.
            remote_response(
                remote_request(&listener, "POST", "/execute ", Some("parent")),
                200,
                serde_json::json!({ "columns": [], "rows": [], "rowsAffected": 0 }),
            );
            remote_handshake(&listener, "replacement", true);
            remote_response(
                remote_request(
                    &listener,
                    "POST",
                    "/transaction/begin ",
                    Some("replacement"),
                ),
                200,
                serde_json::json!({ "transactionId": "replacement-transaction" }),
            );
            remote_response(
                remote_request(
                    &listener,
                    "POST",
                    "/transaction/commit ",
                    Some("replacement"),
                ),
                204,
                serde_json::Value::Null,
            );
            remote_response(
                remote_request(&listener, "DELETE", "/session ", Some("replacement")),
                204,
                serde_json::Value::Null,
            );
            remote_response(
                remote_request(&listener, "DELETE", "/session ", Some("parent")),
                204,
                serde_json::Value::Null,
            );
            resume_rx
                .recv_timeout(std::time::Duration::from_secs(5))
                .unwrap();
            remote_response(
                pending_close,
                500,
                serde_json::json!({ "error": {"code": "TEST_CLOSE_FAILED", "message": "close failed"} }),
            );
        });
        let lix = open_lix()
            .with_server(ServerOptions::new(format!(
                "http://{address}/lix/00000000-0000-4000-8000-000000000001"
            )))
            .await
            .unwrap();
        drop(lix.begin_transaction().await.unwrap());
        closing_rx.await.unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(5), async {
            lix.execute("SELECT 1", &[])
                .await
                .expect("parent SQL during cleanup");
            lix.begin_transaction()
                .await
                .expect("parent transaction during cleanup")
                .commit()
                .await
                .unwrap();
            lix.close().await.expect("parent close during cleanup");
        })
        .await
        .expect("cleanup must not block parent operations");
        resume_tx.send(()).unwrap();
        thread.join().unwrap();
    }

    #[cfg(not(target_family = "wasm"))]
    #[tokio::test]
    async fn failed_or_cancelled_remote_transaction_begin_closes_only_its_dedicated_session() {
        for cancel in [false, true] {
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            let address = listener.local_addr().unwrap();
            let (begin_tx, begin_rx) = tokio::sync::oneshot::channel();
            let (closed_tx, closed_rx) = tokio::sync::oneshot::channel();
            let thread = std::thread::spawn(move || {
                remote_handshake(&listener, "parent", false);
                remote_handshake(&listener, "child", true);
                let begin = remote_request(&listener, "POST", "/transaction/begin ", Some("child"));
                begin_tx.send(()).unwrap();
                let pending_begin = if cancel {
                    Some(begin)
                } else {
                    remote_response(
                        begin,
                        500,
                        serde_json::json!({ "error": {"code": "TEST_BEGIN_FAILED", "message": "begin failed"} }),
                    );
                    None
                };
                remote_response(
                    remote_request(&listener, "DELETE", "/session ", Some("child")),
                    204,
                    serde_json::Value::Null,
                );
                drop(pending_begin);
                closed_tx.send(()).unwrap();
                remote_response(
                    remote_request(&listener, "POST", "/execute ", Some("parent")),
                    200,
                    serde_json::json!({ "columns": [], "rows": [], "rowsAffected": 0 }),
                );
                remote_response(
                    remote_request(&listener, "DELETE", "/session ", Some("parent")),
                    204,
                    serde_json::Value::Null,
                );
            });
            let lix = open_lix()
                .with_server(ServerOptions::new(format!(
                    "http://{address}/lix/00000000-0000-4000-8000-000000000001"
                )))
                .await
                .unwrap();
            let opening = tokio::spawn({
                let lix = lix.clone();
                async move { lix.begin_transaction().await }
            });
            tokio::time::timeout(std::time::Duration::from_secs(5), begin_rx)
                .await
                .unwrap()
                .unwrap();
            if cancel {
                opening.abort();
                assert!(opening.await.unwrap_err().is_cancelled());
            } else {
                assert_eq!(
                    opening.await.unwrap().unwrap_err().code,
                    "TEST_BEGIN_FAILED"
                );
            }
            tokio::time::timeout(std::time::Duration::from_secs(5), closed_rx)
                .await
                .unwrap()
                .unwrap();
            lix.execute("SELECT 1", &[])
                .await
                .expect("failed child begin leaves parent usable");
            lix.close().await.unwrap();
            thread.join().unwrap();
        }
    }

    #[tokio::test]
    async fn remote_open_rejects_local_configuration_before_network_access() {
        let result = open_lix()
            .with_open_progress_sink(Arc::new(CallbackOpenProgressSink::new(|_| {})))
            .with_server(ServerOptions::new(
                "https://example.invalid/lix/00000000-0000-4000-8000-000000000001",
            ))
            .await;
        let error = result.expect_err("remote open must reject local progress configuration");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
        assert!(error.message.contains("local runtime"));
    }

    #[tokio::test]
    async fn server_then_storage_selects_sync_without_initializing_invalid_destination() {
        let storage = Memory::new();
        let result = open_lix()
            .with_server(ServerOptions::new("https://example.test/not-a-lix"))
            .with_storage(storage.clone())
            .await;
        assert!(result.is_err());
        let local = open_lix().with_storage(storage).await.unwrap();
        assert!(local.open_report().initialized);
    }

    #[tokio::test]
    async fn invalid_sync_locator_is_rejected_before_storage_initialization() {
        let storage = Memory::new();
        let result = open_lix()
            .with_storage(storage.clone())
            .with_server(ServerOptions::new("https://example.test/not-a-lix"))
            .await;
        let Err(error) = result else {
            panic!("invalid sync locator must fail");
        };
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);

        let lix = open_lix()
            .with_storage(storage)
            .await
            .expect("open untouched storage");
        assert!(
            lix.open_report().initialized,
            "the rejected sync open must leave initialization to the next valid open"
        );
    }

    #[tokio::test]
    async fn child_session_telemetry_isolated_and_inherited_by_nested_sessions() {
        let root_spans = Arc::new(Mutex::new(Vec::<CompletedTelemetrySpan>::new()));
        let captured = root_spans.clone();
        let root = open_lix()
            .with_telemetry(Arc::new(CallbackTelemetrySink::new(move |span| {
                captured.lock().unwrap().push(span);
            })))
            .await
            .unwrap();
        let child_spans = Arc::new(Mutex::new(Vec::<CompletedTelemetrySpan>::new()));
        let captured = child_spans.clone();
        let child = root
            .open_another_session()
            .await
            .unwrap()
            .with_session_telemetry(Some(Arc::new(CallbackTelemetrySink::new(move |span| {
                captured.lock().unwrap().push(span);
            }))))
            .unwrap();
        let nested = child.open_another_session().await.unwrap();
        root_spans.lock().unwrap().clear();
        child_spans.lock().unwrap().clear();
        child.execute("SELECT 41", &[]).await.unwrap();
        nested.execute("SELECT 42", &[]).await.unwrap();
        assert!(!child_spans.lock().unwrap().is_empty());
        assert!(root_spans.lock().unwrap().is_empty());
        child_spans.lock().unwrap().clear();
        root.execute("SELECT 43", &[]).await.unwrap();
        assert!(!root_spans.lock().unwrap().is_empty());
        assert!(child_spans.lock().unwrap().is_empty());
        nested.close().await.unwrap();
        child.close().await.unwrap();
        root.close().await.unwrap();
    }

    #[tokio::test]
    async fn open_lix_emits_one_opened_span_when_a_sink_is_attached() {
        let spans = Arc::new(Mutex::new(Vec::<CompletedTelemetrySpan>::new()));
        let captured = Arc::clone(&spans);
        let telemetry = Arc::new(CallbackTelemetrySink::new(move |span| {
            captured.lock().expect("spans").push(span);
        }));
        let lix = open_lix()
            .with_telemetry(telemetry)
            .await
            .expect("open Lix");
        let branch_id = lix.active_branch_id().await.expect("branch");
        let reused = lix.clone();
        reused
            .execute("SELECT 1", &[])
            .await
            .expect("reuse should execute");
        let _another = lix
            .open_another_session()
            .await
            .expect("another session should open");

        let spans = spans.lock().expect("spans");
        let opened = opened_spans(&spans);
        assert_eq!(opened.len(), 1);
        assert_eq!(opened[0].start.name, "lix.repository.opened");
        assert_eq!(attribute_string(opened[0], "lix.id"), Some(lix.lix_id()));
        assert_eq!(
            attribute_string(opened[0], "lix.branch_id"),
            Some(branch_id.as_str())
        );
        assert_eq!(
            attribute_string(opened[0], "lix.account_id"),
            Some(lix.active_account_id())
        );
        assert!(
            spans.iter().any(|span| span.start.name == "lix.sql.query"),
            "SQL spans still work after an opened span"
        );
    }

    #[tokio::test]
    async fn open_lix_without_a_sink_emits_no_spans() {
        let lix = open_lix().await.expect("open Lix");
        lix.execute("SELECT 1", &[]).await.expect("execute");
        assert!(lix.telemetry().is_none());
    }

    #[tokio::test]
    async fn open_lix_owns_the_storage_session_without_changing_the_public_handle_type() {
        fn assert_public_type(_: &Lix<Memory>) {}

        let storage = Memory::new();
        let first = open_lix()
            .with_storage(storage.clone())
            .await
            .expect("open first Lix");
        assert_public_type(&first);

        assert!(matches!(
            storage
                .begin_read(crate::storage::ReadOptions::default())
                .await,
            Err(crate::storage::StorageError::Fenced)
        ));

        let second = open_lix()
            .with_storage(storage)
            .await
            .expect("a second current handle joins the active generation");
        second
            .execute("SELECT 1", &[])
            .await
            .expect("joined handle remains usable");
    }

    #[tokio::test]
    async fn disabled_opened_kind_does_no_opened_span_work() {
        struct SqlOnlySink {
            started: Mutex<Vec<&'static str>>,
        }

        impl SqlOnlySink {
            fn into_sink(self: Arc<Self>) -> Arc<dyn TelemetrySink> {
                self
            }
        }

        impl TelemetrySink for SqlOnlySink {
            fn enabled(&self, descriptor: &TelemetrySpanDescriptor) -> bool {
                descriptor.name() != "lix.repository.opened"
            }

            fn start_span(&self, start: TelemetrySpanStart) -> Box<dyn TelemetrySpanHandle> {
                assert_ne!(
                    start.name, "lix.repository.opened",
                    "disabled opened spans must not be started"
                );
                self.started.lock().expect("started").push(start.name);
                Box::new(NoopHandle(crate::telemetry::new_span_context(
                    start.parent_span_context.as_ref(),
                )))
            }
        }

        struct NoopHandle(opentelemetry::trace::SpanContext);

        impl TelemetrySpanHandle for NoopHandle {
            fn span_context(&self) -> &opentelemetry::trace::SpanContext {
                &self.0
            }

            fn enter(&self) -> Box<dyn crate::telemetry::TelemetrySpanEnterGuard + '_> {
                Box::new(())
            }

            fn finish(self: Box<Self>, _end: TelemetrySpanEnd) {}
        }

        let sink = Arc::new(SqlOnlySink {
            started: Mutex::new(Vec::new()),
        });
        let lix = open_lix()
            .with_telemetry(Arc::clone(&sink).into_sink())
            .await
            .expect("open Lix");
        lix.execute("SELECT 1", &[]).await.expect("execute");
        let started = sink.started.lock().expect("started");
        assert!(started.iter().all(|name| *name != "lix.repository.opened"));
        assert!(started.contains(&"lix.sql.query"));
    }

    #[tokio::test]
    async fn host_can_bind_an_already_open_runtime_without_opening_another_engine() {
        let spans = Arc::new(Mutex::new(Vec::<CompletedTelemetrySpan>::new()));
        let captured = Arc::clone(&spans);
        let telemetry = Arc::new(CallbackTelemetrySink::new(move |span| {
            captured.lock().expect("spans").push(span);
        }));
        let lix = open_lix()
            .with_telemetry(telemetry)
            .await
            .expect("open Lix");
        let first_id = lix.lix_id().to_owned();
        lix.bind_session();
        crate::telemetry::bind_session(
            lix.telemetry(),
            lix.lix_id(),
            &lix.active_branch_id().await.expect("branch"),
            Some(lix.active_account_id()),
        );

        let spans = spans.lock().expect("spans");
        let opened = opened_spans(&spans);
        assert_eq!(opened.len(), 3);
        assert!(
            opened
                .iter()
                .all(|span| span.start.name == "lix.repository.opened")
        );
        assert!(
            opened
                .iter()
                .all(|span| attribute_string(span, "lix.id") == Some(first_id.as_str()))
        );
    }

    #[tokio::test]
    async fn retries_distinct_sync_demands_until_the_operation_succeeds() {
        let mut lix = open_lix().await.expect("open Lix");
        let (demand_tx, mut demand_rx) = tokio::sync::mpsc::channel(4);
        lix.sync_demand_tx = Some(demand_tx);
        let responder = tokio::spawn(async move {
            for _ in 0..3 {
                demand_rx
                    .recv()
                    .await
                    .expect("demand should arrive")
                    .succeed_for_test();
            }
        });
        let attempts = AtomicUsize::new(0);
        let result = lix
            .retry_sync_demands(|| {
                let attempt = attempts.fetch_add(1, Ordering::Relaxed);
                std::future::ready(match attempt {
                    0 => Err(LixError::new(
                        "LIX_SYNC_HISTORY_REQUIRED",
                        "first history body is deferred",
                    )
                    .with_details(serde_json::json!({ "commitIds": ["first"] }))),
                    1 => Err(LixError::new(
                        "LIX_SYNC_HISTORY_REQUIRED",
                        "second history body is deferred",
                    )
                    .with_details(serde_json::json!({ "commitIds": ["second"] }))),
                    2 => Err(LixError::commit_not_found(
                        uuid::Uuid::now_v7().to_string(),
                        "walk_commit_graph",
                        "graph_node",
                    )),
                    _ => Ok("hydrated"),
                })
            })
            .await
            .expect("distinct demands should retry to success");
        assert_eq!(result, "hydrated");
        assert_eq!(attempts.load(Ordering::Relaxed), 4);
        responder.await.expect("demand responder should finish");
    }

    #[tokio::test]
    async fn replica_history_and_mixed_coherent_reads_use_local_state() {
        let lix = open_lix().await.expect("open Lix");
        lix.execute(
            "INSERT INTO lix_key_value (key, value) VALUES ('local-history', 'value')",
            &[],
        )
        .await
        .expect("seed working state");
        let checkpoint = lix.create_checkpoint().await.expect("seed checkpoint");
        lix.set_sync_role(crate::sync::SyncRole::Replica)
            .expect("mark replica");

        let params = [Value::Text(checkpoint.commit_id)];
        let sql = "SELECT id AS commit_id FROM lix_commit WHERE is_checkpoint AND id = $1";
        let local = lix
            .execute(sql, &params)
            .await
            .expect("cached history is local");
        assert_eq!(local.rows().len(), 1);
        let batch = lix
            .execute_coherent_read_batch(&[
                (
                    "SELECT value FROM lix_key_value WHERE key = 'local-history'",
                    &[],
                ),
                (sql, &params),
            ])
            .await
            .expect("current state and history share a local snapshot");
        assert_eq!(batch.results[0].rows().len(), 1);
        assert_eq!(batch.results[1].rows().len(), 1);
        assert!(batch.storage_mutation_revision.is_some());
        lix.close().await.expect("close replica");
    }

    #[tokio::test]
    async fn replica_coherent_reads_reject_mutations_before_execution() {
        let lix = open_lix().await.expect("open Lix");
        lix.set_sync_role(crate::sync::SyncRole::Replica)
            .expect("mark replica");
        for sql in [
            "INSERT INTO lix_key_value (key, value) VALUES ('read-only', 'unexpected')",
            "SELECT uuidv7()",
            "SELECT current_timestamp",
        ] {
            let error = lix
                .execute_coherent_read_batch(&[("SELECT * FROM lix_checkpoint", &[]), (sql, &[])])
                .await
                .expect_err("coherent reads cannot mutate either engine");
            assert_eq!(error.code, LixError::CODE_INVALID_PARAM, "{sql}");
        }
        lix.close().await.expect("close replica");
    }

    #[tokio::test]
    async fn replica_coherent_hot_read_without_authority_does_not_panic() {
        let lix = open_lix().await.expect("open Lix");
        lix.set_sync_role(crate::sync::SyncRole::Replica)
            .expect("mark replica");
        let batch = lix
            .execute_coherent_read_batch(&[("SELECT 1 AS value", &[])])
            .await
            .expect("a local read does not require a connected authority client");
        assert_eq!(batch.results[0].rows()[0].get::<i64>("value").unwrap(), 1);
        lix.close().await.expect("close replica");
    }

    #[tokio::test]
    async fn connected_hot_read_restarts_after_publication_snapshot_expiry() {
        let lix = open_lix().await.expect("open Lix");
        lix.set_sync_role(crate::sync::SyncRole::Replica)
            .expect("mark handle as a connected replica");
        let attempts = AtomicUsize::new(0);

        let result = lix
            .retry_replica_read(ExecutionDisposition::CancellableRead, || {
                let attempt = attempts.fetch_add(1, Ordering::Relaxed);
                std::future::ready(if attempt == 0 {
                    Err(LixError::new(
                        LixError::CODE_STORAGE_READ_EXPIRED,
                        "authority publication invalidated the serving snapshot",
                    ))
                } else {
                    Ok("certified")
                })
            })
            .await
            .expect("connected HOT reads should transparently restart");

        assert_eq!(result, "certified");
        assert_eq!(attempts.load(Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn connected_non_hot_operation_is_never_retried() {
        let lix = open_lix().await.expect("open Lix");
        lix.set_sync_role(crate::sync::SyncRole::Replica)
            .expect("mark handle as a connected replica");
        let attempts = AtomicUsize::new(0);

        let error = lix
            .retry_replica_read(ExecutionDisposition::Durable, || {
                attempts.fetch_add(1, Ordering::Relaxed);
                std::future::ready(Err::<(), _>(LixError::new(
                    LixError::CODE_STORAGE_READ_EXPIRED,
                    "mutation execution is not restartable at this boundary",
                )))
            })
            .await
            .expect_err("non-HOT operations must preserve the original error");

        assert_eq!(error.code, LixError::CODE_STORAGE_READ_EXPIRED);
        assert_eq!(attempts.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn sessions_share_one_engine_but_have_independent_lifecycles() {
        let root = open_lix().await.expect("open root Lix");
        let first = root
            .open_another_session()
            .await
            .expect("open first child session");
        let second = root
            .open_another_session()
            .await
            .expect("open second child session");

        first.close().await.expect("close first child session");
        let error = first
            .execute("SELECT 1", &[])
            .await
            .expect_err("closed child session must reject work");
        assert_eq!(error.code, LixError::CODE_CLOSED);

        second
            .execute("SELECT 2", &[])
            .await
            .expect("second child remains open");
        root.execute("SELECT 3", &[])
            .await
            .expect("root remains open");
    }

    #[tokio::test]
    async fn sessions_validate_and_retain_branch_switches() {
        let root = open_lix().await.expect("open root Lix");
        let main_branch_id = root.active_branch_id().await.expect("main branch");
        let draft = root
            .create_branch(CreateBranchOptions {
                id: Some("01920000-0000-7000-8000-000000000501".to_string()),
                name: "Pinned draft".to_string(),
                from_commit_id: None,
            })
            .await
            .expect("create draft");

        let session = root
            .open_another_session()
            .await
            .expect("open main session");
        let session_clone = session.clone();
        let receipt = session
            .switch_branch(SwitchBranchOptions {
                branch_id: draft.id.clone(),
            })
            .await
            .expect("switch session");

        assert_eq!(receipt.branch_id, draft.id);
        assert_eq!(
            session.active_branch_id().await.unwrap(),
            "01920000-0000-7000-8000-000000000501"
        );
        assert_eq!(
            session_clone.active_branch_id().await.unwrap(),
            "01920000-0000-7000-8000-000000000501"
        );
        assert_eq!(root.active_branch_id().await.unwrap(), main_branch_id);

        let error = session
            .switch_branch(SwitchBranchOptions {
                branch_id: "01920000-0000-7000-8000-000000000599".to_string(),
            })
            .await
            .expect_err("missing branch must not open");
        assert_eq!(error.code, LixError::CODE_BRANCH_NOT_FOUND);
    }

    #[tokio::test]
    async fn accounts_are_mutable_and_changes_have_one_required_account() {
        const AUTHOR_ID: &str = "01920000-0000-7000-8000-000000000601";
        const UNUSED_ID: &str = "01920000-0000-7000-8000-000000000602";
        let root = open_lix().await.expect("open root Lix");

        root.ensure_account(AUTHOR_ID, "Ada", "human")
            .await
            .expect("provision author");
        root.ensure_account(UNUSED_ID, "Unused", "human")
            .await
            .expect("provision unused account");

        let author = root
            .open_another_session()
            .with_account(AUTHOR_ID)
            .await
            .expect("open attributed session");
        assert_eq!(author.active_account_id(), AUTHOR_ID);
        let inherited = author
            .open_another_session()
            .await
            .expect("open session inheriting the author");
        assert_eq!(inherited.active_account_id(), AUTHOR_ID);
        let active = author
            .execute("SELECT lix_active_account_id() AS account_id", &[])
            .await
            .expect("read SQL active account");
        assert_eq!(
            active.rows()[0].values(),
            &[Value::Text(AUTHOR_ID.to_string())]
        );

        author
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('account-test', CAST('true' AS JSONB))",
                &[],
            )
            .await
            .expect("write attributed change");
        let attribution = author
            .execute(
                "SELECT account_id FROM lix_change WHERE schema_key = 'lix_key_value'",
                &[],
            )
            .await
            .expect("query attribution");
        assert_eq!(
            attribution
                .rows()
                .last()
                .expect("attributed key-value change")
                .values(),
            &[Value::Text(AUTHOR_ID.to_string())]
        );

        let system = root
            .open_another_session()
            .with_branch(lix::GLOBAL_BRANCH_ID)
            .with_account(lix::SYSTEM_ACCOUNT_ID)
            .await
            .expect("open system session");
        system
            .execute(
                "UPDATE lix_account SET name = 'Ada Lovelace' WHERE id = $1",
                &[Value::Text(AUTHOR_ID.to_string())],
            )
            .await
            .expect("rename account");
        let account = system
            .execute(
                "SELECT name FROM lix_account WHERE id = $1",
                &[Value::Text(AUTHOR_ID.to_string())],
            )
            .await
            .expect("read renamed account");
        assert_eq!(
            account.rows()[0].values(),
            &[Value::Text("Ada Lovelace".to_string())]
        );

        let unused = root
            .open_another_session()
            .with_account(UNUSED_ID)
            .await
            .expect("open unused account session");

        system
            .execute(
                "DELETE FROM lix_account WHERE id = $1",
                &[Value::Text(UNUSED_ID.to_string())],
            )
            .await
            .expect("delete unused account");
        let error = unused
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('deleted-account', CAST('true' AS JSONB))",
                &[],
            )
            .await
            .expect_err("deleted account must not keep writing through an open session");
        assert_eq!(error.code, "LIX_ACCOUNT_NOT_FOUND");
        let error = system
            .execute(
                "DELETE FROM lix_account WHERE id = $1",
                &[Value::Text(AUTHOR_ID.to_string())],
            )
            .await
            .expect_err("authored changes must restrict account deletion");
        assert_eq!(error.code, "LIX_FOREIGN_KEY_VIOLATION");

        system
            .execute(
                "UPDATE lix_account SET status = 'disabled' WHERE id = $1",
                &[Value::Text(AUTHOR_ID.to_string())],
            )
            .await
            .expect("disable author");
        let error = author
            .execute(
                "INSERT INTO lix_key_value (key, value) VALUES ('disabled-account', CAST('true' AS JSONB))",
                &[],
            )
            .await
            .expect_err("disabled account must not keep writing through an open session");
        assert_eq!(error.code, "LIX_ACCOUNT_DISABLED");

        let error = system
            .execute(
                "UPDATE lix_account SET status = 'disabled' WHERE id = $1",
                &[Value::Text(lix::ANONYMOUS_ACCOUNT_ID.to_string())],
            )
            .await
            .expect_err("built-in accounts must remain active");
        assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
    }

    #[tokio::test]
    async fn bootstrap_accounts_are_global_rows_inherited_by_branches() {
        const AUTHOR_ID: &str = "01920000-0000-7000-8000-0000000006a1";
        let root = open_lix().await.expect("open root Lix");

        // SELECT on the default (main) session inherits the two built-ins.
        // Before this fix those rows were staged onto main as local copies
        // (`lixcol_global = false`) that shadowed the global rows.
        let accounts = root
            .execute(
                "SELECT id, name, lixcol_global FROM lix_account ORDER BY name",
                &[],
            )
            .await
            .expect("query accounts should succeed");
        assert_eq!(
            accounts.rows().len(),
            2,
            "should see exactly two bootstrap accounts"
        );
        for row in accounts.rows() {
            assert_eq!(
                &row.values()[2],
                &Value::Boolean(true),
                "bootstrap account should have lixcol_global=true"
            );
        }

        let global = root
            .open_another_session()
            .with_branch(lix::GLOBAL_BRANCH_ID)
            .await
            .expect("global session should open");
        let home_rows = global
            .execute(
                "SELECT id, name, lixcol_global \
                 FROM lix_account \
                 WHERE id IN ($1, $2) \
                 ORDER BY name",
                &[
                    Value::Text(lix::SYSTEM_ACCOUNT_ID.to_string()),
                    Value::Text(lix::ANONYMOUS_ACCOUNT_ID.to_string()),
                ],
            )
            .await
            .expect("query home account rows should succeed");
        assert_eq!(
            home_rows.rows().len(),
            2,
            "built-in accounts live on GLOBAL_BRANCH_ID"
        );
        for row in home_rows.rows() {
            let values = row.values();
            assert_eq!(&values[2], &Value::Boolean(true));
        }

        // A later ensure_account write has the same physical/home shape.
        root.ensure_account(AUTHOR_ID, "Ada", "human")
            .await
            .expect("provision author");
        let author_rows = global
            .execute(
                "SELECT id, lixcol_global FROM lix_account WHERE id = $1",
                &[Value::Text(AUTHOR_ID.to_string())],
            )
            .await
            .expect("query ensure_account row should succeed");
        assert_eq!(author_rows.rows().len(), 1);
        assert_eq!(author_rows.rows()[0].values()[1], Value::Boolean(true));

        let draft = root
            .create_branch(CreateBranchOptions {
                id: None,
                name: "draft".to_string(),
                from_commit_id: None,
            })
            .await
            .expect("create draft branch");
        root.switch_branch(SwitchBranchOptions {
            branch_id: draft.id.clone(),
        })
        .await
        .expect("switch to draft branch");

        let draft_accounts = root
            .execute(
                "SELECT id, name, lixcol_global FROM lix_account ORDER BY name",
                &[],
            )
            .await
            .expect("query accounts on draft branch should succeed");
        assert_eq!(
            draft_accounts.rows().len(),
            3,
            "draft branch should inherit the two built-ins plus the ensure_account row"
        );
        for row in draft_accounts.rows() {
            assert_eq!(
                &row.values()[2],
                &Value::Boolean(true),
                "inherited account should still have lixcol_global=true on draft"
            );
        }
    }
}

/// See `session::execute::assume_send_future_proofs`.
#[cfg(test)]
mod assume_send_future_proofs {
    use super::*;

    fn is_send<T: Send>(_: &T) {}

    // handle.rs -- OpenLixBuilder::into_future
    #[allow(dead_code)]
    fn open_lix_inner_is_send(
        storage: StorageSession<Memory>,
        wasm_runtime: Option<Arc<dyn WasmRuntime>>,
        telemetry: Option<Arc<dyn TelemetrySink>>,
    ) {
        is_send(&open_lix_inner(
            storage,
            wasm_runtime,
            telemetry,
            None,
            Arc::new(RetainingOpenProgressSink::new(None)),
            Durability::default(),
        ));
    }

    // handle.rs -- Lix::switch_branch (body mirrored verbatim)
    #[allow(dead_code)]
    fn switch_branch_body_is_send(lix: &Lix<Memory>, options: SwitchBranchOptions) {
        is_send(&async move {
            let _primary_switch_guard = match &lix.primary_switch_gate {
                Some(gate) => Some(gate.lock().await),
                None => None,
            };
            lix.session.switch_branch(options).await
        });
    }

    #[allow(dead_code)]
    fn lix_handle_is_send_for_every_storage<S>()
    where
        S: Storage + Clone + Send + Sync + 'static,
    {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}
        assert_send::<Lix<S>>();
        assert_sync::<Lix<S>>();
    }
}

impl<S: Storage + Clone + Send + Sync + 'static> Lix<S> {
    /// Atomic recovery publication: branch creation, restored rows and local
    /// idempotency receipt either all commit or none do.
    pub(crate) async fn restore_replica_rows_atomic(
        &self,
        branch_id: &str,
        name: &str,
        recovery_rows: &[crate::sync::ReplicaRecoveryRow],
        file_content: Vec<crate::transaction_types::TransactionFileContent>,
        receipt_key: &str,
        receipt: serde_json::Value,
    ) -> Result<(), LixError> {
        use crate::branch::{
            BranchHeadWrite, BranchLifecycle, BranchOperation, BranchReferenceRole,
            branch_descriptor_stage_row,
        };
        use crate::transaction_types::{
            RawWriteBatch, TransactionJson, TransactionWrite, TransactionWriteMode,
            TransactionWriteRow,
        };
        let adapter = self.storage_adapter();
        let mut head = self
            .retry_sync_demands(|| async {
                let read = adapter
                    .begin_read(crate::storage_adapter::StorageReadOptions::default())
                    .await?;
                BranchLifecycle::new(&crate::branch::BranchContext::new().ref_reader(&read))
                    .require_existing_commit_id(
                        crate::GLOBAL_BRANCH_ID,
                        BranchOperation::CreateBranch,
                        BranchReferenceRole::Source,
                    )
                    .await
            })
            .await?;
        // Resolve immutable ancestry before publication. Per-node hydration
        // retains this cursor, so sparse history cannot repeatedly replay the
        // traversed prefix. Without jump metadata this is O(history depth).
        loop {
            let node = self
                .retry_sync_demands(|| async {
                    let read = adapter
                        .begin_read(crate::storage_adapter::StorageReadOptions::default())
                        .await?;
                    crate::commit_graph::CommitGraphContext::new()
                        .reader(&read)
                        .load_node(&head)
                        .await?
                        .ok_or_else(|| crate::commit_graph::missing_commit_graph_error(&head))
                })
                .await?;
            let Some(parent) = node.parent_commit_ids.first().copied() else {
                break;
            };
            head = if node.first_parent_jump_span > 0 {
                node.first_parent_jump_commit_id
            } else {
                parent
            };
        }
        // Complete captured local state is restored on the fixed repository
        // root, never on unrelated caller state. Normal commit validation still
        // proves this source while atomically publishing rows and receipt.
        self.retry_sync_demands(|| async {
            self.session
                .with_write_transaction_lending(async |transaction| {
                    let mut creation = RawWriteBatch::with_capacity(2);
                    creation.push(branch_descriptor_stage_row(branch_id, name, false));
                    creation.push_branch_head(BranchHeadWrite::new(branch_id, Some(head)));
                    transaction
                        .stage_write(TransactionWrite::Rows {
                            mode: TransactionWriteMode::Insert,
                            rows: creation,
                        })
                        .await?;
                    let mut rows = RawWriteBatch::with_capacity(recovery_rows.len() + 1);
                    for row in recovery_rows {
                        rows.push(TransactionWriteRow {
                            row_pk: Some(
                                crate::row_pk::RowPk::from_typed_json_array_value(&row.row_pk)
                                    .map_err(|error| LixError::unknown(error.to_string()))?,
                            ),
                            schema_key: row.schema_key.clone().into(),
                            file_id: row.file_id.clone().map(Into::into),
                            snapshot: if row.deleted {
                                None
                            } else {
                                row.snapshot
                                    .clone()
                                    .map(TransactionJson::from_value_unchecked)
                            },
                            metadata: row
                                .metadata
                                .clone()
                                .map(TransactionJson::from_value_unchecked),
                            origin: None,
                            created_at: None,
                            updated_at: None,
                            global: false,
                            change_id: None,
                            commit_id: None,
                            untracked: false,
                            branch_id: branch_id.to_owned().into(),
                        });
                    }
                    transaction
                        .stage_recovery_write(TransactionWrite::RowsWithFileContent {
                            mode: TransactionWriteMode::Replace,
                            rows,
                            count: recovery_rows.len() as u64,
                            file_content: file_content.clone(),
                        })
                        .await?;
                    let mut receipt_rows = RawWriteBatch::with_capacity(1);
                    receipt_rows.push(TransactionWriteRow {
                        row_pk: Some(crate::row_pk::RowPk::single(receipt_key)),
                        schema_key: "lix_key_value".into(),
                        file_id: None,
                        snapshot: Some(TransactionJson::from_value_unchecked(
                            serde_json::json!({"key": receipt_key, "value": receipt}),
                        )),
                        metadata: None,
                        origin: None,
                        created_at: None,
                        updated_at: None,
                        global: true,
                        change_id: None,
                        commit_id: None,
                        untracked: false,
                        branch_id: crate::GLOBAL_BRANCH_ID.into(),
                    });
                    transaction
                        .stage_write(TransactionWrite::Rows {
                            mode: TransactionWriteMode::Insert,
                            rows: receipt_rows,
                        })
                        .await?;
                    Ok(())
                })
                .await
        })
        .await
    }
}

#[cfg(test)]
mod recovery_branch_publication_tests;

/// Converts closed full-replica storage to a partial replica with on-demand sync.
/// Ordinary pending edits and new branches whose global changes contain only
/// branch-descriptor additions reconcile natively before publication. Other
/// unsupported global/checkpoint/reset changes preserve the full
/// source and return an explicit recovery error. Migration may inspect all data.
#[cfg(any(feature = "offline-migration", test))]
pub async fn convert_replica_to_partial<S>(
    storage: S,
    server: ServerOptions,
    branch_id: Option<&str>,
) -> Result<(), LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    partial::convert_full_replica_for_partial_open(storage, server, branch_id).await
}

/// Retries temporary native migration-pin cleanup on closed partial storage.
/// This explicit maintenance may inspect journals and contact the authority;
/// ordinary opening and the published local working set remain unchanged.
/// Returns the number of newly acknowledged cleanup records.
#[cfg(any(feature = "offline-migration", test))]
pub async fn retry_replica_migration_cleanup<S>(
    storage: S,
    server: ServerOptions,
) -> Result<usize, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    partial::retry_partial_migration_cleanup(storage, server).await
}

#[cfg(test)]
#[path = "handle/session_open_retry_tests.rs"]
mod session_open_retry_tests;

#[cfg(all(test, feature = "server-protocol"))]
impl<S: Storage + Clone + Send + Sync + 'static> Lix<S> {
    pub(crate) fn from_partial_engine_for_test(
        engine: Arc<Engine<StorageSession<S>>>,
        session: SessionContext<StorageSession<S>>,
        sender: tokio::sync::mpsc::Sender<crate::sync::SyncDemand>,
    ) -> Self {
        let lix = Self {
            engine,
            session: Arc::new(session),
            transaction_lifecycle: Arc::default(),
            primary_switch_gate: Some(Arc::default()),
            sync_lease: None,
            sync_demand_tx: Some(sender),
            server: None,
            open_report: Arc::new(OpenReport {
                format: crate::init::CURRENT_FORMAT_VERSION,
                initialized: false,
                migration: None,
            }),
        };
        lix.bind_session();
        lix
    }
}

#[cfg(test)]
mod durability_tests;