djogi 0.1.0-alpha.17

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
//! Schema differ — compares two [`AppliedSchema`] values and emits
//! a typed [`SchemaDelta`] of structural operations classified by
//! reversibility / destructiveness.
//! # Operation taxonomy
//! Every difference between two schemas is encoded as one or more
//! [`SchemaOperation`] entries with a stable shape so the SQL emitter
//! the SQL emitter can lower them deterministically. Operations come in three
//! categories:
//! - **Table-level**: `AddTable` / `DropTable` / `RenameTable` /
//!   `MoveModelBetweenApps`.
//! - **Column-level**: `AddColumn` / `DropColumn` / `RenameColumn` /
//!   `AlterColumn` / `AddForeignKey` / `DropForeignKey`.
//! - **Other**: `AddIndex` / `DropIndex` / `AddEnum` / `DropEnum` /
//!   `AddEnumVariant` / `RenameApp` / `PkTypeFlip`.
//!   `RenameTable` and `RenameColumn` are emitted only when the new
//!   schema's `renamed_from` field flags the change as a rename. Without
//!   the annotation the differ emits a destructive `DropTable` +
//!   `AddTable` (or `DropColumn` + `AddColumn`) pair so unannotated
//!   "renames" cannot silently destroy data.
//! # Classification
//! Each [`SchemaDelta`] carries a [`Classification`]:
//! - `NoOp` — schemas are equal (no operations).
//! - `Additive` — every op is non-destructive: new tables, new
//!   nullable columns, new indexes, new enum variants. Safe to ship.
//! - `Reversible` — contains operations that are destructive in one
//!   direction but have a clean inverse (e.g. a `RenameTable` whose
//!   inverse is the symmetric rename). The runner treats reversible
//!   deltas the same as destructive but the down-migration is
//!   well-defined.
//! - `Destructive` — at least one operation removes data
//!   structurally (`DropTable`, `DropColumn`, `DropEnum`,
//!   `DropIndex`, `DropForeignKey`). The runner gates these behind
//!   `--allow-destructive`; the gate is runner-side state, not
//!   differ output, so the variant carries no payload.
//! - `Lossy` — a destructive op that would also lose row data with
//!   no recovery path (e.g. dropping a non-nullable column that has
//!   no default). Stricter than `Destructive`.
//! - `Unsupported { reason }` — the differ cannot lower the change
//!   safely (e.g. partition method change). Operator must hand-edit
//!   the migration.
//! - `PkTypeFlip` — at least one table changed its PK type variant
//!   (HeerId ↔ HeerIdRecencyBiased, RanjId ↔ RanjIdRecencyBiased).
//!   This is a **native classification** for PK type flips. It owns the full
//!   expand/contract orchestration including FK cascade composition.
//!   The migration engine handles it directly.
//! # No-op detection
//! [`diff_schemas`] returns a delta with `Classification::NoOp` and an
//! empty operations vector when the two schemas compare equal. The
//! runner short-circuits no-ops without touching the ledger.

use std::collections::{BTreeMap, BTreeSet};

use super::projection::BucketKey;
use super::schema::{
    AppliedSchema, ColumnSchema, EnumSchema, ExclusionConstraintSchema, ForeignKeySchema,
    GeneratedColumnSchema, IndexSchema, PkKindSchema, TableSchema,
};

/// Typed delta between two [`AppliedSchema`] values, scoped to a
/// single [`BucketKey`].
/// One [`SchemaDelta`] represents the migration for one `(database,
/// app)` bucket. Multi-bucket migrations are a `Vec<SchemaDelta>`
/// with deterministic bucket ordering — see
/// [`diff_bucket_maps`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaDelta {
    /// Which `(database, app)` bucket this delta describes.
    pub bucket: BucketKey,
    /// Operations in execution order — table creates before
    /// column-on-table changes; FK adds after both endpoints exist.
    pub operations: Vec<SchemaOperation>,
    /// Aggregate classification — the most-destructive flavour any
    /// operation triggered.
    pub classification: Classification,
}

/// One structural change between two schemas. The SQL emitter
/// lowers each variant into one or more `up`/`down` statements.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaOperation {
    /// New table with all of its columns + primary key + flags. The
    /// SQL emitter generates `CREATE TABLE` plus any column-level
    /// constraints; [`AddIndex`](Self::AddIndex) entries land
    /// separately so they can be batched into the
    /// non-transactional segment.
    AddTable(TableSchema),

    /// Existing table is gone from the new schema. **Destructive.**
    DropTable(String),

    /// Table whose name changed via `#[model(renamed_from = "old")]`.
    /// Emitted only when the new schema's `TableSchema.renamed_from`
    /// matches an existing table name in the old schema. Reversible.
    RenameTable { from: String, to: String },

    /// Column added to an existing table.
    AddColumn { table: String, column: ColumnSchema },

    /// Column removed. **Destructive.**
    DropColumn { table: String, column: String },

    /// Column renamed via `#[field(renamed_from = "old_name")]`.
    /// Reversible.
    RenameColumn {
        table: String,
        from: String,
        to: String,
    },

    /// Column type / nullability / default changed. The differ
    /// records the full new column shape so the SQL emitter can produce the right
    /// `ALTER COLUMN` sequence.
    AlterColumn {
        table: String,
        column: String,
        change: ColumnChange,
    },

    /// Foreign key added on a column.
    AddForeignKey {
        table: String,
        column: String,
        fk: ForeignKeySchema,
    },

    /// Foreign key dropped. The column may still exist; only the
    /// `REFERENCES` constraint is removed. The full
    /// [`ForeignKeySchema`] (including the cascade discipline that
    /// existed on the old side) is carried so the SQL emitter can produce a
    /// reversible rollback that restores the original `FOREIGN KEY
    /// ... REFERENCES ... ON DELETE ...` clause without operator
    /// hand-edit.
    /// drop carried only `(table, column)` and the rollback was a
    /// SQL comment.
    DropForeignKey {
        table: String,
        column: String,
        fk: ForeignKeySchema,
    },

    /// Index added.
    AddIndex(IndexSchema),

    /// Index dropped — carries the full [`IndexSchema`] so the
    /// segment planner can preserve the old index's
    /// `requires_out_of_transaction`, `extension_dependency`, and
    /// uniqueness shape when laddering the drop into the right
    /// segment kind. Dropping just the name (the previous shape)
    /// forced the emitter to re-derive metadata it shouldn't need to recover.
    DropIndex(IndexSchema),

    /// Table-level `EXCLUDE` constraint added on an existing table.
    /// Adding an `EXCLUDE` to a populated table classifies as
    /// [`OnlineSafetyClassification::OfflineOnly`] — Pg18 has no
    /// `NOT VALID` for `EXCLUDE`, so the live-migration two-phase
    /// staging pattern is structurally impossible. Empty-table
    /// additions still flow through this variant; the classifier
    /// gates on the row-count probe.
    /// `EXCLUDE` constraints declared at table-creation time are
    /// emitted inside the [`AddTable`](Self::AddTable) operation's
    /// inline DDL, never as a separate `AddExclusionConstraint`.
    AddExclusionConstraint {
        table: String,
        exclusion: ExclusionConstraintSchema,
    },

    /// Table-level `EXCLUDE` constraint dropped. The full schema is
    /// carried so the down migration can re-create the constraint
    /// without re-walking the descriptor.
    DropExclusionConstraint {
        table: String,
        name: String,
        exclusion: ExclusionConstraintSchema,
    },

    /// `CREATE TYPE ... AS ENUM` for a new Postgres enum.
    AddEnum(EnumSchema),

    /// `DROP TYPE` for an enum no longer referenced. **Destructive.**
    DropEnum(String),

    /// `ALTER TYPE ... ADD VALUE` — adding a variant to an existing
    /// enum. Removing variants is rejected (Postgres has no native
    /// `DROP VALUE`).
    AddEnumVariant {
        enum_name: String,
        variant: String,
        /// Anchor for the `BEFORE` / `AFTER` placement clause. `None`
        /// means "append at the tail" (no positional clause). The
        /// differ chooses, in priority order:
        /// 1. `Some(EnumVariantAnchor { kind: Before, variant: post })`
        ///    when there is a post-anchor variant in the new list
        ///    that already existed in the old list. This places the
        ///    new variant immediately before that anchor.
        /// 2. `Some(EnumVariantAnchor { kind: After, variant: pre })`
        ///    when there is no usable post-anchor but a pre-anchor
        ///    exists in both old and new lists. This is the case for
        ///    a tail-append onto an enum that already has variants
        ///    from the old list — the new variant lands `AFTER` the
        ///    last existing one. (`ALTER TYPE ... ADD VALUE 'x' AFTER
        /// 'y'` is deterministic Postgres DDL, so anchoring beats
        ///    bare append even though both produce the same physical
        ///    ordering.)
        /// 3. `None` only on degenerate or malformed inputs where no
        ///    anchor exists in the old list in either direction
        ///    e.g. every old variant has been concurrently dropped
        ///    (`Unsupported` upstream) OR a malformed snapshot where
        ///    the existing enum's variant list is empty (Postgres
        ///    rejects an empty-variant enum at `CREATE TYPE`, so this
        ///    is malformed-snapshot territory only — the runtime
        ///    enum-creation path also rejects it). In practice
        ///    [`pick_enum_variant_anchor`] returns `None` only on
        ///    these inputs; tail-appends with prior real variants
        ///    always land in case (2).
        ///    emitter unconditionally appended (no `BEFORE`/`AFTER`
        ///    clause) regardless of where the differ placed the variant.
        ///    Carrying an anchor variant name (rather than a positional
        ///    integer) makes the emission self-contained — the emitter
        ///    no longer needs the full new-variant list to resolve a
        ///    position.
        ///    description here to match the helper's actual behaviour
        ///    for tail-appends onto a non-empty enum.
        anchor: Option<EnumVariantAnchor>,
    },

    /// PK type changed within the supported flip pairs (HeerId ↔
    /// HeerIdRecencyBiased, RanjId ↔ RanjIdRecencyBiased). Triggers
    /// `Classification::PkTypeFlip` and is the entry point for the
    /// PK-flip expand/contract orchestration.
    /// **Production lifecycle.** The per-table flip op is emitted by
    /// the per-table differ ([`diff_pk_in_table`]). At the bucket-walk
    /// finalisation step ([`diff_bucket_maps`]) every per-table
    /// `PkTypeFlip` is **promoted** into a single
    /// [`SchemaOperation::PkTypeFlipGroup`] for that bucket — the
    /// group payload carries the parent table plus every dependent
    /// child / self-FK / join-table / partitioned-parent shape so the
    /// segment planner has the full transitive closure available
    /// without re-walking the schema. The standalone `PkTypeFlip`
    /// variant survives for unit-test reach-in fixtures and for
    /// snapshot-level differ assertions; production callers (compose,
    /// runner) only ever see `PkTypeFlipGroup` after the post-walk
    /// finalisation runs.
    PkTypeFlip {
        table: String,
        from: PkKindSchema,
        to: PkKindSchema,
    },

    /// Aggregated PK-type flip across one parent table and every
    /// dependent child whose FK references the parent's PK. Emitted
    /// by [`diff_bucket_maps`] from per-table [`PkTypeFlip`] ops at
    /// finalisation time. The segment planner consumes this single
    /// op to emit the multi-stage flip plan (preparation, autofill
    /// trigger install, backfill, concurrent unique index, NOT NULL
    /// proof, cutover) verbatim from the HeeRanjID playbook.
    /// **Why a group, not per-table.** The cutover transaction in
    /// the playbook (§4 / §6 / §7 / §9) is **one atomic Postgres
    /// transaction across parent and every child**. Without the
    /// grouping the segment planner would emit one isolated cutover
    /// per table and the shared atomic invariant would not hold.
    /// **Cycles + self-FK + join-table + partitioned** — the group
    /// records each via a typed sub-shape so the planner can switch
    /// on the playbook section that applies. A single delta typically
    /// carries one group per migrating parent; multi-parent flips
    /// (e.g. `tags` and `authors` migrating together) emit one group
    /// per parent and the operator composes them as one migration.
    PkTypeFlipGroup(PkTypeFlipGroup),

    /// Merged multi-parent PK-type flip — emitted when two or more
    /// parents share a cross-flipping join table (both parents
    /// flipping in the same delta AND a junction whose two FKs each
    /// reference one parent) AND
    /// [`PkFlipJoinTableOption::OptionA`] is in effect. Per playbook
    /// §7 (line 327 of `asc-to-desc.md`) Option A is the
    /// **stage-interleaved** mega-tx layout: all parents prepare in
    /// one transaction, all backfill in one segment, all index in
    /// one segment, all NOT-VALID-FK in one segment, all NOT-NULL-
    /// proof in one segment, and **one** atomic cutover transaction
    /// re-points every FK column on the join table at the new
    /// `id_desc` columns of every parent.
    /// **Why not just emit several `PkTypeFlipGroup`s back-to-back.**
    /// The segment planner used to lower each `PkTypeFlipGroup` as a
    /// full 5-segment plan and concatenate them. With a cross-
    /// flipping join table that scheme is incorrect — the winner's
    /// segment 3b emits `... FOREIGN KEY (tag_id_desc) REFERENCES
    /// jt_tags(id_desc) NOT VALID` against `jt_tags(id_desc)` that
    /// the loser's segment 1 has not yet created. Postgres rejects
    /// the migration mid-apply. This multi-parent variant is the
    /// structural fix.
    /// **Construction.** [`apply_pk_flip_join_table_option`] under
    /// Option A merges every cross-flipping cluster of single-parent
    /// `PkTypeFlipGroup` ops into one `PkTypeFlipMultiGroup` carrying
    /// the participating groups in alphabetical-by-parent order. The
    /// "winner takes ownership of the join table" rule still applies
    /// inside the merged group: only the alphabetically smallest
    /// parent's `join_tables` list keeps the cross-flipping entry
    /// (so the join table's shadow columns / triggers / indexes are
    /// installed once, not twice). Non-cross-flipping flips (no
    /// shared join table, or Option B) remain plain
    /// `PkTypeFlipGroup` ops.
    /// **Lowering.** [`crate::migrate::pk_flip::build_segments_multi`]
    /// builds a single 5-segment (or 7-segment when partitioned or
    /// FK-cascading) plan that, at each stage, emits every parent's
    /// stage-N statements in alphabetical order. The cutover (final
    /// segment) is one transaction; every parent's drop / rename /
    /// add-constraint statements run inside it.
    PkTypeFlipMultiGroup(Vec<PkTypeFlipGroup>),

    /// App rename via `#[app(renamed_from = "old_label")]`. The
    /// migration engine emits both a `git mv` of the per-app folder
    /// and a single `UPDATE djogi_schema_migrations SET app_label
    /// = 'new' WHERE app_label = 'old'` — the only sanctioned
    /// mutation of historical ledger rows (per v3 plan §6
    /// "Rename exception to append-only ledger").
    RenameApp { from: String, to: String },

    /// Model moved from one app to another via
    /// `#[model(moved_from_app = OldApp)]`. SQL is a no-op; only the
    /// per-app folder placement and the `app_label` UPDATE differ
    /// (per ruling).
    MoveModelBetweenApps {
        model: String,
        from_app: String,
        to_app: String,
    },

    /// Set / change / clear the table-level `COMMENT ON TABLE`
    /// metadata for `table`.
    /// Carries both `from` and `to` so the SQL emitter renders a
    /// fully reversible down side — `from = Some(prev)` restores the
    /// pre-operation comment, `from = None` rolls back to the
    /// commentless state with `COMMENT ON TABLE … IS NULL`. The
    /// differ filters no-op pairs (`(None, None)` and
    /// `(Some(a), Some(b))` with `a == b`) before emission. The op
    /// classifies as catalog-only (`OnlineSafe`) — `COMMENT ON` is a
    /// pure `pg_description` write with no row touch.
    SetTableComment {
        /// Table whose comment is being set / changed / cleared.
        table: String,
        /// Prior `COMMENT ON TABLE` value. `None` when no comment
        /// existed before the operation.
        from: Option<String>,
        /// Target `COMMENT ON TABLE` value. `None` clears the
        /// comment (lowered to `COMMENT ON TABLE … IS NULL`).
        to: Option<String>,
    },

    /// Set / change / clear table storage parameters.
    SetStorageParams {
        table: String,
        from: Option<String>,
        to: Option<String>,
    },

    /// Set / change / clear the explicit table tablespace.
    SetTablespace {
        table: String,
        from: Option<String>,
        to: Option<String>,
    },

    /// Catch-all for changes the differ recognised but cannot lower
    /// safely — non-flip PK transitions (e.g. `HeerId → Serial`),
    /// enum variant removals, partition method changes. Carries an
    /// operator-actionable reason. Drives
    /// [`Classification::Unsupported`].
    Unsupported { reason: String },
}

/// Detailed shape of a column-level alteration.
/// Keeps the differ's [`SchemaOperation::AlterColumn`] entry compact
/// while letting the SQL emitter dispatch on a typed enum rather than diffing
/// the full [`ColumnSchema`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColumnChange {
    /// `SET NOT NULL` / `DROP NOT NULL`.
    SetNullable(bool),

    /// `SET DEFAULT <expr>` / `DROP DEFAULT`.
    SetDefault(Option<String>),

    /// `ALTER COLUMN ... TYPE <new>`. Carries both old and new
    /// rendered SQL types so the emitter can decide whether a `USING`
    /// clause is needed, plus the optional adopter-supplied `using`
    /// expression for non-default cast paths.
    /// **`using` semantics.** `Some(expr)` is sourced from the AFTER
    /// column's `#[field(type_change_using = "<expr>")]`; the SQL
    /// emitter inlines the expression verbatim into the emitted
    /// `ALTER COLUMN … TYPE … USING (<expr>)` statement so adopters
    /// can perform non-default casts (e.g. `TEXT → UUID`) that
    /// Postgres refuses to convert automatically. `None` falls back to
    /// the framework's default `USING <col>::<new_type>` cast, which
    /// works for every pair Postgres accepts implicitly (e.g. widenings
    /// like `INTEGER → BIGINT`). The down-side rollback always uses
    /// the default cast — symmetric down-side USING expressions are
    /// not modelled because the rollback path is operator-owned in
    /// practice (the adopter hand-edits the emitted down SQL when
    /// the inverse cast also needs special handling).
    ChangeType {
        from: String,
        to: String,
        /// Adopter-supplied `USING` expression for the forward
        /// (apply) direction. `None` when the field carried no
        /// `#[field(type_change_using = "...")]` attribute.
        using: Option<String>,
    },

    /// A column's at-rest codec changed (added / swapped / removed) —
    /// `#[field(protected(codec = "<id>"))]` drift. Carries both sides so
    /// the classifier and offline emitter can name the transition.
    /// Emitted whenever `before.codec != after.codec`, **independent of
    /// whether `sql_type` also changed** — a codec→codec swap between two
    /// codecs with the same storage type (e.g. `aes256_gcm_v1` →
    /// `aes256_gcm_v2`, both BYTEA) leaves `sql_type` unchanged and would
    /// otherwise be invisible to the differ. Re-encoding every row under
    /// the new codec is never a plain SQL cast, so the classifier routes
    /// this `OfflineOnly` (add / drop codec) or `ExpandContract`
    /// (codec → codec) and never to an online in-place backfill. Online
    /// codec rotation is deferred (issue #371); v1 emits this op only on
    /// the offline compose path.
    CodecChange {
        /// Codec on the BEFORE (loaded-from-disk) side. `None` = the
        /// column was plaintext.
        from_codec: Option<String>,
        /// Codec on the AFTER (freshly-projected) side. `None` = the
        /// codec was dropped (codec → plaintext).
        to_codec: Option<String>,
    },

    /// `SET / DROP CHECK` constraint at the column level.
    /// Carries **both** the prior CHECK expression (`from`) and the new
    /// CHECK expression (`to`) so the SQL emitter can render a fully
    /// reversible down-migration. Without `from`, a `DROP CHECK`
    /// rollback would have no way to restore the original constraint
    /// the same lossy-rollback gap
    /// migrations on checked columns.
    /// Variant semantics — `(from, to)` pair:
    /// - `(None, None)` — never emitted; the differ filters no-op.
    /// - `(Some(b), Some(a))` with `b == a` — never emitted; differ
    ///   filters identical.
    /// - `(None, Some(expr))` — ADD CHECK. Up: `ADD CONSTRAINT ...
    /// CHECK (expr)`. Down: `DROP CONSTRAINT ...`.
    /// - `(Some(prior), None)` — DROP CHECK. Up: `DROP CONSTRAINT ...`.
    ///   Down: `ADD CONSTRAINT ... CHECK (prior)` — fully recoverable.
    /// - `(Some(b), Some(a))` with `b != a` — currently the differ
    ///   splits AMEND into two emissions: `(Some(b), None)` then
    ///   `(None, Some(a))`. The SQL emitter handles the merged form
    ///   too (DROP+ADD in one statement pair) for callers that may
    ///   want it later.
    SetCheck {
        /// Prior CHECK expression (the constraint already on the column).
        /// `None` when no CHECK existed before the operation.
        from: Option<String>,
        /// Target CHECK expression (the constraint after the operation).
        /// `None` to drop the constraint without replacement.
        to: Option<String>,
    },

    /// Column-level `UNIQUE` constraint flipped.
    SetUnique(bool),

    /// `#[field(index)]` flag flipped (column-level implicit index).
    /// **Deprecated path (backward-compat only).** The differ no longer
    /// emits this variant — field-level indexed columns are now projected
    /// into `AppliedSchema::indexes` as full `IndexSchema` entries, and
    /// `diff_indexes` handles the `AddIndex` / `DropIndex` pair for every
    /// transition shape including fresh-create. This variant is retained so
    /// pending migrations serialised before that change can still be applied.
    SetIndexed(bool),

    /// `GENERATED ALWAYS AS (<expr>) STORED` declaration changed.
    /// `from = None, to = Some(_)` adds a generated expression to a
    /// regular column; `from = Some(_), to = None` strips it; both
    /// `Some` with differing expressions is an expression change.
    /// All cases on populated tables classify as `OfflineOnly` because
    /// Postgres rewrites every row under `AccessExclusiveLock` to
    /// materialise / clear the stored expression. The empty-table
    /// case flows through the regular fast-path.
    SetGenerated {
        from: Option<GeneratedColumnSchema>,
        to: Option<GeneratedColumnSchema>,
    },

    /// Set / change / clear the column-level `COMMENT ON COLUMN`
    /// metadata. .
    /// Carries both `from` and `to` so the SQL emitter renders a
    /// fully reversible down side — `from = Some(prev)` restores the
    /// pre-operation comment, `from = None` rolls back to the
    /// commentless state with `COMMENT ON COLUMN … IS NULL`. The
    /// differ filters no-op pairs (`(None, None)` and
    /// `(Some(a), Some(b))` with `a == b`) before emission.
    SetComment {
        /// Prior `COMMENT ON COLUMN` value. `None` when no comment
        /// existed before the operation.
        from: Option<String>,
        /// Target `COMMENT ON COLUMN` value. `None` clears the
        /// comment (lowered to `COMMENT ON COLUMN … IS NULL`).
        to: Option<String>,
    },

    /// Identity-column declaration changed
    /// (`GENERATED BY DEFAULT / ALWAYS AS IDENTITY`).
    /// Transitions:
    /// - `from = None, to = Some(kind)` — add identity to existing
    ///   column. Lowered to
    ///   `ALTER TABLE t ALTER COLUMN c ADD <kind sql_clause>`.
    /// - `from = Some(_), to = None` — drop identity. Lowered to
    ///   `ALTER TABLE t ALTER COLUMN c DROP IDENTITY`.
    /// - `from = Some(a), to = Some(b)` (a ≠ b) — kind change
    ///   (BY DEFAULT ↔ ALWAYS). Lowered to
    ///   `ALTER TABLE t ALTER COLUMN c SET GENERATED <kind>`.
    ///   Identity columns are sequence-backed at the Postgres level;
    ///   the ADD migration triggers Postgres's own sequence allocation
    ///   and starts the sequence after MAX(c) for existing rows. No
    ///   Djogi-side backfill needed.
    SetIdentity {
        from: Option<crate::migrate::schema::IdentityKindSchema>,
        to: Option<crate::migrate::schema::IdentityKindSchema>,
    },
}

/// Anchor variant for an [`SchemaOperation::AddEnumVariant`] insertion.
/// Postgres `ALTER TYPE ... ADD VALUE 'new' [BEFORE|AFTER 'anchor']`
/// requires a real existing variant as the anchor. The differ
/// picks the anchor by walking the new variant list around the
/// inserted variant and finding the nearest neighbour that already
/// exists in the old list — see the doc on
/// [`SchemaOperation::AddEnumVariant::anchor`] for the exact priority.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumVariantAnchor {
    /// The existing variant the new value should be placed relative
    /// to. Must already exist in the enum at the time `ALTER TYPE`
    /// runs.
    pub variant: String,
    /// Whether to place the new variant before or after the anchor.
    pub kind: EnumVariantAnchorKind,
}

