lix 0.15.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
use std::{ops::Bound, sync::Arc, time::Duration};

use bytes::Bytes;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use futures_util::{FutureExt as _, select_biased};

use crate::LixError;
use crate::engine::{Engine, EngineOptions};
use crate::open_types::{
    OpenMigrationReport, OpenPhase, OpenProgress, OpenProgressSink, OpenReport, emit_open_progress,
};
use crate::storage_adapter::{
    EpochBank, MAX_SCAN_PAGE_ROWS, MemoryRead, MemoryWrite, PutBatch, PutEntry,
    REPOSITORY_EPOCH_KEY, REPOSITORY_EPOCH_SPACE, Storage, StorageAdapter, StorageAdapterRead as _,
    StorageBeginScanOptions as BeginScanOptions, StorageCommitResult as CommitResult,
    StorageCoreProjection as CoreProjection, StorageError, StorageGetManyRequest as GetManyRequest,
    StorageGetManyResult as GetManyResult, StorageGetOptions as GetOptions, StorageKey as Key,
    StorageKeyRange as KeyRange, StoragePrecondition as Precondition,
    StorageProjectedValue as ProjectedValue, StorageRead, StorageReadEntry as ReadEntry,
    StorageReadOptions as ReadOptions, StorageScanChunk as ScanChunk,
    StorageScanCursor as ScanCursor, StorageScanSource, StorageSessionToken, StorageSpace,
    StorageValue as StoredValue, StorageWrite, StorageWriteOptions as WriteOptions,
};

const POINTER_PREFIX: &str = "lix.repository-epoch.v1";
const LEGACY_FENCE: &[u8] = b"tracked-default-branch.v76-epoch-migrating";
const REPOSITORY_EPOCH_LEASE_KEY: &[u8] = b"lease";
const REPOSITORY_EPOCH_SOURCE_MARKER_KEY: &[u8] = b"source-marker";
const REPOSITORY_LEGACY_RETIRED_KEY: &[u8] = b"legacy-retired";
#[cfg(not(test))]
const MIGRATION_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
#[cfg(test)]
const MIGRATION_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(10);
const MISSED_HEARTBEATS_BEFORE_RECOVERY: usize = 10;

fn durable_candidate_write_options() -> WriteOptions {
    WriteOptions {
        // A durable epoch pointer must never outlive candidate rows or the
        // deletion of stale rows in the bank it makes reachable.
        await_durable: true,
        ..WriteOptions::default()
    }
}

fn epoch_data_spaces() -> impl Iterator<Item = StorageSpace> {
    crate::storage_spaces::SNAPSHOT_STORAGE_SPACES
        .iter()
        .copied()
}

pub(crate) struct EpochAdmission<S> {
    pub(crate) adapter: StorageAdapter<S>,
    pub(crate) report: OpenReport,
}

/// Owns one hidden, durably fenced epoch while a complete external state is
/// imported. Only the exact-pointer publication makes the candidate visible.
pub(crate) struct FreshEpochImport<S>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    storage: S,
    candidate: StorageAdapter<S>,
    claim: Bytes,
    publication: uuid::Uuid,
    heartbeat: Option<MigrationHeartbeat>,
    cleanup: Option<FreshEpochCleanup>,
}

enum FreshEpochCleanupCommand {
    Cleanup,
    Disarm,
}

struct FreshEpochCleanup {
    command: Option<tokio::sync::oneshot::Sender<FreshEpochCleanupCommand>>,
    claimed: Option<tokio::sync::oneshot::Receiver<Result<(), LixError>>>,
    done: Option<tokio::sync::oneshot::Receiver<Result<(), LixError>>>,
}

impl FreshEpochCleanup {
    async fn wait_for_claim(&mut self) -> Result<(), LixError> {
        self.claimed
            .take()
            .expect("fresh epoch claim completion receiver is present")
            .await
            .map_err(|_| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "snapshot restore claim task stopped without reporting completion",
                )
            })?
    }

    async fn cleanup(mut self) -> Result<(), LixError> {
        let command = self
            .command
            .take()
            .expect("fresh epoch cleanup command sender is present");
        command
            .send(FreshEpochCleanupCommand::Cleanup)
            .map_err(|_| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "snapshot restore cleanup task stopped before receiving cancellation",
                )
            })?;
        self.done
            .take()
            .expect("fresh epoch cleanup completion receiver is present")
            .await
            .map_err(|_| {
                LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "snapshot restore cleanup task stopped without reporting completion",
                )
            })?
    }

    fn disarm(mut self) {
        if let Some(command) = self.command.take() {
            let _ = command.send(FreshEpochCleanupCommand::Disarm);
        }
    }
}

impl Drop for FreshEpochCleanup {
    fn drop(&mut self) {
        // Closing the command channel is the cancellation signal. The cleanup
        // task is started before the claim is attempted, so Drop never needs
        // to create a task or block on asynchronous storage work.
        self.command.take();
    }
}

pub(crate) async fn begin_fresh_epoch_import<S>(storage: S) -> Result<FreshEpochImport<S>, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    let target = EpochBank::A;
    let publication = uuid::Uuid::now_v7();
    let claim = encode_pointer(PointerState::Migrating {
        source: EpochBank::Legacy,
        source_format: 0,
        target,
        generation: 1,
        attempt: publication,
    });
    let candidate = StorageAdapter::for_epoch_migration(storage.clone(), target, claim.clone());
    let mut cleanup = start_fresh_epoch_cleanup(storage.clone(), candidate.clone(), claim.clone())?;
    cleanup.wait_for_claim().await?;
    let heartbeat = match start_migration_heartbeat(storage.clone(), claim.clone()) {
        Ok(heartbeat) => heartbeat,
        Err(error) => {
            let cleaned = cleanup.cleanup().await;
            return Err(with_cleanup_error(error, cleaned));
        }
    };
    if let Err(error) = clear_bank(&candidate).await {
        let cleaned = cleanup.cleanup().await;
        let stopped = heartbeat.stop().await;
        return Err(with_cleanup_error(
            error,
            combine_cleanup_results(Ok(()), cleaned, stopped),
        ));
    }
    Ok(FreshEpochImport {
        storage,
        candidate,
        claim,
        publication,
        heartbeat: Some(heartbeat),
        cleanup: Some(cleanup),
    })
}

impl<S> FreshEpochImport<S>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    pub(crate) fn candidate(&self) -> &StorageAdapter<S> {
        &self.candidate
    }

    pub(crate) async fn write_exact_batch(
        &self,
        space: StorageSpace,
        batch: PutBatch,
    ) -> Result<(), LixError> {
        let mut write = self
            .candidate
            .begin_migration_write(durable_candidate_write_options())
            .await
            .map_err(storage_error)?;
        write.put_many(space, batch).await.map_err(storage_error)?;
        write.commit().await.map_err(storage_error)?;
        Ok(())
    }

    pub(crate) async fn publish(mut self, format: u32) -> Result<S, LixError> {
        let active_bytes = encode_pointer(PointerState::Active {
            bank: EpochBank::A,
            generation: 1,
            format,
            publication: Some(self.publication),
        });
        if let Err(error) = replace_pointer(&self.storage, &self.claim, &active_bytes).await {
            if error.code == LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN {
                if let Some(heartbeat) = self.heartbeat.take() {
                    let _ = heartbeat.stop().await;
                }
                return Err(error);
            }
            match load_pointer(&self.storage).await {
                Ok(Some((_, bytes))) if bytes == active_bytes => {}
                Ok(Some((_, bytes))) if bytes == self.claim => {
                    let cleanup = self.abort().await;
                    return Err(with_cleanup_error(error, cleanup));
                }
                Ok(_) => {
                    if let Some(heartbeat) = self.heartbeat.take() {
                        let _ = heartbeat.stop().await;
                    }
                    return Err(error);
                }
                Err(inspect_error) => {
                    if let Some(heartbeat) = self.heartbeat.take() {
                        let _ = heartbeat.stop().await;
                    }
                    return Err(LixError::new(
                        error.code.clone(),
                        format!(
                            "{error}; could not resolve snapshot publication outcome: {inspect_error}"
                        ),
                    ));
                }
            }
        }
        // Publication is now exact and durable. Cancellation while joining the
        // heartbeat must not tear down the epoch that was just made active.
        if let Some(cleanup) = self.cleanup.take() {
            cleanup.disarm();
        }
        if let Some(heartbeat) = self.heartbeat.take() {
            // The active pointer is the durable commit point. A heartbeat join
            // failure after it cannot turn a committed restore into a failure.
            let _ = heartbeat.stop().await;
        }
        Ok(self.storage)
    }

    pub(crate) async fn abort(mut self) -> Result<(), LixError> {
        let cleaned = match self.cleanup.take() {
            Some(cleanup) => cleanup.cleanup().await,
            None => Ok(()),
        };
        let stopped = match self.heartbeat.take() {
            Some(heartbeat) => heartbeat.stop().await,
            None => Ok(()),
        };
        combine_cleanup_results(Ok(()), cleaned, stopped)
    }
}

fn start_fresh_epoch_cleanup<S>(
    storage: S,
    candidate: StorageAdapter<S>,
    claim: Bytes,
) -> Result<FreshEpochCleanup, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    let (command, receive_command) = tokio::sync::oneshot::channel();
    let (report_claimed, claimed) = tokio::sync::oneshot::channel();
    let (report_done, done) = tokio::sync::oneshot::channel();
    crate::background_task::spawn(
        "lix-snapshot-restore-cleanup",
        move || async move {
            // Claim acquisition is owned by this task, not by the restore
            // future. JavaScript promises and remote commits can continue after
            // their Rust waiter is dropped; keeping the waiter here guarantees
            // that cancellation cannot run cleanup against an absent pointer
            // and then let an in-flight claim appear after cleanup has exited.
            if let Err(error) = claim_fresh_import(&storage, &claim).await {
                let cleaned = cleanup_fresh_epoch_claim(&storage, &candidate, &claim).await;
                let error = with_cleanup_error(error, cleaned);
                let _ = report_done.send(Ok(()));
                let _ = report_claimed.send(Err(error));
                return;
            }
            if report_claimed.send(Ok(())).is_err() {
                // The restore was cancelled before it observed ownership. The
                // claim is now settled and exact, so it is safe to remove it.
                let result = cleanup_fresh_epoch_claim(&storage, &candidate, &claim).await;
                let _ = report_done.send(result);
                return;
            }
            let should_cleanup = !matches!(
                receive_command.await,
                Ok(FreshEpochCleanupCommand::Disarm)
            );
            let result = if should_cleanup {
                cleanup_fresh_epoch_claim(&storage, &candidate, &claim).await
            } else {
                Ok(())
            };
            let _ = report_done.send(result);
        },
    )?;
    Ok(FreshEpochCleanup {
        command: Some(command),
        claimed: Some(claimed),
        done: Some(done),
    })
}

async fn cleanup_fresh_epoch_claim<S>(
    storage: &S,
    candidate: &StorageAdapter<S>,
    claim: &Bytes,
) -> Result<(), LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    let cleared = clear_bank(&candidate).await;
    // Always release the exact claim. A later admission clears its hidden
    // target before use, so stale candidate rows are safer than an orphaned
    // epoch-control pointer that makes restore permanently unretryable.
    let deleted = delete_pointer_resolving_outcome(storage, claim).await;
    combine_cleanup_results(cleared, deleted, Ok(()))
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PointerState {
    Active {
        bank: EpochBank,
        generation: u64,
        format: u32,
        publication: Option<uuid::Uuid>,
    },
    Migrating {
        source: EpochBank,
        source_format: u32,
        target: EpochBank,
        generation: u64,
        attempt: uuid::Uuid,
    },
}

