duroxide-pg 0.2.0

A PostgreSQL-based provider implementation for Duroxide, a durable task orchestration framework
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use anyhow::{Context, Result};
use include_dir::{include_dir, Dir};
use sqlx::{pool::PoolConnection, Connection, PgPool, Postgres};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;

// Touch this module when adding embedded files so incremental builds see them. Latest: 0030.
static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");

const DDL_LOCK_TIMEOUT_SQL: &str = "SET LOCAL lock_timeout = '250ms'";
const DDL_RETRY_BUDGET: Duration = Duration::from_secs(10);
const NOTIFICATION_TRIGGERS: &[(&str, &str)] = &[
    ("worker_queue", "trg_notify_worker_work"),
    ("worker_queue", "trg_notify_worker_work_released"),
    ("orchestrator_queue", "trg_notify_orch_work"),
    ("orchestrator_queue", "trg_notify_orch_work_released"),
    ("orchestrator_queue", "trg_notify_orch_work_consumed"),
    ("sessions", "trg_notify_session_lease"),
];

const BASE_TABLES: &[&str] = &[
    "instances",
    "executions",
    "history",
    "orchestrator_queue",
    "worker_queue",
    "instance_locks",
];
const ALL_CORE_TABLES: &[&str] = &[
    "instances",
    "executions",
    "history",
    "orchestrator_queue",
    "worker_queue",
    "instance_locks",
    "sessions",
    "kv_store",
    "kv_delta",
];

/// Migration metadata
#[derive(Debug)]
struct Migration {
    version: i64,
    name: String,
    sql: String,
}

/// Migration runner that handles schema-qualified migrations
pub struct MigrationRunner {
    pool: Arc<PgPool>,
    schema_name: String,
}

struct MigrationConnection {
    connection: PoolConnection<Postgres>,
    reusable: bool,
}

impl Drop for MigrationConnection {
    fn drop(&mut self) {
        if !self.reusable {
            self.connection.close_on_drop();
        }
    }
}

impl MigrationRunner {
    /// Create a new migration runner
    pub fn new(pool: Arc<PgPool>, schema_name: String) -> Self {
        Self { pool, schema_name }
    }

    fn advisory_lock_key(&self) -> i64 {
        // Stable 64-bit FNV-1a hash over (namespace + schema name).
        // This avoids using Rust's DefaultHasher (randomized per-process).
        const OFFSET: u64 = 0xcbf29ce484222325;
        const PRIME: u64 = 0x100000001b3;

        let mut hash = OFFSET;
        for b in b"duroxide_pg:migrations:" {
            hash ^= *b as u64;
            hash = hash.wrapping_mul(PRIME);
        }
        for b in self.schema_name.as_bytes() {
            hash ^= *b as u64;
            hash = hash.wrapping_mul(PRIME);
        }

        hash as i64
    }