/// Direction of an [`EnumVariantAnchor`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnumVariantAnchorKind {
    /// `ALTER TYPE ... ADD VALUE 'new' BEFORE 'anchor'` — anchor is
    /// the variant that should sort immediately AFTER the new one.
    Before,
    /// `ALTER TYPE ... ADD VALUE 'new' AFTER 'anchor'` — anchor is
    /// the variant that should sort immediately BEFORE the new one.
    After,
}

/// Aggregated PK-type-flip group payload — see
/// [`SchemaOperation::PkTypeFlipGroup`] for the lifecycle contract.
/// **Determinism.** Every collection inside this struct is sorted
/// (table names alphabetically; column pairs by source column name)
/// so two runs of the differ produce byte-identical output. The
/// segment planner depends on this — its emitted SQL must be
/// reproducible across runs to satisfy the byte-equality regression
/// tests against the HeeRanjID playbook.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PkTypeFlipGroup {
    /// Postgres table name of the parent whose PK is flipping.
    pub parent_table: String,
    /// Source PK kind (e.g. `HeerId`).
    pub parent_from: PkKindSchema,
    /// Target PK kind (e.g. `HeerIdRecencyBiased`).
    pub parent_to: PkKindSchema,
    /// Direction of the flip — derived from `parent_from` /
    /// `parent_to` for convenience. Asc→Desc uses `heerid_to_desc` /
    /// `ranjid_to_desc`; Desc→Asc uses `heerid_to_asc` / `ranjid_to_asc`.
    pub direction: PkFlipDirection,
    /// Children with a single ascending-side FK pointing at
    /// `parent_table.id`. Each child gets its own `_desc` shadow
    /// column, NOT-VALID FK, backfill, index — all assembled into
    /// the shared cutover transaction. Sorted by table name then
    /// FK column for determinism.
    pub children: Vec<PkFlipChild>,
    /// Self-FK pairs — when `parent_table` has at least one FK
    /// pointing back at itself, those pairs migrate alongside the PK
    /// via a single multi-pair trigger install. `None` when the
    /// parent has no self-FK; when present, the `(src, dst)` list
    /// always begins with `("id", "id_desc")` followed by each
    /// self-FK column in alphabetical order.
    pub self_fk: Option<PkFlipSelfFk>,
    /// Join tables — junction tables whose `is_through` flag is set
    /// AND whose two FK columns both point at this parent (rare
    /// most join tables span two parents) OR participate via
    /// `join_table_partner`. Drives §7 of the playbook.
    pub join_tables: Vec<PkFlipJoinTable>,
    /// Cycles — pairs of tables with mutual FKs. Each cycle entry
    /// records the peer table name; the planner emits both FKs as
    /// `DEFERRABLE INITIALLY DEFERRED` and prefixes the cutover with
    /// `SET CONSTRAINTS ALL DEFERRED`. Sorted alphabetically.
    pub cycles: Vec<PkFlipCycle>,
    /// Partitioned-parent metadata — `Some(...)` when `parent_table`
    /// has a `PARTITION BY` declaration. The planner emits the §9
    /// PG 13+ shape (parent-level shadow column, parent-level
    /// trigger, per-partition backfill, per-partition unique index +
    /// parent UNIQUE placeholder + ATTACH, partitioned-parent PK via
    /// `ADD PRIMARY KEY (...)`). Per-partition leaf names are
    /// supplied at runtime via the runner because partition leaves
    /// are live-DB state, not descriptor state. The presence of
    /// `Some` here is the trigger; the runner reads `pg_inherits`
    /// to enumerate leaves at apply time.
    pub partitioned_parent: Option<PkFlipPartitionedMeta>,
    /// Co-existing destructive ops in the same delta. Mirrors the
    /// per-delta `co_destructive` flag — duplicated here so the SQL
    /// emitter / runner can decide gating without re-walking the
    /// delta classification.
    pub co_destructive: bool,
    /// Co-existing lossy ops in the same delta.
    pub co_lossy: bool,
    /// Join-table cutover layout — `OptionA` (default) emits one
    /// shared cutover transaction across both parents and the join
    /// table per playbook §7; `OptionB` splits the cutover into
    /// sequential per-parent migrations. Set by the differ from
    /// [`crate::config::MigrateConfig::pk_flip_join_table_option`]
    /// at delta-construction time so the planner reads the operator-
    /// chosen layout straight from the group without needing the
    /// `MigrateConfig` plumbed through to lowering. The default
    /// value is `OptionA`; the differ overrides it per the operator
    /// config when the delta is built. **Behaviourally,** Option B
    /// emits a smaller cutover statement set per group — the join
    /// table's partner-side FK statements are deferred to the next
    /// flip group's cutover instead of bundled into this one.
    pub join_table_option: PkFlipJoinTableOption,
}

/// Join-table cutover layout. Mirrors the operator-facing knob in
/// [`crate::config::MigrateConfig::pk_flip_join_table_option`]
/// (which carries an ASCII `'A'` / `'B'` because TOML doesn't have
/// a strongly-typed enum). The differ converts the config char to
/// this enum once and writes it onto every emitted
/// [`PkTypeFlipGroup`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PkFlipJoinTableOption {
    /// Single mega-transaction covers both parents + the join table
    /// in one cutover (playbook §7 default).
    OptionA,
    /// Sequential per-parent flips. The current flip group's cutover
    /// only re-points `fk_to_parent_column`; the partner FK on the
    /// same join table is left for the second parent's flip group
    /// to re-point in its own cutover.
    OptionB,
}

impl PkFlipJoinTableOption {
    /// Parse from the [`crate::config::MigrateConfig`] char value.
    /// Anything other than `'B'` (case-insensitive) maps to
    /// [`PkFlipJoinTableOption::OptionA`] — keeping the unknown-
    /// value fallback aligned with the safer default.
    pub fn from_config_char(c: char) -> Self {
        match c {
            'B' | 'b' => Self::OptionB,
            _ => Self::OptionA,
        }
    }
}

/// Walk a list of [`SchemaDelta`]s and overwrite every emitted
/// [`PkTypeFlipGroup`]'s `join_table_option` with the operator-
/// configured value.
/// **When to call.** After [`diff_bucket_maps`] has produced the
/// per-bucket deltas and before the segment planner is invoked.
/// The compose pipeline + `db reset` replay both call this helper
/// so the operator's TOML choice reaches the planner.
/// **Idempotent.** Calling twice with the same option is a no-op.
/// **Multi-parent merge.** Under
/// [`PkFlipJoinTableOption::OptionA`] the function does more than
/// stamp the option — it MERGES every cluster of cross-flipping
/// `PkTypeFlipGroup` ops in a delta into a single
/// [`SchemaOperation::PkTypeFlipMultiGroup`]. The merger is what
/// makes Option A's "single mega-transaction" semantics structurally
/// realisable. Without merging, the segment planner lowers each
/// group as a back-to-back 5-segment plan, and the winner's segment
/// 3b emits `... FOREIGN KEY (tag_id_desc) REFERENCES
/// jt_tags(id_desc) NOT VALID` against a partner shadow column that
/// only lands in the loser's segment 1 — Postgres rejects the
/// migration mid-apply. The merged variant replaces N back-to-back
/// 5-segment plans with ONE stage-interleaved 5-segment plan that
/// emits every parent's stage-N statements together. Cluster
/// detection uses Union-Find over the join-table peer relation
/// (parents A and B share a cluster when at least one
/// `PkFlipJoinTable` in either group references the other parent
/// via `fk_to_partner_column = Some(_)` AND
/// `fk_to_partner_table = Some(<peer>)`).
pub fn apply_pk_flip_join_table_option(deltas: &mut [SchemaDelta], option: PkFlipJoinTableOption) {
    // First pass: stamp the option onto every emitted group.
    for delta in deltas.iter_mut() {
        for op in &mut delta.operations {
            if let SchemaOperation::PkTypeFlipGroup(group) = op {
                group.join_table_option = option;
            } else if let SchemaOperation::PkTypeFlipMultiGroup(groups) = op {
                // Idempotent re-stamp — `apply_pk_flip_join_table_option`
                // may run more than once during the compose pipeline
                // (e.g. tests that toggle the option). Stamp every
                // member group inside an existing multi-group too.
                for g in groups.iter_mut() {
                    g.join_table_option = option;
                }
            }
        }
    }
    // Under Option B leave the per-parent groups in place — the
    // sequential-per-parent layout each cutover only touches its
    // own FK column on the join table. Per-group `join_tables`
    // lists keep the cross-flipping entry on BOTH sides so each
    // group's `jt_shadow_pairs` returns the parent's pair and the
    // cutover finalises only that side of the join table; the
    // partner pair survives until the partner parent's group runs.
    if option != PkFlipJoinTableOption::OptionA {
        return;
    }
    // Under Option A, find every cross-flipping cluster of groups
    // and merge each cluster (of 2+ groups) into a
    // `PkTypeFlipMultiGroup` so the segment planner can lower the
    // cluster as ONE stage-interleaved 5-segment plan. Single-
    // parent groups (no cross-flipping peer) stay as plain
    // `PkTypeFlipGroup` ops — the back-to-back layout is correct
    // for them because there is no partner shadow column to
    // reference.
    for delta in deltas.iter_mut() {
        merge_cross_flipping_groups_into_multi(delta).expect(
            "partitioned multi-parent clusters must already be rejected by diff_bucket_maps",
        );
    }
}

pub(crate) fn partitioned_multi_parent_cluster_error(
    groups: &[PkTypeFlipGroup],
) -> Option<DiffError> {
    if groups.len() < 2 {
        return None;
    }
    let mut partitioned_parents: Vec<String> = groups
        .iter()
        .filter(|g| g.partitioned_parent.is_some())
        .map(|g| g.parent_table.clone())
        .collect();
    if partitioned_parents.is_empty() {
        return None;
    }
    partitioned_parents.sort();
    partitioned_parents.dedup();

    let mut cross_flipping_partners: Vec<String> =
        groups.iter().map(|g| g.parent_table.clone()).collect();
    cross_flipping_partners.sort();
    cross_flipping_partners.dedup();

    Some(DiffError::PartitionedMultiParentClusterUnsupported {
        partitioned_parents,
        cross_flipping_partners,
    })
}

fn cluster_pk_flip_groups(ops: &[SchemaOperation]) -> BTreeMap<String, Vec<&PkTypeFlipGroup>> {
    let groups: Vec<&PkTypeFlipGroup> = ops
        .iter()
        .filter_map(|op| match op {
            SchemaOperation::PkTypeFlipGroup(group) => Some(group),
            _ => None,
        })
        .collect();

    let mut peer_edges: BTreeSet<(String, String)> = BTreeSet::new();
    let mut rep: BTreeMap<String, String> = BTreeMap::new();
    for group in &groups {
        rep.insert(group.parent_table.clone(), group.parent_table.clone());
        for jt in &group.join_tables {
            if let Some(partner) = jt.fk_to_partner_table.as_deref() {
                let a = group.parent_table.clone();
                let b = partner.to_string();
                let edge = if a <= b { (a, b) } else { (b, a) };
                peer_edges.insert(edge);
            }
        }
    }
    if peer_edges.is_empty() {
        return BTreeMap::new();
    }

    fn find(rep: &mut BTreeMap<String, String>, x: &str) -> String {
        let mut cur = x.to_string();
        loop {
            let parent = rep.get(&cur).cloned().unwrap_or_else(|| cur.clone());
            if parent == cur {
                return cur;
            }
            let grand = rep.get(&parent).cloned().unwrap_or_else(|| parent.clone());
            rep.insert(cur.clone(), grand.clone());
            cur = grand;
        }
    }

    for (a, b) in &peer_edges {
        let ra = find(&mut rep, a);
        let rb = find(&mut rep, b);
        if ra != rb {
            let (winner, loser) = if ra <= rb { (ra, rb) } else { (rb, ra) };
            rep.insert(loser, winner);
        }
    }

    let mut clusters: BTreeMap<String, Vec<&PkTypeFlipGroup>> = BTreeMap::new();
    for group in groups {
        let root = find(&mut rep, &group.parent_table);
        clusters.entry(root).or_default().push(group);
    }
    clusters
}

fn reject_partitioned_multi_parent_clusters(ops: &[SchemaOperation]) -> Result<(), DiffError> {
    let clusters = cluster_pk_flip_groups(ops);

    for (_root, mut cluster) in clusters {
        if cluster.len() < 2 {
            continue;
        }
        cluster.sort_by(|a, b| a.parent_table.cmp(&b.parent_table));
        let member_set: BTreeSet<String> = cluster.iter().map(|g| g.parent_table.clone()).collect();
        let has_internal_cross_flip = cluster.iter().any(|group| {
            group.join_tables.iter().any(|jt| {
                jt.fk_to_partner_table
                    .as_ref()
                    .is_some_and(|partner| member_set.contains(partner))
            })
        });
        if !has_internal_cross_flip {
            continue;
        }
        let cluster_groups: Vec<PkTypeFlipGroup> = cluster.into_iter().cloned().collect();
        if let Some(err) = partitioned_multi_parent_cluster_error(&cluster_groups) {
            return Err(err);
        }
    }

    Ok(())
}

/// Errors the differ surfaces.
/// Distinct from [`super::sql::SqlEmitError`] — `DiffError`
/// reports failures that occur BEFORE SQL emission, during the
/// per-bucket walk and the PK-flip group promotion. Every variant
/// carries enough context for an actionable operator message.
/// Errors that can surface during PK-flip group promotion.
/// [`promote_pk_flips_to_groups`] returns structured errors instead of
/// panicking on contract violations. This enum carries context so the
/// operator can identify the offending structure (cycle, depth overflow, etc.).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffError {
    /// The PK-flip transitive FK closure walked more levels than
    /// [`promote_pk_flips_to_groups`]'s `MAX_CLOSURE_DEPTH` allows.
    /// The graph is pathological — likely an unbounded fan-out or
    /// a cycle the visited-set protection failed to short-circuit
    /// in time. The differ refuses to compose a migration over a
    /// graph it cannot reason about.
    PkFlipCascadeDepthExceeded {
        /// Postgres table name of the migrating parent that rooted
        /// the closure walk.
        parent_table: String,
        /// Trail of one representative table per depth level. The
        /// first entry is `parent_table`; subsequent entries are
        /// one (alphabetically-first) member of each next-frontier
        /// pass. Operators read this to identify the FK shape that
        /// triggered the depth blow-out.
        chain: Vec<String>,
        /// The maximum depth the closure was allowed to walk.
        /// Captured here so the operator-facing message can render
        /// the contract limit alongside the chain.
        max_depth: u32,
    },
    /// A cross-flipping cluster includes one or more partitioned
    /// parents. This is rejected because the multi-parent lowerer
    /// cannot safely interleave partitioned cutovers with
    /// partner-referencing join-table work.
    PartitionedMultiParentClusterUnsupported {
        /// Every partitioned parent in the cluster.
        partitioned_parents: Vec<String>,
        /// Every parent participating in the cross-flipping cluster.
        cross_flipping_partners: Vec<String>,
    },
    /// A `PkTypeFlipGroup` reached the lowering path with malformed
    /// self-FK metadata (sidecar vector lengths out of sync). This
    /// surfaces the underlying [`PkFlipError`] so the segment planner
    /// and related code never bypass validation.
    PkFlipMalformedSelfFkMetadata(super::pk_flip::PkFlipError),
}

impl From<super::pk_flip::PkFlipError> for DiffError {
    fn from(err: super::pk_flip::PkFlipError) -> Self {
        DiffError::PkFlipMalformedSelfFkMetadata(err)
    }
}

impl std::fmt::Display for DiffError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DiffError::PkFlipCascadeDepthExceeded {
                parent_table,
                chain,
                max_depth,
            } => write!(
                f,
                "PK-flip transitive FK closure exceeded {max_depth} levels rooted at \
                 {parent_table}; table_chain={chain:?}; graph likely has a pathological \
                 cycle or unbounded fan-out — refusing to compose the migration",
            ),
            DiffError::PkFlipMalformedSelfFkMetadata(err) => {
                write!(f, "diff lowering rejected a malformed PK-flip group: {err}")
            }
            DiffError::PartitionedMultiParentClusterUnsupported {
                partitioned_parents,
                cross_flipping_partners,
            } => write!(
                f,
                "PK-flip cross-flipping cluster mixes partitioned parents \
                 {partitioned_parents:?} with partners {cross_flipping_partners:?}; \
                 this unsupported multi-parent partitioned shape is rejected",
            ),
        }
    }
}

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

/// Merge every cross-flipping cluster of `PkTypeFlipGroup` ops in a
/// single delta into one [`SchemaOperation::PkTypeFlipMultiGroup`].
/// **What "cross-flipping" means.** A pair `(A, B)` of
/// `PkTypeFlipGroup`s is cross-flipping when at least one
/// `PkFlipJoinTable` entry in EITHER group records the other parent
/// via `fk_to_partner_table = Some(<peer>)` AND
/// `fk_to_partner_column = Some(_)`. The partner-table field is
/// recorded so the planner can resolve the cross-flipping shape
/// without re-walking the schema.
/// **Cluster construction (Union-Find).** Cross-flipping is
/// transitive — if A↔B share a join table and B↔C share a different
/// join table, the SQL emission needs ALL THREE in one mega-tx
/// because B's segment 3b would otherwise reference shadow columns
/// on both A and C that haven't landed yet. The merger therefore
/// uses Union-Find over the parent-table set, with edges drawn from
/// every cross-flipping `PkFlipJoinTable` entry. Clusters of size
/// 1 (no cross-flipping peer) stay as their original
/// `PkTypeFlipGroup` op; clusters of size 2+ are replaced by ONE
/// `PkTypeFlipMultiGroup` carrying the cluster's groups in
/// alphabetical-by-parent order.
/// **Winner-takes-all on join_tables.** Inside a merged cluster the
/// alphabetically smallest parent retains every cross-flipping
/// `PkFlipJoinTable` entry; the other members' `join_tables` are
/// emptied of cross-flipping entries (single-parent join tables
/// `fk_to_partner_column = None` — survive on whichever group owns
/// them). The lowering walks the multi-group's groups in order and
/// emits each member's stage-N statements at stage N; the winner's
/// stage-N is where the join table's stage-N statements appear, so
/// the join table's shadow column / trigger / index / FK / cutover
/// SQL is emitted exactly once per stage and references both
/// parents' `id_desc` columns that exist by the time stage-3b runs
/// (because every parent prepared in stage 1).
/// **Determinism.** Cluster ordering is deterministic — alphabetical
/// by the smallest parent in the cluster. Within a cluster, member
/// groups are alphabetical by `parent_table`. The same input
/// produces the same `PkTypeFlipMultiGroup` shape across runs,
/// preserving the byte-stable SQL guarantee.
fn merge_cross_flipping_groups_into_multi(delta: &mut SchemaDelta) -> Result<(), DiffError> {
    let clusters: BTreeMap<String, Vec<String>> = cluster_pk_flip_groups(&delta.operations)
        .into_iter()
        .map(|(root, members)| {
            (
                root,
                members
                    .into_iter()
                    .map(|group| group.parent_table.clone())
                    .collect(),
            )
        })
        .collect();

    // For each cluster of 2+ parents, drain those `PkTypeFlipGroup`
    // ops out of the operation list, apply the winner-takes-all
    // transfer of cross-flipping `PkFlipJoinTable` entries inside
    // the cluster, and push a single `PkTypeFlipMultiGroup` in
    // their place.
    let mut multi_groups: Vec<Vec<PkTypeFlipGroup>> = Vec::new();
    for (_rep, members) in clusters {
        if members.len() < 2 {
            continue;
        }
        // Stable membership lookup for the retain pass below.
        let mem_set: std::collections::BTreeSet<String> = members.iter().cloned().collect();
        let mut cluster_groups: Vec<PkTypeFlipGroup> = delta
            .operations
            .extract_if(.., |op| {
                matches!(
                    op,
                    SchemaOperation::PkTypeFlipGroup(g) if mem_set.contains(&g.parent_table)
                )
            })
            .filter_map(|op| match op {
                SchemaOperation::PkTypeFlipGroup(g) => Some(g),
                _ => None,
            })
            .collect();
        // Sort the cluster's groups alphabetically by parent_table
        // the lowering depends on this for deterministic stage-N
        // emission order.
        cluster_groups.sort_by(|a, b| a.parent_table.cmp(&b.parent_table));
        if let Some(err) = partitioned_multi_parent_cluster_error(&cluster_groups) {
            return Err(err);
        }

        // Winner-takes-all on cross-flipping join_tables. The
        // alphabetically smallest parent (cluster_groups[0]) keeps
        // every cross-flipping entry. Other members drop the
        // cross-flipping rows from their `join_tables` so the
        // join-table SQL is emitted exactly once per stage. Single-
        // parent (`fk_to_partner_column = None`) entries stay on
        // whichever group originally carried them.
        let cross_flipping_jt_names: std::collections::BTreeSet<String> = cluster_groups
            .iter()
            .flat_map(|g| {
                g.join_tables
                    .iter()
                    .filter(|jt| jt.fk_to_partner_column.is_some())
                    .map(|jt| jt.table.clone())
            })
            .collect();
        for (idx, g) in cluster_groups.iter_mut().enumerate() {
            if idx == 0 {
                // Winner — keep all cross-flipping entries; collect
                // any cross-flipping entries that lived on losers
                // and graft them onto the winner.
                continue;
            }
            g.join_tables.retain(|jt| {
                // Drop only cross-flipping entries shared with the
                // cluster — single-parent entries (no partner col)
                // stay where they are.
                !(jt.fk_to_partner_column.is_some() && cross_flipping_jt_names.contains(&jt.table))
            });
        }
        // Graft any cross-flipping entries that lived only on a
        // loser onto the winner (rare — typically the winner has
        // them already because both sides record the same join-
        // table). Without the graft, the winner would lower the
        // cluster missing one half of the join-table orchestration.
        let winner_existing: std::collections::BTreeSet<String> = cluster_groups[0]
            .join_tables
            .iter()
            .filter(|jt| jt.fk_to_partner_column.is_some())
            .map(|jt| jt.table.clone())
            .collect();
        // Re-collect from non-winner indices BEFORE we drop them
        // (which already happened above).
        // We need to iterate the original cluster's pre-mutation
        // join_tables to find any that should graft; but we already
        // mutated them. So instead, walk the deltas again with the
        // operation freshly drained: the winner_existing set tells
        // us which cross-flipping JTs the winner already covers; if
        // any cross_flipping_jt_names entry isn't in winner_existing,
        // it must have been dropped from a loser — but the loser's
        // entry was structurally symmetrical to the winner's (both
        // sides record the same `(jt, partner)` shape), so this
        // case should not arise in practice. We log and continue
        // rather than silently swallow; an asymmetric pair is a
        // differ bug.
        for jt_name in &cross_flipping_jt_names {
            if !winner_existing.contains(jt_name) {
                // Differ produced an asymmetric cross-flipping pair
                // one side recorded the partner, the other did
                // not. Defensive: skip the graft (the planner emits
                // the half it can see) rather than panic. Future
                // hardening: a `DiffError` for this case.
                continue;
            }
        }
        multi_groups.push(cluster_groups);
    }

    // Push every multi-group at the END of the operation list so
    // the planner reaches them after every other (single-parent)
    // group. The segment planner already iterates ops in input
    // order, so this produces a deterministic plan.
    for groups in multi_groups {
        delta
            .operations
            .push(SchemaOperation::PkTypeFlipMultiGroup(groups));
    }
    Ok(())
}

/// Direction of a PK-type flip.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PkFlipDirection {
    /// Ascending → descending. Uses `heerid_to_desc` /
    /// `ranjid_to_desc` and `heerid_next_desc()` / `ranjid_next_desc()`
    /// as the new column DEFAULT.
    AscToDesc,
    /// Descending → ascending. Uses `heerid_to_asc` / `ranjid_to_asc`
    /// and `heerid_next()` / `ranjid_next()` as the new column
    /// DEFAULT. The autofill trigger SQL is the symmetric mirror
    /// `IdKind::Heer.flip_fn()` always returns `heerid_to_desc` so
    /// the reverse-direction emitter substitutes `heerid_to_asc`
    /// directly in the trigger body it generates.
    DescToAsc,
}

/// Which family of generators (HeerId vs RanjId) the flip uses.
/// Derived from the PK kind variants on the group; cached on the
/// child / self-FK / join-table records so the planner can emit
/// the right generator name without re-deriving from the parent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PkFlipFamily {
    /// `BIGINT` PK, `heerid_to_desc` / `heerid_to_asc` /
    /// `heerid_next` / `heerid_next_desc`.
    Heer,
    /// `UUID` PK, `ranjid_to_desc` / `ranjid_to_asc` /
    /// `ranjid_next` / `ranjid_next_desc`.
    Ranj,
}