pub(crate) async fn admit_repository<S>(
    storage: &S,
    progress: Option<&Arc<dyn OpenProgressSink>>,
) -> Result<EpochAdmission<S>, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    'admission: loop {
        match load_pointer(storage).await? {
            Some((
                PointerState::Active {
                    bank,
                    generation,
                    format,
                    ..
                },
                bytes,
            )) => {
                if format > crate::init::CURRENT_FORMAT_VERSION {
                    return Err(epoch_error(format!(
                        "repository epoch format v{format} is newer than this engine's v{}",
                        crate::init::CURRENT_FORMAT_VERSION
                    )));
                }
                if format < crate::init::CURRENT_FORMAT_VERSION {
                    return migrate_active(storage, bank, generation, format, bytes, progress)
                        .await;
                }
                if generation >= 2 {
                    let _ = schedule_legacy_retirement(storage.clone(), bytes.clone());
                }
                return Ok(EpochAdmission {
                    adapter: StorageAdapter::for_epoch(storage.clone(), bank, bytes),
                    report: OpenReport {
                        format,
                        initialized: false,
                        migration: None,
                    },
                });
            }
            Some((state @ PointerState::Migrating { .. }, bytes)) => {
                let PointerState::Migrating { source_format, .. } = state else {
                    unreachable!()
                };
                emit_migrating(progress, source_format);
                // A renewable lease distinguishes a slow live owner from an
                // interrupted one without trusting process clocks. Recovery
                // CASes both the exact pointer and the last observed lease.
                let mut observed_lease = load_lease(storage).await?;
                let observed_source_marker = load_source_marker(storage).await?;
                let mut missed = 0;
                loop {
                    portable_sleep(MIGRATION_HEARTBEAT_INTERVAL).await?;
                    match load_pointer(storage).await? {
                        Some((_, current)) if current == bytes => {}
                        _ => continue 'admission,
                    }
                    let current_lease = load_lease(storage).await?;
                    if current_lease != observed_lease {
                        observed_lease = current_lease;
                        missed = 0;
                        continue;
                    }
                    missed += 1;
                    if missed >= MISSED_HEARTBEATS_BEFORE_RECOVERY {
                        break;
                    }
                }
                if let Err(error) = recover_interrupted_migration(
                    storage,
                    state,
                    &bytes,
                    observed_lease.as_ref(),
                    observed_source_marker.as_ref(),
                )
                .await
                {
                    // A concurrent recovery or the original owner may have
                    // won the exact-pointer CAS. Reinspect before surfacing a
                    // genuine storage failure.
                    match load_pointer(storage).await? {
                        Some((_, current)) if current == bytes => {
                            if load_lease(storage).await? != observed_lease {
                                continue 'admission;
                            }
                            return Err(error);
                        }
                        _ => continue 'admission,
                    }
                }
            }
            None => return admit_legacy(storage, progress).await,
        }
    }
}

fn emit_migrating(progress: Option<&Arc<dyn OpenProgressSink>>, from_format: u32) {
    emit_open_progress(
        progress,
        OpenProgress {
            phase: OpenPhase::Migrating,
            from_format: (from_format != 0).then_some(from_format),
            to_format: crate::init::CURRENT_FORMAT_VERSION,
            completed: Some(0),
            total: None,
        },
    );
}

fn emit_validating(progress: Option<&Arc<dyn OpenProgressSink>>, from_format: u32) {
    emit_open_progress(
        progress,
        OpenProgress {
            phase: OpenPhase::Validating,
            from_format: (from_format != 0).then_some(from_format),
            to_format: crate::init::CURRENT_FORMAT_VERSION,
            completed: None,
            total: None,
        },
    );
}

async fn recover_interrupted_migration<S>(
    storage: &S,
    state: PointerState,
    migrating_bytes: &Bytes,
    observed_lease: Option<&Bytes>,
    observed_source_marker: Option<&Bytes>,
) -> Result<(), LixError>
where
    S: Storage + Clone,
{
    let PointerState::Migrating {
        source,
        source_format,
        target,
        generation,
        ..
    } = state
    else {
        return Err(epoch_error("cannot recover a non-migrating epoch pointer"));
    };
    if source == EpochBank::Legacy && source_format == 0 {
        return recover_interrupted_fresh_import(
            storage,
            target,
            generation,
            migrating_bytes,
            observed_lease,
        )
        .await;
    }
    let mut preconditions = vec![Precondition::KeyValueEquals {
        space: REPOSITORY_EPOCH_SPACE,
        key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
        expected: migrating_bytes.clone(),
    }];
    preconditions.push(match observed_lease {
        Some(expected) => Precondition::KeyValueEquals {
            space: REPOSITORY_EPOCH_SPACE,
            key: Key(Bytes::from_static(REPOSITORY_EPOCH_LEASE_KEY)),
            expected: expected.clone(),
        },
        None => Precondition::KeyAbsent {
            space: REPOSITORY_EPOCH_SPACE,
            key: Key(Bytes::from_static(REPOSITORY_EPOCH_LEASE_KEY)),
        },
    });
    if source == EpochBank::Legacy && source_format != 0 {
        let marker = observed_source_marker.ok_or_else(|| {
            epoch_error("interrupted legacy migration lost its exact source marker")
        })?;
        preconditions.push(Precondition::KeyValueEquals {
            space: REPOSITORY_EPOCH_SPACE,
            key: Key(Bytes::from_static(REPOSITORY_EPOCH_SOURCE_MARKER_KEY)),
            expected: marker.clone(),
        });
    }
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions,
            ..WriteOptions::default()
        })
        .await
        .map_err(storage_error)?;
    let mut restored_active = None;
    match (source, source_format) {
        (EpochBank::Legacy, 0) => unreachable!("fresh import recovery returns above"),
        (EpochBank::Legacy, _format) => {
            let marker = observed_source_marker.ok_or_else(|| {
                epoch_error("interrupted legacy migration lost its exact source marker")
            })?;
            write
                .put_many(
                    crate::init::REPOSITORY_PROTOCOL_SPACE,
                    single_put(crate::init::REPOSITORY_PROTOCOL_KEY, marker.clone()),
                )
                .await
                .map_err(storage_error)?;
            delete_epoch_control(&mut write)
                .await
                .map_err(storage_error)?;
            crate::storage_adapter::stage_mutation_revision(&mut write)
                .await
                .map_err(storage_error)?;
        }
        (bank, format) => {
            let active = encode_pointer(PointerState::Active {
                bank,
                generation: generation.saturating_sub(1),
                format,
                publication: None,
            });
            put_pointer(&mut write, active.clone())
                .await
                .map_err(storage_error)?;
            delete_lease(&mut write).await.map_err(storage_error)?;
            restored_active = Some(active);
        }
    }
    let commit = write.commit().await;
    if let Some(active) = restored_active {
        resolve_exact_pointer_commit(storage, commit, &active)
            .await
            .map_err(storage_error)?;
    } else {
        commit.map_err(storage_error)?;
    }
    Ok(())
}

async fn recover_interrupted_fresh_import<S>(
    storage: &S,
    target: EpochBank,
    generation: u64,
    migrating_bytes: &Bytes,
    observed_lease: Option<&Bytes>,
) -> Result<(), LixError>
where
    S: Storage + Clone,
{
    // Recovery must own a distinct pointer before touching the candidate. The
    // prior importer and all of its adapters are fenced by this transition.
    let recovery_bytes = encode_pointer(PointerState::Migrating {
        source: EpochBank::Legacy,
        source_format: 0,
        target,
        generation,
        attempt: uuid::Uuid::now_v7(),
    });
    let mut preconditions = vec![Precondition::KeyValueEquals {
        space: REPOSITORY_EPOCH_SPACE,
        key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
        expected: migrating_bytes.clone(),
    }];
    preconditions.push(match observed_lease {
        Some(expected) => Precondition::KeyValueEquals {
            space: REPOSITORY_EPOCH_SPACE,
            key: Key(Bytes::from_static(REPOSITORY_EPOCH_LEASE_KEY)),
            expected: expected.clone(),
        },
        None => Precondition::KeyAbsent {
            space: REPOSITORY_EPOCH_SPACE,
            key: Key(Bytes::from_static(REPOSITORY_EPOCH_LEASE_KEY)),
        },
    });
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions,
            ..WriteOptions::default()
        })
        .await
        .map_err(storage_error)?;
    put_pointer(&mut write, recovery_bytes.clone())
        .await
        .map_err(storage_error)?;
    put_lease(&mut write, Bytes::from_static(b"0"))
        .await
        .map_err(storage_error)?;
    resolve_exact_pointer_commit(storage, write.commit().await, &recovery_bytes)
        .await
        .map_err(storage_error)?;

    let recovery =
        StorageAdapter::for_epoch_migration((*storage).clone(), target, recovery_bytes.clone());
    clear_bank(&recovery).await?;
    delete_pointer_resolving_outcome(storage, &recovery_bytes).await
}

