udb 0.2.0

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

use serde::Serialize;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::{
    Arc,
    atomic::{AtomicU64, Ordering},
};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

#[cfg(feature = "s3")]
use aws_config::BehaviorVersion;
#[cfg(feature = "s3")]
use aws_sdk_s3::config::{Credentials, Region};
#[cfg(feature = "s3")]
use aws_sdk_s3::presigning::PresigningConfig;
#[cfg(feature = "s3")]
use aws_sdk_s3::primitives::ByteStream;
use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
// prost_types imported transitively via executor_utils::*
#[cfg(feature = "kafka")]
use rdkafka::ClientConfig;
#[cfg(feature = "kafka")]
use rdkafka::consumer::{BaseConsumer, Consumer};
#[cfg(feature = "redis")]
use redis::AsyncCommands;
// reqwest::StatusCode used via executor_utils::qdrant_status re-export
use serde_json::Value as JsonValue;
use sha2::{Digest, Sha256};
// sha2 re-exported transitively via executor_utils; no direct use in core.rs
use sqlx::postgres::{PgPoolOptions, PgRow};
// sqlx::query::Query used via postgres_helpers::bind_values re-export
use sqlx::{Column, Executor, PgPool, Row, TypeInfo};
use tokio_stream::StreamExt;
use uuid::Uuid;

use crate::broker::{
    DeletePlanRequest, RequestContext, SelectPlanRequest, SortSpec, UpsertPlanRequest,
    build_delete_plan, build_select_query_plan, build_upsert_plan, table_for_message,
};
#[cfg(feature = "s3")]
use crate::broker::{
    ObjectAccessRequest, ObjectStreamPlanRequest, build_object_stream_plan, evaluate_object_access,
};
#[cfg(feature = "qdrant")]
use crate::broker::{
    VectorSearchPlanRequest, VectorUpsertPlanRequest, build_vector_search_plan,
    build_vector_upsert_plan,
};
use crate::generation::{CatalogManifest, GeneratedArtifact, ManifestStore, ManifestTable};
use crate::proto::{
    CdcEnvelope, CdcSubscriptionRequest, Chunk, MultipartUploadRequest, MultipartUploadResponse,
    Mutation, MutationResponse, RecordSet, Row as ProtoRow, SelectRequest, TxStatus, UpsertRequest,
    UrlRequest, UrlResponse, VectorHybridSearchRequest, VectorSearchRequest, VectorSet,
    VectorUpsertRequest, ViewDefinition,
};
use crate::security::{AbacPolicy, PolicyEffect};

#[cfg(feature = "s3")]
use super::config::MinioConfig;
#[cfg(feature = "redis")]
use super::config::RedisConfig;
use super::config::{
    BackendInstance, BackendInstanceConfig, BackendInstanceRole, DbConfig, UdbConfig,
};
use super::connection_manager::ConnectionManager;
use super::encryption::EncryptionRuntime;
use super::executor_utils::*;
#[cfg(feature = "clickhouse")]
use super::executors::clickhouse::ClickHouseConfig;
#[cfg(feature = "clickhouse")]
use super::executors::clickhouse::ClickHouseExecutor;
#[cfg(feature = "mongodb")]
use super::executors::mongodb::MongoDbConfig;
#[cfg(feature = "mongodb")]
use super::executors::mongodb::MongoDbExecutor;
#[cfg(feature = "mongodb-native")]
use super::executors::mongodb::MongoDbNativeConfig;
#[cfg(feature = "neo4j")]
use super::executors::neo4j::Neo4jConfig;
#[cfg(feature = "neo4j")]
use super::executors::neo4j::Neo4jExecutor;
// PostgresExecutor / S3Executor are now constructed by their respective
// `DispatchFactory` plugin impls (U2 step 5), not directly here.
#[cfg(feature = "qdrant")]
use super::executors::qdrant::{QdrantExecutor, QdrantHttpClient};
use super::executors::{BackendExecutorRegistration, BackendExecutorRegistry};
// `DefaultBackendExecutor` was deleted in U2 step 6; `backend_executor()` now
// returns a typed `ResolvedExecutorTarget` and the live dispatch executor is
// built via `resolve_dispatch_executor` (plugin-keyed).
use super::postgres_helpers::*;
use super::replica::{
    PgReplicaManager, PgReplicaPool, PgReplicaSnapshot, PgReplicaStrategy, append_application_name,
};
use super::system::{
    SystemCatalogInspection, SystemCatalogReport, ensure_system_catalog, inspect_system_catalog,
};
#[cfg(feature = "s3")]
const GET_OBJECT_CHUNK_BYTES: usize = 256 * 1024;

#[derive(Debug, Clone, Default)]
pub struct RuntimeInitReport {
    pub postgres_configured: bool,
    pub redis_configured: bool,
    pub qdrant_configured: bool,
    pub s3_configured: bool,
    pub encryption_configured: bool,
    pub mongodb_configured: bool,
    pub neo4j_configured: bool,
    pub clickhouse_configured: bool,
    /// NW3-1: MySQL primary configured via UDB_MYSQL_DSN.
    pub mysql_configured: bool,
    /// NW3-2: SQLite primary configured via UDB_SQLITE_DSN (or
    /// `sqlite::memory:` for the test profile).
    pub sqlite_configured: bool,
    /// C9: Elasticsearch primary configured via UDB_ELASTIC_DSN.
    pub elasticsearch_configured: bool,
    /// C9: Memcached primary configured via UDB_MEMCACHED_DSN.
    pub memcached_configured: bool,
    /// C9: SQL Server primary configured via UDB_MSSQL_DSN.
    pub mssql_configured: bool,
    /// C9: Weaviate primary configured via UDB_WEAVIATE_DSN.
    pub weaviate_configured: bool,
    /// C9: Pinecone primary configured via UDB_PINECONE_DSN.
    pub pinecone_configured: bool,
    /// C9: Cassandra primary configured via UDB_CASSANDRA_DSN.
    pub cassandra_configured: bool,
    /// C9: Azure Blob primary configured via UDB_AZUREBLOB_DSN.
    pub azureblob_configured: bool,
    /// C9: GCS primary configured via UDB_GCS_DSN.
    pub gcs_configured: bool,
    pub backend_instances: Vec<RuntimeBackendInstance>,
    pub warnings: Vec<String>,
}

/// PostgreSQL privilege check results used by `doctor` and `GetHealthReport`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct PostgresPrivilegeReport {
    /// Whether the privilege checks were actually executed (false if PG not configured).
    pub checked: bool,
    /// Role has CREATE privilege on the current database (needed to create schemas).
    pub create_schema: bool,
    /// Role has CREATE privilege on at least one relevant schema (for tables).
    pub create_table: bool,
    /// Role has superuser, replication, or pg_publication_admin membership
    /// (needed for CREATE PUBLICATION).
    pub create_publication: bool,
    /// Role has superuser or replication role (needed for logical replication slots).
    pub replication_slot: bool,
    /// Role can successfully acquire a session-level advisory lock.
    pub advisory_lock: bool,
    /// Non-fatal errors encountered during privilege checks.
    pub errors: Vec<String>,
}

/// Liveness probe result for a single backend.
#[derive(Debug, Clone, Serialize)]
pub struct BackendProbeResult {
    pub backend: String,
    pub ok: bool,
    pub latency_ms: u64,
    pub error: Option<String>,
}

