djogi 0.1.0-alpha.2

Model-first web framework for Rust — web-framework-agnostic core; Axum integration opt-in via the `axum` feature flag
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
//! Migration runner — applies a [`MigrationPlan`] against a target
//! database, recording each step in the `djogi_schema_migrations`
//! ledger and persisting the snapshot only on full success.
//!
//! # Lifecycle (Phase 7 v3 §6 / §8)
//!
//! ```text
//! 1. Acquire workspace file lock (T4 guard primitive).
//! 2. Bootstrap djogi_schema_migrations table.
//! 3. Acquire pg_advisory_lock on a 64-bit key derived from BucketKey.
//! 4. Verify the supplied checksum matches a freshly-computed one.
//! 5. Insert the pending ledger row OUTSIDE the apply transaction.
//! 6. For each segment, dispatch by SegmentKind:
//!      - Transactional   → BEGIN; statements; COMMIT.
//!      - NonTransactional → autocommit each statement; update progress.
//!      - MetadataOnly    → no SQL runs; metadata path is T6's job.
//! 7. On success: mark_applied + persist snapshot.
//! 8. On failure: mark_failed (or mark_partial for split-apply)
//!    and propagate. Snapshot is NOT moved forward.
//! 9. Always: release pg_advisory_lock and workspace file lock.
//! ```
//!
//! # Snapshot persistence invariant
//!
//! The snapshot file at `migrations/<target>/<app>/schema_snapshot.json`
//! is written ONLY after the ledger row reaches `applied`. Any failure
//! — transactional rollback, non-transactional crash, ledger update
//! error — leaves the snapshot at its prior value. This is the hard
//! invariant T4 owes T5 (`repair`) and T7 (`status`): if the snapshot
//! moved, every preceding migration succeeded.
//!
//! # Determinism
//!
//! Two runs against the same plan + same DB state must produce the
//! same ledger writes (modulo `applied_at`, `applied_by`,
//! `execution_time_ms`, and `run_id`). Hashing of `BucketKey` to the
//! advisory-lock key uses SHA-256 truncated to the low 64 bits — a
//! stable hash that does not depend on Rust's randomised default
//! `Hasher`.
//!
//! # Relpages probe (Phase 7-Zero v3 §6.5)
//!
//! Before every transactional `CREATE INDEX` whose `IndexSchema`
//! does NOT carry `requires_out_of_transaction == true`, the runner
//! queries `pg_class.relpages` for the target table. When relpages
//! exceeds [`MigrateConfig::concurrent_warn_relpages`] (default 128
//! pages ≈ 1 MB), the runner emits `tracing::warn!` advising the
//! operator to opt the index into `CREATE INDEX CONCURRENTLY`. With
//! [`MigrateConfig::strict_concurrent_warnings`] the warn upgrades
//! to a hard `RunnerError::RelpagesThresholdExceeded`.

use std::collections::BTreeSet;
use std::path::PathBuf;
use std::time::Instant;

use sha2::{Digest, Sha256};
use time::OffsetDateTime;

use crate::__bypass::guarded_batch_execute;
use crate::config::MigrateConfig;
use crate::context::{DjogiContext, PinnedCtx};
use crate::error::{DbError, DjogiError};
use crate::types::HeerId;

use super::guard::WorkspaceGuard;
use super::ledger::{
    self, ChecksumFormatError, ChecksumMismatch, ExecutionMode, LedgerRow, LedgerStatus,
    VerifyError, compute_checksum, load_full_row_by_version,
};
use super::projection::BucketKey;
use super::schema::SNAPSHOT_FORMAT_VERSION;
use super::segment::{MigrationPlan, Segment, SegmentKind};
use super::snapshot::{SnapshotError, save_snapshot};
use super::sql::{LossyRollbackKind, OperationSql};

// ── Public types ──────────────────────────────────────────────────────────

/// Why a migration statement is incompatible with the runner's
/// segment execution model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SegmentSqlExecutionModeProblem {
    /// Top-level transaction control is forbidden in migration
    /// statements because the runner owns every BEGIN/COMMIT boundary.
    TransactionControl {
        /// Canonical leading keyword or keyword pair, e.g. `BEGIN`,
        /// `START TRANSACTION`, `RELEASE SAVEPOINT`.
        keyword: &'static str,
    },
    /// The statement must run outside any transaction, but the plan
    /// placed it in a transactional segment.
    RequiresNonTransactional {
        /// Canonical SQL shape that triggered the classification.
        statement_shape: &'static str,
    },
}

/// Errors surfaced by the runner. Each variant carries enough context
/// for an actionable operator message — no panicking, no silent
/// drops.
#[derive(Debug)]
#[non_exhaustive]
pub enum RunnerError {
    /// Workspace file lock could not be acquired within the timeout.
    LockTimeout {
        path: PathBuf,
        holder_pid: Option<i32>,
    },

    /// File-level workspace lock errored for any reason other than
    /// timeout (I/O, kernel error, Windows-not-supported).
    GuardError(super::guard::GuardError),

    /// Postgres advisory lock could not be acquired within the
    /// retry budget. Distinct from `LockTimeout` (file-lock) so the
    /// operator can disambiguate the two layers.
    AdvisoryLockFailed {
        bucket: BucketKey,
        key: i64,
        attempts: u32,
    },

    /// The `pg_try_advisory_lock` probe itself failed (the query
    /// errored, or its boolean result could not be extracted).
    /// Distinct from [`RunnerError::AdvisoryLockFailed`] (which
    /// fires after the probe succeeded but returned `false` for
    /// every retry) and from [`RunnerError::LedgerWriteFailed`]
    /// (which is reserved for actual ledger writes — see
    /// cluster-2 Finding 6).
    AdvisoryLockQueryFailed {
        /// `app_label` of the bucket whose lock was being acquired.
        app_label: String,
        /// The underlying Postgres error.
        source: DjogiError,
    },

    /// Stored checksum does not match a freshly-computed one. The
    /// runner refuses to apply when a migration's SQL has been
    /// edited after it was committed.
    ChecksumMismatch(ChecksumMismatch),

    /// One of the two checksum strings handed to the runner failed
    /// [`super::ledger::validate_checksum_format`]. The wrapped error
    /// identifies which side (expected vs. actual) was malformed and
    /// the rule violated.
    ChecksumFormat(ChecksumFormatError),

    /// A ledger row CRUD operation failed (INSERT, UPDATE).
    LedgerWriteFailed { version: String, source: DjogiError },

    /// A read-only ledger query failed (SELECT against
    /// `djogi_schema_migrations` — out-of-order conflict probe,
    /// rollback row-fetch, etc.). Distinct from
    /// [`RunnerError::LedgerWriteFailed`]
    /// — no row was written; the failure is in a reading probe and
    /// surfaces with a `query_label` so operators can correlate the
    /// error to the specific ledger probe (sibling of
    /// [`RunnerError::CatalogQueryFailed`] for the ledger surface).
    LedgerQueryFailed {
        /// A static label naming the ledger probe that failed (e.g.
        /// `"out_of_order_check"`, `"load_row_for_version"`).
        query_label: &'static str,
        /// The underlying Postgres error.
        source: DjogiError,
    },

    /// `SELECT heerid_next()` failed during runner startup, before
    /// the migration could touch the ledger. The run_id is a
    /// per-invocation HeerId stamped into every ledger row written
    /// by this run; failure here means we cannot tag rows for crash
    /// recovery and must abort the run before it begins.
    RunIdGenerationFailed { source: DjogiError },

    /// `ledger::bootstrap` failed — the ledger table's
    /// `CREATE TABLE IF NOT EXISTS` DDL could not run. Distinct from
    /// [`RunnerError::LedgerWriteFailed`] (row CRUD: INSERT/UPDATE)
    /// — bootstrap is DDL, not row-level work, and almost always
    /// signals a permissions or connection problem rather than a
    /// data conflict.
    LedgerBootstrapFailed { source: DjogiError },

    /// Insertion of the pending ledger row collided with an existing
    /// row carrying the same `version`. Surfaces a typed error rather
    /// than a raw `LedgerWriteFailed { source: 23505 }` so operators
    /// re-running an already-applied migration get an actionable
    /// message that names the prior `applied_at` timestamp.
    VersionAlreadyApplied {
        version: String,
        applied_at: Option<OffsetDateTime>,
    },

    /// Insertion of the pending ledger row collided on `version`, but
    /// the existing row is in a non-terminal lifecycle status. Surface
    /// the row's status and run_id so operators can inspect and repair
    /// the blocking run instead of being told the migration is already
    /// applied.
    VersionCollisionNonTerminal {
        version: String,
        status: LedgerStatus,
        run_id: i64,
    },

    /// The relpages probe queried `pg_class` for a target table that
    /// did NOT match any AddTable in the current plan and the table
    /// was not present in the database. This catches typos / mis-
    /// quoted identifiers — silently dropping to `relpages = 0` would
    /// disable the strict-mode warning path for any mis-targeted
    /// `CREATE INDEX`.
    TargetTableNotFound {
        bucket: BucketKey,
        index_name: String,
        target_table: String,
    },

    /// A `CREATE INDEX` was about to run against a table whose
    /// `pg_class.relpages` exceeded the operator-configured
    /// threshold, AND `migrate.strict_concurrent_warnings` is true.
    /// Surface fields match the warn-path emit so logs and errors
    /// share identifiers.
    RelpagesThresholdExceeded {
        bucket: BucketKey,
        index_name: String,
        target_table: String,
        relpages: i32,
        threshold: u32,
    },

    /// A statement's SQL shape conflicts with the runner-managed
    /// execution mode for its segment. This is a preflight refusal:
    /// no ledger row is inserted and no SQL runs.
    SegmentSqlExecutionModeConflict {
        segment_index: usize,
        segment_kind: SegmentKind,
        statement_label: String,
        problem: SegmentSqlExecutionModeProblem,
    },

    /// A statement inside a transactional segment failed; the
    /// transaction was rolled back. Carries the failing statement
    /// label and the underlying error.
    TransactionalSegmentFailed {
        segment_index: usize,
        statement_label: String,
        source: DjogiError,
    },

    /// A statement inside a non-transactional segment failed. The
    /// runner records `applied_steps_count` so a `repair` invocation
    /// can resume from the next step.
    NonTransactionalSegmentFailed {
        segment_index: usize,
        step_index: usize,
        statement_label: String,
        applied_steps_count: i32,
        source: DjogiError,
    },

    /// A non-transactional statement committed successfully, but the
    /// runner failed to durably acknowledge the step boundary on the
    /// ledger. The row is left with a structured claim note so repair
    /// resume refuses to replay the ambiguous step automatically.
    NonTransactionalProgressAckFailed {
        segment_index: usize,
        step_index: usize,
        statement_label: String,
        applied_steps_count: i32,
        source: DjogiError,
    },

    /// Failed to load `Djogi.toml` for the relpages-probe config.
    ConfigLoadFailed { source: figment::Error },

    /// Snapshot file write failed AFTER the ledger row was marked
    /// applied. The runner surfaces this as a separate variant
    /// because the operator's recovery path is "manually invoke
    /// `compose` to regenerate the snapshot" — different from a
    /// rollback path.
    SnapshotPersistFailed {
        path: PathBuf,
        source: SnapshotError,
    },

    /// `baseline_plan` was called with `runner_ctx.snapshot.is_some()`.
    /// Baseline derives the canonical snapshot from a fresh live-DB
    /// projection (B-11) so the operator-supplied channel is rejected
    /// up-front to prevent stale-snapshot baselines from poisoning
    /// future diffs.
    BaselineSnapshotShouldNotBeProvided,

    /// The candidate version applies out-of-order (it sorts before
    /// some already-applied row in the same `(database, app)` bucket)
    /// AND the runner's [`super::policy::OutOfOrderPolicy`] is
    /// `Reject`. Surfaces the conflicting peer so the operator can
    /// decide between rebasing the migration to a later timestamp,
    /// supplying an explicit override, or reordering the apply.
    ///
    /// Note: this error fires BEFORE the pending ledger row is
    /// inserted, so a `Reject` outcome leaves no trace in the
    /// database. The operator-facing message is the only artifact.
    OutOfOrderRejected {
        /// The candidate version that triggered the conflict.
        version: String,
        /// The already-applied peer whose `version` is lexically
        /// greater than `version`.
        conflicting_version: String,
        /// `applied_at` of the conflicting peer, when available. The
        /// formatted RFC 3339 string is used so the message is
        /// timezone-explicit.
        conflicting_applied_at: Option<String>,
    },

    /// The live-DB projection underpinning `baseline_plan` failed
    /// before the ledger row could be inserted. Distinct from
    /// `LedgerWriteFailed` so the operator-facing message names the
    /// projection step (not the ledger) as the failing phase.
    BaselineProjectionFailed {
        source: Box<super::verify::VerifyRunError>,
    },

    /// **D060** — T9 PK-flip pre-flight: logical-replication apply
    /// machinery is active in this database. Walsenders surfaced via
    /// `pg_stat_replication` and/or local subscriptions surfaced via
    /// `pg_subscription` (`subenabled = true`) signal that a separate
    /// session may be applying replicated changes with
    /// `session_replication_role = 'replica'` — that mode suppresses
    /// the BEFORE row triggers the cutover relies on. Postgres does
    /// not let one backend introspect another backend's GUC settings
    /// from `pg_stat_activity`, so we surface the broader replication
    /// signal as the hazard. Operator action: pause the apply
    /// worker(s) (or `ALTER TABLE ... ENABLE ALWAYS TRIGGER zzz_*`)
    /// before retrying.
    PkFlipHazardReplicaSessions {
        /// Active walsenders observed via `pg_stat_replication`.
        /// `(application_name, client_addr_text)` pairs.
        walsenders: Vec<(String, String)>,
        /// Enabled local subscriptions observed via `pg_subscription`
        /// (subscribers run an apply worker in `replica` role). Each
        /// entry is the subscription name.
        subscriptions: Vec<String>,
    },

    /// **D061** — T9 PK-flip pre-flight: a `zzz_*` trigger already
    /// exists on the migrating table (or one of its children).
    /// Collisions with the autofill trigger naming convention abort
    /// the install; the operator must rename or drop the existing
    /// trigger before retrying.
    PkFlipHazardPreexistingZzzTrigger {
        /// Postgres table carrying the offending trigger.
        table: String,
        /// Trigger names found.
        trigger_names: Vec<String>,
    },

    /// **D062** — T9 PK-flip pre-flight: at least one trigger on the
    /// migrating table (or a child) is already disabled (`tgenabled
    /// <> 'O'`). A disabled trigger leaves writes during the window
    /// without their `_desc` shadow populated; the runner refuses.
    PkFlipHazardDisabledTriggers {
        /// Postgres table carrying the offending trigger.
        table: String,
        /// `(trigger_name, tgenabled_char)` pairs.
        triggers: Vec<(String, char)>,
    },

    /// **D063** — T9 PK-flip pre-flight: at least one open Postgres
    /// transaction has run for longer than the configured threshold
    /// (`MigrateConfig::pk_flip_long_tx_threshold_secs`). The
    /// cutover would either block on `AccessExclusiveLock` or abort
    /// on `lock_timeout`; the runner refuses.
    PkFlipHazardLongRunningTx {
        /// `(pid, age_seconds)` pairs.
        offenders: Vec<(i32, i64)>,
        /// Threshold the offenders exceeded.
        threshold_secs: u32,
    },

    /// **D064** — T9 verification halt: between backfill and
    /// cutover, the per-table verification SELECT returned a non-zero
    /// count of NULL / mismatched shadow rows. The runner halts
    /// before opening the cutover transaction.
    PkFlipVerificationFailed {
        /// Postgres table whose verification failed.
        table: String,
        /// Number of violating rows the verification query returned.
        count_violating: i64,
    },

    /// A Postgres system-catalog query (pg_class, pg_constraint,
    /// pg_subscription, etc.) failed before the migration could
    /// proceed. Distinct from [`RunnerError::LedgerWriteFailed`] —
    /// the ledger was not touched; the failure is in a read-only
    /// catalog probe. The `query_label` field names the probe so
    /// operators can correlate the error to the specific catalog
    /// object being queried (cluster-2 simplify Finding 6).
    CatalogQueryFailed {
        /// A static label naming the catalog object or query that
        /// failed (e.g. `"pg_stat_replication"`, `"pg_class relpages"`).
        query_label: &'static str,
        /// The underlying Postgres error.
        source: DjogiError,
    },

    /// **#274** — Failed to check out a single pinned Postgres connection
    /// from the pool before the migration operation began. The runner
    /// requires one physical session for the entire advisory-lock window
    /// (lock acquisition, DDL, ledger writes, and lock release must all
    /// occur on the same backend). Pool checkout failure means the
    /// operation cannot start; no ledger row is inserted and no DDL runs.
    PinnedSessionCheckoutFailed {
        /// The underlying pool or connection error.
        source: DjogiError,
    },

    /// **#274 / #280** — `pg_advisory_unlock` returned `false`, meaning
    /// the advisory lock was NOT held on the physical session that called
    /// it. This is a session-pinning correctness failure: the lock was
    /// either never acquired on this session or was acquired on a
    /// different one (the pre-#274 pool-backed bug).
    ///
    /// This variant fires ONLY when the migration operation itself
    /// succeeded. If both the operation and the release fail, the
    /// original operation error is returned and the unlock failure is
    /// logged via `tracing::error!`.
    AdvisoryUnlockReturnedFalse {
        /// The advisory lock key that `pg_advisory_unlock` returned false for.
        key: i64,
        /// The bucket whose advisory lock could not be confirmed as released.
        bucket: BucketKey,
    },

    /// Strict replay expansion refused: partitioned parent has zero leaves.
    /// In apply mode this falls back to a no-op comment; in replay-strict
    /// mode (rollback/repair) we refuse because replaying a shorter stream
    /// would silently miss leaf work that the ledger already counted.
    PartitionExpansionNoLeaves {
        parent: String,
        statement_label: String,
    },
}

impl std::fmt::Display for RunnerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RunnerError::LockTimeout { path, holder_pid } => match holder_pid {
                Some(pid) => write!(
                    f,
                    "D025 lock held by another invocation (PID {pid}) at {}; \
                     refusing to apply",
                    path.display(),
                ),
                None => write!(
                    f,
                    "D025 lock held by another invocation at {}; refusing to apply \
                     (PID unknown)",
                    path.display(),
                ),
            },
            RunnerError::GuardError(e) => write!(f, "workspace lock error: {e}"),
            RunnerError::AdvisoryLockFailed {
                bucket,
                key,
                attempts,
            } => write!(
                f,
                "Postgres advisory lock for bucket database={db} app={app} \
                 (key=0x{key:016x}) could not be acquired after {attempts} attempts",
                db = bucket.database,
                app = bucket.app,
            ),
            RunnerError::AdvisoryLockQueryFailed { app_label, source } => write!(
                f,
                "pg_try_advisory_lock query failed for app `{app_label}`: {source}",
            ),
            RunnerError::ChecksumMismatch(m) => write!(f, "{m}"),
            RunnerError::ChecksumFormat(e) => write!(f, "{e}"),
            RunnerError::LedgerWriteFailed { version, source } => {
                write!(f, "ledger write failed for version `{version}`: {source}")
            }
            RunnerError::LedgerQueryFailed {
                query_label,
                source,
            } => write!(
                f,
                "ledger query `{query_label}` failed before the migration could proceed: {source}",
            ),
            RunnerError::RunIdGenerationFailed { source } => write!(
                f,
                "run_id generation via `SELECT heerid_next()` failed before any \
                 migration ran: {source}",
            ),
            RunnerError::LedgerBootstrapFailed { source } => write!(
                f,
                "ledger bootstrap (CREATE TABLE IF NOT EXISTS djogi_schema_migrations) \
                 failed: {source}",
            ),
            RunnerError::VersionAlreadyApplied {
                version,
                applied_at,
            } => match applied_at {
                Some(when) => write!(
                    f,
                    "migration version `{version}` was already applied at {when}; \
                     re-running is rejected — use `djogi migrations status` to confirm",
                ),
                None => write!(
                    f,
                    "migration version `{version}` was already applied; \
                     re-running is rejected — use `djogi migrations status` to confirm",
                ),
            },
            RunnerError::VersionCollisionNonTerminal {
                version,
                status,
                run_id,
            } => {
                let guidance = match status {
                    LedgerStatus::Pending => {
                        "use `djogi migrations status` to inspect it, then `repair_partial_apply` to resolve it in place"
                    }
                    LedgerStatus::Failed => {
                        "use `djogi migrations status` to inspect it, then `repair_resume_partial_apply` if it is still resumable or `repair_partial_apply` otherwise"
                    }
                    LedgerStatus::RolledBack => {
                        "use `djogi migrations status` to inspect it; re-running `djogi migrations apply` will remove the rolled-back row and re-apply the migration"
                    }
                    LedgerStatus::Applied | LedgerStatus::Baseline | LedgerStatus::Faked => {
                        unreachable!(
                            "VersionCollisionNonTerminal only carries pending, failed, or rolled_back rows",
                        )
                    }
                };
                write!(
                    f,
                    "migration version `{version}` collided with an existing non-terminal \
                     ledger row (status `{status}`, run_id {run_id}); re-running is rejected \
                     until that run is reconciled — {guidance}",
                    status = status.as_db_str(),
                )
            }
            RunnerError::TargetTableNotFound {
                bucket,
                index_name,
                target_table,
            } => write!(
                f,
                "relpages probe for `{index}` could not locate target table `{table}` \
                 (bucket database={db} app={app}); the index plan does not create \
                 this table either — check for a typo or a mis-quoted identifier",
                index = index_name,
                table = target_table,
                db = bucket.database,
                app = bucket.app,
            ),
            RunnerError::RelpagesThresholdExceeded {
                bucket,
                index_name,
                target_table,
                relpages,
                threshold,
            } => write!(
                f,
                "relpages probe rejected `CREATE INDEX {index}` on `{table}` (bucket \
                 database={db} app={app}): {relpages} > {threshold}; \
                 set `requires_out_of_transaction = true` on the IndexSpec, or \
                 lower `migrate.strict_concurrent_warnings`",
                index = index_name,
                table = target_table,
                db = bucket.database,
                app = bucket.app,
            ),
            RunnerError::SegmentSqlExecutionModeConflict {
                segment_index,
                segment_kind,
                statement_label,
                problem,
            } => match problem {
                SegmentSqlExecutionModeProblem::TransactionControl { keyword } => write!(
                    f,
                    "{} segment {segment_index} statement `{statement_label}` embeds top-level \
                     transaction control `{keyword}`; djogi owns migration transaction boundaries \
                     and refuses inline BEGIN/COMMIT/SAVEPOINT control",
                    segment_kind_name(*segment_kind),
                ),
                SegmentSqlExecutionModeProblem::RequiresNonTransactional { statement_shape } => {
                    write!(
                        f,
                        "{} segment {segment_index} statement `{statement_label}` uses `{statement_shape}`, \
                     which must run in a non-transactional segment",
                        segment_kind_name(*segment_kind),
                    )
                }
            },
            RunnerError::TransactionalSegmentFailed {
                segment_index,
                statement_label,
                source,
            } => write!(
                f,
                "transactional segment {segment_index} failed at `{statement_label}`: {source}",
            ),
            RunnerError::NonTransactionalSegmentFailed {
                segment_index,
                step_index,
                statement_label,
                applied_steps_count,
                source,
            } => write!(
                f,
                "non-transactional segment {segment_index} step {step_index} `{statement_label}` \
                 failed after {applied_steps_count} successful step(s): {source}",
            ),
            RunnerError::NonTransactionalProgressAckFailed {
                segment_index,
                step_index,
                statement_label,
                applied_steps_count,
                source,
            } => write!(
                f,
                "non-transactional segment {segment_index} step {} `{statement_label}` \
                 committed, but the runner failed to durably acknowledge \
                 applied_steps_count={applied_steps_count}; the row now carries a \
                 non-tx progress claim and must be reconciled before resume: {source}",
                step_index + 1,
            ),
            RunnerError::ConfigLoadFailed { source } => {
                write!(f, "failed to load Djogi.toml: {source}")
            }
            RunnerError::SnapshotPersistFailed { path, source } => {
                write!(f, "snapshot persist failed at {}: {source}", path.display(),)
            }
            RunnerError::BaselineSnapshotShouldNotBeProvided => f.write_str(
                "baseline_plan rejects caller-supplied snapshots: baseline projects the \
                 live database itself; pass `runner_ctx.snapshot = None`",
            ),
            RunnerError::BaselineProjectionFailed { source } => write!(
                f,
                "baseline live-DB projection failed before ledger insert: {source}",
            ),
            RunnerError::PkFlipHazardReplicaSessions {
                walsenders,
                subscriptions,
            } => write!(
                f,
                "D060 PK-flip cutover refused: logical-replication machinery is active and \
                 may be applying changes with session_replication_role = 'replica' (which \
                 suppresses BEFORE row triggers and would leave the autofill skipped). \
                 Pause the apply worker(s) or `ALTER TABLE ... ENABLE ALWAYS TRIGGER zzz_*` \
                 before retrying. Walsenders ({nw}): {walsenders:?}; \
                 enabled subscriptions ({ns}): {subscriptions:?}",
                nw = walsenders.len(),
                ns = subscriptions.len(),
            ),
            RunnerError::PkFlipHazardPreexistingZzzTrigger {
                table,
                trigger_names,
            } => write!(
                f,
                "D061 PK-flip cutover refused: pre-existing zzz_* trigger(s) on `{table}` \
                 collide with the autofill install: {trigger_names:?}. Rename or drop them \
                 before retrying.",
            ),
            RunnerError::PkFlipHazardDisabledTriggers { table, triggers } => write!(
                f,
                "D062 PK-flip cutover refused: disabled trigger(s) on `{table}` would \
                 silently bypass the autofill: {triggers:?}. Re-enable them or pause \
                 whatever process disabled them before retrying.",
            ),
            RunnerError::PkFlipHazardLongRunningTx {
                offenders,
                threshold_secs,
            } => write!(
                f,
                "D063 PK-flip cutover refused: {n} transaction(s) have been open longer \
                 than {threshold_secs}s and would block AccessExclusiveLock or trigger \
                 lock_timeout. Cancel or terminate them via pg_cancel_backend / \
                 pg_terminate_backend, then retry. Offenders (pid, age_secs): {offenders:?}",
                n = offenders.len(),
            ),
            RunnerError::PkFlipVerificationFailed {
                table,
                count_violating,
            } => write!(
                f,
                "D064 PK-flip verification halt: table `{table}` has {count_violating} row(s) \
                 with NULL or stale shadow values. Re-run the backfill (and audit any DISABLE \
                 TRIGGER / replica writes during the window) before retrying the cutover.",
            ),
            RunnerError::OutOfOrderRejected {
                version,
                conflicting_version,
                conflicting_applied_at,
            } => match conflicting_applied_at {
                Some(when) => write!(
                    f,
                    "version `{version}` would apply out-of-order: peer \
                     `{conflicting_version}` was already applied at {when}; \
                     the active OutOfOrderPolicy is Reject. Either rebase \
                     this migration to a later timestamp, supply \
                     OutOfOrderPolicy::AllowExplicit with an override reason, \
                     or run on a non-CI / non-production profile to inherit \
                     AllowWithDiagnostic."
                ),
                None => write!(
                    f,
                    "version `{version}` would apply out-of-order: peer \
                     `{conflicting_version}` is already applied; \
                     the active OutOfOrderPolicy is Reject."
                ),
            },
            RunnerError::CatalogQueryFailed {
                query_label,
                source,
            } => write!(f, "Postgres catalog query '{query_label}' failed: {source}",),
            RunnerError::PinnedSessionCheckoutFailed { source } => write!(
                f,
                "failed to check out a pinned Postgres session from the pool before \
                 the migration operation began (GH #274): {source}",
            ),
            // D274 is shared by runner and repair for advisory-lock
            // correctness failures (GH #274); shared code is intentional.
            RunnerError::AdvisoryUnlockReturnedFalse { key, bucket } => write!(
                f,
                "D274 pg_advisory_unlock returned false for bucket database={db} app={app} \
                 (key=0x{key:016x}); the advisory lock was not held on the session that \
                 called pg_advisory_unlock — this is a session-pinning correctness failure \
                 (GH #274/#280). The migration SQL and ledger writes may have succeeded; \
                 inspect the ledger row to determine the actual applied state.",
                db = bucket.database,
                app = bucket.app,
            ),
            RunnerError::PartitionExpansionNoLeaves {
                parent,
                statement_label,
            } => write!(
                f,
                "partition expansion for `{statement_label}` refused: \
                 partitioned parent `{parent}` has 0 leaves in replay-strict mode",
            ),
        }
    }
}

