exochain-dag-db-postgres 0.2.0-beta

EXOCHAIN DAG DB PostgreSQL persistence adapters
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
#![cfg(feature = "postgres")]
#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]

use std::{fs, path::PathBuf, process};

use exo_dag_db_postgres::postgres::{
    CATALOG_ROOT_HASH_SEMANTICS, DAGDB_EXPORT_SCHEMA_SQL, DAGDB_GRAPH_SCHEMA_SQL,
    DAGDB_OPERATIONAL_EVENT_TYPES_AND_RLS_EXPANSION_SCHEMA_SQL,
    DAGDB_OPERATIONAL_RECEIPT_EVENT_TYPES_SCHEMA_SQL, DAGDB_PRD17_CONTEXT_PACKET_SCHEMA_SQL,
    DAGDB_PRD17_DEFAULT_ROUTE_SCHEMA_SQL, DAGDB_PRD17_LIFECYCLE_SCHEMA_SQL, DAGDB_SCHEMA_SQL,
    DAGDB_TENANT_RLS_SCHEMA_SQL, bind_tenant_context, init_pool, run_migrations_in_schema,
};
use sqlx::{Connection, PgConnection, Pool, Postgres, Row, Transaction, migrate::Migrator};

const EXPECTED_TABLES: &[&str] = &[
    "dagdb_agent_safety_scores",
    "dagdb_benchmark_runs",
    "dagdb_catalog_entries",
    "dagdb_context_packet_records",
    "dagdb_context_packets",
    "dagdb_continuation_records",
    "dagdb_council_decisions",
    "dagdb_dag_outbox",
    "dagdb_default_routes",
    "dagdb_export_challenges",
    "dagdb_exports",
    "dagdb_gateway_state_records",
    "dagdb_graph_canonicalization_decisions",
    "dagdb_graph_edge_tombstones",
    "dagdb_graph_edges",
    "dagdb_graph_layer_edges",
    "dagdb_graph_layer_memberships",
    "dagdb_graph_layers",
    "dagdb_graph_nodes",
    "dagdb_graph_placement_traces",
    "dagdb_graph_route_invalidations",
    "dagdb_graph_similarity_results",
    "dagdb_graph_views",
    "dagdb_idempotency_keys",
    "dagdb_inbound_agent_credentials",
    "dagdb_lifecycle_actions",
    "dagdb_lifecycle_rollbacks",
    "dagdb_memory_edges",
    "dagdb_memory_objects",
    "dagdb_node_commit_certificates",
    "dagdb_node_committed",
    "dagdb_node_consensus_meta",
    "dagdb_node_consensus_votes",
    "dagdb_node_dag_nodes",
    "dagdb_node_dag_parents",
    "dagdb_node_economy_anchors",
    "dagdb_node_economy_meta",
    "dagdb_node_economy_objects",
    "dagdb_node_trust_receipts",
    "dagdb_node_validators",
    "dagdb_receipts",
    "dagdb_root_bundle_receipts",
    "dagdb_route_invalidation_events",
    "dagdb_route_receipts",
    "dagdb_subject_receipt_heads",
    "dagdb_validation_reports",
    "dagdb_zerodentity_records",
];

const EXPECTED_TENANT_RLS_TABLES: &[&str] = &[
    "dagdb_agent_safety_scores",
    "dagdb_catalog_entries",
    "dagdb_context_packet_records",
    "dagdb_context_packets",
    "dagdb_continuation_records",
    "dagdb_council_decisions",
    "dagdb_dag_outbox",
    "dagdb_default_routes",
    "dagdb_export_challenges",
    "dagdb_exports",
    "dagdb_gateway_state_records",
    "dagdb_graph_canonicalization_decisions",
    "dagdb_graph_edge_tombstones",
    "dagdb_graph_edges",
    "dagdb_graph_layer_edges",
    "dagdb_graph_layer_memberships",
    "dagdb_graph_layers",
    "dagdb_graph_nodes",
    "dagdb_graph_placement_traces",
    "dagdb_graph_route_invalidations",
    "dagdb_graph_similarity_results",
    "dagdb_graph_views",
    "dagdb_idempotency_keys",
    "dagdb_inbound_agent_credentials",
    "dagdb_lifecycle_actions",
    "dagdb_memory_edges",
    "dagdb_memory_objects",
    "dagdb_node_commit_certificates",
    "dagdb_node_committed",
    "dagdb_node_consensus_meta",
    "dagdb_node_consensus_votes",
    "dagdb_node_dag_nodes",
    "dagdb_node_dag_parents",
    "dagdb_node_economy_anchors",
    "dagdb_node_economy_meta",
    "dagdb_node_economy_objects",
    "dagdb_node_trust_receipts",
    "dagdb_node_validators",
    "dagdb_receipts",
    "dagdb_route_invalidation_events",
    "dagdb_route_receipts",
    "dagdb_subject_receipt_heads",
    "dagdb_validation_reports",
    "dagdb_zerodentity_records",
];

const PR708_NEW_TENANT_RLS_TABLES: &[&str] = &[
    "dagdb_node_dag_nodes",
    "dagdb_node_dag_parents",
    "dagdb_node_committed",
    "dagdb_node_consensus_meta",
    "dagdb_node_consensus_votes",
    "dagdb_node_commit_certificates",
    "dagdb_node_validators",
    "dagdb_node_trust_receipts",
    "dagdb_node_economy_objects",
    "dagdb_node_economy_anchors",
    "dagdb_node_economy_meta",
    "dagdb_zerodentity_records",
    "dagdb_gateway_state_records",
];

const PR708_NEW_MIGRATION_VERSIONS: &[i64] = &[
    20260623000001,
    20260623000002,
    20260623000003,
    20260623000004,
    20260623000005,
    20260623000006,
];

const LAST_SUCCESSFUL_DEPLOYED_MIGRATION_FILES: &[&str] = &[
    "20260505000001_create_dagdb_schema.sql",
    "20260505000002_create_dagdb_graph_schema.sql",
    "20260511000001_create_dagdb_export_persistence_schema.sql",
    "20260511000002_create_dagdb_export_finality_outbox_schema.sql",
    "20260602000001_create_dagdb_graph_edge_tombstones.sql",
    "20260602000002_create_dagdb_layered_graph_schema.sql",
    "20260607000001_create_prd17_default_route_schema.sql",
    "20260607000002_create_prd17_context_packet_schema.sql",
    "20260607000003_create_prd17_lifecycle_schema.sql",
    "20260612000001_create_dagdb_telemetry_facet_node_type.sql",
    "20260612000002_add_dagdb_graph_layers_aggregate_summary.sql",
    "20260612000003_add_dagdb_memory_deep_detail_summary.sql",
    "20260619000001_enable_dagdb_tenant_rls.sql",
    "20260620000001_add_dagdb_operational_receipt_event_types.sql",
];

const OPERATIONAL_RECEIPT_EVENT_TYPES: &[&str] = &[
    "dagdb_approval_request_submitted",
    "dagdb_approval_granted",
    "dagdb_approval_denied",
    "dagdb_record_accepted",
    "dagdb_import_completed",
    "dagdb_export_completed",
    "dagdb_replay_detected",
    "dagdb_idempotency_conflict",
    "dagdb_rls_tenant_violation",
    "dagdb_signature_failure",
    "dagdb_council_operator_decision",
];

