rabs-cas 2.1.7

Durable RABS content-addressed storage, action-cache indexing, object lifecycle, and publication transactions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
//! `RabsMetadataStore`: the narrow transactional metadata interface, its
//! reference SQLite backend, and the FrankenSQLite differential backend
//! (bead H009; plan §62; risk R59).
//!
//! One generic SQL implementation runs on two engines:
//!
//! - **rusqlite** (bundled C SQLite) — the differential/crash-recovery
//!   TRUTH;
//! - **fsqlite** (FrankenSQLite, pure Rust) — the preferred dogfood,
//!   authoritative only after it passes the identical suite (the H024
//!   gate builds on the harness here).
//!
//! Because both backends share the store logic, the differential harness
//! compares the ENGINES: SQL semantics, constraint behavior, transaction
//! atomicity, and on-disk round-tripping — exactly what the FrankenSQLite
//! gate must prove. The plan's binding constraints encoded here:
//!
//! - one active coordinator authority owns authoritative writes; only it
//!   may create a generation or commit a publication;
//! - `ActionGenerationId` is never reused: a monotone high-water mark
//!   survives tombstoning and store reopen;
//! - the publication row, its serving state, and its durable reachability
//!   pin are written in ONE transaction;
//! - a same-key candidate with a different descriptor digest enters
//!   conflict quarantine — never an overwrite;
//! - attempts are append-only lifecycle records; lease renewals are
//!   strictly monotonic sequence numbers (no wall clocks, risk R127);
//! - migrations are transactional and versioned (`schema_epochs`);
//! - the database never holds large object bytes (digests + scalar
//!   metadata only);
//! - typed digests round-trip with their semantic domain, and a domain
//!   read back that this process never wrote is a fail-closed corruption
//!   error, not a silent re-typing (risk R121).

use std::collections::HashMap;

use rabs_protocol::generation::{
    ActionGeneration, ActionGenerationId, AttemptAuthority, LeaseRenewal, WorkerBootGeneration,
    WorkerIncarnationId,
};
use rabs_protocol::release_authorization::ReleaseVerdict;
use rabs_protocol::result_identity::{DigestAlgorithm, TypedDigest};
use rabs_protocol::serving::ServingValidity;
use rabs_protocol::wire_time::PeerId;
use rabs_protocol::worker_fence::{
    WorkerAdmission, WorkerIncarnationFenceRecord, WorkerLeaseBindingRejection, WorkerSessionOffer,
};

/// Current schema version (v8 = the full H038 authoritative table set;
/// v9 = H040 revisioned authority-bound serving state; v10 = H026
/// append-only divergence incidents; v11 = H029 evidence rows name the
/// canonical result manifest they support; v12 = H032 location rows
/// carry their durability state; v13 = H028 provisional-ancestor
/// lineage + adoption edges; v14 = M004 provisional `.rmeta` upload
/// pins + authorized-visibility grants; v15 = M006 dependent-action
/// provisional-consumption obligations; v16 = M017 transitive
/// pin-lineage closure edges + producer contract bindings on pins;
/// v17 = M020 per-edge min-hop depths (I025 transitive-depth bounds)
/// on the lineage closure; v18 = M019 provisional install journal
/// (edge-local records of outputs installed before lineage closure,
/// with ownership-safe recovery state); v19 = L008 native child
/// bindings gating parent build-script publication; v20 = S022 durable
/// worker boot-generation and active-incarnation fencing; v21 = T038
/// durable clone ambiguity plus normalized worker bindings on attempts
/// (every execution lease links through its attempt); v22 = peer
/// authority incarnation fencing (legacy rows require a newer term);
/// v23 = credential-generation fencing (legacy unknown generations fail closed).
pub const SCHEMA_VERSION: u32 = 25;

/// One transactional, versioned migration step.
pub struct Migration {
    /// Version this step migrates TO.
    pub version: u32,
    /// DDL statements applied inside one transaction.
    pub statements: &'static [&'static str],
}

/// The versioned migration set. Digest columns are always the triple
/// `*_algo TEXT, *_domain TEXT, *_bytes BLOB` plus a derived `*_key TEXT`
/// (domain:hex) used for keys/joins; object bytes NEVER appear here.
pub const MIGRATIONS: &[Migration] = &[
    Migration {
        version: 1,
        statements: &[
            "CREATE TABLE schema_epochs (version INTEGER PRIMARY KEY, applied_seq INTEGER NOT NULL)",
            "CREATE TABLE coordinator_authorities (key TEXT PRIMARY KEY, algo TEXT NOT NULL, \
         domain TEXT NOT NULL, bytes BLOB NOT NULL, cluster_id TEXT NOT NULL, \
         incarnation BLOB NOT NULL, term INTEGER NOT NULL, acquired_seq INTEGER NOT NULL, \
         released INTEGER NOT NULL)",
            "CREATE TABLE action_entries (key TEXT PRIMARY KEY, algo TEXT NOT NULL, \
         domain TEXT NOT NULL, bytes BLOB NOT NULL, key_epoch INTEGER NOT NULL, \
         projection_epoch INTEGER NOT NULL)",
            "CREATE TABLE action_generations (id_hex TEXT PRIMARY KEY, id BLOB NOT NULL, \
         action_key TEXT NOT NULL, authority_key TEXT NOT NULL, tombstoned INTEGER NOT NULL)",
            "CREATE TABLE generation_high_water (kind TEXT PRIMARY KEY, value BLOB NOT NULL)",
            "CREATE TABLE action_attempts (id_hex TEXT PRIMARY KEY, id BLOB NOT NULL, \
         generation_hex TEXT NOT NULL, worker TEXT NOT NULL, seq INTEGER NOT NULL)",
            "CREATE TABLE execution_leases (id_hex TEXT PRIMARY KEY, id BLOB NOT NULL, \
         attempt_hex TEXT NOT NULL, renewal_seq INTEGER NOT NULL, \
         expires_at_seq INTEGER NOT NULL, released INTEGER NOT NULL)",
            "CREATE TABLE action_publications (action_key TEXT PRIMARY KEY, \
         descriptor_algo TEXT NOT NULL, descriptor_domain TEXT NOT NULL, \
         descriptor_bytes BLOB NOT NULL, manifest_algo TEXT NOT NULL, \
         manifest_domain TEXT NOT NULL, manifest_bytes BLOB NOT NULL, \
         winner_generation_hex TEXT NOT NULL, winner_attempt_hex TEXT NOT NULL, \
         result_kind TEXT NOT NULL, pin_hex TEXT NOT NULL)",
            "CREATE TABLE action_serving_states (action_key TEXT PRIMARY KEY, \
         disposition TEXT NOT NULL, version INTEGER NOT NULL)",
            "CREATE TABLE objects (key TEXT PRIMARY KEY, algo TEXT NOT NULL, \
         domain TEXT NOT NULL, bytes BLOB NOT NULL, logical_size INTEGER NOT NULL)",
            "CREATE TABLE object_locations (object_key TEXT NOT NULL, store_path TEXT NOT NULL, \
         verified_seq INTEGER, PRIMARY KEY (object_key, store_path))",
            "CREATE TABLE pins (id_hex TEXT PRIMARY KEY, id BLOB NOT NULL, root_key TEXT NOT NULL, \
         owner TEXT NOT NULL, class TEXT NOT NULL, expires_at_seq INTEGER, \
         released INTEGER NOT NULL)",
            "CREATE TABLE observed_input_recipes (action_key TEXT PRIMARY KEY, \
         recipe_algo TEXT NOT NULL, recipe_domain TEXT NOT NULL, recipe_bytes BLOB NOT NULL)",
            "CREATE TABLE key_breakdowns (action_key TEXT NOT NULL, component TEXT NOT NULL, \
         algo TEXT NOT NULL, domain TEXT NOT NULL, bytes BLOB NOT NULL, \
         PRIMARY KEY (action_key, component))",
            "CREATE TABLE trust_states (action_key TEXT PRIMARY KEY, state TEXT NOT NULL, \
         reason TEXT NOT NULL)",
            "CREATE TABLE quarantines (scope TEXT NOT NULL, subject TEXT NOT NULL, \
         reason TEXT NOT NULL, PRIMARY KEY (scope, subject))",
            "CREATE TABLE verification_samples (action_key TEXT NOT NULL, attempt_hex TEXT NOT NULL, \
         passed INTEGER NOT NULL, seq INTEGER NOT NULL, \
         PRIMARY KEY (action_key, attempt_hex, seq))",
            "CREATE TABLE gc_runs (id INTEGER PRIMARY KEY, seq INTEGER NOT NULL, \
         pinned_roots INTEGER NOT NULL, located_objects INTEGER NOT NULL)",
        ],
    },
    Migration {
        // H011: attempts' evidence bundles are append-only associations; the
        // winner's evidence row is written in the SAME transaction as the
        // publication pointer + pin.
        version: 2,
        statements: &[
            "CREATE TABLE action_evidence_index (action_key TEXT NOT NULL, \
         evidence_algo TEXT NOT NULL, evidence_domain TEXT NOT NULL, \
         evidence_bytes BLOB NOT NULL, generation_hex TEXT NOT NULL, \
         attempt_hex TEXT NOT NULL, PRIMARY KEY (action_key, evidence_domain, evidence_bytes))",
        ],
    },
    Migration {
        // H010: object edges (reachability), location EVIDENCE columns
        // (encoding + quarantine status — never identity), and full pin
        // semantics (evidence, renewal lease, durable-vs-ephemeral,
        // reason).
        version: 3,
        statements: &[
            "CREATE TABLE object_edges (parent_key TEXT NOT NULL, child_key TEXT NOT NULL, \
         kind TEXT NOT NULL, PRIMARY KEY (parent_key, child_key, kind))",
            "ALTER TABLE object_locations ADD COLUMN encoding TEXT NOT NULL DEFAULT 'raw'",
            "ALTER TABLE object_locations ADD COLUMN quarantined INTEGER NOT NULL DEFAULT 0",
            "ALTER TABLE pins ADD COLUMN evidence TEXT",
            "ALTER TABLE pins ADD COLUMN renewal_seq INTEGER NOT NULL DEFAULT 0",
            "ALTER TABLE pins ADD COLUMN durable INTEGER NOT NULL DEFAULT 1",
            "ALTER TABLE pins ADD COLUMN reason TEXT NOT NULL DEFAULT ''",
            "ALTER TABLE gc_runs ADD COLUMN reachable_objects INTEGER NOT NULL DEFAULT 0",
        ],
    },
    Migration {
        // H014: planned + actual reclaim receipts, one row per GC run.
        version: 4,
        statements: &[
            "CREATE TABLE gc_receipts (id INTEGER PRIMARY KEY, seq INTEGER NOT NULL, \
         mode TEXT NOT NULL, planned INTEGER NOT NULL, reclaimed INTEGER NOT NULL, \
         skipped INTEGER NOT NULL, truncated INTEGER NOT NULL)",
        ],
    },
    Migration {
        // H022: mark → tombstone → grace → recheck → unlink. A tombstone
        // is a marked location awaiting its grace window; deletion is
        // NEVER immediate.
        version: 5,
        statements: &["CREATE TABLE gc_tombstones (object_key TEXT NOT NULL, \
         store_path TEXT NOT NULL, marked_seq INTEGER NOT NULL, \
         grace_until_seq INTEGER NOT NULL, PRIMARY KEY (object_key, store_path))"],
    },
    Migration {
        // H034: result digests survive blob eviction so a post-eviction
        // recomputation can be compared — mismatch is a divergence
        // incident, never a silent replacement.
        version: 6,
        statements: &[
            "CREATE TABLE eviction_tombstones (action_key TEXT PRIMARY KEY, \
         semantic_algo TEXT NOT NULL, semantic_domain TEXT NOT NULL, \
         semantic_bytes BLOB NOT NULL, observable_algo TEXT NOT NULL, \
         observable_domain TEXT NOT NULL, observable_bytes BLOB NOT NULL, \
         evicted_seq INTEGER NOT NULL)",
        ],
    },
    Migration {
        // H037: consumed operator-reset generations — the ONLY path that
        // resumes serving over lost/rolled-back authoritative state.
        version: 7,
        statements: &[
            "CREATE TABLE operator_resets (generation INTEGER PRIMARY KEY, \
         applied_seq INTEGER NOT NULL)",
        ],
    },
    Migration {
        // H038: the remainder of the full authoritative table set.
        // Incarnations and peer terms fence stale writers; edge handoffs
        // model at most ONE active row with exactly one NAMED
        // predecessor; trust evaluations are the append-only versioned
        // ledger behind the mutable `trust_states` row. Deterministic
        // failures remain `ResultKind` publications — there is
        // deliberately NO failure table in this set.
        version: 8,
        statements: &[
            "CREATE TABLE peer_authority_high_water (peer_id TEXT PRIMARY KEY, \
         term INTEGER NOT NULL, observed_seq INTEGER NOT NULL)",
            "CREATE TABLE worker_incarnation_fences (worker TEXT PRIMARY KEY, \
         incarnation BLOB NOT NULL)",
            "CREATE TABLE edge_incarnation_fences (edge_id TEXT PRIMARY KEY, \
         incarnation BLOB NOT NULL)",
            "CREATE TABLE edge_handoffs (edge_id TEXT PRIMARY KEY, \
         active_incarnation BLOB NOT NULL, predecessor_incarnation BLOB NOT NULL, \
         begun_seq INTEGER NOT NULL, resolved INTEGER NOT NULL)",
            "CREATE TABLE action_trust_evaluations (action_key TEXT NOT NULL, \
         version INTEGER NOT NULL, state TEXT NOT NULL, reason TEXT NOT NULL, \
         evaluated_seq INTEGER NOT NULL, PRIMARY KEY (action_key, version))",
            "CREATE TABLE operations (id_hex TEXT PRIMARY KEY, id BLOB NOT NULL, \
         kind TEXT NOT NULL, state TEXT NOT NULL, updated_seq INTEGER NOT NULL)",
            "CREATE TABLE edge_subscribers (edge_id TEXT NOT NULL, subscriber TEXT NOT NULL, \
         registered_seq INTEGER NOT NULL, PRIMARY KEY (edge_id, subscriber))",
            "CREATE TABLE manifests (key TEXT PRIMARY KEY, algo TEXT NOT NULL, \
         domain TEXT NOT NULL, bytes BLOB NOT NULL, kind TEXT NOT NULL, \
         entry_count INTEGER NOT NULL)",
            "CREATE TABLE worker_sessions (worker TEXT NOT NULL, incarnation BLOB NOT NULL, \
         started_seq INTEGER NOT NULL, ended_seq INTEGER, \
         PRIMARY KEY (worker, started_seq))",
            "CREATE TABLE worker_capabilities (worker TEXT NOT NULL, capability TEXT NOT NULL, \
         PRIMARY KEY (worker, capability))",
            "CREATE TABLE worker_health_samples (worker TEXT NOT NULL, seq INTEGER NOT NULL, \
         healthy INTEGER NOT NULL, detail TEXT NOT NULL, PRIMARY KEY (worker, seq))",
            "CREATE TABLE decision_receipts (kind TEXT NOT NULL, subject TEXT NOT NULL, \
         seq INTEGER NOT NULL, decision TEXT NOT NULL, reason TEXT NOT NULL, \
         PRIMARY KEY (kind, subject, seq))",
            "CREATE TABLE provenance_edges (from_key TEXT NOT NULL, to_key TEXT NOT NULL, \
         kind TEXT NOT NULL, PRIMARY KEY (from_key, to_key, kind))",
            "CREATE TABLE determinism_audits (action_key TEXT NOT NULL, \
         attempt_hex TEXT NOT NULL, seq INTEGER NOT NULL, verdict TEXT NOT NULL, \
         PRIMARY KEY (action_key, attempt_hex, seq))",
            "CREATE TABLE materialization_records (id_hex TEXT PRIMARY KEY, id BLOB NOT NULL, \
         root_key TEXT NOT NULL, dest_path TEXT NOT NULL, state TEXT NOT NULL, \
         updated_seq INTEGER NOT NULL)",
        ],
    },
    Migration {
        // H040: revisioned authority-bound serving state with a durable
        // conservative validity window (R126). Blocking quarantines are
        // NAMED rows in a junction table — a reason string is never the
        // gate. Legacy rows carry state_revision 0, so every H040 write
        // (revision >= 1) supersedes them.
        version: 9,
        statements: &[
            "ALTER TABLE action_serving_states ADD COLUMN state_revision INTEGER NOT NULL \
         DEFAULT 0",
            "ALTER TABLE action_serving_states ADD COLUMN authority_key TEXT NOT NULL \
         DEFAULT ''",
            "ALTER TABLE action_serving_states ADD COLUMN evaluated_at_micros INTEGER NOT NULL \
         DEFAULT 0",
            "ALTER TABLE action_serving_states ADD COLUMN max_age_micros INTEGER",
            "ALTER TABLE action_serving_states ADD COLUMN clock_uncertainty_micros INTEGER \
         NOT NULL DEFAULT 0",
            "ALTER TABLE action_serving_states ADD COLUMN clock_epoch INTEGER NOT NULL \
         DEFAULT 0",
            "CREATE TABLE serving_blocking_quarantines (action_key TEXT NOT NULL, \
         scope TEXT NOT NULL, subject TEXT NOT NULL, PRIMARY KEY (action_key, scope, subject))",
        ],
    },
    Migration {
        // H026: same-key divergence incidents (I34; risk R63). Append-only:
        // one row per admitted divergence observation, keyed by
        // (action_key, seq); a conflicting rewrite of an existing key is a
        // typed refusal. Both candidates' manifest/evidence keys and the
        // candidate-preservation pin are NAMED in the row, so the incident
        // is auditable after the offer path returns.
        version: 10,
        statements: &[
            "CREATE TABLE divergence_incidents (action_key TEXT NOT NULL, \
         seq INTEGER NOT NULL, class TEXT NOT NULL, \
         committed_manifest_key TEXT NOT NULL, candidate_manifest_key TEXT NOT NULL, \
         candidate_evidence_key TEXT NOT NULL, candidate_pin_hex TEXT NOT NULL, \
         generation_hex TEXT NOT NULL, attempt_hex TEXT NOT NULL, detail TEXT NOT NULL, \
         PRIMARY KEY (action_key, seq))",
        ],
    },
    Migration {
        // H029: every evidence row NAMES the canonical result manifest it
        // supports (I37; risks R80/R115). Evidence for a divergence
        // candidate binds to the CANDIDATE manifest, so listing evidence
        // for the committed canonical result can never conflate the two.
        // Legacy rows carry '' (pre-H029 attribution is unknown, never
        // guessed).
        version: 11,
        statements: &[
            "ALTER TABLE action_evidence_index ADD COLUMN manifest_key TEXT NOT NULL DEFAULT ''",
        ],
    },
    Migration {
        // H032: a location row states whether its copy satisfied the FULL
        // durability policy (file + directory fsync) when recorded.
        // Commit acknowledgement gates on durable locations, so a
        // committed pointer can never name an object that only exists in
        // volatile page cache. Legacy rows default to 0: durability is
        // never assumed retroactively.
        version: 12,
        statements: &["ALTER TABLE object_locations ADD COLUMN durable INTEGER NOT NULL DEFAULT 0"],
    },
    Migration {
        // H028: provisional-ancestor lineage (I32; risk R64). A committed
        // consumer NAMES every producer whose provisional output it
        // consumed — rows are written in the SAME transaction as the
        // publication pointer, so the transitive closure walk at a later
        // dependent's commit reads durable truth, never offer-time
        // claims. Adoption edges are the coordinator's explicit,
        // authority-gated declaration that a consumed losing-attempt
        // object is compatible with the winning attempt's committed
        // object for the same logical output.
        version: 13,
        statements: &[
            "CREATE TABLE provisional_ancestry (consumer_action_key TEXT NOT NULL, \
         producer_action_key TEXT NOT NULL, role TEXT NOT NULL, \
         virtual_path BLOB NOT NULL, object_key TEXT NOT NULL, \
         adopted INTEGER NOT NULL, \
         PRIMARY KEY (consumer_action_key, producer_action_key, role, virtual_path))",
            "CREATE TABLE adoption_edges (producer_action_key TEXT NOT NULL, \
         role TEXT NOT NULL, virtual_path BLOB NOT NULL, \
         from_object_key TEXT NOT NULL, to_object_key TEXT NOT NULL, \
         PRIMARY KEY (producer_action_key, role, virtual_path, from_object_key))",
        ],
    },
    Migration {
        // M004: provisional `.rmeta` upload pins (plan §65). One row per
        // candidate pin binding an early metadata object to its full
        // producer identity tuple; grants name the ONLY readers (dependent
        // attempts + the awaiting edge/subscriber) — visibility is closed
        // by default and every read is authorized against this table.
        version: 14,
        statements: &[
            "CREATE TABLE provisional_pins (pin_key TEXT PRIMARY KEY, \
         authority_key TEXT NOT NULL, action_key TEXT NOT NULL, \
         generation_hex TEXT NOT NULL, attempt_hex TEXT NOT NULL, \
         lease_hex TEXT NOT NULL, role INTEGER NOT NULL, \
         virtual_path BLOB NOT NULL, obj_algo TEXT NOT NULL, \
         obj_domain TEXT NOT NULL, obj_bytes BLOB NOT NULL, \
         object_key TEXT NOT NULL, protective_pin_hex TEXT NOT NULL, \
         renewal_seq INTEGER NOT NULL DEFAULT 0, adopted_object_key TEXT, \
         invalidated_reason TEXT, released INTEGER NOT NULL DEFAULT 0)",
            "CREATE TABLE provisional_pin_grants (pin_key TEXT NOT NULL, \
         grantee_kind TEXT NOT NULL, grantee_id TEXT NOT NULL, \
         granted_seq INTEGER NOT NULL, \
         PRIMARY KEY (pin_key, grantee_kind, grantee_id))",
        ],
    },
    Migration {
        // M006: dependent-action provisional obligations. Consuming a
        // provisional output creates ONE row binding the consumer attempt
        // to the producer lineage (action/generation/attempt, logical
        // output, exact object). Open rows block the descendant's terminal
        // paths; resolved rows record the satisfying commit; cancelled
        // rows permanently refuse it (producer lineage failed/superseded).
        version: 15,
        statements: &[
            "CREATE TABLE provisional_obligations (consumer_worker TEXT NOT NULL, \
         consumer_attempt_hex TEXT NOT NULL, pin_key TEXT NOT NULL, \
         producer_action_key TEXT NOT NULL, producer_generation_hex TEXT NOT NULL, \
         producer_attempt_hex TEXT NOT NULL, role INTEGER NOT NULL, \
         virtual_path BLOB NOT NULL, object_key TEXT NOT NULL, \
         status TEXT NOT NULL DEFAULT 'open', resolution_object_key TEXT, \
         created_seq INTEGER NOT NULL, \
         PRIMARY KEY (consumer_worker, consumer_attempt_hex, pin_key))",
        ],
    },
    Migration {
        // M017: transitive pin-lineage closure + producer contract
        // bindings. Every prepared descendant pin materializes the FULL
        // transitive ancestor-pin closure at open time (edges written in
        // the SAME transaction as the pin row, so a tear can never leave
        // a pin without its recorded ancestry), and each pin binds the
        // toolchain/event contract digests its producer ran under — the
        // equality a different-winning-attempt adoption must prove.
        version: 16,
        statements: &[
            "ALTER TABLE provisional_pins ADD COLUMN toolchain_contract_key \
         TEXT NOT NULL DEFAULT ''",
            "ALTER TABLE provisional_pins ADD COLUMN event_contract_key \
         TEXT NOT NULL DEFAULT ''",
            "CREATE TABLE provisional_pin_lineage (descendant_pin_key TEXT NOT NULL, \
         ancestor_pin_key TEXT NOT NULL, \
         PRIMARY KEY (descendant_pin_key, ancestor_pin_key))",
            "CREATE INDEX idx_provisional_pin_lineage_ancestor \
         ON provisional_pin_lineage (ancestor_pin_key)",
        ],
    },
    Migration {
        // M020: per-edge min-hop depths on the materialized closure
        // (I025). Depth is computed at pin-open time by layered BFS over
        // the ancestors' own recorded depths and lets the terminal-gate
        // layer bound lineage-waiting wrappers by TRANSITIVE DEPTH, not
        // just count. Legacy (v16) rows read as depth 1 — a conservative
        // underestimate only for pre-M020 pins, which never carried
        // multi-hop closures anyway.
        version: 17,
        statements: &["ALTER TABLE provisional_pin_lineage ADD COLUMN \
         min_hops INTEGER NOT NULL DEFAULT 1"],
    },
    Migration {
        // M019: provisional install journal (R86). Edge-local record of
        // EVERY output installed to a real path before its lineage
        // closed, keyed by (pin, consumer attempt, exact path) so
        // recovery can be ownership-safe: a path is removed only when
        // its CURRENT bytes still hash to the recorded object AND the
        // path is one this operation recorded; anything else is marked
        // dirty for Cargo revalidation — never guess-deleted.
        version: 18,
        statements: &[
            "CREATE TABLE provisional_install_journal (pin_key TEXT NOT NULL, \
         consumer_worker TEXT NOT NULL, consumer_attempt_hex TEXT NOT NULL, \
         installed_path BLOB NOT NULL, obj_algo TEXT NOT NULL, \
         obj_domain TEXT NOT NULL, obj_bytes BLOB NOT NULL, object_key TEXT NOT NULL, \
         installed_seq INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'installed', \
         PRIMARY KEY (pin_key, consumer_attempt_hex, installed_path))",
            "CREATE INDEX idx_provisional_install_state \
         ON provisional_install_journal (state)",
        ],
    },
    Migration {
        // L008: native child bindings. A build-script (parent) action
        // declares the native child actions whose outputs it consumes;
        // the parent's publication is refused while any binding stays
        // `bound` (child unresolved) and flips to `satisfied` — with an
        // idempotent provenance edge — once the child result commits.
        version: 19,
        statements: &[
            "CREATE TABLE native_child_bindings (parent_action_key TEXT NOT NULL, \
         child_action_key TEXT NOT NULL, bound_seq INTEGER NOT NULL, \
         state TEXT NOT NULL DEFAULT 'bound', \
         PRIMARY KEY (parent_action_key, child_action_key))",
        ],
    },
    Migration {
        // S022/I47: a worker incarnation is random, so it is NOT an
        // ordered high-water value. The durable ordering fence is the
        // worker's boot generation; the random incarnation names the
        // one live session admitted for that identity/generation. Old
        // rows conservatively remain active at generation zero until an
        // exact-incarnation release or a newer boot supersedes them.
        version: 20,
        statements: &[
            "ALTER TABLE worker_incarnation_fences ADD COLUMN \
         highest_boot_generation BLOB NOT NULL DEFAULT X'0000000000000000'",
            "ALTER TABLE worker_incarnation_fences ADD COLUMN \
         active INTEGER NOT NULL DEFAULT 1",
            "ALTER TABLE worker_incarnation_fences ADD COLUMN \
         operator_reenrollment_generation BLOB NOT NULL DEFAULT X'0000000000000000'",
        ],
    },
    Migration {
        // T038/I47: clone detection fences BOTH contenders until a fresh
        // proof selects one. Attempts created before this migration remain
        // NULL-bound and therefore can never acquire/renew a live lease or
        // publish; silently defaulting them to a current worker would turn
        // unknown legacy provenance into authority.
        version: 21,
        statements: &[
            "ALTER TABLE worker_incarnation_fences ADD COLUMN \
         clone_ambiguous INTEGER NOT NULL DEFAULT 1",
            "ALTER TABLE action_generations ADD COLUMN per_key_ordinal BLOB",
            "ALTER TABLE action_attempts ADD COLUMN worker_boot_generation BLOB",
            "ALTER TABLE action_attempts ADD COLUMN worker_incarnation BLOB",
            "ALTER TABLE action_attempts ADD COLUMN execution_lease_hex TEXT",
        ],
    },
    Migration {
        version: 22,
        statements: &["ALTER TABLE peer_authority_high_water ADD COLUMN incarnation BLOB"],
    },
    Migration {
        version: 23,
        statements: &[
            "ALTER TABLE peer_authority_high_water ADD COLUMN credential_generation INTEGER",
        ],
    },
    Migration {
        // T010/bd-iuorn: `pins` is append-only. A released pin is marked
        // and kept, and nothing anywhere deletes from it, so the table
        // grows by one row per pin lifecycle forever. Live PROTECTION
        // stays flat — `gc_snapshot` selects `released = 0` — but it
        // finds those few live rows by scanning a table sized by every
        // lifecycle the deployment has EVER run, so GC cost grows with
        // history rather than with live work.
        //
        // Index the selected column so the collector reads live pins
        // instead of history. Same shape as
        // `idx_provisional_install_state` over `(state)`; deliberately
        // NOT a partial index, so no engine needs to support the
        // `WHERE` form for the A002 differential lanes to agree.
        version: 24,
        statements: &["CREATE INDEX idx_pins_released ON pins (released)"],
    },
    Migration {
        // T011: the durable landing site for the stock-differential
        // corpus gate's verdict. `rabs-replay` mints it, this store
        // keeps it, and the coordinator consults it before serving —
        // the three cannot call each other directly, because rabs-cas
        // must not depend on the replay harness (A002).
        //
        // Keyed by BUILD, one row per build, because a verdict is a
        // statement about a binary. Recording a second verdict for the
        // same build replaces it: a fresh corpus run supersedes an
        // older one rather than accumulating rows whose precedence
        // would then need its own rule.
        //
        // The validity columns mirror `action_serving_states` exactly,
        // so a release verdict expires under the same clock discipline
        // as a publication rather than under a second notion of time.
        version: 25,
        statements: &["CREATE TABLE release_verdicts ( \
         build TEXT PRIMARY KEY, \
         corpus TEXT NOT NULL, \
         replayed INTEGER NOT NULL, \
         explained INTEGER NOT NULL, \
         evaluated_at_micros INTEGER NOT NULL, \
         max_age_micros INTEGER, \
         clock_uncertainty_micros INTEGER NOT NULL, \
         clock_epoch INTEGER NOT NULL)"],
    },
];

impl std::fmt::Display for StoreError {
    /// Delegates to the derived [`Debug`] output: the enum is closed over by
    /// this crate's tests, every variant is information-carrying, and a
    /// hand-written arm list would silently rot as M019/M020 add variants.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "store error: {self:?}")
    }
}

impl std::error::Error for StoreError {}

/// Typed store errors (comparable so the differential harness can assert
/// both backends fail IDENTICALLY).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StoreError {
    /// Engine-level failure (SQL error, I/O), carried verbatim.
    Backend(String),
    /// A different unreleased authority already holds the slot.
    AuthorityHeld {
        /// Digest key of the current holder.
        holder: String,
    },
    /// The presented authority is not the active one.
    NotActiveAuthority,
    /// Generation id at or below the high-water mark (ids are NEVER
    /// reused, even after tombstoning).
    GenerationIdNotAboveHighWater,
    /// The durable global generation identity cannot advance without reuse.
    GenerationIdentityExhausted,
    /// The action's durable ordinal cannot advance without wrapping.
    GenerationOrdinalExhausted,
    /// Attempt id already recorded (attempts are append-only).
    DuplicateAttempt,
    /// Execution lease id already exists.
    DuplicateLease,
    /// Referenced generation does not exist.
    UnknownGeneration,
    /// Referenced generation was closed and may issue no new/renewed work.
    GenerationTombstoned,
    /// Referenced lease does not exist.
    UnknownLease,
    /// The lease row names a different attempt than the presented full
    /// attempt authority.
    LeaseAttemptMismatch,
    /// The attempt row is legacy/unbound or disagrees with the presented
    /// generation/worker tuple.
    AttemptAuthorityMismatch,
    /// A pre-v21 generation or attempt lacks the authority columns needed
    /// to prove a lease binding; legacy uncertainty always fails closed.
    LegacyUnboundAuthority,
    /// No durable worker fence exists for the attempt's worker.
    UnknownWorkerFence,
    /// The attempt's bound worker tuple is stale, inactive, or ambiguous.
    WorkerLeaseRejected(WorkerLeaseBindingRejection),
    /// The renewal sequence carried by an authority-bearing message does
    /// not equal the store's last accepted value.
    LeaseRenewalMismatch,
    /// Lease already released.
    LeaseReleased,
    /// The coordinator's own monotonic deadline has elapsed. Expiry never
    /// grants publication or permits a late renewal to revive the attempt.
    LeaseExpired,
    /// Renewal sequence not strictly greater than the stored one.
    NonMonotonicRenewal,
    /// Referenced pin does not exist.
    UnknownPin,
    /// Pin release attempted by a non-owner.
    PinOwnerMismatch,
    /// Pin already released.
    PinReleased,
    /// Pin renewal sequence not strictly greater than the stored one.
    NonMonotonicPinRenewal,
    /// Operator-reset generation not strictly greater than every
    /// recorded one (replayed or stale proof).
    StaleOperatorReset,
    /// Peer authority term below the recorded per-peer high-water
    /// (a stale view of that peer; H038).
    StalePeerAuthority,
    /// Edge incarnation below the recorded fence, or a handoff whose
    /// active incarnation does not exceed its named predecessor.
    StaleEdgeIncarnation,
    /// An unresolved handoff with different content already exists for
    /// this edge (at most ONE active handoff per edge).
    EdgeHandoffActive,
    /// An adoption edge for this (producer, role, path, from-object)
    /// already exists with a DIFFERENT target object (H028; edges are
    /// never patched).
    AdoptionEdgeConflict,
    /// The handoff's named predecessor is not the edge's fenced
    /// incarnation.
    EdgeHandoffPredecessorMismatch,
    /// No unresolved handoff row matches (edge, active incarnation).
    UnknownEdgeHandoff,
    /// Trust-evaluation version not strictly greater than the stored
    /// maximum for the action (evaluations are append-only history).
    NonMonotonicTrustEvaluation,
    /// Operation id already recorded.
    DuplicateOperation,
    /// Referenced operation does not exist.
    UnknownOperation,
    /// A manifest row exists under this digest with different metadata
    /// (same-digest/different-content is an incident, never an
    /// overwrite).
    ManifestDivergence,
    /// An append-only row exists under this key with different content;
    /// carries the table name for diagnosis.
    AppendConflict(String),
    /// Referenced materialization record does not exist.
    UnknownMaterialization,
    /// Serving-state revision not strictly greater than the stored one
    /// (replayed or stale evaluation; H040).
    StaleServingRevision,
    /// An ordinary serving writer attempted to weaken quarantine without
    /// the verified incident-repair flow. A newer revision is not a receipt.
    QuarantineRequiresRepair,
    /// A named blocking quarantine row does not exist — references are
    /// the authority, so dangling ones are refused at write.
    UnknownQuarantineReference,
    /// A digest domain was read back that this process never wrote —
    /// fail-closed (R121), never silently re-typed.
    DomainNotInterned(String),
    /// Structural corruption (wrong column shape, bad enum tag).
    Corruption(String),
}

/// Outcome of a publication commit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommitOutcome {
    /// Publication + serving state + pin written in one transaction.
    Committed,
    /// Same key, same descriptor digest: idempotent no-op.
    IdempotentDuplicate,
    /// Same key, DIFFERENT descriptor digest: quarantined, original row
    /// untouched.
    ConflictQuarantined,
}

/// Coordinator authority row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityRow {
    /// Canonical digest of the full authority.
    pub digest: TypedDigest,
    /// Cluster identity.
    pub cluster_id: String,
    /// Coordinator incarnation id.
    pub incarnation: u128,
    /// Election/lock term.
    pub term: u64,
    /// Logical sequence at acquisition.
    pub acquired_seq: u64,
}

/// Action-cache entry row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActionEntryRow {
    /// The action key.
    pub action_key: TypedDigest,
    /// Key epoch (retained for inspection/migration; plan §62).
    pub key_epoch: u32,
    /// Projection epoch.
    pub projection_epoch: u32,
}

/// Publication submitted for coordinator-only commit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicationRow {
    /// The action key being answered.
    pub action_key: TypedDigest,
    /// Canonical descriptor digest (conflict identity).
    pub descriptor_digest: TypedDigest,
    /// Canonical result-manifest digest.
    pub manifest_digest: TypedDigest,
    /// Winning attempt's evidence-bundle digest (recorded in the SAME
    /// transaction as the publication pointer; H011).
    pub evidence_digest: TypedDigest,
    /// Winning generation id.
    pub winner_generation: u128,
    /// Winning attempt id.
    pub winner_attempt: u128,
    /// `"success"` or `"deterministic-failure"` (one publication path for
    /// both; I16).
    pub result_kind: ResultKindTag,
    /// Pin id created in the same transaction as the publication.
    pub pin_id: u128,
    /// Pin owner recorded for the publication reachability root.
    pub pin_owner: String,
    /// Verified provisional-ancestor lineage, written in the SAME
    /// transaction as the publication pointer (H028; I32). Empty when
    /// the result consumed no provisional outputs.
    pub provisional_ancestors: Vec<ProvisionalAncestorRow>,
}

/// One verified provisional-ancestor lineage row (H028): the consumer
/// consumed `object_key` as the producer's `(role, virtual_path)`
/// provisional output; `adopted` records that compatibility went through
/// an explicit adoption edge rather than exact-object identity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvisionalAncestorRow {
    /// Digest key of the producer action.
    pub producer_action_key: String,
    /// Role tag of the consumed logical output.
    pub role: String,
    /// Canonical virtual path bytes of the consumed logical output.
    pub virtual_path: Vec<u8>,
    /// Digest key of the exact object the consumer consumed.
    pub object_key: String,
    /// Whether an explicit adoption edge (not exact-object identity)
    /// established compatibility.
    pub adopted: bool,
}

/// One provisional-upload pin row (M004; plan §65): an early `.rmeta`
/// object bound to its full producer identity tuple
/// `(authority, action key, generation, attempt, lease, logical output)`.
/// State columns are read-side facts: `adopted_object_key` records a
/// winner adoption (§65.1), `invalidated_reason` a producer failure or
/// supersession, `released` the post-drain close. The contract keys
/// (M017) bind the toolchain/event contracts the producer ran under;
/// empty on pre-v16 rows, and a different-winning-attempt adoption
/// refuses fail-closed against an unbound pin.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvisionalPinRecord {
    /// Canonical digest key of the identity tuple.
    pub pin_key: String,
    /// Digest key of the minting coordinator authority.
    pub authority_key: String,
    /// Digest key of the producer action.
    pub action_key: String,
    /// Producer generation id (hex).
    pub generation_hex: String,
    /// Producer attempt id (hex).
    pub attempt_hex: String,
    /// Producer execution lease id (hex).
    pub lease_hex: String,
    /// Role tag of the logical output.
    pub role_tag: i64,
    /// Canonical virtual path bytes.
    pub virtual_path: Vec<u8>,
    /// The pinned object (domain-restored digest).
    pub object: TypedDigest,
    /// Derived digest key of [`Self::object`].
    pub object_key: String,
    /// Hex id of the protective row in `pins` keeping this object
    /// GC-safe while the candidate pin is live.
    pub protective_pin_hex: String,
    /// Monotonic renewal sequence.
    pub renewal_seq: u64,
    /// Object key of the committed result that adopted this pin, if any.
    pub adopted_object_key: Option<String>,
    /// Why the producer lineage failed/superseded/lost authority, if it did.
    pub invalidated_reason: Option<String>,
    /// Whether the pin is closed (drained or invalidated).
    pub released: bool,
    /// Digest key of the producer's toolchain contract (F007); empty when
    /// the pin predates v16 or the caller bound no contracts.
    pub toolchain_contract_key: String,
    /// Digest key of the producer's event contract; same binding rules.
    pub event_contract_key: String,
}

/// Insert payload for a new provisional-upload pin. Identity scalars are
/// raw values (hex encoding happens at the SQL boundary); the object is a
/// full typed digest so its domain is interned on write (R121).
///
/// M017: `ancestor_pin_keys` is the COMPLETE transitive ancestor-pin
/// closure of the producing attempt, computed by the caller and written
/// in the SAME transaction as the pin row — a prepared descendant always
/// carries its full lineage, and no tear can strip it. Each entry pairs
/// the ancestor key with its MIN-HOP distance from the new pin (M020):
/// 1 for direct ancestors, min-over-parents otherwise.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvisionalPinInsert {
    /// Canonical digest key of the identity tuple.
    pub pin_key: String,
    /// Digest key of the minting coordinator authority.
    pub authority_key: String,
    /// Digest key of the producer action.
    pub action_key: String,
    /// Producer generation id.
    pub generation: u128,
    /// Producer attempt id.
    pub attempt: u128,
    /// Producer execution lease id.
    pub lease: u128,
    /// Role tag of the logical output.
    pub role_tag: i64,
    /// Canonical virtual path bytes.
    pub virtual_path: Vec<u8>,
    /// The pinned object.
    pub object: TypedDigest,
    /// Deterministic id of the protective `pins` row (derived from the
    /// pin digest by the caller).
    pub protective_pin_id: u128,
    /// Human-auditable reason stored with the protective pin.
    pub reason: String,
    /// Digest key of the producer's toolchain contract (F007); empty when
    /// unbound — different-winner adoption then refuses fail-closed.
    pub toolchain_contract_key: String,
    /// Digest key of the producer's event contract; empty when unbound.
    pub event_contract_key: String,
    /// Complete transitive ancestor-pin closure (M017): (ancestor key,
    /// min-hop distance from this pin) pairs, sorted for deterministic
    /// SQL ordering. Distances feed I025 transitive-depth bounds.
    pub ancestor_pin_keys: Vec<(String, u64)>,
}
/// One dependent-action provisional-consumption obligation (M006; plan
/// §65): the consumer attempt consumed `object_key` as the producer
/// tuple's provisional `(role, virtual_path)` output. Status lifecycle:
/// `open` (blocks descendant terminal paths) → `resolved` (producer
/// committed/adoption satisfied the lineage with `resolution_object_key`)
/// or `cancelled` (producer failed/superseded — the descendant is refused,
/// never published).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvisionalObligationRow {
    /// Worker running the consuming attempt.
    pub consumer_worker: String,
    /// Consuming attempt id (hex).
    pub consumer_attempt_hex: String,
    /// Canonical key of the consumed provisional pin.
    pub pin_key: String,
    /// Digest key of the producer action.
    pub producer_action_key: String,
    /// Producer generation id (hex).
    pub producer_generation_hex: String,
    /// Producer attempt id (hex).
    pub producer_attempt_hex: String,
    /// Role tag of the consumed logical output.
    pub role_tag: i64,
    /// Canonical virtual path bytes.
    pub virtual_path: Vec<u8>,
    /// Digest key of the exact object consumed.
    pub object_key: String,
    /// Lifecycle status (`open` | `resolved` | `cancelled`).
    pub status: String,
    /// Object key of the commit that resolved the obligation, if resolved.
    pub resolution_object_key: Option<String>,
    /// Coordinator sequence at consumption.
    pub created_seq: u64,
}

/// Insert payload for one consumption obligation (identity scalars raw;
/// encoding at the SQL boundary).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvisionalObligationInsert {
    /// Worker running the consuming attempt.
    pub consumer_worker: String,
    /// Consuming attempt id.
    pub consumer_attempt: u128,
    /// Canonical key of the consumed provisional pin.
    pub pin_key: String,
    /// Digest key of the producer action.
    pub producer_action_key: String,
    /// Producer generation id.
    pub producer_generation: u128,
    /// Producer attempt id.
    pub producer_attempt: u128,
    /// Role tag of the consumed logical output.
    pub role_tag: i64,
    /// Canonical virtual path bytes.
    pub virtual_path: Vec<u8>,
    /// Digest key of the exact object consumed.
    pub object_key: String,
    /// Coordinator sequence at consumption.
    pub created_seq: u64,
}

/// One provisional install-journal row (M019/R86): an output this
/// operation installed to a REAL path before its lineage closed.
/// `object` is the identity the installed bytes had at record time;
/// recovery removes the path only when current bytes still hash to it,
/// otherwise marks the row dirty for Cargo revalidation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvisionalInstallRecord {
    /// Pin whose lineage the installed output belonged to.
    pub pin_key: String,
    /// Worker running the consuming/installing attempt.
    pub consumer_worker: String,
    /// Installing attempt id (hex).
    pub consumer_attempt_hex: String,
    /// Exact recorded path bytes (full path; recovery never touches
    /// anything not recorded verbatim).
    pub installed_path: Vec<u8>,
    /// Identity of the installed bytes at record time.
    pub object: TypedDigest,
    /// Derived digest key of [`Self::object`].
    pub object_key: String,
    /// Coordinator sequence at install.
    pub installed_seq: u64,
    /// Lifecycle state (`installed` | `removed` | `dirty`).
    pub state: String,
}

/// Insert payload for one provisional install journal row (identity
/// scalars raw; encoding at the SQL boundary).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvisionalInstallInsert {
    /// Pin whose lineage the installed output belongs to.
    pub pin_key: String,
    /// Worker running the installing attempt.
    pub consumer_worker: String,
    /// Installing attempt id.
    pub consumer_attempt: u128,
    /// Exact recorded path bytes.
    pub installed_path: Vec<u8>,
    /// Identity of the installed bytes (recomputed from disk by the
    /// caller at record time — journal what IS there).
    pub object: TypedDigest,
    /// Coordinator sequence at install.
    pub installed_seq: u64,
}

/// Result kind tag persisted with a publication.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResultKindTag {
    /// Successful result.
    Success,
    /// Admitted deterministic failure.
    DeterministicFailure,
}

impl ResultKindTag {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::DeterministicFailure => "deterministic-failure",
        }
    }
}

/// Quarantine scope: distinct selection rules per scope (risk R51).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuarantineScope {
    /// One stored location is suspect.
    Location,
    /// A logical object/manifest is suspect.
    LogicalObject,
    /// An action entry is suspect.
    ActionEntry,
}

impl QuarantineScope {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Location => "location",
            Self::LogicalObject => "logical-object",
            Self::ActionEntry => "action-entry",
        }
    }
}

/// Existence + tombstone state of a generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GenerationState {
    /// Whether the generation is tombstoned.
    pub tombstoned: bool,
}

/// Observable lease state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LeaseState {
    /// Whether the lease has been released.
    pub released: bool,
    /// Last accepted renewal sequence.
    pub renewal_seq: u64,
    /// Deadline on the granting coordinator's own monotonic millisecond clock.
    /// The schema's historical `expires_at_seq` column stores this value; it
    /// is independent of receipt sequences and peer/wall-clock timestamps.
    pub expires_at_own_monotonic_ms: u64,
}

/// One pin row as the lease layer sees it (H041).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PinRow {
    /// Pin root digest key.
    pub root_key: String,
    /// Owner identity string.
    pub owner: String,
    /// Pin class (e.g. `"action-publication"`).
    pub class: String,
    /// Expiry sequence, if any.
    pub expires_at_seq: Option<u64>,
    /// Whether the pin has been released.
    pub released: bool,
    /// Last accepted renewal sequence.
    pub renewal_seq: u64,
}

/// One tombstoned location awaiting (or past) its grace window (H022).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GcTombstoneRow {
    /// Object digest key.
    pub object_key: String,
    /// Store path of the marked copy.
    pub store_path: String,
    /// Sequence at marking.
    pub marked_seq: u64,
    /// First sequence at which unlink may proceed.
    pub grace_until_seq: u64,
}

/// One planned-vs-actual GC reclaim receipt (H014).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GcReceiptRow {
    /// Logical sequence of the run.
    pub seq: u64,
    /// `"normal"` or `"emergency"`.
    pub mode: String,
    /// Locations the plan intended to reclaim.
    pub planned: u64,
    /// Locations actually reclaimed.
    pub reclaimed: u64,
    /// Planned locations skipped at execution time.
    pub skipped: u64,
    /// Whether the plan was truncated by the reclaim budget.
    pub truncated: bool,
}

/// GC snapshot: what the collector must preserve.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GcSnapshot {
    /// Unreleased pin roots (digest keys).
    pub pinned_roots: Vec<String>,
    /// Objects with at least one recorded location (digest keys).
    pub located_objects: Vec<String>,
    /// Closure of the unreleased pin roots over `object_edges` (digest
    /// keys, sorted): what GC must preserve beyond the roots themselves.
    pub reachable_from_pins: Vec<String>,
}

/// One row of a reconciliation scan (checked against filesystem reality).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReconciliationRow {
    /// Object digest key.
    pub object_key: String,
    /// Recorded store path.
    pub store_path: String,
    /// Last verification sequence, if any.
    pub verified_seq: Option<u64>,
    /// Storage encoding of this copy (location EVIDENCE, never identity).
    pub encoding: String,
    /// Whether this location (this COPY, not the object) is quarantined.
    pub quarantined: bool,
}

/// One versioned trust evaluation (H038). The mutable `trust_states`
/// row is the CURRENT state; this is the append-only ledger behind it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrustEvaluationRow {
    /// Strictly increasing evaluation version for the action.
    pub version: u32,
    /// Evaluated trust state.
    pub state: String,
    /// Why this evaluation was reached.
    pub reason: String,
    /// Logical sequence of the evaluation.
    pub evaluated_seq: u64,
}

/// The unresolved handoff for an edge: exactly one active incarnation
/// and exactly one NAMED predecessor (H038).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EdgeHandoffRow {
    /// Incarnation taking over the edge.
    pub active_incarnation: u128,
    /// The named predecessor incarnation being replaced.
    pub predecessor_incarnation: u128,
    /// Logical sequence when the handoff began.
    pub begun_seq: u64,
}

/// One revisioned, authority-bound serving-state record (H040). The
/// legacy `disposition`-only rows read back with `state_revision` 0 and
/// an empty authority key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServingRecordRow {
    /// Serving disposition string (`"servable"`, `"evidence-pending"`,
    /// `"quarantined"`, ...).
    pub disposition: String,
    /// Monotonic revision; replays are refused, never overwritten.
    pub state_revision: u64,
    /// Digest key of the authority that evaluated this state.
    pub authority_key: String,
    /// Conservative durable validity window (R126).
    pub validity: ServingValidity,
    /// NAMED blocking quarantine rows (scope tag, subject), sorted. The
    /// references are the gate — a reason string never is.
    pub blocking: Vec<(String, String)>,
}

/// One append-only same-key divergence incident (H026; I34/R63). The
/// committed candidate stays the published row; the offered candidate is
/// preserved under the named pin — neither is ever patched in place.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DivergenceIncidentRow {
    /// Action key (digest key form) the divergence was observed on.
    pub action_key: String,
    /// Logical sequence of the observation (part of the primary key).
    pub seq: u64,
    /// Divergence class tag (`"semantic"`, `"observable-only"`,
    /// `"projection-completeness"`).
    pub class: String,
    /// Manifest digest key of the already-committed candidate.
    pub committed_manifest_key: String,
    /// Manifest digest key of the offered (losing) candidate.
    pub candidate_manifest_key: String,
    /// Evidence-bundle digest key of the offered candidate.
    pub candidate_evidence_key: String,
    /// Hex id of the durable candidate-preservation pin.
    pub candidate_pin_hex: String,
    /// Offering generation id, hex.
    pub generation_hex: String,
    /// Offering attempt id, hex.
    pub attempt_hex: String,
    /// Human-readable incident detail.
    pub detail: String,
}

/// One recorded verification sample (H033 trust-evaluation input).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerificationSampleRow {
    /// Attempt id, hex.
    pub attempt_hex: String,
    /// Whether the verification passed.
    pub passed: bool,
    /// Logical sequence of the sample.
    pub seq: u64,
}

/// The narrow transactional metadata interface (plan §62). Every method
/// is one transaction in the backing engine.
pub trait RabsMetadataStore {
    /// Applied schema version.
    fn schema_version(&mut self) -> Result<u32, StoreError>;

    /// Raw read-only SQL over the store backend (`?1..?N` placeholders).
    /// Escape hatch for operator surfaces (e.g. `rch rabs gc` receipts)
    /// whose schemas are owned by the rch crate, not by typed methods here.
    fn query(&mut self, sql: &str, params: &[SqlValue]) -> Result<Vec<Vec<SqlValue>>, StoreError>;

    /// Declare a digest domain this process is prepared to read back.
    ///
    /// Restoring a stored digest requires the READING process to already
    /// know its domain as a `&'static str` (R121: a domain a process
    /// never named cannot be silently re-typed on read — the read fails
    /// with [`StoreError::DomainNotInterned`]). Writes intern implicitly,
    /// which is enough within one incarnation; a FRESH process that must
    /// read rows an earlier incarnation wrote — the coordinator reading
    /// back the authority it left behind, at boot, before it has written
    /// anything — declares them here first.
    ///
    /// This does not weaken the fence: the caller can only pass a
    /// `'static` domain its own code holds, so an unknown domain in the
    /// database still cannot be restored.
    fn intern_domain(&mut self, domain: &'static str);

    /// Acquire the coordinator authority slot. Refused while a DIFFERENT
    /// unreleased authority holds it; re-acquiring the same digest is
    /// idempotent.
    fn acquire_authority(&mut self, row: &AuthorityRow) -> Result<(), StoreError>;

    /// Release an authority (by digest).
    fn release_authority(&mut self, digest: &TypedDigest) -> Result<(), StoreError>;

    /// The active (unreleased) authority, if any.
    fn active_authority(&mut self) -> Result<Option<AuthorityRow>, StoreError>;

    /// Insert or update an action entry.
    fn upsert_action_entry(&mut self, row: &ActionEntryRow) -> Result<(), StoreError>;

    /// Look up an action entry.
    fn lookup_action(&mut self, key: &TypedDigest) -> Result<Option<ActionEntryRow>, StoreError>;

    /// Create a generation. Coordinator-only; the id must be strictly
    /// above the never-reuse high-water mark.
    fn create_generation(
        &mut self,
        authority: &TypedDigest,
        id: u128,
        action_key: &TypedDigest,
    ) -> Result<(), StoreError>;

    /// Create a generation with its full v21 authority binding. Unlike
    /// [`Self::create_generation`], this persists the diagnostic ordinal;
    /// only bound generations may receive live execution leases.
    fn create_bound_generation(
        &mut self,
        authority: &TypedDigest,
        generation: &ActionGeneration,
        action_key: &TypedDigest,
    ) -> Result<(), StoreError>;

    /// Allocate and insert a bound generation atomically. The global identity
    /// and per-key ordinal advance from durable history, including tombstones,
    /// independently of process clocks and coordinator restarts.
    fn allocate_bound_generation(
        &mut self,
        authority: &TypedDigest,
        action_key: &TypedDigest,
    ) -> Result<ActionGeneration, StoreError>;

    /// Tombstone a generation (the id stays burned forever).
    fn tombstone_generation(&mut self, id: u128) -> Result<(), StoreError>;

    /// G020/R120: on a coordinator term/incarnation change, close every
    /// still-ACTIVE generation created under any authority other than
    /// `active`. Returns how many generations were closed. Idempotent:
    /// already-tombstoned generations are left alone, and the active
    /// authority's own generations are never touched. Publication-eligible
    /// work reissues only in fresh generations minted under `active`
    /// (whose ids sit above the never-reuse high-water mark).
    fn close_generations_for_other_authorities(
        &mut self,
        active: &TypedDigest,
    ) -> Result<u64, StoreError>;

    /// Record an attempt without granting an execution lease (append-only;
    /// duplicate id is an error). This observational/recovery seam leaves
    /// the v21 authority-binding columns NULL, so the row can never pass a
    /// lease or publication gate. Live admission must use
    /// [`Self::admit_attempt_lease`].
    fn record_attempt(
        &mut self,
        id: u128,
        generation: u128,
        worker: &str,
        seq: u64,
    ) -> Result<(), StoreError>;

    /// Atomically record an attempt and acquire its execution lease after
    /// validating the full authority, generation, and exact active,
    /// non-ambiguous worker tuple. The deadline is measured only on the
    /// granting coordinator's own monotonic clock; `recorded_seq` is unrelated
    /// causal history. The live coordinator derives the deadline from a TTL.
    fn admit_attempt_lease(
        &mut self,
        authority: &AttemptAuthority,
        recorded_seq: u64,
        expires_at_own_monotonic_ms: u64,
    ) -> Result<(), StoreError>;

    /// Renew an execution lease after revalidating its normalized
    /// lease-to-attempt link and the attempt's exact current worker fence.
    /// The authority carries the last accepted sequence; `renewal` must
    /// name the same lease and advance it strictly (a durable CAS). The current
    /// lease and its replacement deadline must both be live on the coordinator's
    /// own monotonic clock; late renewal never resurrects expired authority.
    fn renew_attempt_lease(
        &mut self,
        authority: &AttemptAuthority,
        renewal: LeaseRenewal,
        expires_at_own_monotonic_ms: u64,
        own_monotonic_now_ms: &dyn Fn() -> u64,
    ) -> Result<(), StoreError>;

    /// Release a lease.
    fn release_lease(&mut self, id: u128) -> Result<(), StoreError>;

    /// Coordinator-only atomic publication commit (row + serving state +
    /// winner evidence row + reachability pin in ONE transaction;
    /// conflicts quarantine). Live offer admission supplies
    /// `attempt_authority` and a coordinator-owned monotonic clock callback
    /// so the exact lease deadline and worker fence are revalidated inside
    /// this same transaction. The clock is sampled again before commit;
    /// elapsed validation time cannot extend a lease. `None` is the narrow
    /// metadata repair/fixture seam and grants no worker-originated right.
    fn commit_publication(
        &mut self,
        authority: &TypedDigest,
        attempt_authority: Option<(&AttemptAuthority, &dyn Fn() -> u64)>,
        row: &PublicationRow,
    ) -> Result<CommitOutcome, StoreError>;

    /// Append an evidence-bundle association for an action, bound to the
    /// canonical result manifest (digest key) the evidence supports
    /// (H029; I37). Append-only and first-writer-wins: re-appending the
    /// same evidence digest is an idempotent no-op that NEVER rewrites
    /// the original (manifest, generation, attempt) attribution.
    fn append_evidence(
        &mut self,
        action: &TypedDigest,
        manifest_key: &str,
        evidence: &TypedDigest,
        generation: u128,
        attempt: u128,
    ) -> Result<(), StoreError>;

    /// Append candidate evidence only while its exact lease is live. Action,
    /// generation, and attempt attribution come from the validated authority;
    /// checks before and after the write share its transaction.
    fn append_evidence_for_attempt(
        &mut self,
        authority: &AttemptAuthority,
        manifest_key: &str,
        evidence: &TypedDigest,
        own_monotonic_now_ms: &dyn Fn() -> u64,
    ) -> Result<(), StoreError>;

    /// Whether a publication row exists for an action key.
    fn has_publication(&mut self, action: &TypedDigest) -> Result<bool, StoreError>;

    /// The committed manifest digest key for an action, if published.
    fn published_manifest_key(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Option<String>, StoreError>;

    /// [`Self::published_manifest_key`] addressed by the action's digest
    /// KEY string (H028 transitive walk: recorded lineage rows carry
    /// keys, not typed digests — R121).
    fn published_manifest_key_str(
        &mut self,
        action_key: &str,
    ) -> Result<Option<String>, StoreError>;

    /// Whether a generation exists, and whether it is tombstoned.
    fn generation_state(&mut self, id: u128) -> Result<Option<GenerationState>, StoreError>;

    /// Whether an attempt exists under the given generation.
    fn attempt_exists(&mut self, id: u128, generation: u128) -> Result<bool, StoreError>;

    /// Lease state (released flag, renewal sequence, own-clock deadline).
    fn lease_state(&mut self, id: u128) -> Result<Option<LeaseState>, StoreError>;

    /// Revalidate one authority-bearing attempt/lease against the durable
    /// normalized binding and the worker's current non-ambiguous fence.
    /// The returned state belongs to this exact attempt and lease and must be
    /// strictly before its deadline on the granting coordinator's clock.
    fn validate_attempt_lease(
        &mut self,
        authority: &AttemptAuthority,
        own_monotonic_now_ms: u64,
    ) -> Result<LeaseState, StoreError>;

    /// Whether an object has at least one recorded location.
    fn object_located(&mut self, object: &TypedDigest) -> Result<bool, StoreError>;

    /// Every NON-QUARANTINED stored copy of an object, as
    /// `(store_path, encoding, durable)`, ordered by path so the answer
    /// is stable. A reader (materialization, manifest reload) needs the
    /// path, not just the boolean — and must never be handed a
    /// quarantined copy, which is exactly why this filters the same way
    /// [`RabsMetadataStore::object_located`] does.
    fn object_locations(
        &mut self,
        object: &TypedDigest,
    ) -> Result<Vec<(String, String, bool)>, StoreError>;

    /// Record object metadata (digest + logical size; never bytes).
    fn record_object(&mut self, id: &TypedDigest, logical_size: u64) -> Result<(), StoreError>;

    /// Record a stored location for an object. `encoding` names the
    /// stored representation of this COPY (location evidence — it never
    /// changes the object's logical identity). `durable` states whether
    /// this copy satisfied the FULL durability policy (file + directory
    /// fsync) when recorded (H032) — a claim about THIS copy, never
    /// inferred. Refreshing an existing location preserves its quarantine;
    /// ordinary ingestion or index reconstruction is not incident repair.
    fn add_location(
        &mut self,
        object: &TypedDigest,
        store_path: &str,
        verified_seq: Option<u64>,
        encoding: &str,
        durable: bool,
    ) -> Result<(), StoreError>;

    /// Whether the object has at least one durable, non-quarantined
    /// location (H032: the commit-gate durability check).
    fn object_durably_located(&mut self, object: &TypedDigest) -> Result<bool, StoreError>;

    /// Quarantine (or clear quarantine on) one location. Location
    /// quarantine is evidence about a COPY: the object row and its edges
    /// are untouched by construction.
    fn set_location_quarantined(
        &mut self,
        object: &TypedDigest,
        store_path: &str,
        quarantined: bool,
    ) -> Result<(), StoreError>;

    /// Record a reachability edge between two objects.
    fn add_object_edge(
        &mut self,
        parent: &TypedDigest,
        child: &TypedDigest,
        kind: &str,
    ) -> Result<(), StoreError>;

    /// Create a pin with full H010 semantics.
    #[allow(clippy::too_many_arguments)]
    fn create_pin(
        &mut self,
        id: u128,
        root: &TypedDigest,
        owner: &str,
        class: &str,
        expires_at_seq: Option<u64>,
        evidence: Option<&str>,
        durable: bool,
        reason: &str,
    ) -> Result<(), StoreError>;

    /// Renew a pin's lease: `renewal_seq` must be strictly greater than
    /// the stored one; released pins refuse renewal.
    fn renew_pin(&mut self, id: u128, renewal_seq: u64) -> Result<(), StoreError>;

    /// Full pin row by id (H041 lease judgments).
    fn pin_row(&mut self, id: u128) -> Result<Option<PinRow>, StoreError>;

    /// Release a pin; the owner must match.
    fn release_pin(&mut self, id: u128, owner: &str) -> Result<(), StoreError>;

    /// Store the observed-input recipe digest for an action.
    fn put_recipe(&mut self, action: &TypedDigest, recipe: &TypedDigest) -> Result<(), StoreError>;

    /// Store one component of a key breakdown.
    fn put_key_breakdown(
        &mut self,
        action: &TypedDigest,
        component: &str,
        digest: &TypedDigest,
    ) -> Result<(), StoreError>;

    /// Set trust state for an action.
    fn set_trust(
        &mut self,
        action: &TypedDigest,
        state: &str,
        reason: &str,
    ) -> Result<(), StoreError>;

    /// Add a scoped quarantine row.
    fn add_quarantine(
        &mut self,
        scope: QuarantineScope,
        subject: &str,
        reason: &str,
    ) -> Result<(), StoreError>;

    /// Record a verification sample.
    fn record_verification_sample(
        &mut self,
        action: &TypedDigest,
        attempt: u128,
        passed: bool,
        seq: u64,
    ) -> Result<(), StoreError>;

    /// Canonical evidence-ID keys (`domain:hex`) recorded for an action,
    /// sorted (H033 evidence-set input). Keys, not typed digests, so a
    /// fresh process can enumerate history without re-typing domains it
    /// never wrote (R121).
    fn list_evidence_keys(&mut self, action: &TypedDigest) -> Result<Vec<String>, StoreError>;

    /// Canonical evidence-ID keys (`domain:hex`) bound to ONE canonical
    /// result manifest (digest key), sorted (H029; I37). Divergence
    /// candidates' evidence binds to the candidate manifest, so this view
    /// never conflates evidence across same-key candidates.
    fn list_evidence_keys_for_manifest(
        &mut self,
        manifest_key: &str,
    ) -> Result<Vec<String>, StoreError>;

    /// All verification samples recorded for an action, ordered by
    /// (attempt, seq).
    fn list_verification_samples(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Vec<VerificationSampleRow>, StoreError>;

    /// The worker that ran an attempt (addressed by hex id), if the
    /// attempt exists.
    fn attempt_worker_by_hex(&mut self, attempt_hex: &str) -> Result<Option<String>, StoreError>;

    /// Take a GC snapshot (and record the run).
    fn gc_snapshot(&mut self, seq: u64) -> Result<GcSnapshot, StoreError>;

    /// List location rows for reconciliation against the filesystem.
    fn reconciliation_scan(&mut self) -> Result<Vec<ReconciliationRow>, StoreError>;

    /// Remove one location row (GC reclaim). Works on digest KEYS because
    /// GC plans over snapshot keys, never typed digests. Returns whether
    /// a row was removed.
    fn remove_location_by_key(
        &mut self,
        object_key: &str,
        store_path: &str,
    ) -> Result<bool, StoreError>;

    /// Record a planned-vs-actual GC reclaim receipt (H014).
    fn record_gc_receipt(&mut self, receipt: &GcReceiptRow) -> Result<(), StoreError>;

    /// Mark a location with a tombstone (H022 phase 1): idempotent —
    /// re-marking keeps the ORIGINAL grace deadline.
    fn add_gc_tombstone(
        &mut self,
        object_key: &str,
        store_path: &str,
        marked_seq: u64,
        grace_until_seq: u64,
    ) -> Result<(), StoreError>;

    /// Tombstones whose grace window has elapsed at `now_seq`.
    fn due_gc_tombstones(&mut self, now_seq: u64) -> Result<Vec<GcTombstoneRow>, StoreError>;

    /// Remove a tombstone (after unlink, or as a rescue). Returns whether
    /// a row was removed.
    fn remove_gc_tombstone(
        &mut self,
        object_key: &str,
        store_path: &str,
    ) -> Result<bool, StoreError>;

    /// All publications as (action key, pin hex) pairs (H013 integrity
    /// sweep input).
    fn list_publications(&mut self) -> Result<Vec<(String, String)>, StoreError>;

    /// Action keys whose publication names a `winner_generation` that has
    /// no surviving `action_generations` row (R113 lineage loss).
    ///
    /// A store with publications must be able to account for the
    /// generations that produced them. This is the PRECISE form of that
    /// check: a count-based rule ("are there any generations at all")
    /// misses partial row loss, where some generations survive and the
    /// winner's does not.
    ///
    /// # Errors
    /// Store errors.
    fn publications_missing_their_generation(&mut self) -> Result<Vec<String>, StoreError>;

    /// Released flag of a pin addressed by hex id, if it exists.
    fn pin_released_by_hex(&mut self, pin_hex: &str) -> Result<Option<bool>, StoreError>;

    /// Whether a serving-state row exists for an action key.
    fn has_serving_state_key(&mut self, action_key: &str) -> Result<bool, StoreError>;

    /// Whether at least one evidence row exists for an action key.
    fn has_evidence_key(&mut self, action_key: &str) -> Result<bool, StoreError>;

    /// Total authority rows ever recorded (released or not).
    fn authority_count(&mut self) -> Result<u64, StoreError>;

    /// Total generation rows.
    fn generation_count(&mut self) -> Result<u64, StoreError>;

    /// Whether the generation never-reuse high-water mark exists.
    fn has_generation_high_water(&mut self) -> Result<bool, StoreError>;

    /// Retain a published result's projection digests across blob
    /// eviction (H034). Overwrites an existing tombstone for the key.
    fn record_eviction_tombstone(
        &mut self,
        action: &TypedDigest,
        semantic: &TypedDigest,
        observable: &TypedDigest,
        evicted_seq: u64,
    ) -> Result<(), StoreError>;

    /// The retained (semantic, observable) digests for an action, if a
    /// tombstone exists.
    fn eviction_tombstone(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Option<(TypedDigest, TypedDigest)>, StoreError>;

    /// Consume (remove) an eviction tombstone. Returns whether one
    /// existed.
    fn consume_eviction_tombstone(&mut self, action: &TypedDigest) -> Result<bool, StoreError>;

    /// Record a consumed operator-reset generation (H037). The
    /// generation must be strictly greater than every recorded one —
    /// replayed or stale proofs are refused.
    fn record_operator_reset(&mut self, generation: u64, seq: u64) -> Result<(), StoreError>;

    /// Apply a signature-verified operator reset (H037/S020): atomically
    /// consume `generation` into the reset ledger and rewrite `peer_id`'s
    /// high-water to the offered (credential_generation, term, incarnation).
    /// The CALLER must have verified the cluster-root reset signature;
    /// this API only enforces ledger monotonicity and atomicity. A
    /// generation not strictly above the ledger refuses (replayed proof),
    /// and a non-strictly-increasing pair is rejected outright.
    fn apply_operator_reset_to_peer(
        &mut self,
        authority: &TypedDigest,
        peer_id: &str,
        reset_generation: u64,
        credential_generation: u64,
        term: u64,
        incarnation: u128,
    ) -> Result<(), StoreError>;

    /// Highest consumed operator-reset generation, if any.
    fn highest_operator_reset(&mut self) -> Result<Option<u64>, StoreError>;

    /// Serving disposition for an action key, if a row exists.
    fn serving_disposition_key(&mut self, action_key: &str) -> Result<Option<String>, StoreError>;

    /// Set the serving disposition for an action key. A changed disposition
    /// atomically advances its H040 revision while preserving validity,
    /// authority, and blocking references. Restating the same disposition is
    /// idempotent; a stale prepared renewal cannot erase a newer quarantine.
    /// Ordinary writes cannot weaken either full or presentation quarantine.
    fn set_serving_disposition_key(
        &mut self,
        action_key: &str,
        disposition: &str,
    ) -> Result<(), StoreError>;

    /// Accept a candidate's serving-state change under its exact live lease.
    /// The action comes from the authority, and expiry during the transaction
    /// rolls back the disposition write. Successful commit is the divergence
    /// acceptance point; diagnostic recording may follow that accepted decision.
    fn set_serving_disposition_for_attempt(
        &mut self,
        authority: &AttemptAuthority,
        disposition: &str,
        own_monotonic_now_ms: &dyn Fn() -> u64,
    ) -> Result<(), StoreError>;

    // --- H038: fences, peer high-water, handoffs (authoritative
    // coordination state; writes require the ACTIVE authority) ---

    /// Record an authenticated peer's credential generation, term and incarnation.
    /// Compare generation first, then term; equal pairs require the same incarnation.
    /// The caller must verify the credential chain before recording a new generation.
    /// Legacy rows with unknown generations fail closed; no reset bypass is implied.
    fn record_peer_authority_high_water(
        &mut self,
        authority: &TypedDigest,
        peer_id: &str,
        credential_generation: u64,
        term: u64,
        incarnation: u128,
        observed_seq: u64,
    ) -> Result<(), StoreError>;

    /// The recorded (credential generation, term, `observed_seq`) for a peer.
    fn peer_authority_high_water(
        &mut self,
        peer_id: &str,
    ) -> Result<Option<(u64, u64, u64)>, StoreError>;

    /// Atomically admit a worker session under the active coordinator:
    /// evaluate the durable boot-generation/incarnation fence, advance
    /// it on admission, and append the open session row in the SAME
    /// transaction. Rejections are typed [`WorkerAdmission`] values.
    /// Stale/identity refusals write nothing; clone ambiguity atomically
    /// persists the ambiguity and revokes that worker's live leases while
    /// appending no session row.
    fn admit_worker_session(
        &mut self,
        authority: &TypedDigest,
        offer: &WorkerSessionOffer,
        started_seq: u64,
    ) -> Result<WorkerAdmission, StoreError>;

    /// End the exact admitted worker session and clear the active
    /// incarnation in the SAME transaction. A stale/different session
    /// cannot clear the current incarnation and returns `false`.
    fn release_worker_session(
        &mut self,
        authority: &TypedDigest,
        worker: &PeerId,
        incarnation: WorkerIncarnationId,
        started_seq: u64,
        ended_seq: u64,
    ) -> Result<bool, StoreError>;

    /// The durable worker fence row, if this identity has ever been
    /// admitted.
    fn worker_incarnation_fence(
        &mut self,
        worker: &PeerId,
    ) -> Result<Option<WorkerIncarnationFenceRecord>, StoreError>;

    /// Advance an edge's ordered incarnation fence. A lower incarnation
    /// is refused as stale; equality is an idempotent no-op.
    fn advance_edge_fence(
        &mut self,
        authority: &TypedDigest,
        edge_id: &str,
        incarnation: u128,
    ) -> Result<(), StoreError>;

    /// The fenced incarnation for an edge, if any.
    fn edge_fence(&mut self, edge_id: &str) -> Result<Option<u128>, StoreError>;

    /// Begin an edge handoff: at most ONE unresolved handoff per edge;
    /// the predecessor must be NAMED and must match the edge's fenced
    /// incarnation when a fence exists; the active incarnation must
    /// exceed the predecessor. Identical re-begin is idempotent.
    fn begin_edge_handoff(
        &mut self,
        authority: &TypedDigest,
        edge_id: &str,
        active_incarnation: u128,
        predecessor_incarnation: u128,
        begun_seq: u64,
    ) -> Result<(), StoreError>;

    /// Resolve the unresolved handoff matching (edge, active) and
    /// advance the edge fence to the active incarnation in the SAME
    /// transaction.
    fn resolve_edge_handoff(
        &mut self,
        authority: &TypedDigest,
        edge_id: &str,
        active_incarnation: u128,
    ) -> Result<(), StoreError>;

    /// The unresolved handoff for an edge, if any.
    fn active_edge_handoff(&mut self, edge_id: &str) -> Result<Option<EdgeHandoffRow>, StoreError>;

    // --- H038: versioned trust evaluations (authority-gated ledger) ---

    /// Append a trust evaluation; the version must be strictly greater
    /// than the stored maximum for the action.
    fn append_trust_evaluation(
        &mut self,
        authority: &TypedDigest,
        action: &TypedDigest,
        row: &TrustEvaluationRow,
    ) -> Result<(), StoreError>;

    /// The highest-version trust evaluation for an action, if any.
    fn latest_trust_evaluation(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Option<TrustEvaluationRow>, StoreError>;

    // --- H038: operations (creation is the authoritative admission) ---

    /// Create an operation lifecycle record (coordinator-only;
    /// duplicate ids refused).
    fn create_operation(
        &mut self,
        authority: &TypedDigest,
        id: u128,
        kind: &str,
        state: &str,
        seq: u64,
    ) -> Result<(), StoreError>;

    /// Update an existing operation's state.
    fn update_operation_state(&mut self, id: u128, state: &str, seq: u64)
    -> Result<(), StoreError>;

    /// Current state of an operation, if it exists.
    fn operation_state(&mut self, id: u128) -> Result<Option<String>, StoreError>;

    // --- H038: edge subscribers, manifests, worker records,
    // receipts/audits/provenance, materializations (observational
    // lifecycle; conflicting rewrites are typed refusals, never silent
    // overwrites) ---

    /// Register an edge subscriber. Idempotent: the FIRST registration
    /// sequence wins; re-registration is a no-op.
    fn register_edge_subscriber(
        &mut self,
        edge_id: &str,
        subscriber: &str,
        registered_seq: u64,
    ) -> Result<(), StoreError>;

    /// Remove an edge subscriber. Returns whether a row was removed.
    fn remove_edge_subscriber(
        &mut self,
        edge_id: &str,
        subscriber: &str,
    ) -> Result<bool, StoreError>;

    /// Subscribers registered for an edge, ordered.
    fn list_edge_subscribers(&mut self, edge_id: &str) -> Result<Vec<String>, StoreError>;

    /// Record manifest metadata (digest + kind + entry count; never
    /// manifest bytes). Identical re-record is idempotent; different
    /// content under the same digest is a divergence incident.
    fn record_manifest(
        &mut self,
        manifest: &TypedDigest,
        kind: &str,
        entry_count: u64,
    ) -> Result<(), StoreError>;

    /// Recorded (kind, entry count) for a manifest digest, if any.
    fn manifest_meta(
        &mut self,
        manifest: &TypedDigest,
    ) -> Result<Option<(String, u64)>, StoreError>;

    /// Record a worker session journal row without granting authority.
    /// This is an append-only recovery/fixture seam; live coordinator
    /// admission must use [`Self::admit_worker_session`] so the fence and
    /// journal change atomically. A conflicting rewrite of the same
    /// (worker, start) is refused.
    fn record_worker_session(
        &mut self,
        worker: &str,
        incarnation: u128,
        started_seq: u64,
    ) -> Result<(), StoreError>;

    /// Mark only the journal row ended; this does not clear an active
    /// authority fence. Live teardown must use
    /// [`Self::release_worker_session`]. Returns whether an open session
    /// row was updated.
    fn end_worker_session(
        &mut self,
        worker: &str,
        started_seq: u64,
        ended_seq: u64,
    ) -> Result<bool, StoreError>;

    /// Record a worker capability (idempotent).
    fn record_worker_capability(
        &mut self,
        worker: &str,
        capability: &str,
    ) -> Result<(), StoreError>;

    /// Capabilities recorded for a worker, ordered.
    fn list_worker_capabilities(&mut self, worker: &str) -> Result<Vec<String>, StoreError>;

    /// Record a worker health sample (append-only; conflicting rewrite
    /// refused).
    fn record_worker_health_sample(
        &mut self,
        worker: &str,
        seq: u64,
        healthy: bool,
        detail: &str,
    ) -> Result<(), StoreError>;

    /// Record a decision receipt (append-only; conflicting rewrite
    /// refused).
    fn record_decision_receipt(
        &mut self,
        kind: &str,
        subject: &str,
        seq: u64,
        decision: &str,
        reason: &str,
    ) -> Result<(), StoreError>;

    /// Record a provenance edge between two digests (idempotent).
    fn add_provenance_edge(
        &mut self,
        from: &TypedDigest,
        to: &TypedDigest,
        kind: &str,
    ) -> Result<(), StoreError>;

    /// Record a determinism-audit verdict (append-only; conflicting
    /// rewrite refused).
    fn record_determinism_audit(
        &mut self,
        action: &TypedDigest,
        attempt: u128,
        seq: u64,
        verdict: &str,
    ) -> Result<(), StoreError>;

    /// Create a materialization record. Identical re-create is
    /// idempotent; a different-content duplicate id is refused.
    fn create_materialization(
        &mut self,
        id: u128,
        root: &TypedDigest,
        dest_path: &str,
        state: &str,
        seq: u64,
    ) -> Result<(), StoreError>;

    /// Update an existing materialization's state.
    fn update_materialization_state(
        &mut self,
        id: u128,
        state: &str,
        seq: u64,
    ) -> Result<(), StoreError>;

    /// Current state of a materialization record, if it exists.
    fn materialization_state(&mut self, id: u128) -> Result<Option<String>, StoreError>;

    // --- H040: revisioned authority-bound serving state ---

    /// Write a serving-state record in ONE transaction: the revision
    /// must be strictly greater than the stored one (legacy rows are
    /// revision 0, so H040 records start at 1); every named blocking
    /// quarantine must exist; the record is stamped with the ACTIVE
    /// authority's digest key. Existing blocking references must be retained:
    /// an ordinary renewal cannot release quarantine by omitting a reference.
    /// The reference set and row are updated atomically.
    fn put_serving_record(
        &mut self,
        authority: &TypedDigest,
        action_key: &str,
        disposition: &str,
        state_revision: u64,
        validity: &ServingValidity,
        blocking: &[(QuarantineScope, String)],
    ) -> Result<(), StoreError>;

    /// The full serving record for an action key, if a row exists
    /// (legacy rows read back at revision 0 with defaults).
    fn serving_record(&mut self, action_key: &str) -> Result<Option<ServingRecordRow>, StoreError>;

    // --- T011: durable stock-differential release verdicts ---

    /// Record the corpus gate's verdict for one build, replacing any
    /// earlier verdict for that same build.
    ///
    /// Replacement rather than append is deliberate: a newer corpus run
    /// over the same binary supersedes the older one, and keeping both
    /// would require a precedence rule whose only correct answer is
    /// "the newest", which is what a replace already is.
    ///
    /// Deliberately NOT authority-gated, unlike the publication writes
    /// nearby. A release verdict is produced by CI or an operator
    /// BEFORE and OUTSIDE any coordinator term — requiring the active
    /// authority would mean the gate could only be recorded by the very
    /// process whose right to serve it governs.
    ///
    /// # Errors
    /// [`StoreError`] on a backend failure, or
    /// [`StoreError::Corruption`] if a count exceeds the storable
    /// range.
    fn record_release_verdict(&mut self, verdict: &ReleaseVerdict) -> Result<(), StoreError>;

    /// The recorded verdict for `build`, if any. Returns the row as
    /// stored; whether it AUTHORIZES anything is decided by
    /// [`rabs_protocol::release_authorization::authorization`], never
    /// here — a store that answered "authorized" would be a second
    /// place for that policy to live.
    ///
    /// # Errors
    /// [`StoreError`] on a backend failure or a malformed row.
    fn release_verdict(&mut self, build: &str) -> Result<Option<ReleaseVerdict>, StoreError>;

    // --- H026: same-key divergence incidents + served-consumer
    // provenance (append-only; coordinator-authority-gated writes) ---

    /// Append a divergence incident (H026). Requires the ACTIVE
    /// authority. Identical re-record of an existing (action, seq) row is
    /// idempotent; a conflicting rewrite is a typed refusal — incidents
    /// are never patched.
    fn record_divergence_incident(
        &mut self,
        authority: &TypedDigest,
        row: &DivergenceIncidentRow,
    ) -> Result<(), StoreError>;

    /// All divergence incidents recorded for an action key, ordered by
    /// sequence.
    fn list_divergence_incidents(
        &mut self,
        action_key: &str,
    ) -> Result<Vec<DivergenceIncidentRow>, StoreError>;

    /// Record an explicit adoption edge (H028): the coordinator's
    /// authority-gated declaration that `from_object_key` (a consumed
    /// losing-attempt output) is compatible with `to_object_key` (the
    /// winning attempt's committed object) for the producer's
    /// `(role, virtual_path)` logical output. Idempotent per
    /// (producer, role, path, from) — a conflicting rewrite to a
    /// DIFFERENT target is a typed refusal.
    fn record_adoption_edge(
        &mut self,
        authority: &TypedDigest,
        producer_action_key: &str,
        role: &str,
        virtual_path: &[u8],
        from_object_key: &str,
        to_object_key: &str,
    ) -> Result<(), StoreError>;

    /// Whether an adoption edge exists for exactly this
    /// (producer, role, path, from → to) tuple (H028 commit check).
    fn has_adoption_edge(
        &mut self,
        producer_action_key: &str,
        role: &str,
        virtual_path: &[u8],
        from_object_key: &str,
        to_object_key: &str,
    ) -> Result<bool, StoreError>;
    /// Record (idempotently) that a dependent attempt consumed a
    /// provisional output, creating its DirectProducerCommit obligation
    /// (M006). Repeat reads of the same output by the same attempt do not
    /// duplicate the row.
    fn record_provisional_consumption(
        &mut self,
        consumption: &ProvisionalObligationInsert,
    ) -> Result<(), StoreError>;

    /// All NON-resolved obligations of one consumer attempt, ordered by
    /// (status, pin key): `open` rows block terminal paths, `cancelled`
    /// rows refuse them.
    fn list_open_provisional_obligations(
        &mut self,
        consumer_worker: &str,
        consumer_attempt_hex: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError>;

    /// Resolve every open obligation on one pin (producer committed /
    /// adoption satisfied the lineage); returns how many rows resolved.
    fn resolve_provisional_obligations(
        &mut self,
        pin_key: &str,
        resolution_object_key: &str,
    ) -> Result<usize, StoreError>;

    /// Cancel every open obligation on one pin (producer lineage failed /
    /// superseded / lost authority); returns how many rows cancelled.
    fn cancel_provisional_obligations(&mut self, pin_key: &str) -> Result<usize, StoreError>;

    /// Number of OPEN (unresolved, uncancelled) obligations on one pin —
    /// the consumer-debt figure the §65 drain/GC rule gates on.
    fn count_open_provisional_obligations(&mut self, pin_key: &str) -> Result<usize, StoreError>;

    /// Record (idempotently) one provisional output installed to a real
    /// path before lineage closure (M019/R86). The journal is the
    /// ownership truth for recovery: paths absent from it are never
    /// touched.
    fn insert_provisional_install(
        &mut self,
        install: &ProvisionalInstallInsert,
    ) -> Result<(), StoreError>;

    /// Journal rows for the given pins, ANY state, ordered by
    /// (pin key, attempt, path) — the recovery sweep's input.
    fn list_provisional_installs_for_pins(
        &mut self,
        pin_keys: &[String],
    ) -> Result<Vec<ProvisionalInstallRecord>, StoreError>;

    /// Journal rows in ONE state (e.g. `dirty` for the Cargo
    /// revalidation audit), ordered by (pin key, attempt, path).
    fn list_provisional_installs_by_state(
        &mut self,
        state: &str,
    ) -> Result<Vec<ProvisionalInstallRecord>, StoreError>;

    /// Transition one journal row's state (`installed` → `removed` |
    /// `dirty`). Unknown rows are a typed error — recovery never
    /// invents bookkeeping.
    fn set_provisional_install_state(
        &mut self,
        pin_key: &str,
        consumer_attempt_hex: &str,
        installed_path: &[u8],
        state: &str,
    ) -> Result<(), StoreError>;

    /// Bind native child actions to a parent build-script action
    /// (L008). Idempotent per (parent, child); children are appended to
    /// any existing set.
    fn bind_native_children(
        &mut self,
        parent_action_key: &str,
        child_action_keys: &[String],
        bound_seq: u64,
    ) -> Result<(), StoreError>;

    /// All native child bindings of one parent action with their
    /// states (`bound` | `satisfied`), ordered by child key.
    fn list_native_child_bindings(
        &mut self,
        parent_action_key: &str,
    ) -> Result<Vec<(String, String)>, StoreError>;

    /// Transition one binding's state (`bound` → `satisfied`). Unknown
    /// rows are a typed error.
    fn set_native_child_binding_state(
        &mut self,
        parent_action_key: &str,
        child_action_key: &str,
        state: &str,
    ) -> Result<(), StoreError>;
    /// Open provisional pins minted by ONE action generation (M007
    /// generation-failure invalidation trigger), ordered by pin key.
    fn list_open_provisional_pins_for_action_generation(
        &mut self,
        action_key: &str,
        generation_hex: &str,
    ) -> Result<Vec<ProvisionalPinRecord>, StoreError>;

    /// Open provisional pins of an action across ALL generations (M007
    /// supersession trigger), ordered by pin key.
    fn list_open_provisional_pins_for_action(
        &mut self,
        action_key: &str,
    ) -> Result<Vec<ProvisionalPinRecord>, StoreError>;

    /// Open provisional pins minted under one coordinator authority
    /// (M007 authority-loss trigger), ordered by pin key.
    fn list_open_provisional_pins_for_authority(
        &mut self,
        authority_key: &str,
    ) -> Result<Vec<ProvisionalPinRecord>, StoreError>;

    /// ALL consumption obligations on one pin — every status — the M007
    /// causal-trace record of which dependents started from this output.
    fn list_provisional_obligations_for_pin(
        &mut self,
        pin_key: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError>;

    /// Ancestor pin keys of one provisional pin with their min-hop
    /// distances (M017/M020): the materialized transitive closure
    /// recorded at open time, ordered by key.
    fn list_provisional_pin_ancestors(
        &mut self,
        descendant_pin_key: &str,
    ) -> Result<Vec<(String, u64)>, StoreError>;

    /// Longest min-hop chain in one pin's recorded closure — the pin's
    /// transitive lineage depth (M020/I025). Zero for a root producer.
    fn provisional_pin_closure_depth(
        &mut self,
        descendant_pin_key: &str,
    ) -> Result<u64, StoreError>;

    /// Descendant pin keys whose recorded closure contains this pin
    /// (M017) — the reverse edge that makes lineage invalidation cascade
    /// transitively. Ordered by key.
    fn list_provisional_pin_descendants(
        &mut self,
        ancestor_pin_key: &str,
    ) -> Result<Vec<String>, StoreError>;

    /// All NON-resolved obligations of ONE consuming attempt regardless
    /// of worker (M017): attempt ids are globally unique, so lineage
    /// closure walks key on the attempt alone. Ordered by pin key.
    fn list_open_provisional_obligations_by_attempt(
        &mut self,
        consumer_attempt_hex: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError>;

    /// ALL obligations of ONE consuming attempt regardless of worker or
    /// status (M020): the terminal-delivery gate verifies each row's
    /// final state, including that `resolved` rows resolved to the EXACT
    /// consumed object. Ordered by (status, pin key).
    fn list_provisional_obligations_by_attempt_all(
        &mut self,
        consumer_attempt_hex: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError>;

    /// The recorded provisional-ancestor lineage of a committed consumer
    /// (H028), ordered by (producer, role, path) — input to the
    /// transitive closure walk at a dependent's commit.
    fn list_provisional_ancestors(
        &mut self,
        consumer_action_key: &str,
    ) -> Result<Vec<ProvisionalAncestorRow>, StoreError>;

    /// One provisional-upload pin row by canonical key (M004).
    fn provisional_pin_row(
        &mut self,
        pin_key: &str,
    ) -> Result<Option<ProvisionalPinRecord>, StoreError>;

    /// Register a provisional-upload pin AND its protective `pins` row in
    /// ONE transaction (M004): the object is GC-safe from the instant the
    /// registry row exists, and no tear can leave one without the other.
    fn insert_provisional_pin(&mut self, pin: &ProvisionalPinInsert) -> Result<(), StoreError>;

    /// Grant one reader visibility of a provisional output (M004). The
    /// grant table IS the authorization truth; readers absent from it are
    /// refused.
    fn record_provisional_grant(
        &mut self,
        pin_key: &str,
        grantee_kind: &str,
        grantee_id: &str,
        granted_seq: u64,
    ) -> Result<(), StoreError>;

    /// Grants of one provisional pin, ordered by (kind, id).
    fn list_provisional_grants(
        &mut self,
        pin_key: &str,
    ) -> Result<Vec<(String, String, u64)>, StoreError>;

    /// Monotonically renew a provisional pin's sequence; refuses closed
    /// pins and stale sequences.
    fn renew_provisional_pin(&mut self, pin_key: &str, renewal_seq: u64) -> Result<(), StoreError>;

    /// Close a provisional pin: mark it released (recording WHY when the
    /// producer lineage failed/superseded/lost authority) so reads refuse
    /// immediately. Closing happens BEFORE the protective pin is released
    /// by the caller — a tear between the two fails toward retention.
    fn close_provisional_pin(
        &mut self,
        pin_key: &str,
        invalidation_reason: Option<&str>,
    ) -> Result<(), StoreError>;

    /// Record a winner adoption (§65.1) on a provisional pin. Callers
    /// MUST have verified exact-object compatibility first; this only
    /// persists the resolution.
    fn adopt_provisional_pin(
        &mut self,
        pin_key: &str,
        committed_object_key: &str,
    ) -> Result<(), StoreError>;
    /// Record that a consumer was served this action's published result
    /// (a `served-to` provenance edge; idempotent). This is what H026
    /// escalation later enumerates — serving paths must call it when they
    /// hand a result to a consumer.
    fn record_served_consumer(
        &mut self,
        action_key: &str,
        consumer: &str,
    ) -> Result<(), StoreError>;

    /// Consumers previously served this action's result, from `served-to`
    /// provenance edges, ordered.
    fn list_served_consumers(&mut self, action_key: &str) -> Result<Vec<String>, StoreError>;

    /// Deterministic dump of every table for differential comparison.
    fn differential_snapshot(&mut self) -> Result<Vec<String>, StoreError>;
}

// ---------------------------------------------------------------------
// SQL engine abstraction: one store logic, two engines.
// ---------------------------------------------------------------------

/// A bound SQL value (the subset the schema uses; floats deliberately
/// excluded from authoritative metadata).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SqlValue {
    /// SQL NULL.
    Null,
    /// 64-bit integer.
    Int(i64),
    /// UTF-8 text.
    Text(String),
    /// Byte blob.
    Blob(Vec<u8>),
}

/// Minimal SQL engine surface the store needs. `?1..?N` placeholders.
pub trait SqlEngine {
    /// Execute a statement; returns affected-row count.
    fn execute(&mut self, sql: &str, params: &[SqlValue]) -> Result<usize, StoreError>;
    /// Run a query; returns all rows.
    fn query(&mut self, sql: &str, params: &[SqlValue]) -> Result<Vec<Vec<SqlValue>>, StoreError>;
}

/// The generic SQL-backed store.
pub struct SqlMetadataStore<E: SqlEngine> {
    engine: E,
    /// Domains this process has written, interned so reads can restore
    /// `&'static str` domains fail-closed (R121).
    domains: HashMap<String, &'static str>,
}

fn hex(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        use std::fmt::Write;
        let _ = write!(out, "{b:02x}");
    }
    out
}

/// Canonical `domain:hex` key for a typed digest (table keys/joins).
#[must_use]
pub fn digest_key(d: &TypedDigest) -> String {
    format!("{}:{}", d.domain, hex(&d.bytes))
}

const fn algo_tag(a: DigestAlgorithm) -> &'static str {
    match a {
        DigestAlgorithm::Sha256V1 => "sha256-v1",
    }
}

fn u128_blob(v: u128) -> Vec<u8> {
    v.to_be_bytes().to_vec()
}

fn u64_blob(v: u64) -> Vec<u8> {
    v.to_be_bytes().to_vec()
}

fn u128_hex(v: u128) -> String {
    hex(&v.to_be_bytes())
}

impl<E: SqlEngine> SqlMetadataStore<E> {
    /// Open the store over an engine, applying all pending migrations in one
    /// transaction. A failed upgrade preserves the previously applied schema.
    pub fn open(engine: E) -> Result<Self, StoreError> {
        let mut store = Self {
            engine,
            domains: HashMap::new(),
        };
        store.apply_migrations()?;
        Ok(store)
    }

    /// Highest durable operation update sequence, clamped to the initial
    /// sequence floor used by operator tooling.
    ///
    /// This narrow query keeps cross-crate diagnostics from receiving a
    /// mutable SQL escape hatch around authority and clone fencing.
    pub fn operation_update_high_water(&mut self) -> Result<u64, StoreError> {
        let rows = self
            .engine
            .query("SELECT COALESCE(MAX(updated_seq), 1) FROM operations", &[])?;
        let [row] = rows.as_slice() else {
            return Err(StoreError::Corruption(
                "operation update high-water row count".into(),
            ));
        };
        let [value] = row.as_slice() else {
            return Err(StoreError::Corruption(
                "operation update high-water shape".into(),
            ));
        };
        Ok(expect_u64(value, "operation update high-water")?.max(1))
    }

    /// Crate-internal engine access for reconciliation, authority-gate,
    /// crash-injection, and corruption fixtures. External callers cannot
    /// bypass the transactional metadata API with arbitrary SQL.
    pub(crate) fn engine_mut(&mut self) -> &mut E {
        &mut self.engine
    }

    fn apply_migrations(&mut self) -> Result<(), StoreError> {
        let applied: u32 = {
            let has_epochs = !self
                .engine
                .query(
                    "SELECT name FROM sqlite_master WHERE type = 'table' \
                     AND name = 'schema_epochs'",
                    &[],
                )?
                .is_empty();
            if has_epochs {
                let rows = self
                    .engine
                    .query("SELECT MAX(version) FROM schema_epochs", &[])?;
                match rows.first().and_then(|r| r.first()) {
                    Some(SqlValue::Int(v)) => u32::try_from(*v)
                        .map_err(|_| StoreError::Corruption("negative schema version".into()))?,
                    _ => 0,
                }
            } else {
                0
            }
        };
        let Some(first_pending) = MIGRATIONS
            .iter()
            .position(|migration| migration.version > applied)
        else {
            return Ok(());
        };
        // No caller can use the store until every pending step has succeeded.
        // Commit the complete upgrade once, rather than paying a durability
        // barrier for each historical version on every fresh daemon boot.
        self.engine.execute("BEGIN", &[])?;
        let result = (|| -> Result<(), StoreError> {
            for migration in &MIGRATIONS[first_pending..] {
                for statement in migration.statements {
                    self.engine.execute(statement, &[])?;
                }
                self.engine.execute(
                    "INSERT INTO schema_epochs (version, applied_seq) VALUES (?1, ?2)",
                    &[
                        SqlValue::Int(i64::from(migration.version)),
                        SqlValue::Int(0),
                    ],
                )?;
            }
            self.engine.execute("COMMIT", &[])?;
            Ok(())
        })();
        if result.is_err() {
            // Include COMMIT failures: a busy/failed commit may leave the
            // transaction open. Dropping the engine remains the final fallback.
            let _ = self.engine.execute("ROLLBACK", &[]);
        }
        result
    }

    fn intern(&mut self, domain: &'static str) {
        self.domains.entry(domain.to_owned()).or_insert(domain);
    }

    fn restore_domain(&self, domain: &str) -> Result<&'static str, StoreError> {
        self.domains
            .get(domain)
            .copied()
            .ok_or_else(|| StoreError::DomainNotInterned(domain.to_owned()))
    }

    fn restore_digest(
        &self,
        algo: &SqlValue,
        domain: &SqlValue,
        bytes: &SqlValue,
    ) -> Result<TypedDigest, StoreError> {
        let (SqlValue::Text(algo), SqlValue::Text(domain), SqlValue::Blob(bytes)) =
            (algo, domain, bytes)
        else {
            return Err(StoreError::Corruption("digest column shape".into()));
        };
        if algo != "sha256-v1" {
            return Err(StoreError::Corruption(format!("unknown algorithm {algo}")));
        }
        let bytes: [u8; 32] = bytes
            .as_slice()
            .try_into()
            .map_err(|_| StoreError::Corruption("digest not 32 bytes".into()))?;
        Ok(TypedDigest {
            algorithm: DigestAlgorithm::Sha256V1,
            domain: self.restore_domain(domain)?,
            bytes,
        })
    }

    fn digest_params(d: &TypedDigest) -> [SqlValue; 3] {
        [
            SqlValue::Text(algo_tag(d.algorithm).to_owned()),
            SqlValue::Text(d.domain.to_owned()),
            SqlValue::Blob(d.bytes.to_vec()),
        ]
    }

    fn in_txn<T>(
        &mut self,
        body: impl FnOnce(&mut E) -> Result<T, StoreError>,
    ) -> Result<T, StoreError> {
        self.engine.execute("BEGIN", &[])?;
        match body(&mut self.engine) {
            Ok(v) => {
                self.engine.execute("COMMIT", &[])?;
                Ok(v)
            }
            Err(e) => {
                let _ = self.engine.execute("ROLLBACK", &[]);
                Err(e)
            }
        }
    }

    fn active_authority_key(engine: &mut E) -> Result<Option<String>, StoreError> {
        let rows = engine.query(
            "SELECT key FROM coordinator_authorities WHERE released = 0",
            &[],
        )?;
        match rows.as_slice() {
            [] => Ok(None),
            [row] => match row.first() {
                Some(SqlValue::Text(k)) => Ok(Some(k.clone())),
                _ => Err(StoreError::Corruption("authority key shape".into())),
            },
            _ => Err(StoreError::Corruption(
                "more than one active authority".into(),
            )),
        }
    }

    fn require_active(engine: &mut E, authority: &TypedDigest) -> Result<(), StoreError> {
        match Self::active_authority_key(engine)? {
            Some(active) if active == digest_key(authority) => Ok(()),
            _ => Err(StoreError::NotActiveAuthority),
        }
    }

    fn attempt_authority_digest(authority: &AttemptAuthority) -> TypedDigest {
        rabs_key::authority_binding::coordinator_authority_digest(&authority.coordinator)
    }

    fn require_attempt_context(
        engine: &mut E,
        authority: &AttemptAuthority,
    ) -> Result<TypedDigest, StoreError> {
        let coordinator = Self::attempt_authority_digest(authority);
        Self::require_active(engine, &coordinator)?;
        if authority.action_generation.created_under_authority_digest != coordinator {
            return Err(StoreError::AttemptAuthorityMismatch);
        }
        let rows = engine.query(
            "SELECT action_key, authority_key, tombstoned, per_key_ordinal \
             FROM action_generations WHERE id_hex = ?1",
            &[SqlValue::Text(u128_hex(
                authority.action_generation.generation_id.0,
            ))],
        )?;
        let Some(row) = rows.first() else {
            return Err(StoreError::UnknownGeneration);
        };
        if rows.len() != 1 {
            return Err(StoreError::Corruption(
                "duplicate action generation rows".into(),
            ));
        }
        let [action_key, authority_key, tombstoned, ordinal] = row.as_slice() else {
            return Err(StoreError::Corruption(
                "action generation binding shape".into(),
            ));
        };
        if expect_u64(tombstoned, "generation tombstoned")? != 0 {
            return Err(StoreError::GenerationTombstoned);
        }
        let stored_ordinal = match ordinal {
            SqlValue::Null => return Err(StoreError::LegacyUnboundAuthority),
            value => expect_u64_blob(value, "generation ordinal")?,
        };
        if expect_text(action_key, "generation action key")? != digest_key(&authority.action_key)
            || expect_text(authority_key, "generation authority")? != digest_key(&coordinator)
            || stored_ordinal != authority.action_generation.per_key_ordinal
        {
            return Err(StoreError::AttemptAuthorityMismatch);
        }
        Ok(coordinator)
    }

    fn require_worker_lease_binding(
        engine: &mut E,
        worker: &PeerId,
        boot_generation: WorkerBootGeneration,
        incarnation: WorkerIncarnationId,
    ) -> Result<(), StoreError> {
        let rows = engine.query(
            "SELECT highest_boot_generation, incarnation, active, \
             operator_reenrollment_generation, clone_ambiguous \
             FROM worker_incarnation_fences WHERE worker = ?1",
            &[SqlValue::Text(worker.0.clone())],
        )?;
        let Some(row) = rows.first() else {
            return Err(StoreError::UnknownWorkerFence);
        };
        if rows.len() != 1 {
            return Err(StoreError::Corruption("duplicate worker fence rows".into()));
        }
        let fence = decode_worker_incarnation_fence(&worker.0, row)?;
        fence
            .validate_lease_binding(worker, boot_generation, incarnation)
            .map_err(StoreError::WorkerLeaseRejected)
    }

    fn revoke_worker_leases(engine: &mut E, worker: &str) -> Result<(), StoreError> {
        engine.execute(
            "UPDATE execution_leases SET released = 1 \
             WHERE released = 0 AND attempt_hex IN \
             (SELECT id_hex FROM action_attempts WHERE worker = ?1)",
            &[SqlValue::Text(worker.to_owned())],
        )?;
        Ok(())
    }

    fn require_live_attempt(
        engine: &mut E,
        authority: &AttemptAuthority,
        own_monotonic_now_ms: &dyn Fn() -> u64,
    ) -> Result<(), StoreError> {
        let state = Self::bound_lease_state(engine, authority)?;
        if state.released {
            return Err(StoreError::LeaseReleased);
        }
        if own_monotonic_now_ms() >= state.expires_at_own_monotonic_ms {
            return Err(StoreError::LeaseExpired);
        }
        if state.renewal_seq != authority.lease_renewal_seq.0 {
            return Err(StoreError::LeaseRenewalMismatch);
        }
        Ok(())
    }

    fn append_evidence_row(
        engine: &mut E,
        action: &TypedDigest,
        manifest_key: &str,
        evidence: &TypedDigest,
        generation: u128,
        attempt: u128,
    ) -> Result<(), StoreError> {
        let [algo, domain, bytes] = Self::digest_params(evidence);
        // Append-only, first-writer-wins: re-append never rewrites the
        // original manifest, generation, or attempt attribution (H029; I37).
        engine.execute(
            "INSERT OR IGNORE INTO action_evidence_index \
             (action_key, evidence_algo, evidence_domain, evidence_bytes, \
              generation_hex, attempt_hex, manifest_key) \
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            &[
                SqlValue::Text(digest_key(action)),
                algo,
                domain,
                bytes,
                SqlValue::Text(u128_hex(generation)),
                SqlValue::Text(u128_hex(attempt)),
                SqlValue::Text(manifest_key.to_owned()),
            ],
        )?;
        Ok(())
    }

    fn require_quarantine_preserved(current: &str, proposed: &str) -> Result<(), StoreError> {
        if (current == "quarantined" && proposed != "quarantined")
            || (current == "presentation-quarantined"
                && !matches!(proposed, "presentation-quarantined" | "quarantined"))
        {
            return Err(StoreError::QuarantineRequiresRepair);
        }
        Ok(())
    }

    fn set_serving_disposition_row(
        engine: &mut E,
        action_key: &str,
        disposition: &str,
    ) -> Result<(), StoreError> {
        let rows = engine.query(
            "SELECT disposition, state_revision FROM action_serving_states WHERE action_key = ?1",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        if let Some(row) = rows.first() {
            let [stored_disposition, stored_revision] = row.as_slice() else {
                return Err(StoreError::Corruption(
                    "serving disposition row shape".into(),
                ));
            };
            let stored_disposition = expect_text(stored_disposition, "disposition")?;
            Self::require_quarantine_preserved(&stored_disposition, disposition)?;
            let revision = expect_u64(stored_revision, "state_revision")?;
            let revision = if stored_disposition == disposition {
                revision
            } else {
                revision
                    .checked_add(1)
                    .ok_or_else(|| StoreError::Corruption("serving revision exhausted".into()))?
            };
            let revision = to_seq(revision, "state_revision")?;
            // The disposition and its revision land in ONE transaction.
            // In particular, quarantine must fence renewals prepared before
            // this write even if later incident bookkeeping never lands.
            engine.execute(
                "UPDATE action_serving_states SET disposition = ?2, state_revision = ?3 \
                 WHERE action_key = ?1",
                &[
                    SqlValue::Text(action_key.to_owned()),
                    SqlValue::Text(disposition.to_owned()),
                    SqlValue::Int(revision),
                ],
            )?;
        } else {
            engine.execute(
                "INSERT INTO action_serving_states (action_key, disposition, version, state_revision) \
                 VALUES (?1, ?2, 1, 0)",
                &[
                    SqlValue::Text(action_key.to_owned()),
                    SqlValue::Text(disposition.to_owned()),
                ],
            )?;
        }
        Ok(())
    }

    fn bound_lease_state(
        engine: &mut E,
        authority: &AttemptAuthority,
    ) -> Result<LeaseState, StoreError> {
        Self::require_attempt_context(engine, authority)?;
        let rows = engine.query(
            "SELECT l.attempt_hex, l.released, l.renewal_seq, l.expires_at_seq, \
                    a.generation_hex, a.worker, a.worker_boot_generation, \
                    a.worker_incarnation, a.execution_lease_hex \
             FROM execution_leases l \
             LEFT JOIN action_attempts a ON a.id_hex = l.attempt_hex \
             WHERE l.id_hex = ?1",
            &[SqlValue::Text(u128_hex(authority.execution_lease_id.0))],
        )?;
        let Some(row) = rows.first() else {
            return Err(StoreError::UnknownLease);
        };
        if rows.len() != 1 {
            return Err(StoreError::Corruption(
                "duplicate execution lease rows".into(),
            ));
        }
        let [
            attempt_hex,
            released,
            renewal_seq,
            expires_at_seq,
            generation_hex,
            worker,
            boot,
            incarnation,
            attempt_lease_hex,
        ] = row.as_slice()
        else {
            return Err(StoreError::Corruption("bound lease row shape".into()));
        };
        if expect_text(attempt_hex, "lease attempt")? != u128_hex(authority.attempt_id.0) {
            return Err(StoreError::LeaseAttemptMismatch);
        }
        let (stored_boot, stored_incarnation, stored_attempt_lease) =
            match (boot, incarnation, attempt_lease_hex) {
                (SqlValue::Null, _, _) | (_, SqlValue::Null, _) | (_, _, SqlValue::Null) => {
                    return Err(StoreError::LegacyUnboundAuthority);
                }
                (boot, incarnation, attempt_lease) => (
                    expect_u64_blob(boot, "attempt worker boot generation")?,
                    expect_u128(incarnation, "attempt worker incarnation")?,
                    expect_text(attempt_lease, "attempt execution lease")?,
                ),
            };
        if expect_text(generation_hex, "attempt generation")?
            != u128_hex(authority.action_generation.generation_id.0)
            || expect_text(worker, "attempt worker")? != authority.worker_peer_id.0
            || stored_boot != authority.worker_boot_generation.0
            || stored_incarnation != authority.worker_incarnation_id.0
            || stored_attempt_lease != u128_hex(authority.execution_lease_id.0)
        {
            return Err(StoreError::AttemptAuthorityMismatch);
        }
        Self::require_worker_lease_binding(
            engine,
            &authority.worker_peer_id,
            authority.worker_boot_generation,
            authority.worker_incarnation_id,
        )?;
        Ok(LeaseState {
            released: expect_u64(released, "released")? != 0,
            renewal_seq: expect_u64(renewal_seq, "renewal_seq")?,
            expires_at_own_monotonic_ms: expect_u64(expires_at_seq, "expires_at_seq")?,
        })
    }

    /// The never-reuse generation high-water (I51/R108).
    ///
    /// The stored row is the fast path, but it is only a row, and a
    /// rollback can lose it while the `action_generations` rows it was
    /// summarising survive. Reading 0 in that case silently downgraded
    /// the fence from a monotone watermark to primary-key uniqueness, so
    /// an id BELOW the lost watermark that was never minted became
    /// mintable again — the R108 ABA window, opened by a loss R113 was
    /// written to catch (bd-9nnqm).
    ///
    /// So the watermark is the MAXIMUM of the two sources. The stored
    /// row still covers ids whose rows were evicted or compacted away,
    /// and the surviving rows still cover a lost row. Neither alone is
    /// sufficient; the maximum is monotone under losing either.
    ///
    /// `action_generations.id` is a big-endian 16-byte blob, so SQL
    /// `MAX` over it orders numerically.
    fn generation_high_water(engine: &mut E) -> Result<u128, StoreError> {
        fn decode(value: &SqlValue) -> Result<u128, StoreError> {
            match value {
                SqlValue::Blob(b) => {
                    let bytes: [u8; 16] = b
                        .as_slice()
                        .try_into()
                        .map_err(|_| StoreError::Corruption("high-water not 16 bytes".into()))?;
                    Ok(u128::from_be_bytes(bytes))
                }
                SqlValue::Null => Ok(0),
                _ => Err(StoreError::Corruption("high-water shape".into())),
            }
        }

        let stored = engine.query(
            "SELECT value FROM generation_high_water WHERE kind = 'action-generation'",
            &[],
        )?;
        let stored = match stored.first().and_then(|r| r.first()) {
            None => 0,
            Some(value) => decode(value)?,
        };

        let observed = engine.query("SELECT MAX(id) FROM action_generations", &[])?;
        let observed = match observed.first().and_then(|r| r.first()) {
            None => 0,
            Some(value) => decode(value)?,
        };

        Ok(stored.max(observed))
    }

    /// Shared row mapper for `provisional_pins` SELECTs (single source of
    /// truth for the 19-column shape; R121 domain restore included).
    fn map_provisional_pin_row(
        &self,
        row: &[SqlValue],
    ) -> Result<ProvisionalPinRecord, StoreError> {
        let [
            pin,
            authority,
            action,
            generation,
            attempt,
            lease,
            role,
            path,
            algo,
            domain,
            bytes,
            object,
            protective,
            renewal,
            adopted,
            invalidation,
            released,
            toolchain_contract,
            event_contract,
        ] = row
        else {
            return Err(StoreError::Corruption("provisional pin shape".into()));
        };
        Ok(ProvisionalPinRecord {
            pin_key: expect_text(pin, "provisional pin key")?,
            authority_key: expect_text(authority, "provisional authority")?,
            action_key: expect_text(action, "provisional action")?,
            generation_hex: expect_text(generation, "provisional generation")?,
            attempt_hex: expect_text(attempt, "provisional attempt")?,
            lease_hex: expect_text(lease, "provisional lease")?,
            role_tag: match role {
                SqlValue::Int(v) => *v,
                _ => return Err(StoreError::Corruption("provisional role shape".into())),
            },
            virtual_path: match path {
                SqlValue::Blob(b) => b.clone(),
                _ => return Err(StoreError::Corruption("provisional path shape".into())),
            },
            object: self.restore_digest(algo, domain, bytes)?,
            object_key: expect_text(object, "provisional object")?,
            protective_pin_hex: expect_text(protective, "provisional protective pin")?,
            renewal_seq: expect_u64(renewal, "provisional renewal")?,
            adopted_object_key: expect_opt_text(adopted, "provisional adoption")?,
            invalidated_reason: expect_opt_text(invalidation, "provisional invalidation")?,
            released: expect_u64(released, "provisional released")? != 0,
            toolchain_contract_key: expect_text(
                toolchain_contract,
                "provisional toolchain contract",
            )?,
            event_contract_key: expect_text(event_contract, "provisional event contract")?,
        })
    }

    /// Shared row mapper for `provisional_obligations` SELECTs (single
    /// source of truth for the 12-column shape).
    fn map_obligation_row(row: &[SqlValue]) -> Result<ProvisionalObligationRow, StoreError> {
        let [
            worker,
            attempt_hex,
            pin,
            action,
            generation,
            producer,
            role,
            path,
            object,
            status,
            resolution,
            created,
        ] = row
        else {
            return Err(StoreError::Corruption("obligation row shape".into()));
        };
        Ok(ProvisionalObligationRow {
            consumer_worker: expect_text(worker, "obligation worker")?,
            consumer_attempt_hex: expect_text(attempt_hex, "obligation attempt")?,
            pin_key: expect_text(pin, "obligation pin")?,
            producer_action_key: expect_text(action, "obligation action")?,
            producer_generation_hex: expect_text(generation, "obligation generation")?,
            producer_attempt_hex: expect_text(producer, "obligation producer")?,
            role_tag: match role {
                SqlValue::Int(v) => *v,
                _ => return Err(StoreError::Corruption("obligation role shape".into())),
            },
            virtual_path: match path {
                SqlValue::Blob(b) => b.clone(),
                _ => return Err(StoreError::Corruption("obligation path shape".into())),
            },
            object_key: expect_text(object, "obligation object")?,
            status: expect_text(status, "obligation status")?,
            resolution_object_key: expect_opt_text(resolution, "obligation resolution")?,
            created_seq: expect_u64(created, "obligation seq")?,
        })
    }

    /// Shared row mapper for `provisional_install_journal` SELECTs
    /// (single source of truth for the 10-column shape; R121 domain
    /// restore included).
    fn map_install_row(&self, row: &[SqlValue]) -> Result<ProvisionalInstallRecord, StoreError> {
        let [
            pin,
            worker,
            attempt_hex,
            path,
            algo,
            domain,
            bytes,
            object_key,
            seq,
            state,
        ] = row
        else {
            return Err(StoreError::Corruption("install journal shape".into()));
        };
        Ok(ProvisionalInstallRecord {
            pin_key: expect_text(pin, "install pin")?,
            consumer_worker: expect_text(worker, "install worker")?,
            consumer_attempt_hex: expect_text(attempt_hex, "install attempt")?,
            installed_path: match path {
                SqlValue::Blob(b) => b.clone(),
                _ => return Err(StoreError::Corruption("install path shape".into())),
            },
            object: self.restore_digest(algo, domain, bytes)?,
            object_key: expect_text(object_key, "install object")?,
            installed_seq: expect_u64(seq, "install seq")?,
            state: expect_text(state, "install state")?,
        })
    }
}

fn expect_u64(v: &SqlValue, what: &str) -> Result<u64, StoreError> {
    match v {
        SqlValue::Int(i) => {
            u64::try_from(*i).map_err(|_| StoreError::Corruption(format!("negative {what}")))
        }
        _ => Err(StoreError::Corruption(format!("{what} shape"))),
    }
}

fn expect_u128(v: &SqlValue, what: &str) -> Result<u128, StoreError> {
    match v {
        SqlValue::Blob(b) => {
            let bytes: [u8; 16] = b
                .as_slice()
                .try_into()
                .map_err(|_| StoreError::Corruption(format!("{what} not 16 bytes")))?;
            Ok(u128::from_be_bytes(bytes))
        }
        _ => Err(StoreError::Corruption(format!("{what} shape"))),
    }
}

fn expect_u64_blob(v: &SqlValue, what: &str) -> Result<u64, StoreError> {
    match v {
        SqlValue::Blob(b) => {
            let bytes: [u8; 8] = b
                .as_slice()
                .try_into()
                .map_err(|_| StoreError::Corruption(format!("{what} not 8 bytes")))?;
            Ok(u64::from_be_bytes(bytes))
        }
        _ => Err(StoreError::Corruption(format!("{what} shape"))),
    }
}

fn decode_worker_incarnation_fence(
    worker: &str,
    row: &[SqlValue],
) -> Result<WorkerIncarnationFenceRecord, StoreError> {
    let [
        highest_boot_generation,
        incarnation,
        active,
        operator_reenrollment_generation,
        clone_ambiguous,
    ] = row
    else {
        return Err(StoreError::Corruption("worker fence shape".into()));
    };
    let incarnation = WorkerIncarnationId(expect_u128(incarnation, "worker incarnation")?);
    let active_incarnation = match expect_u64(active, "worker fence active")? {
        0 => None,
        1 => Some(incarnation),
        other => {
            return Err(StoreError::Corruption(format!(
                "worker fence active flag {other}"
            )));
        }
    };
    Ok(WorkerIncarnationFenceRecord {
        worker_peer_id: PeerId(worker.to_owned()),
        highest_boot_generation: WorkerBootGeneration(expect_u64_blob(
            highest_boot_generation,
            "worker boot generation",
        )?),
        active_incarnation,
        clone_ambiguous: match expect_u64(clone_ambiguous, "clone ambiguous")? {
            0 => false,
            1 => true,
            other => {
                return Err(StoreError::Corruption(format!(
                    "clone ambiguous flag {other}"
                )));
            }
        },
        operator_reenrollment_generation: expect_u64_blob(
            operator_reenrollment_generation,
            "worker reenrollment generation",
        )?,
    })
}

fn expect_text(v: &SqlValue, what: &str) -> Result<String, StoreError> {
    match v {
        SqlValue::Text(t) => Ok(t.clone()),
        _ => Err(StoreError::Corruption(format!("{what} shape"))),
    }
}

fn expect_opt_text(v: &SqlValue, what: &str) -> Result<Option<String>, StoreError> {
    match v {
        SqlValue::Null => Ok(None),
        SqlValue::Text(t) => Ok(Some(t.clone())),
        _ => Err(StoreError::Corruption(format!("{what} shape"))),
    }
}

fn to_seq(v: u64, what: &str) -> Result<i64, StoreError> {
    i64::try_from(v).map_err(|_| StoreError::Corruption(format!("{what} out of range")))
}

/// Decode `(evidence_domain, evidence_bytes)` rows into sorted
/// `domain:hex` keys (shared by the per-action and per-manifest listings).
fn evidence_key_rows(rows: &[Vec<SqlValue>]) -> Result<Vec<String>, StoreError> {
    rows.iter()
        .map(|row| {
            let [domain, bytes] = row.as_slice() else {
                return Err(StoreError::Corruption("evidence row shape".into()));
            };
            let SqlValue::Blob(bytes) = bytes else {
                return Err(StoreError::Corruption("evidence bytes shape".into()));
            };
            Ok(format!(
                "{}:{}",
                expect_text(domain, "evidence domain")?,
                hex(bytes)
            ))
        })
        .collect()
}

impl<E: SqlEngine> RabsMetadataStore for SqlMetadataStore<E> {
    fn query(&mut self, sql: &str, params: &[SqlValue]) -> Result<Vec<Vec<SqlValue>>, StoreError> {
        self.engine.query(sql, params)
    }

    fn schema_version(&mut self) -> Result<u32, StoreError> {
        let rows = self
            .engine
            .query("SELECT MAX(version) FROM schema_epochs", &[])?;
        match rows.first().and_then(|r| r.first()) {
            Some(SqlValue::Int(v)) => u32::try_from(*v)
                .map_err(|_| StoreError::Corruption("negative schema version".into())),
            _ => Err(StoreError::Corruption("missing schema_epochs".into())),
        }
    }

    fn intern_domain(&mut self, domain: &'static str) {
        self.intern(domain);
    }

    fn acquire_authority(&mut self, row: &AuthorityRow) -> Result<(), StoreError> {
        self.intern(row.digest.domain);
        let key = digest_key(&row.digest);
        let [algo, domain, bytes] = SqlMetadataStore::<E>::digest_params(&row.digest);
        let cluster = row.cluster_id.clone();
        let incarnation = u128_blob(row.incarnation);
        let term = i64::try_from(row.term)
            .map_err(|_| StoreError::Corruption("term out of range".into()))?;
        let acquired = i64::try_from(row.acquired_seq)
            .map_err(|_| StoreError::Corruption("acquired_seq out of range".into()))?;
        self.in_txn(move |engine| {
            match SqlMetadataStore::<E>::active_authority_key(engine)? {
                Some(active) if active == key => return Ok(()), // idempotent
                Some(active) => return Err(StoreError::AuthorityHeld { holder: active }),
                None => {}
            }
            engine.execute(
                "INSERT OR REPLACE INTO coordinator_authorities \
                 (key, algo, domain, bytes, cluster_id, incarnation, term, acquired_seq, released) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 0)",
                &[
                    SqlValue::Text(key),
                    algo,
                    domain,
                    bytes,
                    SqlValue::Text(cluster),
                    SqlValue::Blob(incarnation),
                    SqlValue::Int(term),
                    SqlValue::Int(acquired),
                ],
            )?;
            Ok(())
        })
    }

    fn release_authority(&mut self, digest: &TypedDigest) -> Result<(), StoreError> {
        let key = digest_key(digest);
        self.in_txn(move |engine| {
            engine.execute(
                "UPDATE coordinator_authorities SET released = 1 WHERE key = ?1",
                &[SqlValue::Text(key)],
            )?;
            Ok(())
        })
    }

    fn active_authority(&mut self) -> Result<Option<AuthorityRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT algo, domain, bytes, cluster_id, incarnation, term, acquired_seq \
             FROM coordinator_authorities WHERE released = 0",
            &[],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        if rows.len() > 1 {
            return Err(StoreError::Corruption(
                "more than one active authority".into(),
            ));
        }
        let [algo, domain, bytes, cluster, incarnation, term, acquired] = row.as_slice() else {
            return Err(StoreError::Corruption("authority row shape".into()));
        };
        let digest = self.restore_digest(algo, domain, bytes)?;
        let SqlValue::Text(cluster) = cluster else {
            return Err(StoreError::Corruption("cluster_id shape".into()));
        };
        let SqlValue::Blob(incarnation) = incarnation else {
            return Err(StoreError::Corruption("incarnation shape".into()));
        };
        let incarnation_bytes: [u8; 16] = incarnation
            .as_slice()
            .try_into()
            .map_err(|_| StoreError::Corruption("incarnation not 16 bytes".into()))?;
        Ok(Some(AuthorityRow {
            digest,
            cluster_id: cluster.clone(),
            incarnation: u128::from_be_bytes(incarnation_bytes),
            term: expect_u64(term, "term")?,
            acquired_seq: expect_u64(acquired, "acquired_seq")?,
        }))
    }

    fn upsert_action_entry(&mut self, row: &ActionEntryRow) -> Result<(), StoreError> {
        self.intern(row.action_key.domain);
        let key = digest_key(&row.action_key);
        let [algo, domain, bytes] = SqlMetadataStore::<E>::digest_params(&row.action_key);
        let key_epoch = i64::from(row.key_epoch);
        let projection_epoch = i64::from(row.projection_epoch);
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO action_entries \
                 (key, algo, domain, bytes, key_epoch, projection_epoch) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                &[
                    SqlValue::Text(key),
                    algo,
                    domain,
                    bytes,
                    SqlValue::Int(key_epoch),
                    SqlValue::Int(projection_epoch),
                ],
            )?;
            Ok(())
        })
    }

    fn lookup_action(&mut self, key: &TypedDigest) -> Result<Option<ActionEntryRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT algo, domain, bytes, key_epoch, projection_epoch \
             FROM action_entries WHERE key = ?1",
            &[SqlValue::Text(digest_key(key))],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [algo, domain, bytes, key_epoch, projection_epoch] = row.as_slice() else {
            return Err(StoreError::Corruption("action entry shape".into()));
        };
        let action_key = self.restore_digest(algo, domain, bytes)?;
        let key_epoch = u32::try_from(expect_u64(key_epoch, "key_epoch")?)
            .map_err(|_| StoreError::Corruption("key_epoch out of range".into()))?;
        let projection_epoch = u32::try_from(expect_u64(projection_epoch, "projection_epoch")?)
            .map_err(|_| StoreError::Corruption("projection_epoch out of range".into()))?;
        Ok(Some(ActionEntryRow {
            action_key,
            key_epoch,
            projection_epoch,
        }))
    }

    fn create_generation(
        &mut self,
        authority: &TypedDigest,
        id: u128,
        action_key: &TypedDigest,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let action = digest_key(action_key);
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let high_water = SqlMetadataStore::<E>::generation_high_water(engine)?;
            if id <= high_water {
                return Err(StoreError::GenerationIdNotAboveHighWater);
            }
            engine.execute(
                "INSERT INTO action_generations (id_hex, id, action_key, authority_key, tombstoned) \
                 VALUES (?1, ?2, ?3, ?4, 0)",
                &[
                    SqlValue::Text(u128_hex(id)),
                    SqlValue::Blob(u128_blob(id)),
                    SqlValue::Text(action),
                    SqlValue::Text(digest_key(&authority)),
                ],
            )?;
            engine.execute(
                "INSERT OR REPLACE INTO generation_high_water (kind, value) \
                 VALUES ('action-generation', ?1)",
                &[SqlValue::Blob(u128_blob(id))],
            )?;
            Ok(())
        })
    }
    fn create_bound_generation(
        &mut self,
        authority: &TypedDigest,
        generation: &ActionGeneration,
        action_key: &TypedDigest,
    ) -> Result<(), StoreError> {
        if generation.created_under_authority_digest != *authority {
            return Err(StoreError::AttemptAuthorityMismatch);
        }
        let authority = authority.clone();
        let action = digest_key(action_key);
        let generation = generation.clone();
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let id = generation.generation_id.0;
            let high_water = SqlMetadataStore::<E>::generation_high_water(engine)?;
            if id <= high_water {
                return Err(StoreError::GenerationIdNotAboveHighWater);
            }
            engine.execute(
                "INSERT INTO action_generations \
                 (id_hex, id, action_key, authority_key, tombstoned, per_key_ordinal) \
                 VALUES (?1, ?2, ?3, ?4, 0, ?5)",
                &[
                    SqlValue::Text(u128_hex(id)),
                    SqlValue::Blob(u128_blob(id)),
                    SqlValue::Text(action),
                    SqlValue::Text(digest_key(&authority)),
                    SqlValue::Blob(u64_blob(generation.per_key_ordinal)),
                ],
            )?;
            engine.execute(
                "INSERT OR REPLACE INTO generation_high_water (kind, value) \
                 VALUES ('action-generation', ?1)",
                &[SqlValue::Blob(u128_blob(id))],
            )?;
            Ok(())
        })
    }

    fn allocate_bound_generation(
        &mut self,
        authority: &TypedDigest,
        action_key: &TypedDigest,
    ) -> Result<ActionGeneration, StoreError> {
        let authority = authority.clone();
        let action = digest_key(action_key);
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let id = SqlMetadataStore::<E>::generation_high_water(engine)?
                .checked_add(1)
                .ok_or(StoreError::GenerationIdentityExhausted)?;
            // Fixed-width big-endian blobs have numeric byte ordering. Validate
            // every non-NULL row's representation before trusting the maximum;
            // an older corrupt row must not hide behind a valid larger ordinal.
            // Legacy NULL ordinals have no live lease authority (migration 21).
            let malformed = engine.query(
                "SELECT per_key_ordinal FROM action_generations \
                 WHERE action_key = ?1 AND per_key_ordinal IS NOT NULL \
                 AND (typeof(per_key_ordinal) != 'blob' OR length(per_key_ordinal) != 8) \
                 LIMIT 1",
                &[SqlValue::Text(action.clone())],
            )?;
            if !malformed.is_empty() {
                return Err(StoreError::Corruption(
                    "generation ordinal representation".into(),
                ));
            }
            let rows = engine.query(
                "SELECT per_key_ordinal FROM action_generations \
                 WHERE action_key = ?1 AND per_key_ordinal IS NOT NULL \
                 ORDER BY per_key_ordinal DESC LIMIT 1",
                &[SqlValue::Text(action.clone())],
            )?;
            let previous = match rows.as_slice() {
                [] => 0,
                [row] => match row.as_slice() {
                    [value] => expect_u64_blob(value, "generation ordinal")?,
                    _ => return Err(StoreError::Corruption("generation ordinal shape".into())),
                },
                _ => {
                    return Err(StoreError::Corruption(
                        "generation ordinal row count".into(),
                    ));
                }
            };
            let ordinal = previous
                .checked_add(1)
                .ok_or(StoreError::GenerationOrdinalExhausted)?;
            let generation = ActionGeneration {
                generation_id: ActionGenerationId(id),
                per_key_ordinal: ordinal,
                created_under_authority_digest: authority.clone(),
            };
            engine.execute(
                "INSERT INTO action_generations \
                 (id_hex, id, action_key, authority_key, tombstoned, per_key_ordinal) \
                 VALUES (?1, ?2, ?3, ?4, 0, ?5)",
                &[
                    SqlValue::Text(u128_hex(id)),
                    SqlValue::Blob(u128_blob(id)),
                    SqlValue::Text(action),
                    SqlValue::Text(digest_key(&authority)),
                    SqlValue::Blob(u64_blob(ordinal)),
                ],
            )?;
            engine.execute(
                "INSERT OR REPLACE INTO generation_high_water (kind, value) \
                 VALUES ('action-generation', ?1)",
                &[SqlValue::Blob(u128_blob(id))],
            )?;
            Ok(generation)
        })
    }

    fn close_generations_for_other_authorities(
        &mut self,
        active: &TypedDigest,
    ) -> Result<u64, StoreError> {
        let active = digest_key(active);
        self.in_txn(move |engine| {
            let closed = engine.execute(
                "UPDATE action_generations SET tombstoned = 1 \
                 WHERE tombstoned = 0 AND authority_key != ?1",
                &[SqlValue::Text(active)],
            )?;
            u64::try_from(closed)
                .map_err(|_| StoreError::Corruption("generation close count out of range".into()))
        })
    }
    fn tombstone_generation(&mut self, id: u128) -> Result<(), StoreError> {
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "UPDATE action_generations SET tombstoned = 1 WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            if changed == 0 {
                return Err(StoreError::UnknownGeneration);
            }
            Ok(())
        })
    }

    fn record_attempt(
        &mut self,
        id: u128,
        generation: u128,
        worker: &str,
        seq: u64,
    ) -> Result<(), StoreError> {
        let worker = worker.to_owned();
        let seq =
            i64::try_from(seq).map_err(|_| StoreError::Corruption("seq out of range".into()))?;
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT id_hex FROM action_attempts WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            if !existing.is_empty() {
                return Err(StoreError::DuplicateAttempt);
            }
            let generation_exists = engine.query(
                "SELECT id_hex FROM action_generations WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(generation))],
            )?;
            if generation_exists.is_empty() {
                return Err(StoreError::UnknownGeneration);
            }
            engine.execute(
                "INSERT INTO action_attempts (id_hex, id, generation_hex, worker, seq) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(u128_hex(id)),
                    SqlValue::Blob(u128_blob(id)),
                    SqlValue::Text(u128_hex(generation)),
                    SqlValue::Text(worker),
                    SqlValue::Int(seq),
                ],
            )?;
            Ok(())
        })
    }

    fn admit_attempt_lease(
        &mut self,
        authority: &AttemptAuthority,
        recorded_seq: u64,
        expires_at_own_monotonic_ms: u64,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let recorded = i64::try_from(recorded_seq)
            .map_err(|_| StoreError::Corruption("recorded_seq out of range".into()))?;
        let renewal = i64::try_from(authority.lease_renewal_seq.0)
            .map_err(|_| StoreError::Corruption("renewal_seq out of range".into()))?;
        let expires = i64::try_from(expires_at_own_monotonic_ms)
            .map_err(|_| StoreError::Corruption("expires_at_seq out of range".into()))?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_attempt_context(engine, &authority)?;
            SqlMetadataStore::<E>::require_worker_lease_binding(
                engine,
                &authority.worker_peer_id,
                authority.worker_boot_generation,
                authority.worker_incarnation_id,
            )?;
            let attempt_id = authority.attempt_id.0;
            if !engine
                .query(
                    "SELECT id_hex FROM action_attempts WHERE id_hex = ?1",
                    &[SqlValue::Text(u128_hex(attempt_id))],
                )?
                .is_empty()
            {
                return Err(StoreError::DuplicateAttempt);
            }
            let lease_id = authority.execution_lease_id.0;
            if !engine
                .query(
                    "SELECT id_hex FROM execution_leases WHERE id_hex = ?1",
                    &[SqlValue::Text(u128_hex(lease_id))],
                )?
                .is_empty()
            {
                return Err(StoreError::DuplicateLease);
            }
            engine.execute(
                "INSERT INTO action_attempts \
                 (id_hex, id, generation_hex, worker, seq, \
                  worker_boot_generation, worker_incarnation, execution_lease_hex) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                &[
                    SqlValue::Text(u128_hex(attempt_id)),
                    SqlValue::Blob(u128_blob(attempt_id)),
                    SqlValue::Text(u128_hex(authority.action_generation.generation_id.0)),
                    SqlValue::Text(authority.worker_peer_id.0.clone()),
                    SqlValue::Int(recorded),
                    SqlValue::Blob(u64_blob(authority.worker_boot_generation.0)),
                    SqlValue::Blob(u128_blob(authority.worker_incarnation_id.0)),
                    SqlValue::Text(u128_hex(lease_id)),
                ],
            )?;
            engine.execute(
                "INSERT INTO execution_leases \
                 (id_hex, id, attempt_hex, renewal_seq, expires_at_seq, released) \
                 VALUES (?1, ?2, ?3, ?4, ?5, 0)",
                &[
                    SqlValue::Text(u128_hex(lease_id)),
                    SqlValue::Blob(u128_blob(lease_id)),
                    SqlValue::Text(u128_hex(attempt_id)),
                    SqlValue::Int(renewal),
                    SqlValue::Int(expires),
                ],
            )?;
            Ok(())
        })
    }

    fn renew_attempt_lease(
        &mut self,
        authority: &AttemptAuthority,
        renewal: LeaseRenewal,
        expires_at_own_monotonic_ms: u64,
        own_monotonic_now_ms: &dyn Fn() -> u64,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let expires = i64::try_from(expires_at_own_monotonic_ms)
            .map_err(|_| StoreError::Corruption("expires_at_seq out of range".into()))?;
        self.in_txn(move |engine| {
            let state = SqlMetadataStore::<E>::bound_lease_state(engine, &authority)?;
            if state.released {
                return Err(StoreError::LeaseReleased);
            }
            let now = own_monotonic_now_ms();
            if now >= state.expires_at_own_monotonic_ms || expires_at_own_monotonic_ms <= now {
                return Err(StoreError::LeaseExpired);
            }
            if renewal.lease != authority.execution_lease_id {
                return Err(StoreError::LeaseAttemptMismatch);
            }
            if authority.lease_renewal_seq.0 != state.renewal_seq {
                return Err(StoreError::LeaseRenewalMismatch);
            }
            if renewal.seq.0 <= state.renewal_seq {
                return Err(StoreError::NonMonotonicRenewal);
            }
            let renewal_seq = i64::try_from(renewal.seq.0)
                .map_err(|_| StoreError::Corruption("renewal_seq out of range".into()))?;
            engine.execute(
                "UPDATE execution_leases SET renewal_seq = ?1, expires_at_seq = ?2 \
                 WHERE id_hex = ?3",
                &[
                    SqlValue::Int(renewal_seq),
                    SqlValue::Int(expires),
                    SqlValue::Text(u128_hex(authority.execution_lease_id.0)),
                ],
            )?;
            // A delayed transaction cannot use an earlier clock sample to
            // re-arm authority after either the old or new deadline elapsed.
            let now = own_monotonic_now_ms();
            if now >= state.expires_at_own_monotonic_ms || now >= expires_at_own_monotonic_ms {
                return Err(StoreError::LeaseExpired);
            }
            Ok(())
        })
    }

    fn release_lease(&mut self, id: u128) -> Result<(), StoreError> {
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "UPDATE execution_leases SET released = 1 WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            if changed == 0 {
                return Err(StoreError::UnknownLease);
            }
            Ok(())
        })
    }

    fn commit_publication(
        &mut self,
        authority: &TypedDigest,
        attempt_authority: Option<(&AttemptAuthority, &dyn Fn() -> u64)>,
        row: &PublicationRow,
    ) -> Result<CommitOutcome, StoreError> {
        self.intern(row.action_key.domain);
        self.intern(row.descriptor_digest.domain);
        self.intern(row.manifest_digest.domain);
        self.intern(row.evidence_digest.domain);
        let authority = authority.clone();
        let attempt_authority = attempt_authority.map(|(attempt, now)| (attempt.clone(), now));
        let row = row.clone();
        self.in_txn(move |engine| {
            let lease_clock_and_deadline = match &attempt_authority {
                Some((attempt, own_monotonic_now_ms)) => {
                    if SqlMetadataStore::<E>::attempt_authority_digest(attempt) != authority
                        || row.action_key != attempt.action_key
                        || row.winner_generation != attempt.action_generation.generation_id.0
                        || row.winner_attempt != attempt.attempt_id.0
                    {
                        return Err(StoreError::AttemptAuthorityMismatch);
                    }
                    let state = SqlMetadataStore::<E>::bound_lease_state(engine, attempt)?;
                    if state.released {
                        return Err(StoreError::LeaseReleased);
                    }
                    if own_monotonic_now_ms() >= state.expires_at_own_monotonic_ms {
                        return Err(StoreError::LeaseExpired);
                    }
                    if state.renewal_seq != attempt.lease_renewal_seq.0 {
                        return Err(StoreError::LeaseRenewalMismatch);
                    }
                    Some((own_monotonic_now_ms, state.expires_at_own_monotonic_ms))
                }
                None => {
                    SqlMetadataStore::<E>::require_active(engine, &authority)?;
                    None
                }
            };
            let require_live_lease = || {
                if let Some((clock, deadline)) = lease_clock_and_deadline
                    && clock() >= deadline
                {
                    return Err(StoreError::LeaseExpired);
                }
                Ok(())
            };
            let action = digest_key(&row.action_key);
            let existing = engine.query(
                "SELECT descriptor_domain, descriptor_bytes FROM action_publications \
                 WHERE action_key = ?1",
                &[SqlValue::Text(action.clone())],
            )?;
            require_live_lease()?;
            if let Some(existing_row) = existing.first() {
                let [domain, bytes] = existing_row.as_slice() else {
                    return Err(StoreError::Corruption("publication row shape".into()));
                };
                let (SqlValue::Text(domain), SqlValue::Blob(bytes)) = (domain, bytes) else {
                    return Err(StoreError::Corruption("publication digest shape".into()));
                };
                let same = domain == row.descriptor_digest.domain
                    && bytes.as_slice() == row.descriptor_digest.bytes.as_slice();
                if same {
                    return Ok(CommitOutcome::IdempotentDuplicate);
                }
                // Different descriptor for the same key: quarantine, never
                // overwrite.
                engine.execute(
                    "INSERT OR REPLACE INTO quarantines (scope, subject, reason) \
                     VALUES ('action-entry', ?1, 'publication descriptor conflict')",
                    &[SqlValue::Text(action)],
                )?;
                require_live_lease()?;
                return Ok(CommitOutcome::ConflictQuarantined);
            }
            let [d_algo, d_domain, d_bytes] =
                SqlMetadataStore::<E>::digest_params(&row.descriptor_digest);
            let [m_algo, m_domain, m_bytes] =
                SqlMetadataStore::<E>::digest_params(&row.manifest_digest);
            engine.execute(
                "INSERT INTO action_publications \
                 (action_key, descriptor_algo, descriptor_domain, descriptor_bytes, \
                  manifest_algo, manifest_domain, manifest_bytes, \
                  winner_generation_hex, winner_attempt_hex, result_kind, pin_hex) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
                &[
                    SqlValue::Text(action.clone()),
                    d_algo,
                    d_domain,
                    d_bytes,
                    m_algo,
                    m_domain,
                    m_bytes,
                    SqlValue::Text(u128_hex(row.winner_generation)),
                    SqlValue::Text(u128_hex(row.winner_attempt)),
                    SqlValue::Text(row.result_kind.as_str().to_owned()),
                    SqlValue::Text(u128_hex(row.pin_id)),
                ],
            )?;
            // A pre-existing serving row may carry an operator quarantine or
            // an H040 revision. Publication is not permission to erase either.
            let serving_exists = engine.query(
                "SELECT 1 FROM action_serving_states WHERE action_key = ?1",
                &[SqlValue::Text(action.clone())],
            )?;
            if serving_exists.is_empty() {
                engine.execute(
                    "INSERT INTO action_serving_states (action_key, disposition, version) \
                     VALUES (?1, 'servable', 1)",
                    &[SqlValue::Text(action.clone())],
                )?;
            } else {
                Self::set_serving_disposition_row(engine, &action, "servable")?;
            }
            // The winner's evidence association, SAME transaction (H011),
            // bound to the committed canonical manifest (H029; I37) and
            // append-only (OR IGNORE: never rewrite prior attribution).
            let [e_algo, e_domain, e_bytes] =
                SqlMetadataStore::<E>::digest_params(&row.evidence_digest);
            engine.execute(
                "INSERT OR IGNORE INTO action_evidence_index \
                 (action_key, evidence_algo, evidence_domain, evidence_bytes, \
                  generation_hex, attempt_hex, manifest_key) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                &[
                    SqlValue::Text(action),
                    e_algo,
                    e_domain,
                    e_bytes,
                    SqlValue::Text(u128_hex(row.winner_generation)),
                    SqlValue::Text(u128_hex(row.winner_attempt)),
                    SqlValue::Text(digest_key(&row.manifest_digest)),
                ],
            )?;
            // The durable publication reachability pin, SAME transaction.
            engine.execute(
                "INSERT INTO pins (id_hex, id, root_key, owner, class, expires_at_seq, released, \
                 evidence, renewal_seq, durable, reason) \
                 VALUES (?1, ?2, ?3, ?4, 'action-publication', NULL, 0, ?5, 0, 1, \
                 'publication reachability root')",
                &[
                    SqlValue::Text(u128_hex(row.pin_id)),
                    SqlValue::Blob(u128_blob(row.pin_id)),
                    SqlValue::Text(digest_key(&row.manifest_digest)),
                    SqlValue::Text(row.pin_owner.clone()),
                    SqlValue::Text(digest_key(&row.action_key)),
                ],
            )?;
            // The verified provisional-ancestor lineage, SAME transaction
            // (H028; I32): a dependent's later commit walks these rows as
            // durable truth.
            for ancestor in &row.provisional_ancestors {
                engine.execute(
                    "INSERT OR IGNORE INTO provisional_ancestry \
                     (consumer_action_key, producer_action_key, role, virtual_path, \
                      object_key, adopted) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    &[
                        SqlValue::Text(digest_key(&row.action_key)),
                        SqlValue::Text(ancestor.producer_action_key.clone()),
                        SqlValue::Text(ancestor.role.clone()),
                        SqlValue::Blob(ancestor.virtual_path.clone()),
                        SqlValue::Text(ancestor.object_key.clone()),
                        SqlValue::Int(i64::from(ancestor.adopted)),
                    ],
                )?;
            }
            // Roll back the complete pointer/evidence/pin transaction if its
            // writes outlived the lease. A stale admission sample is no grant.
            require_live_lease()?;
            Ok(CommitOutcome::Committed)
        })
    }

    fn append_evidence(
        &mut self,
        action: &TypedDigest,
        manifest_key: &str,
        evidence: &TypedDigest,
        generation: u128,
        attempt: u128,
    ) -> Result<(), StoreError> {
        self.intern(evidence.domain);
        self.in_txn(|engine| {
            Self::append_evidence_row(engine, action, manifest_key, evidence, generation, attempt)
        })
    }

    fn append_evidence_for_attempt(
        &mut self,
        authority: &AttemptAuthority,
        manifest_key: &str,
        evidence: &TypedDigest,
        own_monotonic_now_ms: &dyn Fn() -> u64,
    ) -> Result<(), StoreError> {
        self.intern(evidence.domain);
        self.in_txn(|engine| {
            Self::require_live_attempt(engine, authority, own_monotonic_now_ms)?;
            Self::append_evidence_row(
                engine,
                &authority.action_key,
                manifest_key,
                evidence,
                authority.action_generation.generation_id.0,
                authority.attempt_id.0,
            )?;
            Self::require_live_attempt(engine, authority, own_monotonic_now_ms)
        })
    }

    fn has_publication(&mut self, action: &TypedDigest) -> Result<bool, StoreError> {
        let rows = self.engine.query(
            "SELECT action_key FROM action_publications WHERE action_key = ?1",
            &[SqlValue::Text(digest_key(action))],
        )?;
        Ok(!rows.is_empty())
    }

    fn published_manifest_key(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Option<String>, StoreError> {
        self.published_manifest_key_str(&digest_key(action))
    }

    fn published_manifest_key_str(
        &mut self,
        action_key: &str,
    ) -> Result<Option<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT manifest_domain, manifest_bytes FROM action_publications WHERE action_key = ?1",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [SqlValue::Text(domain), SqlValue::Blob(bytes)] = row.as_slice() else {
            return Err(StoreError::Corruption("publication manifest shape".into()));
        };
        Ok(Some(format!("{}:{}", domain, hex(bytes))))
    }

    fn generation_state(&mut self, id: u128) -> Result<Option<GenerationState>, StoreError> {
        let rows = self.engine.query(
            "SELECT tombstoned FROM action_generations WHERE id_hex = ?1",
            &[SqlValue::Text(u128_hex(id))],
        )?;
        match rows.first().and_then(|r| r.first()) {
            None => Ok(None),
            Some(v) => Ok(Some(GenerationState {
                tombstoned: expect_u64(v, "tombstoned")? != 0,
            })),
        }
    }

    fn attempt_exists(&mut self, id: u128, generation: u128) -> Result<bool, StoreError> {
        let rows = self.engine.query(
            "SELECT id_hex FROM action_attempts WHERE id_hex = ?1 AND generation_hex = ?2",
            &[
                SqlValue::Text(u128_hex(id)),
                SqlValue::Text(u128_hex(generation)),
            ],
        )?;
        Ok(!rows.is_empty())
    }

    fn lease_state(&mut self, id: u128) -> Result<Option<LeaseState>, StoreError> {
        let rows = self.engine.query(
            "SELECT released, renewal_seq, expires_at_seq FROM execution_leases WHERE id_hex = ?1",
            &[SqlValue::Text(u128_hex(id))],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [released, renewal_seq, expires_at_seq] = row.as_slice() else {
            return Err(StoreError::Corruption("lease state shape".into()));
        };
        Ok(Some(LeaseState {
            released: expect_u64(released, "released")? != 0,
            renewal_seq: expect_u64(renewal_seq, "renewal_seq")?,
            expires_at_own_monotonic_ms: expect_u64(expires_at_seq, "expires_at_seq")?,
        }))
    }

    fn validate_attempt_lease(
        &mut self,
        authority: &AttemptAuthority,
        own_monotonic_now_ms: u64,
    ) -> Result<LeaseState, StoreError> {
        let state = SqlMetadataStore::<E>::bound_lease_state(&mut self.engine, authority)?;
        if state.released {
            return Err(StoreError::LeaseReleased);
        }
        if own_monotonic_now_ms >= state.expires_at_own_monotonic_ms {
            return Err(StoreError::LeaseExpired);
        }
        if state.renewal_seq != authority.lease_renewal_seq.0 {
            return Err(StoreError::LeaseRenewalMismatch);
        }
        Ok(state)
    }

    fn object_located(&mut self, object: &TypedDigest) -> Result<bool, StoreError> {
        // A quarantined location is suspect COPY evidence: it does not
        // count as availability (the object's identity is untouched).
        let rows = self.engine.query(
            "SELECT object_key FROM object_locations \
             WHERE object_key = ?1 AND quarantined = 0 LIMIT 1",
            &[SqlValue::Text(digest_key(object))],
        )?;
        Ok(!rows.is_empty())
    }

    fn object_locations(
        &mut self,
        object: &TypedDigest,
    ) -> Result<Vec<(String, String, bool)>, StoreError> {
        let rows = self.engine.query(
            "SELECT store_path, encoding, durable FROM object_locations \
             WHERE object_key = ?1 AND quarantined = 0 ORDER BY store_path",
            &[SqlValue::Text(digest_key(object))],
        )?;
        rows.iter()
            .map(|row| {
                let [path, encoding, durable] = row.as_slice() else {
                    return Err(StoreError::Corruption("object location shape".into()));
                };
                Ok((
                    expect_text(path, "store_path")?,
                    expect_text(encoding, "encoding")?,
                    expect_u64(durable, "durable")? != 0,
                ))
            })
            .collect()
    }

    fn record_object(&mut self, id: &TypedDigest, logical_size: u64) -> Result<(), StoreError> {
        self.intern(id.domain);
        let key = digest_key(id);
        let [algo, domain, bytes] = SqlMetadataStore::<E>::digest_params(id);
        let size = i64::try_from(logical_size)
            .map_err(|_| StoreError::Corruption("logical_size out of range".into()))?;
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO objects (key, algo, domain, bytes, logical_size) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(key),
                    algo,
                    domain,
                    bytes,
                    SqlValue::Int(size),
                ],
            )?;
            Ok(())
        })
    }

    fn add_location(
        &mut self,
        object: &TypedDigest,
        store_path: &str,
        verified_seq: Option<u64>,
        encoding: &str,
        durable: bool,
    ) -> Result<(), StoreError> {
        let key = digest_key(object);
        let path = store_path.to_owned();
        let encoding = encoding.to_owned();
        let verified = match verified_seq {
            None => SqlValue::Null,
            Some(v) => SqlValue::Int(
                i64::try_from(v)
                    .map_err(|_| StoreError::Corruption("verified_seq out of range".into()))?,
            ),
        };
        self.in_txn(move |engine| {
            // Location refreshes carry storage/verification observations,
            // not permission to release a prior containment decision. In
            // particular, pack reindexing never re-reads the member bytes.
            // Preserve the flag in the same transaction as the refresh so
            // neither stale inventories nor duplicate puts can clear it.
            let existing = engine.query(
                "SELECT quarantined FROM object_locations WHERE object_key = ?1 AND store_path = ?2",
                &[SqlValue::Text(key.clone()), SqlValue::Text(path.clone())],
            )?;
            let quarantined = if let Some(row) = existing.first() {
                let [value] = row.as_slice() else {
                    return Err(StoreError::Corruption("location quarantine shape".into()));
                };
                expect_u64(value, "quarantined")? != 0
            } else {
                false
            };
            engine.execute(
                "INSERT OR REPLACE INTO object_locations \
                 (object_key, store_path, verified_seq, encoding, quarantined, durable) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                &[
                    SqlValue::Text(key),
                    SqlValue::Text(path),
                    verified,
                    SqlValue::Text(encoding),
                    SqlValue::Int(i64::from(quarantined)),
                    SqlValue::Int(i64::from(durable)),
                ],
            )?;
            Ok(())
        })
    }

    fn object_durably_located(&mut self, object: &TypedDigest) -> Result<bool, StoreError> {
        // Same quarantine rule as `object_located`, plus the H032 gate:
        // only a copy recorded as satisfying the FULL durability policy
        // counts.
        let rows = self.engine.query(
            "SELECT object_key FROM object_locations \
             WHERE object_key = ?1 AND quarantined = 0 AND durable = 1 LIMIT 1",
            &[SqlValue::Text(digest_key(object))],
        )?;
        Ok(!rows.is_empty())
    }

    fn set_location_quarantined(
        &mut self,
        object: &TypedDigest,
        store_path: &str,
        quarantined: bool,
    ) -> Result<(), StoreError> {
        let key = digest_key(object);
        let path = store_path.to_owned();
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "UPDATE object_locations SET quarantined = ?1 \
                 WHERE object_key = ?2 AND store_path = ?3",
                &[
                    SqlValue::Int(i64::from(quarantined)),
                    SqlValue::Text(key),
                    SqlValue::Text(path),
                ],
            )?;
            if changed == 0 {
                return Err(StoreError::Corruption("unknown location".into()));
            }
            Ok(())
        })
    }

    fn add_object_edge(
        &mut self,
        parent: &TypedDigest,
        child: &TypedDigest,
        kind: &str,
    ) -> Result<(), StoreError> {
        let parent = digest_key(parent);
        let child = digest_key(child);
        let kind = kind.to_owned();
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO object_edges (parent_key, child_key, kind) \
                 VALUES (?1, ?2, ?3)",
                &[
                    SqlValue::Text(parent),
                    SqlValue::Text(child),
                    SqlValue::Text(kind),
                ],
            )?;
            Ok(())
        })
    }

    fn create_pin(
        &mut self,
        id: u128,
        root: &TypedDigest,
        owner: &str,
        class: &str,
        expires_at_seq: Option<u64>,
        evidence: Option<&str>,
        durable: bool,
        reason: &str,
    ) -> Result<(), StoreError> {
        let root = digest_key(root);
        let owner = owner.to_owned();
        let class = class.to_owned();
        let evidence = match evidence {
            None => SqlValue::Null,
            Some(e) => SqlValue::Text(e.to_owned()),
        };
        let reason = reason.to_owned();
        let expires = match expires_at_seq {
            None => SqlValue::Null,
            Some(v) => SqlValue::Int(
                i64::try_from(v)
                    .map_err(|_| StoreError::Corruption("expires_at_seq out of range".into()))?,
            ),
        };
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT INTO pins (id_hex, id, root_key, owner, class, expires_at_seq, released, \
                 evidence, renewal_seq, durable, reason) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?7, 0, ?8, ?9)",
                &[
                    SqlValue::Text(u128_hex(id)),
                    SqlValue::Blob(u128_blob(id)),
                    SqlValue::Text(root),
                    SqlValue::Text(owner),
                    SqlValue::Text(class),
                    expires,
                    evidence,
                    SqlValue::Int(i64::from(durable)),
                    SqlValue::Text(reason),
                ],
            )?;
            Ok(())
        })
    }

    fn renew_pin(&mut self, id: u128, renewal_seq: u64) -> Result<(), StoreError> {
        self.in_txn(move |engine| {
            let rows = engine.query(
                "SELECT renewal_seq, released FROM pins WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            let Some(row) = rows.first() else {
                return Err(StoreError::UnknownPin);
            };
            let [stored_seq, released] = row.as_slice() else {
                return Err(StoreError::Corruption("pin row shape".into()));
            };
            if expect_u64(released, "released")? != 0 {
                return Err(StoreError::PinReleased);
            }
            if renewal_seq <= expect_u64(stored_seq, "renewal_seq")? {
                return Err(StoreError::NonMonotonicPinRenewal);
            }
            let renewal = i64::try_from(renewal_seq)
                .map_err(|_| StoreError::Corruption("renewal_seq out of range".into()))?;
            engine.execute(
                "UPDATE pins SET renewal_seq = ?1 WHERE id_hex = ?2",
                &[SqlValue::Int(renewal), SqlValue::Text(u128_hex(id))],
            )?;
            Ok(())
        })
    }

    fn release_pin(&mut self, id: u128, owner: &str) -> Result<(), StoreError> {
        let owner = owner.to_owned();
        self.in_txn(move |engine| {
            let rows = engine.query(
                "SELECT owner FROM pins WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            let Some(row) = rows.first() else {
                return Err(StoreError::UnknownPin);
            };
            match row.first() {
                Some(SqlValue::Text(stored)) if *stored == owner => {}
                Some(SqlValue::Text(_)) => return Err(StoreError::PinOwnerMismatch),
                _ => return Err(StoreError::Corruption("pin owner shape".into())),
            }
            engine.execute(
                "UPDATE pins SET released = 1 WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            Ok(())
        })
    }

    fn put_recipe(&mut self, action: &TypedDigest, recipe: &TypedDigest) -> Result<(), StoreError> {
        self.intern(recipe.domain);
        let action = digest_key(action);
        let [algo, domain, bytes] = SqlMetadataStore::<E>::digest_params(recipe);
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO observed_input_recipes \
                 (action_key, recipe_algo, recipe_domain, recipe_bytes) VALUES (?1, ?2, ?3, ?4)",
                &[SqlValue::Text(action), algo, domain, bytes],
            )?;
            Ok(())
        })
    }

    fn put_key_breakdown(
        &mut self,
        action: &TypedDigest,
        component: &str,
        digest: &TypedDigest,
    ) -> Result<(), StoreError> {
        self.intern(digest.domain);
        let action = digest_key(action);
        let component = component.to_owned();
        let [algo, domain, bytes] = SqlMetadataStore::<E>::digest_params(digest);
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO key_breakdowns \
                 (action_key, component, algo, domain, bytes) VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(action),
                    SqlValue::Text(component),
                    algo,
                    domain,
                    bytes,
                ],
            )?;
            Ok(())
        })
    }

    fn set_trust(
        &mut self,
        action: &TypedDigest,
        state: &str,
        reason: &str,
    ) -> Result<(), StoreError> {
        let action = digest_key(action);
        let state = state.to_owned();
        let reason = reason.to_owned();
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO trust_states (action_key, state, reason) \
                 VALUES (?1, ?2, ?3)",
                &[
                    SqlValue::Text(action),
                    SqlValue::Text(state),
                    SqlValue::Text(reason),
                ],
            )?;
            Ok(())
        })
    }

    fn add_quarantine(
        &mut self,
        scope: QuarantineScope,
        subject: &str,
        reason: &str,
    ) -> Result<(), StoreError> {
        let subject = subject.to_owned();
        let reason = reason.to_owned();
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO quarantines (scope, subject, reason) \
                 VALUES (?1, ?2, ?3)",
                &[
                    SqlValue::Text(scope.as_str().to_owned()),
                    SqlValue::Text(subject),
                    SqlValue::Text(reason),
                ],
            )?;
            Ok(())
        })
    }

    fn record_verification_sample(
        &mut self,
        action: &TypedDigest,
        attempt: u128,
        passed: bool,
        seq: u64,
    ) -> Result<(), StoreError> {
        let action = digest_key(action);
        let seq =
            i64::try_from(seq).map_err(|_| StoreError::Corruption("seq out of range".into()))?;
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO verification_samples (action_key, attempt_hex, passed, seq) \
                 VALUES (?1, ?2, ?3, ?4)",
                &[
                    SqlValue::Text(action),
                    SqlValue::Text(u128_hex(attempt)),
                    SqlValue::Int(i64::from(passed)),
                    SqlValue::Int(seq),
                ],
            )?;
            Ok(())
        })
    }

    fn list_evidence_keys(&mut self, action: &TypedDigest) -> Result<Vec<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT evidence_domain, evidence_bytes FROM action_evidence_index \
             WHERE action_key = ?1 ORDER BY evidence_domain, evidence_bytes",
            &[SqlValue::Text(digest_key(action))],
        )?;
        evidence_key_rows(&rows)
    }

    fn list_evidence_keys_for_manifest(
        &mut self,
        manifest_key: &str,
    ) -> Result<Vec<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT evidence_domain, evidence_bytes FROM action_evidence_index \
             WHERE manifest_key = ?1 ORDER BY evidence_domain, evidence_bytes",
            &[SqlValue::Text(manifest_key.to_owned())],
        )?;
        evidence_key_rows(&rows)
    }

    fn list_verification_samples(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Vec<VerificationSampleRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT attempt_hex, passed, seq FROM verification_samples \
             WHERE action_key = ?1 ORDER BY attempt_hex, seq",
            &[SqlValue::Text(digest_key(action))],
        )?;
        rows.iter()
            .map(|row| {
                let [attempt_hex, passed, seq] = row.as_slice() else {
                    return Err(StoreError::Corruption("verification sample shape".into()));
                };
                Ok(VerificationSampleRow {
                    attempt_hex: expect_text(attempt_hex, "attempt_hex")?,
                    passed: expect_u64(passed, "passed")? != 0,
                    seq: expect_u64(seq, "seq")?,
                })
            })
            .collect()
    }

    fn attempt_worker_by_hex(&mut self, attempt_hex: &str) -> Result<Option<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT worker FROM action_attempts WHERE id_hex = ?1",
            &[SqlValue::Text(attempt_hex.to_owned())],
        )?;
        match rows.first().and_then(|r| r.first()) {
            None => Ok(None),
            Some(v) => Ok(Some(expect_text(v, "worker")?)),
        }
    }

    fn gc_snapshot(&mut self, seq: u64) -> Result<GcSnapshot, StoreError> {
        let seq =
            i64::try_from(seq).map_err(|_| StoreError::Corruption("seq out of range".into()))?;
        self.in_txn(move |engine| {
            let pinned = engine.query(
                "SELECT root_key FROM pins WHERE released = 0 ORDER BY root_key",
                &[],
            )?;
            let located = engine.query(
                "SELECT DISTINCT object_key FROM object_locations ORDER BY object_key",
                &[],
            )?;
            let text_col = |rows: Vec<Vec<SqlValue>>| -> Result<Vec<String>, StoreError> {
                rows.into_iter()
                    .map(|row| match row.into_iter().next() {
                        Some(SqlValue::Text(t)) => Ok(t),
                        _ => Err(StoreError::Corruption("gc column shape".into())),
                    })
                    .collect()
            };
            let pinned_roots = text_col(pinned)?;
            let located_objects = text_col(located)?;
            // Reachability closure over object_edges from the unreleased
            // pin roots (cycle-safe via the visited set).
            let edges = engine.query(
                "SELECT parent_key, child_key FROM object_edges ORDER BY parent_key, child_key",
                &[],
            )?;
            let mut children: std::collections::BTreeMap<String, Vec<String>> =
                std::collections::BTreeMap::new();
            for row in edges {
                let [SqlValue::Text(parent), SqlValue::Text(child)] = row.as_slice() else {
                    return Err(StoreError::Corruption("edge row shape".into()));
                };
                children
                    .entry(parent.clone())
                    .or_default()
                    .push(child.clone());
            }
            let mut reachable: std::collections::BTreeSet<String> =
                std::collections::BTreeSet::new();
            let mut frontier: Vec<String> = pinned_roots.clone();
            while let Some(key) = frontier.pop() {
                if !reachable.insert(key.clone()) {
                    continue;
                }
                if let Some(next) = children.get(&key) {
                    frontier.extend(next.iter().cloned());
                }
            }
            let reachable_from_pins: Vec<String> = reachable.into_iter().collect();
            let pinned_count = i64::try_from(pinned_roots.len())
                .map_err(|_| StoreError::Corruption("pin count".into()))?;
            let located_count = i64::try_from(located_objects.len())
                .map_err(|_| StoreError::Corruption("location count".into()))?;
            let reachable_count = i64::try_from(reachable_from_pins.len())
                .map_err(|_| StoreError::Corruption("reachable count".into()))?;
            engine.execute(
                "INSERT INTO gc_runs (seq, pinned_roots, located_objects, reachable_objects) \
                 VALUES (?1, ?2, ?3, ?4)",
                &[
                    SqlValue::Int(seq),
                    SqlValue::Int(pinned_count),
                    SqlValue::Int(located_count),
                    SqlValue::Int(reachable_count),
                ],
            )?;
            Ok(GcSnapshot {
                pinned_roots,
                located_objects,
                reachable_from_pins,
            })
        })
    }

    fn reconciliation_scan(&mut self) -> Result<Vec<ReconciliationRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT object_key, store_path, verified_seq, encoding, quarantined \
             FROM object_locations ORDER BY object_key, store_path",
            &[],
        )?;
        rows.into_iter()
            .map(|row| {
                let [key, path, verified, encoding, quarantined] = row.as_slice() else {
                    return Err(StoreError::Corruption("location row shape".into()));
                };
                let (SqlValue::Text(key), SqlValue::Text(path), SqlValue::Text(encoding)) =
                    (key, path, encoding)
                else {
                    return Err(StoreError::Corruption("location column shape".into()));
                };
                let verified_seq = match verified {
                    SqlValue::Null => None,
                    other => Some(expect_u64(other, "verified_seq")?),
                };
                Ok(ReconciliationRow {
                    object_key: key.clone(),
                    store_path: path.clone(),
                    verified_seq,
                    encoding: encoding.clone(),
                    quarantined: expect_u64(quarantined, "quarantined")? != 0,
                })
            })
            .collect()
    }

    fn remove_location_by_key(
        &mut self,
        object_key: &str,
        store_path: &str,
    ) -> Result<bool, StoreError> {
        let object_key = object_key.to_owned();
        let store_path = store_path.to_owned();
        self.in_txn(move |engine| {
            let removed = engine.execute(
                "DELETE FROM object_locations WHERE object_key = ?1 AND store_path = ?2",
                &[SqlValue::Text(object_key), SqlValue::Text(store_path)],
            )?;
            Ok(removed > 0)
        })
    }

    fn record_gc_receipt(&mut self, receipt: &GcReceiptRow) -> Result<(), StoreError> {
        let to_int = |v: u64, what: &str| -> Result<i64, StoreError> {
            i64::try_from(v).map_err(|_| StoreError::Corruption(format!("{what} out of range")))
        };
        let seq = to_int(receipt.seq, "seq")?;
        let planned = to_int(receipt.planned, "planned")?;
        let reclaimed = to_int(receipt.reclaimed, "reclaimed")?;
        let skipped = to_int(receipt.skipped, "skipped")?;
        let mode = receipt.mode.clone();
        let truncated = i64::from(receipt.truncated);
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT INTO gc_receipts (seq, mode, planned, reclaimed, skipped, truncated) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                &[
                    SqlValue::Int(seq),
                    SqlValue::Text(mode),
                    SqlValue::Int(planned),
                    SqlValue::Int(reclaimed),
                    SqlValue::Int(skipped),
                    SqlValue::Int(truncated),
                ],
            )?;
            Ok(())
        })
    }

    fn add_gc_tombstone(
        &mut self,
        object_key: &str,
        store_path: &str,
        marked_seq: u64,
        grace_until_seq: u64,
    ) -> Result<(), StoreError> {
        let object_key = object_key.to_owned();
        let store_path = store_path.to_owned();
        let marked = i64::try_from(marked_seq)
            .map_err(|_| StoreError::Corruption("marked_seq out of range".into()))?;
        let grace = i64::try_from(grace_until_seq)
            .map_err(|_| StoreError::Corruption("grace_until_seq out of range".into()))?;
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT object_key FROM gc_tombstones WHERE object_key = ?1 AND store_path = ?2",
                &[
                    SqlValue::Text(object_key.clone()),
                    SqlValue::Text(store_path.clone()),
                ],
            )?;
            if !existing.is_empty() {
                // Idempotent re-mark keeps the ORIGINAL deadline.
                return Ok(());
            }
            engine.execute(
                "INSERT INTO gc_tombstones (object_key, store_path, marked_seq, grace_until_seq) \
                 VALUES (?1, ?2, ?3, ?4)",
                &[
                    SqlValue::Text(object_key),
                    SqlValue::Text(store_path),
                    SqlValue::Int(marked),
                    SqlValue::Int(grace),
                ],
            )?;
            Ok(())
        })
    }

    fn due_gc_tombstones(&mut self, now_seq: u64) -> Result<Vec<GcTombstoneRow>, StoreError> {
        // Clamp: any u64 beyond i64::MAX is later than every storable
        // deadline, so the clamp is semantically exact.
        let now = i64::try_from(now_seq).unwrap_or(i64::MAX);
        let rows = self.engine.query(
            "SELECT object_key, store_path, marked_seq, grace_until_seq FROM gc_tombstones \
             WHERE grace_until_seq <= ?1 ORDER BY object_key, store_path",
            &[SqlValue::Int(now)],
        )?;
        rows.into_iter()
            .map(|row| {
                let [key, path, marked, grace] = row.as_slice() else {
                    return Err(StoreError::Corruption("tombstone row shape".into()));
                };
                let (SqlValue::Text(key), SqlValue::Text(path)) = (key, path) else {
                    return Err(StoreError::Corruption("tombstone column shape".into()));
                };
                Ok(GcTombstoneRow {
                    object_key: key.clone(),
                    store_path: path.clone(),
                    marked_seq: expect_u64(marked, "marked_seq")?,
                    grace_until_seq: expect_u64(grace, "grace_until_seq")?,
                })
            })
            .collect()
    }

    fn remove_gc_tombstone(
        &mut self,
        object_key: &str,
        store_path: &str,
    ) -> Result<bool, StoreError> {
        let object_key = object_key.to_owned();
        let store_path = store_path.to_owned();
        self.in_txn(move |engine| {
            let removed = engine.execute(
                "DELETE FROM gc_tombstones WHERE object_key = ?1 AND store_path = ?2",
                &[SqlValue::Text(object_key), SqlValue::Text(store_path)],
            )?;
            Ok(removed > 0)
        })
    }

    fn list_publications(&mut self) -> Result<Vec<(String, String)>, StoreError> {
        let rows = self.engine.query(
            "SELECT action_key, pin_hex FROM action_publications ORDER BY action_key",
            &[],
        )?;
        rows.into_iter()
            .map(|row| match row.as_slice() {
                [SqlValue::Text(action), SqlValue::Text(pin)] => Ok((action.clone(), pin.clone())),
                _ => Err(StoreError::Corruption("publication list shape".into())),
            })
            .collect()
    }

    fn publications_missing_their_generation(&mut self) -> Result<Vec<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT p.action_key FROM action_publications p \
             LEFT JOIN action_generations g ON g.id_hex = p.winner_generation_hex \
             WHERE g.id_hex IS NULL ORDER BY p.action_key",
            &[],
        )?;
        rows.into_iter()
            .map(|row| match row.as_slice() {
                [SqlValue::Text(action)] => Ok(action.clone()),
                _ => Err(StoreError::Corruption(
                    "orphaned-publication list shape".into(),
                )),
            })
            .collect()
    }

    fn pin_row(&mut self, id: u128) -> Result<Option<PinRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT root_key, owner, class, expires_at_seq, released, renewal_seq \
             FROM pins WHERE id_hex = ?1",
            &[SqlValue::Text(u128_hex(id))],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [root_key, owner, class, expires, released, renewal] = row.as_slice() else {
            return Err(StoreError::Corruption("pin row shape".into()));
        };
        let (SqlValue::Text(root_key), SqlValue::Text(owner), SqlValue::Text(class)) =
            (root_key, owner, class)
        else {
            return Err(StoreError::Corruption("pin column shape".into()));
        };
        let expires_at_seq = match expires {
            SqlValue::Null => None,
            other => Some(expect_u64(other, "expires_at_seq")?),
        };
        Ok(Some(PinRow {
            root_key: root_key.clone(),
            owner: owner.clone(),
            class: class.clone(),
            expires_at_seq,
            released: expect_u64(released, "released")? != 0,
            renewal_seq: expect_u64(renewal, "renewal_seq")?,
        }))
    }

    fn pin_released_by_hex(&mut self, pin_hex: &str) -> Result<Option<bool>, StoreError> {
        let rows = self.engine.query(
            "SELECT released FROM pins WHERE id_hex = ?1",
            &[SqlValue::Text(pin_hex.to_owned())],
        )?;
        match rows.first().and_then(|r| r.first()) {
            None => Ok(None),
            Some(v) => Ok(Some(expect_u64(v, "released")? != 0)),
        }
    }

    fn has_serving_state_key(&mut self, action_key: &str) -> Result<bool, StoreError> {
        let rows = self.engine.query(
            "SELECT action_key FROM action_serving_states WHERE action_key = ?1",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        Ok(!rows.is_empty())
    }

    fn has_evidence_key(&mut self, action_key: &str) -> Result<bool, StoreError> {
        let rows = self.engine.query(
            "SELECT action_key FROM action_evidence_index WHERE action_key = ?1 LIMIT 1",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        Ok(!rows.is_empty())
    }

    fn authority_count(&mut self) -> Result<u64, StoreError> {
        let rows = self
            .engine
            .query("SELECT COUNT(*) FROM coordinator_authorities", &[])?;
        match rows.first().and_then(|r| r.first()) {
            Some(v) => expect_u64(v, "authority count"),
            None => Err(StoreError::Corruption("count shape".into())),
        }
    }

    fn generation_count(&mut self) -> Result<u64, StoreError> {
        let rows = self
            .engine
            .query("SELECT COUNT(*) FROM action_generations", &[])?;
        match rows.first().and_then(|r| r.first()) {
            Some(v) => expect_u64(v, "generation count"),
            None => Err(StoreError::Corruption("count shape".into())),
        }
    }

    fn has_generation_high_water(&mut self) -> Result<bool, StoreError> {
        let rows = self.engine.query(
            "SELECT kind FROM generation_high_water WHERE kind = 'action-generation'",
            &[],
        )?;
        Ok(!rows.is_empty())
    }

    fn record_eviction_tombstone(
        &mut self,
        action: &TypedDigest,
        semantic: &TypedDigest,
        observable: &TypedDigest,
        evicted_seq: u64,
    ) -> Result<(), StoreError> {
        self.intern(semantic.domain);
        self.intern(observable.domain);
        let action = digest_key(action);
        let [s_algo, s_domain, s_bytes] = SqlMetadataStore::<E>::digest_params(semantic);
        let [o_algo, o_domain, o_bytes] = SqlMetadataStore::<E>::digest_params(observable);
        let seq = i64::try_from(evicted_seq)
            .map_err(|_| StoreError::Corruption("evicted_seq out of range".into()))?;
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR REPLACE INTO eviction_tombstones \
                 (action_key, semantic_algo, semantic_domain, semantic_bytes, \
                  observable_algo, observable_domain, observable_bytes, evicted_seq) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                &[
                    SqlValue::Text(action),
                    s_algo,
                    s_domain,
                    s_bytes,
                    o_algo,
                    o_domain,
                    o_bytes,
                    SqlValue::Int(seq),
                ],
            )?;
            Ok(())
        })
    }

    fn eviction_tombstone(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Option<(TypedDigest, TypedDigest)>, StoreError> {
        let rows = self.engine.query(
            "SELECT semantic_algo, semantic_domain, semantic_bytes, \
             observable_algo, observable_domain, observable_bytes \
             FROM eviction_tombstones WHERE action_key = ?1",
            &[SqlValue::Text(digest_key(action))],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [s_algo, s_domain, s_bytes, o_algo, o_domain, o_bytes] = row.as_slice() else {
            return Err(StoreError::Corruption("eviction tombstone shape".into()));
        };
        let semantic = self.restore_digest(s_algo, s_domain, s_bytes)?;
        let observable = self.restore_digest(o_algo, o_domain, o_bytes)?;
        Ok(Some((semantic, observable)))
    }

    fn consume_eviction_tombstone(&mut self, action: &TypedDigest) -> Result<bool, StoreError> {
        let action = digest_key(action);
        self.in_txn(move |engine| {
            let removed = engine.execute(
                "DELETE FROM eviction_tombstones WHERE action_key = ?1",
                &[SqlValue::Text(action)],
            )?;
            Ok(removed > 0)
        })
    }

    fn record_operator_reset(&mut self, generation: u64, seq: u64) -> Result<(), StoreError> {
        let generation_int = i64::try_from(generation)
            .map_err(|_| StoreError::Corruption("reset generation out of range".into()))?;
        let seq =
            i64::try_from(seq).map_err(|_| StoreError::Corruption("seq out of range".into()))?;
        self.in_txn(move |engine| {
            let rows = engine.query("SELECT MAX(generation) FROM operator_resets", &[])?;
            if let Some(SqlValue::Int(highest)) = rows.first().and_then(|r| r.first())
                && generation_int <= *highest
            {
                return Err(StoreError::StaleOperatorReset);
            }
            engine.execute(
                "INSERT INTO operator_resets (generation, applied_seq) VALUES (?1, ?2)",
                &[SqlValue::Int(generation_int), SqlValue::Int(seq)],
            )?;
            Ok(())
        })
    }

    fn highest_operator_reset(&mut self) -> Result<Option<u64>, StoreError> {
        let rows = self
            .engine
            .query("SELECT MAX(generation) FROM operator_resets", &[])?;
        match rows.first().and_then(|r| r.first()) {
            Some(SqlValue::Int(v)) => {
                Ok(Some(u64::try_from(*v).map_err(|_| {
                    StoreError::Corruption("negative reset generation".into())
                })?))
            }
            _ => Ok(None),
        }
    }

    fn serving_disposition_key(&mut self, action_key: &str) -> Result<Option<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT disposition FROM action_serving_states WHERE action_key = ?1",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        match rows.first().and_then(|r| r.first()) {
            None => Ok(None),
            Some(SqlValue::Text(d)) => Ok(Some(d.clone())),
            Some(_) => Err(StoreError::Corruption("disposition shape".into())),
        }
    }

    fn set_serving_disposition_key(
        &mut self,
        action_key: &str,
        disposition: &str,
    ) -> Result<(), StoreError> {
        self.in_txn(|engine| Self::set_serving_disposition_row(engine, action_key, disposition))
    }

    fn set_serving_disposition_for_attempt(
        &mut self,
        authority: &AttemptAuthority,
        disposition: &str,
        own_monotonic_now_ms: &dyn Fn() -> u64,
    ) -> Result<(), StoreError> {
        self.in_txn(|engine| {
            Self::require_live_attempt(engine, authority, own_monotonic_now_ms)?;
            Self::set_serving_disposition_row(
                engine,
                &digest_key(&authority.action_key),
                disposition,
            )?;
            Self::require_live_attempt(engine, authority, own_monotonic_now_ms)
        })
    }
    fn apply_operator_reset_to_peer(
        &mut self,
        authority: &TypedDigest,
        peer_id: &str,
        reset_generation: u64,
        credential_generation: u64,
        term: u64,
        incarnation: u128,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let peer = peer_id.to_owned();
        let reset_int = i64::try_from(reset_generation)
            .map_err(|_| StoreError::Corruption("reset generation out of range".into()))?;
        let term_int = to_seq(term, "term")?;
        let generation_int = to_seq(credential_generation, "credential_generation")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let ledger = engine.query("SELECT MAX(generation) FROM operator_resets", &[])?;
            if let Some(SqlValue::Int(highest)) = ledger.first().and_then(|r| r.first())
                && reset_int <= *highest
            {
                return Err(StoreError::StaleOperatorReset);
            }
            engine.execute(
                "INSERT INTO operator_resets (generation, applied_seq) VALUES (?1, ?2)",
                &[SqlValue::Int(reset_int), SqlValue::Int(reset_int)],
            )?;
            engine.execute(
                "INSERT OR REPLACE INTO peer_authority_high_water \
                 (peer_id, term, observed_seq, incarnation, credential_generation) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(peer),
                    SqlValue::Int(term_int),
                    SqlValue::Int(reset_int),
                    SqlValue::Blob(incarnation.to_be_bytes().to_vec()),
                    SqlValue::Int(generation_int),
                ],
            )?;
            Ok(())
        })
    }

    fn record_peer_authority_high_water(
        &mut self,
        authority: &TypedDigest,
        peer_id: &str,
        credential_generation: u64,
        term: u64,
        incarnation: u128,
        observed_seq: u64,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let peer = peer_id.to_owned();
        let term_int = to_seq(term, "term")?;
        let generation_int = to_seq(credential_generation, "credential_generation")?;
        let observed = to_seq(observed_seq, "observed_seq")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let rows = engine.query(
                "SELECT term, incarnation, credential_generation FROM peer_authority_high_water WHERE peer_id = ?1",
                &[SqlValue::Text(peer.clone())],
            )?;
            if let Some(row) = rows.first() {
                let stored = expect_u64(
                    row.first()
                        .ok_or_else(|| StoreError::Corruption("peer high-water shape".into()))?,
                    "peer term",
                )?;
                let stored_generation = match row.get(2) {
                    Some(SqlValue::Null) => return Err(StoreError::StalePeerAuthority),
                    Some(value) => expect_u64(value, "peer credential generation")?,
                    None => return Err(StoreError::Corruption("peer high-water shape".into())),
                };
                if (credential_generation, term) < (stored_generation, stored) {
                    return Err(StoreError::StalePeerAuthority);
                }
                if (credential_generation, term) == (stored_generation, stored) {
                    if !matches!(row.get(1), Some(SqlValue::Blob(bytes)) if bytes.as_slice() == incarnation.to_be_bytes()) {
                        return Err(StoreError::StalePeerAuthority);
                    }
                    return Ok(());
                }
            }
            engine.execute(
                "INSERT OR REPLACE INTO peer_authority_high_water \
                 (peer_id, term, observed_seq, incarnation, credential_generation) VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(peer),
                    SqlValue::Int(term_int),
                    SqlValue::Int(observed),
                    SqlValue::Blob(incarnation.to_be_bytes().to_vec()),
                    SqlValue::Int(generation_int),
                ],
            )?;
            Ok(())
        })
    }

    fn peer_authority_high_water(
        &mut self,
        peer_id: &str,
    ) -> Result<Option<(u64, u64, u64)>, StoreError> {
        let rows = self.engine.query(
            "SELECT credential_generation, term, observed_seq FROM peer_authority_high_water WHERE peer_id = ?1",
            &[SqlValue::Text(peer_id.to_owned())],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [generation, term, observed] = row.as_slice() else {
            return Err(StoreError::Corruption("peer high-water shape".into()));
        };
        if matches!(generation, SqlValue::Null) {
            return Err(StoreError::StalePeerAuthority);
        }
        Ok(Some((
            expect_u64(generation, "peer credential generation")?,
            expect_u64(term, "peer term")?,
            expect_u64(observed, "observed_seq")?,
        )))
    }

    fn admit_worker_session(
        &mut self,
        authority: &TypedDigest,
        offer: &WorkerSessionOffer,
        started_seq: u64,
    ) -> Result<WorkerAdmission, StoreError> {
        let authority = authority.clone();
        let offer = offer.clone();
        let worker = offer.worker_peer_id.0.clone();
        let started = to_seq(started_seq, "started_seq")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let rows = engine.query(
                "SELECT highest_boot_generation, incarnation, active, \
                 operator_reenrollment_generation, clone_ambiguous \
                 FROM worker_incarnation_fences \
                 WHERE worker = ?1",
                &[SqlValue::Text(worker.clone())],
            )?;
            let (admission, fence, revoke_prior_leases) = match rows.as_slice() {
                [] => (
                    WorkerAdmission::AdmitNewGeneration,
                    WorkerIncarnationFenceRecord {
                        worker_peer_id: offer.worker_peer_id.clone(),
                        highest_boot_generation: offer.boot_generation,
                        active_incarnation: Some(offer.incarnation),
                        clone_ambiguous: false,
                        operator_reenrollment_generation: offer
                            .reenrollment_proof
                            .unwrap_or_default(),
                    },
                    false,
                ),
                [row] => {
                    let prior_incarnation =
                        WorkerIncarnationId(expect_u128(&row[1], "worker incarnation")?);
                    let mut fence = decode_worker_incarnation_fence(&worker, row)?;
                    let admission = fence.evaluate(&offer);
                    let revoke_prior_leases = match admission {
                        WorkerAdmission::AdmitNewGeneration => {
                            fence.highest_boot_generation = offer.boot_generation;
                            fence.active_incarnation = Some(offer.incarnation);
                            fence.clone_ambiguous = false;
                            true
                        }
                        WorkerAdmission::AdmitReconnect => false,
                        WorkerAdmission::AdmitResume => {
                            fence.active_incarnation = Some(offer.incarnation);
                            prior_incarnation != offer.incarnation
                        }
                        WorkerAdmission::AdmitViaReenrollment => {
                            let proof = offer.reenrollment_proof.ok_or_else(|| {
                                StoreError::Corruption(
                                    "reenrollment admission without proof".into(),
                                )
                            })?;
                            // `evaluate` admits re-enrollment only at or
                            // above the durable global high-water. Never
                            // lower it: an old clone at the former mark
                            // must remain stale after operator recovery.
                            fence.highest_boot_generation = offer.boot_generation;
                            fence.active_incarnation = Some(offer.incarnation);
                            fence.clone_ambiguous = false;
                            fence.operator_reenrollment_generation = proof;
                            true
                        }
                        WorkerAdmission::RejectCloneAmbiguity => {
                            engine.execute(
                                "UPDATE worker_incarnation_fences \
                                 SET clone_ambiguous = 1 WHERE worker = ?1",
                                &[SqlValue::Text(worker.clone())],
                            )?;
                            SqlMetadataStore::<E>::revoke_worker_leases(engine, &worker)?;
                            return Ok(admission);
                        }
                        WorkerAdmission::RejectStaleBootGeneration
                        | WorkerAdmission::RejectIdentityMismatch => return Ok(admission),
                    };
                    (admission, fence, revoke_prior_leases)
                }
                _ => {
                    return Err(StoreError::Corruption("duplicate worker fence rows".into()));
                }
            };

            if revoke_prior_leases {
                SqlMetadataStore::<E>::revoke_worker_leases(engine, &worker)?;
            }

            let active_incarnation = fence.active_incarnation.ok_or_else(|| {
                StoreError::Corruption("admitted worker fence is inactive".into())
            })?;
            let existing = engine.query(
                "SELECT incarnation, ended_seq FROM worker_sessions \
                 WHERE worker = ?1 AND started_seq = ?2",
                &[SqlValue::Text(worker.clone()), SqlValue::Int(started)],
            )?;
            let insert_session = match existing.as_slice() {
                [] => true,
                [row] => {
                    let [stored_incarnation, ended_seq] = row.as_slice() else {
                        return Err(StoreError::Corruption("worker session shape".into()));
                    };
                    if expect_u128(stored_incarnation, "session incarnation")?
                        == active_incarnation.0
                        && matches!(ended_seq, SqlValue::Null)
                    {
                        false
                    } else {
                        return Err(StoreError::AppendConflict("worker_sessions".into()));
                    }
                }
                _ => {
                    return Err(StoreError::Corruption(
                        "duplicate worker session rows".into(),
                    ));
                }
            };

            engine.execute(
                "INSERT OR REPLACE INTO worker_incarnation_fences \
                 (worker, incarnation, highest_boot_generation, active, \
                  operator_reenrollment_generation, clone_ambiguous) \
                 VALUES (?1, ?2, ?3, 1, ?4, ?5)",
                &[
                    SqlValue::Text(worker.clone()),
                    SqlValue::Blob(u128_blob(active_incarnation.0)),
                    SqlValue::Blob(u64_blob(fence.highest_boot_generation.0)),
                    SqlValue::Blob(u64_blob(fence.operator_reenrollment_generation)),
                    SqlValue::Int(i64::from(fence.clone_ambiguous)),
                ],
            )?;
            if insert_session {
                engine.execute(
                    "INSERT INTO worker_sessions \
                     (worker, incarnation, started_seq, ended_seq) VALUES (?1, ?2, ?3, NULL)",
                    &[
                        SqlValue::Text(worker),
                        SqlValue::Blob(u128_blob(active_incarnation.0)),
                        SqlValue::Int(started),
                    ],
                )?;
            }
            Ok(admission)
        })
    }

    fn release_worker_session(
        &mut self,
        authority: &TypedDigest,
        worker: &PeerId,
        incarnation: WorkerIncarnationId,
        started_seq: u64,
        ended_seq: u64,
    ) -> Result<bool, StoreError> {
        let authority = authority.clone();
        let worker = worker.0.clone();
        let started = to_seq(started_seq, "started_seq")?;
        let ended = to_seq(ended_seq, "ended_seq")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let rows = engine.query(
                "SELECT highest_boot_generation, incarnation, active, \
                 operator_reenrollment_generation, clone_ambiguous \
                 FROM worker_incarnation_fences \
                 WHERE worker = ?1",
                &[SqlValue::Text(worker.clone())],
            )?;
            let fence = match rows.as_slice() {
                [] => return Ok(false),
                [row] => decode_worker_incarnation_fence(&worker, row)?,
                _ => {
                    return Err(StoreError::Corruption("duplicate worker fence rows".into()));
                }
            };
            if fence.active_incarnation != Some(incarnation) {
                return Ok(false);
            }
            let ended_session = engine.execute(
                "UPDATE worker_sessions SET ended_seq = ?1 \
                 WHERE worker = ?2 AND incarnation = ?3 AND started_seq = ?4 \
                 AND ended_seq IS NULL",
                &[
                    SqlValue::Int(ended),
                    SqlValue::Text(worker.clone()),
                    SqlValue::Blob(u128_blob(incarnation.0)),
                    SqlValue::Int(started),
                ],
            )?;
            if ended_session == 0 {
                return Ok(false);
            }
            let remaining = engine.query(
                "SELECT COUNT(*) FROM worker_sessions \
                 WHERE worker = ?1 AND incarnation = ?2 AND ended_seq IS NULL",
                &[
                    SqlValue::Text(worker.clone()),
                    SqlValue::Blob(u128_blob(incarnation.0)),
                ],
            )?;
            let remaining = match remaining.as_slice() {
                [row] => match row.as_slice() {
                    [value] => expect_u64(value, "open worker session count")?,
                    _ => {
                        return Err(StoreError::Corruption(
                            "open worker session count shape".into(),
                        ));
                    }
                },
                _ => {
                    return Err(StoreError::Corruption(
                        "open worker session count shape".into(),
                    ));
                }
            };
            if remaining > 0 {
                return Ok(true);
            }
            let cleared = engine.execute(
                "UPDATE worker_incarnation_fences SET active = 0 \
                 WHERE worker = ?1 AND incarnation = ?2 AND active = 1",
                &[
                    SqlValue::Text(worker),
                    SqlValue::Blob(u128_blob(incarnation.0)),
                ],
            )?;
            if cleared != 1 {
                return Err(StoreError::Corruption(
                    "worker session ended without clearing its fence".into(),
                ));
            }
            Ok(true)
        })
    }

    fn worker_incarnation_fence(
        &mut self,
        worker: &PeerId,
    ) -> Result<Option<WorkerIncarnationFenceRecord>, StoreError> {
        let rows = self.engine.query(
            "SELECT highest_boot_generation, incarnation, active, \
             operator_reenrollment_generation, clone_ambiguous \
             FROM worker_incarnation_fences \
             WHERE worker = ?1",
            &[SqlValue::Text(worker.0.clone())],
        )?;
        match rows.as_slice() {
            [] => Ok(None),
            [row] => decode_worker_incarnation_fence(&worker.0, row).map(Some),
            _ => Err(StoreError::Corruption("duplicate worker fence rows".into())),
        }
    }

    fn advance_edge_fence(
        &mut self,
        authority: &TypedDigest,
        edge_id: &str,
        incarnation: u128,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let edge = edge_id.to_owned();
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let rows = engine.query(
                "SELECT incarnation FROM edge_incarnation_fences WHERE edge_id = ?1",
                &[SqlValue::Text(edge.clone())],
            )?;
            if let Some(row) = rows.first() {
                let stored = expect_u128(
                    row.first()
                        .ok_or_else(|| StoreError::Corruption("edge fence shape".into()))?,
                    "edge fence",
                )?;
                if incarnation < stored {
                    return Err(StoreError::StaleEdgeIncarnation);
                }
                if incarnation == stored {
                    return Ok(()); // idempotent
                }
            }
            engine.execute(
                "INSERT OR REPLACE INTO edge_incarnation_fences (edge_id, incarnation) \
                 VALUES (?1, ?2)",
                &[SqlValue::Text(edge), SqlValue::Blob(u128_blob(incarnation))],
            )?;
            Ok(())
        })
    }

    fn edge_fence(&mut self, edge_id: &str) -> Result<Option<u128>, StoreError> {
        let rows = self.engine.query(
            "SELECT incarnation FROM edge_incarnation_fences WHERE edge_id = ?1",
            &[SqlValue::Text(edge_id.to_owned())],
        )?;
        match rows.first().and_then(|r| r.first()) {
            None => Ok(None),
            Some(v) => Ok(Some(expect_u128(v, "edge fence")?)),
        }
    }

    fn begin_edge_handoff(
        &mut self,
        authority: &TypedDigest,
        edge_id: &str,
        active_incarnation: u128,
        predecessor_incarnation: u128,
        begun_seq: u64,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let edge = edge_id.to_owned();
        let begun = to_seq(begun_seq, "begun_seq")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            // At most one handoff row per edge; only a RESOLVED row may
            // be replaced.
            let rows = engine.query(
                "SELECT active_incarnation, predecessor_incarnation, resolved \
                 FROM edge_handoffs WHERE edge_id = ?1",
                &[SqlValue::Text(edge.clone())],
            )?;
            if let Some(row) = rows.first() {
                let [active, predecessor, resolved] = row.as_slice() else {
                    return Err(StoreError::Corruption("edge handoff shape".into()));
                };
                if expect_u64(resolved, "resolved")? == 0 {
                    if expect_u128(active, "active incarnation")? == active_incarnation
                        && expect_u128(predecessor, "predecessor incarnation")?
                            == predecessor_incarnation
                    {
                        return Ok(()); // idempotent re-begin
                    }
                    return Err(StoreError::EdgeHandoffActive);
                }
            }
            // The NAMED predecessor must be the fenced incarnation when
            // a fence exists.
            let fence = engine.query(
                "SELECT incarnation FROM edge_incarnation_fences WHERE edge_id = ?1",
                &[SqlValue::Text(edge.clone())],
            )?;
            if let Some(v) = fence.first().and_then(|r| r.first())
                && expect_u128(v, "edge fence")? != predecessor_incarnation
            {
                return Err(StoreError::EdgeHandoffPredecessorMismatch);
            }
            if active_incarnation <= predecessor_incarnation {
                return Err(StoreError::StaleEdgeIncarnation);
            }
            engine.execute(
                "INSERT OR REPLACE INTO edge_handoffs \
                 (edge_id, active_incarnation, predecessor_incarnation, begun_seq, resolved) \
                 VALUES (?1, ?2, ?3, ?4, 0)",
                &[
                    SqlValue::Text(edge),
                    SqlValue::Blob(u128_blob(active_incarnation)),
                    SqlValue::Blob(u128_blob(predecessor_incarnation)),
                    SqlValue::Int(begun),
                ],
            )?;
            Ok(())
        })
    }

    fn resolve_edge_handoff(
        &mut self,
        authority: &TypedDigest,
        edge_id: &str,
        active_incarnation: u128,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let edge = edge_id.to_owned();
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let rows = engine.query(
                "SELECT active_incarnation, resolved FROM edge_handoffs WHERE edge_id = ?1",
                &[SqlValue::Text(edge.clone())],
            )?;
            let Some(row) = rows.first() else {
                return Err(StoreError::UnknownEdgeHandoff);
            };
            let [active, resolved] = row.as_slice() else {
                return Err(StoreError::Corruption("edge handoff shape".into()));
            };
            if expect_u64(resolved, "resolved")? != 0
                || expect_u128(active, "active incarnation")? != active_incarnation
            {
                return Err(StoreError::UnknownEdgeHandoff);
            }
            engine.execute(
                "UPDATE edge_handoffs SET resolved = 1 WHERE edge_id = ?1",
                &[SqlValue::Text(edge.clone())],
            )?;
            // Fence advance in the SAME transaction: the handoff is not
            // resolved unless the edge is fenced at the new incarnation.
            engine.execute(
                "INSERT OR REPLACE INTO edge_incarnation_fences (edge_id, incarnation) \
                 VALUES (?1, ?2)",
                &[
                    SqlValue::Text(edge),
                    SqlValue::Blob(u128_blob(active_incarnation)),
                ],
            )?;
            Ok(())
        })
    }

    fn active_edge_handoff(&mut self, edge_id: &str) -> Result<Option<EdgeHandoffRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT active_incarnation, predecessor_incarnation, begun_seq \
             FROM edge_handoffs WHERE edge_id = ?1 AND resolved = 0",
            &[SqlValue::Text(edge_id.to_owned())],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [active, predecessor, begun] = row.as_slice() else {
            return Err(StoreError::Corruption("edge handoff shape".into()));
        };
        Ok(Some(EdgeHandoffRow {
            active_incarnation: expect_u128(active, "active incarnation")?,
            predecessor_incarnation: expect_u128(predecessor, "predecessor incarnation")?,
            begun_seq: expect_u64(begun, "begun_seq")?,
        }))
    }

    fn append_trust_evaluation(
        &mut self,
        authority: &TypedDigest,
        action: &TypedDigest,
        row: &TrustEvaluationRow,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let action = digest_key(action);
        let row = row.clone();
        let evaluated = to_seq(row.evaluated_seq, "evaluated_seq")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let stored = engine.query(
                "SELECT MAX(version) FROM action_trust_evaluations WHERE action_key = ?1",
                &[SqlValue::Text(action.clone())],
            )?;
            if let Some(SqlValue::Int(max)) = stored.first().and_then(|r| r.first())
                && u64::from(row.version) <= u64::try_from(*max).unwrap_or(0)
            {
                return Err(StoreError::NonMonotonicTrustEvaluation);
            }
            engine.execute(
                "INSERT INTO action_trust_evaluations \
                 (action_key, version, state, reason, evaluated_seq) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(action),
                    SqlValue::Int(i64::from(row.version)),
                    SqlValue::Text(row.state),
                    SqlValue::Text(row.reason),
                    SqlValue::Int(evaluated),
                ],
            )?;
            Ok(())
        })
    }

    fn latest_trust_evaluation(
        &mut self,
        action: &TypedDigest,
    ) -> Result<Option<TrustEvaluationRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT version, state, reason, evaluated_seq FROM action_trust_evaluations \
             WHERE action_key = ?1 ORDER BY version DESC LIMIT 1",
            &[SqlValue::Text(digest_key(action))],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [version, state, reason, evaluated] = row.as_slice() else {
            return Err(StoreError::Corruption("trust evaluation shape".into()));
        };
        Ok(Some(TrustEvaluationRow {
            version: u32::try_from(expect_u64(version, "version")?)
                .map_err(|_| StoreError::Corruption("version out of range".into()))?,
            state: expect_text(state, "state")?,
            reason: expect_text(reason, "reason")?,
            evaluated_seq: expect_u64(evaluated, "evaluated_seq")?,
        }))
    }

    fn create_operation(
        &mut self,
        authority: &TypedDigest,
        id: u128,
        kind: &str,
        state: &str,
        seq: u64,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let kind = kind.to_owned();
        let state = state.to_owned();
        let seq = to_seq(seq, "seq")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let existing = engine.query(
                "SELECT id_hex FROM operations WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            if !existing.is_empty() {
                return Err(StoreError::DuplicateOperation);
            }
            engine.execute(
                "INSERT INTO operations (id_hex, id, kind, state, updated_seq) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(u128_hex(id)),
                    SqlValue::Blob(u128_blob(id)),
                    SqlValue::Text(kind),
                    SqlValue::Text(state),
                    SqlValue::Int(seq),
                ],
            )?;
            Ok(())
        })
    }

    fn update_operation_state(
        &mut self,
        id: u128,
        state: &str,
        seq: u64,
    ) -> Result<(), StoreError> {
        let state = state.to_owned();
        let seq = to_seq(seq, "seq")?;
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "UPDATE operations SET state = ?1, updated_seq = ?2 WHERE id_hex = ?3",
                &[
                    SqlValue::Text(state),
                    SqlValue::Int(seq),
                    SqlValue::Text(u128_hex(id)),
                ],
            )?;
            if changed == 0 {
                return Err(StoreError::UnknownOperation);
            }
            Ok(())
        })
    }

    fn operation_state(&mut self, id: u128) -> Result<Option<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT state FROM operations WHERE id_hex = ?1",
            &[SqlValue::Text(u128_hex(id))],
        )?;
        match rows.first().and_then(|r| r.first()) {
            None => Ok(None),
            Some(v) => Ok(Some(expect_text(v, "operation state")?)),
        }
    }

    fn register_edge_subscriber(
        &mut self,
        edge_id: &str,
        subscriber: &str,
        registered_seq: u64,
    ) -> Result<(), StoreError> {
        let edge = edge_id.to_owned();
        let subscriber = subscriber.to_owned();
        let seq = to_seq(registered_seq, "registered_seq")?;
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR IGNORE INTO edge_subscribers (edge_id, subscriber, registered_seq) \
                 VALUES (?1, ?2, ?3)",
                &[
                    SqlValue::Text(edge),
                    SqlValue::Text(subscriber),
                    SqlValue::Int(seq),
                ],
            )?;
            Ok(())
        })
    }

    fn remove_edge_subscriber(
        &mut self,
        edge_id: &str,
        subscriber: &str,
    ) -> Result<bool, StoreError> {
        let edge = edge_id.to_owned();
        let subscriber = subscriber.to_owned();
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "DELETE FROM edge_subscribers WHERE edge_id = ?1 AND subscriber = ?2",
                &[SqlValue::Text(edge), SqlValue::Text(subscriber)],
            )?;
            Ok(changed > 0)
        })
    }

    fn list_edge_subscribers(&mut self, edge_id: &str) -> Result<Vec<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT subscriber FROM edge_subscribers WHERE edge_id = ?1 ORDER BY subscriber",
            &[SqlValue::Text(edge_id.to_owned())],
        )?;
        rows.iter()
            .map(|row| {
                expect_text(
                    row.first()
                        .ok_or_else(|| StoreError::Corruption("subscriber shape".into()))?,
                    "subscriber",
                )
            })
            .collect()
    }

    fn record_manifest(
        &mut self,
        manifest: &TypedDigest,
        kind: &str,
        entry_count: u64,
    ) -> Result<(), StoreError> {
        self.intern(manifest.domain);
        let key = digest_key(manifest);
        let [algo, domain, bytes] = SqlMetadataStore::<E>::digest_params(manifest);
        let kind = kind.to_owned();
        let count = to_seq(entry_count, "entry_count")?;
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT kind, entry_count FROM manifests WHERE key = ?1",
                &[SqlValue::Text(key.clone())],
            )?;
            if let Some(row) = existing.first() {
                let [stored_kind, stored_count] = row.as_slice() else {
                    return Err(StoreError::Corruption("manifest row shape".into()));
                };
                if expect_text(stored_kind, "manifest kind")? == kind
                    && expect_u64(stored_count, "entry_count")? == entry_count
                {
                    return Ok(()); // idempotent
                }
                return Err(StoreError::ManifestDivergence);
            }
            engine.execute(
                "INSERT INTO manifests (key, algo, domain, bytes, kind, entry_count) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                &[
                    SqlValue::Text(key),
                    algo,
                    domain,
                    bytes,
                    SqlValue::Text(kind),
                    SqlValue::Int(count),
                ],
            )?;
            Ok(())
        })
    }

    fn manifest_meta(
        &mut self,
        manifest: &TypedDigest,
    ) -> Result<Option<(String, u64)>, StoreError> {
        let rows = self.engine.query(
            "SELECT kind, entry_count FROM manifests WHERE key = ?1",
            &[SqlValue::Text(digest_key(manifest))],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [kind, count] = row.as_slice() else {
            return Err(StoreError::Corruption("manifest row shape".into()));
        };
        Ok(Some((
            expect_text(kind, "manifest kind")?,
            expect_u64(count, "entry_count")?,
        )))
    }

    fn record_worker_session(
        &mut self,
        worker: &str,
        incarnation: u128,
        started_seq: u64,
    ) -> Result<(), StoreError> {
        let worker = worker.to_owned();
        let started = to_seq(started_seq, "started_seq")?;
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT incarnation FROM worker_sessions WHERE worker = ?1 AND started_seq = ?2",
                &[SqlValue::Text(worker.clone()), SqlValue::Int(started)],
            )?;
            if let Some(row) = existing.first() {
                let stored = expect_u128(
                    row.first()
                        .ok_or_else(|| StoreError::Corruption("worker session shape".into()))?,
                    "session incarnation",
                )?;
                if stored == incarnation {
                    return Ok(()); // idempotent
                }
                return Err(StoreError::AppendConflict("worker_sessions".into()));
            }
            engine.execute(
                "INSERT INTO worker_sessions (worker, incarnation, started_seq, ended_seq) \
                 VALUES (?1, ?2, ?3, NULL)",
                &[
                    SqlValue::Text(worker),
                    SqlValue::Blob(u128_blob(incarnation)),
                    SqlValue::Int(started),
                ],
            )?;
            Ok(())
        })
    }

    fn end_worker_session(
        &mut self,
        worker: &str,
        started_seq: u64,
        ended_seq: u64,
    ) -> Result<bool, StoreError> {
        let worker = worker.to_owned();
        let started = to_seq(started_seq, "started_seq")?;
        let ended = to_seq(ended_seq, "ended_seq")?;
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "UPDATE worker_sessions SET ended_seq = ?1 \
                 WHERE worker = ?2 AND started_seq = ?3 AND ended_seq IS NULL",
                &[
                    SqlValue::Int(ended),
                    SqlValue::Text(worker),
                    SqlValue::Int(started),
                ],
            )?;
            Ok(changed > 0)
        })
    }

    fn record_worker_capability(
        &mut self,
        worker: &str,
        capability: &str,
    ) -> Result<(), StoreError> {
        let worker = worker.to_owned();
        let capability = capability.to_owned();
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR IGNORE INTO worker_capabilities (worker, capability) \
                 VALUES (?1, ?2)",
                &[SqlValue::Text(worker), SqlValue::Text(capability)],
            )?;
            Ok(())
        })
    }

    fn list_worker_capabilities(&mut self, worker: &str) -> Result<Vec<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT capability FROM worker_capabilities WHERE worker = ?1 ORDER BY capability",
            &[SqlValue::Text(worker.to_owned())],
        )?;
        rows.iter()
            .map(|row| {
                expect_text(
                    row.first()
                        .ok_or_else(|| StoreError::Corruption("capability shape".into()))?,
                    "capability",
                )
            })
            .collect()
    }

    fn record_worker_health_sample(
        &mut self,
        worker: &str,
        seq: u64,
        healthy: bool,
        detail: &str,
    ) -> Result<(), StoreError> {
        let worker = worker.to_owned();
        let seq = to_seq(seq, "seq")?;
        let detail = detail.to_owned();
        let healthy_int = i64::from(healthy);
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT healthy, detail FROM worker_health_samples \
                 WHERE worker = ?1 AND seq = ?2",
                &[SqlValue::Text(worker.clone()), SqlValue::Int(seq)],
            )?;
            if let Some(row) = existing.first() {
                let [stored_healthy, stored_detail] = row.as_slice() else {
                    return Err(StoreError::Corruption("health sample shape".into()));
                };
                if expect_u64(stored_healthy, "healthy")? == u64::from(healthy)
                    && expect_text(stored_detail, "detail")? == detail
                {
                    return Ok(()); // idempotent
                }
                return Err(StoreError::AppendConflict("worker_health_samples".into()));
            }
            engine.execute(
                "INSERT INTO worker_health_samples (worker, seq, healthy, detail) \
                 VALUES (?1, ?2, ?3, ?4)",
                &[
                    SqlValue::Text(worker),
                    SqlValue::Int(seq),
                    SqlValue::Int(healthy_int),
                    SqlValue::Text(detail),
                ],
            )?;
            Ok(())
        })
    }

    fn record_decision_receipt(
        &mut self,
        kind: &str,
        subject: &str,
        seq: u64,
        decision: &str,
        reason: &str,
    ) -> Result<(), StoreError> {
        let kind = kind.to_owned();
        let subject = subject.to_owned();
        let seq = to_seq(seq, "seq")?;
        let decision = decision.to_owned();
        let reason = reason.to_owned();
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT decision, reason FROM decision_receipts \
                 WHERE kind = ?1 AND subject = ?2 AND seq = ?3",
                &[
                    SqlValue::Text(kind.clone()),
                    SqlValue::Text(subject.clone()),
                    SqlValue::Int(seq),
                ],
            )?;
            if let Some(row) = existing.first() {
                let [stored_decision, stored_reason] = row.as_slice() else {
                    return Err(StoreError::Corruption("decision receipt shape".into()));
                };
                if expect_text(stored_decision, "decision")? == decision
                    && expect_text(stored_reason, "reason")? == reason
                {
                    return Ok(()); // idempotent
                }
                return Err(StoreError::AppendConflict("decision_receipts".into()));
            }
            engine.execute(
                "INSERT INTO decision_receipts (kind, subject, seq, decision, reason) \
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(kind),
                    SqlValue::Text(subject),
                    SqlValue::Int(seq),
                    SqlValue::Text(decision),
                    SqlValue::Text(reason),
                ],
            )?;
            Ok(())
        })
    }

    fn add_provenance_edge(
        &mut self,
        from: &TypedDigest,
        to: &TypedDigest,
        kind: &str,
    ) -> Result<(), StoreError> {
        let from = digest_key(from);
        let to = digest_key(to);
        let kind = kind.to_owned();
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR IGNORE INTO provenance_edges (from_key, to_key, kind) \
                 VALUES (?1, ?2, ?3)",
                &[
                    SqlValue::Text(from),
                    SqlValue::Text(to),
                    SqlValue::Text(kind),
                ],
            )?;
            Ok(())
        })
    }

    fn record_determinism_audit(
        &mut self,
        action: &TypedDigest,
        attempt: u128,
        seq: u64,
        verdict: &str,
    ) -> Result<(), StoreError> {
        let action = digest_key(action);
        let seq = to_seq(seq, "seq")?;
        let verdict = verdict.to_owned();
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT verdict FROM determinism_audits \
                 WHERE action_key = ?1 AND attempt_hex = ?2 AND seq = ?3",
                &[
                    SqlValue::Text(action.clone()),
                    SqlValue::Text(u128_hex(attempt)),
                    SqlValue::Int(seq),
                ],
            )?;
            if let Some(row) = existing.first() {
                let stored = expect_text(
                    row.first()
                        .ok_or_else(|| StoreError::Corruption("determinism audit shape".into()))?,
                    "verdict",
                )?;
                if stored == verdict {
                    return Ok(()); // idempotent
                }
                return Err(StoreError::AppendConflict("determinism_audits".into()));
            }
            engine.execute(
                "INSERT INTO determinism_audits (action_key, attempt_hex, seq, verdict) \
                 VALUES (?1, ?2, ?3, ?4)",
                &[
                    SqlValue::Text(action),
                    SqlValue::Text(u128_hex(attempt)),
                    SqlValue::Int(seq),
                    SqlValue::Text(verdict),
                ],
            )?;
            Ok(())
        })
    }

    fn create_materialization(
        &mut self,
        id: u128,
        root: &TypedDigest,
        dest_path: &str,
        state: &str,
        seq: u64,
    ) -> Result<(), StoreError> {
        let root = digest_key(root);
        let dest = dest_path.to_owned();
        let state = state.to_owned();
        let seq = to_seq(seq, "seq")?;
        self.in_txn(move |engine| {
            let existing = engine.query(
                "SELECT root_key, dest_path FROM materialization_records WHERE id_hex = ?1",
                &[SqlValue::Text(u128_hex(id))],
            )?;
            if let Some(row) = existing.first() {
                let [stored_root, stored_dest] = row.as_slice() else {
                    return Err(StoreError::Corruption("materialization shape".into()));
                };
                if expect_text(stored_root, "root_key")? == root
                    && expect_text(stored_dest, "dest_path")? == dest
                {
                    return Ok(()); // idempotent
                }
                return Err(StoreError::AppendConflict("materialization_records".into()));
            }
            engine.execute(
                "INSERT INTO materialization_records \
                 (id_hex, id, root_key, dest_path, state, updated_seq) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                &[
                    SqlValue::Text(u128_hex(id)),
                    SqlValue::Blob(u128_blob(id)),
                    SqlValue::Text(root),
                    SqlValue::Text(dest),
                    SqlValue::Text(state),
                    SqlValue::Int(seq),
                ],
            )?;
            Ok(())
        })
    }

    fn update_materialization_state(
        &mut self,
        id: u128,
        state: &str,
        seq: u64,
    ) -> Result<(), StoreError> {
        let state = state.to_owned();
        let seq = to_seq(seq, "seq")?;
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "UPDATE materialization_records SET state = ?1, updated_seq = ?2 \
                 WHERE id_hex = ?3",
                &[
                    SqlValue::Text(state),
                    SqlValue::Int(seq),
                    SqlValue::Text(u128_hex(id)),
                ],
            )?;
            if changed == 0 {
                return Err(StoreError::UnknownMaterialization);
            }
            Ok(())
        })
    }

    fn materialization_state(&mut self, id: u128) -> Result<Option<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT state FROM materialization_records WHERE id_hex = ?1",
            &[SqlValue::Text(u128_hex(id))],
        )?;
        match rows.first().and_then(|r| r.first()) {
            None => Ok(None),
            Some(v) => Ok(Some(expect_text(v, "materialization state")?)),
        }
    }

    fn put_serving_record(
        &mut self,
        authority: &TypedDigest,
        action_key: &str,
        disposition: &str,
        state_revision: u64,
        validity: &ServingValidity,
        blocking: &[(QuarantineScope, String)],
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let action_key = action_key.to_owned();
        let disposition = disposition.to_owned();
        let revision = to_seq(state_revision, "state_revision")?;
        let evaluated_at = validity.evaluated_at_unix_micros;
        let max_age = validity
            .maximum_age_micros
            .map(|v| to_seq(v, "max_age_micros"))
            .transpose()?;
        let uncertainty = to_seq(
            validity.clock_uncertainty_micros,
            "clock_uncertainty_micros",
        )?;
        let epoch = to_seq(validity.coordinator_clock_epoch, "clock_epoch")?;
        let blocking: Vec<(String, String)> = blocking
            .iter()
            .map(|(scope, subject)| (scope.as_str().to_owned(), subject.clone()))
            .collect();
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let stored = engine.query(
                "SELECT state_revision, disposition FROM action_serving_states WHERE action_key = ?1",
                &[SqlValue::Text(action_key.clone())],
            )?;
            let stored_revision = match stored.first().and_then(|r| r.first()) {
                None => None,
                Some(v) => Some(expect_u64(v, "state_revision")?),
            };
            // Legacy rows are revision 0; H040 records start at 1.
            if state_revision == 0 || stored_revision.is_some_and(|s| state_revision <= s) {
                return Err(StoreError::StaleServingRevision);
            }
            if let Some(row) = stored.first() {
                let [_, current] = row.as_slice() else {
                    return Err(StoreError::Corruption("serving revision row shape".into()));
                };
                Self::require_quarantine_preserved(&expect_text(current, "disposition")?, &disposition)?;
            }
            // The named reference is the action's durable association with
            // a quarantined location or logical object. Once omitted, the
            // serving gate cannot rediscover that dependency from an action
            // quarantine row. Check inside this write transaction so a
            // newer renewal, including one based on stale state, cannot
            // discard any existing blocker without explicit incident repair.
            let existing_blocking = engine.query(
                "SELECT scope, subject FROM serving_blocking_quarantines WHERE action_key = ?1",
                &[SqlValue::Text(action_key.clone())],
            )?;
            for row in &existing_blocking {
                let [scope, subject] = row.as_slice() else {
                    return Err(StoreError::Corruption("blocking reference shape".into()));
                };
                let reference = (
                    expect_text(scope, "scope")?,
                    expect_text(subject, "subject")?,
                );
                if !blocking.contains(&reference) {
                    return Err(StoreError::QuarantineRequiresRepair);
                }
            }
            // Every NAMED blocking quarantine must exist (references are
            // the authority; dangling ones are refused at write).
            for (scope, subject) in &blocking {
                let exists = engine.query(
                    "SELECT scope FROM quarantines WHERE scope = ?1 AND subject = ?2",
                    &[
                        SqlValue::Text(scope.clone()),
                        SqlValue::Text(subject.clone()),
                    ],
                )?;
                if exists.is_empty() {
                    return Err(StoreError::UnknownQuarantineReference);
                }
            }
            engine.execute(
                "INSERT OR REPLACE INTO action_serving_states \
                 (action_key, disposition, version, state_revision, authority_key, \
                  evaluated_at_micros, max_age_micros, clock_uncertainty_micros, clock_epoch) \
                 VALUES (?1, ?2, 1, ?3, ?4, ?5, ?6, ?7, ?8)",
                &[
                    SqlValue::Text(action_key.clone()),
                    SqlValue::Text(disposition),
                    SqlValue::Int(revision),
                    SqlValue::Text(digest_key(&authority)),
                    SqlValue::Int(evaluated_at),
                    max_age.map_or(SqlValue::Null, SqlValue::Int),
                    SqlValue::Int(uncertainty),
                    SqlValue::Int(epoch),
                ],
            )?;
            // Replace the reference set atomically with the row.
            engine.execute(
                "DELETE FROM serving_blocking_quarantines WHERE action_key = ?1",
                &[SqlValue::Text(action_key.clone())],
            )?;
            for (scope, subject) in &blocking {
                engine.execute(
                    "INSERT OR IGNORE INTO serving_blocking_quarantines \
                     (action_key, scope, subject) VALUES (?1, ?2, ?3)",
                    &[
                        SqlValue::Text(action_key.clone()),
                        SqlValue::Text(scope.clone()),
                        SqlValue::Text(subject.clone()),
                    ],
                )?;
            }
            Ok(())
        })
    }

    fn serving_record(&mut self, action_key: &str) -> Result<Option<ServingRecordRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT disposition, state_revision, authority_key, evaluated_at_micros, \
             max_age_micros, clock_uncertainty_micros, clock_epoch \
             FROM action_serving_states WHERE action_key = ?1",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [
            disposition,
            revision,
            authority_key,
            evaluated_at,
            max_age,
            uncertainty,
            epoch,
        ] = row.as_slice()
        else {
            return Err(StoreError::Corruption("serving record shape".into()));
        };
        let evaluated_at = match evaluated_at {
            SqlValue::Int(v) => *v,
            _ => return Err(StoreError::Corruption("evaluated_at_micros shape".into())),
        };
        let max_age = match max_age {
            SqlValue::Null => None,
            SqlValue::Int(_) => Some(expect_u64(max_age, "max_age_micros")?),
            _ => return Err(StoreError::Corruption("max_age_micros shape".into())),
        };
        let blocking_rows = self.engine.query(
            "SELECT scope, subject FROM serving_blocking_quarantines \
             WHERE action_key = ?1 ORDER BY scope, subject",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        let blocking = blocking_rows
            .iter()
            .map(|row| {
                let [scope, subject] = row.as_slice() else {
                    return Err(StoreError::Corruption("blocking reference shape".into()));
                };
                Ok((
                    expect_text(scope, "scope")?,
                    expect_text(subject, "subject")?,
                ))
            })
            .collect::<Result<Vec<_>, StoreError>>()?;
        Ok(Some(ServingRecordRow {
            disposition: expect_text(disposition, "disposition")?,
            state_revision: expect_u64(revision, "state_revision")?,
            authority_key: expect_text(authority_key, "authority_key")?,
            validity: ServingValidity {
                evaluated_at_unix_micros: evaluated_at,
                maximum_age_micros: max_age,
                clock_uncertainty_micros: expect_u64(uncertainty, "clock_uncertainty_micros")?,
                coordinator_clock_epoch: expect_u64(epoch, "clock_epoch")?,
            },
            blocking,
        }))
    }

    fn record_release_verdict(&mut self, verdict: &ReleaseVerdict) -> Result<(), StoreError> {
        let replayed = to_seq(verdict.replayed, "replayed")?;
        let explained = to_seq(verdict.explained, "explained")?;
        let uncertainty = to_seq(
            verdict.validity.clock_uncertainty_micros,
            "clock_uncertainty_micros",
        )?;
        let epoch = to_seq(verdict.validity.coordinator_clock_epoch, "clock_epoch")?;
        let max_age = match verdict.validity.maximum_age_micros {
            None => SqlValue::Null,
            Some(age) => SqlValue::Int(to_seq(age, "max_age_micros")?),
        };
        let build = verdict.build.clone();
        let corpus = verdict.corpus.clone();
        let evaluated_at = verdict.validity.evaluated_at_unix_micros;
        // Delete-then-insert rather than an upsert: `ON CONFLICT ... DO
        // UPDATE` appears nowhere else in this store, because the A002
        // differential lanes require every statement to mean the same
        // thing on each engine, and the upsert form is the one most
        // likely to diverge. The pair is atomic inside the transaction,
        // so no reader can observe the gap.
        self.in_txn(move |engine| {
            engine.execute(
                "DELETE FROM release_verdicts WHERE build = ?1",
                &[SqlValue::Text(build.clone())],
            )?;
            engine.execute(
                "INSERT INTO release_verdicts (build, corpus, replayed, explained, \
                 evaluated_at_micros, max_age_micros, clock_uncertainty_micros, clock_epoch) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                &[
                    SqlValue::Text(build),
                    SqlValue::Text(corpus),
                    SqlValue::Int(replayed),
                    SqlValue::Int(explained),
                    SqlValue::Int(evaluated_at),
                    max_age,
                    SqlValue::Int(uncertainty),
                    SqlValue::Int(epoch),
                ],
            )?;
            Ok(())
        })
    }

    fn release_verdict(&mut self, build: &str) -> Result<Option<ReleaseVerdict>, StoreError> {
        let rows = self.engine.query(
            "SELECT corpus, replayed, explained, evaluated_at_micros, max_age_micros, \
             clock_uncertainty_micros, clock_epoch FROM release_verdicts WHERE build = ?1",
            &[SqlValue::Text(build.to_owned())],
        )?;
        let Some(row) = rows.first() else {
            return Ok(None);
        };
        let [
            corpus,
            replayed,
            explained,
            evaluated_at,
            max_age,
            uncertainty,
            epoch,
        ] = row.as_slice()
        else {
            return Err(StoreError::Corruption("release verdict shape".into()));
        };
        let evaluated_at = match evaluated_at {
            SqlValue::Int(v) => *v,
            _ => return Err(StoreError::Corruption("evaluated_at_micros shape".into())),
        };
        let maximum_age_micros = match max_age {
            SqlValue::Null => None,
            SqlValue::Int(_) => Some(expect_u64(max_age, "max_age_micros")?),
            _ => return Err(StoreError::Corruption("max_age_micros shape".into())),
        };
        Ok(Some(ReleaseVerdict {
            build: build.to_owned(),
            corpus: expect_text(corpus, "corpus")?,
            replayed: expect_u64(replayed, "replayed")?,
            explained: expect_u64(explained, "explained")?,
            validity: ServingValidity {
                evaluated_at_unix_micros: evaluated_at,
                maximum_age_micros,
                clock_uncertainty_micros: expect_u64(uncertainty, "clock_uncertainty_micros")?,
                coordinator_clock_epoch: expect_u64(epoch, "clock_epoch")?,
            },
        }))
    }

    fn record_divergence_incident(
        &mut self,
        authority: &TypedDigest,
        row: &DivergenceIncidentRow,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let row = row.clone();
        let seq = to_seq(row.seq, "seq")?;
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let existing = engine.query(
                "SELECT class, committed_manifest_key, candidate_manifest_key, \
                 candidate_evidence_key, candidate_pin_hex, generation_hex, attempt_hex, \
                 detail FROM divergence_incidents WHERE action_key = ?1 AND seq = ?2",
                &[SqlValue::Text(row.action_key.clone()), SqlValue::Int(seq)],
            )?;
            if let Some(stored) = existing.first() {
                let same = stored.len() == 8
                    && expect_text(&stored[0], "class")? == row.class
                    && expect_text(&stored[1], "committed_manifest_key")?
                        == row.committed_manifest_key
                    && expect_text(&stored[2], "candidate_manifest_key")?
                        == row.candidate_manifest_key
                    && expect_text(&stored[3], "candidate_evidence_key")?
                        == row.candidate_evidence_key
                    && expect_text(&stored[4], "candidate_pin_hex")? == row.candidate_pin_hex
                    && expect_text(&stored[5], "generation_hex")? == row.generation_hex
                    && expect_text(&stored[6], "attempt_hex")? == row.attempt_hex
                    && expect_text(&stored[7], "detail")? == row.detail;
                if same {
                    return Ok(()); // idempotent
                }
                return Err(StoreError::AppendConflict("divergence_incidents".into()));
            }
            engine.execute(
                "INSERT INTO divergence_incidents (action_key, seq, class, \
                 committed_manifest_key, candidate_manifest_key, candidate_evidence_key, \
                 candidate_pin_hex, generation_hex, attempt_hex, detail) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
                &[
                    SqlValue::Text(row.action_key),
                    SqlValue::Int(seq),
                    SqlValue::Text(row.class),
                    SqlValue::Text(row.committed_manifest_key),
                    SqlValue::Text(row.candidate_manifest_key),
                    SqlValue::Text(row.candidate_evidence_key),
                    SqlValue::Text(row.candidate_pin_hex),
                    SqlValue::Text(row.generation_hex),
                    SqlValue::Text(row.attempt_hex),
                    SqlValue::Text(row.detail),
                ],
            )?;
            Ok(())
        })
    }

    fn list_divergence_incidents(
        &mut self,
        action_key: &str,
    ) -> Result<Vec<DivergenceIncidentRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT seq, class, committed_manifest_key, candidate_manifest_key, \
             candidate_evidence_key, candidate_pin_hex, generation_hex, attempt_hex, detail \
             FROM divergence_incidents WHERE action_key = ?1 ORDER BY seq",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        rows.iter()
            .map(|row| {
                let [
                    seq,
                    class,
                    committed,
                    candidate,
                    evidence,
                    pin,
                    generation,
                    attempt,
                    detail,
                ] = row.as_slice()
                else {
                    return Err(StoreError::Corruption("divergence incident shape".into()));
                };
                Ok(DivergenceIncidentRow {
                    action_key: action_key.to_owned(),
                    seq: expect_u64(seq, "seq")?,
                    class: expect_text(class, "class")?,
                    committed_manifest_key: expect_text(committed, "committed_manifest_key")?,
                    candidate_manifest_key: expect_text(candidate, "candidate_manifest_key")?,
                    candidate_evidence_key: expect_text(evidence, "candidate_evidence_key")?,
                    candidate_pin_hex: expect_text(pin, "candidate_pin_hex")?,
                    generation_hex: expect_text(generation, "generation_hex")?,
                    attempt_hex: expect_text(attempt, "attempt_hex")?,
                    detail: expect_text(detail, "detail")?,
                })
            })
            .collect()
    }

    fn record_adoption_edge(
        &mut self,
        authority: &TypedDigest,
        producer_action_key: &str,
        role: &str,
        virtual_path: &[u8],
        from_object_key: &str,
        to_object_key: &str,
    ) -> Result<(), StoreError> {
        let authority = authority.clone();
        let producer = producer_action_key.to_owned();
        let role = role.to_owned();
        let path = virtual_path.to_vec();
        let from = from_object_key.to_owned();
        let to = to_object_key.to_owned();
        self.in_txn(move |engine| {
            SqlMetadataStore::<E>::require_active(engine, &authority)?;
            let existing = engine.query(
                "SELECT to_object_key FROM adoption_edges \
                 WHERE producer_action_key = ?1 AND role = ?2 AND virtual_path = ?3 \
                 AND from_object_key = ?4",
                &[
                    SqlValue::Text(producer.clone()),
                    SqlValue::Text(role.clone()),
                    SqlValue::Blob(path.clone()),
                    SqlValue::Text(from.clone()),
                ],
            )?;
            if let Some(row) = existing.first() {
                let [existing_to] = row.as_slice() else {
                    return Err(StoreError::Corruption("adoption edge shape".into()));
                };
                // Idempotent re-record; a rewrite to a DIFFERENT target
                // is a typed refusal — edges are never patched.
                return if expect_text(existing_to, "adoption target")? == to {
                    Ok(())
                } else {
                    Err(StoreError::AdoptionEdgeConflict)
                };
            }
            engine.execute(
                "INSERT INTO adoption_edges (producer_action_key, role, virtual_path, \
                 from_object_key, to_object_key) VALUES (?1, ?2, ?3, ?4, ?5)",
                &[
                    SqlValue::Text(producer),
                    SqlValue::Text(role),
                    SqlValue::Blob(path),
                    SqlValue::Text(from),
                    SqlValue::Text(to),
                ],
            )?;
            Ok(())
        })
    }

    fn has_adoption_edge(
        &mut self,
        producer_action_key: &str,
        role: &str,
        virtual_path: &[u8],
        from_object_key: &str,
        to_object_key: &str,
    ) -> Result<bool, StoreError> {
        let rows = self.engine.query(
            "SELECT producer_action_key FROM adoption_edges \
             WHERE producer_action_key = ?1 AND role = ?2 AND virtual_path = ?3 \
             AND from_object_key = ?4 AND to_object_key = ?5 LIMIT 1",
            &[
                SqlValue::Text(producer_action_key.to_owned()),
                SqlValue::Text(role.to_owned()),
                SqlValue::Blob(virtual_path.to_vec()),
                SqlValue::Text(from_object_key.to_owned()),
                SqlValue::Text(to_object_key.to_owned()),
            ],
        )?;
        Ok(!rows.is_empty())
    }

    fn list_provisional_ancestors(
        &mut self,
        consumer_action_key: &str,
    ) -> Result<Vec<ProvisionalAncestorRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT producer_action_key, role, virtual_path, object_key, adopted \
             FROM provisional_ancestry WHERE consumer_action_key = ?1 \
             ORDER BY producer_action_key, role, virtual_path",
            &[SqlValue::Text(consumer_action_key.to_owned())],
        )?;
        rows.iter()
            .map(|row| {
                let [producer, role, path, object, adopted] = row.as_slice() else {
                    return Err(StoreError::Corruption("provisional ancestry shape".into()));
                };
                let SqlValue::Blob(path) = path else {
                    return Err(StoreError::Corruption("ancestry path shape".into()));
                };
                Ok(ProvisionalAncestorRow {
                    producer_action_key: expect_text(producer, "ancestry producer")?,
                    role: expect_text(role, "ancestry role")?,
                    virtual_path: path.clone(),
                    object_key: expect_text(object, "ancestry object")?,
                    adopted: expect_u64(adopted, "ancestry adopted")? != 0,
                })
            })
            .collect()
    }

    fn provisional_pin_row(
        &mut self,
        pin_key: &str,
    ) -> Result<Option<ProvisionalPinRecord>, StoreError> {
        let rows = self.engine.query(
            "SELECT pin_key, authority_key, action_key, generation_hex, attempt_hex, \
             lease_hex, role, virtual_path, obj_algo, obj_domain, obj_bytes, object_key, \
             protective_pin_hex, renewal_seq, adopted_object_key, invalidated_reason, \
             released, toolchain_contract_key, event_contract_key \
             FROM provisional_pins WHERE pin_key = ?1",
            &[SqlValue::Text(pin_key.to_owned())],
        )?;
        rows.first()
            .map(|row| self.map_provisional_pin_row(row))
            .transpose()
    }

    fn insert_provisional_pin(&mut self, pin: &ProvisionalPinInsert) -> Result<(), StoreError> {
        let row = pin.clone();
        // R121: intern the object's domain so later reads in THIS process
        // can restore the typed digest fail-closed.
        self.intern(row.object.domain);
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT INTO provisional_pins (pin_key, authority_key, action_key, \
                 generation_hex, attempt_hex, lease_hex, role, virtual_path, obj_algo, \
                 obj_domain, obj_bytes, object_key, protective_pin_hex, renewal_seq, \
                 adopted_object_key, invalidated_reason, released, \
                 toolchain_contract_key, event_contract_key) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, 0, \
                 NULL, NULL, 0, ?14, ?15)",
                &[
                    SqlValue::Text(row.pin_key.clone()),
                    SqlValue::Text(row.authority_key.clone()),
                    SqlValue::Text(row.action_key.clone()),
                    SqlValue::Text(u128_hex(row.generation)),
                    SqlValue::Text(u128_hex(row.attempt)),
                    SqlValue::Text(u128_hex(row.lease)),
                    SqlValue::Int(row.role_tag),
                    SqlValue::Blob(row.virtual_path.clone()),
                    SqlValue::Text(algo_tag(row.object.algorithm).to_owned()),
                    SqlValue::Text(row.object.domain.to_owned()),
                    SqlValue::Blob(row.object.bytes.to_vec()),
                    SqlValue::Text(digest_key(&row.object)),
                    SqlValue::Text(u128_hex(row.protective_pin_id)),
                    SqlValue::Text(row.toolchain_contract_key.clone()),
                    SqlValue::Text(row.event_contract_key.clone()),
                ],
            )?;
            // The GC-protective twin in `pins` (H010 semantics): same
            // transaction, so the registry row and the protection root are
            // born together.
            engine.execute(
                "INSERT INTO pins (id_hex, id, root_key, owner, class, expires_at_seq, \
                 released, evidence, renewal_seq, durable, reason) \
                 VALUES (?1, ?2, ?3, 'coordinator', 'provisional-metadata', NULL, 0, \
                 NULL, 0, 1, ?4)",
                &[
                    SqlValue::Text(u128_hex(row.protective_pin_id)),
                    SqlValue::Blob(row.protective_pin_id.to_be_bytes().to_vec()),
                    SqlValue::Text(digest_key(&row.object)),
                    SqlValue::Text(row.reason),
                ],
            )?;
            // M017: the materialized transitive ancestor closure is born
            // in the SAME transaction as the pin — a tear can never leave
            // a prepared descendant without its recorded lineage.
            for (ancestor_key, min_hops) in &row.ancestor_pin_keys {
                engine.execute(
                    "INSERT OR IGNORE INTO provisional_pin_lineage \
                     (descendant_pin_key, ancestor_pin_key, min_hops) VALUES (?1, ?2, ?3)",
                    &[
                        SqlValue::Text(row.pin_key.clone()),
                        SqlValue::Text(ancestor_key.clone()),
                        SqlValue::Int(*min_hops as i64),
                    ],
                )?;
            }
            Ok(())
        })
    }

    fn list_provisional_pin_ancestors(
        &mut self,
        descendant_pin_key: &str,
    ) -> Result<Vec<(String, u64)>, StoreError> {
        let rows = self.engine.query(
            "SELECT ancestor_pin_key, min_hops FROM provisional_pin_lineage \
             WHERE descendant_pin_key = ?1 ORDER BY ancestor_pin_key",
            &[SqlValue::Text(descendant_pin_key.to_owned())],
        )?;
        rows.into_iter()
            .map(|row| match row.as_slice() {
                [SqlValue::Text(k), SqlValue::Int(h)] => {
                    Ok((k.clone(), u64::try_from(*h).unwrap_or(0)))
                }
                _ => Err(StoreError::Corruption("pin lineage ancestor shape".into())),
            })
            .collect()
    }

    fn provisional_pin_closure_depth(
        &mut self,
        descendant_pin_key: &str,
    ) -> Result<u64, StoreError> {
        let rows = self.engine.query(
            "SELECT COALESCE(MAX(min_hops), 0) FROM provisional_pin_lineage \
             WHERE descendant_pin_key = ?1",
            &[SqlValue::Text(descendant_pin_key.to_owned())],
        )?;
        match rows.first().map(Vec::as_slice) {
            Some([SqlValue::Int(h)]) => Ok(u64::try_from(*h).unwrap_or(0)),
            _ => Err(StoreError::Corruption("pin lineage depth shape".into())),
        }
    }

    fn list_provisional_pin_descendants(
        &mut self,
        ancestor_pin_key: &str,
    ) -> Result<Vec<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT descendant_pin_key FROM provisional_pin_lineage \
             WHERE ancestor_pin_key = ?1 ORDER BY descendant_pin_key",
            &[SqlValue::Text(ancestor_pin_key.to_owned())],
        )?;
        rows.into_iter()
            .map(|row| match row.first() {
                Some(SqlValue::Text(k)) => Ok(k.clone()),
                _ => Err(StoreError::Corruption(
                    "pin lineage descendant shape".into(),
                )),
            })
            .collect()
    }

    fn record_provisional_grant(
        &mut self,
        pin_key: &str,
        grantee_kind: &str,
        grantee_id: &str,
        granted_seq: u64,
    ) -> Result<(), StoreError> {
        let (pin_key, kind, id) = (
            pin_key.to_owned(),
            grantee_kind.to_owned(),
            grantee_id.to_owned(),
        );
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR IGNORE INTO provisional_pin_grants \
                 (pin_key, grantee_kind, grantee_id, granted_seq) VALUES (?1, ?2, ?3, ?4)",
                &[
                    SqlValue::Text(pin_key),
                    SqlValue::Text(kind),
                    SqlValue::Text(id),
                    SqlValue::Int(granted_seq as i64),
                ],
            )?;
            Ok(())
        })
    }

    fn list_provisional_grants(
        &mut self,
        pin_key: &str,
    ) -> Result<Vec<(String, String, u64)>, StoreError> {
        let rows = self.engine.query(
            "SELECT grantee_kind, grantee_id, granted_seq FROM provisional_pin_grants \
             WHERE pin_key = ?1 ORDER BY grantee_kind, grantee_id",
            &[SqlValue::Text(pin_key.to_owned())],
        )?;
        rows.iter()
            .map(|row| {
                let [kind, id, seq] = row.as_slice() else {
                    return Err(StoreError::Corruption("provisional grant shape".into()));
                };
                Ok((
                    expect_text(kind, "grant kind")?,
                    expect_text(id, "grant id")?,
                    expect_u64(seq, "grant seq")?,
                ))
            })
            .collect()
    }

    fn renew_provisional_pin(&mut self, pin_key: &str, renewal_seq: u64) -> Result<(), StoreError> {
        let pin_key = pin_key.to_owned();
        self.in_txn(move |engine| {
            let rows = engine.query(
                "SELECT renewal_seq, released FROM provisional_pins WHERE pin_key = ?1",
                &[SqlValue::Text(pin_key.clone())],
            )?;
            let Some(row) = rows.first() else {
                return Err(StoreError::UnknownPin);
            };
            let [stored, released] = row.as_slice() else {
                return Err(StoreError::Corruption("provisional renewal shape".into()));
            };
            if expect_u64(released, "released")? != 0 {
                return Err(StoreError::PinReleased);
            }
            if renewal_seq <= expect_u64(stored, "renewal")? {
                return Err(StoreError::NonMonotonicPinRenewal);
            }
            engine.execute(
                "UPDATE provisional_pins SET renewal_seq = ?1 WHERE pin_key = ?2",
                &[SqlValue::Int(renewal_seq as i64), SqlValue::Text(pin_key)],
            )?;
            Ok(())
        })
    }

    fn close_provisional_pin(
        &mut self,
        pin_key: &str,
        invalidation_reason: Option<&str>,
    ) -> Result<(), StoreError> {
        let pin_key = pin_key.to_owned();
        let reason = invalidation_reason.map(str::to_owned);
        self.in_txn(move |engine| {
            // Idempotent close; the protective pin is left for the caller
            // to release AFTER this commit (fail toward retention on tear).
            let changed = engine.execute(
                "UPDATE provisional_pins SET released = 1, invalidated_reason = \
                 COALESCE(?1, invalidated_reason) WHERE pin_key = ?2 AND released = 0",
                &[
                    reason.map(SqlValue::Text).unwrap_or(SqlValue::Null),
                    SqlValue::Text(pin_key.clone()),
                ],
            )?;
            if changed == 0
                && engine
                    .query(
                        "SELECT 1 FROM provisional_pins WHERE pin_key = ?1",
                        &[SqlValue::Text(pin_key)],
                    )?
                    .is_empty()
            {
                return Err(StoreError::UnknownPin);
            }
            Ok(())
        })
    }

    fn adopt_provisional_pin(
        &mut self,
        pin_key: &str,
        committed_object_key: &str,
    ) -> Result<(), StoreError> {
        let pin_key = pin_key.to_owned();
        let committed = committed_object_key.to_owned();
        self.in_txn(move |engine| {
            let changed = engine.execute(
                "UPDATE provisional_pins SET adopted_object_key = ?1 \
                 WHERE pin_key = ?2 AND adopted_object_key IS NULL",
                &[SqlValue::Text(committed), SqlValue::Text(pin_key.clone())],
            )?;
            if changed == 0
                && engine
                    .query(
                        "SELECT 1 FROM provisional_pins WHERE pin_key = ?1",
                        &[SqlValue::Text(pin_key)],
                    )?
                    .is_empty()
            {
                return Err(StoreError::UnknownPin);
            }
            Ok(())
        })
    }

    fn record_provisional_consumption(
        &mut self,
        consumption: &ProvisionalObligationInsert,
    ) -> Result<(), StoreError> {
        let row = consumption.clone();
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR IGNORE INTO provisional_obligations (consumer_worker, \
                 consumer_attempt_hex, pin_key, producer_action_key, \
                 producer_generation_hex, producer_attempt_hex, role, virtual_path, \
                 object_key, status, resolution_object_key, created_seq) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 'open', NULL, ?10)",
                &[
                    SqlValue::Text(row.consumer_worker),
                    SqlValue::Text(u128_hex(row.consumer_attempt)),
                    SqlValue::Text(row.pin_key),
                    SqlValue::Text(row.producer_action_key),
                    SqlValue::Text(u128_hex(row.producer_generation)),
                    SqlValue::Text(u128_hex(row.producer_attempt)),
                    SqlValue::Int(row.role_tag),
                    SqlValue::Blob(row.virtual_path),
                    SqlValue::Text(row.object_key),
                    SqlValue::Int(to_seq(row.created_seq, "consumption seq")?),
                ],
            )?;
            Ok(())
        })
    }

    fn list_open_provisional_obligations(
        &mut self,
        consumer_worker: &str,
        consumer_attempt_hex: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT consumer_worker, consumer_attempt_hex, pin_key, producer_action_key, \
             producer_generation_hex, producer_attempt_hex, role, virtual_path, object_key, \
             status, resolution_object_key, created_seq FROM provisional_obligations \
             WHERE consumer_worker = ?1 AND consumer_attempt_hex = ?2 AND status != 'resolved' \
             ORDER BY status, pin_key",
            &[
                SqlValue::Text(consumer_worker.to_owned()),
                SqlValue::Text(consumer_attempt_hex.to_owned()),
            ],
        )?;
        rows.iter()
            .map(|row| {
                let [
                    worker,
                    attempt_hex,
                    pin,
                    action,
                    generation,
                    producer,
                    role,
                    path,
                    object,
                    status,
                    resolution,
                    created,
                ] = row.as_slice()
                else {
                    return Err(StoreError::Corruption("obligation row shape".into()));
                };
                Ok(ProvisionalObligationRow {
                    consumer_worker: expect_text(worker, "obligation worker")?,
                    consumer_attempt_hex: expect_text(attempt_hex, "obligation attempt")?,
                    pin_key: expect_text(pin, "obligation pin")?,
                    producer_action_key: expect_text(action, "obligation action")?,
                    producer_generation_hex: expect_text(generation, "obligation generation")?,
                    producer_attempt_hex: expect_text(producer, "obligation producer")?,
                    role_tag: match role {
                        SqlValue::Int(v) => *v,
                        _ => return Err(StoreError::Corruption("obligation role shape".into())),
                    },
                    virtual_path: match path {
                        SqlValue::Blob(b) => b.clone(),
                        _ => return Err(StoreError::Corruption("obligation path shape".into())),
                    },
                    object_key: expect_text(object, "obligation object")?,
                    status: expect_text(status, "obligation status")?,
                    resolution_object_key: expect_opt_text(resolution, "obligation resolution")?,
                    created_seq: expect_u64(created, "obligation seq")?,
                })
            })
            .collect()
    }

    fn resolve_provisional_obligations(
        &mut self,
        pin_key: &str,
        resolution_object_key: &str,
    ) -> Result<usize, StoreError> {
        let (pin_key, resolved) = (pin_key.to_owned(), resolution_object_key.to_owned());
        self.in_txn(move |engine| {
            engine.execute(
                "UPDATE provisional_obligations SET status = 'resolved', \
                 resolution_object_key = ?1 WHERE pin_key = ?2 AND status = 'open'",
                &[SqlValue::Text(resolved), SqlValue::Text(pin_key)],
            )
        })
    }

    fn cancel_provisional_obligations(&mut self, pin_key: &str) -> Result<usize, StoreError> {
        let pin_key = pin_key.to_owned();
        self.in_txn(move |engine| {
            engine.execute(
                "UPDATE provisional_obligations SET status = 'cancelled' \
                 WHERE pin_key = ?1 AND status = 'open'",
                &[SqlValue::Text(pin_key)],
            )
        })
    }

    fn record_served_consumer(
        &mut self,
        action_key: &str,
        consumer: &str,
    ) -> Result<(), StoreError> {
        let action_key = action_key.to_owned();
        let consumer = consumer.to_owned();
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR IGNORE INTO provenance_edges (from_key, to_key, kind) \
                 VALUES (?1, ?2, 'served-to')",
                &[SqlValue::Text(action_key), SqlValue::Text(consumer)],
            )?;
            Ok(())
        })
    }

    fn list_served_consumers(&mut self, action_key: &str) -> Result<Vec<String>, StoreError> {
        let rows = self.engine.query(
            "SELECT to_key FROM provenance_edges \
             WHERE from_key = ?1 AND kind = 'served-to' ORDER BY to_key",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        rows.iter()
            .map(|row| {
                expect_text(
                    row.first()
                        .ok_or_else(|| StoreError::Corruption("served consumer shape".into()))?,
                    "consumer",
                )
            })
            .collect()
    }

    fn differential_snapshot(&mut self) -> Result<Vec<String>, StoreError> {
        // Deterministic dump: every table, every column, ordered rows.
        const DUMPS: &[(&str, &str)] = &[
            (
                "schema_epochs",
                "SELECT version, applied_seq FROM schema_epochs ORDER BY version",
            ),
            (
                "coordinator_authorities",
                "SELECT key, algo, domain, bytes, cluster_id, incarnation, term, acquired_seq, \
                 released FROM coordinator_authorities ORDER BY key",
            ),
            (
                "action_entries",
                "SELECT key, algo, domain, bytes, key_epoch, projection_epoch \
                 FROM action_entries ORDER BY key",
            ),
            (
                "action_generations",
                "SELECT id_hex, id, action_key, authority_key, tombstoned, per_key_ordinal \
                 FROM action_generations ORDER BY id_hex",
            ),
            (
                "generation_high_water",
                "SELECT kind, value FROM generation_high_water ORDER BY kind",
            ),
            (
                "action_attempts",
                "SELECT id_hex, id, generation_hex, worker, seq, worker_boot_generation, \
                 worker_incarnation, execution_lease_hex FROM action_attempts \
                 ORDER BY id_hex",
            ),
            (
                "execution_leases",
                "SELECT id_hex, id, attempt_hex, renewal_seq, expires_at_seq, released \
                 FROM execution_leases ORDER BY id_hex",
            ),
            (
                "action_publications",
                "SELECT action_key, descriptor_algo, descriptor_domain, descriptor_bytes, \
                 manifest_algo, manifest_domain, manifest_bytes, winner_generation_hex, \
                 winner_attempt_hex, result_kind, pin_hex FROM action_publications \
                 ORDER BY action_key",
            ),
            (
                "action_serving_states",
                "SELECT action_key, disposition, version, state_revision, authority_key, \
                 evaluated_at_micros, max_age_micros, clock_uncertainty_micros, clock_epoch \
                 FROM action_serving_states ORDER BY action_key",
            ),
            (
                "serving_blocking_quarantines",
                "SELECT action_key, scope, subject FROM serving_blocking_quarantines \
                 ORDER BY action_key, scope, subject",
            ),
            (
                "objects",
                "SELECT key, algo, domain, bytes, logical_size FROM objects ORDER BY key",
            ),
            (
                "object_locations",
                "SELECT object_key, store_path, verified_seq, encoding, quarantined, durable \
                 FROM object_locations ORDER BY object_key, store_path",
            ),
            (
                "object_edges",
                "SELECT parent_key, child_key, kind FROM object_edges \
                 ORDER BY parent_key, child_key, kind",
            ),
            (
                "pins",
                "SELECT id_hex, id, root_key, owner, class, expires_at_seq, released, \
                 evidence, renewal_seq, durable, reason FROM pins ORDER BY id_hex",
            ),
            (
                "observed_input_recipes",
                "SELECT action_key, recipe_algo, recipe_domain, recipe_bytes \
                 FROM observed_input_recipes ORDER BY action_key",
            ),
            (
                "key_breakdowns",
                "SELECT action_key, component, algo, domain, bytes FROM key_breakdowns \
                 ORDER BY action_key, component",
            ),
            (
                "trust_states",
                "SELECT action_key, state, reason FROM trust_states ORDER BY action_key",
            ),
            (
                "quarantines",
                "SELECT scope, subject, reason FROM quarantines ORDER BY scope, subject",
            ),
            (
                "verification_samples",
                "SELECT action_key, attempt_hex, passed, seq FROM verification_samples \
                 ORDER BY action_key, attempt_hex, seq",
            ),
            (
                "gc_runs",
                "SELECT id, seq, pinned_roots, located_objects, reachable_objects \
                 FROM gc_runs ORDER BY id",
            ),
            (
                "operator_resets",
                "SELECT generation, applied_seq FROM operator_resets ORDER BY generation",
            ),
            (
                "eviction_tombstones",
                "SELECT action_key, semantic_algo, semantic_domain, semantic_bytes, \
                 observable_algo, observable_domain, observable_bytes, evicted_seq \
                 FROM eviction_tombstones ORDER BY action_key",
            ),
            (
                "gc_tombstones",
                "SELECT object_key, store_path, marked_seq, grace_until_seq \
                 FROM gc_tombstones ORDER BY object_key, store_path",
            ),
            (
                "gc_receipts",
                "SELECT id, seq, mode, planned, reclaimed, skipped, truncated \
                 FROM gc_receipts ORDER BY id",
            ),
            (
                "action_evidence_index",
                "SELECT action_key, evidence_algo, evidence_domain, evidence_bytes, \
                 generation_hex, attempt_hex, manifest_key FROM action_evidence_index \
                 ORDER BY action_key, evidence_domain, evidence_bytes",
            ),
            (
                "peer_authority_high_water",
                "SELECT peer_id, term, observed_seq, incarnation, credential_generation FROM peer_authority_high_water \
                 ORDER BY peer_id",
            ),
            (
                "worker_incarnation_fences",
                "SELECT worker, incarnation, highest_boot_generation, active, \
                 operator_reenrollment_generation, clone_ambiguous \
                 FROM worker_incarnation_fences \
                 ORDER BY worker",
            ),
            (
                "edge_incarnation_fences",
                "SELECT edge_id, incarnation FROM edge_incarnation_fences ORDER BY edge_id",
            ),
            (
                "edge_handoffs",
                "SELECT edge_id, active_incarnation, predecessor_incarnation, begun_seq, \
                 resolved FROM edge_handoffs ORDER BY edge_id",
            ),
            (
                "action_trust_evaluations",
                "SELECT action_key, version, state, reason, evaluated_seq \
                 FROM action_trust_evaluations ORDER BY action_key, version",
            ),
            (
                "operations",
                "SELECT id_hex, id, kind, state, updated_seq FROM operations ORDER BY id_hex",
            ),
            (
                "edge_subscribers",
                "SELECT edge_id, subscriber, registered_seq FROM edge_subscribers \
                 ORDER BY edge_id, subscriber",
            ),
            (
                "manifests",
                "SELECT key, algo, domain, bytes, kind, entry_count FROM manifests \
                 ORDER BY key",
            ),
            (
                "worker_sessions",
                "SELECT worker, incarnation, started_seq, ended_seq FROM worker_sessions \
                 ORDER BY worker, started_seq",
            ),
            (
                "worker_capabilities",
                "SELECT worker, capability FROM worker_capabilities \
                 ORDER BY worker, capability",
            ),
            (
                "native_child_bindings",
                "SELECT parent_action_key, child_action_key, bound_seq, state \
                 FROM native_child_bindings \
                 ORDER BY parent_action_key, child_action_key",
            ),
            (
                "worker_health_samples",
                "SELECT worker, seq, healthy, detail FROM worker_health_samples \
                 ORDER BY worker, seq",
            ),
            (
                "decision_receipts",
                "SELECT kind, subject, seq, decision, reason FROM decision_receipts \
                 ORDER BY kind, subject, seq",
            ),
            (
                "provenance_edges",
                "SELECT from_key, to_key, kind FROM provenance_edges \
                 ORDER BY from_key, to_key, kind",
            ),
            (
                "determinism_audits",
                "SELECT action_key, attempt_hex, seq, verdict FROM determinism_audits \
                 ORDER BY action_key, attempt_hex, seq",
            ),
            (
                "materialization_records",
                "SELECT id_hex, id, root_key, dest_path, state, updated_seq \
                 FROM materialization_records ORDER BY id_hex",
            ),
            (
                "divergence_incidents",
                "SELECT action_key, seq, class, committed_manifest_key, \
                 candidate_manifest_key, candidate_evidence_key, candidate_pin_hex, \
                 generation_hex, attempt_hex, detail FROM divergence_incidents \
                 ORDER BY action_key, seq",
            ),
            (
                "provisional_ancestry",
                "SELECT consumer_action_key, producer_action_key, role, virtual_path, \
                 object_key, adopted FROM provisional_ancestry \
                 ORDER BY consumer_action_key, producer_action_key, role, virtual_path",
            ),
            (
                "adoption_edges",
                "SELECT producer_action_key, role, virtual_path, from_object_key, \
                 to_object_key FROM adoption_edges \
                 ORDER BY producer_action_key, role, virtual_path, from_object_key",
            ),
            (
                "provisional_pins",
                "SELECT pin_key, authority_key, action_key, generation_hex, attempt_hex, \
                 lease_hex, role, virtual_path, obj_algo, obj_domain, obj_bytes, object_key, \
                 protective_pin_hex, renewal_seq, adopted_object_key, invalidated_reason, \
                 released, toolchain_contract_key, event_contract_key \
                 FROM provisional_pins ORDER BY pin_key",
            ),
            (
                "provisional_pin_grants",
                "SELECT pin_key, grantee_kind, grantee_id, granted_seq \
                 FROM provisional_pin_grants ORDER BY pin_key, grantee_kind, grantee_id",
            ),
            (
                "provisional_pin_lineage",
                "SELECT descendant_pin_key, ancestor_pin_key, min_hops \
                 FROM provisional_pin_lineage \
                 ORDER BY descendant_pin_key, ancestor_pin_key",
            ),
            (
                "provisional_install_journal",
                "SELECT pin_key, consumer_worker, consumer_attempt_hex, installed_path, \
                 obj_algo, obj_domain, obj_bytes, object_key, installed_seq, state \
                 FROM provisional_install_journal \
                 ORDER BY pin_key, consumer_attempt_hex, installed_path",
            ),
            (
                "provisional_obligations",
                "SELECT consumer_worker, consumer_attempt_hex, pin_key, producer_action_key, \
                 producer_generation_hex, producer_attempt_hex, role, virtual_path, object_key, \
                 status, resolution_object_key, created_seq FROM provisional_obligations \
                 ORDER BY consumer_worker, consumer_attempt_hex, pin_key",
            ),
        ];
        let mut lines = Vec::new();
        for (table, sql) in DUMPS {
            for row in self.engine.query(sql, &[])? {
                let mut line = String::new();
                line.push_str(table);
                for value in &row {
                    line.push('|');
                    match value {
                        SqlValue::Null => line.push_str("NULL"),
                        SqlValue::Int(i) => {
                            use std::fmt::Write;
                            let _ = write!(line, "{i}");
                        }
                        SqlValue::Text(t) => line.push_str(t),
                        SqlValue::Blob(b) => line.push_str(&hex(b)),
                    }
                }
                lines.push(line);
            }
        }
        Ok(lines)
    }

    fn count_open_provisional_obligations(&mut self, pin_key: &str) -> Result<usize, StoreError> {
        let rows = self.engine.query(
            "SELECT COUNT(*) FROM provisional_obligations \
             WHERE pin_key = ?1 AND status = 'open'",
            &[SqlValue::Text(pin_key.to_owned())],
        )?;
        let Some(row) = rows.first() else {
            return Ok(0);
        };
        expect_u64(
            row.first()
                .ok_or_else(|| StoreError::Corruption("obligation count shape".into()))?,
            "obligation count",
        )
        .map(|v| v as usize)
    }

    fn list_open_provisional_pins_for_action_generation(
        &mut self,
        action_key: &str,
        generation_hex: &str,
    ) -> Result<Vec<ProvisionalPinRecord>, StoreError> {
        let rows = self.engine.query(
            "SELECT pin_key, authority_key, action_key, generation_hex, attempt_hex, \
             lease_hex, role, virtual_path, obj_algo, obj_domain, obj_bytes, object_key, \
             protective_pin_hex, renewal_seq, adopted_object_key, invalidated_reason, \
             released, toolchain_contract_key, event_contract_key \
             FROM provisional_pins \
             WHERE action_key = ?1 AND generation_hex = ?2 AND released = 0 ORDER BY pin_key",
            &[
                SqlValue::Text(action_key.to_owned()),
                SqlValue::Text(generation_hex.to_owned()),
            ],
        )?;
        rows.iter()
            .map(|row| self.map_provisional_pin_row(row))
            .collect()
    }

    fn list_open_provisional_pins_for_action(
        &mut self,
        action_key: &str,
    ) -> Result<Vec<ProvisionalPinRecord>, StoreError> {
        let rows = self.engine.query(
            "SELECT pin_key, authority_key, action_key, generation_hex, attempt_hex, \
             lease_hex, role, virtual_path, obj_algo, obj_domain, obj_bytes, object_key, \
             protective_pin_hex, renewal_seq, adopted_object_key, invalidated_reason, \
             released, toolchain_contract_key, event_contract_key \
             FROM provisional_pins WHERE action_key = ?1 AND released = 0 \
             ORDER BY pin_key",
            &[SqlValue::Text(action_key.to_owned())],
        )?;
        rows.iter()
            .map(|row| self.map_provisional_pin_row(row))
            .collect()
    }

    fn list_open_provisional_pins_for_authority(
        &mut self,
        authority_key: &str,
    ) -> Result<Vec<ProvisionalPinRecord>, StoreError> {
        let rows = self.engine.query(
            "SELECT pin_key, authority_key, action_key, generation_hex, attempt_hex, \
             lease_hex, role, virtual_path, obj_algo, obj_domain, obj_bytes, object_key, \
             protective_pin_hex, renewal_seq, adopted_object_key, invalidated_reason, \
             released, toolchain_contract_key, event_contract_key \
             FROM provisional_pins WHERE authority_key = ?1 AND released = 0 \
             ORDER BY pin_key",
            &[SqlValue::Text(authority_key.to_owned())],
        )?;
        rows.iter()
            .map(|row| self.map_provisional_pin_row(row))
            .collect()
    }

    fn list_open_provisional_obligations_by_attempt(
        &mut self,
        consumer_attempt_hex: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT consumer_worker, consumer_attempt_hex, pin_key, producer_action_key, \
             producer_generation_hex, producer_attempt_hex, role, virtual_path, object_key, \
             status, resolution_object_key, created_seq FROM provisional_obligations \
             WHERE consumer_attempt_hex = ?1 AND status != 'resolved' \
             ORDER BY pin_key",
            &[SqlValue::Text(consumer_attempt_hex.to_owned())],
        )?;
        rows.iter()
            .map(|row| Self::map_obligation_row(row))
            .collect()
    }

    fn list_provisional_obligations_by_attempt_all(
        &mut self,
        consumer_attempt_hex: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT consumer_worker, consumer_attempt_hex, pin_key, producer_action_key, \
             producer_generation_hex, producer_attempt_hex, role, virtual_path, object_key, \
             status, resolution_object_key, created_seq FROM provisional_obligations \
             WHERE consumer_attempt_hex = ?1 \
             ORDER BY status, pin_key",
            &[SqlValue::Text(consumer_attempt_hex.to_owned())],
        )?;
        rows.iter()
            .map(|row| Self::map_obligation_row(row))
            .collect()
    }

    fn insert_provisional_install(
        &mut self,
        install: &ProvisionalInstallInsert,
    ) -> Result<(), StoreError> {
        let row = install.clone();
        // R121: intern the object's domain for fail-closed restoration.
        self.intern(row.object.domain);
        self.in_txn(move |engine| {
            engine.execute(
                "INSERT OR IGNORE INTO provisional_install_journal \
                 (pin_key, consumer_worker, consumer_attempt_hex, installed_path, \
                 obj_algo, obj_domain, obj_bytes, object_key, installed_seq, state) \
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 'installed')",
                &[
                    SqlValue::Text(row.pin_key),
                    SqlValue::Text(row.consumer_worker),
                    SqlValue::Text(u128_hex(row.consumer_attempt)),
                    SqlValue::Blob(row.installed_path),
                    SqlValue::Text(algo_tag(row.object.algorithm).to_owned()),
                    SqlValue::Text(row.object.domain.to_owned()),
                    SqlValue::Blob(row.object.bytes.to_vec()),
                    SqlValue::Text(digest_key(&row.object)),
                    SqlValue::Int(row.installed_seq as i64),
                ],
            )?;
            Ok(())
        })
    }

    fn list_provisional_installs_for_pins(
        &mut self,
        pin_keys: &[String],
    ) -> Result<Vec<ProvisionalInstallRecord>, StoreError> {
        if pin_keys.is_empty() {
            return Ok(Vec::new());
        }
        let placeholders = (0..pin_keys.len())
            .map(|i| format!("?{}", i + 1))
            .collect::<Vec<_>>()
            .join(", ");
        let params: Vec<SqlValue> = pin_keys
            .iter()
            .map(|key| SqlValue::Text(key.clone()))
            .collect();
        let rows = self.engine.query(
            &format!(
                "SELECT pin_key, consumer_worker, consumer_attempt_hex, installed_path, \
                 obj_algo, obj_domain, obj_bytes, object_key, installed_seq, state \
                 FROM provisional_install_journal WHERE pin_key IN ({placeholders}) \
                 ORDER BY pin_key, consumer_attempt_hex, installed_path"
            ),
            &params,
        )?;
        rows.iter()
            .map(|row| Self::map_install_row(self, row))
            .collect()
    }

    fn list_provisional_installs_by_state(
        &mut self,
        state: &str,
    ) -> Result<Vec<ProvisionalInstallRecord>, StoreError> {
        let rows = self.engine.query(
            "SELECT pin_key, consumer_worker, consumer_attempt_hex, installed_path, \
             obj_algo, obj_domain, obj_bytes, object_key, installed_seq, state \
             FROM provisional_install_journal WHERE state = ?1 \
             ORDER BY pin_key, consumer_attempt_hex, installed_path",
            &[SqlValue::Text(state.to_owned())],
        )?;
        rows.iter()
            .map(|row| Self::map_install_row(self, row))
            .collect()
    }

    fn set_provisional_install_state(
        &mut self,
        pin_key: &str,
        consumer_attempt_hex: &str,
        installed_path: &[u8],
        state: &str,
    ) -> Result<(), StoreError> {
        let (pin_key, attempt_hex, path, state) = (
            pin_key.to_owned(),
            consumer_attempt_hex.to_owned(),
            installed_path.to_vec(),
            state.to_owned(),
        );
        self.in_txn(move |engine| {
            let affected = engine.execute(
                "UPDATE provisional_install_journal SET state = ?4 \
                 WHERE pin_key = ?1 AND consumer_attempt_hex = ?2 AND installed_path = ?3",
                &[
                    SqlValue::Text(pin_key),
                    SqlValue::Text(attempt_hex),
                    SqlValue::Blob(path),
                    SqlValue::Text(state),
                ],
            )?;
            if affected == 0 {
                return Err(StoreError::UnknownPin);
            }
            Ok(())
        })
    }

    fn bind_native_children(
        &mut self,
        parent_action_key: &str,
        child_action_keys: &[String],
        bound_seq: u64,
    ) -> Result<(), StoreError> {
        let parent = parent_action_key.to_owned();
        let children: Vec<String> = child_action_keys.to_vec();
        self.in_txn(move |engine| {
            for child in children {
                engine.execute(
                    "INSERT OR IGNORE INTO native_child_bindings \
                     (parent_action_key, child_action_key, bound_seq, state) \
                     VALUES (?1, ?2, ?3, 'bound')",
                    &[
                        SqlValue::Text(parent.clone()),
                        SqlValue::Text(child),
                        SqlValue::Int(bound_seq as i64),
                    ],
                )?;
            }
            Ok(())
        })
    }

    fn list_native_child_bindings(
        &mut self,
        parent_action_key: &str,
    ) -> Result<Vec<(String, String)>, StoreError> {
        let rows = self.engine.query(
            "SELECT child_action_key, state FROM native_child_bindings \
             WHERE parent_action_key = ?1 ORDER BY child_action_key",
            &[SqlValue::Text(parent_action_key.to_owned())],
        )?;
        rows.into_iter()
            .map(|row| match row.as_slice() {
                [SqlValue::Text(child), SqlValue::Text(state)] => {
                    Ok((child.clone(), state.clone()))
                }
                _ => Err(StoreError::Corruption("native child binding shape".into())),
            })
            .collect()
    }

    fn set_native_child_binding_state(
        &mut self,
        parent_action_key: &str,
        child_action_key: &str,
        state: &str,
    ) -> Result<(), StoreError> {
        let (parent, child, state) = (
            parent_action_key.to_owned(),
            child_action_key.to_owned(),
            state.to_owned(),
        );
        self.in_txn(move |engine| {
            let affected = engine.execute(
                "UPDATE native_child_bindings SET state = ?3 \
                 WHERE parent_action_key = ?1 AND child_action_key = ?2",
                &[
                    SqlValue::Text(parent),
                    SqlValue::Text(child),
                    SqlValue::Text(state),
                ],
            )?;
            if affected == 0 {
                return Err(StoreError::UnknownPin);
            }
            Ok(())
        })
    }

    fn list_provisional_obligations_for_pin(
        &mut self,
        pin_key: &str,
    ) -> Result<Vec<ProvisionalObligationRow>, StoreError> {
        let rows = self.engine.query(
            "SELECT consumer_worker, consumer_attempt_hex, pin_key, producer_action_key, \
             producer_generation_hex, producer_attempt_hex, role, virtual_path, object_key, \
             status, resolution_object_key, created_seq FROM provisional_obligations \
             WHERE pin_key = ?1 ORDER BY consumer_worker, consumer_attempt_hex",
            &[SqlValue::Text(pin_key.to_owned())],
        )?;
        rows.iter()
            .map(|row| Self::map_obligation_row(row))
            .collect()
    }
}

// ---------------------------------------------------------------------
// Engine: rusqlite (reference TRUTH).
// ---------------------------------------------------------------------

/// The reference SQLite engine (bundled C SQLite via rusqlite).
pub struct RusqliteEngine {
    conn: rusqlite::Connection,
}

impl RusqliteEngine {
    /// Open (or create) a database file.
    pub fn open(path: &std::path::Path) -> Result<Self, StoreError> {
        rusqlite::Connection::open(path)
            .map(|conn| Self { conn })
            .map_err(|e| StoreError::Backend(e.to_string()))
    }

    /// Open an in-memory database.
    pub fn open_in_memory() -> Result<Self, StoreError> {
        rusqlite::Connection::open_in_memory()
            .map(|conn| Self { conn })
            .map_err(|e| StoreError::Backend(e.to_string()))
    }
}

fn to_rusqlite(v: &SqlValue) -> rusqlite::types::Value {
    match v {
        SqlValue::Null => rusqlite::types::Value::Null,
        SqlValue::Int(i) => rusqlite::types::Value::Integer(*i),
        SqlValue::Text(t) => rusqlite::types::Value::Text(t.clone()),
        SqlValue::Blob(b) => rusqlite::types::Value::Blob(b.clone()),
    }
}

impl SqlEngine for RusqliteEngine {
    fn execute(&mut self, sql: &str, params: &[SqlValue]) -> Result<usize, StoreError> {
        let bound = rusqlite::params_from_iter(params.iter().map(to_rusqlite));
        self.conn
            .execute(sql, bound)
            .map_err(|e| StoreError::Backend(e.to_string()))
    }

    fn query(&mut self, sql: &str, params: &[SqlValue]) -> Result<Vec<Vec<SqlValue>>, StoreError> {
        let mut statement = self
            .conn
            .prepare(sql)
            .map_err(|e| StoreError::Backend(e.to_string()))?;
        let column_count = statement.column_count();
        let bound = rusqlite::params_from_iter(params.iter().map(to_rusqlite));
        let mut rows = statement
            .query(bound)
            .map_err(|e| StoreError::Backend(e.to_string()))?;
        let mut out = Vec::new();
        while let Some(row) = rows
            .next()
            .map_err(|e| StoreError::Backend(e.to_string()))?
        {
            let mut cols = Vec::with_capacity(column_count);
            for i in 0..column_count {
                let value: rusqlite::types::Value =
                    row.get(i).map_err(|e| StoreError::Backend(e.to_string()))?;
                cols.push(match value {
                    rusqlite::types::Value::Null => SqlValue::Null,
                    rusqlite::types::Value::Integer(v) => SqlValue::Int(v),
                    rusqlite::types::Value::Real(f) => {
                        return Err(StoreError::Corruption(format!(
                            "unexpected float column {f}"
                        )));
                    }
                    rusqlite::types::Value::Text(t) => SqlValue::Text(t),
                    rusqlite::types::Value::Blob(b) => SqlValue::Blob(b),
                });
            }
            out.push(cols);
        }
        Ok(out)
    }
}

// ---------------------------------------------------------------------
// Engine: fsqlite (FrankenSQLite dogfood candidate).
// ---------------------------------------------------------------------

/// The FrankenSQLite engine (pure Rust).
pub struct FsqliteEngine {
    conn: fsqlite::AsyncConnection,
}

impl FsqliteEngine {
    /// Open (or create) a database file.
    pub fn open(path: &std::path::Path) -> Result<Self, StoreError> {
        fsqlite::AsyncConnection::open_sync(path.display().to_string())
            .map(|conn| Self { conn })
            .map_err(|e| StoreError::Backend(e.to_string()))
    }
}

impl Drop for FsqliteEngine {
    fn drop(&mut self) {
        // Join the engine worker before callers can reopen the database.
        // Preserve the old Connection Drop behavior: rollback unfinished work
        // and release resources without checkpointing the committed WAL.
        if let Err(error) = self.conn.close_without_checkpoint_sync() {
            use std::io::Write as _;
            let _ = writeln!(std::io::stderr(), "FrankenSQLite close failed: {error}");
        }
    }
}

fn to_fsqlite(v: &SqlValue) -> fsqlite::SqliteValue {
    match v {
        SqlValue::Null => fsqlite::SqliteValue::Null,
        SqlValue::Int(i) => fsqlite::SqliteValue::Integer(*i),
        SqlValue::Text(t) => fsqlite::SqliteValue::Text(t.as_str().into()),
        SqlValue::Blob(b) => fsqlite::SqliteValue::Blob(b.clone().into()),
    }
}

fn from_fsqlite(v: &fsqlite::SqliteValue) -> Result<SqlValue, StoreError> {
    match v {
        fsqlite::SqliteValue::Null => Ok(SqlValue::Null),
        fsqlite::SqliteValue::Integer(i) => Ok(SqlValue::Int(*i)),
        fsqlite::SqliteValue::Float(f) => Err(StoreError::Corruption(format!(
            "unexpected float column {f}"
        ))),
        fsqlite::SqliteValue::Text(t) => Ok(SqlValue::Text(t.as_str().to_owned())),
        fsqlite::SqliteValue::Blob(b) => Ok(SqlValue::Blob(b.as_ref().to_vec())),
    }
}

impl SqlEngine for FsqliteEngine {
    fn execute(&mut self, sql: &str, params: &[SqlValue]) -> Result<usize, StoreError> {
        if params.is_empty() {
            return self
                .conn
                .execute_sync(sql)
                .map_err(|e| StoreError::Backend(e.to_string()));
        }
        let bound: Vec<fsqlite::SqliteValue> = params.iter().map(to_fsqlite).collect();
        self.conn
            .execute_with_params_sync(sql, &bound)
            .map_err(|e| StoreError::Backend(e.to_string()))
    }

    fn query(&mut self, sql: &str, params: &[SqlValue]) -> Result<Vec<Vec<SqlValue>>, StoreError> {
        let bound: Vec<fsqlite::SqliteValue> = params.iter().map(to_fsqlite).collect();
        let rows = self
            .conn
            .query_with_params_sync(sql, &bound)
            .map_err(|e| StoreError::Backend(e.to_string()))?;
        rows.iter()
            .map(|row| row.values().iter().map(from_fsqlite).collect())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rabs_protocol::authority::{ClusterId, CoordinatorAuthority, CoordinatorIncarnationId};
    use rabs_protocol::generation::{
        ActionGenerationId, AttemptId, ExecutionLeaseId, LeaseRenewalSeq,
    };
    use std::sync::atomic::{AtomicU64, Ordering};

    static DB_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn fresh_path(tag: &str) -> std::path::PathBuf {
        let n = DB_COUNTER.fetch_add(1, Ordering::SeqCst);
        std::env::temp_dir().join(format!("rabs-h009-{}-{}-{}.db", std::process::id(), tag, n))
    }

    #[test]
    fn fsqlite_drop_finishes_rollback_before_immediate_reopen() {
        let path = fresh_path("fsqlite-drop-rollback");
        assert!(!path.exists());
        {
            let mut engine = FsqliteEngine::open(&path).unwrap();
            engine
                .execute("CREATE TABLE lifecycle (id INTEGER PRIMARY KEY)", &[])
                .unwrap();
            engine
                .execute("INSERT INTO lifecycle VALUES (?1)", &[SqlValue::Int(1)])
                .unwrap();
            engine.execute("BEGIN", &[]).unwrap();
            engine
                .execute("INSERT INTO lifecycle VALUES (?1)", &[SqlValue::Int(2)])
                .unwrap();
        }
        let mut reopened = FsqliteEngine::open(&path).unwrap();
        assert_eq!(
            reopened
                .query("SELECT id FROM lifecycle ORDER BY id", &[])
                .unwrap(),
            vec![vec![SqlValue::Int(1)]]
        );
        reopened
            .execute("INSERT INTO lifecycle VALUES (?1)", &[SqlValue::Int(3)])
            .unwrap();
        assert_eq!(
            reopened
                .query("SELECT id FROM lifecycle ORDER BY id", &[])
                .unwrap(),
            vec![vec![SqlValue::Int(1)], vec![SqlValue::Int(3)]]
        );
    }

    #[test]
    fn fsqlite_drop_preserves_committed_wal_before_reopen() {
        let path = fresh_path("fsqlite-drop-wal");
        assert!(!path.exists());
        let mut wal_path = path.as_os_str().to_os_string();
        wal_path.push("-wal");
        let wal_path = std::path::PathBuf::from(wal_path);
        assert!(!wal_path.exists());
        let wal_before;
        {
            let mut engine = FsqliteEngine::open(&path).unwrap();
            engine.query("PRAGMA journal_mode=WAL", &[]).unwrap();
            engine.execute("PRAGMA wal_autocheckpoint=0", &[]).unwrap();
            engine
                .execute("CREATE TABLE lifecycle (id INTEGER PRIMARY KEY)", &[])
                .unwrap();
            engine
                .execute("INSERT INTO lifecycle VALUES (?1)", &[SqlValue::Int(7)])
                .unwrap();
            wal_before = std::fs::read(&wal_path).unwrap();
            // A WAL header alone is 32 bytes; require committed frame content.
            assert!(wal_before.len() > 32);
        }
        assert_eq!(std::fs::read(&wal_path).unwrap(), wal_before);
        let mut reopened = FsqliteEngine::open(&path).unwrap();
        assert_eq!(
            reopened.query("SELECT id FROM lifecycle", &[]).unwrap(),
            vec![vec![SqlValue::Int(7)]]
        );
    }

    /// Execute real SQL, optionally refusing exactly one mutation before it
    /// reaches the engine. Rollback remains available after the injected error.
    struct MigrationProbe<E> {
        inner: E,
        executed: Vec<String>,
        fail_at: Option<usize>,
    }

    impl<E: SqlEngine> SqlEngine for MigrationProbe<E> {
        fn execute(&mut self, sql: &str, params: &[SqlValue]) -> Result<usize, StoreError> {
            let index = self.executed.len();
            self.executed.push(sql.to_owned());
            if self.fail_at == Some(index) {
                return Err(StoreError::Backend("injected migration failure".into()));
            }
            self.inner.execute(sql, params)
        }

        fn query(
            &mut self,
            sql: &str,
            params: &[SqlValue],
        ) -> Result<Vec<Vec<SqlValue>>, StoreError> {
            self.inner.query(sql, params)
        }
    }

    fn migration_probe<E>(inner: E, fail_at: Option<usize>) -> MigrationProbe<E> {
        MigrationProbe {
            inner,
            executed: Vec::new(),
            fail_at,
        }
    }

    fn assert_one_migration_commit<E: SqlEngine>(store: &mut SqlMetadataStore<MigrationProbe<E>>) {
        assert_eq!(store.schema_version().unwrap(), SCHEMA_VERSION);
        let statements = &store.engine.executed;
        assert_eq!(statements.iter().filter(|sql| *sql == "BEGIN").count(), 1);
        assert_eq!(statements.iter().filter(|sql| *sql == "COMMIT").count(), 1);
        assert!(!statements.iter().any(|sql| sql == "ROLLBACK"));
        assert_eq!(
            store
                .engine
                .query("SELECT version FROM schema_epochs ORDER BY version", &[])
                .unwrap(),
            (1..=SCHEMA_VERSION)
                .map(|version| vec![SqlValue::Int(i64::from(version))])
                .collect::<Vec<_>>()
        );
    }

    fn migration_batch_behavior<E: SqlEngine>(open: fn(&std::path::Path) -> Result<E, StoreError>) {
        let fresh = fresh_path("migration-single-commit");
        let mut store =
            SqlMetadataStore::open(migration_probe(open(&fresh).unwrap(), None)).unwrap();
        assert_one_migration_commit(&mut store);
        drop(store);
        let store = SqlMetadataStore::open(migration_probe(open(&fresh).unwrap(), None)).unwrap();
        assert!(
            store.engine.executed.is_empty(),
            "current-schema reopen must not write"
        );
        drop(store);

        for version in [0, 19, 20] {
            let pending_writes: usize = MIGRATIONS
                .iter()
                .filter(|migration| migration.version > version)
                .map(|migration| migration.statements.len() + 1)
                .sum();
            // Refuse the final DDL, final epoch insert, or COMMIT itself.
            for fail_at in [pending_writes - 1, pending_writes, pending_writes + 1] {
                let path = fresh_path("migration-rollback");
                let mut engine = open(&path).unwrap();
                match version {
                    19 => seed_v19_worker_fence(&mut engine),
                    20 => seed_v20_attempt_lease(&mut engine),
                    _ => {}
                }
                let queries = [
                    "SELECT * FROM worker_incarnation_fences ORDER BY worker",
                    "SELECT * FROM action_generations ORDER BY id_hex",
                    "SELECT * FROM action_attempts ORDER BY id_hex",
                ];
                let prior_rows = if version == 0 {
                    Vec::new()
                } else {
                    queries
                        .iter()
                        .map(|sql| engine.query(sql, &[]).unwrap())
                        .collect::<Vec<_>>()
                };
                let mut failed = SqlMetadataStore {
                    engine: migration_probe(engine, Some(fail_at)),
                    domains: HashMap::new(),
                };
                assert_eq!(
                    failed.apply_migrations(),
                    Err(StoreError::Backend("injected migration failure".into()))
                );
                assert_eq!(
                    failed.engine.executed.last().map(String::as_str),
                    Some("ROLLBACK")
                );
                // Verify cleanup before dropping the connection: a still-open
                // migration transaction would reject this new transaction.
                failed.engine.execute("BEGIN", &[]).unwrap();
                failed.engine.execute("ROLLBACK", &[]).unwrap();
                drop(failed);

                // Reopen the actual file before attempting any new migration.
                let mut reopened = open(&path).unwrap();
                if version == 0 {
                    assert!(
                        reopened
                            .query(
                                "SELECT name FROM sqlite_master WHERE name = 'schema_epochs'",
                                &[]
                            )
                            .unwrap()
                            .is_empty()
                    );
                } else {
                    assert_eq!(
                        reopened
                            .query("SELECT MAX(version) FROM schema_epochs", &[])
                            .unwrap(),
                        vec![vec![SqlValue::Int(i64::from(version))]]
                    );
                    for (sql, expected) in queries.iter().zip(&prior_rows) {
                        assert_eq!(
                            &reopened.query(sql, &[]).unwrap(),
                            expected,
                            "version {version}, failure {fail_at}, query {sql}"
                        );
                    }
                }
                let mut retried = SqlMetadataStore::open(migration_probe(reopened, None)).unwrap();
                assert_one_migration_commit(&mut retried);
                if version == 19 {
                    assert_v19_worker_fence_migrated(&mut retried);
                } else if version == 20 {
                    assert_v20_attempt_lease_fails_closed(&mut retried);
                }
            }
        }
    }

    #[test]
    fn pending_migrations_commit_once_and_rollback_reference() {
        migration_batch_behavior(RusqliteEngine::open);
    }

    #[test]
    fn pending_migrations_commit_once_and_rollback_frankensqlite() {
        migration_batch_behavior(FsqliteEngine::open);
    }

    fn digest(domain: &'static str, tag: u8) -> TypedDigest {
        TypedDigest {
            algorithm: DigestAlgorithm::Sha256V1,
            domain,
            bytes: [tag; 32],
        }
    }

    fn authority(tag: u8) -> AuthorityRow {
        AuthorityRow {
            digest: digest("rabs.authority.sha256.v1", tag),
            cluster_id: "cluster-a".to_owned(),
            incarnation: u128::from(tag),
            term: u64::from(tag),
            acquired_seq: 1,
        }
    }

    fn coordinator_authority() -> CoordinatorAuthority {
        CoordinatorAuthority {
            cluster_id: ClusterId("cluster-a".to_owned()),
            credential_generation: 1,
            term: 1,
            incarnation_id: CoordinatorIncarnationId(1),
        }
    }

    fn bound_authority_row() -> AuthorityRow {
        let coordinator = coordinator_authority();
        AuthorityRow {
            digest: rabs_key::authority_binding::coordinator_authority_digest(&coordinator),
            cluster_id: "cluster-a".to_owned(),
            incarnation: 1,
            term: 1,
            acquired_seq: 1,
        }
    }

    fn bound_attempt_authority() -> AttemptAuthority {
        let coordinator = coordinator_authority();
        let created_under = rabs_key::authority_binding::coordinator_authority_digest(&coordinator);
        AttemptAuthority {
            coordinator,
            action_key: digest("rabs.action-key.sha256.v1", 7),
            action_generation: ActionGeneration {
                generation_id: ActionGenerationId(11),
                per_key_ordinal: 1,
                created_under_authority_digest: created_under,
            },
            attempt_id: AttemptId(22),
            execution_lease_id: ExecutionLeaseId(30),
            lease_renewal_seq: LeaseRenewalSeq(1),
            worker_peer_id: PeerId("lease-worker".to_owned()),
            worker_boot_generation: WorkerBootGeneration(3),
            worker_incarnation_id: WorkerIncarnationId(99),
        }
    }

    fn worker_offer(worker: &str, generation: u64, incarnation: u128) -> WorkerSessionOffer {
        WorkerSessionOffer {
            worker_peer_id: PeerId(worker.to_owned()),
            boot_generation: WorkerBootGeneration(generation),
            incarnation: WorkerIncarnationId(incarnation),
            reenrollment_proof: None,
        }
    }

    fn publication(action_tag: u8, descriptor_tag: u8, pin: u128) -> PublicationRow {
        PublicationRow {
            action_key: digest("rabs.action-key.sha256.v1", action_tag),
            descriptor_digest: digest("rabs.descriptor.sha256.v1", descriptor_tag),
            manifest_digest: digest("rabs.result-manifest.sha256.v1", descriptor_tag),
            evidence_digest: digest("rabs.evidence-bundle.sha256.v1", descriptor_tag),
            winner_generation: 10,
            winner_attempt: 20,
            result_kind: ResultKindTag::Success,
            pin_id: pin,
            pin_owner: "coordinator".to_owned(),
            provisional_ancestors: Vec::new(),
        }
    }

    /// Drive one full behavioral pass over any backend. Returns the
    /// differential snapshot so callers can compare backends.
    fn behavioral_pass(store: &mut dyn RabsMetadataStore) -> Vec<String> {
        // H009 migrations: versioned, applied, reported.
        assert_eq!(store.schema_version().unwrap(), SCHEMA_VERSION);

        // Single-writer authority.
        let bound_authority = bound_authority_row();
        store.acquire_authority(&bound_authority).unwrap();
        store.acquire_authority(&bound_authority).unwrap(); // idempotent
        assert!(matches!(
            store.acquire_authority(&authority(2)),
            Err(StoreError::AuthorityHeld { .. })
        ));
        assert_eq!(store.active_authority().unwrap().unwrap(), bound_authority);

        // Action entries round-trip.
        let action = ActionEntryRow {
            action_key: digest("rabs.action-key.sha256.v1", 7),
            key_epoch: 3,
            projection_epoch: 4,
        };
        store.upsert_action_entry(&action).unwrap();
        assert_eq!(
            store.lookup_action(&action.action_key).unwrap(),
            Some(action.clone())
        );
        assert_eq!(
            store
                .lookup_action(&digest("rabs.action-key.sha256.v1", 99))
                .unwrap(),
            None
        );

        // Generations: coordinator-only + never-reused ids.
        let active = bound_authority_row().digest;
        let wrong = digest("rabs.authority.sha256.v1", 2);
        assert_eq!(
            store.create_generation(&wrong, 10, &action.action_key),
            Err(StoreError::NotActiveAuthority)
        );
        store
            .create_generation(&active, 10, &action.action_key)
            .unwrap();
        store.tombstone_generation(10).unwrap();
        // Tombstoning does NOT free the id — high-water forbids reuse.
        assert_eq!(
            store.create_generation(&active, 10, &action.action_key),
            Err(StoreError::GenerationIdNotAboveHighWater)
        );
        assert_eq!(
            store.create_generation(&active, 9, &action.action_key),
            Err(StoreError::GenerationIdNotAboveHighWater)
        );
        let attempt_authority = bound_attempt_authority();
        store
            .create_bound_generation(
                &active,
                &attempt_authority.action_generation,
                &action.action_key,
            )
            .unwrap();

        // Attempts: append-only.
        store.record_attempt(20, 11, "worker-a", 5).unwrap();
        assert_eq!(
            store.record_attempt(20, 11, "worker-a", 6),
            Err(StoreError::DuplicateAttempt)
        );
        assert_eq!(
            store.record_attempt(21, 999, "worker-a", 6),
            Err(StoreError::UnknownGeneration)
        );

        // Leases: exact worker binding + durable compare-and-swap renewal,
        // with no renewal after release.
        store
            .admit_worker_session(
                &active,
                &WorkerSessionOffer {
                    worker_peer_id: attempt_authority.worker_peer_id.clone(),
                    boot_generation: attempt_authority.worker_boot_generation,
                    incarnation: attempt_authority.worker_incarnation_id,
                    reenrollment_proof: None,
                },
                4,
            )
            .unwrap();
        store
            .admit_attempt_lease(&attempt_authority, 5, 100)
            .unwrap();
        let renewal = LeaseRenewal {
            lease: attempt_authority.execution_lease_id,
            seq: LeaseRenewalSeq(2),
        };
        store
            .renew_attempt_lease(&attempt_authority, renewal, 200, &|| 10)
            .unwrap();
        assert_eq!(
            store.renew_attempt_lease(&attempt_authority, renewal, 300, &|| 10),
            Err(StoreError::LeaseRenewalMismatch)
        );
        let mut current_authority = attempt_authority.clone();
        current_authority.lease_renewal_seq = LeaseRenewalSeq(2);
        assert_eq!(
            store.renew_attempt_lease(
                &current_authority,
                LeaseRenewal {
                    lease: current_authority.execution_lease_id,
                    seq: LeaseRenewalSeq(2),
                },
                300,
                &|| 10,
            ),
            Err(StoreError::NonMonotonicRenewal)
        );
        let mut unknown = current_authority.clone();
        unknown.execution_lease_id = rabs_protocol::generation::ExecutionLeaseId(31);
        assert_eq!(
            store.renew_attempt_lease(
                &unknown,
                LeaseRenewal {
                    lease: unknown.execution_lease_id,
                    seq: LeaseRenewalSeq(3),
                },
                300,
                &|| 10,
            ),
            Err(StoreError::UnknownLease)
        );
        store.release_lease(30).unwrap();
        assert_eq!(
            store.renew_attempt_lease(
                &current_authority,
                LeaseRenewal {
                    lease: current_authority.execution_lease_id,
                    seq: LeaseRenewalSeq(3),
                },
                300,
                &|| 10,
            ),
            Err(StoreError::LeaseReleased)
        );

        // Publication: coordinator-only, transactional with pin,
        // conflict-quarantined on descriptor mismatch.
        let publication_row = publication(7, 1, 40);
        assert_eq!(
            store.commit_publication(&wrong, None, &publication_row),
            Err(StoreError::NotActiveAuthority)
        );
        assert_eq!(
            store
                .commit_publication(&active, None, &publication_row)
                .unwrap(),
            CommitOutcome::Committed
        );
        assert_eq!(
            store
                .commit_publication(&active, None, &publication_row)
                .unwrap(),
            CommitOutcome::IdempotentDuplicate
        );
        assert_eq!(
            store
                .commit_publication(&active, None, &publication(7, 2, 41))
                .unwrap(),
            CommitOutcome::ConflictQuarantined
        );
        assert!(store.has_publication(&publication_row.action_key).unwrap());
        assert!(
            !store
                .has_publication(&digest("rabs.action-key.sha256.v1", 99))
                .unwrap()
        );
        // Evidence is append-only and idempotent per digest.
        let extra_evidence = digest("rabs.evidence-bundle.sha256.v1", 90);
        let manifest_key = digest_key(&publication_row.manifest_digest);
        store
            .append_evidence(
                &publication_row.action_key,
                &manifest_key,
                &extra_evidence,
                11,
                20,
            )
            .unwrap();
        // Re-append under a DIFFERENT attribution: idempotent no-op, the
        // original (manifest, generation, attempt) row is never rewritten
        // (H029).
        store
            .append_evidence(
                &publication_row.action_key,
                "rabs.canonical-result-manifest.sha256.v1:ff",
                &extra_evidence,
                99,
                98,
            )
            .unwrap();
        let evidence_line = store
            .differential_snapshot()
            .unwrap()
            .into_iter()
            .find(|l| l.starts_with("action_evidence_index|") && l.contains("|5a5a"))
            .expect("extra evidence row present");
        assert!(
            evidence_line.contains(&u128_hex(11)) && evidence_line.contains(&u128_hex(20)),
            "first-writer attribution preserved: {evidence_line}"
        );
        assert!(
            !evidence_line.ends_with(":ff"),
            "re-append must not rebind the manifest: {evidence_line}"
        );
        // Per-manifest listing binds evidence to the canonical result.
        let for_manifest = store
            .list_evidence_keys_for_manifest(&manifest_key)
            .unwrap();
        assert!(for_manifest.contains(&digest_key(&extra_evidence)));
        assert!(
            store
                .list_evidence_keys_for_manifest("rabs.canonical-result-manifest.sha256.v1:ff")
                .unwrap()
                .is_empty()
        );

        // Objects, locations, pins.
        let object = digest("rabs.object.sha256.v1", 50);
        store.record_object(&object, 4096).unwrap();
        store
            .add_location(&object, "/cas/aa/bb", Some(7), "raw", true)
            .unwrap();
        store
            .add_location(&object, "/cas/cc/dd", None, "zstd", false)
            .unwrap();
        store
            .create_pin(
                60,
                &object,
                "operator",
                "administrative",
                Some(500),
                Some("manual hold"),
                false,
                "operator investigation",
            )
            .unwrap();
        assert_eq!(
            store.release_pin(60, "someone-else"),
            Err(StoreError::PinOwnerMismatch)
        );
        assert_eq!(
            store.release_pin(61, "operator"),
            Err(StoreError::UnknownPin)
        );
        // H010: pin lease renewal is strictly monotonic.
        store.renew_pin(60, 2).unwrap();
        assert_eq!(
            store.renew_pin(60, 2),
            Err(StoreError::NonMonotonicPinRenewal)
        );
        assert_eq!(store.renew_pin(62, 1), Err(StoreError::UnknownPin));

        // H010: reachability edges from the pinned root.
        let child = digest("rabs.object.sha256.v1", 51);
        let grandchild = digest("rabs.object.sha256.v1", 52);
        let orphan = digest("rabs.object.sha256.v1", 53);
        store.record_object(&child, 16).unwrap();
        store.record_object(&grandchild, 16).unwrap();
        store.record_object(&orphan, 16).unwrap();
        store
            .add_object_edge(&object, &child, "manifest-entry")
            .unwrap();
        store.add_object_edge(&child, &grandchild, "chunk").unwrap();
        // Cycle back to the root must not loop the traversal.
        store
            .add_object_edge(&grandchild, &object, "back-ref")
            .unwrap();

        // H010: location quarantine is COPY evidence, never identity.
        store
            .set_location_quarantined(&object, "/cas/aa/bb", true)
            .unwrap();
        store
            .add_location(&object, "/cas/aa/bb", Some(8), "raw", true)
            .unwrap();
        assert!(
            store.object_located(&object).unwrap(),
            "second clean copy remains"
        );
        assert!(
            !store.object_durably_located(&object).unwrap(),
            "refreshing the durable copy must not release its quarantine"
        );
        store
            .set_location_quarantined(&object, "/cas/cc/dd", true)
            .unwrap();
        store
            .add_location(&object, "/cas/cc/dd", None, "zstd", false)
            .unwrap();
        assert!(
            !store.object_located(&object).unwrap(),
            "all copies quarantined: object unavailable"
        );
        // The object row and its edges are untouched by construction.
        store
            .set_location_quarantined(&object, "/cas/aa/bb", false)
            .unwrap();
        assert!(store.object_located(&object).unwrap());

        // Recipes, breakdowns, trust, quarantine, verification.
        store
            .put_recipe(&action.action_key, &digest("rabs.recipe.sha256.v1", 70))
            .unwrap();
        store
            .put_key_breakdown(
                &action.action_key,
                "toolchain",
                &digest("rabs.component.sha256.v1", 71),
            )
            .unwrap();
        store
            .set_trust(&action.action_key, "trusted", "verified twice")
            .unwrap();
        store
            .add_quarantine(QuarantineScope::Location, "/cas/cc/dd", "checksum mismatch")
            .unwrap();
        store
            .record_verification_sample(&action.action_key, 20, true, 8)
            .unwrap();

        // GC snapshot + reconciliation scan.
        let snapshot = store.gc_snapshot(9).unwrap();
        // Publication pin (40) + administrative pin (60) both unreleased.
        assert_eq!(snapshot.pinned_roots.len(), 2);
        assert_eq!(snapshot.located_objects, vec![digest_key(&object)]);
        // H010 reachability: both pin roots plus the object→child→
        // grandchild closure (the cycle edge terminates via the visited
        // set); the orphan is NOT reachable.
        assert_eq!(snapshot.reachable_from_pins.len(), 4);
        assert!(snapshot.reachable_from_pins.contains(&digest_key(&object)));
        assert!(snapshot.reachable_from_pins.contains(&digest_key(&child)));
        assert!(
            snapshot
                .reachable_from_pins
                .contains(&digest_key(&grandchild))
        );
        assert!(!snapshot.reachable_from_pins.contains(&digest_key(&orphan)));
        let scan = store.reconciliation_scan().unwrap();
        assert_eq!(scan.len(), 2);
        assert_eq!(scan[0].verified_seq, Some(8));
        assert_eq!(scan[0].encoding, "raw");
        assert!(!scan[0].quarantined);
        assert_eq!(scan[1].verified_seq, None);
        assert_eq!(scan[1].encoding, "zstd");
        assert!(scan[1].quarantined);

        // Peer authority terms fence rollback; equal terms also fence clones.
        assert_eq!(
            store.record_peer_authority_high_water(&wrong, "peer-1", 2, 5, 11, 100),
            Err(StoreError::NotActiveAuthority)
        );
        store
            .record_peer_authority_high_water(&active, "peer-1", 2, 5, 11, 100)
            .unwrap();
        store
            .record_peer_authority_high_water(&active, "peer-1", 2, 5, 11, 101)
            .unwrap();
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 2, 5, 12, 102),
            Err(StoreError::StalePeerAuthority)
        );
        assert_eq!(
            store.peer_authority_high_water("peer-1").unwrap(),
            Some((2, 5, 100)),
            "a conflicting incarnation must not change the durable mark"
        );
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 2, 4, 11, 102),
            Err(StoreError::StalePeerAuthority)
        );
        store
            .record_peer_authority_high_water(&active, "peer-1", 2, 6, 12, 103)
            .unwrap();
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 2, 6, 11, 104),
            Err(StoreError::StalePeerAuthority)
        );
        assert_eq!(
            store.peer_authority_high_water("peer-1").unwrap(),
            Some((2, 6, 103))
        );
        assert_eq!(store.peer_authority_high_water("peer-2").unwrap(), None);
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 1, 999, 12, 105),
            Err(StoreError::StalePeerAuthority),
            "a larger term cannot revive an older credential generation"
        );
        store
            .record_peer_authority_high_water(&active, "peer-1", 3, 1, 13, 106)
            .unwrap();
        assert_eq!(
            store.peer_authority_high_water("peer-1").unwrap(),
            Some((3, 1, 106)),
            "a new credential generation opens a new term namespace"
        );

        // S022/I47: BOOT generations are monotone; random incarnation
        // IDs are equality fences, never ordered counters. Admission and
        // the open-session journal append are one transaction.
        let first = worker_offer("worker-a", 3, 11);
        assert_eq!(
            store.admit_worker_session(&wrong, &first, 1_100),
            Err(StoreError::NotActiveAuthority)
        );
        assert_eq!(
            store.admit_worker_session(&active, &first, 1_100),
            Ok(WorkerAdmission::AdmitNewGeneration)
        );
        assert_eq!(
            store.admit_worker_session(&active, &first, 1_100),
            Ok(WorkerAdmission::AdmitReconnect),
            "same session admission is idempotent"
        );
        assert_eq!(
            store.admit_worker_session(&active, &first, 1_101),
            Ok(WorkerAdmission::AdmitReconnect),
            "one incarnation may hold multiple reconnect sessions"
        );
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 2, u128::MAX), 1_102,),
            Ok(WorkerAdmission::RejectStaleBootGeneration)
        );
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 3, 22), 1_103),
            Ok(WorkerAdmission::RejectCloneAmbiguity)
        );
        assert!(
            !store
                .release_worker_session(
                    &active,
                    &PeerId("worker-a".into()),
                    WorkerIncarnationId(22),
                    1_100,
                    1_104,
                )
                .unwrap()
        );
        assert!(
            store
                .release_worker_session(
                    &active,
                    &PeerId("worker-a".into()),
                    WorkerIncarnationId(11),
                    1_100,
                    1_104,
                )
                .unwrap()
        );
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 3, 22), 1_105),
            Ok(WorkerAdmission::RejectCloneAmbiguity),
            "releasing one reconnect must not clear another open session's fence"
        );
        assert!(
            store
                .release_worker_session(
                    &active,
                    &PeerId("worker-a".into()),
                    WorkerIncarnationId(11),
                    1_101,
                    1_106,
                )
                .unwrap()
        );
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 3, 22), 1_107),
            Ok(WorkerAdmission::RejectCloneAmbiguity),
            "session release cannot adjudicate a detected clone"
        );
        let mut rolled_back = worker_offer("worker-a", 1, 99);
        rolled_back.reenrollment_proof = Some(1);
        assert_eq!(
            store.admit_worker_session(&active, &rolled_back, 1_108),
            Ok(WorkerAdmission::RejectStaleBootGeneration),
            "operator proof cannot lower the durable global high-water"
        );
        let mut reenrolled = worker_offer("worker-a", 3, 99);
        reenrolled.reenrollment_proof = Some(1);
        assert_eq!(
            store.admit_worker_session(&active, &reenrolled, 1_109),
            Ok(WorkerAdmission::AdmitViaReenrollment)
        );
        let mut replay = worker_offer("worker-a", 3, 100);
        replay.reenrollment_proof = Some(1);
        assert_eq!(
            store.admit_worker_session(&active, &replay, 1_110),
            Ok(WorkerAdmission::RejectCloneAmbiguity),
            "a consumed operator proof cannot pick a second clone"
        );
        assert_eq!(
            store.worker_incarnation_fence(&PeerId("worker-a".into())),
            Ok(Some(WorkerIncarnationFenceRecord {
                worker_peer_id: PeerId("worker-a".into()),
                highest_boot_generation: WorkerBootGeneration(3),
                active_incarnation: Some(WorkerIncarnationId(99)),
                clone_ambiguous: true,
                operator_reenrollment_generation: 1,
            }))
        );
        assert_eq!(
            store.worker_incarnation_fence(&PeerId("worker-b".into())),
            Ok(None)
        );

        let max_generation = worker_offer("worker-max", u64::MAX, u128::MAX);
        assert_eq!(
            store.admit_worker_session(&active, &max_generation, 1_111),
            Ok(WorkerAdmission::AdmitNewGeneration)
        );
        assert_eq!(
            store
                .worker_incarnation_fence(&PeerId("worker-max".into()))
                .unwrap()
                .unwrap()
                .highest_boot_generation,
            WorkerBootGeneration(u64::MAX),
        );

        // H038: edge handoff — at most one active row, predecessor NAMED
        // and matching the fence, fence advances only at resolve.
        store.advance_edge_fence(&active, "edge-1", 10).unwrap();
        assert_eq!(
            store.advance_edge_fence(&active, "edge-1", 9),
            Err(StoreError::StaleEdgeIncarnation)
        );
        assert_eq!(
            store.begin_edge_handoff(&active, "edge-1", 11, 9, 200),
            Err(StoreError::EdgeHandoffPredecessorMismatch)
        );
        assert_eq!(
            store.begin_edge_handoff(&active, "edge-1", 10, 10, 200),
            Err(StoreError::StaleEdgeIncarnation)
        );
        store
            .begin_edge_handoff(&active, "edge-1", 11, 10, 200)
            .unwrap();
        store
            .begin_edge_handoff(&active, "edge-1", 11, 10, 200)
            .unwrap(); // idempotent re-begin
        assert_eq!(
            store.begin_edge_handoff(&active, "edge-1", 12, 10, 201),
            Err(StoreError::EdgeHandoffActive)
        );
        assert_eq!(
            store.active_edge_handoff("edge-1").unwrap(),
            Some(EdgeHandoffRow {
                active_incarnation: 11,
                predecessor_incarnation: 10,
                begun_seq: 200,
            })
        );
        assert_eq!(
            store.edge_fence("edge-1").unwrap(),
            Some(10),
            "fence advances only at resolve"
        );
        assert_eq!(
            store.resolve_edge_handoff(&active, "edge-1", 12),
            Err(StoreError::UnknownEdgeHandoff)
        );
        store.resolve_edge_handoff(&active, "edge-1", 11).unwrap();
        assert_eq!(store.edge_fence("edge-1").unwrap(), Some(11));
        assert_eq!(store.active_edge_handoff("edge-1").unwrap(), None);
        // The NEXT handoff must name the NEW fence as predecessor.
        assert_eq!(
            store.begin_edge_handoff(&active, "edge-1", 12, 10, 202),
            Err(StoreError::EdgeHandoffPredecessorMismatch)
        );
        store
            .begin_edge_handoff(&active, "edge-1", 12, 11, 202)
            .unwrap();

        // H038: trust evaluations are an authority-gated append-only
        // versioned ledger.
        let evaluation = TrustEvaluationRow {
            version: 1,
            state: "trusted".to_owned(),
            reason: "verified once".to_owned(),
            evaluated_seq: 300,
        };
        assert_eq!(
            store.append_trust_evaluation(&wrong, &action.action_key, &evaluation),
            Err(StoreError::NotActiveAuthority)
        );
        store
            .append_trust_evaluation(&active, &action.action_key, &evaluation)
            .unwrap();
        assert_eq!(
            store.append_trust_evaluation(&active, &action.action_key, &evaluation),
            Err(StoreError::NonMonotonicTrustEvaluation)
        );
        let demotion = TrustEvaluationRow {
            version: 2,
            state: "suspect".to_owned(),
            reason: "divergent recompute".to_owned(),
            evaluated_seq: 301,
        };
        store
            .append_trust_evaluation(&active, &action.action_key, &demotion)
            .unwrap();
        assert_eq!(
            store.latest_trust_evaluation(&action.action_key).unwrap(),
            Some(demotion)
        );

        // H038: operations — coordinator-only creation, duplicates
        // refused.
        assert_eq!(
            store.create_operation(&wrong, 400, "transfer", "running", 310),
            Err(StoreError::NotActiveAuthority)
        );
        store
            .create_operation(&active, 400, "transfer", "running", 310)
            .unwrap();
        assert_eq!(
            store.create_operation(&active, 400, "transfer", "running", 311),
            Err(StoreError::DuplicateOperation)
        );
        store.update_operation_state(400, "done", 312).unwrap();
        assert_eq!(
            store.update_operation_state(401, "done", 312),
            Err(StoreError::UnknownOperation)
        );
        assert_eq!(store.operation_state(400).unwrap(), Some("done".to_owned()));

        // H038: edge subscribers — first registration wins.
        store
            .register_edge_subscriber("edge-1", "sub-a", 320)
            .unwrap();
        store
            .register_edge_subscriber("edge-1", "sub-a", 999)
            .unwrap(); // no-op; seq 320 retained
        store
            .register_edge_subscriber("edge-1", "sub-b", 321)
            .unwrap();
        assert_eq!(
            store.list_edge_subscribers("edge-1").unwrap(),
            vec!["sub-a".to_owned(), "sub-b".to_owned()]
        );
        assert!(store.remove_edge_subscriber("edge-1", "sub-b").unwrap());
        assert!(!store.remove_edge_subscriber("edge-1", "sub-b").unwrap());

        // H038: manifest metadata — divergence under one digest refused.
        let manifest = digest("rabs.result-manifest.sha256.v1", 80);
        store.record_manifest(&manifest, "tree", 12).unwrap();
        store.record_manifest(&manifest, "tree", 12).unwrap();
        assert_eq!(
            store.record_manifest(&manifest, "tree", 13),
            Err(StoreError::ManifestDivergence)
        );
        assert_eq!(
            store.manifest_meta(&manifest).unwrap(),
            Some(("tree".to_owned(), 12))
        );

        // H038: worker sessions / capabilities / health samples.
        store.record_worker_session("worker-a", 3, 330).unwrap();
        store.record_worker_session("worker-a", 3, 330).unwrap();
        assert_eq!(
            store.record_worker_session("worker-a", 4, 330),
            Err(StoreError::AppendConflict("worker_sessions".into()))
        );
        assert!(store.end_worker_session("worker-a", 330, 340).unwrap());
        assert!(!store.end_worker_session("worker-a", 330, 341).unwrap());
        store.record_worker_capability("worker-a", "nix").unwrap();
        store.record_worker_capability("worker-a", "nix").unwrap();
        store.record_worker_capability("worker-a", "cargo").unwrap();
        assert_eq!(
            store.list_worker_capabilities("worker-a").unwrap(),
            vec!["cargo".to_owned(), "nix".to_owned()]
        );
        store
            .record_worker_health_sample("worker-a", 350, true, "ok")
            .unwrap();
        store
            .record_worker_health_sample("worker-a", 350, true, "ok")
            .unwrap();
        assert_eq!(
            store.record_worker_health_sample("worker-a", 350, false, "ok"),
            Err(StoreError::AppendConflict("worker_health_samples".into()))
        );

        // H038: decision receipts, provenance edges, determinism audits.
        store
            .record_decision_receipt("gc", "run-1", 360, "reclaim", "under pressure")
            .unwrap();
        store
            .record_decision_receipt("gc", "run-1", 360, "reclaim", "under pressure")
            .unwrap();
        assert_eq!(
            store.record_decision_receipt("gc", "run-1", 360, "skip", "under pressure"),
            Err(StoreError::AppendConflict("decision_receipts".into()))
        );
        store
            .add_provenance_edge(&object, &child, "derived-from")
            .unwrap();
        store
            .add_provenance_edge(&object, &child, "derived-from")
            .unwrap();
        store
            .record_determinism_audit(&action.action_key, 20, 370, "deterministic")
            .unwrap();
        store
            .record_determinism_audit(&action.action_key, 20, 370, "deterministic")
            .unwrap();
        assert_eq!(
            store.record_determinism_audit(&action.action_key, 20, 370, "divergent"),
            Err(StoreError::AppendConflict("determinism_audits".into()))
        );

        // H038: materialization records.
        store
            .create_materialization(500, &object, "/work/out", "staging", 380)
            .unwrap();
        store
            .create_materialization(500, &object, "/work/out", "staging", 380)
            .unwrap();
        assert_eq!(
            store.create_materialization(500, &object, "/work/other", "staging", 381),
            Err(StoreError::AppendConflict("materialization_records".into()))
        );
        store
            .update_materialization_state(500, "complete", 382)
            .unwrap();
        assert_eq!(
            store.update_materialization_state(501, "complete", 382),
            Err(StoreError::UnknownMaterialization)
        );
        assert_eq!(
            store.materialization_state(500).unwrap(),
            Some("complete".to_owned())
        );

        // Authority release + handover.
        store.release_authority(&active).unwrap();
        assert_eq!(store.active_authority().unwrap(), None);
        store.acquire_authority(&authority(2)).unwrap();

        store.differential_snapshot().unwrap()
    }

    #[test]
    fn h009_reference_backend_full_behavioral_pass() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        let snapshot = behavioral_pass(&mut store);
        assert!(!snapshot.is_empty());
    }

    #[test]
    fn h009_frankensqlite_backend_full_behavioral_pass() {
        let engine = FsqliteEngine::open(&fresh_path("fsqlite-pass")).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        let snapshot = behavioral_pass(&mut store);
        assert!(!snapshot.is_empty());
    }

    #[test]
    fn h009_differential_harness_reference_vs_frankensqlite() {
        // THE H009 acceptance: the identical operation script runs on the
        // reference backend and on FrankenSQLite, and every table dumps
        // IDENTICALLY (outcome equality is asserted inside the pass).
        let reference_engine = RusqliteEngine::open(&fresh_path("ref-diff")).unwrap();
        let mut reference = SqlMetadataStore::open(reference_engine).unwrap();
        let candidate_engine = FsqliteEngine::open(&fresh_path("fsq-diff")).unwrap();
        let mut candidate = SqlMetadataStore::open(candidate_engine).unwrap();
        let reference_snapshot = behavioral_pass(&mut reference);
        let candidate_snapshot = behavioral_pass(&mut candidate);
        assert_eq!(reference_snapshot, candidate_snapshot);
    }

    #[test]
    fn h009_generation_high_water_survives_reopen() {
        // Never-reused generation ids must survive a store restart (the
        // high-water outlives active-slot state; plan §62).
        let path = fresh_path("reopen");
        {
            let engine = RusqliteEngine::open(&path).unwrap();
            let mut store = SqlMetadataStore::open(engine).unwrap();
            store.acquire_authority(&authority(1)).unwrap();
            let action = ActionEntryRow {
                action_key: digest("rabs.action-key.sha256.v1", 7),
                key_epoch: 0,
                projection_epoch: 0,
            };
            store.upsert_action_entry(&action).unwrap();
            store
                .create_generation(
                    &digest("rabs.authority.sha256.v1", 1),
                    42,
                    &action.action_key,
                )
                .unwrap();
        }
        let engine = RusqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        // Migrations are idempotent across reopen.
        assert_eq!(store.schema_version().unwrap(), SCHEMA_VERSION);
        store.acquire_authority(&authority(1)).unwrap();
        assert_eq!(
            store.create_generation(
                &digest("rabs.authority.sha256.v1", 1),
                42,
                &digest("rabs.action-key.sha256.v1", 7),
            ),
            Err(StoreError::GenerationIdNotAboveHighWater)
        );
    }

    fn allocation_behavior<E: SqlEngine>(store: &mut SqlMetadataStore<E>) {
        let active = authority(1);
        let action = digest("rabs.action-key.sha256.v1", 7);
        let other = digest("rabs.action-key.sha256.v1", 8);
        store.acquire_authority(&active).unwrap();
        store
            .create_generation(&active.digest, 899, &action)
            .unwrap();
        let old = ActionGeneration {
            generation_id: ActionGenerationId(900),
            per_key_ordinal: 255,
            created_under_authority_digest: active.digest.clone(),
        };
        store
            .create_bound_generation(&active.digest, &old, &action)
            .unwrap();
        store.tombstone_generation(900).unwrap();
        let next = store
            .allocate_bound_generation(&active.digest, &action)
            .unwrap();
        assert_eq!(next.generation_id, ActionGenerationId(901));
        assert_eq!(
            next.per_key_ordinal, 256,
            "BE blob ordering crosses byte boundary"
        );
        assert_eq!(next.created_under_authority_digest, active.digest);
        let independent = store
            .allocate_bound_generation(&active.digest, &other)
            .unwrap();
        assert_eq!(independent.generation_id, ActionGenerationId(902));
        assert_eq!(independent.per_key_ordinal, 1);
        assert_eq!(
            store.allocate_bound_generation(&authority(2).digest, &action),
            Err(StoreError::NotActiveAuthority)
        );
        assert_eq!(store.generation_count().unwrap(), 4);

        // Bad older ordinals must refuse even with a valid larger row present.
        for corrupt in [
            SqlValue::Blob(vec![0; 7]),
            SqlValue::Text("00000000".into()),
        ] {
            store
                .engine
                .execute(
                    "UPDATE action_generations SET per_key_ordinal = ?1 WHERE id_hex = ?2",
                    &[corrupt, SqlValue::Text(u128_hex(900))],
                )
                .unwrap();
            assert!(matches!(
                store.allocate_bound_generation(&active.digest, &action),
                Err(StoreError::Corruption(_))
            ));
            assert_eq!(store.generation_count().unwrap(), 4);
            assert_eq!(
                SqlMetadataStore::<E>::generation_high_water(&mut store.engine).unwrap(),
                902
            );
        }
        store
            .engine
            .execute(
                "UPDATE action_generations SET per_key_ordinal = ?1 WHERE id_hex = ?2",
                &[SqlValue::Blob(u64_blob(255)), SqlValue::Text(u128_hex(900))],
            )
            .unwrap();
        let next = store
            .allocate_bound_generation(&active.digest, &action)
            .unwrap();
        assert_eq!(next.generation_id, ActionGenerationId(903));
        assert_eq!(next.per_key_ordinal, 257, "256 must sort above 255");
        let exhausted = ActionGeneration {
            generation_id: ActionGenerationId(904),
            per_key_ordinal: u64::MAX,
            created_under_authority_digest: active.digest.clone(),
        };
        store
            .create_bound_generation(&active.digest, &exhausted, &action)
            .unwrap();
        assert_eq!(
            store.allocate_bound_generation(&active.digest, &action),
            Err(StoreError::GenerationOrdinalExhausted)
        );
        assert_eq!(store.generation_count().unwrap(), 6);
        assert_eq!(
            SqlMetadataStore::<E>::generation_high_water(&mut store.engine).unwrap(),
            904
        );
        store
            .create_generation(&active.digest, u128::MAX, &other)
            .unwrap();
        assert_eq!(
            store.allocate_bound_generation(&active.digest, &other),
            Err(StoreError::GenerationIdentityExhausted)
        );
        assert_eq!(store.generation_count().unwrap(), 7);
    }

    #[test]
    fn allocated_generations_enforce_fences_and_bounds_on_both_sql_engines() {
        let reference = RusqliteEngine::open_in_memory().unwrap();
        allocation_behavior(&mut SqlMetadataStore::open(reference).unwrap());
        let candidate = FsqliteEngine::open(&fresh_path("allocation-fsq")).unwrap();
        allocation_behavior(&mut SqlMetadataStore::open(candidate).unwrap());
    }

    #[test]
    fn allocated_generation_identity_and_ordinal_survive_reopen_and_new_authority() {
        let path = fresh_path("allocation-reopen");
        let action = digest("rabs.action-key.sha256.v1", 7);
        let old_id = 1_u128 << 100;
        {
            let mut store = SqlMetadataStore::open(RusqliteEngine::open(&path).unwrap()).unwrap();
            let active = authority(1);
            store.acquire_authority(&active).unwrap();
            let old = ActionGeneration {
                generation_id: ActionGenerationId(old_id),
                per_key_ordinal: 17,
                created_under_authority_digest: active.digest.clone(),
            };
            store
                .create_bound_generation(&active.digest, &old, &action)
                .unwrap();
            let next = store
                .allocate_bound_generation(&active.digest, &action)
                .unwrap();
            assert_eq!(next.generation_id, ActionGenerationId(old_id + 1));
            assert_eq!(next.per_key_ordinal, 18);
            store.tombstone_generation(next.generation_id.0).unwrap();
            store.release_authority(&active.digest).unwrap();
        }
        let mut store = SqlMetadataStore::open(RusqliteEngine::open(&path).unwrap()).unwrap();
        let active = authority(2);
        store.acquire_authority(&active).unwrap();
        store
            .close_generations_for_other_authorities(&active.digest)
            .unwrap();
        let next = store
            .allocate_bound_generation(&active.digest, &action)
            .unwrap();
        assert_eq!(next.generation_id, ActionGenerationId(old_id + 2));
        assert_eq!(next.per_key_ordinal, 19);
        assert_eq!(next.created_under_authority_digest, active.digest);
        assert_eq!(store.generation_count().unwrap(), 3);
    }

    #[test]
    fn h009_domain_restore_is_fail_closed() {
        // A domain never written by this process cannot be silently
        // re-typed on read (R121): a fresh store instance over the same
        // file refuses to restore rows whose domains it has not interned.
        let path = fresh_path("domains");
        {
            let engine = RusqliteEngine::open(&path).unwrap();
            let mut store = SqlMetadataStore::open(engine).unwrap();
            store.acquire_authority(&authority(1)).unwrap();
        }
        let engine = RusqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        assert_eq!(
            store.active_authority(),
            Err(StoreError::DomainNotInterned(
                "rabs.authority.sha256.v1".to_owned()
            ))
        );
    }

    fn h038_fence_seed(store: &mut dyn RabsMetadataStore) {
        store.acquire_authority(&authority(1)).unwrap();
        let active = digest("rabs.authority.sha256.v1", 1);
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 7, 70), 700),
            Ok(WorkerAdmission::AdmitNewGeneration)
        );
        store.advance_edge_fence(&active, "edge-1", 9).unwrap();
        store
            .record_peer_authority_high_water(&active, "peer-1", 2, 5, 11, 100)
            .unwrap();
    }
    fn h038_fence_check_after_reopen(store: &mut dyn RabsMetadataStore) {
        // Fence rows written by the seed survive the reopen: values set
        // before the reopen stay refused after it.
        store.acquire_authority(&authority(1)).unwrap();
        let active = digest("rabs.authority.sha256.v1", 1);
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 2, 5, 12, 101),
            Err(StoreError::StalePeerAuthority),
            "reopening must not let a clone reuse an accepted term"
        );
        store
            .record_peer_authority_high_water(&active, "peer-1", 2, 5, 11, 102)
            .unwrap();
        assert_eq!(
            store.peer_authority_high_water("peer-1").unwrap(),
            Some((2, 5, 100))
        );
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 1, 999, 11, 103),
            Err(StoreError::StalePeerAuthority),
            "credential rollback remains fenced after reopening"
        );
        store
            .record_peer_authority_high_water(&active, "peer-1", 3, 1, 12, 104)
            .unwrap();
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 2, 999, 11, 105),
            Err(StoreError::StalePeerAuthority)
        );
        assert_eq!(
            store.peer_authority_high_water("peer-1").unwrap(),
            Some((3, 1, 104))
        );
        assert_eq!(
            store
                .worker_incarnation_fence(&PeerId("worker-a".into()))
                .unwrap()
                .unwrap()
                .highest_boot_generation,
            WorkerBootGeneration(7)
        );
        assert_eq!(store.edge_fence("edge-1").unwrap(), Some(9));
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 6, 60), 701),
            Ok(WorkerAdmission::RejectStaleBootGeneration)
        );
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 7, 71), 702),
            Ok(WorkerAdmission::RejectCloneAmbiguity)
        );
        assert_eq!(
            store.advance_edge_fence(&active, "edge-1", 8),
            Err(StoreError::StaleEdgeIncarnation)
        );
        assert_eq!(
            store.admit_worker_session(&active, &worker_offer("worker-a", 8, 80), 703),
            Ok(WorkerAdmission::RejectCloneAmbiguity),
            "a self-reported boot increment cannot select the legitimate clone"
        );
        let mut resolved = worker_offer("worker-a", 8, 80);
        resolved.reenrollment_proof = Some(1);
        assert_eq!(
            store.admit_worker_session(&active, &resolved, 704),
            Ok(WorkerAdmission::AdmitViaReenrollment)
        );
    }

    fn seed_v19_worker_fence<E: SqlEngine>(engine: &mut E) {
        for migration in MIGRATIONS
            .iter()
            .filter(|migration| migration.version <= 19)
        {
            engine.execute("BEGIN", &[]).unwrap();
            for statement in migration.statements {
                engine.execute(statement, &[]).unwrap();
            }
            engine
                .execute(
                    "INSERT INTO schema_epochs (version, applied_seq) VALUES (?1, 0)",
                    &[SqlValue::Int(i64::from(migration.version))],
                )
                .unwrap();
            engine.execute("COMMIT", &[]).unwrap();
        }
        engine
            .execute(
                "INSERT INTO worker_incarnation_fences (worker, incarnation) VALUES (?1, ?2)",
                &[
                    SqlValue::Text("legacy-worker".to_owned()),
                    SqlValue::Blob(u128_blob(0xCAFE)),
                ],
            )
            .unwrap();
    }

    fn assert_v19_worker_fence_migrated(store: &mut dyn RabsMetadataStore) {
        assert_eq!(store.schema_version(), Ok(SCHEMA_VERSION));
        assert_eq!(
            store.worker_incarnation_fence(&PeerId("legacy-worker".to_owned())),
            Ok(Some(WorkerIncarnationFenceRecord {
                worker_peer_id: PeerId("legacy-worker".to_owned()),
                highest_boot_generation: WorkerBootGeneration(0),
                active_incarnation: Some(WorkerIncarnationId(0xCAFE)),
                clone_ambiguous: true,
                operator_reenrollment_generation: 0,
            })),
            "a pre-S022 row migrates as an ambiguous active generation-zero fence"
        );
    }

    fn seed_v20_attempt_lease<E: SqlEngine>(engine: &mut E) {
        for migration in MIGRATIONS
            .iter()
            .filter(|migration| migration.version <= 20)
        {
            engine.execute("BEGIN", &[]).unwrap();
            for statement in migration.statements {
                engine.execute(statement, &[]).unwrap();
            }
            engine
                .execute(
                    "INSERT INTO schema_epochs (version, applied_seq) VALUES (?1, 0)",
                    &[SqlValue::Int(i64::from(migration.version))],
                )
                .unwrap();
            engine.execute("COMMIT", &[]).unwrap();
        }

        let authority = bound_authority_row().digest;
        let action = digest("rabs.action-key.sha256.v1", 7);
        engine
            .execute(
                "INSERT INTO action_generations \
                 (id_hex, id, action_key, authority_key, tombstoned) \
                 VALUES (?1, ?2, ?3, ?4, 0)",
                &[
                    SqlValue::Text(u128_hex(11)),
                    SqlValue::Blob(u128_blob(11)),
                    SqlValue::Text(digest_key(&action)),
                    SqlValue::Text(digest_key(&authority)),
                ],
            )
            .unwrap();
        engine
            .execute(
                "INSERT INTO generation_high_water (kind, value) \
                 VALUES ('action-generation', ?1)",
                &[SqlValue::Blob(u128_blob(11))],
            )
            .unwrap();
        engine
            .execute(
                "INSERT INTO action_attempts (id_hex, id, generation_hex, worker, seq) \
                 VALUES (?1, ?2, ?3, 'lease-worker', 5)",
                &[
                    SqlValue::Text(u128_hex(22)),
                    SqlValue::Blob(u128_blob(22)),
                    SqlValue::Text(u128_hex(11)),
                ],
            )
            .unwrap();
        engine
            .execute(
                "INSERT INTO execution_leases \
                 (id_hex, id, attempt_hex, renewal_seq, expires_at_seq, released) \
                 VALUES (?1, ?2, ?3, 1, 100, 0)",
                &[
                    SqlValue::Text(u128_hex(30)),
                    SqlValue::Blob(u128_blob(30)),
                    SqlValue::Text(u128_hex(22)),
                ],
            )
            .unwrap();
        engine
            .execute(
                "INSERT INTO worker_incarnation_fences \
                 (worker, incarnation, highest_boot_generation, active, \
                  operator_reenrollment_generation) \
                 VALUES ('lease-worker', ?1, ?2, 1, ?3)",
                &[
                    SqlValue::Blob(u128_blob(99)),
                    SqlValue::Blob(u64_blob(3)),
                    SqlValue::Blob(u64_blob(0)),
                ],
            )
            .unwrap();
    }

    fn assert_v20_attempt_lease_fails_closed(store: &mut dyn RabsMetadataStore) {
        assert_eq!(store.schema_version(), Ok(SCHEMA_VERSION));
        store.acquire_authority(&bound_authority_row()).unwrap();
        assert_eq!(
            store.worker_incarnation_fence(&PeerId("lease-worker".to_owned())),
            Ok(Some(WorkerIncarnationFenceRecord {
                worker_peer_id: PeerId("lease-worker".to_owned()),
                highest_boot_generation: WorkerBootGeneration(3),
                active_incarnation: Some(WorkerIncarnationId(99)),
                clone_ambiguous: true,
                operator_reenrollment_generation: 0,
            }))
        );
        let legacy = bound_attempt_authority();
        assert_eq!(
            store.validate_attempt_lease(&legacy, 10),
            Err(StoreError::LegacyUnboundAuthority)
        );
        assert_eq!(
            store.renew_attempt_lease(
                &legacy,
                LeaseRenewal {
                    lease: legacy.execution_lease_id,
                    seq: LeaseRenewalSeq(2),
                },
                200,
                &|| 10,
            ),
            Err(StoreError::LegacyUnboundAuthority)
        );
        let mut legacy_row = publication(7, 1, 40);
        legacy_row.winner_generation = 11;
        legacy_row.winner_attempt = 22;
        assert_eq!(
            store.commit_publication(
                &bound_authority_row().digest,
                Some((&legacy, &|| 10)),
                &legacy_row,
            ),
            Err(StoreError::LegacyUnboundAuthority)
        );
        assert!(!store.has_publication(&legacy.action_key).unwrap());

        let mut selected = worker_offer("lease-worker", 3, 100);
        selected.reenrollment_proof = Some(1);
        assert_eq!(
            store.admit_worker_session(&bound_authority_row().digest, &selected, 200),
            Ok(WorkerAdmission::AdmitViaReenrollment)
        );
        let mut replacement = legacy;
        replacement.action_generation.generation_id = ActionGenerationId(12);
        replacement.action_generation.per_key_ordinal = 2;
        replacement.attempt_id = AttemptId(23);
        replacement.execution_lease_id = ExecutionLeaseId(31);
        replacement.worker_incarnation_id = WorkerIncarnationId(100);
        store
            .upsert_action_entry(&ActionEntryRow {
                action_key: replacement.action_key.clone(),
                key_epoch: 1,
                projection_epoch: 1,
            })
            .unwrap();
        store
            .create_bound_generation(
                &bound_authority_row().digest,
                &replacement.action_generation,
                &replacement.action_key,
            )
            .unwrap();
        store.admit_attempt_lease(&replacement, 201, 300).unwrap();
        assert_eq!(
            store.validate_attempt_lease(&replacement, 10),
            Ok(LeaseState {
                released: false,
                renewal_seq: 1,
                expires_at_own_monotonic_ms: 300,
            })
        );
    }

    #[test]
    fn s022_migrates_populated_v19_worker_fence_reference() {
        let path = fresh_path("s022-v19-ref");
        {
            let mut engine = RusqliteEngine::open(&path).unwrap();
            seed_v19_worker_fence(&mut engine);
        }
        let engine = RusqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        assert_v19_worker_fence_migrated(&mut store);
    }

    #[test]
    fn s022_migrates_populated_v19_worker_fence_frankensqlite() {
        let path = fresh_path("s022-v19-fsq");
        {
            let mut engine = FsqliteEngine::open(&path).unwrap();
            seed_v19_worker_fence(&mut engine);
        }
        let engine = FsqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        assert_v19_worker_fence_migrated(&mut store);
    }

    #[test]
    fn t038_migrates_populated_v20_attempt_lease_fail_closed_reference() {
        let path = fresh_path("t038-v20-ref");
        {
            let mut engine = RusqliteEngine::open(&path).unwrap();
            seed_v20_attempt_lease(&mut engine);
        }
        let engine = RusqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        assert_v20_attempt_lease_fails_closed(&mut store);
    }

    #[test]
    fn t038_migrates_populated_v20_attempt_lease_fail_closed_frankensqlite() {
        let path = fresh_path("t038-v20-fsq");
        {
            let mut engine = FsqliteEngine::open(&path).unwrap();
            seed_v20_attempt_lease(&mut engine);
        }
        let engine = FsqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        assert_v20_attempt_lease_fails_closed(&mut store);
    }

    #[test]
    fn s022_and_h038_fences_survive_reopen_reference() {
        let path = fresh_path("h038-fence-ref");
        {
            let engine = RusqliteEngine::open(&path).unwrap();
            let mut store = SqlMetadataStore::open(engine).unwrap();
            h038_fence_seed(&mut store);
        }
        let engine = RusqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        h038_fence_check_after_reopen(&mut store);
    }

    #[test]
    fn s022_and_h038_fences_survive_reopen_frankensqlite() {
        let path = fresh_path("h038-fence-fsq");
        {
            let engine = FsqliteEngine::open(&path).unwrap();
            let mut store = SqlMetadataStore::open(engine).unwrap();
            h038_fence_seed(&mut store);
        }
        let engine = FsqliteEngine::open(&path).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        h038_fence_check_after_reopen(&mut store);
    }

    fn s020_operator_reset_consumption<E: SqlEngine>(
        open: fn(&std::path::Path) -> Result<E, StoreError>,
        tag: &str,
    ) {
        let path = fresh_path(tag);
        let mut store = SqlMetadataStore::open(open(&path).unwrap()).unwrap();
        store.acquire_authority(&authority(1)).unwrap();
        let active = digest("rabs.authority.sha256.v1", 1);
        store
            .record_peer_authority_high_water(&active, "peer-1", 2, 5, 11, 100)
            .unwrap();
        // A signature-verified reset (caller-verified; this API consumes
        // it) fencing the old authority must lift the incarnation and
        // generation fences in one atomic step.
        store
            .apply_operator_reset_to_peer(&active, "peer-1", 1, 2, 5, 99)
            .unwrap();
        assert_eq!(
            store.peer_authority_high_water("peer-1").unwrap(),
            Some((2, 5, 1))
        );
        store
            .record_peer_authority_high_water(&active, "peer-1", 2, 5, 99, 201)
            .unwrap();
        assert_eq!(
            store.record_peer_authority_high_water(&active, "peer-1", 2, 5, 11, 202),
            Err(StoreError::StalePeerAuthority),
            "the fenced pre-reset incarnation must stay refused"
        );
        // Replayed reset generations are refused by ledger monotonicity.
        assert_eq!(
            store.apply_operator_reset_to_peer(&active, "peer-1", 1, 2, 6, 99),
            Err(StoreError::StaleOperatorReset)
        );
        store
            .apply_operator_reset_to_peer(&active, "peer-1", 2, 3, 7, 100)
            .unwrap();
        assert_eq!(store.highest_operator_reset().unwrap(), Some(2));
        assert_eq!(
            store.peer_authority_high_water("peer-1").unwrap(),
            Some((3, 7, 2))
        );
    }
    #[test]
    fn s020_operator_reset_reopens_fenced_peer_reference() {
        s020_operator_reset_consumption(RusqliteEngine::open, "s020-reset-ref");
    }

    #[test]
    fn s020_operator_reset_reopens_fenced_peer_frankensqlite() {
        s020_operator_reset_consumption(FsqliteEngine::open, "s020-reset-fsq");
    }

    fn table_names<E: SqlEngine>(store: &mut SqlMetadataStore<E>) -> Vec<String> {
        store
            .engine_mut()
            .query(
                "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",
                &[],
            )
            .unwrap()
            .into_iter()
            .map(|row| match row.into_iter().next() {
                Some(SqlValue::Text(t)) => t,
                other => panic!("table name shape: {other:?}"),
            })
            .collect()
    }

    #[test]
    fn h038_full_authoritative_table_set_no_failure_table() {
        // The COMPLETE Epic-H table surface, pinned exactly: a table
        // appearing or disappearing without this list changing is a
        // schema regression. Deterministic failures are ResultKind
        // publications — the absence of any failure table is asserted
        // below, not just assumed.
        let expected: Vec<String> = [
            "action_attempts",
            "action_entries",
            "action_evidence_index",
            "action_generations",
            "action_publications",
            "action_serving_states",
            "action_trust_evaluations",
            "adoption_edges",
            "coordinator_authorities",
            "decision_receipts",
            "determinism_audits",
            "divergence_incidents",
            "edge_handoffs",
            "edge_incarnation_fences",
            "edge_subscribers",
            "eviction_tombstones",
            "execution_leases",
            "gc_receipts",
            "gc_runs",
            "gc_tombstones",
            "generation_high_water",
            "key_breakdowns",
            "manifests",
            "materialization_records",
            "native_child_bindings",
            "object_edges",
            "object_locations",
            "objects",
            "observed_input_recipes",
            "operations",
            "operator_resets",
            "peer_authority_high_water",
            "pins",
            "provenance_edges",
            "provisional_ancestry",
            "provisional_install_journal",
            "provisional_obligations",
            "provisional_pin_grants",
            "provisional_pin_lineage",
            "provisional_pins",
            "quarantines",
            "release_verdicts",
            "schema_epochs",
            "serving_blocking_quarantines",
            "trust_states",
            "verification_samples",
            "worker_capabilities",
            "worker_health_samples",
            "worker_incarnation_fences",
            "worker_sessions",
        ]
        .iter()
        .map(|s| (*s).to_owned())
        .collect();
        assert!(
            expected.iter().all(|name| !name.contains("failure")),
            "deterministic failures are ResultKind publications; no failure table may exist"
        );
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        assert_eq!(table_names(&mut store), expected);
        let engine = FsqliteEngine::open(&fresh_path("h038-tables")).unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        assert_eq!(table_names(&mut store), expected);
    }

    #[test]
    fn t011_a_release_verdict_round_trips_and_a_rerun_supersedes_it() {
        use rabs_protocol::release_authorization::{
            ReleaseAuthorization, ReleaseAuthorizationMode, authorization,
        };

        let mut verdict = ReleaseVerdict {
            build: "rabs-build-1".to_owned(),
            corpus: "corpus-abc".to_owned(),
            replayed: 1_200,
            explained: 3,
            validity: ServingValidity {
                evaluated_at_unix_micros: 5_000,
                maximum_age_micros: Some(100_000),
                clock_uncertainty_micros: 25,
                coordinator_clock_epoch: 4,
            },
        };

        let stores: [Box<dyn RabsMetadataStore>; 2] = [
            Box::new(SqlMetadataStore::open(RusqliteEngine::open_in_memory().unwrap()).unwrap()),
            // Both engines, because the A002 differential lanes must
            // agree on this table exactly as they do on every other.
            Box::new(
                SqlMetadataStore::open(
                    FsqliteEngine::open(&fresh_path("t011-release-verdicts")).unwrap(),
                )
                .unwrap(),
            ),
        ];
        for mut store in stores {
            // An unrecorded build reads back as nothing at all, which is
            // the `Absent` standing rather than a silently empty pass.
            assert_eq!(store.release_verdict("rabs-build-1").unwrap(), None);

            store.record_release_verdict(&verdict).unwrap();
            assert_eq!(
                store.release_verdict("rabs-build-1").unwrap().as_ref(),
                Some(&verdict),
                "every field must survive the round trip, including the validity window"
            );

            // A verdict is keyed by BUILD: recording one says nothing
            // about any other build, which is what stops a proof from
            // outliving the binary it examined.
            assert_eq!(store.release_verdict("rabs-build-2").unwrap(), None);

            // A fresh corpus run over the same build SUPERSEDES rather
            // than accumulating: two live verdicts for one build would
            // need a precedence rule, and the only correct answer is
            // "the newest", which is what replacement already is.
            let mut rerun = verdict.clone();
            rerun.corpus = "corpus-def".to_owned();
            rerun.replayed = 1_500;
            rerun.validity.evaluated_at_unix_micros = 9_000;
            store.record_release_verdict(&rerun).unwrap();
            assert_eq!(
                store.release_verdict("rabs-build-1").unwrap(),
                Some(rerun.clone()),
                "the rerun must replace the earlier verdict, not sit beside it"
            );

            // And the durable row drives the real decision: live here,
            // expired once the window elapses, under either mode.
            let stored = store.release_verdict("rabs-build-1").unwrap();
            assert_eq!(
                authorization(stored.as_ref(), "rabs-build-1", 9_500, 4),
                ReleaseAuthorization::Authorized { replayed: 1_500 }
            );
            let expired = authorization(stored.as_ref(), "rabs-build-1", 500_000, 4);
            assert_eq!(expired, ReleaseAuthorization::Expired);
            assert!(!expired.permits_serving(ReleaseAuthorizationMode::Required));
        }

        // A verdict with no expiry stores its NULL max-age as absence of
        // a bound, not as a zero-length window that expires instantly.
        verdict.validity.maximum_age_micros = None;
        let mut store = SqlMetadataStore::open(RusqliteEngine::open_in_memory().unwrap()).unwrap();
        store.record_release_verdict(&verdict).unwrap();
        let stored = store.release_verdict("rabs-build-1").unwrap();
        assert_eq!(
            stored.as_ref().unwrap().validity.maximum_age_micros,
            None,
            "NULL max-age must read back as no bound"
        );
        assert_eq!(
            authorization(stored.as_ref(), "rabs-build-1", i64::MAX, 4),
            ReleaseAuthorization::Authorized { replayed: 1_200 }
        );
    }

    #[test]
    fn h038_deterministic_failure_publishes_as_result_kind() {
        // One publication path for success AND deterministic failure
        // (I16): the failure lands in action_publications carrying its
        // result kind — there is no separate failure table to receive
        // it (asserted structurally in the table-set test above).
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        store.acquire_authority(&authority(1)).unwrap();
        let active = digest("rabs.authority.sha256.v1", 1);
        let mut row = publication(9, 3, 90);
        row.result_kind = ResultKindTag::DeterministicFailure;
        assert_eq!(
            store.commit_publication(&active, None, &row).unwrap(),
            CommitOutcome::Committed
        );
        let dump = store.differential_snapshot().unwrap();
        assert!(
            dump.iter().any(|line| {
                line.starts_with("action_publications|") && line.contains("|deterministic-failure|")
            }),
            "failure publication must appear in action_publications with its result kind"
        );
    }
}