impl std::error::Error for RunnerError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            RunnerError::ChecksumMismatch(e) => Some(e),
            RunnerError::ChecksumFormat(e) => Some(e),
            RunnerError::GuardError(e) => Some(e),
            RunnerError::LedgerWriteFailed { source, .. } => Some(source),
            RunnerError::AdvisoryLockQueryFailed { source, .. } => Some(source),
            RunnerError::SegmentSqlExecutionModeConflict { .. } => None,
            RunnerError::TransactionalSegmentFailed { source, .. } => Some(source),
            RunnerError::NonTransactionalSegmentFailed { source, .. } => Some(source),
            RunnerError::NonTransactionalProgressAckFailed { source, .. } => Some(source),
            RunnerError::ConfigLoadFailed { source } => Some(source),
            RunnerError::SnapshotPersistFailed { source, .. } => Some(source),
            RunnerError::BaselineProjectionFailed { source } => Some(source.as_ref()),
            RunnerError::CatalogQueryFailed { source, .. } => Some(source),
            RunnerError::LedgerQueryFailed { source, .. } => Some(source),
            RunnerError::RunIdGenerationFailed { source } => Some(source),
            RunnerError::LedgerBootstrapFailed { source } => Some(source),
            RunnerError::PinnedSessionCheckoutFailed { source } => Some(source),
            RunnerError::VersionCollisionNonTerminal { .. } => None,
            _ => None,
        }
    }
}

/// Caller-supplied context for one runner invocation. Decouples the
/// runner from a hard-coded `Djogi.toml` location so tests can
/// inject their own knobs.
///
/// **Snapshot path policy.** `snapshot_path` is owned by the caller
/// — the runner does not invent a path. T6's `apply` orchestrator
/// constructs `migrations/<target>/<app>/schema_snapshot.json` from
/// the workspace root and the bucket; tests pass `None` to skip the
/// snapshot persist step entirely (useful when the test cares only
/// about ledger semantics).
pub struct RunnerCtx {
    /// The bucket this run is applying. Derives the advisory-lock
    /// key and, in production, the snapshot path.
    pub bucket: BucketKey,
    /// The version label (e.g. `V20260425010203__add_users`)
    /// recorded in the ledger.
    pub version: String,
    /// Operator-facing one-line description.
    pub description: String,
    /// Pre-computed checksum_up. The runner recomputes from the
    /// plan's SQL fragments and verifies match before applying.
    /// Format: `V1:<sha256-hex>`.
    pub checksum_up: String,
    /// Pre-computed checksum_down, or `None` when every operation's
    /// down side is a SQL-comment placeholder.
    pub checksum_down: Option<String>,
    /// Snapshot to persist on success. `None` skips the persist step
    /// (used by tests that only care about ledger writes).
    pub snapshot: Option<super::schema::AppliedSchema>,
    /// Where to write the snapshot. Required iff `snapshot.is_some()`.
    pub snapshot_path: Option<PathBuf>,
    /// Migrate-engine config (relpages threshold + strict mode).
    pub config: MigrateConfig,
    /// Policy gate for out-of-order applies (T7). Defaults to
    /// [`super::policy::OutOfOrderPolicy::AllowWithDiagnostic`] for
    /// dev iteration; CI / production loaders flip to `Reject` via
    /// [`super::policy::OutOfOrderPolicy::default_for_config`]. The
    /// runner consults this BEFORE inserting the pending ledger row,
    /// so a `Reject` outcome leaves no database trace.
    pub out_of_order_policy: super::policy::OutOfOrderPolicy,
    /// Optional pool pointing at the **audit DB** (`crud_log_url` in
    /// `Djogi.toml`).
    ///
    /// When `Some`, the runner writes one row to `djogi_ddl_audit`
    /// per successful migration via [`super::audit::record_ddl`],
    /// so `djogi db reset` (which drops the app DB) cannot erase
    /// the migration history. When `None` the audit write is
    /// silently skipped — appropriate for tests and for adopters
    /// who have not yet provisioned the second DB.
    ///
    /// **Wiring status:**
    ///
    /// - **Cluster 8ε (T9.4 / T9.5)** added the field and wired
    ///   [`super::record_ddl_audit`] into `apply_plan_inner`'s
    ///   success-only path. The runner writes audit rows whenever
    ///   the caller supplies `Some(pool)`.
    /// - **Phase 8.5 Cluster 2 issue #118** wired the production CLI
    ///   dispatch (`db reset` replay path) to populate this field
    ///   from `crud_log_url` (env-var override or
    ///   derive-from-`database.url` fallback) via
    ///   [`super::resolve_audit_url`] + [`super::build_audit_pool`].
    ///
    /// Tests that build `RunnerCtx` literals typically leave this
    /// `None` — the dedicated audit-row coverage runs in
    /// `tests/internal/sources/phase8_5_c2_118_*`.
    ///
    /// **Why `deadpool_postgres::Pool` and not `DjogiPool`:** the
    /// audit pool is not user-facing — adopters never see it, and
    /// the runner constructs the audit-side `DjogiContext` itself
    /// via `DjogiPool { inner: pool.clone() }` at the call site.
    /// Holding the raw pool here keeps the dependency on
    /// `DjogiPool`'s wider invariants (post-connect callbacks,
    /// status reporting) out of `RunnerCtx`'s shape — those are
    /// app-side concerns that do not apply to the audit DB.
    pub audit_pool: Option<deadpool_postgres::Pool>,
}

/// Successful-apply report. The runner returns this on a clean
/// `apply_plan` so the caller can log structured progress data.
#[derive(Debug, Clone)]
pub struct RunReport {
    /// `id` of the ledger row this run inserted.
    pub ledger_id: i64,
    /// `run_id` recorded on the ledger row.
    pub run_id: i64,
    /// Number of transactional segments executed.
    pub transactional_segments: usize,
    /// Number of non-transactional segments executed.
    pub non_transactional_segments: usize,
    /// Number of metadata-only segments encountered. T4 records the
    /// segments but does not execute filesystem moves; T6 owns that
    /// path.
    pub metadata_segments: usize,
    /// Wall-clock elapsed time in milliseconds.
    pub execution_time_ms: i64,
}

// ── Public entry point ────────────────────────────────────────────────────

/// Apply a [`MigrationPlan`] against the runner's context.
///
/// **Witness-typed workspace lock.** The `_guard: &WorkspaceGuard`
/// parameter is a compile-time witness that the caller already holds
/// the workspace file lock — its mere presence at the type level
/// proves the lock is alive for the duration of the call. The runner
/// itself does not touch the guard; the parameter is named with a
/// leading underscore to signal "consumed at the type level only".
///
/// Misuse — calling `apply_plan` without first acquiring the lock —
/// is a compile error rather than a silent race window. Tests that
/// only care about ledger semantics still go through the lock by
/// asking the [`super::guard::acquire`] helper for a per-test path.
///
/// **Three-database awareness.** The runner currently routes every
/// query through the supplied `&mut DjogiContext`'s pool. The
/// `RunnerCtx::bucket.database` field is hashed into the advisory
/// lock key and surfaced in operator-facing errors, but the actual
/// query routing follows the context the caller supplied. Phase 4's
/// `DjogiContext` is single-pool today; when the three-database
/// `DjogiContext::pool_for(database)` API lands the runner will
/// pull the right pool from `runner_ctx.bucket.database` here. The
/// `BucketKey.database` channel exists today so the orchestrator
/// (T6 `apply`) can construct one `DjogiContext` per database before
/// invoking the runner.
///
/// **Per-bucket advisory lock.** The runner DOES acquire and
/// release the per-bucket Postgres advisory lock around every
/// segment dispatch.
///
/// **Snapshot persistence.** Writes the snapshot file ONLY after
/// the ledger row reaches `applied` and every segment succeeded.
/// Any failure leaves the snapshot at its prior value.
pub async fn apply_plan(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    _guard: &WorkspaceGuard,
) -> Result<RunReport, RunnerError> {
    // GH #274 / #331 — pin one physical Postgres session for the
    // entire operation window so the advisory lock, DDL, ledger
    // writes, and lock release all run on the same backend.
    let mut pinned = ctx
        .pin_for_migration()
        .await
        .map_err(|e| RunnerError::PinnedSessionCheckoutFailed { source: e })?;
    apply_plan_pinned(&mut pinned, plan, runner_ctx).await
}

/// Internal apply path that runs on an already-pinned context.
///
/// Both pool-backed (after checkout) and transaction-backed callers
/// route here. All queries in this function — bootstrap, advisory
/// lock, DDL, ledger writes, and unlock — run on the same physical
/// Postgres session.
async fn apply_plan_pinned(
    ctx: &mut PinnedCtx<'_>,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
) -> Result<RunReport, RunnerError> {
    // 1. Bootstrap the ledger table.
    ledger::bootstrap(ctx)
        .await
        .map_err(|e| RunnerError::LedgerBootstrapFailed { source: e })?;

    // 2. Acquire pg advisory lock for this bucket.
    let lock_key = advisory_lock_key(&plan.bucket);
    acquire_advisory_lock(ctx, &plan.bucket, lock_key).await?;

    // Whatever happens below, we must release the advisory lock.
    let result = apply_plan_inner(ctx, plan, runner_ctx).await;

    // 9. Always release advisory lock. Check the bool: false means the
    // lock was not held on this session (GH #274/#280).
    let released = release_advisory_lock(ctx, lock_key).await;

    let result = handle_release_result(result, released, &plan.bucket, lock_key);
    if result.is_ok() {
        ctx.mark_clean();
    }
    result
}

/// Core apply logic. Called from `apply_plan_pinned` after the advisory
/// lock is held. Returning early from any error path is fine; the outer
/// function's `release_advisory_lock` runs after.
async fn apply_plan_inner(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
) -> Result<RunReport, RunnerError> {
    let started = Instant::now();

    // T9 pre-flight: when the plan classifies as `PkTypeFlip`, run
    // the hazard checks (D060–D063) BEFORE any side effect. The
    // runner refuses on any hit with an actionable diagnostic; no
    // ledger row is inserted, no SQL runs.
    if matches!(
        plan.classification,
        super::diff::Classification::PkTypeFlip { .. }
    ) {
        pk_flip_preflight(ctx, runner_ctx, plan).await?;
    }

    // 4. Verify checksum BEFORE inserting the pending row. A
    // mismatch means the plan supplied to the runner does not
    // match the runner_ctx's `checksum_up` — most likely the SQL
    // file was hand-edited. A FormatError means one of the inputs
    // was not a well-formed `V1:<sha256-hex>` string and is also
    // a hard error: we never want to fall through to the byte
    // compare with malformed inputs.
    let computed_up = compute_checksum_for_plan_up(plan);
    if let Err(e) =
        ledger::verify_checksum(&runner_ctx.version, &runner_ctx.checksum_up, &computed_up)
    {
        return Err(match e {
            VerifyError::Mismatch(m) => RunnerError::ChecksumMismatch(m),
            VerifyError::Format(f) => RunnerError::ChecksumFormat(f),
        });
    }

    // T7: out-of-order detection. Walk the bucket's existing applied
    // ledger rows and surface any whose `version` is lexically greater
    // than ours — that indicates this version applies "before" a
    // previously-applied peer (the dev branch picked up a feature
    // branch's older migration after main shipped a newer one).
    //
    // Lexical compare is correct because the version prefix is
    // `V<14 digits>` (timestamp-derived) so lexical order = chronological.
    //
    // The detection runs BEFORE inserting the pending row so a
    // `Reject` policy leaves no database trace.
    let conflicting_peer = find_higher_applied_version(ctx, &plan.bucket, &runner_ctx.version)
        .await
        .map_err(|e| RunnerError::LedgerQueryFailed {
            query_label: "out_of_order_check",
            source: e,
        })?;
    let is_out_of_order = conflicting_peer.is_some();
    if is_out_of_order && !runner_ctx.out_of_order_policy.allows() {
        let (conflicting_version, conflicting_applied_at) =
            conflicting_peer.unwrap_or_else(|| (String::new(), None));
        return Err(RunnerError::OutOfOrderRejected {
            version: runner_ctx.version.clone(),
            conflicting_version,
            conflicting_applied_at,
        });
    }
    if is_out_of_order {
        let (conflicting_version, applied_at) = conflicting_peer
            .as_ref()
            .map(|(v, ts)| (v.as_str(), ts.as_deref()))
            .unwrap_or(("", None));
        tracing::warn!(
            bucket_database = %plan.bucket.database,
            bucket_app = %plan.bucket.app,
            version = %runner_ctx.version,
            conflicting_version,
            conflicting_applied_at = applied_at.unwrap_or("<unknown>"),
            policy = ?runner_ctx.out_of_order_policy,
            "out-of-order migration apply allowed by policy",
        );
    }
    // Compose a partial_apply_note when the policy is AllowExplicit so
    // the operator-supplied override reason lands on the row alongside
    // the out_of_order_flag. This is the audit-trail half of the
    // "tracing::warn! plus partial_apply_note" contract called out in
    // the T7 brief.
    let initial_note = compose_initial_note(
        is_out_of_order,
        runner_ctx.out_of_order_policy.override_reason(),
        conflicting_peer.as_ref(),
    );
    let durable_non_tx_note = initial_note.clone();

    // B-2: expand `<EACH_LEAF_TABLE>` placeholders inside any
    // partitioned-flip segment before any runner-owned writes. This
    // produces the concrete SQL the runner will actually execute, so
    // every downstream preflight and step-count calculation works on
    // the real statement list.
    let (plan_owned, leaves_cache) =
        materialize_execution_plan(ctx, plan, PartitionExpansionMode::ApplyLenient).await?;
    let plan = &plan_owned;

    preflight_segment_sql_execution_compatibility(plan)?;

    // Determine execution_mode + total_steps from the concrete plan
    // shape. `total_steps` counts non-transactional steps (each of
    // which is its own resumable unit). Transactional segments
    // collapse to a single atomic step from the resumability
    // perspective.
    let mut total_non_tx_steps: i32 = 0;
    let mut has_non_tx = false;
    for seg in &plan.segments {
        if seg.kind == SegmentKind::NonTransactional {
            has_non_tx = true;
            total_non_tx_steps = total_non_tx_steps.saturating_add(seg.statements.len() as i32);
        }
    }
    let execution_mode = if has_non_tx {
        ExecutionMode::NonTransactional
    } else {
        ExecutionMode::Transactional
    };

    // 5. Insert pending ledger row. Generate a fresh run_id.
    let run_id = generate_run_id(ctx, &runner_ctx.version).await?;
    let ledger_row = LedgerRow {
        version: runner_ctx.version.clone(),
        description: runner_ctx.description.clone(),
        checksum_up: runner_ctx.checksum_up.clone(),
        checksum_down: runner_ctx.checksum_down.clone(),
        execution_mode,
        status: LedgerStatus::Pending,
        execution_time_ms: 0,
        out_of_order_flag: is_out_of_order,
        applied_steps_count: 0,
        total_steps: if has_non_tx {
            Some(total_non_tx_steps)
        } else {
            None
        },
        partial_apply_note: initial_note,
        run_id,
        snapshot_version: SNAPSHOT_FORMAT_VERSION.to_string(),
        app_label: plan.bucket.app.clone(),
        leaf_identity: serialize_leaf_identity(&leaves_cache),
    };
    let ledger_id = match ledger::insert_pending(ctx, &ledger_row).await {
        Ok(id) => id,
        Err(e) => {
            if is_unique_violation(&e) {
                return Err(classify_duplicate_version_collision(ctx, &runner_ctx.version).await);
            }
            return Err(RunnerError::LedgerWriteFailed {
                version: runner_ctx.version.clone(),
                source: e,
            });
        }
    };

    // 6. Walk segments. Track counts for the run report.
    let mut transactional_segments = 0usize;
    let mut non_transactional_segments = 0usize;
    let mut metadata_segments = 0usize;
    let mut applied_non_tx_steps: i32 = 0;

    // Build the `AddTable` set from the plan. The relpages probe
    // uses this to disambiguate "table being created in this same
    // plan" (legit `relpages = None`) from "typo / mis-quoted
    // identifier" (hard `TargetTableNotFound`).
    let add_table_set = collect_add_table_targets(plan);

    for (seg_idx, segment) in plan.segments.iter().enumerate() {
        match segment.kind {
            SegmentKind::Transactional => {
                if let Err(e) =
                    run_transactional_segment(ctx, segment, seg_idx, runner_ctx, &add_table_set)
                        .await
                {
                    // N-1: the relpages probe runs BEFORE BEGIN, so
                    // a probe failure must NOT be reported as a
                    // transactional-segment failure (the tx has not
                    // even opened yet). Distinguish probe-side
                    // failures from in-tx statement failures so the
                    // operator-facing note matches the actual phase
                    // that failed.
                    let note = note_for_failed_transactional_segment(seg_idx, &e);
                    let _ = ledger::mark_failed(ctx, ledger_id, &note).await;
                    return Err(e);
                }
                transactional_segments += 1;
            }
            SegmentKind::NonTransactional => {
                match run_non_transactional_segment(
                    ctx,
                    segment,
                    NonTransactionalSegmentRun {
                        segment_index: seg_idx,
                        version: &runner_ctx.version,
                        ledger_id,
                        prior_steps_completed: applied_non_tx_steps,
                        total_non_tx_steps,
                        stable_note: durable_non_tx_note.as_deref(),
                        runner_ctx,
                    },
                )
                .await
                {
                    Ok(steps_completed) => {
                        applied_non_tx_steps = applied_non_tx_steps.saturating_add(steps_completed);
                        non_transactional_segments += 1;
                    }
                    Err(e) => {
                        // mark_partial already recorded inside run_non_transactional_segment
                        // for the per-step failure. We do not double-write; just propagate.
                        return Err(e);
                    }
                }
            }
            SegmentKind::MetadataOnly => {
                // T4 records the segment count but does not execute
                // filesystem moves — that is T6's `apply`
                // orchestrator. The presence of metadata-only
                // segments is captured in the ledger via the count
                // tracked here and returned in the RunReport.
                metadata_segments += 1;
            }
        }
    }

    // 7. Mark applied + persist snapshot. The order is:
    //    a. Write the snapshot file.
    //    b. Mark the ledger row applied.
    //
    // If (a) fails, the ledger stays `pending` and the operator can
    // inspect the partial state. If (b) fails after (a) succeeded,
    // the snapshot is on disk but the ledger says pending — also a
    // recoverable state because the runner's idempotency check
    // (T6) sees the snapshot match the descriptor and treats it as
    // already-applied.
    //
    // However: per the v3 plan's hard invariant ("snapshot moves
    // forward AFTER ledger reaches applied"), we flip the order:
    //    a. Mark the ledger row applied.
    //    b. Write the snapshot file.
    //
    // If (b) fails, the operator runs `compose` to regenerate the
    // snapshot from the descriptor inventory.
    let elapsed_ms: i64 = elapsed_ms(started);

    // T7: when the row was flagged out-of-order, preserve the
    // partial_apply_note so the historical conflict + override reason
    // stay visible alongside `applied` status. The default
    // `mark_applied` clears the note (its prior purpose was to
    // describe a partial-apply state that resolves on success).
    if is_out_of_order {
        ledger::mark_applied_keep_note(ctx, ledger_id, elapsed_ms, applied_non_tx_steps)
            .await
            .map_err(|e| RunnerError::LedgerWriteFailed {
                version: runner_ctx.version.clone(),
                source: e,
            })?;
    } else {
        ledger::mark_applied(ctx, ledger_id, elapsed_ms, applied_non_tx_steps)
            .await
            .map_err(|e| RunnerError::LedgerWriteFailed {
                version: runner_ctx.version.clone(),
                source: e,
            })?;
    }

    if let (Some(snapshot), Some(path)) = (&runner_ctx.snapshot, &runner_ctx.snapshot_path) {
        save_snapshot(snapshot, path).map_err(|e| RunnerError::SnapshotPersistFailed {
            path: path.clone(),
            source: e,
        })?;
    }

    // T9.5 / Phase 8.5 issue #118 — DDL audit. Best-effort: if any
    // audit-side step fails we log via `tracing::warn!` and SKIP. The
    // app DB DDL has already succeeded; an audit-DB outage MUST NOT
    // roll back work that already committed. See
    // `record_ddl_audit_for_plan` for the full failure-mode
    // rationale.
    //
    // **Snapshot decoupling (issue #118).** The audit-write loop runs
    // whenever `audit_pool.is_some()`, regardless of whether a
    // snapshot was persisted on this apply. The snapshot signature
    // becomes part of the audit row only when a snapshot was just
    // written; the `db reset` replay path deliberately passes
    // `snapshot: None` (the on-disk snapshot is unchanged across the
    // drop / recreate / replay cycle) and would otherwise have its
    // audit row suppressed by an unrelated pre-condition. The audit
    // row's primary purpose — recording that a migration's DDL ran —
    // is independent of whether new schema bytes hit disk.
    record_ddl_audit_for_plan(plan, runner_ctx, runner_ctx.snapshot.as_ref()).await;

    Ok(RunReport {
        ledger_id,
        run_id,
        transactional_segments,
        non_transactional_segments,
        metadata_segments,
        execution_time_ms: elapsed_ms,
    })
}

/// Write one `djogi_ddl_audit` row per executed (non-metadata-only)
/// segment in the plan. T9.5; snapshot decoupling Phase 8.5 issue
/// #118.
///
/// # Why this lives on the success-only path
///
/// The caller invokes this AFTER:
///
/// 1. Every segment has committed (transactional or non-transactional).
/// 2. `mark_applied` flipped the ledger row to `applied`.
/// 3. `save_snapshot` persisted the new schema-of-record to disk
///    (when a snapshot was supplied by the caller; the `db reset`
///    replay path deliberately does not).
///
/// Calling it earlier would risk an audit row whose
/// `snapshot_signature_hex` does not correspond to any persisted
/// snapshot — the signature would be of an in-memory `AppliedSchema`
/// that never reached disk. Per v3 plan §453 the audit row's purpose
/// is to ground the migration trail to the schema-of-record file
/// `djogi verify` (T9.6) inspects.
///
/// # Snapshot is optional (Phase 8.5 issue #118)
///
/// The `snapshot` parameter is `Option<&AppliedSchema>`. The audit
/// row's primary purpose — recording that a migration's DDL ran — is
/// independent of whether new schema bytes hit disk on this apply:
///
/// - **`Some(snapshot)`** — the runner just persisted these bytes to
///   `snapshot_path`. The audit row's `snapshot_signature_hex` is
///   the HMAC over those bytes (or the no-op zero hex when the
///   signing key is unset).
/// - **`None`** — no snapshot was persisted (e.g. `db reset` replay,
///   which re-runs the existing migrations against a fresh DB
///   without producing new schema bytes). The audit row carries
///   `NULL` in the signature column. NULL distinguishes "no snapshot
///   was written this apply" from "snapshot written, signed under
///   the no-op key" (the latter produces 64 zero hex chars).
///
/// Pre-issue-#118 this function took `&AppliedSchema` and the call
/// site gated audit writes on snapshot presence — which meant `db
/// reset` (the only production constructor of `RunnerCtx`) could
/// never write audit rows.
///
/// # Three-database awareness
///
/// The audit DB is operationally separate from the app DB
/// (`crud_log_url` vs. `url`). We construct a fresh
/// [`DjogiContext`] from `runner_ctx.audit_pool` — NEVER from the
/// app-side context — so a query routed here cannot accidentally
/// run against the app DB. See CLAUDE.md "Three-Database
/// Architecture".
///
/// # Failure-mode rationale
///
/// Three steps can fail: the audit-DDL bootstrap, individual
/// `INSERT` calls, and the implicit pool checkout each `DjogiContext`
/// helper performs. ALL THREE log via `tracing::warn!` and SKIP —
/// none propagate. Reasons:
///
/// - The app DB DDL has already committed.
/// - The on-disk snapshot has already been persisted (when supplied).
/// - The ledger row has already reached `applied`.
///
/// Rolling any of those back because the audit DB is unreachable
/// would be a worse outcome than a missing audit row. Operators
/// rebuilding the audit trail can replay from the ledger + snapshot;
/// they cannot recover from a runner that refused to record an
/// otherwise-clean migration apply because a sibling DB happened to
/// be down.
///
/// # Per-segment rows
///
/// One row per executed segment so the audit trail captures the same
/// granularity the runner reports (the `Transactional /
/// NonTransactional` split). MetadataOnly segments produce no SQL so
/// they are skipped — there is no `ddl_sql` to record. The same
/// `snapshot_signature_hex` (or `NULL` when no snapshot was supplied)
/// lands on every segment row from a single apply: rows from one
/// apply share the post-apply schema-of-record, and the audit reader
/// reconstructs the per-segment timeline from `applied_at` ordering
/// on the ledger side.
///
/// # Signing key
///
/// `DJOGI_SNAPSHOT_SIGNING_KEY` unset OR malformed → silently
/// degrades to the no-op key `[0u8; 32]`. The runner intentionally
/// does NOT log on malformed input; the CLI entry point that sets
/// up signing owns the operator-facing surface for key errors
/// (`djogi verify` surfaces them as `VerifyError::KeyDecode`).
/// Signing under the no-op key produces `[0u8; 32]` → 64 zero hex
/// chars → a non-NULL string in the audit column. `NULL` is reserved
/// for code paths where no snapshot was supplied at all (today:
/// `db reset` replay).
fn audit_signing_key_from_loaded(
    loaded: Result<Option<[u8; 32]>, crate::snapshot::sign::SnapshotKeyError>,
) -> [u8; 32] {
    loaded.ok().flatten().unwrap_or([0u8; 32])
}

fn audit_signature_hex_for_snapshot(
    snapshot: &super::schema::AppliedSchema,
    key: [u8; 32],
) -> Result<String, SnapshotError> {
    let snapshot_bytes = super::snapshot::serialize_snapshot(snapshot)?;
    let sig = crate::snapshot::sign::sign_snapshot(&snapshot_bytes, &key);
    Ok(super::audit::signature_to_hex(&sig))
}

