qail 0.27.10

Schema-first database toolkit - migrations, diff, lint, and query generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
//! Main apply entry point — migrate_apply.

use super::backfill::{enforce_contract_safety, parse_backfill_spec, run_chunked_backfill};
use super::codegen::{commands_to_sql, parse_qail_to_commands_strict};
use super::discovery::{discover_migrations, phase_rank};
use super::types::{ApplyPhase, BackfillRun, MigrateDirection, MigrationFile, MigrationPhase};
use crate::backup::analyze_impact;
use crate::colors::*;
use crate::migrations::risk::preflight_lock_risk;
use crate::migrations::{
    EnforcementMode, MigrationPolicy, MigrationReceipt, ReceiptSignatureStatus,
    ReceiptValidationMode, StoredMigrationReceipt, acquire_migration_lock, ensure_migration_table,
    load_migration_policy, maybe_failpoint, now_epoch_ms, runtime_actor, runtime_git_sha,
    stable_cmds_checksum, verify_stored_receipt_signature, write_migration_receipt,
};
use crate::shadow::has_verified_shadow_receipt_with_driver;
use crate::util::parse_pg_url;
use anyhow::{Context, Result, anyhow, bail};
use qail_core::ast::{Action, Expr, JoinKind};
use qail_core::prelude::Qail;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;

#[derive(Clone, Copy)]
pub struct MigrateApplyOptions<'a> {
    pub direction: MigrateDirection,
    pub phase_filter: ApplyPhase,
    pub codebase: Option<&'a str>,
    pub allow_contract_with_references: bool,
    pub allow_destructive: bool,
    pub allow_no_shadow_receipt: bool,
    pub allow_lock_risk: bool,
    pub adopt_existing: bool,
    pub backfill_chunk_size: usize,
    pub wait_for_lock: bool,
    pub lock_timeout_secs: Option<u64>,
}