async fn admit_legacy<S>(
    storage: &S,
    progress: Option<&Arc<dyn OpenProgressSink>>,
) -> Result<EpochAdmission<S>, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    let legacy_status = super::inspect_lix(storage).await?;
    if matches!(legacy_status, super::MigrationStatus::Missing) {
        let legacy = StorageAdapter::new(storage.clone());
        if legacy
            .load_mutation_revision()
            .await
            .map_err(storage_error)?
            .is_some()
        {
            return Err(crate::init::unsupported_repository_protocol_error());
        }
        let target = EpochBank::A;
        let migrating_bytes = encode_pointer(PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target,
            generation: 1,
            attempt: uuid::Uuid::now_v7(),
        });
        if let Err(error) = publish_migration_claim_absent(storage, &migrating_bytes).await {
            if is_admission_race(&error) {
                return Box::pin(admit_repository(storage, progress)).await;
            }
            return Err(storage_error(error));
        }
        let heartbeat = match start_migration_heartbeat(storage.clone(), migrating_bytes.clone()) {
            Ok(heartbeat) => heartbeat,
            Err(error) => {
                delete_pointer(storage, &migrating_bytes).await?;
                return Err(error);
            }
        };
        let result = async {
            let candidate = StorageAdapter::for_epoch_migration(
                storage.clone(),
                target,
                migrating_bytes.clone(),
            );
            // Allocate and publish the empty bank, but leave repository
            // initialization to the normal engine-open path. Sync bootstrap
            // learns the authority's default branch only after admission, and
            // that path must be able to supply it to the initializer. An active
            // empty bank is restart-safe: the next open observes the missing
            // protocol marker and completes initialization.
            if let Err(error) = clear_bank(&candidate).await {
                delete_pointer(storage, &migrating_bytes).await?;
                return Err(error);
            }
            let active = PointerState::Active {
                bank: target,
                generation: 1,
                format: crate::init::CURRENT_FORMAT_VERSION,
                publication: None,
            };
            let active_bytes = encode_pointer(active);
            replace_pointer(storage, &migrating_bytes, &active_bytes).await?;
            Ok(EpochAdmission {
                adapter: StorageAdapter::for_epoch(storage.clone(), target, active_bytes),
                report: OpenReport {
                    format: crate::init::CURRENT_FORMAT_VERSION,
                    // This admission owns the fresh open; the engine-open path
                    // completes initialization after sync can supply its
                    // authoritative default branch.
                    initialized: true,
                    migration: None,
                },
            })
        }
        .await;
        return finish_after_heartbeat(heartbeat, result).await;
    }

    let from_format = match legacy_status {
        super::MigrationStatus::Current { version }
        | super::MigrationStatus::Required {
            from_version: version,
            ..
        } => version,
        super::MigrationStatus::TooNew { found_version, .. } => {
            return Err(epoch_error(format!(
                "repository v{found_version} is newer than this engine"
            )));
        }
        super::MigrationStatus::Malformed | super::MigrationStatus::Missing => {
            return Err(epoch_error(
                "repository has no valid versioned protocol marker",
            ));
        }
    };
    if from_format < 72
        || !super::registry::has_complete_migration_path(
            from_format,
            crate::init::CURRENT_FORMAT_VERSION,
        )
    {
        return Err(epoch_error(format!(
            "repository v{from_format} predates the v{} complete-snapshot commit format; no automatic upgrade is available",
            crate::init::CURRENT_FORMAT_VERSION
        )));
    }
    let original_marker = load_storage_value(
        storage,
        crate::init::REPOSITORY_PROTOCOL_SPACE,
        crate::init::REPOSITORY_PROTOCOL_KEY,
    )
    .await?
    .ok_or_else(|| epoch_error("repository protocol marker disappeared during inspection"))?;
    emit_migrating(progress, from_format);
    let source = StorageAdapter::new(storage.clone());
    let target_bank = EpochBank::A;
    let source_revision = match source.load_mutation_revision().await {
        Ok(revision) => revision,
        Err(error) if is_admission_race(&error) => {
            return Box::pin(admit_repository(storage, progress)).await;
        }
        Err(error) => return Err(storage_error(error)),
    };
    let migrating = PointerState::Migrating {
        source: EpochBank::Legacy,
        source_format: from_format,
        target: target_bank,
        generation: 1,
        attempt: uuid::Uuid::now_v7(),
    };
    let migrating_bytes = encode_pointer(migrating);
    if let Err(error) =
        claim_legacy(storage, source_revision, &original_marker, &migrating_bytes).await
    {
        if is_admission_race(&error) {
            return Box::pin(admit_repository(storage, progress)).await;
        }
        return Err(storage_error(error));
    }
    let heartbeat = match start_migration_heartbeat(storage.clone(), migrating_bytes.clone()) {
        Ok(heartbeat) => heartbeat,
        Err(error) => {
            rollback_legacy(storage, &migrating_bytes, &original_marker).await?;
            return Err(error);
        }
    };

    let result = async {
        let target = StorageAdapter::for_epoch_migration(
            storage.clone(),
            target_bank,
            migrating_bytes.clone(),
        );

        let migration_source = StorageAdapter::for_epoch_migration(
            storage.clone(),
            EpochBank::Legacy,
            migrating_bytes.clone(),
        );
        let fenced_revision = migration_source
            .load_mutation_revision()
            .await
            .map_err(storage_error)?;
        let candidate_result = async {
            clear_bank(&target).await?;
            let _ = copy_repository(&migration_source, &target).await?;
            let mut marker_write = target.new_write_set();
            marker_write.put(
                crate::init::REPOSITORY_PROTOCOL_SPACE,
                crate::init::REPOSITORY_PROTOCOL_KEY,
                original_marker.as_ref(),
            );
            target
                .commit_write_set(marker_write, durable_candidate_write_options())
                .await
                .map_err(|error| epoch_error(format!("candidate marker write failed: {error}")))?;
            super::migrate_lix_with_adapter(
                storage.clone(),
                target.clone(),
                super::MigrationOptions::automatic(),
            )
            .await?;
            emit_validating(progress, from_format);
            match super::inspect_lix_with_adapter(&target).await? {
                super::MigrationStatus::Current { .. } => {}
                status => {
                    return Err(epoch_error(format!(
                        "candidate repository validation observed {status:?}"
                    )));
                }
            }
            let engine = Engine::new_with_adapter(target.clone(), EngineOptions::new()).await?;
            drop(engine);
            Ok::<(), LixError>(())
        }
        .await;
        if let Err(error) = candidate_result {
            rollback_legacy(storage, &migrating_bytes, &original_marker).await?;
            return Err(error);
        }

        let active = PointerState::Active {
            bank: target_bank,
            generation: 1,
            format: crate::init::CURRENT_FORMAT_VERSION,
            publication: None,
        };
        let active_bytes = encode_pointer(active);
        if let Err(error) =
            activate_legacy(storage, &migrating_bytes, fenced_revision, &active_bytes).await
        {
            if matches!(error, StorageError::CommitOutcomeUnknown(_)) {
                return Err(LixError::from(error));
            }
            rollback_legacy(storage, &migrating_bytes, &original_marker).await?;
            return Err(storage_error(error));
        }
        Ok(EpochAdmission {
            adapter: StorageAdapter::for_epoch(storage.clone(), target_bank, active_bytes),
            report: OpenReport {
                format: crate::init::CURRENT_FORMAT_VERSION,
                initialized: false,
                migration: Some(OpenMigrationReport {
                    from_format,
                    to_format: crate::init::CURRENT_FORMAT_VERSION,
                }),
            },
        })
    }
    .await;
    finish_after_heartbeat(heartbeat, result).await
}

async fn migrate_active<S>(
    storage: &S,
    source_bank: EpochBank,
    source_generation: u64,
    from_format: u32,
    active_source_bytes: Bytes,
    progress: Option<&Arc<dyn OpenProgressSink>>,
) -> Result<EpochAdmission<S>, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    if !super::registry::has_complete_migration_path(
        from_format,
        crate::init::CURRENT_FORMAT_VERSION,
    ) {
        return Err(epoch_error(format!(
            "repository epoch v{from_format} has no registered upgrade path to v{}",
            crate::init::CURRENT_FORMAT_VERSION
        )));
    }
    let source =
        StorageAdapter::for_epoch(storage.clone(), source_bank, active_source_bytes.clone());
    emit_migrating(progress, from_format);
    let target_bank = source_bank.alternate();
    let source_revision = match source.load_mutation_revision().await {
        Ok(revision) => revision,
        Err(error) if is_admission_race(&error) => {
            return Box::pin(admit_repository(storage, progress)).await;
        }
        Err(error) => return Err(storage_error(error)),
    };
    let migrating = PointerState::Migrating {
        source: source_bank,
        source_format: from_format,
        target: target_bank,
        generation: source_generation.saturating_add(1),
        attempt: uuid::Uuid::now_v7(),
    };
    let migrating_bytes = encode_pointer(migrating);
    let mut claim = match source
        .begin_migration_write(WriteOptions {
            await_durable: true,
            preconditions: vec![StorageAdapter::<S>::mutation_revision_precondition(
                source_revision,
            )],
            ..WriteOptions::default()
        })
        .await
    {
        Ok(claim) => claim,
        Err(error) if is_admission_race(&error) => {
            return Box::pin(admit_repository(storage, progress)).await;
        }
        Err(error) => return Err(storage_error(error)),
    };
    put_pointer(&mut claim, migrating_bytes.clone())
        .await
        .map_err(storage_error)?;
    put_lease(&mut claim, Bytes::from_static(b"0"))
        .await
        .map_err(storage_error)?;
    if let Err(error) =
        resolve_exact_pointer_commit(storage, claim.commit().await, &migrating_bytes).await
    {
        if is_admission_race(&error) {
            return Box::pin(admit_repository(storage, progress)).await;
        }
        return Err(storage_error(error));
    }
    let heartbeat = match start_migration_heartbeat(storage.clone(), migrating_bytes.clone()) {
        Ok(heartbeat) => heartbeat,
        Err(error) => {
            replace_pointer(storage, &migrating_bytes, &active_source_bytes).await?;
            return Err(error);
        }
    };

    let result = async {
        let target = StorageAdapter::for_epoch_migration(
            storage.clone(),
            target_bank,
            migrating_bytes.clone(),
        );
        let migration_source = StorageAdapter::for_epoch_migration(
            storage.clone(),
            source_bank,
            migrating_bytes.clone(),
        );

        let candidate_result = async {
            clear_bank(&target).await?;
            let _ = copy_repository(&migration_source, &target).await?;
            super::migrate_lix_with_adapter(
                storage.clone(),
                target.clone(),
                super::MigrationOptions::automatic(),
            )
            .await?;
            emit_validating(progress, from_format);
            let engine = Engine::new_with_adapter(target.clone(), EngineOptions::new()).await?;
            drop(engine);
            Ok::<(), LixError>(())
        }
        .await;
        if let Err(error) = candidate_result {
            replace_pointer(storage, &migrating_bytes, &active_source_bytes).await?;
            return Err(error);
        }

        let active = PointerState::Active {
            bank: target_bank,
            generation: source_generation.saturating_add(1),
            format: crate::init::CURRENT_FORMAT_VERSION,
            publication: None,
        };
        let active_bytes = encode_pointer(active);
        replace_pointer(storage, &migrating_bytes, &active_bytes).await?;
        // Keep the immediately previous bank for rollback. Once a later epoch has
        // activated, the pre-epoch layout is older than that rollback window and
        // can be reclaimed without making cleanup part of publication success.
        let _ = schedule_legacy_retirement(storage.clone(), active_bytes.clone());
        Ok(EpochAdmission {
            adapter: StorageAdapter::for_epoch(storage.clone(), target_bank, active_bytes),
            report: OpenReport {
                format: crate::init::CURRENT_FORMAT_VERSION,
                initialized: false,
                migration: Some(OpenMigrationReport {
                    from_format,
                    to_format: crate::init::CURRENT_FORMAT_VERSION,
                }),
            },
        })
    }
    .await;
    finish_after_heartbeat(heartbeat, result).await
}

fn schedule_legacy_retirement<S>(storage: S, active_pointer: Bytes) -> Result<(), LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    crate::background_task::spawn("lix-retire-legacy-repository-layout", move || async move {
        let _ = retire_legacy_layout(&storage, &active_pointer).await;
    })
}

async fn retire_legacy_layout<S>(storage: &S, active_pointer: &Bytes) -> Result<(), LixError>
where
    S: Storage + Clone,
{
    if load_storage_value(
        storage,
        REPOSITORY_EPOCH_SPACE,
        REPOSITORY_LEGACY_RETIRED_KEY,
    )
    .await?
    .is_some()
    {
        return Ok(());
    }
    let legacy = StorageAdapter::new(storage.clone());
    for space in crate::storage_spaces::SNAPSHOT_STORAGE_SPACES
        .iter()
        .copied()
    {
        legacy
            .clear_space(
                space,
                WriteOptions {
                    await_durable: true,
                    preconditions: vec![Precondition::KeyValueEquals {
                        space: REPOSITORY_EPOCH_SPACE,
                        key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                        expected: active_pointer.clone(),
                    }],
                    ..WriteOptions::default()
                },
            )
            .await
            .map_err(storage_error)?;
    }
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![Precondition::KeyValueEquals {
                space: REPOSITORY_EPOCH_SPACE,
                key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                expected: active_pointer.clone(),
            }],
            ..WriteOptions::default()
        })
        .await
        .map_err(storage_error)?;
    write
        .put_many(
            REPOSITORY_EPOCH_SPACE,
            single_put(REPOSITORY_LEGACY_RETIRED_KEY, Bytes::from_static(b"1")),
        )
        .await
        .map_err(storage_error)?;
    write.commit().await.map_err(storage_error)?;
    Ok(())
}

async fn clear_bank<S>(adapter: &StorageAdapter<S>) -> Result<(), LixError>
where
    S: Storage,
{
    for space in epoch_data_spaces() {
        adapter
            .clear_space(space, durable_candidate_write_options())
            .await
            .map_err(storage_error)?;
    }
    Ok(())
}

async fn copy_repository<S>(
    source: &StorageAdapter<S>,
    target: &StorageAdapter<S>,
) -> Result<Option<Bytes>, LixError>
where
    S: Storage,
{
    let read = source
        .begin_read(ReadOptions::default())
        .await
        .map_err(storage_error)?;
    let revision = StorageAdapter::<S>::load_mutation_revision_from_read(&read)
        .await
        .map_err(storage_error)?;
    drop(read);
    for space in epoch_data_spaces() {
        let mut lower = Bound::Unbounded;
        loop {
            // The migration claim makes the source bank immutable. Reopen a
            // bounded read for every page so backends whose read generations
            // expire after any commit (notably OPFS) can publish the previous
            // page to the target bank without invalidating the next source
            // page. The exclusive key bound is the durable continuation.
            let (entries, has_more) = read_copy_page(source, space, &lower, &revision).await?;
            if entries.is_empty() {
                break;
            }
            let next_lower = Bound::Excluded(
                entries
                    .last()
                    .expect("a storage scan chunk cannot be empty")
                    .key
                    .clone(),
            );
            let mut writes = target.new_write_set();
            for entry in entries {
                let ProjectedValue::FullValue(value) = entry.value else {
                    return Err(epoch_error("full-value epoch scan returned a key-only row"));
                };
                writes.put(space, entry.key, StoredValue { bytes: value });
            }
            target
                .commit_write_set(writes, durable_candidate_write_options())
                .await
                .map_err(|error| epoch_error(format!("copy target write failed: {error}")))?;
            if !has_more {
                break;
            }
            lower = next_lower;
        }
    }
    Ok(revision)
}