async fn record_ddl_audit_for_plan(
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    snapshot: Option<&super::schema::AppliedSchema>,
) {
    let Some(audit_pool) = runner_ctx.audit_pool.as_ref() else {
        // Audit pool not configured — this is the supported "no
        // audit DB" deployment shape. Silent skip is correct.
        return;
    };

    // Resolve the signing key before rendering the signature. Per the
    // no-op-key sentinel contract in `snapshot::sign`, an unset env var
    // (`Ok(None)`) and malformed value (`Err`) both collapse here to the
    // no-op key. The CLI entry point that sets the env var owns the
    // operator-facing surface for malformed keys (`djogi verify` surfaces
    // them as `VerifyError::KeyDecode`); the runner is the audit-side
    // consumer, not the configuration owner.
    //
    // **Snapshot decoupling (Phase 8.5 issue #118).** Audit rows now
    // fire whenever `audit_pool.is_some()` regardless of whether a
    // snapshot was persisted on this apply (the runner's `db reset`
    // replay path deliberately passes `snapshot: None`). When no
    // snapshot is supplied the audit row's `snapshot_signature_hex`
    // column is `NULL` — distinguishing "no snapshot was written" from
    // "snapshot written, signed under the no-op key" (the latter
    // produces 64 zero hex chars, the former is `NULL`). This matches
    // the `record_ddl` parameter contract: `snapshot_sig_hex:
    // Option<&str>` was always optional; pre-issue-#118 the call site
    // happened to always pass `Some`, but the column is nullable by
    // design.
    let key = audit_signing_key_from_loaded(crate::snapshot::sign::load_signing_key_from_env());
    let sig_hex_opt: Option<String> = match snapshot {
        Some(s) => match audit_signature_hex_for_snapshot(s, key) {
            Ok(sig_hex) => Some(sig_hex),
            Err(e) => {
                tracing::warn!(
                    target: "djogi::migrate::audit",
                    error = ?e,
                    "snapshot re-serialisation for audit signature failed; \
                     proceeding with NULL signature so the DDL audit row still records the apply",
                );
                None
            }
        },
        None => None,
    };

    // Construct an audit-side DjogiContext. `DjogiPool` wraps the
    // raw deadpool pool; `inner` is `pub(crate)`, so this lives in
    // the same crate as `pg::pool`. We clone the pool handle (an
    // `Arc` bump under the hood — zero cost) so the runner does not
    // disturb the caller's ownership of `runner_ctx.audit_pool`.
    let audit_djogi_pool = crate::pg::pool::DjogiPool {
        inner: audit_pool.clone(),
        // Audit pools don't surface a URL — internal substrate only,
        // never reaches the NOTIFY subscriber path. See `DjogiPool::url`
        // doc for the contract.
        url: None,
        // Fresh per-process id every time the runner constructs an
        // audit-side `DjogiPool`, so this transient handle never
        // collides with any other pool's NOTIFY-registry slot.
        pool_id: crate::pg::pool::next_pool_id(),
    };
    let mut audit_ctx = DjogiContext::from_pool(audit_djogi_pool);

    // Bootstrap the audit table — `CREATE TABLE IF NOT EXISTS` is
    // idempotent so calling on every apply is cheap. Doing it here
    // (rather than once at process start) keeps the runner
    // self-contained: no separate "init audit DB" CLI step is
    // required.
    if let Err(e) = super::audit::bootstrap_ddl_audit(&mut audit_ctx).await {
        tracing::warn!(
            target: "djogi::migrate::audit",
            bucket_database = %plan.bucket.database,
            bucket_app = %plan.bucket.app,
            error = ?e,
            "djogi_ddl_audit bootstrap failed; skipping audit rows for this apply",
        );
        return;
    }

    // One row per executed segment. MetadataOnly segments carry no
    // SQL — the apply path skips them and the audit trail follows.
    for (seg_idx, segment) in plan.segments.iter().enumerate() {
        if segment.kind == SegmentKind::MetadataOnly {
            continue;
        }
        // Concatenate the `up` SQL for this segment in execution
        // order, separated by `;\n`. Storing the concatenated text
        // (rather than one row per statement) matches the segment
        // granularity the runner already reports and keeps the
        // audit table at one row per atomic-commit unit.
        let ddl_sql: String = segment
            .statements
            .iter()
            .map(|s| s.up.as_str())
            .collect::<Vec<_>>()
            .join(";\n");
        // Routes through the public re-export `record_ddl_audit`
        // (the in-module fn is `audit::record_ddl`; the re-export
        // adds the `_audit` suffix to disambiguate from sibling
        // ledger / seed CRUD helpers — see T9.4 INFO finding on
        // naming drift). Calling the re-export keeps the runner
        // aligned with the public-surface name even though the
        // private path would also resolve.
        if let Err(e) = super::record_ddl_audit(
            &mut audit_ctx,
            &plan.bucket.database,
            &plan.bucket.app,
            &ddl_sql,
            sig_hex_opt.as_deref(),
        )
        .await
        {
            tracing::warn!(
                target: "djogi::migrate::audit",
                bucket_database = %plan.bucket.database,
                bucket_app = %plan.bucket.app,
                segment_index = seg_idx,
                error = ?e,
                "djogi_ddl_audit insert failed; continuing with remaining segments",
            );
            // Continue — best-effort. A transient error on one
            // segment row should not suppress the next.
        }
    }
}

// ── Rollback / fake-apply / baseline (Phase 7 v3 §8 — T5) ─────────────────

/// Operator-supplied policy for a rollback whose `down` SQL is
/// flagged lossy by the SQL emitter (e.g. `DropColumn`, `DropTable`,
/// `DropEnum`, `DropIndex`).
///
/// Lossy rollback means the down SQL cannot reconstruct the original
/// row data — for `DropColumn` the column is gone, for `DropTable`
/// the rows are gone, for `DropEnum` the type's existence is gone.
/// Rollback refuses to run a lossy operation by default; the operator
/// must explicitly opt in via `LossyRollbackPolicy::Allow { reason }`.
/// The reason is recorded verbatim in the ledger row's
/// `partial_apply_note` so the audit trail captures *why* the loss
/// was acceptable.
#[derive(Debug, Clone)]
pub enum LossyRollbackPolicy {
    /// Refuse to run any lossy down statement. The default and the
    /// safe choice — verifying the rollback is a non-event before
    /// proceeding.
    Refuse,
    /// Run lossy down statements anyway. The `reason` field is
    /// preserved into the ledger's `partial_apply_note` for audit.
    Allow {
        /// Operator-supplied rationale; non-empty by convention. The
        /// rollback path does not enforce non-emptiness so dev
        /// iterations can pass `String::new()`, but production
        /// callers should always set a real string.
        reason: String,
    },
}

/// Errors specific to [`rollback_plan`]. Distinct from [`RunnerError`]
/// because rollback shares many shapes with apply but adds the
/// lossy-policy refusal path.
#[derive(Debug)]
pub enum RollbackError {
    /// Workspace lock / Postgres error from the apply substrate.
    /// Wraps [`RunnerError`] so the caller can match the specific
    /// underlying failure.
    Runner(RunnerError),
    /// At least one operation's `down` SQL is flagged lossy and the
    /// operator did not opt in. The rollback was rejected before any
    /// SQL ran.
    LossyRollbackRefused {
        /// Operation labels carrying a lossy marker.
        offending_labels: Vec<String>,
        /// Per-label loss kind so the operator-facing message names
        /// the categories.
        kinds: Vec<LossyRollbackKind>,
    },
    /// The version is not present in the ledger or already in a
    /// status that admits no rollback (`pending`, `failed`,
    /// `rolled_back`, `baseline`).
    VersionNotRollbackable {
        version: String,
        current_status: LedgerStatus,
    },
    /// The version was not found in the ledger at all.
    VersionNotFound { version: String },
    /// The plan's `bucket.app` does not match the ledger row's
    /// `app_label`. The advisory lock is acquired on `plan.bucket`
    /// before the row is loaded; if they differ the runner would
    /// mutate the row while holding a lock for the wrong logical
    /// bucket. Rollback refuses and releases the lock on the same
    /// pinned session before returning (GH #274 hardening).
    BucketAppMismatch {
        /// The migration version whose row was loaded.
        version: String,
        /// The `app_label` stored in the ledger row.
        row_app_label: String,
        /// The `bucket.app` from the caller-supplied plan.
        supplied_app: String,
    },
    /// A `down` statement raised a Postgres error mid-rollback.
    DownStatementFailed {
        segment_index: usize,
        statement_label: String,
        source: DjogiError,
    },
    /// The runner was asked to revert the snapshot to a prior version
    /// but no `prior_snapshot` was supplied.
    PriorSnapshotMissing,
    /// **#356** — The freshly materialized leaf identity for this migration
    /// does not match the value stored in the ledger. The partition topology
    /// has changed since the original apply, so rolling back against different
    /// leaves would be unsafe.
    LeafIdentityMismatch {
        /// Migration version being rolled back.
        version: String,
        /// Leaf identity stored in the ledger row from the original apply.
        stored_leaf_identity: String,
        /// Leaf identity recomputed from the current live partition topology.
        current_leaf_identity: String,
    },
    /// I/O failure persisting the prior snapshot back to disk.
    SnapshotPersistFailed {
        path: PathBuf,
        source: SnapshotError,
    },
}

impl std::fmt::Display for RollbackError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RollbackError::Runner(e) => write!(f, "rollback failed at runner level: {e}"),
            RollbackError::LossyRollbackRefused {
                offending_labels, ..
            } => write!(
                f,
                "rollback refused: {n} operation(s) carry a lossy down side; \
                 supply LossyRollbackPolicy::Allow {{ reason }} to proceed: {labels:?}",
                n = offending_labels.len(),
                labels = offending_labels,
            ),
            RollbackError::VersionNotRollbackable {
                version,
                current_status,
            } => write!(
                f,
                "version `{version}` is not in a rollbackable status (current: {current})",
                current = current_status.as_db_str(),
            ),
            RollbackError::VersionNotFound { version } => {
                write!(f, "version `{version}` is not present in the ledger")
            }
            RollbackError::BucketAppMismatch {
                version,
                row_app_label,
                supplied_app,
            } => write!(
                f,
                "rollback rejected: version `{version}` belongs to app \
                 `{row_app_label}` but the supplied plan has bucket app \
                 `{supplied_app}`; the advisory lock would be held for \
                 the wrong logical bucket",
            ),
            RollbackError::DownStatementFailed {
                segment_index,
                statement_label,
                source,
            } => write!(
                f,
                "rollback `down` segment {segment_index} `{statement_label}` failed: {source}",
            ),
            RollbackError::PriorSnapshotMissing => f.write_str(
                "rollback requires a prior_snapshot to revert to but the caller passed None",
            ),
            RollbackError::SnapshotPersistFailed { path, source } => {
                write!(
                    f,
                    "rollback snapshot persist at {} failed: {source}",
                    path.display()
                )
            }
            RollbackError::LeafIdentityMismatch {
                version,
                stored_leaf_identity: _,
                current_leaf_identity: _,
            } => write!(
                f,
                "[D624] rollback refused: partition leaf identity mismatch for `{version}`",
            ),
        }
    }
}