/// Apply all pending migrations from the migrations/ folder.
///
/// Tracks applied migrations in `_qail_migrations` table so re-running
/// is safe (idempotent). Skips migrations that have already been applied.
pub async fn migrate_apply(url: &str, options: MigrateApplyOptions<'_>) -> Result<()> {
    let MigrateApplyOptions {
        direction,
        phase_filter,
        codebase,
        allow_contract_with_references,
        allow_destructive,
        allow_no_shadow_receipt,
        allow_lock_risk,
        adopt_existing,
        backfill_chunk_size,
        wait_for_lock,
        lock_timeout_secs,
    } = options;

    let migrations_dir = crate::migrations::resolve_deltas_dir(false)?;
    let policy = load_migration_policy()?;

    if matches!(direction, MigrateDirection::Down) && !matches!(phase_filter, ApplyPhase::All) {
        bail!("--phase is only supported for --direction up");
    }

    let discovered = discover_migrations(&migrations_dir, direction)?;
    if matches!(direction, MigrateDirection::Up) {
        let discovered_down = discover_migrations(&migrations_dir, MigrateDirection::Down)?;
        ensure_up_down_pairing(&discovered, &discovered_down)?;
    }
    let all_discovered = discovered.clone();
    let migrations: Vec<MigrationFile> = discovered
        .into_iter()
        .filter(|m| {
            if matches!(direction, MigrateDirection::Down) {
                return true;
            }
            phase_filter.allows(m.phase)
        })
        .collect();

    if migrations.is_empty() {
        let suffix = match direction {
            MigrateDirection::Up => "up.qail",
            MigrateDirection::Down => "down.qail",
        };
        println!(
            "{} No {} migrations found for phase '{}'",
            "!".yellow(),
            suffix,
            phase_filter
        );
        return Ok(());
    }

    println!(
        "{} Found {} migration file(s) (phase: {})\n",
        "".cyan(),
        migrations.len(),
        phase_filter.to_string().yellow(),
    );

    // Connect to database
    let (host, port, user, password, database) = parse_pg_url(url)?;
    let mut pg = if let Some(password) = password {
        qail_pg::PgDriver::connect_with_password(&host, port, &user, &database, &password).await?
    } else {
        qail_pg::PgDriver::connect(&host, port, &user, &database).await?
    };

    println!("{} Connected to {}", "".green(), database.cyan());

    // Bootstrap migration tracking table
    ensure_migration_table(&mut pg)
        .await
        .context("Failed to create _qail_migrations table")?;
    acquire_migration_lock(
        &mut pg,
        "migrate apply",
        wait_for_lock,
        lock_timeout_secs,
        Some(database.as_str()),
    )
    .await?;
    let enforce_shadow_receipt = if matches!(direction, MigrateDirection::Up) {
        resolve_apply_shadow_receipt_policy(&policy, allow_no_shadow_receipt)?
    } else {
        false
    };

    // Query already-applied migration versions + receipt metadata.
    let status_cmd = Qail::get("_qail_migrations").columns(vec![
        "version",
        "checksum",
        "name",
        "sql_up",
        "git_sha",
        "qail_version",
        "actor",
        "started_at_ms",
        "finished_at_ms",
        "duration_ms",
        "affected_rows_est",
        "risk_summary",
        "shadow_checksum",
        "receipt_sig",
    ]);

    let (mut applied_migrations, applied_receipts): (
        HashMap<String, String>,
        HashMap<String, StoredMigrationReceipt>,
    ) = match pg.query_ast(&status_cmd).await {
        Ok(result) => {
            let mut checksums = HashMap::new();
            let mut receipts = HashMap::new();
            for row in &result.rows {
                let Some(version) = row.first().and_then(|v| v.as_ref()).cloned() else {
                    continue;
                };

                let checksum_opt = row.get(1).and_then(|v| v.as_ref()).cloned();
                checksums.insert(version.clone(), checksum_opt.clone().unwrap_or_default());
                receipts.insert(
                    version.clone(),
                    StoredMigrationReceipt {
                        version,
                        checksum: checksum_opt,
                        name: row.get(2).and_then(|v| v.as_ref()).cloned(),
                        sql_up: row.get(3).and_then(|v| v.as_ref()).cloned(),
                        git_sha: row.get(4).and_then(|v| v.as_ref()).cloned(),
                        qail_version: row.get(5).and_then(|v| v.as_ref()).cloned(),
                        actor: row.get(6).and_then(|v| v.as_ref()).cloned(),
                        started_at_ms: parse_i64_field(row.get(7).and_then(|v| v.as_ref())),
                        finished_at_ms: parse_i64_field(row.get(8).and_then(|v| v.as_ref())),
                        duration_ms: parse_i64_field(row.get(9).and_then(|v| v.as_ref())),
                        affected_rows_est: parse_i64_field(row.get(10).and_then(|v| v.as_ref())),
                        risk_summary: row.get(11).and_then(|v| v.as_ref()).cloned(),
                        shadow_checksum: row.get(12).and_then(|v| v.as_ref()).cloned(),
                        receipt_sig: row.get(13).and_then(|v| v.as_ref()).cloned(),
                    },
                );
            }
            (checksums, receipts)
        }
        Err(e) => {
            return Err(anyhow!(
                "Failed to query applied migrations from _qail_migrations: {}",
                e
            ));
        }
    };

    if matches!(direction, MigrateDirection::Up) {
        validate_receipts_against_local(
            &all_discovered,
            &applied_migrations,
            &applied_receipts,
            policy.receipt_validation,
            backfill_chunk_size,
        )?;
    }

    // For down-direction apply, reconcile history by deleting matching applied up versions.
    // This keeps `_qail_migrations` consistent so a later `migrate apply` (up) can re-run.
    let mut applied_up_versions_by_group: HashMap<String, Vec<String>> = HashMap::new();
    if matches!(direction, MigrateDirection::Down) {
        let discovered_up = discover_migrations(&migrations_dir, MigrateDirection::Up)?;
        ensure_up_down_pairing(&discovered_up, &migrations)?;
        for up_mig in &discovered_up {
            if applied_migrations.contains_key(&up_mig.display_name) {
                applied_up_versions_by_group
                    .entry(up_mig.group_key.clone())
                    .or_default()
                    .push(up_mig.display_name.clone());
            }
        }
    }

    // Phase prerequisite check: when running --phase backfill or --phase contract,
    // verify that earlier phases for each group have already been applied.
    if matches!(direction, MigrateDirection::Up)
        && !matches!(phase_filter, ApplyPhase::All | ApplyPhase::Expand)
    {
        let all_discovered = discover_migrations(&migrations_dir, direction)?;
        // Group migrations by group_key and check prerequisites
        let mut groups: std::collections::BTreeMap<String, Vec<&MigrationFile>> =
            std::collections::BTreeMap::new();
        for m in &all_discovered {
            groups.entry(m.group_key.clone()).or_default().push(m);
        }

        for mig in &migrations {
            if let Some(group_files) = groups.get(&mig.group_key) {
                // Already applied — no need to check prerequisites
                if applied_migrations.contains_key(&mig.display_name) {
                    continue;
                }

                let required_phases: &[MigrationPhase] = match mig.phase {
                    MigrationPhase::Backfill => &[MigrationPhase::Expand],
                    MigrationPhase::Contract => &[MigrationPhase::Expand, MigrationPhase::Backfill],
                    MigrationPhase::Expand => &[],
                };

                for &req_phase in required_phases {
                    // Check if there are files for this prerequisite phase in the group
                    let prereq_files: Vec<&&MigrationFile> = group_files
                        .iter()
                        .filter(|f| f.phase == req_phase)
                        .collect();

                    for prereq in &prereq_files {
                        if !applied_migrations.contains_key(&prereq.display_name) {
                            bail!(
                                "Phase prerequisite not met for '{}': \
                                 {} phase '{}' has not been applied yet. \
                                 Run --phase {} first.",
                                mig.display_name,
                                req_phase,
                                prereq.display_name,
                                req_phase
                            );
                        }
                    }
                }
            }
        }
    }

    // Apply each pending migration
    let mut applied = 0;
    let mut skipped = 0;
    let mut current_phase = MigrationPhase::Expand;
    let mut current_group = String::new();

    for mig in &migrations {
        if mig.group_key != current_group {
            current_group = mig.group_key.clone();
            current_phase = MigrationPhase::Expand;
        }

        if matches!(direction, MigrateDirection::Up)
            && phase_rank(mig.phase) < phase_rank(current_phase)
        {
            bail!(
                "Phase ordering violation at {}: found '{}' after '{}'. Expected expand -> backfill -> contract.",
                mig.display_name,
                mig.phase,
                current_phase
            );
        }
        current_phase = mig.phase;

        print!(
            "  {} {} [{}]... ",
            "".cyan(),
            mig.display_name,
            mig.phase.to_string().yellow()
        );

        let versions_to_delete = if matches!(direction, MigrateDirection::Down) {
            applied_up_versions_by_group
                .get(&mig.group_key)
                .cloned()
                .unwrap_or_default()
        } else {
            Vec::new()
        };
        if matches!(direction, MigrateDirection::Down) && versions_to_delete.is_empty() {
            println!(
                "  {} {} {}",
                "".dimmed(),
                mig.display_name.dimmed(),
                "(group not applied; skipped)".dimmed()
            );
            skipped += 1;
            continue;
        }

        let content = fs::read_to_string(&mig.path)
            .context(format!("Failed to read {}", mig.path.display()))?;

        let mut risk_summary = format!(
            "source=folder_apply;direction={};phase={}",
            match direction {
                MigrateDirection::Up => "up",
                MigrateDirection::Down => "down",
            },
            mig.phase
        );

        let started_ms = now_epoch_ms();
        let mut chunked_backfill_spec = None;
        let (cmds, executed_sql_for_receipt, checksum_input) =
            if matches!(direction, MigrateDirection::Up) && mig.phase == MigrationPhase::Backfill {
                if let Some(spec) = parse_backfill_spec(&content, backfill_chunk_size)? {
                    chunked_backfill_spec = Some(spec);
                    (Vec::new(), content.clone(), content.clone())
                } else {
                    let cmds = parse_qail_to_commands_strict(&content)
                        .context("Failed to compile backfill migration to AST commands")?;
                    let sql = commands_to_sql(&cmds);
                    risk_summary.push_str(";chunked_backfill=false");
                    (cmds, sql.clone(), sql)
                }
            } else {
                let cmds = parse_qail_to_commands_strict(&content)
                    .context("Failed to compile migration to AST commands")?;
                let sql = commands_to_sql(&cmds);
                (cmds, sql.clone(), sql)
            };

        let expected_checksum = crate::time::md5_hex(&checksum_input);
        if matches!(direction, MigrateDirection::Up)
            && let Some(stored_checksum) = applied_migrations.get(&mig.display_name)
        {
            ensure_applied_checksum_matches(
                &mig.display_name,
                stored_checksum,
                &expected_checksum,
            )?;
            println!(
                "  {} {} {}",
                "".dimmed(),
                mig.display_name.dimmed(),
                "(already applied)".dimmed()
            );
            skipped += 1;
            continue;
        }

        if matches!(direction, MigrateDirection::Up) && !cmds.is_empty() {
            if enforce_shadow_receipt {
                let planned_checksum = stable_cmds_checksum(&cmds);
                let has_receipt =
                    has_verified_shadow_receipt_with_driver(&mut pg, &planned_checksum).await?;
                if !has_receipt {
                    bail!(
                        "Migration blocked: no verified shadow receipt for '{}'.\n\
                         Expected checksum: {}.\n\
                         Run 'qail migrate shadow <old.qail:new.qail> --url <db>' first, \
                         or re-run apply with --allow-no-shadow-receipt.",
                        mig.display_name,
                        planned_checksum
                    );
                }
                println!(
                    "  {} Verified shadow receipt checksum: {}",
                    "".green(),
                    planned_checksum.cyan()
                );
            }

            preflight_lock_risk(
                &mut pg,
                &cmds,
                allow_lock_risk,
                policy.lock_risk,
                policy.lock_risk_max_score,
            )
            .await?;

            let mut destructive_ops = Vec::<String>::new();
            for cmd in &cmds {
                let impact = analyze_impact(&mut pg, cmd).await?;
                if impact.is_destructive {
                    destructive_ops.push(format!("{} {}", impact.operation, impact.table));
                }
            }

            enforce_apply_destructive_policy(
                &mig.display_name,
                &destructive_ops,
                policy.destructive,
                allow_destructive,
            )?;
        }

        if matches!(direction, MigrateDirection::Up) && mig.phase == MigrationPhase::Contract {
            enforce_contract_safety(
                &mig.display_name,
                &executed_sql_for_receipt,
                codebase,
                allow_contract_with_references,
            )?;
        }

        let backfill_result = if let Some(spec) = chunked_backfill_spec {
            let backfill_result = run_chunked_backfill(&mut pg, &mig.display_name, &spec)
                .await
                .with_context(|| format!("Failed to run chunked backfill {}", mig.display_name))?;
            risk_summary.push_str(&format!(
                ";chunked_backfill=true;rows_updated={};chunks={};resumed={}",
                backfill_result.rows_updated, backfill_result.chunks, backfill_result.resumed
            ));
            backfill_result
        } else {
            BackfillRun::default()
        };

        let affected_rows_est = if backfill_result.rows_updated > 0 {
            Some(backfill_result.rows_updated)
        } else {
            None
        };
        risk_summary.push_str(&format!(
            ";allow_destructive_flag={};allow_lock_risk_flag={};adopt_existing_flag={};shadow_receipt_required={};policy_destructive={:?};policy_lock_risk={:?};policy_lock_risk_max_score={}",
            allow_destructive,
            allow_lock_risk,
            adopt_existing,
            matches!(direction, MigrateDirection::Up) && enforce_shadow_receipt,
            policy.destructive,
            policy.lock_risk,
            policy.lock_risk_max_score
        ));
        if matches!(direction, MigrateDirection::Down) {
            apply_down_commands_and_reconcile_history_atomic(
                &mut pg,
                &cmds,
                ApplyDownContext {
                    migration_name: &mig.display_name,
                    started_ms,
                    executed_sql_for_receipt,
                    checksum_input,
                    risk_summary,
                    versions_to_delete: versions_to_delete.as_slice(),
                    failpoint_override: None,
                },
            )
            .await
            .context(format!(
                "Failed to apply down migration {}",
                mig.display_name
            ))?;

            for version in &versions_to_delete {
                applied_migrations.remove(version);
            }
            applied_up_versions_by_group.remove(&mig.group_key);
        } else {
            apply_commands_and_record_receipt_atomic(
                &mut pg,
                &cmds,
                adopt_existing,
                ApplyReceiptContext {
                    migration_name: &mig.display_name,
                    started_ms,
                    executed_sql_for_receipt,
                    checksum_input,
                    risk_summary,
                    affected_rows_est,
                    failpoint_override: None,
                },
            )
            .await
            .context(format!("Failed to apply migration {}", mig.display_name))?;

            applied_migrations.insert(mig.display_name.clone(), expected_checksum);
        }

        println!("{}", "".green());
        applied += 1;
    }

    // Summary
    if applied > 0 {
        println!(
            "\n{}",
            format!("{} migration(s) applied successfully!", applied)
                .green()
                .bold()
        );
    }
    if skipped > 0 {
        println!(
            "  {} {} migration(s) already applied (skipped)",
            "".dimmed(),
            skipped
        );
    }
    if applied == 0 && skipped > 0 {
        println!("\n{}", "✓ Database is up to date.".green().bold());
    }
    Ok(())
}