async fn read_copy_page<S>(
    source: &StorageAdapter<S>,
    space: StorageSpace,
    lower: &Bound<Key>,
    expected_revision: &Option<Bytes>,
) -> Result<(Vec<ReadEntry>, bool), LixError>
where
    S: Storage,
{
    let mut retry = crate::common::ExpiredReadRetryState::default();
    loop {
        let result = async {
            let read = source
                .begin_read(ReadOptions::default())
                .await
                .map_err(storage_error)?;
            let observed_revision = StorageAdapter::<S>::load_mutation_revision_from_read(&read)
                .await
                .map_err(storage_error)?;
            if &observed_revision != expected_revision {
                return Err(epoch_error(
                    "source repository changed while its epoch was being copied",
                ));
            }
            let mut cursor = read
                .begin_scan(
                    space,
                    KeyRange {
                        lower: lower.clone(),
                        upper: Bound::Unbounded,
                    },
                    BeginScanOptions {
                        projection: CoreProjection::FullValue,
                        ..BeginScanOptions::default()
                    },
                )
                .await
                .map_err(storage_error)?;
            cursor
                .next_page(MAX_SCAN_PAGE_ROWS)
                .await
                .map_err(storage_error)
                .map(ScanChunk::into_parts)
        }
        .await;
        match result {
            Ok(page) => return Ok(page),
            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 load_pointer<S>(storage: &S) -> Result<Option<(PointerState, Bytes)>, LixError>
where
    S: Storage + ?Sized,
{
    let Some(bytes) = load_pointer_bytes(storage).await.map_err(storage_error)? else {
        return Ok(None);
    };
    let state = decode_pointer(&bytes)?;
    Ok(Some((state, bytes)))
}

async fn load_pointer_bytes<S>(storage: &S) -> Result<Option<Bytes>, StorageError>
where
    S: Storage + ?Sized,
{
    let read = storage.begin_read(ReadOptions::default()).await?;
    let keys = [Key(Bytes::from_static(REPOSITORY_EPOCH_KEY))];
    let values = read
        .get_many(&[GetManyRequest {
            space: REPOSITORY_EPOCH_SPACE,
            keys: &keys,
            opts: GetOptions {
                projection: CoreProjection::FullValue,
            },
        }])
        .await?;
    match values.values.into_iter().next().flatten() {
        Some(ProjectedValue::FullValue(bytes)) => Ok(Some(bytes)),
        Some(ProjectedValue::KeyOnly) => Err(StorageError::Corruption(
            "epoch pointer full-value read returned key-only data".to_string(),
        )),
        None => Ok(None),
    }
}

async fn resolve_exact_pointer_commit<S>(
    storage: &S,
    result: Result<CommitResult, StorageError>,
    expected: &Bytes,
) -> Result<(), StorageError>
where
    S: Storage + ?Sized,
{
    match result {
        Ok(_) => Ok(()),
        Err(StorageError::CommitOutcomeUnknown(message)) => {
            match load_pointer_bytes(storage).await {
                Ok(Some(observed)) if observed == *expected => Ok(()),
                Ok(_) => Err(StorageError::CommitOutcomeUnknown(message)),
                Err(read_error) => Err(StorageError::CommitOutcomeUnknown(format!(
                    "{message}; exact-pointer resolution read failed: {read_error}"
                ))),
            }
        }
        Err(error) => Err(error),
    }
}

async fn load_lease<S>(storage: &S) -> Result<Option<Bytes>, LixError>
where
    S: Storage + ?Sized,
{
    load_storage_value(storage, REPOSITORY_EPOCH_SPACE, REPOSITORY_EPOCH_LEASE_KEY).await
}

async fn load_source_marker<S>(storage: &S) -> Result<Option<Bytes>, LixError>
where
    S: Storage + ?Sized,
{
    load_storage_value(
        storage,
        REPOSITORY_EPOCH_SPACE,
        REPOSITORY_EPOCH_SOURCE_MARKER_KEY,
    )
    .await
}

async fn load_storage_value<S>(
    storage: &S,
    space: StorageSpace,
    key: &'static [u8],
) -> Result<Option<Bytes>, LixError>
where
    S: Storage + ?Sized,
{
    let read = storage
        .begin_read(ReadOptions::default())
        .await
        .map_err(storage_error)?;
    let keys = [Key(Bytes::from_static(key))];
    let values = read
        .get_many(&[GetManyRequest {
            space,
            keys: &keys,
            opts: GetOptions {
                projection: CoreProjection::FullValue,
            },
        }])
        .await
        .map_err(storage_error)?;
    Ok(values
        .values
        .into_iter()
        .next()
        .flatten()
        .and_then(|value| match value {
            ProjectedValue::FullValue(bytes) => Some(bytes),
            ProjectedValue::KeyOnly => None,
        }))
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
type HeartbeatStopSender = std::sync::mpsc::Sender<()>;
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
type HeartbeatStopReceiver = std::sync::mpsc::Receiver<()>;

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
type HeartbeatStopSender = tokio::sync::watch::Sender<bool>;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
type HeartbeatStopReceiver = tokio::sync::watch::Receiver<bool>;

struct MigrationHeartbeat {
    stop: HeartbeatStopSender,
    done: Option<tokio::sync::oneshot::Receiver<()>>,
}

impl MigrationHeartbeat {
    async fn stop(mut self) -> Result<(), LixError> {
        signal_heartbeat_stop(&self.stop);
        let done = self
            .done
            .take()
            .expect("migration heartbeat completion receiver is present");
        done.await.map_err(|_| {
            LixError::new(
                LixError::CODE_INTERNAL_ERROR,
                "repository migration heartbeat stopped without releasing its storage handle",
            )
        })
    }
}

async fn finish_after_heartbeat<T>(
    heartbeat: MigrationHeartbeat,
    result: Result<T, LixError>,
) -> Result<T, LixError> {
    let stopped = heartbeat.stop().await;
    if result
        .as_ref()
        .is_err_and(|error| error.code == LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN)
    {
        return result;
    }
    stopped?;
    result
}

impl Drop for MigrationHeartbeat {
    fn drop(&mut self) {
        signal_heartbeat_stop(&self.stop);
    }
}

fn start_migration_heartbeat<S>(
    storage: S,
    migrating: Bytes,
) -> Result<MigrationHeartbeat, LixError>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    let (stop, mut stop_rx) = std::sync::mpsc::channel();
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    let (stop, mut stop_rx) = tokio::sync::watch::channel(false);
    let (done_tx, done) = tokio::sync::oneshot::channel();
    let task = async move {
        let mut current = Bytes::from_static(b"0");
        let mut sequence = 1_u64;
        while wait_for_heartbeat_interval(&mut stop_rx).await {
            let next = Bytes::from(sequence.to_string());
            if advance_lease(&storage, &migrating, &current, &next)
                .await
                .is_err()
            {
                match (load_pointer(&storage).await, load_lease(&storage).await) {
                    (Ok(Some((_, pointer))), Ok(Some(lease)))
                        if pointer == migrating && lease == next =>
                    {
                        current = next;
                        sequence = sequence.saturating_add(1);
                        continue;
                    }
                    (Ok(Some((_, pointer))), Ok(Some(lease)))
                        if pointer == migrating && lease == current =>
                    {
                        continue;
                    }
                    (Err(_), _) | (_, Err(_)) => continue,
                    _ => break,
                }
            }
            current = next;
            sequence = sequence.saturating_add(1);
        }
        // Completion is also the lifetime barrier: release every task-owned
        // storage clone before waking the opener that is joining us.
        drop(storage);
        drop(migrating);
        let _ = done_tx.send(());
    };
    crate::background_task::spawn("lix-repository-migration-heartbeat", move || task)?;
    Ok(MigrationHeartbeat {
        stop,
        done: Some(done),
    })
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
fn signal_heartbeat_stop(stop: &HeartbeatStopSender) {
    let _ = stop.send(());
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn signal_heartbeat_stop(stop: &HeartbeatStopSender) {
    let _ = stop.send(true);
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
async fn wait_for_heartbeat_interval(stop: &mut HeartbeatStopReceiver) -> bool {
    matches!(
        stop.recv_timeout(MIGRATION_HEARTBEAT_INTERVAL),
        Err(std::sync::mpsc::RecvTimeoutError::Timeout)
    )
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
async fn wait_for_heartbeat_interval(stop: &mut HeartbeatStopReceiver) -> bool {
    if *stop.borrow() {
        return false;
    }
    let timer = crate::sync::sleep(MIGRATION_HEARTBEAT_INTERVAL).fuse();
    let changed = stop.changed().fuse();
    futures_util::pin_mut!(timer, changed);
    select_biased! {
        _ = changed => false,
        _ = timer => true,
    }
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
async fn portable_sleep(duration: Duration) -> Result<(), LixError> {
    let (done_tx, done_rx) = tokio::sync::oneshot::channel();
    crate::background_task::spawn("lix-repository-migration-wait", move || async move {
        std::thread::sleep(duration);
        let _ = done_tx.send(());
    })?;
    done_rx.await.map_err(|_| {
        LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            "repository migration wait task stopped unexpectedly",
        )
    })
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
async fn portable_sleep(duration: Duration) -> Result<(), LixError> {
    crate::sync::sleep(duration).await;
    Ok(())
}

async fn advance_lease<S>(
    storage: &S,
    migrating: &Bytes,
    current: &Bytes,
    next: &Bytes,
) -> Result<(), StorageError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            preconditions: vec![
                Precondition::KeyValueEquals {
                    space: REPOSITORY_EPOCH_SPACE,
                    key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                    expected: migrating.clone(),
                },
                Precondition::KeyValueEquals {
                    space: REPOSITORY_EPOCH_SPACE,
                    key: Key(Bytes::from_static(REPOSITORY_EPOCH_LEASE_KEY)),
                    expected: current.clone(),
                },
            ],
            ..WriteOptions::default()
        })
        .await?;
    put_lease(&mut write, next.clone()).await?;
    write.commit().await?;
    Ok(())
}

async fn publish_pointer_absent<S>(storage: &S, active: &Bytes) -> Result<(), LixError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![Precondition::KeyAbsent {
                space: REPOSITORY_EPOCH_SPACE,
                key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
            }],
            ..WriteOptions::default()
        })
        .await
        .map_err(storage_error)?;
    put_pointer(&mut write, active.clone())
        .await
        .map_err(storage_error)?;
    resolve_exact_pointer_commit(storage, write.commit().await, active)
        .await
        .map_err(storage_error)?;
    Ok(())
}

async fn publish_migration_claim_absent<S>(
    storage: &S,
    migrating: &Bytes,
) -> Result<(), StorageError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![
                Precondition::KeyAbsent {
                    space: REPOSITORY_EPOCH_SPACE,
                    key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                },
                StorageAdapter::<S>::mutation_revision_precondition(None),
            ],
            ..WriteOptions::default()
        })
        .await?;
    put_pointer(&mut write, migrating.clone()).await?;
    put_lease(&mut write, Bytes::from_static(b"0")).await?;
    resolve_exact_pointer_commit(storage, write.commit().await, migrating).await
}