impl std::error::Error for RollbackError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            RollbackError::Runner(e) => Some(e),
            RollbackError::DownStatementFailed { source, .. } => Some(source),
            RollbackError::SnapshotPersistFailed { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Roll back a previously-applied migration by running its emitted
/// `down` SQL in reverse order.
///
/// **Witness-typed workspace lock.** Like [`apply_plan`], rollback
/// requires a `&WorkspaceGuard` so the file lock is held for the
/// entire operation.
///
/// **Order of execution.** Apply runs transactional segments first
/// then non-transactional. Rollback inverts that:
///
/// 1. Non-transactional segments run first, in reverse statement
///    order, autocommitting each step. (Apply's order is
///    NonTx-segment-after-Tx-segment by segment-list position; the
///    rollback walks segments in *reverse list position* and reverses
///    each segment's statements.)
/// 2. Transactional segments run last, all wrapped in one Postgres
///    transaction so a partial-rollback failure rolls back cleanly.
///
/// **Lossy down handling.** Pre-walks the plan and collects every
/// operation whose `lossy.is_some()`. With
/// [`LossyRollbackPolicy::Refuse`] (the default), surfaces the list
/// as [`RollbackError::LossyRollbackRefused`] before any SQL runs.
/// With [`LossyRollbackPolicy::Allow { reason }`], the rollback
/// proceeds and the reason is preserved in the ledger row's
/// `partial_apply_note`.
///
/// **Snapshot semantics.** Rollback does NOT re-derive the prior
/// snapshot from the down SQL — that requires a full delta-replay
/// engine which is not in T5's scope. The caller (typically T6's
/// `apply` orchestrator with a snapshot history) supplies the prior
/// snapshot explicitly via `prior_snapshot` and `prior_snapshot_path`.
/// Pass `None` to skip the snapshot revert (tests, when the snapshot
/// is not under test).
///
/// **Ledger update.** On success, the ledger row's status flips to
/// [`LedgerStatus::RolledBack`], `applied_steps_count` resets to 0,
/// and `partial_apply_note` is filled with a record of the rollback
/// (timestamp + lossy reason if any).
pub async fn rollback_plan(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    _guard: &WorkspaceGuard,
    lossy_policy: LossyRollbackPolicy,
    prior_snapshot: Option<&super::schema::AppliedSchema>,
) -> Result<RollbackReport, RollbackError> {
    // B-3: hoist the PriorSnapshotMissing check to the very top —
    // before any ledger bootstrap, before any DDL, before any ledger
    // mutation.
    if prior_snapshot.is_none() && runner_ctx.snapshot_path.is_some() {
        return Err(RollbackError::PriorSnapshotMissing);
    }

    // GH #274 / #331 — pin one physical Postgres session for the
    // entire rollback window (same contract as apply_plan).
    let mut pinned = ctx.pin_for_migration().await.map_err(|e| {
        RollbackError::Runner(RunnerError::PinnedSessionCheckoutFailed { source: e })
    })?;
    rollback_plan_pinned(&mut pinned, plan, runner_ctx, lossy_policy, prior_snapshot).await
}

/// Determine whether lossy rollback is permitted for the given plan.
///
/// Scans all statements in the plan for lossy markers and enforces
/// the policy. Returns the operator-supplied reason string (if any)
/// when lossy operations are present but allowed, or None if no
/// lossy operations exist. Refuses with [`RollbackError`] when
/// lossy operations are present and the policy is `Refuse`.
///
/// This operates against the materialized replay plan (partition-expanded),
/// not the original unexpanded plan, so per-leaf lossy markers are properly
/// detected (GH #317).
// RollbackError is a large enum by design; this sync helper returns it by
// value and needs the suppression. Same rationale as handle_release_result.
#[allow(clippy::result_large_err)]
fn rollback_lossy_allow_reason(
    plan: &MigrationPlan,
    lossy_policy: &LossyRollbackPolicy,
) -> Result<Option<String>, RollbackError> {
    let lossy_ops: Vec<(String, LossyRollbackKind)> = plan
        .segments
        .iter()
        .flat_map(|s| s.statements.iter())
        .filter_map(|stmt| stmt.lossy.as_ref().map(|w| (stmt.label.clone(), w.kind)))
        .collect();

    match (lossy_policy, lossy_ops.is_empty()) {
        (_, true) => Ok(None),
        (LossyRollbackPolicy::Refuse, false) => Err(RollbackError::LossyRollbackRefused {
            offending_labels: lossy_ops.iter().map(|(label, _)| label.clone()).collect(),
            kinds: lossy_ops.iter().map(|(_, kind)| *kind).collect(),
        }),
        (LossyRollbackPolicy::Allow { reason }, false) => Ok(Some(reason.clone())),
    }
}

/// Internal rollback path that runs on an already-pinned context.
///
/// Materializes the strict replay plan inside the advisory lock before
/// scanning lossy markers or executing down SQL. Partition-expanded
/// statements are rematerialized from the same execution stream used
/// by apply; rollback replays reverse down SQL against the expanded
/// stream, ensuring per-leaf lossy markers are properly detected
/// (GH #317).
async fn rollback_plan_pinned(
    ctx: &mut PinnedCtx<'_>,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    lossy_policy: LossyRollbackPolicy,
    prior_snapshot: Option<&super::schema::AppliedSchema>,
) -> Result<RollbackReport, RollbackError> {
    // 1. Bootstrap the ledger so the SELECT below cannot fail with
    //    relation-not-found.
    ledger::bootstrap(ctx)
        .await
        .map_err(|e| RollbackError::Runner(RunnerError::LedgerBootstrapFailed { source: e }))?;

    // 2. Acquire the per-bucket advisory lock BEFORE loading the ledger
    //    row. Moving the row read inside the lock eliminates the TOCTOU
    //    window between the status check and the down-SQL mutations
    //    (GH #274).
    let lock_key = advisory_lock_key(&plan.bucket);
    acquire_advisory_lock(ctx, &plan.bucket, lock_key)
        .await
        .map_err(RollbackError::Runner)?;

    // 3. Confirm the row exists and is in a rollbackable status — inside
    //    the lock so the status read is atomic with the subsequent write.
    let row_result = load_ledger_row_for_version(ctx, &runner_ctx.version)
        .await
        .map_err(|e| {
            RollbackError::Runner(RunnerError::LedgerQueryFailed {
                query_label: "load_row_for_version",
                source: e,
            })
        });
    let row_opt = match row_result {
        Ok(r) => r,
        Err(e) => {
            let _released = release_advisory_lock(ctx, lock_key).await;
            return Err(e);
        }
    };
    let row = match row_opt {
        Some(r) => r,
        None => {
            let _released = release_advisory_lock(ctx, lock_key).await;
            return Err(RollbackError::VersionNotFound {
                version: runner_ctx.version.clone(),
            });
        }
    };
    // 3a. Verify the ledger row belongs to the same logical app bucket
    //     that owns the advisory lock. An operator-constructed or stale
    //     MigrationPlan whose bucket.app differs from the row's
    //     app_label would mutate the row while holding a lock for the
    //     wrong bucket — the same hazard the repair flow guards
    //     (GH #274 hardening).
    if row.app_label != plan.bucket.app {
        let e = RollbackError::BucketAppMismatch {
            version: runner_ctx.version.clone(),
            row_app_label: row.app_label.clone(),
            supplied_app: plan.bucket.app.clone(),
        };
        let _released = release_advisory_lock(ctx, lock_key).await;
        return Err(e);
    }

    if !matches!(row.status, LedgerStatus::Applied | LedgerStatus::Faked) {
        let current_status = row.status;
        let _released = release_advisory_lock(ctx, lock_key).await;
        return Err(RollbackError::VersionNotRollbackable {
            version: runner_ctx.version.clone(),
            current_status,
        });
    }

    // #366: Pre-strict leaf-identity check — zero-leaf↔non-empty drift.
    if let Some(ref stored_identity) = row.leaf_identity {
        let pre_cache = match compute_leaf_identity_cache(ctx, plan).await {
            Ok(c) => c,
            Err(e) => {
                let _released = release_advisory_lock(ctx, lock_key).await;
                return Err(RollbackError::Runner(e));
            }
        };
        let pre_identity = serialize_leaf_identity(&pre_cache).unwrap_or_default();
        if pre_identity != *stored_identity {
            let e = RollbackError::LeafIdentityMismatch {
                version: runner_ctx.version.clone(),
                stored_leaf_identity: stored_identity.clone(),
                current_leaf_identity: pre_identity,
            };
            let _released = release_advisory_lock(ctx, lock_key).await;
            return Err(e);
        }
    }

    // 5. Materialize strict replay plan inside advisory lock. Partition-expanded
    //    statements are rematerialized from the same execution stream used by apply;
    //    rollback replays reverse down SQL against the expanded stream. Lossy
    //    scanning operates on the materialized plan, not the original unexpanded
    //    plan, so per-leaf lossy markers are properly detected (GH #317).
    let (replay_plan, leaves_cache_rollback) =
        match materialize_execution_plan(ctx, plan, PartitionExpansionMode::ReplayStrict).await {
            Ok((p, cache)) => (p, cache),
            Err(e) => {
                let _released = release_advisory_lock(ctx, lock_key).await;
                return Err(RollbackError::Runner(e));
            }
        };

    // #356: Compare stored leaf identity against freshly materialized leaves.
    let current_rollback_identity =
        serialize_leaf_identity(&leaves_cache_rollback).unwrap_or_default();
    let rollback_leaf_mismatch = if let Some(ref stored_identity) = row.leaf_identity {
        current_rollback_identity != *stored_identity
    } else {
        false
    };
    if rollback_leaf_mismatch {
        let e = RollbackError::LeafIdentityMismatch {
            version: runner_ctx.version.clone(),
            stored_leaf_identity: row.leaf_identity.clone().unwrap(),
            current_leaf_identity: current_rollback_identity,
        };
        let _released = release_advisory_lock(ctx, lock_key).await;
        return Err(e);
    }

    // 5a. Lossy scanning against the materialized (expanded) plan.
    let allow_reason = match rollback_lossy_allow_reason(&replay_plan, &lossy_policy) {
        Ok(r) => r,
        Err(e) => {
            let _released = release_advisory_lock(ctx, lock_key).await;
            return Err(e);
        }
    };

    let result = rollback_inner(ctx, &replay_plan, runner_ctx, prior_snapshot, allow_reason).await;

    let released = release_advisory_lock(ctx, lock_key).await;

    // Mirror handle_release_result for the RollbackError type.
    match (result, released) {
        (Ok(r), true) => {
            ctx.mark_clean();
            Ok(r)
        }
        (Ok(_), false) => Err(RollbackError::Runner(
            RunnerError::AdvisoryUnlockReturnedFalse {
                key: lock_key,
                bucket: plan.bucket.clone(),
            },
        )),
        (Err(e), _) => Err(e),
    }
}

/// Internal rollback core logic — split out so the advisory-lock release
/// runs on every exit branch.
///
/// **Atomicity contract (B-1).** The transactional segments share ONE
/// Postgres transaction, opened before the first segment's down SQL
/// runs and committed after the last. A failure mid-walk rolls back
/// the entire compound — no transactional segment commits in
/// isolation while a peer fails. Non-transactional segments are
/// inherently auto-committed and run before the compound transaction
/// (per the apply-order inversion the v3 plan calls for in T4).
async fn rollback_inner(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    prior_snapshot: Option<&super::schema::AppliedSchema>,
    allow_reason: Option<String>,
) -> Result<RollbackReport, RollbackError> {
    // 5. Walk segments in reverse list order. Apply runs
    //    transactional segments first then non-transactional. Rollback
    //    inverts that:
    //      a. Non-transactional segments first (auto-committed,
    //         REVERSE statement order per segment, REVERSE segment
    //         order across the plan).
    //      b. Transactional segments second, ALL inside a SINGLE
    //         compound Postgres transaction (REVERSE statement order
    //         per segment, REVERSE segment order across the plan).
    //         A failure inside the compound tx aborts the whole tx.
    let mut transactional_undone = 0usize;
    let mut non_transactional_undone = 0usize;

    // Phase a — non-transactional segments, in reverse plan order.
    for (rev_idx, segment) in plan.segments.iter().enumerate().rev() {
        if segment.kind == SegmentKind::NonTransactional {
            rollback_non_transactional_segment(ctx, segment, rev_idx, runner_ctx).await?;
            non_transactional_undone += 1;
        }
    }

    // Phase b — every transactional segment inside ONE Postgres
    // transaction. Open BEGIN once; walk segments in reverse plan
    // order, statements in reverse per segment; ROLLBACK on any
    // failure; COMMIT at the end.
    let has_transactional = plan
        .segments
        .iter()
        .any(|s| s.kind == SegmentKind::Transactional);
    if has_transactional {
        ctx.batch_execute("BEGIN")
            .await
            .map_err(|e| RollbackError::DownStatementFailed {
                segment_index: usize::MAX,
                statement_label: "<BEGIN compound rollback tx>".to_string(),
                source: e,
            })?;

        for (rev_idx, segment) in plan.segments.iter().enumerate().rev() {
            if segment.kind != SegmentKind::Transactional {
                continue;
            }
            for stmt in segment.statements.iter().rev() {
                if stmt.down.is_empty() {
                    continue;
                }
                if let Err(e) = execute_runner_statement(ctx, &stmt.down, runner_ctx).await {
                    // Best-effort ROLLBACK of the whole compound tx —
                    // surface the original error verbatim.
                    let _ = ctx.batch_execute("ROLLBACK").await;
                    return Err(RollbackError::DownStatementFailed {
                        segment_index: rev_idx,
                        statement_label: stmt.label.clone(),
                        source: e,
                    });
                }
            }
            transactional_undone += 1;
        }

        ctx.batch_execute("COMMIT")
            .await
            .map_err(|e| RollbackError::DownStatementFailed {
                segment_index: usize::MAX,
                statement_label: "<COMMIT compound rollback tx>".to_string(),
                source: e,
            })?;
    }

    // 6. Update the ledger row to `rolled_back`. The note records the
    //    rollback timestamp and (when applicable) the lossy reason.
    //
    //    B-2: clear `total_steps` to NULL so a rolled-back row no
    //    longer advertises stale progress. The columns we touch are:
    //      - status              -> 'rolled_back'
    //      - applied_steps_count -> 0
    //      - total_steps         -> NULL
    //      - partial_apply_note  -> rollback record
    let timestamp = OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .unwrap_or_else(|_| "<unknown timestamp>".to_string());
    let note = match allow_reason.as_deref() {
        Some(reason) => format!("rolled back at {timestamp}; lossy reason: {reason}"),
        None => format!("rolled back at {timestamp}"),
    };
    ctx.execute(
        "UPDATE djogi_schema_migrations \
         SET status = 'rolled_back', \
             applied_steps_count = 0, \
             total_steps = NULL, \
             partial_apply_note = $2 \
         WHERE version = $1",
        &[&runner_ctx.version, &note],
    )
    .await
    .map_err(|e| {
        RollbackError::Runner(RunnerError::LedgerWriteFailed {
            version: runner_ctx.version.clone(),
            source: e,
        })
    })?;

    // 7. Persist the prior snapshot, if supplied. The caller maintains
    //    snapshot history; T5 only writes whatever was handed in.
    //
    // The `prior_snapshot.is_none() && snapshot_path.is_some()` case
    // is rejected at the TOP of `rollback_plan` (B-3) — by the time
    // we reach this branch the invariant is "either both are present
    // or `prior_snapshot` is None and `snapshot_path` is also None".
    let mut snapshot_reverted = false;
    if let (Some(snap), Some(path)) = (prior_snapshot, &runner_ctx.snapshot_path) {
        save_snapshot(snap, path).map_err(|e| RollbackError::SnapshotPersistFailed {
            path: path.clone(),
            source: e,
        })?;
        snapshot_reverted = true;
    }

    Ok(RollbackReport {
        transactional_undone,
        non_transactional_undone,
        snapshot_reverted,
        lossy_reason: allow_reason,
    })
}

/// Run every `down` statement in a non-transactional segment, in
/// REVERSE statement order, with autocommit.
async fn rollback_non_transactional_segment(
    ctx: &mut DjogiContext,
    segment: &Segment,
    segment_index: usize,
    runner_ctx: &RunnerCtx,
) -> Result<(), RollbackError> {
    for stmt in segment.statements.iter().rev() {
        if stmt.down.is_empty() {
            continue;
        }
        if let Err(e) = execute_runner_statement(ctx, &stmt.down, runner_ctx).await {
            return Err(RollbackError::DownStatementFailed {
                segment_index,
                statement_label: stmt.label.clone(),
                source: e,
            });
        }
    }
    Ok(())
}

/// Successful rollback report.
#[derive(Debug, Clone)]
pub struct RollbackReport {
    /// Number of transactional segments whose `down` SQL ran.
    pub transactional_undone: usize,
    /// Number of non-transactional segments whose `down` SQL ran.
    pub non_transactional_undone: usize,
    /// `true` when [`save_snapshot`] was invoked with the
    /// caller-supplied prior snapshot.
    pub snapshot_reverted: bool,
    /// Lossy-rollback reason (when the policy was `Allow`). `None`
    /// for clean rollbacks.
    pub lossy_reason: Option<String>,
}

/// Mark a migration version as `faked` — record the row in the ledger
/// without running any SQL.
///
/// **Use case.** An out-of-band tool already applied the schema
/// change (manual SQL, prior dev tooling, restored backup) and the
/// operator wants Djogi's ledger to reflect "this version is
/// considered applied; skip its DDL on a future apply".
///
/// **Snapshot moves forward.** The caller supplies a `snapshot` and
/// `snapshot_path` representing the state Djogi should consider
/// authoritative now. Fake-apply asserts that the schema is in this
/// state without verifying it — the operator owns that verification.
///
/// **Why a separate function.** Keeping fake-apply distinct from
/// `apply_plan` makes the audit trail honest: the ledger row carries
/// `status = 'faked'` (not `applied`) and a `partial_apply_note`
/// describing the operator's reason. Anyone reviewing the ledger
/// later can immediately see the row was not produced by the runner's
/// happy path.
///
/// `reason` is required and persisted to `partial_apply_note`.
pub async fn fake_apply_plan(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    _guard: &WorkspaceGuard,
    reason: &str,
) -> Result<RunReport, RunnerError> {
    // GH #274 / #331 — pin one physical Postgres session (same contract as apply_plan).
    let mut pinned = ctx
        .pin_for_migration()
        .await
        .map_err(|e| RunnerError::PinnedSessionCheckoutFailed { source: e })?;
    fake_apply_pinned(&mut pinned, plan, runner_ctx, reason).await
}

/// Internal fake-apply path that runs on an already-pinned context.
async fn fake_apply_pinned(
    ctx: &mut PinnedCtx<'_>,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    reason: &str,
) -> Result<RunReport, RunnerError> {
    // Same advisory-lock dance as apply_plan; fake-apply still needs
    // exclusive access to the ledger row insertion.
    ledger::bootstrap(ctx)
        .await
        .map_err(|e| RunnerError::LedgerBootstrapFailed { source: e })?;

    let lock_key = advisory_lock_key(&plan.bucket);
    acquire_advisory_lock(ctx, &plan.bucket, lock_key).await?;

    let result = fake_apply_inner(ctx, plan, runner_ctx, reason).await;
    let released = release_advisory_lock(ctx, lock_key).await;
    let result = handle_release_result(result, released, &plan.bucket, lock_key);
    if result.is_ok() {
        ctx.mark_clean();
    }
    result
}

async fn fake_apply_inner(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    runner_ctx: &RunnerCtx,
    reason: &str,
) -> Result<RunReport, RunnerError> {
    let started = Instant::now();

    // Verify checksum still matches the plan — fake-apply does not
    // run SQL but it still records `checksum_up`, and the row is more
    // useful when the recorded checksum reflects the actual plan.
    let computed_up = compute_checksum_for_plan_up(plan);
    if let Err(e) =
        ledger::verify_checksum(&runner_ctx.version, &runner_ctx.checksum_up, &computed_up)
    {
        return Err(match e {
            VerifyError::Mismatch(m) => RunnerError::ChecksumMismatch(m),
            VerifyError::Format(f) => RunnerError::ChecksumFormat(f),
        });
    }

    // Out-of-order detection — fake-apply respects the same policy
    // gate as real apply. A faked row with a suppressed out_of_order_flag
    // would misrepresent the version-ordering state in the ledger.
    let conflicting_peer = find_higher_applied_version(ctx, &plan.bucket, &runner_ctx.version)
        .await
        .map_err(|e| RunnerError::LedgerQueryFailed {
            query_label: "out_of_order_check",
            source: e,
        })?;
    let is_out_of_order = conflicting_peer.is_some();
    if is_out_of_order && !runner_ctx.out_of_order_policy.allows() {
        let (conflicting_version, conflicting_applied_at) =
            conflicting_peer.unwrap_or_else(|| (String::new(), None));
        return Err(RunnerError::OutOfOrderRejected {
            version: runner_ctx.version.clone(),
            conflicting_version,
            conflicting_applied_at,
        });
    }
    if is_out_of_order {
        let (conflicting_version, applied_at) = conflicting_peer
            .as_ref()
            .map(|(v, ts)| (v.as_str(), ts.as_deref()))
            .unwrap_or(("", None));
        tracing::warn!(
            bucket_database = %plan.bucket.database,
            bucket_app = %plan.bucket.app,
            version = %runner_ctx.version,
            conflicting_version,
            conflicting_applied_at = applied_at.unwrap_or("<unknown>"),
            policy = ?runner_ctx.out_of_order_policy,
            "out-of-order fake-apply allowed by policy",
        );
    }

    let timestamp = OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .unwrap_or_else(|_| "<unknown timestamp>".to_string());
    let fake_note = format!("faked at {timestamp}; reason: {reason}");
    // Compose the out-of-order portion using the same function as
    // apply_plan_inner. The fake-apply reason comes first (primary
    // operation); the out-of-order annotation is supplementary context.
    let ooo_note = compose_initial_note(
        is_out_of_order,
        runner_ctx.out_of_order_policy.override_reason(),
        conflicting_peer.as_ref(),
    );
    let note = match ooo_note {
        Some(note_str) => format!("{fake_note}; {note_str}"),
        None => fake_note,
    };
    let run_id = generate_run_id(ctx, &runner_ctx.version).await?;
    // `insert_pending` binds `row.status.as_db_str()` directly, so
    // constructing the row with `LedgerStatus::Faked` writes the
    // correct terminal status in a single INSERT — no post-insert
    // UPDATE needed (cluster-2 simplify Finding 1). The B-4 concern
    // (crash between INSERT and UPDATE leaving a stranded `pending`
    // row) is eliminated because there is now only one DB operation.
    let row = LedgerRow {
        version: runner_ctx.version.clone(),
        description: runner_ctx.description.clone(),
        checksum_up: runner_ctx.checksum_up.clone(),
        checksum_down: runner_ctx.checksum_down.clone(),
        execution_mode: ExecutionMode::Transactional,
        status: LedgerStatus::Faked,
        execution_time_ms: 0,
        out_of_order_flag: is_out_of_order,
        applied_steps_count: 0,
        total_steps: None,
        partial_apply_note: Some(note.clone()),
        run_id,
        snapshot_version: SNAPSHOT_FORMAT_VERSION.to_string(),
        app_label: plan.bucket.app.clone(),
        leaf_identity: None,
    };

    let ledger_id = match ledger::insert_pending(ctx, &row).await {
        Ok(id) => id,
        Err(e) => {
            if is_unique_violation(&e) {
                return Err(classify_duplicate_version_collision(ctx, &runner_ctx.version).await);
            }
            return Err(RunnerError::LedgerWriteFailed {
                version: runner_ctx.version.clone(),
                source: e,
            });
        }
    };

    // Snapshot moves forward when supplied. The write ordering is:
    //   a. W1: ledger row committed as terminal `faked` (already done above).
    //   b. W3: persist snapshot to disk.
    //
    // If (b) fails, the ledger row is `faked` but the snapshot is stale or
    // missing. Recovery: run `djogi migrations compose` (or `attune`) to
    // regenerate the snapshot from the descriptor inventory. The ledger row
    // does not need repair — it correctly records that the migration was
    // faked. See #326 Amendment 3 (W3a/W3b/W3c crash states).
    if let (Some(snapshot), Some(path)) = (&runner_ctx.snapshot, &runner_ctx.snapshot_path) {
        save_snapshot(snapshot, path).map_err(|e| RunnerError::SnapshotPersistFailed {
            path: path.clone(),
            source: e,
        })?;
    }

    let elapsed = elapsed_ms(started);
    Ok(RunReport {
        ledger_id,
        run_id,
        transactional_segments: 0,
        non_transactional_segments: 0,
        metadata_segments: 0,
        execution_time_ms: elapsed,
    })
}

/// Establish a baseline ledger row for an existing database that was
/// created without Djogi (or by an earlier Djogi version).
///
/// **What it does (B-11).** Projects the LIVE database catalog into
/// an [`AppliedSchema`] using the verify-side projection helper, then
/// inserts a single ledger row with `status = 'baseline'`,
/// `checksum_up` derived from the projected schema, and a
/// `description` that includes a `<baseline>` marker. No SQL runs
/// against user tables; the schema is whatever Postgres currently
/// holds, captured exactly. The projection is then persisted to
/// `runner_ctx.snapshot_path` (when provided) as the canonical
/// baseline so future migrations diff against it.
///
/// **The runner DOES NOT trust a caller-supplied snapshot.** Codex
/// review (B-11) flagged that the previous arrangement let an
/// operator baseline an existing schema with a stale snapshot —
/// future diffs then started from the wrong state. To prevent that
/// failure mode, the runner now refuses any caller that pre-fills
/// `runner_ctx.snapshot` and instead always projects fresh.
///
/// **One baseline per bucket.** A bucket should carry at most one
/// `baseline` row in its history. The unique-violation on `version`
/// already enforces this when the operator picks the convention
/// (e.g. `V0__baseline`); the runner does not enforce one-per-bucket
/// itself because the ledger is shared across buckets via `app_label`
/// and the operator owns the version-naming policy.
///
/// `reason` is recorded in `partial_apply_note` so the audit trail
/// captures why the baseline was established.
pub async fn baseline_plan(
    ctx: &mut DjogiContext,
    bucket: &BucketKey,
    runner_ctx: &RunnerCtx,
    _guard: &WorkspaceGuard,
    reason: &str,
) -> Result<RunReport, RunnerError> {
    // B-11: refuse caller-supplied snapshots.
    if runner_ctx.snapshot.is_some() {
        return Err(RunnerError::BaselineSnapshotShouldNotBeProvided);
    }

    // GH #274 / #331 — pin one physical Postgres session (same contract as apply_plan).
    let mut pinned = ctx
        .pin_for_migration()
        .await
        .map_err(|e| RunnerError::PinnedSessionCheckoutFailed { source: e })?;
    baseline_pinned(&mut pinned, bucket, runner_ctx, reason).await
}

/// Internal baseline path that runs on an already-pinned context.
async fn baseline_pinned(
    ctx: &mut PinnedCtx<'_>,
    bucket: &BucketKey,
    runner_ctx: &RunnerCtx,
    reason: &str,
) -> Result<RunReport, RunnerError> {
    ledger::bootstrap(ctx)
        .await
        .map_err(|e| RunnerError::LedgerBootstrapFailed { source: e })?;

    let lock_key = advisory_lock_key(bucket);
    acquire_advisory_lock(ctx, bucket, lock_key).await?;

    let result = baseline_inner(ctx, bucket, runner_ctx, reason).await;
    let released = release_advisory_lock(ctx, lock_key).await;
    let result = handle_release_result(result, released, bucket, lock_key);
    if result.is_ok() {
        ctx.mark_clean();
    }
    result
}

async fn baseline_inner(
    ctx: &mut DjogiContext,
    bucket: &BucketKey,
    runner_ctx: &RunnerCtx,
    reason: &str,
) -> Result<RunReport, RunnerError> {
    let started = Instant::now();

    // B-11: project the live DB into an AppliedSchema. The projection
    // helper is reserved for repair / baseline use — verify uses the
    // same machinery internally. Failures here surface as the typed
    // BaselineProjectionFailed variant so the operator sees that the
    // projection (not the ledger) was the failing step.
    //
    // Bucket-scoped (Codex round-2 B-11): the projection only includes
    // tables that match this bucket's app boundary, so an app's
    // baseline does not capture another app's tables.
    let projected = super::verify::live_schema_for_repair(ctx, bucket)
        .await
        .map_err(|e| RunnerError::BaselineProjectionFailed {
            source: Box::new(e),
        })?;

    // Compute `checksum_up` over a deterministic rendering of the
    // projected schema. Baseline rows do not carry SQL fragments to
    // hash, so we hash the JSON serialization of the projection
    // itself — a content-addressed marker the operator can later
    // re-derive from the same DB state.
    let checksum_up = checksum_for_baseline_snapshot(&projected);

    let timestamp = OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .unwrap_or_else(|_| "<unknown timestamp>".to_string());
    let note = format!(
        "baseline established at {timestamp} for bucket database={db} app={app}; reason: {reason}",
        db = bucket.database,
        app = bucket.app,
    );
    let run_id = generate_run_id(ctx, &runner_ctx.version).await?;
    let row = LedgerRow {
        version: runner_ctx.version.clone(),
        description: format!("<baseline> {}", runner_ctx.description),
        checksum_up: checksum_up.clone(),
        checksum_down: None,
        execution_mode: ExecutionMode::Transactional,
        status: LedgerStatus::Baseline,
        execution_time_ms: 0,
        out_of_order_flag: false,
        applied_steps_count: 0,
        total_steps: None,
        partial_apply_note: Some(note),
        run_id,
        snapshot_version: SNAPSHOT_FORMAT_VERSION.to_string(),
        app_label: bucket.app.clone(),
        leaf_identity: None,
    };
    // `insert_pending` binds `row.status.as_db_str()` directly, so
    // constructing the row with `LedgerStatus::Baseline` writes the
    // correct terminal status in a single INSERT — no post-insert
    // UPDATE needed (cluster-2 simplify Finding 1).
    let ledger_id = match ledger::insert_pending(ctx, &row).await {
        Ok(id) => id,
        Err(e) => {
            if is_unique_violation(&e) {
                return Err(classify_duplicate_version_collision(ctx, &runner_ctx.version).await);
            }
            return Err(RunnerError::LedgerWriteFailed {
                version: runner_ctx.version.clone(),
                source: e,
            });
        }
    };

    // Persist the projected schema as the canonical baseline snapshot
    // when a path was supplied. (Tests that only care about ledger
    // semantics pass `snapshot_path: None`.)
    if let Some(path) = &runner_ctx.snapshot_path {
        save_snapshot(&projected, path).map_err(|e| RunnerError::SnapshotPersistFailed {
            path: path.clone(),
            source: e,
        })?;
    }

    let elapsed = elapsed_ms(started);
    Ok(RunReport {
        ledger_id,
        run_id,
        transactional_segments: 0,
        non_transactional_segments: 0,
        metadata_segments: 0,
        execution_time_ms: elapsed,
    })
}

/// Compute a `V1:<sha256-hex>` checksum over the canonical JSON
/// rendering of an [`AppliedSchema`]. Baseline rows hash the
/// projection itself (no SQL fragments exist for a baseline) so the
/// stored checksum is content-addressed: re-projecting the same DB
/// later must yield the same checksum. Used by `baseline_plan`
/// (B-11) and `repair_snapshot_rebuild` (B-12).
pub(crate) fn checksum_for_baseline_snapshot(schema: &super::schema::AppliedSchema) -> String {
    // serde_json with sorted keys gives a deterministic byte stream;
    // BTreeMap fields in AppliedSchema already serialize alphabetically.
    // Failure here is impossible in practice (in-memory schema -> JSON)
    // but we degrade gracefully to an empty-input checksum if it ever
    // fires so the function stays total.
    let json = serde_json::to_string(schema).unwrap_or_default();
    compute_checksum([json])
}

/// Read a ledger row for a given version. Used by the rollback path
/// to confirm the row is in a state that admits rollback.
///
/// Delegates to [`ledger::load_full_row_by_version`] — the 14-column
/// SELECT and try_get cascade live in ledger.rs to avoid triplication
/// across runner / repair / verify (cluster-2 simplify Finding 3).
async fn load_ledger_row_for_version(
    ctx: &mut DjogiContext,
    version: &str,
) -> Result<Option<LedgerRow>, DjogiError> {
    load_full_row_by_version(ctx, version).await
}

// ── Segment dispatch helpers ──────────────────────────────────────────────

async fn execute_runner_statement(
    ctx: &mut DjogiContext,
    sql: &str,
    runner_ctx: &RunnerCtx,
) -> Result<(), DjogiError> {
    // The generated phase-zero bootstrap seeds Djogi-owned session
    // GUCs before HeerId exists. Keep the carve-out bound to that
    // canonical framework migration; adopter migrations still route
    // through the session-statement guard.
    if runner_ctx.version == super::bootstrap::PHASE_ZERO_VERSION {
        ctx.batch_execute(sql).await
    } else {
        guarded_batch_execute(ctx, sql).await
    }
}

/// Run every statement inside a transactional segment within a
/// single Postgres transaction. On any error, ROLLBACK and surface
/// the failing statement label.
///
/// `segment_index` is the caller's loop index — threaded in so the
/// error variant carries the correct position rather than always
/// reporting `0` (cluster-2 simplify Finding 2).
async fn run_transactional_segment(
    ctx: &mut DjogiContext,
    segment: &Segment,
    segment_index: usize,
    runner_ctx: &RunnerCtx,
    add_table_set: &BTreeSet<String>,
) -> Result<(), RunnerError> {
    // T9 verification segment short-circuit: when every statement
    // in this segment carries a `PkFlipVerify` label the segment is
    // a halt-point gate, not DDL. Run each as a `query_one` against
    // a `SELECT count(*)` body and assert the count is zero.
    // No BEGIN/COMMIT — the queries are read-only.
    let all_verify = !segment.statements.is_empty()
        && segment
            .statements
            .iter()
            .all(|s| s.label.starts_with("PkFlipVerify "));
    if all_verify {
        for stmt in &segment.statements {
            // Recover the table from the label format "PkFlipVerify
            // <table> <hint>". `<table>` is the second whitespace-
            // separated token.
            let table = stmt
                .label
                .split_whitespace()
                .nth(1)
                .unwrap_or("")
                .to_string();
            let row = ctx.query_one(&stmt.up, &[]).await.map_err(|e| {
                RunnerError::TransactionalSegmentFailed {
                    segment_index,
                    statement_label: stmt.label.clone(),
                    source: e,
                }
            })?;
            let count: i64 = row.try_get(0).unwrap_or(0);
            if count > 0 {
                return Err(RunnerError::PkFlipVerificationFailed {
                    table,
                    count_violating: count,
                });
            }
        }
        return Ok(());
    }

    // Probe relpages for any AddIndex statement that does NOT
    // require out-of-transaction. The probe runs BEFORE BEGIN so
    // the abort path on `strict_concurrent_warnings` doesn't leave
    // an open transaction around.
    for stmt in &segment.statements {
        if let Some((index_name, target_table)) = parse_create_index_statement(stmt) {
            relpages_probe(ctx, runner_ctx, &index_name, &target_table, add_table_set).await?;
        }
    }

    ctx.batch_execute("BEGIN")
        .await
        .map_err(|e| RunnerError::TransactionalSegmentFailed {
            segment_index,
            statement_label: "<BEGIN>".to_string(),
            source: e,
        })?;

    for stmt in &segment.statements {
        if let Err(e) = execute_runner_statement(ctx, &stmt.up, runner_ctx).await {
            // Best-effort rollback — surface the original error
            // regardless of whether the rollback succeeds.
            let _ = ctx.batch_execute("ROLLBACK").await;
            return Err(RunnerError::TransactionalSegmentFailed {
                segment_index,
                statement_label: stmt.label.clone(),
                source: e,
            });
        }
    }

    ctx.batch_execute("COMMIT")
        .await
        .map_err(|e| RunnerError::TransactionalSegmentFailed {
            segment_index,
            statement_label: "<COMMIT>".to_string(),
            source: e,
        })?;

    Ok(())
}

/// Run every statement in a non-transactional segment with autocommit.
/// Before each step, durably claim the boundary in
/// `partial_apply_note`; after the SQL commits, durably acknowledge
/// the new `applied_steps_count`. If the post-DDL ack fails, the
/// claim note remains in place so repair resume refuses to re-run the
/// ambiguous step automatically.
///
/// Returns the number of steps completed within this segment so the
/// outer runner can update its running tally of cross-segment progress.
struct NonTransactionalSegmentRun<'a> {
    segment_index: usize,
    version: &'a str,
    ledger_id: i64,
    prior_steps_completed: i32,
    total_non_tx_steps: i32,
    stable_note: Option<&'a str>,
    runner_ctx: &'a RunnerCtx,
}

async fn run_non_transactional_segment(
    ctx: &mut DjogiContext,
    segment: &Segment,
    run: NonTransactionalSegmentRun<'_>,
) -> Result<i32, RunnerError> {
    let mut completed: i32 = 0;
    for (step_idx, stmt) in segment.statements.iter().enumerate() {
        let claimed_step = run
            .prior_steps_completed
            .saturating_add(completed)
            .saturating_add(1);
        let claim_note = ledger::format_non_tx_progress_claim(
            run.stable_note,
            claimed_step,
            Some(run.total_non_tx_steps),
            run.segment_index,
            &stmt.label,
        );
        ledger::claim_non_tx_progress(ctx, run.ledger_id, &claim_note)
            .await
            .map_err(|e| RunnerError::LedgerWriteFailed {
                version: run.version.to_string(),
                source: e,
            })?;
        if let Err(e) = execute_runner_statement(ctx, &stmt.up, run.runner_ctx).await {
            let total_so_far = run.prior_steps_completed.saturating_add(completed);
            let note = format!(
                "non-tx step {step} of segment {seg} failed: {label}{e}",
                step = step_idx + 1,
                seg = run.segment_index,
                label = stmt.label,
            );
            // Best-effort partial-state record. If the ledger update
            // itself fails, we still surface the original step
            // failure — the partial-state record is forensic only.
            let _ = ledger::mark_partial(ctx, run.ledger_id, total_so_far, &note).await;
            return Err(RunnerError::NonTransactionalSegmentFailed {
                segment_index: run.segment_index,
                step_index: step_idx,
                statement_label: stmt.label.clone(),
                applied_steps_count: total_so_far,
                source: e,
            });
        }
        completed = completed.saturating_add(1);
        let total_so_far = run.prior_steps_completed.saturating_add(completed);
        ledger::ack_non_tx_progress(ctx, run.ledger_id, total_so_far, run.stable_note)
            .await
            .map_err(|e| RunnerError::NonTransactionalProgressAckFailed {
                segment_index: run.segment_index,
                step_index: step_idx,
                statement_label: stmt.label.clone(),
                applied_steps_count: total_so_far,
                source: e,
            })?;
    }
    Ok(completed)
}

// ── Advisory lock + relpages probe ────────────────────────────────────────

/// Derive a stable 64-bit advisory-lock key from a `BucketKey`. Uses
/// SHA-256 truncated to the low 64 bits for a fixed-seed hash —
/// stdlib `Hasher` is randomised per process and cannot be used.
///
/// **Byte order: big-endian.** The Phase 7 v3 contract pins
/// big-endian decoding of the first 8 SHA-256 digest bytes so an
/// alternate-language implementation following the same spec
/// computes the identical `i64` and contends correctly with this
/// runner. Network byte order is the spec; little-endian would key
/// the same bucket to a different value across implementations.
///
/// Format: `SHA256("djogi:advisory_lock:" || database || "\0" || app)`,
/// then take the first 8 digest bytes as a big-endian signed 64-bit
/// integer (Postgres `bigint`). The `djogi:advisory_lock:` prefix
/// scopes the keyspace so we cannot collide with adopter-side
/// advisory locks that hash arbitrary identifiers.
pub fn advisory_lock_key(bucket: &BucketKey) -> i64 {
    let mut hasher = Sha256::new();
    hasher.update(b"djogi:advisory_lock:");
    hasher.update(bucket.database.as_bytes());
    hasher.update(b"\x00");
    hasher.update(bucket.app.as_bytes());
    let digest = hasher.finalize();
    let mut buf = [0u8; 8];
    buf.copy_from_slice(&digest[..8]);
    i64::from_be_bytes(buf)
}

/// Acquire a Postgres advisory lock on `key`.
///
/// Postgres `pg_advisory_lock(bigint)` blocks indefinitely; this
/// function uses `pg_try_advisory_lock(bigint)` in a bounded retry
/// loop so a stuck holder cannot wedge the runner.
///
/// **Session contract (GH #274).** This function MUST be called on
/// a pinned `DjogiContext` — i.e., one backed by a single checked-out
/// `PgConnection`. Postgres session-level advisory locks are bound to
/// the physical backend that issued the SQL; calling this on a
/// pool-backed context would acquire the lock on connection A, but
/// subsequent DDL/ledger operations would run on B, C, … and the
/// `release_advisory_lock` call would return false when invoked on any
/// connection other than A. Runner entry points (`apply_plan`,
/// `rollback_plan`, `fake_apply_plan`, `baseline_plan`) and repair
/// entry points in `migrate::repair` enforce this by pinning a
/// connection from the pool before calling here.
pub(crate) async fn acquire_advisory_lock(
    ctx: &mut PinnedCtx<'_>,
    bucket: &BucketKey,
    key: i64,
) -> Result<(), RunnerError> {
    // GH #331 [H-331-1] — hard assert in ALL build profiles.
    assert!(
        !ctx.is_pool_backed(),
        "acquire_advisory_lock called on a pool-backed context — \
         the advisory lock would be acquired on an arbitrary pool \
         connection and subsequent operations would run on different \
         connections. Callers must use ctx.pin_for_migration() first \
         (GH #274 / #331).",
    );
    const MAX_ATTEMPTS: u32 = 600; // 600 * 50 ms = 30 s
    const RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);
    for attempt in 0..MAX_ATTEMPTS {
        let row = ctx
            .query_one("SELECT pg_try_advisory_lock($1)", &[&key])
            .await
            .map_err(|e| RunnerError::AdvisoryLockQueryFailed {
                app_label: bucket.app.clone(),
                source: e,
            })?;
        let acquired: bool = row
            .try_get(0)
            .map_err(|e| RunnerError::AdvisoryLockQueryFailed {
                app_label: bucket.app.clone(),
                source: DjogiError::from(e),
            })?;
        if acquired {
            return Ok(());
        }
        tokio::time::sleep(RETRY_INTERVAL).await;
        if attempt + 1 == MAX_ATTEMPTS {
            return Err(RunnerError::AdvisoryLockFailed {
                bucket: bucket.clone(),
                key,
                attempts: MAX_ATTEMPTS,
            });
        }
    }
    // Unreachable in practice — the loop body returns on every
    // iteration. This is a defensive fallback to keep the function
    // total against future loop edits.
    Err(RunnerError::AdvisoryLockFailed {
        bucket: bucket.clone(),
        key,
        attempts: MAX_ATTEMPTS,
    })
}

/// Release a previously-acquired advisory lock.
///
/// Returns `true` when `pg_advisory_unlock` confirms the lock was
/// held and released. Returns `false` when `pg_advisory_unlock`
/// returns `false` — meaning the lock was NOT held on this physical
/// session. A `false` return is a session-pinning correctness failure
/// (GH #274 / #280): the lock was either acquired on a different
/// connection or never acquired at all.
///
/// When the unlock query itself fails (e.g. the connection closed),
/// this function logs a `tracing::warn!` and returns `true` — the
/// session death will release the lock anyway and the warn is the
/// observable signal.
///
/// **Callers must always invoke this function even when the migration
/// operation errored.** Use [`handle_release_result`] to reconcile
/// the operation result with the bool returned here: if the operation
/// succeeded but this returns `false`, surface
/// [`RunnerError::AdvisoryUnlockReturnedFalse`]; if both errored,
/// log this result and return the original error.
pub(crate) async fn release_advisory_lock(ctx: &mut PinnedCtx<'_>, key: i64) -> bool {
    assert!(
        !ctx.is_pool_backed(),
        "release_advisory_lock called on a pool-backed context — \
         the unlock would run on a different connection than the one \
         that holds the lock. Callers must use ctx.pin_for_migration() \
         first (GH #274 / #331).",
    );
    let row = match ctx
        .query_one("SELECT pg_advisory_unlock($1)", &[&key])
        .await
    {
        Ok(r) => r,
        Err(e) => {
            // Query failure likely means the connection died; Postgres will
            // auto-release the lock when the backend exits.
            tracing::warn!(
                ?e,
                key,
                "pg_advisory_unlock query failed; lock will auto-release on session close",
            );
            return true;
        }
    };
    let released: bool = match row.try_get(0) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(
                ?e,
                key,
                "pg_advisory_unlock result could not be decoded; assuming released",
            );
            return true;
        }
    };
    if !released {
        // This is a session-pinning correctness failure: pg_advisory_unlock
        // returned false, meaning the lock was NOT held on this session.
        // Log at error level so it is never silently swallowed. Callers are
        // responsible for converting this to a typed RunnerError or RepairError.
        tracing::error!(
            key,
            "pg_advisory_unlock returned false — lock was not held on this Postgres \
             session. This indicates a session-pinning bug: the advisory lock was \
             acquired on a different physical backend than the one executing the \
             migration operations (GH #274/#280).",
        );
    }
    released
}