fn resolve_apply_shadow_receipt_policy(
    policy: &MigrationPolicy,
    allow_no_shadow_receipt: bool,
) -> Result<bool> {
    if !policy.require_shadow_receipt {
        println!(
            "{}",
            "⚠️  Shadow receipt verification disabled by migrations.policy.require_shadow_receipt=false"
                .yellow()
        );
        return Ok(false);
    }
    if allow_no_shadow_receipt {
        if !policy.allow_no_shadow_receipt {
            bail!(
                "Migration blocked: --allow-no-shadow-receipt is disabled by migrations.policy.allow_no_shadow_receipt=false"
            );
        }
        println!(
            "{}",
            "⚠️  Skipping shadow receipt verification due to --allow-no-shadow-receipt".yellow()
        );
        return Ok(false);
    }
    Ok(true)
}

fn enforce_apply_destructive_policy(
    migration_name: &str,
    destructive_ops: &[String],
    policy_mode: EnforcementMode,
    allow_destructive: bool,
) -> Result<()> {
    if destructive_ops.is_empty() {
        return Ok(());
    }

    let detail = destructive_ops
        .iter()
        .take(4)
        .cloned()
        .collect::<Vec<_>>()
        .join(", ");
    match policy_mode {
        EnforcementMode::Deny => bail!(
            "Migration blocked: destructive operations are disabled by migrations.policy.destructive=deny (migration '{}'; examples: {}).",
            migration_name,
            detail
        ),
        EnforcementMode::RequireFlag if !allow_destructive => bail!(
            "Migration blocked: destructive operations detected in '{}'. \
             Re-run with --allow-destructive to continue (examples: {}).",
            migration_name,
            detail
        ),
        EnforcementMode::RequireFlag => {
            println!(
                "{}",
                "⚠️  Destructive changes acknowledged via --allow-destructive".yellow()
            );
        }
        EnforcementMode::Allow => {
            println!(
                "{}",
                "⚠️  Destructive changes allowed by migrations.policy.destructive=allow".yellow()
            );
        }
    }
    Ok(())
}

async fn execute_migration_commands(
    pg: &mut qail_pg::PgDriver,
    cmds: &[Qail],
    migration_name: &str,
    adopt_existing: bool,
) -> Result<()> {
    if cmds.is_empty() {
        return Ok(());
    }

    for (idx, cmd) in cmds.iter().enumerate() {
        let savepoint = if adopt_existing {
            Some(format!("qail_apply_cmd_{}", idx + 1))
        } else {
            None
        };

        if let Some(ref sp) = savepoint {
            pg.execute(&savepoint_cmd(sp)).await.map_err(|e| {
                anyhow!(
                    "Failed to create savepoint '{}' before migration command {} in '{}': {}",
                    sp,
                    idx + 1,
                    migration_name,
                    e
                )
            })?;
        }

        if let Err(err) = pg.execute(cmd).await {
            let err_text = err.to_string();
            if adopt_existing && should_adopt_existing_error(cmd.action, &err_text) {
                if let Some(ref sp) = savepoint {
                    pg.execute(&rollback_to_savepoint_cmd(sp))
                        .await
                        .map_err(|e| {
                            anyhow!(
                                "Failed to rollback to savepoint '{}' after adopting existing object in '{}': {}",
                                sp,
                                migration_name,
                                e
                            )
                        })?;
                    pg.execute(&release_savepoint_cmd(sp)).await.map_err(|e| {
                        anyhow!(
                            "Failed to release savepoint '{}' after adopting existing object in '{}': {}",
                            sp,
                            migration_name,
                            e
                        )
                    })?;
                }
                println!(
                    "  {} Adopted existing object: action={:?} target='{}' (migration='{}')",
                    "".yellow(),
                    cmd.action,
                    cmd.table.cyan(),
                    migration_name
                );
                continue;
            }
            if let Some(ref sp) = savepoint {
                let _ = pg.execute(&rollback_to_savepoint_cmd(sp)).await;
            }
            return Err(anyhow!(
                "Migration command {} failed in '{}': action={:?} table='{}' error={}",
                idx + 1,
                migration_name,
                cmd.action,
                cmd.table,
                err_text
            ));
        }

        if let Some(ref sp) = savepoint {
            pg.execute(&release_savepoint_cmd(sp)).await.map_err(|e| {
                anyhow!(
                    "Failed to release savepoint '{}' after migration command {} in '{}': {}",
                    sp,
                    idx + 1,
                    migration_name,
                    e
                )
            })?;
        }
    }

    Ok(())
}

fn savepoint_cmd(name: &str) -> Qail {
    Qail {
        action: Action::Savepoint,
        savepoint_name: Some(name.to_string()),
        ..Default::default()
    }
}

fn rollback_to_savepoint_cmd(name: &str) -> Qail {
    Qail {
        action: Action::RollbackToSavepoint,
        savepoint_name: Some(name.to_string()),
        ..Default::default()
    }
}

fn release_savepoint_cmd(name: &str) -> Qail {
    Qail {
        action: Action::ReleaseSavepoint,
        savepoint_name: Some(name.to_string()),
        ..Default::default()
    }
}

fn should_adopt_existing_error(action: Action, error_text: &str) -> bool {
    if !is_adoptable_create_action(action) {
        return false;
    }

    if let Some(code) = extract_sqlstate(error_text)
        && matches!(code, "42P07" | "42710" | "42701" | "42P06" | "42723")
    {
        return true;
    }

    let lower = error_text.to_ascii_lowercase();
    lower.contains("already exists")
        || lower.contains("already has row security enabled")
        || lower.contains("already has row security forced")
}

fn is_adoptable_create_action(action: Action) -> bool {
    matches!(
        action,
        Action::Make
            | Action::Index
            | Action::CreateMaterializedView
            | Action::CreateView
            | Action::CreateFunction
            | Action::CreateTrigger
            | Action::CreateExtension
            | Action::CreateSequence
            | Action::CreateEnum
            | Action::CreatePolicy
            | Action::AlterEnableRls
            | Action::AlterForceRls
    )
}