/// One child table whose FK to the migrating parent must follow the
/// flip into the shared cutover transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PkFlipChild {
    /// Postgres table name of the child.
    pub table: String,
    /// FK column on the child (e.g. `"author_id"` for a
    /// `books → authors` relation).
    pub fk_column: String,
    /// FK constraint name as recorded in the live DB. Composed via
    /// `<child_table>_<fk_column>_fkey` (Postgres' default convention
    /// when the schema didn't supply an explicit name); the runtime
    /// drops this exact constraint name during the cutover. The
    /// emitter uses this verbatim so a hand-named constraint that
    /// matches the convention round-trips unchanged.
    pub fk_constraint_name: String,
    /// Original FK cascade discipline, preserved through the cutover.
    pub on_delete: super::schema::OnDeleteSchema,
    /// Original FK deferrability flags. Preserved through the
    /// cutover so a deferrable source FK recreates as deferrable on
    /// the post-cutover column. Cycle peers force `deferrable = true,
    /// initially_deferred = true` regardless of descriptor input
    /// see [`PkTypeFlipGroup`] docs and playbook §8.
    pub fk_deferrable: bool,
    /// `true` iff the original FK was `INITIALLY DEFERRED`. Only
    /// meaningful when `fk_deferrable = true`.
    pub fk_initially_deferred: bool,
    /// Whether the child's FK column is nullable. Drives the
    /// playbook's §3.3 NULL-tracking invariant choice — nullable FKs
    /// allow NULL on the desc shadow.
    pub fk_nullable: bool,
    /// Whether the child's FK column is unique (enforced). Affects
    /// the index emitted on the desc shadow column (UNIQUE vs
    /// non-unique). Composite UNIQUE constraints on the FK column
    /// are not modelled here; the playbook's §3.4 emits a non-unique
    /// index on FK shadows by default.
    pub fk_unique: bool,
    /// HeerId vs RanjId family — derived from the child's column
    /// SQL type. Mirrors the parent's family in practice.
    pub family: PkFlipFamily,
    /// `true` when this child also participates in a mutual-FK cycle
    /// with the migrating parent (the parent has its own FK pointing
    /// back at this child). Cycle peers are regular children for
    /// every segment (preparation / backfill / concurrent index /
    /// NOT NULL proof / cutover) — the only delta is that their FK
    /// constraint at segment 3b is `DEFERRABLE INITIALLY DEFERRED`,
    /// and the cutover prefixes the body with `SET CONSTRAINTS ALL
    /// DEFERRED` so mid-transaction states are tolerated until the
    /// final `COMMIT`. See playbook §8 (asc-to-desc.md). The
    /// [`PkTypeFlipGroup::cycles`] vec preserves the cycle structure
    /// (peer column pairs) for diagnostics + cycle-detection in the
    /// emitter; this flag drives per-child SQL shape.
    pub cycle_flag: bool,
}

/// Self-FK metadata for a parent that references itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PkFlipSelfFk {
    /// Self-FK columns on the parent. Each entry is the FK column
    /// name (e.g. `"parent_id"` for a `nodes(parent_id REFERENCES
    /// nodes(id))`). Sorted alphabetically.
    pub fk_columns: Vec<String>,
    /// FK constraint names matching `fk_columns` index-for-index.
    pub fk_constraint_names: Vec<String>,
    /// Per-FK deferrability. Index-for-index with `fk_columns` /
    /// `fk_constraint_names`. Cycle path forces `true / true`.
    pub fk_deferrable: Vec<bool>,
    /// Per-FK `INITIALLY DEFERRED` flag. Same indexing as
    /// `fk_deferrable`. Only meaningful when the matching
    /// `fk_deferrable` entry is `true`.
    pub fk_initially_deferred: Vec<bool>,
}

/// Join-table metadata for a many-to-many junction whose two FK
/// columns reference the migrating parent (or one parent + one
/// non-migrating peer).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PkFlipJoinTable {
    /// Postgres table name of the join table.
    pub table: String,
    /// The FK column on this join table that points at the migrating
    /// parent. Always populated.
    pub fk_to_parent_column: String,
    /// FK constraint name for `fk_to_parent_column`.
    pub fk_to_parent_constraint: String,
    /// Original deferrability of the parent-side FK. Preserved
    /// through the cutover; defaults to `false` for non-deferrable
    /// FKs.
    pub fk_to_parent_deferrable: bool,
    /// `true` iff the parent-side FK was `INITIALLY DEFERRED`.
    /// Only meaningful when `fk_to_parent_deferrable = true`.
    pub fk_to_parent_initially_deferred: bool,
    /// The other FK column on this join table — either points at a
    /// second migrating parent (`Some(...)`) or at a non-migrating
    /// peer (`None`). When `Some`, the join table participates in
    /// **both** parents' migrations and the planner emits the
    /// multi-pair shadow-column install per §7 of the playbook.
    pub fk_to_partner_column: Option<String>,
    /// FK constraint name for `fk_to_partner_column`. `None` when
    /// `fk_to_partner_column` is `None`.
    pub fk_to_partner_constraint: Option<String>,
    /// Postgres table name the partner FK column references.
    /// `Some(_)` exactly when `fk_to_partner_column` is `Some(_)`
    /// the differ records both fields atomically so the planner
    /// can re-emit the partner's FK constraint targeting the
    /// correct parent table during the cutover. Required under
    /// Option A so the cutover's `ADD CONSTRAINT` statement points
    /// at the right partner table; `None` means single-parent join
    /// where this planner only ever emits the parent-side FK.
    pub fk_to_partner_table: Option<String>,
    /// Original deferrability of the partner-side FK. `false` for
    /// `None` partner. Preserved through the cutover.
    pub fk_to_partner_deferrable: bool,
    /// `true` iff the partner-side FK was `INITIALLY DEFERRED`.
    /// Only meaningful when `fk_to_partner_deferrable = true`.
    pub fk_to_partner_initially_deferred: bool,
    /// Family of the migrating parent's PK.
    pub family: PkFlipFamily,
}

/// One peer in an FK cycle that is migrating alongside this parent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PkFlipCycle {
    /// Postgres table name of the cycle peer.
    pub peer_table: String,
    /// FK column on `peer_table` pointing at this parent.
    pub peer_fk_column: String,
    /// FK column on this parent pointing at `peer_table`.
    pub self_fk_column: String,
}

/// Partitioned-parent metadata, set when the parent table has a
/// `PARTITION BY` declaration in its descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PkFlipPartitionedMeta {
    /// Partition strategy as recorded in the schema snapshot.
    pub partition: super::schema::PartitionSchema,
}

/// Aggregate flavour of a [`SchemaDelta`].
/// Computed from the operations in the delta. Severity ladder:
/// `NoOp` < `Additive` < `Reversible` < `Destructive` < `Lossy` <
/// `Unsupported`. `PkTypeFlip` is orthogonal: any delta carrying a
/// `PkTypeFlip` operation classifies as `PkTypeFlip`, but the
/// `co_destructive` / `co_lossy` flags surface co-existing severity
/// so the PK-flip orchestration knows whether the delta also drops a
/// column / index / FK or tightens a nullability — letting the
/// `--allow-destructive` gate fire even when the headline
/// classification is the flip.
/// `Destructive` no longer carries the runner-side
/// `allow_destructive` flag — that's a `djogi migrations apply`
/// argument, not a differ property. The runner reads its own opt-in
/// flag and gates `Destructive` / `Lossy` accordingly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Classification {
    /// Schemas compared equal. No operations emitted.
    NoOp,

    /// All operations are non-destructive: `AddTable`, `AddColumn`
    /// (nullable or default-having), `AddIndex`, `AddEnum`,
    /// `AddEnumVariant`, `AddForeignKey`.
    Additive,

    /// At least one rename, but no drops. Migration has a clean
    /// inverse.
    Reversible,

    /// At least one destructive operation (`DropTable`,
    /// `DropColumn`, `DropIndex`, `DropForeignKey`, `DropEnum`).
    /// Runner rejects until `--allow-destructive` is passed.
    Destructive,

    /// Destructive operation that loses row data with no fallback
    /// e.g. dropping a non-nullable, non-default column. Stricter
    /// than `Destructive`; runner rejects regardless of flag.
    Lossy,

    /// Differ cannot lower the change safely. Operator must hand-
    /// edit the migration.
    Unsupported { reason: String },

    /// At least one PK-type flip. Routes through the PK-flip
    /// expand/contract orchestration rather than the standard
    /// transactional apply.
    /// `co_destructive` / `co_lossy` surface co-existing severity so
    /// the gate logic can apply `--allow-destructive` semantics
    /// even when the headline classification is the flip. Without
    /// these flags a delta containing both `PkTypeFlip` and
    /// `DropColumn` would silently bypass the destructive gate.
    PkTypeFlip {
        co_destructive: bool,
        co_lossy: bool,
    },
}

/// Diff two snapshots within the same `(database, app)` bucket.
/// Returns `Classification::NoOp` with an empty operations vector
/// when the two schemas compare equal. The output's `bucket` is
/// taken verbatim — both `before` and `after` are expected to belong
/// to the same bucket; multi-bucket diffing is
/// [`diff_bucket_maps`]'s job.
/// `pub(crate)` because external consumers should always go through
/// [`diff_bucket_maps`] (which handles cross-bucket moves
/// correctly). `diff_schemas` is exposed within the crate for tests
/// and for the per-bucket worker in `diff_bucket_maps`.
pub(crate) fn diff_schemas(
    before: &AppliedSchema,
    after: &AppliedSchema,
    bucket: BucketKey,
) -> SchemaDelta {
    if before == after {
        return SchemaDelta {
            bucket,
            operations: Vec::new(),
            classification: Classification::NoOp,
        };
    }

    let mut ops: Vec<SchemaOperation> = Vec::new();

    // Build rename hint maps from the new schema. A new table whose
    // `renamed_from = Some("old")` and "old" exists in `before` is a
    // rename, not a drop+add. Same for column renames.
    let table_rename_targets: BTreeMap<&str, &str> = after
        .models
        .values()
        .filter_map(|t| {
            t.renamed_from
                .as_deref()
                .filter(|prev| before.models.contains_key(*prev))
                .map(|prev| (prev, t.table.as_str()))
        })
        .collect();
    let renamed_table_destinations: BTreeSet<&str> =
        table_rename_targets.values().copied().collect();

    // Tables — handle adds, drops, renames first; per-table column
    // diffs come after on the post-rename name.
    diff_tables(
        before,
        after,
        &table_rename_targets,
        &renamed_table_destinations,
        &mut ops,
    );

    // Indexes — diff after table renames so the index's `table` field
    // resolves to the new name.
    diff_indexes(before, after, &table_rename_targets, &mut ops);

    // Enums — symmetric add/drop/variant-add detection.
    diff_enums(before, after, &mut ops);

    // App moves — `TableSchema.moved_from_app` differs across
    // schemas means the model crossed buckets. The diff_schemas
    // entry point handles within-bucket only; cross-bucket moves
    // are emitted by `diff_bucket_maps`.

    let classification = classify(&ops);
    SchemaDelta {
        bucket,
        operations: ops,
        classification,
    }
}

/// Diff full per-bucket maps. Emits one [`SchemaDelta`] per bucket
/// that exists in either side. Cross-bucket operations
/// (`MoveModelBetweenApps`, `RenameApp`) are placed on the
/// destination bucket's delta.
pub fn diff_bucket_maps(
    before: &BTreeMap<BucketKey, AppliedSchema>,
    after: &BTreeMap<BucketKey, AppliedSchema>,
) -> Result<Vec<SchemaDelta>, DiffError> {
    // Phase 1 — pre-scan for cross-bucket moves driven by
    // `TableSchema.moved_from_app`. A model with `moved_from_app =
    // Some("billing")` in the after-schema, whose table name was
    // present in the before-schema's `(database, "billing")` bucket,
    // is a single logical move. Without this pre-scan, the per-bucket
    // diff would emit a spurious `DropTable` on the source bucket
    // and `AddTable` on the destination bucket — losing the
    // semantics of the move and forcing a destructive classification
    // when the change is structurally additive.
    let mut moves: Vec<(BucketKey, BucketKey, String)> = Vec::new();
    let mut suppressed_drops: BTreeSet<(BucketKey, String)> = BTreeSet::new();
    let mut suppressed_adds: BTreeSet<(BucketKey, String)> = BTreeSet::new();
    for (dest_bucket, dest_schema) in after {
        for (table_name, table) in &dest_schema.models {
            let Some(from_app) = table.moved_from_app.as_deref() else {
                continue;
            };
            // Source bucket = same database, prior app label.
            let src_bucket = BucketKey {
                database: dest_bucket.database.clone(),
                app: from_app.to_string(),
            };
            let Some(src_schema) = before.get(&src_bucket) else {
                // Source bucket isn't in `before`. The
                // `moved_from_app` annotation is unrooted; treat as
                // ordinary AddTable on the destination side.
                continue;
            };
            if !src_schema.models.contains_key(table_name) {
                // Source bucket exists but the table isn't there.
                // Same outcome — treat as ordinary AddTable.
                continue;
            }
            moves.push((src_bucket.clone(), dest_bucket.clone(), table_name.clone()));
            suppressed_drops.insert((src_bucket, table_name.clone()));
            suppressed_adds.insert((dest_bucket.clone(), table_name.clone()));
        }
    }

    let mut buckets: BTreeSet<BucketKey> = BTreeSet::new();
    buckets.extend(before.keys().cloned());
    buckets.extend(after.keys().cloned());

    let mut out = Vec::with_capacity(buckets.len());
    let empty = AppliedSchema {
        djogi_version: String::new(),
        enums: BTreeMap::new(),
        format_version: super::schema::SNAPSHOT_FORMAT_VERSION.to_string(),
        generated_at: String::new(),
        indexes: Vec::new(),
        models: BTreeMap::new(),
        registered_apps: Vec::new(),
    };
    for bucket in buckets {
        let b = before.get(&bucket).unwrap_or(&empty);
        let a = after.get(&bucket).unwrap_or(&empty);
        let mut delta = diff_schemas(b, a, bucket.clone());

        // Suppress DropTable on the source bucket and AddTable on
        // the destination bucket for any logical cross-bucket move.
        delta.operations.retain(|op| match op {
            SchemaOperation::DropTable(name) => {
                !suppressed_drops.contains(&(bucket.clone(), name.clone()))
            }
            SchemaOperation::AddTable(t) => {
                !suppressed_adds.contains(&(bucket.clone(), t.table.clone()))
            }
            _ => true,
        });

        // Emit `MoveModelBetweenApps` on the DESTINATION bucket so the
        // operation lands once and on the side compose anchors
        // its `git mv` against.
        for (src_bucket, dest_bucket, model) in &moves {
            if dest_bucket == &bucket {
                delta
                    .operations
                    .push(SchemaOperation::MoveModelBetweenApps {
                        model: model.clone(),
                        from_app: src_bucket.app.clone(),
                        to_app: dest_bucket.app.clone(),
                    });
            }
        }

        // PK-flip finalisation: aggregate every per-table `PkTypeFlip` op
        // into a `PkTypeFlipGroup` enriched with FK cascade /
        // self-FK / join-table / cycle / partition metadata. The
        // grouping uses the new schema (`a`) as the source of truth
        // for FK relations because that is the post-migration shape
        // every child has to align with — pulling FK metadata from
        // `before` would miss children that gained their FK in this
        // same migration (rare but legal).
        // Closure depth blow-out propagates as a structured
        // `DiffError` rather than panicking — the caller
        // (compose / build) renders the chain in the operator message.
        promote_pk_flips_to_groups(a, &mut delta.operations)?;
        reject_partitioned_multi_parent_clusters(&delta.operations)?;

        // Re-classify after the suppression + emission step.
        delta.classification = classify(&delta.operations);
        out.push(delta);
    }
    Ok(out)
}

/// Walk a delta's operation list, find every per-table
/// [`SchemaOperation::PkTypeFlip`], and promote them to
/// [`SchemaOperation::PkTypeFlipGroup`] with full FK cascade /
/// self-FK / join-table / cycle / partition metadata.
/// **In-place rewrite.** The per-table flip op is removed; the new
/// group op is pushed onto the operation list (after every other op
/// to preserve the existing ordering invariants — the segment
/// planner will hoist the group into its own dedicated multi-segment
/// plan regardless of position). When no flip is present the fn is a
/// pure no-op.
/// **Determinism.** Children, self-FK columns, join tables, and
/// cycles are sorted alphabetically before being attached to the
/// group so the byte-equality regression tests against the playbook
/// SQL are reproducible run-to-run.
fn promote_pk_flips_to_groups(
    after: &AppliedSchema,
    ops: &mut Vec<SchemaOperation>,
) -> Result<(), DiffError> {
    // Collect parents — `(table, from, to)` for every PkTypeFlip op.
    let mut parents: Vec<(String, PkKindSchema, PkKindSchema)> = Vec::new();
    ops.retain(|op| match op {
        SchemaOperation::PkTypeFlip { table, from, to } => {
            parents.push((table.clone(), from.clone(), to.clone()));
            false
        }
        _ => true,
    });
    if parents.is_empty() {
        return Ok(());
    }
    // Migrating-parent set — used by join-table detection (a join
    // table's "partner" FK column points at another migrating parent
    // when both tables are flipping in this delta). Owned strings
    // because we move `parents` below.
    let migrating_parents: BTreeSet<String> = parents.iter().map(|(t, _, _)| t.clone()).collect();

    // Helper: which family does this PK kind belong to?
    fn family_for_kind(k: &PkKindSchema) -> Option<PkFlipFamily> {
        match k {
            PkKindSchema::HeerId | PkKindSchema::HeerIdRecencyBiased => Some(PkFlipFamily::Heer),
            PkKindSchema::RanjId | PkKindSchema::RanjIdRecencyBiased => Some(PkFlipFamily::Ranj),
            _ => None,
        }
    }

    // Transitive FK closure.
    // For each migrating parent we collect every table whose FK
    // (directly or transitively) ranges over the parent's `id`
    // column's value space. The closure terminates because the FK
    // graph is finite and the worklist only ever grows by direct
    // children of an already-collected table.
    // **Why fixed-point is conservative for asc↔desc flips.** The
    // asc↔desc value distribution shift only re-keys the parent's
    // own PK column. A grandchild that points at a CHILD's `id` is
    // unaffected — C's `id` does not change in P's group. The
    // fixed-point therefore stabilises after one pass for
    // asc↔desc; the loop is here so future PK-type variants that
    // DO require transitive shadow columns (e.g., a hypothetical
    // BIGINT → TEXT key migration) inherit the closure for free.
    // **Cycle protection.** The worklist tracks visited tables in a
    // `BTreeSet` so a cycle of arbitrary length cannot loop the
    // closure indefinitely.
    for (parent_table, parent_from, parent_to) in parents {
        let direction = match (&parent_from, &parent_to) {
            (PkKindSchema::HeerId, PkKindSchema::HeerIdRecencyBiased)
            | (PkKindSchema::RanjId, PkKindSchema::RanjIdRecencyBiased) => {
                PkFlipDirection::AscToDesc
            }
            (PkKindSchema::HeerIdRecencyBiased, PkKindSchema::HeerId)
            | (PkKindSchema::RanjIdRecencyBiased, PkKindSchema::RanjId) => {
                PkFlipDirection::DescToAsc
            }
            // Should never happen — `is_pk_kind_flip` gates the
            // PkTypeFlip emission to only the four supported pairs.
            // Pin to AscToDesc as a defensive default; the planner
            // will surface a hard error if the parent kinds are
            // inconsistent with the rest of the group.
            _ => PkFlipDirection::AscToDesc,
        };
        let family = family_for_kind(&parent_from).unwrap_or(PkFlipFamily::Heer);

        // Children: every other table whose column.foreign_key
        // points at `parent_table`. Skip the parent itself (handled
        // via self_fk).
        let mut children: Vec<PkFlipChild> = Vec::new();
        let mut self_fk_cols: Vec<String> = Vec::new();
        let mut self_fk_constraints: Vec<String> = Vec::new();
        // Per-self-FK deferrability flags populated index-for-index
        // alongside `self_fk_cols` / `self_fk_constraints`.
        // Cycle path forces both to `true`.
        let mut self_fk_deferrable: Vec<bool> = Vec::new();
        let mut self_fk_initially_deferred: Vec<bool> = Vec::new();
        let mut join_tables: Vec<PkFlipJoinTable> = Vec::new();
        let mut cycles: Vec<PkFlipCycle> = Vec::new();

        for (other_table_name, other_table) in &after.models {
            for col in &other_table.columns {
                let Some(fk) = col.foreign_key.as_ref() else {
                    continue;
                };
                if fk.ref_table != parent_table {
                    continue;
                }
                let constraint_name = format!("{}_{}_fkey", other_table_name, col.name);
                if other_table_name == &parent_table {
                    // Self-FK pair.
                    self_fk_cols.push(col.name.clone());
                    self_fk_constraints.push(constraint_name);
                    self_fk_deferrable.push(fk.deferrable);
                    self_fk_initially_deferred.push(fk.initially_deferred);
                    continue;
                }
                // Detect cycle: does the parent reference back at
                // `other_table_name` via one of its own FK columns?
                let cycle_back = if let Some(parent_schema) = after.models.get(&parent_table) {
                    parent_schema.columns.iter().find_map(|pc| {
                        let pfk = pc.foreign_key.as_ref()?;
                        if pfk.ref_table == *other_table_name {
                            Some(pc.name.clone())
                        } else {
                            None
                        }
                    })
                } else {
                    None
                };
                if let Some(self_fk_col) = cycle_back {
                    cycles.push(PkFlipCycle {
                        peer_table: other_table_name.clone(),
                        peer_fk_column: col.name.clone(),
                        self_fk_column: self_fk_col,
                    });
                    // Cycle peers are first-class children. The peer's
                    // FK column needs the same shadow-column orchestration
                    // as any other child (preparation, backfill, index,
                    // NOT NULL proof, cutover) — without it the cutover
                    // SQL references a `_desc` column that was never
                    // created. The `cycle_flag = true` marker tells the
                    // segment FK emitter to attach `DEFERRABLE INITIALLY
                    // DEFERRED`, and the cutover `SET CONSTRAINTS ALL
                    // DEFERRED` tolerates mid-transaction FK states.
                    // Together these enforce deferred-constraints behavior.
                    children.push(PkFlipChild {
                        table: other_table_name.clone(),
                        fk_column: col.name.clone(),
                        fk_constraint_name: constraint_name,
                        on_delete: fk.on_delete,
                        // Cycle peers force deferrable +
                        // initially_deferred regardless of
                        // descriptor-side knobs. The cutover emits
                        // `SET CONSTRAINTS ALL DEFERRED` once at the
                        // top, but the recreated FK must ALSO be
                        // marked `DEFERRABLE INITIALLY DEFERRED` so
                        // future deferred-FK use still works post-flip.
                        // Without this the cycle downgrades to
                        // non-deferrable post-cutover.
                        fk_deferrable: true,
                        fk_initially_deferred: true,
                        fk_nullable: col.nullable,
                        fk_unique: col.unique,
                        family,
                        cycle_flag: true,
                    });
                    continue;
                }
                // Detect join-table: through-table whose two FKs
                // both reference parents in the migrating set OR a
                // through-table whose other FK references a peer
                // outside the migrating set.
                if other_table.is_through {
                    // Find the partner FK column (the OTHER FK on
                    // this through-table that does NOT point at
                    // this parent).
                    let partner = other_table.columns.iter().find_map(|pc| {
                        if pc.name == col.name {
                            return None;
                        }
                        let pfk = pc.foreign_key.as_ref()?;
                        if pfk.ref_table == parent_table {
                            return None;
                        }
                        Some((pc.name.clone(), pfk.ref_table.clone()))
                    });
                    let (partner_col, partner_constraint, partner_table) = match partner {
                        Some((pcol, partner_target))
                            if migrating_parents.contains(&partner_target) =>
                        {
                            // The other parent is also migrating
                            // join-table participates in both
                            // migrations. Recorded with `Some(...)`.
                            let pcons = format!("{}_{}_fkey", other_table_name, pcol);
                            (Some(pcol), Some(pcons), Some(partner_target))
                        }
                        _ => (None, None, None),
                    };
                    // Extract partner-side FK deferrability from the
                    // partner column (when present). Without this
                    // lookup the cutover can't preserve deferrable
                    // partner FKs.
                    let (partner_def, partner_init_def) =
                        if let Some(partner_col_name) = partner_col.as_deref() {
                            other_table
                                .columns
                                .iter()
                                .find(|c| c.name == partner_col_name)
                                .and_then(|c| c.foreign_key.as_ref())
                                .map(|fk| (fk.deferrable, fk.initially_deferred))
                                .unwrap_or((false, false))
                        } else {
                            (false, false)
                        };
                    join_tables.push(PkFlipJoinTable {
                        table: other_table_name.clone(),
                        fk_to_parent_column: col.name.clone(),
                        fk_to_parent_constraint: constraint_name,
                        fk_to_parent_deferrable: fk.deferrable,
                        fk_to_parent_initially_deferred: fk.initially_deferred,
                        fk_to_partner_column: partner_col,
                        fk_to_partner_constraint: partner_constraint,
                        fk_to_partner_table: partner_table,
                        fk_to_partner_deferrable: partner_def,
                        fk_to_partner_initially_deferred: partner_init_def,
                        family,
                    });
                    continue;
                }
                // Ordinary child.
                children.push(PkFlipChild {
                    table: other_table_name.clone(),
                    fk_column: col.name.clone(),
                    fk_constraint_name: constraint_name,
                    on_delete: fk.on_delete,
                    // Preserve descriptor-declared deferrability
                    // through the cutover.
                    fk_deferrable: fk.deferrable,
                    fk_initially_deferred: fk.initially_deferred,
                    fk_nullable: col.nullable,
                    fk_unique: col.unique,
                    family,
                    cycle_flag: false,
                });
            }
        }

        // Transitive FK closure (real, non-placeholder).
        // Walk the FK graph rooted at `parent_table` via BFS so the
        // visited-set grows to include indirect descendants. The
        // closure is bounded by `MAX_CLOSURE_DEPTH` and protected
        // against cycles by the visited-set itself.
        // **What `visited_tables` records.** Every table reachable
        // from `parent_table` via at least one FK that points at a
        // PK column of an already-visited table. For asc↔desc the
        // direct children list (`children`) is the only set whose
        // membership requires shadow-column orchestration — a
        // grandchild's FK column points at a CHILD's `id`, and the
        // child's `id` is itself a HeerId whose value space does NOT
        // re-key when the parent flips. The closure exists to:
        // 1. Detect cycles defensively (a real-world cycle of
        // arbitrary length cannot infinite-loop the differ).
        // 2. Terminate cleanly on a pathological graph
        // (`MAX_CLOSURE_DEPTH = 65`).
        // 3. Reserve the structural plumbing for a future PK-type
        // flip variant that DOES re-key grandchildren (e.g. a
        // hypothetical TEXT key change). Such a variant would
        // promote `visited_tables` membership to shadow-column
        // orchestration by extending this body — no rewrite of
        // the closure shape needed.
        // **Cascade-depth panic.** At depth > 65 the closure panics
        // with the chain of tables that drove the depth blow-out so
        // tests can detect the contract violation deterministically.
        let mut visited_tables: BTreeSet<String> = BTreeSet::new();
        visited_tables.insert(parent_table.clone());
        for c in &children {
            visited_tables.insert(c.table.clone());
        }
        for jt in &join_tables {
            visited_tables.insert(jt.table.clone());
        }

        // Bound the closure depth defensively. A real-world FK graph
        // is typically <5 levels; 65 gives us headroom while
        // guaranteeing termination on a malformed graph.
        const MAX_CLOSURE_DEPTH: u32 = 65;
        // Chain-of-tables tracker so a depth blow-out reports the
        // sequence that drove it (operator-actionable signal).
        let mut depth_chain: Vec<String> = vec![parent_table.clone()];
        // Frontier for BFS — the set of tables whose children we have
        // not yet enumerated. Seeded with everything in the visited
        // set so the first pass scans direct children of the parent
        // AND of every direct-child table (depth-2). The first pass
        // therefore picks up grandchildren; subsequent passes pick up
        // great-grandchildren; etc.
        let mut frontier: BTreeSet<String> = visited_tables.clone();

        for depth in 1u32..=MAX_CLOSURE_DEPTH {
            if frontier.is_empty() {
                break;
            }
            // Scan every table in `after.models` for FKs whose
            // `ref_table` is a member of the current frontier. New
            // hits become next-pass frontier.
            let mut next_frontier: BTreeSet<String> = BTreeSet::new();
            for (other_name, other_schema) in &after.models {
                if visited_tables.contains(other_name) {
                    continue;
                }
                for col in &other_schema.columns {
                    let Some(fk) = col.foreign_key.as_ref() else {
                        continue;
                    };
                    if frontier.contains(&fk.ref_table) {
                        next_frontier.insert(other_name.clone());
                        break;
                    }
                }
            }
            if next_frontier.is_empty() {
                break;
            }
            // Record one representative table from this depth so a
            // chain blow-out renders an operator-readable trail.
            if let Some(first) = next_frontier.iter().next() {
                depth_chain.push(first.clone());
            }
            for t in &next_frontier {
                visited_tables.insert(t.clone());
            }
            frontier = next_frontier;
            // The depth-65 contract returns a structured error
            // rather than panicking. The operator-facing message
            // renders the chain so the offending FK shape is
            // identifiable; compose / build surface the error.
            if depth == MAX_CLOSURE_DEPTH {
                return Err(DiffError::PkFlipCascadeDepthExceeded {
                    parent_table: parent_table.clone(),
                    chain: depth_chain.clone(),
                    max_depth: MAX_CLOSURE_DEPTH,
                });
            }
        }

        // Determinism: sort each collection.
        children.sort_by(|a, b| a.table.cmp(&b.table).then(a.fk_column.cmp(&b.fk_column)));
        join_tables.sort_by(|a, b| {
            a.table
                .cmp(&b.table)
                .then(a.fk_to_parent_column.cmp(&b.fk_to_parent_column))
        });
        cycles.sort_by(|a, b| a.peer_table.cmp(&b.peer_table));
        // Self-FK: pair the cols/constraints/deferrability flags in
        // alphabetical order. The zipped tuple carries per-FK
        // deferrability — `(col, cons, deferrable, initially_deferred)`.
        // The cycle path forces both flags to `true` further down.
        let mut self_fk_zipped: Vec<(String, String, bool, bool)> = self_fk_cols
            .into_iter()
            .zip(self_fk_constraints)
            .zip(self_fk_deferrable)
            .zip(self_fk_initially_deferred)
            .map(|(((c, n), d), id)| (c, n, d, id))
            .collect();
        self_fk_zipped.sort_by(|a, b| a.0.cmp(&b.0));
        let self_fk = if self_fk_zipped.is_empty() {
            None
        } else {
            let mut cols: Vec<String> = Vec::with_capacity(self_fk_zipped.len());
            let mut cons: Vec<String> = Vec::with_capacity(self_fk_zipped.len());
            let mut deferr: Vec<bool> = Vec::with_capacity(self_fk_zipped.len());
            let mut init_def: Vec<bool> = Vec::with_capacity(self_fk_zipped.len());
            for (c, n, d, id) in self_fk_zipped {
                cols.push(c);
                cons.push(n);
                deferr.push(d);
                init_def.push(id);
            }
            // Cycle path forces deferrable + initially_deferred on
            // every self-FK when the parent participates in any
            // mutual-FK cycle. Same rationale as the cycle children
            // above — the cutover's `SET CONSTRAINTS ALL DEFERRED`
            // signals the runner-side discipline; the recreated FK
            // must carry the deferrable property post-cutover so
            // future operator-driven deferred-FK use still works.
            if !cycles.is_empty() {
                for d in deferr.iter_mut() {
                    *d = true;
                }
                for d in init_def.iter_mut() {
                    *d = true;
                }
            }
            Some(PkFlipSelfFk {
                fk_columns: cols,
                fk_constraint_names: cons,
                fk_deferrable: deferr,
                fk_initially_deferred: init_def,
            })
        };

        // Partitioned-parent metadata — pulled from the post-flip
        // schema where the partition declaration lives.
        let partitioned_parent = after
            .models
            .get(&parent_table)
            .and_then(|t| t.partition.as_ref())
            .map(|p| PkFlipPartitionedMeta {
                partition: p.clone(),
            });

        // Co-flag values: re-derive locally because this fn runs
        // before `classify()` would have computed them. Walk the
        // remaining ops and check.
        let co_destructive = ops.iter().any(|op| {
            matches!(
                op,
                SchemaOperation::DropTable(_)
                    | SchemaOperation::DropColumn { .. }
                    | SchemaOperation::DropEnum(_)
                    | SchemaOperation::DropIndex(_)
                    | SchemaOperation::DropForeignKey { .. }
            )
        });
        let co_lossy = ops.iter().any(|op| match op {
            SchemaOperation::AlterColumn { change, .. } => {
                matches!(change, ColumnChange::SetNullable(false))
            }
            SchemaOperation::AddColumn { column, .. } => {
                !column.nullable && column.default_sql.is_none()
            }
            _ => false,
        });

        ops.push(SchemaOperation::PkTypeFlipGroup(PkTypeFlipGroup {
            parent_table,
            parent_from,
            parent_to,
            direction,
            children,
            self_fk,
            join_tables,
            cycles,
            partitioned_parent,
            co_destructive,
            co_lossy,
            // Default join-table layout — Option A. The compose
            // pipeline overrides this from
            // `MigrateConfig::pk_flip_join_table_option` after the
            // differ runs, before the planner lowers the group.
            // See `apply_join_table_option` for the override entry
            // point.
            join_table_option: PkFlipJoinTableOption::OptionA,
        }));
    }
    Ok(())
}