const EXPECTED_INDEXES: &[(&str, &str)] = &[
    (
        "idx_dagdb_receipts_subject",
        "dagdb_receipts USING btree (tenant_id, namespace, subject_kind, subject_id, seq DESC)",
    ),
    (
        "idx_dagdb_receipts_event_type",
        "dagdb_receipts USING btree (tenant_id, namespace, event_type, event_hlc_physical_ms DESC, event_hlc_logical DESC)",
    ),
    (
        "idx_dagdb_root_bundle_receipts_ceremony",
        "dagdb_root_bundle_receipts USING btree (ceremony_id, verified_at_physical_ms DESC, verified_at_logical DESC)",
    ),
    (
        "uq_dagdb_memory_active_duplicate",
        "UNIQUE INDEX uq_dagdb_memory_active_duplicate ON",
    ),
    (
        "idx_dagdb_memory_status",
        "dagdb_memory_objects USING btree (tenant_id, namespace, status, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_memory_risk",
        "dagdb_memory_objects USING btree (tenant_id, namespace, risk_class, risk_bp DESC)",
    ),
    (
        "idx_dagdb_memory_receipt",
        "dagdb_memory_objects USING btree (latest_receipt_hash)",
    ),
    (
        "idx_dagdb_memory_dag_finality",
        "dagdb_memory_objects USING btree (tenant_id, namespace, dag_finality_status, status)",
    ),
    (
        "idx_dagdb_edges_to_type",
        "dagdb_memory_edges USING btree (tenant_id, namespace, to_memory_id, edge_type)",
    ),
    (
        "idx_dagdb_catalog_level",
        "dagdb_catalog_entries USING btree (tenant_id, namespace, catalog_level, catalog_id)",
    ),
    (
        "idx_dagdb_catalog_status",
        "dagdb_catalog_entries USING btree (tenant_id, namespace, status, validation_status, council_status)",
    ),
    (
        "idx_dagdb_routes_status",
        "dagdb_route_receipts USING btree (tenant_id, namespace, status, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_routes_task",
        "dagdb_route_receipts USING btree (tenant_id, namespace, task_signature_hash, route_score_bp DESC, route_id)",
    ),
    ("idx_dagdb_routes_stale", "WHERE (status = 'active'::text)"),
    (
        "idx_dagdb_routes_finality",
        "dagdb_route_receipts USING btree (tenant_id, namespace, dag_finality_status, status)",
    ),
    (
        "idx_dagdb_packets_validation",
        "dagdb_context_packets USING btree (tenant_id, namespace, validation_status, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_packets_request",
        "dagdb_context_packets USING btree (tenant_id, namespace, request_id, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_packets_finality",
        "dagdb_context_packets USING btree (tenant_id, namespace, dag_finality_status, validation_status)",
    ),
    (
        "idx_dagdb_validation_subject",
        "dagdb_validation_reports USING btree (tenant_id, namespace, subject_kind, subject_id, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_validation_status",
        "dagdb_validation_reports USING btree (tenant_id, namespace, validation_status, risk_bp DESC)",
    ),
    (
        "idx_dagdb_safety_agent_window",
        "dagdb_agent_safety_scores USING btree (tenant_id, namespace, agent_did, window_end_physical_ms DESC, window_end_logical DESC)",
    ),
    (
        "idx_dagdb_credentials_agent",
        "dagdb_inbound_agent_credentials USING btree (tenant_id, namespace, agent_did, credential_status, expires_at_physical_ms, expires_at_logical)",
    ),
    (
        "idx_dagdb_council_subject",
        "dagdb_council_decisions USING btree (tenant_id, namespace, subject_kind, subject_id, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_council_status",
        "dagdb_council_decisions USING btree (tenant_id, namespace, decision_status, risk_class)",
    ),
    (
        "idx_dagdb_council_expiry",
        "WHERE (decision_status = ANY (ARRAY['approved'::text, 'escalated'::text]))",
    ),
    (
        "idx_dagdb_idempotency_expires",
        "dagdb_idempotency_keys USING btree (expires_at_physical_ms, expires_at_logical)",
    ),
    (
        "idx_dagdb_outbox_status_next",
        "WHERE (dag_finality_status = ANY (ARRAY['pending'::text, 'failed'::text]))",
    ),
    (
        "idx_dagdb_outbox_subject",
        "dagdb_dag_outbox USING btree (tenant_id, namespace, subject_kind, subject_id)",
    ),
    (
        "idx_dagdb_benchmark_fixture",
        "dagdb_benchmark_runs USING btree (fixture_id, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_benchmark_runner",
        "dagdb_benchmark_runs USING btree (runner_name, fixture_id, deterministic_seed)",
    ),
    (
        "idx_dagdb_exports_scope_status",
        "dagdb_exports USING btree (tenant_id, namespace, export_status, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_exports_scope_hash",
        "dagdb_exports USING btree (tenant_id, namespace, export_scope_hash, whole_export_hash)",
    ),
    (
        "idx_dagdb_export_challenges_export",
        "dagdb_export_challenges USING btree (tenant_id, namespace, export_id, challenge_kind)",
    ),
    (
        "idx_dagdb_graph_nodes_memory",
        "dagdb_graph_nodes USING btree (tenant_id, namespace, memory_id, graph_style)",
    ),
    (
        "idx_dagdb_graph_edges_from_kind",
        "dagdb_graph_edges USING btree (tenant_id, namespace, from_memory_id, edge_kind)",
    ),
    (
        "idx_dagdb_graph_edge_tombstones_edge",
        "dagdb_graph_edge_tombstones USING btree (tenant_id, namespace, prior_edge_id)",
    ),
    (
        "idx_dagdb_graph_edge_tombstones_created",
        "dagdb_graph_edge_tombstones USING btree (tenant_id, namespace, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_graph_layers_path",
        "dagdb_graph_layers USING btree (tenant_id, namespace, layer_path)",
    ),
    (
        "idx_dagdb_graph_layers_parent_layer",
        "dagdb_graph_layers USING btree (tenant_id, namespace, parent_layer_id)",
    ),
    (
        "idx_dagdb_graph_layers_parent_graph_node",
        "dagdb_graph_layers USING btree (tenant_id, namespace, parent_graph_node_id)",
    ),
    (
        "idx_dagdb_graph_layer_memberships_layer_node",
        "dagdb_graph_layer_memberships USING btree (tenant_id, namespace, layer_id, graph_node_id)",
    ),
    (
        "idx_dagdb_graph_layer_memberships_graph_node",
        "dagdb_graph_layer_memberships USING btree (tenant_id, namespace, graph_node_id, layer_id)",
    ),
    (
        "idx_dagdb_graph_layer_edges_from",
        "dagdb_graph_layer_edges USING btree (tenant_id, namespace, from_layer_id, edge_kind)",
    ),
    (
        "idx_dagdb_graph_layer_edges_to",
        "dagdb_graph_layer_edges USING btree (tenant_id, namespace, to_layer_id, edge_kind)",
    ),
    (
        "idx_dagdb_graph_layer_edges_kind",
        "dagdb_graph_layer_edges USING btree (tenant_id, namespace, edge_kind, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
    (
        "idx_dagdb_graph_similarity_candidate",
        "dagdb_graph_similarity_results USING btree (tenant_id, namespace, candidate_memory_id, similarity_bp DESC)",
    ),
    (
        "idx_dagdb_graph_canon_input",
        "dagdb_graph_canonicalization_decisions USING btree (tenant_id, namespace, input_memory_id)",
    ),
    (
        "idx_dagdb_graph_views_root_style",
        "dagdb_graph_views USING btree (tenant_id, namespace, source_root_id, graph_style, stale)",
    ),
    (
        "idx_dagdb_graph_route_invalidations_route",
        "dagdb_graph_route_invalidations USING btree (tenant_id, namespace, route_id, created_at_physical_ms DESC, created_at_logical DESC)",
    ),
];

fn final_tenant_rls_schema_sql() -> String {
    format!(
        "{DAGDB_TENANT_RLS_SCHEMA_SQL}\n{DAGDB_OPERATIONAL_EVENT_TYPES_AND_RLS_EXPANSION_SCHEMA_SQL}"
    )
}

fn final_operational_event_schema_sql() -> String {
    format!(
        "{DAGDB_EXPORT_SCHEMA_SQL}\n{DAGDB_OPERATIONAL_RECEIPT_EVENT_TYPES_SCHEMA_SQL}\n{DAGDB_OPERATIONAL_EVENT_TYPES_AND_RLS_EXPANSION_SCHEMA_SQL}"
    )
}

#[tokio::test]
async fn schema_matches_declared_table_and_index_contract() {
    let Some(mut db) = TestDb::maybe_new("migration_contract").await else {
        return;
    };
    db.apply_schema().await;
    db.apply_schema().await;

    assert_tables(&mut db.conn).await;
    assert_required_columns(&mut db.conn).await;
    assert_constraints(&mut db.conn).await;
    assert_indexes(&mut db.conn).await;
    assert!(CATALOG_ROOT_HASH_SEMANTICS.contains("catalog material hashes"));
}

#[test]
fn rls_migration_source_enables_forced_tenant_policy_for_expected_tables() {
    let lower = final_tenant_rls_schema_sql().to_ascii_lowercase();
    let normalized_sql_literal = lower.replace("''", "'");
    assert!(lower.contains("enable row level security"));
    assert!(lower.contains("force row level security"));
    assert!(lower.contains("create or replace function dagdb_current_tenant_id()"));
    assert!(normalized_sql_literal.contains("bound_tenant_id := current_setting('exo.tenant_id')"));
    assert!(lower.contains("raise exception 'exo.tenant_id is not set'"));
    assert!(lower.contains("create policy dagdb_tenant_isolation"));
    assert!(normalized_sql_literal.contains("using (tenant_id = dagdb_current_tenant_id())"));
    assert!(normalized_sql_literal.contains("with check (tenant_id = dagdb_current_tenant_id())"));
    assert!(!normalized_sql_literal.contains("current_setting('exo.tenant_id', true)"));

    for table in EXPECTED_TENANT_RLS_TABLES {
        assert!(
            lower.contains(&format!("'{table}'")),
            "RLS migration must enumerate tenant table {table}"
        );
    }
    assert!(!lower.contains("'dagdb_benchmark_runs'"));
    assert!(!lower.contains("'dagdb_lifecycle_rollbacks'"));
    assert!(!lower.contains("'dagdb_root_bundle_receipts'"));
}

#[test]
fn pr708_additive_migration_owns_post_deploy_contract_expansion() {
    let restored_export = DAGDB_EXPORT_SCHEMA_SQL.to_ascii_lowercase();
    assert!(restored_export.contains("export_challenge_verified"));
    for event_type in OPERATIONAL_RECEIPT_EVENT_TYPES {
        assert!(
            !restored_export.contains(event_type),
            "restored applied export migration must not absorb PR #708 event type {event_type}"
        );
    }

    let restored_rls = DAGDB_TENANT_RLS_SCHEMA_SQL.to_ascii_lowercase();
    for table in PR708_NEW_TENANT_RLS_TABLES {
        assert!(
            !restored_rls.contains(&format!("'{table}'")),
            "restored applied tenant RLS migration must not absorb PR #708 table {table}"
        );
    }

    let final_event_sql = final_operational_event_schema_sql().to_ascii_lowercase();
    let additive = DAGDB_OPERATIONAL_EVENT_TYPES_AND_RLS_EXPANSION_SCHEMA_SQL.to_ascii_lowercase();
    for event_type in OPERATIONAL_RECEIPT_EVENT_TYPES {
        assert!(
            final_event_sql.contains(event_type),
            "final operational event contract must accept event type {event_type}"
        );
        assert!(
            additive.contains(event_type),
            "PR #708 additive migration must accept operational event type {event_type}"
        );
    }
    for table in PR708_NEW_TENANT_RLS_TABLES {
        assert!(
            additive.contains(&format!("'{table}'")),
            "PR #708 additive migration must force tenant RLS on {table}"
        );
    }
}

#[test]
fn root_bundle_receipts_are_global_immutable_schema_contract() {
    let lower = DAGDB_SCHEMA_SQL.to_ascii_lowercase();
    assert!(lower.contains("create table if not exists dagdb_root_bundle_receipts"));
    assert!(lower.contains("bundle_id bytea primary key not null"));
    assert!(lower.contains("root_bundle_hash bytea not null unique"));
    assert!(lower.contains("verification_receipt_hash bytea not null unique"));
    assert!(lower.contains("verification_receipt_body jsonb not null"));
    assert!(lower.contains("immutable boolean not null default true"));
    assert!(lower.contains("check (immutable = true)"));
    assert!(lower.contains("prevent_dagdb_root_bundle_receipt_mutation"));
    assert!(lower.contains("root_bundle_receipts_are_immutable"));
    assert!(!lower.contains("dagdb_root_bundle_receipts (\n    tenant_id"));
}

#[test]
fn node_store_tables_are_dagdb_schema_contract() {
    let lower = DAGDB_SCHEMA_SQL.to_ascii_lowercase();
    for table in [
        "dagdb_node_dag_nodes",
        "dagdb_node_dag_parents",
        "dagdb_node_committed",
        "dagdb_node_consensus_meta",
        "dagdb_node_consensus_votes",
        "dagdb_node_commit_certificates",
        "dagdb_node_validators",
        "dagdb_node_trust_receipts",
        "dagdb_node_economy_objects",
        "dagdb_node_economy_anchors",
        "dagdb_node_economy_meta",
    ] {
        assert!(
            lower.contains(&format!("create table if not exists {table}")),
            "DAG DB schema must include node-store table {table}"
        );
    }
    assert!(lower.contains("tenant_id text not null"));
    assert!(lower.contains("namespace text not null"));
    assert!(lower.contains("cbor_payload bytea not null"));
    assert!(lower.contains("receipt_hash bytea not null"));
    assert!(lower.contains("primary key (tenant_id, namespace, receipt_hash)"));
    assert!(lower.contains("anchor_hash bytea not null"));
    assert!(lower.contains("primary key (tenant_id, namespace, anchor_hash)"));
    assert!(lower.contains("idx_dagdb_node_committed_height"));
    assert!(lower.contains("idx_dagdb_node_trust_receipts_actor"));

    let rls_lower = final_tenant_rls_schema_sql().to_ascii_lowercase();
    for table in [
        "dagdb_node_dag_nodes",
        "dagdb_node_dag_parents",
        "dagdb_node_committed",
        "dagdb_node_consensus_meta",
        "dagdb_node_consensus_votes",
        "dagdb_node_commit_certificates",
        "dagdb_node_validators",
        "dagdb_node_trust_receipts",
        "dagdb_node_economy_objects",
        "dagdb_node_economy_anchors",
        "dagdb_node_economy_meta",
    ] {
        assert!(
            rls_lower.contains(&format!("'{table}'")),
            "DAG DB tenant RLS migration must enumerate node-store table {table}"
        );
    }
}

#[test]
fn zerodentity_records_are_dagdb_schema_contract() {
    let lower = DAGDB_SCHEMA_SQL.to_ascii_lowercase();
    assert!(
        lower.contains("create table if not exists dagdb_zerodentity_records"),
        "DAG DB schema must include the 0dentity durable record table"
    );
    assert!(lower.contains("state_family text not null"));
    assert!(lower.contains("subject_did text not null"));
    assert!(lower.contains("record_key text not null"));
    assert!(lower.contains("secondary_key text not null"));
    assert!(lower.contains("cbor_payload bytea not null"));
    assert!(
        lower.contains(
            "primary key (tenant_id, namespace, state_family, record_key, secondary_key)"
        )
    );
    for family in [
        "claim",
        "score",
        "previous_score",
        "score_history",
        "device_fingerprint",
        "behavioral_sample",
        "otp_challenge",
        "otp_lockout",
        "attestation",
        "identity_session",
        "session_nonce",
        "dag_node",
        "trust_receipt",
    ] {
        assert!(
            lower.contains(&format!("'{family}'")),
            "0dentity durable state family {family} must be schema-enforced"
        );
    }

    let rls_lower = final_tenant_rls_schema_sql().to_ascii_lowercase();
    assert!(
        rls_lower.contains("'dagdb_zerodentity_records'"),
        "DAG DB tenant RLS migration must enumerate 0dentity records"
    );
}

#[test]
fn gateway_state_records_are_dagdb_schema_contract() {
    let lower = DAGDB_SCHEMA_SQL.to_ascii_lowercase();
    for family in [
        "did_document",
        "session",
        "user",
        "agent",
        "decision",
        "delegation",
        "audit_entry",
        "constitution",
        "identity_score",
        "enrollment",
        "livesafe_identity",
        "scan_receipt",
        "consent_anchor",
        "trustee_shard",
        "agent_role",
        "consent_record",
        "authority_chain",
        "layout_template",
        "feedback_issue",
        "conflict_declaration",
        "avc_registry_state",
        "hlc_counter",
    ] {
        assert!(
            lower.contains(&format!("'{family}'")),
            "DAG DB schema must enumerate gateway state family {family}"
        );
    }
    assert!(
        lower.contains("create table if not exists dagdb_gateway_state_records"),
        "DAG DB schema must include the gateway durable state table"
    );
    assert!(lower.contains("state_family text not null"));
    assert!(lower.contains("record_key text not null"));
    assert!(lower.contains("cbor_payload bytea not null"));
    assert!(lower.contains("primary key (tenant_id, namespace, state_family, record_key)"));

    let rls_lower = final_tenant_rls_schema_sql().to_ascii_lowercase();
    assert!(
        rls_lower.contains("'dagdb_gateway_state_records'"),
        "DAG DB tenant RLS migration must enumerate gateway state records"
    );
}

#[tokio::test]
async fn rls_policies_fail_closed_without_tenant_context() {
    let Some(mut db) = TestDb::maybe_new("rls_contract").await else {
        return;
    };
    db.apply_schema().await;

    assert_rls_catalog_state(&mut db.conn).await;
    let rls_test_role = assume_rls_checked_role(&mut db.conn, &db.schema).await;

    let mut tx = db.conn.begin().await.expect("begin tenant-bound insert");
    bind_tenant_context(&mut tx, "tenant-a")
        .await
        .expect("bind tenant-a context");
    insert_idempotency_fixture_tx(&mut tx, "tenant-a", "idem-a")
        .await
        .expect("tenant-bound insert succeeds");
    tx.commit().await.expect("commit tenant-bound insert");

    let missing_context_count = idempotency_count_conn(&mut db.conn, "tenant-a").await;
    assert!(
        missing_context_count.is_err(),
        "read without exo.tenant_id must error instead of returning zero rows"
    );

    let missing_insert =
        insert_idempotency_fixture_conn(&mut db.conn, "tenant-a", "idem-missing").await;
    assert!(
        missing_insert.is_err(),
        "insert without exo.tenant_id must be rejected by RLS WITH CHECK"
    );

    let mut tx = db.conn.begin().await.expect("begin cross-tenant read");
    bind_tenant_context(&mut tx, "tenant-b")
        .await
        .expect("bind tenant-b context");
    let cross_tenant_count = idempotency_count_tx(&mut tx, "tenant-a")
        .await
        .expect("cross-tenant read succeeds");
    tx.commit().await.expect("commit cross-tenant read");
    assert_eq!(cross_tenant_count, 0);

    let mut tx = db.conn.begin().await.expect("begin same-tenant read");
    bind_tenant_context(&mut tx, "tenant-a")
        .await
        .expect("bind tenant-a context");
    let same_tenant_count = idempotency_count_tx(&mut tx, "tenant-a")
        .await
        .expect("same-tenant read succeeds");
    tx.commit().await.expect("commit same-tenant read");
    assert_eq!(same_tenant_count, 1);

    if let Some(role_name) = rls_test_role {
        cleanup_rls_checked_role(&mut db.conn, &role_name).await;
    }
}

#[tokio::test]
async fn migration_rollback_leaves_no_partial_schema() {
    let Some(mut db) = TestDb::maybe_new("rollback_contract").await else {
        return;
    };
    sqlx::raw_sql("BEGIN")
        .execute(&mut db.conn)
        .await
        .expect("begin migration rollback test");
    db.set_search_path().await;
    sqlx::raw_sql(DAGDB_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply DAG DB schema inside rollback transaction");
    sqlx::raw_sql(DAGDB_GRAPH_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply DAG DB graph schema inside rollback transaction");
    sqlx::raw_sql(DAGDB_EXPORT_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply DAG DB export schema inside rollback transaction");
    sqlx::raw_sql(DAGDB_PRD17_DEFAULT_ROUTE_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply PRD17 default-route schema inside rollback transaction");
    sqlx::raw_sql(DAGDB_PRD17_CONTEXT_PACKET_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply PRD17 context-packet schema inside rollback transaction");
    sqlx::raw_sql(DAGDB_PRD17_LIFECYCLE_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply PRD17 lifecycle schema inside rollback transaction");
    sqlx::raw_sql(DAGDB_TENANT_RLS_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply DAG DB tenant RLS schema inside rollback transaction");
    sqlx::raw_sql(DAGDB_OPERATIONAL_EVENT_TYPES_AND_RLS_EXPANSION_SCHEMA_SQL)
        .execute(&mut db.conn)
        .await
        .expect("apply PR #708 operational event/RLS schema inside rollback transaction");
    sqlx::raw_sql("ROLLBACK")
        .execute(&mut db.conn)
        .await
        .expect("rollback DAG DB schema transaction");

    let table_count: i64 = sqlx::query_scalar(
        "SELECT count(*) FROM information_schema.tables \
         WHERE table_schema = $1 AND table_name LIKE 'dagdb_%'",
    )
    .bind(&db.schema)
    .fetch_one(&mut db.conn)
    .await
    .expect("count tables after rollback");
    assert_eq!(table_count, 0);
}

#[tokio::test]
async fn init_pool_runs_registered_migrations_in_clean_schema() {
    let Some(db) = TestDb::maybe_new("init_pool_contract").await else {
        return;
    };
    let scoped_url = database_url_with_search_path(&db.database_url, &db.schema);
    let pool = init_pool(&scoped_url)
        .await
        .expect("init_pool must run registered DAG DB migrations");

    let table_count: i64 = sqlx::query_scalar(
        "SELECT count(*) FROM information_schema.tables \
         WHERE table_schema = current_schema() AND table_name LIKE 'dagdb_%'",
    )
    .fetch_one(&pool)
    .await
    .expect("count tables migrated through init_pool");
    assert_eq!(
        table_count,
        i64::try_from(EXPECTED_TABLES.len()).expect("expected table count fits i64")
    );

    pool.close().await;
}

#[tokio::test]
async fn pr708_migrator_upgrades_from_last_successful_deployed_ledger() {
    let Some(db) = TestDb::maybe_new("pr708_upgrade_contract").await else {
        return;
    };
    let pool = sqlx::postgres::PgPoolOptions::new()
        .max_connections(1)
        .connect(&db.database_url)
        .await
        .expect("connect upgrade regression pool");
    let last_successful_migration_dir =
        create_last_successful_deployed_migration_dir("pr708_upgrade_contract");
    let last_successful_migrator = Migrator::new(last_successful_migration_dir.as_path())
        .await
        .expect("load last successful deployed DAG DB migrations");

    run_migrator_in_schema(&pool, &last_successful_migrator, &db.schema).await;
    run_migrations_in_schema(&pool, &db.schema)
        .await
        .expect("PR #708 migrator must upgrade last successful deployed ledger");

    assert_recorded_versions(&pool, &db.schema, PR708_NEW_MIGRATION_VERSIONS).await;
    assert_tables_present(&pool, &db.schema, PR708_NEW_TENANT_RLS_TABLES).await;
    assert_schema_rls_forced(&pool, &db.schema, PR708_NEW_TENANT_RLS_TABLES).await;
    assert_operational_event_types_accepted(&pool, &db.schema).await;

    pool.close().await;
    fs::remove_dir_all(&last_successful_migration_dir)
        .expect("remove last successful deployed migration test directory");
}

async fn assert_tables(conn: &mut PgConnection) {
    let mut actual = sqlx::query_scalar::<_, String>(
        "SELECT table_name FROM information_schema.tables \
         WHERE table_schema = current_schema() AND table_name LIKE 'dagdb_%' \
         ORDER BY table_name",
    )
    .fetch_all(conn)
    .await
    .expect("query DAG DB tables");
    actual.sort();
    assert_eq!(actual, EXPECTED_TABLES);
}

async fn assert_required_columns(conn: &mut PgConnection) {
    for (table, columns) in expected_columns() {
        if columns.is_empty() {
            continue;
        }
        let actual = sqlx::query(
            "SELECT column_name, data_type, is_nullable, column_default \
             FROM information_schema.columns \
             WHERE table_schema = current_schema() AND table_name = $1 \
             ORDER BY ordinal_position",
        )
        .bind(table)
        .fetch_all(&mut *conn)
        .await
        .unwrap_or_else(|err| panic!("query columns for {table}: {err}"));

        let actual_names = actual
            .iter()
            .map(|row| row.get::<String, _>("column_name"))
            .collect::<Vec<_>>();
        let expected_names = columns
            .iter()
            .map(|column| column.name.to_owned())
            .collect::<Vec<_>>();
        assert_eq!(actual_names, expected_names, "column names for {table}");

        for expected in &columns {
            let row = actual
                .iter()
                .find(|row| row.get::<String, _>("column_name") == expected.name)
                .unwrap_or_else(|| panic!("missing column {}.{}", table, expected.name));
            assert_eq!(
                row.get::<String, _>("data_type"),
                expected.data_type,
                "data type for {table}.{}",
                expected.name
            );
            let nullable = row.get::<String, _>("is_nullable") == "YES";
            assert_eq!(
                nullable, expected.nullable,
                "nullability for {table}.{}",
                expected.name
            );
            if let Some(default) = expected.default_contains {
                let actual_default = row
                    .try_get::<String, _>("column_default")
                    .unwrap_or_default();
                assert!(
                    actual_default.contains(default),
                    "default for {table}.{} expected to contain {default}, got {actual_default:?}",
                    expected.name
                );
            }
        }
    }
}

async fn assert_constraints(conn: &mut PgConnection) {
    let constraints = sqlx::query(
        "SELECT rel.relname AS table_name, con.conname, con.contype, \
         pg_get_constraintdef(con.oid) AS definition \
         FROM pg_constraint con \
         JOIN pg_class rel ON rel.oid = con.conrelid \
         JOIN pg_namespace ns ON ns.oid = rel.relnamespace \
         WHERE ns.nspname = current_schema() AND rel.relname LIKE 'dagdb_%'",
    )
    .fetch_all(conn)
    .await
    .expect("query constraints");
    for (table, snippet) in expected_constraint_snippets() {
        assert!(
            constraints.iter().any(|row| {
                row.get::<String, _>("table_name") == *table
                    && row.get::<String, _>("definition").contains(snippet)
            }),
            "missing constraint snippet {snippet:?} on {table}"
        );
    }
}

async fn assert_indexes(conn: &mut PgConnection) {
    let rows = sqlx::query(
        "SELECT indexname, indexdef FROM pg_indexes \
         WHERE schemaname = current_schema() AND indexname LIKE '%dagdb%'",
    )
    .fetch_all(conn)
    .await
    .expect("query indexes");
    for (index_name, expected_fragment) in EXPECTED_INDEXES {
        let indexdef = rows
            .iter()
            .find(|row| row.get::<String, _>("indexname") == *index_name)
            .map(|row| row.get::<String, _>("indexdef"))
            .unwrap_or_else(|| panic!("missing index {index_name}"));
        assert!(
            indexdef.contains(expected_fragment),
            "index {index_name} expected fragment {expected_fragment:?}, got {indexdef:?}"
        );
    }
}

async fn assert_rls_catalog_state(conn: &mut PgConnection) {
    for table in EXPECTED_TENANT_RLS_TABLES {
        let row = sqlx::query(
            "SELECT relrowsecurity, relforcerowsecurity \
             FROM pg_class rel \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace \
             WHERE ns.nspname = current_schema() AND rel.relname = $1",
        )
        .bind(table)
        .fetch_one(&mut *conn)
        .await
        .unwrap_or_else(|err| panic!("query RLS flags for {table}: {err}"));
        assert!(
            row.get::<bool, _>("relrowsecurity"),
            "{table} must enable RLS"
        );
        assert!(
            row.get::<bool, _>("relforcerowsecurity"),
            "{table} must force RLS"
        );

        let policy = sqlx::query(
            "SELECT qual, with_check FROM pg_policies \
             WHERE schemaname = current_schema() AND tablename = $1 \
               AND policyname = 'dagdb_tenant_isolation'",
        )
        .bind(table)
        .fetch_one(&mut *conn)
        .await
        .unwrap_or_else(|err| panic!("query tenant RLS policy for {table}: {err}"));
        let qual = policy.get::<String, _>("qual").to_ascii_lowercase();
        let with_check = policy.get::<String, _>("with_check").to_ascii_lowercase();
        assert!(qual.contains("tenant_id = dagdb_current_tenant_id()"));
        assert!(with_check.contains("tenant_id = dagdb_current_tenant_id()"));
        assert!(!qual.contains("true"));
        assert!(!with_check.contains("true"));
    }
}

fn create_last_successful_deployed_migration_dir(label: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("exo_dagdb_{label}_{}", process::id()));
    if dir.exists() {
        fs::remove_dir_all(&dir).expect("remove stale last successful migration test directory");
    }
    fs::create_dir_all(&dir).expect("create last successful migration test directory");

    let source_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("migrations");
    for filename in LAST_SUCCESSFUL_DEPLOYED_MIGRATION_FILES {
        let source = source_dir.join(filename);
        let destination = dir.join(filename);
        let copied = fs::copy(&source, &destination)
            .unwrap_or_else(|err| panic!("copy migration {filename} into test directory: {err}"));
        assert!(copied > 0, "migration {filename} must not be empty");
    }

    dir
}

async fn run_migrator_in_schema(pool: &Pool<Postgres>, migrator: &Migrator, schema: &str) {
    sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {schema}"))
        .execute(pool)
        .await
        .expect("create migration test schema");
    let mut conn = pool.acquire().await.expect("acquire migration connection");
    sqlx::query(&format!("SET search_path TO {schema}, public"))
        .execute(&mut *conn)
        .await
        .expect("set migration search_path");
    migrator
        .run(&mut *conn)
        .await
        .expect("run test migrator in schema");
    conn.close()
        .await
        .expect("close migration-scoped connection");
}

async fn assert_recorded_versions(pool: &Pool<Postgres>, schema: &str, expected_versions: &[i64]) {
    let actual_versions: Vec<i64> = sqlx::query_scalar(&format!(
        "SELECT version FROM {schema}._sqlx_migrations ORDER BY version"
    ))
    .fetch_all(pool)
    .await
    .expect("query DAG DB migration ledger versions");
    for expected_version in expected_versions {
        assert!(
            actual_versions.contains(expected_version),
            "migration ledger must record version {expected_version}"
        );
    }
    assert_eq!(
        actual_versions.last().copied(),
        expected_versions.last().copied(),
        "PR #708 upgrade must leave the additive migration as the latest recorded DAG DB version"
    );
}

async fn assert_tables_present(pool: &Pool<Postgres>, schema: &str, tables: &[&str]) {
    for table in tables {
        let exists: bool = sqlx::query_scalar(
            "SELECT EXISTS ( \
             SELECT 1 FROM information_schema.tables \
             WHERE table_schema = $1 AND table_name = $2 \
             )",
        )
        .bind(schema)
        .bind(table)
        .fetch_one(pool)
        .await
        .unwrap_or_else(|err| panic!("query presence for table {table}: {err}"));
        assert!(exists, "PR #708 upgrade must create DAG DB table {table}");
    }
}

async fn assert_schema_rls_forced(pool: &Pool<Postgres>, schema: &str, tables: &[&str]) {
    for table in tables {
        let row = sqlx::query(
            "SELECT relrowsecurity, relforcerowsecurity \
             FROM pg_class rel \
             JOIN pg_namespace ns ON ns.oid = rel.relnamespace \
             WHERE ns.nspname = $1 AND rel.relname = $2",
        )
        .bind(schema)
        .bind(table)
        .fetch_one(pool)
        .await
        .unwrap_or_else(|err| panic!("query RLS state for upgraded table {table}: {err}"));
        assert!(
            row.get::<bool, _>("relrowsecurity"),
            "PR #708 upgrade must enable RLS on {table}"
        );
        assert!(
            row.get::<bool, _>("relforcerowsecurity"),
            "PR #708 upgrade must force RLS on {table}"
        );
    }
}

async fn assert_operational_event_types_accepted(pool: &Pool<Postgres>, schema: &str) {
    let mut conn = pool
        .acquire()
        .await
        .expect("acquire event insert connection");
    sqlx::query(&format!("SET search_path TO {schema}, public"))
        .execute(&mut *conn)
        .await
        .expect("set event insert search_path");
    let mut tx = conn.begin().await.expect("begin event insert transaction");
    bind_tenant_context(&mut tx, "tenant-pr708-upgrade")
        .await
        .expect("bind upgrade tenant context");
    for (index, event_type) in OPERATIONAL_RECEIPT_EVENT_TYPES.iter().enumerate() {
        insert_receipt_event_type_tx(&mut tx, index, event_type)
            .await
            .unwrap_or_else(|err| panic!("insert operational event type {event_type}: {err}"));
    }
    tx.commit().await.expect("commit event insert transaction");
    conn.close().await.expect("close event insert connection");
}

async fn insert_receipt_event_type_tx(
    tx: &mut Transaction<'_, Postgres>,
    index: usize,
    event_type: &str,
) -> std::result::Result<(), sqlx::Error> {
    let seed = u8::try_from(index + 1).expect("operational event fixture index fits u8");
    sqlx::query(
        "INSERT INTO dagdb_receipts \
         (receipt_hash, tenant_id, namespace, subject_kind, subject_id, prev_receipt_hash, seq, \
          event_type, actor_did, event_hlc_physical_ms, event_hlc_logical, event_hash, \
          receipt_body, created_at_physical_ms, created_at_logical) \
         VALUES ($1, 'tenant-pr708-upgrade', 'dag-db', 'memory', $2, $3, $4, $5, \
                 'did:exo:pr708-upgrade-regression', 1, 0, $6, $7, 1, 0)",
    )
    .bind(vec![seed; 32])
    .bind(vec![seed.saturating_add(32); 32])
    .bind(vec![seed.saturating_add(64); 32])
    .bind(i64::try_from(index + 1).expect("operational event fixture sequence fits i64"))
    .bind(event_type)
    .bind(vec![seed.saturating_add(96); 32])
    .bind(serde_json::json!({ "event_type": event_type }))
    .execute(&mut **tx)
    .await?;
    Ok(())
}

async fn assume_rls_checked_role(conn: &mut PgConnection, schema: &str) -> Option<String> {
    let bypasses_rls: bool = sqlx::query_scalar(
        "SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user",
    )
    .fetch_one(&mut *conn)
    .await
    .expect("query current role RLS bypass state");
    if !bypasses_rls {
        return None;
    }

    let role_name = format!("dagdb_rls_test_{}", process::id());
    sqlx::raw_sql(&format!("DROP ROLE IF EXISTS {role_name}"))
        .execute(&mut *conn)
        .await
        .expect("drop stale RLS test role");
    sqlx::raw_sql(&format!("CREATE ROLE {role_name}"))
        .execute(&mut *conn)
        .await
        .expect("create RLS test role");
    sqlx::raw_sql(&format!("GRANT USAGE ON SCHEMA {schema} TO {role_name}"))
        .execute(&mut *conn)
        .await
        .expect("grant schema usage to RLS test role");
    sqlx::raw_sql(&format!(
        "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA {schema} TO {role_name}"
    ))
    .execute(&mut *conn)
    .await
    .expect("grant table privileges to RLS test role");
    sqlx::raw_sql(&format!(
        "GRANT EXECUTE ON FUNCTION {schema}.dagdb_current_tenant_id() TO {role_name}"
    ))
    .execute(&mut *conn)
    .await
    .expect("grant tenant helper execution to RLS test role");
    sqlx::raw_sql(&format!("SET ROLE {role_name}"))
        .execute(conn)
        .await
        .expect("switch to RLS test role");
    Some(role_name)
}

async fn cleanup_rls_checked_role(conn: &mut PgConnection, role_name: &str) {
    sqlx::raw_sql("RESET ROLE")
        .execute(&mut *conn)
        .await
        .expect("reset RLS test role");
    sqlx::raw_sql(&format!("DROP OWNED BY {role_name}"))
        .execute(&mut *conn)
        .await
        .expect("drop RLS test role privileges");
    sqlx::raw_sql(&format!("DROP ROLE IF EXISTS {role_name}"))
        .execute(conn)
        .await
        .expect("drop RLS test role");
}

async fn insert_idempotency_fixture_tx(
    tx: &mut Transaction<'_, Postgres>,
    tenant_id: &str,
    idempotency_key: &str,
) -> std::result::Result<(), sqlx::Error> {
    sqlx::query(
        "INSERT INTO dagdb_idempotency_keys \
         (tenant_id, namespace, route_name, idempotency_key, request_hash, response_hash, response_body, \
          status_code, cached_failure, created_at_physical_ms, created_at_logical, \
          expires_at_physical_ms, expires_at_logical) \
         VALUES ($1, 'dag-db', 'rls-test', $2, $3, $4, $5, 201, false, 1, 0, 2, 0)",
    )
    .bind(tenant_id)
    .bind(idempotency_key)
    .bind(vec![1_u8; 32])
    .bind(vec![2_u8; 32])
    .bind(serde_json::json!({"fixture": "rls"}))
    .execute(&mut **tx)
    .await?;
    Ok(())
}

async fn insert_idempotency_fixture_conn(
    conn: &mut PgConnection,
    tenant_id: &str,
    idempotency_key: &str,
) -> std::result::Result<(), sqlx::Error> {
    sqlx::query(
        "INSERT INTO dagdb_idempotency_keys \
         (tenant_id, namespace, route_name, idempotency_key, request_hash, response_hash, response_body, \
          status_code, cached_failure, created_at_physical_ms, created_at_logical, \
          expires_at_physical_ms, expires_at_logical) \
         VALUES ($1, 'dag-db', 'rls-test', $2, $3, $4, $5, 201, false, 1, 0, 2, 0)",
    )
    .bind(tenant_id)
    .bind(idempotency_key)
    .bind(vec![1_u8; 32])
    .bind(vec![2_u8; 32])
    .bind(serde_json::json!({"fixture": "rls"}))
    .execute(conn)
    .await?;
    Ok(())
}

async fn idempotency_count_tx(
    tx: &mut Transaction<'_, Postgres>,
    tenant_id: &str,
) -> std::result::Result<i64, sqlx::Error> {
    sqlx::query_scalar(
        "SELECT count(*) FROM dagdb_idempotency_keys \
         WHERE tenant_id = $1 AND namespace = 'dag-db' AND route_name = 'rls-test'",
    )
    .bind(tenant_id)
    .fetch_one(&mut **tx)
    .await
}

async fn idempotency_count_conn(
    conn: &mut PgConnection,
    tenant_id: &str,
) -> std::result::Result<i64, sqlx::Error> {
    sqlx::query_scalar(
        "SELECT count(*) FROM dagdb_idempotency_keys \
         WHERE tenant_id = $1 AND namespace = 'dag-db' AND route_name = 'rls-test'",
    )
    .bind(tenant_id)
    .fetch_one(conn)
    .await
}

fn expected_constraint_snippets() -> &'static [(&'static str, &'static str)] {
    &[
        ("dagdb_receipts", "octet_length(receipt_hash) = 32"),
        ("dagdb_receipts", "subject_kind = ANY"),
        ("dagdb_receipts", "dagdb_export_completed"),
        ("dagdb_root_bundle_receipts", "octet_length(bundle_id) = 32"),
        (
            "dagdb_root_bundle_receipts",
            "octet_length(root_bundle_hash) = 32",
        ),
        (
            "dagdb_root_bundle_receipts",
            "octet_length(verification_receipt_hash) = 32",
        ),
        ("dagdb_root_bundle_receipts", "immutable = true"),
        ("dagdb_memory_objects", "node_type = ANY"),
        ("dagdb_memory_objects", "source_type = ANY"),
        ("dagdb_memory_objects", "consent_purpose = ANY"),
        ("dagdb_memory_objects", "risk_bp >= 0"),
        ("dagdb_memory_edges", "edge_type = ANY"),
        ("dagdb_route_receipts", "token_budget > 0"),
        ("dagdb_validation_reports", "decision = ANY"),
        (
            "dagdb_agent_safety_scores",
            "window_end_physical_ms > window_start_physical_ms",
        ),
        ("dagdb_inbound_agent_credentials", "credential_status = ANY"),
        ("dagdb_council_decisions", "decision_source = ANY"),
        ("dagdb_idempotency_keys", "cached_failure = false"),
        ("dagdb_dag_outbox", "max_attempts = 6"),
        ("dagdb_benchmark_runs", "runner_name = ANY"),
        (
            "dagdb_exports",
            "schema_version = 'dagdb_kg_portable_export_v1'",
        ),
        ("dagdb_exports", "export_status = ANY"),
        ("dagdb_export_challenges", "challenge_kind = ANY"),
        (
            "dagdb_export_challenges",
            "proof_algorithm = 'hash_commitment_v1'",
        ),
        ("dagdb_graph_nodes", "graph_style = ANY"),
        ("dagdb_graph_nodes", "node_kind = ANY"),
        ("dagdb_graph_edges", "edge_kind = ANY"),
        ("dagdb_graph_edge_tombstones", "recommended_action = ANY"),
        ("dagdb_graph_layers", "layer_kind = ANY"),
        ("dagdb_graph_layers", "graph_style = ANY"),
        ("dagdb_graph_layers", "layer_depth >= 0"),
        ("dagdb_graph_layer_memberships", "membership_role = ANY"),
        ("dagdb_graph_layer_memberships", "local_node_rank >= 0"),
        ("dagdb_graph_layer_edges", "edge_kind = ANY"),
        ("dagdb_graph_similarity_results", "similarity_bp >= 0"),
        (
            "dagdb_graph_canonicalization_decisions",
            "decision_kind = ANY",
        ),
        ("dagdb_graph_views", "view_type = ANY"),
        ("dagdb_graph_route_invalidations", "trigger_type = ANY"),
        ("dagdb_graph_route_invalidations", "new_route_status = ANY"),
    ]
}

#[derive(Debug, Clone, Copy)]
struct ColumnExpectation {
    name: &'static str,
    data_type: &'static str,
    nullable: bool,
    default_contains: Option<&'static str>,
}

const fn col(
    name: &'static str,
    data_type: &'static str,
    nullable: bool,
    default_contains: Option<&'static str>,
) -> ColumnExpectation {
    ColumnExpectation {
        name,
        data_type,
        nullable,
        default_contains,
    }
}

fn expected_columns() -> Vec<(&'static str, Vec<ColumnExpectation>)> {
    vec![
        (
            "dagdb_receipts",
            vec![
                col("receipt_hash", "bytea", false, None),
                col("tenant_id", "text", false, None),
                col("namespace", "text", false, None),
                col("subject_kind", "text", false, None),
                col("subject_id", "bytea", false, None),
                col("prev_receipt_hash", "bytea", false, None),
                col("seq", "bigint", false, None),
                col("event_type", "text", false, None),
                col("actor_did", "text", false, None),
                col("event_hlc_physical_ms", "bigint", false, None),
                col("event_hlc_logical", "integer", false, None),
                col("event_hash", "bytea", false, None),
                col("receipt_body", "jsonb", false, None),
                col("created_at_physical_ms", "bigint", false, None),
                col("created_at_logical", "integer", false, None),
            ],
        ),
        (
            "dagdb_root_bundle_receipts",
            vec![
                col("bundle_id", "bytea", false, None),
                col("root_bundle_hash", "bytea", false, None),
                col("ceremony_id", "text", false, None),
                col("issuer_did", "text", false, None),
                col("issuer_public_key_hash", "bytea", false, None),
                col("signing_set_hash", "bytea", false, None),
                col("quorum_threshold", "integer", false, None),
                col("verifier_version", "text", false, None),
                col("verification_receipt_hash", "bytea", false, None),
                col("verification_receipt_body", "jsonb", false, None),
                col("verified_at_physical_ms", "bigint", false, None),
                col("verified_at_logical", "integer", false, None),
                col("created_at_physical_ms", "bigint", false, None),
                col("created_at_logical", "integer", false, None),
                col("immutable", "boolean", false, Some("true")),
            ],
        ),
        (
            "dagdb_memory_objects",
            vec![
                col("memory_id", "bytea", false, None),
                col("tenant_id", "text", false, None),
                col("namespace", "text", false, None),
                col("node_type", "text", false, None),
                col("source_type", "text", false, None),
                col("consent_purpose", "text", false, None),
                col("payload_hash", "bytea", false, None),
                col("source_hash", "bytea", false, None),
                col("payload_uri_hash", "bytea", true, None),
                col("owner_did", "text", false, None),
                col("controller_did", "text", false, None),
                col("submitted_by_did", "text", false, None),
                col("access_policy_hash", "bytea", true, None),
                col("declared_rights_hash", "bytea", true, None),
                col("title", "jsonb", false, None),
                col("summary", "jsonb", false, None),
                col("keywords", "jsonb", false, Some("'[]'::jsonb")),
                col("risk_class", "text", false, None),
                col("risk_bp", "integer", false, None),
                col("status", "text", false, Some("'pending'::text")),
                col("validation_status", "text", false, Some("'pending'::text")),
                col(
                    "council_status",
                    "text",
                    false,
                    Some("'not_required'::text"),
                ),
                col(
                    "dag_finality_status",
                    "text",
                    false,
                    Some("'pending'::text"),
                ),
                col("latest_receipt_hash", "bytea", false, None),
                col("created_at_physical_ms", "bigint", false, None),
                col("created_at_logical", "integer", false, None),
                col("updated_at_physical_ms", "bigint", false, None),
                col("updated_at_logical", "integer", false, None),
                col("revoked_at_physical_ms", "bigint", true, None),
                col("revoked_at_logical", "integer", true, None),
                col("superseded_by_memory_id", "bytea", true, None),
                // PRD-D3 (D3-S1): nullable deep-detail-summary tier, appended by
                // the strictly-additive migration (highest ordinal position).
                col("deep_detail_summary", "jsonb", true, None),
            ],
        ),
        (
            "dagdb_inbound_agent_credentials",
            vec![
                col("credential_id", "bytea", false, None),
                col("tenant_id", "text", false, None),
                col("namespace", "text", false, None),
                col("agent_did", "text", false, None),
                col("operator_did", "text", false, None),
                col("model_name", "text", false, None),
                col("model_version", "text", false, None),
                col("provider_or_builder", "text", false, None),
                col("requested_action", "text", false, None),
                col("requested_scope_hash", "bytea", false, None),
                col("purpose", "text", false, None),
                col("autonomy_level", "text", false, None),
                col("nonce", "text", false, None),
                col("expires_at_physical_ms", "bigint", false, None),
                col("expires_at_logical", "integer", false, None),
                col("signature_hash", "bytea", false, None),
                col("credential_status", "text", false, Some("'pending'::text")),
                col("checkpoint_hash", "bytea", true, None),
                col("attestation_hash", "bytea", true, None),
                col("prior_trust_receipt_hash", "bytea", true, None),
                col("created_at_physical_ms", "bigint", false, None),
                col("created_at_logical", "integer", false, None),
            ],
        ),
        ("dagdb_subject_receipt_heads", Vec::new()),
        ("dagdb_memory_edges", Vec::new()),
        ("dagdb_catalog_entries", Vec::new()),
        ("dagdb_route_receipts", Vec::new()),
        ("dagdb_context_packets", Vec::new()),
        ("dagdb_validation_reports", Vec::new()),
        ("dagdb_agent_safety_scores", Vec::new()),
        ("dagdb_council_decisions", Vec::new()),
        ("dagdb_idempotency_keys", Vec::new()),
        ("dagdb_dag_outbox", Vec::new()),
        ("dagdb_benchmark_runs", Vec::new()),
        ("dagdb_exports", Vec::new()),
        ("dagdb_export_challenges", Vec::new()),
        ("dagdb_graph_nodes", Vec::new()),
        ("dagdb_graph_edges", Vec::new()),
        ("dagdb_graph_edge_tombstones", Vec::new()),
        ("dagdb_graph_layer_edges", Vec::new()),
        ("dagdb_graph_layer_memberships", Vec::new()),
        ("dagdb_graph_layers", Vec::new()),
        ("dagdb_graph_similarity_results", Vec::new()),
        ("dagdb_graph_canonicalization_decisions", Vec::new()),
        ("dagdb_graph_views", Vec::new()),
        ("dagdb_graph_placement_traces", Vec::new()),
        ("dagdb_graph_route_invalidations", Vec::new()),
    ]
}

fn database_url_with_search_path(database_url: &str, schema: &str) -> String {
    let separator = if database_url.contains('?') { '&' } else { '?' };
    format!("{database_url}{separator}options=-csearch_path%3D{schema}%2Cpublic")
}

struct TestDb {
    conn: PgConnection,
    schema: String,
    database_url: String,
}

impl TestDb {
    async fn maybe_new(label: &str) -> Option<Self> {
        let Ok(database_url) = std::env::var("EXO_DAGDB_TEST_DATABASE_URL") else {
            eprintln!("skipping migration postgres test: EXO_DAGDB_TEST_DATABASE_URL is not set");
            return None;
        };
        let schema = format!("dagdb_{label}_{}", process::id());
        let mut conn = PgConnection::connect(database_url.as_str())
            .await
            .expect("connect to EXO_DAGDB_TEST_DATABASE_URL");
        sqlx::raw_sql(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE"))
            .execute(&mut conn)
            .await
            .expect("drop existing test schema");
        sqlx::raw_sql(&format!("CREATE SCHEMA {schema}"))
            .execute(&mut conn)
            .await
            .expect("create test schema");
        let mut db = Self {
            conn,
            schema,
            database_url,
        };
        db.set_search_path().await;
        Some(db)
    }

    async fn set_search_path(&mut self) {
        sqlx::raw_sql(&format!("SET search_path TO {}, public", self.schema))
            .execute(&mut self.conn)
            .await
            .expect("set DAG DB test search_path");
    }

    async fn apply_schema(&mut self) {
        self.set_search_path().await;
        sqlx::raw_sql(DAGDB_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply DAG DB schema");
        sqlx::raw_sql(DAGDB_GRAPH_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply DAG DB graph schema");
        sqlx::raw_sql(DAGDB_EXPORT_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply DAG DB export schema");
        sqlx::raw_sql(DAGDB_PRD17_DEFAULT_ROUTE_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply PRD17 default-route schema");
        sqlx::raw_sql(DAGDB_PRD17_CONTEXT_PACKET_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply PRD17 context-packet schema");
        sqlx::raw_sql(DAGDB_PRD17_LIFECYCLE_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply PRD17 lifecycle schema");
        sqlx::raw_sql(DAGDB_TENANT_RLS_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply DAG DB tenant RLS schema");
        sqlx::raw_sql(DAGDB_OPERATIONAL_EVENT_TYPES_AND_RLS_EXPANSION_SCHEMA_SQL)
            .execute(&mut self.conn)
            .await
            .expect("apply PR #708 operational event/RLS schema");
    }
}

impl Drop for TestDb {
    fn drop(&mut self) {
        let schema = self.schema.clone();
        let database_url = self.database_url.clone();
        std::thread::spawn(move || {
            let runtime = tokio::runtime::Runtime::new().expect("create cleanup runtime");
            runtime.block_on(async move {
                let mut conn = PgConnection::connect(&database_url)
                    .await
                    .expect("connect for cleanup");
                sqlx::raw_sql(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE"))
                    .execute(&mut conn)
                    .await
                    .expect("drop DAG DB test schema");
            });
        })
        .join()
        .expect("join cleanup thread");
    }
}