fn extract_sqlstate(error_text: &str) -> Option<&str> {
    let start = error_text.find('[')?;
    let rest = &error_text[start + 1..];
    let end = rest.find(']')?;
    let code = &rest[..end];
    if code.len() == 5 && code.chars().all(|ch| ch.is_ascii_alphanumeric()) {
        Some(code)
    } else {
        None
    }
}

async fn verify_applied_commands_effects(
    pg: &mut qail_pg::PgDriver,
    migration_name: &str,
    cmds: &[Qail],
) -> Result<()> {
    if cmds.is_empty() {
        return Ok(());
    }

    let mut failures = Vec::<String>::new();
    let policy_expectations = collect_policy_final_expectations(cmds);

    for cmd in cmds {
        match cmd.action {
            Action::Make if !table_exists(pg, &cmd.table).await? => {
                failures.push(format!("expected table '{}' to exist", cmd.table));
            }
            Action::Make => {}
            Action::Alter => {
                for column in extract_column_names(&cmd.columns) {
                    if !column_exists(pg, &cmd.table, &column).await? {
                        failures.push(format!(
                            "expected column '{}.{}' to exist",
                            cmd.table, column
                        ));
                    }
                }
            }
            Action::Drop if table_exists(pg, &cmd.table).await? => {
                failures.push(format!("expected table '{}' to be dropped", cmd.table));
            }
            Action::Drop => {}
            Action::Index => {
                let index_name = cmd
                    .index_def
                    .as_ref()
                    .map(|idx| idx.name.as_str())
                    .unwrap_or(cmd.table.as_str());
                let index_name = strip_optional_if_exists_prefix(index_name);
                if !index_name.is_empty() && !index_exists(pg, &index_name).await? {
                    failures.push(format!("expected index '{}' to exist", index_name));
                }
            }
            Action::DropIndex => {
                let index_name = strip_optional_if_exists_prefix(&cmd.table);
                if !index_name.is_empty() && index_exists(pg, &index_name).await? {
                    failures.push(format!("expected index '{}' to be dropped", index_name));
                }
            }
            Action::AlterDrop => {
                for column in extract_column_names(&cmd.columns) {
                    if column_exists(pg, &cmd.table, &column).await? {
                        failures.push(format!(
                            "expected column '{}.{}' to be dropped",
                            cmd.table, column
                        ));
                    }
                }
            }
            Action::Mod => {
                for rename_expr in cmd.columns.iter().filter_map(|col| match col {
                    Expr::Named(raw) => Some(raw.as_str()),
                    _ => None,
                }) {
                    let Some((old_col, new_col)) = parse_rename_expr(rename_expr) else {
                        continue;
                    };

                    let old_exists = column_exists(pg, &cmd.table, old_col).await?;
                    let new_exists = column_exists(pg, &cmd.table, new_col).await?;
                    if old_exists || !new_exists {
                        failures.push(format!(
                            "expected rename '{}.{} -> {}' to be applied (old_exists={}, new_exists={})",
                            cmd.table, old_col, new_col, old_exists, new_exists
                        ));
                    }
                }
            }
            Action::AlterEnableRls => match table_rls_flags(pg, &cmd.table).await? {
                Some((enabled, _)) if enabled => {}
                Some((enabled, _)) => failures.push(format!(
                    "expected table '{}' RLS enabled (relrowsecurity={})",
                    cmd.table, enabled
                )),
                None => failures.push(format!(
                    "expected table '{}' to exist for RLS enable verification",
                    cmd.table
                )),
            },
            Action::AlterForceRls => match table_rls_flags(pg, &cmd.table).await? {
                Some((_, forced)) if forced => {}
                Some((_, forced)) => failures.push(format!(
                    "expected table '{}' FORCE RLS enabled (relforcerowsecurity={})",
                    cmd.table, forced
                )),
                None => failures.push(format!(
                    "expected table '{}' to exist for FORCE RLS verification",
                    cmd.table
                )),
            },
            Action::CreatePolicy => {
                // Verified in final-state pass below so mixed drop/create sequences in the
                // same migration are checked by the last command's intent.
            }
            Action::DropPolicy => {
                // Verified in final-state pass below so mixed drop/create sequences in the
                // same migration are checked by the last command's intent.
            }
            _ => {}
        }
    }

    for ((table, policy_name), should_exist) in policy_expectations {
        let exists = policy_exists(pg, &table, &policy_name).await?;
        if should_exist && !exists {
            failures.push(format!(
                "expected policy '{}' on table '{}' to exist",
                policy_name, table
            ));
        }
        if !should_exist && exists {
            failures.push(format!(
                "expected policy '{}' on table '{}' to be dropped",
                policy_name, table
            ));
        }
    }

    if failures.is_empty() {
        return Ok(());
    }

    let detail = failures
        .into_iter()
        .take(8)
        .collect::<Vec<_>>()
        .join("\n  - ");
    bail!(
        "Post-apply verification failed for '{}':\n  - {}",
        migration_name,
        detail
    );
}

fn split_schema_ident(name: &str) -> (&str, &str) {
    if let Some((schema, object)) = name.rsplit_once('.') {
        let schema = schema.trim();
        let object = object.trim();
        if !schema.is_empty() && !object.is_empty() {
            return (schema, object);
        }
    }
    ("public", name.trim())
}

fn strip_optional_if_exists_prefix(name: &str) -> String {
    let tokens: Vec<&str> = name.split_whitespace().collect();
    if tokens.len() >= 3
        && tokens[0].eq_ignore_ascii_case("if")
        && tokens[1].eq_ignore_ascii_case("exists")
    {
        tokens[2..].join(" ")
    } else {
        name.trim().to_string()
    }
}

fn parse_rename_expr(raw: &str) -> Option<(&str, &str)> {
    let (left, right) = raw.split_once("->")?;
    let left = left.trim();
    let right = right.trim();
    if left.is_empty() || right.is_empty() {
        return None;
    }
    Some((left, right))
}

fn extract_column_names(columns: &[Expr]) -> Vec<String> {
    columns
        .iter()
        .filter_map(|expr| match expr {
            Expr::Named(name) => Some(name.trim().to_string()),
            Expr::Def { name, .. } => Some(name.trim().to_string()),
            _ => None,
        })
        .filter(|name| !name.is_empty())
        .collect()
}

async fn table_exists(pg: &mut qail_pg::PgDriver, table: &str) -> Result<bool> {
    let (schema, table_name) = split_schema_ident(table);
    let cmd = Qail::get("information_schema.tables")
        .column("1")
        .where_eq("table_schema", schema)
        .where_eq("table_name", table_name)
        .limit(1);
    let rows = pg
        .fetch_all(&cmd)
        .await
        .with_context(|| format!("Failed table existence check for '{}'", table))?;
    Ok(!rows.is_empty())
}

fn collect_policy_final_expectations(cmds: &[Qail]) -> HashMap<(String, String), bool> {
    let mut expected = HashMap::<(String, String), bool>::new();
    for cmd in cmds {
        match cmd.action {
            Action::CreatePolicy => {
                if let Some(policy) = &cmd.policy_def {
                    expected.insert((policy.table.clone(), policy.name.clone()), true);
                }
            }
            Action::DropPolicy => {
                if let Some(policy_name) = cmd.payload.as_ref() {
                    expected.insert((cmd.table.clone(), policy_name.clone()), false);
                }
            }
            _ => {}
        }
    }
    expected
}

async fn column_exists(pg: &mut qail_pg::PgDriver, table: &str, column: &str) -> Result<bool> {
    let (schema, table_name) = split_schema_ident(table);
    let cmd = Qail::get("information_schema.columns")
        .column("1")
        .where_eq("table_schema", schema)
        .where_eq("table_name", table_name)
        .where_eq("column_name", column)
        .limit(1);
    let rows = pg.fetch_all(&cmd).await.with_context(|| {
        format!(
            "Failed column existence check for '{}.{}'",
            table_name, column
        )
    })?;
    Ok(!rows.is_empty())
}