/// Redacted runtime view of a configured backend instance.
#[derive(Debug, Clone, Serialize)]
pub struct RuntimeBackendInstance {
    pub name: String,
    pub backend: String,
    pub role: String,
    pub enabled: bool,
    pub configured: bool,
    pub connected: bool,
    pub read_weight: u32,
    pub write_weight: u32,
    pub dsn_env: Option<String>,
    pub labels: HashMap<String, String>,
    pub capabilities: Vec<String>,
    pub healthy: bool,
    pub circuit_open: bool,
}

/// Canonical runtime routing target parsed from a backend selector.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedBackendSelector {
    pub backend: String,
    pub instance: Option<String>,
}

/// Resolved dispatch target — what `backend_executor()` returns after the
/// registry/connectivity/circuit-breaker checks (U2 step 6 replacement for
/// the former `DefaultBackendExecutor` adapter struct). Combine with
/// `resolve_dispatch_executor` to obtain the live executor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedExecutorTarget {
    pub backend: String,
    pub instance: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct DataBrokerRuntime {
    pg_pool: Option<PgPool>,
    /// Named PostgreSQL pools for generic instance-aware routing.
    pg_instances: HashMap<String, PgPool>,
    /// NW3-1: MySQL primary pool. Mirrors `pg_pool` for the MySQL
    /// backend. None means no MySQL is configured.
    #[cfg(feature = "mysql")]
    pub(crate) mysql_pool: Option<sqlx::MySqlPool>,
    #[cfg(feature = "mysql")]
    pub(crate) mysql_instances: HashMap<String, sqlx::MySqlPool>,
    /// NW3-2: SQLite primary pool.
    #[cfg(feature = "sqlite")]
    pub(crate) sqlite_pool: Option<sqlx::SqlitePool>,
    #[cfg(feature = "sqlite")]
    pub(crate) sqlite_instances: HashMap<String, sqlx::SqlitePool>,
    /// Optional read-replica pools — used for SELECT queries when healthy.
    pg_replicas: PgReplicaManager,
    #[cfg(feature = "redis")]
    redis: Option<redis::Client>,
    #[cfg(feature = "redis")]
    redis_instances: HashMap<String, redis::Client>,
    #[cfg(feature = "qdrant")]
    qdrant: Option<QdrantHttpClient>,
    #[cfg(feature = "qdrant")]
    qdrant_instances: HashMap<String, QdrantHttpClient>,
    /// C9: Elasticsearch primary client (`UDB_ELASTIC_DSN` deployment).
    #[cfg(feature = "elasticsearch")]
    pub(crate) elasticsearch:
        Option<crate::runtime::executors::elasticsearch::ElasticsearchHttpClient>,
    #[cfg(feature = "elasticsearch")]
    pub(crate) elasticsearch_instances:
        HashMap<String, crate::runtime::executors::elasticsearch::ElasticsearchHttpClient>,
    /// C9: Memcached primary client (`UDB_MEMCACHED_DSN` deployment).
    /// Real binary-protocol driver via the `memcache` crate.
    #[cfg(feature = "memcached")]
    pub(crate) memcached: Option<crate::runtime::executors::memcached::MemcachedClient>,
    #[cfg(feature = "memcached")]
    pub(crate) memcached_instances:
        HashMap<String, crate::runtime::executors::memcached::MemcachedClient>,
    /// C9: SQL Server primary client (`UDB_MSSQL_DSN` deployment).
    /// Real TDS-protocol driver via tiberius; lazy connect.
    #[cfg(feature = "mssql")]
    pub(crate) mssql: Option<crate::runtime::executors::mssql::MssqlClient>,
    #[cfg(feature = "mssql")]
    pub(crate) mssql_instances: HashMap<String, crate::runtime::executors::mssql::MssqlClient>,
    /// C9: Weaviate (REST + GraphQL via reqwest).
    #[cfg(feature = "weaviate")]
    pub(crate) weaviate: Option<crate::runtime::executors::weaviate::WeaviateHttpClient>,
    #[cfg(feature = "weaviate")]
    pub(crate) weaviate_instances:
        HashMap<String, crate::runtime::executors::weaviate::WeaviateHttpClient>,
    /// C9: Pinecone (REST via reqwest).
    #[cfg(feature = "pinecone")]
    pub(crate) pinecone: Option<crate::runtime::executors::pinecone::PineconeHttpClient>,
    #[cfg(feature = "pinecone")]
    pub(crate) pinecone_instances:
        HashMap<String, crate::runtime::executors::pinecone::PineconeHttpClient>,
    /// C9: Cassandra / ScyllaDB session via the `scylla` driver.
    #[cfg(feature = "cassandra")]
    pub(crate) cassandra: Option<crate::runtime::executors::cassandra::CassandraClient>,
    #[cfg(feature = "cassandra")]
    pub(crate) cassandra_instances:
        HashMap<String, crate::runtime::executors::cassandra::CassandraClient>,
    /// C9: Azure Blob Storage SDK client.
    #[cfg(feature = "azureblob")]
    pub(crate) azureblob: Option<crate::runtime::executors::azureblob::AzureBlobClient>,
    #[cfg(feature = "azureblob")]
    pub(crate) azureblob_instances:
        HashMap<String, crate::runtime::executors::azureblob::AzureBlobClient>,
    /// C9: Google Cloud Storage SDK client.
    #[cfg(feature = "gcs")]
    pub(crate) gcs: Option<crate::runtime::executors::gcs::GcsClient>,
    #[cfg(feature = "gcs")]
    pub(crate) gcs_instances: HashMap<String, crate::runtime::executors::gcs::GcsClient>,
    #[cfg(feature = "s3")]
    s3: Option<aws_sdk_s3::Client>,
    #[cfg(feature = "s3")]
    s3_instances: HashMap<String, aws_sdk_s3::Client>,
    encryption: Option<EncryptionRuntime>,
    #[cfg(feature = "mongodb")]
    mongodb: Option<MongoDbExecutor>,
    #[cfg(feature = "mongodb")]
    mongodb_instances: HashMap<String, MongoDbExecutor>,
    #[cfg(feature = "neo4j")]
    neo4j: Option<Neo4jExecutor>,
    #[cfg(feature = "neo4j")]
    neo4j_instances: HashMap<String, Neo4jExecutor>,
    #[cfg(feature = "clickhouse")]
    clickhouse: Option<ClickHouseExecutor>,
    #[cfg(feature = "clickhouse")]
    clickhouse_instances: HashMap<String, ClickHouseExecutor>,
    connections: ConnectionManager,
    backend_instances: Vec<RuntimeBackendInstance>,
    circuit_breakers: Arc<Mutex<HashMap<String, CircuitBreakerState>>>,
    routing_counters: Arc<Mutex<HashMap<String, u64>>>,
    executor_registry: BackendExecutorRegistry,
    report: RuntimeInitReport,
    config: UdbConfig,
    cache_metrics: CacheMetrics,
    encryption_metrics: EncryptionMetrics,
    channels: super::channels::ChannelManager,
    /// NW1-2: pluggable canonical-store registry. Each
    /// canonical-class backend (PG/MySQL/SQLite/Mongo) registers
    /// itself at startup; downstream system-table call sites
    /// (NW1 step 3+) route through this rather than direct PgPool.
    /// Wrapped in `Arc<Mutex<…>>` so config reload can rebuild the
    /// registry without mutating the snapshot held by in-flight
    /// requests — the swap is atomic at the `Arc` level.
    canonical_stores: Arc<Mutex<crate::runtime::canonical_store::CanonicalStoreRegistry>>,
}

impl DataBrokerRuntime {
    /// NW1-2: snapshot accessor. Returns the current registry by
    /// cloning the Arc-Mutex view (Mutex on the registry itself is
    /// only held briefly to clone the `HashMap`-backed registry).
    pub fn canonical_stores(&self) -> crate::runtime::canonical_store::CanonicalStoreRegistry {
        self.canonical_stores
            .lock()
            .map(|g| g.clone())
            .unwrap_or_default()
    }