fn diff_tables(
    before: &AppliedSchema,
    after: &AppliedSchema,
    table_rename_targets: &BTreeMap<&str, &str>,
    renamed_table_destinations: &BTreeSet<&str>,
    ops: &mut Vec<SchemaOperation>,
) {
    // Tables present in `before` but not in `after` (and not the
    // source of a rename) — DropTable.
    for old_name in before.models.keys() {
        if after.models.contains_key(old_name) {
            continue;
        }
        if table_rename_targets.contains_key(old_name.as_str()) {
            // Renamed → handled below.
            continue;
        }
        ops.push(SchemaOperation::DropTable(old_name.clone()));
    }

    // Tables present in `after` but not in `before`, that are NOT
    // rename destinations — AddTable.
    for new_table in after.models.values() {
        if before.models.contains_key(&new_table.table) {
            // Common to both; handled below.
            continue;
        }
        if renamed_table_destinations.contains(new_table.table.as_str()) {
            continue;
        }
        ops.push(SchemaOperation::AddTable(new_table.clone()));
    }

    // Renames — `from -> to` plus per-column diff against the renamed
    // shape.
    for (from, to) in table_rename_targets {
        let before_table = &before.models[*from];
        let after_table = &after.models[*to];
        ops.push(SchemaOperation::RenameTable {
            from: (*from).to_string(),
            to: (*to).to_string(),
        });
        let column_renames = diff_columns_in_table(before_table, after_table, ops);
        diff_pk_in_table(before_table, after_table, &column_renames, ops);
        diff_exclusion_constraints_in_table(before_table, after_table, ops);
        diff_table_metadata_in_table(before_table, after_table, ops);
    }

    // Common tables (same name in both schemas) — column diff.
    for (name, after_table) in &after.models {
        let Some(before_table) = before.models.get(name) else {
            continue;
        };
        if before_table == after_table {
            continue;
        }
        let column_renames = diff_columns_in_table(before_table, after_table, ops);
        diff_pk_in_table(before_table, after_table, &column_renames, ops);
        diff_app_move_in_table(before_table, after_table, ops);
        diff_exclusion_constraints_in_table(before_table, after_table, ops);
        diff_table_metadata_in_table(before_table, after_table, ops);
    }
}

/// Detect changes to table-level DDL metadata between two snapshots of
/// the same table.
/// Currently handles:
/// - `table_comment` → [`SchemaOperation::SetTableComment`]
/// - `storage_params` → [`SchemaOperation::SetStorageParams`]
/// - `tablespace` → [`SchemaOperation::SetTablespace`]
///   Each slot emits one `SchemaOperation` when the before / after
///   values diverge; identical values produce no operation.
fn diff_table_metadata_in_table(
    before: &TableSchema,
    after: &TableSchema,
    ops: &mut Vec<SchemaOperation>,
) {
    // table comment. Only emit when the value actually
    // changes so two consecutive differ runs against the same source
    // produce byte-identical output.
    if before.table_comment != after.table_comment {
        ops.push(SchemaOperation::SetTableComment {
            table: after.table.clone(),
            from: before.table_comment.clone(),
            to: after.table_comment.clone(),
        });
    }
    if before.storage_params != after.storage_params {
        ops.push(SchemaOperation::SetStorageParams {
            table: after.table.clone(),
            from: before.storage_params.clone(),
            to: after.storage_params.clone(),
        });
    }
    if before.tablespace != after.tablespace {
        ops.push(SchemaOperation::SetTablespace {
            table: after.table.clone(),
            from: before.tablespace.clone(),
            to: after.tablespace.clone(),
        });
    }
}

/// Detect added / dropped / modified `EXCLUDE` constraints between two
/// snapshots of the same table. Constraint identity is the `name`
/// field — modifying any other field (`using`, elements, where_clause,
/// deferrability) emits a drop+add pair so the live system always sees
/// a single canonical shape per name.
fn diff_exclusion_constraints_in_table(
    before: &TableSchema,
    after: &TableSchema,
    ops: &mut Vec<SchemaOperation>,
) {
    let before_by_name: BTreeMap<&str, &ExclusionConstraintSchema> = before
        .exclusion_constraints
        .iter()
        .map(|e| (e.name.as_str(), e))
        .collect();
    let after_by_name: BTreeMap<&str, &ExclusionConstraintSchema> = after
        .exclusion_constraints
        .iter()
        .map(|e| (e.name.as_str(), e))
        .collect();

    // Drops first so the down migration is symmetric with the up.
    for (name, before_excl) in &before_by_name {
        if after_by_name.contains_key(name) {
            continue;
        }
        ops.push(SchemaOperation::DropExclusionConstraint {
            table: after.table.clone(),
            name: (*name).to_string(),
            exclusion: (*before_excl).clone(),
        });
    }

    // Adds (including drop+add for modified constraints).
    for (name, after_excl) in &after_by_name {
        match before_by_name.get(name) {
            Some(before_excl) if before_excl == after_excl => {}
            Some(before_excl) => {
                ops.push(SchemaOperation::DropExclusionConstraint {
                    table: after.table.clone(),
                    name: (*name).to_string(),
                    exclusion: (*before_excl).clone(),
                });
                ops.push(SchemaOperation::AddExclusionConstraint {
                    table: after.table.clone(),
                    exclusion: (*after_excl).clone(),
                });
            }
            None => {
                ops.push(SchemaOperation::AddExclusionConstraint {
                    table: after.table.clone(),
                    exclusion: (*after_excl).clone(),
                });
            }
        }
    }
}

fn diff_columns_in_table<'a>(
    before: &TableSchema,
    after: &'a TableSchema,
    ops: &mut Vec<SchemaOperation>,
) -> BTreeMap<&'a str, &'a str> {
    let before_cols: BTreeMap<&str, &ColumnSchema> = before
        .columns
        .iter()
        .map(|c| (c.name.as_str(), c))
        .collect();
    let after_cols: BTreeMap<&str, &ColumnSchema> =
        after.columns.iter().map(|c| (c.name.as_str(), c)).collect();

    // Column rename hints — same pattern as table renames.
    let column_rename_targets: BTreeMap<&str, &str> = after_cols
        .values()
        .filter_map(|c| {
            c.renamed_from
                .as_deref()
                .filter(|prev| before_cols.contains_key(prev))
                .map(|prev| (prev, c.name.as_str()))
        })
        .collect();
    let renamed_destinations: BTreeSet<&str> = column_rename_targets.values().copied().collect();

    // Drops (no rename source).
    for old_name in before_cols.keys() {
        if after_cols.contains_key(old_name) {
            continue;
        }
        if column_rename_targets.contains_key(old_name) {
            continue;
        }
        ops.push(SchemaOperation::DropColumn {
            table: after.table.clone(),
            column: (*old_name).to_string(),
        });
    }

    // Adds (not a rename destination).
    for new_col in after.columns.iter() {
        if before_cols.contains_key(new_col.name.as_str()) {
            continue;
        }
        if renamed_destinations.contains(new_col.name.as_str()) {
            continue;
        }
        ops.push(SchemaOperation::AddColumn {
            table: after.table.clone(),
            column: new_col.clone(),
        });
    }

    // Renames + alter on renamed columns.
    for (from, to) in &column_rename_targets {
        let bc = before_cols[from];
        let ac = after_cols[to];
        ops.push(SchemaOperation::RenameColumn {
            table: after.table.clone(),
            from: (*from).to_string(),
            to: (*to).to_string(),
        });
        emit_alter_column(after, bc, ac, ops);
    }

    // Common columns (same name on both sides) — alter.
    for (name, ac) in &after_cols {
        let Some(bc) = before_cols.get(name) else {
            continue;
        };
        if bc == ac {
            continue;
        }
        emit_alter_column(after, bc, ac, ops);
    }

    // Return the rename map so the PK differ can normalise column
    // names before flip-pair detection — addresses
    // "PK column rename + flip" edge case.
    column_rename_targets
}

fn emit_alter_column(
    parent: &TableSchema,
    before: &ColumnSchema,
    after: &ColumnSchema,
    ops: &mut Vec<SchemaOperation>,
) {
    let table = parent.table.clone();
    {
        let mut push = |change: ColumnChange| {
            ops.push(SchemaOperation::AlterColumn {
                table: table.clone(),
                column: after.name.clone(),
                change,
            });
        };
        let type_changed = before.sql_type != after.sql_type;
        // A codec add / swap / drop is owned by a dedicated `CodecChange` op
        // (below), NOT by `ChangeType`: a codec transition is a full row
        // re-encode, never a plain SQL cast, and a plaintext→codec transition
        // also flips VARCHAR→BYTEA (so `type_changed` would otherwise fire a
        // corrupting `<col>::BYTEA` cast). When the codec changed, the
        // `ChangeType` and the type-change CHECK-drop/re-add are suppressed so
        // `CodecChange` is the single owner of the transition (issue #371).
        let codec_changed = before.codec != after.codec;
        if type_changed && !codec_changed && before.check.is_some() {
            // If the old CHECK still references the pre-conversion type,
            // drop it before the type migration to avoid Postgres re-validating
            // it against the new type shape. The `from` carries the prior
            // expression so rollback can ADD it back after rolling the
            // type change back — without this, the down-side rollback
            // would leave the column un-checked (the bug
            // flagged: lossy CHECK rollback on type-changed columns).
            // Excluded when `codec_changed`: a codec transition emits no
            // `ChangeType`, so a lone CHECK-drop would have no paired
            // type-change rollback — the operator's offline re-encode owns
            // CHECK handling.
            push(ColumnChange::SetCheck {
                from: before.check.clone(),
                to: None,
            });
        }
        if type_changed && !codec_changed {
            // pull the adopter-supplied USING expression
            // from the AFTER column. The `type_change_using` slot is
            // `#[serde(skip)]` on `ColumnSchema`, so the BEFORE
            // (loaded-from-disk) side always carries `None`; only the
            // freshly-projected AFTER side ever carries `Some(...)`.
            // The expression is emitted verbatim into the migration's
            // `USING (<expr>)` clause; adopters own correctness.
            // Suppressed when `codec_changed`: a plaintext→codec transition
            // flips VARCHAR→BYTEA, and a plain `::BYTEA` cast would write
            // plaintext UTF-8 bytes into the "encrypted" column. The
            // `CodecChange` op below is the sole owner of that transition.
            push(ColumnChange::ChangeType {
                from: before.sql_type.clone(),
                to: after.sql_type.clone(),
                using: after.type_change_using.clone(),
            });
        }
        if codec_changed {
            // Codec add / swap / drop. Owns the transition regardless of
            // whether `sql_type` also flipped (plaintext→codec flips
            // VARCHAR→BYTEA; codec→codec between same-storage codecs does
            // not). Emitted unconditionally on `before.codec != after.codec`
            // so a same-`sql_type` codec swap is detectable at all — without
            // this op it would be a silent no-op (issue #371, Pre-flight §8).
            push(ColumnChange::CodecChange {
                from_codec: before.codec.clone(),
                to_codec: after.codec.clone(),
            });
        }
        if before.nullable != after.nullable {
            push(ColumnChange::SetNullable(after.nullable));
        }
        if before.default_sql != after.default_sql {
            push(ColumnChange::SetDefault(after.default_sql.clone()));
        }
        // CHECK constraint transitions — (non-lossy rollback).
        // Each emitted `SetCheck` carries both `from` (the CHECK on the
        // column at the start of this operation) and `to` (the CHECK
        // after this operation). The SQL emitter uses `from` for the
        // down-side, so rollback restores the prior CHECK rather than
        // leaving a comment-only placeholder.
        // The AMEND case stays as a two-step DROP+ADD pair so each
        // step maps cleanly to one `OperationSql` (one up, one down).
        // Composing the down file in reverse order (per
        // `compose::compose_down_text`) gives the operator:
        // step 2 down (DROP new), then step 1 down (ADD old)
        // returning the column to its prior CHECK shape.
        // For the type-change path, the post-type CHECK re-add carries
        // `from: None` because the prior `SetCheck { from: before.check,
        // to: None }` already dropped the original constraint at the
        // moment this entry runs. The composed down file rolls back
        // in reverse: drop the post-type CHECK, alter the type back,
        // re-add the original CHECK. Non-lossy.
        // Gated `&& !codec_changed` to match the type-change CHECK-drop above:
        // a codec transition emits no `ChangeType`, so there is no paired
        // type change for this CHECK re-add to accompany. When the codec
        // changed, CHECK handling falls through to the standard
        // `(before.check, after.check)` transition arm in the `else` branch
        // (a CHECK change orthogonal to the codec still emits normally).
        if type_changed && !codec_changed && before.check.is_some() {
            if let Some(check) = &after.check {
                push(ColumnChange::SetCheck {
                    from: None,
                    to: Some(check.clone()),
                });
            }
        } else {
            match (&before.check, &after.check) {
                (None, None) => {}                 // unchanged
                (Some(b), Some(a)) if b == a => {} // unchanged
                (Some(b), Some(a)) => {
                    // AMEND — drop the old constraint, then add the new.
                    // Each step carries its full (from, to) so rollback
                    // is symmetric.
                    push(ColumnChange::SetCheck {
                        from: Some(b.clone()),
                        to: None,
                    });
                    push(ColumnChange::SetCheck {
                        from: None,
                        to: Some(a.clone()),
                    });
                }
                // ADD (None → Some) — one entry, lossless rollback via
                // DROP CONSTRAINT.
                (None, Some(a)) => {
                    push(ColumnChange::SetCheck {
                        from: None,
                        to: Some(a.clone()),
                    });
                }
                // DROP (Some → None) — one entry. `from` carries the
                // prior expression so rollback re-installs it via
                // ADD CONSTRAINT.
                (Some(b), None) => {
                    push(ColumnChange::SetCheck {
                        from: Some(b.clone()),
                        to: None,
                    });
                }
            }
        }
        if before.unique != after.unique {
            push(ColumnChange::SetUnique(after.unique));
        }
        // Field-level `#[field(index)]` transitions are handled entirely
        // by `diff_indexes`: the projection layer synthesises an `IndexSchema`
        // entry for every `ColumnSchema::indexed = true` field, so
        // `diff_indexes` emits `AddIndex` / `DropIndex` for all three
        // shapes — fresh create, `false → true`, and `true → false`.
        // `ColumnChange::SetIndexed` is preserved in the enum for backward
        // compatibility with pending migrations that were serialised before
        // this projection path existed, but the differ no longer emits it.
        // `index_type`-only changes (method flip with `indexed` staying
        // `true`) are also caught by `diff_indexes` because `IndexSchema`
        // carries `index_type` and the differ compares it in `logical_eq`.
        if before.generated != after.generated {
            push(ColumnChange::SetGenerated {
                from: before.generated.clone(),
                to: after.generated.clone(),
            });
        }
        // snapshots (where `identity: None`) projected against new
        // schemas (where `identity: Some(ByDefault)` for Serial PKs)
        // emit the correct `ALTER COLUMN ADD GENERATED ... AS IDENTITY`
        // migration. Without this comparison the diff is silent and
        // adopters on existing tables don't get IDENTITY added,
        // leaving INSERT-without-id failing.
        if before.identity != after.identity {
            push(ColumnChange::SetIdentity {
                from: before.identity,
                to: after.identity,
            });
        }
        // `#[field(comment)]` transitions surface as a single
        // `SetComment { from, to }` that the emitter lowers to one
        // `COMMENT ON COLUMN <t>.<c> IS …` statement. Only emit when
        // the value actually changes so consecutive differ runs produce
        // byte-identical output.
        if before.comment != after.comment {
            push(ColumnChange::SetComment {
                from: before.comment.clone(),
                to: after.comment.clone(),
            });
        }
    }
    // FK transitions.
    match (&before.foreign_key, &after.foreign_key) {
        (None, Some(fk)) => ops.push(SchemaOperation::AddForeignKey {
            table: table.clone(),
            column: after.name.clone(),
            fk: fk.clone(),
        }),
        (Some(b_fk), None) => ops.push(SchemaOperation::DropForeignKey {
            table,
            column: after.name.clone(),
            fk: b_fk.clone(),
        }),
        (Some(b_fk), Some(a_fk)) if b_fk != a_fk => {
            // FK retargeting — emit drop + add for clarity. The drop
            // carries the OLD FK so its rollback can restore the
            // pre-retarget shape; the add carries the NEW FK.
            ops.push(SchemaOperation::DropForeignKey {
                table: table.clone(),
                column: after.name.clone(),
                fk: b_fk.clone(),
            });
            ops.push(SchemaOperation::AddForeignKey {
                table,
                column: after.name.clone(),
                fk: a_fk.clone(),
            });
        }
        _ => {}
    }
}