async fn index_exists(pg: &mut qail_pg::PgDriver, index_name: &str) -> Result<bool> {
    let (schema, name) = split_schema_ident(index_name);
    let cmd = Qail::get("pg_class c")
        .column("1")
        .join(JoinKind::Inner, "pg_namespace n", "n.oid", "c.relnamespace")
        .where_eq("n.nspname", schema)
        .where_eq("c.relname", name)
        .limit(1);
    let rows = pg
        .fetch_all(&cmd)
        .await
        .with_context(|| format!("Failed index existence check for '{}'", index_name))?;
    Ok(!rows.is_empty())
}

async fn policy_exists(pg: &mut qail_pg::PgDriver, table: &str, policy_name: &str) -> Result<bool> {
    let (schema, table_name) = split_schema_ident(table);
    let cmd = Qail::get("pg_policies")
        .column("1")
        .where_eq("schemaname", schema)
        .where_eq("tablename", table_name)
        .where_eq("policyname", policy_name)
        .limit(1);
    let rows = pg.fetch_all(&cmd).await.with_context(|| {
        format!(
            "Failed policy existence check for '{}.{}'",
            table_name, policy_name
        )
    })?;
    Ok(!rows.is_empty())
}

async fn table_rls_flags(pg: &mut qail_pg::PgDriver, table: &str) -> Result<Option<(bool, bool)>> {
    let (schema, table_name) = split_schema_ident(table);
    let cmd = Qail::get("pg_class c")
        .columns(["c.relrowsecurity", "c.relforcerowsecurity"])
        .join(JoinKind::Inner, "pg_namespace n", "n.oid", "c.relnamespace")
        .where_eq("n.nspname", schema)
        .where_eq("c.relname", table_name)
        .limit(1);
    let rows = pg
        .fetch_all(&cmd)
        .await
        .with_context(|| format!("Failed RLS flag check for '{}'", table))?;
    let Some(row) = rows.first() else {
        return Ok(None);
    };
    Ok(Some((
        row.get_bool(0).unwrap_or(false),
        row.get_bool(1).unwrap_or(false),
    )))
}

struct ApplyReceiptContext<'a> {
    migration_name: &'a str,
    started_ms: i64,
    executed_sql_for_receipt: String,
    checksum_input: String,
    risk_summary: String,
    affected_rows_est: Option<i64>,
    failpoint_override: Option<&'a str>,
}

async fn apply_commands_and_record_receipt_atomic(
    pg: &mut qail_pg::PgDriver,
    cmds: &[Qail],
    adopt_existing: bool,
    context: ApplyReceiptContext<'_>,
) -> Result<()> {
    let ApplyReceiptContext {
        migration_name,
        started_ms,
        executed_sql_for_receipt,
        checksum_input,
        risk_summary,
        affected_rows_est,
        failpoint_override,
    } = context;

    pg.begin()
        .await
        .map_err(|e| anyhow!("Failed to begin migration transaction: {}", e))?;

    if let Err(err) = execute_migration_commands(pg, cmds, migration_name, adopt_existing).await {
        let _ = pg.rollback().await;
        return Err(err);
    }

    if let Err(err) = verify_applied_commands_effects(pg, migration_name, cmds).await {
        let _ = pg.rollback().await;
        return Err(err);
    }

    let finished_ms = now_epoch_ms();
    let checksum = crate::time::md5_hex(&checksum_input);
    let receipt = MigrationReceipt {
        version: migration_name.to_string(),
        name: migration_name.to_string(),
        checksum,
        sql_up: executed_sql_for_receipt,
        git_sha: runtime_git_sha(),
        qail_version: env!("CARGO_PKG_VERSION").to_string(),
        actor: runtime_actor(),
        started_at_ms: Some(started_ms),
        finished_at_ms: Some(finished_ms),
        duration_ms: Some(finished_ms.saturating_sub(started_ms)),
        affected_rows_est,
        risk_summary: Some(risk_summary),
        shadow_checksum: None,
    };

    if let Err(err) = maybe_failpoint_override("apply.before_receipt", failpoint_override) {
        let _ = pg.rollback().await;
        return Err(err);
    }

    if let Err(err) = write_migration_receipt(pg, &receipt).await {
        let _ = pg.rollback().await;
        return Err(anyhow!(
            "Failed to record migration '{}': {}",
            migration_name,
            err
        ));
    }

    if let Err(err) = maybe_failpoint_override("apply.before_commit", failpoint_override) {
        let _ = pg.rollback().await;
        return Err(err);
    }

    pg.commit()
        .await
        .map_err(|e| anyhow!("Failed to commit migration transaction: {}", e))?;

    Ok(())
}

struct ApplyDownContext<'a> {
    migration_name: &'a str,
    started_ms: i64,
    executed_sql_for_receipt: String,
    checksum_input: String,
    risk_summary: String,
    versions_to_delete: &'a [String],
    failpoint_override: Option<&'a str>,
}