    /// NW1-2: register a canonical store at runtime. Called during
    /// startup once per discovered canonical-class backend
    /// (today: Postgres). Idempotent — re-registering the same key
    /// replaces the previous entry.
    pub(crate) fn register_canonical_store(
        &self,
        store: Arc<dyn crate::runtime::canonical_store::CanonicalStore>,
    ) {
        if let Ok(mut guard) = self.canonical_stores.lock() {
            guard.register(store);
        }
    }

    /// NW1-2: look up the default canonical store. Returns `None` if
    /// no canonical store is registered (slim deployments without
    /// Postgres / MySQL / SQLite).
    pub fn default_canonical_store(
        &self,
    ) -> Option<Arc<dyn crate::runtime::canonical_store::CanonicalStore>> {
        self.canonical_stores.lock().ok()?.default_store()
    }

    /// NW1-3: register a store that satisfies every system-store
    /// trait. The supervisor calls this once per canonical-class
    /// backend at startup.
    pub(crate) fn register_full_canonical_store(
        &self,
        store: Arc<dyn crate::runtime::canonical_store::SystemStores>,
    ) {
        if let Ok(mut guard) = self.canonical_stores.lock() {
            guard.register_full(store);
        }
    }

    /// NW1-3: the rich-view default store. NW1 step 3+ call sites
    /// (consistency_fence, projection worker, saga worker, audit
    /// writers) pull this once and call whichever system-store
    /// methods they need.
    pub fn default_system_stores(
        &self,
    ) -> Option<Arc<dyn crate::runtime::canonical_store::SystemStores>> {
        self.canonical_stores.lock().ok()?.default_full_store()
    }
}

#[derive(Debug, Clone, Default)]
struct CircuitBreakerState {
    failures: u32,
    opened_until: Option<Instant>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CircuitBreakerSnapshot {
    pub backend: String,
    pub instance: String,
    pub failure_count: u32,
    pub open: bool,
    pub opened_until_unix_ms: i64,
}

#[derive(Debug, Clone, Default)]
pub struct CacheMetricSnapshot {
    pub udb_cache_hit_total: u64,
    pub udb_cache_miss_total: u64,
    pub udb_cache_invalidation_total: u64,
}

#[derive(Debug, Clone, Default)]
struct CacheMetrics {
    hit_total: Arc<AtomicU64>,
    miss_total: Arc<AtomicU64>,
    invalidation_total: Arc<AtomicU64>,
}

impl CacheMetrics {
    #[cfg(feature = "redis")]
    fn hit(&self) {
        self.hit_total.fetch_add(1, Ordering::Relaxed);
    }

    #[cfg(feature = "redis")]
    fn miss(&self) {
        self.miss_total.fetch_add(1, Ordering::Relaxed);
    }

    #[cfg(feature = "redis")]
    fn invalidated(&self, count: u64) {
        self.invalidation_total.fetch_add(count, Ordering::Relaxed);
    }