async fn claim_fresh_import<S>(storage: &S, migrating: &Bytes) -> Result<(), LixError>
where
    S: Storage + Clone,
{
    let mut retried_cancelled_handoff = false;
    loop {
        match try_claim_fresh_import(storage, migrating).await {
            Ok(()) => return Ok(()),
            Err(StorageError::PreconditionFailed(failures)) => {
                let Some((state, bytes)) = load_pointer(storage).await? else {
                    // A cancelled importer may release its exact claim between
                    // our failed claim commit and this resolving read. The
                    // control-space precondition is then the only failed item.
                    // Retry the full atomic emptiness check once; a persistent
                    // failure is real pointerless destination state.
                    if !retried_cancelled_handoff
                        && !failures.is_empty()
                        && failures.iter().all(|failure| failure.index == 0)
                    {
                        retried_cancelled_handoff = true;
                        continue;
                    }
                    return Err(nonempty_snapshot_destination());
                };
                retried_cancelled_handoff = false;
                if !matches!(
                    state,
                    PointerState::Migrating {
                        source: EpochBank::Legacy,
                        source_format: 0,
                        ..
                    }
                ) {
                    return Err(nonempty_snapshot_destination());
                }
                wait_for_stale_fresh_import(storage, state, &bytes).await?;
            }
            Err(error) => return Err(storage_error(error)),
        }
    }
}

async fn try_claim_fresh_import<S>(storage: &S, migrating: &Bytes) -> Result<(), StorageError>
where
    S: Storage,
{
    let mut preconditions = Vec::with_capacity(
        crate::storage_spaces::SNAPSHOT_STORAGE_SPACES.len()
            + crate::storage_spaces::RETIRED_STORAGE_SPACES.len()
            + 1,
    );
    preconditions.push(Precondition::RangeEmpty {
        space: REPOSITORY_EPOCH_SPACE,
        range: KeyRange {
            lower: Bound::Unbounded,
            upper: Bound::Unbounded,
        },
    });
    preconditions.extend(
        crate::storage_spaces::SNAPSHOT_STORAGE_SPACES
            .iter()
            .chain(
                crate::storage_spaces::RETIRED_STORAGE_SPACES
                    .iter()
                    .filter(|retired| !retired.emitted_in_lixsnap_v1)
                    .map(|retired| &retired.space),
            )
            .copied()
            .map(|space| Precondition::RangeEmpty {
                space,
                range: KeyRange {
                    lower: Bound::Unbounded,
                    upper: Bound::Unbounded,
                },
            }),
    );
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions,
            ..WriteOptions::default()
        })
        .await?;
    put_pointer(&mut write, migrating.clone()).await?;
    put_lease(&mut write, Bytes::from_static(b"0")).await?;
    resolve_exact_pointer_commit(storage, write.commit().await, migrating).await
}

async fn wait_for_stale_fresh_import<S>(
    storage: &S,
    state: PointerState,
    migrating_bytes: &Bytes,
) -> Result<(), LixError>
where
    S: Storage + Clone,
{
    let mut observed_lease = load_lease(storage).await?;
    let mut missed = 0;
    loop {
        portable_sleep(MIGRATION_HEARTBEAT_INTERVAL).await?;
        match load_pointer(storage).await? {
            Some((_, current)) if current == *migrating_bytes => {}
            _ => return Ok(()),
        }
        let current_lease = load_lease(storage).await?;
        if current_lease != observed_lease {
            observed_lease = current_lease;
            missed = 0;
            continue;
        }
        missed += 1;
        if missed >= MISSED_HEARTBEATS_BEFORE_RECOVERY {
            break;
        }
    }
    match recover_interrupted_migration(
        storage,
        state,
        migrating_bytes,
        observed_lease.as_ref(),
        None,
    )
    .await
    {
        Ok(()) => Ok(()),
        Err(error) => match load_pointer(storage).await? {
            Some((_, current)) if current == *migrating_bytes => {
                if load_lease(storage).await? == observed_lease {
                    Err(error)
                } else {
                    Ok(())
                }
            }
            _ => Ok(()),
        },
    }
}

fn nonempty_snapshot_destination() -> LixError {
    LixError::new(
        LixError::CODE_INVALID_PARAM,
        "snapshot restore destination is not empty",
    )
}

async fn claim_legacy<S>(
    storage: &S,
    revision: Option<Bytes>,
    marker: &Bytes,
    migrating: &Bytes,
) -> Result<(), StorageError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![
                Precondition::KeyAbsent {
                    space: REPOSITORY_EPOCH_SPACE,
                    key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                },
                Precondition::KeyValueEquals {
                    space: crate::init::REPOSITORY_PROTOCOL_SPACE,
                    key: Key(Bytes::from_static(crate::init::REPOSITORY_PROTOCOL_KEY)),
                    expected: marker.clone(),
                },
                StorageAdapter::<S>::mutation_revision_precondition(revision),
            ],
            ..WriteOptions::default()
        })
        .await?;
    put_pointer(&mut write, migrating.clone()).await?;
    put_lease(&mut write, Bytes::from_static(b"0")).await?;
    write
        .put_many(
            REPOSITORY_EPOCH_SPACE,
            single_put(REPOSITORY_EPOCH_SOURCE_MARKER_KEY, marker.clone()),
        )
        .await?;
    write
        .put_many(
            crate::init::REPOSITORY_PROTOCOL_SPACE,
            single_put(
                crate::init::REPOSITORY_PROTOCOL_KEY,
                Bytes::from_static(LEGACY_FENCE),
            ),
        )
        .await?;
    crate::storage_adapter::stage_mutation_revision(&mut write).await?;
    resolve_exact_pointer_commit(storage, write.commit().await, migrating).await
}

async fn activate_legacy<S>(
    storage: &S,
    migrating: &Bytes,
    source_revision: Option<Bytes>,
    active: &Bytes,
) -> Result<(), StorageError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![
                Precondition::KeyValueEquals {
                    space: REPOSITORY_EPOCH_SPACE,
                    key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                    expected: migrating.clone(),
                },
                StorageAdapter::<S>::mutation_revision_precondition(source_revision),
            ],
            ..WriteOptions::default()
        })
        .await?;
    put_pointer(&mut write, active.clone()).await?;
    delete_lease(&mut write).await?;
    resolve_exact_pointer_commit(storage, write.commit().await, active).await
}

async fn rollback_legacy<S>(storage: &S, migrating: &Bytes, marker: &Bytes) -> Result<(), LixError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![Precondition::KeyValueEquals {
                space: REPOSITORY_EPOCH_SPACE,
                key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                expected: migrating.clone(),
            }],
            ..WriteOptions::default()
        })
        .await
        .map_err(storage_error)?;
    write
        .put_many(
            crate::init::REPOSITORY_PROTOCOL_SPACE,
            single_put(crate::init::REPOSITORY_PROTOCOL_KEY, marker.clone()),
        )
        .await
        .map_err(storage_error)?;
    delete_epoch_control(&mut write)
        .await
        .map_err(storage_error)?;
    crate::storage_adapter::stage_mutation_revision(&mut write)
        .await
        .map_err(storage_error)?;
    write.commit().await.map_err(storage_error)?;
    Ok(())
}

async fn replace_pointer<S>(
    storage: &S,
    expected: &Bytes,
    replacement: &Bytes,
) -> Result<(), LixError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![Precondition::KeyValueEquals {
                space: REPOSITORY_EPOCH_SPACE,
                key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                expected: expected.clone(),
            }],
            ..WriteOptions::default()
        })
        .await
        .map_err(storage_error)?;
    put_pointer(&mut write, replacement.clone())
        .await
        .map_err(storage_error)?;
    delete_lease(&mut write).await.map_err(storage_error)?;
    resolve_exact_pointer_commit(storage, write.commit().await, replacement)
        .await
        .map_err(storage_error)?;
    Ok(())
}

async fn delete_pointer<S>(storage: &S, expected: &Bytes) -> Result<(), LixError>
where
    S: Storage,
{
    let mut write = storage
        .begin_write(WriteOptions {
            await_durable: true,
            preconditions: vec![Precondition::KeyValueEquals {
                space: REPOSITORY_EPOCH_SPACE,
                key: Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                expected: expected.clone(),
            }],
            ..WriteOptions::default()
        })
        .await
        .map_err(storage_error)?;
    delete_epoch_control(&mut write)
        .await
        .map_err(storage_error)?;
    write.commit().await.map_err(storage_error)?;
    Ok(())
}

async fn delete_pointer_resolving_outcome<S>(storage: &S, expected: &Bytes) -> Result<(), LixError>
where
    S: Storage,
{
    match delete_pointer(storage, expected).await {
        Ok(()) => Ok(()),
        Err(error) => match load_pointer(storage).await {
            Ok(Some((_, current))) if current == *expected => Err(error),
            Ok(_) => Ok(()),
            Err(inspect_error) => Err(LixError::new(
                error.code.clone(),
                format!("{error}; could not resolve epoch cleanup outcome: {inspect_error}"),
            )),
        },
    }
}

fn combine_cleanup_results(
    cleared: Result<(), LixError>,
    deleted: Result<(), LixError>,
    stopped: Result<(), LixError>,
) -> Result<(), LixError> {
    let mut errors = [cleared.err(), deleted.err(), stopped.err()]
        .into_iter()
        .flatten();
    let Some(first) = errors.next() else {
        return Ok(());
    };
    let code = first.code.clone();
    let mut message = first.to_string();
    for error in errors {
        message.push_str("; additional cleanup failure: ");
        message.push_str(&error.to_string());
    }
    Err(LixError::new(code, message))
}

fn with_cleanup_error(primary: LixError, cleanup: Result<(), LixError>) -> LixError {
    match cleanup {
        Ok(()) => primary,
        Err(cleanup) => LixError::new(
            primary.code.clone(),
            format!("{primary}; snapshot restore cleanup also failed: {cleanup}"),
        ),
    }
}

async fn put_pointer<W>(write: &mut W, bytes: Bytes) -> Result<(), StorageError>
where
    W: StorageWrite,
{
    write
        .put_many(
            REPOSITORY_EPOCH_SPACE,
            single_put(REPOSITORY_EPOCH_KEY, bytes),
        )
        .await
}

async fn put_lease<W>(write: &mut W, bytes: Bytes) -> Result<(), StorageError>
where
    W: StorageWrite,
{
    write
        .put_many(
            REPOSITORY_EPOCH_SPACE,
            single_put(REPOSITORY_EPOCH_LEASE_KEY, bytes),
        )
        .await
}

async fn delete_lease<W>(write: &mut W) -> Result<(), StorageError>
where
    W: StorageWrite,
{
    write
        .delete_many(
            REPOSITORY_EPOCH_SPACE,
            &[
                Key(Bytes::from_static(REPOSITORY_EPOCH_LEASE_KEY)),
                Key(Bytes::from_static(REPOSITORY_EPOCH_SOURCE_MARKER_KEY)),
            ],
        )
        .await
}

async fn delete_epoch_control<W>(write: &mut W) -> Result<(), StorageError>
where
    W: StorageWrite,
{
    write
        .delete_many(
            REPOSITORY_EPOCH_SPACE,
            &[
                Key(Bytes::from_static(REPOSITORY_EPOCH_KEY)),
                Key(Bytes::from_static(REPOSITORY_EPOCH_LEASE_KEY)),
                Key(Bytes::from_static(REPOSITORY_EPOCH_SOURCE_MARKER_KEY)),
            ],
        )
        .await
}

fn single_put(key: &'static [u8], value: Bytes) -> PutBatch {
    PutBatch {
        entries: vec![PutEntry {
            key: Key(Bytes::from_static(key)),
            value: StoredValue { bytes: value },
        }],
    }
}

fn encode_pointer(state: PointerState) -> Bytes {
    let text = match state {
        PointerState::Active {
            bank,
            generation,
            format,
            publication,
        } => match publication {
            Some(publication) => format!(
                "{POINTER_PREFIX}|active|{}|{generation}|{format}|{publication}",
                bank_code(bank)
            ),
            None => format!(
                "{POINTER_PREFIX}|active|{}|{generation}|{format}",
                bank_code(bank)
            ),
        },
        PointerState::Migrating {
            source,
            source_format,
            target,
            generation,
            attempt,
        } => format!(
            "{POINTER_PREFIX}|migrating|{}|{}|{generation}|{source_format}|{attempt}",
            bank_code(source),
            bank_code(target),
        ),
    };
    Bytes::from(text)
}

