autumn-cli 0.9.0

CLI tool for the Autumn web framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
//! `autumn db scrub` — turn a production database (or an `autumn db backup`
//! artifact) into an anonymized copy that is safe on a laptop or a shared
//! staging box (issue #1602).
//!
//! # Why this exists
//!
//! The moment logical backups ship (#1595), a production copy is one command
//! away from a non-production machine — PII and all. Every peer tool for this
//! job (Greenmask, pgsync + obfuscation config, the PostgreSQL Anonymizer
//! extension, django-scrubber) is **schema-blind**: the developer hand-maintains
//! a column list that silently rots the first time someone adds an `email`
//! column, which is exactly the failure mode that leaks PII.
//!
//! Autumn is not schema-blind. This command classifies columns from three
//! sources, in precedence order:
//!
//! 1. **`[tables.<t>.pii]` in `scrub.toml`** — the developer's explicit
//!    declaration, including the replacement strategy.
//! 2. **`#[encrypted]` model columns** — machine-readable PII semantics the
//!    framework already holds ([`crate::schema::parse::parse_encrypted_columns`]).
//!    A `safe` declaration may **not** override these.
//! 3. **GDPR `ModelRegistration::anonymize("<table>")` registrations** — a
//!    table-level signal, so every non-key column of that table is classified
//!    PII unless explicitly declared `safe`.
//!
//! Everything left over is **unclassified**, and an unclassified column is a
//! hard failure (`ScrubError::Unclassified`) — never a silent pass-through.
//! Because the column universe comes from **introspecting the live database**
//! (not from the config file), a column added yesterday cannot be missing from
//! that universe: adding a column without declaring it breaks the scrub, which
//! is the whole point.
//!
//! # Safety properties
//!
//! - **Fail-closed.** Unclassified, stale (naming a column that no longer
//!   exists), and self-contradictory declarations all refuse before a single row
//!   is touched. The one exception is `--artifact`: the restore must run before
//!   the classification can read the schema it creates, so a refusal after a
//!   restore leaves unscrubbed data in the target — and says so, loudly.
//! - **Production guard.** Writing refuses outside `dev`/`test` without
//!   `--force`, the identical protocol as `autumn db drop`
//!   ([`crate::db::guard_destructive`]).
//! - **Constraint-preserving.** PII on a primary- or foreign-key column is
//!   refused outright (so referential integrity is untouched), `NULL` is refused
//!   on a `NOT NULL` column, a constant replacement is refused on a `UNIQUE`
//!   column, and a `varchar(n)` bound narrows the generated value or refuses.
//! - **Atomic.** Every target is classified before any target is written (so an
//!   undeclared column on one shard cannot leave the topology half anonymized),
//!   and every statement for one database runs in a single transaction: a
//!   half-scrubbed database is never left behind.
//! - **Framework-aware.** Introspection excludes `autumn_*` tables from the
//!   classified universe, so the ones that carry app-supplied payloads (queued
//!   jobs, offline-sync rows, `api_tokens`) are reported separately and emptied
//!   when the app opts in with `[framework] purge`.
//! - **Credential-safe.** No error or report ever embeds a resolved URL.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use autumn_schema_core::{Column, ColumnType, Table};
use diesel::connection::SimpleConnection as _;
use diesel::{Connection as _, PgConnection, RunQueryDsl as _, sql_query};
use serde::Deserialize;

use crate::migrate;
use crate::schema::introspect;

/// Referentially-intact row subsetting (issue #1636). A submodule of the scrub
/// rather than a sibling: a sample is a phase of one scrub transaction, never a
/// command of its own, so no flag combination can emit sampled-but-unscrubbed
/// rows.
pub mod sample;

/// `SQLite` targets (issue #2553): the same classifier, a `SQLite` probe and
/// apply step.
mod sqlite;

use super::{quote_ident, quote_literal};

/// The per-app PII declaration file, read from the project root unless
/// `--config` points elsewhere.
pub const SCRUB_CONFIG_FILE: &str = "scrub.toml";

/// Width of the per-row `md5` token, in hex characters.
const TOKEN_HEX_LEN: usize = 32;

/// Width of the per-row `sha256` token used for columns that must stay unique.
const UNIQUE_TOKEN_HEX_LEN: usize = 64;

/// Narrowest token a length-bounded, non-unique column may carry. Below this the
/// column is refused rather than silently truncated.
const MIN_TOKEN_WIDTH: usize = 8;

/// Narrowest token a length-bounded **unique** column may carry: 16 hex
/// characters is 64 bits, so the birthday bound puts a collision beyond any
/// plausible row count. Eight (32 bits) is not enough — it collides in practice
/// around 10⁵ rows, which is a routine table size, and the resulting
/// unique-violation aborts the whole scrub.
const MIN_UNIQUE_TOKEN_WIDTH: usize = 16;

/// The reserved, permanently undeliverable domain scrubbed addresses use
/// (RFC 6761 reserves `.invalid`).
const SCRUB_EMAIL_DOMAIN: &str = "@example.invalid";

// ─── Arguments ──────────────────────────────────────────────────────────────

/// Arguments for `autumn db scrub`.
#[derive(Debug, Clone, Default)]
// Each flag is an independent switch on one run, not a state machine.
#[allow(clippy::struct_excessive_bools)]
pub struct ScrubArgs {
    /// Profile overlay to resolve the connection under (see `db create`).
    pub profile: Option<String>,
    /// Restore this backup run directory (or artifact file) into the resolved
    /// database(s) before scrubbing, closing the backup → scrub → restore loop.
    pub artifact: Option<PathBuf>,
    /// After a successful scrub, write a fresh backup run into this directory —
    /// a scrubbed artifact that can be handed to a teammate.
    pub output: Option<PathBuf>,
    /// Path to the PII declaration file (default: `./scrub.toml`).
    pub config: Option<PathBuf>,
    /// Classify only: report the plan (or the unclassified columns) and write
    /// nothing.
    pub check: bool,
    /// Print the exact SQL the scrub would run and write nothing.
    pub dry_run: bool,
    /// Bypass the production guard (mirrors `autumn db drop --force`).
    pub force: bool,
    /// Bypass the separate guard that refuses to write over the database an
    /// artifact's own non-dev/test profile config declares.
    pub allow_source_overwrite: bool,
    /// Root entities to sample, each `<table>=<count|percent%>` (issue #1636).
    /// Empty means no sampling: the whole scrubbed copy is kept.
    pub sample: Vec<String>,
    /// The seed the sample's row selection is derived from, so the same seed
    /// against the same source data reproduces the identical subset.
    pub seed: u64,
}

// ─── Errors ─────────────────────────────────────────────────────────────────

/// Failure modes for `autumn db scrub`. `Display` is credential-safe: no variant
/// ever embeds a resolved URL (only a parsed host/port/db), matching the rest of
/// the `db` command family.
#[derive(Debug)]
pub enum ScrubError {
    /// One or more columns are neither PII-classified nor explicitly declared
    /// safe. The scrub refuses rather than let real data through (AC #3).
    Unclassified {
        /// `table.column`, sorted.
        columns: Vec<String>,
    },
    /// The declaration names a table or column the database does not have —
    /// the config has rotted away from the schema.
    StaleConfig {
        /// `table` or `table.column`, sorted.
        entries: Vec<String>,
    },
    /// A column is declared both `safe` and PII in the same table.
    Contradiction {
        /// `table.column`, sorted.
        columns: Vec<String>,
    },
    /// A `safe` declaration tried to un-classify an `#[encrypted]` column.
    SafeOverridesEncrypted {
        /// `table.column`, sorted.
        columns: Vec<String>,
    },
    /// PII was declared on a primary-, foreign- or partition-key column. A scrub
    /// may not rewrite these.
    PiiOnKeyColumn {
        /// `table.column`, sorted.
        columns: Vec<String>,
    },
    /// No replacement can be derived from the column's type alone.
    NoAutoStrategy {
        /// The column name.
        column: String,
        /// The unsupported type, rendered for humans.
        detail: String,
    },
    /// The `null` strategy was declared on a `NOT NULL` column.
    NullOnNotNull {
        /// `table.column`.
        column: String,
    },
    /// A strategy that yields the same value for every row was declared on a
    /// `UNIQUE` column.
    NonUniqueStrategy {
        /// `table.column`.
        column: String,
        /// The offending strategy name.
        strategy: &'static str,
    },
    /// A strategy cannot produce a value of the column's type.
    StrategyTypeMismatch {
        /// The column name.
        column: String,
        /// The offending strategy name.
        strategy: &'static str,
        /// The column type, rendered for humans.
        detail: String,
    },
    /// A length-bounded column is too narrow to hold a per-row-unique fake.
    ColumnTooNarrow {
        /// The column name.
        column: String,
        /// The column's character limit.
        limit: usize,
        /// Characters the strategy's fixed affixes already consume.
        overhead: usize,
        /// Token characters the column must still have room for.
        floor: usize,
    },
    /// The replacement envelope of an `#[encrypted]` column is longer than its
    /// bounded column.
    EncryptedEnvelopeTooLong {
        /// `table.column`.
        column: String,
        /// The column's character limit.
        limit: usize,
        /// Characters the envelope takes.
        needed: usize,
    },
    /// A declaration tried to write plaintext into an `#[encrypted]` column.
    PlaintextIntoEncrypted {
        /// Each entry is `table.column` plus the strategy that was declared.
        columns: Vec<String>,
    },
    /// A PII column is covered by a `CHECK` constraint, which no fabricated
    /// value can be proven to satisfy.
    CheckConstrainedColumn {
        /// `table.column`.
        column: String,
    },
    /// A PII column is an operand of a constraint no per-row token can be
    /// shown to keep satisfied: a unique index expression or predicate, or an
    /// exclusion constraint.
    IndexOperandColumn {
        /// `table.column`.
        column: String,
        /// What the column is an operand of.
        kind: &'static str,
    },
    /// The schema changed between classification and the apply transaction, so
    /// the plan no longer covers every column.
    SchemaChanged {
        /// What changed, sorted.
        entries: Vec<String>,
    },
    /// The target holds `#[encrypted]` columns but no encryption key could be
    /// resolved, so a valid replacement envelope cannot be produced.
    EncryptionKeyUnavailable {
        /// The profile whose credentials were read.
        profile: String,
        /// A credential-safe reason.
        detail: String,
    },
    /// Neither the model source nor the declaration says which columns are
    /// `#[encrypted]`, so the scrub cannot tell them apart from plain text.
    EncryptedMetadataUnavailable,
    /// `public` holds base tables the connecting role cannot see, so they never
    /// reached the classifier.
    InaccessibleTables {
        /// The table names, sorted.
        tables: Vec<String>,
    },
    /// The target has base tables outside `public`, which the classification
    /// universe does not cover.
    UnsupportedSchemas {
        /// The schema names, sorted.
        schemas: Vec<String>,
    },
    /// The target uses legacy `INHERITS` table inheritance, which the sample
    /// cannot model: a statement naming the parent silently reaches the child.
    LegacyInheritance {
        /// `child (inherits parent)` descriptions, sorted.
        tables: Vec<String>,
    },
    /// The connection is in a `session_replication_role` other than `origin`,
    /// where `ENABLE REPLICA` triggers and rules fire and ordinary ones do not
    /// — inverting the enablement rule every hazard check here is built on.
    ReplicaSessionRole {
        /// The role the connection reports.
        role: String,
    },
    /// `--dry-run` cannot print a connection boundary for a target, because its
    /// connection string is in keyword form and no password can be removed from
    /// that with certainty. Without the boundary the printed script would run
    /// this target's destructive plan against whatever database the pasting
    /// session happens to be connected to.
    UnprintableTarget {
        /// The target labels, sorted.
        targets: Vec<String>,
    },
    /// `--dry-run` cannot print a runnable script because the plan rewrites an
    /// `#[encrypted]` column, and that rewrite has no SQL form: the replacement
    /// is an AEAD envelope sealed per row under the target's key, which cannot
    /// be printed without printing the key.
    ///
    /// The script is withheld whole rather than printed with the one statement
    /// missing. A printed stream is pasted into an interactive psql, and there
    /// is no marker that stops one: measured on psql 16.13, a `RAISE EXCEPTION`
    /// aborts its own transaction only — the `COMMIT` below it clears the
    /// aborted state, and every later statement, including the next target's
    /// `\connect` and its deletes, runs for real.
    UnprintableEncryptedRewrite {
        /// The columns that cannot be printed, as `target: table.column`, sorted.
        columns: Vec<String>,
    },
    /// `--dry-run` cannot print a runnable script for a profile the command
    /// refuses to scrub without `--force`.
    ///
    /// The script is executable and its `\connect` names the protected target,
    /// so printing it hands over exactly the run the profile guard exists to
    /// stop — and the password is removed on purpose, which `.pgpass` supplies.
    UnprintableProductionTarget {
        /// The refused profile.
        profile: String,
    },
    /// The materialized-view dependency walk did not reach every view, so the
    /// run cannot refresh them all — and an unrefreshed view keeps the rows it
    /// selected before the scrub.
    UnrefreshableViews {
        /// The views the walk never reached, sorted.
        views: Vec<String>,
    },
    /// `--dry-run` cannot print a guard that distinguishes this target from a
    /// physical clone of it: the connection is over a Unix socket (so the
    /// address and port are NULL) and the role cannot read `data_directory`,
    /// which is the only value a clone does not share.
    UnprintableAmbiguousTarget {
        /// The target labels, sorted.
        targets: Vec<String>,
    },
    /// A materialized view's definition calls a function whose body `PostgreSQL`
    /// does not track, so the run cannot know which views it reads and cannot
    /// order the refresh around it.
    UntraceableViewFunction {
        /// `view via function`, sorted.
        views: Vec<String>,
    },
    /// `--dry-run` cannot prove the reconnect for a target whose connection
    /// string leaves the port to libpq: psql resolves it from `PGPORT` (or the
    /// 5432 default) at PASTE time, which need not be what it resolved when the
    /// run planned.
    UnprintablePortlessTarget {
        /// The target labels, sorted.
        targets: Vec<String>,
    },
    /// `--dry-run` cannot print a runnable script for a target whose connection
    /// string states `hostaddr`. It selects the endpoint independently of
    /// `host`, and psql exposes no variable reporting it, so the reconnect proof
    /// cannot tell two such targets apart.
    UnprintableHostaddrTarget {
        /// The target labels, sorted.
        targets: Vec<String>,
    },
    /// A materialized view this run refreshes reads relations named in a STRING
    /// the server executes at runtime, so the catalog records no dependency on
    /// them and the refresh order cannot be derived.
    ViewReadsRelationsByName {
        /// `view via function`, sorted.
        views: Vec<String>,
    },
    /// `--dry-run` cannot print a runnable script for a target whose connection
    /// string names more than one endpoint. Which member libpq picks is decided
    /// per connection, so the counts baked into the script and the session that
    /// pastes it need not be the same database.
    UnprintableMultiHostTarget {
        /// The target labels, sorted.
        targets: Vec<String>,
    },
    /// A table this run promises to empty carries a user-defined trigger or
    /// rewrite rule that fires on `DELETE`. That emptying pass is the run's LAST
    /// write, so anything it writes lands after every rewrite and is never
    /// verified.
    EmptyingTriggerLeak {
        /// The table names, sorted.
        tables: Vec<String>,
    },
    /// The target has row-level security on a table this run reads or writes —
    /// a rewrite, an emptying `DELETE`, the sample's own reads, or an endpoint
    /// of the foreign key re-count.
    RowLevelSecurity {
        /// The table names, sorted.
        tables: Vec<String>,
    },
    /// `[tables.<t>]` declares a framework-owned table, which the column
    /// classification never sees.
    FrameworkTableDeclared {
        /// The table names, sorted.
        tables: Vec<String>,
    },
    /// `[framework] purge` names a table whose contents the database needs.
    PurgeSchemaBookkeeping {
        /// The table names, sorted.
        tables: Vec<String>,
    },
    /// The declaration file could not be read or parsed.
    Config {
        /// The path that failed.
        path: String,
        /// A human-readable reason.
        detail: String,
    },
    /// An app source file could not be read or parsed while scanning for
    /// `#[encrypted]` columns / GDPR registrations.
    SourceScan {
        /// A human-readable reason (carries the offending path).
        detail: String,
    },
    /// A `ModelRegistration::anonymize(...)` call was found whose table name is
    /// not a string literal, so the scanner cannot classify it. Refused rather
    /// than ignored — an unreadable registration must not look like an absent
    /// one.
    UnresolvableAnonymize {
        /// The call as written, for the developer to find it.
        detail: String,
    },
    /// The database could not be introspected or connected to. Carries only the
    /// parsed host/port/db, never the credentials.
    Introspect {
        /// The target label (`control` / `shard:<name>`).
        label: String,
        /// A credential-safe reason.
        detail: String,
    },
    /// A scrub statement failed. The message comes from the server.
    Sql(String),
    /// The configured targets mix `SQLite` and Postgres databases. One run
    /// cannot apply both safely, so nothing is written.
    MixedBackends,
    /// A flag or schema feature has no `SQLite` form. Refused, never ignored.
    UnsupportedOnSqlite {
        /// What is unsupported.
        what: &'static str,
        /// The tables or columns involved, or a short reason.
        detail: String,
    },
    /// The scrub was refused because the active profile is production and
    /// `--force` was not supplied.
    ProductionRefused {
        /// The effective profile name.
        profile: String,
    },
    /// The write target is the database a profile's **config file** declares —
    /// the artifact's own source — so the scrub would overwrite it.
    OverwritesConfiguredTarget {
        /// The profile whose config names this database.
        profile: String,
        /// The database name (never a URL).
        database: String,
    },
    /// `[framework] purge` names a table that is not framework-owned. Emptying a
    /// user table is never something a scrub does implicitly.
    PurgeNotFrameworkTable {
        /// The offending table names, sorted.
        tables: Vec<String>,
    },
    /// `[framework] purge` names one of the two ledger tables without the other.
    /// A mark outlives the revisions it names by design, so emptying either
    /// alone leaves `ledger_verify` accusing every ledgered record (issue #2323).
    PurgeLedgerTablesUnpaired {
        /// The ledger table that was named.
        listed: String,
        /// The ledger table that must be named alongside it.
        missing: String,
    },
    /// A backup/restore step (artifact restore, `--output` re-dump) failed.
    Backup(Box<super::backup::BackupError>),
    /// The `--sample` subset could not be resolved or verified (issue #1636).
    Sample(Box<sample::SampleError>),
}

impl std::fmt::Display for ScrubError {
    // One arm per variant, each a single multi-line, actionable message; splitting
    // the match would scatter the error copy across helpers for no reader benefit.
    #[allow(clippy::too_many_lines)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unclassified { columns } => write!(
                f,
                "{} column(s) are neither PII-classified nor declared safe, so the scrub \
                 cannot prove they carry no real data:\n{}\n  \
                 Declare each one in {SCRUB_CONFIG_FILE} — under [tables.<table>.pii] to \
                 replace it, or in `safe` to keep it verbatim.",
                columns.len(),
                bullet_list(columns),
            ),
            Self::StaleConfig { entries } => write!(
                f,
                "{SCRUB_CONFIG_FILE} names {} table(s)/column(s) the database does not have:\n{}\n  \
                 The declaration has drifted from the schema — remove or rename the stale \
                 entries (a renamed column must be re-declared under its new name).",
                entries.len(),
                bullet_list(entries),
            ),
            Self::Contradiction { columns } => write!(
                f,
                "{} column(s) are declared both `safe` and PII in {SCRUB_CONFIG_FILE}:\n{}\n  \
                 Pick one.",
                columns.len(),
                bullet_list(columns),
            ),
            Self::SafeOverridesEncrypted { columns } => write!(
                f,
                "{} column(s) carry #[encrypted] in the model but are declared `safe` in \
                 {SCRUB_CONFIG_FILE}:\n{}\n  \
                 An at-rest-encrypted column is PII by construction and cannot be declared \
                 safe. Remove the `safe` entry (or drop #[encrypted] from the model if the \
                 column really is not sensitive).",
                columns.len(),
                bullet_list(columns),
            ),
            Self::PiiOnKeyColumn { columns } => write!(
                f,
                "{} column(s) are primary, foreign or partition keys but declared PII:\n{}\n  \
                 Rewriting a key column would break referential integrity or move rows \
                 between partitions. Declare these columns `safe`; an `#[encrypted]` one \
                 then keeps its ciphertext. For a foreign key, scrub the referenced \
                 table's own PII columns.",
                columns.len(),
                bullet_list(columns),
            ),
            Self::NoAutoStrategy { column, detail } => write!(
                f,
                "No replacement can be derived for {column:?} from its type ({detail}).\n  \
                 Declare an explicit strategy for it under [tables.<table>.pii] in \
                 {SCRUB_CONFIG_FILE} (for example `= \"redact\"`), or declare the column \
                 `safe`."
            ),
            Self::NullOnNotNull { column } => write!(
                f,
                "{column:?} is NOT NULL, so the `null` strategy would violate the column \
                 constraint.\n  Use `redact` (or another value-producing strategy) instead."
            ),
            Self::NonUniqueStrategy { column, strategy } => write!(
                f,
                "{column:?} is UNIQUE, but the `{strategy}` strategy writes the same value \
                 into every row and would violate the unique constraint.\n  \
                 Use a per-row-unique strategy (`redact`, `email`, `name`, `uuid`, `bytes`)."
            ),
            Self::StrategyTypeMismatch {
                column,
                strategy,
                detail,
            } => write!(
                f,
                "The `{strategy}` strategy cannot produce a value for {column:?} ({detail}).\n  \
                 Pick a strategy that matches the column type."
            ),
            Self::ColumnTooNarrow {
                column,
                limit,
                overhead,
                floor,
            } => write!(
                f,
                "{column:?} holds at most {limit} characters, but the chosen strategy needs \
                 {overhead} for its fixed text plus at least {floor} more for a per-row token.\n  \
                 Strategies by fixed overhead: `phone` (5), `name` (9), `redact` (11), \
                 `email` (25). Pick one that fits, use `null` if the column is nullable, \
                 widen the column, or declare it `safe`."
            ),
            Self::EncryptedEnvelopeTooLong {
                column,
                limit,
                needed,
            } => write!(
                f,
                "{column:?} holds at most {limit} characters, but the encrypted replacement \
                 takes {needed}.\n  \
                 Widen the column, or declare it `safe` to keep its ciphertext."
            ),
            Self::PlaintextIntoEncrypted { columns } => write!(
                f,
                "{} column(s) carry #[encrypted] in the model but {SCRUB_CONFIG_FILE} declares a \
                 plaintext strategy for them:\n{}\n  \
                 Writing a plain string into an at-rest-encrypted column makes every later read \
                 of that row fail as malformed ciphertext. An #[encrypted] column is \
                 re-encrypted automatically — remove the declaration, or use `null` if the \
                 column is nullable.",
                columns.len(),
                bullet_list(columns),
            ),
            Self::CheckConstrainedColumn { column } => write!(
                f,
                "{column:?} is covered by a CHECK constraint, so no fabricated value can be \
                 proven to satisfy it (a closed-set column reaches the database as TEXT plus a \
                 CHECK, which is why the type alone does not reveal this).\n  \
                 Declare the column `safe` if the constraint means it holds no free-form PII, \
                 or drop the constraint on the copy before scrubbing."
            ),
            Self::IndexOperandColumn { column, kind } => write!(
                f,
                "{column:?} is an operand of {kind}. No per-row value can be shown to keep \
                 that constraint true: a value that is unique alone can still collide \
                 after the expression or predicate.\n  \
                 Declare the column `safe` if it holds no free-form PII, or drop the \
                 constraint on the copy before scrubbing."
            ),
            Self::SchemaChanged { entries } => write!(
                f,
                "The schema changed while the scrub ran:\n{}\n  \
                 The plan used an earlier snapshot and may not cover every column. \
                 Nothing was written. Run the command again.",
                bullet_list(entries),
            ),
            Self::EncryptionKeyUnavailable { profile, detail } => write!(
                f,
                "This database has #[encrypted] columns, but no encryption key could be resolved \
                 for the {profile:?} profile: {detail}\n  \
                 A scrub must write a VALID ciphertext envelope into an encrypted column — a \
                 plaintext replacement would make every later read of that row fail. Provide the \
                 target's `active_record_encryption` credentials (`autumn credentials edit`), or \
                 declare those columns `null` in {SCRUB_CONFIG_FILE} if they are nullable."
            ),
            Self::EncryptedMetadataUnavailable => write!(
                f,
                "No `src/` tree was found, so the scrub cannot tell which columns are \
                 #[encrypted].\n  \
                 This matters: an unrecognised encrypted column declared \
                 `safe` keeps its production ciphertext, and one given a plaintext strategy \
                 becomes permanently unreadable. Run the scrub from the project root (where \
                 `src/` lives), or name them — with their mode — in {SCRUB_CONFIG_FILE}:\n    \
                 [tables.users.encrypted]\n    api_token = \"randomized\"\n    \
                 email = \"deterministic\"\n  \
                 An app with no encrypted columns at all still needs one empty \
                 `[tables.<any>.encrypted]` section to say so deliberately."
            ),
            Self::InaccessibleTables { tables } => write!(
                f,
                "{} table(s) exist in `public` but could not be read by the connecting \
                 role:\n{}\n  \
                 They never reached the classifier, so the scrub cannot claim they carry no \
                 PII — and it will not rewrite them either. Connect as a role that can see \
                 every table (the owner, or one with the needed privileges).",
                tables.len(),
                bullet_list(tables),
            ),
            Self::UnsupportedSchemas { schemas } => write!(
                f,
                "This database has base tables in {} schema(s) outside `public`:\n{}\n  \
                 The classification universe is `public`-only, so a scrub cannot prove those \
                 tables carry no PII and refuses rather than reporting a completeness it did \
                 not check. Scrub those schemas separately, or drop them from the copy.",
                schemas.len(),
                bullet_list(schemas),
            ),
            Self::LegacyInheritance { tables } => write!(
                f,
                "This database uses legacy table inheritance on {} table(s):\n{}\n  \
                 Unlike a declarative partition, an inheritance child is an ordinary table \
                 that the sample plans separately — while `DELETE FROM parent` and \
                 `SELECT ... FROM parent` reach its rows too, because they are not written \
                 `ONLY parent`. Parent and child would then select rows independently and \
                 delete each other's, and the run would report a success it cannot stand \
                 behind. Sample a copy without the inheritance, or drop the child tables \
                 from it.",
                tables.len(),
                bullet_list(tables),
            ),
            Self::UnprintableTarget { targets } => write!(
                f,
                "`--dry-run` cannot print a runnable script for {} target(s):\n{}\n  \
                 Each block it prints is destructive, and the `\\connect` line above it \
                 is what points psql at the right database. These targets are configured \
                 with a keyword-form connection string (`host=... password=...`), which \
                 cannot be printed with its password removed for certain — libpq allows \
                 whitespace around the `=` and quoted values with escapes — or with a \
                 connection-string parameter this command does not recognise, which it \
                 refuses to print rather than guess about (`password_free_conninfo` \
                 allowlists known-non-secret keywords and strips known credentials; \
                 anything else fails closed). A script without the boundary does not fail: \
                 it runs this target's plan against whichever database the pasting session \
                 is already on, which in a multi-target stream is the previous target. \
                 Configure the target as a URI (`postgres://user@host/db`), or run without \
                 `--dry-run`.",
                targets.len(),
                bullet_list(targets),
            ),
            Self::UntraceableViewFunction { views } => write!(
                f,
                "{} materialized view(s) read through a function this run cannot \
                 follow:\n{}\n  \
                 Refresh order is taken from the dependency graph `PostgreSQL` records, \
                 and it records nothing about what a function whose body it cannot \
                 parse reads — a string literal, `plpgsql`, or C. Measured on `a_report -> bridge_fn() -> z_source`: \
                 `pg_depend` holds `a_report -> pg_proc(bridge_fn)` and the function \
                 holds NO relation dependency at all, so the two views sorted by name, \
                 `a_report` refreshed FIRST from a `z_source` still holding pre-scrub \
                 rows, and the run reported success with `users` at 2 rows, 0 original \
                 addresses in the base tables and in `z_source`, and all 200 still in \
                 `a_report`. A `BEGIN ATOMIC` body IS tracked and is followed normally. \
                 Rewrite the function with `BEGIN ATOMIC`, inline its query into the \
                 view, or drop the view and rebuild it after the run.",
                views.len(),
                bullet_list(views),
            ),
            Self::ViewReadsRelationsByName { views } => write!(
                f,
                "{} materialized view(s) read relations named in a string the server \
                 executes:\n{}\n  \
                 `query_to_xml` takes its query as text, and `schema_to_xml` and \
                 `database_to_xml` take no relation argument at all, so PostgreSQL \
                 records no dependency on anything they read — measured, a view \
                 defined `SELECT query_to_xml('SELECT email FROM z_source', …)` records \
                 only itself. Refresh order comes from those dependencies, so the views \
                 sorted by name instead: measured, the dependent refreshed FIRST from a \
                 stale source and kept all 200 pre-scrub addresses under a reported \
                 success. Nothing in the catalog can recover the edge, so it is refused \
                 rather than ordered around a gap. `table_to_xml` is fine and not \
                 refused: its `regclass` argument IS recorded. Name the relation in the \
                 view's own query, or take the view out of the database this run \
                 scrubs.",
                views.len(),
                bullet_list(views),
            ),
            Self::UnprintableMultiHostTarget { targets } => write!(
                f,
                "`--dry-run` cannot print a runnable script for {} target(s):\n{}\n  \
                 Their connection strings name more than one endpoint, and libpq chooses \
                 a member per connection — measured on 16.13, 20 connections with \
                 `load_balance_hosts=random` split 7/13 across two members. The run sizes \
                 the sample on one connection and the pasted script runs on another, so \
                 the root `LIMIT` need not describe the database it lands on: measured \
                 against a two-member URI whose first member held 200 rows and whose \
                 second held none, ten dry runs printed `LIMIT 2` six times and `LIMIT 0` \
                 four times, and `LIMIT 0` selects no root rows at all, so the delete pass \
                 empties the table instead of sampling it. The endpoint proof cannot \
                 separate the members either — it has to accept any of them, which is the \
                 discriminator it exists for. Name one endpoint \
                 (`postgres://user@host:5432/db`), or run without `--dry-run`, where the \
                 command sizes and writes on the one connection it holds.",
                targets.len(),
                bullet_list(targets),
            ),
            Self::UnprintableHostaddrTarget { targets } => write!(
                f,
                "`--dry-run` cannot print a runnable script for {} target(s):\n{}\n  \
                 Something other than `host` and `port` chooses their endpoint — \
                 `hostaddr` in the connection string, `PGHOSTADDR` in the environment, \
                 or a service file named by `service=` or `PGSERVICE`. All three were \
                 measured reaching 127.0.0.1 through `host=not-a-real-host.example`, a \
                 name that does not resolve at all, with psql still reporting \
                 `HOST=not-a-real-host.example`. psql exposes no `:HOSTADDR` to pin \
                 instead: `\\echo [:HOSTADDR]` prints the name back unexpanded. So two \
                 targets sharing a host, port and database name but reaching different \
                 servers are indistinguishable to the reconnect proof, which is the one \
                 thing it exists to tell apart — and a pasting session brings its own \
                 environment, so what this run resolved need not be what it resolves. \
                 Name the endpoint in `host` (`postgres://user@10.0.0.7:5432/db`) with \
                 no `hostaddr`, `service`, `PGHOSTADDR` or `PGSERVICE` in play, or run \
                 without `--dry-run`, where the command holds its own connection and \
                 never has to prove which one it is.",
                targets.len(),
                bullet_list(targets),
            ),
            Self::UnprintablePortlessTarget { targets } => write!(
                f,
                "`--dry-run` cannot print a runnable script for {} target(s):\n{}\n  \
                 Their connection strings name a host but no port, so psql resolves one \
                 when the script is pasted — from `PGPORT`, or 5432 — and that need not \
                 be what libpq resolved while this run planned. The block's proof that \
                 `\\connect` reached the intended endpoint would then have to accept ANY \
                 port for that host, which is the discriminator it exists for: measured, \
                 the same URI resolves to 5433 under `PGPORT=5433` and to 5432 without \
                 it, two different servers. Embedding the port this run resolved is not \
                 an option either — libpq's own resolution can come from a service file \
                 this command does not read. State the port in the connection string \
                 (`postgres://user@host:5432/db`), or run without `--dry-run`, where the \
                 command holds its own connection and never has to prove which one it \
                 is.",
                targets.len(),
                bullet_list(targets),
            ),
            Self::UnprintableEncryptedRewrite { columns } => write!(
                f,
                "`--dry-run` cannot print a runnable script: {} column(s) are \
                 #[encrypted]:\n{}\n  \
                 The scrub replaces each of these with an AEAD envelope sealed per row \
                 under the target's key, so there is no SQL text for it that does not \
                 embed the key. Printing the rest and omitting these is worse than \
                 printing nothing: the script is meant to be pasted into psql, and \
                 nothing in a pasted stream can stop it partway — an aborted \
                 transaction ends at the next `COMMIT`, after which the following \
                 target's `\\connect` and its DELETEs run for real. So the whole \
                 script is withheld, not just the statements that cannot be written. \
                 The plan above is complete and accurate — run `autumn db scrub` \
                 without --dry-run to apply it.",
                columns.len(),
                bullet_list(columns),
            ),
            Self::UnprintableProductionTarget { profile } => write!(
                f,
                "`--dry-run` cannot print a runnable script for the {profile:?} profile.\n  \
                 A scrub REWRITES data in place, and this command refuses to run against \
                 {profile:?} without `--force`. The script it prints is executable and its \
                 `\\connect` line names that same database — with the password removed on \
                 purpose, which is what `.pgpass` is for — so printing it would hand over \
                 the run the profile guard exists to stop. The plan above is complete and \
                 accurate; add `--force` to print the script too, or point `--profile` at a \
                 staging target.",
            ),
            Self::UnrefreshableViews { views } => write!(
                f,
                "{} materialized view(s) cannot be refreshed in dependency order:\n{}\n  \
                 The run refreshes views so each is rebuilt from scrubbed data, and it \
                 orders them by walking `pg_depend`. That walk stops at a fixed depth, so \
                 a chain longer than it leaves these views unreached — and a view that is \
                 not refreshed keeps the rows it selected BEFORE the scrub, including the \
                 values the run just removed from the tables it reads. Measured on a \
                 36-deep chain: 33 views refreshed, `users` left with 0 original \
                 addresses, and the deepest view still holding all 200. Refusing is the \
                 only honest answer until the walk covers the whole graph — shorten the \
                 chain, or drop the views this run cannot reach and rebuild them after \
                 it.",
                views.len(),
                bullet_list(views),
            ),
            Self::UnprintableAmbiguousTarget { targets } => write!(
                f,
                "`--dry-run` cannot print a runnable script for {} target(s):\n{}\n  \
                 These are reached over a Unix socket, where the server reports no \
                 address and no port — and nothing else it reports identifies the \
                 instance either. A physical copy carries its origin's \
                 `system_identifier`; the configured port is shared by two clusters on \
                 different socket directories; and `data_directory` is server-LOCAL, so \
                 two containers each answering `/var/lib/postgresql/data` match on it \
                 while being different databases. Every value the guard can ask for is \
                 either cloned or container-local, so a printed block cannot tell this \
                 target from a copy of it — and `\\connect` keeps the PREVIOUS connection \
                 when it fails. Measured on two clusters sharing port 5433: the clone's \
                 script pasted at its origin passed the guard, committed, and took the \
                 ORIGIN from 200 users to 25. Connect over TCP, where the address and \
                 port identify the endpoint and two clones cannot hold the same pair, or \
                 run without --dry-run — the command opens its own connection and cannot \
                 be on the wrong database.",
                targets.len(),
                bullet_list(targets),
            ),
            Self::ReplicaSessionRole { role } => write!(
                f,
                "This connection runs with `session_replication_role = {role}`, not `origin`.\n  \
                 That inverts which hooks fire: a trigger or rule marked `ENABLE REPLICA` runs \
                 and an ordinary one does not, so every check here that asks whether a `DELETE` \
                 can execute code is answering for the wrong session. A replica-only archive \
                 trigger on a table this run empties would copy the rows it removes into a \
                 table nothing verifies, past a refusal that never saw it. Connect without \
                 `options=-c session_replication_role=...`, or reset it before scrubbing.",
            ),
            Self::EmptyingTriggerLeak { tables } => write!(
                f,
                "{} table(s) this run empties carry a user-defined trigger or rewrite rule \
                 that fires on `DELETE`:\n{}\n  \
                 Emptying them is the LAST thing the run writes \u{2014} it has to be, because a \
                 trigger on a scrubbed table can otherwise re-fill them with the very PII \
                 being removed. Anything attached to a `DELETE` on one of them therefore runs \
                 after every column rewrite, and can copy the rows it is removing into an \
                 ordinary table that has already been scrubbed. Nothing downstream can catch \
                 that: the run verifies these tables are empty, not where their triggers and \
                 rules wrote. On the copy, `ALTER TABLE ... DISABLE TRIGGER ...` or \
                 `DROP RULE ... ON ...` before scrubbing.",
                tables.len(),
                bullet_list(tables),
            ),
            Self::RowLevelSecurity { tables } => write!(
                f,
                "{} table(s) this run reads or writes have row-level security that binds the \
                 connected role:\n{}\n  \
                 A role that does not bypass RLS sees only the rows its policies expose, and \
                 every phase then reports a success it cannot stand behind: an `UPDATE` \
                 rewrites part of the PII, a `DELETE` reports a table emptied that is not, and \
                 the foreign key re-count misses the very orphan it exists to find. \
                 Connect as a superuser, a BYPASSRLS role, or the table owner (the owner is \
                 still bound when the table is FORCE ROW LEVEL SECURITY).",
                tables.len(),
                bullet_list(tables),
            ),
            Self::FrameworkTableDeclared { tables } => write!(
                f,
                "{SCRUB_CONFIG_FILE} declares {} framework-owned table(s) under [tables.*]:\n{}\n  \
                 Framework-owned tables are deliberately outside the column classification \
                 (exactly as `autumn db pull` and `autumn schema pull` skip them), so a \
                 per-column declaration for them has no effect. Use \
                 `[framework] purge = [...]` to empty one instead.",
                tables.len(),
                bullet_list(tables),
            ),
            Self::PurgeSchemaBookkeeping { tables } => write!(
                f,
                "[framework] purge in {SCRUB_CONFIG_FILE} names {} table(s) that hold schema \
                 bookkeeping, not app payloads:\n{}\n  \
                 Emptying them would make the copy un-migratable or un-routable. Remove them \
                 from `purge`.",
                tables.len(),
                bullet_list(tables),
            ),
            Self::Config { path, detail } => write!(f, "Cannot read {path}: {detail}"),
            Self::SourceScan { detail } => write!(
                f,
                "Could not scan the app source for PII annotations: {detail}"
            ),
            Self::UnresolvableAnonymize { detail } => write!(
                f,
                "A GDPR anonymize registration names a table this scanner cannot resolve: \
                 {detail}\n  `autumn db scrub` reads `ModelRegistration::anonymize(\"...\")` \
                 with a string-literal table name. Use a literal there, or declare the \
                 table's columns explicitly in {SCRUB_CONFIG_FILE}."
            ),
            Self::Introspect { label, detail } => {
                write!(f, "Could not read the schema of {label}: {detail}")
            }
            Self::Sql(message) => write!(f, "{message}"),
            Self::MixedBackends => write!(
                f,
                "The configured databases mix SQLite and Postgres targets.\n  \
                 One scrub run cannot apply both safely. Nothing was written. Scrub them \
                 in separate runs, one backend each."
            ),
            Self::UnsupportedOnSqlite { what, detail } => write!(
                f,
                "{what} is not supported for SQLite targets: {detail}\n  \
                 Nothing was written."
            ),
            Self::ProductionRefused { profile } => write!(
                f,
                "Refusing to scrub the {profile:?} profile database.\n  \
                 A scrub REWRITES data in place — running it against production would \
                 destroy the real values. Point --profile at your staging/dev target, or \
                 re-run with --force if you really mean it."
            ),
            Self::OverwritesConfiguredTarget { profile, database } => write!(
                f,
                "Refusing to scrub {database:?}: it is the database the {profile:?} profile's \
                 config file declares.\n  \
                 The scrub would overwrite the source the artifact was taken from. Point the \
                 target at a separate staging database, or re-run with \
                 --allow-source-overwrite if that really is what you mean."
            ),
            Self::PurgeNotFrameworkTable { tables } => write!(
                f,
                "[framework] purge in {SCRUB_CONFIG_FILE} names {} table(s) that are not \
                 framework-owned:\n{}\n  \
                 `purge` empties a table outright and only accepts framework-owned names \
                 (`autumn_*` / `_autumn*`, plus the framework's unprefixed tables). Declare \
                 a user table's columns under [tables.<table>.pii] instead.",
                tables.len(),
                bullet_list(tables),
            ),
            Self::PurgeLedgerTablesUnpaired { listed, missing } => write!(
                f,
                "[framework] purge in {SCRUB_CONFIG_FILE} names {listed:?} but not \
                 {missing:?}.\n  \
                 The ledger's two tables are emptied together or not at all: a high-water \
                 mark is built to outlive the revisions it names, so a copy holding one \
                 without the other makes `ledger_verify` report every ledgered record as \
                 tampered — and, with the marks kept, makes the write path refuse every \
                 subsequent write. Add {missing:?} to `purge`, or remove {listed:?}."
            ),
            Self::Backup(e) => write!(f, "{e}"),
            Self::Sample(e) => write!(f, "{e}"),
        }
    }
}

impl From<sample::SampleError> for ScrubError {
    fn from(e: sample::SampleError) -> Self {
        Self::Sample(Box::new(e))
    }
}

impl From<super::backup::BackupError> for ScrubError {
    fn from(e: super::backup::BackupError) -> Self {
        Self::Backup(Box::new(e))
    }
}

/// Render a sorted list as indented bullets for a multi-line error message.
fn bullet_list(items: &[String]) -> String {
    items
        .iter()
        .map(|item| format!("    - {item}"))
        .collect::<Vec<_>>()
        .join("\n")
}

// ─── Declaration file ───────────────────────────────────────────────────────

/// How a PII column's value is replaced.
///
/// Every strategy derives from an `md5` token over the row's primary key salted
/// with the column name, so two columns of one row never receive the same fake
/// value and a `UNIQUE` column keeps its uniqueness. For a table with a primary
/// key the result is also **stable across runs** (the same row always scrubs to
/// the same value); a table with no primary key falls back to the physical
/// `ctid`, which is unique within the statement but not stable between runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Strategy {
    /// Derive the strategy from the column's type (the default for
    /// automatically-classified columns).
    Auto,
    /// A syntactically valid, permanently undeliverable address.
    Email,
    /// A human-shaped placeholder name.
    Name,
    /// A `+1555`-prefixed placeholder number.
    Phone,
    /// An obviously-fake bracketed marker.
    Redact,
    /// `NULL` (refused on a `NOT NULL` column).
    Null,
    /// A deterministic replacement UUID.
    Uuid,
    /// Deterministic replacement bytes.
    Bytes,
    /// A constant `{"scrubbed": true}` document.
    Json,
    /// Numeric zero / boolean false.
    Zero,
    /// The Unix epoch.
    Epoch,
    /// Re-encrypt: replace an `#[encrypted]` column with a valid AEAD envelope
    /// of a fake plaintext, produced under the target database's own key.
    ///
    /// This is the only strategy that cannot be expressed as SQL — writing a
    /// plain string into an `#[encrypted]` column would make every subsequent
    /// repository read of that row fail as malformed ciphertext, so the
    /// replacement is built in Rust and shipped back per row.
    Encrypted,
}

impl Strategy {
    /// The name as written in `scrub.toml`.
    const fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Email => "email",
            Self::Name => "name",
            Self::Phone => "phone",
            Self::Redact => "redact",
            Self::Null => "null",
            Self::Uuid => "uuid",
            Self::Bytes => "bytes",
            Self::Json => "json",
            Self::Zero => "zero",
            Self::Epoch => "epoch",
            Self::Encrypted => "encrypted",
        }
    }

    /// Whether this strategy may be used on a `UNIQUE` column.
    ///
    /// `Null` qualifies despite writing one value: Postgres permits any number
    /// of `NULL`s in a unique index. `Phone` does not — its digits are a lossy
    /// projection of the token, so collisions are possible.
    const fn allowed_on_unique(self) -> bool {
        matches!(
            self,
            Self::Email
                | Self::Name
                | Self::Redact
                | Self::Null
                | Self::Uuid
                | Self::Bytes
                | Self::Encrypted
        )
    }
}

/// Declarations that apply to every table.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScrubDefaults {
    /// Column names that are safe in **any** table — the one-line escape from
    /// declaring `id` / `created_at` / `updated_at` in every stanza.
    #[serde(default)]
    pub safe_columns: Vec<String>,
}

/// The at-rest encryption mode a column was written with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EncryptionMode {
    /// `#[encrypted]` — a fresh nonce per write.
    Randomized,
    /// `#[encrypted(deterministic)]` — equality-queryable.
    Deterministic,
}

impl EncryptionMode {
    /// Whether this is the deterministic mode.
    const fn is_deterministic(self) -> bool {
        matches!(self, Self::Deterministic)
    }
}

/// One table's declaration.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TableRule {
    /// Columns reviewed and deliberately kept verbatim.
    #[serde(default)]
    pub safe: Vec<String>,
    /// PII columns and how each is replaced.
    #[serde(default)]
    pub pii: BTreeMap<String, Strategy>,
    /// At-rest-encrypted columns and their mode, for a host that has the CLI and
    /// `scrub.toml` but not the model source the `#[encrypted]` markers live in.
    ///
    /// The mode matters: re-encrypting a `deterministic` column in randomized
    /// mode leaves valid ciphertext that the app can no longer equality-query,
    /// so it cannot be guessed.
    #[serde(default)]
    pub encrypted: BTreeMap<String, EncryptionMode>,
}

/// How framework-owned tables are handled.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FrameworkRule {
    /// Framework-owned tables to empty during the scrub. Opt-in: by default the
    /// scrub only *warns* about the ones that carry app-supplied payloads.
    #[serde(default)]
    pub purge: Vec<String>,
}

/// The parsed `scrub.toml`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScrubConfig {
    /// Cross-table declarations.
    #[serde(default)]
    pub defaults: ScrubDefaults,
    /// Per-table declarations, keyed by table name.
    #[serde(default)]
    pub tables: BTreeMap<String, TableRule>,
    /// Framework-owned table handling.
    #[serde(default)]
    pub framework: FrameworkRule,
    /// Per-table subsetting rules for `--sample` (issue #1636).
    #[serde(default)]
    pub sample: sample::SampleRules,
}

/// Framework-owned tables whose rows carry **app-supplied** payloads, and can
/// therefore hold PII the column-level classification never sees: introspection
/// deliberately skips `autumn_*` / `_autumn*` tables (mirroring `autumn db pull`
/// and `autumn schema pull`), so their columns are not part of the classified
/// universe at all.
///
/// A scrub warns when one of these is present, and empties it when the app opts
/// in with `[framework] purge = [...]`. Every entry here is transient
/// operational state that a staging copy has no reason to inherit — a queued job
/// payload, an offline-sync row buffer, an experiment assignment — never
/// schema-bearing bookkeeping like `autumn_migration_checksums`.
const FRAMEWORK_PAYLOAD_TABLES: &[&str] = &[
    // A full verbatim copy of every mutated row, including `#[private]` and
    // `#[encrypted]` columns — so an unscrubbed ledger hands back exactly the
    // plaintext the column-level scrub just removed.
    "_autumn_ledger_revisions",
    // Listed for lock-step emptying rather than because it carries a payload:
    // the #2323 high-water marks hold only table names, tenant keys, sequence
    // numbers and hashes. But a mark outlives the chain it names, so a copy that
    // purged the revisions and kept the marks would have `ledger_verify` report
    // *every* ledgered record as `MissingRevision` — "the whole chain was
    // erased" — and the write path would then refuse every subsequent write.
    // `check_purge_list` refuses to empty one of the pair without the other.
    "_autumn_ledger_high_water",
    // Before/after values for every tracked column; only those named in
    // `#[version_history(sensitive = [...])]` are redacted.
    "_autumn_version_history",
    // Hashed API tokens minted in production. A staging copy that inherits them
    // is a live credential leak, not merely a PII one.
    "api_tokens",
    "autumn_experiment_assignments",
    // `actor` on both: who was pinned to a variant, and who changed what.
    "autumn_experiment_changes",
    "autumn_experiment_overrides",
    // `actor_allowlist` names the individual users a flag is switched on for.
    "autumn_feature_flags",
    "autumn_job_tracking",
    "autumn_jobs",
    // `context` / `record` JSONB hold the full row a hook was queued for.
    "autumn_repository_commit_hooks",
    // `raw_value` is the live operator-set override for each key — it can
    // hold a secret. `autumn_runtime_config_changes` is the append-only audit
    // log: `old_value` / `new_value` / `actor` for every set/unset (#2366).
    "autumn_runtime_config_changes",
    "autumn_runtime_config_values",
    // The indexed text of app records — the search index is a second copy of
    // whatever was made searchable.
    "autumn_search_documents",
    "autumn_sync_applied",
    "autumn_sync_pending",
    "autumn_sync_rows",
    // `actor` records who made each flag change.
    "feature_flag_changes",
];

/// Framework-owned tables whose names do not carry the `autumn_` / `_autumn`
/// prefix. Kept in lock-step with `crate::schema::introspect`'s
/// `is_framework_table`, which is what decides they are excluded from the
/// classified universe in the first place.
const UNPREFIXED_FRAMEWORK_TABLES: &[&str] = &[
    "api_tokens",
    "feature_flag_changes",
    "__diesel_schema_migrations",
];

/// Whether a table name is framework-owned — i.e. one introspection filters out
/// of the classified universe, so the column-level classification never sees it.
fn is_framework_table(table: &str) -> bool {
    table.starts_with("autumn_")
        || table.starts_with("_autumn")
        || UNPREFIXED_FRAMEWORK_TABLES.contains(&table)
}

/// Framework-owned tables `[framework] purge` must never accept: emptying them
/// does not remove a payload, it breaks the copy. `__diesel_schema_migrations`
/// and `autumn_migration_checksums` are the migration ledger (an empty one
/// replays every migration against a populated database); `_autumn_shard_map` /
/// `_autumn_shard_directory` are the routing tables a sharded app reads at boot.
const NEVER_PURGEABLE_TABLES: &[&str] = &[
    "__diesel_schema_migrations",
    "_autumn_shard_directory",
    "_autumn_shard_map",
    "autumn_migration_checksums",
];

/// Validate a `[framework] purge` list: it may only name framework-owned
/// tables, and never schema bookkeeping. A user table listed there would be
/// silently emptied, which is never what a scrub should do behind a one-word
/// config key.
fn check_purge_list(config: &ScrubConfig) -> Result<(), ScrubError> {
    let mut bookkeeping: Vec<String> = config
        .framework
        .purge
        .iter()
        .filter(|t| NEVER_PURGEABLE_TABLES.contains(&t.as_str()))
        .cloned()
        .collect();
    if !bookkeeping.is_empty() {
        bookkeeping.sort();
        return Err(ScrubError::PurgeSchemaBookkeeping {
            tables: bookkeeping,
        });
    }
    let mut offenders: Vec<String> = config
        .framework
        .purge
        .iter()
        .filter(|t| !is_framework_table(t))
        .cloned()
        .collect();
    if !offenders.is_empty() {
        offenders.sort();
        return Err(ScrubError::PurgeNotFrameworkTable { tables: offenders });
    }
    check_ledger_purge_pairing(config)
}

/// The two ledger tables are emptied together or not at all (issue #2323).
///
/// A high-water mark is deliberately built to outlive the revisions it names —
/// that is what makes a deleted revision permanent evidence. So a staging copy
/// that purged `_autumn_ledger_revisions` and kept `_autumn_ledger_high_water`
/// would have `ledger_verify` report every ledgered record as a wholly erased
/// chain, and the write path would refuse every subsequent write to them. The
/// reverse — marks purged, revisions kept — is the same shape from the other
/// side: every record reports `HighWaterMissing`.
///
/// Neither is a state an operator asking for a scrub meant to create, and both
/// are silent until something reads the ledger, so the pairing is enforced here
/// rather than left as documentation.
fn check_ledger_purge_pairing(config: &ScrubConfig) -> Result<(), ScrubError> {
    let has = |table: &str| config.framework.purge.iter().any(|t| t == table);
    let (revisions, marks) = (has(LEDGER_REVISIONS_TABLE), has(LEDGER_HIGH_WATER_TABLE));
    if revisions == marks {
        return Ok(());
    }
    let (listed, missing) = if revisions {
        (LEDGER_REVISIONS_TABLE, LEDGER_HIGH_WATER_TABLE)
    } else {
        (LEDGER_HIGH_WATER_TABLE, LEDGER_REVISIONS_TABLE)
    };
    Err(ScrubError::PurgeLedgerTablesUnpaired {
        listed: listed.to_owned(),
        missing: missing.to_owned(),
    })
}

/// The ledger's revision rows.
const LEDGER_REVISIONS_TABLE: &str = "_autumn_ledger_revisions";
/// The ledger's out-of-band high-water marks (issue #2323).
const LEDGER_HIGH_WATER_TABLE: &str = "_autumn_ledger_high_water";

/// Parse a `scrub.toml` document.
///
/// # Errors
///
/// Returns [`ScrubError::Config`] when the document is not valid TOML, names an
/// unknown key, or names an unknown strategy.
#[cfg(test)]
fn parse_config_str(src: &str) -> Result<ScrubConfig, ScrubError> {
    parse_config_at(src, Path::new(SCRUB_CONFIG_FILE))
}

/// Parse a `scrub.toml` document, attributing any error to the file it came
/// from.
fn parse_config_at(src: &str, path: &Path) -> Result<ScrubConfig, ScrubError> {
    toml::from_str(src).map_err(|e| ScrubError::Config {
        path: path.display().to_string(),
        detail: e.to_string(),
    })
}

/// Load the declaration file, defaulting to an empty declaration when the
/// conventional path is simply absent (every column is then unclassified, which
/// is the fail-closed outcome the developer is told how to fix).
fn load_config(explicit: Option<&Path>) -> Result<ScrubConfig, ScrubError> {
    load_config_at(explicit, Path::new(SCRUB_CONFIG_FILE))
}

/// [`load_config`] against an explicit conventional path, so the "a missing
/// default is fine, a missing explicit path is not" rule is testable without
/// mutating the process working directory.
fn load_config_at(explicit: Option<&Path>, default: &Path) -> Result<ScrubConfig, ScrubError> {
    let path = explicit.map_or_else(|| default.to_path_buf(), Path::to_path_buf);
    match std::fs::read_to_string(&path) {
        Ok(src) => parse_config_at(&src, &path),
        // An explicitly-named file that is missing is an error; the conventional
        // default simply may not exist yet.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound && explicit.is_none() => {
            Ok(ScrubConfig::default())
        }
        Err(e) => Err(ScrubError::Config {
            path: path.display().to_string(),
            detail: e.to_string(),
        }),
    }
}

// ─── Classification ─────────────────────────────────────────────────────────

/// Where a column's classification came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClassSource {
    /// An explicit `[tables.<t>.pii]` entry.
    Config,
    /// An `#[encrypted]` model column.
    Encrypted,
    /// A table registered with the GDPR anonymize strategy.
    GdprAnonymize,
}

impl ClassSource {
    /// A short label for the scrub report.
    const fn as_str(self) -> &'static str {
        match self {
            Self::Config => "declared",
            Self::Encrypted => "#[encrypted]",
            Self::GdprAnonymize => "gdpr:anonymize",
        }
    }
}

/// Everything the classifier reads. Grouped into one struct so the pure
/// classification step stays testable without a database.
pub struct ClassificationInputs<'a> {
    /// The live schema (framework-owned tables already excluded).
    pub tables: &'a [Table],
    /// The developer's declaration.
    pub config: &'a ScrubConfig,
    /// `#[encrypted]` columns keyed by table, each mapped to whether the model
    /// declared `#[encrypted(deterministic)]`.
    pub encrypted: &'a BTreeMap<String, BTreeMap<String, bool>>,
    /// Tables registered with the GDPR anonymize strategy.
    pub anonymize_tables: &'a BTreeSet<String>,
    /// Catalog facts the schema IR does not carry (see [`DatabaseFacts`]).
    pub facts: &'a DatabaseFacts,
}

/// One column the scrub will rewrite.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnPlan {
    /// The column name.
    pub column: String,
    /// The resolved (never [`Strategy::Auto`]) replacement strategy.
    pub strategy: Strategy,
    /// What classified it.
    pub source: ClassSource,
}

/// One `#[encrypted]` column's rewrite. Its replacement is an AEAD envelope
/// built in Rust per row, so it cannot join the table's batched `UPDATE`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptedRewrite {
    /// The column name.
    pub column: String,
    /// Whether the model declared `#[encrypted(deterministic)]`, so equality
    /// lookups against the column keep working after the scrub.
    pub deterministic: bool,
    /// The shape of the fake plaintext to encrypt ([`Strategy::Email`] for an
    /// email-named column, else [`Strategy::Redact`]).
    pub shape: Strategy,
}

/// One table's scrub statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TablePlan {
    /// The table name.
    pub table: String,
    /// The columns rewritten, in table column order.
    pub columns: Vec<ColumnPlan>,
    /// The single `UPDATE` rewriting every SQL-expressible column, or `None`
    /// when the table's only PII columns are `#[encrypted]` ones.
    pub sql: Option<String>,
    /// The SQL expression identifying a row (see [`row_key_expr`]), reused to
    /// match rows when shipping encrypted replacements back.
    pub row_key: String,
    /// Columns whose replacement must be produced in Rust.
    pub encrypted: Vec<EncryptedRewrite>,
}

/// The full set of statements a scrub will run against one database.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScrubPlan {
    /// One entry per table with at least one PII column, in table order.
    pub tables: Vec<TablePlan>,
}

impl ScrubPlan {
    /// Look up one column's decision, if the scrub rewrites it.
    #[cfg(test)]
    fn column(&self, table: &str, column: &str) -> Option<&ColumnPlan> {
        self.tables
            .iter()
            .find(|t| t.table == table)?
            .columns
            .iter()
            .find(|c| c.column == column)
    }

    /// Total number of columns the scrub rewrites.
    #[must_use]
    pub fn column_count(&self) -> usize {
        self.tables.iter().map(|t| t.columns.len()).sum()
    }
}

/// Classify every column of every table and build the statements, or refuse.
///
/// The checks run in a fixed order so one run reports the most fundamental
/// problem rather than a cascade: declaration rot first (stale, contradictory,
/// overriding `#[encrypted]`), then structural refusals (PII on a key column),
/// then the fail-closed sweep, then per-column strategy validation.
///
/// # Errors
///
/// Returns the corresponding [`ScrubError`] variant for each refusal above.
#[allow(clippy::too_many_lines)]
pub fn build_plan(inputs: &ClassificationInputs<'_>) -> Result<ScrubPlan, ScrubError> {
    let by_name: BTreeMap<&str, &Table> =
        inputs.tables.iter().map(|t| (t.name.as_str(), t)).collect();

    check_config_freshness(inputs, &by_name)?;
    check_contradictions(inputs)?;
    check_safe_overrides_encrypted(inputs, &by_name)?;

    let mut unclassified = Vec::new();
    let mut key_pii = Vec::new();
    let mut plaintext_into_encrypted: Vec<(String, &'static str)> = Vec::new();
    let mut planned: Vec<(&Table, Vec<(ColumnPlan, &Column)>)> = Vec::new();

    for table in inputs.tables {
        // A partition's rows are rewritten through its parent, so planning it
        // again would double-update them (and, on a table with no primary key,
        // re-randomize the values the parent pass just wrote).
        if inputs.facts.partitions.contains_key(&table.name) {
            continue;
        }
        let rule = inputs.config.tables.get(&table.name);
        let anonymized = inputs.anonymize_tables.contains(&table.name);
        let encrypted = inputs.encrypted.get(&table.name);
        let mut columns = Vec::new();

        for column in &table.columns {
            let qualified = format!("{}.{}", table.name, column.name);
            // A generated column is derived data Postgres refuses to `UPDATE`
            // at all — scrubbing the columns it reads already covers it — so it
            // is structurally safe rather than something to declare.
            if inputs
                .facts
                .generated_columns
                .contains(&(table.name.clone(), column.name.clone()))
            {
                continue;
            }
            let is_key = is_key_column(table, column, inputs.facts);
            let declared_pii = rule.and_then(|r| r.pii.get(&column.name)).copied();
            let is_encrypted = encrypted.is_some_and(|e| e.contains_key(&column.name));
            let declared_safe_here = rule.is_some_and(|r| r.safe.contains(&column.name));
            // A cross-table convenience list is not a per-column review, so it
            // may not narrow a table-level GDPR anonymize registration: only an
            // explicit `[tables.<t>] safe` entry can.
            let declared_safe = declared_safe_here
                || (!anonymized && inputs.config.defaults.safe_columns.contains(&column.name));

            let (spec, source) =
                if is_encrypted && is_key && declared_pii.is_none() && declared_safe_here {
                    // Never rewrite a structural column. Re-encrypting it is a
                    // write. Only a per-table `safe` entry keeps the ciphertext,
                    // not a cross-table default.
                    continue;
                } else if is_encrypted {
                    // An at-rest-encrypted column is never rewritten with a plain
                    // string: the resolved strategy is always a re-encryption (see
                    // `Strategy::Encrypted`), so a declaration can only choose to
                    // NULL it, never to write plaintext into it.
                    match declared_pii {
                        None | Some(Strategy::Encrypted) => {
                            (Strategy::Encrypted, ClassSource::Encrypted)
                        }
                        Some(Strategy::Null) => (Strategy::Null, ClassSource::Config),
                        Some(other) => {
                            plaintext_into_encrypted.push((qualified, other.as_str()));
                            continue;
                        }
                    }
                } else if let Some(strategy) = declared_pii {
                    (strategy, ClassSource::Config)
                } else if declared_safe {
                    continue;
                } else if anonymized {
                    // A table-level inference never claims the structural columns:
                    // rewriting a key would break referential integrity, and the
                    // registration says nothing about them.
                    if is_key {
                        continue;
                    }
                    (Strategy::Auto, ClassSource::GdprAnonymize)
                } else {
                    unclassified.push(qualified);
                    continue;
                };

            if is_key {
                key_pii.push(qualified);
                continue;
            }
            columns.push((
                ColumnPlan {
                    column: column.name.clone(),
                    strategy: spec,
                    source,
                },
                column,
            ));
        }
        planned.push((table, columns));
    }

    if !plaintext_into_encrypted.is_empty() {
        plaintext_into_encrypted.sort();
        return Err(ScrubError::PlaintextIntoEncrypted {
            columns: plaintext_into_encrypted
                .into_iter()
                .map(|(column, strategy)| format!("{column} (declared `{strategy}`)"))
                .collect(),
        });
    }
    if !key_pii.is_empty() {
        key_pii.sort();
        return Err(ScrubError::PiiOnKeyColumn { columns: key_pii });
    }
    if !unclassified.is_empty() {
        unclassified.sort();
        return Err(ScrubError::Unclassified {
            columns: unclassified,
        });
    }

    let mut out = ScrubPlan::default();
    for (table, columns) in planned {
        if columns.is_empty() {
            continue;
        }
        let mut resolved = Vec::with_capacity(columns.len());
        let mut assignments = Vec::with_capacity(columns.len());
        let mut encrypted_rewrites = Vec::new();
        for (mut plan, column) in columns {
            let qualified = format!("{}.{}", table.name, column.name);
            let pair = (table.name.clone(), column.name.clone());
            let unique = is_unique_column(table, column, inputs.facts);

            // A `CHECK` predicate is arbitrary SQL, so no fabricated value can be
            // proven to satisfy it — and a real Autumn closed-set column reaches
            // the database as plain `TEXT` plus a `CHECK`, so this (not the
            // model-IR-only `ColumnType::Enum`) is what actually catches it.
            if inputs.facts.checked_columns.contains(&pair) {
                return Err(ScrubError::CheckConstrainedColumn { column: qualified });
            }
            if inputs.facts.unique_expression_columns.contains(&pair) {
                return Err(ScrubError::IndexOperandColumn {
                    column: qualified,
                    kind: "a unique index expression or predicate",
                });
            }
            if inputs.facts.exclusion_columns.contains(&pair) {
                return Err(ScrubError::IndexOperandColumn {
                    column: qualified,
                    kind: "an exclusion constraint",
                });
            }
            if plan.strategy == Strategy::Auto {
                plan.strategy = match inputs.facts.dialect {
                    Dialect::Postgres => auto_strategy(column),
                    Dialect::Sqlite => sqlite::auto_strategy(column),
                }
                .map_err(|e| qualify(e, &qualified))?;
            }
            if plan.strategy == Strategy::Null {
                if !column.nullable {
                    return Err(ScrubError::NullOnNotNull { column: qualified });
                }
                // Postgres normally allows any number of NULLs in a unique
                // index — but not under `NULLS NOT DISTINCT`.
                if inputs.facts.nulls_not_distinct_columns.contains(&pair) {
                    return Err(ScrubError::NonUniqueStrategy {
                        column: qualified,
                        strategy: plan.strategy.as_str(),
                    });
                }
            }
            if unique && !plan.strategy.allowed_on_unique() {
                return Err(ScrubError::NonUniqueStrategy {
                    column: qualified,
                    strategy: plan.strategy.as_str(),
                });
            }

            if plan.strategy == Strategy::Encrypted {
                // The same plan-time gates the SQL strategies get: a failure at
                // apply time can land after an artifact restored real data.
                if !is_texty(&column.ty) {
                    return Err(ScrubError::StrategyTypeMismatch {
                        column: qualified,
                        strategy: plan.strategy.as_str(),
                        detail: format!("{:?}", column.ty),
                    });
                }
                let shape = email_shaped(&column.name);
                let needed = envelope_len(shape);
                // `name` holds 63 bytes and truncates silently.
                let limit = char_max_len(&column.ty).or_else(|| {
                    matches!(&column.ty, ColumnType::Opaque { pg_type } if pg_type == "name")
                        .then_some(63)
                });
                if let Some(limit) = limit
                    && limit < needed
                {
                    return Err(ScrubError::EncryptedEnvelopeTooLong {
                        column: qualified,
                        limit,
                        needed,
                    });
                }
                // Not expressible as SQL: the replacement is an AEAD envelope
                // produced in Rust, row by row, under the target's own key.
                encrypted_rewrites.push(EncryptedRewrite {
                    column: column.name.clone(),
                    deterministic: inputs
                        .encrypted
                        .get(&table.name)
                        .and_then(|c| c.get(&column.name))
                        .copied()
                        .unwrap_or(false),
                    shape,
                });
                resolved.push(plan);
                continue;
            }

            let value = match inputs.facts.dialect {
                Dialect::Postgres => {
                    let token = token_expr(table, &column.name, unique);
                    replacement_expr(plan.strategy, column, &token, unique)
                }
                Dialect::Sqlite => {
                    let token = sqlite::token_expr(table, inputs.facts, &column.name, unique);
                    sqlite::replacement_expr(plan.strategy, column, &token)
                }
            }
            .map_err(|e| qualify(e, &qualified))?;
            assignments.push(assignment(column, &value, plan.strategy));
            resolved.push(plan);
        }
        let (target, row_key) = match inputs.facts.dialect {
            Dialect::Postgres => (qualified_ident(&table.name), row_key_expr(table)),
            Dialect::Sqlite => (
                quote_ident(&table.name),
                sqlite::row_key_expr(table, inputs.facts),
            ),
        };
        out.tables.push(TablePlan {
            table: table.name.clone(),
            columns: resolved,
            sql: (!assignments.is_empty())
                .then(|| format!("UPDATE {target} SET {}", assignments.join(", "))),
            row_key,
            encrypted: encrypted_rewrites,
        });
    }
    Ok(out)
}

/// Re-label a per-column error with its `table.column` name.
///
/// The expression builders work from a bare [`Column`] and cannot know which
/// table it came from, but a bare column name is ambiguous in a report (three
/// tables can each have an `email`). The classifier knows both, so it qualifies
/// the name on the way out.
fn qualify(error: ScrubError, qualified: &str) -> ScrubError {
    let column = qualified.to_owned();
    match error {
        ScrubError::NoAutoStrategy { detail, .. } => ScrubError::NoAutoStrategy { column, detail },
        ScrubError::StrategyTypeMismatch {
            strategy, detail, ..
        } => ScrubError::StrategyTypeMismatch {
            column,
            strategy,
            detail,
        },
        ScrubError::ColumnTooNarrow {
            limit,
            overhead,
            floor,
            ..
        } => ScrubError::ColumnTooNarrow {
            column,
            limit,
            overhead,
            floor,
        },
        other => other,
    }
}

/// Refuse a declaration that names a table or column the database no longer has
/// — the exact rot that lets a renamed column leak.
fn check_config_freshness(
    inputs: &ClassificationInputs<'_>,
    by_name: &BTreeMap<&str, &Table>,
) -> Result<(), ScrubError> {
    let mut stale = Vec::new();
    let mut framework = Vec::new();
    for (name, rule) in &inputs.config.tables {
        let Some(table) = by_name.get(name.as_str()) else {
            // A framework-owned table is not "missing" — it is deliberately
            // outside the classified universe, and saying "the database does
            // not have it" would send the developer hunting for a typo.
            if is_framework_table(name) {
                framework.push(name.clone());
            } else {
                stale.push(name.clone());
            }
            continue;
        };
        let columns: BTreeSet<&str> = table.columns.iter().map(|c| c.name.as_str()).collect();
        for column in rule
            .safe
            .iter()
            .chain(rule.pii.keys())
            .chain(rule.encrypted.keys())
        {
            if !columns.contains(column.as_str()) {
                stale.push(format!("{name}.{column}"));
            }
        }
    }
    if !framework.is_empty() {
        framework.sort();
        return Err(ScrubError::FrameworkTableDeclared { tables: framework });
    }
    if stale.is_empty() {
        return Ok(());
    }
    stale.sort();
    stale.dedup();
    Err(ScrubError::StaleConfig { entries: stale })
}

/// Refuse a column declared both `safe` and PII.
fn check_contradictions(inputs: &ClassificationInputs<'_>) -> Result<(), ScrubError> {
    let mut columns = Vec::new();
    for (name, rule) in &inputs.config.tables {
        for column in &rule.safe {
            if rule.pii.contains_key(column) {
                columns.push(format!("{name}.{column}"));
            }
        }
    }
    if columns.is_empty() {
        return Ok(());
    }
    columns.sort();
    Err(ScrubError::Contradiction { columns })
}

/// Refuse a `safe` declaration that would un-classify an `#[encrypted]` column.
/// An at-rest-encrypted column is PII by construction; letting a declaration
/// override it would reintroduce exactly the silent-passthrough this command
/// exists to prevent.
fn check_safe_overrides_encrypted(
    inputs: &ClassificationInputs<'_>,
    by_name: &BTreeMap<&str, &Table>,
) -> Result<(), ScrubError> {
    let mut columns = Vec::new();
    for (table, encrypted) in inputs.encrypted {
        if !by_name.contains_key(table.as_str()) {
            continue;
        }
        let rule = inputs.config.tables.get(table);
        for column in encrypted.keys() {
            // An explicit PII entry is not an override — it only picks the
            // strategy — so only `safe` declarations conflict.
            if rule.is_some_and(|r| r.pii.contains_key(column)) {
                continue;
            }
            // A key column is exempt: it can never be rewritten anyway, so
            // refusing its `safe` declaration would leave the developer with no
            // configuration that terminates.
            //
            // This asks `is_key_column` rather than re-deriving the test from
            // the IR flags alone: the catalog contributes two more sources (the
            // REFERENCED side of a foreign key, and generated columns) that the
            // IR does not carry, so the two tests disagreed about what counts as
            // structural.
            //
            // Classification honours that `safe` declaration for a structural
            // column: the ciphertext stays where it is.
            if by_name
                .get(table.as_str())
                .and_then(|t| {
                    t.columns
                        .iter()
                        .find(|c| &c.name == column)
                        .map(|c| (*t, c))
                })
                .is_some_and(|(t, c)| is_key_column(t, c, inputs.facts))
            {
                continue;
            }
            if rule.is_some_and(|r| r.safe.contains(column))
                || inputs.config.defaults.safe_columns.contains(column)
            {
                columns.push(format!("{table}.{column}"));
            }
        }
    }
    if columns.is_empty() {
        return Ok(());
    }
    columns.sort();
    Err(ScrubError::SafeOverridesEncrypted { columns })
}

/// Base tables the catalog reports in `public` that introspection did not return
/// and that are not framework-owned — i.e. ones the connecting role cannot see.
fn unreachable_tables(facts: &DatabaseFacts, introspected: &[Table]) -> Vec<String> {
    let seen: BTreeSet<&str> = introspected.iter().map(|t| t.name.as_str()).collect();
    let mut missing: Vec<String> = facts
        .public_base_tables
        .iter()
        .filter(|t| !seen.contains(t.as_str()) && !is_framework_table(t))
        .cloned()
        .collect();

    // Privileges are per COLUMN as well as per table: a table can be visible
    // while some of its columns are not, and those would be scrubbed by nothing
    // while the table itself classified cleanly.
    let seen_columns: BTreeSet<(&str, &str)> = introspected
        .iter()
        .flat_map(|t| {
            t.columns
                .iter()
                .map(move |c| (t.name.as_str(), c.name.as_str()))
        })
        .collect();
    missing.extend(
        facts
            .public_columns
            .iter()
            .filter(|(table, column)| {
                seen.contains(table.as_str())
                    && !is_framework_table(table)
                    && !seen_columns.contains(&(table.as_str(), column.as_str()))
            })
            .map(|(table, column)| format!("{table}.{column}")),
    );
    missing.sort();
    missing.dedup();
    missing
}

/// Whether a column is structural — a primary key, either side of any foreign
/// key, a partition key, or a generated column Postgres will not let an
/// `UPDATE` touch.
///
/// The foreign-key half comes from [`DatabaseFacts`], not from the schema IR:
/// the IR records only the *referencing* side and only a composite key's first
/// component, so a natural key another table points at (`users.email` ←
/// `orders.user_email`) would otherwise look freely rewritable and fail the
/// constraint at apply time — or, under `ON UPDATE CASCADE`, silently rewrite a
/// child column that was declared safe.
fn is_key_column(table: &Table, column: &Column, facts: &DatabaseFacts) -> bool {
    let pair = (table.name.clone(), column.name.clone());
    column.primary_key
        || table.primary_key.contains(&column.name)
        || column.references.is_some()
        || facts.foreign_key_columns.contains(&pair)
        || facts.partition_key_columns.contains(&pair)
        || facts.generated_columns.contains(&pair)
}

/// Whether a rewrite of this column could violate a uniqueness constraint.
///
/// This is deliberately **broader** than the schema IR's single-column `unique`
/// flag, which answers the migration-diff question "does this satisfy a model
/// `#[unique]`" and therefore excludes composite and partial unique indexes. For
/// a writer both of those still abort the statement: one member of a composite
/// unique key set to a constant collides as soon as its partner repeats, and a
/// partial unique index constrains every row its predicate matches. So the
/// probed `unique_columns` set — every column of every unique index — is what
/// gates strategy choice.
fn is_unique_column(table: &Table, column: &Column, facts: &DatabaseFacts) -> bool {
    column.unique
        || facts
            .unique_columns
            .contains(&(table.name.clone(), column.name.clone()))
        || table.indexes.iter().any(|index| {
            if !index.unique {
                return false;
            }
            let keys = if index.key_columns.is_empty() {
                &index.columns
            } else {
                &index.key_columns
            };
            keys.iter().any(|k| k == &column.name)
        })
}

// ─── Replacement expressions ────────────────────────────────────────────────

/// The SQL expression identifying a row for deterministic replacement: its
/// primary key when it has one, else its physical `ctid` (unique within the
/// statement, which is all a single `UPDATE` needs).
fn row_key_expr(table: &Table) -> String {
    let mut keys: Vec<&str> = table.primary_key.iter().map(String::as_str).collect();
    if keys.is_empty() {
        keys = table
            .columns
            .iter()
            .filter(|c| c.primary_key)
            .map(|c| c.name.as_str())
            .collect();
    }
    if keys.is_empty() {
        return "ctid::text".to_owned();
    }
    if keys.len() == 1 {
        return format!("coalesce({}::text, '')", quote_ident(keys[0]));
    }
    // `ROW(...)::text` renders a composite key with Postgres's own quoting, so
    // ('a|','b') and ('a','|b') cannot collapse to one row key the way a plain
    // separator-joined concatenation does.
    format!(
        "ROW({})::text",
        keys.iter()
            .map(|key| quote_ident(key))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

/// The per-row, per-column token every replacement is derived from. Salting with
/// the column name keeps two PII columns of one row from receiving identical
/// fake values.
fn token_expr(table: &Table, column: &str, unique: bool) -> String {
    token_expr_from(&row_key_expr(table), column, unique)
}

/// [`token_expr`] against an already-computed row key.
///
/// A column that must stay unique gets a 64-hex-character `sha256` token rather
/// than `md5`'s 32, so a length-bounded column still has room for a token wide
/// enough to make collisions impossible in practice (see [`bounded_token`]).
fn token_expr_from(row_key: &str, column: &str, unique: bool) -> String {
    let seed = format!("{} || '|' || {row_key}", quote_literal(column));
    if unique {
        // Two independently-salted `md5`s concatenated, rather than `sha256`:
        // both halves would have to collide at once, and this needs no
        // `text`-to-`bytea` cast (whose escape-format interpretation would
        // mangle a row key containing a backslash) and no Postgres 11 floor.
        format!("md5({seed}) || md5(({seed}) || '#2')")
    } else {
        format!("md5({seed})")
    }
}

/// The character limit a length-bounded Postgres type imposes, if any.
///
/// Introspection preserves `varchar(n)` / `char(n)` verbatim as
/// [`ColumnType::Opaque`] rather than collapsing them to `Text`, so the limit is
/// readable straight off the type.
fn char_max_len(ty: &ColumnType) -> Option<usize> {
    let ColumnType::Opaque { pg_type } = ty else {
        return None;
    };
    let rest = pg_type
        .strip_prefix("varchar(")
        .or_else(|| pg_type.strip_prefix("char("))?;
    rest.strip_suffix(')')?.parse().ok()
}

/// Whether a column stores character data a text-shaped replacement can be
/// written into.
fn is_texty(ty: &ColumnType) -> bool {
    match ty {
        ColumnType::Text => true,
        ColumnType::Opaque { pg_type } => {
            char_max_len(ty).is_some() || matches!(pg_type.as_str(), "citext" | "name")
        }
        _ => false,
    }
}

/// Derive a replacement strategy from the column type alone — what an
/// automatically-classified column (`#[encrypted]`, GDPR anonymize) uses.
///
/// A closed-set ([`ColumnType::Enum`]) or otherwise exotic type has no safe
/// generic fake (a fabricated value would violate its `CHECK`), so the developer
/// is asked for an explicit strategy rather than guessed at.
///
/// # Errors
///
/// Returns [`ScrubError::NoAutoStrategy`] for a type with no generic fake.
fn auto_strategy(column: &Column) -> Result<Strategy, ScrubError> {
    Ok(match &column.ty {
        ColumnType::Text => email_shaped(&column.name),
        ColumnType::Uuid => Strategy::Uuid,
        ColumnType::Bytes => Strategy::Bytes,
        ColumnType::Json | ColumnType::Attachment => Strategy::Json,
        ColumnType::Int32
        | ColumnType::Int64
        | ColumnType::Float32
        | ColumnType::Float64
        | ColumnType::Bool
        | ColumnType::Decimal { .. } => Strategy::Zero,
        ColumnType::Timestamp | ColumnType::TimestampTz => Strategy::Epoch,
        ty @ ColumnType::Opaque { .. } if is_texty(ty) => email_shaped(&column.name),
        // `from_pg_udt` maps only Autumn's own scalar surface, so several
        // everyday PII column types arrive as `Opaque` — `date_of_birth DATE`
        // most of all. Without these arms `auto` refuses them and the explicit
        // fallbacks (`epoch`, `zero`) reject them too, leaving no usable
        // strategy at all.
        ColumnType::Opaque { pg_type }
            if matches!(pg_type.as_str(), "date" | "time" | "timetz") =>
        {
            Strategy::Epoch
        }
        ColumnType::Opaque { pg_type }
            if matches!(pg_type.as_str(), "int2" | "money" | "oid")
                || pg_type.starts_with("numeric") =>
        {
            Strategy::Zero
        }
        other => {
            return Err(ScrubError::NoAutoStrategy {
                column: column.name.clone(),
                detail: format!("{other:?}"),
            });
        }
    })
}

/// Text columns whose name says "email" get a syntactically valid address, so a
/// scrubbed copy still satisfies format `CHECK`s and app-level parsing. Every
/// other text column is redacted — the name is only ever used to pick a *shape*,
/// never to decide whether a column is PII.
fn email_shaped(name: &str) -> Strategy {
    if name.to_ascii_lowercase().contains("email") {
        Strategy::Email
    } else {
        Strategy::Redact
    }
}

/// Build the replacement expression for one column.
///
/// # Errors
///
/// Returns [`ScrubError::ColumnTooNarrow`] when a length-bounded column cannot
/// hold a per-row-unique value, [`ScrubError::StrategyTypeMismatch`] when the
/// strategy cannot produce the column's type, or [`ScrubError::NoAutoStrategy`]
/// when [`Strategy::Auto`] cannot be resolved.
#[allow(clippy::too_many_lines)]
fn replacement_expr(
    strategy: Strategy,
    column: &Column,
    token: &str,
    unique: bool,
) -> Result<String, ScrubError> {
    let limit = char_max_len(&column.ty);
    let narrow = |overhead: usize| -> Result<String, ScrubError> {
        bounded_token(token, limit, overhead, &column.name, unique)
    };
    // Every text-shaped strategy needs a character column to land in. Without
    // this gate `age = "redact"` on an `integer` (or `last_login_ip = "redact"`
    // on an `inet`) passes classification and only fails once Postgres runs the
    // statement — after an `--artifact` restore has already written real data.
    if matches!(
        strategy,
        Strategy::Email | Strategy::Name | Strategy::Redact | Strategy::Phone
    ) {
        require_type(column, strategy, is_texty(&column.ty))?;
    }
    Ok(match strategy {
        Strategy::Auto => replacement_expr(auto_strategy(column)?, column, token, unique)?,
        Strategy::Encrypted => {
            return Err(ScrubError::StrategyTypeMismatch {
                column: column.name.clone(),
                strategy: strategy.as_str(),
                detail: "an encrypted replacement is built in Rust, not in SQL".to_owned(),
            });
        }
        Strategy::Email => {
            let tok = narrow("scrubbed+".len() + SCRUB_EMAIL_DOMAIN.len())?;
            format!("'scrubbed+' || {tok} || '{SCRUB_EMAIL_DOMAIN}'")
        }
        Strategy::Name => {
            let tok = narrow("Scrubbed ".len())?;
            format!("'Scrubbed ' || {tok}")
        }
        Strategy::Redact => {
            let tok = narrow("[scrubbed:]".len())?;
            format!("'[scrubbed:' || {tok} || ']'")
        }
        Strategy::Phone => {
            // 10 hex characters mapped onto digits: `translate` is lossy, which
            // is why `allowed_on_unique` excludes this strategy.
            const PHONE_DIGITS: usize = 10;
            let overhead = "+1555".len();
            if let Some(limit) = limit
                && limit < overhead + PHONE_DIGITS
            {
                return Err(ScrubError::ColumnTooNarrow {
                    column: column.name.clone(),
                    limit,
                    overhead,
                    floor: PHONE_DIGITS,
                });
            }
            format!("'+1555' || translate(substr({token}, 1, {PHONE_DIGITS}), 'abcdef', '0123456')")
        }
        Strategy::Null => "NULL".to_owned(),
        Strategy::Uuid => {
            require_type(column, strategy, matches!(column.ty, ColumnType::Uuid))?;
            // A UUID is exactly 128 bits, and Postgres rejects any other width —
            // so the wider token a unique column gets must be trimmed to its
            // first 32 hex characters. That is the full entropy a UUID can hold,
            // so nothing is lost.
            format!("(substr({token}, 1, 32))::uuid")
        }
        Strategy::Bytes => {
            require_type(column, strategy, matches!(column.ty, ColumnType::Bytes))?;
            format!("decode({token}, 'hex')")
        }
        Strategy::Json => {
            let json = "'{\"scrubbed\": true}'";
            match &column.ty {
                ColumnType::Json | ColumnType::Attachment => format!("{json}::jsonb"),
                ColumnType::Opaque { pg_type } if pg_type == "json" => format!("{json}::json"),
                ty if is_texty(ty) => {
                    // Unlike every other text-producing strategy this one is a
                    // fixed literal, so a narrow `varchar(n)` has to be checked
                    // explicitly rather than by narrowing a token.
                    const JSON_LITERAL_LEN: usize = 18;
                    if let Some(limit) = limit
                        && limit < JSON_LITERAL_LEN
                    {
                        return Err(ScrubError::ColumnTooNarrow {
                            column: column.name.clone(),
                            limit,
                            overhead: JSON_LITERAL_LEN,
                            floor: 0,
                        });
                    }
                    json.to_owned()
                }
                other => {
                    return Err(ScrubError::StrategyTypeMismatch {
                        column: column.name.clone(),
                        strategy: strategy.as_str(),
                        detail: format!("{other:?}"),
                    });
                }
            }
        }
        Strategy::Zero => match &column.ty {
            ColumnType::Bool => "false".to_owned(),
            ColumnType::Int32
            | ColumnType::Int64
            | ColumnType::Float32
            | ColumnType::Float64
            | ColumnType::Decimal { .. } => "0".to_owned(),
            ColumnType::Opaque { pg_type }
                if pg_type.starts_with("numeric")
                    || matches!(pg_type.as_str(), "int2" | "money" | "oid") =>
            {
                "0".to_owned()
            }
            other => {
                return Err(ScrubError::StrategyTypeMismatch {
                    column: column.name.clone(),
                    strategy: strategy.as_str(),
                    detail: format!("{other:?}"),
                });
            }
        },
        Strategy::Epoch => match &column.ty {
            ColumnType::Timestamp => "'1970-01-01 00:00:00'::timestamp".to_owned(),
            ColumnType::TimestampTz => "'1970-01-01 00:00:00+00'::timestamptz".to_owned(),
            ColumnType::Opaque { pg_type } if pg_type == "date" => "'1970-01-01'::date".to_owned(),
            ColumnType::Opaque { pg_type } if pg_type == "time" => "'00:00:00'::time".to_owned(),
            ColumnType::Opaque { pg_type } if pg_type == "timetz" => {
                "'00:00:00+00'::timetz".to_owned()
            }
            other => {
                return Err(ScrubError::StrategyTypeMismatch {
                    column: column.name.clone(),
                    strategy: strategy.as_str(),
                    detail: format!("{other:?}"),
                });
            }
        },
    })
}

/// Refuse a strategy whose output type cannot be stored in the column.
fn require_type(column: &Column, strategy: Strategy, ok: bool) -> Result<(), ScrubError> {
    if ok {
        return Ok(());
    }
    Err(ScrubError::StrategyTypeMismatch {
        column: column.name.clone(),
        strategy: strategy.as_str(),
        detail: format!("{:?}", column.ty),
    })
}

/// Narrow the token so `overhead` fixed characters plus the token fit inside a
/// length-bounded column, or refuse when what is left cannot stay unique.
fn bounded_token(
    token: &str,
    limit: Option<usize>,
    overhead: usize,
    column: &str,
    unique: bool,
) -> Result<String, ScrubError> {
    let (full, floor) = if unique {
        (UNIQUE_TOKEN_HEX_LEN, MIN_UNIQUE_TOKEN_WIDTH)
    } else {
        (TOKEN_HEX_LEN, MIN_TOKEN_WIDTH)
    };
    let Some(limit) = limit else {
        return Ok(token.to_owned());
    };
    let available = limit.saturating_sub(overhead);
    if available >= full {
        Ok(token.to_owned())
    } else if available >= floor {
        Ok(format!("substr({token}, 1, {available})"))
    } else {
        Err(ScrubError::ColumnTooNarrow {
            column: column.to_owned(),
            limit,
            overhead,
            floor,
        })
    }
}

/// One `SET` clause. A nullable column keeps its `NULL`s (a scrub anonymizes
/// values, it does not invent them), so it is wrapped in a `CASE`; a `NOT NULL`
/// column needs no guard.
fn assignment(column: &Column, value: &str, strategy: Strategy) -> String {
    let ident = quote_ident(&column.name);
    // A `CASE` whose arms are both bare `NULL` has no type to infer from, so
    // Postgres resolves it to `text` and the assignment fails on every
    // non-character column. The guard is pointless there anyway: the
    // replacement already IS null.
    if column.nullable && strategy != Strategy::Null {
        format!("{ident} = CASE WHEN {ident} IS NULL THEN NULL ELSE {value} END")
    } else {
        format!("{ident} = {value}")
    }
}

/// A `public`-qualified table identifier.
///
/// Every catalog read that produced the plan is scoped to `public`, so the
/// writes must be too: a database- or role-level `search_path` (which Autumn
/// supports for tenant schemas) would otherwise resolve a bare `UPDATE "users"`
/// to a *different* table than the one that was classified — leaving the
/// classified rows unscrubbed and overwriting rows nothing planned.
fn qualified_ident(table: &str) -> String {
    format!("\"public\".{}", quote_ident(table))
}

// ─── GDPR anonymize registrations ───────────────────────────────────────────

/// Extract the tables registered with the GDPR anonymize strategy from one Rust
/// source file.
///
/// The registry is built at runtime (`GdprRegistry::new().register(...)`) so it
/// is not readable without booting the app; the registrations themselves are
/// plain calls, and reading them with `syn` keeps the scrub usable against a
/// dump without a compiled binary. A call whose argument is not a string literal
/// is **refused**, never skipped — an unreadable registration must not look like
/// an absent one.
///
/// # Errors
///
/// Returns [`ScrubError::SourceScan`] if the source is not valid Rust, or
/// [`ScrubError::UnresolvableAnonymize`] for a non-literal table name.
#[cfg(test)]
fn extract_anonymize_tables(src: &str) -> Result<BTreeSet<String>, ScrubError> {
    scan_anonymize_source(src)
}

/// Collect the production anonymize registrations in one source file.
fn scan_anonymize_source(src: &str) -> Result<BTreeSet<String>, ScrubError> {
    use syn::visit::Visit as _;

    let file = syn::parse_file(src).map_err(|e| ScrubError::SourceScan {
        detail: e.to_string(),
    })?;
    if !crate::schema::parse::production_enabled(&file.attrs) {
        return Ok(BTreeSet::new());
    }
    let mut scan = AnonymizeScan::default();
    scan.visit_file(&file);
    if let Some(detail) = scan.unresolved.into_iter().next() {
        return Err(ScrubError::UnresolvableAnonymize { detail });
    }
    Ok(scan.tables)
}

/// `syn` visitor collecting `ModelRegistration::anonymize("<table>")` calls
/// outside `cfg`-disabled syntax.
#[derive(Default)]
struct AnonymizeScan {
    tables: BTreeSet<String>,
    unresolved: Vec<String>,
}

impl<'ast> syn::visit::Visit<'ast> for AnonymizeScan {
    fn visit_item(&mut self, item: &'ast syn::Item) {
        let attrs: &[syn::Attribute] = crate::schema::parse::item_attrs(item);
        if crate::schema::parse::production_enabled(attrs) {
            syn::visit::visit_item(self, item);
        }
    }

    fn visit_trait_item(&mut self, item: &'ast syn::TraitItem) {
        let attrs: &[syn::Attribute] = crate::schema::parse::trait_item_attrs(item);
        if crate::schema::parse::production_enabled(attrs) {
            syn::visit::visit_trait_item(self, item);
        }
    }

    fn visit_impl_item(&mut self, item: &'ast syn::ImplItem) {
        let attrs: &[syn::Attribute] = crate::schema::parse::impl_item_attrs(item);
        if crate::schema::parse::production_enabled(attrs) {
            syn::visit::visit_impl_item(self, item);
        }
    }

    fn visit_expr(&mut self, expr: &'ast syn::Expr) {
        let attrs: &[syn::Attribute] = crate::schema::parse::expr_attrs(expr);
        if crate::schema::parse::production_enabled(attrs) {
            syn::visit::visit_expr(self, expr);
        }
    }

    fn visit_arm(&mut self, arm: &'ast syn::Arm) {
        if crate::schema::parse::production_enabled(&arm.attrs) {
            syn::visit::visit_arm(self, arm);
        }
    }

    fn visit_stmt_macro(&mut self, stmt: &'ast syn::StmtMacro) {
        if crate::schema::parse::production_enabled(&stmt.attrs) {
            syn::visit::visit_stmt_macro(self, stmt);
        }
    }

    fn visit_foreign_item(&mut self, item: &'ast syn::ForeignItem) {
        if crate::schema::parse::production_enabled(crate::schema::parse::foreign_item_attrs(item))
        {
            syn::visit::visit_foreign_item(self, item);
        }
    }

    fn visit_pat(&mut self, pat: &'ast syn::Pat) {
        if crate::schema::parse::production_enabled(crate::schema::parse::pat_attrs(pat)) {
            syn::visit::visit_pat(self, pat);
        }
    }

    fn visit_generic_param(&mut self, param: &'ast syn::GenericParam) {
        if crate::schema::parse::production_enabled(crate::schema::parse::generic_param_attrs(
            param,
        )) {
            syn::visit::visit_generic_param(self, param);
        }
    }

    fn visit_fn_arg(&mut self, arg: &'ast syn::FnArg) {
        if crate::schema::parse::production_enabled(crate::schema::parse::fn_arg_attrs(arg)) {
            syn::visit::visit_fn_arg(self, arg);
        }
    }

    fn visit_field(&mut self, field: &'ast syn::Field) {
        if crate::schema::parse::production_enabled(&field.attrs) {
            syn::visit::visit_field(self, field);
        }
    }

    fn visit_variant(&mut self, variant: &'ast syn::Variant) {
        if crate::schema::parse::production_enabled(&variant.attrs) {
            syn::visit::visit_variant(self, variant);
        }
    }

    fn visit_field_value(&mut self, field: &'ast syn::FieldValue) {
        if crate::schema::parse::production_enabled(&field.attrs) {
            syn::visit::visit_field_value(self, field);
        }
    }

    fn visit_local(&mut self, local: &'ast syn::Local) {
        if crate::schema::parse::production_enabled(&local.attrs) {
            syn::visit::visit_local(self, local);
        }
    }

    fn visit_expr_call(&mut self, node: &'ast syn::ExprCall) {
        if !crate::schema::parse::production_enabled(&node.attrs) {
            return;
        }
        if let syn::Expr::Path(path) = &*node.func {
            let segments = &path.path.segments;
            let is_anonymize = segments.len() >= 2
                && segments[segments.len() - 1].ident == "anonymize"
                && segments[segments.len() - 2].ident == "ModelRegistration";
            if is_anonymize {
                match node.args.first() {
                    Some(syn::Expr::Lit(syn::ExprLit {
                        lit: syn::Lit::Str(table),
                        ..
                    })) => {
                        self.tables.insert(table.value());
                    }
                    _ => self.unresolved.push(quote::quote!(#node).to_string()),
                }
            }
        }
        syn::visit::visit_expr_call(self, node);
    }
}

/// Scan every production `.rs` file under `root` (recursively) for anonymize
/// registrations. A file reached only through a `#[cfg(test)] mod x;` is test
/// code and is skipped with everything below it.
fn scan_anonymize_tables(root: &Path) -> Result<BTreeSet<String>, ScrubError> {
    if !root.is_dir() {
        return Ok(BTreeSet::new());
    }
    let io_err = |path: &Path, e: &dyn std::fmt::Display| ScrubError::SourceScan {
        detail: format!("{}: {e}", path.display()),
    };
    let mut files = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        for entry in std::fs::read_dir(&dir).map_err(|e| io_err(&dir, &e))? {
            let entry = entry.map_err(|e| io_err(&dir, &e))?;
            let path = entry.path();
            let file_type = entry.file_type().map_err(|e| io_err(&path, &e))?;
            if file_type.is_dir() {
                stack.push(path);
            } else if file_type.is_file() && path.extension().is_some_and(|ext| ext == "rs") {
                files.push(path);
            }
        }
    }
    files.sort();

    let mut scanned = Vec::with_capacity(files.len());
    let mut sources = Vec::with_capacity(files.len());
    for path in files {
        let src = std::fs::read_to_string(&path).map_err(|e| io_err(&path, &e))?;
        scanned.push((path.clone(), scan_anonymize_source(&src)));
        sources.push((path, src));
    }
    let disabled = crate::schema::parse::disabled_module_paths(&sources);

    let mut out = BTreeSet::new();
    for (path, result) in scanned {
        if disabled.excludes(&path) {
            continue;
        }
        match result {
            Ok(tables) => out.extend(tables),
            Err(ScrubError::SourceScan { detail }) => {
                return Err(ScrubError::SourceScan {
                    detail: format!("{}: {detail}", path.display()),
                });
            }
            Err(ScrubError::UnresolvableAnonymize { detail }) => {
                return Err(ScrubError::UnresolvableAnonymize {
                    detail: format!("{} — {detail}", path.display()),
                });
            }
            Err(other) => return Err(other),
        }
    }
    Ok(out)
}

/// Read the `#[encrypted]` column set from every production source file under
/// `src/`, the tree the GDPR scanner walks too. A model may live anywhere; a
/// column the scan missed would keep its ciphertext or take plaintext.
/// Degrades to an empty map when the project has no `src/` at all.
fn encrypted_columns(
    project_root: &Path,
) -> Result<BTreeMap<String, BTreeMap<String, bool>>, ScrubError> {
    let src = project_root.join("src");
    if !src.is_dir() {
        return Ok(BTreeMap::new());
    }
    crate::schema::parse::parse_encrypted_columns_path(&src).map_err(|e| ScrubError::SourceScan {
        detail: e.to_string(),
    })
}

// ─── Guards ─────────────────────────────────────────────────────────────────

/// Refuse a scrub against a production profile without `--force` — the identical
/// protocol as `autumn db drop` (AC #5).
///
/// # Errors
///
/// Returns [`ScrubError::ProductionRefused`] for any profile outside
/// `dev`/`test` when `force` is not set.
fn guard_scrub_target(profile: &str, force: bool) -> Result<(), ScrubError> {
    super::guard_destructive(profile, force).map_err(|_| ScrubError::ProductionRefused {
        profile: profile.to_owned(),
    })
}

/// Whether two connection strings address the same database: same host, same
/// port, same database name. Credentials are deliberately ignored — a read-only
/// role pointed at production is still production. `env` supplies `PGHOST` /
/// `PGPORT` for hostless URLs.
///
/// An unparsable URL never claims a match (the guard errs toward "different",
/// leaving the profile guard as the enforcement).
fn same_database_in(a: &str, b: &str, env: &dyn Fn(&str) -> Option<String>) -> bool {
    if let (Some(a), Some(b)) = (sqlite::database_file(a), sqlite::database_file(b)) {
        return a == b;
    }
    match (database_endpoint(a, env), database_endpoint(b, env)) {
        (Some((ends_a, name_a)), Some((ends_b, name_b))) => {
            name_a == name_b
                && ends_a
                    .iter()
                    .any(|a| ends_b.iter().any(|b| same_endpoint(a, b)))
        }
        _ => false,
    }
}

/// Whether two `(host, port)` endpoints can be one server. An empty host is the
/// compiled-in default socket directory, which this guard cannot name, so it
/// also matches any explicit socket path on the same port. That errs toward
/// refusing.
fn same_endpoint(a: &(String, u16), b: &(String, u16)) -> bool {
    let socket = |h: &str| h.starts_with('/');
    a == b || (a.1 == b.1 && ((a.0.is_empty() && socket(&b.0)) || (b.0.is_empty() && socket(&a.0))))
}

/// The `(host, port)` endpoints and database a URL reaches, resolved as libpq does.
///
/// A hostless URL (`postgres:///db?host=/run/postgresql`) names its host in the
/// `host` or `hostaddr` query parameter, else in `PGHOST`, else it uses the
/// default local socket (an empty host). The port follows the same order.
fn database_endpoint(
    raw: &str,
    env: &dyn Fn(&str) -> Option<String>,
) -> Option<(Vec<(String, u16)>, String)> {
    // The same test tokio-postgres uses: only these prefixes start a URL, so a
    // keyword string with `password=https://…` is not one.
    if !(raw.starts_with("postgres://") || raw.starts_with("postgresql://")) {
        return conninfo_endpoint(raw, env);
    }
    let user = url_user(raw);
    let stripped = without_userinfo(raw);
    let (scheme, rest) = stripped.split_once("://")?;
    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    // The authority can list several `host:port` pairs, which `url::Url`
    // rejects. Read them here and parse the rest behind a placeholder.
    let listed = authority_endpoints(&rest[..end])?;
    let parsed = url::Url::parse(&format!("{scheme}://placeholder{}", &rest[end..])).ok()?;
    let pairs = raw_query_pairs(parsed.query().unwrap_or_default());
    // The last repeat of a parameter wins, even when empty. An empty value is
    // the default and does not fall back to the environment.
    let query = |key: &str| {
        pairs
            .iter()
            .rev()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.clone())
    };
    let query_set = |key: &str| query(key).filter(|v| !v.is_empty());
    // An explicit `dbname` replaces the path, even when empty. The whole path is
    // the name, so it may hold a slash.
    let path_name =
        percent_encoding::percent_decode_str(parsed.path().strip_prefix('/').unwrap_or_default())
            .decode_utf8_lossy()
            .into_owned();
    let name = Some(query("dbname").unwrap_or(path_name))
        .filter(|n| !n.is_empty())
        .or_else(|| env("PGDATABASE").filter(|n| !n.is_empty()))
        .or_else(|| query_set("user"))
        .or(user)
        .or_else(|| env("PGUSER").filter(|n| !n.is_empty()))
        .unwrap_or_else(crate::pg::current_os_user);
    // Named query parameters apply after the authority, so they win. `hostaddr`
    // is the network address libpq connects to; `host` is then only a name.
    let addr = query("hostaddr").or_else(|| env("PGHOSTADDR").filter(|v| !v.is_empty()));
    let fallback_hosts = query("host").or_else(|| {
        if listed.is_empty() {
            env("PGHOST").filter(|v| !v.is_empty())
        } else if addr.is_some() {
            // The authority hosts name the empty `hostaddr` items.
            Some(
                listed
                    .iter()
                    .map(|(host, _)| host.as_str())
                    .collect::<Vec<_>>()
                    .join(","),
            )
        } else {
            None
        }
    });
    let merged = merge_hosts(addr, fallback_hosts);
    let (hosts, own_ports): (Vec<String>, Vec<Option<u16>>) = if let Some(list) = merged {
        let hosts: Vec<String> = list.split(',').map(normalize_host).collect();
        let ports = if listed.len() == hosts.len() {
            listed.iter().map(|(_, p)| *p).collect()
        } else if let [(_, port)] = listed.as_slice() {
            // One port applies to every host.
            vec![*port; hosts.len()]
        } else {
            vec![None; hosts.len()]
        };
        (hosts, ports)
    } else if listed.is_empty() {
        let list = env("PGHOST").filter(|v| !v.is_empty()).unwrap_or_default();
        let hosts: Vec<String> = list.split(',').map(normalize_host).collect();
        let none = vec![None; hosts.len()];
        (hosts, none)
    } else {
        listed.into_iter().unzip()
    };
    // A named `port` overrides the authority's port, as the host does.
    let query_port = query("port");
    let own_ports = if query_port.is_some() {
        vec![None; hosts.len()]
    } else {
        own_ports
    };
    Some((pair_endpoints(hosts, own_ports, query_port, env), name))
}

/// Pair hosts with ports as libpq does. A port list matches the host list by
/// position, one port applies to every host, and an empty item or a missing
/// port is the default port (`PGPORT`, else 5432).
fn pair_endpoints(
    hosts: Vec<String>,
    own_ports: Vec<Option<u16>>,
    port_list: Option<String>,
    env: &dyn Fn(&str) -> Option<String>,
) -> Vec<(String, u16)> {
    // An explicit empty port is the compiled-in default, not `PGPORT`.
    let fallback = if port_list.is_some() {
        5432
    } else {
        env("PGPORT").and_then(|p| p.parse().ok()).unwrap_or(5432)
    };
    let items: Vec<Option<u16>> = port_list
        .filter(|l| !l.is_empty())
        .map(|l| l.split(',').map(|v| v.trim().parse().ok()).collect())
        .unwrap_or_default();
    hosts
        .into_iter()
        .zip(own_ports)
        .enumerate()
        .map(|(i, (host, own))| {
            let port = own
                .or_else(|| {
                    if items.len() == 1 {
                        items[0]
                    } else {
                        items.get(i).copied().flatten()
                    }
                })
                .unwrap_or(fallback);
            (host, port)
        })
        .collect()
}

fn normalize_host(host: &str) -> String {
    let host = percent_encoding::percent_decode_str(host.trim())
        .decode_utf8_lossy()
        .into_owned();
    // A socket directory is case-sensitive. A DNS name is not, and an IP
    // literal has one canonical spelling.
    if host.starts_with(['/', '@']) {
        return host.trim_end_matches('/').to_owned();
    }
    let name = host
        .trim_matches(['[', ']'])
        .trim_end_matches('.')
        .to_ascii_lowercase();
    name.parse::<std::net::IpAddr>()
        .map_or(name, |ip| ip.to_string())
}

/// The `host[:port]` pairs of a URI authority, comma separated. Empty for an
/// empty authority; `None` for a port that is not a number.
fn authority_endpoints(authority: &str) -> Option<Vec<(String, Option<u16>)>> {
    if authority.is_empty() {
        return Some(Vec::new());
    }
    authority
        .split(',')
        .map(|item| {
            let (host, port) = if let Some(inner) = item.strip_prefix('[') {
                let (host, after) = inner.split_once(']')?;
                (host, after.strip_prefix(':'))
            } else if let Some((host, port)) = item.rsplit_once(':') {
                (host, Some(port))
            } else {
                (item, None)
            };
            let port = match port {
                Some("") | None => None,
                Some(p) => Some(p.parse().ok()?),
            };
            Some((normalize_host(host), port))
        })
        .collect()
}

/// Parse libpq `key = value` pairs the way `autumn/src/pg_conn_str.rs` does:
/// whitespace around `=`, single-quoted values, and `\` escaping the next
/// character inside and outside quotes. `None` for a string it rejects.
fn conninfo_pairs(s: &str) -> Option<Vec<(String, String)>> {
    let mut pairs = Vec::new();
    let mut it = s.chars().peekable();
    loop {
        while it.next_if(|c| c.is_whitespace()).is_some() {}
        let mut key = String::new();
        while let Some(&c) = it.peek() {
            if c.is_whitespace() || c == '=' {
                break;
            }
            key.push(c);
            it.next();
        }
        if key.is_empty() {
            return Some(pairs);
        }
        while it.next_if(|c| c.is_whitespace()).is_some() {}
        if it.next() != Some('=') {
            return None;
        }
        while it.next_if(|c| c.is_whitespace()).is_some() {}
        let mut value = String::new();
        if it.next_if_eq(&'\'').is_some() {
            loop {
                match it.next()? {
                    '\'' => break,
                    '\\' => value.push(it.next()?),
                    c => value.push(c),
                }
            }
        } else {
            while let Some(&c) = it.peek() {
                if c.is_whitespace() {
                    break;
                }
                it.next();
                if c == '\\' {
                    match it.next() {
                        Some(escaped) => value.push(escaped),
                        None => break,
                    }
                } else {
                    value.push(c);
                }
            }
            if value.is_empty() {
                return None;
            }
        }
        pairs.push((key, value));
    }
}

/// [`database_endpoint`] for the keyword/value form: `host=h port=5432 dbname=d`.
fn conninfo_endpoint(
    raw: &str,
    env: &dyn Fn(&str) -> Option<String>,
) -> Option<(Vec<(String, u16)>, String)> {
    // The last repeat of a keyword wins, even when empty. An empty value is the
    // default and does not fall back to the environment.
    let values: BTreeMap<String, String> = conninfo_pairs(raw)?.into_iter().collect();
    let set = |key: &str| values.get(key).filter(|v| !v.is_empty()).cloned();
    let env = |key: &str| env(key).filter(|v| !v.is_empty());
    // The database defaults to the user name when none is given.
    let name = set("dbname")
        .or_else(|| env("PGDATABASE"))
        .or_else(|| set("user"))
        .or_else(|| env("PGUSER"))
        .unwrap_or_else(crate::pg::current_os_user);
    // `hostaddr` is the network address libpq connects to.
    let host_list = merge_hosts(
        values
            .get("hostaddr")
            .cloned()
            .or_else(|| env("PGHOSTADDR")),
        values.get("host").cloned().or_else(|| env("PGHOST")),
    )
    .unwrap_or_default();
    let hosts: Vec<String> = host_list.split(',').map(normalize_host).collect();
    let own = vec![None; hosts.len()];
    let endpoints = pair_endpoints(hosts, own, values.get("port").cloned(), &env);
    Some((endpoints, name))
}

/// Merge `hostaddr` and `host` lists. An empty `hostaddr` item uses the host
/// name at the same position.
fn merge_hosts(addr: Option<String>, name: Option<String>) -> Option<String> {
    let Some(addr) = addr else { return name };
    let names: Vec<&str> = name
        .as_deref()
        .map_or_else(Vec::new, |n| n.split(',').collect());
    let merged: Vec<&str> = addr
        .split(',')
        .enumerate()
        .map(|(i, a)| {
            if a.is_empty() {
                names.get(i).copied().unwrap_or_default()
            } else {
                a
            }
        })
        .collect();
    Some(merged.join(","))
}

/// The user name of a URL, percent-decoded. The database defaults to it.
fn url_user(raw: &str) -> Option<String> {
    let (_, rest) = raw.split_once("://")?;
    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (userinfo, _) = rest[..end].rsplit_once('@')?;
    let user = userinfo.split(':').next()?;
    (!user.is_empty()).then(|| {
        percent_encoding::percent_decode_str(user)
            .decode_utf8_lossy()
            .into_owned()
    })
}

/// The `key=value` pairs of a URI query, percent-decoded only. A `+` stays a
/// plus, as in the connection parser; `url::Url::query_pairs` would read it as
/// a space.
fn raw_query_pairs(query: &str) -> Vec<(String, String)> {
    let decode = |text: &str| {
        percent_encoding::percent_decode_str(text)
            .decode_utf8_lossy()
            .into_owned()
    };
    query
        .split('&')
        .filter(|pair| !pair.is_empty())
        .map(|pair| {
            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
            (decode(key), decode(value))
        })
        .collect()
}

/// Whether a connection string selects a libpq `service`, as a keyword or as a
/// URI query parameter.
fn uses_libpq_service(raw: &str) -> bool {
    if raw.starts_with("postgres://") || raw.starts_with("postgresql://") {
        let query = raw.split_once('?').map_or("", |(_, q)| q);
        let query = query.split('#').next().unwrap_or_default();
        raw_query_pairs(query).iter().any(|(k, _)| k == "service")
    } else {
        conninfo_pairs(raw).is_some_and(|pairs| pairs.iter().any(|(k, _)| k == "service"))
    }
}

/// `raw` with any `user:password@` removed. An empty host with credentials
/// (`postgres://app@/db`) is valid libpq but does not parse as a URL.
fn without_userinfo(raw: &str) -> String {
    let Some((scheme, rest)) = raw.split_once("://") else {
        return raw.to_owned();
    };
    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    rest[..end].rfind('@').map_or_else(
        || raw.to_owned(),
        |at| format!("{scheme}://{}", &rest[at + 1..]),
    )
}

/// Refuse `--output` when the scrub covers only some configured targets.
fn refuse_partial_output(
    args: &ScrubArgs,
    scrubbed: usize,
    configured: usize,
) -> Result<(), ScrubError> {
    if args.output.is_some() && scrubbed < configured {
        return Err(ScrubError::SourceScan {
            detail: "--output needs every configured target, but the artifact restores only some"
                .to_owned(),
        });
    }
    Ok(())
}

/// The write targets an artifact restore actually wrote to.
///
/// A control-only or single-shard artifact leaves every other configured shard
/// live; scrubbing those would anonymize data nobody asked to touch.
fn restored_targets(targets: Vec<(String, String)>, restored: &[String]) -> Vec<(String, String)> {
    targets
        .into_iter()
        .filter(|(label, _)| restored.contains(label))
        .collect()
}

/// Profiles whose config could name the artifact's source: the artifact's own
/// profile plus every profile with a config overlay, minus the always-safe
/// `dev` and `test`. The destination's own overlay is skipped (it names the
/// target), but a manifest that names the destination as the source stays.
fn source_candidates(
    artifact_profile: Option<&str>,
    configured: &[String],
    destination: &str,
) -> Vec<String> {
    let destination = migrate::canonical_profile(destination);
    let mut candidates: Vec<String> = artifact_profile
        .map(str::to_owned)
        .into_iter()
        .chain(
            configured
                .iter()
                .filter(|p| migrate::canonical_profile(p) != destination)
                .cloned(),
        )
        .filter(|p| !super::is_safe_destructive_profile(p))
        .collect();
    candidates.sort();
    candidates.dedup();
    candidates
}

/// The first `(profile, database)` where a declared URL is a write target.
fn overwritten_source(
    declared: &[(String, Vec<String>)],
    targets: &[(String, String)],
    env: &dyn Fn(&str) -> Option<String>,
) -> Option<(String, String)> {
    declared.iter().find_map(|(profile, urls)| {
        urls.iter().find_map(|declared_url| {
            targets
                .iter()
                .find(|(_, url)| same_database_in(declared_url, url, env))
                .map(|(_, url)| (profile.clone(), parsed_db_name(url)))
        })
    })
}

/// Refuse to scrub a database that a **config file** declares for a
/// production-ish profile — the "I pointed staging at the production URL"
/// mistake the profile guard alone cannot see.
///
/// Every non-dev/test profile with an `autumn-<profile>.toml` in the project is
/// checked, not just the one an artifact's manifest names. A bare `.dump`/`.sql`
/// artifact carries no manifest at all, so keying the guard off known provenance
/// would silently skip it in exactly the case where the operator knows least
/// about what they are restoring. The destination profile is not a source: its
/// own overlay names the target by definition.
///
/// A profile's control URL and every shard URL are compared, because a restore
/// writes control plus every shard.
///
/// Deliberately reads only `autumn.toml` / `autumn-<profile>.toml`, never the
/// environment for URLs: an env-provided `DATABASE_URL` is shared by every
/// profile resolution, so consulting it would make this guard fire on
/// legitimate scrubs.
///
/// It has its own waiver (`--allow-source-overwrite`) rather than riding on
/// `--force`: the documented staging drill ALWAYS passes `--force` (staging is
/// not `dev`/`test`), so a guard that `--force` waived would be inert in exactly
/// the workflow it exists for.
/// The guard skips the config overlay of `destination_profile`. That overlay
/// names the database you scrub. The artifact profile is always checked.
fn guard_configured_source(
    artifact_profile: Option<&str>,
    destination_profile: &str,
    project_root: &Path,
    targets: &[(String, String)],
    allowed: bool,
) -> Result<(), ScrubError> {
    if allowed {
        return Ok(());
    }
    let candidates = source_candidates(
        artifact_profile,
        &profiles_with_config(project_root),
        destination_profile,
    );
    let mut declared: Vec<(String, Vec<String>)> = Vec::new();
    for profile in candidates {
        let table = migrate::read_autumn_toml_table_with_profile_in(project_root, Some(&profile));
        let control = migrate::resolve_primary_database_url_from_sources(
            |_| Err(std::env::VarError::NotPresent),
            table.as_ref(),
        );
        // A shard list that does not resolve cannot be compared. Refuse rather
        // than treat it as "no shards".
        let shards = migrate::try_resolve_shard_database_urls_from_sources(
            |_| Err(std::env::VarError::NotPresent),
            table.as_ref(),
        )
        .map_err(|detail| ScrubError::Config {
            path: format!("autumn-{profile}.toml"),
            detail,
        })?;
        let urls: Vec<String> = control
            .into_iter()
            .chain(shards.into_iter().map(|(_, url)| url))
            .collect();
        // A libpq `service` names its host and port in a file this guard does
        // not read. Refuse rather than model it as the default local endpoint.
        // The ambient `PGSERVICE` applies to a string that names none.
        let ambient_service =
            !urls.is_empty() && std::env::var("PGSERVICE").is_ok_and(|service| !service.is_empty());
        if ambient_service || urls.iter().any(|url| uses_libpq_service(url)) {
            return Err(ScrubError::SourceScan {
                detail: format!(
                    "the {profile:?} profile uses a libpq `service`, whose host the source \
                     guard cannot resolve; pass --allow-source-overwrite to continue"
                ),
            });
        }
        if !urls.is_empty() {
            declared.push((profile, urls));
        }
    }
    // A target that names a `service` hides its host the same way.
    if !declared.is_empty() && targets.iter().any(|(_, url)| uses_libpq_service(url)) {
        return Err(ScrubError::SourceScan {
            detail: "a restore target uses a libpq `service`, whose host the source guard \
                     cannot resolve; pass --allow-source-overwrite to continue"
                .to_owned(),
        });
    }
    match overwritten_source(&declared, targets, &|key| std::env::var(key).ok()) {
        Some((profile, database)) => {
            Err(ScrubError::OverwritesConfiguredTarget { profile, database })
        }
        None => Ok(()),
    }
}

/// Profile names that have an `autumn-<profile>.toml` overlay in the project.
fn profiles_with_config(project_root: &Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(project_root) else {
        return Vec::new();
    };
    let mut out: Vec<String> = entries
        .filter_map(Result::ok)
        .filter_map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            name.strip_prefix("autumn-")
                .and_then(|rest| rest.strip_suffix(".toml"))
                .map(str::to_owned)
        })
        .filter(|p| !p.is_empty())
        .collect();
    out.sort();
    out.dedup();
    out
}

/// The database name in a connection URL, for credential-safe reporting.
fn parsed_db_name(url: &str) -> String {
    url::Url::parse(url)
        .ok()
        .and_then(|u| {
            u.path_segments()
                .and_then(|mut s| s.next())
                .map(str::to_owned)
        })
        .filter(|n| !n.is_empty())
        .unwrap_or_else(|| "<unknown>".to_owned())
}

// ─── Reporting ──────────────────────────────────────────────────────────────

/// A paste-ready `scrub.toml` fragment declaring every unclassified column, so
/// adopting the command on an existing schema is one copy away.
fn suggested_config_stanza(unclassified: &[String]) -> String {
    use std::fmt::Write as _;

    let mut by_table: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for entry in unclassified {
        if let Some((table, column)) = entry.split_once('.') {
            by_table.entry(table).or_default().push(column);
        }
    }
    let mut out = String::from(
        "# Paste into scrub.toml, then replace `auto` with an explicit strategy\n\
         # (email/name/phone/redact/null/uuid/bytes/json/zero/epoch), or move the\n\
         # column into that table's `safe = [...]` list if it holds no PII.\n",
    );
    for (table, columns) in by_table {
        let _ = write!(out, "\n[tables.{table}.pii]\n");
        for column in columns {
            let _ = writeln!(out, "{column} = \"auto\"");
        }
    }
    out
}

// ─── Entry point ────────────────────────────────────────────────────────────

/// Entry point for `autumn db scrub`. Prints a credential-safe message and exits
/// non-zero on failure.
pub fn run(args: &ScrubArgs) {
    eprintln!("\u{1F342} autumn db scrub\n");
    if let Err(e) = scrub(args) {
        eprintln!("\u{2717} {e}");
        if let ScrubError::Unclassified { columns } = &e {
            // stdout, not stderr: the diagnostics above are stderr, so
            // `autumn db scrub --check 2>/dev/null >> scrub.toml` appends a
            // valid stanza instead of a wall of interleaved prose.
            println!("{}", suggested_config_stanza(columns));
        }
        std::process::exit(1);
    }
}

fn scrub(args: &ScrubArgs) -> Result<(), ScrubError> {
    let profile = migrate::effective_profile(args.profile.as_deref());
    let writes = !args.check && !args.dry_run;
    if writes {
        guard_scrub_target(&profile, args.force)?;
    }

    // Everything that does NOT need the database is resolved first, so a typo in
    // `scrub.toml`, an unknown strategy, a `purge` entry naming a user table, or
    // an unparsable model file fails BEFORE an `--artifact` restore writes real
    // data into the target. Only schema-dependent refusals can land after it.
    let sources = load_source_classification(args)?;

    let mut targets = super::backup::resolve_all_target_urls(args.profile.as_deref())?;
    let configured = targets.len();
    // Decided before an `--artifact` restore writes anything, so a refusal
    // never lands after real data is in the target.
    let on_sqlite = sqlite::check_targets(args, &targets)?;

    let restored = if let Some(artifact) = &args.artifact {
        let artifact_profile = super::backup::artifact_source_profile(artifact);
        // `--check`/`--dry-run` promise to write nothing, and a restore is the
        // largest write there is. clap already rejects the combination; this
        // keeps the invariant true inside the function that relies on it.
        debug_assert!(
            writes,
            "--check/--dry-run must never reach an artifact restore"
        );
        eprintln!(
            "  \u{2139} Artifact provenance: {}.",
            artifact_profile.as_deref().map_or_else(
                || "unknown (no manifest)".to_owned(),
                |p| format!("{p:?} profile")
            )
        );
        // Only the targets the restore will write matter to the guard. A local
        // artifact names them up front; an offsite one is resolved later, so
        // every configured target counts.
        let guarded = super::backup::artifact_labels(artifact).map_or_else(
            || targets.clone(),
            |labels| restored_targets(targets.clone(), &labels),
        );
        // `--output` backs up every configured target, so a partial artifact
        // would package databases the scrub never touched.
        refuse_partial_output(args, guarded.len(), configured)?;
        guard_configured_source(
            artifact_profile.as_deref(),
            &profile,
            Path::new("."),
            &guarded,
            args.allow_source_overwrite,
        )?;
        eprintln!(
            "\u{2500}\u{2500} restoring {} \u{2500}\u{2500}",
            artifact.display()
        );
        let restored_labels = super::backup::restore(&super::backup::RestoreArgs {
            artifact: artifact.clone(),
            profile: args.profile.clone(),
            force: args.force,
            shard: None,
            offsite: false,
        })?;
        // Scrub only what the restore wrote. A partial artifact leaves the
        // other configured shards live, and they are not ours to anonymize.
        targets = restored_targets(targets, &restored_labels);
        refuse_partial_output(args, targets.len(), configured)
            .inspect_err(|_| warn_unscrubbed())?;
        if targets.is_empty() {
            warn_unscrubbed();
            return Err(ScrubError::SourceScan {
                detail: "the restore reported no target it wrote to".to_owned(),
            });
        }
        true
    } else {
        false
    };

    // The classification that remains reads the schema the restore just created,
    // so it cannot run earlier — and a refusal here leaves the artifact's real
    // data in the target. Say so in the loudest possible terms.
    let applied = if on_sqlite {
        sqlite::classify_and_apply(args, &profile, &targets, &sources)
    } else {
        classify_and_apply(args, &profile, &targets, &sources)
    };
    applied.inspect_err(|_| {
        if restored {
            warn_unscrubbed();
        }
    })
}

/// Say that a failed run left restored, unscrubbed data in the target.
fn warn_unscrubbed() {
    eprintln!(
        "\n\u{26A0}\u{FE0F}  The artifact was ALREADY RESTORED before this failure, so \
         the target database now holds UNSCRUBBED data.\n  \
         Do not hand it to anyone: fix the problem below and re-run the same \
         command, or drop the database."
    );
}

/// The classification inputs that come from files rather than from the database.
struct SourceClassification {
    config: ScrubConfig,
    encrypted: BTreeMap<String, BTreeMap<String, bool>>,
    anonymize: BTreeSet<String>,
    /// Parsed `--sample` roots. Empty means the whole copy is kept.
    roots: Vec<sample::SampleSpec>,
}

/// Read and validate every file-based classification source, reporting what each
/// one contributed.
///
/// The counts are printed rather than assumed: both automatic sources degrade to
/// empty when the command runs outside the project root (a deployed staging host
/// often has the binary and `scrub.toml` but no source tree), and a silently
/// empty `#[encrypted]` map would also silently disable the "a `safe`
/// declaration may not override `#[encrypted]`" refusal.
fn load_source_classification(args: &ScrubArgs) -> Result<SourceClassification, ScrubError> {
    let config = load_config(args.config.as_deref())?;
    check_purge_list(&config)?;
    let project_root = Path::new(".");
    let has_sources = project_root.join("src").is_dir();
    let declared_encrypted = config
        .tables
        .iter()
        .any(|(_, rule)| !rule.encrypted.is_empty());

    // Without the model source there is no way to know WHICH columns are
    // `#[encrypted]`, and an unknown one is the worst possible outcome: declared
    // `safe` it keeps production ciphertext, given a plaintext strategy it
    // becomes permanently unreadable. So this is a refusal, not a warning —
    // unless the declaration names them (and their mode) itself.
    if !has_sources && !declared_encrypted {
        return Err(ScrubError::EncryptedMetadataUnavailable);
    }

    let mut encrypted = encrypted_columns(project_root)?;
    // A declaration supplements the model scan (and supplies everything when
    // there is no model source at all); the model stays authoritative where the
    // two overlap, since it is the definition rather than a copy of it.
    for (table, rule) in &config.tables {
        for (column, mode) in &rule.encrypted {
            encrypted
                .entry(table.clone())
                .or_default()
                .entry(column.clone())
                .or_insert_with(|| mode.is_deterministic());
        }
    }
    let anonymize = scan_anonymize_tables(&project_root.join("src"))?;

    let encrypted_count: usize = encrypted.values().map(BTreeMap::len).sum();
    eprintln!(
        "  \u{2139} Automatic classification: {encrypted_count} #[encrypted] column(s), \
         {} GDPR anonymize registration(s).",
        anonymize.len()
    );

    // Parsed here rather than at the call site so a mistyped `--sample` fails
    // alongside every other file-based refusal: BEFORE an `--artifact` restore
    // writes real data into the target.
    let roots = args
        .sample
        .iter()
        .map(|spec| sample::parse_spec(spec))
        .collect::<Result<Vec<_>, _>>()?;
    if roots.is_empty() && sources_declare_sampling(&config) {
        eprintln!(
            "  \u{2139} scrub.toml declares [sample] rules, but no --sample root was \
             given \u{2014} the whole copy is kept."
        );
    }

    Ok(SourceClassification {
        config,
        encrypted,
        anonymize,
        roots,
    })
}

/// Whether `scrub.toml` carries any `[sample]` rule at all.
const fn sources_declare_sampling(config: &ScrubConfig) -> bool {
    !config.sample.always_include.is_empty() || !config.sample.never_include.is_empty()
}

/// Classify every target, then — only once every target has classified cleanly —
/// apply the statements.
///
/// The two passes are deliberate and mirror how `autumn db restore` verifies
/// every artifact before touching any database: with a control database plus
/// shards, a single-pass loop would scrub the control database and only then
/// discover that a shard has an undeclared column, leaving the topology half
/// anonymized.
#[allow(clippy::too_many_lines)]
fn classify_and_apply(
    args: &ScrubArgs,
    profile: &str,
    targets: &[(String, String)],
    sources: &SourceClassification,
) -> Result<(), ScrubError> {
    // ── Pass 1: classify everything ─────────────────────────────────────────
    let mut plans = Vec::with_capacity(targets.len());
    for (label, url) in targets {
        let facts = probe_database_facts(url, label, &sources.config)?;

        // A universe the classifier never looked at cannot be reported clean.
        if !facts.other_schemas.is_empty() {
            return Err(ScrubError::UnsupportedSchemas {
                schemas: facts.other_schemas.iter().cloned().collect(),
            });
        }

        let tables = introspect::introspect_postgres(url).map_err(|e| ScrubError::Introspect {
            label: label.clone(),
            detail: e.to_string(),
        })?;

        // A table the connecting role cannot see is absent from the classified
        // universe, and "not classified" must never read as "clean".
        let unreachable = unreachable_tables(&facts, &tables);
        if !unreachable.is_empty() {
            return Err(ScrubError::InaccessibleTables {
                tables: unreachable,
            });
        }

        // Before the sample is planned, not after. An inheritance child has no
        // foreign key of its own — legacy `INHERITS` does not carry constraints
        // down — so the coverage check would otherwise report it as unreachable
        // and advise naming it as a root, which is precisely the arrangement
        // that corrupts. Only the sample is refused: the column rewrites are
        // per-row UPDATEs that reach the child's rows correctly either way.
        if !args.sample.is_empty() && !facts.legacy_inheritance.is_empty() {
            return Err(ScrubError::LegacyInheritance {
                tables: facts.legacy_inheritance,
            });
        }
        // A view whose order cannot be DERIVED at all, because its definition
        // calls a function whose body PostgreSQL does not track. Refused before
        // the reachability check below, which can only compare two lists built
        // from a graph this shape is missing from entirely.
        if !facts.views_reading_by_name.is_empty() {
            return Err(ScrubError::ViewReadsRelationsByName {
                views: facts.views_reading_by_name,
            });
        }
        if !facts.untraceable_view_functions.is_empty() {
            return Err(ScrubError::UntraceableViewFunction {
                views: facts.untraceable_view_functions,
            });
        }
        // A view the dependency walk never reached is one the run cannot
        // refresh, and an unrefreshed view keeps its pre-scrub rows. Detected by
        // comparing the ordered list against the flat enumeration rather than by
        // knowing the walk's depth limit, so it stays true if that limit moves.
        //
        // Measured on a 36-deep chain: the run refreshed 33 views, reported
        // success, left `users` with 0 original addresses — and the deepest view
        // still held all 200. That is a silent leak, so it is refused instead.
        let mut unreachable_views: Vec<String> = facts
            .all_materialized_views
            .iter()
            .filter(|view| !facts.materialized_views.contains(view))
            .cloned()
            .collect();
        if !unreachable_views.is_empty() {
            unreachable_views.sort();
            return Err(ScrubError::UnrefreshableViews {
                views: unreachable_views,
            });
        }
        let plan = build_plan(&ClassificationInputs {
            tables: &tables,
            config: &sources.config,
            encrypted: &sources.encrypted,
            anonymize_tables: &sources.anonymize,
            facts: &facts,
        })?;

        // Resolved in the same pass as the classification, and before ANY
        // target is written, so a graph gap on one shard cannot leave the rest
        // of the topology sampled.
        let sampling = if sources.roots.is_empty() {
            None
        } else {
            Some(build_sample_plan_for(args, sources, &tables, &facts)?)
        };

        // RLS makes an `UPDATE` silently apply to policy-visible rows only,
        // which is a fail-OPEN in a fail-closed tool — refuse rather than
        // report a partial scrub as complete.
        // Purge targets are framework tables, which are excluded from
        // `plan.tables` — so without them an RLS-protected job/token/sync table
        // would have its `DELETE` silently apply to policy-visible rows only,
        // and still be reported emptied.
        // The sample's tables are the third class of write, and the one a
        // column-level plan can never cover: a pure join table has no PII
        // column (PII on a key is refused outright), so it is absent from
        // `plan.tables` — yet the sample deletes from it, and reads it to
        // decide what to keep. Under RLS both would see policy-visible rows
        // only, and the run would report a table emptied that is not.
        let mut rls: Vec<String> = plan
            .tables
            .iter()
            .map(|t| t.table.clone())
            .chain(
                purge_statements(&facts.framework_tables, &sources.config)
                    .into_iter()
                    .map(|(table, _)| table),
            )
            .chain(
                sampling
                    .iter()
                    .flat_map(sample::SamplePlan::locked_tables)
                    .map(str::to_owned),
            )
            .filter(|t| facts.rls_tables.contains(t))
            .collect();
        rls.sort();
        rls.dedup();
        if !rls.is_empty() {
            return Err(ScrubError::RowLevelSecurity { tables: rls });
        }

        // Before any hazard check that reads `tgenabled` or `ev_enabled`: in
        // replica mode those columns mean the opposite of what the checks
        // assume, so their answers cannot be trusted at all.
        if facts.replication_role != "origin" {
            return Err(ScrubError::ReplicaSessionRole {
                role: facts.replication_role,
            });
        }

        // The emptying pass runs LAST — after every column rewrite — because
        // that is the only order in which "this table ends up empty" survives a
        // rewrite trigger re-filling it. The cost is that its own `DELETE`
        // triggers fire after everything else: an archive trigger on a purged
        // or `never_include` table can copy the rows it is removing into an
        // ordinary classified table whose rewrite has already run, and the
        // verification that follows counts these tables rather than tracing
        // where their triggers wrote. There is no order that satisfies both —
        // the trigger graph can be cyclic — and no postcondition to check
        // instead, because a trigger body can write anywhere. So it is refused
        // before anything is written.
        let mut emptying_triggers: Vec<String> =
            purge_statements(&facts.framework_tables, &sources.config)
                .into_iter()
                .map(|(table, _)| table)
                .chain(
                    sampling
                        .iter()
                        .flat_map(|s| s.emptied_tables())
                        .map(|(table, _)| table.to_owned()),
                )
                .filter(|t| facts.delete_triggered_tables.contains(t))
                .collect();
        emptying_triggers.sort();
        emptying_triggers.dedup();
        if !emptying_triggers.is_empty() {
            return Err(ScrubError::EmptyingTriggerLeak {
                tables: emptying_triggers,
            });
        }

        report_plan(label, &plan);
        report_framework_tables(&facts.framework_tables, &sources.config);
        report_triggers(
            &plan,
            &purge_statements(&facts.framework_tables, &sources.config),
            sampling.as_ref(),
            &facts,
        );
        if let Some(sampling) = &sampling {
            report_sample_plan(label, sampling);
        }
        plans.push((label, url, plan, facts, sampling));
    }

    if args.check {
        eprintln!(
            "\n\u{2713} Every column in `public` is classified \u{2014} no unclassified data can leak."
        );
        if !sources.roots.is_empty() {
            eprintln!(
                "\u{2713} Every table is covered by the sample \u{2014} no table would be \
                 emptied unannounced."
            );
        }
        return Ok(());
    }
    if args.dry_run {
        // Refuse before printing anything, if any target's boundary cannot be
        // emitted. The alternative — a comment saying "connect yourself" above
        // a BEGIN and a page of DELETEs — reads as advice and behaves as a
        // loaded gun: pasted, it runs against whatever database the session is
        // already on. Fail closed here, like every other promise in this
        // command that cannot be arranged safely.
        let unprintable: Vec<String> = plans
            .iter()
            .filter(|(_, url, _, _, _)| password_free_conninfo(url).is_none())
            .map(|(label, _, _, _, _)| (*label).clone())
            .collect();
        if !unprintable.is_empty() {
            return Err(ScrubError::UnprintableTarget {
                targets: unprintable,
            });
        }
        // And refuse, the same way, if any target rewrites an #[encrypted]
        // column. That rewrite has no SQL form — the replacement is sealed per
        // row under the target's key — so the script could only be printed with
        // that one statement missing, and a script missing its rewrites empties
        // and samples exactly as advertised while leaving every kept row's
        // production ciphertext in place. Measured: pasting such a script left
        // `users` sampled 200 -> 100 with every address rewritten AND all 100
        // kept rows still holding their original ciphertext, committed without
        // an error.
        //
        // A marker in the stream does not close this. A `RAISE EXCEPTION` aborts
        // its own transaction, and that much works — the deletes below it are
        // refused. But the `COMMIT` this script prints turns the abort into a
        // ROLLBACK and clears the state, and measured on psql 16.13 the pasted
        // lines after it run: the out-of-transaction `VACUUM (FULL)`s, then the
        // next target's `\connect` and its whole block. On two clusters, a
        // stopped first target still took the second from 200 comments to 0,
        // committed. `\quit` is not an answer either: psql exits and the rest
        // of the paste is read by the shell that launched it, which executed a
        // trailing `echo` in the same measurement. Fail closed instead, exactly
        // as above: the plan is still reported in full, only the runnable script
        // is withheld.
        // And refuse for a profile this command will not scrub. `writes` is
        // false for a dry run, so `guard_scrub_target` never ran — harmless
        // when the dry run only described a plan, and not harmless now that it
        // prints a paste-ready script whose `\connect` names the protected
        // target. Measured: `--dry-run --profile production` printed 14
        // runnable lines, including that `\connect`, for a database the same
        // command refuses to touch without `--force`.
        guard_scrub_target(profile, args.force).map_err(|_| {
            ScrubError::UnprintableProductionTarget {
                profile: profile.to_owned(),
            }
        })?;
        // And refuse a socket target outright, because no value the server
        // reports identifies the instance behind a socket. Address and port are
        // NULL there by construction; `system_identifier` is copied by any
        // physical clone; the configured port is shared by two clusters on
        // different socket directories; and `data_directory` is server-LOCAL,
        // so two containers each answering `/var/lib/postgresql/data` match on
        // it while being different databases. Three narrower guards were each
        // defeated by the next topology, which is the shape of a value that
        // does not exist rather than one not yet found. Measured on two
        // clusters sharing port 5433: the clone's script pasted at its origin,
        // guard passed, COMMIT, origin 200 users -> 25.
        let mut ambiguous: Vec<String> = plans
            .iter()
            .filter(|(_, _, _, facts, _)| {
                let e = &facts.endpoint;
                e.address.is_none() && e.port.is_none()
            })
            .map(|(label, _, _, _, _)| (*label).clone())
            .collect();
        ambiguous.sort();
        if !ambiguous.is_empty() {
            return Err(ScrubError::UnprintableAmbiguousTarget { targets: ambiguous });
        }
        // And refuse a TCP target whose conninfo leaves the port to libpq. The
        // reconnect proof pins psql's own `:PORT`, and psql reports the RESOLVED
        // port — measured, the same host-only URI reports 5433 under
        // `PGPORT=5433` and 5432 without it. Accepting any port for the host
        // would drop the discriminator on exactly the pair of servers this proof
        // exists to tell apart; asserting a port this run computed itself would
        // mean replicating libpq's resolution, which can read a service file
        // this command does not. Neither is honest, so it refuses instead.
        let mut portless: Vec<String> = plans
            .iter()
            .filter(|(_, url, _, _, _)| {
                password_free_conninfo(url)
                    .is_some_and(|conninfo| stated_host_and_port(&conninfo).1.is_none())
            })
            .map(|(label, _, _, _, _)| (*label).clone())
            .collect();
        portless.sort();
        if !portless.is_empty() {
            return Err(ScrubError::UnprintablePortlessTarget { targets: portless });
        }
        // Same reasoning, one parameter over: `hostaddr` picks the endpoint on
        // its own. Measured, `host=not-a-real-host.example hostaddr=127.0.0.1`
        // reaches 127.0.0.1 while psql still reports that unresolvable name as
        // `:HOST`, and there is no `:HOSTADDR` to pin in its place — `\echo
        // [:HOSTADDR]` prints the name back unexpanded. Two such targets can
        // therefore agree on every term the proof can state and still be
        // different servers.
        let mut addressed: Vec<String> = plans
            .iter()
            .filter(|(_, url, _, _, _)| {
                password_free_conninfo(url).is_some_and(|c| endpoint_can_come_from_elsewhere(&c))
            })
            .map(|(label, _, _, _, _)| (*label).clone())
            .collect();
        addressed.sort();
        if !addressed.is_empty() {
            return Err(ScrubError::UnprintableHostaddrTarget { targets: addressed });
        }
        // And a target naming more than one endpoint. The sizing connection and
        // the pasting session are separate draws, so the printed `LIMIT` can be
        // computed on a different member than the script runs against —
        // measured, ten dry runs against a two-member URI printed `LIMIT 2` six
        // times and `LIMIT 0` four times, and `LIMIT 0` makes the delete pass
        // empty the root instead of sampling it.
        let mut multi: Vec<String> = plans
            .iter()
            .filter(|(_, url, _, _, _)| {
                password_free_conninfo(url).is_some_and(|c| states_multiple_endpoints(&c))
            })
            .map(|(label, _, _, _, _)| (*label).clone())
            .collect();
        multi.sort();
        if !multi.is_empty() {
            return Err(ScrubError::UnprintableMultiHostTarget { targets: multi });
        }
        let mut encrypted_rewrites: Vec<String> = plans
            .iter()
            .flat_map(|(label, _, plan, _, _)| {
                plan.tables.iter().flat_map(move |table| {
                    table
                        .encrypted
                        .iter()
                        .map(move |rewrite| format!("{label}: {}.{}", table.table, rewrite.column))
                })
            })
            .collect();
        encrypted_rewrites.sort();
        if !encrypted_rewrites.is_empty() {
            return Err(ScrubError::UnprintableEncryptedRewrite {
                columns: encrypted_rewrites,
            });
        }
        // Printed in the order `execute` runs them: purges, then the sample,
        // then the rewrites — and, like `execute`, holding back the purges the
        // plan defers until after the sample. The order is load-bearing (a
        // framework-owned table is emptied before the sample removes the rows
        // it points at, except where the sample must empty its child first), so
        // a reader auditing the dry run has to see the real sequence: printing
        // a deferred purge early would show SQL that fails if it were run.
        //
        // The BEGIN/COMMIT is part of that sequence, not decoration. `execute`
        // runs all of this in one transaction, and the sample's keep-sets are
        // `CREATE TEMPORARY TABLE ... ON COMMIT DROP`: pasted into psql's
        // autocommit, each one would be committed and dropped before the seed
        // INSERT that follows it. Without the envelope the advertised "exact
        // SQL" is not runnable.
        // Non-interactive is the supported way to run this, and there a failed
        // `\connect` already stops processing. This makes every OTHER error stop
        // it too, which a stream of destructive blocks wants. It does nothing for
        // an interactive paste — measured, psql ignores it there — which is what
        // the per-target guard below is for.
        // Size every sampled target BEFORE printing a line. Sizing opens its own
        // connection and reads live counts, so it is the one fallible step left
        // in the emission loop — and a failure on a LATER target used to land
        // after an EARLIER one's complete block, `COMMIT` included. Measured on
        // a control plus one shard where the role could read the catalogs but
        // not `SELECT` the shard's `users`: the run exited 1 with `permission
        // denied for table users`, having already printed the control's whole
        // transaction (one `COMMIT`, seven `DELETE FROM`). Saving that output
        // and running it scrubs the control and leaves the shard untouched —
        // the half-anonymized topology this function's two passes exist to
        // prevent, reached through the one fallible call that had not moved
        // into pass 1.
        let mut sized: Vec<Option<BTreeMap<String, i64>>> = Vec::with_capacity(plans.len());
        for (label, url, _, _, sampling) in &plans {
            sized.push(match sampling {
                Some(plan) => {
                    let mut conn = probe_connection(url, label, "size the sample")?;
                    Some(
                        sample::source_counts(&mut conn, plan)
                            .map_err(|e| ScrubError::Sql(e.to_string()))?,
                    )
                }
                None => None,
            });
        }
        eprintln!("  \\set ON_ERROR_STOP on");
        // One flag for the whole stream: "everything so far succeeded, and the
        // last block was on the target it named". `execute` returns on the first
        // target that fails and never touches the rest, so the script must not
        // either — measured, without this the next target's `\connect` and its
        // whole destructive block ran after an earlier target rolled back,
        // leaving a partially scrubbed topology and a stream that ends without
        // an error. Nested `\if` carries it: a target whose block is skipped
        // never reaches the `\gset` that would set the flag true again, so one
        // failure skips every target after it.
        eprintln!("  \\set autumn_ok true");
        for (index, (label, url, plan, facts, sampling)) in plans.iter().enumerate() {
            let no_deferral = BTreeSet::new();
            let deferred: &BTreeSet<String> =
                sampling.as_ref().map_or(&no_deferral, |s| &s.purge_after);
            let purges = purge_statements(&facts.framework_tables, &sources.config);
            let phases = emptying_phases(&purges, deferred, sampling.as_ref());
            // Each target is a DIFFERENT database, and the printed stream is one
            // file. Without a boundary, pasting it runs every target's
            // transaction against whichever database the session happens to be
            // connected to — sampling one of them repeatedly, with row counts
            // taken from the others, and leaving the rest untouched.
            // Gate the WHOLE block, `\connect` included: an earlier target
            // that rolled back must not be followed by this one connecting and
            // scrubbing anyway.
            eprintln!("  \\if :autumn_ok");
            for line in psql_connect(label, url) {
                eprintln!("  {line}");
            }
            // And prove the reconnect landed where it was aimed, before the
            // BEGIN below. This reads psql's own view of the connection, which
            // the server's answers cannot stand in for — see
            // `psql_connection_assertion`.
            if let Some(conninfo) = password_free_conninfo(url) {
                for line in psql_connection_assertion(&conninfo, &facts.endpoint.database) {
                    eprintln!("  {line}");
                }
            }
            // Reset per target: a previous target's success must not vouch for
            // this one. `\gset` leaves a variable untouched when its query
            // fails, so this explicit `false` is what survives an aborted
            // transaction.
            eprintln!("  \\set autumn_scrubbed false");
            eprintln!("  BEGIN;");
            // The same session pins `execute` sets, before anything reads or
            // writes: without them a role-level `search_path` resolves the
            // generated calls somewhere else entirely. They come before the
            // guard for that reason — the guard is `pg_catalog`-qualified too,
            // but a pin that only lands after the check it protects is not a
            // pin. `SET LOCAL` writes nothing, so nothing destructive precedes
            // the proof below.
            for statement in session_settings() {
                eprintln!("  {statement};");
            }
            // The precondition the run refuses to plan without, asserted here
            // because the pasting session brings its own — see
            // `replication_role_assertion`.
            eprintln!("  {}", replication_role_assertion());
            // Inside the transaction, so a `\connect` that silently failed
            // aborts this block instead of running it against the previous
            // target. Before every destructive statement: nothing may run until
            // the session has proved it is where this block thinks it is.
            eprintln!("  {}", target_guard(&facts.endpoint));
            // The same locks `execute` takes, before any destructive statement:
            // without them a pasted run lets a concurrent insert land after the
            // DELETE that was supposed to remove it.
            for statement in lock_statements(plan, &purges, sampling.as_ref()) {
                eprintln!("  {statement};");
            }
            for (_, statement) in &phases.before {
                eprintln!("  {statement};");
            }
            if let Some(sampling) = sampling {
                report_sample_sql(sampling, sized[index].as_ref());
            }
            for (_, statement) in &phases.after_sample {
                eprintln!("  {statement};");
            }
            // No `table.encrypted` arm here: a plan with any encrypted rewrite
            // is refused above, before a line of this script is printed.
            for table in &plan.tables {
                if let Some(sql) = &table.sql {
                    eprintln!("  {sql};");
                }
            }
            // Last, exactly as `execute` runs it: the pass that makes "emptied"
            // true even if a rewrite trigger just re-filled one of these tables.
            for (_, statement) in &phases.final_pass {
                eprintln!("  {statement};");
            }
            // The emptying statements above fire triggers, and one can refill a
            // table an earlier one emptied. `execute` counts them all and rolls
            // back; the printed sequence has to do the same, or an operator who
            // runs it commits exactly the rows the real command refuses.
            // Last inside the transaction, exactly where `execute` runs them: a
            // materialized view keeps its own physical copy of whatever it
            // selected, so a script that skips this leaves the view's heap
            // holding the pre-scrub rows — including the PII just removed from
            // the base tables it reads. In dependency order, so a view over
            // another is rebuilt from the refreshed one rather than the stale
            // one. Inside the envelope like the rest, so a refresh the role may
            // not run rolls the rewrites back instead of committing base tables
            // a stale view contradicts.
            for view in &facts.materialized_views {
                eprintln!("  REFRESH MATERIALIZED VIEW {};", qualified_ident(view));
            }
            // And the same closing pass `execute` runs, in the same position:
            // every view that had no data when the run probed ends with none,
            // whether it was populated for a dependent or skipped entirely.
            for view in &facts.unpopulated_views {
                eprintln!(
                    "  REFRESH MATERIALIZED VIEW {} WITH NO DATA;",
                    qualified_ident(view)
                );
            }
            // And the emptiness proof, after every write in the block — the
            // refreshes included, because a view's query can call a function
            // that INSERTs into a table this run promised would be empty.
            // `execute` checks in exactly this position and rolls back; the
            // printed sequence has to, or an operator who runs it commits
            // exactly the rows the real command refuses.
            for (table, _) in &phases.final_pass {
                eprintln!("  {};", emptiness_assertion(table));
            }
            // And the sample's own postconditions, in the position
            // `verify_sample_survived_refreshes` runs in the executed path —
            // after every write in the block, the refreshes included, because
            // a view's query can call a function that INSERTs into a sampled
            // table. The dry run advertised the same "exact SQL" without
            // this, and a pasted script committed a subset the real command
            // rolls back. See `sample_postcondition_statements`.
            if let Some(sampling) = sampling {
                for (statement, comment) in sample_postcondition_statements(sampling) {
                    eprintln!("  {statement}; -- {comment}");
                }
            }
            // The last statement inside the transaction, and the whole reason
            // the compaction below can tell a scrubbed target from an aborted
            // one. In an aborted transaction this SELECT is refused like every
            // other, so `\gset` assigns nothing and the `false` above stands.
            eprintln!("  SELECT true AS autumn_scrubbed \\gset");
            eprintln!("  COMMIT;");
            // Whether this target actually scrubbed, recorded for the
            // compaction pass that follows every target's block. Emitted for
            // EVERY target, not only a sampled one: the flag is also what
            // carries a failure forward, and a target with nothing to compact
            // still has to say whether it succeeded.
            for line in post_commit_fence(&facts.endpoint) {
                eprintln!("  {line}");
            }
            // Closes the `\if :autumn_ok` the connection assertion opened, then
            // the one this target opened.
            eprintln!("  \\endif");
            eprintln!("  \\endif");
        }
        // Compaction comes after EVERY target's transaction, never between two
        // of them, because that is where `classify_and_apply` runs it: it
        // commits each target in one loop and then compacts in a second, where
        // a failure is a warning and the next target is compacted anyway.
        //
        // Printed inside the per-target block it was neither. Measured on two
        // TCP targets with `ON_ERROR_STOP on` — the supported non-interactive
        // way to run this — a `VACUUM (FULL, ANALYZE)` on the first target that
        // timed out against a concurrent reader ended the script at rc=3: the
        // first database was scrubbed and sampled (2 users, 0 original
        // addresses) and the SECOND still held all 200 of its own, from a
        // failure the command itself only warns about.
        //
        // Guarded as a whole on `:autumn_ok`, which matches the executor again:
        // it propagates the first `execute` failure with `?`, so a later
        // target's failure means no earlier target is compacted either.
        let sampled: Vec<_> = plans
            .iter()
            .filter_map(|(label, url, _, facts, sampling)| {
                sampling.as_ref().map(|s| (label, url, facts, s))
            })
            .collect();
        if !sampled.is_empty() {
            eprintln!("  \\if :autumn_ok");
            // Warning-only from here, as in the executor: with `ON_ERROR_STOP`
            // still on, one target's failed VACUUM would skip every later
            // target's. Nothing destructive follows — these statements are
            // outside every transaction and rewrite no rows — and the per-target
            // guard below is what a failed `\connect` runs into, exactly as it
            // does above.
            eprintln!("  \\set ON_ERROR_STOP off");
            for (label, url, facts, sampling) in sampled {
                let purges = purge_statements(&facts.framework_tables, &sources.config);
                for line in psql_connect(label, url) {
                    eprintln!("  {line}");
                }
                // The same fail-closed shape the fence uses: false first, so a
                // `\gset` whose query fails cannot carry the previous target's
                // answer into this one's VACUUM statements.
                //
                // And the SAME psql proof the transaction opens with, not the
                // endpoint alone: this is a second `\connect`, with the same
                // retained-connection failure mode, and server-reported identity
                // cannot tell two clones behind colliding addresses apart. A
                // `VACUUM (FULL)` on the wrong target takes an ACCESS EXCLUSIVE
                // lock and rewrites every table it names.
                eprintln!("  \\set autumn_here false");
                eprintln!(
                    "  SELECT ({} AND NOT ({})) AS autumn_here \\gset",
                    password_free_conninfo(url).map_or_else(
                        || "false".to_owned(),
                        |conninfo| psql_connection_terms(&conninfo, &facts.endpoint.database),
                    ),
                    endpoint_mismatch(&facts.endpoint)
                );
                eprintln!("  \\if :autumn_here");
                eprintln!("  SET lock_timeout = '{COMPACT_LOCK_TIMEOUT}';");
                for table in compacted_tables(sampling, &purged_tables(&purges)) {
                    eprintln!("  VACUUM (FULL, ANALYZE) {};", qualified_ident(table));
                }
                eprintln!("  \\endif");
            }
            eprintln!("  \\endif");
        }
        eprintln!("\n\u{2713} Dry run only \u{2014} nothing was written.");
        return Ok(());
    }

    // An encrypted rewrite needs the target's key BEFORE anything is written,
    // so a missing key is a refusal rather than a half-scrubbed database.
    if plans
        .iter()
        .any(|(_, _, plan, _, _)| plan.tables.iter().any(|t| !t.encrypted.is_empty()))
    {
        let ring = resolve_key_ring(profile, Path::new("."))?;
        autumn_web::encryption::install_key_ring(ring);
    }

    // ── Pass 2: apply ───────────────────────────────────────────────────────
    //
    // Every failure from here on says which databases are already scrubbed and
    // which still hold real data — including the post-commit compaction, which
    // runs after this target has committed.
    let mut committed: Vec<&str> = Vec::new();
    let warn_committed = |committed: &[&str]| {
        if !committed.is_empty() {
            eprintln!(
                "\n\u{26A0}\u{FE0F}  Already committed before this failure: {}. \
                 Those databases ARE scrubbed; every later target is untouched and still \
                 holds real data.",
                committed.join(", ")
            );
        }
    };
    // The refreshed materialized views ride along beside the purge targets: the
    // size report has to measure them, though compaction does not touch them
    // (`REFRESH` already rewrote each one's heap).
    let mut pending_compaction: Vec<PendingCompaction<'_>> = Vec::new();
    for (label, url, plan, facts, sampling) in &plans {
        let purges = purge_statements(&facts.framework_tables, &sources.config);
        let (applied, sampled) = execute(
            url,
            plan,
            &purges,
            &ViewRefresh {
                ordered: &facts.materialized_views,
                all: &facts.all_materialized_views,
                unpopulated: &facts.unpopulated_views,
            },
            sampling.as_ref(),
            facts,
            label,
        )
        .inspect_err(|_| warn_committed(&committed))?;
        // This target is committed from here on, so a later failure must say so.
        committed.push(label);
        for (table, rows) in applied {
            eprintln!("  \u{2713} {table}: {rows} row(s) scrubbed.");
        }
        if let (Some(sampling), Some(sampled)) = (sampling.as_ref(), sampled) {
            report_sample_outcome(label, &sampled);
            pending_compaction.push((
                url.as_str(),
                label.as_str(),
                sampling,
                purged_tables(&purges),
                facts.all_materialized_views.clone(),
                sampled.size_before,
            ));
        }
    }

    // The artifact is captured BEFORE compaction, not after.
    //
    // Every lock is released at commit, so any window between committing and
    // dumping is one in which a concurrent write can land unscrubbed rows in a
    // target and have them captured into an artifact advertised as a scrubbed
    // subset. Compaction is per-table `VACUUM FULL` over the whole schema,
    // which on a large source is long — running it first would stretch that
    // window from moments to minutes. It also contributes nothing to the
    // artifact: `pg_dump` is logical, so a compacted table dumps to exactly the
    // same bytes as an uncompacted one. Compaction is about the live copy's
    // disk, so it can wait until the artifact is safely written.
    //
    // The remaining window — commit to the dump's own snapshot — is inherent to
    // dumping a database the scrub has already released, and is why the guide
    // says to scrub a restored copy rather than something still taking writes.
    if let Some(dir) = &args.output {
        eprintln!("\u{2500}\u{2500} writing a scrubbed artifact \u{2500}\u{2500}");
        super::backup::backup(&super::backup::BackupArgs {
            profile: args.profile.clone(),
            dir: Some(dir.clone()),
            format: super::backup::BackupFormat::Custom,
            keep: None,
            target: super::backup::TargetSelector::All,
            upload: false,
        })?;
    }

    // Deleting rows leaves the table files exactly as large as they were, so a
    // sample that is not compacted still needs the source's disk. This is the
    // step that makes the live subset actually laptop-sized, and it can only run
    // after the commit: VACUUM FULL rewrites each table and cannot join a
    // transaction.
    for (url, label, sampling, purged, refreshed, size_before) in pending_compaction {
        report_reclaimed_size(url, label, sampling, &purged, &refreshed, size_before);
    }

    eprintln!("\n\u{2713} Scrub complete.");
    Ok(())
}

/// Resolve the `--sample` subset for one target from the same schema snapshot
/// the column classification used.
fn build_sample_plan_for(
    args: &ScrubArgs,
    sources: &SourceClassification,
    tables: &[Table],
    facts: &DatabaseFacts,
) -> Result<sample::SamplePlan, ScrubError> {
    // A partition's rows belong to its parent, which is what the walk and the
    // deletes address — planning it separately would count and remove them
    // twice, exactly as `build_plan` skips it for the rewrites.
    let universe: Vec<(String, Vec<String>)> = tables
        .iter()
        .filter(|t| !facts.partitions.contains_key(&t.name))
        .map(|t| (t.name.clone(), t.primary_key.clone()))
        .collect();
    let framework: BTreeSet<String> = facts.framework_tables.iter().cloned().collect();
    let purged: BTreeSet<String> = purge_statements(&facts.framework_tables, &sources.config)
        .into_iter()
        .map(|(table, _)| table)
        .collect();
    Ok(sample::build_plan(&sample::SampleInputs {
        roots: &sources.roots,
        seed: args.seed,
        rules: &sources.config.sample,
        tables: &universe,
        foreign_keys: &facts.foreign_keys,
        framework_tables: &framework,
        purged: &purged,
        partitions: &facts.partitions,
    })?)
}

/// Print what the sample will select, before anything is written.
fn report_sample_plan(label: &str, plan: &sample::SamplePlan) {
    let roots: Vec<String> = plan
        .tables
        .iter()
        .filter_map(|t| match t.role {
            sample::SampleRole::Root(amount) => Some(match amount {
                sample::SampleAmount::Percent(pct) => format!("{} {pct}%", t.table),
                sample::SampleAmount::Count(n) => format!("{} {n} row(s)", t.table),
            }),
            _ => None,
        })
        .collect();
    eprintln!(
        "  \u{2139} Sampling {label} from {}, seed {} \u{2014} the same seed against the same \
         source selects the identical rows.",
        roots.join(", "),
        plan.seed,
    );
}

/// Print the statements a sample would run, for `--dry-run`.
///
/// The selection walk repeats until it stops finding related rows, so its
/// statements are shown once with that noted rather than unrolled: how many
/// passes a schema needs is a property of the data, not of the plan.
fn report_sample_sql(plan: &sample::SamplePlan, counts: Option<&BTreeMap<String, i64>>) {
    // The counts are read for EVERY target before this prints anything, so a
    // target that cannot be sized takes the whole script down before a line of
    // it exists. They are still live counts read outside the scrub's own
    // transaction, so a concurrent write can move one between this print and a
    // later real run — as it can for any dry run against a live database.
    let empty = BTreeMap::new();
    let counts = counts.unwrap_or(&empty);
    for statement in plan.setup_statements() {
        eprintln!("  {statement};");
    }
    for statement in plan.seed_statements(counts) {
        eprintln!("  {statement};");
    }
    for statement in plan.index_statements() {
        eprintln!("  {statement};");
    }
    // The walk as the loop it really is, not the statements plus a comment
    // saying to repeat them. Within a pass the statements run in list order, so
    // running them once selects only as deep as the catalog's edge order
    // happens to reach; the rows below that survive the walk but not the
    // DELETEs, and nothing catches it, because dropping a descendant leaves
    // every foreign key satisfied and every assertion below still passes.
    eprintln!("  {};", plan.walk_loop_statement().replace('\n', "\n  "));
    for statement in plan.delete_statements() {
        eprintln!("  {statement};");
    }
    for (constraint, statement) in plan.integrity_statements() {
        eprintln!(
            "  {}; -- verifies {constraint}",
            integrity_assertion(&statement)
        );
    }
    // Capture every sampled table's post-sample row count where the executor
    // captures its own `after` counts — after the deletes and the integrity
    // checks, and before the rewrites, purges and refreshes that follow in the
    // printed sequence. The printed half of `verify_sample_survived_refreshes`
    // asserts against these after the refreshes: the subset is what must
    // survive, and its size is data-dependent, so it is captured at paste
    // time rather than baked at print time.
    for statement in sample_count_capture_statements(plan) {
        eprintln!("  {statement};");
    }
}

/// Statements capturing every sampled table's post-sample row count.
///
/// The printed equivalent of the `after` snapshot in
/// `sample::apply`'s `SettledSampleCounts`: a temporary table (`ON COMMIT
/// DROP`, like the sample's own keep sets) holding `(table_index, n)` for
/// every sampled table, captured exactly where the executor captures its own
/// counts — after the deletes and the integrity checks, before everything
/// that follows in the printed sequence.
///
/// A temp table rather than `\gset` variables: psql does not interpolate
/// variables inside dollar-quoted `DO` blocks, where the assertion below
/// reads them back — and a variable per table would need a `\if`/`\else`
/// pair each, a new idiom for this script. One table, one index, no escaping
/// puzzles: the counts never pass through a string literal.
fn sample_count_capture_statements(plan: &sample::SamplePlan) -> Vec<String> {
    if plan.tables.is_empty() {
        return Vec::new();
    }
    let selects = plan
        .tables
        .iter()
        .enumerate()
        .map(|(index, table)| {
            format!(
                "SELECT {index} AS table_index, (SELECT count(*) FROM {}) AS n",
                qualified_ident(&table.table)
            )
        })
        .collect::<Vec<_>>()
        .join(" UNION ALL ");
    vec![format!(
        "CREATE TEMPORARY TABLE {SAMPLE_COUNTS_TABLE} ON COMMIT DROP AS {selects}"
    )]
}

/// The temp table the printed sample captures its counts into.
///
/// `pg_temp` is searched first for unqualified relation names, so for the
/// rest of the pasted transaction this table would shadow an application
/// relation of the same name — a rewrite trigger doing an unqualified
/// `INSERT` would write here instead, and the dry run would diverge from the
/// executed path, which creates no such table. The suffix makes a collision
/// implausible, and every read goes through `pg_temp.` explicitly.
const SAMPLE_COUNTS_TABLE: &str = "autumn_scrub_sample_counts_7c3e91d4a2";

/// Statements re-proving the sample's postconditions after the refreshes.
///
/// This is the printed half of `verify_sample_survived_refreshes`, which the
/// executed path runs in exactly this position. The dry run advertised the
/// same "exact SQL" without it, so a pasted script committed a subset the
/// real command rolls back: a refresh's query can call a function whose body
/// INSERTs — measured, a tracked `BEGIN ATOMIC` function writing into a
/// `never_include` table left the run reporting `audit_logs: 503 -> 0 row(s)`
/// and `✓ Scrub complete` while three rows carrying real addresses survived.
///
/// The counts are asserted against [`SAMPLE_COUNTS_TABLE`]
/// (`sample_count_capture_statements`): the printer has no live values at
/// print time, and baking the print-time source counts would assert the
/// wrong thing — the subset is what must survive, not the source. The
/// foreign-key half re-runs the same statements `report_sample_sql` prints: a
/// refresh that UPDATEs in place moves no count, and the re-count misses the
/// part of that which breaks the subset's integrity. An in-place edit that
/// keeps every reference valid is not visible here either, and is not claimed
/// to be — the same limit the executor documents.
///
/// Each pair is `(statement, comment)` so the caller can terminate the
/// statement before the `--` comment, the way `integrity_assertion`'s callers
/// do: a `;` after a `--` comment is inside the comment, and the statement
/// would never terminate. The single `DO` block raises once and aborts the
/// transaction, like every other generated assertion here. Table names appear
/// only as quoted identifiers — nothing is escaped into a string literal;
/// the comment carries the `comment_safe`d names for the auditor instead.
/// Same dollar-tag rule as `integrity_assertion`: an identifier may legally
/// contain `$`.
fn sample_postcondition_statements(plan: &sample::SamplePlan) -> Vec<(String, String)> {
    if plan.tables.is_empty() {
        return Vec::new();
    }
    let tables = plan
        .tables
        .iter()
        .map(|table| sample::comment_safe(&table.table))
        .collect::<Vec<_>>()
        .join(", ");
    let mismatches = plan
        .tables
        .iter()
        .enumerate()
        .map(|(index, table)| {
            format!(
                "(SELECT count(*) FROM {}) <> \
                 (SELECT n FROM pg_temp.{SAMPLE_COUNTS_TABLE} WHERE table_index = {index})",
                qualified_ident(&table.table)
            )
        })
        .collect::<Vec<_>>()
        .join(" OR ");
    let body = format!(
        "BEGIN IF {mismatches} THEN \
         RAISE EXCEPTION 'a sampled table''s row count moved during the materialized-view refreshes'; \
         END IF; END"
    );
    let tag = sample::dollar_tag(&body);
    let mut statements = vec![(
        format!("DO {tag} {body} {tag}"),
        format!(
            "sampled tables ({tables}): row counts still the sampled subset after the refreshes"
        ),
    )];
    for (constraint, statement) in plan.integrity_statements() {
        statements.push((
            integrity_assertion(&statement),
            format!("re-verifies {constraint} after the refreshes"),
        ));
    }
    statements
}

/// Report what the sample kept, per table and in total (AC #6).
fn report_sample_outcome(label: &str, outcome: &sample::SampleOutcome) {
    eprintln!("  \u{2500}\u{2500} {label}: sampled rows \u{2500}\u{2500}");
    for count in &outcome.counts {
        eprintln!(
            "    {}: {} \u{2192} {} row(s) ({}, {})",
            count.table,
            count.before,
            count.after,
            percent_of(count.after, count.before),
            count.role,
        );
    }
    let before: i64 = outcome.counts.iter().map(|c| c.before).sum();
    let after: i64 = outcome.counts.iter().map(|c| c.after).sum();
    eprintln!(
        "    Total: {before} \u{2192} {after} row(s) ({} of the source), settled in {} pass(es).",
        percent_of(after, before),
        outcome.passes,
    );
    eprintln!(
        "  \u{2713} {} foreign key(s) re-verified \u{2014} every reference in the subset resolves.",
        outcome.verified,
    );
}

/// Rewrite every subsetted table so the freed space is really freed, then
/// report the size the sample actually costs.
///
/// This runs AFTER the commit, so the subset is already correct and durable —
/// compaction only decides whether the files match it. A failure here is
/// therefore a warning, not a refusal: the alternative would be to fail a run
/// whose data is already right, and to do it on the one step that waits for an
/// `ACCESS EXCLUSIVE` lock. The wait is bounded for the same reason; an idle
/// connection left open against the target would otherwise block it forever.
fn report_reclaimed_size(
    url: &str,
    label: &str,
    plan: &sample::SamplePlan,
    purged: &[String],
    refreshed: &[String],
    before: i64,
) {
    let Ok(mut conn) = probe_connection(url, label, "compact the sampled tables") else {
        warn_not_compacted(before, "could not connect to compact the sampled tables");
        return;
    };
    if let Err(e) = sql_query(format!("SET lock_timeout = '{COMPACT_LOCK_TIMEOUT}'"))
        .execute(&mut conn)
        .map_err(|e| e.to_string())
    {
        warn_not_compacted(before, &e);
        return;
    }
    // A full-copy table is never deleted from, so it has nothing to reclaim.
    // `data_size` still measures it on both sides, which keeps the ratio
    // comparable.
    for table in compacted_tables(plan, purged) {
        // Not in a transaction, and deliberately: VACUUM FULL takes an
        // exclusive lock and rewrites the table, neither of which a transaction
        // block permits.
        if let Err(e) = sql_query(format!("VACUUM (FULL, ANALYZE) {}", qualified_ident(table)))
            .execute(&mut conn)
        {
            warn_not_compacted(before, &format!("{table}: {e}"));
            return;
        }
    }
    // Measured over the same set as `size_before`: the purge targets AND the
    // materialized views this run refreshed. Compaction above deliberately
    // skips the views — REFRESH rewrote each heap already — but leaving them
    // out of the measurement is what let the report announce a laptop-sized
    // result for a database a refreshed view still dominated.
    let Ok(after) = sample::data_size(&mut conn, plan, &also_measured(purged, refreshed)) else {
        warn_not_compacted(before, "could not measure the compacted size");
        return;
    };
    eprintln!(
        "    Table size: {} \u{2192} {} ({} of the source).",
        human_bytes(before),
        human_bytes(after),
        percent_of(after, before),
    );
}

/// How long the compaction waits for the exclusive lock it needs.
const COMPACT_LOCK_TIMEOUT: &str = "30s";

/// Say that the subset is committed but its files were not rewritten, and how
/// to finish the job by hand.
fn warn_not_compacted(before: i64, detail: &str) {
    eprintln!(
        "    \u{26A0}\u{FE0F}  The subset is committed, but the tables were NOT compacted \
         ({detail}).\n    \
         Deleting rows frees no disk on its own, so they still occupy {} \u{2014} close any \
         other connection to this database and run `VACUUM (FULL, ANALYZE)` to reclaim it.",
        human_bytes(before),
    );
}

/// `part` as a percentage of `whole`, one decimal place.
#[allow(clippy::cast_precision_loss)]
fn percent_of(part: i64, whole: i64) -> String {
    if whole <= 0 {
        return "n/a".to_owned();
    }
    format!("{:.1}%", part as f64 * 100.0 / whole as f64)
}

/// Bytes at human scale, so "128.0 MB → 3.0 MB" reads at a glance.
#[allow(clippy::cast_precision_loss)]
fn human_bytes(bytes: i64) -> String {
    const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
    let mut value = bytes.max(0) as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit + 1 < UNITS.len() {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes} B")
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

/// Tables this run writes to that carry a user-defined trigger or rule.
///
/// Covers all three classes of write: the column plan, the `[framework] purge`
/// targets (framework tables are not in `plan.tables`), and the sample.
fn triggered_write_targets(
    plan: &ScrubPlan,
    purges: &[(String, String)],
    sampling: Option<&sample::SamplePlan>,
    facts: &DatabaseFacts,
) -> Vec<String> {
    let mut triggered: Vec<String> = plan
        .tables
        .iter()
        .map(|t| t.table.as_str())
        .chain(purges.iter().map(|(table, _)| table.as_str()))
        .chain(
            sampling
                .into_iter()
                .flat_map(sample::SamplePlan::subsetted_tables),
        )
        .filter(|t| facts.triggered_tables.contains(*t))
        .map(str::to_owned)
        .collect();
    triggered.sort_unstable();
    triggered.dedup();
    triggered
}

/// Warn when a table the scrub rewrites carries user-defined triggers.
///
/// An audit/history trigger copies the pre-scrub `OLD` row into another table as
/// the `UPDATE` runs — so a table scrubbed earlier in the same transaction can be
/// re-populated with real values behind the scrub's back.
fn report_triggers(
    plan: &ScrubPlan,
    purges: &[(String, String)],
    sampling: Option<&sample::SamplePlan>,
    facts: &DatabaseFacts,
) {
    let triggered = triggered_write_targets(plan, purges, sampling, facts);
    if triggered.is_empty() {
        return;
    }
    eprintln!(
        "  \u{26A0}\u{FE0F}  {} table(s) this run writes to carry user-defined triggers or \
         rules: {}.\n    \
         An audit or history trigger copies the PRE-scrub row into another table as the \
         rewrite or the sample's removals run, which can re-introduce real values; an \
         `ON DELETE ... DO INSTEAD` rule can stop the sample removing anything at all. \
         Check them, or disable them on the copy before scrubbing.",
        triggered.len(),
        triggered.join(", ")
    );
}

/// Print what one database's scrub will do: every column, its strategy, and what
/// classified it — so the operator can audit the decision, not just its effect.
fn report_plan(label: &str, plan: &ScrubPlan) {
    eprintln!(
        "\u{2500}\u{2500} {label} \u{2500}\u{2500}\n  {} column(s) across {} table(s) \
         classified as PII.",
        plan.column_count(),
        plan.tables.len()
    );
    for table in &plan.tables {
        for column in &table.columns {
            eprintln!(
                "    {}.{} \u{2192} {} ({})",
                table.table,
                column.column,
                column.strategy.as_str(),
                column.source.as_str()
            );
        }
    }
}

/// The shared prefix of the materialized-view queries: every view in `public`
/// (`mv`), the source-to-dependent edges among them (`edge`), the closure the
/// run has to refresh (`needed`), and those edges restricted to it (`nedge`).
///
/// `edge` is derived rather than read straight out of the catalog, because a
/// materialized view can read another THROUGH an ordinary view and `pg_depend`
/// records only the hop it actually took. Matching a rewrite rule's dependency
/// directly against the set of materialized views drops both hops of `a_report
/// -> bridge_view -> z_source`, leaving two roots that then sort by name.
/// Measured on `PostgreSQL` 16.13: `a_report` refreshed FIRST, from a `z_source`
/// still holding pre-scrub rows, and refreshing `z_source` afterwards does not
/// touch it — `users` scrubbed to 2 rows with 0 original addresses, `z_source`
/// clean, and `a_report` holding all 200, under a reported success. So
/// `rel_edge` takes every rewrite-rule dependency between relations — and the
/// function hops `PostgreSQL` records, `rewrite -> pg_proc -> pg_class`, which a
/// `BEGIN ATOMIC` body produces. `fn_reach` closes that over function-to-function
/// calls first, so a tracked function calling another tracked function is
/// followed the whole way: measured, `a_report -> outer_fn() -> inner_fn() ->
/// z_source` yielded no edge when only the outer function's own relation
/// dependencies were read, and `a_report` refreshed first from a stale
/// `z_source` while keeping all 200 original addresses. `reach` walks that from each
/// materialized view through anything that is not one, and `edge` keeps the
/// pairs that land on one. A function whose body is a string literal records no
/// such dependency at all and cannot be walked; `untraceable_view_functions`
/// refuses those rather than ordering around a gap. `reach` recurses with `UNION` over a
/// finite set of pairs, so it terminates whatever the view graph looks like.
///
/// `fn_seed` is keyed by the RULE, not by the object the rule references,
/// because a rule can name a function by more than one catalog path and the
/// earlier shape could only follow one of them. Measured on `PostgreSQL`
/// 16.13, over the four indirections a rule can record:
///
/// | how the view reaches the function | the rule's `pg_depend` row |
/// | --- | --- |
/// | calls it directly                | `pg_proc` |
/// | through a cast                   | `pg_proc` (the cast function) |
/// | through an aggregate             | `pg_proc` (then `pg_proc -> pg_proc` to the sfunc) |
/// | through a user-defined operator  | `pg_operator` — and NO `pg_proc` row |
/// | through a domain's CHECK         | `pg_type` — and NO `pg_proc` row |
///
/// The first three were already followed; the last two were not, and the
/// operator case is a silent leak rather than a missed refinement. Measured:
/// `a_report` reading `z_source` only through `1 ==> 200`, whose implementation
/// is a tracked `BEGIN ATOMIC` function, produced no edge at all, so the two
/// views sorted by name, `a_report` refreshed FIRST from a stale `z_source`,
/// and the run reported `Scrub complete` with `users` at 2 rows, `z_source`
/// clean, and all 200 original addresses still in `a_report`. The domain case
/// is the same blind spot and fails closed instead — the check fires against
/// the stale view during the rewrite and aborts the transaction — but it is the
/// same missing edge, so it is seeded the same way rather than left to luck.
///
/// `oprcode` and `pg_constraint.contypid` are both older than every server this
/// command supports, so neither needs a `has_catalog_column` probe.
///
/// `needed` is every POPULATED view, plus every view one of those reads, however
/// deep. Both halves matter:
///
/// - A view created — or last refreshed — `WITH NO DATA` holds no rows at all.
///   Measured on `PostgreSQL` 16.13: `REFRESH ... WITH NO DATA` truncates the
///   heap (24 kB to 8 kB on a 200-row view) and selecting from one afterwards
///   raises `materialized view "…" has not been populated`. So it has no
///   pre-scrub copy to rebuild, and refreshing it would run the view's query and
///   materialize a heap the database deliberately does not have — on the
///   expensive query such a view usually guards, time and disk spent inside the
///   scrub's transaction, where exhausting either rolls the whole run back.
/// - An unpopulated view a populated one reads is a different case: `REFRESH`
///   on the dependent fails outright while its source is unpopulated (measured:
///   `materialized view "mv_a" has not been populated`), and an unrefreshed
///   populated view keeps its pre-scrub rows. So the source is refreshed after
///   all — and `unpopulated_views` puts it back after, which is safe because
///   emptying a source does not un-populate the dependent already rebuilt from
///   it (measured: the dependent kept `relispopulated` and all 200 rows).
///
/// `needed` recurses with `UNION`, not `UNION ALL`, so it terminates on its own
/// and needs no depth cap. The ordered walk built on top of it still has one,
/// and the unreachable-view refusal exists to catch what that cap drops.
const MV_REFRESH_CLOSURE: &str = "WITH RECURSIVE mv AS ( \
     SELECT rel.oid, rel.relispopulated FROM pg_class rel \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE rel.relkind = 'm' \
 ), viewrule AS ( \
     SELECT oid, ev_class FROM pg_rewrite WHERE rulename = '_RETURN' AND ev_type = '1' \
 ), dep_fn AS ( \
     SELECT d.classid, d.objid, d.refobjid AS fn \
     FROM pg_depend d \
     WHERE d.classid IN ('pg_rewrite'::regclass, 'pg_proc'::regclass) \
       AND d.refclassid = 'pg_proc'::regclass \
       AND (d.classid = 'pg_proc'::regclass OR d.objid IN (SELECT oid FROM viewrule)) \
     UNION \
     SELECT d.classid, d.objid, o.oprcode \
     FROM pg_depend d \
     JOIN pg_operator o ON o.oid = d.refobjid \
     WHERE d.classid IN ('pg_rewrite'::regclass, 'pg_proc'::regclass) \
       AND d.refclassid = 'pg_operator'::regclass AND o.oprcode <> 0 \
       AND (d.classid = 'pg_proc'::regclass OR d.objid IN (SELECT oid FROM viewrule)) \
     UNION \
     SELECT d.classid, d.objid, cd.refobjid \
     FROM pg_depend d \
     JOIN pg_constraint con ON con.contypid = d.refobjid \
     JOIN pg_depend cd ON cd.classid = 'pg_constraint'::regclass \
       AND cd.objid = con.oid AND cd.refclassid = 'pg_proc'::regclass \
     WHERE d.classid IN ('pg_rewrite'::regclass, 'pg_proc'::regclass) \
       AND d.refclassid = 'pg_type'::regclass \
       AND (d.classid = 'pg_proc'::regclass OR d.objid IN (SELECT oid FROM viewrule)) \
 ), fn_reach AS ( \
     SELECT df.objid AS rule, df.fn FROM dep_fn df \
     WHERE df.classid = 'pg_rewrite'::regclass \
     UNION \
     SELECT r.rule, df.fn FROM fn_reach r \
     JOIN dep_fn df ON df.classid = 'pg_proc'::regclass AND df.objid = r.fn \
 ), rel_edge AS ( \
     SELECT DISTINCT r.ev_class AS dependent, d.refobjid AS source \
     FROM pg_depend d \
     JOIN viewrule r ON r.oid = d.objid \
     WHERE d.classid = 'pg_rewrite'::regclass \
       AND d.refclassid = 'pg_class'::regclass \
       AND d.refobjid <> r.ev_class \
     UNION \
     SELECT DISTINCT r.ev_class AS dependent, fd.refobjid AS source \
     FROM viewrule r \
     JOIN fn_reach fr ON fr.rule = r.oid \
     JOIN pg_depend fd ON fd.classid = 'pg_proc'::regclass \
       AND fd.objid = fr.fn AND fd.refclassid = 'pg_class'::regclass \
     WHERE fd.refobjid <> r.ev_class \
 ), reach AS ( \
     SELECT m.oid AS dependent, e.source FROM mv m \
     JOIN rel_edge e ON e.dependent = m.oid \
     UNION \
     SELECT h.dependent, e.source FROM reach h \
     JOIN rel_edge e ON e.dependent = h.source \
     WHERE h.source NOT IN (SELECT oid FROM mv) \
 ), edge AS ( \
     SELECT DISTINCT dependent, source FROM reach \
     WHERE source IN (SELECT oid FROM mv) \
 ), needed AS ( \
     SELECT oid FROM mv WHERE relispopulated \
     UNION \
     SELECT e.source FROM edge e JOIN needed n ON n.oid = e.dependent \
 ), nedge AS ( \
     SELECT dependent, source FROM edge WHERE dependent IN (SELECT oid FROM needed) \
 )";

/// Tables a statement naming them can fire a user-defined rewrite rule on.
///
/// Unlike triggers this needs no walk up `pg_inherits`: measured on
/// `PostgreSQL` 16, a rule on a leaf partition or an inheritance child does not
/// fire for a statement naming the parent, because rewriting happens against the
/// relation the query names. `_RETURN` is the `SELECT` rule every view carries,
/// and `ev_enabled` follows the same `O`/`A` rule as `tgenabled`.
///
/// `extra` is an additional `pg_rewrite` predicate, e.g. restricting the event.
fn rules_reaching(extra: &str) -> String {
    format!(
        "SELECT DISTINCT rel.relname AS name FROM pg_rewrite r \
         JOIN pg_class rel ON rel.oid = r.ev_class \
         JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
         WHERE r.rulename <> '_RETURN' AND r.ev_enabled IN ('O', 'A') {extra}"
    )
}

/// Tables a statement naming them can fire a user-defined trigger on.
///
/// Two catalog rules decide this, and both have bitten this command:
///
/// - **`tgenabled`.** A trigger disabled with `ALTER TABLE ... DISABLE TRIGGER`
///   stays in the catalog and cannot fire — and disabling it is exactly what the
///   trigger warning and the emptying refusal tell operators to do, so counting
///   it would make the documented remedy do nothing. `O` fires for an ordinary
///   session and `A` fires always; `D` never fires, and `R` only under
///   `session_replication_role = replica`, which a scrub does not set.
///
/// - **Row versus statement level, walking up `pg_inherits`.** A statement
///   naming a partitioned parent (or a legacy `INHERITS` parent) fires
///   **row-level** triggers declared on the children, so a row trigger anywhere
///   below a table has to mark that table. It does **not** fire their
///   statement-level triggers — measured on `PostgreSQL` 16, for both inheritance
///   flavours — so those mark only the table they are declared on. Propagating
///   them would refuse a run over a trigger that cannot execute.
///
/// Descendants need no walk: a trigger on a partitioned parent is cloned onto
/// its partitions, and the parent is already named.
///
/// `extra` is an additional `pg_trigger` predicate, e.g. restricting the event.
fn triggers_reaching(extra: &str) -> String {
    format!(
        "WITH RECURSIVE fires AS ( \
           SELECT t.tgrelid AS oid, (t.tgtype & 1) <> 0 AS by_row FROM pg_trigger t \
           WHERE NOT t.tgisinternal AND t.tgenabled IN ('O', 'A') {extra}\
         ), ancestry AS ( \
           SELECT oid, by_row FROM fires \
           UNION \
           SELECT i.inhparent, true FROM pg_inherits i \
           JOIN ancestry a ON a.oid = i.inhrelid AND a.by_row \
         ) \
         SELECT DISTINCT rel.relname AS name FROM ancestry a \
         JOIN pg_class rel ON rel.oid = a.oid \
         JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public'"
    )
}

/// Where a connection actually landed, as the server itself reports it.
///
/// Both `None` over a Unix socket, where Postgres has no address or port to
/// report. Held as strings because they only ever go back into SQL as literals.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ServerEndpoint {
    /// `current_database()`, asked of the target itself rather than parsed out
    /// of its URL. libpq defaults an omitted database name to the user name,
    /// which defaults to the OS user — rules this command would have to
    /// reimplement to guess, and did not: a URI with no database silently
    /// emitted no guard at all, leaving 19 destructive statements unprotected.
    /// The connection already knows the answer.
    pub database: String,
    /// `inet_server_addr()`, e.g. `10.0.0.2/32`. `None` over a Unix socket.
    pub address: Option<String>,
    /// `inet_server_port()`. `None` over a Unix socket.
    pub port: Option<String>,
    /// The cluster's `system_identifier`, from `pg_control_system()`.
    ///
    /// Address and port are `None` for EVERY Unix-socket connection, so two
    /// socket clusters holding the same database name are indistinguishable by
    /// them — measured, both reported `<null>/<null>` while their identifiers
    /// differed. This one is generated at initdb, survives the socket path, and
    /// is readable by an ordinary `LOGIN` role (verified against a non-superuser
    /// on `PostgreSQL` 16.13).
    ///
    /// It does NOT distinguish a cluster from a physical copy of itself: a
    /// replica, or a promoted staging clone, carries the identifier of the
    /// cluster it was cloned from. Hence the three fields below.
    pub system_identifier: Option<String>,
    /// `current_setting('port')` — the port the SERVER is configured on.
    ///
    /// Not the same question as `inet_server_port()`, which is the port this
    /// client reached and is NULL over a Unix socket. This one answers over a
    /// socket too (verified: 5433 and 5434 read back from two socket-only
    /// clusters), and unlike `data_directory` it is readable by an ordinary
    /// `LOGIN` role, so it discriminates even where the scrub role cannot
    /// examine restricted settings.
    pub server_port: Option<String>,
    /// `data_directory`, or `None` where the role may not read it.
    ///
    /// The value a physical clone cannot share with its origin while both run on
    /// the same machine: two postmasters cannot hold one data directory. It is
    /// restricted to `pg_read_all_settings`, so it is read out of `pg_settings`
    /// rather than with `current_setting` — that view omits the row entirely for
    /// a role without the privilege, and the scalar subquery yields NULL instead
    /// of raising `permission denied to examine ...`, which `current_setting`
    /// does raise, `missing_ok` or not (that flag covers unknown parameters, not
    /// forbidden ones). Verified both ways on `PostgreSQL` 16.13.
    pub data_directory: Option<String>,
}

/// Which SQL dialect the plan's statements are written in.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Dialect {
    /// `PostgreSQL`: `md5`, `ctid`, `"public".` qualification.
    #[default]
    Postgres,
    /// `SQLite`: `autumn_sha256`, `rowid`, unqualified names.
    Sqlite,
}

/// Everything about one live database that the pure classifier cannot read from
/// the schema IR, gathered in a single connection.
///
/// The IR [`crate::schema::introspect`] produces is shaped for *migration
/// diffing*, not for "is it safe to rewrite this column": it records only
/// outgoing single-column foreign keys, drops generated/identity semantics, and
/// says nothing about row-level security, triggers, partitions, materialized
/// views, or schemas outside `public`. Every one of those decides whether an
/// `UPDATE` this command emits succeeds, silently under-applies, or leaks — so
/// they are probed here rather than assumed.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct DatabaseFacts {
    /// The dialect the plan's SQL is written in. Defaults to Postgres.
    pub dialect: Dialect,
    /// `SQLite` tables that have a `rowid` (all but `WITHOUT ROWID` tables).
    /// Such a table can hold several rows whose non-integer primary key is
    /// `NULL`, so the row key falls back to `rowid`. Empty on Postgres.
    pub rowid_tables: BTreeSet<String>,
    /// Every column on either side of any foreign key, all components of a
    /// composite key included, as `(table, column)`. Rewriting any of them
    /// breaks referential integrity (or is silently cascaded into a child).
    pub foreign_key_columns: BTreeSet<(String, String)>,
    /// Columns named by a `CHECK` constraint. A fabricated value has no way to
    /// satisfy an arbitrary predicate, so these are refused rather than guessed.
    pub checked_columns: BTreeSet<(String, String)>,
    /// Generated / `GENERATED ALWAYS AS IDENTITY` columns. Postgres refuses to
    /// `UPDATE` them at all, and they are derived data that a scrub of their
    /// source columns already covers.
    pub generated_columns: BTreeSet<(String, String)>,
    /// Columns covered by ANY unique index — composite and partial included.
    /// Broader than the IR's single-column `unique` flag, which is the right
    /// question for a migration diff and the wrong one for "can this rewrite
    /// collide".
    pub unique_columns: BTreeSet<(String, String)>,
    /// Columns read by a unique index's expression or predicate. Injectivity on
    /// a column's own value does not survive an arbitrary expression: every
    /// scrubbed address starts `scrubbed+`, so `UNIQUE (left(email, 1))` collides.
    pub unique_expression_columns: BTreeSet<(String, String)>,
    /// Columns named by an exclusion constraint, which is not `indisunique`.
    pub exclusion_columns: BTreeSet<(String, String)>,
    /// Columns covered by a `NULLS NOT DISTINCT` unique index, where more than
    /// one `NULL` is itself a uniqueness violation.
    pub nulls_not_distinct_columns: BTreeSet<(String, String)>,
    /// Tables that are partitions, each mapped to the top-level table it
    /// belongs to. Their rows are rewritten through that parent, so planning
    /// them again double-updates — and the mapping also says whose role decides
    /// whether a key declared on a leaf can be ignored.
    pub partitions: BTreeMap<String, String>,
    /// Partition-key columns, keyed by the top-level table. A rewrite through
    /// the parent moves each row to the partition its new key belongs to: it
    /// aborts when none exists, and collapses the table into one when one does.
    pub partition_key_columns: BTreeSet<(String, String)>,
    /// Tables whose row-level security binds the connected role. Such a role
    /// silently updates only the rows its policies expose — a fail-open a scrub
    /// cannot tolerate. A superuser, a `BYPASSRLS` role and an unforced owner
    /// are not bound, so their tables are absent.
    pub rls_tables: BTreeSet<String>,
    /// Legacy `INHERITS` children as `child (inherits parent)`, sorted. Empty
    /// for a declaratively partitioned schema, which the sample does model.
    pub legacy_inheritance: Vec<String>,
    /// Tables carrying user-defined triggers, which can copy pre-scrub values
    /// into another table mid-scrub.
    pub triggered_tables: BTreeSet<String>,
    /// The address and port the connection actually reached, as the server
    /// reports them. Both `None` over a Unix socket. The dry run's target guard
    /// compares these so a retained connection to a different host holding the
    /// same database name cannot pass for the intended one.
    pub endpoint: ServerEndpoint,
    /// The connection's `session_replication_role`. Anything but `origin`
    /// inverts which triggers and rules fire, so the hazard checks below would
    /// be answering for a session the run is not in.
    pub replication_role: String,
    /// The subset of those whose triggers fire on `DELETE`. The run's emptying
    /// pass is its last write, so a trigger here fires after every rewrite and
    /// can put pre-scrub values into a table already scrubbed.
    pub delete_triggered_tables: BTreeSet<String>,
    /// The materialized views the run refreshes, in dependency order (sources
    /// before dependents), so refreshing them in sequence never re-derives from
    /// stale data. Drawn from the `MV_REFRESH_CLOSURE` set, not from every view:
    /// one left `WITH NO DATA` that nothing populated reads is not refreshed.
    pub materialized_views: Vec<String>,
    /// That same closure, enumerated flat.
    ///
    /// The ordered list above is built by a recursive walk that stops at a depth
    /// cap, so a view past it is absent from that list — and the size report
    /// measures over this set. Measuring the ordered list instead let the report
    /// announce a laptop-sized result while an unmeasured view still held the
    /// disk. A view that is not refreshed still occupies its heap, so honest
    /// measurement enumerates them all; refresh ORDER is a separate question and
    /// keeps its own list. It has to be drawn from the same closure the ordered
    /// list is, though: the unreachable-view refusal compares the two, so a view
    /// present in only one of them reads as one the walk could not reach.
    pub all_materialized_views: Vec<String>,
    /// EVERY materialized view in `public` that was unpopulated when the run
    /// probed it — not only the closure members among them.
    ///
    /// Each gets a `REFRESH ... WITH NO DATA` as the transaction's last view
    /// statement, which does two jobs. A closure member was populated only so a
    /// dependent could be rebuilt from it, and this puts it back. A view outside
    /// the closure was skipped, and this closes the race that skipping opened:
    /// probing runs on its own connection before the apply transaction, the
    /// locks that transaction takes are `SHARE ROW EXCLUSIVE` on base tables and
    /// none at all on a view, and `REFRESH MATERIALIZED VIEW` needs only
    /// `ACCESS SHARE` on the tables it reads. Measured on `PostgreSQL` 16.13: a
    /// concurrent session refreshed a skipped view mid-scrub without waiting,
    /// and the run committed with `users` scrubbed to 2 rows and the view
    /// holding all 200 original addresses. Emptying it under the `ACCESS
    /// EXCLUSIVE` this statement takes serialises that session behind the
    /// commit, after which it can only re-derive from scrubbed rows.
    ///
    /// It costs nothing that skipping saved: `REFRESH ... WITH NO DATA` does not
    /// run the view's query. Measured on a view defined as `SELECT 1/0`, it
    /// succeeds where a plain `REFRESH` raises `division by zero`.
    pub unpopulated_views: Vec<String>,
    /// `view via function` for every materialized view whose definition calls a
    /// non-system function that records no relation dependency of its own.
    ///
    /// Opacity is read from `prosqlbody`, which holds the parsed body of a
    /// `BEGIN ATOMIC` function and is NULL for everything else — a string
    /// literal, `plpgsql`, or C. That is the property itself, where "records no
    /// relation dependency" was only a proxy for it, and a wrong one: a tracked
    /// wrapper that merely calls another tracked function records no relation of
    /// its own, and was refused although `fn_reach` can follow it all the way to
    /// the table. Measured — `view -> wrap_fn() -> inner_fn() -> z_source`, every
    /// body `BEGIN ATOMIC`, refused as `via wrap_fn`.
    ///
    /// `prosqlbody` is `PostgreSQL` 14, so it is probed for with
    /// `has_catalog_column` like every other version-specific catalog fact
    /// here. Reading it unguarded broke every scrub on an older server with
    /// `column p.prosqlbody does not exist` — the testcontainer default is
    /// `postgres:11-alpine`. On a server without it the answer is "every
    /// function reached from a view", not "none": before 14 no SQL body is
    /// parsed into the catalog, so none of them can be followed.
    ///
    /// Read over the views this run will actually EVALUATE — `needed`, not every
    /// materialized view. A standalone view left `WITH NO DATA` only ever gets
    /// `REFRESH ... WITH NO DATA`, which provably never runs its query
    /// (measured on a view defined `SELECT 1/0`, where it succeeds), so an
    /// opaque function in its definition can hide nothing. Refusing on it
    /// blocked a whole valid scrub.
    ///
    /// And only through `_RETURN` rules, the ones that DEFINE a view. A base
    /// table reached from a view can carry unrelated DML rules, and a `REFRESH`
    /// is a `SELECT`: measured, an `ON INSERT` rule on `users` calling a
    /// `plpgsql` function refused the run as `a_view via log_it`, for a rule
    /// the refresh can never fire.
    ///
    /// Read over every relation REACHABLE from a materialized view, not only the
    /// views themselves: the walk crosses ordinary views, so a function called by
    /// one of those is just as invisible and just as able to reorder the
    /// refresh. And over every function in the `fn_reach` closure, not only the
    /// one a rule names directly — a tracked function can call an opaque one,
    /// and the outer function's own relation dependency would otherwise vouch
    /// for a body nothing can see into.
    pub untraceable_view_functions: Vec<String>,
    /// `view via function` for every view this run refreshes whose definition
    /// calls a catalog function that reads relations named in a string.
    ///
    /// These record no dependency at all — not an opaque body the walk could
    /// refuse for, but nothing to walk. `table_to_xml` is excluded: its
    /// `regclass` argument is recorded like any other relation reference
    /// (measured, `pg_class -> users`), so its order is derivable.
    pub views_reading_by_name: Vec<String>,
    /// Non-system schemas other than `public` that hold base tables. The whole
    /// classification universe is `public`-only, so these are refused.
    pub other_schemas: BTreeSet<String>,
    /// Framework-owned tables present that the classification never sees.
    pub framework_tables: Vec<String>,
    /// Every column of every `public` table, read from `pg_attribute`.
    ///
    /// A role can hold privileges on some columns of a table but not others, and
    /// `information_schema.columns` (what introspection reads) omits the ones it
    /// cannot see — so the table would classify, the visible columns would be
    /// rewritten, and the hidden PII would survive.
    pub public_columns: BTreeSet<(String, String)>,
    /// Every base table in `public`, read from `pg_class`.
    ///
    /// Introspection enumerates through `information_schema.tables`, which shows
    /// only what the connecting role has some privilege on — so a table the
    /// scrub role cannot see would silently drop out of the classified universe
    /// and be reported clean. `pg_class` shows them all, and the difference is
    /// a refusal.
    pub public_base_tables: BTreeSet<String>,
    /// Every materialized view in `public` as `name:oid:populated`. The drift check
    /// compares it, because the refresh list is fixed at probe time.
    pub public_materialized_views: BTreeSet<String>,
    /// Every user trigger and rule by identity. The drift check compares it.
    pub trigger_identities: BTreeSet<String>,
    /// Every foreign key in `public`, whole constraints rather than the loose
    /// columns above: `--sample` walks this graph to decide which rows a subset
    /// must carry for every reference to resolve.
    pub foreign_keys: Vec<sample::ForeignKeyConstraint>,
}

/// A single `n` count column, for the promised-empty verification.
#[derive(diesel::QueryableByName)]
struct RowCount {
    #[diesel(sql_type = diesel::sql_types::BigInt)]
    n: i64,
}

/// A single `name` column.
#[derive(diesel::QueryableByName)]
struct NameRow {
    #[diesel(sql_type = diesel::sql_types::Text)]
    name: String,
}

/// A `(table, column)` pair.
#[derive(diesel::QueryableByName)]
struct PairRow {
    #[diesel(sql_type = diesel::sql_types::Text)]
    tbl: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    col: String,
}

/// One whole foreign key constraint, both key lists rendered as unit-separated
/// column names (a separator no identifier can contain).
#[derive(diesel::QueryableByName)]
struct ConstraintRow {
    #[diesel(sql_type = diesel::sql_types::Text)]
    name: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    child: String,
    /// The key's columns in key order, as an array rather than a joined
    /// string: a Postgres identifier may contain any character, so no separator
    /// is safe to split on afterwards.
    #[diesel(sql_type = diesel::sql_types::Array<diesel::sql_types::Text>)]
    child_cols: Vec<String>,
    #[diesel(sql_type = diesel::sql_types::Text)]
    parent: String,
    #[diesel(sql_type = diesel::sql_types::Array<diesel::sql_types::Text>)]
    parent_cols: Vec<String>,
    /// True for `MATCH FULL`, whose composite NULL rule differs from the
    /// default `MATCH SIMPLE`.
    #[diesel(sql_type = diesel::sql_types::Bool)]
    match_full: bool,
    /// True when Postgres cloned this constraint onto a partition from its
    /// partitioned parent. The parent's own constraint covers the same rows, so
    /// a clone must not be walked or verified a second time — while a key
    /// declared directly on a partition is NOT a clone and must not be dropped.
    #[diesel(sql_type = diesel::sql_types::Bool)]
    cloned: bool,
}

/// A `(tbl, col)` probe read as a map rather than a set of pairs.
fn pair_rows(sql: &str, conn: &mut PgConnection) -> Result<BTreeMap<String, String>, ScrubError> {
    let rows: Vec<PairRow> = sql_query(sql)
        .load(conn)
        .map_err(|e| ScrubError::Sql(e.to_string()))?;
    Ok(rows.into_iter().map(|r| (r.tbl, r.col)).collect())
}

/// Every `(partitioned table, key column)` pair, at any depth.
///
/// A plain key is read from `partattrs`. An expression key records no column
/// there (and `pg_depend` holds none), so the key definition is matched by whole
/// word instead. The escape uses `chr(92)`, so it does not depend on
/// `standard_conforming_strings`.
const PARTITION_KEY_COLUMNS: &str = "SELECT rel.relname AS tbl, att.attname AS col \
     FROM pg_partitioned_table p \
     JOIN pg_class rel ON rel.oid = p.partrelid \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     JOIN pg_attribute att ON att.attrelid = p.partrelid \
       AND att.attnum > 0 AND NOT att.attisdropped \
     WHERE att.attnum = ANY (p.partattrs::int2[]) \
        OR (0 = ANY (p.partattrs::int2[]) AND pg_get_partkeydef(p.partrelid) ~ ( \
             '(^|[^[:alnum:]_])' \
             || regexp_replace(quote_ident(att.attname), '([^[:alnum:]_])', \
             chr(92) || chr(92) || chr(92) || '1', 'g') \
             || '($|[^[:alnum:]_])'))";

/// Move each sub-partitioned table's key columns onto its root table.
fn fold_into_parent(
    keys: impl IntoIterator<Item = (String, String)>,
    partitions: &BTreeMap<String, String>,
) -> BTreeSet<(String, String)> {
    keys.into_iter()
        .map(|(table, column)| (partitions.get(&table).cloned().unwrap_or(table), column))
        .collect()
}

fn pair_set(rows: Vec<PairRow>) -> BTreeSet<(String, String)> {
    rows.into_iter().map(|r| (r.tbl, r.col)).collect()
}

/// Open a connection for a probe, mapping failure to a credential-safe error.
fn probe_connection(url: &str, label: &str, what: &str) -> Result<PgConnection, ScrubError> {
    let mut conn = PgConnection::establish(url).map_err(|_| ScrubError::Introspect {
        label: label.to_owned(),
        detail: format!(
            "could not connect to database {:?} to {what}",
            parsed_db_name(url)
        ),
    })?;
    // Pinned here, not only inside the scrub's transaction: `pg_catalog` is
    // searched implicitly ONLY when the path does not name it, so a target whose
    // `search_path` is `public, pg_catalog` lets an application object shadow a
    // built-in — and every question this command asks the catalog is asked over
    // THIS connection, before any transaction opens. A `public.current_setting`
    // returning `'origin'` was enough to walk straight past the replica-role
    // refusal.
    conn.batch_execute("SET search_path = pg_catalog, public")
        .map_err(|e| ScrubError::Introspect {
            label: label.to_owned(),
            detail: format!("could not pin the search path to {what}: {e}"),
        })?;
    Ok(conn)
}

/// Whether a system catalog has a given column on this server.
///
/// The catalog grows with each Postgres release — `attgenerated` arrives in 12,
/// `indnkeyatts` in 11, `indnullsnotdistinct` in 15 — and a scrub that only ran
/// on the newest server would be useless. Each version-specific fact is probed
/// for first and degrades to "no such thing on this server", which is the
/// correct answer: a release without generated columns has none to skip.
fn has_catalog_column(
    conn: &mut PgConnection,
    relation: &str,
    column: &str,
) -> Result<bool, ScrubError> {
    let rows: Vec<NameRow> = sql_query(format!(
        "SELECT 'yes' AS name FROM pg_attribute \
         WHERE attrelid = {}::regclass AND attname = {} AND NOT attisdropped",
        quote_literal(relation),
        quote_literal(column)
    ))
    .load(conn)
    .map_err(|e| ScrubError::Sql(e.to_string()))?;
    Ok(!rows.is_empty())
}

/// Tables in `public` whose row-level security restricts the connected role.
///
/// RLS only binds a role the table's policies apply to. A superuser and a
/// `BYPASSRLS` role skip it; so does the table owner, unless the table is
/// `FORCE ROW LEVEL SECURITY`. Refusing those would make the documented remedy
/// ("connect as the owner") a dead end. `current_user` is the role RLS checks.
const RLS_RESTRICTED_TABLES: &str = "SELECT rel.relname AS name FROM pg_class rel \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE rel.relrowsecurity \
       AND NOT COALESCE((SELECT r.rolsuper OR r.rolbypassrls FROM pg_roles r \
                         WHERE r.rolname = current_user), false) \
       AND NOT (pg_has_role(current_user, rel.relowner, 'USAGE') \
                AND NOT rel.relforcerowsecurity)";

/// Every base table in `public`, foreign tables included.
const PUBLIC_BASE_TABLES: &str = "SELECT rel.relname AS name FROM pg_class rel \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE rel.relkind IN ('r', 'p', 'f')";

/// Every user trigger and rewrite rule on a `public` relation, by identity:
/// name, event bits and enabled state. A table-name set cannot see a second
/// trigger added to a table that already has one.
const TRIGGER_IDENTITIES: &str = "SELECT rel.relname || ':trigger:' || t.tgname || ':' || t.tgtype::text \
         || ':' || t.tgenabled::text || ':' || md5(pg_get_triggerdef(t.oid)) AS name \
     FROM pg_trigger t \
     JOIN pg_class rel ON rel.oid = t.tgrelid \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE NOT t.tgisinternal \
     UNION ALL \
     SELECT rel.relname || ':rule:' || r.rulename || ':' || r.ev_type::text \
         || ':' || r.ev_enabled::text || ':' || md5(pg_get_ruledef(r.oid)) AS name \
     FROM pg_rewrite r \
     JOIN pg_class rel ON rel.oid = r.ev_class \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE r.rulename <> '_RETURN'";

/// Generated and `GENERATED ALWAYS` identity columns, read through `to_jsonb` so
/// the same text runs on servers that lack `attgenerated` (before 12). A column
/// that stops being generated mid-run is an ordinary column holding real values.
const GENERATED_COLUMNS: &str = "SELECT rel.relname AS tbl, att.attname AS col \
     FROM pg_attribute att \
     JOIN pg_class rel ON rel.oid = att.attrelid \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE att.attnum > 0 AND NOT att.attisdropped \
       AND (coalesce(to_jsonb(att)->>'attgenerated', '') <> '' \
            OR to_jsonb(att)->>'attidentity' = 'a')";

/// Every materialized view in `public`, by name, OID and population state, and
/// every ordinary view in any user schema by definition hash. The refresh list and its order are
/// drawn from the probe. A view created, recreated (new OID), or replaced in
/// place would keep stale rows or reorder the refreshes.
const PUBLIC_MATVIEWS: &str = "SELECT rel.relname || ':' || rel.oid::text || ':' || rel.relispopulated::text AS name \
     FROM pg_class rel \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE rel.relkind = 'm' \
     UNION ALL \
     SELECT ns.nspname || '.' || rel.relname || ':view:' || md5(pg_get_viewdef(rel.oid)) AS name \
     FROM pg_class rel \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace \
       AND ns.nspname <> 'information_schema' AND ns.nspname !~ '^pg_' \
     WHERE rel.relkind = 'v'";

/// Every live column of those tables.
const PUBLIC_COLUMNS: &str = "SELECT rel.relname AS tbl, att.attname AS col \
     FROM pg_attribute att \
     JOIN pg_class rel ON rel.oid = att.attrelid \
     JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
     WHERE rel.relkind IN ('r', 'p', 'f') AND att.attnum > 0 AND NOT att.attisdropped";

/// Compare the facts the plan was built from with what this connection sees now.
///
/// Covers the names the plan classified, and the hazards the refusals read: the
/// RLS set and the trigger and rule sets. A migration that lands between the
/// probe and the locks must not leave a stale answer behind.
fn live_schema_drift(
    conn: &mut PgConnection,
    facts: &DatabaseFacts,
) -> Result<Vec<String>, diesel::result::Error> {
    let names = |conn: &mut PgConnection, sql: &str| -> Result<BTreeSet<String>, _> {
        Ok::<_, diesel::result::Error>(
            sql_query(sql)
                .load::<NameRow>(conn)?
                .into_iter()
                .map(|r| r.name)
                .collect(),
        )
    };
    let tables = names(conn, PUBLIC_BASE_TABLES)?;
    let columns = pair_set(sql_query(PUBLIC_COLUMNS).load::<PairRow>(conn)?);
    let mut drift = schema_drift(
        (&facts.public_base_tables, &facts.public_columns),
        (&tables, &columns),
    );
    let generated = pair_set(sql_query(GENERATED_COLUMNS).load::<PairRow>(conn)?);
    drift.extend(
        generated
            .symmetric_difference(&facts.generated_columns)
            .map(|(t, c)| format!("{t}.{c} (generated state changed)")),
    );
    let mut triggered = names(conn, &triggers_reaching(""))?;
    triggered.extend(names(conn, &rules_reaching(""))?);
    let mut delete_triggered = names(conn, &triggers_reaching("AND (t.tgtype & 8) <> 0 "))?;
    delete_triggered.extend(names(conn, &rules_reaching("AND r.ev_type = '4' "))?);
    for (label, before, after) in [
        (
            "row-level security",
            &facts.rls_tables,
            names(conn, RLS_RESTRICTED_TABLES)?,
        ),
        (
            "materialized view",
            &facts.public_materialized_views,
            names(conn, PUBLIC_MATVIEWS)?,
        ),
        (
            "trigger or rule",
            &facts.trigger_identities,
            names(conn, TRIGGER_IDENTITIES)?,
        ),
        ("triggers or rules", &facts.triggered_tables, triggered),
        (
            "DELETE triggers or rules",
            &facts.delete_triggered_tables,
            delete_triggered,
        ),
    ] {
        drift.extend(
            after
                .symmetric_difference(before)
                .map(|t| format!("{t} ({label} changed)")),
        );
    }
    drift.sort();
    Ok(drift)
}

/// List the tables and columns that differ between two snapshots, sorted.
fn schema_drift(
    before: (&BTreeSet<String>, &BTreeSet<(String, String)>),
    after: (&BTreeSet<String>, &BTreeSet<(String, String)>),
) -> Vec<String> {
    let mut drift: Vec<String> = Vec::new();
    drift.extend(
        after
            .0
            .difference(before.0)
            .map(|t| format!("{t} (table added)")),
    );
    drift.extend(
        before
            .0
            .difference(after.0)
            .map(|t| format!("{t} (table dropped)")),
    );
    drift.extend(
        after
            .1
            .difference(before.1)
            .map(|(t, c)| format!("{t}.{c} (column added)")),
    );
    drift.extend(
        before
            .1
            .difference(after.1)
            .map(|(t, c)| format!("{t}.{c} (column dropped)")),
    );
    drift.sort();
    drift
}

/// Gather every catalog fact the plan validation needs.
// One catalog read per fact; splitting it would scatter closely-related SQL
// across helpers that each need the same connection.
#[allow(clippy::too_many_lines)]
fn probe_database_facts(
    url: &str,
    label: &str,
    config: &ScrubConfig,
) -> Result<DatabaseFacts, ScrubError> {
    let mut conn = probe_connection(url, label, "inspect its catalog")?;

    // ── Foreign keys: BOTH sides, every component ───────────────────────────
    // `pg_constraint.conkey`/`confkey` are arrays; `unnest` covers composite
    // keys, which the IR (first component, referencing side only) cannot.
    let foreign_key_columns = pair_set(
        sql_query(
            "SELECT rel.relname AS tbl, att.attname AS col \
             FROM pg_constraint c \
             JOIN pg_class rel ON rel.oid = c.conrelid \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             CROSS JOIN LATERAL unnest(c.conkey) AS k(attnum) \
             JOIN pg_attribute att ON att.attrelid = rel.oid AND att.attnum = k.attnum \
             WHERE c.contype = 'f' \
             UNION \
             SELECT frel.relname AS tbl, fatt.attname AS col \
             FROM pg_constraint c \
             JOIN pg_class frel ON frel.oid = c.confrelid \
             JOIN pg_namespace fns ON fns.oid = frel.relnamespace AND fns.nspname = 'public' \
             CROSS JOIN LATERAL unnest(c.confkey) AS fk(attnum) \
             JOIN pg_attribute fatt ON fatt.attrelid = frel.oid AND fatt.attnum = fk.attnum \
             WHERE c.contype = 'f'",
        )
        .load(&mut conn)
        .map_err(|e| ScrubError::Sql(e.to_string()))?,
    );

    // ── Foreign keys as whole constraints ───────────────────────────────────
    // The set above answers "may this column be rewritten"; `--sample` asks a
    // different question — "which rows must travel together" — and that needs
    // the constraint, in key order, both sides paired.
    let cloned = if has_catalog_column(&mut conn, "pg_constraint", "conparentid")? {
        "c.conparentid <> 0"
    } else {
        "false"
    };
    let constraint_rows: Vec<ConstraintRow> = sql_query(format!(
        "SELECT c.conname AS name, rel.relname AS child, frel.relname AS parent, \
         (SELECT array_agg(att.attname::text ORDER BY k.ord) \
          FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord) \
          JOIN pg_attribute att ON att.attrelid = c.conrelid AND att.attnum = k.attnum) \
         AS child_cols, \
         (SELECT array_agg(att.attname::text ORDER BY k.ord) \
          FROM unnest(c.confkey) WITH ORDINALITY AS k(attnum, ord) \
          JOIN pg_attribute att ON att.attrelid = c.confrelid AND att.attnum = k.attnum) \
         AS parent_cols, \
         {cloned} AS cloned, \
         c.confmatchtype = 'f' AS match_full \
         FROM pg_constraint c \
         JOIN pg_class rel ON rel.oid = c.conrelid \
         JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
         JOIN pg_class frel ON frel.oid = c.confrelid \
         JOIN pg_namespace fns ON fns.oid = frel.relnamespace AND fns.nspname = 'public' \
         WHERE c.contype = 'f'"
    ))
    .load(&mut conn)
    .map_err(|e| ScrubError::Sql(e.to_string()))?;
    let foreign_keys: Vec<sample::ForeignKeyConstraint> = constraint_rows
        .into_iter()
        .filter(|row| !row.cloned)
        .map(|row| sample::ForeignKeyConstraint {
            name: row.name,
            child_table: row.child,
            child_columns: row.child_cols,
            parent_table: row.parent,
            parent_columns: row.parent_cols,
            match_full: row.match_full,
        })
        .collect();

    // ── CHECK-constrained columns ───────────────────────────────────────────
    let checked_columns = pair_set(
        sql_query(
            "SELECT rel.relname AS tbl, att.attname AS col \
             FROM pg_constraint c \
             JOIN pg_class rel ON rel.oid = c.conrelid \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             CROSS JOIN LATERAL unnest(c.conkey) AS k(attnum) \
             JOIN pg_attribute att ON att.attrelid = rel.oid AND att.attnum = k.attnum \
             WHERE c.contype = 'c'",
        )
        .load(&mut conn)
        .map_err(|e| ScrubError::Sql(e.to_string()))?,
    );

    // ── Generated / identity-always columns ─────────────────────────────────
    let mut generated_predicates: Vec<&str> = Vec::new();
    if has_catalog_column(&mut conn, "pg_attribute", "attgenerated")? {
        generated_predicates.push("att.attgenerated <> ''");
    }
    if has_catalog_column(&mut conn, "pg_attribute", "attidentity")? {
        generated_predicates.push("att.attidentity = 'a'");
    }
    let generated_columns = if generated_predicates.is_empty() {
        BTreeSet::new()
    } else {
        pair_set(
            sql_query(format!(
                "SELECT rel.relname AS tbl, att.attname AS col \
                 FROM pg_attribute att \
                 JOIN pg_class rel ON rel.oid = att.attrelid \
                 JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
                 WHERE att.attnum > 0 AND NOT att.attisdropped AND ({})",
                generated_predicates.join(" OR ")
            ))
            .load(&mut conn)
            .map_err(|e| ScrubError::Sql(e.to_string()))?,
        )
    };

    // ── Uniqueness, the write-side question ─────────────────────────────────
    // ANY unique index counts (composite and partial included): the IR's
    // single-column `unique` flag answers a migration-diff question, not
    // "can this rewrite collide".
    // `pg_index.indkey` is an `int2vector`, not a real array, so it is matched
    // with `= ANY(...)` rather than `unnest`. The `[0:indnkeyatts-1]` slice is
    // the KEY columns only — a covering index's `INCLUDE` columns carry no
    // uniqueness and must not be treated as constrained.
    // Covering indexes (`INCLUDE`) arrived with `indnkeyatts` in Postgres 11; on
    // an older server every `indkey` entry IS a key column.
    let key_slice = if has_catalog_column(&mut conn, "pg_index", "indnkeyatts")? {
        "i.indkey[0:i.indnkeyatts-1]"
    } else {
        "i.indkey"
    };
    let unique_columns = pair_set(
        sql_query(format!(
            "SELECT rel.relname AS tbl, att.attname AS col \
             FROM pg_index i \
             JOIN pg_class rel ON rel.oid = i.indrelid \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             JOIN pg_attribute att ON att.attrelid = rel.oid \
             AND att.attnum = ANY({key_slice}) \
             WHERE i.indisunique AND att.attnum > 0"
        ))
        .load(&mut conn)
        .map_err(|e| ScrubError::Sql(e.to_string()))?,
    );

    // Two kinds of unique index whose real inputs `indkey` does not name:
    //
    // - an EXPRESSION index (`ON users (left(email, 1))`) stores `0` for the
    //   expression position, so the join above sees no column at all — and
    //   uniqueness after an arbitrary expression cannot be preserved by a
    //   per-row token, since `left(x, 1)` collapses every scrubbed value onto
    //   one character;
    // - a PARTIAL index (`ON events (group_id) WHERE active = false`) is keyed
    //   on `group_id`, but rewriting `active` changes which rows the index
    //   COVERS — pulling previously-excluded duplicates into it.
    //
    // Keep these in their own set, not in `unique_columns`. A strategy that is
    // unique on the column value says nothing about an expression over it, so
    // no strategy is allowed.
    //
    // `pg_depend` cannot find them: a column that an expression or predicate
    // reads is an auto dependency, like a plain key column. The stored node
    // trees name each column as `varattno N`. Match on that, as
    // `PARTITION_KEY_COLUMNS` does for expression partition keys. `varattno 0`
    // is a whole-row reference: it reads every column.
    let unique_expression_columns = pair_set(
        sql_query(
            "SELECT rel.relname AS tbl, att.attname AS col \
             FROM pg_index i \
             JOIN pg_class rel ON rel.oid = i.indrelid \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             JOIN pg_attribute att ON att.attrelid = rel.oid \
               AND att.attnum > 0 AND NOT att.attisdropped \
             WHERE i.indisunique \
               AND (i.indexprs IS NOT NULL OR i.indpred IS NOT NULL) \
               AND (coalesce(i.indexprs::text, '') || ' ' || coalesce(i.indpred::text, '')) \
                   ~ ('[^[:alnum:]_]varattno (0|' || att.attnum || ')[^0-9]')",
        )
        .load(&mut conn)
        .map_err(|e| ScrubError::Sql(e.to_string()))?,
    );

    // An exclusion constraint index is `indisexclusion`, not `indisunique`, so
    // the probes above miss it. Count its plain columns (`indkey`) and the
    // columns its expressions and predicate read (`pg_depend` and the node
    // trees, as for the unique probe above).
    let exclusion_columns = pair_set(
        sql_query(format!(
            "SELECT rel.relname AS tbl, att.attname AS col \
             FROM pg_index i \
             JOIN pg_class rel ON rel.oid = i.indrelid \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             JOIN pg_attribute att ON att.attrelid = rel.oid \
             AND att.attnum = ANY({key_slice}) \
             WHERE i.indisexclusion AND att.attnum > 0 \
             UNION \
             SELECT rel.relname, att.attname \
             FROM pg_index i \
             JOIN pg_class rel ON rel.oid = i.indrelid \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             JOIN pg_depend d ON d.objid = i.indexrelid AND d.refobjid = i.indrelid \
             JOIN pg_attribute att ON att.attrelid = rel.oid AND att.attnum = d.refobjsubid \
             WHERE i.indisexclusion AND d.refobjsubid > 0 \
             UNION \
             SELECT rel.relname, att.attname \
             FROM pg_index i \
             JOIN pg_class rel ON rel.oid = i.indrelid \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             JOIN pg_attribute att ON att.attrelid = rel.oid \
               AND att.attnum > 0 AND NOT att.attisdropped \
             WHERE i.indisexclusion \
               AND (coalesce(i.indexprs::text, '') || ' ' || coalesce(i.indpred::text, '')) \
                   ~ ('[^[:alnum:]_]varattno (0|' || att.attnum || ')[^0-9]')"
        ))
        .load(&mut conn)
        .map_err(|e| ScrubError::Sql(e.to_string()))?,
    );

    // `NULLS NOT DISTINCT` (PG15+) makes a second NULL a violation, so the
    // `null` strategy stops being unique-safe. `indnullsnotdistinct` does not
    // exist before 15; probe the column's presence first so this stays
    // compatible with older servers.
    let nulls_not_distinct_columns =
        if has_catalog_column(&mut conn, "pg_index", "indnullsnotdistinct")? {
            pair_set(
                sql_query(format!(
                    "SELECT rel.relname AS tbl, att.attname AS col \
                 FROM pg_index i \
                 JOIN pg_class rel ON rel.oid = i.indrelid \
                 JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
                 JOIN pg_attribute att ON att.attrelid = rel.oid \
                 AND att.attnum = ANY({key_slice}) \
                 WHERE i.indisunique AND i.indnullsnotdistinct AND att.attnum > 0"
                ))
                .load(&mut conn)
                .map_err(|e| ScrubError::Sql(e.to_string()))?,
            )
        } else {
            BTreeSet::new()
        };

    // ── Table-level facts ───────────────────────────────────────────────────
    let names = |q: &str, conn: &mut PgConnection| -> Result<Vec<String>, ScrubError> {
        let rows: Vec<NameRow> = sql_query(q)
            .load(conn)
            .map_err(|e| ScrubError::Sql(e.to_string()))?;
        Ok(rows.into_iter().map(|r| r.name).collect())
    };

    // Each partition mapped to the top-level table it belongs to, not just
    // named: a key declared on a leaf is unrepresentable in general, but
    // harmless when the run empties that leaf's whole tree, and only the
    // mapping can tell the two apart.
    let partitions: BTreeMap<String, String> =
        if has_catalog_column(&mut conn, "pg_class", "relispartition")? {
            pair_rows(
                "WITH RECURSIVE up AS ( \
               SELECT rel.oid, rel.oid AS leaf FROM pg_class rel \
               JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
               WHERE rel.relispartition AND rel.relkind IN ('r', 'p', 'f') \
               UNION ALL \
               SELECT i.inhparent, up.leaf FROM pg_inherits i JOIN up ON up.oid = i.inhrelid \
             ) \
             SELECT DISTINCT leafrel.relname AS tbl, rootrel.relname AS col \
             FROM up \
             JOIN pg_class leafrel ON leafrel.oid = up.leaf \
             JOIN pg_class rootrel ON rootrel.oid = up.oid \
             WHERE NOT rootrel.relispartition",
                &mut conn,
            )?
        } else {
            BTreeMap::new()
        };

    // A constraint declared on a partition alone (a child-only `CHECK`, a local
    // unique index) still fires when the run's `UPDATE` reaches that partition
    // through its parent, and the plan only looks at the parent. Fold each
    // constraint fact onto the root, as the partition keys are below.
    let foreign_key_columns = fold_into_parent(foreign_key_columns, &partitions);
    let checked_columns = fold_into_parent(checked_columns, &partitions);
    let unique_columns = fold_into_parent(unique_columns, &partitions);
    let unique_expression_columns = fold_into_parent(unique_expression_columns, &partitions);
    let exclusion_columns = fold_into_parent(exclusion_columns, &partitions);
    let nulls_not_distinct_columns = fold_into_parent(nulls_not_distinct_columns, &partitions);

    // Partition-key columns. `partattrs` holds `0` for an expression key. For
    // those tables, match the column names in the key definition. An over-match
    // refuses a non-key column, which is safe. Sub-partition keys fold into the
    // root, because a rewrite through the root moves rows across them.
    let partition_key_columns: BTreeSet<(String, String)> =
        if has_catalog_column(&mut conn, "pg_class", "relispartition")? {
            let rows = pair_set(
                sql_query(PARTITION_KEY_COLUMNS)
                    .load(&mut conn)
                    .map_err(|e| ScrubError::Sql(e.to_string()))?,
            );
            fold_into_parent(rows, &partitions)
        } else {
            BTreeSet::new()
        };

    // A declarative partition is also a `pg_inherits` child, so the partition
    // case is excluded explicitly — those the sample models through the parent
    // on purpose. What is left is legacy `INHERITS`, which it cannot.
    let legacy_inheritance: Vec<String> = {
        let partition_filter = if has_catalog_column(&mut conn, "pg_class", "relispartition")? {
            "AND NOT child.relispartition"
        } else {
            ""
        };
        let rows: Vec<NameRow> = sql_query(format!(
            "SELECT child.relname || ' (inherits ' || parent.relname || ')' AS name \
             FROM pg_inherits i \
             JOIN pg_class child ON child.oid = i.inhrelid \
             JOIN pg_namespace cns ON cns.oid = child.relnamespace AND cns.nspname = 'public' \
             JOIN pg_class parent ON parent.oid = i.inhparent \
             JOIN pg_namespace pns ON pns.oid = parent.relnamespace AND pns.nspname = 'public' \
             WHERE child.relkind IN ('r', 'p', 'f') {partition_filter}"
        ))
        .load(&mut conn)
        .map_err(|e| ScrubError::Sql(e.to_string()))?;
        let mut names: Vec<String> = rows.into_iter().map(|r| r.name).collect();
        names.sort();
        names
    };

    let rls_tables = names(RLS_RESTRICTED_TABLES, &mut conn)?
        .into_iter()
        .collect();

    // Two questions, one shape: which tables carry a user-defined trigger at
    // all (the warning), and which carry one that fires on `DELETE` (the
    // refusal). `triggers_reaching` builds both, so they cannot drift on the
    // catalog rules they share.
    // Triggers and rules alike: both run code on a write, and this warning exists
    // to say "something here can copy a row somewhere this run does not look".
    // A `DO INSTEAD` rule can also stop the sample's `DELETE` removing anything.
    let mut triggered_tables: BTreeSet<String> = names(&triggers_reaching(""), &mut conn)?
        .into_iter()
        .collect();
    triggered_tables.extend(names(&rules_reaching(""), &mut conn)?);
    // `tgtype` bit 3 is the DELETE event. These are the ones that matter for
    // the run's last write, so the refusal can name exactly the tables that
    // carry one rather than every table carrying any trigger at all.
    // Read rather than pinned: `session_replication_role` needs privileges an
    // ordinary scrub role does not have — measured, a non-superuser cannot set
    // it even to its own default — so `SET LOCAL` would break every unprivileged
    // run to close a hazard only a privileged one can create.
    let replication_role = names(
        "SELECT pg_catalog.current_setting('session_replication_role') AS name",
        &mut conn,
    )?
    .into_iter()
    .next()
    .unwrap_or_else(|| "origin".to_owned());

    // The endpoint this connection actually reached, for the dry run's target
    // guard. Comparing the database name alone is not enough: a sharded fleet
    // runs the SAME database name on different hosts — the topology in
    // docs/guide/sharding.md names all three `app` — so a retained connection to
    // one shard answers `current_database()` exactly as the intended one would.
    // Measured: two clusters both holding `app`, a failed `\connect`, and the
    // shard1 block scrubbed shard0 (200 -> 100 users) past a name-only guard.
    //
    // Read from the live connection rather than parsed out of the URL, because a
    // hostname is not what the server reports back — `inet_server_addr()` is an
    // address, and resolving one at print time is not this command's job. NULL
    // over a Unix socket, which the guard compares as NULL rather than papering
    // over.
    let (address, port) = pair_rows(
        "SELECT coalesce(pg_catalog.inet_server_addr()::text, '') AS tbl, \
         coalesce(pg_catalog.inet_server_port()::text, '') AS col",
        &mut conn,
    )?
    .into_iter()
    .next()
    .unwrap_or_default();
    // A value the target may not be able to answer for. `coalesce` to the empty
    // string rather than letting a NULL fail to deserialize, so "the role may
    // not read this" and "this connection has no such value" arrive the same
    // way: as `None`, which the guard compares as NULL.
    let optional = |query: &str, conn: &mut PgConnection| -> Option<String> {
        names(query, conn)
            .ok()
            .and_then(|rows| rows.into_iter().next())
            .filter(|value| !value.is_empty())
    };
    let setting_of = |parameter: &str| {
        format!(
            "SELECT coalesce((SELECT setting FROM pg_catalog.pg_settings \
             WHERE name = {}), '') AS name",
            quote_literal(parameter),
        )
    };
    let endpoint = ServerEndpoint {
        database: names("SELECT pg_catalog.current_database() AS name", &mut conn)?
            .into_iter()
            .next()
            .unwrap_or_default(),
        address: (!address.is_empty()).then_some(address),
        port: (!port.is_empty()).then_some(port),
        system_identifier: optional(
            "SELECT system_identifier::text AS name FROM pg_catalog.pg_control_system()",
            &mut conn,
        ),
        server_port: optional(
            "SELECT pg_catalog.current_setting('port') AS name",
            &mut conn,
        ),
        // Through `pg_settings`, not `current_setting`: the parameter is
        // restricted to `pg_read_all_settings`, and `current_setting` raises
        // `permission denied to examine ...` for a role without it — which
        // would abort the introspection an ordinary scrub role has to complete.
        // The view simply omits the row, so the scalar subquery answers NULL and
        // the guard compares NULL to NULL, losing the discriminator rather than
        // the run. Verified both ways on PostgreSQL 16.13: as a non-superuser,
        // `current_setting` errored and this returned empty.
        data_directory: optional(&setting_of("data_directory"), &mut conn),
    };

    // Rules are the other way a `DELETE` runs code the plan never saw. Unlike a
    // trigger they fire only on the relation the statement NAMES — measured on
    // PostgreSQL 16: a rule on a leaf partition or an inheritance child does not
    // fire for `DELETE FROM parent` — so this needs no walk up `pg_inherits`.
    // `ev_type` `4` is DELETE; `_RETURN` is the SELECT rule every view carries.
    let mut delete_triggered_tables: BTreeSet<String> =
        names(&triggers_reaching("AND (t.tgtype & 8) <> 0 "), &mut conn)?
            .into_iter()
            .collect();
    delete_triggered_tables.extend(names(&rules_reaching("AND r.ev_type = '4' "), &mut conn)?);

    // `m` (materialized views) belongs here as much as the table relkinds do: a
    // schema holding only `analytics.user_emails AS SELECT … FROM public.users`
    // keeps its own copy of the PII, and the refresh pass only reaches `public`.
    let other_schemas = names(
        "SELECT DISTINCT ns.nspname AS name FROM pg_class rel \
         JOIN pg_namespace ns ON ns.oid = rel.relnamespace \
         WHERE rel.relkind IN ('r', 'p', 'f', 'm') \
         AND ns.nspname NOT IN ('public', 'information_schema') \
         AND ns.nspname NOT LIKE 'pg\\_%'",
        &mut conn,
    )?
    .into_iter()
    .collect();

    // Materialized views in dependency order: a view that reads another must be
    // refreshed after it, or it re-derives from pre-scrub data. Restricted to
    // the closure `MV_REFRESH_CLOSURE` defines — every populated view, and the
    // views those read, however deep.
    let materialized_views = names(
        &format!(
            "{MV_REFRESH_CLOSURE}, depth AS ( \
                 SELECT oid, 0 AS lvl FROM needed \
                 WHERE oid NOT IN (SELECT dependent FROM nedge) \
                 UNION ALL \
                 SELECT e.dependent, d.lvl + 1 FROM nedge e JOIN depth d ON d.oid = e.source \
                 WHERE d.lvl < 32 \
             ) \
             SELECT rel.relname AS name \
             FROM (SELECT oid, max(lvl) AS lvl FROM depth GROUP BY oid) o \
             JOIN pg_class rel ON rel.oid = o.oid ORDER BY o.lvl, rel.relname"
        ),
        &mut conn,
    )?;

    // The same closure, flat and uncapped: the size report measures over this,
    // and a view the walk's depth cap dropped still occupies its heap. It has to
    // be the same set the ordered list is drawn from, because the
    // unreachable-view refusal compares the two — a view missing from only one
    // of them would be read as a view the walk could not reach.
    let all_materialized_views = names(
        &format!(
            "{MV_REFRESH_CLOSURE} \
             SELECT rel.relname AS name FROM needed n \
             JOIN pg_class rel ON rel.oid = n.oid ORDER BY rel.relname"
        ),
        &mut conn,
    )?;

    // The views whose order cannot be derived at all. Deliberately not part of
    // the closure query: this is a refusal, not an edge.
    // Over EVERY relation reachable from a materialized view, not just the views
    // themselves: `reach` walks through ordinary views, so an untracked function
    // called by one of THOSE is exactly as invisible. Measured on
    // `a_report -> bridge_view -> bridge_fn() -> z_source`, where only
    // `bridge_view`'s rule names the function — the earlier `relkind = 'm'`
    // predicate skipped it, `a_report` refreshed first from a stale `z_source`,
    // and the run reported success with all 200 original addresses still in
    // `a_report`.
    //
    // `pg_proc.prosqlbody` holds the PARSED body of a `BEGIN ATOMIC` function
    // and is NULL for a string literal, `plpgsql` or C — the property itself
    // rather than a shadow of it. It arrived in PostgreSQL 14 along with
    // `BEGIN ATOMIC`, so it is probed for like every other version-specific
    // catalog fact in this file. On an older server the answer is not
    // "unknown", it is "every one of them": before 14 no SQL body is parsed
    // into the catalog at all, so no function reached from a view can be
    // followed, and each one is untraceable by construction.
    //
    // An AGGREGATE is exempt, and only an aggregate. Its `pg_proc` row is a
    // shell with no body of any kind, so `prosqlbody` is NULL for a perfectly
    // traceable one and the predicate refused it — measured, an aggregate whose
    // transition function is a tracked `BEGIN ATOMIC` body was refused as
    // `a_report via gather`, a valid scrub blocked. Exempting it loses nothing,
    // because everything an aggregate actually runs is a separate `pg_proc` the
    // closure already reaches: measured on one with both a transition and a
    // final function, the shell records `pg_proc -> s_step` AND
    // `pg_proc -> s_final`, and the opaque final function is still named. A
    // window function (`prokind = 'w'`) is NOT exempt — it has no body because
    // it is written in C, which is opacity rather than a shell.
    let opaque_body = if has_catalog_column(&mut conn, "pg_proc", "prosqlbody")? {
        "p.prokind <> 'a' AND p.prosqlbody IS NULL"
    } else {
        "p.prokind <> 'a'"
    };
    let untraceable_view_functions = names(
        &format!(
            "{MV_REFRESH_CLOSURE}, node AS ( \
                 SELECT oid AS root, oid AS relation FROM needed \
                 UNION \
                 SELECT h.dependent, h.source FROM reach h \
                 JOIN needed nd ON nd.oid = h.dependent \
             ) \
             SELECT DISTINCT root.relname || ' via ' || p.proname AS name \
             FROM node n \
             JOIN pg_class root ON root.oid = n.root \
             JOIN viewrule rw ON rw.ev_class = n.relation \
             JOIN fn_reach fr ON fr.rule = rw.oid \
             JOIN pg_proc p ON p.oid = fr.fn \
             JOIN pg_namespace pn ON pn.oid = p.pronamespace \
             WHERE pn.nspname NOT IN ('pg_catalog', 'information_schema') \
               AND {opaque_body} \
             ORDER BY name"
        ),
        &mut conn,
    )?;

    // Views that read relations named in a STRING. Not an opaque body — there is
    // no dependency recorded at all, because the relation is named in text the
    // server parses at runtime. Detected from the rule's PARSED tree rather than
    // its SQL text, so a column or literal that merely spells the name cannot
    // trip it.
    let views_reading_by_name = names(
        &format!(
            "{MV_REFRESH_CLOSURE}, node AS ( \
                 SELECT oid AS root, oid AS relation FROM needed \
                 UNION \
                 SELECT h.dependent, h.source FROM reach h \
                 JOIN needed nd ON nd.oid = h.dependent \
             ) \
             SELECT DISTINCT root.relname || ' via ' || p.proname AS name \
             FROM node n \
             JOIN pg_class root ON root.oid = n.root \
             JOIN viewrule rw ON rw.ev_class = n.relation \
             JOIN pg_rewrite rr ON rr.oid = rw.oid \
             JOIN pg_proc p ON p.proname IN ( \
                     'query_to_xml', 'query_to_xmlschema', 'query_to_xml_and_xmlschema', \
                     'schema_to_xml', 'schema_to_xmlschema', 'schema_to_xml_and_xmlschema', \
                     'database_to_xml', 'database_to_xmlschema', \
                     'database_to_xml_and_xmlschema') \
             JOIN pg_namespace pn ON pn.oid = p.pronamespace AND pn.nspname = 'pg_catalog' \
             WHERE rr.ev_action ~ (':funcid ' || p.oid || '\\y') \
             ORDER BY name"
        ),
        &mut conn,
    )?;

    // EVERY unpopulated view, not only the closure members among them, because
    // this list closes a race as well as restoring a state. See
    // `DatabaseFacts::unpopulated_views`.
    let unpopulated_views = names(
        "SELECT rel.relname AS name FROM pg_class rel \
         JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
         WHERE rel.relkind = 'm' AND NOT rel.relispopulated ORDER BY rel.relname",
        &mut conn,
    )?;

    // ── Framework-owned tables (read from pg_class, not information_schema,
    //    which hides tables the connecting role has no privilege on) ─────────
    let wanted = probe_table_names(config)
        .iter()
        .map(|t| quote_literal(t))
        .collect::<Vec<_>>()
        .join(", ");
    let framework_tables = names(
        &format!(
            "SELECT rel.relname AS name FROM pg_class rel \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace AND ns.nspname = 'public' \
             WHERE rel.relkind IN ('r', 'p') AND rel.relname IN ({wanted}) \
             ORDER BY rel.relname"
        ),
        &mut conn,
    )?;

    // `f` (foreign tables) is deliberately included: introspection reads only
    // `BASE TABLE`, so a foreign table left pointing at production would be
    // classified by nothing at all and still report a clean scrub.
    let public_base_tables = names(PUBLIC_BASE_TABLES, &mut conn)?.into_iter().collect();
    let public_materialized_views = names(PUBLIC_MATVIEWS, &mut conn)?.into_iter().collect();
    let trigger_identities = names(TRIGGER_IDENTITIES, &mut conn)?.into_iter().collect();

    let public_columns = pair_set(
        sql_query(PUBLIC_COLUMNS)
            .load(&mut conn)
            .map_err(|e| ScrubError::Sql(e.to_string()))?,
    );

    Ok(DatabaseFacts {
        dialect: Dialect::Postgres,
        rowid_tables: BTreeSet::new(),
        foreign_key_columns,
        checked_columns,
        generated_columns,
        unique_columns,
        unique_expression_columns,
        exclusion_columns,
        nulls_not_distinct_columns,
        partitions,
        partition_key_columns,
        rls_tables,
        legacy_inheritance,
        triggered_tables,
        endpoint,
        replication_role,
        delete_triggered_tables,
        materialized_views,
        all_materialized_views,
        unpopulated_views,
        untraceable_view_functions,
        views_reading_by_name,
        other_schemas,
        framework_tables,
        public_columns,
        public_base_tables,
        public_materialized_views,
        trigger_identities,
        foreign_keys,
    })
}

/// The framework-owned table names worth probing for: the built-in payload
/// carriers plus every `[framework] purge` entry.
fn probe_table_names(config: &ScrubConfig) -> BTreeSet<String> {
    FRAMEWORK_PAYLOAD_TABLES
        .iter()
        .map(|t| (*t).to_owned())
        .chain(config.framework.purge.iter().cloned())
        .collect()
}

/// Tell the operator about framework-owned payload tables the classification
/// never sees: which ones will be emptied, and which ones are being left alone.
fn report_framework_tables(present: &[String], config: &ScrubConfig) {
    if present.is_empty() {
        return;
    }
    let (purged, kept): (Vec<&String>, Vec<&String>) = present
        .iter()
        .partition(|t| config.framework.purge.contains(t));
    for table in purged {
        eprintln!("    {table} \u{2192} emptied (framework, [framework] purge)");
    }
    // Only the built-in payload carriers are warned about: an app that named
    // some other framework table in `purge` has already decided about it.
    let kept: Vec<&&String> = kept
        .iter()
        .filter(|t| FRAMEWORK_PAYLOAD_TABLES.contains(&t.as_str()))
        .collect();
    if kept.is_empty() {
        return;
    }
    eprintln!(
        "  \u{26A0}\u{FE0F}  {} framework-owned table(s) are NOT scrubbed and may carry app-supplied \
         payloads (queued jobs, offline-sync rows, experiment assignments):\n{}\n    \
         Add them to `[framework] purge = [...]` in {SCRUB_CONFIG_FILE} to empty them, or \
         empty them yourself.",
        kept.len(),
        kept.iter()
            .map(|t| format!("      - {t}"))
            .collect::<Vec<_>>()
            .join("\n"),
    );
}

/// The `DELETE FROM` statements for the opted-in framework tables that exist.
/// The three emptying passes, in the order `execute` runs them.
///
/// `execute` and `--dry-run` both read this, because they drifted apart twice:
/// the dry run kept printing a purge order the executor no longer used, and then
/// missed the final pass entirely. One definition means the printed SQL is the
/// executed SQL by construction rather than by review.
///
/// - **before** — purges that are safe first, so the sample's deletes can remove
///   the rows they point at;
/// - **`after_sample`** — purges the sample's own emptied rows reference, which
///   have to wait for it;
/// - **`final_pass`** — every purge again, plus the `never_include` tables, run
///   after all writes. This is the pass that makes "emptied" true: a trigger on
///   a scrubbed table can insert the original PII into either kind of table
///   while the rewrites run.
fn emptying_phases<'a>(
    purges: &'a [(String, String)],
    deferred: &BTreeSet<String>,
    sampling: Option<&'a sample::SamplePlan>,
) -> EmptyingPhases<'a> {
    let owned = |t: &'a (String, String)| (t.0.as_str(), t.1.clone());
    let mut final_pass: Vec<(&str, String)> = purges.iter().map(owned).collect();
    final_pass.extend(
        sampling
            .map(sample::SamplePlan::emptied_tables)
            .unwrap_or_default(),
    );
    EmptyingPhases {
        before: purges
            .iter()
            .filter(|(t, _)| !deferred.contains(t))
            .map(owned)
            .collect(),
        after_sample: purges
            .iter()
            .filter(|(t, _)| deferred.contains(t))
            .map(owned)
            .collect(),
        final_pass,
    }
}

/// The tables `[framework] purge` empties, as owned names.
///
/// They sit outside the classified universe the sample plans over, so every
/// place that reasons about "what this run empties" has to add them back.
fn purged_tables(purges: &[(String, String)]) -> Vec<String> {
    purges.iter().map(|(table, _)| table.clone()).collect()
}

/// One target's deferred compaction: its URL and label, the sample plan, the
/// `[framework] purge` targets, the materialized views the run refreshed, and
/// the size measured before any of it ran.
///
/// Compaction can only happen after the commit — `VACUUM FULL` cannot join a
/// transaction — so every target's inputs are carried out of the loop that
/// scrubbed it.
type PendingCompaction<'a> = (
    &'a str,
    &'a str,
    &'a sample::SamplePlan,
    Vec<String>,
    Vec<String>,
    i64,
);

/// Every relation the size report measures beside the sample's own tables.
///
/// The `[framework] purge` targets, because `DELETE` frees no file space so an
/// emptied buffer keeps its whole file until compaction rewrites it — and the
/// materialized views the run refreshes, because a view is rebuilt from
/// whatever survives the sample and one over reference data does not shrink at
/// all. Both sides of the ratio use this same set, or the ratio compares
/// different things.
fn also_measured(purged: &[String], refreshed: &[String]) -> Vec<String> {
    let mut names: Vec<String> = purged.iter().chain(refreshed).cloned().collect();
    names.sort_unstable();
    names.dedup();
    names
}

/// Every table the run rewrites with `VACUUM (FULL, ANALYZE)` after the commit.
///
/// Deleting rows frees no file space, so a table this run emptied still costs
/// the source's disk until it is rewritten — and the size report is measured
/// over this same set, so a table missing here is one the run reports as
/// reclaimed while its file is untouched. `[framework] purge` targets belong in
/// it for exactly that reason: an emptied offline-sync buffer is often the
/// largest thing the run removes.
///
/// Shared with the dry run, so the printed compaction is the executed one.
fn compacted_tables<'a>(plan: &'a sample::SamplePlan, purged: &'a [String]) -> Vec<&'a str> {
    let mut tables: Vec<&str> = plan
        .subsetted_tables()
        .into_iter()
        .chain(purged.iter().map(String::as_str))
        .collect();
    tables.sort_unstable();
    tables.dedup();
    tables
}

/// The `psql` meta-command that moves the session to one target.
///
/// A bare `\connect dbname` reuses the host, port and user of the existing
/// connection, so on a fleet whose shards are the same database name on
/// different servers it silently keeps running against the first one — the
/// boundary would look like it switched and would not have.
///
/// The whole connection string is therefore passed as a conninfo, rather than
/// rebuilt from parts. Reconstruction is where this goes wrong: a query
/// parameter overrides the authority it duplicates (`?host=` beats the URL's
/// own host, as `pg::sanitize_db_url` exists to normalise), so an endpoint
/// assembled from `Url::host_str` and friends can name a database the run never
/// touches — and this string is the header on destructive SQL.
///
/// Only the password is removed. If it cannot be removed with certainty the
/// line is not emitted at all: a comment naming the target is a lesser failure
/// than a printed credential.
fn psql_connect(label: &str, url: &str) -> Vec<String> {
    password_free_conninfo(url).map_or_else(
        || {
            // Unreachable: the dry run refuses up front when any target's
            // boundary cannot be printed. Kept, and made to STOP rather than to
            // advise, because the failure mode if that guard is ever bypassed is
            // a destructive block running against the previous target. A comment
            // does not stop a paste; `\quit` does.
            vec![
                format!(
                    "\\echo '{label}: no printable connection string (keyword form) \
                     -- connect to this target yourself, then delete the \\quit below'"
                ),
                "\\quit".to_owned(),
            ]
        },
        |conninfo| {
            vec![
                // Pin the endpoint against the PASTING session's environment.
                // libpq resolves `PGHOSTADDR` and `PGSERVICE` at connect time,
                // so a script generated with them unset and pasted where they
                // are set reaches a different server than the reconnect proof
                // below asserts — while psql still reports the conninfo's own
                // host as `:HOST`, so the proof cannot catch it. The
                // generation-time guard (`endpoint_can_come_from_elsewhere`)
                // refuses targets whose environment already sets them; this
                // covers the other half, the session that pastes the script.
                // `\setenv` with no value unsets the variable. Unsetting is
                // safe for every printed target: one naming `service=` or
                // `hostaddr` in its conninfo is refused before printing, so no
                // printed `\connect` can depend on either variable.
                "\\setenv PGHOSTADDR".to_owned(),
                "\\setenv PGSERVICE".to_owned(),
                format!(
                    "\\connect -reuse-previous=off {}",
                    quote_psql_arg(&conninfo)
                ),
            ]
        },
    )
}

/// The host and port a conninfo STATES, or `None` where it leaves one to libpq.
///
/// A query pair wins over the authority it duplicates — `?host=` beats the URL's
/// own host, which is why `pg::sanitize_db_url` exists — so both are read and
/// the query is preferred, the same precedence libpq applies.
///
/// Only stated components are returned. A default is deliberately not guessed:
/// `PGPORT` can differ between the machine that planned the run and the one that
/// pastes the script, so asserting `5432` for an omitted port would refuse a
/// CORRECT paste. An omitted component also cannot be what distinguishes two
/// targets — libpq resolves it identically for both, so two conninfos that
/// differ only there are the same endpoint written twice.
/// Whether anything outside `host`/`port` can choose this target's endpoint.
///
/// `hostaddr` selects the endpoint independently of `host`, and psql reports no
/// variable for it, so a printed reconnect proof cannot pin it. It has more than
/// one source, and all of them were measured on `PostgreSQL` 16.13 reaching
/// 127.0.0.1 through a `host` that does not resolve:
///
/// - `hostaddr` in the conninfo itself;
/// - `PGHOSTADDR` in the environment;
/// - a service file, named by `service=` in the conninfo or by `PGSERVICE`,
///   which supplies `hostaddr` for an otherwise explicit URI.
///
/// A service file also cannot be read back reliably (`PGSERVICEFILE`, then
/// `~/.pg_service.conf`, then a build-time system path), so a target that uses
/// one is refused whether or not this run could find the file. See
/// `ScrubError::UnprintableHostaddrTarget`.
fn endpoint_can_come_from_elsewhere(conninfo: &str) -> bool {
    if std::env::var("PGHOSTADDR").is_ok_and(|v| !v.is_empty())
        || std::env::var("PGSERVICE").is_ok_and(|v| !v.is_empty())
    {
        return true;
    }
    let Ok(parsed) = url::Url::parse(conninfo) else {
        return false;
    };
    crate::pg::parse_raw_query_pairs(parsed.query().unwrap_or(""))
        .into_iter()
        .any(|(key, value)| (key == "hostaddr" || key == "service") && !value.is_empty())
}

/// Whether the conninfo names more than one endpoint.
///
/// libpq picks a member per connection, so the run's sizing connection and the
/// session that pastes the script need not reach the same database. See
/// `ScrubError::UnprintableMultiHostTarget`.
fn states_multiple_endpoints(conninfo: &str) -> bool {
    let (host, port) = stated_host_and_port(conninfo);
    let parts =
        |value: Option<String>| value.map_or(0, |v| v.split(',').filter(|p| !p.is_empty()).count());
    parts(host) > 1 || parts(port) > 1
}

fn stated_host_and_port(conninfo: &str) -> (Option<String>, Option<String>) {
    let Ok(parsed) = url::Url::parse(conninfo) else {
        return (None, None);
    };
    let mut host = parsed
        .host_str()
        .filter(|h| !h.is_empty())
        .map(str::to_owned);
    let mut port = parsed.port().map(|p| p.to_string());
    for (key, value) in crate::pg::parse_raw_query_pairs(parsed.query().unwrap_or("")) {
        if value.is_empty() {
            continue;
        }
        match key.as_str() {
            "host" => host = Some(value),
            "port" => port = Some(value),
            _ => {}
        }
    }
    (host, port)
}

/// The psql-level proof that `\connect` actually moved the session, read from
/// psql's OWN connection variables rather than from anything the server reports.
///
/// The in-transaction guard below compares what the server says about itself,
/// and that is not the connection's identity. `inet_server_addr()` and
/// `inet_server_port()` are the address and port the SERVER accepted on, not the
/// endpoint the operator configured — measured through a forwarder, a session
/// connected to `127.0.0.1:15433` reports `127.0.0.1:5433`. So two servers
/// behind different forwards, or in separate container networks with the same
/// private address, report the same pair; add a physical clone's inherited
/// `system_identifier` and a container-local `data_directory` both answer
/// `/var/lib/postgresql/data` to, and every value that guard compares can match
/// on two different databases. (Two colliding networks are not something this
/// container can build, and I am not claiming to have run that half.)
///
/// psql's `:HOST`, `:PORT` and `:DBNAME` are connection-specific in the way the
/// server's answers are not: they describe the conninfo psql resolved, and a
/// failed `\connect` leaves them describing the PREVIOUS one. Measured on psql
/// 16.13 in an interactive session, where `ON_ERROR_STOP` is ignored and a
/// failed `\connect` keeps the old connection: before, `HOST=127.0.0.1
/// PORT=15433 DBNAME=postgres`; after a `\connect` to port 25433 failed,
/// unchanged — and `inet_server_port()` still answered for the old server.
/// A failed `\connect` sets no error flag to fence on instead: measured,
/// `:ERROR` is still unset afterwards and `LAST_ERROR_MESSAGE` is empty.
///
/// The comparison is `pg_catalog`-qualified so a `public.=` cannot answer it,
/// and the flag is cleared first so a `\gset` whose query fails leaves it false.
fn psql_connection_terms(conninfo: &str, database: &str) -> String {
    let equals = |variable: &str, value: &str| {
        format!(
            ":'{variable}' OPERATOR(pg_catalog.=) {}",
            quote_literal(value)
        )
    };
    let database_is = equals("DBNAME", database);
    // A conninfo that states no host cannot be proved at all, so the proof is
    // `false` and the block is skipped. Unreachable today — a URI with an empty
    // authority (`postgres:///app`, `postgres://user@/app`) fails
    // `password_free_conninfo`, and the run refuses to print it as an
    // unprintable target before this is ever reached, measured both ways — but
    // stated here rather than left to that distant refusal. Omitting the host
    // term instead would silently drop the one discriminator this proof exists
    // for, leaving the database name to stand alone against a physical clone
    // that shares it.
    let (Some(host), port) = stated_host_and_port(conninfo) else {
        return "false".to_owned();
    };
    let hosts: Vec<&str> = host.split(',').filter(|part| !part.is_empty()).collect();
    let ports: Vec<&str> = port
        .as_deref()
        .map(|p| p.split(',').filter(|part| !part.is_empty()).collect())
        .unwrap_or_default();
    if hosts.is_empty() {
        return "false".to_owned();
    }
    let any_host = || {
        hosts
            .iter()
            .map(|h| equals("HOST", h))
            .collect::<Vec<_>>()
            .join(" OR ")
    };
    // libpq pairs a multi-host list with a multi-port list POSITIONALLY, and
    // broadcasts a single port to every host. Measured on 16.13:
    // `host=127.0.0.9,127.0.0.1&port=5433,5434` connected to 5434 — the port
    // belonging to the host it reached, not the first in the list — and
    // `host=127.0.0.9,127.0.0.1&port=5433` connected to 5433. So `a:5433` is NOT
    // an endpoint `host=a,b&port=5432,5433` names, and matching host and port
    // independently would accept a retained connection to one.
    let endpoint = match (ports.len(), hosts.len()) {
        // Unreachable: a conninfo stating no port is refused before any line is
        // printed, for the reason above. Fail closed rather than accept any port
        // for the host if that refusal is ever relaxed.
        (0, _) => return "false".to_owned(),
        (1, _) => format!("({}) AND {}", any_host(), equals("PORT", ports[0])),
        (p, h) if p == h => hosts
            .iter()
            .zip(&ports)
            .map(|(host, port)| format!("({} AND {})", equals("HOST", host), equals("PORT", port)))
            .collect::<Vec<_>>()
            .join(" OR "),
        // libpq refuses this outright — measured, `could not match 3 port
        // numbers to 2 hosts` — so the run could not have connected either.
        _ => return "false".to_owned(),
    };
    format!("{database_is} AND ({endpoint})")
}

/// Those terms as the psql conditional each target's transaction opens with.
fn psql_connection_assertion(conninfo: &str, database: &str) -> Vec<String> {
    vec![
        "\\set autumn_ok false".to_owned(),
        format!(
            "SELECT ({}) AS autumn_ok \\gset",
            psql_connection_terms(conninfo, database)
        ),
        "\\if :autumn_ok".to_owned(),
    ]
}

/// Abort the transaction unless the session is on the target this block is for.
///
/// `\connect` does NOT close the old connection when the new one fails. Measured
/// on psql 16.13: a failed `\connect -reuse-previous=off` prints "Previous
/// connection kept" and the session carries on against the PREVIOUS database, so
/// a pasted stream runs this target's `BEGIN` and its deletes against the
/// preceding one. `\set ON_ERROR_STOP on` does not help; measured, an
/// interactive session ignores it and keeps going. It is the likely case rather
/// than a remote one, because the printed conninfo has its password removed on
/// purpose: a password-authenticated target fails to connect exactly this way.
///
/// Identity is the whole endpoint, not the database name. A sharded fleet runs
/// the same name on every shard — the topology in docs/guide/sharding.md names
/// all three `app` — and measured on two clusters both holding `app`, a
/// name-only guard let shard1's block scrub shard0 from 200 users to 100 while
/// the shard it named went untouched.
///
/// Every value is asked of the target connection while planning, never parsed
/// out of its URL. libpq defaults an omitted database name to the user name,
/// which defaults to the OS user: deriving it meant reimplementing those rules,
/// and the version that tried simply emitted NO guard for a URI without one,
/// leaving 19 destructive statements unprotected.
///
/// Every call is `pg_catalog`-qualified, and the caller emits this after the
/// session pins. Unqualified, they are resolved by the pasting session's own
/// `search_path`: measured on a database configured `public, pg_catalog`, a
/// `public.current_database()` returning the intended name answered `app` while
/// `pg_catalog.current_database()` answered the truth, so the guard would have
/// consulted the shadow and passed.
///
/// `IS DISTINCT FROM` rather than `<>`, because address and port are both NULL
/// over a Unix socket and `NULL <> NULL` is NULL, which would let the guard pass
/// by failing to be false.
///
/// Printed and never executed: `execute` opens its own connection to a URL it
/// was given and cannot be on the wrong database.
fn target_guard(endpoint: &ServerEndpoint) -> String {
    let literal =
        |value: Option<&String>| value.map_or_else(|| "NULL".to_owned(), |v| quote_literal(v));
    // `RAISE` substitutes bare `%` in argument order and has no `%1$s` form.
    // Writing one named each database as the other and left `2$s` in the text.
    // Every parameter is read the same way the introspection read it, so a value
    // the pasting role may not examine answers NULL on BOTH sides rather than
    // raising inside the guard: `pg_settings` omits a restricted row, where
    // `current_setting` would raise `permission denied to examine ...`.
    let setting = |parameter: &str| {
        format!(
            "coalesce((SELECT setting FROM pg_catalog.pg_settings WHERE name = {}), '')",
            quote_literal(parameter),
        )
    };
    let datadir = setting("data_directory");
    let sysid_call = "(SELECT system_identifier::text FROM pg_catalog.pg_control_system())";
    let body = format!(
        " BEGIN IF {mismatch} THEN \
         RAISE EXCEPTION {message}, {name}, {addr}, {port}, {sysid}, {server_port}, \
         {datadir_want}, \
         pg_catalog.current_database(), pg_catalog.inet_server_addr()::text, \
         pg_catalog.inet_server_port()::text, {sysid_seen}, \
         pg_catalog.current_setting('port'), {datadir_seen}; END IF; END ",
        mismatch = endpoint_mismatch(endpoint),
        // Report a discriminator the planning role could not read as unknown
        // rather than calling for it: `pg_control_system()` raises for a role
        // without EXECUTE, and a RAISE whose own argument raises replaces the
        // mismatch this block exists to explain with `permission denied for
        // function pg_control_system`.
        sysid_seen = if endpoint.system_identifier.is_some() {
            sysid_call.to_owned()
        } else {
            "NULL".to_owned()
        },
        datadir_seen = if endpoint.data_directory.is_some() {
            format!("nullif({datadir}, '')")
        } else {
            "NULL".to_owned()
        },
        name = quote_literal(&endpoint.database),
        addr = literal(endpoint.address.as_ref()),
        port = literal(endpoint.port.as_ref()),
        sysid = literal(endpoint.system_identifier.as_ref()),
        server_port = literal(endpoint.server_port.as_ref()),
        datadir_want = literal(endpoint.data_directory.as_ref()),
        message = quote_literal(
            "this block is for % at %:% (cluster %, port %, data directory %), but the \
             session is on % at %:% (cluster %, port %, data directory %) — the \
             \\connect above did not take effect (psql keeps the previous connection \
             when one fails)"
        ),
    );
    let tag = sample::dollar_tag(&body);
    format!("DO {tag}{body}{tag};")
}

/// Abort the transaction unless the pasting session fires the same triggers the
/// plan was built against.
///
/// `session_replication_role` decides which triggers fire: `origin` fires `O`
/// and `A`, `replica` fires `R` and `A`. The run REFUSES to plan from a
/// connection that is not `origin`, because `triggers_reaching` only ever
/// inspected the `O`/`A` set — but the printed script inherits whatever the
/// pasting session is in, and nothing in it said so. An operator already
/// connected to the right endpoint in `replica` can paste a block whose
/// `\connect` fails (the printed conninfo has its password removed on purpose),
/// keep that session, pass both the psql proof and the endpoint guard — every
/// value matches, it IS the right database — and then fire a replica-only
/// trigger on a table the final pass empties, copying `OLD` rows into one the
/// rewrites already scrubbed.
///
/// Asserted rather than pinned, exactly as the command refuses rather than
/// resets: `session_replication_role` is `SUSET`, so a `SET LOCAL` would fail
/// for the ordinary role this script is written for, and silently switching a
/// superuser out of a mode they chose is not this command's call.
fn replication_role_assertion() -> String {
    let body = " BEGIN IF pg_catalog.current_setting('session_replication_role') <> 'origin' \
                 THEN RAISE EXCEPTION 'this block was planned against \
                 session_replication_role = origin, but this session is in % — a \
                 replica-only trigger fires here that the plan never inspected'\
                 , pg_catalog.current_setting('session_replication_role'); END IF; END "
        .to_owned();
    let tag = sample::dollar_tag(&body);
    format!("DO {tag}{body}{tag};")
}

/// The boolean that is TRUE when the session is NOT on the endpoint this block
/// was planned for.
///
/// Shared by the in-transaction guard and by the psql conditional that fences
/// the post-`COMMIT` compaction, so the two cannot come to disagree about what
/// counts as the right server.
fn endpoint_mismatch(endpoint: &ServerEndpoint) -> String {
    let literal =
        |value: Option<&String>| value.map_or_else(|| "NULL".to_owned(), |v| quote_literal(v));
    // Address and port are compared even when `None`, because there `None` is
    // the target's REAL answer: both are NULL for every Unix-socket connection,
    // and pinning that is what stops a socket block running against a TCP one.
    let mut terms = vec![
        format!(
            "pg_catalog.current_database() <> {}",
            quote_literal(&endpoint.database)
        ),
        format!(
            "pg_catalog.inet_server_addr()::text IS DISTINCT FROM {}",
            literal(endpoint.address.as_ref())
        ),
        format!(
            "pg_catalog.inet_server_port()::text IS DISTINCT FROM {}",
            literal(endpoint.port.as_ref())
        ),
        format!(
            "pg_catalog.current_setting('port') IS DISTINCT FROM {}",
            literal(endpoint.server_port.as_ref())
        ),
    ];
    // These two are different: `None` means the PLANNING role could not read the
    // value, not that the target has none — every live server has both. A term
    // comparing against a value we never learned can only be wrong. It refuses a
    // CORRECT paste whenever the pasting role can read what the planning role
    // could not, and `pg_control_system()` is worse still: measured, with its
    // EXECUTE revoked an ordinary role gets `permission denied for function
    // pg_control_system`, which inside the guard aborts the transaction and
    // takes the whole paste down. So an unreadable discriminator is dropped
    // rather than guessed at; the four above still identify the endpoint.
    if let Some(sysid) = endpoint.system_identifier.as_ref() {
        terms.push(format!(
            "(SELECT system_identifier::text FROM pg_catalog.pg_control_system()) \
             IS DISTINCT FROM {}",
            quote_literal(sysid)
        ));
    }
    if let Some(datadir) = endpoint.data_directory.as_ref() {
        terms.push(format!(
            "nullif(coalesce((SELECT setting FROM pg_catalog.pg_settings \
             WHERE name = 'data_directory'), ''), '') IS DISTINCT FROM {}",
            quote_literal(datadir)
        ));
    }
    terms.join(" OR ")
}

/// The psql predicate that decides whether this target really scrubbed, read by
/// the compaction pass that runs after every target's `COMMIT`.
///
/// `VACUUM (FULL)` cannot run inside a transaction block, so the compaction is
/// the one part of a target's plan the in-transaction guard cannot cover — and
/// measured, that gap was reachable. When a `\connect` fails psql keeps the
/// previous connection; the guard aborts the transaction, every `DELETE` below
/// it is refused, and the printed `COMMIT` then turns that abort into a
/// `ROLLBACK` and clears the aborted state. On a `pg_basebackup` clone pasted
/// at its origin, all 64 destructive statements were refused and six
/// `VACUUM (FULL, ANALYZE)` statements then ran on the ORIGIN — each taking an
/// `ACCESS EXCLUSIVE` lock and rewriting the table.
///
/// So psql decides instead of the server. `\gset` reads the same predicate the
/// guard uses into `autumn_ok`, and the compaction pass `\if`s on it. Both
/// failure modes are closed, measured on psql 16.13: a false value prints
/// `query ignored`, and a `\gset` whose query ERRORED leaves the variable
/// unset, which `\if` reports as `Boolean expected` and still skips.
///
/// The `\if` itself is NOT emitted here. Compaction is printed after every
/// target's transaction rather than inside one, because that is where the
/// executor runs it; this leaves the flag for that pass to read.
///
/// The `search_path` pin is re-applied first because the run's own pins are
/// `SET LOCAL` — they belong to the transaction that just rolled back, so the
/// operators in this predicate would otherwise resolve through whatever the
/// pasting session's path happens to be.
fn post_commit_fence(endpoint: &ServerEndpoint) -> Vec<String> {
    vec![
        // FIRST, before any statement runs: a query would reset psql's own
        // `:ERROR`, and this is the only moment it still describes the `COMMIT`.
        // `\set` is a meta-command and executes nothing, so it is safe here.
        "\\set autumn_commit_error :ERROR".to_owned(),
        "SET search_path = pg_catalog, public;".to_owned(),
        // False FIRST, so a `\\gset` whose query fails leaves it false instead of
        // carrying the previous target's success forward.
        "\\set autumn_ok false".to_owned(),
        format!(
            "SELECT (:'autumn_scrubbed'::bool AND NOT :'autumn_commit_error'::bool \
             AND NOT ({})) AS autumn_ok \\gset",
            endpoint_mismatch(endpoint),
        ),
    ]
}

/// Connection-string keywords whose value is a credential, stripped before
/// printing.
///
/// A URI carries these two ways — `postgres://user:secret@host/db` and
/// `postgres://host/db?password=secret` — and the query form wins where both
/// appear, which `pg::sanitize_prefers_query_user_password_dbname_over_url_structure`
/// pins. Clearing only the userinfo therefore prints the effective password.
///
/// `oauth_client_secret` (Postgres 18) authenticates the same way a password
/// does, and the old two-keyword denylist printed it verbatim into `--dry-run`
/// output — the output that exists to be pasted and shared.
const SECRET_KEYWORDS: [&str; 3] = ["password", "sslpassword", "oauth_client_secret"];

/// Connection-string keywords known to carry no credential.
///
/// An allowlist, not a denylist: this function's contract is credential-free
/// output, and a denylist fails open the day a Postgres release adds a
/// parameter nobody here has heard of — which is exactly how
/// `oauth_client_secret` arrived above. A keyword on neither list makes the
/// whole conninfo unprintable: the dry run refuses the target
/// (`UnprintableTarget`) rather than guessing about a parameter it cannot
/// vouch for. Dropping the unknown keyword instead would be the worse
/// failure — dropping `hostaddr` reconnects somewhere else, and dropping a
/// future credential parameter prints a conninfo that cannot do what the run
/// did.
///
/// Compared without case, because a URI query key is not normalised for us.
/// `passfile`, `sslcert` and friends name files, not secrets — printing the
/// path does not print the credential — so they stay printable.
const PRINTABLE_KEYWORDS: [&str; 47] = [
    "application_name",
    "channel_binding",
    "client_encoding",
    "connect_timeout",
    "dbname",
    "fallback_application_name",
    "gssdelegation",
    "gssencmode",
    "gsslib",
    "host",
    "hostaddr",
    "keepalives",
    "keepalives_count",
    "keepalives_idle",
    "keepalives_interval",
    "krbsrvname",
    "load_balance_hosts",
    "max_protocol_version",
    "min_protocol_version",
    "oauth_client_id",
    "oauth_discovery_url",
    "oauth_issuer",
    "oauth_scope",
    "options",
    "passfile",
    "port",
    "replication",
    "require_auth",
    "requirepeer",
    "requiressl",
    "service",
    "ssl_max_protocol_version",
    "ssl_min_protocol_version",
    "sslcert",
    "sslcertmode",
    "sslcompression",
    "sslcrl",
    "sslcrldir",
    "sslkey",
    "sslkeylogfile",
    "sslmode",
    "sslnegotiation",
    "sslrootcert",
    "sslsni",
    "target_session_attrs",
    "tcp_user_timeout",
    "user",
];

/// `url` with every credential removed, or `None` if that cannot be guaranteed.
///
/// Only the URI form is handled. Keyword form (`host=db password = secret`)
/// looks tokenizable and is not: `libpq` allows whitespace around the `=`, and
/// values may be single-quoted with backslash escapes, so "split on whitespace
/// and drop the secret tokens" has now been wrong twice in a row — once for a
/// quoted value, once for a spaced `=`. Rather than reach for a third
/// tokenizer, that form is declined outright, which makes the promise above
/// true by construction instead of by enumerating the ways it can be written.
///
/// The query half is an allowlist (`PRINTABLE_KEYWORDS`), not a denylist: any
/// keyword that is neither a stripped credential nor known-non-secret refuses
/// the whole conninfo, so a parameter a future Postgres release invents —
/// the way 18's `oauth_client_secret` arrived — cannot slip a credential into
/// printed output.
fn password_free_conninfo(url: &str) -> Option<String> {
    let mut parsed = url::Url::parse(url).ok()?;
    // `set_password` returns Err only for a URL that cannot have one
    // (`mailto:` and friends), which a connection string is not.
    parsed.set_password(None).ok()?;
    // Read and rewrite the query the way libpq does, NOT the way
    // `url::Url::query_pairs()` does. That method applies
    // `application/x-www-form-urlencoded` rules, and its `query_pairs_mut()`
    // counterpart serializes a space back as `+` — while libpq's URI parser
    // only ever percent-decodes, so it reads that `+` literally. Measured
    // against psql 16.13: an operator's `?options=-c%20search_path%3Dpg_catalog`
    // connects and sets the path, and the `+` form this used to print does not
    // connect at all —
    //
    //   FATAL:  unrecognized configuration parameter "+search_path"
    //
    // which is the failure mode the target guard exists for. `pg.rs` already
    // holds both halves of the libpq grammar, with the reasoning; this uses
    // them rather than keeping a second opinion about encoding here.
    let pairs = crate::pg::parse_raw_query_pairs(parsed.query().unwrap_or(""));
    // Fail closed on a keyword on neither list: this is the allowlist half —
    // a parameter this code has never heard of refuses the whole conninfo
    // rather than being printed. Dropping it instead would be the worse
    // failure: dropping `hostaddr` reconnects somewhere else, and dropping a
    // future credential parameter prints a conninfo that cannot do what the
    // run did. The dry run refuses such a target up front
    // (`UnprintableTarget`).
    if pairs
        .iter()
        .any(|(key, _)| !is_secret_keyword(key) && !is_printable_keyword(key))
    {
        return None;
    }
    let kept: Vec<(String, String)> = pairs
        .into_iter()
        .filter(|(key, _)| !is_secret_keyword(key))
        .collect();
    if kept.is_empty() {
        parsed.set_query(None);
    } else {
        let query = kept
            .iter()
            .map(|(key, value)| {
                format!(
                    "{}={}",
                    crate::pg::query_value_token(key),
                    crate::pg::query_value_token(value),
                )
            })
            .collect::<Vec<_>>()
            .join("&");
        parsed.set_query(Some(&query));
    }
    Some(parsed.into())
}

/// Whether a connection-string keyword carries a credential. Compared without
/// case, because a URI query key is not normalised for us.
fn is_secret_keyword(key: &str) -> bool {
    SECRET_KEYWORDS
        .iter()
        .any(|secret| key.eq_ignore_ascii_case(secret))
}

/// Whether a connection-string keyword is known to carry no credential.
/// Compared without case, like `is_secret_keyword`.
fn is_printable_keyword(key: &str) -> bool {
    PRINTABLE_KEYWORDS
        .iter()
        .any(|known| key.eq_ignore_ascii_case(known))
}

/// One `psql` meta-command argument, double-quoted with backslash escapes —
/// `psql` reads them that way inside double quotes, unlike SQL identifiers.
fn quote_psql_arg(value: &str) -> String {
    let escaped: String = value
        .chars()
        .flat_map(|c| {
            let escape = matches!(c, '"' | '\\');
            escape.then_some('\\').into_iter().chain(std::iter::once(c))
        })
        .collect();
    format!("\"{escaped}\"")
}

/// The session settings the scrub pins for the whole transaction.
///
/// A role- or database-level `search_path` (tenant schemas) would otherwise
/// redirect an unqualified name — every `md5`, `quote_nullable` and `count` the
/// generated SQL calls — to something the classification never saw, and
/// `quote_literal`'s doubled quotes would mean something else under
/// `standard_conforming_strings = off`.
///
/// Shared with the dry run: printing the statements without them advertises SQL
/// that resolves differently from the command it claims to be, on exactly the
/// targets whose `search_path` made the pinning necessary.
fn session_settings() -> Vec<String> {
    [
        "SET LOCAL search_path = pg_catalog, public",
        "SET LOCAL standard_conforming_strings = on",
        // The rest pin how a value RENDERS, because the sample's row key is
        // hashed from `key::text` and `--seed` promises the same seed against
        // the same source selects the same rows. Measured: the same seed over a
        // `date` primary key selects a different subset under `DateStyle = ISO,
        // YMD` than under `Postgres, DMY`. `bytea_output` and
        // `extra_float_digits` do the same for their types, and `IntervalStyle`
        // for intervals. (`TimeZone` is pinned by the driver on connect, but
        // relying on that leaves the guarantee resting on a dependency's
        // default.)
        "SET LOCAL DateStyle = 'ISO, YMD'",
        "SET LOCAL IntervalStyle = 'iso_8601'",
        "SET LOCAL TimeZone = 'UTC'",
        "SET LOCAL bytea_output = 'hex'",
        "SET LOCAL lc_monetary = 'C'",
        "SET LOCAL extra_float_digits = 3",
    ]
    .into_iter()
    .map(str::to_owned)
    .collect()
}

/// Every table the run locks, deduplicated and ordered, as `LOCK TABLE` SQL.
///
/// Shared with the dry run: an operator pasting the printed sequence into a
/// target that still takes writes must exclude the same writers the command
/// does, or a row inserted after that table's `DELETE` survives unsampled and
/// unscrubbed — a difference between the advertised SQL and the real one that
/// shows up as data, not as an error.
fn lock_statements(
    plan: &ScrubPlan,
    purges: &[(String, String)],
    sampling: Option<&sample::SamplePlan>,
) -> Vec<String> {
    let mut locked: Vec<&str> = plan
        .tables
        .iter()
        .map(|t| t.table.as_str())
        .chain(purges.iter().map(|(table, _)| table.as_str()))
        // Every table the sample reads or empties, too: a row inserted into one
        // after the walk selected from it would survive a run that reports the
        // table subsetted.
        .chain(
            sampling
                .into_iter()
                .flat_map(sample::SamplePlan::locked_tables),
        )
        .collect();
    locked.sort_unstable();
    locked.dedup();
    locked
        .into_iter()
        .map(|table| {
            format!(
                "LOCK TABLE {} IN SHARE ROW EXCLUSIVE MODE",
                qualified_ident(table)
            )
        })
        .collect()
}

/// The SQL that asserts a foreign key re-count found no orphans.
///
/// `execute` reads the count so it can report how many; the dry run prints this,
/// because a bare `SELECT count(*)` in a pasted sequence returns a number and
/// then commits anyway — exactly the run the command refuses.
fn integrity_assertion(check: &str) -> String {
    // The tag is chosen from the finished body, never fixed: `check` carries
    // quoted identifiers, a Postgres identifier may legally contain `$`, and
    // dollar quoting is lexical — a `$$` inside a column name would close this
    // block mid-statement and turn the rest into a syntax error in the one
    // sequence the operator was told to paste.
    let body = format!(
        "BEGIN IF ({check}) > 0 THEN \
         RAISE EXCEPTION 'a foreign key this run checked does not resolve'; \
         END IF; END"
    );
    let tag = sample::dollar_tag(&body);
    format!("DO {tag} {body} {tag}")
}

/// The SQL that asserts a promised-empty table really is empty.
///
/// `execute` runs the equivalent as a counted query so it can name the row
/// count; the dry run prints this, because a printed sequence that commits where
/// the real command aborts is worse than no sequence at all. Emitted as a `DO`
/// block so pasting it actually fails the transaction rather than quietly
/// returning a row. The table name appears only as an identifier — already
/// quoted — so nothing has to be escaped into a string literal.
fn emptiness_assertion(table: &str) -> String {
    // Same reason as `integrity_assertion`: the table name is an identifier and
    // may legally contain `$`, so the delimiter comes from the body.
    let body = format!(
        "BEGIN IF EXISTS (SELECT 1 FROM {}) THEN \
         RAISE EXCEPTION 'a table this run promised would be empty still holds rows'; \
         END IF; END",
        qualified_ident(table)
    );
    let tag = sample::dollar_tag(&body);
    format!("DO {tag} {body} {tag}")
}

/// The emptying passes `emptying_phases` returns, as `(table, statement)`.
struct EmptyingPhases<'a> {
    before: Vec<(&'a str, String)>,
    after_sample: Vec<(&'a str, String)>,
    final_pass: Vec<(&'a str, String)>,
}

fn purge_statements(present: &[String], config: &ScrubConfig) -> Vec<(String, String)> {
    present
        .iter()
        .filter(|t| config.framework.purge.contains(t))
        .map(|t| (t.clone(), format!("DELETE FROM {}", qualified_ident(t))))
        .collect()
}

/// Resolve the target's attribute-encryption key ring from the project's
/// credentials for `profile`.
///
/// Refused rather than skipped when the plan needs one: writing a plain string
/// into an `#[encrypted]` column would make every later repository read of that
/// row fail as malformed ciphertext, so a missing key is a hard stop, not a
/// silent downgrade.
fn resolve_key_ring(
    profile: &str,
    project_root: &Path,
) -> Result<autumn_web::encryption::KeyRing, ScrubError> {
    let store = autumn_web::credentials::load_credentials(profile, project_root).map_err(|e| {
        ScrubError::EncryptionKeyUnavailable {
            profile: profile.to_owned(),
            detail: e.to_string(),
        }
    })?;
    match autumn_web::encryption::key_ring_from_credentials(&store) {
        Ok(Some(ring)) => Ok(ring),
        Ok(None) => Err(ScrubError::EncryptionKeyUnavailable {
            profile: profile.to_owned(),
            detail: format!(
                "`{}.primary_key` is not configured",
                autumn_web::encryption::CREDENTIALS_NAMESPACE
            ),
        }),
        Err(e) => Err(ScrubError::EncryptionKeyUnavailable {
            profile: profile.to_owned(),
            detail: e.to_string(),
        }),
    }
}

/// How many rows of encrypted replacements are shipped back per statement.
const ENCRYPTED_BATCH_ROWS: usize = 500;

/// One row's encrypted replacement.
#[derive(diesel::QueryableByName)]
struct RowTokenRow {
    #[diesel(sql_type = diesel::sql_types::Text)]
    row_key: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    token: String,
}

/// Rewrite one `#[encrypted]` column, row by row, with a valid AEAD envelope of
/// a fake plaintext produced under the target's own key.
///
/// This is the one rewrite that cannot be a SQL expression: the envelope is
/// `base64(header ‖ nonce ‖ ciphertext)` built by [`autumn_web::encryption`], so
/// the rows are read, encrypted in Rust, and shipped back in batched
/// `UPDATE … FROM (VALUES …)` statements. Rows whose value is already `NULL` are
/// left alone, exactly as the SQL path's `CASE` does.
fn rewrite_encrypted_column(
    conn: &mut PgConnection,
    table: &str,
    row_key: &str,
    rewrite: &EncryptedRewrite,
) -> Result<usize, diesel::result::Error> {
    use autumn_web::encryption::{Mode, encrypt_text};

    let ident = quote_ident(&rewrite.column);
    let seed = format!("{} || '|' || ({row_key})", quote_literal(&rewrite.column));
    let rows: Vec<RowTokenRow> = sql_query(format!(
        "SELECT ({row_key}) AS row_key, md5({seed}) || md5(({seed}) || '#2') AS token \
         FROM {} WHERE {ident} IS NOT NULL",
        qualified_ident(table),
    ))
    .load(conn)?;

    let mode = if rewrite.deterministic {
        Mode::Deterministic
    } else {
        Mode::Randomized
    };
    let mut updated = 0;
    for chunk in rows.chunks(ENCRYPTED_BATCH_ROWS) {
        let mut values = Vec::with_capacity(chunk.len());
        for row in chunk {
            let plaintext = encrypted_plaintext(rewrite.shape, &row.token);
            // A key ring is installed before the apply pass, so this can only
            // fail on a genuinely broken key — surfaced as a SQL-shaped error so
            // the transaction rolls back with everything else.
            let envelope = encrypt_text(mode, &plaintext).map_err(|e| {
                diesel::result::Error::QueryBuilderError(
                    format!(
                        "could not encrypt a replacement for {table}.{}: {e}",
                        rewrite.column
                    )
                    .into(),
                )
            })?;
            values.push(format!(
                "({}, {})",
                quote_literal(&row.row_key),
                quote_literal(&envelope)
            ));
        }
        updated += sql_query(format!(
            "UPDATE {} AS t SET {ident} = v.val FROM (VALUES {}) AS v(k, val) \
             WHERE ({row_key}) = v.k",
            qualified_ident(table),
            values.join(", ")
        ))
        .execute(conn)?;
    }
    Ok(updated)
}

/// The plaintext sealed into an `#[encrypted]` column for one row.
fn encrypted_plaintext(shape: Strategy, token: &str) -> String {
    match shape {
        Strategy::Email => format!("scrubbed+{token}{SCRUB_EMAIL_DOMAIN}"),
        _ => format!("[scrubbed:{token}]"),
    }
}

/// Characters of the stored base64 envelope for [`encrypted_plaintext`]: a
/// 20-byte header, the plaintext, and a 16-byte AEAD tag. The token is two
/// `md5` hex digests, 64 characters.
fn envelope_len(shape: Strategy) -> usize {
    const HEADER_AND_TAG: usize = 20 + 16;
    const TOKEN: usize = 64;
    let plaintext = encrypted_plaintext(shape, &"0".repeat(TOKEN)).len();
    (HEADER_AND_TAG + plaintext).div_ceil(3) * 4
}

/// What one database's scrub wrote: `(table, rows)` per rewrite, plus the
/// sample's own outcome when `--sample` was given.
type Applied = (Vec<(String, usize)>, Option<sample::SampleOutcome>);

/// The materialized-view work one target's transaction owes: which views to
/// refresh and in what order, the flat closure the size report measures over,
/// and every view to leave `WITH NO DATA` once those refreshes are done.
struct ViewRefresh<'a> {
    ordered: &'a [String],
    all: &'a [String],
    unpopulated: &'a [String],
}

/// Re-check the sample's postconditions after every materialized view refresh.
///
/// `sample::apply` selects the subset, deletes, verifies the foreign keys and
/// counts — all BEFORE the refreshes, which are the last writes in the
/// transaction and can perform DML of their own. Measured, a tracked `BEGIN
/// ATOMIC` function writing into `comments` left the run reporting
/// `comments: 403 -> 4 row(s)` and `Scrub complete` over a table holding 7 rows,
/// 3 of them never rewritten: the subset was not the subset, and the reported
/// number was not the number.
///
/// A refresh can also UPDATE, which moves no count. Re-running the foreign-key
/// checks catches the part of that which breaks the subset's integrity; an
/// in-place edit that keeps every reference valid is not something this run can
/// see, and is not claimed to be.
fn verify_sample_survived_refreshes(
    conn: &mut PgConnection,
    settled: &sample::SampleOutcome,
    plan: &sample::SamplePlan,
) -> Result<(), sample::SampleFailure> {
    let mut moved = Vec::new();
    for count in &settled.counts {
        let now: RowCount = sql_query(format!(
            "SELECT count(*) AS n FROM {}",
            qualified_ident(&count.table)
        ))
        .get_result(conn)?;
        if now.n != count.after {
            moved.push(format!(
                "{} ({} row(s), sampled to {})",
                count.table, now.n, count.after
            ));
        }
    }
    if !moved.is_empty() {
        moved.sort();
        return Err(sample::SampleFailure::Refused(
            sample::SampleError::SampleMutatedByRefresh { tables: moved },
        ));
    }
    let mut violations = Vec::new();
    for (label, sql) in &plan.integrity_statements() {
        let orphans: RowCount = sql_query(sql).get_result(conn)?;
        if orphans.n > 0 {
            violations.push(format!("{label}: {} unresolved reference(s)", orphans.n));
        }
    }
    if !violations.is_empty() {
        violations.sort();
        return Err(sample::SampleFailure::Refused(
            sample::SampleError::IntegrityViolation { violations },
        ));
    }
    Ok(())
}

/// Run every statement for one database inside a single transaction, so a
/// failure can never leave a half-scrubbed database behind.
// One transaction, in write order; splitting it would hide that order.
#[allow(clippy::too_many_lines)]
fn execute(
    url: &str,
    plan: &ScrubPlan,
    purges: &[(String, String)],
    views: &ViewRefresh<'_>,
    sampling: Option<&sample::SamplePlan>,
    facts: &DatabaseFacts,
    label: &str,
) -> Result<Applied, ScrubError> {
    if plan.tables.is_empty() && purges.is_empty() && views.ordered.is_empty() && sampling.is_none()
    {
        return Ok((Vec::new(), None));
    }
    let mut conn = probe_connection(url, label, "apply the scrub")?;
    let mut counts = Vec::with_capacity(plan.tables.len());
    let mut outcome = None;
    let mut drift: Vec<String> = Vec::new();
    // The transaction's error type carries BOTH channels, so a sample refusal
    // rolls back as itself rather than as an opaque database error.
    conn.transaction::<_, sample::SampleFailure, _>(|conn| {
        // Pin the resolution of every unqualified name and the meaning of every
        // string literal for the whole transaction, so a role- or
        // database-level `search_path` (tenant schemas) cannot redirect a write
        // to a table nothing classified, and `quote_literal`'s doubled quotes
        // cannot be re-interpreted under `standard_conforming_strings = off`.
        conn.batch_execute(&session_settings().join("; "))?;
        // Hold the tables for the duration: the plan was built from a snapshot
        // taken on another connection, and a row inserted between the two would
        // otherwise survive the scrub unnoticed. SHARE ROW EXCLUSIVE blocks
        // writers while still allowing plain reads.
        // Every table the transaction writes, including the ones it empties: a
        // producer inserting into a purged job/sync/token table after that
        // `DELETE` took its snapshot would otherwise survive a run that reports
        // the table emptied.
        for statement in lock_statements(plan, purges, sampling) {
            sql_query(statement).execute(conn)?;
        }
        // The locks above wait for a concurrent migration to commit, then see
        // its schema. Compare against the snapshot the plan was built from, so
        // a column added in that window cannot commit unclassified.
        drift = live_schema_drift(conn, facts)?;
        if !drift.is_empty() {
            return Err(sample::SampleFailure::Db(
                diesel::result::Error::RollbackTransaction,
            ));
        }
        // Purges run FIRST so a framework-owned table that references a
        // sampled one is already empty when the sample removes its parents —
        // except the ones the plan defers, which are the mirror image: a table
        // the sample empties references them, so they have to wait for it.
        //
        // These early passes exist to make the DELETEs possible, not to make the
        // guarantee true: the authoritative pass is the one after the rewrites,
        // because a trigger on a scrubbed table can write fresh rows — carrying
        // the very PII being removed — into a purged table after these run.
        // Rows removed are accumulated across all passes and reported once.
        let no_deferral = BTreeSet::new();
        let deferred: &BTreeSet<String> = sampling.map_or(&no_deferral, |s| &s.purge_after);
        let phases = emptying_phases(purges, deferred, sampling);
        let mut purged_rows: BTreeMap<&str, usize> = BTreeMap::new();
        for (table, statement) in &phases.before {
            let rows = sql_query(statement).execute(conn)?;
            *purged_rows.entry(*table).or_default() += rows;
        }
        // Then the subset, so the rewrites below touch only the rows that
        // survive it — and so no combination of flags can commit a row that was
        // sampled but not scrubbed: both happen in this one transaction.
        if let Some(sampling) = sampling {
            outcome = Some(sample::apply(
                conn,
                sampling,
                // The uncapped list: refresh ORDER comes from the walk, but a
                // view the walk's depth cap dropped still holds its heap, and
                // measuring only the ordered subset is what let the report
                // announce a size a large unmeasured view contradicted.
                &also_measured(&purged_tables(purges), views.all),
            )?);
        }
        // The deferred purges, now that the sample has emptied what referenced
        // them. Empty unless a plan deferred one, so an unsampled scrub still
        // runs every purge in the single pass above.
        for (table, statement) in &phases.after_sample {
            let rows = sql_query(statement).execute(conn)?;
            *purged_rows.entry(*table).or_default() += rows;
        }
        for table in &plan.tables {
            if let Some(sql) = &table.sql {
                let rows = sql_query(sql).execute(conn)?;
                counts.push((table.table.clone(), rows));
            }
            for rewrite in &table.encrypted {
                let rows = rewrite_encrypted_column(conn, &table.table, &table.row_key, rewrite)?;
                counts.push((format!("{}.{}", table.table, rewrite.column), rows));
            }
        }
        // The authoritative pass, after every rewrite: every purge again AND the
        // `never_include` tables. An `UPDATE` trigger on a scrubbed table — or a
        // `DELETE` trigger fired by the sample — can copy `OLD` values into
        // either kind, so emptying only beforehand would report a table emptied
        // while it holds rows carrying the original PII. Both promises are
        // "this table ends up empty", so both are enforced here, last; the
        // passes above exist only to order the sample's own deletes.
        for (table, statement) in &phases.final_pass {
            let rows = sql_query(statement).execute(conn)?;
            *purged_rows.entry(*table).or_default() += rows;
        }
        for (table, rows) in purged_rows {
            counts.push((format!("{table} (emptied)"), rows));
        }

        // Prove the promise instead of ordering for it.
        //
        // Each statement in the pass above can fire triggers, and one of those
        // can insert into a table an EARLIER statement already emptied — an
        // `ON DELETE` archive trigger between two promised-empty tables does
        // exactly that. No ordering of the deletes rules that out in general:
        // the trigger graph decides, and it can be cyclic. So the guarantee is
        // checked rather than arranged, in the same transaction, the same way
        // the sample re-counts its foreign keys rather than trusting the walk.
        // Inside the transaction, so a refresh the role is not allowed to run
        // rolls the rewrites back rather than committing base tables that a
        // stale materialized view still contradicts.
        for view in views.ordered {
            sql_query(format!(
                "REFRESH MATERIALIZED VIEW {}",
                qualified_ident(view)
            ))
            .execute(conn)?;
            counts.push((format!("{view} (materialized view refreshed)"), 0));
        }
        // And `WITH NO DATA` for every view that had none when the run probed:
        // the ones populated only so a dependent could be rebuilt from them, and
        // the ones skipped entirely — which a concurrent session could have
        // populated from pre-scrub rows in the meantime, since nothing here
        // locks a view the run does not refresh. Last, after every refresh,
        // because emptying a source before its dependent is rebuilt makes that
        // refresh fail — and safe here, because emptying it afterwards does not
        // un-populate the dependent already rebuilt from it.
        for view in views.unpopulated {
            sql_query(format!(
                "REFRESH MATERIALIZED VIEW {} WITH NO DATA",
                qualified_ident(view)
            ))
            .execute(conn)?;
            counts.push((format!("{view} (materialized view left unpopulated)"), 0));
        }

        // Prove the promise instead of ordering for it — AFTER the refreshes,
        // which are the last writes in the transaction.
        //
        // Each statement in the emptying pass can fire triggers, and one of
        // those can insert into a table an EARLIER statement already emptied —
        // an `ON DELETE` archive trigger between two promised-empty tables does
        // exactly that. No ordering of the deletes rules that out in general:
        // the trigger graph decides, and it can be cyclic.
        //
        // A refresh writes too. A materialized view's query can call a function
        // whose body INSERTs, and `REFRESH` runs that query — measured on a
        // tracked `BEGIN ATOMIC` function writing into a `never_include` table,
        // the run reported `audit_logs: 503 -> 0 row(s)` and `✓ Scrub complete`
        // while leaving three rows carrying real addresses. Volatility does not
        // separate those functions out: measured, `CREATE FUNCTION ... STABLE
        // BEGIN ATOMIC INSERT ...` is accepted, so a `provolatile` test would
        // miss exactly this one. Checking after every write covers both causes
        // and needs no guess about which functions can write.
        let mut refilled = Vec::new();
        for (table, _) in &phases.final_pass {
            let row: RowCount = sql_query(format!(
                "SELECT count(*) AS n FROM {}",
                qualified_ident(table)
            ))
            .get_result(conn)?;
            if row.n > 0 {
                refilled.push(format!("{table} ({} row(s))", row.n));
            }
        }
        if !refilled.is_empty() {
            refilled.sort();
            refilled.dedup();
            return Err(sample::SampleFailure::Refused(
                sample::SampleError::NotEmptied { tables: refilled },
            ));
        }

        // The sample's own postconditions belong here for the same reason: they
        // are checked BEFORE the refreshes, which can write. See
        // `verify_sample_survived_refreshes`.
        if let (Some(settled), Some(plan)) = (outcome.as_ref(), sampling) {
            verify_sample_survived_refreshes(conn, settled, plan)?;
        }
        // Again, as the last check before commit: a table the plan does not
        // lock can change after the first comparison.
        drift = live_schema_drift(conn, facts)?;
        if !drift.is_empty() {
            return Err(sample::SampleFailure::Db(
                diesel::result::Error::RollbackTransaction,
            ));
        }
        Ok(())
    })
    .map_err(|e| match e {
        _ if !drift.is_empty() => ScrubError::SchemaChanged {
            entries: std::mem::take(&mut drift),
        },
        sample::SampleFailure::Refused(refusal) => ScrubError::from(refusal),
        sample::SampleFailure::Db(error) => ScrubError::Sql(error.to_string()),
    })?;
    Ok((counts, outcome))
}

#[cfg(test)]
mod tests {
    use super::{emptiness_assertion, integrity_assertion, rules_reaching, triggers_reaching};

    // ── The dry run's session and connection preamble ──────────────────────

    /// The statement the dry run cannot print truthfully withholds the whole
    /// script, because nothing in a pasted stream can stop it partway.
    ///
    /// Measured: printing the script with the rewrite replaced by a comment left
    /// `users` sampled 200 -> 100 with every address rewritten AND all 100 kept
    /// rows still holding their original production ciphertext, committed
    /// without a single error. Replacing the comment with a `RAISE EXCEPTION`
    /// fixed only that target: on psql 16.13 the abort ends at the printed
    /// `COMMIT`, and the following `VACUUM (FULL)`s and the NEXT target's
    /// `\connect` and DELETEs ran for real — a second cluster went from 200
    /// comments to 0. `\quit` fares no better: psql exits and the shell that
    /// launched it reads the rest of the paste, executing a trailing `echo` in
    /// the same measurement. So the script is refused before it is printed.
    #[test]
    fn an_encrypted_rewrite_withholds_the_whole_printed_script() {
        let refusal = ScrubError::UnprintableEncryptedRewrite {
            columns: vec!["control: users.api_token".to_owned()],
        }
        .to_string();
        assert!(
            refusal.contains("cannot print a runnable script"),
            "it must refuse the script, not annotate it: {refusal}"
        );
        assert!(
            refusal.contains("users.api_token"),
            "and name the column that cannot be printed: {refusal}"
        );
        assert!(
            refusal.contains("without --dry-run"),
            "and say what to run instead: {refusal}"
        );
        // Withholding the SQL is the point; the plan report above it still
        // stands, so the refusal must not read as "nothing was analysed".
        assert!(
            refusal.contains("plan above is complete"),
            "and keep the reported plan standing: {refusal}"
        );
        // The key is the reason this cannot be printed as SQL, so it must not
        // appear in the reason either.
        assert!(
            !refusal.to_lowercase().contains("primary_key")
                && !refusal.contains("deterministic_key")
                && !refusal.contains("key_derivation_salt"),
            "no key material may reach the refusal: {refusal}"
        );
    }

    /// `VACUUM (FULL)` cannot run inside a transaction, so the compaction is the
    /// one part of a target's plan the in-transaction guard cannot cover — and
    /// that gap was reachable, not theoretical.
    ///
    /// Measured against a `pg_basebackup` clone pasted at its origin: the guard
    /// refused all 64 destructive statements, and then six
    /// `VACUUM (FULL, ANALYZE)` statements ran on the ORIGIN, each taking an
    /// `ACCESS EXCLUSIVE` lock and rewriting the table. The printed `COMMIT`
    /// turns the guard's abort into a `ROLLBACK` and clears the aborted state,
    /// so the server has nothing left to refuse with.
    ///
    /// psql decides instead. With the fence, the same paste ran zero VACUUMs on
    /// the origin (seven `query ignored` lines) and the legitimate paste still
    /// ran all six against the clone, 200 -> 100 users, zero errors.
    #[test]
    fn the_compaction_after_commit_is_fenced_by_psql() {
        let endpoint = super::ServerEndpoint {
            database: "app".to_owned(),
            address: None,
            port: None,
            system_identifier: Some("7682669380557907941".to_owned()),
            server_port: Some("5435".to_owned()),
            data_directory: Some("/tmp/pgd3".to_owned()),
        };
        let fence = super::post_commit_fence(&endpoint);
        // The run's own pins are SET LOCAL, so they belong to the transaction
        // that just rolled back. Without re-pinning, the operators below resolve
        // through the pasting session's own search_path.
        assert!(
            fence
                .iter()
                .any(|line| line == "SET search_path = pg_catalog, public;"),
            "the fence must re-pin the path it needs: {fence:?}"
        );
        assert!(
            fence
                .iter()
                .any(|line| line.contains("\\gset") && line.contains("AS autumn_ok")),
            "psql, not the server, has to decide this one: {fence:?}"
        );
        // The `\if` belongs to the compaction pass, which runs after EVERY
        // target's transaction rather than inside one. Emitting it here put the
        // VACUUM statements between two targets: measured on two TCP targets
        // under `ON_ERROR_STOP on`, a first-target VACUUM that timed out ended
        // the script at rc=3 with that database scrubbed and the SECOND still
        // holding all 200 of its original addresses — from a failure the
        // executor only warns about.
        assert!(
            !fence.iter().any(|line| line == "\\if :autumn_ok"),
            "the fence sets the flag; the compaction pass reads it: {fence:?}"
        );
        // One flag for the whole stream, not one per target: `execute` returns
        // on the first target that fails and never touches the rest, and the
        // script has to match. Measured with two real targets and a non-guard
        // failure in the first: without it the second target's `\connect` and
        // its whole destructive block ran anyway, leaving a partially scrubbed
        // topology and a stream that ends with no error. With it, 90 statements
        // were skipped and the second target was untouched at 100 rows.
        assert_eq!(
            fence
                .iter()
                .filter(|line| *line == "\\set autumn_ok false")
                .count(),
            1,
            "the flag must be cleared before the gset that may not run: {fence:?}"
        );
        // Being on the right server is not the same as having scrubbed it.
        // Measured: with a statement inside the transaction failing for a
        // reason the guard knows nothing about, `COMMIT` returned ROLLBACK and
        // an endpoint-only probe still ran all six VACUUM (FULL, ANALYZE) —
        // ACCESS EXCLUSIVE locks and full rewrites on a target whose scrub had
        // just rolled back. `:ERROR` does not catch it either: measured, psql
        // reports that ROLLBACK as SUCCESS, so it is false there. Hence the
        // explicit flag, set as the transaction's last statement.
        assert!(
            fence
                .iter()
                .any(|line| line.contains("autumn_scrubbed") && line.contains("::bool")),
            "the fence must require the transaction to have succeeded: {fence:?}"
        );
        // And `:ERROR` must be captured before anything else runs, because a
        // statement of any kind resets it — `\set` is a meta-command and
        // executes nothing, which is why it can come first.
        assert_eq!(
            fence.first().map(String::as_str),
            Some("\\set autumn_commit_error :ERROR"),
            "the commit's own error state has to be read before it is lost: {fence:?}"
        );
        // The same predicate as the guard, so the two cannot come to disagree
        // about what counts as the right server.
        let mismatch = super::endpoint_mismatch(&endpoint);
        assert!(
            fence.iter().any(|line| line.contains(&mismatch)),
            "the fence must ask exactly what the guard asks: {fence:?}"
        );
        assert!(
            super::target_guard(&endpoint).contains(&mismatch),
            "and the guard must ask it too: {mismatch}"
        );
    }

    /// A failed `\connect` leaves psql on the PREVIOUS database, so the block
    /// proves where it is before it writes — and proves the whole endpoint.
    ///
    /// Measured on psql 16.13: a failed `\connect -reuse-previous=off` prints
    /// "Previous connection kept" and the session carries on; `ON_ERROR_STOP`
    /// does not stop an interactive paste. With the database name alone, two
    /// clusters both holding `app` let shard1's block scrub shard0 from 200
    /// users to 100. With the endpoint pinned, the same paste aborted and left
    /// shard0 at 200/400/500.
    #[test]
    fn the_target_guard_pins_the_whole_endpoint_and_qualifies_every_call() {
        let here = super::ServerEndpoint {
            database: "app_copy".to_owned(),
            address: Some("10.0.0.2/32".to_owned()),
            port: Some("5432".to_owned()),
            system_identifier: Some("7682669380557907941".to_owned()),
            server_port: Some("5432".to_owned()),
            data_directory: Some("/var/lib/postgresql/16/main".to_owned()),
        };
        let guard = super::target_guard(&here);
        assert!(
            guard.contains("pg_catalog.current_database() <> 'app_copy'")
                && guard
                    .contains("pg_catalog.inet_server_addr()::text IS DISTINCT FROM '10.0.0.2/32'")
                && guard.contains("pg_catalog.inet_server_port()::text IS DISTINCT FROM '5432'"),
            "the guard must pin the whole endpoint: {guard}"
        );
        // Address and port are None for EVERY Unix-socket connection, so two
        // socket clusters holding the same database name are identical by them.
        // Measured: both reported `<null>/<null>` while their system identifiers
        // differed (7682669380557907941 vs 7683257673996527196).
        assert!(
            guard.contains("IS DISTINCT FROM '7682669380557907941'"),
            "the cluster identity must be pinned too, or two socket clusters are \
             indistinguishable: {guard}"
        );
        // And the identifier alone is not identity either: a physical copy —
        // a replica, or a promoted staging clone — carries the identifier of
        // the cluster it was cloned from. The configured port answers over a
        // socket where `inet_server_port()` is NULL, and the data directory is
        // the value two postmasters on one machine cannot share.
        assert!(
            guard.contains("pg_catalog.current_setting('port') IS DISTINCT FROM '5432'"),
            "the server's configured port must be pinned: {guard}"
        );
        assert!(
            guard.contains("IS DISTINCT FROM '/var/lib/postgresql/16/main'"),
            "the data directory must be pinned, or a clone passes: {guard}"
        );
        // Read through `pg_settings`, never `current_setting`: the parameter is
        // restricted to `pg_read_all_settings`, and `current_setting` raises
        // `permission denied to examine ...` for a role without it — inside the
        // guard, that failure would abort a CORRECT paste.
        assert!(
            !guard.contains("current_setting('data_directory')")
                && guard.contains("FROM pg_catalog.pg_settings WHERE name = 'data_directory'"),
            "a restricted setting must degrade to NULL, not raise: {guard}"
        );
        // Unqualified, these resolve through the PASTING session's search_path.
        // Measured on a database configured `public, pg_catalog`, a shadowing
        // `public.current_database()` answered `app` while
        // `pg_catalog.current_database()` answered the truth — so an unqualified
        // guard consults the shadow and passes.
        for call in [
            "current_database()",
            "inet_server_addr()",
            "inet_server_port()",
            "pg_control_system()",
        ] {
            for (at, _) in guard.match_indices(call) {
                assert!(
                    guard[..at].ends_with("pg_catalog."),
                    "every catalog call must be qualified: {call} at {at} in {guard}"
                );
            }
        }
        assert!(
            !guard.contains("$s"),
            "RAISE has no positional format specifiers: {guard}"
        );
        assert_eq!(
            guard.matches('%').count(),
            12,
            "six placeholders for the target endpoint, six for the session's: {guard}"
        );

        // Over a Unix socket the server reports neither, and the guard compares
        // that as NULL rather than papering over it.
        let socket = super::target_guard(&super::ServerEndpoint {
            database: "app_copy".to_owned(),
            ..super::ServerEndpoint::default()
        });
        assert!(
            socket.contains("IS DISTINCT FROM NULL"),
            "a socket target pins NULL explicitly: {socket}"
        );
        assert_eq!(
            socket.matches("IS DISTINCT FROM NULL").count(),
            3,
            "address, port and the configured port are compared even when NULL — \
             for a socket target that IS the answer: {socket}"
        );
        // The cluster identifier and the data directory are NOT compared when
        // the planning role could not read them: there, `None` means "unknown",
        // not "the target has none". A term comparing against a value never
        // learned refuses a CORRECT paste whenever the pasting role can read
        // what the planning role could not — and for `pg_control_system()` it
        // is worse: measured, with EXECUTE revoked an ordinary role gets
        // `permission denied for function pg_control_system`, which inside the
        // guard aborts the transaction and takes the whole paste with it.
        assert!(
            !socket.contains("pg_control_system()) IS DISTINCT FROM")
                && !socket.contains("'data_directory'), ''), '') IS DISTINCT FROM"),
            "an unreadable discriminator must be dropped, not guessed at: {socket}"
        );
        // Nor may the RAISE call for one: an argument that raises would replace
        // the mismatch this block exists to explain with a permission error.
        assert!(
            !socket.contains("pg_catalog.pg_control_system()"),
            "and the message must not call for it either: {socket}"
        );

        // The database name comes from the target connection, so a quote in it
        // reaches SQL as a literal like every other value this module prints.
        let hostile = super::target_guard(&super::ServerEndpoint {
            database: "it's".to_owned(),
            ..super::ServerEndpoint::default()
        });
        assert!(
            hostile.contains("'it''s'"),
            "a quote in the database name must not break out of the literal: {hostile}"
        );
    }

    /// Both sides of the size ratio measure the same set of relations.
    ///
    /// The purge targets keep their whole file until compaction rewrites them,
    /// The reconnect proves itself from psql's view, not the server's.
    ///
    /// `inet_server_addr()`/`inet_server_port()` are the endpoint the SERVER
    /// accepted on, not the one the operator configured — measured through a
    /// forwarder, a session connected to `127.0.0.1:15433` reports
    /// `127.0.0.1:5433`. Two servers behind different forwards, or in separate
    /// container networks sharing a private address, therefore report the same
    /// pair, and with a physical clone's inherited `system_identifier` and a
    /// container-local `data_directory` every server-side value can match on two
    /// different databases.
    #[test]
    fn the_reconnect_is_proved_from_psql_own_variables() {
        let lines = super::psql_connection_assertion(
            "postgres://postgres@127.0.0.1:25433/dry_t2",
            "dry_t2",
        );
        // False FIRST, so a `\gset` whose query fails cannot carry the previous
        // target's answer into this target's destructive block.
        assert_eq!(
            lines.first().map(String::as_str),
            Some("\\set autumn_ok false"),
            "the flag must be cleared before the gset that may not run: {lines:?}"
        );
        let probe = lines
            .iter()
            .find(|l| l.contains("\\gset"))
            .unwrap_or_else(|| panic!("psql, not the server, has to decide this: {lines:?}"));
        // The operator's endpoint, which is what `\connect` acted on — NOT the
        // 5434 the server behind that forward reports for itself.
        assert!(
            probe.contains(":'PORT' OPERATOR(pg_catalog.=) '25433'")
                && probe.contains(":'HOST' OPERATOR(pg_catalog.=) '127.0.0.1'")
                && probe.contains(":'DBNAME' OPERATOR(pg_catalog.=) 'dry_t2'"),
            "every stated component must be pinned to psql's own value: {probe}"
        );
        // `pg_catalog`-qualified, so a `public.=` in the pasting session's path
        // cannot answer the one comparison the whole block depends on.
        assert!(
            !probe.contains(" = '"),
            "the comparison must not resolve through search_path: {probe}"
        );
        assert_eq!(
            lines.last().map(String::as_str),
            Some("\\if :autumn_ok"),
            "and the block has to sit inside it: {lines:?}"
        );
    }

    /// A query pair overrides the authority it duplicates.
    ///
    /// That is the precedence libpq applies and `pg::sanitize_db_url`
    /// normalises, so the proof has to read the conninfo the same way — pinning
    /// the authority's port here would assert a port psql never connects to.
    #[test]
    fn a_query_pair_overrides_the_authority_it_duplicates() {
        let overridden = super::psql_connection_assertion(
            "postgres://postgres@a.example:5432/app?port=6000",
            "app",
        )
        .into_iter()
        .find(|l| l.contains("\\gset"))
        .expect("the probe must be emitted");
        assert!(
            overridden.contains(":'PORT' OPERATOR(pg_catalog.=) '6000'")
                && !overridden.contains("'5432'"),
            "the query pair wins over the authority: {overridden}"
        );
    }

    /// A failover list is matched the way libpq resolves it: positionally.
    ///
    /// Measured on `PostgreSQL` 16.13, `host=127.0.0.9,127.0.0.1&port=5433,5434`
    /// connected to 5434 — the port belonging to the host it reached, not the
    /// first in the list — and `host=127.0.0.9,127.0.0.1&port=5433` connected to
    /// 5433. So `a:5433` is not an endpoint `host=a,b&port=5432,5433` names, and
    /// matching host and port independently would accept a retained connection
    /// to one that was never configured.
    #[test]
    fn a_failover_list_keeps_its_host_port_pairing() {
        let paired = super::psql_connection_terms(
            "postgres://postgres@a.example/app?host=a.example,b.example&port=5432,5433",
            "app",
        );
        assert!(
            paired.contains(
                "(:'HOST' OPERATOR(pg_catalog.=) 'a.example' AND :'PORT' OPERATOR(pg_catalog.=) '5432')"
            ) && paired.contains(
                "(:'HOST' OPERATOR(pg_catalog.=) 'b.example' AND :'PORT' OPERATOR(pg_catalog.=) '5433')"
            ),
            "each host must carry its OWN port: {paired}"
        );
        // A single port applies to every host, which libpq does and this must
        // not turn into a refusal.
        let broadcast = super::psql_connection_terms(
            "postgres://postgres@a.example/app?host=a.example,b.example&port=5432",
            "app",
        );
        assert!(
            broadcast.contains(":'HOST' OPERATOR(pg_catalog.=) 'a.example'")
                && broadcast.contains(":'HOST' OPERATOR(pg_catalog.=) 'b.example'")
                && broadcast.matches(":'PORT'").count() == 1,
            "one port must cover every host: {broadcast}"
        );
        // libpq refuses a length mismatch outright — measured, `could not match
        // 3 port numbers to 2 hosts` — so the run could not have connected
        // either. Fail closed rather than invent a pairing.
        let mismatched = super::psql_connection_terms(
            "postgres://postgres@a.example/app?host=a.example,b.example&port=1,2,3",
            "app",
        );
        assert_eq!(
            mismatched, "false",
            "a pairing libpq itself rejects must not be guessed at: {mismatched}"
        );
    }

    /// A conninfo stating no host cannot be proved, so it proves nothing.
    ///
    /// Unreachable today: a URI with an empty authority fails
    /// `password_free_conninfo`, and the run refuses to print such a target
    /// before this is reached — measured for both `postgres:///app` and
    /// `postgres://user@/app`. Pinned here anyway, because omitting the host
    /// term instead would leave the database name standing alone against a
    /// physical clone that shares it.
    #[test]
    fn a_conninfo_without_a_host_proves_nothing() {
        assert_eq!(
            super::psql_connection_terms("postgres:///app", "app"),
            "false",
            "the one discriminator this proof exists for cannot be optional"
        );
        // Nor the port. psql reports the RESOLVED port, and the same host-only
        // URI resolves to 5433 under `PGPORT=5433` and to 5432 without it —
        // measured, two different servers. Such a target is refused before
        // anything is printed; this is the fail-closed answer if that is ever
        // relaxed.
        assert_eq!(
            super::psql_connection_terms("postgres://db.internal/app", "app"),
            "false",
            "accepting any port for the host drops the discriminator"
        );
    }

    /// The pasting session must fire the triggers the plan was built against.
    ///
    /// The run refuses to PLAN from a connection that is not `origin`, because
    /// the trigger walk only inspects the `O`/`A` set — but the printed script
    /// inherits whatever the pasting session is in. Measured: with the session
    /// in `replica` and the printed `\connect` failing (so that session is
    /// retained, on the right endpoint, past both the psql proof and the
    /// endpoint guard), this assertion raised and the transaction aborted with
    /// the database untouched at 200 rows.
    #[test]
    fn the_pasting_session_must_be_in_the_origin_replication_role() {
        let assertion = super::replication_role_assertion();
        assert!(
            assertion
                .contains("pg_catalog.current_setting('session_replication_role') <> 'origin'")
                && assertion.contains("RAISE EXCEPTION"),
            "the script must assert what the command refuses to plan without: {assertion}"
        );
        // Asserted, not pinned: the setting is SUSET, so a `SET LOCAL` would fail
        // for the ordinary role this script is written for.
        assert!(
            !assertion.contains("SET LOCAL"),
            "it must not try to reset a setting an ordinary role cannot: {assertion}"
        );
    }

    /// and a refreshed materialized view is rebuilt from whatever survives the
    /// sample — a view over reference data does not shrink at all. Measuring
    /// base tables only reported `488.0 kB -> 232.0 kB` on a database still
    /// holding a 44 MB refreshed view.
    #[test]
    fn the_measured_set_covers_purges_and_refreshed_views_once_each() {
        let purged = vec!["autumn_jobs".to_owned(), "shared".to_owned()];
        let refreshed = vec!["shared".to_owned(), "big_report".to_owned()];
        assert_eq!(
            super::also_measured(&purged, &refreshed),
            vec![
                "autumn_jobs".to_owned(),
                "big_report".to_owned(),
                "shared".to_owned()
            ],
            "every relation the run touches outside the plan, and each one once"
        );
        assert!(
            super::also_measured(&[], &[]).is_empty(),
            "and an unsampled target with neither measures nothing extra"
        );
    }

    #[test]
    fn the_connect_boundary_carries_the_whole_endpoint_and_no_password() {
        // A bare `\\connect dbname` inherits host, port and user, so a fleet whose
        // shards share a database name on different servers would keep running
        // against the first one while looking like it had moved.
        let lines = super::psql_connect(
            "control",
            "postgres://scrubby:hunter2@db1.internal:6543/app",
        );
        // The boundary pins the endpoint against the PASTING session's
        // environment first: a libpq `PGHOSTADDR` or `PGSERVICE` set where the
        // script is pasted would otherwise reroute the `\connect` while the
        // reconnect proof below still reports the conninfo's own host — and
        // psql cannot see the difference.
        assert_eq!(
            &lines[..2],
            &[r"\setenv PGHOSTADDR", r"\setenv PGSERVICE"],
            "the boundary must clear libpq's environment-routed endpoint knobs first: {lines:?}"
        );
        let line = lines.join("\n");
        assert!(
            lines[2].starts_with(r#"\connect -reuse-previous=off ""#),
            "the boundary must inherit nothing from the previous connection: {line}"
        );
        assert!(
            !line.contains("hunter2"),
            "the password must never reach the printed script: {line}"
        );
        assert!(
            line.contains("db1.internal") && line.contains("6543") && line.contains("app"),
            "and the endpoint must survive: {line}"
        );

        // The whole string is passed through, not rebuilt from parts: a query
        // parameter overrides the authority component it duplicates, so an
        // endpoint reassembled from the URL's own host would name the wrong
        // database on the header of destructive SQL.
        let overridden = super::psql_connect(
            "control",
            "postgres://authority/app?host=queryhost&dbname=copy",
        )
        .join("\n");
        assert!(
            overridden.contains("host=queryhost") && overridden.contains("dbname=copy"),
            "an override must survive into the printed boundary: {overridden}"
        );

        // A query value is re-encoded the way libpq reads one, not the way a
        // web form does. `url::Url::query_pairs()` applies
        // `x-www-form-urlencoded` rules and `query_pairs_mut()` writes a space
        // back as `+`; libpq only ever percent-decodes, so it reads that `+`
        // literally. Measured against psql 16.13, the operator's own value
        // connects and the `+` form does not:
        //
        //   ?options=-c%20search_path%3Dpg_catalog   -> search_path = pg_catalog
        //   ?options=-c+search_path%3Dpg_catalog     -> FATAL: unrecognized
        //                                               configuration parameter
        //                                               "+search_path"
        //
        // A boundary that cannot connect is the exact case the target guard
        // exists for — psql keeps the PREVIOUS connection — so printing one is
        // not a cosmetic defect.
        let spaced = super::psql_connect(
            "control",
            "postgres://u@h/app?options=-c%20search_path%3Dpg_catalog&password=hunter2",
        )
        .join("\n");
        assert!(
            !spaced.contains('+'),
            "a space must be percent-encoded, never written as `+`: {spaced}"
        );
        assert!(
            spaced.contains("%20"),
            "and it must still be there, not dropped: {spaced}"
        );
        assert!(
            !spaced.contains("hunter2") && !spaced.contains("password"),
            "while the credential is still removed: {spaced}"
        );

        // Keyword form is declined outright rather than tokenized. `libpq`
        // allows whitespace around the `=` and single-quoted values with
        // backslash escapes, so a whitespace split reads `password = secret` as
        // three unrelated tokens and prints the credential — which is exactly
        // what two successive tokenizers here got wrong.
        for keyword in [
            "host=db2.internal dbname=app password=hunter2",
            "host=db2.internal dbname=app password = hunter2",
            "host=db2 password='two words' dbname=app",
        ] {
            let line = super::psql_connect("control", keyword).join("\n");
            assert!(
                !line.contains("hunter2") && !line.contains("two words"),
                "no keyword form may print its password: {line}"
            );
            assert!(
                !line.contains("\\connect"),
                "and none may claim to move the session: {line}"
            );
            assert!(
                line.contains("control"),
                "the operator must still be told which target it was: {line}"
            );
            // And it must STOP the paste, not merely advise. The dry run refuses
            // before printing anything for such a target, so this branch is
            // unreachable in practice; if that guard is ever bypassed, a comment
            // would let a destructive block run against the previous target and
            // `\quit` will not.
            assert!(
                line.contains("\\quit"),
                "a boundary that cannot be printed must halt psql: {line}"
            );
        }

        // A URI carries the password two ways, and the query form is the
        // EFFECTIVE one where both appear — so clearing the userinfo alone
        // prints the credential that actually authenticates.
        let in_query =
            super::psql_connect("control", "postgres://bob@db/app?password=secret2").join("\n");
        assert!(
            !in_query.contains("secret2"),
            "a query-string password must be stripped too: {in_query}"
        );
        let both = super::psql_connect(
            "control",
            "postgres://alice:secret1@db/app?password=secret2&sslpassword=k3y&application_name=x",
        )
        .join("\n");
        assert!(
            !both.contains("secret1") && !both.contains("secret2") && !both.contains("k3y"),
            "every credential form must go: {both}"
        );
        assert!(
            both.contains("application_name=x"),
            "and every non-secret parameter must stay: {both}"
        );
    }

    /// Postgres 18's `oauth_client_secret` authenticates like a password,
    /// and the old two-keyword denylist printed it verbatim into `--dry-run`
    /// output — the output that exists to be pasted and shared.
    #[test]
    fn oauth_client_secret_is_stripped_not_printed() {
        let printed = super::psql_connect(
            "control",
            "postgres://u@db/app?oauth_client_secret=s3cr3t&oauth_issuer=https%3A%2F%2Fidp.example",
        )
        .join("\n");
        assert!(
            printed.contains("\\connect"),
            "the target must stay printable: {printed}"
        );
        assert!(
            !printed.contains("s3cr3t"),
            "the OAuth client secret must never reach the printed script: {printed}"
        );
        assert!(
            printed.contains("oauth_issuer="),
            "the non-secret OAuth parameters must survive: {printed}"
        );
        // The keyword match is case-insensitive, like libpq's.
        let upper = super::password_free_conninfo("postgres://u@db/app?OAUTH_CLIENT_SECRET=s3cr3t")
            .expect("a URI must stay printable");
        assert!(
            !upper.contains("s3cr3t"),
            "OAUTH_CLIENT_SECRET must strip like oauth_client_secret: {upper}"
        );
    }

    /// A connection-string parameter this command has never heard of refuses
    /// the target instead of being printed or dropped: dropping `hostaddr`
    /// would reconnect somewhere else, and printing a future credential
    /// parameter would repeat the `oauth_client_secret` disclosure above. A
    /// denylist cannot know the next Postgres release; the allowlist fails
    /// closed.
    #[test]
    fn an_unknown_keyword_refuses_the_target() {
        assert!(
            super::password_free_conninfo("postgres://u@db/app?widgets=1").is_none(),
            "an unrecognised keyword must make the conninfo unprintable"
        );
        let refused = super::psql_connect("control", "postgres://u@db/app?widgets=1").join("\n");
        assert!(
            !refused.contains("\\connect"),
            "and the boundary must not claim to move the session: {refused}"
        );
        assert!(
            refused.contains("\\quit"),
            "a boundary that cannot be printed must halt psql: {refused}"
        );
    }

    /// Supported non-secret libpq options (`sslcertmode`, `sslsni`, 18's
    /// protocol-version bounds and `oauth_client_id`) print, so a target that
    /// uses them still dry-runs; the SCRAM key parameters are credentials
    /// and stay unlisted, so they still refuse the target.
    #[test]
    fn supported_non_secret_libpq_options_print() {
        let url = "postgres://u@db/app?sslcertmode=allow&sslsni=1&min_protocol_version=3.0\
                   &max_protocol_version=latest&oauth_client_id=cli";
        let conninfo =
            super::password_free_conninfo(url).expect("supported non-secret options must print");
        for key in [
            "sslcertmode",
            "sslsni",
            "min_protocol_version",
            "max_protocol_version",
            "oauth_client_id",
        ] {
            assert!(conninfo.contains(key), "{key} must be kept: {conninfo}");
        }
        assert!(
            super::password_free_conninfo("postgres://u@db/app?scram_client_key=AAAA").is_none(),
            "a SCRAM key is a credential, not a printable option"
        );
    }

    /// The allowlist must not become a refusal list for ordinary
    /// connections: every keyword below is a real libpq parameter that
    /// carries no credential, and a target using them must stay printable.
    #[test]
    fn the_allowlist_keeps_ordinary_parameters() {
        let printed = super::password_free_conninfo(
            "postgres://u@db/app?sslmode=verify-full&sslrootcert=%2Fetc%2Fca.pem&connect_timeout=10&target_session_attrs=read-write&application_name=autumn-scrub&hostaddr=10.0.0.5&keepalives_idle=60&tcp_user_timeout=5000&passfile=%2Frun%2Fsecrets%2Fpgpass&options=-c%20search_path%3Dapp",
        )
        .expect("ordinary libpq parameters must stay printable");
        for keyword in [
            "sslmode=",
            "sslrootcert=",
            "connect_timeout=",
            "target_session_attrs=",
            "application_name=",
            "hostaddr=",
            "keepalives_idle=",
            "tcp_user_timeout=",
            "passfile=",
            "options=",
        ] {
            assert!(
                printed.contains(keyword),
                "a known-non-secret parameter must survive: {printed}"
            );
        }
    }

    /// URI query keys are not normalised for us, so both lists compare
    /// without case — the way libpq treats them.
    #[test]
    fn keyword_matching_is_case_insensitive() {
        let printed = super::password_free_conninfo(
            "postgres://u@db/app?PASSWORD=s3cr3t&HOST=db.internal&AppLICATION_Name=x",
        )
        .expect("a URI must stay printable");
        assert!(
            !printed.contains("s3cr3t"),
            "PASSWORD must strip like password: {printed}"
        );
        assert!(
            printed.contains("HOST=db.internal"),
            "HOST must survive like host: {printed}"
        );
        assert!(
            printed.contains("AppLICATION_Name=x"),
            "the key keeps its own spelling: {printed}"
        );
    }

    /// The printed sample re-proves its postconditions after the refreshes,
    /// the way `verify_sample_survived_refreshes` does in the executed path:
    /// the counts are captured where the executor takes its own `after`
    /// snapshot, and asserted against after every write in the block.
    #[test]
    fn the_printed_sample_reproves_its_postconditions_after_refresh() {
        use super::sample::{
            ForeignKeyConstraint, SampleAmount, SampleInputs, SampleRules, SampleSpec, build_plan,
        };
        use std::collections::{BTreeMap, BTreeSet};

        let tables = vec![
            ("users".to_owned(), vec!["id".to_owned()]),
            ("orders".to_owned(), vec!["id".to_owned()]),
        ];
        let keys = vec![ForeignKeyConstraint {
            name: "orders_user_fk".to_owned(),
            child_table: "orders".to_owned(),
            child_columns: vec!["user_id".to_owned()],
            parent_table: "users".to_owned(),
            parent_columns: vec!["id".to_owned()],
            match_full: false,
        }];
        let roots = vec![SampleSpec {
            table: "users".to_owned(),
            amount: SampleAmount::Count(10),
        }];
        let rules = SampleRules::default();
        let plan = build_plan(&SampleInputs {
            roots: &roots,
            seed: 7,
            rules: &rules,
            tables: &tables,
            foreign_keys: &keys,
            framework_tables: &BTreeSet::new(),
            purged: &BTreeSet::new(),
            partitions: &BTreeMap::new(),
        })
        .expect("the fixture plan must build");

        // The capture: one temp table holding every sampled table's
        // post-sample count — the printed half of the executor's `after`
        // snapshot, taken in the same position.
        let capture = super::sample_count_capture_statements(&plan);
        assert_eq!(capture.len(), 1, "one capture statement: {capture:?}");
        let capture = &capture[0];
        assert!(
            capture.starts_with(&format!(
                "CREATE TEMPORARY TABLE {} ON COMMIT DROP AS ",
                super::SAMPLE_COUNTS_TABLE
            )),
            "the counts must live in a temp table, not psql variables — psql does not \
             interpolate variables inside dollar-quoted DO blocks: {capture}"
        );
        for table in &plan.tables {
            assert!(
                capture.contains(&format!(
                    "(SELECT count(*) FROM {})",
                    super::qualified_ident(&table.table)
                )),
                "every sampled table must be captured: {capture}"
            );
        }

        // The assertion: one `DO` block comparing live counts against the
        // capture, then the same FK statements the sample printed — re-run,
        // not re-derived.
        let postconditions = super::sample_postcondition_statements(&plan);
        let integrity: Vec<String> = plan
            .integrity_statements()
            .iter()
            .map(|(_, statement)| super::integrity_assertion(statement))
            .collect();
        assert_eq!(
            postconditions.len(),
            1 + integrity.len(),
            "one count check plus the same FK statements the sample printed: {postconditions:?}"
        );
        let (block, comment) = &postconditions[0];
        assert!(
            block.contains("RAISE EXCEPTION")
                && block.contains(&format!("pg_temp.{}", super::SAMPLE_COUNTS_TABLE)),
            "the count check must abort the transaction on mismatch, reading the captured \
             counts rather than print-time values: {block}"
        );
        for table in &plan.tables {
            assert!(
                block.contains(&super::qualified_ident(&table.table)),
                "every sampled table must be re-counted: {block}"
            );
        }
        assert!(
            comment.contains("after the refreshes"),
            "the comment must say when it runs: {comment}"
        );
        for (index, expected) in integrity.iter().enumerate() {
            let (statement, comment) = &postconditions[index + 1];
            assert_eq!(
                statement, expected,
                "the FK half must re-run the printed statements, not new ones"
            );
            assert!(
                comment.contains("after the refreshes"),
                "and say so: {comment}"
            );
        }
    }

    /// An unsampled target emits nothing: no capture, no assertions.
    #[test]
    fn an_unsampled_target_prints_no_postconditions() {
        use super::sample::{SampleInputs, SampleRules, build_plan};
        use std::collections::{BTreeMap, BTreeSet};

        let rules = SampleRules::default();
        let empty = build_plan(&SampleInputs {
            roots: &[],
            seed: 7,
            rules: &rules,
            tables: &[],
            foreign_keys: &[],
            framework_tables: &BTreeSet::new(),
            purged: &BTreeSet::new(),
            partitions: &BTreeMap::new(),
        })
        .expect("an empty plan must build");
        assert!(empty.tables.is_empty());
        assert!(super::sample_count_capture_statements(&empty).is_empty());
        assert!(super::sample_postcondition_statements(&empty).is_empty());
    }

    #[test]
    fn the_session_pins_cover_every_rendering_the_row_key_depends_on() {
        // `--seed` promises the same seed over the same source selects the same
        // rows, and the key is hashed from `key::text`. Measured: a `date`
        // primary key selects a different subset under `DateStyle = ISO, YMD`
        // than under `Postgres, DMY`.
        let pinned = super::session_settings().join("; ");
        for setting in [
            "search_path",
            "standard_conforming_strings",
            "DateStyle",
            "IntervalStyle",
            "TimeZone",
            "bytea_output",
            "extra_float_digits",
            "lc_monetary",
        ] {
            assert!(
                pinned.contains(setting),
                "{setting} changes how a value renders, so it must be pinned: {pinned}"
            );
        }
        assert!(
            super::session_settings()
                .iter()
                .all(|s| s.starts_with("SET LOCAL ")),
            "and every pin must be transaction-scoped: {pinned}"
        );
    }

    // ── Which triggers a statement can actually fire ────────────────────────

    #[test]
    fn rules_are_asked_for_by_the_same_rules_but_without_the_walk() {
        let sql = rules_reaching("AND r.ev_type = '4' ");
        // Measured on PostgreSQL 16: a rule on a leaf partition or an
        // inheritance child does NOT fire for a statement naming the parent,
        // because rewriting happens against the relation the query names. So
        // this must not grow the ancestry walk its trigger counterpart needs.
        assert!(
            !sql.contains("pg_inherits"),
            "a rule fires only on the relation named, so no walk: {sql}"
        );
        assert!(
            sql.contains("r.ev_enabled IN ('O', 'A')"),
            "a disabled rule cannot fire either: {sql}"
        );
        assert!(
            sql.contains("r.rulename <> '_RETURN'"),
            "every view's own SELECT rule must be excluded: {sql}"
        );
        assert!(
            sql.contains("AND r.ev_type = '4'"),
            "the caller's event filter must reach the query: {sql}"
        );
        assert!(
            !rules_reaching("").contains("ev_type"),
            "and an empty filter must not smuggle one in"
        );
    }

    #[test]
    fn only_row_triggers_propagate_up_the_inheritance_tree() {
        let sql = triggers_reaching("AND (t.tgtype & 8) <> 0 ");
        // Measured on PostgreSQL 16, both inheritance flavours: `DELETE FROM
        // parent` fires a child's ROW trigger and not its STATEMENT trigger. A
        // statement trigger must therefore mark only the table it is on, or the
        // run refuses over a trigger that cannot execute.
        assert!(
            sql.contains("(t.tgtype & 1) <> 0 AS by_row"),
            "the seed must record whether each trigger is row-level: {sql}"
        );
        assert!(
            sql.contains("JOIN ancestry a ON a.oid = i.inhrelid AND a.by_row"),
            "and only row-level ones may propagate to an ancestor: {sql}"
        );
        // A disabled trigger cannot fire, and disabling one is the remedy both
        // the warning and the refusal recommend.
        assert!(
            sql.contains("t.tgenabled IN ('O', 'A')"),
            "a disabled trigger must not count: {sql}"
        );
        assert!(
            sql.contains("AND (t.tgtype & 8) <> 0"),
            "the caller's event filter must reach the seed: {sql}"
        );
        // The warning asks the same question without an event filter.
        assert!(
            !triggers_reaching("").contains("tgtype & 8"),
            "and an empty filter must not smuggle one in"
        );
    }

    // ── Printed assertions survive hostile identifiers ──────────────────────

    #[test]
    fn an_assertion_delimiter_cannot_be_closed_by_an_identifier() {
        // Postgres permits `$` in a quoted identifier, and dollar quoting is
        // lexical — a fixed `DO $$ ... $$` around a query naming `"us$$ers"`
        // closes mid-statement, so the sequence the operator was told to paste
        // is a syntax error rather than the check it advertises.
        let check = r#"SELECT count(*) FROM "public"."us$$ers""#;
        let sql = integrity_assertion(check);
        assert!(
            !sql.starts_with("DO $$ "),
            "the delimiter must come from the body, not a constant: {sql}"
        );
        assert!(sql.contains(check), "the check itself must survive: {sql}");
        let tag = sql
            .split_whitespace()
            .nth(1)
            .expect("the block must open with `DO <tag>`");
        assert_eq!(
            sql.matches(tag).count(),
            2,
            "the tag must appear exactly twice — opening and closing: {sql}"
        );
        assert!(sql.ends_with(tag), "and must close the block: {sql}");
    }

    #[test]
    fn an_emptiness_assertion_delimiter_widens_the_same_way() {
        let sql = emptiness_assertion("jobs$autumn_walk$queue");
        let tag = sql
            .split_whitespace()
            .nth(1)
            .expect("the block must open with `DO <tag>`");
        assert_ne!(
            tag, "$autumn_walk$",
            "a table name carrying the default tag must push it wider: {sql}"
        );
        assert_eq!(sql.matches(tag).count(), 2, "opened and closed once: {sql}");
    }

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

    use autumn_schema_core::{Backend, Column, ColumnType, ForeignKey, Index, Table};

    use super::*;

    // ── Fixtures ────────────────────────────────────────────────────────────

    fn text_col(name: &str) -> Column {
        Column::new(name, ColumnType::Text)
    }

    fn pk_col(name: &str) -> Column {
        let mut c = Column::new(name, ColumnType::Int64);
        c.primary_key = true;
        c
    }

    /// `users(id PK, email TEXT UNIQUE, full_name TEXT, bio TEXT NULL,
    /// created_at TIMESTAMP)`.
    fn users_table() -> Table {
        let mut t = Table::new("users", Backend::Postgres);
        t.primary_key = vec!["id".to_owned()];
        let mut email = text_col("email");
        email.unique = true;
        let mut bio = text_col("bio");
        bio.nullable = true;
        t.columns = vec![
            pk_col("id"),
            email,
            text_col("full_name"),
            bio,
            Column::new("created_at", ColumnType::Timestamp),
        ];
        t
    }

    fn empty_encrypted() -> BTreeMap<String, BTreeMap<String, bool>> {
        BTreeMap::new()
    }

    /// `#[encrypted]` columns for one table, all randomized-mode.
    fn encrypted_columns_of(
        table: &str,
        columns: &[&str],
    ) -> BTreeMap<String, BTreeMap<String, bool>> {
        BTreeMap::from([(
            table.to_owned(),
            columns.iter().map(|c| ((*c).to_owned(), false)).collect(),
        )])
    }

    fn no_anonymize() -> BTreeSet<String> {
        BTreeSet::new()
    }

    fn plan_for(
        tables: &[Table],
        config: &ScrubConfig,
        encrypted: &BTreeMap<String, BTreeMap<String, bool>>,
        anonymize: &BTreeSet<String>,
    ) -> Result<ScrubPlan, ScrubError> {
        plan_with_facts(
            tables,
            config,
            encrypted,
            anonymize,
            &DatabaseFacts::default(),
        )
    }

    fn plan_with_facts(
        tables: &[Table],
        config: &ScrubConfig,
        encrypted: &BTreeMap<String, BTreeMap<String, bool>>,
        anonymize: &BTreeSet<String>,
        facts: &DatabaseFacts,
    ) -> Result<ScrubPlan, ScrubError> {
        build_plan(&ClassificationInputs {
            tables,
            config,
            encrypted,
            anonymize_tables: anonymize,
            facts,
        })
    }

    /// The single `UPDATE` a table plan carries (panics when it has none).
    fn sql_of(plan: &ScrubPlan, table: &str) -> String {
        plan.tables
            .iter()
            .find(|t| t.table == table)
            .unwrap_or_else(|| panic!("no plan for {table}"))
            .sql
            .clone()
            .unwrap_or_else(|| panic!("{table} has no SQL statement"))
    }

    // ── Config parsing ──────────────────────────────────────────────────────

    #[test]
    fn config_parses_the_sample_rules() {
        let config = parse_config_str(
            r#"
            [sample]
            always_include = ["countries"]
            never_include = ["audit_logs"]
            "#,
        )
        .unwrap();
        assert_eq!(config.sample.always_include, vec!["countries".to_owned()]);
        assert_eq!(config.sample.never_include, vec!["audit_logs".to_owned()]);
        assert!(sources_declare_sampling(&config));
        assert!(!sources_declare_sampling(&ScrubConfig::default()));
    }

    #[test]
    fn an_unknown_sample_key_is_refused_rather_than_ignored() {
        // A typo that silently did nothing would leave a table subsetted the
        // operator believed was excluded.
        let err = parse_config_str(
            r#"
            [sample]
            allways_include = ["countries"]
            "#,
        )
        .unwrap_err();
        assert!(matches!(err, ScrubError::Config { .. }));
    }

    #[test]
    fn percentages_report_n_a_rather_than_dividing_by_zero() {
        assert_eq!(percent_of(0, 0), "n/a");
        assert_eq!(percent_of(2, 200), "1.0%");
        assert_eq!(percent_of(200, 200), "100.0%");
    }

    #[test]
    fn byte_sizes_read_at_human_scale() {
        assert_eq!(human_bytes(0), "0 B");
        assert_eq!(human_bytes(512), "512 B");
        assert_eq!(human_bytes(1024), "1.0 kB");
        assert_eq!(human_bytes(1024 * 1024 * 3), "3.0 MB");
    }

    #[test]
    fn config_parses_defaults_safe_and_pii() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at"]

            [tables.users]
            safe = ["role"]

            [tables.users.pii]
            email = "email"
            full_name = "name"
            "#,
        )
        .expect("config must parse");

        assert_eq!(config.defaults.safe_columns, vec!["id", "created_at"]);
        let users = config.tables.get("users").expect("users rule");
        assert_eq!(users.safe, vec!["role"]);
        assert_eq!(users.pii.get("email"), Some(&Strategy::Email));
        assert_eq!(users.pii.get("full_name"), Some(&Strategy::Name));
    }

    #[test]
    fn config_rejects_unknown_strategy() {
        let err = parse_config_str(
            r#"
            [tables.users.pii]
            email = "obfuscate"
            "#,
        )
        .expect_err("unknown strategy must be rejected");
        assert!(
            err.to_string().contains("obfuscate"),
            "error should name the bad strategy: {err}"
        );
    }

    #[test]
    fn config_rejects_unknown_keys() {
        let err = parse_config_str(
            r#"
            [tables.users]
            saf = ["role"]
            "#,
        )
        .expect_err("a typo'd key must not be silently ignored");
        assert!(err.to_string().contains("saf"), "error: {err}");
    }

    #[test]
    fn empty_config_parses_to_default() {
        assert_eq!(parse_config_str("").unwrap(), ScrubConfig::default());
    }

    // ── Fail-closed classification (AC #3) ──────────────────────────────────

    #[test]
    fn unclassified_columns_are_refused_and_listed() {
        let tables = vec![users_table()];
        let err = plan_for(
            &tables,
            &ScrubConfig::default(),
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("an all-unclassified schema must be refused");

        let ScrubError::Unclassified { columns } = &err else {
            panic!("expected Unclassified, got {err:?}");
        };
        assert_eq!(
            columns,
            &vec![
                "users.bio".to_owned(),
                "users.created_at".to_owned(),
                "users.email".to_owned(),
                "users.full_name".to_owned(),
                "users.id".to_owned(),
            ]
        );
        // The message must be actionable: it names the columns and the file.
        let rendered = err.to_string();
        assert!(rendered.contains("users.email"), "{rendered}");
        assert!(rendered.contains(SCRUB_CONFIG_FILE), "{rendered}");
    }

    #[test]
    fn a_newly_added_column_flips_a_previously_clean_config_to_failure() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at"]
            [tables.users]
            safe = []
            [tables.users.pii]
            email = "email"
            full_name = "name"
            bio = "redact"
            "#,
        )
        .unwrap();
        let tables = vec![users_table()];
        plan_for(&tables, &config, &empty_encrypted(), &no_anonymize())
            .expect("the fully-declared schema must pass");

        // Someone adds `users.ssn` and forgets the declaration.
        let mut with_new_column = users_table();
        with_new_column.columns.push(text_col("ssn"));
        let err = plan_for(
            &[with_new_column],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("a new undeclared column must fail the scrub");
        assert!(matches!(
            err,
            ScrubError::Unclassified { ref columns } if columns == &vec!["users.ssn".to_owned()]
        ));
    }

    #[test]
    fn stale_config_entries_are_refused() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name", "bio"]
            [tables.users.pii]
            emial = "email"
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("a config naming a column that no longer exists must fail");
        assert!(
            matches!(err, ScrubError::StaleConfig { ref entries } if entries.contains(&"users.emial".to_owned())),
            "got {err:?}"
        );
    }

    #[test]
    fn stale_config_table_is_refused() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name", "bio"]
            [tables.legacy_users]
            safe = ["x"]
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("a config table that no longer exists must fail");
        assert!(
            matches!(err, ScrubError::StaleConfig { ref entries } if entries.contains(&"legacy_users".to_owned())),
            "got {err:?}"
        );
    }

    #[test]
    fn a_column_cannot_be_both_safe_and_pii() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users]
            safe = ["email"]
            [tables.users.pii]
            email = "email"
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("a contradictory declaration must fail");
        assert!(matches!(err, ScrubError::Contradiction { .. }), "{err:?}");
    }

    // ── Automatic classification (AC #2) ────────────────────────────────────

    #[test]
    fn encrypted_columns_are_pii_without_any_declaration() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users]
            safe = []
            "#,
        )
        .unwrap();
        let encrypted = encrypted_columns_of("users", &["email"]);

        let plan = plan_for(&[users_table()], &config, &encrypted, &no_anonymize())
            .expect("an #[encrypted] column needs no declaration");
        let column = plan
            .column("users", "email")
            .expect("email must be in the plan");
        assert_eq!(column.source, ClassSource::Encrypted);
    }

    #[test]
    fn safe_cannot_override_an_encrypted_column() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users]
            safe = ["email"]
            "#,
        )
        .unwrap();
        let encrypted = encrypted_columns_of("users", &["email"]);

        let err = plan_for(&[users_table()], &config, &encrypted, &no_anonymize())
            .expect_err("marking an #[encrypted] column safe must be refused");
        assert!(
            matches!(err, ScrubError::SafeOverridesEncrypted { ref columns } if columns == &vec!["users.email".to_owned()]),
            "got {err:?}"
        );
    }

    #[test]
    fn gdpr_anonymize_table_classifies_its_columns_as_pii() {
        let config = parse_config_str(
            r#"
            [tables.users]
            safe = ["id", "created_at"]
            "#,
        )
        .unwrap();
        let anonymize = BTreeSet::from(["users".to_owned()]);
        let plan = plan_for(&[users_table()], &config, &empty_encrypted(), &anonymize)
            .expect("a GDPR-anonymize table needs no per-column declaration");

        for column in ["email", "full_name", "bio"] {
            let decision = plan
                .column("users", column)
                .unwrap_or_else(|| panic!("{column} must be scrubbed"));
            assert_eq!(decision.source, ClassSource::GdprAnonymize);
        }
        // `id`/`created_at` were explicitly declared safe FOR THIS TABLE, so
        // they are untouched.
        assert!(plan.column("users", "id").is_none());
        assert!(plan.column("users", "created_at").is_none());
    }

    #[test]
    fn the_global_safe_list_may_not_narrow_a_gdpr_anonymize_table() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name"]
            "#,
        )
        .unwrap();
        let anonymize = BTreeSet::from(["users".to_owned()]);
        let plan = plan_for(&[users_table()], &config, &empty_encrypted(), &anonymize).unwrap();
        // A cross-table convenience list is not a per-column review, so it must
        // not silently exempt a column from a table the app registered for
        // anonymization.
        assert!(
            plan.column("users", "full_name").is_some(),
            "a global safe_columns entry must not narrow an anonymize registration"
        );
        // Structural columns are still skipped: the registration says nothing
        // about them and rewriting one would break referential integrity.
        assert!(plan.column("users", "id").is_none());
    }

    #[test]
    fn a_table_the_role_cannot_see_is_a_refusal_not_a_clean_report() {
        // `information_schema.tables` shows only what the connecting role has
        // privileges on, so a hidden table drops out of the classified universe
        // entirely — and "not classified" must never read as "clean".
        let facts = DatabaseFacts {
            public_base_tables: BTreeSet::from([
                "users".to_owned(),
                "secrets".to_owned(),
                // Framework-owned tables are excluded on purpose, not hidden.
                "autumn_jobs".to_owned(),
            ]),
            ..DatabaseFacts::default()
        };
        assert_eq!(
            unreachable_tables(&facts, &[users_table()]),
            vec!["secrets".to_owned()]
        );
        // Nothing hidden: no refusal.
        let visible = DatabaseFacts {
            public_base_tables: BTreeSet::from(["users".to_owned()]),
            ..DatabaseFacts::default()
        };
        assert!(unreachable_tables(&visible, &[users_table()]).is_empty());
    }

    #[test]
    fn a_unique_uuid_column_still_gets_a_castable_32_hex_value() {
        // A UUID is exactly 128 bits; Postgres rejects any other width, so the
        // wider token a unique column gets has to be trimmed.
        let column = Column::new("token", ColumnType::Uuid);
        let expr = replacement_expr(Strategy::Uuid, &column, "TOK", true).unwrap();
        assert_eq!(expr, "(substr(TOK, 1, 32))::uuid");
    }

    #[test]
    fn a_purge_target_under_rls_is_refused_like_any_other_write() {
        // Framework tables are excluded from `plan.tables`, so without this the
        // `DELETE` would apply to policy-visible rows only and still report the
        // table emptied.
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name", "bio"]
            [framework]
            purge = ["autumn_jobs"]
            "#,
        )
        .unwrap();
        let facts = DatabaseFacts {
            framework_tables: vec!["autumn_jobs".to_owned()],
            rls_tables: BTreeSet::from(["autumn_jobs".to_owned()]),
            ..DatabaseFacts::default()
        };
        // The plan itself is clean — the hazard is entirely in the purge target.
        let plan = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .unwrap();
        assert!(plan.tables.is_empty());
        let purges = purge_statements(&facts.framework_tables, &config);
        assert_eq!(purges.len(), 1);
        assert!(
            facts.rls_tables.contains(&purges[0].0),
            "a purge target under RLS must reach the refusal"
        );
    }

    #[test]
    fn a_purge_target_with_a_trigger_is_reported_like_any_other_write() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name", "bio"]
            [framework]
            purge = ["autumn_jobs"]
            "#,
        )
        .unwrap();
        let facts = DatabaseFacts {
            framework_tables: vec!["autumn_jobs".to_owned()],
            triggered_tables: BTreeSet::from(["autumn_jobs".to_owned()]),
            ..DatabaseFacts::default()
        };
        let plan = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .unwrap();
        let purges = purge_statements(&facts.framework_tables, &config);
        assert_eq!(
            triggered_write_targets(&plan, &purges, None, &facts),
            vec!["autumn_jobs".to_owned()]
        );
    }

    #[test]
    fn column_level_privilege_gaps_are_refused_too() {
        // A role can see a table but not all of its columns: the table
        // classifies, the visible columns are rewritten, and the hidden PII
        // survives a "successful" scrub.
        let facts = DatabaseFacts {
            public_base_tables: BTreeSet::from(["users".to_owned()]),
            public_columns: BTreeSet::from([
                ("users".to_owned(), "id".to_owned()),
                ("users".to_owned(), "email".to_owned()),
                ("users".to_owned(), "ssn".to_owned()),
            ]),
            ..DatabaseFacts::default()
        };
        // `users_table()` has no `ssn`, standing in for a column introspection
        // could not see.
        assert_eq!(
            unreachable_tables(&facts, &[users_table()]),
            vec!["users.ssn".to_owned()]
        );
    }

    #[test]
    fn every_payload_bearing_framework_table_is_listed() {
        // Each of these is excluded from classification by the `autumn_` prefix
        // (or the explicit filter) while holding app-supplied payloads or actor
        // identities.
        for table in [
            "_autumn_ledger_revisions",
            "_autumn_ledger_high_water",
            "_autumn_version_history",
            "api_tokens",
            "autumn_experiment_assignments",
            "autumn_experiment_changes",
            "autumn_experiment_overrides",
            "autumn_feature_flags",
            "autumn_jobs",
            "autumn_repository_commit_hooks",
            "autumn_runtime_config_changes",
            "autumn_runtime_config_values",
            "autumn_search_documents",
            "autumn_sync_rows",
            "feature_flag_changes",
        ] {
            assert!(
                FRAMEWORK_PAYLOAD_TABLES.contains(&table),
                "{table} carries app data the classification never sees"
            );
        }
    }

    #[test]
    fn encrypted_columns_may_be_declared_when_there_is_no_model_source() {
        let config = parse_config_str(
            r#"
            [tables.users.encrypted]
            api_token = "randomized"
            email = "deterministic"
            "#,
        )
        .unwrap();
        let users = config.tables.get("users").unwrap();
        assert_eq!(
            users.encrypted.get("email"),
            Some(&EncryptionMode::Deterministic),
            "the mode cannot be guessed: re-encrypting a deterministic column in \
             randomized mode leaves ciphertext the app can no longer equality-query"
        );
        assert!(!users.encrypted["api_token"].is_deterministic());
    }

    #[test]
    fn the_feature_flag_identity_tables_are_payload_carriers() {
        // `feature_flag_changes.actor` and `autumn_feature_flags.actor_allowlist`
        // both name individual users, and both are outside the classified
        // universe.
        for table in ["feature_flag_changes", "autumn_feature_flags"] {
            assert!(
                FRAMEWORK_PAYLOAD_TABLES.contains(&table),
                "{table} carries actor identities the classification never sees"
            );
            assert!(is_framework_table(table));
        }
    }

    #[test]
    fn a_check_constrained_column_is_refused_rather_than_guessed_at() {
        // A real Autumn closed-set column reaches the database as plain TEXT
        // plus a CHECK, so the model-IR-only `ColumnType::Enum` never fires
        // against a live schema — this is what actually catches it.
        let facts = DatabaseFacts {
            checked_columns: BTreeSet::from([("users".to_owned(), "bio".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name"]
            [tables.users.pii]
            bio = "redact"
            "#,
        )
        .unwrap();
        let err = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .expect_err("no fabricated value can be proven to satisfy an arbitrary CHECK");
        assert!(
            matches!(err, ScrubError::CheckConstrainedColumn { ref column } if column == "users.bio"),
            "got {err:?}"
        );
    }

    #[test]
    fn a_structural_encrypted_column_can_be_declared_safe() {
        // `users.email` is `#[encrypted]` and another table references it, so it
        // can never be rewritten. The only honest outcome is that the ciphertext
        // stays; a `safe` declaration must be able to say so.
        let facts = DatabaseFacts {
            foreign_key_columns: BTreeSet::from([("users".to_owned(), "email".to_owned())]),
            ..DatabaseFacts::default()
        };
        let encrypted = encrypted_columns_of("users", &["email"]);
        let safe = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "bio"]
            [tables.users]
            safe = ["email"]
            [tables.users.pii]
            full_name = "name"
            "#,
        )
        .unwrap();
        let plan = plan_with_facts(&[users_table()], &safe, &encrypted, &no_anonymize(), &facts)
            .expect("a declared-safe structural encrypted column terminates");
        assert!(plan.column("users", "email").is_none());

        let undeclared = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "bio"]
            [tables.users.pii]
            full_name = "name"
            "#,
        )
        .unwrap();
        let err = plan_with_facts(
            &[users_table()],
            &undeclared,
            &encrypted,
            &no_anonymize(),
            &facts,
        )
        .expect_err("without a declaration it still fails");
        assert!(
            matches!(err, ScrubError::PiiOnKeyColumn { ref columns } if columns == &vec!["users.email".to_owned()]),
            "{err:?}"
        );
        assert!(err.to_string().contains("ciphertext"), "{err}");
    }

    #[test]
    fn a_libpq_service_source_is_not_modelled_as_a_local_endpoint() {
        assert!(uses_libpq_service(
            "service=production user=app dbname=mydb"
        ));
        assert!(!uses_libpq_service("host=prod dbname=app"));
        assert!(uses_libpq_service("postgres:///app?service=production"));
        assert!(!uses_libpq_service("postgres://prod/app?sslmode=require"));
    }

    #[test]
    fn the_new_refusals_render_an_actionable_message() {
        let too_long = ScrubError::EncryptedEnvelopeTooLong {
            column: "users.bio".to_owned(),
            limit: 100,
            needed: 148,
        }
        .to_string();
        assert!(
            too_long.contains("100") && too_long.contains("148"),
            "{too_long}"
        );
        let operand = ScrubError::IndexOperandColumn {
            column: "users.email".to_owned(),
            kind: "an exclusion constraint",
        }
        .to_string();
        assert!(
            operand.contains("exclusion constraint") && operand.contains("`safe`"),
            "{operand}"
        );
        let drift = ScrubError::SchemaChanged {
            entries: vec!["users.ssn (column added)".to_owned()],
        }
        .to_string();
        assert!(
            drift.contains("users.ssn") && drift.contains("Nothing was written"),
            "{drift}"
        );
    }

    #[test]
    fn the_anonymize_scan_visits_every_item_and_expression_kind() {
        // Parse-only: the scan never type-checks. Each construct reaches a
        // visitor arm, and none of them registers a table.
        let src = r#"
            const C: u8 = 1;
            static S: u8 = 2;
            trait T { const X: u8; fn f(&self) { let _ = 1; } }
            struct W;
            impl W { const Y: u8 = 3; fn g(&self) -> u8 { 4 } }
            async fn h(v: Vec<u8>, mut n: u8, o: Option<u8>) -> Option<u8> {
                let a = [1, 2];
                n = a[0] + 1;
                let _ = async { 5 }.await;
                let _ = (n as u16, |x: u8| x, const { 6 }, v.len(), (n), &n, n..3);
                let _ = [0u8; 2];
                for i in 0..2 { if i == 1 { break; } else { continue; } }
                while n > 9 { n -= 1; }
                loop { break; }
                if let Some(z) = o { let _ = z; }
                let _ = unsafe { 7 };
                let _ = -n;
                let _ = struct_lit();
                let _ = o?;
                println!("{}", n);
                match n { 0 => {} _ => {} }
                return o;
            }
            fn struct_lit() -> W { W }
        "#;
        assert!(extract_anonymize_tables(src).unwrap().is_empty());
        let disabled = r#"
            #[cfg(test)] const C: u8 = 1;
            #[cfg(test)] static S: u8 = 2;
            trait T { #[cfg(test)] const X: u8; #[cfg(test)] fn f(&self); }
            struct W;
            impl W { #[cfg(test)] const Y: u8 = 3; #[cfg(test)] fn g(&self) {} }
            fn k() { #[cfg(test)] println!("x"); #[cfg(test)] let _ = 1; }
        "#;
        assert!(extract_anonymize_tables(disabled).unwrap().is_empty());
        let field = r#"
            fn reg() -> R { R { #[cfg(test)] m: ModelRegistration::anonymize("users") } }
        "#;
        assert!(extract_anonymize_tables(field).unwrap().is_empty());
        let variant = r#"
            enum E { #[cfg(test)] V = { ModelRegistration::anonymize("users"); 0 } }
        "#;
        assert!(extract_anonymize_tables(variant).unwrap().is_empty());
        let decl = r#"
            struct S { #[cfg(test)] f: [(); { ModelRegistration::anonymize("users"); 0 }] }
        "#;
        assert!(extract_anonymize_tables(decl).unwrap().is_empty());
        let item = r#"
            #[cfg(test)] struct F { f: [(); { ModelRegistration::anonymize("users"); 0 }] }
        "#;
        assert!(extract_anonymize_tables(item).unwrap().is_empty());
        let param = r#"
            fn f(#[cfg(test)] x: [(); { ModelRegistration::anonymize("users"); 0 }]) {}
        "#;
        assert!(extract_anonymize_tables(param).unwrap().is_empty());
        let generic = r#"
            struct R<#[cfg(test)] T = [(); { ModelRegistration::anonymize("users"); 0 }]>(T);
        "#;
        assert!(extract_anonymize_tables(generic).unwrap().is_empty());
        let closure = r#"
            fn c() { let _ = |#[cfg(test)] x: [(); { ModelRegistration::anonymize("users"); 0 }]| {}; }
        "#;
        assert!(extract_anonymize_tables(closure).unwrap().is_empty());
        let foreign = r#"
            #[cfg(test)] extern "C" { static X: [u8; { ModelRegistration::anonymize("users"); 0 }]; }
            extern "C" { #[cfg(test)] static Y: [u8; { ModelRegistration::anonymize("users"); 0 }]; }
        "#;
        assert!(extract_anonymize_tables(foreign).unwrap().is_empty());
    }

    #[test]
    fn output_needs_every_configured_target() {
        let with_output = ScrubArgs {
            output: Some(PathBuf::from("out")),
            ..ScrubArgs::default()
        };
        assert!(refuse_partial_output(&with_output, 1, 2).is_err());
        assert!(refuse_partial_output(&with_output, 2, 2).is_ok());
        assert!(refuse_partial_output(&ScrubArgs::default(), 1, 2).is_ok());
    }

    #[test]
    fn the_anonymize_scan_reports_unreadable_and_unresolvable_sources() {
        let dir = tempfile::tempdir().unwrap();
        assert!(
            scan_anonymize_tables(&dir.path().join("missing"))
                .unwrap()
                .is_empty()
        );
        std::fs::write(dir.path().join("bad.rs"), "fn {").unwrap();
        let err = scan_anonymize_tables(dir.path()).unwrap_err();
        assert!(matches!(err, ScrubError::SourceScan { .. }), "{err:?}");
        std::fs::write(
            dir.path().join("bad.rs"),
            "fn f(t: &str) { ModelRegistration::anonymize(t); }",
        )
        .unwrap();
        let err = scan_anonymize_tables(dir.path()).unwrap_err();
        assert!(
            matches!(err, ScrubError::UnresolvableAnonymize { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn conninfo_pairs_handles_quotes_escapes_and_rejections() {
        let pairs = |s: &str| conninfo_pairs(s);
        assert_eq!(
            pairs("host = 'a b' dbname=x\\ y"),
            Some(vec![
                ("host".to_owned(), "a b".to_owned()),
                ("dbname".to_owned(), "x y".to_owned())
            ])
        );
        assert_eq!(
            pairs("host='a\\'b'"),
            Some(vec![("host".to_owned(), "a'b".to_owned())])
        );
        assert_eq!(pairs("host"), None, "no equals sign");
        assert_eq!(pairs("host='open"), None, "unterminated quote");
        assert_eq!(pairs("host="), None, "empty unquoted value");
        assert_eq!(
            pairs("host=a\\"),
            Some(vec![("host".to_owned(), "a".to_owned())])
        );
        assert_eq!(pairs(""), Some(Vec::new()));
        assert_eq!(without_userinfo("no scheme"), "no scheme");
        assert_eq!(without_userinfo("postgres://h/db"), "postgres://h/db");
    }

    #[test]
    fn report_triggers_prints_only_for_triggered_write_targets() {
        let plan = ScrubPlan::default();
        let facts = DatabaseFacts {
            triggered_tables: BTreeSet::from(["autumn_jobs".to_owned()]),
            ..DatabaseFacts::default()
        };
        // No purge: nothing to report.
        report_triggers(&plan, &[], None, &facts);
        // A purge target with a trigger: prints the warning.
        report_triggers(
            &plan,
            &[(
                "autumn_jobs".to_owned(),
                "DELETE FROM autumn_jobs".to_owned(),
            )],
            None,
            &facts,
        );
    }

    #[test]
    fn the_generated_column_probe_runs_on_servers_without_attgenerated() {
        assert!(GENERATED_COLUMNS.contains("to_jsonb(att)"));
    }

    #[test]
    fn the_matview_snapshot_changes_when_a_view_is_recreated() {
        assert!(TRIGGER_IDENTITIES.contains("pg_get_triggerdef"));
        assert!(TRIGGER_IDENTITIES.contains("pg_get_ruledef"));
        assert!(PUBLIC_MATVIEWS.contains("rel.oid"));
        assert!(PUBLIC_MATVIEWS.contains("pg_get_viewdef"));
    }

    #[test]
    fn the_view_snapshot_covers_views_outside_public() {
        assert!(PUBLIC_MATVIEWS.contains("ns.nspname || '.'"));
        assert!(PUBLIC_MATVIEWS.contains("!~ '^pg_'"));
    }

    #[test]
    fn the_rls_probe_asks_about_the_connected_role() {
        for term in [
            "rolsuper",
            "rolbypassrls",
            "relforcerowsecurity",
            "relowner",
        ] {
            assert!(
                RLS_RESTRICTED_TABLES.contains(term),
                "the RLS probe must consult {term}"
            );
        }
    }

    #[test]
    fn an_index_expression_or_exclusion_operand_is_refused_for_every_strategy() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "email"
            "#,
        )
        .unwrap();
        for facts in [
            DatabaseFacts {
                unique_expression_columns: BTreeSet::from([(
                    "users".to_owned(),
                    "email".to_owned(),
                )]),
                ..DatabaseFacts::default()
            },
            DatabaseFacts {
                exclusion_columns: BTreeSet::from([("users".to_owned(), "email".to_owned())]),
                ..DatabaseFacts::default()
            },
        ] {
            let err = plan_with_facts(
                &[users_table()],
                &config,
                &empty_encrypted(),
                &no_anonymize(),
                &facts,
            )
            .expect_err("injective on its own value is not injective under an expression");
            assert!(
                matches!(err, ScrubError::IndexOperandColumn { ref column, .. } if column == "users.email"),
                "got {err:?}"
            );
        }
    }

    #[test]
    fn a_partition_only_constraint_folds_into_its_parent() {
        let partitions = BTreeMap::from([("users_2026".to_owned(), "users".to_owned())]);
        let checks = fold_into_parent(
            vec![
                ("users_2026".to_owned(), "email".to_owned()),
                ("orders".to_owned(), "total".to_owned()),
            ],
            &partitions,
        );
        assert!(checks.contains(&("users".to_owned(), "email".to_owned())));
        assert!(checks.contains(&("orders".to_owned(), "total".to_owned())));
    }

    #[test]
    fn an_encrypted_declaration_on_a_non_text_column_is_refused_at_plan_time() {
        let mut table = users_table();
        table.columns[3].ty = ColumnType::Int64; // `bio`
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name"]
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[table],
            &config,
            &encrypted_columns_of("users", &["bio"]),
            &no_anonymize(),
        )
        .expect_err("an AEAD text envelope cannot be stored in an integer column");
        assert!(
            matches!(err, ScrubError::StrategyTypeMismatch { ref column, strategy: "encrypted", .. } if column == "users.bio"),
            "{err:?}"
        );
    }

    #[test]
    fn an_envelope_that_cannot_fit_a_bounded_column_is_refused_at_plan_time() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name"]
            "#,
        )
        .unwrap();
        let bounded = |limit: &str| {
            let mut table = users_table();
            table.columns[3].ty = ColumnType::Opaque {
                pg_type: format!("varchar({limit})"),
            };
            plan_for(
                &[table],
                &config,
                &encrypted_columns_of("users", &["bio"]),
                &no_anonymize(),
            )
        };
        let err = bounded("100").expect_err("a 148-character envelope cannot fit 100");
        assert!(
            matches!(err, ScrubError::EncryptedEnvelopeTooLong { ref column, limit: 100, needed: 148 } if column == "users.bio"),
            "{err:?}"
        );
        bounded("148").expect("exactly enough room");
    }

    #[test]
    fn the_referenced_side_of_a_foreign_key_is_refused() {
        // `orders.user_email REFERENCES users(email)` leaves `users.email` with
        // no `references` of its own, so only the probed catalog set can see it.
        let facts = DatabaseFacts {
            foreign_key_columns: BTreeSet::from([("users".to_owned(), "email".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "email"
            "#,
        )
        .unwrap();
        let err = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .expect_err("rewriting a referenced natural key breaks its children");
        assert!(
            matches!(err, ScrubError::PiiOnKeyColumn { ref columns } if columns == &vec!["users.email".to_owned()]),
            "got {err:?}"
        );
    }

    #[test]
    fn a_partition_key_column_is_refused_as_pii() {
        // Rewriting the key moves rows between partitions, or aborts.
        let facts = DatabaseFacts {
            partition_key_columns: BTreeSet::from([("users".to_owned(), "email".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "email"
            "#,
        )
        .unwrap();
        let err = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .expect_err("a partition key must not be rewritten");
        assert!(
            matches!(err, ScrubError::PiiOnKeyColumn { ref columns } if columns == &vec!["users.email".to_owned()]),
            "got {err:?}"
        );
    }

    #[test]
    fn a_partition_key_column_declared_safe_is_left_alone() {
        let facts = DatabaseFacts {
            partition_key_columns: BTreeSet::from([("users".to_owned(), "email".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "bio"]
            [tables.users.pii]
            full_name = "name"
            "#,
        )
        .unwrap();
        let plan = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .expect("a safe partition key needs no refusal");
        assert!(plan.column("users", "email").is_none());
    }

    #[test]
    fn a_table_level_anonymize_skips_the_partition_key() {
        let facts = DatabaseFacts {
            partition_key_columns: BTreeSet::from([("users".to_owned(), "email".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at"]
            "#,
        )
        .unwrap();
        let anonymize = BTreeSet::from(["users".to_owned()]);
        let plan = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &anonymize,
            &facts,
        )
        .expect("anonymize leaves structural columns alone");
        assert!(plan.column("users", "email").is_none());
        assert!(plan.column("users", "full_name").is_some());
    }

    #[test]
    fn a_sub_partition_key_is_folded_into_the_root() {
        let facts = DatabaseFacts {
            partitions: BTreeMap::from([("users_2026".to_owned(), "users".to_owned())]),
            ..DatabaseFacts::default()
        };
        let keys = fold_into_parent(
            vec![("users_2026".to_owned(), "email".to_owned())],
            &facts.partitions,
        );
        assert_eq!(
            keys,
            BTreeSet::from([("users".to_owned(), "email".to_owned())])
        );
    }

    #[test]
    fn a_generated_column_is_never_rewritten() {
        // Postgres refuses `UPDATE` on a generated column outright, and it is
        // derived data that a scrub of its source columns already covers.
        let facts = DatabaseFacts {
            generated_columns: BTreeSet::from([("users".to_owned(), "full_name".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "bio"]
            "#,
        )
        .unwrap();
        let plan = plan_with_facts(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .expect("a generated column needs no declaration");
        assert!(plan.column("users", "full_name").is_none());
    }

    #[test]
    fn a_partition_is_scrubbed_through_its_parent_not_twice() {
        let mut partition = users_table();
        partition.name = "users_2026_01".to_owned();
        let facts = DatabaseFacts {
            partitions: BTreeMap::from([("users_2026_01".to_owned(), "users".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at"]
            [tables.users.pii]
            email = "email"
            full_name = "name"
            bio = "redact"
            "#,
        )
        .unwrap();
        let plan = plan_with_facts(
            &[users_table(), partition],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
            &facts,
        )
        .expect("a partition needs no declaration of its own");
        assert_eq!(
            plan.tables.len(),
            1,
            "the parent UPDATE already covers the partition's rows"
        );
        assert_eq!(plan.tables[0].table, "users");
    }

    #[test]
    fn null_is_refused_on_a_nulls_not_distinct_unique_column() {
        let mut t = users_table();
        t.columns[3].unique = true; // `bio`, nullable
        let facts = DatabaseFacts {
            nulls_not_distinct_columns: BTreeSet::from([("users".to_owned(), "bio".to_owned())]),
            ..DatabaseFacts::default()
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name"]
            [tables.users.pii]
            bio = "null"
            "#,
        )
        .unwrap();
        // `null` is normally unique-safe (Postgres allows many NULLs in a
        // unique index) — but not under NULLS NOT DISTINCT.
        let err = plan_with_facts(&[t], &config, &empty_encrypted(), &no_anonymize(), &facts)
            .expect_err("a second NULL is a violation under NULLS NOT DISTINCT");
        assert!(
            matches!(err, ScrubError::NonUniqueStrategy { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn a_unique_column_gets_a_wider_token_and_a_higher_floor() {
        let table = users_table();
        let unique_token = token_expr(&table, "email", true);
        assert_eq!(
            unique_token.matches("md5(").count(),
            2,
            "a unique column needs more entropy than one md5's 32 hex characters: \
             {unique_token}"
        );
        assert!(token_expr(&table, "bio", false).contains("md5("));

        // 19 chars with `redact`'s 11 of affixes leaves 8 — fine for a
        // non-unique column, a collision generator for a unique one (32 bits
        // collides in practice around 10^5 rows).
        let narrow = Column::new(
            "code",
            ColumnType::Opaque {
                pg_type: "varchar(19)".to_owned(),
            },
        );
        assert!(replacement_expr(Strategy::Redact, &narrow, "TOK", false).is_ok());
        assert!(matches!(
            replacement_expr(Strategy::Redact, &narrow, "TOK", true),
            Err(ScrubError::ColumnTooNarrow { .. })
        ));
    }

    #[test]
    fn a_text_strategy_is_refused_on_a_non_character_column() {
        for (name, ty) in [
            ("age", ColumnType::Int32),
            ("seen_at", ColumnType::TimestampTz),
            (
                "ip",
                ColumnType::Opaque {
                    pg_type: "inet".to_owned(),
                },
            ),
        ] {
            let column = Column::new(name, ty);
            for strategy in [
                Strategy::Email,
                Strategy::Name,
                Strategy::Redact,
                Strategy::Phone,
            ] {
                assert!(
                    matches!(
                        replacement_expr(strategy, &column, "TOK", false),
                        Err(ScrubError::StrategyTypeMismatch { .. })
                    ),
                    "{strategy:?} on {name} must be refused at plan time, not at apply time"
                );
            }
        }
    }

    #[test]
    fn the_null_assignment_carries_no_untyped_case() {
        // A `CASE` whose arms are both bare NULL has no type to infer from, so
        // Postgres resolves it to `text` and the assignment fails on every
        // non-character column.
        let mut column = Column::new("token", ColumnType::Uuid);
        column.nullable = true;
        assert_eq!(
            assignment(&column, "NULL", Strategy::Null),
            r#""token" = NULL"#
        );
        assert!(
            assignment(&column, "X", Strategy::Uuid).contains("CASE WHEN"),
            "every other strategy still preserves NULLs"
        );
    }

    #[test]
    fn auto_strategy_covers_the_everyday_opaque_pii_types() {
        for (pg_type, expected) in [
            ("date", Strategy::Epoch),
            ("time", Strategy::Epoch),
            ("int2", Strategy::Zero),
            ("numeric(12,2)", Strategy::Zero),
        ] {
            let column = Column::new(
                "value",
                ColumnType::Opaque {
                    pg_type: pg_type.to_owned(),
                },
            );
            assert_eq!(
                auto_strategy(&column).unwrap(),
                expected,
                "`{pg_type}` is an everyday PII column type and needs a usable strategy"
            );
            assert!(replacement_expr(expected, &column, "TOK", false).is_ok());
        }
    }

    #[test]
    fn purge_never_accepts_schema_bookkeeping() {
        for table in NEVER_PURGEABLE_TABLES {
            let config =
                parse_config_str(&format!("[framework]\npurge = [\"{table}\"]\n")).unwrap();
            assert!(
                matches!(
                    check_purge_list(&config),
                    Err(ScrubError::PurgeSchemaBookkeeping { .. })
                ),
                "emptying {table} would make the copy un-migratable or un-routable"
            );
        }
    }

    #[test]
    fn declaring_a_framework_table_points_at_the_right_mechanism() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name", "bio"]
            [tables.api_tokens.pii]
            token = "redact"
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("a framework table cannot be declared column-by-column");
        // Not "the database does not have it" — that would send the developer
        // hunting for a typo in a name that is spelled correctly.
        assert!(
            matches!(err, ScrubError::FrameworkTableDeclared { ref tables } if tables == &vec!["api_tokens".to_owned()]),
            "got {err:?}"
        );
    }

    #[test]
    fn safe_may_narrow_a_gdpr_anonymize_table() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at"]
            [tables.users]
            safe = ["full_name"]
            "#,
        )
        .unwrap();
        let anonymize = BTreeSet::from(["users".to_owned()]);
        let plan = plan_for(&[users_table()], &config, &empty_encrypted(), &anonymize).unwrap();
        assert!(plan.column("users", "full_name").is_none());
        assert!(plan.column("users", "email").is_some());
    }

    #[test]
    fn explicit_pii_wins_over_the_auto_strategy() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "bio"]
            [tables.users.pii]
            full_name = "redact"
            "#,
        )
        .unwrap();
        let plan = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .unwrap();
        let column = plan.column("users", "full_name").unwrap();
        assert_eq!(column.strategy, Strategy::Redact);
        assert_eq!(column.source, ClassSource::Config);
    }

    #[test]
    fn a_plaintext_strategy_is_refused_on_an_encrypted_column() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "redact"
            "#,
        )
        .unwrap();
        // Writing a plain string into an at-rest-encrypted column makes every
        // later read of that row fail as malformed ciphertext, so a declaration
        // may not choose one.
        let err = plan_for(
            &[users_table()],
            &config,
            &encrypted_columns_of("users", &["email"]),
            &no_anonymize(),
        )
        .expect_err("plaintext must never be written into an #[encrypted] column");
        assert!(
            matches!(err, ScrubError::PlaintextIntoEncrypted { ref columns } if columns[0].starts_with("users.email")),
            "got {err:?}"
        );
    }

    #[test]
    fn an_encrypted_column_resolves_to_a_re_encryption_and_carries_its_mode() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            "#,
        )
        .unwrap();
        let encrypted = BTreeMap::from([(
            "users".to_owned(),
            BTreeMap::from([("email".to_owned(), true)]),
        )]);
        let plan = plan_for(&[users_table()], &config, &encrypted, &no_anonymize()).unwrap();
        assert_eq!(
            plan.column("users", "email").unwrap().strategy,
            Strategy::Encrypted
        );
        let table = &plan.tables[0];
        assert!(
            table.sql.is_none(),
            "an encrypted rewrite is not expressible as SQL: {:?}",
            table.sql
        );
        assert_eq!(table.encrypted.len(), 1);
        assert!(
            table.encrypted[0].deterministic,
            "a deterministic column must be re-encrypted deterministically, or equality \
             lookups against it stop matching"
        );
        assert_eq!(table.encrypted[0].shape, Strategy::Email);
    }

    #[test]
    fn null_may_still_be_declared_on_a_nullable_encrypted_column() {
        let mut t = users_table();
        t.columns[1].nullable = true;
        t.columns[1].unique = false;
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "null"
            "#,
        )
        .unwrap();
        let plan = plan_for(
            &[t],
            &config,
            &encrypted_columns_of("users", &["email"]),
            &no_anonymize(),
        )
        .expect("NULL is a valid, readable value for an encrypted column");
        assert_eq!(
            plan.column("users", "email").unwrap().strategy,
            Strategy::Null
        );
    }

    // ── Constraint safety (AC #4)     // ── Constraint safety (AC #4) ───────────────────────────────────────────

    #[test]
    fn pii_on_a_primary_key_is_refused() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["created_at", "email", "full_name", "bio"]
            [tables.users.pii]
            id = "zero"
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("scrubbing a primary key would break referencing rows");
        assert!(
            matches!(err, ScrubError::PiiOnKeyColumn { ref columns } if columns == &vec!["users.id".to_owned()]),
            "got {err:?}"
        );
    }

    #[test]
    fn pii_on_a_foreign_key_is_refused() {
        let mut posts = Table::new("posts", Backend::Postgres);
        posts.primary_key = vec!["id".to_owned()];
        let mut author = Column::new("author_id", ColumnType::Int64);
        author.references = Some(ForeignKey::new("users", "id"));
        posts.columns = vec![pk_col("id"), author];

        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id"]
            [tables.posts.pii]
            author_id = "zero"
            "#,
        )
        .unwrap();
        let err = plan_for(&[posts], &config, &empty_encrypted(), &no_anonymize())
            .expect_err("scrubbing a foreign key would break referential integrity");
        assert!(
            matches!(err, ScrubError::PiiOnKeyColumn { ref columns } if columns == &vec!["posts.author_id".to_owned()]),
            "got {err:?}"
        );
    }

    #[test]
    fn a_gdpr_anonymize_table_never_auto_classifies_its_key_columns() {
        let mut posts = Table::new("posts", Backend::Postgres);
        posts.primary_key = vec!["id".to_owned()];
        let mut author = Column::new("author_id", ColumnType::Int64);
        author.references = Some(ForeignKey::new("users", "id"));
        posts.columns = vec![pk_col("id"), author, text_col("body")];

        let plan = plan_for(
            &[posts],
            &ScrubConfig::default(),
            &empty_encrypted(),
            &BTreeSet::from(["posts".to_owned()]),
        )
        .expect("key columns are structurally safe under a table-level inference");
        assert!(plan.column("posts", "id").is_none());
        assert!(plan.column("posts", "author_id").is_none());
        assert!(plan.column("posts", "body").is_some());
    }

    #[test]
    fn null_strategy_is_refused_on_a_not_null_column() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "bio"]
            [tables.users.pii]
            full_name = "null"
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("NULL into a NOT NULL column must be refused at plan time");
        assert!(matches!(err, ScrubError::NullOnNotNull { .. }), "{err:?}");
    }

    #[test]
    fn null_strategy_is_allowed_on_a_nullable_column() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name"]
            [tables.users.pii]
            bio = "null"
            "#,
        )
        .unwrap();
        let plan = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .unwrap();
        assert_eq!(
            plan.column("users", "bio").unwrap().strategy,
            Strategy::Null
        );
    }

    #[test]
    fn a_non_injective_strategy_is_refused_on_a_unique_column() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "json"
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("a constant replacement would violate the unique index");
        assert!(
            matches!(err, ScrubError::NonUniqueStrategy { .. }),
            "got {err:?}"
        );
    }

    // ── Replacement expressions ─────────────────────────────────────────────

    #[test]
    fn row_key_uses_the_primary_key_when_present() {
        assert_eq!(row_key_expr(&users_table()), r#"coalesce("id"::text, '')"#);
    }

    #[test]
    fn row_key_falls_back_to_ctid_without_a_primary_key() {
        let mut t = Table::new("legacy", Backend::Postgres);
        t.columns = vec![text_col("note")];
        assert_eq!(row_key_expr(&t), "ctid::text");
    }

    #[test]
    fn row_key_concatenates_a_composite_primary_key() {
        let mut t = Table::new("memberships", Backend::Postgres);
        t.primary_key = vec!["user_id".to_owned(), "team_id".to_owned()];
        let mut user_id = Column::new("user_id", ColumnType::Int64);
        user_id.primary_key = true;
        let mut team_id = Column::new("team_id", ColumnType::Int64);
        team_id.primary_key = true;
        t.columns = vec![user_id, team_id];
        // `ROW(...)::text` carries Postgres's own quoting, so ('a|','b') and
        // ('a','|b') cannot collapse into one row key the way a plain
        // separator-joined concatenation does.
        assert_eq!(row_key_expr(&t), r#"ROW("user_id", "team_id")::text"#);
    }

    #[test]
    fn token_is_salted_per_column_so_two_columns_never_match() {
        let table = users_table();
        assert_ne!(
            token_expr(&table, "email", false),
            token_expr(&table, "full_name", false),
            "two PII columns of one row must not receive the same fake value"
        );
    }

    #[test]
    fn email_expression_is_unique_per_row_and_uses_a_reserved_domain() {
        let expr = replacement_expr(Strategy::Email, &text_col("email"), "TOK", false).unwrap();
        assert!(expr.contains("TOK"), "must vary per row: {expr}");
        assert!(
            expr.contains("@example.invalid"),
            "must use a reserved, undeliverable domain: {expr}"
        );
    }

    #[test]
    fn varchar_length_bounds_the_generated_value() {
        let column = Column::new(
            "email",
            ColumnType::Opaque {
                pg_type: "varchar(40)".to_owned(),
            },
        );
        let expr = replacement_expr(Strategy::Email, &column, "TOK", false).unwrap();
        // `scrubbed+` (9) + token + `@example.invalid` (16) must fit in 40.
        assert!(
            expr.contains("substr(TOK, 1, 15)"),
            "token must be narrowed to fit varchar(40): {expr}"
        );
    }

    #[test]
    fn a_too_narrow_column_is_refused_rather_than_silently_truncated() {
        let column = Column::new(
            "email",
            ColumnType::Opaque {
                pg_type: "varchar(28)".to_owned(),
            },
        );
        let err = replacement_expr(Strategy::Email, &column, "TOK", false)
            .expect_err("a column too narrow for a unique fake must be refused");
        assert!(matches!(err, ScrubError::ColumnTooNarrow { .. }), "{err:?}");
    }

    #[test]
    fn char_length_is_parsed_from_the_opaque_pg_type() {
        assert_eq!(
            char_max_len(&ColumnType::Opaque {
                pg_type: "varchar(64)".to_owned()
            }),
            Some(64)
        );
        assert_eq!(
            char_max_len(&ColumnType::Opaque {
                pg_type: "char(2)".to_owned()
            }),
            Some(2)
        );
        assert_eq!(char_max_len(&ColumnType::Text), None);
        assert_eq!(
            char_max_len(&ColumnType::Opaque {
                pg_type: "citext".to_owned()
            }),
            None
        );
    }

    #[test]
    fn auto_strategy_is_derived_from_the_column_type() {
        assert_eq!(
            auto_strategy(&text_col("email")).unwrap(),
            Strategy::Email,
            "an email-named text column gets a syntactically valid address"
        );
        assert_eq!(auto_strategy(&text_col("bio")).unwrap(), Strategy::Redact);
        assert_eq!(
            auto_strategy(&Column::new("token", ColumnType::Uuid)).unwrap(),
            Strategy::Uuid
        );
        assert_eq!(
            auto_strategy(&Column::new("blob", ColumnType::Bytes)).unwrap(),
            Strategy::Bytes
        );
        assert_eq!(
            auto_strategy(&Column::new("meta", ColumnType::Json)).unwrap(),
            Strategy::Json
        );
        assert_eq!(
            auto_strategy(&Column::new("age", ColumnType::Int32)).unwrap(),
            Strategy::Zero
        );
        assert_eq!(
            auto_strategy(&Column::new("seen_at", ColumnType::TimestampTz)).unwrap(),
            Strategy::Epoch
        );
    }

    #[test]
    fn auto_strategy_refuses_to_guess_for_a_closed_set_or_exotic_type() {
        assert!(matches!(
            auto_strategy(&Column::new(
                "status",
                ColumnType::Enum {
                    variants: vec!["draft".to_owned()]
                }
            )),
            Err(ScrubError::NoAutoStrategy { .. })
        ));
        assert!(matches!(
            auto_strategy(&Column::new(
                "addr",
                ColumnType::Opaque {
                    pg_type: "inet".to_owned()
                }
            )),
            Err(ScrubError::NoAutoStrategy { .. })
        ));
    }

    // ── Statement generation ────────────────────────────────────────────────

    #[test]
    fn update_preserves_nulls_and_batches_a_table_into_one_statement() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at"]
            [tables.users.pii]
            email = "email"
            full_name = "name"
            bio = "redact"
            "#,
        )
        .unwrap();
        let plan = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .unwrap();
        assert_eq!(plan.tables.len(), 1, "one statement per table");
        let sql = sql_of(&plan, "users");
        assert!(sql.starts_with(r#"UPDATE "public"."users" SET "#), "{sql}");
        assert!(
            sql.contains(r#""bio" = CASE WHEN "bio" IS NULL THEN NULL ELSE"#),
            "a nullable column must keep its NULLs: {sql}"
        );
        assert!(
            !sql.contains(r#""full_name" = CASE"#),
            "a NOT NULL column needs no CASE: {sql}"
        );
        assert!(sql.contains(r#""email" = "#) && sql.contains(r#""full_name" = "#));
    }

    #[test]
    fn a_table_with_no_pii_produces_no_statement() {
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name", "bio"]
            "#,
        )
        .unwrap();
        let plan = plan_for(
            &[users_table()],
            &config,
            &empty_encrypted(),
            &no_anonymize(),
        )
        .unwrap();
        assert!(plan.tables.is_empty(), "nothing to scrub, nothing emitted");
    }

    #[test]
    fn identifiers_with_quotes_are_escaped_in_the_statement() {
        let mut t = Table::new(r#"we"ird"#, Backend::Postgres);
        t.primary_key = vec!["id".to_owned()];
        t.columns = vec![pk_col("id"), text_col(r#"na"me"#)];
        let mut config = ScrubConfig::default();
        config.defaults.safe_columns = vec!["id".to_owned()];
        config.tables.insert(
            r#"we"ird"#.to_owned(),
            TableRule {
                safe: Vec::new(),
                pii: BTreeMap::from([(r#"na"me"#.to_owned(), Strategy::Redact)]),
                encrypted: BTreeMap::new(),
            },
        );
        let plan = plan_for(&[t], &config, &empty_encrypted(), &no_anonymize()).unwrap();
        let sql = sql_of(&plan, r#"we"ird"#);
        assert!(
            sql.starts_with(r#"UPDATE "public"."we""ird" SET "na""me" = "#),
            "{sql}"
        );
    }

    // ── GDPR anonymize extraction from app source ───────────────────────────

    #[test]
    fn anonymize_registrations_are_extracted_from_source() {
        let src = r#"
            use autumn_web::gdpr::{GdprRegistry, ModelRegistration};
            fn registry() -> GdprRegistry {
                GdprRegistry::new()
                    .register(ModelRegistration::hard_delete("posts"))
                    .register(ModelRegistration::anonymize("comments"))
                    .register(ModelRegistration::retain("invoices", "legal hold"))
                    .register(autumn_web::gdpr::ModelRegistration::anonymize("profiles"))
            }
        "#;
        let found = extract_anonymize_tables(src).expect("source must parse");
        assert_eq!(
            found,
            BTreeSet::from(["comments".to_owned(), "profiles".to_owned()])
        );
    }

    #[test]
    fn a_commented_out_registration_is_not_extracted() {
        let src = r#"
            fn registry() {
                // ModelRegistration::anonymize("ghosts")
                let _ = ModelRegistration::anonymize("comments");
            }
        "#;
        let found = extract_anonymize_tables(src).unwrap();
        assert_eq!(found, BTreeSet::from(["comments".to_owned()]));
    }

    #[test]
    fn a_non_literal_registration_argument_is_reported_not_ignored() {
        let src = "
            fn registry() {
                let _ = ModelRegistration::anonymize(table_name());
            }
        ";
        let err = extract_anonymize_tables(src)
            .expect_err("a table name the scanner cannot resolve must not pass silently");
        assert!(
            matches!(err, ScrubError::UnresolvableAnonymize { .. }),
            "{err:?}"
        );
    }

    // ── Production guard (AC #5) ────────────────────────────────────────────

    #[test]
    fn scrub_refuses_a_production_profile_without_force() {
        for profile in ["prod", "production", "staging"] {
            assert!(
                matches!(
                    guard_scrub_target(profile, false),
                    Err(ScrubError::ProductionRefused { .. })
                ),
                "{profile} must be refused"
            );
            assert!(guard_scrub_target(profile, true).is_ok());
        }
        for profile in ["dev", "development", "test"] {
            assert!(guard_scrub_target(profile, false).is_ok());
        }
    }

    #[test]
    fn same_database_compares_host_port_and_name_ignoring_credentials() {
        // Same server + database, different credentials: still the same target.
        assert!(same_database_in(
            "postgres://app:pw@db.example.com:5432/myapp",
            "postgres://readonly:other@db.example.com:5432/myapp",
            &env_of(&[])
        ));
        assert!(!same_database_in(
            "postgres://app:pw@db.example.com:5432/myapp",
            "postgres://app:pw@db.example.com:5432/myapp_staging",
            &env_of(&[])
        ));
        assert!(!same_database_in(
            "postgres://app:pw@db.example.com:5432/myapp",
            "postgres://app:pw@staging.example.com:5432/myapp",
            &env_of(&[])
        ));
        // An unparsable URL never claims a match.
        assert!(!same_database_in("not a url", "not a url", &env_of(&[])));
    }

    fn env_of<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
        move |key| {
            vars.iter()
                .find(|(k, _)| *k == key)
                .map(|(_, v)| (*v).to_owned())
        }
    }

    #[test]
    fn hostless_urls_naming_one_socket_are_the_same_database() {
        let env = env_of(&[]);
        assert!(same_database_in(
            "postgres:///prod?host=/var/run/postgresql",
            "postgres://app:pw@/prod?host=/var/run/postgresql",
            &env
        ));
        assert!(!same_database_in(
            "postgres:///prod?host=/var/run/postgresql",
            "postgres:///prod?host=/tmp",
            &env
        ));
        assert!(!same_database_in(
            "postgres:///prod?host=/tmp",
            "postgres:///staging?host=/tmp",
            &env
        ));
    }

    #[test]
    fn a_hostless_url_resolves_its_host_and_port_like_libpq() {
        let env = env_of(&[("PGHOST", "db.example.com"), ("PGPORT", "6543")]);
        assert!(same_database_in(
            "postgres:///prod",
            "postgres://db.example.com:6543/prod",
            &env
        ));
        assert!(!same_database_in(
            "postgres:///prod",
            "postgres://db.example.com:5432/prod",
            &env
        ));
        assert!(same_database_in(
            "postgres://u@/prod?hostaddr=10.0.0.5&port=5433",
            "postgres://10.0.0.5:5433/prod",
            &env
        ));
    }

    #[test]
    fn two_bare_urls_share_the_default_socket() {
        let env = env_of(&[]);
        assert!(same_database_in(
            "postgres:///prod",
            "postgres:///prod",
            &env
        ));
    }

    #[test]
    fn a_shard_url_of_a_source_profile_is_a_protected_source() {
        let env = env_of(&[]);
        let declared = vec![(
            "prod".to_owned(),
            vec![
                "postgres://app@prod-control/ctl".to_owned(),
                "postgres://app@prod-shard-a/orders".to_owned(),
            ],
        )];
        let targets = vec![
            (
                "control".to_owned(),
                "postgres://app@staging-control/ctl".to_owned(),
            ),
            (
                "shard:a".to_owned(),
                "postgres://app@prod-shard-a:5432/orders".to_owned(),
            ),
        ];
        assert_eq!(
            overwritten_source(&declared, &targets, &env),
            Some(("prod".to_owned(), "orders".to_owned()))
        );
        let clean = vec![(
            "control".to_owned(),
            "postgres://app@staging-control/ctl".to_owned(),
        )];
        assert_eq!(overwritten_source(&declared, &clean, &env), None);
    }

    #[test]
    fn the_destination_profile_is_never_its_own_source() {
        let configured = vec!["prod".to_owned(), "staging".to_owned(), "dev".to_owned()];
        assert_eq!(
            source_candidates(Some("prod"), &configured, "staging"),
            vec!["prod".to_owned()],
            "staging is the destination; dev is safe by definition"
        );
        assert_eq!(
            source_candidates(None, &configured, "staging"),
            vec!["prod".to_owned()]
        );
        assert_eq!(
            source_candidates(Some("prod"), &["prod".to_owned()], "prod"),
            vec!["prod".to_owned()],
            "a manifest that names the destination as the source stays protected"
        );
        assert_eq!(
            source_candidates(None, &["staging".to_owned()], "staging"),
            Vec::<String>::new(),
            "the destination's own overlay names the target, not a source"
        );
    }

    #[test]
    fn only_the_targets_an_artifact_restored_are_scrubbed() {
        let targets = vec![
            ("control".to_owned(), "postgres://h/ctl".to_owned()),
            ("shard:a".to_owned(), "postgres://h/a".to_owned()),
            ("shard:b".to_owned(), "postgres://h/b".to_owned()),
        ];
        let kept = restored_targets(targets.clone(), &["shard:a".to_owned()]);
        assert_eq!(kept, vec![targets[1].clone()]);
        assert!(
            restored_targets(targets, &[]).is_empty(),
            "an artifact that restored nothing scrubs nothing"
        );
    }

    #[test]
    fn encrypted_columns_are_read_from_the_whole_src_tree() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(src.join("billing")).unwrap();
        std::fs::write(
            src.join("models.rs"),
            "#[model] pub struct User { #[id] pub id: i64, #[encrypted] pub ssn: String }",
        )
        .unwrap();
        std::fs::write(
            src.join("billing").join("card.rs"),
            "#[model] pub struct Card { #[id] pub id: i64, #[encrypted] pub pan: String }",
        )
        .unwrap();
        let found = encrypted_columns(dir.path()).unwrap();
        assert!(found["users"].contains_key("ssn"));
        assert!(
            found["cards"].contains_key("pan"),
            "a model outside `src/models` is still found"
        );
    }

    #[test]
    fn registrations_under_cfg_test_are_not_production_registrations() {
        let found = |src: &str| extract_anonymize_tables(src).unwrap();
        let reg = |t: &str| format!("fn f() {{ ModelRegistration::anonymize(\"{t}\"); }}");

        assert!(found(&format!("#[cfg(test)] mod tests {{ {} }}", reg("a"))).is_empty());
        assert!(found(&format!("#[cfg(test)] {}", reg("a"))).is_empty());
        assert!(
            found("fn f() { #[cfg(test)] { ModelRegistration::anonymize(\"a\"); } }").is_empty()
        );
        assert!(
            found("fn f() { #[cfg(test)] (ModelRegistration::anonymize(\"a\"),); }").is_empty()
        );
        assert!(
            found(&format!(
                "#[cfg_attr(not(test), cfg(test))] mod m {{ {} }}",
                reg("a")
            ))
            .is_empty()
        );
        assert!(
            found(&format!(
                "#[cfg_attr(not(test), cfg_attr(all(), cfg(test)))] mod m {{ {} }}",
                reg("a")
            ))
            .is_empty()
        );
        // An unknown predicate may or may not add the `cfg`: keep the item.
        assert_eq!(
            found(&format!(
                "#[cfg_attr(feature = \"x\", cfg(test))] mod m {{ {} }}",
                reg("a")
            )),
            BTreeSet::from(["a".to_owned()])
        );
        assert!(
            found(
                "fn f(x: u8) { match x { #[cfg(test)] 0 => { ModelRegistration::anonymize(\"a\"); } _ => {} } }"
            )
            .is_empty()
        );
        assert!(found(&format!("#[cfg(test)] trait T {{ {} }}", reg("a"))).is_empty());
        assert!(found(&format!("#![cfg(test)]\n{}", reg("a"))).is_empty());
        assert!(
            found(&format!(
                "#[cfg(all(test, feature = \"x\"))] mod t {{ {} }}",
                reg("a")
            ))
            .is_empty()
        );
        assert!(
            found(&format!(
                "struct S; #[cfg(test)] impl S {{ {} }}",
                reg("a").replace("fn f", "fn g")
            ))
            .is_empty()
        );
        // Enabled or unknown cfgs keep their registrations: erring toward the
        // scrub is the safe direction.
        for cfg in [
            "not(test)",
            "any(test, feature = \"x\")",
            "feature = \"x\"",
            "unix",
        ] {
            assert_eq!(
                found(&format!("#[cfg({cfg})] mod m {{ {} }}", reg("a"))),
                BTreeSet::from(["a".to_owned()]),
                "cfg({cfg})"
            );
        }
    }

    #[test]
    fn an_out_of_line_cfg_test_module_file_is_not_scanned() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path();
        std::fs::create_dir_all(src.join("tests")).unwrap();
        std::fs::write(src.join("lib.rs"), "#[cfg(test)] mod tests;\nmod live;\n").unwrap();
        std::fs::write(
            src.join("tests.rs"),
            "mod deep;\nfn f() { ModelRegistration::anonymize(\"fixture\"); }",
        )
        .unwrap();
        std::fs::write(
            src.join("tests").join("deep.rs"),
            "fn f() { ModelRegistration::anonymize(\"deep_fixture\"); }",
        )
        .unwrap();
        std::fs::write(
            src.join("live.rs"),
            "fn f() { ModelRegistration::anonymize(\"users\"); }",
        )
        .unwrap();
        assert_eq!(
            scan_anonymize_tables(src).unwrap(),
            BTreeSet::from(["users".to_owned()])
        );
    }

    #[test]
    fn schema_drift_names_added_and_dropped_tables_and_columns() {
        let pair = |t: &str, c: &str| (t.to_owned(), c.to_owned());
        let before_tables = BTreeSet::from(["users".to_owned(), "old".to_owned()]);
        let before_columns = BTreeSet::from([pair("users", "id"), pair("users", "bio")]);
        let after_tables = BTreeSet::from(["users".to_owned(), "fresh".to_owned()]);
        let after_columns = BTreeSet::from([pair("users", "id"), pair("users", "ssn")]);
        assert_eq!(
            schema_drift(
                (&before_tables, &before_columns),
                (&after_tables, &after_columns)
            ),
            vec![
                "fresh (table added)".to_owned(),
                "old (table dropped)".to_owned(),
                "users.bio (column dropped)".to_owned(),
                "users.ssn (column added)".to_owned(),
            ]
        );
        assert!(
            schema_drift(
                (&before_tables, &before_columns),
                (&before_tables, &before_columns)
            )
            .is_empty()
        );
    }

    #[test]
    fn cfg_predicates_combine_and_unknown_ones_count_as_on() {
        let on = |cfg: &str| {
            crate::schema::parse::production_enabled(
                &syn::parse_str::<syn::ItemFn>(&format!("#[cfg({cfg})] fn f() {{}}"))
                    .unwrap()
                    .attrs,
            )
        };
        for (cfg, kept) in [
            ("test", false),
            ("not(not(test))", false),
            ("all(unix, test)", false),
            ("not(all(test, feature = \"x\"))", true),
            ("any(test, test)", false),
            ("all()", true),
            ("any()", false),
        ] {
            assert_eq!(on(cfg), kept, "cfg({cfg})");
        }
    }

    #[test]
    fn endpoints_decode_the_database_name_and_honour_dbname() {
        let env = env_of(&[]);
        assert!(same_database_in(
            "postgres://h/prod%5Fdb",
            "postgres://h/prod_db",
            &env
        ));
        assert!(same_database_in(
            "postgres://h?dbname=prod",
            "postgres://h/prod",
            &env
        ));
        assert!(same_database_in(
            "postgres://%2Fvar%2Frun%2Fpostgresql/prod",
            "postgres:///prod?host=/var/run/postgresql",
            &env
        ));
        assert!(same_database_in(
            "postgres://a,b/prod",
            "postgres://b/prod",
            &env
        ));
        assert!(same_database_in(
            "postgres://u:p%40ss@h/prod",
            "postgres://h/prod",
            &env
        ));
    }

    #[test]
    fn an_encrypted_name_column_cannot_hold_the_envelope() {
        let mut table = users_table();
        table.columns[3].ty = ColumnType::Opaque {
            pg_type: "name".to_owned(),
        };
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "email", "full_name"]
            "#,
        )
        .unwrap();
        let err = plan_for(
            &[table],
            &config,
            &encrypted_columns_of("users", &["bio"]),
            &no_anonymize(),
        )
        .expect_err("`name` holds 63 bytes");
        assert!(
            matches!(err, ScrubError::EncryptedEnvelopeTooLong { limit: 63, .. }),
            "{err:?}"
        );
    }

    #[test]
    fn an_empty_hostaddr_item_uses_the_host_name() {
        let env = env_of(&[]);
        assert!(same_database_in(
            "host=a,b hostaddr=,10.0.0.5 dbname=app",
            "host=a dbname=app",
            &env
        ));
        assert!(same_database_in(
            "postgres:///app?host=a,b&hostaddr=,10.0.0.5",
            "postgres://a/app",
            &env
        ));
        let pghost = env_of(&[("PGHOST", "a,b")]);
        assert!(same_database_in(
            "hostaddr=,10.0.0.5 dbname=app",
            "host=a dbname=app",
            &pghost
        ));
        assert!(same_database_in(
            "postgres:///app?hostaddr=,10.0.0.5",
            "postgres://a/app",
            &pghost
        ));
        assert!(same_database_in(
            "postgres://a,b/app?hostaddr=,10.0.0.5",
            "postgres://a/app",
            &env
        ));
        assert!(same_database_in(
            "postgres://a:6543/app?host=b,c",
            "postgres://b:6543/app",
            &env
        ));
        assert_eq!(merge_hosts(None, Some("h".into())), Some("h".into()));
        assert_eq!(merge_hosts(Some(",x".into()), None), Some(",x".into()));
    }

    #[test]
    fn empty_keyword_and_environment_values_are_ignored() {
        let env = env_of(&[]);
        assert!(same_database_in(
            "host=prod hostaddr=10.0.0.5 hostaddr='' dbname=app",
            "host=prod dbname=app",
            &env
        ));
        let me = crate::pg::current_os_user();
        assert!(same_database_in(
            "host=prod",
            &format!("host=prod user={me} dbname={me}"),
            &env
        ));
        assert!(same_database_in(
            "postgres://prod",
            &format!("postgres://{me}@prod/{me}"),
            &env
        ));
        let pgport = env_of(&[("PGPORT", "6543")]);
        assert!(same_database_in(
            "host=prod port='' dbname=app",
            "host=prod port=5432 dbname=app",
            &pgport
        ));
        assert!(same_database_in(
            "host=prod dbname=app",
            "host=prod port=6543 dbname=app",
            &pgport
        ));
        let empty_db = env_of(&[("PGDATABASE", "")]);
        assert!(same_database_in(
            "host=prod user=app",
            "host=prod dbname=app",
            &empty_db
        ));
    }

    #[test]
    fn libpq_pairs_a_port_list_with_the_host_list() {
        let env = env_of(&[]);
        assert!(same_database_in(
            "postgres:///d?host=a,b&port=5432,6543",
            "postgres://b:6543/d",
            &env
        ));
        assert!(!same_database_in(
            "postgres:///d?host=a,b&port=5432,6543",
            "postgres://b:5432/d",
            &env
        ));
        assert!(same_database_in(
            "postgresql://a:5432,b:6543/app",
            "postgres://b:6543/app",
            &env
        ));
        assert!(!same_database_in(
            "postgresql://a:5432,b:6543/app",
            "postgres://b:5432/app",
            &env
        ));
        assert!(same_database_in(
            "postgres:///app?host=prod.example&hostaddr=10.0.0.5",
            "postgres://10.0.0.5/app",
            &env
        ));
        assert!(same_database_in(
            "host=prod.example hostaddr=10.0.0.5 dbname=app",
            "postgres://10.0.0.5/app",
            &env
        ));
        assert!(same_database_in(
            "host=prod user=app",
            "postgres://app@prod/app",
            &env
        ));
        assert!(same_database_in(
            "postgres://app@prod",
            "host=prod dbname=app",
            &env
        ));
        assert!(same_database_in(
            "postgres://prod.example/app?hostaddr=10.0.0.5",
            "postgres://10.0.0.5/app",
            &env
        ));
        assert!(same_database_in(
            "postgres:///app?hostaddr=10.0.0.1&hostaddr=10.0.0.5",
            "postgres://10.0.0.5/app",
            &env
        ));
        assert!(same_database_in(
            "host=prod user=app dbname=''",
            "host=prod user=app dbname=app",
            &env
        ));
        assert!(same_database_in(
            "postgres:///app",
            "postgresql://%2Fvar%2Frun%2Fpostgresql/app",
            &env
        ));
        assert!(!same_database_in(
            "postgres:///app",
            "postgres://db.example/app",
            &env
        ));
        assert!(same_database_in(
            "postgres://alice@prod/?user=app",
            "postgres://app@prod/app",
            &env
        ));
        assert!(same_database_in(
            "postgres://db/?dbname=prod+db",
            "postgres://db/prod+db",
            &env
        ));
        assert!(same_database_in(
            "postgres://db:5432/app?port=6543",
            "postgres://db:6543/app",
            &env
        ));
        assert!(same_database_in(
            "postgres://prod.example/app",
            "postgres://10.0.0.5/app",
            &env_of(&[("PGHOSTADDR", "10.0.0.5")])
        ));
        assert!(same_database_in(
            "postgres:///app?host=a,b&port=,6543",
            "postgres://a:5432/app",
            &env
        ));
        assert!(same_database_in(
            "host=a,b port=,6543 dbname=app",
            "postgres://b:6543/app",
            &env
        ));
    }

    #[test]
    fn keyword_strings_and_ipv6_endpoints_compare_like_urls() {
        let env = env_of(&[]);
        assert!(same_database_in(
            "host=prod dbname=app password=https://issuer",
            "postgres://prod/app",
            &env
        ));
        assert!(same_database_in(
            "postgres://[::1]:5432/app",
            "postgres:///app?host=::1",
            &env
        ));
        assert!(same_database_in(
            "host=prod port=5433 dbname=app",
            "postgres://prod:5433/app",
            &env
        ));
        assert!(same_database_in(
            "host='a' dbname='app' user=u",
            "postgres://a/app",
            &env
        ));
        assert!(same_database_in(
            "host=/tmp/postgres\\ socket dbname=app",
            "postgres:///app?host=/tmp/postgres%20socket",
            &env
        ));
    }

    #[test]
    fn the_envelope_length_is_exact_for_both_shapes() {
        assert_eq!(envelope_len(Strategy::Redact), 148);
        assert_eq!(envelope_len(Strategy::Email), 168);
    }

    #[test]
    fn a_bare_artifact_with_no_manifest_still_gets_the_source_guard() {
        // `autumn-prod.toml` declares the very database the scrub would write.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[database]\nprimary_url = \"postgres://app:pw@db.example.com:5432/myapp\"\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("autumn-dev.toml"), "[database]\n").unwrap();

        assert_eq!(
            profiles_with_config(dir.path()),
            vec!["dev".to_owned(), "prod".to_owned()],
            "every profile overlay is a candidate, not just the one an artifact names"
        );
        // A bare `.dump` carries no manifest, so provenance is `None` — which
        // must not read as permission to continue.
        assert!(
            !profiles_with_config(dir.path()).is_empty(),
            "the guard has candidates to check even with unknown provenance"
        );
    }

    #[test]
    fn the_source_guard_waiver_is_not_force() {
        // `--force` is mandatory in the documented staging drill, so a guard it
        // waived would be inert in exactly the workflow it exists for.
        let targets = vec![(
            "control".to_owned(),
            "postgres://app:pw@db.example.com:5432/myapp".to_owned(),
        )];
        let empty = tempfile::tempdir().unwrap();
        assert!(
            guard_configured_source(Some("prod"), "staging", empty.path(), &targets, false).is_ok(),
            "no config overlay means nothing to compare against"
        );
        assert!(
            guard_configured_source(Some("prod"), "staging", empty.path(), &targets, true).is_ok(),
            "--allow-source-overwrite is the waiver"
        );
    }

    fn overlay(dir: &Path, profile: &str, body: &str) {
        std::fs::write(dir.join(format!("autumn-{profile}.toml")), body).unwrap();
    }

    fn control_target(url: &str) -> Vec<(String, String)> {
        vec![("control".to_owned(), url.to_owned())]
    }

    #[test]
    fn the_destination_profile_is_not_a_protected_source() {
        // Issue #2366: the drill scrubs `staging` while `autumn-staging.toml` exists.
        let dir = tempfile::tempdir().unwrap();
        let url = "postgres://app:pw@stg.example.com:5432/myapp";
        overlay(
            dir.path(),
            "staging",
            &format!("[database]\nprimary_url = \"{url}\"\n"),
        );
        assert!(
            guard_configured_source(
                Some("prod"),
                "staging",
                dir.path(),
                &control_target(url),
                false
            )
            .is_ok()
        );
        // The same overlay still guards when it is not the destination.
        assert!(
            guard_configured_source(
                Some("prod"),
                "other",
                dir.path(),
                &control_target(url),
                false
            )
            .is_err()
        );
    }

    #[test]
    fn a_protected_shard_url_is_compared_too() {
        // Issue #2366: a shard of a protected profile is a protected database.
        let dir = tempfile::tempdir().unwrap();
        overlay(
            dir.path(),
            "prod",
            "[database]\nprimary_url = \"postgres://a@prod.example.com/ctl\"\n\n\
             [[database.shards]]\nname = \"s1\"\n\
             primary_url = \"postgres://a@prod.example.com/shard1\"\n",
        );
        let targets = vec![
            (
                "control".to_owned(),
                "postgres://a@stg.example.com/ctl".to_owned(),
            ),
            (
                "s1".to_owned(),
                "postgres://a@prod.example.com/shard1".to_owned(),
            ),
        ];
        assert!(
            guard_configured_source(Some("prod"), "staging", dir.path(), &targets, false).is_err()
        );
    }

    #[test]
    fn hostless_urls_name_the_same_database() {
        // Issue #2366: a URL without a host takes its host from libpq settings.
        assert!(same_database_in(
            "postgres:///prod?user=app&host=/var/run/postgresql",
            "postgres:///prod?host=/var/run/postgresql",
            &|_| None
        ));
        assert!(!same_database_in(
            "postgres:///prod?host=/var/run/postgresql",
            "postgres:///prod?host=/tmp",
            &|_| None
        ));
        // Bare form resolves through `PGHOST`.
        assert!(same_database_in(
            "postgres:///prod",
            "postgres://h.example.com/prod",
            &|k| (k == "PGHOST").then(|| "h.example.com".to_owned())
        ));
        assert!(!same_database_in(
            "postgres:///prod",
            "postgres://h.example.com/prod",
            &|_| None
        ));
        // A different database on the same socket stays different.
        assert!(!same_database_in(
            "postgres:///prod?host=/tmp",
            "postgres:///other?host=/tmp",
            &|_| None
        ));
        // `PGHOSTADDR` picks the server whatever name the URL gives.
        let addr = |k: &str| (k == "PGHOSTADDR").then(|| "10.0.0.1".to_owned());
        assert!(same_database_in(
            "postgres://prod.example/app",
            "postgres://staging.example/app",
            &addr
        ));
        // An inline `hostaddr` beats the environment.
        assert!(!same_database_in(
            "postgres://a/app?hostaddr=10.0.0.2",
            "postgres://b/app",
            &addr
        ));
        // An explicit empty `host=` means the default socket, not `PGHOST`.
        let pghost = |k: &str| (k == "PGHOST").then(|| "h.example.com".to_owned());
        assert!(!same_database_in(
            "postgres:///app?host=",
            "postgres://h.example.com/app",
            &pghost
        ));
        assert!(same_database_in(
            "postgres:///app?host=",
            "postgres:///app?host=",
            &pghost
        ));
        // Parameter names are percent-decoded, as the connection parser does.
        assert!(same_database_in(
            "postgres:///app?ho%73t=prod.example.com",
            "postgres://prod.example.com/app",
            &|_| None
        ));
        // An empty `dbname` defaults to `PGDATABASE`, then to the user name.
        assert!(same_database_in(
            "postgres://app@prod/app?dbname=",
            "postgres://app@prod/app",
            &|_| None
        ));
        assert!(same_database_in(
            "postgres://prod/x?dbname=",
            "postgres://prod/db1",
            &|k| (k == "PGDATABASE").then(|| "db1".to_owned())
        ));
        // The keyword form `host=... dbname=...` names a database as well.
        assert!(same_database_in(
            "host=prod.example.com dbname=app",
            "postgres://prod.example.com/app",
            &|_| None
        ));
        assert!(same_database_in(
            "host=prod.example.com port=6543 dbname='app'",
            "postgres://prod.example.com:6543/app",
            &|_| None
        ));
        assert!(same_database_in(
            "host=prod.example.com dbname=app user=a",
            "host=prod.example.com dbname=app user=b",
            &|_| None
        ));
        assert!(!same_database_in(
            "host=prod.example.com dbname=app",
            "postgres://prod.example.com/other",
            &|_| None
        ));
        // A non-Postgres scheme never names a Postgres database.
        assert!(!same_database_in(
            "sqlite:///app",
            "postgres:///app",
            &|_| None
        ));
    }

    #[test]
    fn libpq_defaults_and_full_paths_name_the_database() {
        // An omitted port defaults to `PGPORT`.
        assert!(same_database_in(
            "postgres://prod.example/app",
            "postgres://prod.example:6543/app",
            &|k| (k == "PGPORT").then(|| "6543".to_owned())
        ));
        // The effective user names the database: `user` parameter, URL user, then
        // `PGUSER`.
        let pguser = |k: &str| (k == "PGUSER").then(|| "alice".to_owned());
        assert!(same_database_in(
            "postgres://prod.example/?dbname=&user=bob",
            "postgres://prod.example/bob",
            &pguser
        ));
        assert!(same_database_in(
            "postgres://carol@prod.example/?dbname=",
            "postgres://prod.example/carol",
            &pguser
        ));
        assert!(same_database_in(
            "postgres://prod.example/?dbname=",
            "postgres://prod.example/alice",
            &pguser
        ));
        // With no `dbname`, `PGDATABASE` or user, the OS login names the database.
        assert!(same_database_in(
            "postgres://prod.example/?dbname=",
            &format!("postgres://prod.example/{}", crate::pg::current_os_user()),
            &|_| None
        ));
        // A database name may hold a slash: the whole path is the name.
        assert!(same_database_in(
            "postgres://prod/db/name",
            "postgres://prod/db%2Fname",
            &|_| None
        ));
        assert!(!same_database_in(
            "postgres://prod/db/name",
            "postgres://prod/db",
            &|_| None
        ));
        // Only the path delimiter is stripped: `//app` names the database `/app`.
        assert!(same_database_in(
            "postgres://prod//app",
            "postgres://prod/%2Fapp",
            &|_| None
        ));
        // IP literals compare by address, not by spelling.
        assert!(same_database_in(
            "postgres:///app?hostaddr=0:0:0:0:0:0:0:1",
            "postgres://[::1]/app",
            &|_| None
        ));
        // The default socket directory is unknown, so an empty host may be any
        // socket path.
        assert!(same_database_in(
            "postgres:///app?host=",
            "postgres:///app?host=/var/run/postgresql",
            &|_| None
        ));
        assert!(same_database_in(
            "postgres:///app?host=/var/run/postgresql",
            "postgres:///app?host=",
            &|_| None
        ));
        assert!(!same_database_in(
            "postgres:///app?host=",
            "postgres://h.example.com/app",
            &|_| None
        ));
        // One SQLite file reached by two spellings is a source overwrite.
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("app.db");
        std::fs::write(&file, b"").unwrap();
        let url = format!("sqlite://{}", file.display());
        let detour = format!(
            "sqlite://{}/../{}/app.db",
            dir.path().display(),
            dir.path().file_name().unwrap().to_string_lossy()
        );
        assert!(same_database_in(&url, &detour, &|_| None));
        assert!(!same_database_in(&url, "sqlite:///other/app.db", &|_| None));
    }

    #[test]
    fn the_artifact_source_profile_is_protected_even_as_destination() {
        let dir = tempfile::tempdir().unwrap();
        let url = "postgres://a@prod.example.com/app";
        overlay(
            dir.path(),
            "prod",
            &format!("[database]\nprimary_url = \"{url}\"\n"),
        );
        assert!(
            guard_configured_source(
                Some("prod"),
                "prod",
                dir.path(),
                &control_target(url),
                false
            )
            .is_err()
        );
    }

    #[test]
    fn a_profile_alias_still_names_the_destination() {
        let dir = tempfile::tempdir().unwrap();
        let url = "postgres://a@prod.example.com/app";
        overlay(
            dir.path(),
            "prod",
            &format!("[database]\nprimary_url = \"{url}\"\n"),
        );
        assert!(
            guard_configured_source(None, "production", dir.path(), &control_target(url), false)
                .is_ok()
        );
    }

    #[test]
    fn a_malformed_shard_entry_refuses_instead_of_skipping_the_check() {
        let dir = tempfile::tempdir().unwrap();
        overlay(
            dir.path(),
            "prod",
            "[database]\nprimary_url = \"postgres://a@prod.example.com/ctl\"\n\n\
             [[database.shards]]\nprimary_url = \"postgres://a@prod.example.com/s1\"\n",
        );
        let targets = control_target("postgres://a@stg.example.com/ctl");
        assert!(matches!(
            guard_configured_source(Some("prod"), "staging", dir.path(), &targets, false),
            Err(ScrubError::Config { .. })
        ));
    }

    #[test]
    fn libpq_query_overrides_and_encoding_are_normalised() {
        let same = |a, b| same_database_in(a, b, &|_| None);
        assert!(same("postgres://h/ctl", "postgres://h/stg?dbname=ctl"));
        assert!(same("postgres://h?dbname=prod", "postgres://h/prod"));
        assert!(same(
            "postgres://h:6432/prod",
            "postgres://h/prod?port=6432"
        ));
        assert!(same("postgres://h/pr%6Fd", "postgres://h/prod"));
        assert!(same(
            "postgres://prod.example.com./app",
            "postgres://prod.example.com/app"
        ));
        assert!(same(
            "postgres://%2Fvar%2Frun%2Fpostgresql/prod",
            "postgres:///prod?host=/var/run/postgresql"
        ));
        // libpq connects to `hostaddr` even when the URL names a host.
        assert!(same(
            "postgres://prod.example.com/prod?hostaddr=10.0.0.1",
            "postgres://10.0.0.1/prod"
        ));
        // Query parameters override the authority. The last repeat wins.
        assert!(same(
            "postgres://placeholder/prod?host=a.example.com",
            "postgres://a.example.com/prod"
        ));
        assert!(same(
            "postgres://x/db?host=stg&host=prod",
            "postgres://prod/db"
        ));
        assert!(same("postgres://h:1/db?port=6432", "postgres://h:6432/db"));
        // Socket paths are case-sensitive. DNS names are not.
        assert!(!same(
            "postgres:///db?host=/run/PostgreSQL",
            "postgres:///db?host=/run/postgresql"
        ));
        assert!(same(
            "postgres://Prod.Example.com/db",
            "postgres://prod.example.com/db"
        ));
        // `+` is a literal in libpq query values. An empty final value resets.
        assert!(same(
            "postgres://h/db?dbname=foo+bar",
            "postgres://h/foo+bar"
        ));
        assert!(same(
            "postgres://prod:6543/app?port=",
            "postgres://prod:5432/app"
        ));
        assert!(same(
            "postgres://h/db?port=6543&port=5432",
            "postgres://h/db"
        ));
        // An IPv6 address matches with or without brackets.
        assert!(same("postgres:///app?hostaddr=::1", "postgres://[::1]/app"));
        // A URL that does not parse still matches itself.
        assert!(same(
            "postgres://h1:1,h2:2/prod",
            "postgres://h1:1,h2:2/prod"
        ));
        assert!(!same("postgres://h/prod", "postgres://h/other"));
    }

    #[test]
    fn errors_never_leak_credentials() {
        let err = ScrubError::ProductionRefused {
            profile: "prod".to_owned(),
        };
        let rendered = err.to_string();
        assert!(rendered.contains("prod"));
        assert!(!rendered.contains("postgres://"));
        assert!(!rendered.contains("hunter2"));
    }

    // ── Report ──────────────────────────────────────────────────────────────

    #[test]
    fn check_report_prints_a_paste_ready_stanza_for_unclassified_columns() {
        let stanza = suggested_config_stanza(&[
            "users.email".to_owned(),
            "users.full_name".to_owned(),
            "posts.body".to_owned(),
        ]);
        assert!(stanza.contains("[tables.users.pii]"), "{stanza}");
        assert!(stanza.contains("email = \"auto\""), "{stanza}");
        assert!(stanza.contains("[tables.posts.pii]"), "{stanza}");
        assert!(stanza.contains("body = \"auto\""), "{stanza}");
    }

    #[test]
    fn per_column_errors_are_reported_with_their_table() {
        let mut t = Table::new("orders", Backend::Postgres);
        t.primary_key = vec!["id".to_owned()];
        t.columns = vec![
            pk_col("id"),
            Column::new(
                "status",
                ColumnType::Enum {
                    variants: vec!["draft".to_owned(), "paid".to_owned()],
                },
            ),
        ];
        let err = plan_for(
            &[t],
            &parse_config_str(
                r#"
                [defaults]
                safe_columns = ["id"]
                [tables.orders.pii]
                status = "auto"
                "#,
            )
            .unwrap(),
            &empty_encrypted(),
            &no_anonymize(),
        )
        .expect_err("a closed-set column has no generic fake");
        assert!(
            matches!(err, ScrubError::NoAutoStrategy { ref column, .. } if column == "orders.status"),
            "the error must name the table too: {err:?}"
        );
    }

    #[test]
    fn a_strategy_that_cannot_produce_the_column_type_is_refused() {
        let err = replacement_expr(Strategy::Uuid, &text_col("note"), "TOK", false)
            .expect_err("a uuid cannot be written into a text column");
        assert!(
            matches!(err, ScrubError::StrategyTypeMismatch { .. }),
            "{err:?}"
        );
        assert!(
            matches!(
                replacement_expr(Strategy::Zero, &text_col("note"), "TOK", false),
                Err(ScrubError::StrategyTypeMismatch { .. })
            ),
            "zero is meaningless for a text column"
        );
        assert!(
            matches!(
                replacement_expr(
                    Strategy::Epoch,
                    &Column::new("n", ColumnType::Int64),
                    "TOK",
                    false
                ),
                Err(ScrubError::StrategyTypeMismatch { .. })
            ),
            "epoch is meaningless for an integer column"
        );
    }

    #[test]
    fn typed_strategies_render_their_casts() {
        assert_eq!(
            replacement_expr(
                Strategy::Uuid,
                &Column::new("t", ColumnType::Uuid),
                "TOK",
                false
            )
            .unwrap(),
            "(substr(TOK, 1, 32))::uuid"
        );
        assert_eq!(
            replacement_expr(
                Strategy::Bytes,
                &Column::new("b", ColumnType::Bytes),
                "TOK",
                false
            )
            .unwrap(),
            "decode(TOK, 'hex')"
        );
        assert_eq!(
            replacement_expr(
                Strategy::Zero,
                &Column::new("ok", ColumnType::Bool),
                "TOK",
                false
            )
            .unwrap(),
            "false"
        );
        assert_eq!(
            replacement_expr(
                Strategy::Epoch,
                &Column::new("at", ColumnType::TimestampTz),
                "TOK",
                false
            )
            .unwrap(),
            "'1970-01-01 00:00:00+00'::timestamptz"
        );
        assert_eq!(
            replacement_expr(Strategy::Null, &text_col("bio"), "TOK", false).unwrap(),
            "NULL"
        );
    }

    #[test]
    fn phone_produces_digits_and_refuses_a_column_that_cannot_hold_them() {
        let expr = replacement_expr(Strategy::Phone, &text_col("phone"), "TOK", false).unwrap();
        assert!(
            expr.contains("translate("),
            "must map hex onto digits: {expr}"
        );
        assert!(expr.starts_with("'+1555'"), "{expr}");

        let narrow = Column::new(
            "phone",
            ColumnType::Opaque {
                pg_type: "varchar(8)".to_owned(),
            },
        );
        assert!(matches!(
            replacement_expr(Strategy::Phone, &narrow, "TOK", false),
            Err(ScrubError::ColumnTooNarrow { .. })
        ));
    }

    #[test]
    fn a_partial_unique_index_still_constrains_the_rows_it_covers() {
        let mut t = users_table();
        t.columns[1].unique = false;
        let mut index = Index::new("idx_users_email", vec!["email".to_owned()], true);
        index.is_partial = true;
        t.indexes = vec![index];
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "json"
            "#,
        )
        .unwrap();
        // A partial unique index does not satisfy a model `#[unique]` — but it
        // absolutely does abort an UPDATE that writes one constant into every
        // row its predicate matches, which is the only question a writer asks.
        let err = plan_for(&[t], &config, &empty_encrypted(), &no_anonymize())
            .expect_err("a partial unique index still constrains the rows it covers");
        assert!(
            matches!(err, ScrubError::NonUniqueStrategy { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn a_composite_unique_index_constrains_each_of_its_members() {
        let mut t = Table::new("cards", Backend::Postgres);
        t.primary_key = vec!["id".to_owned()];
        t.columns = vec![
            pk_col("id"),
            Column::new("user_id", ColumnType::Int64),
            Column::new("last4", ColumnType::Int32),
        ];
        let mut config = ScrubConfig::default();
        config.defaults.safe_columns = vec!["id".to_owned(), "user_id".to_owned()];
        config.tables.insert(
            "cards".to_owned(),
            TableRule {
                safe: Vec::new(),
                pii: BTreeMap::from([("last4".to_owned(), Strategy::Zero)]),
                encrypted: BTreeMap::new(),
            },
        );
        let facts = DatabaseFacts {
            unique_columns: BTreeSet::from([
                ("cards".to_owned(), "user_id".to_owned()),
                ("cards".to_owned(), "last4".to_owned()),
            ]),
            ..DatabaseFacts::default()
        };
        let err = plan_with_facts(&[t], &config, &empty_encrypted(), &no_anonymize(), &facts)
            .expect_err("a constant in one member of a composite unique key collides");
        assert!(
            matches!(err, ScrubError::NonUniqueStrategy { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn a_missing_config_file_is_not_an_error_but_an_explicit_one_is() {
        let dir = tempfile::tempdir().unwrap();
        let absent = dir.path().join("scrub.toml");
        // The conventional path may simply not exist yet.
        assert_eq!(
            load_config_at(None, &absent).unwrap(),
            ScrubConfig::default()
        );
        // A path the developer named explicitly must not be silently ignored.
        assert!(matches!(
            load_config_at(Some(&absent), &absent),
            Err(ScrubError::Config { .. })
        ));
    }

    // ── Framework-owned tables ──────────────────────────────────────────────

    #[test]
    fn purge_only_accepts_framework_owned_tables() {
        let config = parse_config_str(
            r#"
            [framework]
            purge = ["autumn_jobs", "users"]
            "#,
        )
        .unwrap();
        let err = check_purge_list(&config)
            .expect_err("emptying a user table must never hide behind `purge`");
        assert!(
            matches!(err, ScrubError::PurgeNotFrameworkTable { ref tables } if tables == &vec!["users".to_owned()]),
            "got {err:?}"
        );

        let ok = parse_config_str(
            r#"
            [framework]
            purge = ["autumn_jobs", "_autumn_ledger_revisions", "_autumn_ledger_high_water"]
            "#,
        )
        .unwrap();
        assert!(check_purge_list(&ok).is_ok());
    }

    #[test]
    fn purging_one_ledger_table_without_the_other_is_refused() {
        // #2323: a high-water mark outlives the revisions it names on purpose,
        // so a staging copy holding one without the other has `ledger_verify`
        // accusing every ledgered record on a database nobody tampered with.
        for (listed, missing) in [
            ("_autumn_ledger_revisions", "_autumn_ledger_high_water"),
            ("_autumn_ledger_high_water", "_autumn_ledger_revisions"),
        ] {
            let config = parse_config_str(&format!(
                "[framework]\npurge = [\"autumn_jobs\", \"{listed}\"]\n"
            ))
            .unwrap();
            let err = check_purge_list(&config)
                .expect_err("emptying one ledger table alone must be refused");
            assert!(
                matches!(
                    err,
                    ScrubError::PurgeLedgerTablesUnpaired {
                        listed: ref got_listed,
                        missing: ref got_missing,
                    } if got_listed == listed && got_missing == missing
                ),
                "got {err:?}"
            );
            assert!(err.to_string().contains(missing), "{err}");
        }

        // Both, or neither, is fine.
        for purge in [
            r#"["autumn_jobs"]"#,
            r#"["_autumn_ledger_revisions", "_autumn_ledger_high_water"]"#,
        ] {
            let ok = parse_config_str(&format!("[framework]\npurge = {purge}\n")).unwrap();
            assert!(check_purge_list(&ok).is_ok(), "{purge}");
        }
    }

    #[test]
    fn purge_statements_cover_only_the_opted_in_tables_that_exist() {
        let config = parse_config_str(
            r#"
            [framework]
            purge = ["autumn_jobs", "autumn_sync_rows"]
            "#,
        )
        .unwrap();
        // `autumn_sync_rows` is opted in but absent; `autumn_job_tracking` is
        // present but not opted in.
        let present = vec!["autumn_job_tracking".to_owned(), "autumn_jobs".to_owned()];
        let statements = purge_statements(&present, &config);
        assert_eq!(
            statements,
            vec![(
                "autumn_jobs".to_owned(),
                r#"DELETE FROM "public"."autumn_jobs""#.to_owned()
            )]
        );
    }

    #[test]
    fn no_purge_declaration_empties_nothing() {
        let present = vec!["autumn_jobs".to_owned()];
        assert!(purge_statements(&present, &ScrubConfig::default()).is_empty());
    }

    #[test]
    fn the_probe_covers_the_built_in_list_plus_every_purge_entry() {
        let config = parse_config_str(
            r#"
            [framework]
            purge = ["autumn_custom_outbox"]
            "#,
        )
        .unwrap();
        let probed = probe_table_names(&config);
        assert!(
            probed.contains("autumn_custom_outbox"),
            "a purge entry outside the built-in list must still be probed, or it \
             would be accepted and then silently do nothing"
        );
        for table in FRAMEWORK_PAYLOAD_TABLES {
            assert!(probed.contains(*table));
        }
    }

    #[test]
    fn framework_payload_tables_are_all_framework_owned() {
        for table in FRAMEWORK_PAYLOAD_TABLES {
            assert!(
                is_framework_table(table),
                "{table} must be filtered out of the classified universe"
            );
        }
        // The unprefixed set must stay in lock-step with the introspection
        // filter, or a table nothing classifies would also be un-purgeable.
        for table in UNPREFIXED_FRAMEWORK_TABLES {
            assert!(is_framework_table(table));
        }
        assert!(
            FRAMEWORK_PAYLOAD_TABLES.contains(&"api_tokens"),
            "production API tokens in a staging copy are a live credential leak"
        );
        // Schema bookkeeping must never be offered for purging.
        assert!(!FRAMEWORK_PAYLOAD_TABLES.contains(&"autumn_migration_checksums"));
        assert!(!FRAMEWORK_PAYLOAD_TABLES.contains(&"_autumn_shard_map"));
    }

    #[test]
    fn index_backed_uniqueness_is_recognized() {
        // A single-column unique INDEX (not a column flag) still forbids a
        // constant replacement.
        let mut t = users_table();
        t.columns[1].unique = false;
        t.indexes = vec![Index::new(
            "idx_users_email",
            vec!["email".to_owned()],
            true,
        )];
        let config = parse_config_str(
            r#"
            [defaults]
            safe_columns = ["id", "created_at", "full_name", "bio"]
            [tables.users.pii]
            email = "json"
            "#,
        )
        .unwrap();
        let err = plan_for(&[t], &config, &empty_encrypted(), &no_anonymize())
            .expect_err("a unique index must be honored like a unique column");
        assert!(
            matches!(err, ScrubError::NonUniqueStrategy { .. }),
            "{err:?}"
        );
    }
}