    fn snapshot(&self) -> CacheMetricSnapshot {
        CacheMetricSnapshot {
            udb_cache_hit_total: self.hit_total.load(Ordering::Relaxed),
            udb_cache_miss_total: self.miss_total.load(Ordering::Relaxed),
            udb_cache_invalidation_total: self.invalidation_total.load(Ordering::Relaxed),
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct EncryptionMetricSnapshot {
    pub encrypt_ok: u64,
    pub encrypt_error: u64,
    pub decrypt_ok: u64,
    pub decrypt_error: u64,
}

#[derive(Debug, Clone, Default)]
struct EncryptionMetrics {
    encrypt_ok: Arc<AtomicU64>,
    encrypt_error: Arc<AtomicU64>,
    decrypt_ok: Arc<AtomicU64>,
    decrypt_error: Arc<AtomicU64>,
}

impl EncryptionMetrics {
    fn record(&self, op: &str, ok: bool) {
        match (op, ok) {
            ("encrypt", true) => self.encrypt_ok.fetch_add(1, Ordering::Relaxed),
            ("encrypt", false) => self.encrypt_error.fetch_add(1, Ordering::Relaxed),
            ("decrypt", true) => self.decrypt_ok.fetch_add(1, Ordering::Relaxed),
            ("decrypt", false) => self.decrypt_error.fetch_add(1, Ordering::Relaxed),
            _ => return,
        };
    }

    fn snapshot(&self) -> EncryptionMetricSnapshot {
        EncryptionMetricSnapshot {
            encrypt_ok: self.encrypt_ok.load(Ordering::Relaxed),
            encrypt_error: self.encrypt_error.load(Ordering::Relaxed),
            decrypt_ok: self.decrypt_ok.load(Ordering::Relaxed),
            decrypt_error: self.decrypt_error.load(Ordering::Relaxed),
        }
    }
}

// Phase F: God-impl split into continuation impl blocks.
mod helpers;
pub(crate) use helpers::*;
mod accessors;
mod catalog_admin;
mod catalog_sql;
pub use catalog_sql::ManifestDrift;
mod probe_dispatch;
mod reload;
pub use reload::{ConfigReloadMode, ConfigReloadOptions, ConfigReloadReport};
pub(crate) mod setup_data;
mod tx_object;

/// Result returned by `enqueue_outbox_event`.
#[derive(Debug, Clone)]
pub struct EnqueueOutboxEventResult {
    pub event_id: String,
    pub enqueued: bool,
    pub was_duplicate: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TxSemantics {
    SingleBackendAcid,
    CrossBackendSaga,
}

impl TxSemantics {
    fn as_str(self) -> &'static str {
        match self {
            Self::SingleBackendAcid => "single_backend_acid",
            Self::CrossBackendSaga => "cross_backend_saga",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TxStrategy {
    Saga,
    BestEffort,
    TwoPhase,
}

fn requested_tx_strategy(
    metadata_context: &RequestContext,
    mutations: &[Mutation],
) -> Result<TxStrategy, tonic::Status> {
    let mut strategy = None;
    for policy in std::iter::once(metadata_context.routing_policy.as_str()).chain(
        mutations
            .iter()
            .filter_map(|mutation| mutation.context.as_ref())
            .map(|context| context.routing_policy.as_str()),
    ) {
        let Some(parsed) = parse_tx_strategy(policy)? else {
            continue;
        };
        if let Some(existing) = strategy
            && existing != parsed
        {
            return Err(tonic::Status::invalid_argument(
                "conflicting transaction strategies in request routing policy",
            ));
        }
        strategy = Some(parsed);
    }
    Ok(strategy.unwrap_or(TxStrategy::Saga))
}

fn parse_tx_strategy(policy: &str) -> Result<Option<TxStrategy>, tonic::Status> {
    for token in policy
        .split([',', ';', ' '])
        .map(str::trim)
        .filter(|token| !token.is_empty())
    {
        let value = token
            .strip_prefix("tx_strategy=")
            .or_else(|| token.strip_prefix("transaction_strategy="))
            .or_else(|| token.strip_prefix("tx:"))
            .unwrap_or(token)
            .trim()
            .to_ascii_lowercase();
        let parsed = match value.as_str() {
            "saga" => Some(TxStrategy::Saga),
            "best_effort" | "best-effort" | "besteffort" => Some(TxStrategy::BestEffort),
            "two_phase" | "two-phase" | "2pc" | "xa" => Some(TxStrategy::TwoPhase),
            _ if token.contains("tx_strategy=")
                || token.contains("transaction_strategy=")
                || token.starts_with("tx:") =>
            {
                return Err(tonic::Status::invalid_argument(format!(
                    "unsupported transaction strategy '{value}'"
                )));
            }
            _ => None,
        };
        if parsed.is_some() {
            return Ok(parsed);
        }
    }
    Ok(None)
}

/// B (2026-05-30): operator opt-in for live two-phase commit.
/// Re-exported from `runtime::config` so the runtime env-discipline
/// test stays satisfied (env reads live in the allowlisted config
/// module). When `UDB_2PC_ENABLED=true`, requests with
/// `tx_strategy=two_phase` no longer fail closed; the runtime
/// drives the prepared-transaction path through `XaCoordinator`.
pub(crate) use crate::runtime::config::two_phase_runtime_enabled;

fn validate_tx_strategy(strategy: TxStrategy, mutations: &[Mutation]) -> Result<(), tonic::Status> {
    match strategy {
        TxStrategy::Saga | TxStrategy::BestEffort => Ok(()),
        TxStrategy::TwoPhase => {
            let unsupported = mutations
                .iter()
                .filter(|mutation| !mutation.commit && !mutation.rollback)
                .map(|mutation| mutation.operation.to_ascii_lowercase())
                .find(|operation| !matches!(operation.as_str(), "upsert" | "delete"));
            if let Some(operation) = unsupported {
                return Err(tonic::Status::failed_precondition(format!(
                    "two_phase requested but operation '{operation}' is not a prepared-transaction participant"
                )));
            }
            // B: when operator has opted-in via `UDB_2PC_ENABLED=true`,
            // accept the request — `tx_object::begin_tx` will replace
            // the plain COMMIT with PREPARE TRANSACTION + COMMIT
            // PREPARED via the XA coordinator. Otherwise stay
            // fail-closed (the historical default).
            if two_phase_runtime_enabled() {
                Ok(())
            } else {
                Err(tonic::Status::failed_precondition(
                    "two_phase requested but prepared transaction execution is disabled; \
                     set UDB_2PC_ENABLED=true to enable live PREPARE TRANSACTION + COMMIT PREPARED",
                ))
            }
        }
    }
}

fn classify_tx_semantics(mutations: &[Mutation]) -> TxSemantics {
    let has_external_side_effect = mutations
        .iter()
        .filter(|mutation| !mutation.commit && !mutation.rollback)
        .any(|mutation| {
            matches!(
                mutation.operation.to_ascii_lowercase().as_str(),
                "vector_upsert" | "put_object"
            )
        });
    if has_external_side_effect {
        TxSemantics::CrossBackendSaga
    } else {
        TxSemantics::SingleBackendAcid
    }
}

fn tx_backend_instance(mutations: &[Mutation]) -> Option<String> {
    let mut instances = mutations
        .iter()
        .filter_map(|mutation| mutation.context.as_ref())
        .map(|context| context.target_instance.trim())
        .filter(|instance| !instance.is_empty())
        .map(ToString::to_string)
        .collect::<Vec<_>>();
    instances.sort();
    instances.dedup();
    match instances.len() {
        0 => None,
        1 => instances.pop(),
        _ => Some("multiple".to_string()),
    }
}

fn prepare_outbox_envelope(
    topic: &str,
    partition_key: &str,
    payload: serde_json::Value,
    schema_uri: Option<&str>,
) -> Result<(Uuid, String, serde_json::Value), tonic::Status> {
    if topic.trim().is_empty() {
        return Err(tonic::Status::invalid_argument("outbox topic is required"));
    }
    if partition_key.trim().is_empty() {
        return Err(tonic::Status::invalid_argument(
            "outbox partition_key is required",
        ));
    }
    let obj = payload.as_object().ok_or_else(|| {
        tonic::Status::invalid_argument(
            "event payload must be a JSON object conforming to the EventEnvelope schema",
        )
    })?;
    let envelope_field = |field: &str| -> Result<&str, tonic::Status> {
        obj.get(field)
            .and_then(|value| value.as_str())
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                tonic::Status::invalid_argument(format!(
                    "event payload field '{field}' must be a non-empty string"
                ))
            })
    };
    let event_id_uuid = Uuid::parse_str(envelope_field("event_id")?).map_err(|err| {
        tonic::Status::invalid_argument(format!(
            "event payload field 'event_id' must be a valid UUID: {err}"
        ))
    })?;
    for field in ["event_type", "correlation_id", "document_id"] {
        envelope_field(field)?;
    }
    let document_id = envelope_field("document_id")?;
    if partition_key != document_id {
        return Err(tonic::Status::invalid_argument(
            "outbox partition_key must equal payload.document_id",
        ));
    }

    let event_id = event_id_uuid.to_string();
    let mut enriched_obj = obj.clone();
    enriched_obj.insert(
        "event_id".to_string(),
        serde_json::Value::String(event_id.clone()),
    );
    if let Some(uri) = schema_uri {
        enriched_obj
            .entry("schema_uri".to_string())
            .or_insert_with(|| serde_json::Value::String(uri.to_string()));
    }
    enriched_obj
        .entry("timestamp".to_string())
        .or_insert_with(|| serde_json::Value::String(Utc::now().to_rfc3339()));
    enriched_obj
        .entry("payload".to_string())
        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
    Ok((
        event_id_uuid,
        event_id,
        serde_json::Value::Object(enriched_obj),
    ))
}

fn artifact_content_checksum(content: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    format!("sha256:{:x}", hasher.finalize())
}

fn extract_manifest_checksum(content: &str) -> String {
    for line in content.lines().take(16) {
        if let Some(value) = line.strip_prefix("-- UDB:proto_manifest_checksum=") {
            return value.trim().to_string();
        }
    }
    String::new()
}

fn decode_catalog_manifest_row(
    json_row: Option<(String,)>,
) -> Result<Option<CatalogManifest>, tonic::Status> {
    match json_row {
        None => Ok(None),
        Some((json,)) => match serde_json::from_str::<CatalogManifest>(&json) {
            Ok(manifest) => Ok(Some(manifest)),
            Err(err) => {
                // Schema evolution: stored manifest was serialized by an older
                // UDB binary that lacked newly-added fields. Rather than
                // aborting the migration, treat it as "no prior manifest" and
                // let the caller fall back to an idempotent bootstrap plan.
                tracing::warn!(
                    error = %err,
                    "stored manifest in proto_schema_versions is incompatible with \
                     current schema (likely a forward-migration); treating as absent \
                     — delta will regenerate all alter statements idempotently"
                );
                Ok(None)
            }
        },
    }
}

pub(crate) async fn set_request_local_settings(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    context: &RequestContext,
) -> Result<(), tonic::Status> {
    let app_name = if context.correlation_id.trim().is_empty() {
        "udb".to_string()
    } else {
        format!(
            "udb/{}",
            &context.correlation_id[..context.correlation_id.len().min(58)]
        )
    };
    // Item 135: the `app.current_*` variables come from the single canonical
    // source (`AppliedContext::session_context_pairs`) shared with the
    // dialect-aware renderer, so the PG fast path and the universal backend
    // enforcer never drift. `application_name` is PG-specific and stays here.
    let applied = crate::runtime::backend_context::AppliedContext::from_request(context);
    let mut settings: Vec<(&str, String)> = vec![("application_name", app_name)];
    settings.extend(
        applied
            .session_context_pairs()
            .into_iter()
            .map(|(key, value)| (key, value.to_string())),
    );
    for (key, value) in settings {
        sqlx::query("SELECT set_config($1, $2, true)")
            .bind(key)
            .bind(value)
            .execute(&mut **tx)
            .await
            .map_err(|err| {
                tonic::Status::internal(format!("failed to set request database context: {err}"))
            })?;
    }
    Ok(())
}

#[allow(clippy::items_after_test_module)]
#[cfg(test)]
mod outbox_envelope_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn prepare_outbox_envelope_requires_document_partition_key() {
        let err = prepare_outbox_envelope(
            "document.uploaded.v1",
            "doc-2",
            json!({
                "event_id": "11111111-1111-4111-8111-111111111111",
                "event_type": "document.uploaded.v1",
                "correlation_id": "corr-1",
                "document_id": "doc-1"
            }),
            None,
        )
        .unwrap_err();
        assert_eq!(err.code(), tonic::Code::InvalidArgument);
        assert!(err.message().contains("partition_key"));
    }

    #[test]
    fn prepare_outbox_envelope_enriches_schema_timestamp_and_payload() {
        let (_, event_id, payload) = prepare_outbox_envelope(
            "document.uploaded.v1",
            "doc-1",
            json!({
                "event_id": "11111111-1111-4111-8111-111111111111",
                "event_type": "document.uploaded.v1",
                "correlation_id": "corr-1",
                "document_id": "doc-1"
            }),
            Some("buf.build/example/document.uploaded.v1"),
        )
        .unwrap();
        assert_eq!(event_id, "11111111-1111-4111-8111-111111111111");
        assert_eq!(
            payload["schema_uri"],
            "buf.build/example/document.uploaded.v1"
        );
        assert!(
            payload["timestamp"]
                .as_str()
                .unwrap_or_default()
                .contains('T')
        );
        assert!(payload["payload"].is_object());
    }

    #[test]
    fn split_backend_selector_accepts_colon_and_dot() {
        assert_eq!(
            split_backend_selector("postgres:primary"),
            ("postgres", Some("primary"))
        );
        assert_eq!(
            split_backend_selector("qdrant.vector_a"),
            ("qdrant", Some("vector_a"))
        );
        assert_eq!(split_backend_selector("mongodb"), ("mongodb", None));
    }

    #[test]
    fn resolve_backend_selector_validates_named_instance() {
        let runtime = DataBrokerRuntime {
            backend_instances: vec![RuntimeBackendInstance {
                name: "primary".to_string(),
                backend: "postgres".to_string(),
                role: "read_write".to_string(),
                enabled: true,
                configured: true,
                connected: true,
                read_weight: 1,
                write_weight: 1,
                dsn_env: Some("UDB_PG_DSN".to_string()),
                labels: HashMap::new(),
                capabilities: Vec::new(),
                healthy: true,
                circuit_open: false,
            }],
            ..DataBrokerRuntime::default()
        };

        let resolved = runtime
            .resolve_backend_selector("postgres:primary")
            .unwrap();
        assert_eq!(resolved.backend, "postgres");
        assert_eq!(resolved.instance.as_deref(), Some("primary"));
        assert_eq!(
            runtime
                .resolve_backend_selector("postgres:missing")
                .unwrap_err()
                .code(),
            tonic::Code::NotFound
        );
    }

    #[test]
    fn resolve_backend_targets_supports_all_and_label_filters() {
        let runtime = DataBrokerRuntime {
            backend_instances: vec![
                RuntimeBackendInstance {
                    name: "vector_a".to_string(),
                    backend: "qdrant".to_string(),
                    role: "read_write".to_string(),
                    enabled: true,
                    configured: true,
                    connected: true,
                    read_weight: 1,
                    write_weight: 1,
                    dsn_env: None,
                    labels: HashMap::from([("region".to_string(), "local".to_string())]),
                    capabilities: Vec::new(),
                    healthy: true,
                    circuit_open: false,
                },
                RuntimeBackendInstance {
                    name: "vector_b".to_string(),
                    backend: "qdrant".to_string(),
                    role: "read".to_string(),
                    enabled: true,
                    configured: true,
                    connected: true,
                    read_weight: 1,
                    write_weight: 0,
                    dsn_env: None,
                    labels: HashMap::from([("region".to_string(), "remote".to_string())]),
                    capabilities: Vec::new(),
                    healthy: true,
                    circuit_open: false,
                },
            ],
            ..DataBrokerRuntime::default()
        };

        let all = runtime.resolve_backend_targets("qdrant:*", "{}").unwrap();
        assert_eq!(all.len(), 2);
        let local = runtime
            .resolve_backend_targets("qdrant", r#"{"target_labels":{"region":"local"}}"#)
            .unwrap();
        assert_eq!(local.len(), 1);
        assert_eq!(local[0].instance.as_deref(), Some("vector_a"));
    }

    #[test]
    fn resolve_backend_selector_filters_named_instance_by_project_label() {
        let runtime = DataBrokerRuntime {
            backend_instances: vec![RuntimeBackendInstance {
                name: "billing_vector".to_string(),
                backend: "qdrant".to_string(),
                role: "read_write".to_string(),
                enabled: true,
                configured: true,
                connected: true,
                read_weight: 1,
                write_weight: 1,
                dsn_env: None,
                labels: HashMap::from([("project_id".to_string(), "billing".to_string())]),
                capabilities: Vec::new(),
                healthy: true,
                circuit_open: false,
            }],
            ..DataBrokerRuntime::default()
        };

        let resolved = runtime
            .resolve_backend_selector_for_project("qdrant:billing_vector", "billing")
            .unwrap();
        assert_eq!(resolved.instance.as_deref(), Some("billing_vector"));
        assert_eq!(
            runtime
                .resolve_backend_selector_for_project("qdrant:billing_vector", "hr")
                .unwrap_err()
                .code(),
            tonic::Code::NotFound
        );
    }

    #[test]
    fn resolve_backend_targets_filters_wildcards_by_project_labels() {
        let runtime = DataBrokerRuntime {
            backend_instances: vec![
                RuntimeBackendInstance {
                    name: "billing_vector".to_string(),
                    backend: "qdrant".to_string(),
                    role: "read_write".to_string(),
                    enabled: true,
                    configured: true,
                    connected: true,
                    read_weight: 1,
                    write_weight: 1,
                    dsn_env: None,
                    labels: HashMap::from([("projects".to_string(), "billing,ocr".to_string())]),
                    capabilities: Vec::new(),
                    healthy: true,
                    circuit_open: false,
                },
                RuntimeBackendInstance {
                    name: "hr_vector".to_string(),
                    backend: "qdrant".to_string(),
                    role: "read_write".to_string(),
                    enabled: true,
                    configured: true,
                    connected: true,
                    read_weight: 1,
                    write_weight: 1,
                    dsn_env: None,
                    labels: HashMap::from([("project".to_string(), "hr".to_string())]),
                    capabilities: Vec::new(),
                    healthy: true,
                    circuit_open: false,
                },
                RuntimeBackendInstance {
                    name: "global_vector".to_string(),
                    backend: "qdrant".to_string(),
                    role: "read_write".to_string(),
                    enabled: true,
                    configured: true,
                    connected: true,
                    read_weight: 1,
                    write_weight: 1,
                    dsn_env: None,
                    labels: HashMap::new(),
                    capabilities: Vec::new(),
                    healthy: true,
                    circuit_open: false,
                },
            ],
            ..DataBrokerRuntime::default()
        };

        let billing = runtime
            .resolve_backend_targets_for_project("qdrant:*", "{}", "billing")
            .unwrap();
        assert_eq!(
            billing
                .iter()
                .filter_map(|target| target.instance.as_deref())
                .collect::<Vec<_>>(),
            vec!["billing_vector", "global_vector"]
        );
    }

    #[test]
    fn strict_project_routing_blocks_unlabeled_instances() {
        let runtime = DataBrokerRuntime {
            config: UdbConfig {
                project_routing_mode: "strict".to_string(),
                ..UdbConfig::default()
            },
            backend_instances: vec![RuntimeBackendInstance {
                name: "global_vector".to_string(),
                backend: "qdrant".to_string(),
                role: "read_write".to_string(),
                enabled: true,
                configured: true,
                connected: true,
                read_weight: 1,
                write_weight: 1,
                dsn_env: None,
                labels: HashMap::new(),
                capabilities: Vec::new(),
                healthy: true,
                circuit_open: false,
            }],
            ..DataBrokerRuntime::default()
        };

        assert_eq!(
            runtime
                .resolve_backend_selector_for_project("qdrant:global_vector", "billing")
                .unwrap_err()
                .code(),
            tonic::Code::NotFound
        );
        assert!(
            runtime
                .resolve_backend_selector_for_project("qdrant:global_vector", "default")
                .is_ok()
        );
    }

    #[test]
    fn strict_project_routing_blocks_direct_postgres_instance_pool_lookup() {
        let runtime = DataBrokerRuntime {
            config: UdbConfig {
                project_routing_mode: "strict".to_string(),
                ..UdbConfig::default()
            },
            backend_instances: vec![RuntimeBackendInstance {
                name: "primary".to_string(),
                backend: "postgres".to_string(),
                role: "read_write".to_string(),
                enabled: true,
                configured: true,
                connected: true,
                read_weight: 1,
                write_weight: 1,
                dsn_env: None,
                labels: HashMap::new(),
                capabilities: Vec::new(),
                healthy: true,
                circuit_open: false,
            }],
            ..DataBrokerRuntime::default()
        };
        let context = RequestContext {
            project_id: "billing".to_string(),
            target_backend: "postgres".to_string(),
            target_instance: "primary".to_string(),
            ..RequestContext::default()
        };

        let err = runtime
            .pg_read_pool_for_context_checked(&context)
            .unwrap_err();
        assert_eq!(err.code(), tonic::Code::NotFound);
        assert!(err.message().contains("strict routing"));
    }

    #[test]
    fn choose_instance_name_filters_by_project_labels() {
        let runtime = DataBrokerRuntime {
            backend_instances: vec![
                RuntimeBackendInstance {
                    name: "hr_vector".to_string(),
                    backend: "qdrant".to_string(),
                    role: "read_write".to_string(),
                    enabled: true,
                    configured: true,
                    connected: true,
                    read_weight: 100,
                    write_weight: 100,
                    dsn_env: None,
                    labels: HashMap::from([("project".to_string(), "hr".to_string())]),
                    capabilities: Vec::new(),
                    healthy: true,
                    circuit_open: false,
                },
                RuntimeBackendInstance {
                    name: "billing_vector".to_string(),
                    backend: "qdrant".to_string(),
                    role: "read_write".to_string(),
                    enabled: true,
                    configured: true,
                    connected: true,
                    read_weight: 1,
                    write_weight: 1,
                    dsn_env: None,
                    labels: HashMap::from([("project".to_string(), "billing".to_string())]),
                    capabilities: Vec::new(),
                    healthy: true,
                    circuit_open: false,
                },
            ],
            ..DataBrokerRuntime::default()
        };

        assert_eq!(
            runtime.choose_instance_name_for_project("qdrant", false, "billing"),
            Some("billing_vector")
        );
    }

    #[test]
    fn classify_tx_semantics_distinguishes_acid_from_saga() {
        let relational = vec![Mutation {
            operation: "upsert".to_string(),
            message_type: "Patient".to_string(),
            ..Mutation::default()
        }];
        assert_eq!(
            classify_tx_semantics(&relational),
            TxSemantics::SingleBackendAcid
        );

        let cross_backend = vec![
            Mutation {
                operation: "upsert".to_string(),
                message_type: "Patient".to_string(),
                ..Mutation::default()
            },
            Mutation {
                operation: "vector_upsert".to_string(),
                collection: "patient_embeddings".to_string(),
                ..Mutation::default()
            },
        ];
        assert_eq!(
            classify_tx_semantics(&cross_backend),
            TxSemantics::CrossBackendSaga
        );
    }

    #[test]
    fn tx_backend_instance_reports_single_or_multiple_targets() {
        let one = vec![Mutation {
            context: Some(crate::proto::RequestContext {
                target_instance: "primary".to_string(),
                ..Default::default()
            }),
            ..Mutation::default()
        }];
        assert_eq!(tx_backend_instance(&one).as_deref(), Some("primary"));

        let multiple = vec![
            Mutation {
                context: Some(crate::proto::RequestContext {
                    target_instance: "a".to_string(),
                    ..Default::default()
                }),
                ..Mutation::default()
            },
            Mutation {
                context: Some(crate::proto::RequestContext {
                    target_instance: "b".to_string(),
                    ..Default::default()
                }),
                ..Mutation::default()
            },
        ];
        assert_eq!(tx_backend_instance(&multiple).as_deref(), Some("multiple"));
    }

    #[test]
    fn requested_tx_strategy_parses_and_rejects_conflicts() {
        let metadata = RequestContext {
            routing_policy: "tx_strategy=best_effort".to_string(),
            ..Default::default()
        };
        assert_eq!(
            requested_tx_strategy(&metadata, &[]).unwrap(),
            TxStrategy::BestEffort
        );

        let conflict = requested_tx_strategy(
            &metadata,
            &[Mutation {
                context: Some(crate::proto::RequestContext {
                    routing_policy: "tx_strategy=saga".to_string(),
                    ..Default::default()
                }),
                ..Default::default()
            }],
        )
        .unwrap_err();
        assert_eq!(conflict.code(), tonic::Code::InvalidArgument);
    }

    /// Serialise env-flipping 2PC tests so they don't race with
    /// each other on the process-wide `UDB_2PC_ENABLED` variable.
    fn two_phase_env_lock() -> &'static std::sync::Mutex<()> {
        use std::sync::OnceLock;
        static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| std::sync::Mutex::new(()))
    }

    #[test]
    fn two_phase_strategy_fails_before_side_effects() {
        let _g = two_phase_env_lock()
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        // SAFETY: test reads/writes UDB_2PC_ENABLED. Make sure the
        // env is unset before asserting the fail-closed branch.
        unsafe {
            std::env::remove_var("UDB_2PC_ENABLED");
        }
        let relational_only = vec![Mutation {
            operation: "upsert".to_string(),
            message_type: "Patient".to_string(),
            ..Default::default()
        }];
        let err = validate_tx_strategy(TxStrategy::TwoPhase, &relational_only).unwrap_err();
        assert_eq!(err.code(), tonic::Code::FailedPrecondition);
        assert!(err.message().contains("disabled"));

        let external = vec![Mutation {
            operation: "vector_upsert".to_string(),
            collection: "patient_embeddings".to_string(),
            ..Default::default()
        }];
        let err = validate_tx_strategy(TxStrategy::TwoPhase, &external).unwrap_err();
        assert_eq!(err.code(), tonic::Code::FailedPrecondition);
        assert!(
            err.message()
                .contains("not a prepared-transaction participant")
        );
    }

    #[test]
    fn b_two_phase_accepted_when_runtime_enabled_env_set() {
        let _g = two_phase_env_lock()
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        // B (2026-05-30): with UDB_2PC_ENABLED=true the validate
        // step accepts the request and lets begin_tx drive the
        // live PREPARE TRANSACTION + COMMIT PREPARED path.
        unsafe {
            std::env::set_var("UDB_2PC_ENABLED", "true");
        }
        let relational_only = vec![Mutation {
            operation: "upsert".to_string(),
            message_type: "Patient".to_string(),
            ..Default::default()
        }];
        let res = validate_tx_strategy(TxStrategy::TwoPhase, &relational_only);
        unsafe {
            std::env::remove_var("UDB_2PC_ENABLED");
        }
        assert!(res.is_ok(), "got: {res:?}");
    }

    #[test]
    fn b_runtime_toggle_recognises_common_truthy_values() {
        // Tests cargo runs in parallel; reading the process env
        // races with sibling tests that set/clear it. Drive the
        // pure parser instead.
        use crate::runtime::config::parse_two_phase_toggle;
        for v in ["1", "true", "TRUE", "Yes", "on"] {
            assert!(parse_two_phase_toggle(Some(v)), "should be true for '{v}'");
        }
        for v in ["0", "false", "no", "off", ""] {
            assert!(
                !parse_two_phase_toggle(Some(v)),
                "should be false for '{v}'"
            );
        }
        assert!(!parse_two_phase_toggle(None), "None must be false");
    }

    #[test]
    fn backend_executor_resolves_registered_instance() {
        let instances = vec![RuntimeBackendInstance {
            name: "vector_a".to_string(),
            backend: "qdrant".to_string(),
            role: "read_write".to_string(),
            enabled: true,
            configured: true,
            connected: true,
            read_weight: 1,
            write_weight: 1,
            dsn_env: None,
            labels: HashMap::from([("region".to_string(), "local".to_string())]),
            capabilities: Vec::new(),
            healthy: true,
            circuit_open: false,
        }];
        let runtime = DataBrokerRuntime {
            executor_registry: build_executor_registry(&instances),
            backend_instances: instances,
            ..DataBrokerRuntime::default()
        };

        let executor = runtime
            .backend_executor("qdrant", Some("vector_a"))
            .unwrap();
        assert_eq!(executor.backend, "qdrant");
        assert_eq!(executor.instance.as_deref(), Some("vector_a"));
        assert!(
            runtime
                .executor_registry()
                .get("qdrant", Some("vector_a"))
                .is_some()
        );
    }

    #[tokio::test]
    async fn checked_runtime_constructor_rejects_invalid_config_before_registration() {
        let config = UdbConfig {
            primary: DbConfig {
                host: "pg".to_string(),
                database: "db".to_string(),
                role: "app".to_string(),
                ..DbConfig::default()
            },
            backend_instances: BackendInstanceConfig {
                instances: vec![BackendInstance {
                    name: "cache".to_string(),
                    backend: "redis".to_string(),
                    dsn: Some("not a dsn".to_string()),
                    dsn_env: None,
                    ..BackendInstance::default()
                }],
            },
            ..UdbConfig::default()
        };

        let result = DataBrokerRuntime::try_from_config(config).await;
        let err = match result {
            Ok(_) => panic!("invalid config should fail before runtime registration"),
            Err(err) => err,
        };
        assert!(err.contains("config validation failed"));
        assert!(err.contains("does not look valid"));
    }

    #[test]
    fn circuit_breaker_failover_skips_open_instance() {
        let instances = vec![
            RuntimeBackendInstance {
                name: "vector_a".to_string(),
                backend: "qdrant".to_string(),
                role: "read_write".to_string(),
                enabled: true,
                configured: true,
                connected: true,
                read_weight: 10,
                write_weight: 10,
                dsn_env: None,
                labels: HashMap::from([("region".to_string(), "a".to_string())]),
                capabilities: Vec::new(),
                healthy: true,
                circuit_open: false,
            },
            RuntimeBackendInstance {
                name: "vector_b".to_string(),
                backend: "qdrant".to_string(),
                role: "read_write".to_string(),
                enabled: true,
                configured: true,
                connected: true,
                read_weight: 1,
                write_weight: 1,
                dsn_env: None,
                labels: HashMap::from([("region".to_string(), "b".to_string())]),
                capabilities: Vec::new(),
                healthy: true,
                circuit_open: false,
            },
        ];
        let runtime = DataBrokerRuntime {
            config: UdbConfig {
                circuit_breaker: crate::runtime::config::CircuitBreakerSettings {
                    failure_threshold: 1,
                    cooldown_secs: 60,
                },
                ..UdbConfig::default()
            },
            executor_registry: build_executor_registry(&instances),
            backend_instances: instances,
            ..DataBrokerRuntime::default()
        };

        runtime.record_backend_result("qdrant", Some("vector_a"), false);
        assert!(!runtime.circuit_breaker_allows("qdrant", Some("vector_a")));
        let explicit_err = match runtime.backend_executor("qdrant", Some("vector_a")) {
            Ok(_) => panic!("open circuit should reject explicitly targeted vector_a"),
            Err(err) => err,
        };
        assert_eq!(explicit_err.code(), tonic::Code::Unavailable);
        let executor = runtime.backend_executor("qdrant", None).unwrap();
        assert_eq!(executor.instance.as_deref(), Some("vector_b"));

        let targets = runtime.resolve_backend_targets("qdrant:*", "{}").unwrap();
        assert_eq!(targets.len(), 1);
        assert_eq!(targets[0].instance.as_deref(), Some("vector_b"));
    }

    #[test]
    fn pg_dispatch_sql_validation_separates_reads_and_writes() {
        assert!(validate_pg_read_sql("SELECT 1").is_ok());
        assert!(validate_pg_read_sql("WITH x AS (SELECT 1) SELECT * FROM x").is_ok());
        assert_eq!(
            validate_pg_read_sql("DELETE FROM users")
                .unwrap_err()
                .code(),
            tonic::Code::FailedPrecondition
        );
        assert!(validate_pg_mutation_sql("INSERT INTO audit_log(message) VALUES ($1)").is_ok());
        assert!(validate_pg_mutation_sql("UPDATE users SET name = $1 WHERE id = $2").is_ok());
        assert_eq!(
            validate_pg_mutation_sql("DROP TABLE users")
                .unwrap_err()
                .code(),
            tonic::Code::FailedPrecondition
        );
        assert_eq!(
            validate_pg_read_sql("SELECT 1; SELECT 2")
                .unwrap_err()
                .code(),
            tonic::Code::InvalidArgument
        );
    }

    #[test]
    fn dispatch_params_accepts_params_or_parameters_array() {
        assert_eq!(
            dispatch_params(&json!({"params": [1, "two"]})).unwrap(),
            vec![json!(1), json!("two")]
        );
        assert_eq!(
            dispatch_params(&json!({"parameters": [true]})).unwrap(),
            vec![json!(true)]
        );
        assert_eq!(
            dispatch_params(&json!({"params": {"bad": true}}))
                .unwrap_err()
                .code(),
            tonic::Code::InvalidArgument
        );
    }

    #[test]
    fn object_bytes_from_json_accepts_base64_and_text() {
        let base64 = object_bytes_from_json(&json!({"data_base64": "aGVsbG8="})).unwrap();
        assert_eq!(base64, b"hello");
        let text = object_bytes_from_json(&json!({"content_text": "plain"})).unwrap();
        assert_eq!(text, b"plain");
    }
}

// ── Internal postgres helpers, join fusion, bind helpers are in postgres_helpers.rs ──
// ── rows_to_record_set, decrypt_record_value, row_value_to_json remain here   ──
// ── because they depend on the private EncryptionMetrics type.                 ──

fn rows_to_record_set(
    rows: Vec<PgRow>,
    table: Option<&ManifestTable>,
    masked_columns: &[String],
    context: &RequestContext,
    encryption: Option<&EncryptionRuntime>,
    encryption_metrics: &EncryptionMetrics,
) -> Result<RecordSet, tonic::Status> {
    let can_read_pii = context
        .scopes
        .iter()
        .any(|scope| scope == "udb:pii:read" || scope == "udb:*" || scope == "*");
    let mut proto_rows = Vec::new();
    let mut records_json = Vec::new();
    for row in rows {
        let mut fields = HashMap::new();
        let mut json_row = serde_json::Map::new();
        for (idx, column) in row.columns().iter().enumerate() {
            let name = column.name().to_string();
            let mut json_value = row_value_to_json(&row, idx, column.type_info().name())?;
            if table
                .and_then(|table| {
                    table
                        .columns
                        .iter()
                        .find(|column| column.column_name == name)
                })
                .is_some_and(is_encrypted_column)
            {
                json_value =
                    decrypt_record_value(encryption, encryption_metrics, &name, json_value)?;
            }
            if masked_columns.contains(&name) && !can_read_pii {
                json_value = JsonValue::String("***MASKED***".to_string());
            }
            if let Some(prost) = json_to_prost_value(&json_value) {
                fields.insert(name.clone(), prost);
            }
            json_row.insert(name, json_value);
        }
        records_json.push(
            serde_json::to_vec(&JsonValue::Object(json_row)).map_err(|err| {
                tonic::Status::internal(format!("failed to serialize record JSON: {err}"))
            })?,
        );
        proto_rows.push(ProtoRow { fields });
    }
    Ok(RecordSet {
        total_count: proto_rows.len() as i32,
        rows: proto_rows,
        records_json,
        ..RecordSet::default()
    })
}

fn decrypt_record_value(
    encryption: Option<&EncryptionRuntime>,
    metrics: &EncryptionMetrics,
    column_name: &str,
    value: JsonValue,
) -> Result<JsonValue, tonic::Status> {
    let JsonValue::String(ciphertext) = value else {
        return Ok(value);
    };
    if !is_ciphertext(&ciphertext) {
        return Ok(JsonValue::String(ciphertext));
    }
    let Some(encryption) = encryption else {
        metrics.record("decrypt", false);
        return Err(tonic::Status::failed_precondition(format!(
            "column {column_name} is encrypted but UDB encryption key is not configured"
        )));
    };
    match encryption.decrypt_json_value(&ciphertext) {
        Ok(value) => {
            metrics.record("decrypt", true);
            Ok(value)
        }
        Err(err) => {
            metrics.record("decrypt", false);
            Err(tonic::Status::internal(format!(
                "failed to decrypt column {column_name}: {err}"
            )))
        }
    }
}

fn row_value_to_json(row: &PgRow, idx: usize, type_name: &str) -> Result<JsonValue, tonic::Status> {
    let type_name = type_name.to_ascii_uppercase();
    if type_name.contains("INT2") || type_name.contains("INT4") {
        return Ok(row
            .try_get::<Option<i32>, _>(idx)
            .map(|value| value.map(JsonValue::from).unwrap_or(JsonValue::Null))
            .unwrap_or(JsonValue::Null));
    }
    if type_name.contains("INT8") || type_name == "BIGINT" {
        return Ok(row
            .try_get::<Option<i64>, _>(idx)
            .map(|value| value.map(JsonValue::from).unwrap_or(JsonValue::Null))
            .unwrap_or(JsonValue::Null));
    }
    if type_name.contains("FLOAT") || type_name.contains("DOUBLE") || type_name.contains("REAL") {
        return Ok(row
            .try_get::<Option<f64>, _>(idx)
            .map(|value| value.map(JsonValue::from).unwrap_or(JsonValue::Null))
            .unwrap_or(JsonValue::Null));
    }
    // GAP 10: NUMERIC / DECIMAL — deserialise as string to avoid floating-point
    // precision loss.  Clients can parse the string value to their preferred
    // arbitrary-precision type.
    if type_name.contains("NUMERIC") || type_name.contains("DECIMAL") {
        return Ok(row
            .try_get::<Option<String>, _>(idx)
            .or_else(|_| {
                // Fallback: try f64 and convert to string when text cast fails.
                row.try_get::<Option<f64>, _>(idx)
                    .map(|v| v.map(|f| f.to_string()))
            })
            .map(|value| value.map(JsonValue::String).unwrap_or(JsonValue::Null))
            .unwrap_or(JsonValue::Null));
    }
    if type_name.contains("BOOL") {
        return Ok(row
            .try_get::<Option<bool>, _>(idx)
            .map(|value| value.map(JsonValue::from).unwrap_or(JsonValue::Null))
            .unwrap_or(JsonValue::Null));
    }
    if type_name.contains("UUID") {
        return Ok(row
            .try_get::<Option<Uuid>, _>(idx)
            .map(|value| {
                value
                    .map(|uuid| JsonValue::String(uuid.to_string()))
                    .unwrap_or(JsonValue::Null)
            })
            .unwrap_or(JsonValue::Null));
    }
    if type_name.contains("JSON") {
        return Ok(row
            .try_get::<Option<sqlx::types::Json<JsonValue>>, _>(idx)
            .map(|value| value.map(|json| json.0).unwrap_or(JsonValue::Null))
            .unwrap_or(JsonValue::Null));
    }
    // GAP 10: BYTEA — encode as base64 string so the binary data survives JSON.
    if type_name == "BYTEA" {
        use base64::{Engine as _, engine::general_purpose::STANDARD as B64};
        return Ok(row
            .try_get::<Option<Vec<u8>>, _>(idx)
            .map(|value| {
                value
                    .map(|bytes| JsonValue::String(B64.encode(&bytes)))
                    .unwrap_or(JsonValue::Null)
            })
            .unwrap_or(JsonValue::Null));
    }
    if type_name.contains("TIMESTAMPTZ") {
        return Ok(row
            .try_get::<Option<DateTime<Utc>>, _>(idx)
            .map(|value| {
                value
                    .map(|dt| JsonValue::String(dt.to_rfc3339()))
                    .unwrap_or(JsonValue::Null)
            })
            .unwrap_or(JsonValue::Null));
    }
    if type_name == "TIMESTAMP" {
        return Ok(row
            .try_get::<Option<NaiveDateTime>, _>(idx)
            .map(|value| {
                value
                    .map(|dt| JsonValue::String(dt.to_string()))
                    .unwrap_or(JsonValue::Null)
            })
            .unwrap_or(JsonValue::Null));
    }
    if type_name == "DATE" {
        return Ok(row
            .try_get::<Option<NaiveDate>, _>(idx)
            .map(|value| {
                value
                    .map(|dt| JsonValue::String(dt.to_string()))
                    .unwrap_or(JsonValue::Null)
            })
            .unwrap_or(JsonValue::Null));
    }
    // GAP 10: TEXT[] and other PostgreSQL array types — deserialise as a JSON array
    // of strings.  Covers VARCHAR[], TEXT[], BIGINT[], INT[], etc.
    if type_name.ends_with("[]") {
        let arr: Vec<String> = row
            .try_get::<Option<Vec<String>>, _>(idx)
            .unwrap_or(None)
            .unwrap_or_default();
        return Ok(JsonValue::Array(
            arr.into_iter().map(JsonValue::String).collect(),
        ));
    }
    // GAP 10: INET, CIDR, MACADDR, TSVECTOR — all have sensible text representations.
    // Fall through to the string catch-all below which handles these correctly.
    Ok(row
        .try_get::<Option<String>, _>(idx)
        .map(|value| value.map(JsonValue::from).unwrap_or(JsonValue::Null))
        .unwrap_or(JsonValue::Null))
}