fn decode_pointer(bytes: &Bytes) -> Result<PointerState, LixError> {
    let text = std::str::from_utf8(bytes).map_err(|_| epoch_error("epoch pointer is not UTF-8"))?;
    let parts = text.split('|').collect::<Vec<_>>();
    if parts.first().copied() != Some(POINTER_PREFIX) {
        return Err(epoch_error("epoch pointer has an unsupported encoding"));
    }
    match parts.get(1).copied() {
        Some("active") if parts.len() == 5 => Ok(PointerState::Active {
            bank: parse_bank(parts[2])?,
            generation: parse_generation(parts[3])?,
            format: parse_format(parts[4])?,
            publication: None,
        }),
        Some("active") if parts.len() == 6 => Ok(PointerState::Active {
            bank: parse_bank(parts[2])?,
            generation: parse_generation(parts[3])?,
            format: parse_format(parts[4])?,
            publication: Some(
                uuid::Uuid::parse_str(parts[5])
                    .map_err(|_| epoch_error("epoch pointer publication is invalid"))?,
            ),
        }),
        Some("migrating") if parts.len() == 7 => Ok(PointerState::Migrating {
            source: parse_bank(parts[2])?,
            target: parse_bank(parts[3])?,
            generation: parse_generation(parts[4])?,
            source_format: parse_format(parts[5])?,
            attempt: uuid::Uuid::parse_str(parts[6])
                .map_err(|_| epoch_error("epoch pointer migration attempt is invalid"))?,
        }),
        _ => Err(epoch_error("epoch pointer state is invalid")),
    }
}

fn parse_generation(value: &str) -> Result<u64, LixError> {
    value
        .parse::<u64>()
        .map_err(|_| epoch_error("epoch pointer generation is invalid"))
}

fn parse_format(value: &str) -> Result<u32, LixError> {
    value
        .parse::<u32>()
        .map_err(|_| epoch_error("epoch pointer format is invalid"))
}

fn bank_code(bank: EpochBank) -> &'static str {
    match bank {
        EpochBank::Legacy => "legacy",
        EpochBank::A => "a",
        EpochBank::B => "b",
    }
}

fn parse_bank(value: &str) -> Result<EpochBank, LixError> {
    match value {
        "legacy" => Ok(EpochBank::Legacy),
        "a" => Ok(EpochBank::A),
        "b" => Ok(EpochBank::B),
        _ => Err(epoch_error("epoch pointer bank is invalid")),
    }
}

fn epoch_error(message: impl Into<String>) -> LixError {
    LixError::new("LIX_ERROR_MIGRATION_FAILED", message.into())
}

fn storage_error(error: StorageError) -> LixError {
    if matches!(
        error,
        StorageError::ReadExpired | StorageError::CommitOutcomeUnknown(_)
    ) {
        return LixError::from(error);
    }
    LixError::new(
        "LIX_ERROR_REPOSITORY_UPGRADE",
        format!("repository upgrade storage error: {error}"),
    )
}