/// Reconcile an operation result with the advisory lock release outcome.
///
/// # Behaviour matrix
///
/// | Operation | Release | Result |
/// |-----------|---------|--------|
/// | `Ok`  | `true`  | `Ok` (success, lock properly released) |
/// | `Ok`  | `false` | `Err(AdvisoryUnlockReturnedFalse)` — correctness failure |
/// | `Err` | `true`  | `Err` — original operation error |
/// | `Err` | `false` | `Err` — original error; release failure already logged |
///
/// The `false` case on the success path is the hard correctness failure
/// added by GH #274 / #280: it means the migration SQL may have run but
/// the advisory lock was not protecting it on the correct session.
// RunnerError is a large enum by design (it carries full operator context in
// every variant). Async callers return it through boxed futures so clippy
// does not flag them; this sync helper also returns it and needs the
// suppression. Same rationale as reset.rs / compose.rs.
#[allow(clippy::result_large_err)]
pub(crate) fn handle_release_result<T>(
    result: Result<T, RunnerError>,
    released: bool,
    bucket: &BucketKey,
    key: i64,
) -> Result<T, RunnerError> {
    match result {
        Ok(v) if released => Ok(v),
        Ok(_) => Err(RunnerError::AdvisoryUnlockReturnedFalse {
            key,
            bucket: bucket.clone(),
        }),
        Err(e) => Err(e), // release false already logged inside release_advisory_lock
    }
}

/// Run the relpages probe before a transactional `CREATE INDEX`.
/// On WARN path: emit `tracing::warn!` and continue. On strict path
/// (`migrate.strict_concurrent_warnings = true`): surface
/// `RunnerError::RelpagesThresholdExceeded`.
///
/// **`pg_class.relpages = None` disambiguation.** A `None` row from
/// the probe means Postgres does not currently know about the table.
/// Two legitimate cases produce that:
///
/// 1. The current plan creates the table in an earlier segment of
///    THIS run (`AddTable` statement). The runner treats this as
///    `relpages = 0` (a freshly-created empty table cannot exceed
///    the threshold).
/// 2. The table genuinely does not exist and is not being created.
///    That is a typo / mis-quoted identifier — the index would fail
///    inside `BEGIN` anyway, but the strict-mode probe catches it
///    earlier with a clearer `TargetTableNotFound` diagnostic.
///
/// Silently dropping case 2 to `relpages = 0` would disable the
/// strict warning path for any mis-targeted `CREATE INDEX`, which
/// is exactly the failure mode strict-mode exists to catch.
async fn relpages_probe(
    ctx: &mut DjogiContext,
    runner_ctx: &RunnerCtx,
    index_name: &str,
    target_table: &str,
    add_table_set: &BTreeSet<String>,
) -> Result<(), RunnerError> {
    let row_opt = ctx
        .query_opt(
            "SELECT relpages FROM pg_class WHERE relname = $1 AND relkind = 'r'",
            &[&target_table],
        )
        .await
        .map_err(|e| RunnerError::CatalogQueryFailed {
            query_label: "pg_class relpages",
            source: e,
        })?;
    let relpages: i32 = match row_opt {
        Some(r) => r
            .try_get::<_, i32>(0)
            .map_err(|e| RunnerError::CatalogQueryFailed {
                query_label: "pg_class relpages",
                source: DjogiError::from(e),
            })?,
        // Table not found in pg_class — distinguish the two legitimate
        // cases (see fn doc).
        None => {
            if add_table_set.contains(target_table) {
                // Case 1: table is being CREATEd in this same plan;
                // relpages of a yet-uncommitted CREATE TABLE is
                // undefined. Treat as 0 so the warn path does not
                // fire.
                0
            } else {
                // Case 2: hard error. The plan does not create this
                // table and Postgres does not know about it.
                return Err(RunnerError::TargetTableNotFound {
                    bucket: runner_ctx.bucket.clone(),
                    index_name: index_name.to_string(),
                    target_table: target_table.to_string(),
                });
            }
        }
    };
    let threshold = runner_ctx.config.concurrent_warn_relpages;
    if (relpages as i64) > (threshold as i64) {
        if runner_ctx.config.strict_concurrent_warnings {
            return Err(RunnerError::RelpagesThresholdExceeded {
                bucket: runner_ctx.bucket.clone(),
                index_name: index_name.to_string(),
                target_table: target_table.to_string(),
                relpages,
                threshold,
            });
        } else {
            tracing::warn!(
                bucket_database = %runner_ctx.bucket.database,
                bucket_app = %runner_ctx.bucket.app,
                index_name,
                target_table,
                relpages,
                threshold,
                "transactional CREATE INDEX on a large table will hold ACCESS EXCLUSIVE \
                 for the duration; consider opting into CREATE INDEX CONCURRENTLY",
            );
        }
    }
    Ok(())
}

/// **T9 pre-flight gate** — run before any side effect when the
/// plan is a PK-type-flip migration.
///
/// Implements D060–D063 from the v3 plan §T9 contract:
///
/// - **D060** Logical-replication machinery active — `pg_stat_replication`
///   walsenders OR enabled rows in `pg_subscription` for the current
///   database → refusal. Postgres does not expose another backend's
///   `session_replication_role` GUC via `pg_stat_activity`, so we
///   detect the apply machinery itself rather than the GUC value.
/// - **D061** Pre-existing `zzz_*` triggers on the migrating tables
///   → refusal (collision with the autofill install).
/// - **D062** Already-disabled triggers on the migrating tables
///   → refusal.
/// - **D063** Open transactions older than the configured threshold
///   → refusal.
///
/// The set of "migrating tables" is recovered from the cutover
/// segment's labels — every `PkFlipPrep` / `PkFlipCutover` /
/// `PkFlipBackfill` / `PkFlipConcurrentIndex` / `PkFlipNotNullProof`
/// label carries the parent table name as its trailing token; we
/// also collect every child table name from the multi-segment SQL
/// via byte-level identifier scanning of the `up` text. This avoids
/// re-walking the descriptor here — the segment plan already carries
/// the full set the cutover will touch.
///
/// **No regex** — the table-name extraction uses byte-level forward
/// scans for `ALTER TABLE <ident> ` literal substrings; the
/// identifier rules (ASCII letter or underscore, then alphanumerics
/// or underscore, ≤ 63 bytes) are spelled out in plain English in
/// the helper.
async fn pk_flip_preflight(
    ctx: &mut DjogiContext,
    runner_ctx: &RunnerCtx,
    plan: &MigrationPlan,
) -> Result<(), RunnerError> {
    // Recover migrating tables from the segment plan. The label
    // format is `PkFlip<Stage> <parent>` (no spaces in the parent
    // identifier per descriptor / projection enforcement).
    let mut tables: BTreeSet<String> = BTreeSet::new();
    for seg in &plan.segments {
        for stmt in &seg.statements {
            if let Some(parent) = stmt.label.strip_prefix("PkFlipPrep ") {
                tables.insert(parent.to_string());
            } else if let Some(parent) = stmt.label.strip_prefix("PkFlipCutover ") {
                tables.insert(parent.to_string());
            } else if let Some(parent) = stmt.label.strip_prefix("PkFlipPartitionedPrep ") {
                tables.insert(parent.to_string());
            }
            // Scan `ALTER TABLE <ident>` to recover child tables.
            for child in scan_alter_table_targets(&stmt.up) {
                tables.insert(child);
            }
        }
    }

    // D060 — logical-replication machinery active in this DB.
    //
    // Why the indirection: Postgres does not let one backend read
    // another backend's `session_replication_role` GUC from
    // `pg_stat_activity`. The playbook §12.3 hazard names "Logical
    // replication apply workers" as the concrete failure mode, and
    // those are observable via:
    //   - `pg_stat_replication` — every active walsender (the apply
    //     side runs with role = 'replica' by default).
    //   - `pg_subscription`     — subscriptions with `subenabled =
    //     true` indicate an apply worker may be running in this DB.
    //
    // We surface BOTH as the D060 hazard so the operator knows which
    // signal fired. Either alone is sufficient to refuse.
    let walsender_rows = ctx
        .query_all(
            "SELECT COALESCE(application_name, ''), COALESCE(client_addr::text, '') \
             FROM pg_stat_replication",
            &[],
        )
        .await
        .map_err(|e| RunnerError::CatalogQueryFailed {
            query_label: "pg_stat_replication",
            source: e,
        })?;
    let mut walsenders: Vec<(String, String)> = Vec::with_capacity(walsender_rows.len());
    for r in &walsender_rows {
        let app: String = r.try_get(0).unwrap_or_default();
        let client: String = r.try_get(1).unwrap_or_default();
        walsenders.push((app, client));
    }

    let sub_rows = ctx
        .query_all(
            "SELECT subname FROM pg_subscription \
             WHERE subdbid = (SELECT oid FROM pg_database WHERE datname = current_database()) \
               AND subenabled = true",
            &[],
        )
        .await
        .map_err(|e| RunnerError::CatalogQueryFailed {
            query_label: "pg_subscription",
            source: e,
        })?;
    let mut subscriptions: Vec<String> = Vec::with_capacity(sub_rows.len());
    for r in &sub_rows {
        let name: String = r.try_get(0).unwrap_or_default();
        subscriptions.push(name);
    }

    if !walsenders.is_empty() || !subscriptions.is_empty() {
        return Err(RunnerError::PkFlipHazardReplicaSessions {
            walsenders,
            subscriptions,
        });
    }

    // D061 + D062 — per-table trigger checks.
    for table in &tables {
        // The LIKE pattern `zzz\_%` uses `\` as an explicit escape
        // character (NOT regex) so the `_` is a literal underscore
        // rather than the LIKE wildcard.
        let zzz_rows = ctx
            .query_all(
                "SELECT tgname FROM pg_trigger \
                 WHERE tgrelid = (SELECT oid FROM pg_class WHERE relname = $1 AND relkind = 'r' LIMIT 1) \
                   AND NOT tgisinternal \
                   AND tgname LIKE 'zzz\\_%' ESCAPE '\\'",
                &[table],
            )
            .await
            .map_err(|e| RunnerError::CatalogQueryFailed {
                query_label: "pg_trigger zzz scan",
                source: e,
            })?;
        if !zzz_rows.is_empty() {
            let names: Vec<String> = zzz_rows
                .iter()
                .map(|r| r.try_get::<_, String>(0).unwrap_or_default())
                .collect();
            return Err(RunnerError::PkFlipHazardPreexistingZzzTrigger {
                table: table.clone(),
                trigger_names: names,
            });
        }
        let disabled_rows = ctx
            .query_all(
                "SELECT tgname, tgenabled FROM pg_trigger \
                 WHERE tgrelid = (SELECT oid FROM pg_class WHERE relname = $1 AND relkind = 'r' LIMIT 1) \
                   AND NOT tgisinternal \
                   AND tgenabled <> 'O'",
                &[table],
            )
            .await
            .map_err(|e| RunnerError::CatalogQueryFailed {
                query_label: "pg_trigger disabled scan",
                source: e,
            })?;
        if !disabled_rows.is_empty() {
            let mut triggers: Vec<(String, char)> = Vec::with_capacity(disabled_rows.len());
            for r in &disabled_rows {
                let name: String = r.try_get(0).unwrap_or_default();
                let raw: i8 = r.try_get(1).unwrap_or(0);
                // tgenabled is a single-byte CHAR (Postgres `char`)
                // mapped to Rust as `i8`; valid values are 'O', 'D',
                // 'R', 'A' — all positive ASCII. Re-interpret as
                // unsigned without bounds-checking the high half
                // because i8 cannot exceed 127.
                let ch = if raw >= 0 { (raw as u8) as char } else { '?' };
                triggers.push((name, ch));
            }
            return Err(RunnerError::PkFlipHazardDisabledTriggers {
                table: table.clone(),
                triggers,
            });
        }
    }

    // D063 — long-running transactions.
    let threshold = runner_ctx.config.pk_flip_long_tx_threshold_secs;
    if threshold > 0 {
        let long_rows = ctx
            .query_all(
                "SELECT pid, EXTRACT(EPOCH FROM (now() - xact_start))::bigint AS age \
                 FROM pg_stat_activity \
                 WHERE pid <> pg_backend_pid() \
                   AND xact_start IS NOT NULL \
                   AND now() - xact_start > make_interval(secs => $1::int)",
                &[&(threshold as i32)],
            )
            .await
            .map_err(|e| RunnerError::CatalogQueryFailed {
                query_label: "pg_stat_activity long tx scan",
                source: e,
            })?;
        if !long_rows.is_empty() {
            let mut offenders: Vec<(i32, i64)> = Vec::with_capacity(long_rows.len());
            for r in &long_rows {
                let pid: i32 = r.try_get(0).unwrap_or(0);
                let age: i64 = r.try_get(1).unwrap_or(0);
                offenders.push((pid, age));
            }
            return Err(RunnerError::PkFlipHazardLongRunningTx {
                offenders,
                threshold_secs: threshold,
            });
        }
    }

    Ok(())
}

/// Recover every table name appearing immediately after an
/// `ALTER TABLE` token in `sql`. Byte-level forward scan; no regex.
///
/// Identifier rule: ASCII letter or underscore as the first byte,
/// then ASCII alphanumerics or underscores, up to 63 bytes (the
/// Postgres `NAMEDATALEN - 1` ceiling). We accept double-quoted
/// identifiers too — the inner contents are passed through verbatim
/// (the descriptor / projection layer guarantees identifier shape
/// upstream so the contents survive interpretation as a plain
/// table name in `pg_class`).
fn scan_alter_table_targets(sql: &str) -> Vec<String> {
    const MARKER: &[u8] = b"ALTER TABLE ";
    let bytes = sql.as_bytes();
    let mut out: Vec<String> = Vec::new();
    let mut i = 0usize;
    while i + MARKER.len() <= bytes.len() {
        if &bytes[i..i + MARKER.len()] == MARKER {
            let start = i + MARKER.len();
            // Identifier may be plain or double-quoted.
            let (id, end) = if start < bytes.len() && bytes[start] == b'"' {
                let id_start = start + 1;
                let mut j = id_start;
                while j < bytes.len() && bytes[j] != b'"' {
                    j += 1;
                }
                if j > id_start && j < bytes.len() {
                    (
                        String::from_utf8_lossy(&bytes[id_start..j]).into_owned(),
                        j + 1,
                    )
                } else {
                    (String::new(), bytes.len())
                }
            } else {
                let id_start = start;
                let mut j = id_start;
                let mut len = 0usize;
                while j < bytes.len() && len < 63 {
                    let b = bytes[j];
                    let valid = if len == 0 {
                        b.is_ascii_alphabetic() || b == b'_'
                    } else {
                        b.is_ascii_alphanumeric() || b == b'_'
                    };
                    if !valid {
                        break;
                    }
                    j += 1;
                    len += 1;
                }
                if j > id_start {
                    (String::from_utf8_lossy(&bytes[id_start..j]).into_owned(), j)
                } else {
                    (String::new(), j)
                }
            };
            if !id.is_empty() {
                out.push(id);
            }
            i = end;
        } else {
            i += 1;
        }
    }
    out
}

// ── Helpers ───────────────────────────────────────────────────────────────

fn segment_kind_name(kind: SegmentKind) -> &'static str {
    match kind {
        SegmentKind::Transactional => "transactional",
        SegmentKind::NonTransactional => "non-transactional",
        SegmentKind::MetadataOnly => "metadata-only",
    }
}

#[allow(clippy::result_large_err)]
fn preflight_segment_sql_execution_compatibility(plan: &MigrationPlan) -> Result<(), RunnerError> {
    for (segment_index, segment) in plan.segments.iter().enumerate() {
        if segment.kind == SegmentKind::MetadataOnly {
            continue;
        }
        for statement in &segment.statements {
            if let Some(problem) =
                classify_segment_sql_execution_mode_problem(segment.kind, &statement.up)
            {
                return Err(RunnerError::SegmentSqlExecutionModeConflict {
                    segment_index,
                    segment_kind: segment.kind,
                    statement_label: statement.label.clone(),
                    problem,
                });
            }
        }
    }
    Ok(())
}

fn classify_segment_sql_execution_mode_problem(
    segment_kind: SegmentKind,
    sql: &str,
) -> Option<SegmentSqlExecutionModeProblem> {
    let bytes = sql.as_bytes();
    let mut idx = 0usize;
    let first = next_sql_leading_keyword(bytes, &mut idx)?;
    let second = next_sql_leading_keyword(bytes, &mut idx);
    let third = next_sql_leading_keyword(bytes, &mut idx);
    let fourth = next_sql_leading_keyword(bytes, &mut idx);

    if token_eq(first, "BEGIN") {
        return Some(SegmentSqlExecutionModeProblem::TransactionControl { keyword: "BEGIN" });
    }
    if token_eq(first, "START") && second.is_some_and(|tok| token_eq(tok, "TRANSACTION")) {
        return Some(SegmentSqlExecutionModeProblem::TransactionControl {
            keyword: "START TRANSACTION",
        });
    }
    if token_eq(first, "COMMIT") {
        return Some(SegmentSqlExecutionModeProblem::TransactionControl { keyword: "COMMIT" });
    }
    if token_eq(first, "ROLLBACK") {
        return Some(SegmentSqlExecutionModeProblem::TransactionControl {
            keyword: "ROLLBACK",
        });
    }
    if token_eq(first, "SAVEPOINT") {
        return Some(SegmentSqlExecutionModeProblem::TransactionControl {
            keyword: "SAVEPOINT",
        });
    }
    if token_eq(first, "RELEASE") && second.is_some_and(|tok| token_eq(tok, "SAVEPOINT")) {
        return Some(SegmentSqlExecutionModeProblem::TransactionControl {
            keyword: "RELEASE SAVEPOINT",
        });
    }

    if segment_kind != SegmentKind::Transactional {
        return None;
    }

    if token_eq(first, "CREATE")
        && second.is_some_and(|tok| token_eq(tok, "INDEX"))
        && third.is_some_and(|tok| token_eq(tok, "CONCURRENTLY"))
    {
        return Some(SegmentSqlExecutionModeProblem::RequiresNonTransactional {
            statement_shape: "CREATE INDEX CONCURRENTLY",
        });
    }
    if token_eq(first, "CREATE")
        && second.is_some_and(|tok| token_eq(tok, "UNIQUE"))
        && third.is_some_and(|tok| token_eq(tok, "INDEX"))
        && fourth.is_some_and(|tok| token_eq(tok, "CONCURRENTLY"))
    {
        return Some(SegmentSqlExecutionModeProblem::RequiresNonTransactional {
            statement_shape: "CREATE UNIQUE INDEX CONCURRENTLY",
        });
    }
    if token_eq(first, "DROP")
        && second.is_some_and(|tok| token_eq(tok, "INDEX"))
        && third.is_some_and(|tok| token_eq(tok, "CONCURRENTLY"))
    {
        return Some(SegmentSqlExecutionModeProblem::RequiresNonTransactional {
            statement_shape: "DROP INDEX CONCURRENTLY",
        });
    }

    None
}

fn next_sql_leading_keyword<'a>(bytes: &'a [u8], idx: &mut usize) -> Option<&'a [u8]> {
    skip_sql_leading_ws_and_comments(bytes, idx);
    if *idx >= bytes.len() || !is_sql_ident_start(bytes[*idx]) {
        return None;
    }
    let start = *idx;
    *idx += 1;
    while *idx < bytes.len() && is_sql_ident_continue(bytes[*idx]) {
        *idx += 1;
    }
    Some(&bytes[start..*idx])
}

fn skip_sql_leading_ws_and_comments(bytes: &[u8], idx: &mut usize) {
    loop {
        while *idx < bytes.len() && bytes[*idx].is_ascii_whitespace() {
            *idx += 1;
        }
        if *idx + 1 < bytes.len() && bytes[*idx] == b'-' && bytes[*idx + 1] == b'-' {
            *idx += 2;
            while *idx < bytes.len() && bytes[*idx] != b'\n' {
                *idx += 1;
            }
            continue;
        }
        if *idx + 1 < bytes.len() && bytes[*idx] == b'/' && bytes[*idx + 1] == b'*' {
            *idx += 2;
            let mut depth = 1usize;
            while *idx < bytes.len() && depth > 0 {
                if *idx + 1 < bytes.len() && bytes[*idx] == b'/' && bytes[*idx + 1] == b'*' {
                    depth += 1;
                    *idx += 2;
                    continue;
                }
                if *idx + 1 < bytes.len() && bytes[*idx] == b'*' && bytes[*idx + 1] == b'/' {
                    depth -= 1;
                    *idx += 2;
                    continue;
                }
                *idx += 1;
            }
            continue;
        }
        return;
    }
}

fn is_sql_ident_start(byte: u8) -> bool {
    byte.is_ascii_alphabetic() || byte == b'_'
}

fn is_sql_ident_continue(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'_'
}

fn token_eq(token: &[u8], expected: &str) -> bool {
    token.eq_ignore_ascii_case(expected.as_bytes())
}

/// Compute the `up`-side checksum across every segment's statements.
/// Concatenates each statement's `up` SQL with `\n` separators in
/// segment-then-statement order. Mirrors the runner_ctx pre-compute
/// path so the two sides match by construction.
fn compute_checksum_for_plan_up(plan: &MigrationPlan) -> String {
    let fragments: Vec<&str> = plan
        .segments
        .iter()
        .flat_map(|s| s.statements.iter())
        .map(|s| s.up.as_str())
        .collect();
    compute_checksum(fragments)
}

/// Lift an `OperationSql` into a `(index_name, target_table)` pair if
/// the statement is a transactional `CREATE INDEX`. Returns `None`
/// for any other operation.
///
/// The label format is set by the SQL emitter — `AddIndex <name>`
/// for new indexes (see `sql.rs::emit_add_index`). The table name is
/// recovered from the SQL's `ON "<table>"` clause via byte-level
/// scanning — explicit forward scan over the bytes, no
/// pattern-matching engine.
fn parse_create_index_statement(stmt: &OperationSql) -> Option<(String, String)> {
    // Only AddIndex labels are eligible. The DropIndex labels start
    // with "DropIndex" so they cannot collide.
    let label = stmt.label.as_str();
    let index_name = label.strip_prefix("AddIndex ")?.to_string();

    // Extract the table name by scanning for the literal ` ON "`
    // marker followed by the quoted table name. Postgres `CREATE
    // INDEX` SQL always emits `ON "<table>"` — see emit_add_index.
    // Byte-level forward scan; no pattern-matching engine.
    let bytes = stmt.up.as_bytes();
    let needle = b" ON \"";
    let mut i = 0usize;
    while i + needle.len() <= bytes.len() {
        if &bytes[i..i + needle.len()] == needle {
            let start = i + needle.len();
            // Find the closing quote.
            let mut j = start;
            while j < bytes.len() && bytes[j] != b'"' {
                j += 1;
            }
            if j > start && j < bytes.len() {
                // SAFETY: we restricted the byte range to
                // identifier characters (Postgres double-quoted
                // identifier — ASCII alphanumerics + underscores +
                // some punctuation; never invalid UTF-8 in practice
                // because identifiers are ASCII). Falling back to
                // the lossy converter keeps this fn total.
                let table = String::from_utf8_lossy(&bytes[start..j]).into_owned();
                return Some((index_name, table));
            }
            return None;
        }
        i += 1;
    }
    None
}

/// Build the initial `partial_apply_note` for a run, when the apply
/// is out-of-order and either the policy carries an override reason
/// or there's a known conflicting peer. Returns `None` for the
/// in-order common case. Pure function — no DB access (cluster-2
/// simplify Finding 7 — note-composition extraction).
fn compose_initial_note(
    is_out_of_order: bool,
    override_reason: Option<&str>,
    conflicting_peer: Option<&(String, Option<String>)>,
) -> Option<String> {
    match (is_out_of_order, override_reason) {
        (true, Some(reason)) if !reason.is_empty() => {
            let header = match conflicting_peer {
                Some((peer, Some(ts))) => {
                    format!("out-of-order apply (peer {peer} applied at {ts}) override: {reason}")
                }
                Some((peer, None)) => {
                    format!("out-of-order apply (peer {peer}) override: {reason}")
                }
                None => format!("out-of-order apply override: {reason}"),
            };
            Some(header)
        }
        (true, None) => match conflicting_peer {
            Some((peer, Some(ts))) => Some(format!(
                "out-of-order apply: peer {peer} was already applied at {ts}"
            )),
            Some((peer, None)) => Some(format!("out-of-order apply: peer {peer}")),
            None => None,
        },
        _ => None,
    }
}

/// Build the `partial_apply_note` string for a failed transactional
/// segment. Centralizes the inline format strings that previously
/// lived in `apply_plan_inner`'s match arm (cluster-2 simplify
/// Finding 7 — note-formatting extraction).
fn note_for_failed_transactional_segment(seg_idx: usize, e: &RunnerError) -> String {
    match e {
        RunnerError::RelpagesThresholdExceeded {
            index_name,
            target_table,
            relpages,
            threshold,
            ..
        } => format!(
            "relpages-probe failed at AddIndex {index_name} on table \
             {target_table} (relpages={relpages} > threshold={threshold})",
        ),
        RunnerError::TargetTableNotFound {
            index_name,
            target_table,
            ..
        } => format!(
            "relpages-probe failed at AddIndex {index_name}: target table \
             `{target_table}` not found and not in plan's AddTable set",
        ),
        RunnerError::TransactionalSegmentFailed {
            statement_label,
            source,
            ..
        } => format!(
            "transactional segment {seg_idx} failed at `{statement_label}`: \
             {source}",
        ),
        RunnerError::PkFlipVerificationFailed {
            table,
            count_violating,
        } => format!(
            "PK-flip verification halt at segment {seg_idx}: table `{table}` \
             has {count_violating} row(s) with NULL or stale shadow values",
        ),
        other => format!("transactional segment {seg_idx} failed: {other}"),
    }
}

/// Generate a fresh `run_id` via the HeerId default-allocation path.
/// HeerId is a 64-bit time-ordered ID — perfect for the per-runner
/// invocation key, which we want to be unique, sortable, and stable
/// across machines.
///
/// **Phase 0 carve-out (Track 0).** When `version` is the canonical
/// Phase 0 bootstrap label (`super::bootstrap::PHASE_ZERO_VERSION`),
/// HeeRanjID is by definition not yet installed — Phase 0 is what
/// installs it. Calling `heerid_next()` would fail with "function
/// does not exist". For Phase 0 only, we fall back to a wall-clock
/// nanosecond-precision id derived from
/// `clock_timestamp() - epoch '2026-01-01'`, which fits in `i64`
/// for the next ~140 years and is unique-enough across the one-time
/// Phase 0 emission per database. Subsequent migrations route
/// through the standard HeerId path because Phase 0 has by then
/// installed `heerid_next()`.
async fn generate_run_id(ctx: &mut DjogiContext, version: &str) -> Result<i64, RunnerError> {
    if version == super::bootstrap::PHASE_ZERO_VERSION {
        // Phase 0 carve-out — HeerRanjID not yet installed at this
        // point. Fall back to a wall-clock nanosecond id. We use
        // `EXTRACT(EPOCH FROM clock_timestamp()) * 1e9` for nanosecond
        // resolution; the cast to BIGINT fits comfortably in i64
        // for the foreseeable future. Two concurrent Phase 0 applies
        // against the same workspace are impossible (the workspace
        // lock guarantees exclusion), so collision risk is zero.
        let row = ctx
            .__query_one_for_macros(
                "SELECT (EXTRACT(EPOCH FROM clock_timestamp()) * 1000000000)::BIGINT AS run_id",
                &[],
            )
            .await
            .map_err(|e| RunnerError::RunIdGenerationFailed { source: e })?;
        let id: i64 = row
            .try_get("run_id")
            .map_err(|e| RunnerError::RunIdGenerationFailed {
                source: crate::DjogiError::Db(crate::DbError::other(format!("decode run_id: {e}"))),
            })?;
        return Ok(id);
    }
    use crate::primary_key::PrimaryKeyDbGen;
    let id = HeerId::generate(ctx)
        .await
        .map_err(|e| RunnerError::RunIdGenerationFailed { source: e })?;
    // HeerId exposes a direct `as_i64()` accessor (and an equivalent
    // `From<HeerId> for i64` impl). Use the typed conversion rather
    // than routing through `Display + parse + unwrap_or(0)` so a
    // misbehaving Display impl cannot collapse a real ID to `0`.
    Ok(id.as_i64())
}