/// Diff PK shape between `before` and `after`. Recognised flip
/// pairs emit `PkTypeFlip`; every other non-equal PK transition
/// emits `Unsupported` with a specific reason so `classify()` can
/// surface it cleanly. Non-flip transitions handled here include:
/// - kind changes outside the flip pairs (e.g. `HeerId → Serial`)
/// - column-set changes (composite ↔ single, or composite reshape
///   that survives column-rename normalisation)
/// - custom PK shape changes (any transition involving
///   `PkKindSchema::Custom` on either side; see
///   [`custom_pk_unsupported_reason`] for the typed diagnostic shape)
///   **Custom PK transitions.** A model declared with a
///   `djogi::primary_key!` newtype on either side of the diff is rejected
///   with a dedicated message that names which side carries the custom
///   kind, the inner SQL types, and the type names. The stock
///   `pk_flip` family routes (`PkFlipFamily::Heer` / `Ranj`) only know
///   how to migrate the four built-in asc↔desc pairs — no playbook
///   exists for arbitrary `Custom → Custom`, `Custom → built-in`, or
///   `built-in → Custom` shape changes, and quietly emitting a generic
///   `ALTER COLUMN TYPE` would risk silent data loss when the inner SQL
///   types differ. See `docs/spec/migrations.md` §10.10a for the v0.1.0
///   support matrix.
///   **PK column rename + supported flip** is recognised as a flip:
///   the `column_renames` map is applied to `before.primary_key.columns`
///   before comparing against `after.primary_key.columns`, so a single
///   `RenameColumn` op + a kind flip together still produce
///   `SchemaOperation::PkTypeFlip` rather than `Unsupported`. The
///   `RenameColumn` was already emitted by `diff_columns_in_table`
///   before this fn runs.
fn diff_pk_in_table(
    before: &TableSchema,
    after: &TableSchema,
    column_renames: &BTreeMap<&str, &str>,
    ops: &mut Vec<SchemaOperation>,
) {
    if before.primary_key == after.primary_key {
        return;
    }
    // Normalise PK columns through the column-rename map so a PK
    // column renamed from `old_id` to `id` doesn't look like a
    // composite-shape change.
    let normalised_before: Vec<&str> = before
        .primary_key
        .columns
        .iter()
        .map(|c| {
            column_renames
                .get(c.as_str())
                .copied()
                .unwrap_or(c.as_str())
        })
        .collect();
    let normalised_after: Vec<&str> = after
        .primary_key
        .columns
        .iter()
        .map(|c| c.as_str())
        .collect();

    let columns_match = normalised_before == normalised_after;
    if columns_match && is_pk_kind_flip(&before.primary_key.kind, &after.primary_key.kind) {
        ops.push(SchemaOperation::PkTypeFlip {
            table: after.table.clone(),
            from: before.primary_key.kind.clone(),
            to: after.primary_key.kind.clone(),
        });
        return;
    }
    // route any transition that involves a custom-PK
    // newtype on either side to its own diagnostic instead of the
    // generic debug-dump fallback. Rationale in the docstring above
    // and in `custom_pk_unsupported_reason`.
    if matches!(&before.primary_key.kind, PkKindSchema::Custom(_))
        || matches!(&after.primary_key.kind, PkKindSchema::Custom(_))
    {
        ops.push(SchemaOperation::Unsupported {
            reason: custom_pk_unsupported_reason(
                &after.table,
                &before.primary_key.kind,
                &after.primary_key.kind,
            ),
        });
        return;
    }
    // Anything else in the PK changed — surface as Unsupported so
    // the operator hand-rolls a migration. The PK-flip expand/contract
    // playbook only covers the asc↔desc flips today; other PK
    // transitions don't have a generated playbook.
    ops.push(SchemaOperation::Unsupported {
        reason: format!(
            "table `{}`: primary key change is not auto-supported \
             ({:?}{:?}). Recognised auto-flips: HeerId ↔ \
             HeerIdRecencyBiased, RanjId ↔ RanjIdRecencyBiased \
             with identical column lists. Hand-write this migration.",
            after.table, before.primary_key, after.primary_key
        ),
    });
}

/// Format the v0.1.0 reject diagnostic for a primary-key transition
/// that involves a `djogi::primary_key!` custom newtype on at least
/// one side.
/// The message names the table, classifies the transition into one
/// of three buckets (`custom-to-custom`, `custom-to-built-in`,
/// `built-in-to-custom`), surfaces the full `type_name` / `sql_type` /
/// `default_sql` of the custom side(s) so a same-type but
/// different-`default_sql` change (e.g. a generator rotation) is
/// distinguishable from a same-generator type rename, and points
/// operators at the docs section that explains why `pk_flip.rs` does
/// not auto-migrate custom shapes in v0.1.0. Kept as a free fn so the
/// test mod can pin the exact phrasing per bucket.
fn custom_pk_unsupported_reason(
    table: &str,
    before: &PkKindSchema,
    after: &PkKindSchema,
) -> String {
    fn describe(kind: &PkKindSchema) -> String {
        match kind {
            PkKindSchema::Custom(c) => format!(
                "Custom(type_name = `{}`, sql_type = `{}`, default_sql = `{}`)",
                c.type_name, c.sql_type, c.default_sql,
            ),
            other => format!("{other:?}"),
        }
    }
    let before_desc = describe(before);
    let after_desc = describe(after);
    let bucket = match (before, after) {
        (PkKindSchema::Custom(_), PkKindSchema::Custom(_)) => "custom-to-custom",
        (PkKindSchema::Custom(_), _) => "custom-to-built-in",
        (_, PkKindSchema::Custom(_)) => "built-in-to-custom",
        // Defensive: the caller gates on at least one Custom side, but
        // this fallback keeps the format strictly total without
        // panicking if a future refactor relaxes the gate.
        _ => "non-custom",
    };
    format!(
        "table `{table}`: primary key change involves a \
         `djogi::primary_key!` custom newtype ({bucket}: {before_desc}\
         {after_desc}) and is not auto-supported in v0.1.0. The \
         `pk_flip` family only ships migration playbooks for the four \
         built-in asc↔desc pairs (HeerId ↔ HeerIdRecencyBiased, \
         RanjId ↔ RanjIdRecencyBiased); transitions involving a custom \
         PK newtype must be hand-written so the operator can decide on \
         the value-preserving cast and the FK cascade strategy. See \
         `docs/spec/migrations.md` §10.10a for the v0.1.0 support \
         matrix and rationale."
    )
}

fn is_pk_kind_flip(before: &PkKindSchema, after: &PkKindSchema) -> bool {
    matches!(
        (before, after),
        (PkKindSchema::HeerId, PkKindSchema::HeerIdRecencyBiased)
            | (PkKindSchema::HeerIdRecencyBiased, PkKindSchema::HeerId)
            | (PkKindSchema::RanjId, PkKindSchema::RanjIdRecencyBiased)
            | (PkKindSchema::RanjIdRecencyBiased, PkKindSchema::RanjId)
    )
}

fn diff_app_move_in_table(
    before: &TableSchema,
    after: &TableSchema,
    ops: &mut Vec<SchemaOperation>,
) {
    if before.app == after.app {
        return;
    }
    let from_app = before.app.clone().unwrap_or_default();
    let to_app = after.app.clone().unwrap_or_default();
    ops.push(SchemaOperation::MoveModelBetweenApps {
        model: after.table.clone(),
        from_app,
        to_app,
    });
}

fn diff_indexes(
    before: &AppliedSchema,
    after: &AppliedSchema,
    table_rename_targets: &BTreeMap<&str, &str>,
    ops: &mut Vec<SchemaOperation>,
) {
    let before_idx: BTreeMap<&str, &IndexSchema> = before
        .indexes
        .iter()
        .map(|i| (i.name.as_str(), i))
        .collect();
    let after_idx: BTreeMap<&str, &IndexSchema> =
        after.indexes.iter().map(|i| (i.name.as_str(), i)).collect();

    for (name, ai) in &after_idx {
        let resolved_old = before_idx.get(name).copied();
        match resolved_old {
            Some(bi) => {
                // Resolve the table name through the rename map to
                // detect "logical-equivalent under a table rename"
                // the index's `table` field changed only because
                // the table itself was renamed, not because the
                // index was retargeted. The map is keyed
                // `old → new`, so look up `bi.table` (the OLD table
                // name) and compare its `new` value against `ai.table`.
                // The earlier search direction (find the entry whose
                // `to` matches `bi.table`) was backwards and could
                // spuriously force drop+add on pure renames.
                let resolved_table_match = match table_rename_targets.get(bi.table.as_str()) {
                    Some(new_name) => *new_name == ai.table.as_str(),
                    None => bi.table == ai.table,
                };
                let logical_eq = resolved_table_match
                    && bi.target == ai.target
                    && bi.kind == ai.kind
                    && bi.index_type == ai.index_type
                    && bi.predicate == ai.predicate
                    && bi.include == ai.include
                    && bi.nulls_not_distinct == ai.nulls_not_distinct
                    && bi.requires_out_of_transaction == ai.requires_out_of_transaction
                    && bi.extension_dependency == ai.extension_dependency;
                if !logical_eq {
                    // Drop + Add carries the full IndexSchema for both
                    // sides so the segment planner knows whether the
                    // dropped index was non-transactional, unique,
                    // constraint-backed, or carried an extension
                    // dependency — without that metadata the planner
                    // would have to re-derive it or assume defaults.
                    ops.push(SchemaOperation::DropIndex((*bi).clone()));
                    ops.push(SchemaOperation::AddIndex((*ai).clone()));
                }
            }
            None => {
                ops.push(SchemaOperation::AddIndex((*ai).clone()));
            }
        }
    }
    for (name, bi) in &before_idx {
        if after_idx.contains_key(name) {
            continue;
        }
        ops.push(SchemaOperation::DropIndex((*bi).clone()));
    }
}

fn diff_enums(before: &AppliedSchema, after: &AppliedSchema, ops: &mut Vec<SchemaOperation>) {
    for (name, ae) in &after.enums {
        match before.enums.get(name) {
            None => ops.push(SchemaOperation::AddEnum((*ae).clone())),
            Some(be) if be == ae => {}
            Some(be) => {
                let before_set: BTreeSet<&str> = be.variants.iter().map(|v| v.as_str()).collect();
                for (i, v) in ae.variants.iter().enumerate() {
                    if !before_set.contains(v.as_str()) {
                        let anchor = pick_enum_variant_anchor(&ae.variants, i, &before_set);
                        ops.push(SchemaOperation::AddEnumVariant {
                            enum_name: name.clone(),
                            variant: v.clone(),
                            anchor,
                        });
                    }
                }
                // Removals — Postgres has no `DROP VALUE`. Surface
                // via the typed `Unsupported` variant so `classify`
                // routes cleanly to `Classification::Unsupported`
                // without string-matching on the `DropEnum` reason
                // field.
                let after_set: BTreeSet<&str> = ae.variants.iter().map(|v| v.as_str()).collect();
                for v in &be.variants {
                    if !after_set.contains(v.as_str()) {
                        ops.push(SchemaOperation::Unsupported {
                            reason: format!(
                                "enum `{name}`: variant `{v}` removed. Postgres has \
                                 no `DROP VALUE`; rebuild the type via a hand-written \
                                 migration (drop dependent columns, drop type, \
                                 recreate type without the variant, add columns \
                                 back)."
                            ),
                        });
                    }
                }
            }
        }
    }
    for name in before.enums.keys() {
        if !after.enums.contains_key(name) {
            ops.push(SchemaOperation::DropEnum(name.clone()));
        }
    }
}

/// Pick the BEFORE/AFTER anchor for a newly-inserted enum variant.
/// Walks `new_variants` outward from `pos` and returns the first
/// neighbour that already exists in `before_set` (i.e. lives in the
/// old enum). The post-anchor (next index) wins over the pre-anchor
/// (previous index) when both exist — this keeps the convention
/// consistent: "place before the first existing post-neighbour" so
/// chained inserts of multiple new variants in one delta produce a
/// stable, readable migration where each insert anchors against an
/// already-existing variant rather than another freshly-added one.
/// Returns `None` when no anchor in `before_set` exists in either
/// direction — that case is "first variants of a brand new enum",
/// which the caller already routes through [`SchemaOperation::AddEnum`]
/// rather than through `AddEnumVariant`, so this fallback is only
/// reached when every variant in the old list has been removed in
/// the new list (which would itself trigger `Unsupported` first).
fn pick_enum_variant_anchor(
    new_variants: &[String],
    pos: usize,
    before_set: &BTreeSet<&str>,
) -> Option<EnumVariantAnchor> {
    // Look forward first — find the nearest already-existing variant
    // that comes after `pos` in the new list.
    for v in new_variants.iter().skip(pos + 1) {
        if before_set.contains(v.as_str()) {
            return Some(EnumVariantAnchor {
                variant: v.clone(),
                kind: EnumVariantAnchorKind::Before,
            });
        }
    }
    // Then backward — find the nearest already-existing predecessor.
    for v in new_variants[..pos].iter().rev() {
        if before_set.contains(v.as_str()) {
            return Some(EnumVariantAnchor {
                variant: v.clone(),
                kind: EnumVariantAnchorKind::After,
            });
        }
    }
    None
}

/// Compute the aggregate [`Classification`] for an operation list.
/// Severity ladder: `NoOp` < `Additive` < `Reversible` <
/// `Destructive` < `Lossy` < `Unsupported`. `PkTypeFlip` is
/// orthogonal: when present, it wins as the headline classification,
/// but it carries `co_destructive` / `co_lossy` flags so co-existing
/// destructive or lossy ops still surface to the runner gate.
/// `Unsupported` always wins, even over `PkTypeFlip`, because an
/// unsupported transition has no executable plan at all.
/// `AddColumn` is classified per the column's actual shape:
/// - nullable, OR has a default → Additive
/// - non-nullable + no default → Lossy (existing rows would violate
///   the constraint immediately on apply)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Severity {
    Additive = 0,
    Reversible = 1,
    Destructive = 2,
    Lossy = 3,
}

fn severity_of(op: &SchemaOperation) -> Severity {
    match op {
        SchemaOperation::RenameTable { .. }
        | SchemaOperation::RenameColumn { .. }
        | SchemaOperation::RenameApp { .. }
        | SchemaOperation::MoveModelBetweenApps { .. } => Severity::Reversible,
        SchemaOperation::DropTable(_)
        | SchemaOperation::DropColumn { .. }
        | SchemaOperation::DropEnum(_)
        | SchemaOperation::DropIndex(_)
        | SchemaOperation::DropForeignKey { .. } => Severity::Destructive,
        SchemaOperation::AlterColumn { change, .. } => {
            if matches!(change, ColumnChange::SetNullable(false)) {
                Severity::Lossy
            } else {
                Severity::Additive
            }
        }
        SchemaOperation::AddColumn { column, .. } => {
            // A column is Lossy on add only if Postgres has no value
            // source for existing rows. Three sources are recognised:
            // 1. nullable column → NULL fills existing rows
            // 2. default_sql → DEFAULT expression fills existing rows
            // 3. generated → GENERATED ALWAYS expression fills rows
            // Only when none of these are set is the add Lossy.
            if !column.nullable && column.default_sql.is_none() && column.generated.is_none() {
                Severity::Lossy
            } else {
                Severity::Additive
            }
        }
        SchemaOperation::AddTable(_)
        | SchemaOperation::SetTableComment { .. }
        | SchemaOperation::SetStorageParams { .. }
        | SchemaOperation::SetTablespace { .. }
        | SchemaOperation::AddIndex(_)
        | SchemaOperation::AddEnum(_)
        | SchemaOperation::AddEnumVariant { .. }
        | SchemaOperation::AddForeignKey { .. }
        | SchemaOperation::AddExclusionConstraint { .. }
        | SchemaOperation::PkTypeFlip { .. }
        | SchemaOperation::PkTypeFlipGroup(_)
        | SchemaOperation::PkTypeFlipMultiGroup(_)
        | SchemaOperation::Unsupported { .. } => Severity::Additive,
        SchemaOperation::DropExclusionConstraint { .. } => Severity::Destructive,
    }
}

/// Re-derive the aggregate classification from a list of operations.
/// Used by the compose pipeline after enum reconciliation modifies
/// delta operations (REQ-396-3).
pub(crate) fn classify_operations(ops: &[SchemaOperation]) -> Classification {
    classify(ops)
}