fn is_admission_race(error: &StorageError) -> bool {
    matches!(
        error,
        StorageError::PreconditionFailed(_) | StorageError::WriteConflict | StorageError::Fenced
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage_adapter::StorageWriteOptions;
    use std::future::Future;
    use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};

    #[test]
    fn candidate_epoch_writes_are_durable_and_cover_snapshot_wire_spaces() {
        assert!(durable_candidate_write_options().await_durable);
        assert_eq!(
            epoch_data_spaces().collect::<Vec<_>>().as_slice(),
            crate::storage_spaces::SNAPSHOT_STORAGE_SPACES
        );
    }

    #[derive(Clone, Debug)]
    struct CommitExpiringStorage {
        inner: crate::Memory,
        generation: Arc<AtomicU64>,
        expire_next_page: Arc<AtomicBool>,
    }

    impl CommitExpiringStorage {
        fn new() -> Self {
            Self {
                inner: crate::Memory::new(),
                generation: Arc::new(AtomicU64::new(0)),
                expire_next_page: Arc::new(AtomicBool::new(false)),
            }
        }

        fn expire_next_page(&self) {
            self.expire_next_page.store(true, Ordering::Release);
        }
    }

    struct CommitExpiringRead {
        inner: MemoryRead,
        generation: Arc<AtomicU64>,
        observed_generation: u64,
        expire_next_page: Arc<AtomicBool>,
    }

    impl CommitExpiringRead {
        fn validate(&self) -> Result<(), StorageError> {
            if self.generation.load(Ordering::Acquire) == self.observed_generation {
                Ok(())
            } else {
                Err(StorageError::ReadExpired)
            }
        }
    }

    struct CommitExpiringScan<'a> {
        inner: ScanCursor<'a>,
        generation: Arc<AtomicU64>,
        observed_generation: u64,
        expire_next_page: Arc<AtomicBool>,
    }

    impl StorageScanSource for CommitExpiringScan<'_> {
        fn next_page(
            &mut self,
            limit_rows: usize,
        ) -> std::pin::Pin<Box<dyn Future<Output = Result<ScanChunk, StorageError>> + Send + '_>>
        {
            Box::pin(async move {
                if self.expire_next_page.swap(false, Ordering::AcqRel) {
                    self.generation.fetch_add(1, Ordering::AcqRel);
                    return Err(StorageError::ReadExpired);
                }
                if self.generation.load(Ordering::Acquire) != self.observed_generation {
                    return Err(StorageError::ReadExpired);
                }
                self.inner.next_page(limit_rows).await
            })
        }
    }

    impl StorageRead for CommitExpiringRead {
        fn snapshot_cache_key(&self) -> Option<u128> {
            self.inner.snapshot_cache_key()
        }

        async fn get_many(
            &self,
            requests: &[GetManyRequest<'_>],
        ) -> Result<GetManyResult, StorageError> {
            self.validate()?;
            self.inner.get_many(requests).await
        }

        async fn begin_scan(
            &self,
            space: StorageSpace,
            range: KeyRange,
            opts: BeginScanOptions,
        ) -> Result<ScanCursor<'_>, StorageError> {
            self.validate()?;
            let checked_range = range.clone();
            let inner = self.inner.begin_scan(space, range, opts).await?;
            ScanCursor::from_source(
                checked_range,
                opts.order,
                CommitExpiringScan {
                    inner,
                    generation: Arc::clone(&self.generation),
                    observed_generation: self.observed_generation,
                    expire_next_page: Arc::clone(&self.expire_next_page),
                },
            )
        }
    }

    struct CommitExpiringWrite {
        inner: MemoryWrite,
        generation: Arc<AtomicU64>,
    }

    impl StorageWrite for CommitExpiringWrite {
        async fn put_many(
            &mut self,
            space: StorageSpace,
            entries: PutBatch,
        ) -> Result<(), StorageError> {
            self.inner.put_many(space, entries).await
        }

        async fn replace_many(
            &mut self,
            space: StorageSpace,
            entries: PutBatch,
        ) -> Result<(), StorageError> {
            self.inner.replace_many(space, entries).await
        }

        async fn delete_many(
            &mut self,
            space: StorageSpace,
            keys: &[Key],
        ) -> Result<(), StorageError> {
            self.inner.delete_many(space, keys).await
        }

        async fn delete_range(
            &mut self,
            space: StorageSpace,
            range: KeyRange,
        ) -> Result<(), StorageError> {
            self.inner.delete_range(space, range).await
        }

        async fn commit(self) -> Result<CommitResult, StorageError> {
            let result = self.inner.commit().await?;
            self.generation.fetch_add(1, Ordering::AcqRel);
            Ok(result)
        }

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

    impl Storage for CommitExpiringStorage {
        type Read<'a> = CommitExpiringRead;
        type Write<'a> = CommitExpiringWrite;

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

        async fn begin_read(&self, opts: ReadOptions) -> Result<Self::Read<'_>, StorageError> {
            let inner = self.inner.begin_read(opts).await?;
            Ok(CommitExpiringRead {
                inner,
                generation: Arc::clone(&self.generation),
                observed_generation: self.generation.load(Ordering::Acquire),
                expire_next_page: Arc::clone(&self.expire_next_page),
            })
        }

        async fn begin_write(&self, opts: WriteOptions) -> Result<Self::Write<'_>, StorageError> {
            Ok(CommitExpiringWrite {
                inner: self.inner.begin_write(opts).await?,
                generation: Arc::clone(&self.generation),
            })
        }
    }

    #[derive(Clone)]
    struct PostCommitUnknownStorage {
        inner: crate::Memory,
        commit_fault: Arc<AtomicU8>,
        fail_next_read: Arc<AtomicBool>,
    }

    const COMMIT_FAULT_NONE: u8 = 0;
    const COMMIT_FAULT_PRE_UNKNOWN: u8 = 1;
    const COMMIT_FAULT_POST_UNKNOWN: u8 = 2;
    const COMMIT_FAULT_POST_UNKNOWN_AND_READ: u8 = 3;

    impl PostCommitUnknownStorage {
        fn new() -> Self {
            Self {
                inner: crate::Memory::new(),
                commit_fault: Arc::new(AtomicU8::new(COMMIT_FAULT_NONE)),
                fail_next_read: Arc::new(AtomicBool::new(false)),
            }
        }

        fn fail_next_commit(&self) {
            self.commit_fault
                .store(COMMIT_FAULT_POST_UNKNOWN, Ordering::Release);
        }

        fn fail_next_commit_before_apply(&self) {
            self.commit_fault
                .store(COMMIT_FAULT_PRE_UNKNOWN, Ordering::Release);
        }

        fn fail_next_commit_and_resolution_read(&self) {
            self.commit_fault
                .store(COMMIT_FAULT_POST_UNKNOWN_AND_READ, Ordering::Release);
        }
    }

    struct PostCommitUnknownWrite {
        inner: MemoryWrite,
        commit_fault: u8,
        fail_next_read: Arc<AtomicBool>,
    }

    impl Storage for PostCommitUnknownStorage {
        type Read<'a> = MemoryRead;
        type Write<'a> = PostCommitUnknownWrite;

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

        async fn begin_read(&self, options: ReadOptions) -> Result<Self::Read<'_>, StorageError> {
            if self.fail_next_read.swap(false, Ordering::AcqRel) {
                return Err(StorageError::Io(
                    "injected exact-pointer resolution read failure".to_string(),
                ));
            }
            self.inner.begin_read(options).await
        }

        async fn begin_write(
            &self,
            options: WriteOptions,
        ) -> Result<Self::Write<'_>, StorageError> {
            Ok(PostCommitUnknownWrite {
                inner: self.inner.begin_write(options).await?,
                commit_fault: self.commit_fault.swap(COMMIT_FAULT_NONE, Ordering::AcqRel),
                fail_next_read: Arc::clone(&self.fail_next_read),
            })
        }
    }

    impl StorageWrite for PostCommitUnknownWrite {
        async fn put_many(
            &mut self,
            space: StorageSpace,
            entries: PutBatch,
        ) -> Result<(), StorageError> {
            self.inner.put_many(space, entries).await
        }

        async fn replace_many(
            &mut self,
            space: StorageSpace,
            entries: PutBatch,
        ) -> Result<(), StorageError> {
            self.inner.replace_many(space, entries).await
        }

        async fn delete_many(
            &mut self,
            space: StorageSpace,
            keys: &[Key],
        ) -> Result<(), StorageError> {
            self.inner.delete_many(space, keys).await
        }

        async fn delete_range(
            &mut self,
            space: StorageSpace,
            range: KeyRange,
        ) -> Result<(), StorageError> {
            self.inner.delete_range(space, range).await
        }

        async fn commit(self) -> Result<CommitResult, StorageError> {
            if self.commit_fault == COMMIT_FAULT_PRE_UNKNOWN {
                return Err(StorageError::CommitOutcomeUnknown(
                    "injected pre-commit failure".to_string(),
                ));
            }
            let result = self.inner.commit().await?;
            if self.commit_fault == COMMIT_FAULT_POST_UNKNOWN_AND_READ {
                self.fail_next_read.store(true, Ordering::Release);
            }
            if matches!(
                self.commit_fault,
                COMMIT_FAULT_POST_UNKNOWN | COMMIT_FAULT_POST_UNKNOWN_AND_READ
            ) {
                return Err(StorageError::CommitOutcomeUnknown(
                    "injected post-commit failure".to_string(),
                ));
            }
            Ok(result)
        }

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

    async fn seed_active_v75(storage: &crate::Memory, bank: EpochBank, generation: u64) -> Bytes {
        let adapter = StorageAdapter::for_epoch_unfenced(storage.clone(), bank);
        Engine::initialize_with_adapter(adapter.clone(), None)
            .await
            .unwrap();
        let mut writes = adapter.new_write_set();
        writes.put(
            crate::init::REPOSITORY_PROTOCOL_SPACE,
            crate::init::REPOSITORY_PROTOCOL_KEY,
            crate::init::REPOSITORY_PROTOCOL_V75,
        );
        adapter
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .unwrap();
        let active = encode_pointer(PointerState::Active {
            bank,
            generation,
            format: 75,
            publication: None,
        });
        publish_pointer_absent(storage, &active).await.unwrap();
        active
    }

    #[test]
    fn pointer_encoding_round_trips() {
        for state in [
            PointerState::Active {
                bank: EpochBank::A,
                generation: 7,
                format: 76,
                publication: None,
            },
            PointerState::Active {
                bank: EpochBank::A,
                generation: 7,
                format: 76,
                publication: Some(uuid::Uuid::from_u128(2)),
            },
            PointerState::Migrating {
                source: EpochBank::A,
                source_format: 75,
                target: EpochBank::B,
                generation: 8,
                attempt: uuid::Uuid::from_u128(1),
            },
        ] {
            let bytes = encode_pointer(state);
            assert_eq!(decode_pointer(&bytes).unwrap(), state);
        }

        let first = encode_pointer(PointerState::Migrating {
            source: EpochBank::A,
            source_format: 75,
            target: EpochBank::B,
            generation: 8,
            attempt: uuid::Uuid::from_u128(10),
        });
        let retry = encode_pointer(PointerState::Migrating {
            source: EpochBank::A,
            source_format: 75,
            target: EpochBank::B,
            generation: 8,
            attempt: uuid::Uuid::from_u128(11),
        });
        assert_ne!(first, retry, "migration retries must not reuse a fence");
    }

    #[tokio::test]
    async fn copy_reopens_source_pages_after_target_commits_expire_reads() {
        let storage = CommitExpiringStorage::new();
        let source_seed = StorageAdapter::for_epoch_unfenced(storage.clone(), EpochBank::A);
        let row_count = MAX_SCAN_PAGE_ROWS + 17;
        let mut writes = source_seed.new_write_set();
        for index in 0..row_count {
            let key = u64::try_from(index).unwrap().to_be_bytes();
            let value = [u8::try_from(index % 251).unwrap()];
            writes.put(
                crate::json_store::JSON_SPACE,
                key.as_slice(),
                value.as_slice(),
            );
        }
        source_seed
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .unwrap();

        let migrating = encode_pointer(PointerState::Migrating {
            source: EpochBank::A,
            source_format: crate::init::CURRENT_FORMAT_VERSION,
            target: EpochBank::B,
            generation: 2,
            attempt: uuid::Uuid::from_u128(30),
        });
        publish_migration_claim_absent(&storage, &migrating)
            .await
            .unwrap();
        let source =
            StorageAdapter::for_epoch_migration(storage.clone(), EpochBank::A, migrating.clone());
        let target = StorageAdapter::for_epoch_migration(storage, EpochBank::B, migrating.clone());

        source.storage().expire_next_page();
        copy_repository(&source, &target)
            .await
            .expect("copy must reopen an expired source generation between target pages");

        let read = target.begin_read(ReadOptions::default()).await.unwrap();
        let mut cursor = read
            .begin_scan(
                crate::json_store::JSON_SPACE,
                KeyRange {
                    lower: Bound::Unbounded,
                    upper: Bound::Unbounded,
                },
                BeginScanOptions::default(),
            )
            .await
            .unwrap();
        let copied = cursor.collect_all().await.unwrap();
        assert_eq!(copied.len(), row_count);
        for (index, entry) in copied.into_iter().enumerate() {
            assert_eq!(
                entry.key.0.as_ref(),
                u64::try_from(index).unwrap().to_be_bytes()
            );
            assert_eq!(
                entry.value,
                ProjectedValue::FullValue(Bytes::from(vec![u8::try_from(index % 251).unwrap(),])),
            );
        }
    }

    #[tokio::test]
    async fn stale_epoch_adapter_is_fenced_after_pointer_change() {
        let storage = crate::Memory::new();
        let admitted = admit_repository(&storage, None).await.unwrap();
        let replacement = encode_pointer(PointerState::Active {
            bank: EpochBank::B,
            generation: 2,
            format: crate::init::CURRENT_FORMAT_VERSION,
            publication: None,
        });
        let mut raw = storage.begin_write(WriteOptions::default()).await.unwrap();
        put_pointer(&mut raw, replacement).await.unwrap();
        raw.commit().await.unwrap();

        match admitted.adapter.begin_read(ReadOptions::default()).await {
            Err(error) => assert_eq!(error, StorageError::Fenced),
            Ok(_) => panic!("stale epoch adapter must not admit a new read"),
        }
        assert_eq!(
            admitted.adapter.load_mutation_revision().await.unwrap_err(),
            StorageError::Fenced
        );

        let mut writes = admitted.adapter.new_write_set();
        writes.put(crate::json_store::JSON_SPACE, &b"stale"[..], &b"write"[..]);
        let error = admitted
            .adapter
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .unwrap_err();
        assert_eq!(
            error,
            crate::storage_adapter::StorageWriteSetError::Storage(StorageError::Fenced)
        );
    }

    #[tokio::test]
    async fn retried_migration_fences_every_capability_from_the_previous_attempt() {
        let storage = crate::Memory::new();
        let first = encode_pointer(PointerState::Migrating {
            source: EpochBank::A,
            source_format: 75,
            target: EpochBank::B,
            generation: 8,
            attempt: uuid::Uuid::from_u128(20),
        });
        publish_migration_claim_absent(&storage, &first)
            .await
            .unwrap();
        let stale =
            StorageAdapter::for_epoch_migration(storage.clone(), EpochBank::B, first.clone());
        let retry = encode_pointer(PointerState::Migrating {
            source: EpochBank::A,
            source_format: 75,
            target: EpochBank::B,
            generation: 8,
            attempt: uuid::Uuid::from_u128(21),
        });
        replace_pointer(&storage, &first, &retry).await.unwrap();

        match stale.begin_read(ReadOptions::default()).await {
            Err(error) => assert_eq!(error, StorageError::Fenced),
            Ok(_) => panic!("a prior migration attempt must not admit a new read"),
        }
        assert_eq!(
            stale.load_mutation_revision().await.unwrap_err(),
            StorageError::Fenced
        );
        let mut writes = stale.new_write_set();
        writes.put(crate::json_store::JSON_SPACE, &b"stale"[..], &b"write"[..]);
        assert_eq!(
            stale
                .commit_write_set(writes, StorageWriteOptions::default())
                .await
                .unwrap_err(),
            crate::storage_adapter::StorageWriteSetError::Storage(StorageError::Fenced)
        );
    }

    #[tokio::test]
    async fn failed_candidate_validation_restores_legacy_marker() {
        let storage = crate::Memory::new();
        let mut raw = storage.begin_write(WriteOptions::default()).await.unwrap();
        raw.put_many(
            crate::init::REPOSITORY_PROTOCOL_SPACE,
            single_put(
                crate::init::REPOSITORY_PROTOCOL_KEY,
                Bytes::from_static(crate::init::REPOSITORY_PROTOCOL_V75),
            ),
        )
        .await
        .unwrap();
        raw.commit().await.unwrap();

        let error = match admit_repository(&storage, None).await {
            Ok(_) => panic!("incomplete candidate must fail validation"),
            Err(error) => error,
        };
        assert!(error.message.contains("not initialized"));
        assert!(load_pointer(&storage).await.unwrap().is_none());
        assert_eq!(
            super::super::inspect_lix(&storage).await.unwrap(),
            super::super::MigrationStatus::Required {
                from_version: 75,
                to_version: crate::init::CURRENT_FORMAT_VERSION,
            }
        );
    }

    #[tokio::test]
    async fn interrupted_fresh_claim_rolls_back_for_a_clean_retry() {
        let storage = crate::Memory::new();
        let state = PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(2),
        };
        let bytes = encode_pointer(state);
        publish_migration_claim_absent(&storage, &bytes)
            .await
            .unwrap();

        let lease = load_lease(&storage).await.unwrap().unwrap();
        recover_interrupted_migration(&storage, state, &bytes, Some(&lease), None)
            .await
            .unwrap();
        assert!(load_pointer(&storage).await.unwrap().is_none());
        let admitted = admit_repository(&storage, None).await.unwrap();
        assert!(admitted.report.initialized);
    }

    #[tokio::test]
    async fn fresh_recovery_claims_ownership_before_clearing_candidate() {
        let storage = crate::Memory::new();
        let state = PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(40),
        };
        let bytes = encode_pointer(state);
        publish_migration_claim_absent(&storage, &bytes)
            .await
            .unwrap();
        let candidate =
            StorageAdapter::for_epoch_migration(storage.clone(), EpochBank::A, bytes.clone());
        let mut write = candidate
            .begin_migration_write(WriteOptions::default())
            .await
            .unwrap();
        write
            .put_many(
                crate::json_store::JSON_SPACE,
                single_put(b"candidate", Bytes::from_static(b"preserved")),
            )
            .await
            .unwrap();
        write.commit().await.unwrap();

        let observed = Bytes::from_static(b"0");
        let advanced = Bytes::from_static(b"1");
        advance_lease(&storage, &bytes, &observed, &advanced)
            .await
            .unwrap();
        assert!(
            recover_interrupted_migration(&storage, state, &bytes, Some(&observed), None)
                .await
                .is_err(),
            "a changed lease must defeat stale recovery"
        );

        let read = candidate.begin_read(ReadOptions::default()).await.unwrap();
        let mut cursor = read
            .begin_scan(
                crate::json_store::JSON_SPACE,
                KeyRange {
                    lower: Bound::Unbounded,
                    upper: Bound::Unbounded,
                },
                BeginScanOptions::default(),
            )
            .await
            .unwrap();
        assert_eq!(cursor.collect_all().await.unwrap().len(), 1);

        recover_interrupted_migration(&storage, state, &bytes, Some(&advanced), None)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn cancelled_fresh_import_is_reclaimed_by_direct_retry() {
        let storage = crate::Memory::new();
        let first = begin_fresh_epoch_import(storage.clone()).await.unwrap();
        let first_claim = first.claim.clone();
        drop(first);

        let second = begin_fresh_epoch_import(storage.clone())
            .await
            .expect("a direct retry should reclaim the cancelled import");
        assert_ne!(second.claim, first_claim);
        assert!(
            load_pointer(&storage)
                .await
                .unwrap()
                .is_some_and(|(_, bytes)| bytes == second.claim)
        );
        second.abort().await.unwrap();
    }

    #[tokio::test]
    async fn ambiguous_fresh_claim_commit_is_resolved_as_owned() {
        let storage = PostCommitUnknownStorage::new();
        storage.fail_next_commit();

        let import = begin_fresh_epoch_import(storage.clone())
            .await
            .expect("the exact committed claim resolves ambiguous acknowledgement");
        assert!(
            load_pointer(&storage)
                .await
                .unwrap()
                .is_some_and(|(_, bytes)| bytes == import.claim)
        );
        import.abort().await.unwrap();
    }

    #[tokio::test]
    async fn precommit_unknown_fresh_claim_preserves_unknown_outcome() {
        let storage = PostCommitUnknownStorage::new();
        storage.fail_next_commit_before_apply();

        let error = match begin_fresh_epoch_import(storage.clone()).await {
            Ok(_) => panic!("a pre-commit unknown claim cannot be acknowledged"),
            Err(error) => error,
        };
        assert_eq!(error.code, LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN);
        assert!(load_pointer(&storage).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn ambiguous_fresh_publication_is_resolved_by_attempt_identity() {
        let storage = PostCommitUnknownStorage::new();
        let mut import = begin_fresh_epoch_import(storage.clone()).await.unwrap();
        if let Some(heartbeat) = import.heartbeat.take() {
            heartbeat.stop().await.unwrap();
        }
        let publication = import.publication;
        storage.fail_next_commit();

        import
            .publish(crate::init::CURRENT_FORMAT_VERSION)
            .await
            .expect("the exact active publication resolves ambiguous acknowledgement");
        assert!(matches!(
            load_pointer(&storage).await.unwrap(),
            Some((
                PointerState::Active {
                    publication: Some(observed),
                    ..
                },
                _
            )) if observed == publication
        ));
    }

    #[tokio::test]
    async fn failed_pointer_resolution_read_preserves_unknown_outcome() {
        let storage = PostCommitUnknownStorage::new();
        let migrating = encode_pointer(PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(50),
        });
        publish_migration_claim_absent(&storage, &migrating)
            .await
            .unwrap();
        let active = encode_pointer(PointerState::Active {
            bank: EpochBank::A,
            generation: 1,
            format: crate::init::CURRENT_FORMAT_VERSION,
            publication: Some(uuid::Uuid::from_u128(50)),
        });
        storage.fail_next_commit_and_resolution_read();

        let error = replace_pointer(&storage, &migrating, &active)
            .await
            .unwrap_err();
        assert_eq!(error.code, LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN);
        assert!(error.message.contains("resolution read failed"));
        assert!(
            load_pointer(&storage)
                .await
                .unwrap()
                .is_some_and(|(_, bytes)| bytes == active)
        );
    }

    #[tokio::test]
    async fn old_snapshot_claim_and_activation_resolve_postcommit_unknown() {
        let storage = PostCommitUnknownStorage::new();
        let marker = Bytes::from_static(crate::init::REPOSITORY_PROTOCOL_V75);
        let mut seed = storage.begin_write(WriteOptions::default()).await.unwrap();
        seed.put_many(
            crate::init::REPOSITORY_PROTOCOL_SPACE,
            single_put(crate::init::REPOSITORY_PROTOCOL_KEY, marker.clone()),
        )
        .await
        .unwrap();
        seed.commit().await.unwrap();

        let migrating = encode_pointer(PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 75,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(51),
        });
        storage.fail_next_commit();
        claim_legacy(&storage, None, &marker, &migrating)
            .await
            .expect("the exact old-snapshot claim resolves post-commit unknown");
        let source = StorageAdapter::for_epoch_migration(
            storage.clone(),
            EpochBank::Legacy,
            migrating.clone(),
        );
        let source_revision = source.load_mutation_revision().await.unwrap();
        let active = encode_pointer(PointerState::Active {
            bank: EpochBank::A,
            generation: 1,
            format: crate::init::CURRENT_FORMAT_VERSION,
            publication: None,
        });
        storage.fail_next_commit();
        activate_legacy(&storage, &migrating, source_revision, &active)
            .await
            .expect("the exact old-snapshot activation resolves post-commit unknown");
        assert!(
            load_pointer(&storage)
                .await
                .unwrap()
                .is_some_and(|(_, bytes)| bytes == active)
        );
    }

    #[tokio::test]
    async fn missing_legacy_marker_with_repository_state_fails_closed() {
        let storage = crate::Memory::new();
        let legacy = StorageAdapter::new(storage.clone());
        let mut writes = legacy.new_write_set();
        writes.put(
            crate::json_store::JSON_SPACE,
            &b"preserved"[..],
            &b"repository-state"[..],
        );
        legacy
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .unwrap();

        let error = match admit_repository(&storage, None).await {
            Ok(_) => panic!("nonempty markerless storage must not become a fresh epoch"),
            Err(error) => error,
        };
        assert_eq!(error.code, "LIX_ERROR_UNSUPPORTED_STORAGE_FORMAT");
        assert!(load_pointer(&storage).await.unwrap().is_none());
        assert!(legacy.load_mutation_revision().await.unwrap().is_some());

        let claim = encode_pointer(PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(8),
        });
        assert!(matches!(
            publish_migration_claim_absent(&storage, &claim).await,
            Err(StorageError::PreconditionFailed(_))
        ));
        assert!(load_pointer(&storage).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn interrupted_legacy_claim_restores_the_exact_transitional_marker() {
        let storage = crate::Memory::new();
        let marker = Bytes::from_static(crate::init::REPOSITORY_PROTOCOL_V72_COMMIT_REWRITE);
        let mut seed = storage.begin_write(WriteOptions::default()).await.unwrap();
        seed.put_many(
            crate::init::REPOSITORY_PROTOCOL_SPACE,
            single_put(crate::init::REPOSITORY_PROTOCOL_KEY, marker.clone()),
        )
        .await
        .unwrap();
        seed.commit().await.unwrap();
        let state = PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 72,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(3),
        };
        let bytes = encode_pointer(state);
        claim_legacy(&storage, None, &marker, &bytes).await.unwrap();
        let lease = load_lease(&storage).await.unwrap().unwrap();
        let stored_marker = load_source_marker(&storage).await.unwrap().unwrap();

        recover_interrupted_migration(&storage, state, &bytes, Some(&lease), Some(&stored_marker))
            .await
            .unwrap();

        assert_eq!(
            load_storage_value(
                &storage,
                crate::init::REPOSITORY_PROTOCOL_SPACE,
                crate::init::REPOSITORY_PROTOCOL_KEY,
            )
            .await
            .unwrap(),
            Some(marker),
        );
        assert!(load_pointer(&storage).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn interrupted_active_claim_restores_source_then_upgrades() {
        let storage = crate::Memory::new();
        let active = seed_active_v75(&storage, EpochBank::A, 7).await;
        let state = PointerState::Migrating {
            source: EpochBank::A,
            source_format: 75,
            target: EpochBank::B,
            generation: 8,
            attempt: uuid::Uuid::from_u128(4),
        };
        let migrating = encode_pointer(state);
        replace_pointer(&storage, &active, &migrating)
            .await
            .unwrap();

        let lease = Bytes::from_static(b"0");
        let mut raw = storage.begin_write(WriteOptions::default()).await.unwrap();
        put_lease(&mut raw, lease.clone()).await.unwrap();
        raw.commit().await.unwrap();
        recover_interrupted_migration(&storage, state, &migrating, Some(&lease), None)
            .await
            .unwrap();
        assert_eq!(load_pointer(&storage).await.unwrap().unwrap().1, active);

        let admitted = admit_repository(&storage, None).await.unwrap();
        assert_eq!(admitted.adapter.epoch_bank(), EpochBank::B);
        assert_eq!(
            admitted.report.migration,
            Some(OpenMigrationReport {
                from_format: 75,
                to_format: crate::init::CURRENT_FORMAT_VERSION,
            })
        );
    }

    #[tokio::test]
    async fn concurrent_fresh_opens_converge_on_one_active_epoch() {
        let storage = crate::Memory::new();
        let (first, second) = tokio::join!(
            admit_repository(&storage, None),
            admit_repository(&storage, None)
        );
        let first = first.unwrap();
        let second = second.unwrap();
        assert_eq!(first.adapter.epoch_bank(), EpochBank::A);
        assert_eq!(second.adapter.epoch_bank(), EpochBank::A);
        assert_ne!(first.report.initialized, second.report.initialized);
    }

    #[tokio::test]
    async fn stale_active_upgrade_reenters_admission_after_winner_activates() {
        let storage = crate::Memory::new();
        let stale_active = seed_active_v75(&storage, EpochBank::A, 7).await;
        let winner = StorageAdapter::for_epoch_unfenced(storage.clone(), EpochBank::B);
        Engine::initialize_with_adapter(winner, None).await.unwrap();
        let winner_active = encode_pointer(PointerState::Active {
            bank: EpochBank::B,
            generation: 8,
            format: crate::init::CURRENT_FORMAT_VERSION,
            publication: None,
        });
        replace_pointer(&storage, &stale_active, &winner_active)
            .await
            .unwrap();

        let admitted = migrate_active(&storage, EpochBank::A, 7, 75, stale_active, None)
            .await
            .expect("a losing opener should join the winner's active epoch");

        assert_eq!(admitted.adapter.epoch_bank(), EpochBank::B);
        assert_eq!(admitted.report.migration, None);
    }

    #[test]
    fn pointer_fencing_is_an_admission_race() {
        assert!(is_admission_race(&StorageError::Fenced));
    }

    #[tokio::test]
    async fn open_reports_initialization_after_empty_epoch_publication_restart() {
        let storage = crate::Memory::new();
        let admission = admit_repository(&storage, None).await.unwrap();
        assert!(admission.report.initialized);
        drop(admission);

        let lix = crate::open_lix()
            .with_storage(storage)
            .await
            .expect("open should initialize the already-published empty epoch");
        assert!(lix.open_report().initialized);
        lix.close().await.unwrap();
    }

    #[tokio::test]
    async fn admission_recovers_a_claim_whose_heartbeat_stopped() {
        let storage = crate::Memory::new();
        let state = PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(5),
        };
        let bytes = encode_pointer(state);
        publish_migration_claim_absent(&storage, &bytes)
            .await
            .unwrap();

        let admitted = admit_repository(&storage, None).await.unwrap();
        assert!(admitted.report.initialized);
        assert!(matches!(
            load_pointer(&storage).await.unwrap().unwrap().0,
            PointerState::Active { .. }
        ));
    }

    #[tokio::test]
    async fn live_heartbeat_prevents_recovery_of_a_slow_owner() {
        let storage = crate::Memory::new();
        let state = PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(6),
        };
        let bytes = encode_pointer(state);
        publish_migration_claim_absent(&storage, &bytes)
            .await
            .unwrap();
        let heartbeat = start_migration_heartbeat(storage.clone(), bytes.clone()).unwrap();
        let waiting_storage = storage.clone();
        let waiter = tokio::spawn(async move { admit_repository(&waiting_storage, None).await });

        crate::sync::sleep(Duration::from_millis(250)).await;
        assert_eq!(load_pointer(&storage).await.unwrap().unwrap().1, bytes);
        heartbeat.stop().await.unwrap();
        delete_pointer(&storage, &bytes).await.unwrap();

        let admitted = waiter.await.unwrap().unwrap();
        assert!(admitted.report.initialized);
    }

    #[tokio::test]
    async fn stopping_heartbeat_releases_its_storage_handle() {
        let storage = crate::Memory::new();
        let state = PointerState::Migrating {
            source: EpochBank::Legacy,
            source_format: 0,
            target: EpochBank::A,
            generation: 1,
            attempt: uuid::Uuid::from_u128(7),
        };
        let bytes = encode_pointer(state);
        publish_migration_claim_absent(&storage, &bytes)
            .await
            .unwrap();
        assert_eq!(storage.shared_handle_count(), 1);

        let heartbeat = start_migration_heartbeat(storage.clone(), bytes).unwrap();
        assert_eq!(storage.shared_handle_count(), 2);
        heartbeat.stop().await.unwrap();

        assert_eq!(
            storage.shared_handle_count(),
            1,
            "stop completion must be a barrier after the task-owned handle drops"
        );
    }
}