fn elapsed_ms(t0: Instant) -> i64 {
    t0.elapsed().as_millis().min(i64::MAX as u128) as i64
}

/// Return `true` iff `e` carries Postgres SQLSTATE 23505
/// (unique_violation). Used by runner insert paths to classify
/// duplicate-version collisions into terminal vs. non-terminal
/// typed errors.
fn is_unique_violation(e: &DjogiError) -> bool {
    use tokio_postgres::error::SqlState;
    match e {
        DjogiError::Db(db) => db_code_matches(db, &SqlState::UNIQUE_VIOLATION),
        _ => false,
    }
}

/// Inspect a `DbError`'s SQLSTATE without reaching across the
/// `DbError` opaque boundary directly. The accessor returns
/// `Option<&SqlState>`; we compare by reference.
fn db_code_matches(db: &DbError, target: &tokio_postgres::error::SqlState) -> bool {
    db.code().map(|c| c == target).unwrap_or(false)
}

/// Classify a duplicate-version collision by loading the full ledger
/// row and dispatching by `status`.
///
/// Terminal statuses (`applied`, `faked`, `baseline`) surface the
/// existing `VersionAlreadyApplied` variant and preserve the
/// informational `applied_at` lookup. Non-terminal statuses
/// (`pending`, `failed`, `rolled_back`) surface
/// `VersionCollisionNonTerminal` with the blocking row identity.
///
/// If the readback lookup errors or returns `None` after a 23505,
/// surface a `LedgerQueryFailed` path explicitly rather than
/// pretending the row is already applied.
async fn classify_duplicate_version_collision(
    ctx: &mut DjogiContext,
    version: &str,
) -> RunnerError {
    let row = match load_ledger_row_for_version(ctx, version).await {
        Ok(Some(row)) => row,
        Ok(None) => {
            return RunnerError::LedgerQueryFailed {
                query_label: "load_row_for_version",
                source: DjogiError::Db(DbError::other(format!(
                    "duplicate-version collision for `{version}` but \
                     no ledger row was returned by load_full_row_by_version",
                ))),
            };
        }
        Err(source) => {
            return RunnerError::LedgerQueryFailed {
                query_label: "load_row_for_version",
                source,
            };
        }
    };

    match row.status {
        LedgerStatus::Applied | LedgerStatus::Faked | LedgerStatus::Baseline => {
            let applied_at = load_applied_at(ctx, version).await;
            RunnerError::VersionAlreadyApplied {
                version: version.to_string(),
                applied_at,
            }
        }
        LedgerStatus::Pending | LedgerStatus::Failed | LedgerStatus::RolledBack => {
            RunnerError::VersionCollisionNonTerminal {
                version: row.version,
                status: row.status,
                run_id: row.run_id,
            }
        }
    }
}

/// Walk the bucket's existing applied / faked / baseline ledger
/// rows and surface the highest-version peer whose `version`
/// lexically exceeds `candidate_version`. Returns the peer's
/// `(version, applied_at_rfc3339)` tuple — or `None` when no peer
/// would conflict (the typical happy-path case).
///
/// **Why "applied / faked / baseline"?** These three statuses
/// represent rows that the runner has acknowledged as "this
/// migration is in the database" — `pending` and `failed` rows do
/// not, and rolled-back rows have explicitly opted out. Treating
/// rolled-back rows as conflicting peers would block re-applying a
/// reverted migration, which is a legitimate workflow.
///
/// **Lexical compare.** The version prefix is `V<14 ASCII digits>`
/// (timestamp-derived) so lexical order = chronological order. We
/// compare the full version string (including the `__<slug>` tail)
/// so two versions sharing the same timestamp prefix sort by their
/// slug, which keeps the comparison deterministic.
async fn find_higher_applied_version(
    ctx: &mut DjogiContext,
    bucket: &BucketKey,
    candidate_version: &str,
) -> Result<Option<(String, Option<String>)>, DjogiError> {
    // app_label is the bucket's per-app key — the per-database
    // dimension is implicit in which connection / pool the runner
    // routes through, mirroring T4 / T5 / T6's single-pool stance.
    // When `DjogiContext::pool_for(database)` lands the per-database
    // routing comes for free; the SELECT still scopes by app_label.
    let row_opt = ctx
        .query_opt(
            "SELECT version, \
                    to_char(applied_at AT TIME ZONE 'UTC', \
                            'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS applied_at_rfc3339 \
             FROM djogi_schema_migrations \
             WHERE app_label = $1 \
               AND status IN ('applied', 'faked', 'baseline') \
               AND version > $2 \
             ORDER BY version DESC \
             LIMIT 1",
            &[&bucket.app, &candidate_version],
        )
        .await?;
    let Some(row) = row_opt else {
        return Ok(None);
    };
    let conflicting_version: String = row.try_get(0)?;
    let applied_at_rfc3339: Option<String> = row.try_get(1).ok();
    Ok(Some((conflicting_version, applied_at_rfc3339)))
}

/// Read the `applied_at` timestamp of an existing row whose
/// `version` we just collided with. Returns `None` if the lookup
/// fails — the operator-facing message degrades gracefully because
/// the message is informational only.
async fn load_applied_at(ctx: &mut DjogiContext, version: &str) -> Option<OffsetDateTime> {
    let row = ctx
        .query_opt(
            "SELECT applied_at FROM djogi_schema_migrations WHERE version = $1",
            &[&version],
        )
        .await
        .ok()??;
    row.try_get::<_, OffsetDateTime>("applied_at").ok()
}

/// Walk the plan and collect the set of table names that an
/// `AddTable` statement creates. The relpages probe uses this to
/// disambiguate "table being created in this very plan" (legit
/// `relpages = None`) from "typo / mis-quoted identifier"
/// (`TargetTableNotFound`).
fn collect_add_table_targets(plan: &MigrationPlan) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    for seg in &plan.segments {
        for stmt in &seg.statements {
            if let Some(table) = stmt.label.strip_prefix("AddTable ") {
                out.insert(table.to_string());
            }
        }
    }
    out
}

// ── B-2: partition leaf-placeholder expansion ─────────────────────────────

/// Controls how empty-leaf partitions are handled during expansion.
///
/// **ApplyLenient** (default for `apply_plan`): preserves the current
/// empty-leaf no-op fallback, emitting a comment-only statement so the
/// segment completes without error. The operator sees the diagnostic and
/// can attach partitions before retrying.
///
/// **ReplayStrict** (rollback / repair): refuses zero leaves because
/// replaying a shorter stream would silently miss leaf work that the
/// ledger already counted. Returns `RunnerError::PartitionExpansionNoLeaves`
/// so the caller can abort or handle the discrepancy explicitly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PartitionExpansionMode {
    ApplyLenient,
    ReplayStrict,
}

/// Public-facing helper wrapping [`expand_partition_leaf_placeholders`].
/// Materializes partition leaf placeholders according to the given mode.
pub(crate) async fn materialize_execution_plan(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    mode: PartitionExpansionMode,
) -> Result<
    (
        MigrationPlan,
        std::collections::HashMap<String, Vec<String>>,
    ),
    RunnerError,
> {
    expand_partition_leaf_placeholders(ctx, plan, mode).await
}

/// Serialize a parent-to-leaves map into the compact `leaf_identity`
/// format stored in the ledger. Parents sorted alphabetically; leaves
/// already sorted by `regclass::text`. Newline-delimited
/// `parent:leaf1,leaf2` entries.
pub(crate) fn serialize_leaf_identity(
    leaves_cache: &std::collections::HashMap<String, Vec<String>>,
) -> Option<String> {
    let mut entries: Vec<_> = leaves_cache
        .iter()
        .map(|(parent, leaves)| format!("{}:{}", parent, leaves.join(",")))
        .collect();
    entries.sort();
    if entries.is_empty() {
        None
    } else {
        Some(entries.join("\n"))
    }
}

/// Compute the current parent-to-leaves cache for `plan` using LENIENT
/// partition expansion, suitable for a pre-strict leaf-identity check.
///
/// **Why lenient.** `apply_plan` records `leaf_identity` from a
/// `ApplyLenient` expansion (which tolerates zero leaves), so a fresh
/// lenient cache compares apples-to-apples against the stored value.
/// Crucially, lenient mode does NOT error on a zero-leaf parent — so a
/// zero-leaf↔non-empty topology drift surfaces as a *comparison*
/// mismatch (empty cache → empty serialized identity) rather than the
/// strict path's [`RunnerError::PartitionExpansionNoLeaves`]. Callers
/// run this before [`materialize_execution_plan`] with
/// [`PartitionExpansionMode::ReplayStrict`] so the leaf-identity
/// mismatch is reported as such instead of a strict zero-leaf refusal.
pub(crate) async fn compute_leaf_identity_cache(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
) -> Result<std::collections::HashMap<String, Vec<String>>, RunnerError> {
    let (_plan, cache) =
        expand_partition_leaf_placeholders(ctx, plan, PartitionExpansionMode::ApplyLenient).await?;
    Ok(cache)
}

/// Walk every segment and expand the `<EACH_LEAF_TABLE>` placeholder
/// inside any partitioned-flip statement into one concrete-leaf
/// statement per leaf, sorted by `regclass::text` for determinism.
///
/// Statements affected (by label prefix):
/// - `PkFlipPartitionedBackfill <parent>` — body carries
///   `CALL heeranjid_bulk_backfill('<EACH_LEAF_TABLE>', ...)`. Each
///   leaf gets its own CALL line.
/// - `PkFlipPartitionedIndex <parent>` — body carries the parent
///   UNIQUE-on-ONLY placeholder plus a comment block describing the
///   per-leaf `CREATE UNIQUE INDEX CONCURRENTLY` + `ALTER INDEX
///   ATTACH PARTITION` pattern. The comment is replaced with two
///   concrete statements per leaf.
///
/// Statements with no placeholder (`PkFlipPartitionedPrep`,
/// `PkFlipPartitionedCutover`) are passed through untouched.
///
/// **No regex.** Placeholder substitution uses byte-level
/// `String::replace` semantics with a fixed literal token. Per-leaf
/// statement composition uses straight string concatenation and the
/// `writeln!` macro.
///
/// **Failure modes.** If `pg_inherits` returns no leaves for a
/// declared partitioned parent, behavior depends on [`PartitionExpansionMode`]:
/// - ApplyLenient: produces a single comment line so the segment SQL
///   surfaces the empty-leaves state cleanly rather than running an
///   `<EACH_LEAF_TABLE>` literal that would fail with `undefined_table`.
///   Operator's job is to attach partitions before retrying.
/// - ReplayStrict: refuses zero leaves because rollback/repair must not
///   silently replay a shorter stream. Returns [`RunnerError::PartitionExpansionNoLeaves`].
async fn expand_partition_leaf_placeholders(
    ctx: &mut DjogiContext,
    plan: &MigrationPlan,
    mode: PartitionExpansionMode,
) -> Result<
    (
        MigrationPlan,
        std::collections::HashMap<String, Vec<String>>,
    ),
    RunnerError,
> {
    // Cache leaves per parent so multiple statements pointing at the
    // same partitioned parent share one query.
    let mut leaves_cache: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();

    let mut new_plan = plan.clone();
    for segment in &mut new_plan.segments {
        let mut new_stmts: Vec<OperationSql> = Vec::with_capacity(segment.statements.len());
        for stmt in std::mem::take(&mut segment.statements) {
            let parent_for_label = partitioned_parent_from_label(&stmt.label);
            match parent_for_label {
                Some(parent) => {
                    if !leaves_cache.contains_key(&parent) {
                        let leaves = lookup_partition_leaves(ctx, &parent).await?;
                        leaves_cache.insert(parent.clone(), leaves);
                    }
                    let leaves = leaves_cache.get(&parent).expect("just inserted");
                    new_stmts.extend(expand_partition_statement(&stmt, &parent, leaves, mode)?);
                }
                None => new_stmts.push(stmt),
            }
        }
        segment.statements = new_stmts;
    }
    Ok((new_plan, leaves_cache))
}

/// Recover the partitioned parent name from a `PkFlipPartitioned…`
/// label. Returns `None` for non-partitioned labels (which carry no
/// `<EACH_LEAF_TABLE>` placeholder).
fn partitioned_parent_from_label(label: &str) -> Option<String> {
    // We expand only the labels whose bodies the emitter populates
    // with the `<EACH_LEAF_TABLE>` placeholder. Prep and cutover
    // operate on the partitioned parent directly via Postgres'
    // partition-aware DDL and do not need expansion.
    for prefix in [
        "PkFlipPartitionedBackfill ",
        "PkFlipPartitionedIndex ",
        "PkFlipPartitionedSelfFkIndex ",
    ] {
        if let Some(rest) = label.strip_prefix(prefix) {
            // Take the first whitespace-separated token — the parent
            // table name. Defensive: future labels may carry trailing
            // qualifiers (e.g. `(parent-level)` after expansion).
            let parent = rest.split_whitespace().next().unwrap_or(rest);
            return Some(parent.to_string());
        }
    }
    None
}

/// Query `pg_inherits` for the leaf partitions of `parent`,
/// deterministically sorted by `regclass::text`.
///
/// **Why a two-step lookup.** Postgres rejects a TEXT bind in the
/// binary-protocol position where it expects `regclass`
/// (tokio-postgres surfaces `WrongType { postgres: Regclass, rust:
/// "&str" }`). Resolving the parent's OID first via `to_regclass`
/// in a separate `query_one` lets us bind the OID as `oid` in the
/// second query against `pg_inherits`, matching the catalog's
/// column type exactly.
async fn lookup_partition_leaves(
    ctx: &mut DjogiContext,
    parent: &str,
) -> Result<Vec<String>, RunnerError> {
    // 1. Resolve parent's OID. `to_regclass` returns NULL for an
    //    unknown / non-relation name; we surface that as an empty
    //    leaf list so callers see "no leaves" rather than a hard
    //    error during plan composition.
    let oid_row = ctx
        .query_one("SELECT to_regclass($1)::oid", &[&parent])
        .await
        .map_err(|e| RunnerError::CatalogQueryFailed {
            query_label: "to_regclass",
            source: e,
        })?;
    let oid_opt: Option<u32> = oid_row.try_get(0).ok();
    let Some(oid) = oid_opt else {
        return Ok(Vec::new());
    };

    // 2. Fetch leaves keyed off the resolved OID. `inhparent` is
    //    `oid`; binding an `Oid` (u32 in tokio-postgres mapping)
    //    matches by type and avoids the regclass binary-protocol
    //    coercion path.
    let rows = ctx
        .query_all(
            "SELECT inhrelid::regclass::text \
             FROM pg_inherits \
             WHERE inhparent = $1 \
             ORDER BY inhrelid::regclass::text",
            &[&oid],
        )
        .await
        .map_err(|e| RunnerError::CatalogQueryFailed {
            query_label: "pg_inherits",
            source: e,
        })?;
    let mut out: Vec<String> = Vec::with_capacity(rows.len());
    for r in &rows {
        let leaf: String = r.try_get(0).unwrap_or_default();
        if !leaf.is_empty() {
            out.push(leaf);
        }
    }
    Ok(out)
}

/// Produce one concrete-leaf [`OperationSql`] per leaf for a
/// partitioned-flip statement. The original statement carries
/// `<EACH_LEAF_TABLE>` as a literal placeholder; we substitute and
/// emit one statement per leaf so the runner walks them in sequence.
///
/// For the index segment we ALSO emit the per-leaf `ATTACH PARTITION`
/// statement immediately after each leaf's CONCURRENTLY index build
/// so the partitioned parent's UNIQUE index becomes valid as soon as
/// the last leaf attaches.
// RunnerError is a large enum by design; this sync helper returns it by
// value and needs the suppression. Same rationale as handle_release_result.
#[allow(clippy::result_large_err)]
fn expand_partition_statement(
    stmt: &OperationSql,
    parent: &str,
    leaves: &[String],
    mode: PartitionExpansionMode,
) -> Result<Vec<OperationSql>, RunnerError> {
    if leaves.is_empty() {
        return match mode {
            PartitionExpansionMode::ApplyLenient => Ok(vec![OperationSql {
                label: format!("{} (no leaves)", stmt.label),
                up: format!(
                    "-- pg_inherits returned 0 leaves for partitioned parent {parent}; nothing to expand"
                ),
                down: stmt.down.clone(),
                lossy: stmt.lossy.clone(),
            }]),
            PartitionExpansionMode::ReplayStrict => Err(RunnerError::PartitionExpansionNoLeaves {
                parent: parent.to_string(),
                statement_label: stmt.label.clone(),
            }),
        };
    }

    let mut out: Vec<OperationSql> = Vec::with_capacity(leaves.len());

    if stmt.label.starts_with("PkFlipPartitionedBackfill ") {
        // The body carries one CALL with `<EACH_LEAF_TABLE>` plus a
        // multi-line comment header. Replace the placeholder once per
        // leaf and emit one OperationSql per CALL so the simple-query
        // batch never wraps multiple CALLs in a tx (the procedure's
        // internal COMMIT would fire `2D000`).
        for leaf in leaves {
            let body = stmt.up.replace("<EACH_LEAF_TABLE>", leaf);
            // Strip any trailing semicolon; runner_ctx dispatches this
            // through the internal single-statement batch path.
            let body = strip_trailing_semicolon(&body);
            // Prefer just the CALL line for the per-leaf statement so
            // the procedure runs cleanly without the multi-line
            // header comment muddying the per-statement record. We
            // recompose the comment as the first leaf's prefix only.
            let upper = format!(
                "-- partitioned backfill, leaf {leaf}\n{body}",
                leaf = leaf,
                body = extract_call_line(&body),
            );
            out.push(OperationSql {
                label: format!("PkFlipPartitionedBackfill {parent} leaf={leaf}"),
                up: upper,
                down: stmt.down.clone(),
                lossy: stmt.lossy.clone(),
            });
        }
        return Ok(out);
    }

    if stmt.label.starts_with("PkFlipPartitionedIndex ") {
        // The body carries the parent-level `CREATE UNIQUE INDEX … ON
        // ONLY <parent> (...)` plus a comment block describing the
        // per-leaf pattern. Keep the parent-level statement as the
        // FIRST OperationSql (transactional-friendly catalog op), then
        // emit one CONCURRENTLY + ATTACH per leaf.
        //
        // Recover the parent index name from the parent-level
        // statement: it's `idx_<parent>_<part_col>_id_desc_idx` (or
        // similar). Rather than parse, pull the marker line that
        // begins with `CREATE UNIQUE INDEX ` and ends at the first `;`.
        let parent_stmt = extract_first_statement_starting_with(&stmt.up, "CREATE UNIQUE INDEX ");
        let parent_index_name = recover_parent_index_name(&parent_stmt);
        let (part_col, suffix) = recover_partition_columns(&parent_stmt);

        out.push(OperationSql {
            label: format!("PkFlipPartitionedIndex {parent} (parent-level)"),
            up: parent_stmt.clone(),
            down: stmt.down.clone(),
            lossy: stmt.lossy.clone(),
        });

        for leaf in leaves {
            // The CREATE INDEX target index name must be BARE (Postgres
            // forbids a schema-qualified index name; the index lands in
            // the leaf's own schema). DROP / ATTACH need the leaf's
            // schema re-attached.
            let (leaf_schema, leaf_bare) = split_leaf_schema(leaf);
            let leaf_idx = format!(
                "{leaf_bare}_{pkey}_id{suffix}_idx",
                pkey = part_col,
                suffix = suffix
            );
            let leaf_idx_qualified = match leaf_schema {
                Some(s) => format!("{s}.{leaf_idx}"),
                None => leaf_idx.clone(),
            };
            // The parent index lives in the parent's schema. The current
            // emitter always produces a bare parent table name, so this
            // returns `parent_index_name` unchanged in practice — but
            // using the parent's own schema is correct by design.
            let (parent_schema, _) = split_leaf_schema(parent);
            let parent_idx_qualified = match parent_schema {
                Some(s) => format!("{s}.{parent_index_name}"),
                None => parent_index_name.clone(),
            };
            let create_concurrent = format!(
                "CREATE UNIQUE INDEX CONCURRENTLY {leaf_idx} ON {leaf} ({pkey}, id{suffix})",
                leaf_idx = leaf_idx,
                leaf = leaf,
                pkey = part_col,
                suffix = suffix,
            );
            // Down SQL: drop the parent index first (CASCADE removes any
            // attached leaf partitions), then drop the leaf itself as a
            // no-op cleanup for the partial-apply case where the leaf was
            // created concurrently but never attached. Both statements use
            // IF EXISTS so they are safe to re-execute in subsequent reverse
            // steps after the parent was already dropped. Both index names
            // are schema-qualified for DROP.
            out.push(OperationSql {
                label: format!("PkFlipPartitionedIndex {parent} leaf={leaf} (concurrent)"),
                up: create_concurrent,
                down: format!(
                    "DROP INDEX IF EXISTS {parent_idx_qualified}; DROP INDEX IF EXISTS {leaf_idx_qualified}",
                ),
                lossy: None,
            });
            let attach = format!(
                "ALTER INDEX {parent_idx_qualified} ATTACH PARTITION {leaf_idx_qualified}",
            );
            out.push(OperationSql {
                label: format!("PkFlipPartitionedIndex {parent} leaf={leaf} (attach)"),
                up: attach,
                down: String::new(),
                lossy: None,
            });
        }
        return Ok(out);
    }

    if stmt.label.starts_with("PkFlipPartitionedSelfFkIndex ") {
        // Single-column self-FK index on a partitioned parent. Body
        // form: `CREATE INDEX <idx> ON ONLY <parent> (<col>_desc);`
        // plus a comment header. Mirror the PkFlipPartitionedIndex
        // expansion: keep the parent-level statement as the FIRST
        // OperationSql, then per-leaf CONCURRENTLY + ATTACH PARTITION.
        let parent_stmt = extract_first_statement_starting_with(&stmt.up, "CREATE INDEX ");
        let parent_index_name = recover_parent_index_name(&parent_stmt);
        let (col, suffix) = recover_self_fk_column(&parent_stmt);

        out.push(OperationSql {
            label: format!("PkFlipPartitionedSelfFkIndex {parent} (parent-level)"),
            up: parent_stmt.clone(),
            down: stmt.down.clone(),
            lossy: stmt.lossy.clone(),
        });

        for leaf in leaves {
            // CREATE target index name is bare; DROP / ATTACH re-attach
            // the leaf's schema. See PkFlipPartitionedIndex above.
            let (leaf_schema, leaf_bare) = split_leaf_schema(leaf);
            let leaf_idx = format!("{leaf_bare}_{col}{suffix}_idx", col = col, suffix = suffix);
            let leaf_idx_qualified = match leaf_schema {
                Some(s) => format!("{s}.{leaf_idx}"),
                None => leaf_idx.clone(),
            };
            let (parent_schema, _) = split_leaf_schema(parent);
            let parent_idx_qualified = match parent_schema {
                Some(s) => format!("{s}.{parent_index_name}"),
                None => parent_index_name.clone(),
            };
            let create_concurrent = format!(
                "CREATE INDEX CONCURRENTLY {leaf_idx} ON {leaf} ({col}{suffix})",
                leaf_idx = leaf_idx,
                leaf = leaf,
                col = col,
                suffix = suffix,
            );
            out.push(OperationSql {
                label: format!("PkFlipPartitionedSelfFkIndex {parent} leaf={leaf} (concurrent)"),
                up: create_concurrent,
                down: format!("DROP INDEX IF EXISTS {leaf_idx_qualified}"),
                lossy: None,
            });
            let attach = format!(
                "ALTER INDEX {parent_idx_qualified} ATTACH PARTITION {leaf_idx_qualified}",
            );
            out.push(OperationSql {
                label: format!("PkFlipPartitionedSelfFkIndex {parent} leaf={leaf} (attach)"),
                up: attach,
                down: String::new(),
                lossy: None,
            });
        }
        return Ok(out);
    }

    // Unknown partitioned label — pass through unchanged. Defensive:
    // future emitters that add new `PkFlipPartitioned…` labels keep
    // working without forcing this fn to learn about them.
    Ok(vec![stmt.clone()])
}

/// Strip a single trailing `;` (with optional trailing whitespace).
/// The runner's internal batch path accepts statements with or without a
/// terminator, but stripping keeps the per-leaf record tidy.
fn strip_trailing_semicolon(s: &str) -> String {
    let trimmed = s.trim_end();
    trimmed.strip_suffix(';').unwrap_or(trimmed).to_string()
}

/// Split a (possibly schema-qualified) relation name into its optional
/// schema prefix and bare relation name. `lookup_partition_leaves`
/// returns `regclass::text` values that Postgres schema-qualifies when
/// the leaf is not on `search_path` (`myschema.events_p_a`).
///
/// The separator is the LAST unquoted `.`; characters inside a
/// double-quoted identifier (`"weird.name"`) are skipped so an embedded
/// dot never splits a quoted segment. Returns `(Some(schema), bare)`
/// when an unquoted dot is present, else `(None, whole)`.
///
/// **Why the split matters.** `CREATE INDEX` forbids a schema-qualified
/// *index* name (the index lands in the table's schema), whereas
/// `DROP INDEX` and `ALTER INDEX … ATTACH PARTITION` accept and need the
/// qualification. Composing the leaf index name from `bare` and then
/// re-qualifying only for DROP/ATTACH keeps both forms correct.
///
/// **No regex.** Byte-level scan tracking quote state; no regex engine.
fn split_leaf_schema(qualified: &str) -> (Option<&str>, &str) {
    let bytes = qualified.as_bytes();
    let mut in_quote = false;
    let mut sep = None;
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'"' => in_quote = !in_quote,
            b'.' if !in_quote => sep = Some(i),
            _ => {}
        }
    }
    match sep {
        Some(i) => (Some(&qualified[..i]), &qualified[i + 1..]),
        None => (None, qualified),
    }
}

/// Pull the FIRST line that contains `CALL heeranjid_bulk_backfill(`
/// from a multi-line body. Falls back to the whole body if the marker
/// is absent.
fn extract_call_line(s: &str) -> String {
    for line in s.lines() {
        if line.contains("CALL heeranjid_bulk_backfill(") {
            return strip_trailing_semicolon(line);
        }
    }
    strip_trailing_semicolon(s)
}