async fn apply_down_commands_and_reconcile_history_atomic(
    pg: &mut qail_pg::PgDriver,
    cmds: &[Qail],
    context: ApplyDownContext<'_>,
) -> Result<()> {
    let ApplyDownContext {
        migration_name,
        started_ms,
        executed_sql_for_receipt,
        checksum_input,
        risk_summary,
        versions_to_delete,
        failpoint_override,
    } = context;

    pg.begin()
        .await
        .map_err(|e| anyhow!("Failed to begin migration transaction: {}", e))?;

    if let Err(err) = execute_migration_commands(pg, cmds, migration_name, false).await {
        let _ = pg.rollback().await;
        return Err(err);
    }

    if let Err(err) = verify_applied_commands_effects(pg, migration_name, cmds).await {
        let _ = pg.rollback().await;
        return Err(err);
    }

    for version in versions_to_delete {
        let delete_cmd = Qail::del("_qail_migrations").where_eq("version", version.as_str());
        if let Err(err) = pg.execute(&delete_cmd).await {
            let _ = pg.rollback().await;
            return Err(anyhow!(
                "Failed to reconcile migration history (delete '{}'): {}",
                version,
                err
            ));
        }
    }

    if let Err(err) = maybe_failpoint_override("apply.before_receipt", failpoint_override) {
        let _ = pg.rollback().await;
        return Err(err);
    }

    let finished_ms = now_epoch_ms();
    let checksum = crate::time::md5_hex(&checksum_input);
    let deleted = if versions_to_delete.is_empty() {
        String::from("none")
    } else {
        versions_to_delete.join(",")
    };
    let receipt_tag: String = migration_name
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() {
                ch.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();
    let receipt = MigrationReceipt {
        version: format!(
            "apply_down_{}_{}",
            receipt_tag,
            crate::time::timestamp_version()
        ),
        name: format!("apply_down {}", migration_name),
        checksum,
        sql_up: executed_sql_for_receipt,
        git_sha: runtime_git_sha(),
        qail_version: env!("CARGO_PKG_VERSION").to_string(),
        actor: runtime_actor(),
        started_at_ms: Some(started_ms),
        finished_at_ms: Some(finished_ms),
        duration_ms: Some(finished_ms.saturating_sub(started_ms)),
        affected_rows_est: Some(i64::try_from(versions_to_delete.len()).unwrap_or(i64::MAX)),
        risk_summary: Some(format!("{risk_summary};rolled_back_versions={deleted}")),
        shadow_checksum: None,
    };

    if let Err(err) = write_migration_receipt(pg, &receipt).await {
        let _ = pg.rollback().await;
        return Err(anyhow!(
            "Failed to record down migration '{}': {}",
            migration_name,
            err
        ));
    }

    if let Err(err) = maybe_failpoint_override("apply.before_commit", failpoint_override) {
        let _ = pg.rollback().await;
        return Err(err);
    }

    pg.commit()
        .await
        .map_err(|e| anyhow!("Failed to commit migration transaction: {}", e))?;

    Ok(())
}

fn maybe_failpoint_override(name: &str, failpoint_override: Option<&str>) -> Result<()> {
    let Some(spec) = failpoint_override else {
        return maybe_failpoint(name);
    };
    if spec
        .split(',')
        .map(str::trim)
        .any(|token| token == "*" || token.eq_ignore_ascii_case(name))
    {
        bail!("Injected failpoint triggered: {}", name);
    }
    Ok(())
}

fn ensure_applied_checksum_matches(
    version: &str,
    stored_checksum: &str,
    expected_checksum: &str,
) -> Result<()> {
    if stored_checksum == expected_checksum {
        return Ok(());
    }
    bail!(
        "Migration checksum drift detected for '{}': stored={}, current={}. \
         Refusing to skip. Rename the migration or reconcile _qail_migrations before re-running.",
        version,
        stored_checksum,
        expected_checksum
    );
}

pub(crate) fn compute_expected_migration_checksum(
    content: &str,
    phase: MigrationPhase,
    backfill_chunk_size: usize,
) -> Result<String> {
    if phase == MigrationPhase::Backfill
        && parse_backfill_spec(content, backfill_chunk_size)?.is_some()
    {
        return Ok(crate::time::md5_hex(content));
    }

    let cmds = parse_qail_to_commands_strict(content)
        .context("Failed to compile migration to AST commands for checksum")?;
    let sql = commands_to_sql(&cmds);
    Ok(crate::time::md5_hex(&sql))
}

fn validate_receipts_against_local(
    discovered_up: &[MigrationFile],
    applied_migrations: &HashMap<String, String>,
    applied_receipts: &HashMap<String, StoredMigrationReceipt>,
    mode: ReceiptValidationMode,
    backfill_chunk_size: usize,
) -> Result<()> {
    if discovered_up.is_empty() || applied_migrations.is_empty() {
        return Ok(());
    }

    let local_versions = discovered_up
        .iter()
        .map(|m| m.display_name.clone())
        .collect::<HashSet<_>>();

    let mut missing_local = Vec::<String>::new();
    for version in applied_migrations.keys() {
        if !version.ends_with(".qail") {
            continue;
        }
        if !local_versions.contains(version) {
            missing_local.push(version.clone());
        }
    }
    missing_local.sort();

    if !missing_local.is_empty() {
        let detail = missing_local
            .iter()
            .take(8)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        let msg = format!(
            "Migration receipt drift detected: {} applied migration version(s) exist in _qail_migrations but no matching local file in deltas/migrations (examples: {}).",
            missing_local.len(),
            detail
        );
        match mode {
            ReceiptValidationMode::Warn => {
                eprintln!("  {} {}", "".yellow(), msg.yellow());
            }
            ReceiptValidationMode::Error => bail!("{}", msg),
        }
    }

    for mig in discovered_up {
        let Some(stored_checksum) = applied_migrations.get(&mig.display_name) else {
            continue;
        };
        let content = std::fs::read_to_string(&mig.path)
            .with_context(|| format!("Failed to read {}", mig.path.display()))?;
        let expected_checksum =
            compute_expected_migration_checksum(&content, mig.phase, backfill_chunk_size)?;
        if stored_checksum == &expected_checksum {
            continue;
        }
        let msg = format!(
            "Migration checksum drift detected for '{}': stored={}, local={}",
            mig.display_name, stored_checksum, expected_checksum
        );
        match mode {
            ReceiptValidationMode::Warn => {
                eprintln!("  {} {}", "".yellow(), msg.yellow());
            }
            ReceiptValidationMode::Error => bail!("{}", msg),
        }
    }

    let mut missing_signature = Vec::<String>::new();
    let mut invalid_signature = Vec::<String>::new();
    for (version, stored) in applied_receipts {
        if !version.ends_with(".qail") {
            continue;
        }
        match verify_stored_receipt_signature(stored) {
            ReceiptSignatureStatus::DisabledNoKey | ReceiptSignatureStatus::Valid => {}
            ReceiptSignatureStatus::Missing => missing_signature.push(version.clone()),
            ReceiptSignatureStatus::Invalid => invalid_signature.push(version.clone()),
        }
    }
    missing_signature.sort();
    invalid_signature.sort();

    if !missing_signature.is_empty() {
        let detail = missing_signature
            .iter()
            .take(8)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        let msg = format!(
            "Migration receipt signature missing for {} applied version(s) (examples: {}). \
             Set migrations.policy.receipt_validation=warn to bypass temporarily while backfilling signatures.",
            missing_signature.len(),
            detail
        );
        match mode {
            ReceiptValidationMode::Warn => eprintln!("  {} {}", "".yellow(), msg.yellow()),
            ReceiptValidationMode::Error => bail!("{}", msg),
        }
    }

    if !invalid_signature.is_empty() {
        let detail = invalid_signature
            .iter()
            .take(8)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        let msg = format!(
            "Migration receipt signature verification failed for {} applied version(s) (examples: {}). \
             Refusing to proceed with untrusted migration history.",
            invalid_signature.len(),
            detail
        );
        match mode {
            ReceiptValidationMode::Warn => eprintln!("  {} {}", "".yellow(), msg.yellow()),
            ReceiptValidationMode::Error => bail!("{}", msg),
        }
    }

    Ok(())
}

fn parse_i64_field(value: Option<&String>) -> Option<i64> {
    value.and_then(|v| v.parse::<i64>().ok())
}

fn ensure_up_down_pairing(up: &[MigrationFile], down: &[MigrationFile]) -> Result<()> {
    if up.is_empty() {
        return Ok(());
    }

    let mut down_groups: HashMap<&str, usize> = HashMap::new();
    let mut down_display = HashSet::<String>::new();
    for mig in down {
        *down_groups.entry(mig.group_key.as_str()).or_insert(0) += 1;
        down_display.insert(mig.display_name.clone());
    }

    let mut missing_groups = BTreeSet::<String>::new();
    let mut ambiguous_groups = BTreeSet::<String>::new();
    let mut missing_flat_pairs = BTreeSet::<String>::new();

    for mig in up {
        match down_groups.get(mig.group_key.as_str()) {
            None => {
                missing_groups.insert(mig.group_key.clone());
            }
            Some(count) if *count > 1 => {
                ambiguous_groups.insert(mig.group_key.clone());
            }
            Some(_) => {}
        }

        if mig.display_name.ends_with(".up.qail") {
            let expected_down = mig.display_name.replacen(".up.qail", ".down.qail", 1);
            if !down_display.contains(&expected_down) {
                missing_flat_pairs.insert(format!("{} -> {}", mig.display_name, expected_down));
            }
        }
    }

    if !missing_groups.is_empty() {
        let groups = missing_groups
            .into_iter()
            .take(8)
            .collect::<Vec<_>>()
            .join(", ");
        bail!(
            "Missing rollback migrations (*.down.qail or <dir>/down.qail) for group(s): {}",
            groups
        );
    }
    if !ambiguous_groups.is_empty() {
        let groups = ambiguous_groups
            .into_iter()
            .take(8)
            .collect::<Vec<_>>()
            .join(", ");
        bail!(
            "Ambiguous rollback mapping: multiple down migrations found for group(s): {}",
            groups
        );
    }
    if !missing_flat_pairs.is_empty() {
        let pairs = missing_flat_pairs
            .into_iter()
            .take(8)
            .collect::<Vec<_>>()
            .join(", ");
        bail!("Missing flat rollback pair(s): {}", pairs);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        ApplyDownContext, ApplyReceiptContext, apply_commands_and_record_receipt_atomic,
        apply_down_commands_and_reconcile_history_atomic, collect_policy_final_expectations,
        enforce_apply_destructive_policy, ensure_applied_checksum_matches, ensure_up_down_pairing,
        parse_rename_expr, should_adopt_existing_error, split_schema_ident,
        strip_optional_if_exists_prefix, validate_receipts_against_local,
    };
    use crate::migrations::apply::MigrationFile;
    use crate::migrations::apply::types::MigrationPhase;
    use crate::migrations::{EnforcementMode, ReceiptValidationMode};
    use qail_core::ast::{Action, Constraint, Expr};
    use qail_core::prelude::Qail;
    use std::collections::HashMap;
    use std::fs;
    use std::path::PathBuf;

    fn mig(group_key: &str, display_name: &str) -> MigrationFile {
        MigrationFile {
            group_key: group_key.to_string(),
            sort_key: display_name.to_string(),
            display_name: display_name.to_string(),
            path: PathBuf::from(display_name),
            phase: MigrationPhase::Expand,
        }
    }

    #[test]
    fn applied_checksum_match_passes() {
        assert!(ensure_applied_checksum_matches("001_init.up.qail", "abc", "abc").is_ok());
    }

    #[test]
    fn applied_checksum_mismatch_fails() {
        let err = ensure_applied_checksum_matches("001_init.up.qail", "abc", "def")
            .expect_err("mismatch must fail");
        assert!(
            err.to_string().contains("checksum drift"),
            "error should mention checksum drift"
        );
    }

    #[test]
    fn split_schema_ident_defaults_to_public() {
        let (schema, name) = split_schema_ident("users");
        assert_eq!(schema, "public");
        assert_eq!(name, "users");
    }

    #[test]
    fn split_schema_ident_handles_qualified_name() {
        let (schema, name) = split_schema_ident("analytics.users");
        assert_eq!(schema, "analytics");
        assert_eq!(name, "users");
    }

    #[test]
    fn strip_optional_if_exists_prefix_normalizes_name() {
        assert_eq!(
            strip_optional_if_exists_prefix("if exists idx_users_email"),
            "idx_users_email"
        );
        assert_eq!(
            strip_optional_if_exists_prefix("IDX_USERS_EMAIL"),
            "IDX_USERS_EMAIL"
        );
    }

    #[test]
    fn parse_rename_expr_extracts_column_pair() {
        assert_eq!(
            parse_rename_expr("old_name -> new_name"),
            Some(("old_name", "new_name"))
        );
        assert_eq!(parse_rename_expr("  a->b "), Some(("a", "b")));
        assert_eq!(parse_rename_expr("old_name"), None);
    }

    #[test]
    fn adopt_existing_accepts_duplicate_relation_errors_for_create_actions() {
        assert!(should_adopt_existing_error(
            Action::CreateSequence,
            "Query error [42P07]: relation \"booking_number_seq\" already exists"
        ));
        assert!(should_adopt_existing_error(
            Action::Make,
            "relation \"users\" already exists"
        ));
    }

    #[test]
    fn adopt_existing_rejects_non_create_actions_and_other_errors() {
        assert!(!should_adopt_existing_error(
            Action::Add,
            "Query error [42P07]: relation \"booking_number_seq\" already exists"
        ));
        assert!(!should_adopt_existing_error(
            Action::CreateSequence,
            "Query error [42501]: permission denied for schema public"
        ));
    }

    #[test]
    fn destructive_policy_passes_when_no_destructive_ops() {
        let result =
            enforce_apply_destructive_policy("001_init.up.qail", &[], EnforcementMode::Deny, false);
        assert!(result.is_ok(), "no-op should pass regardless of policy");
    }

    #[test]
    fn destructive_policy_require_flag_blocks_without_flag() {
        let err = enforce_apply_destructive_policy(
            "002_drop_users.up.qail",
            &[String::from("DROP TABLE users")],
            EnforcementMode::RequireFlag,
            false,
        )
        .expect_err("require-flag should block without --allow-destructive");
        assert!(
            err.to_string().contains("--allow-destructive"),
            "error should mention allow-destructive override"
        );
    }

    #[test]
    fn destructive_policy_require_flag_passes_with_flag() {
        let result = enforce_apply_destructive_policy(
            "002_drop_users.up.qail",
            &[String::from("DROP TABLE users")],
            EnforcementMode::RequireFlag,
            true,
        );
        assert!(
            result.is_ok(),
            "require-flag policy should pass when allow flag is set"
        );
    }

    #[test]
    fn destructive_policy_deny_blocks_even_with_flag() {
        let err = enforce_apply_destructive_policy(
            "002_drop_users.up.qail",
            &[String::from("DROP TABLE users")],
            EnforcementMode::Deny,
            true,
        )
        .expect_err("deny mode must always block destructive migrations");
        assert!(
            err.to_string().contains("destructive=deny"),
            "error should mention deny policy"
        );
    }

    #[test]
    fn up_down_pairing_passes_for_flat_pair() {
        let up = vec![mig("001_add_users", "001_add_users.up.qail")];
        let down = vec![mig("001_add_users", "001_add_users.down.qail")];
        assert!(ensure_up_down_pairing(&up, &down).is_ok());
    }

    #[test]
    fn up_down_pairing_fails_when_missing_group_down() {
        let up = vec![mig("001_add_users", "001_add_users.up.qail")];
        let err = ensure_up_down_pairing(&up, &[]).expect_err("missing down must fail");
        assert!(
            err.to_string().contains("Missing rollback migrations"),
            "error should mention missing rollback migration"
        );
    }

    #[test]
    fn up_down_pairing_fails_when_ambiguous_group() {
        let up = vec![mig("001_add_users", "001_add_users.up.qail")];
        let down = vec![
            mig("001_add_users", "001_add_users.down.qail"),
            mig("001_add_users", "001_add_users_v2.down.qail"),
        ];
        let err = ensure_up_down_pairing(&up, &down).expect_err("ambiguous down must fail");
        assert!(
            err.to_string().contains("Ambiguous rollback mapping"),
            "error should mention ambiguous rollback mapping"
        );
    }

    #[test]
    fn receipt_validation_warns_on_missing_local_file() {
        let migrations = vec![mig("001_add_users", "001_add_users.up.qail")];
        let mut applied = HashMap::new();
        applied.insert("999_missing.up.qail".to_string(), "abc".to_string());
        let applied_receipts = HashMap::new();
        assert!(
            validate_receipts_against_local(
                &migrations,
                &applied,
                &applied_receipts,
                ReceiptValidationMode::Warn,
                5000
            )
            .is_ok()
        );
    }

    #[test]
    fn receipt_validation_errors_on_missing_local_file() {
        let migrations = vec![mig("001_add_users", "001_add_users.up.qail")];
        let mut applied = HashMap::new();
        applied.insert("999_missing.up.qail".to_string(), "abc".to_string());
        let applied_receipts = HashMap::new();
        let err = validate_receipts_against_local(
            &migrations,
            &applied,
            &applied_receipts,
            ReceiptValidationMode::Error,
            5000,
        )
        .expect_err("missing local receipt must fail in error mode");
        assert!(
            err.to_string().contains("receipt drift"),
            "error should mention receipt drift"
        );
    }

    #[test]
    fn receipt_validation_errors_on_checksum_mismatch() {
        let root =
            std::env::temp_dir().join(format!("qail_receipt_validation_{}", std::process::id()));
        let _ = fs::create_dir_all(&root);
        let path = root.join("001_add_users.up.qail");
        fs::write(&path, "table users (id int)\n").expect("write migration");
        let migrations = vec![MigrationFile {
            group_key: "001_add_users".to_string(),
            sort_key: "001_add_users.up.qail".to_string(),
            display_name: "001_add_users.up.qail".to_string(),
            path,
            phase: MigrationPhase::Expand,
        }];
        let mut applied = HashMap::new();
        applied.insert("001_add_users.up.qail".to_string(), "deadbeef".to_string());
        let applied_receipts = HashMap::new();
        let err = validate_receipts_against_local(
            &migrations,
            &applied,
            &applied_receipts,
            ReceiptValidationMode::Error,
            5000,
        )
        .expect_err("checksum mismatch must fail");
        assert!(
            err.to_string().contains("checksum drift"),
            "error should mention checksum drift"
        );
    }

    #[test]
    fn policy_expectations_follow_last_command_intent() {
        let cmds = vec![
            Qail {
                action: Action::DropPolicy,
                table: "tenant_contracts".to_string(),
                payload: Some("tenant_contracts_policy".to_string()),
                ..Default::default()
            },
            Qail {
                action: Action::CreatePolicy,
                policy_def: Some(
                    qail_core::migrate::policy::RlsPolicy::create(
                        "tenant_contracts_policy",
                        "tenant_contracts",
                    )
                    .for_all(),
                ),
                ..Default::default()
            },
        ];

        let expected = collect_policy_final_expectations(&cmds);
        assert_eq!(
            expected.get(&(
                "tenant_contracts".to_string(),
                "tenant_contracts_policy".to_string()
            )),
            Some(&true)
        );
    }

    #[test]
    fn policy_expectations_handle_create_then_drop() {
        let cmds = vec![
            Qail {
                action: Action::CreatePolicy,
                policy_def: Some(
                    qail_core::migrate::policy::RlsPolicy::create(
                        "tenant_isolation",
                        "reseller_pricing_overrides",
                    )
                    .for_all(),
                ),
                ..Default::default()
            },
            Qail {
                action: Action::DropPolicy,
                table: "reseller_pricing_overrides".to_string(),
                payload: Some("tenant_isolation".to_string()),
                ..Default::default()
            },
        ];

        let expected = collect_policy_final_expectations(&cmds);
        assert_eq!(
            expected.get(&(
                "reseller_pricing_overrides".to_string(),
                "tenant_isolation".to_string()
            )),
            Some(&false)
        );
    }

    async fn version_exists(pg: &mut qail_pg::PgDriver, version: &str) -> bool {
        let cmd = Qail::get("_qail_migrations")
            .column("version")
            .where_eq("version", version)
            .limit(1);
        match pg.query_ast(&cmd).await {
            Ok(result) => !result.rows.is_empty(),
            Err(_) => false,
        }
    }

    #[tokio::test]
    async fn apply_failpoint_before_receipt_rolls_back_commands_in_real_db() {
        let Some(url) = std::env::var("QAIL_TEST_DB_URL").ok() else {
            eprintln!("Skipping apply failpoint DB test (set QAIL_TEST_DB_URL)");
            return;
        };

        let mut pg = qail_pg::PgDriver::connect_url(&url)
            .await
            .expect("connect QAIL_TEST_DB_URL");
        crate::migrations::ensure_migration_table(&mut pg)
            .await
            .expect("bootstrap _qail_migrations");

        let suffix = format!(
            "{}_{}",
            std::process::id(),
            crate::time::timestamp_version()
        );
        let marker_version = format!("fp_marker_{}", suffix);
        let migration_name = format!("fp_receipt_{}.up.qail", suffix);

        let cleanup_marker =
            Qail::del("_qail_migrations").where_eq("version", marker_version.as_str());
        let cleanup_receipt =
            Qail::del("_qail_migrations").where_eq("version", migration_name.as_str());
        let _ = pg.execute(&cleanup_marker).await;
        let _ = pg.execute(&cleanup_receipt).await;

        let marker_cmd = Qail::add("_qail_migrations")
            .set_value("version", marker_version.as_str())
            .set_value("name", "fp_marker")
            .set_value("checksum", "fp_marker_checksum")
            .set_value("sql_up", "-- fp marker");

        let err = apply_commands_and_record_receipt_atomic(
            &mut pg,
            &[marker_cmd],
            false,
            ApplyReceiptContext {
                migration_name: &migration_name,
                started_ms: crate::migrations::now_epoch_ms(),
                executed_sql_for_receipt: "-- fp marker".to_string(),
                checksum_input: "-- fp marker".to_string(),
                risk_summary: "source=apply.failpoint.test".to_string(),
                affected_rows_est: None,
                failpoint_override: Some("apply.before_receipt"),
            },
        )
        .await
        .expect_err("failpoint should abort apply transaction");

        assert!(
            err.to_string()
                .contains("Injected failpoint triggered: apply.before_receipt"),
            "unexpected failpoint error: {err}"
        );
        assert!(
            !version_exists(&mut pg, marker_version.as_str()).await,
            "marker command row should have been rolled back"
        );
        assert!(
            !version_exists(&mut pg, migration_name.as_str()).await,
            "migration receipt should not be written when failpoint triggers"
        );
    }

    #[tokio::test]
    async fn apply_down_reconciles_up_history_in_real_db() {
        let Some(url) = std::env::var("QAIL_TEST_DB_URL").ok() else {
            eprintln!("Skipping apply-down history reconciliation DB test (set QAIL_TEST_DB_URL)");
            return;
        };

        let mut pg = qail_pg::PgDriver::connect_url(&url)
            .await
            .expect("connect QAIL_TEST_DB_URL");
        crate::migrations::ensure_migration_table(&mut pg)
            .await
            .expect("bootstrap _qail_migrations");

        let suffix = format!(
            "{}_{}",
            std::process::id(),
            crate::time::timestamp_version()
        );
        let table = format!("apply_down_hist_{}", suffix);
        let up_v1 = format!("{}_001.up.qail", suffix);
        let up_v2 = format!("{}_002.up.qail", suffix);
        let down_name = format!("{}_group/down.qail", suffix);

        // Create a table that down command will drop.
        let create_cmd = Qail {
            action: Action::Make,
            table: table.clone(),
            columns: vec![Expr::Def {
                name: "id".to_string(),
                data_type: "uuid".to_string(),
                constraints: vec![Constraint::PrimaryKey],
            }],
            ..Default::default()
        };
        pg.execute(&create_cmd).await.expect("create test table");

        // Seed synthetic "applied up" history rows.
        for version in [&up_v1, &up_v2] {
            let seed = Qail::add("_qail_migrations")
                .set_value("version", version.as_str())
                .set_value("name", version.as_str())
                .set_value("checksum", "seed_checksum")
                .set_value("sql_up", "-- seed up");
            pg.execute(&seed).await.expect("seed migration history");
        }

        let down_cmds = vec![Qail {
            action: Action::Drop,
            table: table.clone(),
            ..Default::default()
        }];

        apply_down_commands_and_reconcile_history_atomic(
            &mut pg,
            &down_cmds,
            ApplyDownContext {
                migration_name: &down_name,
                started_ms: crate::migrations::now_epoch_ms(),
                executed_sql_for_receipt: format!("drop {};", table),
                checksum_input: format!("drop {};", table),
                risk_summary: "source=apply.down.reconcile.test".to_string(),
                versions_to_delete: &[up_v1.clone(), up_v2.clone()],
                failpoint_override: None,
            },
        )
        .await
        .expect("apply down with history reconciliation");

        assert!(
            !version_exists(&mut pg, up_v1.as_str()).await,
            "first up version should be deleted from _qail_migrations"
        );
        assert!(
            !version_exists(&mut pg, up_v2.as_str()).await,
            "second up version should be deleted from _qail_migrations"
        );
        assert!(
            !super::table_exists(&mut pg, table.as_str())
                .await
                .expect("table existence check"),
            "down command should drop table"
        );

        let versions = pg
            .query_ast(&Qail::get("_qail_migrations").column("version"))
            .await
            .expect("query migration versions")
            .rows
            .iter()
            .filter_map(|row| row.first().and_then(|v| v.as_ref()).cloned())
            .collect::<Vec<_>>();
        assert!(
            versions.iter().all(|v| !v.ends_with(".down.qail")),
            "down-direction apply must not persist .down.qail versions"
        );
        assert!(
            versions.iter().any(|v| v.starts_with("apply_down_")),
            "down-direction apply should record a non-.qail audit receipt"
        );
    }
}