    async fn lock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
        let key = self.advisory_lock_key();
        // Session lock (not xact lock) so it spans multiple transactions.
        // We explicitly unlock at the end.
        sqlx::query("SELECT pg_advisory_lock($1)")
            .bind(key)
            .execute(&mut *conn)
            .await?;
        Ok(())
    }

    async fn unlock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
        let key = self.advisory_lock_key();
        let unlocked: bool = sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
            .bind(key)
            .fetch_one(&mut *conn)
            .await
            .context("Releasing the migration advisory lock")?;
        anyhow::ensure!(
            unlocked,
            "Migration advisory lock was not held for schema {:?}",
            self.schema_name
        );
        Ok(())
    }

    /// Run all pending migrations
    pub async fn migrate(&self) -> Result<()> {
        self.migrate_with_notifications(false).await
    }

    pub(crate) async fn migrate_with_notifications(&self, notifications: bool) -> Result<()> {
        // Cancellation or failed unlocking must not return a session lock to the pool.
        let mut guard = MigrationConnection {
            connection: self.pool.acquire().await?,
            reusable: false,
        };
        let conn = &mut *guard.connection;
        self.lock_for_migrations(conn).await?;

        // Reject unknown migrations while holding the advisory lock so that an
        // older binary cannot rewrite a schema that is ahead of its code.
        // Short-circuit: do NOT run migrate_inner if unknown migrations are
        // detected.
        let result: Result<()> = async {
            self.check_no_unknown_migrations(conn).await?;
            self.migrate_inner(conn).await?;
            if notifications {
                self.enable_notifications(conn).await?;
            }
            Ok(())
        }
        .await;
        let unlock_result = self.unlock_for_migrations(conn).await;
        result?;
        unlock_result?;
        guard.reusable = true;
        Ok(())
    }

    /// Verify that the migration tracking table exists and that every embedded
    /// migration has already been applied. Does not take the migration
    /// advisory lock and does not create or modify any database objects.
    ///
    /// Returns an error if the `_duroxide_migrations` table is missing in
    /// `schema_name` or if any bundled migration version is absent from it.
    ///
    /// Intended for processes that must not perform DDL (e.g. application
    /// backends, where a separately privileged worker is responsible for
    /// applying schema changes).
    pub async fn verify(&self) -> Result<()> {
        self.verify_with_notifications(false).await
    }

    pub(crate) async fn verify_with_notifications(&self, notifications: bool) -> Result<()> {
        let mut conn = self.pool.acquire().await?;
        let conn = &mut *conn;

        // Check that the tracking table exists in the target schema.
        let table_exists = self.check_migration_table_exists(conn).await?;

        if !table_exists {
            anyhow::bail!(
                "duroxide migrations not initialized: schema {:?} does not \
                 contain _duroxide_migrations. Construct a provider with \
                 MigrationPolicy::ApplyAll (the default) from a process with \
                 DDL privileges before using MigrationPolicy::VerifyOnly.",
                self.schema_name
            );
        }

        // Reject schemas that have migrations the running binary does not
        // recognize (schema is ahead of the code).
        self.check_no_unknown_migrations(conn).await?;

        let migrations = Self::load_migrations()?;
        let applied = self.get_applied_versions(conn).await?;
        self.validate_applied_prefix(&migrations, &applied)?;
        let existing_tables = self.get_existing_core_relations(conn).await?;
        self.validate_core_table_state(&applied, &existing_tables)?;
        let applied: std::collections::HashSet<i64> = applied.into_iter().collect();

        let mut missing: Vec<i64> = migrations
            .iter()
            .map(|m| m.version)
            .filter(|v| !applied.contains(v))
            .collect();
        missing.sort_unstable();

        if !missing.is_empty() {
            anyhow::bail!(
                "duroxide migrations not up to date in schema {:?}: missing \
                 versions {:?}. Run migrations from a provider configured with \
                 MigrationPolicy::ApplyAll before constructing VerifyOnly \
                 providers.",
                self.schema_name,
                missing,
            );
        }

        if notifications
            && self.notification_trigger_counts(conn).await?.1 != NOTIFICATION_TRIGGERS.len() as i64
        {
            anyhow::bail!(
                "long-poll notifications are not enabled in schema {:?}. \
                 Construct a provider with MigrationPolicy::ApplyAll and \
                 long_poll.enabled = true from a process with DDL privileges first.",
                self.schema_name,
            );
        }

        Ok(())
    }

    async fn notification_trigger_counts(
        &self,
        conn: &mut sqlx::postgres::PgConnection,
    ) -> Result<(i64, i64)> {
        let (relations, names): (Vec<_>, Vec<_>) = NOTIFICATION_TRIGGERS
            .iter()
            .map(|(table, trigger)| (format!("{}.{table}", self.schema_name), *trigger))
            .unzip();
        let counts: (i64, i64) = sqlx::query_as(
            "SELECT COUNT(*), COUNT(*) FILTER (WHERE tgenabled IN ('O', 'A')) \
             FROM pg_catalog.pg_trigger \
             JOIN unnest($1::TEXT[], $2::TEXT[]) expected(relation, name) \
               ON tgrelid = expected.relation::REGCLASS AND tgname = expected.name",
        )
        .bind(relations)
        .bind(names)
        .fetch_one(conn)
        .await?;
        anyhow::ensure!(
            counts.0 == NOTIFICATION_TRIGGERS.len() as i64,
            "long-poll notification triggers are missing in schema {:?}; repair the schema before enabling long-polling",
            self.schema_name,
        );
        Ok(counts)
    }

    async fn enable_notifications(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
        if self.notification_trigger_counts(conn).await?.1 == NOTIFICATION_TRIGGERS.len() as i64 {
            return Ok(());
        }

        let deadline = Instant::now() + DDL_RETRY_BUDGET;
        loop {
            let result = async {
                let mut tx = conn.begin().await?;
                let result = async {
                    sqlx::query(DDL_LOCK_TIMEOUT_SQL).execute(&mut *tx).await?;
                    // Match acknowledgments, but bound every wait because admin
                    // deletion can acquire the queue locks in the opposite order.
                    for table in ["worker_queue", "orchestrator_queue", "sessions"] {
                        sqlx::query(&format!(
                            "LOCK TABLE {}.{table} IN SHARE ROW EXCLUSIVE MODE",
                            self.schema_name,
                        ))
                        .execute(&mut *tx)
                        .await?;
                    }
                    for (table, trigger) in NOTIFICATION_TRIGGERS {
                        sqlx::query(&format!(
                            "ALTER TABLE {}.{table} ENABLE TRIGGER {trigger}",
                            self.schema_name,
                        ))
                        .execute(&mut *tx)
                        .await?;
                    }
                    Ok(())
                }
                .await;
                Self::finish_ddl(tx, result).await
            }
            .await;
            match result {
                Ok(()) => return Ok(()),
                Err(error) => {
                    if !self
                        .retry_ddl(&error, deadline, "activating long-poll notifications")
                        .await
                    {
                        return Err(error.context(format!(
                            "Failed to activate long-poll notifications in schema {:?}",
                            self.schema_name
                        )));
                    }
                }
            }
        }
    }

    async fn finish_ddl(
        tx: sqlx::Transaction<'_, sqlx::Postgres>,
        result: Result<()>,
    ) -> Result<()> {
        match result {
            Ok(()) => tx.commit().await.context("Committing DDL transaction"),
            Err(error) => {
                tx.rollback()
                    .await
                    .with_context(|| format!("Rolling back DDL after {error:#}"))?;
                Err(error)
            }
        }
    }

    async fn retry_ddl(&self, error: &anyhow::Error, deadline: Instant, operation: &str) -> bool {
        let sqlstate = error
            .downcast_ref::<sqlx::Error>()
            .and_then(sqlx::Error::as_database_error)
            .and_then(|error| error.code());
        if !matches!(sqlstate.as_deref(), Some("40P01" | "55P03")) || Instant::now() >= deadline {
            return false;
        }
        tracing::warn!(
            schema = %self.schema_name,
            operation,
            sqlstate = sqlstate.as_deref(),
            error = %format_args!("{error:#}"),
            "DDL lock contention; retrying the rolled-back transaction"
        );
        let jitter = Duration::from_millis(50 + u64::from(uuid::Uuid::new_v4().as_bytes()[0]));
        tokio::time::sleep(jitter.min(deadline.saturating_duration_since(Instant::now()))).await;
        Instant::now() < deadline
    }

    /// Check that the database has no migrations the running binary does not
    /// recognize. Used by both `migrate()` (to refuse running DDL against a
    /// schema ahead of the code) and `verify()` (to refuse claiming
    /// successful verification of an unknown schema).
    ///
    /// Returns `Ok(())` if the tracking table does not yet exist: under
    /// `ApplyAll` it will be created by `migrate_inner`, and under
    /// `VerifyOnly` the missing table is reported separately before this is
    /// called.
    async fn check_no_unknown_migrations(
        &self,
        conn: &mut sqlx::postgres::PgConnection,
    ) -> Result<()> {
        if !self.check_migration_table_exists(conn).await? {
            return Ok(());
        }

        let applied = self.get_applied_versions(conn).await?;
        let expected: std::collections::HashSet<i64> = Self::load_migrations()?
            .into_iter()
            .map(|m| m.version)
            .collect();

        let mut unknown: Vec<i64> = applied
            .into_iter()
            .filter(|v| !expected.contains(v))
            .collect();
        unknown.sort_unstable();

        if !unknown.is_empty() {
            anyhow::bail!(
                "schema {:?} has migrations not recognized by this version of \
                 the code: {:?}. The database schema is ahead of the code. \
                 Update the code to a compatible version.",
                self.schema_name,
                unknown,
            );
        }

        Ok(())
    }

    async fn check_migration_table_exists(
        &self,
        conn: &mut sqlx::postgres::PgConnection,
    ) -> Result<bool> {
        let relation_kind: Option<String> = sqlx::query_scalar(
            "SELECT c.relkind::text \
             FROM pg_catalog.pg_class c \
             JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
             WHERE n.nspname = $1 AND c.relname = '_duroxide_migrations'",
        )
        .bind(&self.schema_name)
        .fetch_optional(&mut *conn)
        .await?;

        match relation_kind.as_deref() {
            None => Ok(false),
            Some("r" | "p") => Ok(true),
            Some(kind) => anyhow::bail!(
                "duroxide migration tracking object in schema {:?} has PostgreSQL \
                 relation kind {:?}, not a base table; refusing to read or replace it",
                self.schema_name,
                kind,
            ),
        }
    }

    fn validate_applied_prefix(
        &self,
        migrations: &[Migration],
        applied_versions: &[i64],
    ) -> Result<()> {
        for (index, (migration, applied)) in
            migrations.iter().zip(applied_versions.iter()).enumerate()
        {
            if migration.version != *applied {
                anyhow::bail!(
                    "duroxide migration history is inconsistent in schema {:?}: \
                     expected version {} at ledger position {}, but found version {}. \
                     Applied migrations must be an ordered prefix of the bundled \
                     migrations; refusing to apply migrations or modify the ledger.",
                    self.schema_name,
                    migration.version,
                    index + 1,
                    applied,
                );
            }
        }

        if applied_versions.len() > migrations.len() {
            anyhow::bail!(
                "duroxide migration history is inconsistent in schema {:?}: \
                 the ledger contains {} entries, but this binary bundles only {}. \
                 Refusing to apply migrations or modify the ledger.",
                self.schema_name,
                applied_versions.len(),
                migrations.len(),
            );
        }

        Ok(())
    }

    fn expected_core_tables(applied_versions: &[i64]) -> HashSet<String> {
        let Some(latest) = applied_versions.last().copied() else {
            return HashSet::new();
        };

        let mut expected: HashSet<String> =
            BASE_TABLES.iter().map(|name| (*name).to_string()).collect();
        if latest >= 14 {
            expected.insert("sessions".to_string());
        }
        if latest >= 18 {
            expected.insert("kv_store".to_string());
        }
        if latest >= 20 {
            expected.insert("kv_delta".to_string());
        }
        expected
    }

    fn validate_core_table_state(
        &self,
        applied_versions: &[i64],
        existing_relations: &HashMap<String, String>,
    ) -> Result<()> {
        let expected_tables = Self::expected_core_tables(applied_versions);
        let mut missing: Vec<&str> = expected_tables
            .iter()
            .filter(|name| !existing_relations.contains_key(*name))
            .map(String::as_str)
            .collect();
        let mut wrong_kind: Vec<(&str, &str)> = expected_tables
            .iter()
            .filter_map(|name| {
                existing_relations.get(name).and_then(|kind| {
                    (!matches!(kind.as_str(), "r" | "p")).then_some((name.as_str(), kind.as_str()))
                })
            })
            .collect();
        let mut unexpected: Vec<&str> = existing_relations
            .keys()
            .filter(|name| !expected_tables.contains(*name))
            .map(String::as_str)
            .collect();
        missing.sort_unstable();
        wrong_kind.sort_unstable();
        unexpected.sort_unstable();

        if !wrong_kind.is_empty() {
            anyhow::bail!(
                "duroxide schema {:?} has required relations {:?} with non-table \
                 PostgreSQL relation kinds. The schema may be corrupted; refusing \
                 to apply migrations or modify the ledger automatically.",
                self.schema_name,
                wrong_kind,
            );
        }

        if !missing.is_empty() {
            anyhow::bail!(
                "duroxide migration history in schema {:?} requires tables {:?}, \
                 but they are missing. The schema may be corrupted; refusing to \
                 apply migrations or modify the ledger automatically.",
                self.schema_name,
                missing,
            );
        }

        if !unexpected.is_empty() {
            anyhow::bail!(
                "duroxide schema {:?} contains tables {:?} that are not represented \
                 by its migration ledger. The schema may be corrupted; refusing to \
                 apply migrations or modify the ledger automatically.",
                self.schema_name,
                unexpected,
            );
        }

        Ok(())
    }

    async fn migrate_inner(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
        let schema_exists = self.check_schema_exists(conn).await?;
        if !schema_exists && self.schema_name != "public" {
            sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {}", self.schema_name))
                .execute(&mut *conn)
                .await?;
        }

        // Load migrations from filesystem
        let migrations = Self::load_migrations()?;

        tracing::debug!(
            "Loaded {} migrations for schema {}",
            migrations.len(),
            self.schema_name
        );

        let tracking_exists = self.check_migration_table_exists(conn).await?;
        let existing_tables = self.get_existing_core_relations(conn).await?;

        if !tracking_exists && !existing_tables.is_empty() {
            let mut relations: Vec<(&str, &str)> = existing_tables
                .iter()
                .map(|(name, kind)| (name.as_str(), kind.as_str()))
                .collect();
            relations.sort_unstable();
            anyhow::bail!(
                "duroxide relations {:?} exist in schema {:?}, but the migration \
                 tracking table is missing. The schema may be corrupted; refusing \
                 to create a new ledger or apply migrations automatically.",
                relations,
                self.schema_name,
            );
        }

        if !tracking_exists {
            self.ensure_migration_table(conn).await?;
        }

        let applied_versions = self.get_applied_versions(conn).await?;
        self.validate_applied_prefix(&migrations, &applied_versions)?;
        self.validate_core_table_state(&applied_versions, &existing_tables)?;
        tracing::debug!("Applied migrations: {:?}", applied_versions);

        for migration in migrations.into_iter().skip(applied_versions.len()) {
            tracing::debug!(
                "Applying migration {}: {}",
                migration.version,
                migration.name
            );
            self.apply_migration(conn, &migration).await?;
        }

        Ok(())
    }

    /// Load migrations from the embedded migrations directory
    fn load_migrations() -> Result<Vec<Migration>> {
        let mut migrations = Vec::new();

        // Get all files from embedded directory
        let mut files: Vec<_> = MIGRATIONS
            .files()
            .filter(|file| file.path().extension().and_then(|ext| ext.to_str()) == Some("sql"))
            .collect();

        // Sort by path to ensure consistent ordering
        files.sort_by_key(|f| f.path());

        for file in files {
            let file_name = file
                .path()
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| anyhow::anyhow!("Invalid filename in migrations"))?;

            let sql = file
                .contents_utf8()
                .ok_or_else(|| anyhow::anyhow!("Migration file is not valid UTF-8: {file_name}"))?
                .to_string();

            let version = Self::parse_version(file_name)?;
            let name = file_name.to_string();

            migrations.push(Migration { version, name, sql });
        }

        Ok(migrations)
    }

    /// Parse version number from migration filename (e.g., "0001_initial.sql" -> 1)
    fn parse_version(filename: &str) -> Result<i64> {
        let version_str = filename
            .split('_')
            .next()
            .ok_or_else(|| anyhow::anyhow!("Invalid migration filename: {filename}"))?;

        version_str
            .parse::<i64>()
            .map_err(|e| anyhow::anyhow!("Invalid migration version {version_str}: {e}"))
    }

    /// Ensure migration tracking table exists
    async fn ensure_migration_table(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
        // Create migration table in the target schema
        sqlx::query(&format!(
            r#"
            CREATE TABLE IF NOT EXISTS {}._duroxide_migrations (
                version BIGINT PRIMARY KEY,
                name TEXT NOT NULL,
                applied_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
            )
            "#,
            self.schema_name
        ))
        .execute(&mut *conn)
        .await?;

        Ok(())
    }

    async fn check_schema_exists(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<bool> {
        let exists = sqlx::query_scalar(
            "SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = $1)",
        )
        .bind(&self.schema_name)
        .fetch_one(&mut *conn)
        .await?;

        Ok(exists)
    }

    async fn get_existing_core_relations(
        &self,
        conn: &mut sqlx::postgres::PgConnection,
    ) -> Result<HashMap<String, String>> {
        let known_tables: Vec<String> = ALL_CORE_TABLES
            .iter()
            .map(|name| (*name).to_string())
            .collect();
        let relations: Vec<(String, String)> = sqlx::query_as(
            "SELECT c.relname::text, c.relkind::text \
             FROM pg_catalog.pg_class c \
             JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
             WHERE n.nspname = $1 AND c.relname = ANY($2::text[])",
        )
        .bind(&self.schema_name)
        .bind(&known_tables)
        .fetch_all(&mut *conn)
        .await?;

        Ok(relations.into_iter().collect())
    }

    /// Get list of applied migration versions
    async fn get_applied_versions(
        &self,
        conn: &mut sqlx::postgres::PgConnection,
    ) -> Result<Vec<i64>> {
        let versions: Vec<i64> = sqlx::query_scalar(&format!(
            "SELECT version FROM {}._duroxide_migrations ORDER BY version",
            self.schema_name
        ))
        .fetch_all(&mut *conn)
        .await?;

        Ok(versions)
    }

    /// Split SQL into statements, respecting dollar-quoted strings ($$...$$)
    /// This handles stored procedures and other constructs that use dollar-quoting
    fn split_sql_statements(sql: &str) -> Vec<String> {
        let mut statements = Vec::new();
        let mut current_statement = String::new();
        let chars: Vec<char> = sql.chars().collect();
        let mut i = 0;
        let mut in_dollar_quote = false;
        let mut dollar_tag: Option<String> = None;

        while i < chars.len() {
            let ch = chars[i];

            if !in_dollar_quote {
                // Check for start of dollar-quoted string
                if ch == '$' {
                    let mut tag = String::new();
                    tag.push(ch);
                    i += 1;

                    // Collect the tag (e.g., $$, $tag$, $function$)
                    while i < chars.len() {
                        let next_ch = chars[i];
                        if next_ch == '$' {
                            tag.push(next_ch);
                            dollar_tag = Some(tag.clone());
                            in_dollar_quote = true;
                            current_statement.push_str(&tag);
                            i += 1;
                            break;
                        } else if next_ch.is_alphanumeric() || next_ch == '_' {
                            tag.push(next_ch);
                            i += 1;
                        } else {
                            // Not a dollar quote, just a $ character
                            current_statement.push(ch);
                            break;
                        }
                    }
                } else if ch == ';' {
                    // End of statement (only if not in dollar quote)
                    current_statement.push(ch);
                    let trimmed = current_statement.trim().to_string();
                    if !trimmed.is_empty() {
                        statements.push(trimmed);
                    }
                    current_statement.clear();
                    i += 1;
                } else {
                    current_statement.push(ch);
                    i += 1;
                }
            } else {
                // Inside dollar-quoted string
                current_statement.push(ch);

                // Check for end of dollar-quoted string
                if ch == '$' {
                    let tag = dollar_tag.as_ref().unwrap();
                    let mut matches = true;

                    // Check if the following characters match the closing tag
                    for (j, tag_char) in tag.chars().enumerate() {
                        if j == 0 {
                            continue; // Skip first $ (we already matched it)
                        }
                        if i + j >= chars.len() || chars[i + j] != tag_char {
                            matches = false;
                            break;
                        }
                    }

                    if matches {
                        // Found closing tag - consume remaining tag characters
                        for _ in 0..(tag.len() - 1) {
                            if i + 1 < chars.len() {
                                current_statement.push(chars[i + 1]);
                                i += 1;
                            }
                        }
                        in_dollar_quote = false;
                        dollar_tag = None;
                    }
                }
                i += 1;
            }
        }

        // Add remaining statement if any
        let trimmed = current_statement.trim().to_string();
        if !trimmed.is_empty() {
            statements.push(trimmed);
        }

        statements
    }

    /// Build the `SET LOCAL search_path` statement used while applying a migration.
    ///
    /// `pg_temp` is pinned last so it sits at the lowest priority instead of its
    /// implicit highest-priority position, preventing a temporary object from
    /// shadowing the unqualified references a migration resolves via the
    /// `search_path`. This is defense-in-depth (CVE-2018-1058); `pg_catalog` is left
    /// unlisted so PostgreSQL keeps it implicitly first.
    ///
    /// `schema_name` is validated at provider construction
    /// (`^[A-Za-z_][A-Za-z0-9_]*$`), so direct interpolation here is safe.
    fn migration_search_path_stmt(schema_name: &str) -> String {
        format!("SET LOCAL search_path TO {schema_name}, pg_temp")
    }

    /// Apply a single migration
    async fn apply_migration(
        &self,
        conn: &mut sqlx::postgres::PgConnection,
        migration: &Migration,
    ) -> Result<()> {
        let deadline = Instant::now() + DDL_RETRY_BUDGET;
        loop {
            match self.apply_migration_once(conn, migration).await {
                Ok(()) => return Ok(()),
                Err(error) => {
                    if !self.retry_ddl(&error, deadline, &migration.name).await {
                        return Err(error);
                    }
                }
            }
        }
    }

    async fn apply_migration_once(
        &self,
        conn: &mut sqlx::postgres::PgConnection,
        migration: &Migration,
    ) -> Result<()> {
        // Remove comment lines and split SQL into individual statements
        let sql = migration.sql.trim();
        let cleaned_sql: String = sql
            .lines()
            .map(|line| {
                // Remove full-line comments
                if let Some(idx) = line.find("--") {
                    // Check if -- is inside a string (simple check)
                    let before = &line[..idx];
                    if before.matches('\'').count() % 2 == 0 {
                        // Even number of quotes means -- is not in a string
                        line[..idx].trim()
                    } else {
                        line
                    }
                } else {
                    line
                }
            })
            .filter(|line| !line.is_empty())
            .collect::<Vec<_>>()
            .join("\n");

        // Split by semicolon, but respect dollar-quoted strings ($$...$$)
        let statements = Self::split_sql_statements(&cleaned_sql);

        tracing::debug!(
            "Executing {} statements for migration {}",
            statements.len(),
            migration.version
        );

        let mut tx = conn.begin().await?;
        let result =
            async {
                sqlx::query(DDL_LOCK_TIMEOUT_SQL).execute(&mut *tx).await?;
                sqlx::query(&Self::migration_search_path_stmt(&self.schema_name))
                    .execute(&mut *tx)
                    .await?;
                for (idx, statement) in statements.iter().enumerate() {
                    if !statement.trim().is_empty() {
                        tracing::debug!(
                            "Executing statement {} of {}: {}...",
                            idx + 1,
                            statements.len(),
                            &statement.chars().take(50).collect::<String>()
                        );
                        sqlx::query(statement)
                            .execute(&mut *tx)
                            .await
                            .map_err(|error| {
                                let message = format!(
                                    "Failed to execute statement {} in migration {}: {error}\nStatement: {}",
                                    idx + 1, migration.version, statement
                                );
                                anyhow::Error::new(error).context(message)
                            })?;
                    }
                }

                sqlx::query(&format!(
                    "INSERT INTO {}._duroxide_migrations (version, name) VALUES ($1, $2)",
                    self.schema_name
                ))
                .bind(migration.version)
                .bind(&migration.name)
                .execute(&mut *tx)
                .await?;
                Ok(())
            }
            .await;

        Self::finish_ddl(tx, result).await?;

        tracing::info!(
            "Applied migration {}: {}",
            migration.version,
            migration.name
        );

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn migration_connection_is_reused_after_successful_unlock() {
        dotenvy::dotenv().ok();
        let Ok(url) = std::env::var("DATABASE_URL") else {
            eprintln!("DATABASE_URL not set; skipping migration connection database test");
            return;
        };
        let pool = sqlx::postgres::PgPoolOptions::new()
            .min_connections(1)
            .max_connections(1)
            .connect(&url)
            .await
            .unwrap();
        let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
        let schema = format!("reuse_migration_{}", uuid::Uuid::new_v4().simple());
        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
        let original_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
            .fetch_one(&pool)
            .await
            .unwrap();
        let mut results = Vec::new();
        for notifications in [false, false, true] {
            runner
                .migrate_with_notifications(notifications)
                .await
                .unwrap();
            let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
                .fetch_one(&pool)
                .await
                .unwrap();
            let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
                .bind(runner.advisory_lock_key())
                .fetch_one(&mut control)
                .await
                .unwrap();
            results.push((pid, unlocked));
        }
        pool.close().await;
        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
            .execute(&mut control)
            .await
            .unwrap();
        for (pid, unlocked) in results {
            assert_eq!(
                pid, original_pid,
                "migration success must not force a new connection"
            );
            assert!(
                unlocked,
                "the reused connection must not retain the migration lock"
            );
        }
    }

    #[tokio::test]
    async fn migration_connection_is_discarded_when_unlock_is_not_confirmed() {
        dotenvy::dotenv().ok();
        let Ok(url) = std::env::var("DATABASE_URL") else {
            eprintln!("DATABASE_URL not set; skipping migration unlock database test");
            return;
        };
        let pool = sqlx::postgres::PgPoolOptions::new()
            .min_connections(1)
            .max_connections(1)
            .connect(&url)
            .await
            .unwrap();
        let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
        let schema = format!("lost_migration_lock_{}", uuid::Uuid::new_v4().simple());
        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
        sqlx::query(&format!("CREATE SCHEMA {schema}"))
            .execute(&mut control)
            .await
            .unwrap();
        runner.ensure_migration_table(&mut control).await.unwrap();
        let versions: Vec<_> = MigrationRunner::load_migrations()
            .unwrap()
            .iter()
            .map(|m| m.version)
            .collect();
        let last = versions.last().unwrap();
        sqlx::Executor::execute(&mut control, format!(
            "CREATE FUNCTION {schema}.release_lock_early() RETURNS TRIGGER LANGUAGE plpgsql AS $$
             BEGIN PERFORM pg_advisory_unlock_all(); RETURN NEW; END $$;
             CREATE TRIGGER release_lock_early AFTER INSERT ON {schema}._duroxide_migrations
             FOR EACH ROW WHEN (NEW.version = {last}) EXECUTE FUNCTION {schema}.release_lock_early();"
        ).as_str()).await.unwrap();
        let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
            .fetch_one(&pool)
            .await
            .unwrap();
        let error = runner
            .migrate()
            .await
            .expect_err("an unconfirmed unlock is not success");
        let after: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
            .fetch_one(&pool)
            .await
            .unwrap();
        let applied = runner.get_applied_versions(&mut control).await.unwrap();
        let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
            .bind(runner.advisory_lock_key())
            .fetch_one(&mut control)
            .await
            .unwrap();
        pool.close().await;
        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
            .execute(&mut control)
            .await
            .unwrap();
        assert!(
            error
                .to_string()
                .contains("Migration advisory lock was not held"),
            "{error:#}"
        );
        assert_ne!(
            after, before,
            "failed unlock must not return the connection to the pool"
        );
        assert_eq!(
            applied, versions,
            "a cleanup error must not rewrite committed migration records"
        );
        assert!(unlocked);
    }

    #[tokio::test]
    async fn migration_connection_is_discarded_when_lock_acquisition_is_cancelled() {
        dotenvy::dotenv().ok();
        let Ok(url) = std::env::var("DATABASE_URL") else {
            eprintln!("DATABASE_URL not set; skipping migration cancellation database test");
            return;
        };
        let pool = sqlx::postgres::PgPoolOptions::new()
            .min_connections(1)
            .max_connections(1)
            .connect(&url)
            .await
            .unwrap();
        let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
        let schema = format!("cancel_migration_{}", uuid::Uuid::new_v4().simple());
        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
        let key = runner.advisory_lock_key();
        let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
            .fetch_one(&pool)
            .await
            .unwrap();
        sqlx::query("SELECT pg_advisory_lock($1)")
            .bind(key)
            .execute(&mut control)
            .await
            .unwrap();
        let migration = tokio::spawn(async move { runner.migrate().await });
        let waiting = tokio::time::timeout(Duration::from_secs(3), async {
            loop {
                let blocked: bool = sqlx::query_scalar(
                    "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = $1 AND wait_event = 'advisory')",
                ).bind(before).fetch_one(&mut control).await.unwrap();
                if blocked {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        }).await;
        migration.abort();
        assert!(migration.await.unwrap_err().is_cancelled());
        sqlx::query("SELECT pg_advisory_unlock($1)")
            .bind(key)
            .execute(&mut control)
            .await
            .unwrap();
        let after = tokio::time::timeout(
            Duration::from_secs(3),
            sqlx::query_scalar::<_, i32>("SELECT pg_backend_pid()").fetch_one(&pool),
        )
        .await
        .expect("cancellation must release the pool slot")
        .unwrap();
        let exited = tokio::time::timeout(Duration::from_secs(3), async {
            loop {
                let gone: bool = sqlx::query_scalar(
                    "SELECT NOT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = $1)",
                )
                .bind(before)
                .fetch_one(&mut control)
                .await
                .unwrap();
                if gone {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await;
        let absent: bool = sqlx::query_scalar("SELECT to_regnamespace($1) IS NULL")
            .bind(&schema)
            .fetch_one(&mut control)
            .await
            .unwrap();
        let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
            .bind(key)
            .fetch_one(&mut control)
            .await
            .unwrap();
        pool.close().await;
        sqlx::query(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE"))
            .execute(&mut control)
            .await
            .unwrap();
        waiting.expect("migration must reach the advisory-lock wait");
        exited.expect("the cancelled session must exit rather than keep its advisory lock");
        assert_ne!(after, before);
        assert!(
            absent,
            "cancellation before acquiring the lock must not apply DDL"
        );
        assert!(
            unlocked,
            "no cancelled session may retain the migration lock"
        );
    }

    #[tokio::test]
    async fn migration_statement_display_preserves_database_message_and_source() {
        dotenvy::dotenv().ok();
        let Ok(url) = std::env::var("DATABASE_URL") else {
            eprintln!("DATABASE_URL not set; skipping migration error database test");
            return;
        };
        let pool = sqlx::postgres::PgPoolOptions::new()
            .max_connections(1)
            .connect(&url)
            .await
            .unwrap();
        let schema = format!("migration_error_{}", uuid::Uuid::new_v4().simple());
        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
        let mut connection = pool.acquire().await.unwrap();
        sqlx::query(&format!("CREATE SCHEMA {schema}"))
            .execute(&mut *connection)
            .await
            .unwrap();
        runner
            .ensure_migration_table(&mut connection)
            .await
            .unwrap();
        let valid = Migration {
            version: 1,
            name: "0001_error_fixture.sql".to_string(),
            sql: "CREATE TABLE history_probe (id INTEGER PRIMARY KEY, valid BOOLEAN);
                  INSERT INTO history_probe VALUES (7, false);
                  CREATE FUNCTION validate_history_probe() RETURNS VOID LANGUAGE plpgsql AS $$
                  DECLARE bad_id INTEGER;
                  BEGIN
                      SELECT id INTO bad_id FROM history_probe WHERE NOT valid LIMIT 1;
                      IF FOUND THEN
                          RAISE EXCEPTION 'Malformed history: instance=damaged-history execution_id=1 event_id=%', bad_id
                              USING ERRCODE = '22023';
                      END IF;
                  END $$;".to_string(),
        };
        runner
            .apply_migration(&mut connection, &valid)
            .await
            .unwrap();
        let snapshot = format!(
            "SELECT jsonb_build_object(
                'ledger', (SELECT jsonb_agg(to_jsonb(m) ORDER BY version) FROM {schema}._duroxide_migrations m),
                'history', (SELECT jsonb_agg(to_jsonb(h) ORDER BY id) FROM {schema}.history_probe h),
                'function', pg_get_functiondef('{schema}.validate_history_probe()'::regprocedure))"
        );
        let before: serde_json::Value = sqlx::query_scalar(&snapshot)
            .fetch_one(&mut *connection)
            .await
            .unwrap();
        let invalid = Migration {
            version: 2,
            name: "0002_validate_history.sql".to_string(),
            sql: "INSERT INTO history_probe VALUES (8, true);
                  ALTER FUNCTION validate_history_probe() STABLE;
                  SELECT validate_history_probe();"
                .to_string(),
        };
        let error = runner
            .apply_migration(&mut connection, &invalid)
            .await
            .unwrap_err();
        let after: serde_json::Value = sqlx::query_scalar(&snapshot)
            .fetch_one(&mut *connection)
            .await
            .unwrap();
        sqlx::query(&format!("UPDATE {schema}.history_probe SET valid = true"))
            .execute(&mut *connection)
            .await
            .unwrap();
        runner
            .apply_migration(&mut connection, &invalid)
            .await
            .unwrap();
        let versions = runner.get_applied_versions(&mut connection).await.unwrap();
        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
            .execute(&mut *connection)
            .await
            .unwrap();
        drop(connection);
        pool.close().await;
        assert_eq!(
            after, before,
            "failed migration must preserve its ledger, function, and history"
        );
        assert_eq!(versions, vec![1, 2]);
        let database_error = error
            .downcast_ref::<sqlx::Error>()
            .and_then(sqlx::Error::as_database_error)
            .expect("retain the database source");
        assert_eq!(database_error.code().as_deref(), Some("22023"));
        let display = error.to_string();
        for expected in [
            "Failed to execute statement 3 in migration 2",
            "Malformed history: instance=damaged-history execution_id=1 event_id=7",
            "Statement: SELECT validate_history_probe();",
        ] {
            assert!(
                display.contains(expected),
                "missing {expected:?} in Display: {display}"
            );
        }
    }

    #[tokio::test]
    async fn ddl_retry_logs_sqlstate_and_full_error_context() {
        #[derive(Clone, Default)]
        struct Capture(Arc<std::sync::Mutex<Vec<u8>>>);

        impl std::io::Write for Capture {
            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
                self.0.lock().unwrap().extend_from_slice(bytes);
                Ok(bytes.len())
            }

            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        dotenvy::dotenv().ok();
        let Ok(url) = std::env::var("DATABASE_URL") else {
            eprintln!("DATABASE_URL not set; skipping DDL logging database test");
            return;
        };
        let pool = sqlx::postgres::PgPoolOptions::new()
            .max_connections(1)
            .connect(&url)
            .await
            .unwrap();
        let runner = MigrationRunner::new(Arc::new(pool.clone()), "diagnostic_test".to_string());
        let captured = Capture::default();
        let writer = captured.clone();
        let subscriber = tracing_subscriber::fmt()
            .without_time()
            .with_ansi(false)
            .with_env_filter("off,duroxide_pg::migrations=warn")
            .with_writer(move || writer.clone())
            .finish();
        let _guard = tracing::subscriber::set_default(subscriber);
        for (code, message) in [
            ("40P01", "simulated migration deadlock"),
            ("55P03", "simulated migration lock timeout"),
        ] {
            let error = sqlx::query(&format!(
                "DO $$ BEGIN RAISE EXCEPTION '{message}' USING ERRCODE = '{code}'; END $$"
            ))
            .execute(&pool)
            .await
            .unwrap_err();
            let error = anyhow::Error::new(error).context("outer migration statement context");
            assert!(
                runner
                    .retry_ddl(
                        &error,
                        Instant::now() + Duration::from_secs(5),
                        "test migration"
                    )
                    .await
            );
            let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
            assert!(
                output.contains("sqlstate=") && output.contains(code),
                "{output}"
            );
            assert!(
                output.contains("outer migration statement context") && output.contains(message),
                "{output}"
            );
        }
        pool.close().await;
    }

    #[test]
    fn embedded_migration_versions_are_unique_and_increasing() {
        let migrations = MigrationRunner::load_migrations().expect("load embedded migrations");
        assert!(!migrations.is_empty(), "expected embedded SQL migrations");
        for pair in migrations.windows(2) {
            assert!(
                pair[0].version < pair[1].version,
                "embedded migrations must have unique, increasing versions: {} then {}",
                pair[0].name,
                pair[1].name,
            );
        }
    }

    #[test]
    fn migration_search_path_pins_pg_temp_last() {
        // The security property: pg_temp must be present and last, so temporary
        // objects cannot shadow the unqualified references a migration relies on
        // the search_path to resolve.
        let stmt = MigrationRunner::migration_search_path_stmt("duroxide");
        assert_eq!(stmt, "SET LOCAL search_path TO duroxide, pg_temp");
    }
}