/// Pull the FIRST statement (terminated by the first `;`) that
/// starts with `start_marker`. Falls back to an empty string if not
/// found. Used to extract the parent-level `CREATE UNIQUE INDEX ON
/// ONLY <parent>` from the multi-line index segment body.
fn extract_first_statement_starting_with(body: &str, start_marker: &str) -> String {
    let bytes = body.as_bytes();
    let mut i = 0usize;
    while i < bytes.len() {
        // Skip leading whitespace + comments on this line.
        while i < bytes.len() && bytes[i] == b' ' {
            i += 1;
        }
        if i + start_marker.len() <= bytes.len()
            && &bytes[i..i + start_marker.len()] == start_marker.as_bytes()
        {
            // Find the terminating `;`.
            let start = i;
            let mut j = i + start_marker.len();
            while j < bytes.len() && bytes[j] != b';' {
                j += 1;
            }
            // Include the `;` if present, normalize internal whitespace.
            let raw = String::from_utf8_lossy(&bytes[start..j]).into_owned();
            return raw;
        }
        // Skip to next line.
        while i < bytes.len() && bytes[i] != b'\n' {
            i += 1;
        }
        if i < bytes.len() {
            i += 1;
        }
    }
    String::new()
}

/// Recover the parent index name from a `CREATE [UNIQUE] INDEX
/// <name> ON ONLY ...` body. Tries the UNIQUE form first
/// (PkFlipPartitionedIndex composite PK indexes use it), then the
/// non-unique form (PkFlipPartitionedSelfFkIndex single-column
/// indexes use it). Falls back to an empty string if neither
/// matches.
fn recover_parent_index_name(parent_stmt: &str) -> String {
    let bytes = parent_stmt.as_bytes();
    for marker in [b"CREATE UNIQUE INDEX " as &[u8], b"CREATE INDEX " as &[u8]] {
        if bytes.len() < marker.len() {
            continue;
        }
        let mut i = 0usize;
        while i + marker.len() <= bytes.len() {
            if &bytes[i..i + marker.len()] == marker {
                let start = i + marker.len();
                let mut name_start = start;
                // Skip leading spaces.
                while name_start < bytes.len() && bytes[name_start] == b' ' {
                    name_start += 1;
                }
                // Skip optional CONCURRENTLY keyword (and any following
                // spaces). The parent-level emitter writes `ON ONLY` form
                // without CONCURRENTLY, but the per-leaf statements this
                // helper may also be handed do carry it — skip so the
                // captured name is the index, not the keyword.
                const CONC: &[u8] = b"CONCURRENTLY";
                if name_start + CONC.len() <= bytes.len()
                    && &bytes[name_start..name_start + CONC.len()] == CONC
                {
                    name_start += CONC.len();
                    while name_start < bytes.len() && bytes[name_start] == b' ' {
                        name_start += 1;
                    }
                }
                let mut j = name_start;
                while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
                    j += 1;
                }
                if j > name_start {
                    return String::from_utf8_lossy(&bytes[name_start..j]).into_owned();
                }
                break;
            }
            i += 1;
        }
    }
    String::new()
}

/// Recover the partition column + shadow suffix from the parent
/// index statement. The expected form is
/// `CREATE UNIQUE INDEX <idx> ON ONLY <parent> (<pkey>, id<suffix>)`.
/// Returns `(pkey, suffix)`; falls back to `("partition_key", "_desc")`
/// when the body cannot be parsed.
fn recover_partition_columns(parent_stmt: &str) -> (String, String) {
    let bytes = parent_stmt.as_bytes();
    // Find `(` and `)`.
    let mut open = None;
    let mut close = None;
    for (i, b) in bytes.iter().enumerate() {
        if *b == b'(' && open.is_none() {
            open = Some(i + 1);
        } else if *b == b')' {
            close = Some(i);
            break;
        }
    }
    let (Some(o), Some(c)) = (open, close) else {
        return ("partition_key".to_string(), "_desc".to_string());
    };
    if o >= c {
        return ("partition_key".to_string(), "_desc".to_string());
    }
    let inside = String::from_utf8_lossy(&bytes[o..c]).into_owned();
    // Split by `,` and trim. First is pkey, second is `id<suffix>`.
    let mut parts = inside.splitn(2, ',');
    let pkey = parts.next().unwrap_or("").trim().to_string();
    let id_col = parts.next().unwrap_or("").trim();
    // `suffix` is the part after `id` — empty string is valid when the
    // column is plain `id` (no ordering suffix like `_desc`). Only fall
    // back when `id_col` does not start with `id` at all (parse failure).
    let suffix = match id_col.strip_prefix("id") {
        Some(s) => s.to_string(),
        None => return ("partition_key".to_string(), "_desc".to_string()),
    };
    if pkey.is_empty() {
        return ("partition_key".to_string(), "_desc".to_string());
    }
    (pkey, suffix)
}

/// Recover the self-FK column name + shadow suffix from the parent
/// self-FK index statement. The expected form is
/// `CREATE INDEX <idx> ON ONLY <parent> (<col>_desc)`. Returns
/// `(col, suffix)`; falls back to `("col", "_desc")` when the body
/// cannot be parsed.
fn recover_self_fk_column(parent_stmt: &str) -> (String, String) {
    let bytes = parent_stmt.as_bytes();
    let mut open = None;
    let mut close = None;
    for (i, b) in bytes.iter().enumerate() {
        if *b == b'(' && open.is_none() {
            open = Some(i + 1);
        } else if *b == b')' {
            close = Some(i);
            break;
        }
    }
    let (Some(o), Some(c)) = (open, close) else {
        return ("col".to_string(), "_desc".to_string());
    };
    if o >= c {
        return ("col".to_string(), "_desc".to_string());
    }
    let inside = parent_stmt[o..c].trim();
    // Single column form `<col>_desc`. Strip the `_desc` suffix.
    if let Some(col) = inside.strip_suffix("_desc")
        && !col.is_empty()
    {
        return (col.to_string(), "_desc".to_string());
    }
    ("col".to_string(), "_desc".to_string())
}

#[cfg(test)]
mod tests {
    #![allow(clippy::await_holding_lock)]

    use super::*;
    use std::collections::BTreeMap;
    use std::path::PathBuf;
    use std::time::Duration;

    use crate::config::MigrateConfig;
    use crate::migrate::diff::Classification;
    use crate::migrate::projection::BucketKey;
    use crate::migrate::schema::AppliedSchema;
    use crate::migrate::segment::{MigrationPlan, Segment, SegmentKind};
    use crate::migrate::sql::OperationSql;
    use djogi_macros::djogi_test;

    fn bucket(db: &str, app: &str) -> BucketKey {
        BucketKey {
            database: db.to_string(),
            app: app.to_string(),
        }
    }

    fn empty_snapshot() -> AppliedSchema {
        AppliedSchema {
            djogi_version: "0.1.0".to_string(),
            enums: BTreeMap::new(),
            format_version: SNAPSHOT_FORMAT_VERSION.to_string(),
            generated_at: "2026-05-09T00:00:00Z".to_string(),
            indexes: Vec::new(),
            models: BTreeMap::new(),
            registered_apps: vec!["".to_string()],
        }
    }

    fn op(label: &str, up: &str) -> OperationSql {
        OperationSql {
            label: label.to_string(),
            up: up.to_string(),
            down: format!("-- down for {label}"),
            lossy: None,
        }
    }