fn classify(ops: &[SchemaOperation]) -> Classification {
    if ops.is_empty() {
        return Classification::NoOp;
    }

    // Unsupported wins over everything: there's no apply plan.
    if let Some(reason) = ops.iter().find_map(|op| match op {
        SchemaOperation::Unsupported { reason } => Some(reason.clone()),
        _ => None,
    }) {
        return Classification::Unsupported { reason };
    }

    let has_pk_flip = ops.iter().any(|op| {
        matches!(
            op,
            SchemaOperation::PkTypeFlip { .. }
                | SchemaOperation::PkTypeFlipGroup(_)
                | SchemaOperation::PkTypeFlipMultiGroup(_)
        )
    });

    // PkTypeFlip is orthogonal — surface co-flags so the gate logic
    // can still apply destructive / lossy semantics. Compute each
    // flag independently: a list with only Lossy ops must not also
    // claim co_destructive, and a list with only Destructive ops
    // must not claim co_lossy.
    if has_pk_flip {
        let mut co_destructive = false;
        let mut co_lossy = false;
        for op in ops {
            match severity_of(op) {
                Severity::Destructive => co_destructive = true,
                Severity::Lossy => co_lossy = true,
                Severity::Additive | Severity::Reversible => {}
            }
        }
        return Classification::PkTypeFlip {
            co_destructive,
            co_lossy,
        };
    }

    let max = ops
        .iter()
        .map(severity_of)
        .max()
        .unwrap_or(Severity::Additive);

    match max {
        Severity::Additive => Classification::Additive,
        Severity::Reversible => Classification::Reversible,
        Severity::Destructive => Classification::Destructive,
        Severity::Lossy => Classification::Lossy,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::apps::AppDescriptor;
    use crate::descriptor::{
        EnumDescriptor, FieldDescriptor, FieldSqlType, IndexColumnSpec, IndexKind, IndexSpec,
        IndexTarget, IndexType, ModelDescriptor, PkType, field_descriptor, model_descriptor,
    };
    use crate::migrate::projection::project_from_iters;
    use crate::migrate::schema::{IndexTypeSchema, PrimaryKeySchema, SNAPSHOT_FORMAT_VERSION};

    fn synth_app(label: &'static str, database: &'static str) -> AppDescriptor {
        AppDescriptor {
            label,
            database,
            renamed_from: None,
            tombstone: false,
        }
    }

    fn synth_model(table: &'static str, type_name: &'static str) -> ModelDescriptor {
        ModelDescriptor {
            ..model_descriptor(type_name, table, PkType::HeerIdDesc, &[])
        }
    }

    fn empty_global() -> BucketKey {
        BucketKey {
            database: "main".to_string(),
            app: "".to_string(),
        }
    }

    fn project_one(m: &ModelDescriptor) -> AppliedSchema {
        let mut buckets = project_from_iters(
            [m],
            std::iter::empty::<&EnumDescriptor>(),
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("project");
        buckets.remove(&empty_global()).unwrap()
    }

    fn project_empty() -> AppliedSchema {
        let mut buckets = project_from_iters(
            std::iter::empty::<&ModelDescriptor>(),
            std::iter::empty::<&EnumDescriptor>(),
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("project");
        buckets.remove(&empty_global()).unwrap()
    }

    #[test]
    fn equal_schemas_yield_noop() {
        let m = synth_model("widgets", "Widget");
        let s = project_one(&m);
        let delta = diff_schemas(&s, &s, empty_global());
        assert_eq!(delta.classification, Classification::NoOp);
        assert!(delta.operations.is_empty());
    }

    #[test]
    fn add_table_is_additive() {
        let before = project_empty();
        let m = synth_model("widgets", "Widget");
        let after = project_one(&m);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Additive);
        assert!(matches!(
            delta.operations.first(),
            Some(SchemaOperation::AddTable(t)) if t.table == "widgets"
        ));
    }

    #[test]
    fn drop_table_is_destructive() {
        let m = synth_model("widgets", "Widget");
        let before = project_one(&m);
        let after = project_empty();
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Destructive);
        assert!(matches!(
            delta.operations.first(),
            Some(SchemaOperation::DropTable(t)) if t == "widgets"
        ));
    }

    #[test]
    fn renamed_table_is_reversible_not_destructive() {
        let old_m = synth_model("widgets", "Widget");
        let new_m = ModelDescriptor {
            table_name: "gadgets",
            renamed_from: Some("widgets"),
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&old_m);
        let after = project_one(&new_m);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Reversible);
        assert_eq!(delta.operations.len(), 1);
        assert!(matches!(
            &delta.operations[0],
            SchemaOperation::RenameTable { from, to } if from == "widgets" && to == "gadgets"
        ));
    }

    #[test]
    fn unannotated_table_swap_is_destructive_drop_plus_add() {
        // Without `renamed_from`, a name change is two unrelated
        // operations: drop the old, add the new.
        let old_m = synth_model("widgets", "Widget");
        let new_m = synth_model("gadgets", "Gadget");
        let before = project_one(&old_m);
        let after = project_one(&new_m);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Destructive);
        let kinds: Vec<_> = delta
            .operations
            .iter()
            .map(|op| match op {
                SchemaOperation::DropTable(_) => "drop",
                SchemaOperation::AddTable(_) => "add",
                _ => "other",
            })
            .collect();
        assert!(kinds.contains(&"drop"));
        assert!(kinds.contains(&"add"));
    }

    #[test]
    fn add_column_is_additive() {
        const NAME: FieldDescriptor = field_descriptor("name", FieldSqlType::Text, true);
        static FIELDS_WITH_NAME: &[FieldDescriptor] = &[NAME];
        let bare = synth_model("widgets", "Widget");
        let new_field = ModelDescriptor {
            fields: FIELDS_WITH_NAME,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&bare);
        let after = project_one(&new_field);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Additive);
        assert!(matches!(
            delta.operations.first(),
            Some(SchemaOperation::AddColumn { table, column }) if table == "widgets" && column.name == "name"
        ));
    }

    #[test]
    fn pk_flip_classifies_as_pk_type_flip() {
        let asc = ModelDescriptor {
            pk_type: PkType::HeerId,
            ..synth_model("widgets", "Widget")
        };
        let desc = ModelDescriptor {
            pk_type: PkType::HeerIdDesc,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&asc);
        let after = project_one(&desc);
        let delta = diff_schemas(&before, &after, empty_global());
        assert!(matches!(
            delta.classification,
            Classification::PkTypeFlip {
                co_destructive: false,
                co_lossy: false
            }
        ));
        assert!(delta.operations.iter().any(|op| matches!(
            op,
            SchemaOperation::PkTypeFlip {
                from: PkKindSchema::HeerId,
                to: PkKindSchema::HeerIdRecencyBiased,
                ..
            }
        )));
    }

    #[test]
    fn pk_flip_reverse_direction_also_classifies() {
        let desc = ModelDescriptor {
            pk_type: PkType::HeerIdDesc,
            ..synth_model("widgets", "Widget")
        };
        let asc = ModelDescriptor {
            pk_type: PkType::HeerId,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&desc);
        let after = project_one(&asc);
        let delta = diff_schemas(&before, &after, empty_global());
        assert!(matches!(
            delta.classification,
            Classification::PkTypeFlip { .. }
        ));
    }

    #[test]
    fn pk_unrelated_change_classifies_as_unsupported() {
        // HeerId → Serial is NOT a flip pair. Per the v3 contract,
        // the differ surfaces this as Unsupported so the operator
        // hand-rolls a migration rather than letting it silently
        // degrade to an AlterColumn-only delta.
        let heer = ModelDescriptor {
            pk_type: PkType::HeerId,
            ..synth_model("widgets", "Widget")
        };
        let serial = ModelDescriptor {
            pk_type: PkType::Serial,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&heer);
        let after = project_one(&serial);
        let delta = diff_schemas(&before, &after, empty_global());
        assert!(matches!(
            delta.classification,
            Classification::Unsupported { .. }
        ));
    }

    // ── — custom-PK newtype shape flips ─────────────────
    // Every transition involving a `djogi::primary_key!`-declared
    // custom newtype on either side gets the typed reject diagnostic
    // from `custom_pk_unsupported_reason`. We pin the bucket label
    // and the type-name surfacing so operators see WHICH custom kind
    // changed, not a generic `PrimaryKeySchema { ... }` debug dump.
    // The four cases below cover the matrix the issue calls out:
    // 1. same inner SQL type, different Rust newtype name
    // 2. same Rust newtype name, different inner SQL type
    // 3. built-in → custom transition
    // 4. custom → built-in transition
    // The tests build descriptors directly via `PkType::Custom(...)`
    // the same `CustomPrimaryKeyKind` shape the `primary_key!` macro
    // emits via inventory at adopter-build time — so we exercise the
    // exact projection / diff path the runtime takes without needing
    // the macro fixture to live under `djogi/src/`.

    fn synth_model_with_pk(
        table: &'static str,
        type_name: &'static str,
        pk: PkType,
    ) -> ModelDescriptor {
        ModelDescriptor {
            pk_type: pk,
            ..synth_model(table, type_name)
        }
    }

    /// Build before/after `users` descriptors with `before_pk` and
    /// `after_pk`, run them through the differ, and return the
    /// `Classification::Unsupported` reason string. Panics if the
    /// differ produced any other classification — the four reject
    /// tests below all assume `Unsupported` is the only correct
    /// answer for a custom-PK shape change.
    fn unsupported_pk_reason(before_pk: PkType, after_pk: PkType) -> String {
        let before = project_one(&synth_model_with_pk("users", "User", before_pk));
        let after = project_one(&synth_model_with_pk("users", "User", after_pk));
        let delta = diff_schemas(&before, &after, empty_global());
        match delta.classification {
            Classification::Unsupported { reason } => reason,
            other => panic!("expected Unsupported, got {other:?}"),
        }
    }

    const CUSTOM_USER_ID: PkType = PkType::Custom(crate::descriptor::CustomPrimaryKeyKind {
        type_name: "crate::ids::UserId",
        sql_type: "BIGINT",
        default_sql: "user_id_next()",
    });
    const CUSTOM_USER_ID_V2: PkType = PkType::Custom(crate::descriptor::CustomPrimaryKeyKind {
        type_name: "crate::ids::UserIdV2",
        sql_type: "BIGINT",
        default_sql: "user_id_next()",
    });
    const CUSTOM_USER_ID_UUID: PkType = PkType::Custom(crate::descriptor::CustomPrimaryKeyKind {
        type_name: "crate::ids::UserId",
        sql_type: "UUID",
        default_sql: "gen_random_uuid()",
    });
    // Same `type_name` and `sql_type` as `CUSTOM_USER_ID` but a different
    // `default_sql` — pins the diagnostic surfaces every part of the
    // `CustomPkKindSchema` identity so operators can see what changed
    // when the generator function rotates (e.g. shard split, new
    // sequence cadence).
    const CUSTOM_USER_ID_NEXT_V2: PkType =
        PkType::Custom(crate::descriptor::CustomPrimaryKeyKind {
            type_name: "crate::ids::UserId",
            sql_type: "BIGINT",
            default_sql: "user_id_next_v2()",
        });

    #[test]
    fn pk_custom_same_inner_type_different_newtype_is_unsupported() {
        // Same inner SQL type (BIGINT) but the adopter renamed the
        // Rust newtype from `UserId` to `UserIdV2`. The `type_name`
        // field of `CustomPrimaryKeyKind` differs, so PartialEq says
        // "not equal" and the differ rejects with the custom-PK
        // diagnostic. The reject is intentional even though the
        // underlying column type is unchanged: a different Rust
        // newtype implies a different `PrimaryKey` impl, a different
        // `IntoFilterValue` discriminant, and potentially a different
        // `bulk_sql` / `default_sql` — the migration engine cannot
        // tell which fields the adopter changed under the rename.
        let reason = unsupported_pk_reason(CUSTOM_USER_ID, CUSTOM_USER_ID_V2);
        assert!(
            reason.contains("custom-to-custom"),
            "diagnostic must label the bucket; got: {reason}"
        );
        assert!(
            reason.contains("crate::ids::UserId") && reason.contains("crate::ids::UserIdV2"),
            "diagnostic must surface both type_names; got: {reason}"
        );
        assert!(
            reason.contains("djogi::primary_key!"),
            "diagnostic must mention the macro so operators know where to look; got: {reason}"
        );
    }

    #[test]
    fn pk_custom_changed_inner_sql_type_is_unsupported() {
        // Same `type_name` but the inner SQL type changes from BIGINT
        // to UUID. This is the dangerous case the issue calls out:
        // silently emitting an `ALTER COLUMN TYPE` would either fail
        // outright (no implicit BIGINT→UUID cast) or, worse, succeed
        // with a USING clause the operator never reviewed and
        // truncate live row IDs.
        let reason = unsupported_pk_reason(CUSTOM_USER_ID, CUSTOM_USER_ID_UUID);
        assert!(
            reason.contains("custom-to-custom"),
            "diagnostic must label the bucket; got: {reason}"
        );
        assert!(
            reason.contains("BIGINT") && reason.contains("UUID"),
            "diagnostic must surface both inner SQL types; got: {reason}"
        );
    }

    #[test]
    fn pk_custom_changed_default_sql_is_unsupported() {
        // Same `type_name` AND same `sql_type` — only the `default_sql`
        // changes. `CustomPkKindSchema` derives `PartialEq` over all
        // three identity fields, so a generator rotation (sequence
        // bump, shard split, new ID minting service) still fails the
        // equality check and routes through the custom-PK reject.
        // The diagnostic MUST include both `default_sql` strings — without
        // them the operator would see two identical-looking `Custom(...)`
        // arms in the surfaced `ComposeError::UnsupportedDelta` and have
        // no way to tell what the differ actually objected to.
        let reason = unsupported_pk_reason(CUSTOM_USER_ID, CUSTOM_USER_ID_NEXT_V2);
        assert!(
            reason.contains("custom-to-custom"),
            "diagnostic must label the bucket; got: {reason}"
        );
        assert!(
            reason.contains("user_id_next()") && reason.contains("user_id_next_v2()"),
            "diagnostic must surface both default_sql generators so the \
             operator can see what changed; got: {reason}"
        );
    }

    #[test]
    fn pk_builtin_to_custom_is_unsupported() {
        // Migrating a model from the default HeerId to a custom
        // newtype lands here. No playbook exists for this transition
        // both the column DEFAULT generator (heerid_next →
        // user_id_next()) and the FK cascade strategy depend on the
        // adopter's intent, so we reject and let them hand-write it.
        let reason = unsupported_pk_reason(PkType::HeerId, CUSTOM_USER_ID);
        assert!(
            reason.contains("built-in-to-custom"),
            "diagnostic must label the bucket; got: {reason}"
        );
        assert!(
            reason.contains("crate::ids::UserId"),
            "diagnostic must surface the custom side's type_name; got: {reason}"
        );
        assert!(
            reason.contains("HeerId"),
            "diagnostic must surface the built-in side; got: {reason}"
        );
    }

    #[test]
    fn pk_custom_to_builtin_is_unsupported() {
        // Reverse direction — a model walks back from a custom
        // newtype to a built-in. Same reasoning: the value-preserving
        // cast is adopter-decided, not framework-derivable.
        let reason = unsupported_pk_reason(CUSTOM_USER_ID, PkType::HeerId);
        assert!(
            reason.contains("custom-to-built-in"),
            "diagnostic must label the bucket; got: {reason}"
        );
        assert!(
            reason.contains("crate::ids::UserId") && reason.contains("HeerId"),
            "diagnostic must surface both sides; got: {reason}"
        );
    }

    #[test]
    fn pk_custom_unchanged_is_noop() {
        // Sanity pin — when the custom PK shape is identical on both
        // sides (same type_name + sql_type + default_sql), the differ
        // must produce a NoOp. Without this, a stable custom-PK model
        // would emit a migration on every `compose` run.
        let m = synth_model_with_pk("users", "User", CUSTOM_USER_ID);
        let s = project_one(&m);
        let delta = diff_schemas(&s, &s, empty_global());
        assert_eq!(delta.classification, Classification::NoOp);
        assert!(delta.operations.is_empty());
    }

    #[test]
    fn add_index_is_additive() {
        let bare = synth_model("widgets", "Widget");
        static IDX_SLICE: &[IndexSpec] = &[IndexSpec {
            name: "widgets_name_idx",
            target: IndexTarget::Columns(&[IndexColumnSpec::simple("name")]),
            kind: IndexKind::NonUnique,
            index_type: IndexType::BTree,
            predicate: None,
            include: &[],
            nulls_not_distinct: false,
            requires_out_of_transaction: false,
            extension_dependency: None,
        }];
        let with_idx = ModelDescriptor {
            indexes: IDX_SLICE,
            ..bare.clone()
        };
        let before = project_one(&bare);
        let after = project_one(&with_idx);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Additive);
        assert!(matches!(
            delta.operations.first(),
            Some(SchemaOperation::AddIndex(idx)) if idx.name == "widgets_name_idx"
        ));
    }

    #[test]
    fn add_enum_is_additive() {
        // Model must reference the enum via <postgres_type> so it projects
        // into the bucket under per-bucket enum scoping (REQ-396-1).
        let status_field = field_descriptor("status", FieldSqlType::Custom("status"), true);
        let fields: &'static [FieldDescriptor] = Box::leak(Box::new([status_field]));
        let m = model_descriptor("Widget", "widgets", PkType::HeerIdDesc, fields);
        let e = EnumDescriptor {
            type_name: "Status",
            postgres_type: "status",
            variants: &["active", "deleted"],
        };
        let mut buckets_before = project_from_iters(
            [&m],
            std::iter::empty::<&EnumDescriptor>(),
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("p");
        let mut buckets_after = project_from_iters(
            [&m],
            [&e],
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("p");
        let before = buckets_before.remove(&empty_global()).unwrap();
        let after = buckets_after.remove(&empty_global()).unwrap();
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Additive);
        assert!(
            delta
                .operations
                .iter()
                .any(|op| matches!(op, SchemaOperation::AddEnum(_)))
        );
    }

    #[test]
    fn variant_removal_classifies_as_unsupported() {
        // Model must reference the enum via <postgres_type> so it projects
        // into the bucket under per-bucket enum scoping (REQ-396-1).
        let status_field = field_descriptor("status", FieldSqlType::Custom("status"), true);
        let fields: &'static [FieldDescriptor] = Box::leak(Box::new([status_field]));
        let m = model_descriptor("Widget", "widgets", PkType::HeerIdDesc, fields);
        let two = EnumDescriptor {
            type_name: "Status",
            postgres_type: "status",
            variants: &["active", "deleted"],
        };
        let one = EnumDescriptor {
            type_name: "Status",
            postgres_type: "status",
            variants: &["active"],
        };
        let mut buckets_before = project_from_iters(
            [&m],
            [&two],
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("p");
        let mut buckets_after = project_from_iters(
            [&m],
            [&one],
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("p");
        let before = buckets_before.remove(&empty_global()).unwrap();
        let after = buckets_after.remove(&empty_global()).unwrap();
        let delta = diff_schemas(&before, &after, empty_global());
        assert!(matches!(
            delta.classification,
            Classification::Unsupported { .. }
        ));
    }

    #[test]
    fn diff_bucket_maps_handles_added_bucket() {
        let m = synth_model("widgets", "Widget");
        let before = BTreeMap::new();
        let mut after = BTreeMap::new();
        after.insert(empty_global(), project_one(&m));
        let deltas = diff_bucket_maps(&before, &after).expect("differ must succeed in this test");
        assert_eq!(deltas.len(), 1);
        assert_eq!(deltas[0].bucket, empty_global());
        assert!(matches!(deltas[0].classification, Classification::Additive));
    }

    #[test]
    fn renamed_column_emits_rename_not_drop_add() {
        const OLD_NAME: FieldDescriptor = field_descriptor("old_name", FieldSqlType::Text, true);
        static OLD_SLICE: &[FieldDescriptor] = &[OLD_NAME];
        const NEW_NAME: FieldDescriptor = FieldDescriptor {
            renamed_from: Some("old_name"),
            ..field_descriptor("new_name", FieldSqlType::Text, true)
        };
        static NEW_SLICE: &[FieldDescriptor] = &[NEW_NAME];
        let bare = ModelDescriptor {
            fields: OLD_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let renamed = ModelDescriptor {
            fields: NEW_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&bare);
        let after = project_one(&renamed);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Reversible);
        assert!(matches!(
            delta.operations.first(),
            Some(SchemaOperation::RenameColumn { from, to, .. }) if from == "old_name" && to == "new_name"
        ));
    }

    #[test]
    fn nullability_change_to_not_null_classifies_lossy() {
        const NULLABLE: FieldDescriptor = field_descriptor("name", FieldSqlType::Text, true);
        const NOT_NULL: FieldDescriptor = field_descriptor("name", FieldSqlType::Text, false);
        static NULLABLE_SLICE: &[FieldDescriptor] = &[NULLABLE];
        static NOT_NULL_SLICE: &[FieldDescriptor] = &[NOT_NULL];
        let nullable = ModelDescriptor {
            fields: NULLABLE_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let not_null = ModelDescriptor {
            fields: NOT_NULL_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&nullable);
        let after = project_one(&not_null);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Lossy);
    }

    #[test]
    fn nullability_change_to_nullable_is_additive() {
        const NOT_NULL: FieldDescriptor = field_descriptor("name", FieldSqlType::Text, false);
        const NULLABLE: FieldDescriptor = field_descriptor("name", FieldSqlType::Text, true);
        static NOT_NULL_SLICE: &[FieldDescriptor] = &[NOT_NULL];
        static NULLABLE_SLICE: &[FieldDescriptor] = &[NULLABLE];
        let not_null = ModelDescriptor {
            fields: NOT_NULL_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let nullable = ModelDescriptor {
            fields: NULLABLE_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&not_null);
        let after = project_one(&nullable);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Additive);
    }

    #[test]
    fn type_change_emits_alter_column_change_type() {
        const TEXT: FieldDescriptor = field_descriptor("amount", FieldSqlType::Text, true);
        const BIGINT: FieldDescriptor = field_descriptor("amount", FieldSqlType::BigInt, true);
        static TEXT_SLICE: &[FieldDescriptor] = &[TEXT];
        static BIGINT_SLICE: &[FieldDescriptor] = &[BIGINT];
        let text = ModelDescriptor {
            fields: TEXT_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let bigint = ModelDescriptor {
            fields: BIGINT_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&text);
        let after = project_one(&bigint);
        let delta = diff_schemas(&before, &after, empty_global());
        assert!(delta.operations.iter().any(|op| matches!(
            op,
            SchemaOperation::AlterColumn {
                change: ColumnChange::ChangeType { .. },
                ..
            }
        )));
    }

    // ── — CHECK constraint AMEND-replace lifecycle ───────────────
    // The differ detects CHECK transitions and emits
    // ColumnChange::SetCheck variants. The AMEND case (`Some(old) →
    // Some(new)` with `old != new`) emits two `SetCheck` entries
    // first `{ from: Some(old), to: None }` (drop) followed by
    // `{ from: None, to: Some(new) }` (add) — so the SQL pair is
    // `DROP CONSTRAINT` then `ADD CONSTRAINT`. Each variant carries
    // `from` so each step's rollback restores the pre-step state
    // symmetrically. These tests pin all four cells of the CHECK
    // transition matrix so a future refactor cannot silently regress.

    fn build_table_with_check(check: Option<&str>) -> crate::migrate::schema::AppliedSchema {
        build_table_with_check_and_type(check, "BIGINT")
    }

    fn build_table_with_check_and_type(
        check: Option<&str>,
        sql_type: &str,
    ) -> crate::migrate::schema::AppliedSchema {
        use crate::migrate::schema::{
            AppliedSchema, ColumnSchema, PkKindSchema, PrimaryKeySchema, TableSchema,
        };
        use std::collections::BTreeMap;

        let id_col = ColumnSchema {
            check: None,
            codec: None,
            comment: None,
            default_sql: Some("heerid_next()".to_string()),
            foreign_key: None,
            generated: None,
            identity: None,
            index_type: None,
            indexed: false,
            max_length: None,
            name: "id".to_string(),
            nullable: false,
            on_delete: None,
            outbox_exclude: false,
            rationale: None,
            relation_kind: None,
            renamed_from: None,
            sequence_within: None,
            sql_type: "BIGINT".to_string(),
            unique: false,
            type_change_using: None,
        };
        let amount_col = ColumnSchema {
            check: check.map(|s| s.to_string()),
            codec: None,
            comment: None,
            default_sql: None,
            foreign_key: None,
            generated: None,
            identity: None,
            index_type: None,
            indexed: false,
            max_length: None,
            name: "amount".to_string(),
            nullable: false,
            on_delete: None,
            outbox_exclude: false,
            rationale: None,
            relation_kind: None,
            renamed_from: None,
            sequence_within: None,
            sql_type: sql_type.to_string(),
            unique: false,
            type_change_using: None,
        };
        let mut models = BTreeMap::new();
        models.insert(
            "widgets".to_string(),
            TableSchema {
                app: None,
                columns: vec![id_col, amount_col],
                exclusion_constraints: vec![],
                fts: None,
                is_through: false,
                moved_from_app: None,
                partition: None,
                primary_key: PrimaryKeySchema {
                    columns: vec!["id".to_string()],
                    kind: PkKindSchema::HeerId,
                },
                rationale: None,
                renamed_from: None,
                rls_enabled: false,
                table: "widgets".to_string(),
                table_comment: None,
                storage_params: None,
                tablespace: None,
                tenant_key: None,
            },
        );
        AppliedSchema {
            djogi_version: "0.1.0".to_string(),
            enums: BTreeMap::new(),
            format_version: "1".to_string(),
            generated_at: "2026-05-10T00:00:00Z".to_string(),
            indexes: vec![],
            models,
            registered_apps: vec!["".to_string()],
        }
    }

    fn alter_column_changes_for(
        delta: &crate::migrate::diff::SchemaDelta,
        column: &str,
    ) -> Vec<ColumnChange> {
        delta
            .operations
            .iter()
            .filter_map(|op| match op {
                SchemaOperation::AlterColumn {
                    column: c, change, ..
                } if c == column => Some(change.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn check_unchanged_some_emits_no_set_check() {
        let before = build_table_with_check(Some("\"amount\" >= 0 AND \"amount\" <= 4294967295"));
        let after = build_table_with_check(Some("\"amount\" >= 0 AND \"amount\" <= 4294967295"));
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "amount");
        assert!(
            changes.is_empty(),
            "identical CHECK on both sides must not emit any AlterColumn change: {changes:?}",
        );
    }

    #[test]
    fn check_unchanged_none_emits_no_set_check() {
        let before = build_table_with_check(None);
        let after = build_table_with_check(None);
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "amount");
        assert!(
            changes.is_empty(),
            "absent CHECK on both sides must not emit any AlterColumn change: {changes:?}",
        );
    }

    #[test]
    fn check_add_emits_single_set_check_some() {
        // ADD scenario — descriptor evolves from i64 (no CHECK) to a
        // type that projects a CHECK. The differ emits a single
        // SetCheck { from: None, to: Some(new) } which the emitter
        // renders as `ALTER TABLE … ADD CONSTRAINT … CHECK (…)`.
        let after_expr = "\"amount\" >= 0 AND \"amount\" <= 4294967295";
        let before = build_table_with_check(None);
        let after = build_table_with_check(Some(after_expr));
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "amount");
        assert_eq!(
            changes.len(),
            1,
            "ADD CHECK is a single ColumnChange entry: {changes:?}"
        );
        assert!(
            matches!(
                changes.first(),
                Some(ColumnChange::SetCheck { from: None, to: Some(s) }) if s == after_expr
            ),
            "ADD CHECK emits SetCheck {{ from: None, to: Some(new) }}: {changes:?}"
        );
    }

    #[test]
    fn table_metadata_changes_emit_dedicated_operations() {
        let mut before = build_table_with_check(None);
        let mut after = build_table_with_check(None);
        let before_table = before.models.get_mut("widgets").expect("before table");
        before_table.table_comment = Some("old comment".to_string());
        before_table.storage_params = Some("fillfactor=80".to_string());
        before_table.tablespace = Some("slowspace".to_string());
        let after_table = after.models.get_mut("widgets").expect("after table");
        after_table.table_comment = Some("new comment".to_string());
        after_table.storage_params = Some("fillfactor=70, autovacuum_enabled=false".to_string());
        after_table.tablespace = Some("fastspace".to_string());

        let delta = diff_schemas(&before, &after, empty_global());

        assert!(delta.operations.iter().any(|op| matches!(
            op,
            SchemaOperation::SetTableComment {
                table,
                from: Some(from),
                to: Some(to),
            } if table == "widgets" && from == "old comment" && to == "new comment"
        )));
        assert!(delta.operations.iter().any(|op| matches!(
            op,
            SchemaOperation::SetStorageParams {
                table,
                from: Some(from),
                to: Some(to),
            } if table == "widgets"
                && from == "fillfactor=80"
                && to == "fillfactor=70, autovacuum_enabled=false"
        )));
        assert!(delta.operations.iter().any(|op| matches!(
            op,
            SchemaOperation::SetTablespace {
                table,
                from: Some(from),
                to: Some(to),
            } if table == "widgets" && from == "slowspace" && to == "fastspace"
        )));
    }

    #[test]
    fn check_drop_emits_single_set_check_none() {
        // DROP scenario — descriptor evolves from u32 (with CHECK) to
        // i64 (no CHECK). The differ emits a single
        // SetCheck { from: Some(prior), to: None } which the emitter
        // renders as `ALTER TABLE … DROP CONSTRAINT …` and a
        // recoverable down-side that restores `prior`.
        let prior_expr = "\"amount\" >= 0 AND \"amount\" <= 4294967295";
        let before = build_table_with_check(Some(prior_expr));
        let after = build_table_with_check(None);
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "amount");
        assert_eq!(
            changes.len(),
            1,
            "DROP CHECK is a single ColumnChange entry: {changes:?}"
        );
        assert!(
            matches!(
                changes.first(),
                Some(ColumnChange::SetCheck { from: Some(s), to: None }) if s == prior_expr
            ),
            "DROP CHECK emits SetCheck {{ from: Some(prior), to: None }}: {changes:?}"
        );
    }

    #[test]
    fn check_amend_emits_drop_then_add() {
        // AMEND scenario — the central lifecycle case.
        // Descriptor evolves from u32 → u64 (or any other CHECK
        // expression change). The differ MUST emit two ColumnChange
        // entries in order:
        // SetCheck { from: Some(b), to: None }
        // SetCheck { from: None, to: Some(a) }
        // The SQL emitter renders these as `DROP CONSTRAINT …; ADD
        // CONSTRAINT … CHECK (…);` — two separate ALTERs against the
        // same constraint name slot, which Postgres accepts cleanly.
        // Each step now carries its own (from, to) so the down side
        // restores the previous state symmetrically (.
        let before_expr = "\"amount\" >= 0 AND \"amount\" <= 4294967295";
        let after_expr = "\"amount\" >= 0 AND \"amount\" <= 18446744073709551615";
        let before = build_table_with_check(Some(before_expr));
        let after = build_table_with_check(Some(after_expr));
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "amount");
        assert_eq!(
            changes.len(),
            2,
            "AMEND CHECK emits exactly two ColumnChange entries: {changes:?}"
        );
        assert!(
            matches!(
                changes.first(),
                Some(ColumnChange::SetCheck { from: Some(b), to: None }) if b == before_expr
            ),
            "AMEND step 1: SetCheck {{ from: Some(prior), to: None }}: {changes:?}"
        );
        assert!(
            matches!(
                changes.get(1),
                Some(ColumnChange::SetCheck { from: None, to: Some(a) }) if a == after_expr
            ),
            "AMEND step 2: SetCheck {{ from: None, to: Some(new) }}: {changes:?}"
        );
    }

    #[test]
    fn check_type_change_readds_same_check_after_type_change() {
        // When converting SQL type, an unchanged CHECK still needs a
        // drop+re-add around `ALTER COLUMN TYPE`, otherwise Postgres
        // can re-validate the old expression first and fail. The
        // first step's `from` carries the prior expression so the
        // down-side rollback restores it after reverting the type.
        let check_expr = "\"amount\" >= 0 AND \"amount\" <= 4294967295";
        let before = build_table_with_check_and_type(Some(check_expr), "INTEGER");
        let after = build_table_with_check_and_type(Some(check_expr), "BIGINT");
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "amount");
        assert_eq!(
            changes.len(),
            3,
            "unchanged CHECK plus type migration must emit drop/type/readd steps: {changes:?}"
        );
        assert!(
            matches!(
                changes.first(),
                Some(ColumnChange::SetCheck { from: Some(b), to: None }) if b == check_expr
            ),
            "existing CHECK must be dropped before ALTER TYPE \
             (carrying `from` for rollback): {changes:?}"
        );
        assert!(
            matches!(changes.get(1), Some(ColumnChange::ChangeType { from, to, .. }) if from == "INTEGER" && to == "BIGINT"),
            "ALTER TYPE should be between drop and re-add: {changes:?}"
        );
        assert!(
            matches!(
                changes.get(2),
                Some(ColumnChange::SetCheck { from: None, to: Some(s) }) if s == check_expr
            ),
            "same CHECK should be re-added after type conversion \
             (forward-only `to`; the prior is restored by step 0's down): \
             {changes:?}"
        );
    }

    #[test]
    fn check_type_change_reorders_drop_and_readd_for_changed_check() {
        // Type migration with a CHECK expression change must still drop the
        // pre-migration CHECK before TYPE and re-add the post-migration
        // CHECK after it. The drop step carries the OLD expression in
        // `from`; the readd step carries the NEW expression in `to`.
        // Rollback walks down in reverse: drop new, revert type, ADD old.
        let before_expr = "\"amount\" >= 0 AND \"amount\" <= 4294967295";
        let after_expr = "\"amount\" >= 0 AND \"amount\" <= 18446744073709551615";
        let before = build_table_with_check_and_type(Some(before_expr), "INTEGER");
        let after = build_table_with_check_and_type(Some(after_expr), "BIGINT");
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "amount");
        assert_eq!(
            changes.len(),
            3,
            "changed CHECK + type migration must emit drop/type/readd steps: {changes:?}"
        );
        assert!(
            matches!(
                changes.first(),
                Some(ColumnChange::SetCheck { from: Some(b), to: None }) if b == before_expr
            ),
            "existing CHECK must be dropped before ALTER TYPE \
             with `from` carrying the OLD expression for rollback: {changes:?}"
        );
        assert!(
            matches!(changes.get(1), Some(ColumnChange::ChangeType { from, to, .. }) if from == "INTEGER" && to == "BIGINT"),
            "ALTER TYPE should be between drop and re-add: {changes:?}"
        );
        assert!(
            matches!(
                changes.get(2),
                Some(ColumnChange::SetCheck { from: None, to: Some(s) }) if s == after_expr
            ),
            "new CHECK should be re-added after type conversion \
             (the OLD expression is restored by step 0's down side): {changes:?}"
        );
    }

    // ── SetIdentity diff regression test ────────────────────────────

    #[test]
    fn diff_detects_identity_none_to_some_by_default_as_set_identity() {
        // A snapshot predating the `identity` field (which deserialises
        // as `None` via `#[serde(default)]`) projected against a fresh
        // schema (Serial PKs project `identity = Some(ByDefault)`) must
        // surface a SetIdentity AlterColumn, not silently no-op.
        use crate::migrate::schema::{
            AppliedSchema, ColumnSchema, IdentityKindSchema, PkKindSchema, PrimaryKeySchema,
            TableSchema,
        };
        use std::collections::BTreeMap;

        fn build_schema(identity: Option<IdentityKindSchema>) -> AppliedSchema {
            let id_col = ColumnSchema {
                check: None,
                codec: None,
                comment: None,
                default_sql: None,
                foreign_key: None,
                generated: None,
                identity,
                index_type: None,
                indexed: false,
                max_length: None,
                name: "id".to_string(),
                nullable: false,
                on_delete: None,
                outbox_exclude: false,
                rationale: None,
                relation_kind: None,
                renamed_from: None,
                sequence_within: None,
                sql_type: "INTEGER".to_string(),
                unique: false,
                type_change_using: None,
            };
            let table = TableSchema {
                app: None,
                columns: vec![id_col],
                exclusion_constraints: Vec::new(),
                fts: None,
                is_through: false,
                moved_from_app: None,
                partition: None,
                primary_key: PrimaryKeySchema {
                    columns: vec!["id".to_string()],
                    kind: PkKindSchema::Serial,
                },
                rationale: None,
                renamed_from: None,
                rls_enabled: false,
                table: "countries".to_string(),
                table_comment: None,
                storage_params: None,
                tablespace: None,
                tenant_key: None,
            };
            let mut models = BTreeMap::new();
            models.insert("countries".to_string(), table);
            AppliedSchema {
                djogi_version: "0.1.0".to_string(),
                enums: BTreeMap::new(),
                format_version: SNAPSHOT_FORMAT_VERSION.to_string(),
                generated_at: "2026-05-02T00:00:00Z".to_string(),
                indexes: Vec::new(),
                models,
                registered_apps: vec!["".to_string()],
            }
        }

        let before = build_schema(None);
        let after = build_schema(Some(IdentityKindSchema::ByDefault));
        let delta = diff_schemas(&before, &after, empty_global());

        let has_set_identity = delta.operations.iter().any(|op| {
            matches!(
                op,
                SchemaOperation::AlterColumn {
                    change: ColumnChange::SetIdentity {
                        from: None,
                        to: Some(IdentityKindSchema::ByDefault)
                    },
                    ..
                }
            )
        });
        assert!(
            has_set_identity,
            "expected SetIdentity {{ from: None, to: Some(ByDefault) }} in delta; got: {:?}",
            delta.operations
        );
    }

    // ── Classification accuracy tests ───────────────────────────────

    #[test]
    fn add_not_null_column_without_default_classifies_lossy() {
        // AddColumn must inspect the column's shape. NOT NULL without
        // a default = Lossy because existing rows would immediately
        // violate the constraint on apply.
        const NOT_NULL: FieldDescriptor = field_descriptor("required", FieldSqlType::Text, false);
        static FIELDS: &[FieldDescriptor] = &[NOT_NULL];
        let bare = synth_model("widgets", "Widget");
        let with_required = ModelDescriptor {
            fields: FIELDS,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&bare);
        let after = project_one(&with_required);
        let delta = diff_schemas(&before, &after, empty_global());
        assert_eq!(delta.classification, Classification::Lossy);
    }

    #[test]
    fn pk_flip_with_concurrent_drop_surfaces_co_destructive_flag() {
        // PkTypeFlip must NOT mask co-existing destructive ops.
        // A flip + DropTable in the same delta
        // classifies as PkTypeFlip { co_destructive: true } so the
        // runner's --allow-destructive gate still fires.
        let asc = ModelDescriptor {
            pk_type: PkType::HeerId,
            ..synth_model("widgets", "Widget")
        };
        let asc_other = ModelDescriptor {
            pk_type: PkType::HeerId,
            ..synth_model("decommissioned", "Decommissioned")
        };
        let mut before_buckets = project_from_iters(
            [&asc, &asc_other],
            std::iter::empty::<&EnumDescriptor>(),
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("project");
        let desc = ModelDescriptor {
            pk_type: PkType::HeerIdDesc,
            ..synth_model("widgets", "Widget")
        };
        // Note: `decommissioned` removed from after, AND `widgets`
        // pk flipped HeerId → HeerIdDesc — combined drop + PK flip
        // in the same delta.
        let mut after_buckets = project_from_iters(
            [&desc],
            std::iter::empty::<&EnumDescriptor>(),
            std::iter::empty::<&AppDescriptor>(),
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("project");
        let before = before_buckets.remove(&empty_global()).unwrap();
        let after = after_buckets.remove(&empty_global()).unwrap();
        let delta = diff_schemas(&before, &after, empty_global());
        match delta.classification {
            Classification::PkTypeFlip {
                co_destructive,
                co_lossy,
            } => {
                assert!(
                    co_destructive,
                    "DropTable alongside PkTypeFlip must set co_destructive"
                );
                assert!(!co_lossy);
            }
            other => panic!("expected PkTypeFlip with co_destructive, got {other:?}"),
        }
    }

    #[test]
    fn pk_flip_with_lossy_only_op_does_not_claim_co_destructive() {
        // Regression: classify() previously computed
        // co_destructive: max >= Severity::Destructive
        // which is true whenever max == Lossy because Lossy > Destructive
        // in the severity ordering. That conflated the two flags so a
        // delta carrying ONLY a Lossy op (no Destructive op) wrongly
        // surfaced co_destructive=true and tripped the
        // --allow-destructive gate.
        // The fix scans ops independently: co_destructive only when
        // some op classifies as Destructive, co_lossy only when some op
        // classifies as Lossy. This test pins both flags to their
        // expected values for a PK-flip + AddColumn(NOT NULL, no
        // default) delta.
        const REQUIRED: FieldDescriptor = field_descriptor("required", FieldSqlType::Text, false);
        static FIELDS: &[FieldDescriptor] = &[REQUIRED];
        let asc = ModelDescriptor {
            pk_type: PkType::HeerId,
            ..synth_model("widgets", "Widget")
        };
        let desc_with_required = ModelDescriptor {
            pk_type: PkType::HeerIdDesc,
            fields: FIELDS,
            ..synth_model("widgets", "Widget")
        };
        let before = project_one(&asc);
        let after = project_one(&desc_with_required);
        let delta = diff_schemas(&before, &after, empty_global());
        match delta.classification {
            Classification::PkTypeFlip {
                co_destructive,
                co_lossy,
            } => {
                assert!(
                    !co_destructive,
                    "Lossy-only op alongside PkTypeFlip must NOT set co_destructive"
                );
                assert!(
                    co_lossy,
                    "AddColumn(NOT NULL, no default) alongside PkTypeFlip must set co_lossy"
                );
            }
            other => panic!("expected PkTypeFlip with co_lossy only, got {other:?}"),
        }
    }

    #[test]
    fn drop_index_carries_full_metadata() {
        // DropIndex must carry IndexSchema, not just the name, so the
        // segment planner knows the dropped index's
        // `requires_out_of_transaction`, kind, etc.
        static IDX_SLICE: &[IndexSpec] = &[IndexSpec {
            name: "widgets_name_idx",
            target: IndexTarget::Columns(&[IndexColumnSpec::simple("name")]),
            kind: IndexKind::NonUnique,
            index_type: IndexType::Gist,
            predicate: None,
            include: &[],
            nulls_not_distinct: false,
            requires_out_of_transaction: true,
            extension_dependency: Some("postgis"),
        }];
        let with_idx = ModelDescriptor {
            indexes: IDX_SLICE,
            ..synth_model("widgets", "Widget")
        };
        let bare = synth_model("widgets", "Widget");
        let before = project_one(&with_idx);
        let after = project_one(&bare);
        let delta = diff_schemas(&before, &after, empty_global());
        let drop = delta
            .operations
            .iter()
            .find_map(|op| match op {
                SchemaOperation::DropIndex(idx) => Some(idx),
                _ => None,
            })
            .expect("DropIndex emitted");
        assert_eq!(drop.name, "widgets_name_idx");
        assert!(drop.requires_out_of_transaction);
        assert_eq!(drop.extension_dependency.as_deref(), Some("postgis"));
        assert_eq!(drop.index_type, IndexTypeSchema::Gist);
    }

    #[test]
    fn cross_bucket_move_via_moved_from_app_emits_move_not_drop_add() {
        // A model with `moved_from_app = "billing"` whose table existed
        // in the before-billing-bucket must produce a single
        // MoveModelBetweenApps op on the destination bucket — NOT a
        // spurious DropTable and AddTable on other buckets.
        let billing = synth_app("billing", "main");
        let users = synth_app("users", "main");

        let before_model = ModelDescriptor {
            app: Some("billing"),
            ..synth_model("user_settings", "UserSettings")
        };
        let after_model = ModelDescriptor {
            app: Some("users"),
            moved_from_app: Some("billing"),
            ..synth_model("user_settings", "UserSettings")
        };

        let before = project_from_iters(
            [&before_model],
            std::iter::empty::<&EnumDescriptor>(),
            [&billing, &users],
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("project before");
        let after = project_from_iters(
            [&after_model],
            std::iter::empty::<&EnumDescriptor>(),
            [&billing, &users],
            "2026-04-25T00:00:00Z".to_string(),
        )
        .expect("project after");

        let deltas = diff_bucket_maps(&before, &after).expect("differ must succeed in this test");

        // Source bucket (billing): no spurious DropTable.
        let billing_bucket = BucketKey {
            database: "main".to_string(),
            app: "billing".to_string(),
        };
        let billing_delta = deltas.iter().find(|d| d.bucket == billing_bucket);
        if let Some(d) = billing_delta {
            assert!(
                !d.operations
                    .iter()
                    .any(|op| matches!(op, SchemaOperation::DropTable(_))),
                "source bucket must not emit DropTable for moved model"
            );
        }

        // Destination bucket (users): MoveModelBetweenApps emitted,
        // no spurious AddTable.
        let users_bucket = BucketKey {
            database: "main".to_string(),
            app: "users".to_string(),
        };
        let users_delta = deltas.iter().find(|d| d.bucket == users_bucket).unwrap();
        assert!(
            users_delta.operations.iter().any(|op| matches!(
                op,
                SchemaOperation::MoveModelBetweenApps { model, from_app, to_app }
                    if model == "user_settings" && from_app == "billing" && to_app == "users"
            )),
            "destination bucket must emit MoveModelBetweenApps"
        );
        assert!(
            !users_delta
                .operations
                .iter()
                .any(|op| matches!(op, SchemaOperation::AddTable(_))),
            "destination bucket must not emit AddTable for moved model"
        );
    }

    #[test]
    fn pk_column_rename_normalises_under_kind_flip() {
        // A PK column rename concurrent with a kind flip must be
        // recognised as a PkTypeFlip, not Unsupported. The differ runs
        // `diff_columns_in_table` first (which emits `RenameColumn`
        // and returns the rename map) and then `diff_pk_in_table`
        // with that map, normalising the before-PK columns through
        // the rename so the column-list comparison succeeds.
        // We construct two synthetic schemas DIRECTLY (bypassing
        // `project_*`) so we can pin a `Composite(["old_id"])` PK
        // shape on the before side and `Composite(["new_id"])` on
        // the after side with a column rename annotation in
        // between. `project_from_iters` would always synthesise
        // single-column `id` PKs from the descriptor inventory,
        // which doesn't exercise the normalisation code path.
        let bucket = empty_global();

        let mut before = 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()],
        };
        before.models.insert(
            "widgets".to_string(),
            TableSchema {
                app: None,
                columns: vec![ColumnSchema {
                    check: None,
                    codec: None,
                    comment: None,
                    default_sql: None,
                    foreign_key: None,
                    generated: None,
                    identity: None,
                    index_type: None,
                    indexed: false,
                    max_length: None,
                    name: "old_id".to_string(),
                    nullable: false,
                    on_delete: None,
                    outbox_exclude: false,
                    rationale: None,
                    relation_kind: None,
                    renamed_from: None,
                    sequence_within: None,
                    sql_type: "BIGINT".to_string(),
                    unique: false,
                    type_change_using: None,
                }],
                exclusion_constraints: Vec::new(),
                fts: None,
                is_through: false,
                moved_from_app: None,
                partition: None,
                primary_key: PrimaryKeySchema {
                    columns: vec!["old_id".to_string()],
                    kind: PkKindSchema::HeerId,
                },
                rationale: None,
                renamed_from: None,
                rls_enabled: false,
                table: "widgets".to_string(),
                table_comment: None,
                storage_params: None,
                tablespace: None,
                tenant_key: None,
            },
        );

        let mut after = before.clone();
        after.models.insert(
            "widgets".to_string(),
            TableSchema {
                app: None,
                columns: vec![ColumnSchema {
                    name: "new_id".to_string(),
                    renamed_from: Some("old_id".to_string()),
                    ..before.models["widgets"].columns[0].clone()
                }],
                primary_key: PrimaryKeySchema {
                    columns: vec!["new_id".to_string()],
                    kind: PkKindSchema::HeerIdRecencyBiased,
                },
                ..before.models["widgets"].clone()
            },
        );

        let delta = diff_schemas(&before, &after, bucket);

        assert!(
            delta.operations.iter().any(|op| matches!(
                op,
                SchemaOperation::RenameColumn { from, to, .. }
                    if from == "old_id" && to == "new_id"
            )),
            "RenameColumn must be emitted before the PK comparison"
        );
        assert!(
            delta.operations.iter().any(|op| matches!(
                op,
                SchemaOperation::PkTypeFlip {
                    from: PkKindSchema::HeerId,
                    to: PkKindSchema::HeerIdRecencyBiased,
                    ..
                }
            )),
            "PK rename + kind flip must classify as PkTypeFlip, not Unsupported. \
             Operations were: {:?}",
            delta.operations
        );
        assert!(
            !delta
                .operations
                .iter()
                .any(|op| matches!(op, SchemaOperation::Unsupported { .. })),
            "PK rename + kind flip must NOT emit Unsupported"
        );
        // Headline classification is PkTypeFlip (with a co_destructive
        // co-flag of false because no drops are happening).
        assert!(matches!(
            delta.classification,
            Classification::PkTypeFlip {
                co_destructive: false,
                co_lossy: false
            }
        ));
    }

    // ── AddEnumVariant anchor tests ──────────────────────────────────

    /// Build an `AppliedSchema` with a single enum and no models.
    fn schema_with_enum(name: &str, variants: &[&str]) -> AppliedSchema {
        let mut enums = BTreeMap::new();
        enums.insert(
            name.to_string(),
            EnumSchema {
                name: name.to_string(),
                variants: variants.iter().map(|s| s.to_string()).collect(),
            },
        );
        AppliedSchema {
            djogi_version: "0.1.0".to_string(),
            enums,
            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()],
        }
    }

    #[test]
    fn enum_variant_inserted_at_head_anchors_before_first_existing() {
        // Old: ["b", "c"]. New: ["a", "b", "c"]. The new "a" sits at
        // index 0; the next existing variant in the new list is "b",
        // which is in the old set. Anchor: Before "b".
        let before = schema_with_enum("status", &["b", "c"]);
        let after = schema_with_enum("status", &["a", "b", "c"]);
        let delta = diff_schemas(&before, &after, empty_global());
        let anchor = delta
            .operations
            .iter()
            .find_map(|op| match op {
                SchemaOperation::AddEnumVariant {
                    variant, anchor, ..
                } if variant == "a" => Some(anchor.clone()),
                _ => None,
            })
            .expect("AddEnumVariant for `a`");
        assert_eq!(
            anchor,
            Some(EnumVariantAnchor {
                variant: "b".to_string(),
                kind: EnumVariantAnchorKind::Before,
            })
        );
    }

    #[test]
    fn enum_variant_inserted_in_middle_anchors_before_next_existing() {
        // Old: ["a", "c"]. New: ["a", "b", "c"]. New "b" at index 1;
        // post-anchor "c" exists in old. Anchor: Before "c".
        let before = schema_with_enum("status", &["a", "c"]);
        let after = schema_with_enum("status", &["a", "b", "c"]);
        let delta = diff_schemas(&before, &after, empty_global());
        let anchor = delta
            .operations
            .iter()
            .find_map(|op| match op {
                SchemaOperation::AddEnumVariant {
                    variant, anchor, ..
                } if variant == "b" => Some(anchor.clone()),
                _ => None,
            })
            .expect("AddEnumVariant for `b`");
        assert_eq!(
            anchor,
            Some(EnumVariantAnchor {
                variant: "c".to_string(),
                kind: EnumVariantAnchorKind::Before,
            })
        );
    }

    #[test]
    fn enum_variant_inserted_at_tail_anchors_after_last_existing() {
        // Old: ["a", "b"]. New: ["a", "b", "c"]. New "c" lands at the
        // tail of the new list. No post-anchor exists (nothing follows
        // "c"), so per the priority rule on `pick_enum_variant_anchor`
        // the helper falls back to the nearest pre-anchor — "b", the
        // immediate predecessor that is also in the old set. The
        // emitted DDL is `ALTER TYPE "status" ADD VALUE 'c' AFTER 'b'`.
        // The test name matches the helper's actual contract — see the
        // doc-comment on `SchemaOperation::AddEnumVariant.anchor`.
        let before = schema_with_enum("status", &["a", "b"]);
        let after = schema_with_enum("status", &["a", "b", "c"]);
        let delta = diff_schemas(&before, &after, empty_global());
        let anchor = delta
            .operations
            .iter()
            .find_map(|op| match op {
                SchemaOperation::AddEnumVariant {
                    variant, anchor, ..
                } if variant == "c" => Some(anchor.clone()),
                _ => None,
            })
            .expect("AddEnumVariant for `c`");
        assert_eq!(
            anchor,
            Some(EnumVariantAnchor {
                variant: "b".to_string(),
                kind: EnumVariantAnchorKind::After,
            })
        );
    }

    #[test]
    fn multiple_new_variants_each_anchor_against_an_existing_neighbour() {
        // Old: ["b"]. New: ["a", "b", "c"]. Insertions: "a" before
        // "b" (post-anchor in old), "c" after "b" (no post-anchor;
        // pre-anchor "b" works).
        let before = schema_with_enum("status", &["b"]);
        let after = schema_with_enum("status", &["a", "b", "c"]);
        let delta = diff_schemas(&before, &after, empty_global());
        let anchor_a = delta
            .operations
            .iter()
            .find_map(|op| match op {
                SchemaOperation::AddEnumVariant {
                    variant, anchor, ..
                } if variant == "a" => Some(anchor.clone()),
                _ => None,
            })
            .expect("AddEnumVariant a");
        let anchor_c = delta
            .operations
            .iter()
            .find_map(|op| match op {
                SchemaOperation::AddEnumVariant {
                    variant, anchor, ..
                } if variant == "c" => Some(anchor.clone()),
                _ => None,
            })
            .expect("AddEnumVariant c");
        assert_eq!(
            anchor_a,
            Some(EnumVariantAnchor {
                variant: "b".to_string(),
                kind: EnumVariantAnchorKind::Before,
            })
        );
        assert_eq!(
            anchor_c,
            Some(EnumVariantAnchor {
                variant: "b".to_string(),
                kind: EnumVariantAnchorKind::After,
            })
        );
    }

    // ── Transitive FK closure unit tests ─────────────────────────────

    /// Build a minimal `TableSchema` with the given name, a HeerId
    /// PK column called `id`, and the supplied FK columns.
    /// Each `(col_name, ref_table)` entry becomes a `BIGINT NOT NULL`
    /// column with an FK pointing at `ref_table.id`.
    fn synth_table_with_fks(
        table: &str,
        fks: &[(&str, &str)],
        pk_kind: crate::migrate::schema::PkKindSchema,
    ) -> crate::migrate::schema::TableSchema {
        use crate::migrate::schema::{
            ColumnSchema, ForeignKeySchema, OnDeleteSchema, PrimaryKeySchema, TableSchema,
        };
        let mut columns = Vec::new();
        // PK column
        columns.push(ColumnSchema {
            check: None,
            codec: None,
            comment: None,
            default_sql: None,
            foreign_key: None,
            generated: None,
            identity: None,
            index_type: None,
            indexed: false,
            max_length: None,
            name: "id".to_string(),
            nullable: false,
            on_delete: None,
            outbox_exclude: false,
            rationale: None,
            relation_kind: None,
            renamed_from: None,
            sequence_within: None,
            sql_type: "BIGINT".to_string(),
            unique: false,
            type_change_using: None,
        });
        for (col, ref_table) in fks {
            columns.push(ColumnSchema {
                check: None,
                codec: None,
                comment: None,
                default_sql: None,
                foreign_key: Some(ForeignKeySchema {
                    deferrable: false,
                    initially_deferred: false,
                    on_delete: OnDeleteSchema::Restrict,
                    ref_column: "id".to_string(),
                    ref_table: ref_table.to_string(),
                }),
                generated: None,
                identity: None,
                index_type: None,
                indexed: false,
                max_length: None,
                name: col.to_string(),
                nullable: false,
                on_delete: Some(OnDeleteSchema::Restrict),
                outbox_exclude: false,
                rationale: None,
                relation_kind: None,
                renamed_from: None,
                sequence_within: None,
                sql_type: "BIGINT".to_string(),
                unique: false,
                type_change_using: None,
            });
        }
        TableSchema {
            app: None,
            columns,
            exclusion_constraints: Vec::new(),
            fts: None,
            is_through: false,
            moved_from_app: None,
            partition: None,
            primary_key: PrimaryKeySchema {
                columns: vec!["id".to_string()],
                kind: pk_kind,
            },
            rationale: None,
            renamed_from: None,
            rls_enabled: false,
            table: table.to_string(),
            table_comment: None,
            storage_params: None,
            tablespace: None,
            tenant_key: None,
        }
    }

    fn synth_schema_with_tables(
        tables: Vec<crate::migrate::schema::TableSchema>,
    ) -> crate::migrate::schema::AppliedSchema {
        let mut models = BTreeMap::new();
        for t in tables {
            models.insert(t.table.clone(), t);
        }
        crate::migrate::schema::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,
            registered_apps: vec!["".to_string()],
        }
    }

    fn synth_partitioned_cross_flipping_schema(
        left_pk: crate::migrate::schema::PkKindSchema,
        right_pk: crate::migrate::schema::PkKindSchema,
    ) -> crate::migrate::schema::AppliedSchema {
        use crate::migrate::schema::{
            ColumnSchema, ForeignKeySchema, OnDeleteSchema, PartitionSchema, PrimaryKeySchema,
            TableSchema,
        };

        let left = TableSchema {
            app: None,
            columns: vec![
                ColumnSchema {
                    check: None,
                    codec: None,
                    comment: None,
                    default_sql: None,
                    foreign_key: None,
                    generated: None,
                    identity: None,
                    index_type: None,
                    indexed: false,
                    max_length: None,
                    name: "id".to_string(),
                    nullable: false,
                    on_delete: None,
                    outbox_exclude: false,
                    rationale: None,
                    relation_kind: None,
                    renamed_from: None,
                    sequence_within: None,
                    sql_type: "BIGINT".to_string(),
                    unique: false,
                    type_change_using: None,
                },
                ColumnSchema {
                    check: None,
                    codec: None,
                    comment: None,
                    default_sql: None,
                    foreign_key: None,
                    generated: None,
                    identity: None,
                    index_type: None,
                    indexed: false,
                    max_length: None,
                    name: "ts".to_string(),
                    nullable: false,
                    on_delete: None,
                    outbox_exclude: false,
                    rationale: None,
                    relation_kind: None,
                    renamed_from: None,
                    sequence_within: None,
                    sql_type: "TIMESTAMPTZ".to_string(),
                    unique: false,
                    type_change_using: None,
                },
            ],
            exclusion_constraints: Vec::new(),
            fts: None,
            is_through: false,
            moved_from_app: None,
            partition: Some(PartitionSchema::Range {
                column: "ts".to_string(),
            }),
            primary_key: PrimaryKeySchema {
                columns: vec!["ts".to_string(), "id".to_string()],
                kind: left_pk,
            },
            rationale: None,
            renamed_from: None,
            rls_enabled: false,
            table: "left_events".to_string(),
            table_comment: None,
            storage_params: None,
            tablespace: None,
            tenant_key: None,
        };
        let right = synth_table_with_fks("right_tags", &[], right_pk);
        let join = TableSchema {
            app: None,
            columns: vec![
                ColumnSchema {
                    check: None,
                    codec: None,
                    comment: None,
                    default_sql: Some("heerid_next()".to_string()),
                    foreign_key: None,
                    generated: None,
                    identity: None,
                    index_type: None,
                    indexed: false,
                    max_length: None,
                    name: "id".to_string(),
                    nullable: false,
                    on_delete: None,
                    outbox_exclude: false,
                    rationale: None,
                    relation_kind: None,
                    renamed_from: None,
                    sequence_within: None,
                    sql_type: "BIGINT".to_string(),
                    unique: false,
                    type_change_using: None,
                },
                ColumnSchema {
                    check: None,
                    codec: None,
                    comment: None,
                    default_sql: None,
                    foreign_key: Some(ForeignKeySchema {
                        deferrable: false,
                        initially_deferred: false,
                        on_delete: OnDeleteSchema::Restrict,
                        ref_column: "id".to_string(),
                        ref_table: "left_events".to_string(),
                    }),
                    generated: None,
                    identity: None,
                    index_type: None,
                    indexed: false,
                    max_length: None,
                    name: "left_event_id".to_string(),
                    nullable: false,
                    on_delete: Some(OnDeleteSchema::Restrict),
                    outbox_exclude: false,
                    rationale: None,
                    relation_kind: None,
                    renamed_from: None,
                    sequence_within: None,
                    sql_type: "BIGINT".to_string(),
                    unique: false,
                    type_change_using: None,
                },
                ColumnSchema {
                    check: None,
                    codec: None,
                    comment: None,
                    default_sql: None,
                    foreign_key: Some(ForeignKeySchema {
                        deferrable: false,
                        initially_deferred: false,
                        on_delete: OnDeleteSchema::Restrict,
                        ref_column: "id".to_string(),
                        ref_table: "right_tags".to_string(),
                    }),
                    generated: None,
                    identity: None,
                    index_type: None,
                    indexed: false,
                    max_length: None,
                    name: "right_tag_id".to_string(),
                    nullable: false,
                    on_delete: Some(OnDeleteSchema::Restrict),
                    outbox_exclude: false,
                    rationale: None,
                    relation_kind: None,
                    renamed_from: None,
                    sequence_within: None,
                    sql_type: "BIGINT".to_string(),
                    unique: false,
                    type_change_using: None,
                },
            ],
            exclusion_constraints: Vec::new(),
            fts: None,
            is_through: true,
            moved_from_app: None,
            partition: None,
            primary_key: PrimaryKeySchema {
                columns: vec!["left_event_id".to_string(), "right_tag_id".to_string()],
                kind: crate::migrate::schema::PkKindSchema::Serial,
            },
            rationale: None,
            renamed_from: None,
            rls_enabled: false,
            table: "event_tags".to_string(),
            table_comment: None,
            storage_params: None,
            tablespace: None,
            tenant_key: None,
        };
        synth_schema_with_tables(vec![left, right, join])
    }

    /// 4-level cascade A → B → C → D where A flips. The closure
    /// should walk through every level (visited_tables grows to
    /// include B, C, D) without panicking. For asc↔desc the
    /// children list contains B as a direct child (depth 1) — C
    /// and D become reachable via the closure but are NOT
    /// shadow-column targets for this flip variant.
    #[test]
    fn transitive_fk_closure_walks_four_level_cascade() {
        use crate::migrate::schema::PkKindSchema;
        // A has the flipping PK; B → A, C → B, D → C.
        let after = synth_schema_with_tables(vec![
            synth_table_with_fks("a", &[], PkKindSchema::HeerId),
            synth_table_with_fks("b", &[("a_id", "a")], PkKindSchema::HeerId),
            synth_table_with_fks("c", &[("b_id", "b")], PkKindSchema::HeerId),
            synth_table_with_fks("d", &[("c_id", "c")], PkKindSchema::HeerId),
        ]);
        let mut ops = vec![SchemaOperation::PkTypeFlip {
            table: "a".to_string(),
            from: PkKindSchema::HeerId,
            to: PkKindSchema::HeerIdRecencyBiased,
        }];
        // Closure must terminate without panicking.
        promote_pk_flips_to_groups(&after, &mut ops).expect("closure must not error in this test");
        // Resulting group: B is a direct child of A; C and D are NOT
        // children for the asc↔desc flip (their FKs point at B's /
        // C's `id`, not A's). The transitive closure walked them but
        // did not promote them to shadow-column orchestration.
        let group = ops
            .iter()
            .find_map(|op| match op {
                SchemaOperation::PkTypeFlipGroup(g) => Some(g),
                _ => None,
            })
            .expect("PkTypeFlipGroup emitted");
        assert_eq!(group.parent_table, "a");
        assert_eq!(
            group
                .children
                .iter()
                .map(|c| c.table.as_str())
                .collect::<Vec<_>>(),
            vec!["b"],
            "for asc↔desc only depth-1 children become shadow-column targets",
        );
    }

    /// Cycle A ↔ B: A has FK to B, B has FK to A. Closure must
    /// terminate (visited-set protection) and the cycle peer is
    /// recorded BOTH as a [`PkFlipCycle`] (drives cutover-level
    /// `SET CONSTRAINTS ALL DEFERRED`) AND as a [`PkFlipChild`] with
    /// `cycle_flag = true` (drives shadow-column orchestration plus
    /// per-FK `DEFERRABLE INITIALLY DEFERRED`). Cycle peers are
    /// first-class children so every segment emitter (preparation,
    /// backfill, concurrent index, NOT NULL proof, cutover) iterates
    /// them uniformly with the rest of the cascade.
    #[test]
    fn transitive_fk_closure_terminates_on_cycle() {
        use crate::migrate::schema::PkKindSchema;
        let after = synth_schema_with_tables(vec![
            // a.b_id references b
            synth_table_with_fks("a", &[("b_id", "b")], PkKindSchema::HeerId),
            // b.a_id references a — closes the cycle
            synth_table_with_fks("b", &[("a_id", "a")], PkKindSchema::HeerId),
        ]);
        let mut ops = vec![SchemaOperation::PkTypeFlip {
            table: "a".to_string(),
            from: PkKindSchema::HeerId,
            to: PkKindSchema::HeerIdRecencyBiased,
        }];
        // Must not loop indefinitely — visited-set + frontier
        // tracking guarantees termination.
        promote_pk_flips_to_groups(&after, &mut ops).expect("closure must not error in this test");
        let group = ops
            .iter()
            .find_map(|op| match op {
                SchemaOperation::PkTypeFlipGroup(g) => Some(g),
                _ => None,
            })
            .expect("PkTypeFlipGroup emitted");
        assert_eq!(group.cycles.len(), 1, "cycle peer detected");
        assert_eq!(group.cycles[0].peer_table, "b");
        // Peer also lands in `children` with cycle_flag = true
        // so each segment emits the b.a_id_desc shadow-column work.
        let cycle_children: Vec<_> = group
            .children
            .iter()
            .filter(|c| c.cycle_flag)
            .map(|c| (c.table.as_str(), c.fk_column.as_str()))
            .collect();
        assert_eq!(cycle_children, vec![("b", "a_id")]);
    }

    /// 3-level cascade with no cycles — sanity: closure walks
    /// past depth-1 without spuriously panicking.
    #[test]
    fn transitive_fk_closure_handles_three_level_cascade_without_panic() {
        use crate::migrate::schema::PkKindSchema;
        let after = synth_schema_with_tables(vec![
            synth_table_with_fks("p", &[], PkKindSchema::HeerId),
            synth_table_with_fks("c1", &[("p_id", "p")], PkKindSchema::HeerId),
            synth_table_with_fks("g1", &[("c_id", "c1")], PkKindSchema::HeerId),
        ]);
        let mut ops = vec![SchemaOperation::PkTypeFlip {
            table: "p".to_string(),
            from: PkKindSchema::HeerId,
            to: PkKindSchema::HeerIdRecencyBiased,
        }];
        promote_pk_flips_to_groups(&after, &mut ops).expect("closure must not error in this test");
        let group = ops
            .iter()
            .find_map(|op| match op {
                SchemaOperation::PkTypeFlipGroup(g) => Some(g),
                _ => None,
            })
            .expect("group");
        // Depth-1 children only (asc↔desc invariant).
        assert_eq!(group.children.len(), 1);
        assert_eq!(group.children[0].table, "c1");
    }

    /// A chain longer than the closure's `MAX_CLOSURE_DEPTH` returns
    /// a structured [`DiffError::PkFlipCascadeDepthExceeded`] rather
    /// than panicking. The test routes through `diff_bucket_maps`, the
    /// call path that production callers (compose / build / runner) use,
    /// proving the depth-65 contract holds when the differ owns op
    /// promotion.
    /// Test setup:
    /// * `before`: 70-level FK chain (P → T1 → ... → T70) with
    ///   P's PK kind set to `HeerId`.
    /// * `after`: SAME 70-level chain with P's PK kind flipped
    ///   to `HeerIdRecencyBiased`. The differ emits one
    ///   `PkTypeFlip` op for `p` and the closure walks the
    ///   chain.
    /// * Assert `diff_bucket_maps` returns
    ///   `Err(DiffError::PkFlipCascadeDepthExceeded { ... })`
    ///   with the chain populated.
    #[test]
    fn diff_bucket_maps_emits_pk_flip_cascade_depth_exceeded_on_deep_graph() {
        use crate::migrate::projection::BucketKey;
        use crate::migrate::schema::PkKindSchema;
        // Helper: build the 70-level chain with parametric P PK
        // kind so before/after differ only on P's PK.
        let build_chain = |p_pk: PkKindSchema| -> AppliedSchema {
            let mut tables: Vec<crate::migrate::schema::TableSchema> = Vec::new();
            tables.push(synth_table_with_fks("p", &[], p_pk));
            for i in 1..=70u32 {
                let prev = if i == 1 {
                    "p".to_string()
                } else {
                    format!("t{}", i - 1)
                };
                let name = format!("t{i}");
                let prev_str = prev.as_str();
                let table =
                    synth_table_with_fks(&name, &[("ref_id", prev_str)], PkKindSchema::HeerId);
                tables.push(table);
            }
            synth_schema_with_tables(tables)
        };
        let bucket = BucketKey {
            database: "main".to_string(),
            app: "".to_string(),
        };
        let before: BTreeMap<BucketKey, AppliedSchema> = {
            let mut m = BTreeMap::new();
            m.insert(bucket.clone(), build_chain(PkKindSchema::HeerId));
            m
        };
        let after: BTreeMap<BucketKey, AppliedSchema> = {
            let mut m = BTreeMap::new();
            m.insert(
                bucket.clone(),
                build_chain(PkKindSchema::HeerIdRecencyBiased),
            );
            m
        };
        let err = diff_bucket_maps(&before, &after)
            .expect_err("70-level chain must trigger depth contract via diff_bucket_maps");
        match err {
            DiffError::PkFlipCascadeDepthExceeded {
                parent_table,
                chain,
                max_depth,
            } => {
                assert_eq!(parent_table, "p");
                assert_eq!(max_depth, 65);
                // Chain must include the parent + at least one
                // entry per depth level; final length depends on
                // whether the BFS picked p itself as depth-0.
                assert!(
                    chain.len() >= 2,
                    "chain must record at least the parent and one descendant: {chain:?}",
                );
                assert_eq!(chain[0], "p");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn diff_bucket_maps_rejects_partitioned_cross_flipping_cluster() {
        use crate::migrate::projection::BucketKey;
        use crate::migrate::schema::PkKindSchema;

        let bucket = BucketKey {
            database: "main".to_string(),
            app: "".to_string(),
        };
        let before: BTreeMap<BucketKey, AppliedSchema> = {
            let mut m = BTreeMap::new();
            m.insert(
                bucket.clone(),
                synth_partitioned_cross_flipping_schema(PkKindSchema::HeerId, PkKindSchema::HeerId),
            );
            m
        };
        let after: BTreeMap<BucketKey, AppliedSchema> = {
            let mut m = BTreeMap::new();
            m.insert(
                bucket.clone(),
                synth_partitioned_cross_flipping_schema(
                    PkKindSchema::HeerIdRecencyBiased,
                    PkKindSchema::HeerIdRecencyBiased,
                ),
            );
            m
        };

        let err = diff_bucket_maps(&before, &after)
            .expect_err("partitioned + cross-flipping cluster must reject");
        match err {
            DiffError::PartitionedMultiParentClusterUnsupported {
                partitioned_parents,
                cross_flipping_partners,
            } => {
                assert_eq!(partitioned_parents, vec!["left_events".to_string()]);
                assert_eq!(
                    cross_flipping_partners,
                    vec!["left_events".to_string(), "right_tags".to_string()]
                );
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    /// Display rendering of `DiffError::PkFlipCascadeDepthExceeded`
    /// the operator-facing message identifies the chain root,
    /// reports the contract limit, and prints the trail. Pure
    /// formatting test, no differ invocation needed.
    #[test]
    fn pk_flip_cascade_depth_exceeded_display_renders_operator_message() {
        let display = format!(
            "{}",
            DiffError::PkFlipCascadeDepthExceeded {
                parent_table: "p".to_string(),
                chain: vec!["p".to_string(), "t1".to_string()],
                max_depth: 65,
            }
        );
        assert!(display.contains("rooted at p"));
        assert!(display.contains("65 levels"));
        assert!(display.contains("table_chain"));
    }

    // ── VARCHAR(n) type-change detection tests ──────────────────────

    #[test]
    fn text_to_varchar_emits_change_type() {
        // `String` field with no `max_length` → `String` field with
        // `max_length = 100`: the descriptor flips from `Text` to
        // `Varchar(100)`, which must surface as `ColumnChange::ChangeType`
        // from "TEXT" to "VARCHAR(100)".
        const TEXT: FieldDescriptor = field_descriptor("slug", FieldSqlType::Text, false);
        const VARCHAR: FieldDescriptor =
            field_descriptor("slug", FieldSqlType::Varchar(100), false);
        static TEXT_SLICE: &[FieldDescriptor] = &[TEXT];
        static VARCHAR_SLICE: &[FieldDescriptor] = &[VARCHAR];
        let model_text = ModelDescriptor {
            fields: TEXT_SLICE,
            ..synth_model("articles", "Article")
        };
        let model_varchar = ModelDescriptor {
            fields: VARCHAR_SLICE,
            ..synth_model("articles", "Article")
        };
        let before = project_one(&model_text);
        let after = project_one(&model_varchar);
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "slug");
        assert!(
            changes.iter().any(|c| matches!(
                c,
                ColumnChange::ChangeType { from, to, .. }
                    if from == "TEXT" && to == "VARCHAR(100)"
            )),
            "TEXT → VARCHAR(100) must emit ColumnChange::ChangeType; got: {changes:?}"
        );
    }

    #[test]
    fn varchar_width_change_emits_change_type() {
        // `VARCHAR(100)` → `VARCHAR(200)`: must surface as
        // `ColumnChange::ChangeType` from "VARCHAR(100)" to "VARCHAR(200)".
        const V100: FieldDescriptor = field_descriptor("slug", FieldSqlType::Varchar(100), false);
        const V200: FieldDescriptor = field_descriptor("slug", FieldSqlType::Varchar(200), false);
        static V100_SLICE: &[FieldDescriptor] = &[V100];
        static V200_SLICE: &[FieldDescriptor] = &[V200];
        let before = project_one(&ModelDescriptor {
            fields: V100_SLICE,
            ..synth_model("articles", "Article")
        });
        let after = project_one(&ModelDescriptor {
            fields: V200_SLICE,
            ..synth_model("articles", "Article")
        });
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "slug");
        assert!(
            changes.iter().any(|c| matches!(
                c,
                ColumnChange::ChangeType { from, to, .. }
                    if from == "VARCHAR(100)" && to == "VARCHAR(200)"
            )),
            "VARCHAR(100) → VARCHAR(200) must emit ColumnChange::ChangeType; got: {changes:?}"
        );
    }

    // ── Codec transition detection (issue #371, Class C) ────────────────────

    /// Build an `AppliedSchema` with a single user column `token` carrying the
    /// given `sql_type` and optional `codec`, plus the framework `id` column.
    fn build_codec_table(
        sql_type: &str,
        codec: Option<&str>,
    ) -> crate::migrate::schema::AppliedSchema {
        use crate::migrate::schema::{
            AppliedSchema, ColumnSchema, PkKindSchema, PrimaryKeySchema, TableSchema,
        };
        use std::collections::BTreeMap;

        let id_col = ColumnSchema {
            check: None,
            codec: None,
            comment: None,
            default_sql: Some("heerid_next()".to_string()),
            foreign_key: None,
            generated: None,
            identity: None,
            index_type: None,
            indexed: false,
            max_length: None,
            name: "id".to_string(),
            nullable: false,
            on_delete: None,
            outbox_exclude: false,
            rationale: None,
            relation_kind: None,
            renamed_from: None,
            sequence_within: None,
            sql_type: "BIGINT".to_string(),
            unique: false,
            type_change_using: None,
        };
        let token_col = ColumnSchema {
            check: None,
            codec: codec.map(|s| s.to_string()),
            comment: None,
            default_sql: None,
            foreign_key: None,
            generated: None,
            identity: None,
            index_type: None,
            indexed: false,
            max_length: None,
            name: "token".to_string(),
            nullable: false,
            on_delete: None,
            outbox_exclude: false,
            rationale: None,
            relation_kind: None,
            renamed_from: None,
            sequence_within: None,
            sql_type: sql_type.to_string(),
            unique: false,
            type_change_using: None,
        };
        let mut models = BTreeMap::new();
        models.insert(
            "vault".to_string(),
            TableSchema {
                app: None,
                columns: vec![id_col, token_col],
                exclusion_constraints: vec![],
                fts: None,
                is_through: false,
                moved_from_app: None,
                partition: None,
                primary_key: PrimaryKeySchema {
                    columns: vec!["id".to_string()],
                    kind: PkKindSchema::HeerId,
                },
                rationale: None,
                renamed_from: None,
                rls_enabled: false,
                table: "vault".to_string(),
                table_comment: None,
                storage_params: None,
                tablespace: None,
                tenant_key: None,
            },
        );
        AppliedSchema {
            djogi_version: "0.1.0".to_string(),
            enums: BTreeMap::new(),
            format_version: "1".to_string(),
            generated_at: "2026-06-10T00:00:00Z".to_string(),
            indexes: vec![],
            models,
            registered_apps: vec!["".to_string()],
        }
    }

    #[test]
    fn same_sql_type_codec_swap_emits_codec_change_not_nothing() {
        // Both codecs render BYTEA — sql_type is identical on both sides. The
        // differ must still emit exactly one CodecChange op (NOT zero ops —
        // the silent-no-op bug — and NOT a ChangeType, since sql_type is
        // unchanged). This is the load-bearing Pre-flight §8 regression guard.
        let before = build_codec_table("BYTEA", Some("aes256_gcm_v1"));
        let after = build_codec_table("BYTEA", Some("aes256_gcm_v2"));
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "token");
        assert_eq!(
            changes.len(),
            1,
            "a same-sql_type codec swap must emit exactly one op; got: {changes:?}"
        );
        assert!(
            matches!(
                &changes[0],
                ColumnChange::CodecChange { from_codec: Some(f), to_codec: Some(t) }
                    if f == "aes256_gcm_v1" && t == "aes256_gcm_v2"
            ),
            "expected a CodecChange(v1 -> v2); got: {:?}",
            changes[0]
        );
        assert!(
            !changes
                .iter()
                .any(|c| matches!(c, ColumnChange::ChangeType { .. })),
            "no ChangeType op for an unchanged sql_type; got: {changes:?}"
        );
    }

    #[test]
    fn plaintext_to_codec_emits_codec_change_and_suppresses_change_type() {
        // plaintext -> codec flips VARCHAR/TEXT -> BYTEA, so type_changed is
        // true. The transition must be owned by CodecChange and the ChangeType
        // suppressed — otherwise the differ would emit a `::BYTEA` cast that
        // writes plaintext UTF-8 bytes into the "encrypted" column.
        let before = build_codec_table("TEXT", None);
        let after = build_codec_table("BYTEA", Some("aes256_gcm_v1"));
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "token");
        assert!(
            changes.iter().any(|c| matches!(
                c,
                ColumnChange::CodecChange { from_codec: None, to_codec: Some(t) }
                    if t == "aes256_gcm_v1"
            )),
            "plaintext->codec must emit CodecChange(None -> v1); got: {changes:?}"
        );
        assert!(
            !changes
                .iter()
                .any(|c| matches!(c, ColumnChange::ChangeType { .. })),
            "ChangeType must be suppressed when the type change is codec-driven \
             (no ::BYTEA cast); got: {changes:?}"
        );
    }

    #[test]
    fn codec_drop_emits_codec_change() {
        // codec -> plaintext (BYTEA -> TEXT) is also owned by CodecChange.
        let before = build_codec_table("BYTEA", Some("aes256_gcm_v1"));
        let after = build_codec_table("TEXT", None);
        let delta = diff_schemas(&before, &after, empty_global());
        let changes = alter_column_changes_for(&delta, "token");
        assert!(
            changes.iter().any(|c| matches!(
                c,
                ColumnChange::CodecChange { from_codec: Some(f), to_codec: None }
                    if f == "aes256_gcm_v1"
            )),
            "codec->plaintext must emit CodecChange(v1 -> None); got: {changes:?}"
        );
        assert!(
            !changes
                .iter()
                .any(|c| matches!(c, ColumnChange::ChangeType { .. })),
            "ChangeType must be suppressed for a codec drop; got: {changes:?}"
        );
    }

    #[test]
    fn plaintext_to_codec_classifies_offline_only() {
        // End-to-end Class C acceptance (issue #371): a field gaining a codec
        // against a prior plaintext snapshot produces a CodecChange op that the
        // classifier rates OfflineOnly.
        use crate::live_migrate::classify::{ClassifyContext, classify_operation};
        use crate::live_migrate::{LoggingProfile, TargetDatabase};
        use crate::migrate::schema::OnlineSafetyClassification;
        use std::collections::BTreeMap;

        let before = build_codec_table("TEXT", None);
        let after = build_codec_table("BYTEA", Some("aes256_gcm_v1"));
        let delta = diff_schemas(&before, &after, empty_global());
        let codec_op = delta
            .operations
            .iter()
            .find(|op| {
                matches!(
                    op,
                    SchemaOperation::AlterColumn {
                        change: ColumnChange::CodecChange { .. },
                        ..
                    }
                )
            })
            .expect("a CodecChange op must be present for plaintext->codec");

        let inbound: BTreeMap<String, u32> = BTreeMap::new();
        let overrides: BTreeMap<(String, String), crate::descriptor::DefaultVolatility> =
            BTreeMap::new();
        let ctx = ClassifyContext {
            estimated_rows: Some(1_000),
            validation_threshold_rows: 100_000,
            multi_fk_threshold: 4,
            logging_profile: LoggingProfile::Balanced,
            target_database: TargetDatabase::Application,
            inbound_fk_counts: &inbound,
            default_volatility_overrides: &overrides,
        };
        assert_eq!(
            classify_operation(codec_op, &ctx),
            OnlineSafetyClassification::OfflineOnly,
            "plaintext->codec must classify OfflineOnly"
        );
    }
}