    fn audit_plan() -> MigrationPlan {
        MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![
                Segment {
                    kind: SegmentKind::Transactional,
                    statements: vec![
                        op("AddTable audit_a", "CREATE TABLE audit_a (id bigint)"),
                        op("AddTable audit_b", "CREATE TABLE audit_b (id bigint)"),
                    ],
                },
                Segment {
                    kind: SegmentKind::MetadataOnly,
                    statements: vec![op("RenameApp ignored", "-- metadata-only placeholder")],
                },
                Segment {
                    kind: SegmentKind::NonTransactional,
                    statements: vec![op(
                        "AddIndex audit_a_id_idx",
                        "CREATE INDEX CONCURRENTLY audit_a_id_idx ON audit_a (id)",
                    )],
                },
            ],
        }
    }

    fn single_table_plan(table: &str) -> MigrationPlan {
        MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![Segment {
                kind: SegmentKind::Transactional,
                statements: vec![op(
                    &format!("AddTable {table}"),
                    &format!("CREATE TABLE {table} (id bigint)"),
                )],
            }],
        }
    }

    fn single_segment_plan(kind: SegmentKind, label: &str, up: &str) -> MigrationPlan {
        MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![Segment {
                kind,
                statements: vec![op(label, up)],
            }],
        }
    }

    fn runner_ctx_for_audit_with_snapshot_path(
        plan: &MigrationPlan,
        audit_pool: Option<deadpool_postgres::Pool>,
        snapshot_path: Option<PathBuf>,
    ) -> RunnerCtx {
        RunnerCtx {
            bucket: plan.bucket.clone(),
            version: "V20260509000000__audit_test".to_string(),
            description: "audit test".to_string(),
            checksum_up: compute_checksum_for_plan_up(plan),
            checksum_down: None,
            snapshot: Some(empty_snapshot()),
            snapshot_path,
            config: MigrateConfig::default(),
            out_of_order_policy: crate::migrate::policy::OutOfOrderPolicy::AllowWithDiagnostic,
            audit_pool,
        }
    }

    fn unique_temp_path(tag: &str, ext: &str) -> PathBuf {
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("djogi-runner-{tag}-{stamp}.{ext}"))
    }

    fn acquire_test_workspace_guard() -> WorkspaceGuard {
        crate::migrate::acquire_workspace_lock(
            &unique_temp_path("audit", "lock"),
            Duration::from_secs(2),
        )
        .expect("acquire workspace lock")
    }

    struct SigningKeyEnvUnsetGuard {
        previous: Option<std::ffi::OsString>,
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    struct SigningKeyEnvReadGuard {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl SigningKeyEnvReadGuard {
        fn hold() -> Self {
            Self {
                _guard: crate::snapshot::sign::SIGNING_KEY_ENV_MUTEX
                    .lock()
                    .expect("signing-key env mutex"),
            }
        }
    }

    impl SigningKeyEnvUnsetGuard {
        fn unset() -> Self {
            let guard = crate::snapshot::sign::SIGNING_KEY_ENV_MUTEX
                .lock()
                .expect("signing-key env mutex");
            let previous = std::env::var_os("DJOGI_SNAPSHOT_SIGNING_KEY");
            // SAFETY: `SIGNING_KEY_ENV_MUTEX` serialises every unit test in
            // this crate that reads or mutates `DJOGI_SNAPSHOT_SIGNING_KEY`.
            unsafe {
                std::env::remove_var("DJOGI_SNAPSHOT_SIGNING_KEY");
            }
            Self {
                previous,
                _guard: guard,
            }
        }
    }

    impl Drop for SigningKeyEnvUnsetGuard {
        fn drop(&mut self) {
            // SAFETY: this guard still holds `SIGNING_KEY_ENV_MUTEX`, so no
            // sibling unit test can concurrently read or mutate the signing
            // key env var while restoration happens.
            unsafe {
                if let Some(previous) = &self.previous {
                    std::env::set_var("DJOGI_SNAPSHOT_SIGNING_KEY", previous);
                } else {
                    std::env::remove_var("DJOGI_SNAPSHOT_SIGNING_KEY");
                }
            }
        }
    }

    // ── advisory_lock_key determinism ────────────────────────────────────

    #[test]
    fn advisory_lock_key_is_deterministic_across_calls() {
        let b = bucket("main", "");
        let a = advisory_lock_key(&b);
        let c = advisory_lock_key(&b);
        assert_eq!(a, c, "same input must yield same lock key");
    }

    #[test]
    fn advisory_lock_key_differs_on_database() {
        let a = advisory_lock_key(&bucket("alpha", ""));
        let b = advisory_lock_key(&bucket("beta", ""));
        assert_ne!(a, b, "different database must yield different key");
    }

    #[test]
    fn advisory_lock_key_differs_on_app() {
        let a = advisory_lock_key(&bucket("main", "users"));
        let b = advisory_lock_key(&bucket("main", "billing"));
        assert_ne!(a, b, "different app must yield different key");
    }

    #[test]
    fn advisory_lock_key_database_app_separator_prevents_collision() {
        // A naive concat would collide:
        //   ("ab", "c")  ->  "abc"
        //   ("a", "bc")  ->  "abc"
        // The `\0` separator means the two cannot collide.
        let a = advisory_lock_key(&bucket("ab", "c"));
        let b = advisory_lock_key(&bucket("a", "bc"));
        assert_ne!(a, b);
    }

    #[test]
    fn advisory_lock_key_pins_big_endian_byte_decode() {
        // Spec-pinned reference value. The test exists to lock in the
        // big-endian decode of the first 8 SHA-256 digest bytes per
        // the Phase 7 v3 contract — an alternate-language
        // implementation following the same spec must compute the
        // same i64 for these inputs.
        //
        // Reference computation (also verified offline with Python):
        //   d = sha256(b"djogi:advisory_lock:" + b"test_db" + b"\x00" + b"test_app")
        //   bytes[..8] = 7d 01 ce 8f 30 91 ba 37
        //   big-endian i64 = 0x7d01ce8f3091ba37 = 9_007_707_844_108_204_599
        //   little-endian (the WRONG decode) would produce
        //                                     4_015_681_655_511_318_909.
        let bk = bucket("test_db", "test_app");
        let key = advisory_lock_key(&bk);
        assert_eq!(
            key, 9_007_707_844_108_204_599_i64,
            "advisory_lock_key must decode the first 8 SHA-256 bytes as big-endian"
        );
        // Negative-control: confirm we are NOT little-endian decoding.
        assert_ne!(
            key, 4_015_681_655_511_318_909_i64,
            "advisory_lock_key must NOT decode bytes as little-endian"
        );
    }

    // ── parse_create_index_statement ─────────────────────────────────────

    #[test]
    fn parse_index_extracts_name_and_table() {
        let stmt = OperationSql {
            label: "AddIndex users_email_idx".to_string(),
            up: "CREATE INDEX \"users_email_idx\" ON \"users\" (\"email\")".to_string(),
            down: String::new(),
            lossy: None,
        };
        let parsed = parse_create_index_statement(&stmt).expect("parse");
        assert_eq!(parsed.0, "users_email_idx");
        assert_eq!(parsed.1, "users");
    }

    #[test]
    fn parse_index_returns_none_for_non_index_label() {
        let stmt = OperationSql {
            label: "AddTable users".to_string(),
            up: "CREATE TABLE \"users\" ()".to_string(),
            down: String::new(),
            lossy: None,
        };
        assert!(parse_create_index_statement(&stmt).is_none());
    }

    #[test]
    fn parse_index_returns_none_when_marker_missing() {
        let stmt = OperationSql {
            label: "AddIndex weird_idx".to_string(),
            up: "CREATE INDEX weird".to_string(),
            down: String::new(),
            lossy: None,
        };
        assert!(parse_create_index_statement(&stmt).is_none());
    }

    // ── compute_checksum_for_plan_up ─────────────────────────────────────

    #[test]
    fn plan_checksum_matches_manual_concatenation() {
        let plan = MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![Segment {
                kind: SegmentKind::Transactional,
                statements: vec![
                    OperationSql {
                        label: "AddTable a".to_string(),
                        up: "CREATE TABLE a ()".to_string(),
                        down: "DROP TABLE a".to_string(),
                        lossy: None,
                    },
                    OperationSql {
                        label: "AddTable b".to_string(),
                        up: "CREATE TABLE b ()".to_string(),
                        down: "DROP TABLE b".to_string(),
                        lossy: None,
                    },
                ],
            }],
        };
        let computed = compute_checksum_for_plan_up(&plan);
        let manual = compute_checksum(["CREATE TABLE a ()", "CREATE TABLE b ()"]);
        assert_eq!(computed, manual);
    }

    #[test]
    fn plan_checksum_changes_on_segment_reorder() {
        let make = |labels: [&str; 2]| MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![Segment {
                kind: SegmentKind::Transactional,
                statements: labels
                    .iter()
                    .map(|l| OperationSql {
                        label: format!("AddTable {l}"),
                        up: format!("CREATE TABLE {l} ()"),
                        down: format!("DROP TABLE {l}"),
                        lossy: None,
                    })
                    .collect(),
            }],
        };
        let a = compute_checksum_for_plan_up(&make(["a", "b"]));
        let b = compute_checksum_for_plan_up(&make(["b", "a"]));
        assert_ne!(a, b);
    }

    // ── elapsed_ms ────────────────────────────────────────────────────────

    #[test]
    fn elapsed_ms_returns_non_negative() {
        let t = Instant::now();
        let ms = elapsed_ms(t);
        assert!(ms >= 0);
    }

    // ── HeerId direct conversion ─────────────────────────────────────────

    #[test]
    fn heer_id_zero_converts_to_zero_i64_directly() {
        // After A-3, run_id derivation goes through HeerId::as_i64
        // / From<HeerId> for i64 — no Display + parse + unwrap_or
        // detour. ZERO's i64 representation must be 0 by both paths.
        let z = HeerId::ZERO;
        assert_eq!(z.as_i64(), 0);
        let via_from: i64 = i64::from(z);
        assert_eq!(via_from, 0);
    }

    #[test]
    fn heer_id_non_zero_round_trips_directly() {
        // Codex round-2 noted that the ZERO test alone does not exercise
        // the real conversion logic — every implementation maps zero to
        // zero. Pin a non-trivial bit pattern through both paths to
        // catch a future Display-vs-as_i64 drift that the zero case
        // would silently pass. HeerId only exposes a fallible
        // `TryFrom<i64>` (positive 64-bit values only); pick a
        // representative positive bit pattern.
        let v: i64 = 0x0123_4567_89AB_CDEF_i64;
        let id = HeerId::try_from(v).expect("positive i64 round-trips through HeerId");
        assert_eq!(id.as_i64(), v);
        let via_from: i64 = i64::from(id);
        assert_eq!(via_from, v);
    }

    // ── collect_add_table_targets ────────────────────────────────────────

    #[test]
    fn collect_add_table_targets_walks_all_segments() {
        let plan = MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![
                Segment {
                    kind: SegmentKind::Transactional,
                    statements: vec![
                        OperationSql {
                            label: "AddTable users".to_string(),
                            up: "CREATE TABLE users ()".to_string(),
                            down: "DROP TABLE users".to_string(),
                            lossy: None,
                        },
                        OperationSql {
                            label: "AddIndex users_email_idx".to_string(),
                            up: "CREATE INDEX...".to_string(),
                            down: String::new(),
                            lossy: None,
                        },
                    ],
                },
                Segment {
                    kind: SegmentKind::Transactional,
                    statements: vec![OperationSql {
                        label: "AddTable orders".to_string(),
                        up: "CREATE TABLE orders ()".to_string(),
                        down: "DROP TABLE orders".to_string(),
                        lossy: None,
                    }],
                },
            ],
        };
        let set = collect_add_table_targets(&plan);
        assert!(set.contains("users"));
        assert!(set.contains("orders"));
        assert!(!set.contains("users_email_idx")); // AddIndex is not AddTable
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn collect_add_table_targets_empty_plan_returns_empty_set() {
        let plan = MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::NoOp,
            segments: vec![],
        };
        let set = collect_add_table_targets(&plan);
        assert!(set.is_empty());
    }

    // ── segment SQL execution-mode preflight (#286) ─────────────────────

    #[test]
    fn segment_sql_preflight_rejects_concurrent_index_in_transactional_segment() {
        let plan = single_segment_plan(
            SegmentKind::Transactional,
            "AddIndex users_email_idx",
            "CREATE INDEX CONCURRENTLY users_email_idx ON users (email);",
        );

        let err = preflight_segment_sql_execution_compatibility(&plan).expect_err("must reject");
        match err {
            RunnerError::SegmentSqlExecutionModeConflict {
                segment_index,
                segment_kind,
                statement_label,
                problem,
            } => {
                assert_eq!(segment_index, 0);
                assert_eq!(segment_kind, SegmentKind::Transactional);
                assert_eq!(statement_label, "AddIndex users_email_idx");
                assert_eq!(
                    problem,
                    SegmentSqlExecutionModeProblem::RequiresNonTransactional {
                        statement_shape: "CREATE INDEX CONCURRENTLY",
                    }
                );
            }
            other => panic!("expected SegmentSqlExecutionModeConflict, got {other:?}"),
        }
    }

    #[test]
    fn segment_sql_preflight_rejects_comment_separated_concurrent_index_keywords() {
        let plan = single_segment_plan(
            SegmentKind::Transactional,
            "AddIndex users_email_idx",
            "CREATE /* split */ UNIQUE INDEX /* still split */ CONCURRENTLY \
             users_email_idx ON users (email);",
        );

        let err = preflight_segment_sql_execution_compatibility(&plan).expect_err("must reject");
        match err {
            RunnerError::SegmentSqlExecutionModeConflict {
                segment_index,
                segment_kind,
                statement_label,
                problem,
            } => {
                assert_eq!(segment_index, 0);
                assert_eq!(segment_kind, SegmentKind::Transactional);
                assert_eq!(statement_label, "AddIndex users_email_idx");
                assert_eq!(
                    problem,
                    SegmentSqlExecutionModeProblem::RequiresNonTransactional {
                        statement_shape: "CREATE UNIQUE INDEX CONCURRENTLY",
                    }
                );
            }
            other => panic!("expected SegmentSqlExecutionModeConflict, got {other:?}"),
        }
    }

    #[test]
    fn segment_sql_preflight_rejects_begin_in_transactional_segment() {
        let plan = single_segment_plan(SegmentKind::Transactional, "manual begin", "BEGIN;");

        let err = preflight_segment_sql_execution_compatibility(&plan).expect_err("must reject");
        match err {
            RunnerError::SegmentSqlExecutionModeConflict {
                segment_index,
                segment_kind,
                statement_label,
                problem,
            } => {
                assert_eq!(segment_index, 0);
                assert_eq!(segment_kind, SegmentKind::Transactional);
                assert_eq!(statement_label, "manual begin");
                assert_eq!(
                    problem,
                    SegmentSqlExecutionModeProblem::TransactionControl { keyword: "BEGIN" }
                );
            }
            other => panic!("expected SegmentSqlExecutionModeConflict, got {other:?}"),
        }
    }

    #[test]
    fn segment_sql_preflight_rejects_savepoint_in_non_transactional_segment() {
        let plan = single_segment_plan(
            SegmentKind::NonTransactional,
            "manual savepoint",
            "SAVEPOINT retry_guard;",
        );

        let err = preflight_segment_sql_execution_compatibility(&plan).expect_err("must reject");
        match err {
            RunnerError::SegmentSqlExecutionModeConflict {
                segment_index,
                segment_kind,
                statement_label,
                problem,
            } => {
                assert_eq!(segment_index, 0);
                assert_eq!(segment_kind, SegmentKind::NonTransactional);
                assert_eq!(statement_label, "manual savepoint");
                assert_eq!(
                    problem,
                    SegmentSqlExecutionModeProblem::TransactionControl {
                        keyword: "SAVEPOINT",
                    }
                );
            }
            other => panic!("expected SegmentSqlExecutionModeConflict, got {other:?}"),
        }
    }

    #[test]
    fn segment_sql_preflight_allows_set_constraints_in_transactional_segment() {
        let plan = single_segment_plan(
            SegmentKind::Transactional,
            "defer constraints",
            "SET CONSTRAINTS ALL DEFERRED;",
        );

        preflight_segment_sql_execution_compatibility(&plan).expect("set constraints allowed");
    }

    #[test]
    fn segment_sql_preflight_ignores_function_body_begin_commit_tokens() {
        let plan = single_segment_plan(
            SegmentKind::Transactional,
            "install function",
            "-- leading comment mentioning BEGIN\n\
             CREATE OR REPLACE FUNCTION public.bump_counter()\n\
             RETURNS trigger AS $body$\n\
             BEGIN\n\
                 NEW.counter := COALESCE(NEW.counter, 0) + 1;\n\
                 RETURN NEW;\n\
             END;\n\
             $body$ LANGUAGE plpgsql;",
        );

        preflight_segment_sql_execution_compatibility(&plan)
            .expect("function body BEGIN/END must not trip preflight");
    }

    // ── is_unique_violation classifier ───────────────────────────────────

    #[test]
    fn is_unique_violation_rejects_non_db_errors() {
        // Anything that is not a DjogiError::Db must classify as
        // false — only a Db error carries a SQLSTATE.
        let nf = DjogiError::not_found("users");
        assert!(!is_unique_violation(&nf));
    }

    // ── checksum_for_baseline_snapshot (B-11) ────────────────────────────

    #[test]
    fn checksum_for_baseline_snapshot_is_deterministic() {
        use crate::migrate::schema::{AppliedSchema, SNAPSHOT_FORMAT_VERSION};
        use std::collections::BTreeMap;
        let snap = AppliedSchema {
            djogi_version: "0.1.0".to_string(),
            enums: BTreeMap::new(),
            format_version: SNAPSHOT_FORMAT_VERSION.to_string(),
            generated_at: "2026-04-25T00:00:00Z".to_string(),
            indexes: Vec::new(),
            models: BTreeMap::new(),
            registered_apps: vec!["".to_string()],
        };
        let a = checksum_for_baseline_snapshot(&snap);
        let b = checksum_for_baseline_snapshot(&snap);
        assert_eq!(a, b, "same input must produce same checksum");
        assert!(a.starts_with(super::ledger::CHECKSUM_PREFIX));
        assert_eq!(a.len(), super::ledger::CHECKSUM_LEN);
    }

    #[test]
    fn checksum_for_baseline_snapshot_changes_on_schema_change() {
        use crate::migrate::schema::{AppliedSchema, SNAPSHOT_FORMAT_VERSION};
        use std::collections::BTreeMap;
        let mut a = AppliedSchema {
            djogi_version: "0.1.0".to_string(),
            enums: BTreeMap::new(),
            format_version: SNAPSHOT_FORMAT_VERSION.to_string(),
            generated_at: "2026-04-25T00:00:00Z".to_string(),
            indexes: Vec::new(),
            models: BTreeMap::new(),
            registered_apps: vec!["".to_string()],
        };
        let cs_a = checksum_for_baseline_snapshot(&a);
        a.registered_apps.push("billing".to_string());
        let cs_b = checksum_for_baseline_snapshot(&a);
        assert_ne!(cs_a, cs_b, "schema change must yield different checksum");
    }

    // ── BaselineSnapshotShouldNotBeProvided guard (B-11) ─────────────────

    #[test]
    fn baseline_snapshot_should_not_be_provided_renders_message() {
        let e = RunnerError::BaselineSnapshotShouldNotBeProvided;
        let msg = format!("{e}");
        assert!(msg.contains("baseline_plan rejects caller-supplied snapshots"));
        assert!(msg.contains("snapshot = None"));
    }

    #[test]
    fn version_collision_non_terminal_renders_status_and_run_id() {
        for (status, guidance) in [
            (
                LedgerStatus::Pending,
                "then `repair_partial_apply` to resolve it in place",
            ),
            (
                LedgerStatus::Failed,
                "then `repair_resume_partial_apply` if it is still resumable or `repair_partial_apply` otherwise",
            ),
            (
                LedgerStatus::RolledBack,
                "re-running `djogi migrations apply` will remove the rolled-back row and re-apply the migration",
            ),
        ] {
            let e = RunnerError::VersionCollisionNonTerminal {
                version: "V20260524010101__example".to_string(),
                status,
                run_id: 4242,
            };
            let msg = format!("{e}");
            assert!(msg.contains("V20260524010101__example"));
            assert!(msg.contains(status.as_db_str()));
            assert!(msg.contains("run_id 4242"));
            assert!(msg.contains("djogi migrations status"));
            assert!(msg.contains(guidance));
        }
    }

    #[test]
    fn version_collision_non_terminal_has_no_error_source() {
        let e = RunnerError::VersionCollisionNonTerminal {
            version: "V20260524010101__example".to_string(),
            status: LedgerStatus::Pending,
            run_id: 7,
        };
        assert!(std::error::Error::source(&e).is_none());
    }

    // ── apply_plan DDL audit wiring (T9.5) ────────────────────────────────

    #[allow(clippy::await_holding_lock)]
    #[djogi_test]
    async fn apply_plan_writes_audit_rows_for_executed_segments_when_key_unset(
        mut ctx: DjogiContext,
    ) {
        let _signing_key_env = SigningKeyEnvUnsetGuard::unset();
        let plan = audit_plan();
        let audit_pool = ctx
            .share_pool()
            .expect("djogi_test context should be pool-backed")
            .inner;
        let snapshot_path = unique_temp_path("audit-happy-path", "json");
        let cleanup_path = snapshot_path.clone();
        let runner_ctx =
            runner_ctx_for_audit_with_snapshot_path(&plan, Some(audit_pool), Some(snapshot_path));
        let guard = acquire_test_workspace_guard();
        let expected_sig = audit_signature_hex_for_snapshot(
            runner_ctx.snapshot.as_ref().expect("test snapshot"),
            [0u8; 32],
        )
        .expect("expected audit signature");

        let report = apply_plan(&mut ctx, &plan, &runner_ctx, &guard)
            .await
            .expect("apply should write audit rows");
        assert_eq!(report.transactional_segments, 1);
        assert_eq!(report.non_transactional_segments, 1);
        assert_eq!(report.metadata_segments, 1);

        let rows = ctx
            .query_all(
                "SELECT target_database, app_label, ddl_sql, snapshot_signature_hex, \
                        applied_at <= lead(applied_at) OVER (ORDER BY id) AS applied_before_next \
                 FROM djogi_ddl_audit ORDER BY id",
                &[],
            )
            .await
            .expect("read audit rows");
        assert_eq!(
            rows.len(),
            2,
            "transactional and non-transactional segments should be audited; metadata-only skipped"
        );

        let first_sql: String = rows[0].try_get("ddl_sql").expect("first ddl_sql");
        assert!(
            first_sql.contains("CREATE TABLE audit_a")
                && first_sql.contains(";\n")
                && first_sql.contains("CREATE TABLE audit_b"),
            "transactional segment should store concatenated statement SQL; got {first_sql}"
        );
        let second_sql: String = rows[1].try_get("ddl_sql").expect("second ddl_sql");
        assert!(
            second_sql.contains("CREATE INDEX CONCURRENTLY audit_a_id_idx"),
            "non-transactional segment should be audited; got {second_sql}"
        );

        for row in rows {
            let target_database: String = row
                .try_get("target_database")
                .expect("target_database column");
            let app_label: String = row.try_get("app_label").expect("app_label column");
            let sig: String = row
                .try_get("snapshot_signature_hex")
                .expect("snapshot signature column");
            let applied_before_next: Option<bool> = row
                .try_get("applied_before_next")
                .expect("applied_at monotonic column");

            assert_eq!(target_database, "main");
            assert_eq!(app_label, "");
            assert_eq!(sig, expected_sig);
            assert_eq!(
                sig,
                "0".repeat(64),
                "unset signing key should persist the no-op zero signature"
            );
            assert_ne!(
                applied_before_next,
                Some(false),
                "applied_at should be monotonic in audit id order"
            );
        }

        let _ = std::fs::remove_file(cleanup_path);
    }

    #[djogi_test]
    async fn apply_plan_skips_audit_when_pool_none(mut ctx: DjogiContext) {
        let plan = single_table_plan("audit_pool_none_applies");
        let snapshot_path = unique_temp_path("audit-pool-none", "json");
        let cleanup_path = snapshot_path.clone();
        let runner_ctx = runner_ctx_for_audit_with_snapshot_path(&plan, None, Some(snapshot_path));
        let guard = acquire_test_workspace_guard();

        let report = apply_plan(&mut ctx, &plan, &runner_ctx, &guard)
            .await
            .expect("audit_pool = None should not fail app-side apply");
        assert_eq!(report.transactional_segments, 1);

        let app_table: Option<String> = ctx
            .query_one(
                "SELECT to_regclass('public.audit_pool_none_applies')::text",
                &[],
            )
            .await
            .expect("query app table existence")
            .try_get(0)
            .expect("decode app table existence");
        assert_eq!(
            app_table.as_deref(),
            Some("audit_pool_none_applies"),
            "audit opt-out should still apply app-side DDL"
        );

        let audit_table: Option<String> = ctx
            .query_one("SELECT to_regclass('public.djogi_ddl_audit')::text", &[])
            .await
            .expect("query audit table existence")
            .try_get(0)
            .expect("decode audit table existence");
        assert_eq!(
            audit_table, None,
            "audit_pool = None should not bootstrap or write the audit table"
        );

        let _ = std::fs::remove_file(cleanup_path);
    }

    #[test]
    fn audit_signature_for_unset_key_path_is_zero_hex() {
        let key = audit_signing_key_from_loaded(Ok(None));
        let sig_hex = audit_signature_hex_for_snapshot(&empty_snapshot(), key)
            .expect("render audit signature");

        assert_eq!(
            sig_hex,
            "0".repeat(64),
            "an unset signing key should use the no-op key and persist zero hex"
        );
    }

    /// Phase 8.5 issue #118 — apply path with `audit_pool: Some` AND
    /// `snapshot: None` (the `db reset` replay shape) MUST still
    /// write `djogi_ddl_audit` rows. Pre-fix the audit-write loop
    /// was gated on snapshot presence inside the same `if let`
    /// block as `save_snapshot`, so production reset (which passes
    /// `snapshot: None`) silently bypassed the audit overlay even
    /// though the pool was wired through.
    ///
    /// Distinguishing assertion: `snapshot_signature_hex` is `NULL`
    /// (not the no-op zero hex) — `NULL` is the contract for
    /// "no snapshot was supplied this apply".
    #[allow(clippy::await_holding_lock)]
    #[djogi_test]
    async fn apply_plan_writes_audit_rows_when_snapshot_none(mut ctx: DjogiContext) {
        let _signing_key_env = SigningKeyEnvUnsetGuard::unset();
        let plan = single_table_plan("audit_snapshot_none_applies");
        let audit_pool = ctx
            .share_pool()
            .expect("djogi_test context should be pool-backed")
            .inner;
        // Build the runner ctx with audit_pool=Some BUT snapshot=None
        // — this is the production `db reset` replay shape that the
        // pre-fix code path could not service.
        let runner_ctx = RunnerCtx {
            bucket: plan.bucket.clone(),
            version: "V20260509000001__reset_audit_test".to_string(),
            description: "snapshot-none audit test".to_string(),
            checksum_up: compute_checksum_for_plan_up(&plan),
            checksum_down: None,
            snapshot: None,
            snapshot_path: None,
            config: MigrateConfig::default(),
            out_of_order_policy: crate::migrate::policy::OutOfOrderPolicy::AllowWithDiagnostic,
            audit_pool: Some(audit_pool),
        };
        let guard = acquire_test_workspace_guard();

        let report = apply_plan(&mut ctx, &plan, &runner_ctx, &guard)
            .await
            .expect("apply with audit_pool=Some and snapshot=None must succeed");
        assert_eq!(report.transactional_segments, 1);

        let row_count: i64 = ctx
            .query_one(
                "SELECT COUNT(*)::bigint FROM djogi_ddl_audit \
                 WHERE target_database = 'main' AND app_label = ''",
                &[],
            )
            .await
            .expect("count audit rows")
            .try_get(0)
            .expect("decode count");
        assert!(
            row_count >= 1,
            "expected at least one audit row when audit_pool=Some, even with snapshot=None; got {row_count}"
        );

        // Critical: signature column is NULL when no snapshot was
        // supplied. Distinguishes "no snapshot this apply" (NULL)
        // from "snapshot signed under no-op key" (zero hex). The
        // verify CLI's tolerant comparison treats NULL as a
        // no-stored-signature skip — see `verify::run`.
        let sig: Option<String> = ctx
            .query_one(
                "SELECT snapshot_signature_hex FROM djogi_ddl_audit \
                 WHERE target_database = 'main' AND app_label = '' \
                 ORDER BY id DESC LIMIT 1",
                &[],
            )
            .await
            .expect("read most recent audit row signature")
            .try_get(0)
            .expect("decode signature");
        assert_eq!(
            sig, None,
            "snapshot=None must persist NULL signature, not the no-op zero hex"
        );
    }

    #[djogi_test]
    async fn apply_plan_audit_failure_does_not_roll_back_app_db(mut ctx: DjogiContext) {
        let _signing_key_env = SigningKeyEnvReadGuard::hold();
        let plan = single_table_plan("audit_failure_survives");
        let snapshot_path = unique_temp_path("audit-failure-survives", "json");
        let cleanup_path = snapshot_path.clone();
        let audit_pool = crate::pg::pool::DjogiPool::builder(
            "postgres://djogi:djogi@127.0.0.1:1/djogi_unreachable",
        )
        .max_size(1)
        .timeout(Duration::from_millis(50))
        .build()
        .await
        .expect("build unreachable audit pool")
        .inner;
        let runner_ctx =
            runner_ctx_for_audit_with_snapshot_path(&plan, Some(audit_pool), Some(snapshot_path));
        let guard = acquire_test_workspace_guard();

        let report = apply_plan(&mut ctx, &plan, &runner_ctx, &guard)
            .await
            .expect("audit-side failure should not fail app-side apply");
        assert_eq!(report.transactional_segments, 1);

        let app_table: Option<String> = ctx
            .query_one(
                "SELECT to_regclass('public.audit_failure_survives')::text",
                &[],
            )
            .await
            .expect("query app table existence")
            .try_get(0)
            .expect("decode app table existence");
        assert_eq!(
            app_table.as_deref(),
            Some("audit_failure_survives"),
            "app-side DDL should remain committed when the audit DB is unavailable"
        );

        let _ = std::fs::remove_file(cleanup_path);
    }

    // ── B-1: RolledBack re-apply path ──────────────────────────────────────

    #[djogi::deliberately_bypass_convention_with_raw_sql]
    // JUSTIFICATION (PIN): Insert a RolledBack row to test the
    // classify_duplicate_version_collision function's handling of
    // non-terminal statuses. The public API has no insert_rolledback.
    #[djogi_test]
    async fn b1_rolledback_is_non_terminal_collision_class(mut ctx: DjogiContext) {
        // Verify that classify_duplicate_version_collision treats
        // RolledBack as non-terminal (VersionCollisionNonTerminal),
        // consistent with Decision 1 and the CLI's PendingOrPartial path.
        let version = "V20260526000001__b1_rolledback_test";

        ledger::bootstrap(&mut ctx).await.expect("bootstrap ledger");
        ctx.raw_execute(
            "INSERT INTO djogi_schema_migrations \
             (version, description, checksum_up, status, run_id, \
              snapshot_version, app_label) \
             VALUES ($1, 'b1 test', 'V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', \
                     'rolled_back', 99, '1.0', '')",
            &[&version],
        )
        .await
        .expect("insert RolledBack row");

        // Attempt to classify via the runner's collision path
        let result = classify_duplicate_version_collision(&mut ctx, version).await;
        match result {
            RunnerError::VersionCollisionNonTerminal { ref status, .. } => {
                assert!(
                    matches!(status, LedgerStatus::RolledBack),
                    "RolledBack should produce VersionCollisionNonTerminal, got {:?}",
                    status
                );
            }
            RunnerError::VersionAlreadyApplied { .. } => {
                panic!("RolledBack must NOT produce VersionAlreadyApplied (Decision 1)");
            }
            other => {
                panic!("unexpected error: {other:?}");
            }
        }
    }

    // ── B-1 regression guard: Pending status refusal ───────────────────────

    #[djogi::deliberately_bypass_convention_with_raw_sql]
    // JUSTIFICATION (PIN): Insert a Pending row to verify the
    // classify_duplicate_version_collision function distinguishes
    // Pending from Failed/RolledBack. The public API has no
    // insert_pending_row helper for test fixtures.
    #[djogi_test]
    async fn b1_regression_pending_row_not_auto_deleted(mut ctx: DjogiContext) {
        let version = "V20260526000002__b1_pending_guard";

        ledger::bootstrap(&mut ctx).await.expect("bootstrap ledger");
        ctx.raw_execute(
            "INSERT INTO djogi_schema_migrations \
             (version, description, checksum_up, status, run_id, \
              snapshot_version, app_label) \
             VALUES ($1, 'b1 pending guard', 'V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', \
                     'pending', 98, '1.0', '')",
            &[&version],
        )
        .await
        .expect("insert Pending row");

        let result = classify_duplicate_version_collision(&mut ctx, version).await;
        match result {
            RunnerError::VersionCollisionNonTerminal { ref status, .. } => {
                assert!(
                    matches!(status, LedgerStatus::Pending),
                    "Pending should produce VersionCollisionNonTerminal, got {:?}",
                    status
                );
            }
            RunnerError::VersionAlreadyApplied { .. } => {
                panic!("Pending must NOT produce VersionAlreadyApplied");
            }
            other => {
                panic!("unexpected error: {other:?}");
            }
        }
    }

    // ── C-1: fake_apply_inner out-of-order enforcement ────────────────────

    #[djogi::deliberately_bypass_convention_with_raw_sql]
    // JUSTIFICATION (PIN): Insert an Applied row to simulate an
    // existing higher version for the out-of-order detection test.
    #[djogi_test]
    async fn c1_fake_apply_rejects_ooo_with_reject_policy(mut ctx: DjogiContext) {
        let higher_version = "V20260527000000__c1_higher_peer";

        ledger::bootstrap(&mut ctx).await.expect("bootstrap ledger");
        ctx.raw_execute(
            "INSERT INTO djogi_schema_migrations \
             (version, description, checksum_up, status, run_id, \
              snapshot_version, app_label) \
             VALUES ($1, 'c1 higher peer', 'V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', \
                     'applied', 97, '1.0', '')",
            &[&higher_version],
        )
        .await
        .expect("insert higher applied row");

        let plan = MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![Segment {
                kind: SegmentKind::Transactional,
                statements: vec![],
            }],
        };
        let runner_ctx = RunnerCtx {
            bucket: plan.bucket.clone(),
            version: "V20260526000000__c1_lower_version".to_string(),
            description: "c1 lower test".to_string(),
            checksum_up: "V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
                .to_string(),
            checksum_down: None,
            snapshot: None,
            snapshot_path: None,
            config: MigrateConfig {
                concurrent_warn_relpages: 5000,
                strict_concurrent_warnings: false,
                pk_flip_long_tx_threshold_secs: 30,
                pk_flip_join_table_option: Default::default(),
            },
            out_of_order_policy: crate::migrate::OutOfOrderPolicy::Reject,
            audit_pool: None,
        };

        let guard = acquire_test_workspace_guard();
        let result = fake_apply_plan(&mut ctx, &plan, &runner_ctx, &guard, "test reason").await;

        assert!(
            matches!(result, Err(RunnerError::OutOfOrderRejected { .. })),
            "fake-apply with Reject policy and higher peer should return OutOfOrderRejected, got: {result:?}"
        );
    }

    #[djogi::deliberately_bypass_convention_with_raw_sql]
    // JUSTIFICATION (PIN): Insert an Applied row for OOO detection test
    // and read ledger row to verify out_of_order_flag.
    #[djogi_test]
    async fn c1_fake_apply_allows_ooo_with_diagnostic_and_sets_flag(mut ctx: DjogiContext) {
        let higher_version = "V20260527000001__c1_higher_peer2";

        ledger::bootstrap(&mut ctx).await.expect("bootstrap ledger");
        ctx.raw_execute(
            "INSERT INTO djogi_schema_migrations \
             (version, description, checksum_up, status, run_id, \
              snapshot_version, app_label) \
             VALUES ($1, 'c1 higher peer 2', 'V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', \
                     'applied', 96, '1.0', '')",
            &[&higher_version],
        )
        .await
        .expect("insert higher applied row");

        let plan = MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![Segment {
                kind: SegmentKind::Transactional,
                statements: vec![],
            }],
        };
        let runner_ctx = RunnerCtx {
            bucket: plan.bucket.clone(),
            version: "V20260526000001__c1_lower_version2".to_string(),
            description: "c1 lower test 2".to_string(),
            checksum_up: "V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
                .to_string(),
            checksum_down: None,
            snapshot: None,
            snapshot_path: None,
            config: MigrateConfig {
                concurrent_warn_relpages: 5000,
                strict_concurrent_warnings: false,
                pk_flip_long_tx_threshold_secs: 30,
                pk_flip_join_table_option: Default::default(),
            },
            out_of_order_policy: crate::migrate::OutOfOrderPolicy::AllowWithDiagnostic,
            audit_pool: None,
        };

        let guard = acquire_test_workspace_guard();
        let result = fake_apply_plan(&mut ctx, &plan, &runner_ctx, &guard, "test reason").await;

        assert!(
            result.is_ok(),
            "fake-apply with AllowWithDiagnostic should succeed: {result:?}"
        );

        // Verify the ledger row has out_of_order_flag = true
        let rows = ctx
            .query_all(
                "SELECT out_of_order_flag FROM djogi_schema_migrations \
                 WHERE version = 'V20260526000001__c1_lower_version2'",
                &[],
            )
            .await
            .expect("query ledger");

        assert!(rows.len() == 1, "ledger row should exist");
        let ooo_flag: bool = rows[0].try_get(0).expect("get out_of_order_flag");
        assert!(
            ooo_flag,
            "out_of_order_flag should be true for OOO fake-apply"
        );
    }

    #[djogi::deliberately_bypass_convention_with_raw_sql]
    // JUSTIFICATION (PIN): Insert an Applied row for OOO note test
    // and read ledger row to verify note format.
    #[djogi_test]
    async fn c1_fake_apply_ooo_note_contains_override_reason(mut ctx: DjogiContext) {
        let higher_version = "V20260527000002__c1_higher_peer3";

        ledger::bootstrap(&mut ctx).await.expect("bootstrap ledger");
        ctx.raw_execute(
            "INSERT INTO djogi_schema_migrations \
             (version, description, checksum_up, status, run_id, \
              snapshot_version, app_label) \
             VALUES ($1, 'c1 higher peer 3', 'V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', \
                     'applied', 95, '1.0', '')",
            &[&higher_version],
        )
        .await
        .expect("insert higher applied row");

        let plan = MigrationPlan {
            bucket: bucket("main", ""),
            classification: Classification::Additive,
            segments: vec![Segment {
                kind: SegmentKind::Transactional,
                statements: vec![],
            }],
        };
        let runner_ctx = RunnerCtx {
            bucket: plan.bucket.clone(),
            version: "V20260526000002__c1_lower_version3".to_string(),
            description: "c1 lower test 3".to_string(),
            checksum_up: "V1:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
                .to_string(),
            checksum_down: None,
            snapshot: None,
            snapshot_path: None,
            config: MigrateConfig {
                concurrent_warn_relpages: 5000,
                strict_concurrent_warnings: false,
                pk_flip_long_tx_threshold_secs: 30,
                pk_flip_join_table_option: Default::default(),
            },
            out_of_order_policy: crate::migrate::OutOfOrderPolicy::AllowExplicit {
                override_reason: "merge window".to_string(),
            },
            audit_pool: None,
        };

        let guard = acquire_test_workspace_guard();
        let result =
            fake_apply_plan(&mut ctx, &plan, &runner_ctx, &guard, "schema pre-exists").await;

        assert!(
            result.is_ok(),
            "fake-apply with AllowExplicit should succeed: {result:?}"
        );

        // Verify the partial_apply_note contains both the reason and override
        let rows = ctx
            .query_all(
                "SELECT partial_apply_note FROM djogi_schema_migrations \
                 WHERE version = 'V20260526000002__c1_lower_version3'",
                &[],
            )
            .await
            .expect("query ledger");

        assert!(rows.len() == 1, "ledger row should exist");
        let note: String = rows[0].try_get(0).expect("get partial_apply_note");
        assert!(
            note.contains("faked at"),
            "note should contain 'faked at': {note}"
        );
        assert!(
            note.contains("reason: schema pre-exists"),
            "note should contain fake reason: {note}"
        );
        assert!(
            note.contains("out-of-order apply"),
            "note should contain out-of-order annotation: {note}"
        );
        assert!(
            note.contains("override: merge window"),
            "note should contain override reason: {note}"
        );
    }

    #[test]
    fn expand_partition_statement_partitioned_index_preserves_leaf_drop_down_sql() {
        let stmt = OperationSql {
            label: "PkFlipPartitionedIndex events_p".to_string(),
            up: "CREATE UNIQUE INDEX events_p_ts_id_desc_idx ON ONLY events_p (ts, id_desc);\n\
                 -- Per leaf: CREATE UNIQUE INDEX CONCURRENTLY <leaf>_ts_id_desc_idx\n"
                .to_string(),
            down: "DROP INDEX IF EXISTS events_p_ts_id_desc_idx;".to_string(),
            lossy: None,
        };

        let expanded = expand_partition_statement(
            &stmt,
            "events_p",
            &["events_p_a".to_string(), "events_p_b".to_string()],
            PartitionExpansionMode::ReplayStrict,
        )
        .expect("strict replay expansion with leaves");

        assert_eq!(
            expanded[0].label,
            "PkFlipPartitionedIndex events_p (parent-level)"
        );
        assert_eq!(
            expanded[0].down,
            "DROP INDEX IF EXISTS events_p_ts_id_desc_idx;"
        );
        // Leaf concurrent down: parent drop first (CASCADE for attached leaves),
        // then leaf drop (cleanup for unattached/partial-apply case).
        assert!(
            expanded.iter().any(|s| {
                s.label == "PkFlipPartitionedIndex events_p leaf=events_p_a (concurrent)"
                    && s.down
                        == "DROP INDEX IF EXISTS events_p_ts_id_desc_idx; \
                            DROP INDEX IF EXISTS events_p_a_ts_id_desc_idx"
            }),
            "leaf A concurrent must drop parent then leaf: {expanded:?}",
        );
        assert!(
            expanded.iter().any(|s| {
                s.label == "PkFlipPartitionedIndex events_p leaf=events_p_b (concurrent)"
                    && s.down
                        == "DROP INDEX IF EXISTS events_p_ts_id_desc_idx; \
                            DROP INDEX IF EXISTS events_p_b_ts_id_desc_idx"
            }),
            "leaf B concurrent must drop parent then leaf: {expanded:?}",
        );
        assert!(
            expanded
                .iter()
                .filter(|s| s.label.contains("(attach)"))
                .all(|s| s.down.is_empty()),
            "attach statements remain forward-only",
        );
    }

    #[test]
    fn expand_partition_statement_schema_qualified_leaf_in_drop_down_sql() {
        // When `lookup_partition_leaves` returns schema-qualified names
        // (e.g. "myschema.events_p_a"), CREATE INDEX must use the BARE
        // index name (Postgres forbids a schema on the index name), while
        // DROP INDEX and ATTACH PARTITION must re-qualify with the leaf's
        // schema. Regression test for GH #357 / #366.
        //
        // The parent statement here matches the real emitter format from
        // pk_flip.rs: bare index name, schema-qualified `ON ONLY` target,
        // and the underscore column form `id_desc` (not the space form
        // `id DESC`).
        let parent = "myschema.events_p";
        let leaves = vec![
            "myschema.events_p_a".to_string(),
            "myschema.events_p_b".to_string(),
        ];

        let plan = OperationSql {
            label: format!("PkFlipPartitionedIndex {parent}"),
            up: "CREATE UNIQUE INDEX events_p_ts_id_desc_idx ON ONLY myschema.events_p (ts, id_desc)"
                .to_string(),
            down: "DROP INDEX IF EXISTS myschema.events_p_ts_id_desc_idx".to_string(),
            lossy: None,
        };

        let expanded = expand_partition_statement(
            &plan,
            parent,
            &leaves,
            PartitionExpansionMode::ApplyLenient,
        )
        .expect("partition expansion should succeed");

        // parent-level + (concurrent + attach) per leaf = 1 + 2*2 = 5.
        assert_eq!(expanded.len(), 5);

        // Leaf A concurrent: bare index name, schema-qualified ON target,
        // `_desc` suffix (no space), both DROP targets schema-qualified.
        let leaf_a_concurrent = expanded
            .iter()
            .find(|s| s.label == "PkFlipPartitionedIndex myschema.events_p leaf=myschema.events_p_a (concurrent)")
            .expect("leaf A concurrent entry");
        assert_eq!(
            leaf_a_concurrent.up,
            "CREATE UNIQUE INDEX CONCURRENTLY events_p_a_ts_id_desc_idx ON myschema.events_p_a (ts, id_desc)",
        );
        assert_eq!(
            leaf_a_concurrent.down,
            "DROP INDEX IF EXISTS myschema.events_p_ts_id_desc_idx; DROP INDEX IF EXISTS myschema.events_p_a_ts_id_desc_idx",
        );

        // Leaf A attach: both index names schema-qualified, no down.
        let leaf_a_attach = expanded
            .iter()
            .find(|s| {
                s.label
                    == "PkFlipPartitionedIndex myschema.events_p leaf=myschema.events_p_a (attach)"
            })
            .expect("leaf A attach entry");
        assert_eq!(
            leaf_a_attach.up,
            "ALTER INDEX myschema.events_p_ts_id_desc_idx ATTACH PARTITION myschema.events_p_a_ts_id_desc_idx",
        );
        assert_eq!(leaf_a_attach.down, "");

        // Invariant locks across every concurrent entry.
        for entry in expanded.iter().filter(|s| s.label.contains("(concurrent)")) {
            // The bug being guarded: a schema-qualified index name in the
            // CREATE INDEX CONCURRENTLY statement (Postgres syntax error).
            assert!(
                !entry.up.contains("CONCURRENTLY myschema."),
                "concurrent up must not have schema in index name: {}",
                entry.up,
            );
            // The other bug: the space column form `id DESC` instead of the
            // underscore form the emitter actually produces.
            assert!(
                !entry.up.contains("id DESC"),
                "up must not contain space-form 'id DESC': {}",
                entry.up,
            );
        }
    }

    #[test]
    fn expand_partition_leaf_placeholders_replay_mode_refuses_empty_leaves() {
        let stmt = OperationSql {
            label: "PkFlipPartitionedIndex events_p".to_string(),
            up: "CREATE UNIQUE INDEX events_p_ts_id_desc_idx ON ONLY events_p (ts, id_desc);"
                .to_string(),
            down: "DROP INDEX IF EXISTS events_p_ts_id_desc_idx;".to_string(),
            lossy: None,
        };

        let err = expand_partition_statement(
            &stmt,
            "events_p",
            &[],
            PartitionExpansionMode::ReplayStrict,
        )
        .expect_err("strict replay must not replace a partition expansion with a no-op comment");

        match err {
            RunnerError::PartitionExpansionNoLeaves {
                parent,
                statement_label,
            } => {
                assert_eq!(parent, "events_p");
                assert_eq!(statement_label, "PkFlipPartitionedIndex events_p");
            }
            other => panic!("expected PartitionExpansionNoLeaves, got {other:?}"),
        }

        let lenient = expand_partition_statement(
            &stmt,
            "events_p",
            &[],
            PartitionExpansionMode::ApplyLenient,
        )
        .expect("apply mode keeps the existing empty-leaf fallback");
        assert_eq!(lenient.len(), 1);
        assert!(lenient[0].up.contains("pg_inherits returned 0 leaves"));
    }

    #[test]
    fn rollback_leaf_identity_mismatch_display() {
        let err = RollbackError::LeafIdentityMismatch {
            version: "001_create_users".to_string(),
            stored_leaf_identity: "public.users:public.users_p2024_01,public.users_p2024_02\n"
                .to_string(),
            current_leaf_identity: "public.users:public.users_p2024_01,public.users_p2024_03\n"
                .to_string(),
        };
        let msg = format!("{}", err);
        assert!(msg.contains("[D624]"));
        assert!(msg.contains("rollback refused"));
        assert!(msg.contains("partition leaf identity mismatch"));
        assert!(msg.contains("001_create_users"));
    }
}