rustango 0.61.13

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
//! [`TenantPools`] — lazy connection registry for multi-tenant rustango.
//!
//! Two storage modes coexist:
//!
//! * **Schema mode** (`Org.storage_mode == "schema"`). Tenant data
//!   lives in a Postgres schema inside the registry DB. Each tenant gets
//!   two small `search_path`-scoped pools, for [`TenantPools::scoped_pool`]
//!   and for [`TenantPools::acquire`], so a busy tenant never takes the
//!   registry's connections.
//!
//! * **Database mode** (`Org.storage_mode == "database"`). Tenant data
//!   lives in a separate Postgres database. `Org.database_url` is a
//!   *secret reference* — [`SecretsResolver`] turns it into the actual
//!   connection URL, then we lazy-build a dedicated `PgPool` and cache
//!   it. Strong isolation, per-tenant connection budget. On Postgres
//!   [`TenantPools::acquire`] takes from a second pool of its own, so a
//!   held connection never waits on the queries' pool.
//!
//! ## Cache shape
//!
//! Both caches are `RwLock<HashMap<slug, CachedPool>>`, bounded, and
//! LRU past their cap: the most idle entry is evicted and the new
//! tenant takes the slot. The cap is the live pool count, so the
//! connection budgets below are real. Before 0.57.12 database mode
//! refused forever (#1527) and schema mode rebuilt a pool per request
//! (#1528). Each entry remembers the `database_url` / schema it was
//! built from; an `Org` naming another one is a miss (#1882).
//!
//! Schema-mode tenants don't consume the *database* cache. Their
//! separate caches hold the `search_path`-scoped pools
//! [`TenantPools::scoped_pool`] and [`TenantPools::acquire`] use.
//!
//! The two budgets are deliberately separate: one shared cap would let
//! schema-mode tenants silently eat a mixed deployment's database-mode
//! capacity.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, PoisonError, Weak};

#[cfg(feature = "postgres")]
use crate::sql::sqlx::postgres::{PgPool, PgPoolOptions};
use crate::sql::sqlx::{self, Database};
use tokio::sync::RwLock;
use tracing::Instrument as _;

use super::error::TenancyError;
use super::org::{Org, StorageMode};
use super::secrets::{ChainSecretsResolver, SecretsResolver, TenantSecrets};

/// Configuration for [`TenantPools`].
#[derive(Debug, Clone)]
pub struct TenantPoolsConfig {
    /// Maximum number of database-mode pools cached simultaneously.
    /// Past it the most idle tenant is evicted and reconnects on its
    /// next request. Schema-mode tenants don't count against this.
    ///
    /// It is the live pool count, so the connection ceiling is this
    /// times `database_pool_max_connections`. `0` disables caching.
    /// Default: 64.
    pub max_cached_database_pools: usize,
    /// Per-pool `max_connections` for database-mode tenants. On Postgres
    /// each tenant has two such pools, its queries' and the held
    /// connections' (no idle ones), so budget twice this. Keep
    /// small enough that a fleet fan-out doesn't exhaust Postgres'
    /// `max_connections`, but large enough that a single tenant's
    /// concurrent admin traffic (page render + thumbnail fan-out
    /// + background tasks) doesn't deadlock — the framework's
    /// `Tenant` extractor pins one connection for the handler's
    /// whole lifetime, so handlers that also call `fetch_pool(...)`
    /// inside need at least one extra slot to make progress.
    /// 4 is far too tight for that pattern; 16 leaves headroom
    /// without flooding upstream PG. Default: 16.
    pub database_pool_max_connections: u32,

    // v0.27.7 — connection-time tuning (#60). Pre-fix, every tenant
    // pool was built with `PgPoolOptions::new().max_connections(...)`
    // and nothing else, leaving sqlx's defaults to drive timeout /
    // lifetime / idle behavior. Defaults are reasonable but apps
    // that hit slow upstreams (vault-resolved DSNs, distant
    // databases) had no way to tune them without bypassing
    // TenantPools entirely.
    /// Per-pool `min_connections` for database-mode tenants. When
    /// non-zero, sqlx keeps that many connections warm at all
    /// times — first-request latency drops because the TCP /
    /// TLS / auth round-trip is paid at boot rather than on the
    /// hot path. Recommend `1` for production tenants that get
    /// regular traffic, `0` for cold tenants with sparse hits
    /// (the default; preserves pre-0.27.7 behavior). Default: 0.
    pub database_pool_min_connections: u32,

    /// `acquire_timeout` for database-mode tenant pools — how long
    /// `pool.acquire()` waits for an available connection before
    /// erroring with `PoolTimedOut`. Sqlx's default is 30s.
    /// Default: 30s.
    pub database_pool_acquire_timeout: std::time::Duration,

    /// `idle_timeout` — close connections that have sat idle this
    /// long. `None` keeps idle connections forever (sqlx default).
    /// Set when running against a load balancer / Postgres with
    /// `idle_in_transaction_session_timeout` to avoid stale-
    /// connection errors. Default: `Some(10 minutes)`.
    pub database_pool_idle_timeout: Option<std::time::Duration>,

    /// `max_lifetime` — force a connection to be recycled after
    /// this duration, regardless of activity. Helps with rolling
    /// PG credential rotations (vault leases, cloud IAM tokens).
    /// `None` disables. Default: `Some(30 minutes)`.
    pub database_pool_max_lifetime: Option<std::time::Duration>,

    /// When `true`, [`TenantPools`] eagerly builds pools for every
    /// active database-mode tenant at construction time (`new()` /
    /// `with_secrets()`). Bounded by `max_cached_database_pools`.
    /// Schema-mode tenants are never pre-warmed (they share the
    /// registry pool which is already up). Default: `false`.
    pub prewarm_active_tenants: bool,

    // v0.53 — schema-mode scoped-pool caching (#1235).
    /// Maximum number of schema-mode *scoped* pools cached
    /// simultaneously — the `search_path`-baked pools handed out by
    /// [`TenantPools::scoped_pool`].
    ///
    /// Counted separately from `max_cached_database_pools` on
    /// purpose: sharing one budget would silently halve a mixed
    /// deployment's database-mode capacity the moment schema-mode
    /// tenants started consuming slots.
    ///
    /// Past the cap the most idle scoped pool is evicted and the new
    /// tenant takes its slot. Safe here because a scoped pool is
    /// cheap to rebuild: same server, only `search_path` differs.
    /// Before 0.57.12 it returned an uncached pool per call instead,
    /// uncapped (#1528).
    ///
    /// Budget the worst case as `2 * max_cached_scoped_pools *
    /// scoped_pool_max_connections` concurrent connections against
    /// the registry server (held connections have their own pool),
    /// and keep that under its `max_connections`. The default pair
    /// gives 2 × 64 × 8 = 1024, far
    /// above a stock Postgres' 100 — but that ceiling needs every
    /// cached tenant saturated simultaneously, and these pools hold no
    /// idle connections (`min_connections = 0` plus
    /// `database_pool_idle_timeout`), so a quiet tenant costs nothing.
    /// Lower this, or `scoped_pool_max_connections`, if your registry
    /// server's limit is tight and your tenants are uniformly busy.
    /// Default: 64.
    pub max_cached_scoped_pools: usize,

    /// Per-pool `max_connections` for schema-mode scoped pools. Each
    /// tenant has two: `t.pool()`'s and the held connections', so one
    /// never waits on the other. Budget `2 * max_cached_scoped_pools *
    /// scoped_pool_max_connections` against the registry server's
    /// `max_connections`; quiet tenants hold none (`min_connections = 0`).
    /// Default: 8.
    pub scoped_pool_max_connections: u32,

    /// The app's media disks. With the `media` feature, purging a tenant
    /// deletes its `rustango_media` objects from them first (#2569).
    /// Default: `None` (objects are counted and left).
    pub media_storage: Option<crate::storage::StorageRegistry>,
}

impl Default for TenantPoolsConfig {
    fn default() -> Self {
        Self {
            max_cached_database_pools: 64,
            database_pool_max_connections: 16,
            // Below: zeros / None preserve pre-0.27.7 behavior so
            // existing apps don't see surprise behavior on upgrade.
            // Apps that want hot pools opt in via `.config(...)`.
            database_pool_min_connections: 0,
            database_pool_acquire_timeout: std::time::Duration::from_secs(30),
            database_pool_idle_timeout: Some(std::time::Duration::from_secs(10 * 60)),
            database_pool_max_lifetime: Some(std::time::Duration::from_secs(30 * 60)),
            prewarm_active_tenants: false,
            max_cached_scoped_pools: 64,
            // Raised from the pre-#1235 hardcoded 2: these pools are
            // shared per tenant now, and 2 deadlocks the documented
            // `Tenant::conn` + `t.pool()` + job-worker combination.
            scoped_pool_max_connections: 8,
            media_storage: None,
        }
    }
}

/// Outcome of [`TenantPools::prewarm_database_tenants`]. Counts —
/// not lists — so the type stays small enough to log + persist.
/// Per-tenant errors are written to the tracing log during
/// pre-warm; consumers needing them should subscribe to the
/// `crate::tenancy::pools` target.
#[derive(Debug, Clone, Copy, Default)]
pub struct PrewarmReport {
    /// Number of active database-mode tenants the registry returned.
    pub total_active: usize,
    /// Number of pools successfully built and cached.
    pub warmed: usize,
    /// Number of tenants whose pool build failed (skipped, not
    /// fatal — see tracing logs for details).
    pub failed: usize,
    /// Number of tenants skipped because the cache cap was already
    /// reached. Bump `TenantPoolsConfig::max_cached_database_pools`
    /// to pre-warm more.
    pub skipped_cap: usize,
}

/// One tenant's pool reference.
///
/// ## Two storage modes
///
/// **Database-mode** (`Database` variant) is the universal model —
/// each tenant has its own dedicated database (a separate PG database,
/// MySQL database, or SQLite file). Works on every backend. This is
/// the right choice for:
///   - Enterprise B2B (dozens to low hundreds of tenants)
///   - Compliance-sensitive deployments (physical data separation)
///   - Geographic sharding (each region has its own DB cluster)
///   - Anything on sqlite or mysql (database-mode is the only mode
///     these backends support)
///
/// **Schema-mode** (`Schema` variant, PG-only) is a PG-specific
/// optimization — every tenant shares one PG database and one
/// connection pool; tenants are isolated by PG schemas, with
/// `SET search_path` switching namespace per request. Use only when
/// you have high-N-low-revenue SaaS scale (500+ small tenants on PG)
/// and connection-count or per-tenant DB overhead actually bites.
///
/// `SET search_path` is a Postgres-only command — MySQL and SQLite
/// have no equivalent connection-scoped namespace switch. On those
/// backends, schema-mode is unavailable by language semantics; users
/// set `Org.storage_mode = "database"` and get equivalent isolation
/// via per-tenant databases/files.
///
/// ## Generic shape
///
/// Generic over the backend (`DB = sqlx::Postgres` by default — keeps
/// existing call sites compiling unchanged). The `Schema` variant
/// always carries a `PgPool` and is only constructed by
/// `impl TenantPools<sqlx::Postgres>::pool_for_org`. The `Database`
/// variant uses `Arc<sqlx::Pool<DB>>` so a sqlite-only or MySQL-only
/// stack can use this enum without any Postgres dependency at the
/// field level.
/// Default backend for `TenantPool<DB>` / `TenantPools<DB>` /
/// `TenantConn<DB>` so existing PG call sites that write `TenantPools`
/// (no param) keep compiling. On non-PG builds the default is the
/// first available backend in priority order: sqlite → mysql.
#[cfg(feature = "postgres")]
pub type DefaultTenantDb = sqlx::Postgres;
#[cfg(all(not(feature = "postgres"), feature = "sqlite"))]
pub type DefaultTenantDb = sqlx::Sqlite;
#[cfg(all(not(feature = "postgres"), not(feature = "sqlite"), feature = "mysql"))]
pub type DefaultTenantDb = sqlx::MySql;

/// A registry backend opened with the framework's pool setup: `[database]`
/// tuning, the checkout ping and, on SQLite, WAL and a created file.
// Without postgres, only `manage`'s tenancy runserver opens one.
#[cfg_attr(not(any(feature = "postgres", feature = "manage")), allow(dead_code))]
pub(crate) trait RegistryConnect: Database {
    fn connect_registry(
        url: &str,
    ) -> impl std::future::Future<Output = Result<sqlx::Pool<Self>, crate::sql::PoolError>> + Send;
}

#[cfg(feature = "postgres")]
impl RegistryConnect for sqlx::Postgres {
    fn connect_registry(
        url: &str,
    ) -> impl std::future::Future<Output = Result<sqlx::Pool<Self>, crate::sql::PoolError>> + Send
    {
        crate::sql::Pool::connect_postgres(url)
    }
}

#[cfg(feature = "sqlite")]
impl RegistryConnect for sqlx::Sqlite {
    fn connect_registry(
        url: &str,
    ) -> impl std::future::Future<Output = Result<sqlx::Pool<Self>, crate::sql::PoolError>> + Send
    {
        crate::sql::Pool::connect_sqlite(url)
    }
}

#[cfg(feature = "mysql")]
impl RegistryConnect for sqlx::MySql {
    fn connect_registry(
        url: &str,
    ) -> impl std::future::Future<Output = Result<sqlx::Pool<Self>, crate::sql::PoolError>> + Send
    {
        crate::sql::Pool::connect_mysql(url)
    }
}

#[derive(Debug)]
pub enum TenantPool<DB: Database = DefaultTenantDb> {
    /// Tenant data is in a schema in the (Postgres) registry DB. The
    /// pool is the registry pool; the schema name is set on each
    /// connection acquired through [`TenantPools::acquire`]. PG-only
    /// by language — `SET search_path` doesn't exist on MySQL or
    /// SQLite. Constructed only by `impl TenantPools<sqlx::Postgres>`.
    #[cfg(feature = "postgres")]
    Schema { schema: String, registry: PgPool },
    /// Tenant data is in a dedicated DB. Pool is owned by this variant
    /// and shared via `Arc` so callers can clone cheaply.
    Database { pool: Arc<sqlx::Pool<DB>> },
}

// Manual Clone so we don't need `DB: Clone` (sqlx::Pool<DB> is
// already cheap-Arc-clone).
impl<DB: Database> Clone for TenantPool<DB> {
    fn clone(&self) -> Self {
        match self {
            #[cfg(feature = "postgres")]
            Self::Schema { schema, registry } => Self::Schema {
                schema: schema.clone(),
                registry: registry.clone(),
            },
            Self::Database { pool } => Self::Database {
                pool: Arc::clone(pool),
            },
        }
    }
}

impl<DB: Database> TenantPool<DB> {
    /// `true` when this tenant's data lives in a Postgres schema
    /// inside the registry DB. `false` for database mode (or any
    /// non-PG backend, where Schema is unreachable).
    #[must_use]
    pub fn is_schema(&self) -> bool {
        #[cfg(feature = "postgres")]
        {
            matches!(self, Self::Schema { .. })
        }
        #[cfg(not(feature = "postgres"))]
        {
            false
        }
    }
}

#[cfg(feature = "postgres")]
impl TenantPool<sqlx::Postgres> {
    /// PG-typed pool accessor — schema-mode returns the shared
    /// registry pool, database-mode returns the dedicated tenant
    /// pool. Callers running through the pool **without first issuing
    /// `SET search_path`** will hit the wrong schema in schema-mode;
    /// prefer [`TenantPools::acquire`].
    ///
    /// PG-only — use the per-variant accessors below for non-PG
    /// `TenantPool<DB>` instances (database-mode only).
    #[must_use]
    pub fn pool(&self) -> &PgPool {
        match self {
            Self::Schema { registry, .. } => registry,
            Self::Database { pool } => pool,
        }
    }
}

/// Lazy connection registry for multi-tenant rustango. Constructed
/// once at boot from the registry pool + config + secrets resolver;
/// hands out [`TenantPool`] references at request time.
///
/// Generic over the backend (`DB = sqlx::Postgres` by default so
/// existing call sites compile unchanged). Schema-mode methods
/// (which require `SET search_path` and other Postgres-only SQL)
/// live on `impl TenantPools<sqlx::Postgres>` only — the type
/// system forbids schema-mode on non-PG. Database-mode methods are
/// generic and work on any backend.
/// A cached tenant pool plus its LRU stamp. The stamp is a counter,
/// not a clock — eviction needs only the ordering.
///
/// Shared with [`super::database_pools`] so the two never drift into
/// different cap policies, which is how they got here (#1527).
pub(super) struct CachedPool<DB: Database> {
    pub(super) pool: Arc<sqlx::Pool<DB>>,
    source: PoolSource,
    last_used: AtomicU64,
}

/// What a cached pool was built from. An `Org` naming another source is
/// a miss, so an edit made by another process reaches this one (#1882).
/// No `Debug`: the URL can carry a password.
#[derive(Clone, PartialEq, Eq, Hash)]
pub(super) enum PoolSource {
    /// `Org.database_url` as stored (the secret reference, unresolved).
    Database(Option<String>),
    /// The schema baked into the pool's `search_path`.
    #[cfg_attr(not(feature = "postgres"), allow(dead_code))]
    Schema(String),
}

impl PoolSource {
    pub(super) fn database(org: &Org) -> Self {
        Self::Database(org.database_url.clone())
    }
}

impl<DB: Database> CachedPool<DB> {
    pub(super) fn new(pool: Arc<sqlx::Pool<DB>>, source: PoolSource, tick: u64) -> Self {
        Self {
            pool,
            source,
            last_used: AtomicU64::new(tick),
        }
    }

    /// The cached pool for `slug`, only if it was built from `source`.
    pub(super) fn lookup<'a>(
        cache: &'a HashMap<String, Self>,
        slug: &str,
        source: &PoolSource,
    ) -> Option<&'a Self> {
        cache.get(slug).filter(|entry| entry.source == *source)
    }

    /// Mark as just used. Takes `&self` so a hit records itself under
    /// the read lock.
    pub(super) fn touch(&self, tick: u64) {
        self.last_used.store(tick, Ordering::Relaxed);
    }
}

/// One build at a time per slug and source, so a cold tenant hit by many
/// requests resolves its secret and connects once. Requests that wait get
/// that build's outcome, its error included, so they fail together.
pub(super) struct SingleFlight<T>(std::sync::Mutex<HashMap<FlightKey, Weak<Flight<T>>>>);

/// A request for a moved tenant must not join a build for its old source.
#[derive(Clone, PartialEq, Eq, Hash)]
struct FlightKey {
    slug: String,
    source: PoolSource,
}

/// `None` until the build finishes; a cancelled build leaves it `None`.
type Flight<T> = tokio::sync::Mutex<Option<Result<T, TenancyError>>>;

impl<T> Default for SingleFlight<T> {
    fn default() -> Self {
        Self(std::sync::Mutex::default())
    }
}

impl<T: Clone> SingleFlight<T> {
    /// Run `build` unless a flight for `slug` from `source` is under way;
    /// then share its outcome.
    pub(super) async fn run(
        &self,
        slug: &str,
        source: &PoolSource,
        build: impl std::future::Future<Output = Result<T, TenancyError>>,
    ) -> Result<T, TenancyError> {
        let key = FlightKey {
            slug: slug.to_owned(),
            source: source.clone(),
        };
        let flight = {
            let mut map = self.map();
            map.retain(|_, f| f.strong_count() > 0);
            if let Some(f) = map.get(&key).and_then(Weak::upgrade) {
                f
            } else {
                let f = Arc::new(tokio::sync::Mutex::new(None));
                map.insert(key.clone(), Arc::downgrade(&f));
                f
            }
        };
        let mut done = flight.lock().await;
        let copy = |o: &Result<T, TenancyError>| match o {
            Ok(v) => Ok(v.clone()),
            Err(e) => Err(shared_error(e)),
        };
        if let Some(outcome) = done.as_ref() {
            return copy(outcome);
        }
        let out = build.await;
        *done = Some(copy(&out));
        // Later arrivals start a fresh flight: a failure is not cached.
        let mut map = self.map();
        if map
            .get(&key)
            .is_some_and(|f| f.as_ptr() == Arc::as_ptr(&flight))
        {
            map.remove(&key);
        }
        out
    }

    fn map(&self) -> std::sync::MutexGuard<'_, HashMap<FlightKey, Weak<Flight<T>>>> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner)
    }

    #[cfg(test)]
    fn len(&self) -> usize {
        self.map().len()
    }
}

/// A copy of a failed build's error for another waiter. Text-only
/// variants copy as they are; the rest keep their message and kind.
fn shared_error(e: &TenancyError) -> TenancyError {
    use super::secrets::SecretsError;
    match e {
        TenancyError::Resolution(s) => TenancyError::Resolution(s.clone()),
        TenancyError::Validation(s) => TenancyError::Validation(s.clone()),
        TenancyError::Busy => TenancyError::Busy,
        TenancyError::Secrets(SecretsError::NotFound(s)) => {
            TenancyError::Secrets(SecretsError::NotFound(s.clone()))
        }
        TenancyError::Secrets(SecretsError::Invalid(s)) => {
            TenancyError::Secrets(SecretsError::Invalid(s.clone()))
        }
        TenancyError::Secrets(SecretsError::Backend(b)) => {
            TenancyError::Secrets(SecretsError::Backend(b.to_string().into()))
        }
        TenancyError::Driver(sqlx::Error::PoolTimedOut) => {
            TenancyError::Driver(sqlx::Error::PoolTimedOut)
        }
        other => TenancyError::Driver(sqlx::Error::Io(std::io::Error::other(other.to_string()))),
    }
}

/// Drop least-recently-used entries until one more fits under `cap`,
/// returning the evicted slugs to log. Evicting only drops this map's
/// handle; sqlx pools are ref-counted, so a live holder keeps theirs.
pub(super) fn evict_to_fit<DB: Database>(
    cache: &mut HashMap<String, CachedPool<DB>>,
    cap: usize,
) -> Vec<String> {
    let mut evicted = Vec::new();
    // `cap == 0` would loop forever looking for room that cannot
    // exist; callers treat 0 as "do not cache".
    while cap > 0 && cache.len() >= cap {
        let Some(victim) = cache
            .iter()
            .min_by_key(|(_, entry)| entry.last_used.load(Ordering::Relaxed))
            .map(|(slug, _)| slug.clone())
        else {
            break;
        };
        cache.remove(&victim);
        evicted.push(victim);
    }
    evicted
}

pub struct TenantPools<DB: Database = DefaultTenantDb> {
    registry: sqlx::Pool<DB>,
    config: TenantPoolsConfig,
    secrets: TenantSecrets,
    /// Source of `CachedPool::last_used` stamps, shared by both caches
    /// so their orderings never collide.
    lru_tick: AtomicU64,
    /// Latch for the near-cap warning, so it fires on the crossing
    /// rather than on every insert (#1528).
    warned_near_cap: std::sync::atomic::AtomicBool,
    cache: RwLock<HashMap<String, CachedPool<DB>>>,
    /// Schema-mode scoped pools, keyed by `slug` (#1235). Separate
    /// from `cache` so the two capacity budgets can't cannibalise
    /// each other. Generic over `DB` rather than `PgPool`-typed so
    /// this file still builds under `--no-default-features --features
    /// sqlite,tenancy`; only the Postgres impl ever populates it.
    scoped_cache: RwLock<HashMap<String, CachedPool<DB>>>,
    /// Schema-mode pools [`TenantPools::acquire`] takes held connections
    /// from: per tenant, so a busy one never takes the registry's.
    held_cache: RwLock<HashMap<String, CachedPool<DB>>>,
    /// Database-mode pools [`TenantPools::acquire`] takes held connections
    /// from, apart from `cache`'s: one shared pool deadlocked at its max.
    held_database_cache: RwLock<HashMap<String, CachedPool<DB>>>,
    /// Single-flight for `cache` and `scoped_cache` misses.
    building: SingleFlight<Arc<sqlx::Pool<DB>>>,
    #[cfg_attr(not(feature = "postgres"), allow(dead_code))]
    building_held_database: SingleFlight<Arc<sqlx::Pool<DB>>>,
    #[cfg_attr(not(feature = "postgres"), allow(dead_code))]
    building_scoped: SingleFlight<sqlx::Pool<DB>>,
    #[cfg_attr(not(feature = "postgres"), allow(dead_code))]
    building_held: SingleFlight<sqlx::Pool<DB>>,
}

/// Which of a tenant's two pools. Two, so a request holding a
/// connection can still query through `t.pool()` at its max size.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PoolUse {
    /// [`TenantPools::scoped_pool`]'s.
    Queries,
    /// [`TenantPools::acquire`]'s.
    #[cfg_attr(not(feature = "postgres"), allow(dead_code))]
    Held,
}

impl<DB: Database> TenantPools<DB> {
    /// Construct with [`ChainSecretsResolver::standard`]: `env://`, sealed
    /// `enc:` and literal URLs all resolve. Every built-in surface (builder,
    /// manage CLI, console) gets its pools here.
    #[must_use]
    pub fn new(registry: sqlx::Pool<DB>) -> Self {
        Self::with_secrets(registry, ChainSecretsResolver::standard())
    }

    /// Construct with a user-supplied [`SecretsResolver`]. Use
    /// [`super::EnvSecretsResolver`] / [`super::ChainSecretsResolver`]
    /// for env-var lookup, or implement the trait yourself for vault
    /// integration.
    #[must_use]
    pub fn with_secrets<R: SecretsResolver>(registry: sqlx::Pool<DB>, secrets: R) -> Self {
        Self {
            registry,
            config: TenantPoolsConfig::default(),
            secrets: TenantSecrets::new(secrets),
            lru_tick: AtomicU64::new(0),
            warned_near_cap: std::sync::atomic::AtomicBool::new(false),
            cache: RwLock::new(HashMap::new()),
            scoped_cache: RwLock::new(HashMap::new()),
            held_cache: RwLock::new(HashMap::new()),
            held_database_cache: RwLock::new(HashMap::new()),
            building: SingleFlight::default(),
            building_held_database: SingleFlight::default(),
            building_scoped: SingleFlight::default(),
            building_held: SingleFlight::default(),
        }
    }

    /// Next LRU stamp. Relaxed is enough: the value only has to be
    /// unique and increasing, and every reader of it already holds the
    /// cache lock.
    fn next_tick(&self) -> u64 {
        self.lru_tick.fetch_add(1, Ordering::Relaxed)
    }

    /// Warn once a cache passes 80% of its cap, so the operator hears
    /// about it while it is still headroom and not an incident.
    ///
    /// Warns **once per crossing**, not once per insert. A cache that
    /// sits at its cap inserts on every miss, and an unbounded warn
    /// there floods the log with the message meant to be noticed
    /// (#1528). `warned_near_cap` latches on the way up and resets
    /// when occupancy falls back below the threshold, so a cache
    /// hovering on the boundary cannot chatter either.
    fn warn_if_near_cap(&self, len: usize, cap: usize, mode: &'static str) {
        if self.claim_near_cap_warning(len, cap) {
            tracing::warn!(
                target: "rustango::tenancy::pools",
                mode,
                cached = len,
                cap,
                "tenant pool cache is near its cap; past it, the least \
                 recently used tenant is evicted and reconnects on its \
                 next request",
            );
        }
    }

    /// `true` exactly once per crossing into the near-cap band.
    ///
    /// Separated from the logging so a test can count the *decisions*.
    /// Asserting the latch field instead would not catch the bug this
    /// exists to prevent: a version that warns every time while still
    /// setting the latch passes that assertion (#1528).
    fn claim_near_cap_warning(&self, len: usize, cap: usize) -> bool {
        if cap == 0 {
            return false;
        }
        if len * 5 >= cap * 4 {
            // `swap` is the whole point: only the transition claims it.
            !self.warned_near_cap.swap(true, Ordering::Relaxed)
        } else {
            self.warned_near_cap.store(false, Ordering::Relaxed);
            false
        }
    }

    /// Replace the config. Returns `self` for builder ergonomics.
    #[must_use]
    pub fn config(mut self, config: TenantPoolsConfig) -> Self {
        self.config = config;
        self
    }

    /// Read access to the current config. Used by `Server::Builder`
    /// to decide whether to call [`Self::prewarm_database_tenants`]
    /// on boot. (#60, v0.27.7)
    #[must_use]
    pub fn pool_config(&self) -> &TenantPoolsConfig {
        &self.config
    }

    /// v0.38 — backend-typed accessor for the registry `sqlx::Pool<DB>`.
    /// Cheap clone (sqlx pools are Arc-shaped).
    #[must_use]
    pub fn registry_inner(&self) -> &sqlx::Pool<DB> {
        &self.registry
    }

    /// How `database_url` references are opened and stored.
    pub(crate) fn secrets(&self) -> &TenantSecrets {
        &self.secrets
    }

    /// Refuse to store a password URL that cannot be sealed.
    #[must_use]
    pub fn require_sealed_secrets(mut self) -> Self {
        self.secrets = self.secrets.require_sealed();
        self
    }

    /// Same registry, config and secrets resolver; empty caches.
    pub(crate) fn fresh(&self) -> Self {
        let mut pools = Self::new(self.registry.clone()).config(self.config.clone());
        pools.secrets = self.secrets.clone();
        pools
    }
}

#[cfg(feature = "postgres")]
impl TenantPools<sqlx::Postgres> {
    /// The Postgres registry pool — for the legacy `&PgPool` API.
    /// Available only when the registry IS Postgres. For
    /// backend-agnostic access use [`Self::registry_pool`] (returns
    /// `&crate::sql::Pool` which dispatches per-backend through
    /// `fetch` / `insert_pool` / `save_pool`).
    #[must_use]
    pub fn registry(&self) -> &PgPool {
        &self.registry
    }
}

impl<DB: Database> TenantPools<DB>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    /// Same registry pool, wrapped in the backend-erasing
    /// [`rustango::sql::Pool`] enum. Used by the v0.34 resolver
    /// chain which is generic across backends — keeps a single
    /// `TenantPools` API while letting the resolver implementations
    /// route through `fetch` / `insert_pool`.
    ///
    /// Cheap: `Pool` is `Arc`-shaped under sqlx, so the clone is a
    /// reference bump.
    #[must_use]
    pub fn registry_pool(&self) -> crate::sql::Pool {
        crate::sql::Pool::from(self.registry.clone())
    }
}

// ============================================================ generic methods (any backend)

impl<DB: Database> TenantPools<DB> {
    /// Database-mode pool for `org`. Errors on schema-mode orgs —
    /// schema-mode dispatch lives on `impl TenantPools<Postgres>`
    /// only because `SET search_path` is Postgres-specific.
    ///
    /// For PG apps the public `pool_for_org` (on the PG impl) wraps
    /// this with schema-mode handling. Non-PG apps call this directly.
    ///
    /// # Errors
    /// * [`TenancyError::Validation`] for schema-mode orgs (non-PG),
    ///   malformed `storage_mode`, missing `database_url`, or cache
    ///   full.
    /// * [`TenancyError::Secrets`] / [`TenancyError::Driver`] from
    ///   the secret resolve + pool build path.
    pub async fn database_pool_for_org(&self, org: &Org) -> Result<TenantPool<DB>, TenancyError> {
        let mode = StorageMode::parse(&org.storage_mode).map_err(|got| {
            TenancyError::Validation(format!(
                "org `{}` has unknown storage_mode `{got}` (expected `schema` or `database`)",
                org.slug
            ))
        })?;
        match mode {
            StorageMode::Schema => Err(TenancyError::Validation(format!(
                "org `{}` has `storage_mode = 'schema'` but TenantPools<{dbname}> is non-Postgres. \
                 Schema-mode is a Postgres-only optimization (uses `SET search_path` — no \
                 equivalent on MySQL/SQLite). Switch this org to `storage_mode = 'database'` and \
                 set `database_url` to its dedicated database / file; isolation semantics are \
                 equivalent.",
                org.slug,
                dbname = std::any::type_name::<DB>(),
            ))),
            StorageMode::Database => {
                let pool = self.pool_for_database_mode(org).await?;
                Ok(TenantPool::Database { pool })
            }
        }
    }

    /// Database-mode tenant connection — errors on schema-mode orgs.
    /// Generic counterpart of [`Self::acquire`] (PG-only).
    ///
    /// # Errors
    /// As [`Self::database_pool_for_org`].
    pub async fn database_acquire(&self, org: &Org) -> Result<TenantConn<DB>, TenancyError> {
        let pool = self.database_pool_for_org(org).await?;
        #[cfg_attr(not(feature = "postgres"), allow(irrefutable_let_patterns))]
        let TenantPool::Database { pool } = pool
        else {
            unreachable!("database_pool_for_org rejects schema-mode")
        };
        Ok(TenantConn::database(pool.acquire().await?))
    }

    /// Drop a tenant's cached pools. Useful when the operator updates
    /// `Org.database_url` (vault rotation, migration to new server)
    /// and wants the next acquire to rebuild from the new URL.
    ///
    /// Evicts both the database-mode pool and the schema-mode scoped
    /// pool (#1235). The scoped pool bakes `search_path` into its
    /// connect options, so a tenant whose `schema_name` changed would
    /// otherwise keep being served a pool pointing at the old schema —
    /// a cross-tenant read, and the exact failure #1224 was about.
    pub async fn invalidate(&self, slug: &str) {
        self.cache.write().await.remove(slug);
        self.scoped_cache.write().await.remove(slug);
        self.held_cache.write().await.remove(slug);
        self.held_database_cache.write().await.remove(slug);
    }
}

/// v0.38 — backend-erasing handle for tenant-pool invalidation.
/// Used by the operator console (and any other surface that needs
/// to evict a tenant pool after a configuration change) to avoid
/// being generic over `DB`. Implemented by every `TenantPools<DB>`.
pub trait TenantPoolInvalidator: Send + Sync {
    /// Drop the cached pool for the given tenant slug. Idempotent.
    fn invalidate<'a>(
        &'a self,
        slug: &'a str,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>>;

    /// The tenant's literal connection URL, secret references resolved.
    ///
    /// Resolved here rather than handed to a caller's form: the URL
    /// carries a password, and the console must be able to act on it
    /// without it ever reaching a browser.
    fn resolved_database_url<'a>(
        &'a self,
        org: &'a super::org::Org,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<String, super::error::TenancyError>>
                + Send
                + 'a,
        >,
    >;

    /// How tenant URLs are opened and stored, so an edit can check a new
    /// reference before it is written. No default: a fallback would drop
    /// the deployment's `require_sealed_secrets()`.
    ///
    /// ```compile_fail
    /// # use rustango::tenancy::{Org, PrewarmReport, TenancyError, TenantPoolInvalidator};
    /// # use rustango::tenancy::decommission::{Action, Report};
    /// # use std::{future::Future, pin::Pin};
    /// struct NoSecrets;
    /// impl TenantPoolInvalidator for NoSecrets {
    ///     fn invalidate<'a>(&'a self, _: &'a str) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
    ///         Box::pin(async {})
    ///     }
    ///     fn resolved_database_url<'a>(&'a self, _: &'a Org)
    ///         -> Pin<Box<dyn Future<Output = Result<String, TenancyError>> + Send + 'a>> {
    ///         unimplemented!()
    ///     }
    ///     fn decommission<'a>(&'a self, _: &'a str, _: Action)
    ///         -> Pin<Box<dyn Future<Output = Result<Report, TenancyError>> + Send + 'a>> {
    ///         unimplemented!()
    ///     }
    ///     fn prewarm<'a>(&'a self)
    ///         -> Pin<Box<dyn Future<Output = Result<PrewarmReport, TenancyError>> + Send + 'a>> {
    ///         unimplemented!()
    ///     }
    /// }
    /// ```
    fn tenant_secrets(&self) -> TenantSecrets;

    /// Take a tenant out of service — see
    /// [`crate::tenancy::decommission`].
    ///
    /// Here because it is the same erasure and the same capability: a
    /// surface holding this handle is one allowed to change tenants,
    /// and decommissioning invalidates the pool anyway.
    fn decommission<'a>(
        &'a self,
        slug: &'a str,
        action: super::decommission::Action,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<super::decommission::Report, super::error::TenancyError>,
                > + Send
                + 'a,
        >,
    >;

    /// Open a pool for every active database-mode tenant, up front.
    ///
    /// Here for the same reason as `decommission`: it is the same
    /// erasure, and a surface that can invalidate pools is one that can
    /// warm them. Without it `prewarm-pools` stays command-line only,
    /// which is the gap #1341 is about.
    fn prewarm<'a>(
        &'a self,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<PrewarmReport, super::error::TenancyError>>
                + Send
                + 'a,
        >,
    >;
}

impl<DB: Database> TenantPoolInvalidator for TenantPools<DB>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    fn invalidate<'a>(
        &'a self,
        slug: &'a str,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
        Box::pin(async move { TenantPools::<DB>::invalidate(self, slug).await })
    }

    fn resolved_database_url<'a>(
        &'a self,
        org: &'a super::org::Org,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<String, super::error::TenancyError>>
                + Send
                + 'a,
        >,
    > {
        Box::pin(async move { TenantPools::<DB>::resolved_database_url(self, org).await })
    }

    fn tenant_secrets(&self) -> TenantSecrets {
        self.secrets.clone()
    }

    fn decommission<'a>(
        &'a self,
        slug: &'a str,
        action: super::decommission::Action,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<super::decommission::Report, super::error::TenancyError>,
                > + Send
                + 'a,
        >,
    > {
        Box::pin(async move { super::decommission::decommission(self, slug, action).await })
    }

    fn prewarm<'a>(
        &'a self,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<PrewarmReport, super::error::TenancyError>>
                + Send
                + 'a,
        >,
    > {
        Box::pin(async move { TenantPools::<DB>::prewarm_database_tenants(self).await })
    }
}

#[allow(dead_code)]
impl<DB: Database> TenantPools<DB> {
    /// Type-erase this `TenantPools<DB>` into an
    /// `Arc<dyn TenantPoolInvalidator>` for surfaces that only need
    /// the invalidation hook (operator console, admin handlers that
    /// rotate config). Avoids cascading `<DB>` generics through
    /// non-query layers.
    #[must_use]
    pub fn into_invalidator(self: Arc<Self>) -> Arc<dyn TenantPoolInvalidator>
    where
        crate::sql::Pool: From<sqlx::Pool<DB>>,
    {
        self
    }

    /// Resolve `org.database_url` through the configured
    /// [`SecretsResolver`] and return the literal connection URL.
    /// Schema-mode orgs have no database_url — passing one returns
    /// [`TenancyError::Validation`].
    ///
    /// # Errors
    /// * [`TenancyError::Validation`] when `org.database_url` is `None`.
    /// * [`TenancyError::Secrets`] when the secret reference fails to
    ///   resolve.
    pub async fn resolved_database_url(&self, org: &Org) -> Result<String, TenancyError> {
        let reference = org.database_url.as_deref().ok_or_else(|| {
            TenancyError::Validation(format!(
                "org `{}` has no `database_url` to resolve (schema mode?)",
                org.slug
            ))
        })?;
        self.resolve_secret(reference).await
    }

    /// A `database_url` value (literal or secret reference) as a literal URL.
    pub(crate) async fn resolve_secret(&self, reference: &str) -> Result<String, TenancyError> {
        Ok(self.secrets.resolve(reference).await?)
    }

    /// Number of database-mode pools currently cached. Schema-mode
    /// tenants don't count.
    pub async fn cached_database_pool_count(&self) -> usize {
        self.cache.read().await.len()
    }

    /// Number of schema-mode scoped pools currently cached.
    pub async fn cached_scoped_pool_count(&self) -> usize {
        self.scoped_cache.read().await.len()
    }

    /// A cache hit. Recording it needs only `&`, so the LRU stamp costs
    /// no write lock.
    fn database_cache_for(&self, of: PoolUse) -> &RwLock<HashMap<String, CachedPool<DB>>> {
        match of {
            PoolUse::Queries => &self.cache,
            PoolUse::Held => &self.held_database_cache,
        }
    }

    async fn cached_database_pool(
        &self,
        slug: &str,
        source: &PoolSource,
        of: PoolUse,
    ) -> Option<Arc<sqlx::Pool<DB>>> {
        let cache = self.database_cache_for(of).read().await;
        let entry = CachedPool::lookup(&cache, slug, source)?;
        entry.touch(self.next_tick());
        Some(Arc::clone(&entry.pool))
    }

    async fn pool_for_database_mode(&self, org: &Org) -> Result<Arc<sqlx::Pool<DB>>, TenancyError> {
        self.database_mode_pool(org, PoolUse::Queries).await
    }

    /// The tenant's cached `of` pool, built on a miss.
    async fn database_mode_pool(
        &self,
        org: &Org,
        of: PoolUse,
    ) -> Result<Arc<sqlx::Pool<DB>>, TenancyError> {
        let source = PoolSource::database(org);
        if let Some(pool) = self.cached_database_pool(&org.slug, &source, of).await {
            return Ok(pool);
        }
        let build = self.build_database_mode(org, source.clone(), of);
        if self.config.max_cached_database_pools == 0 {
            // Nothing is cached, so there is nothing to share.
            return build.await;
        }
        let flight = match of {
            PoolUse::Queries => &self.building,
            PoolUse::Held => &self.building_held_database,
        };
        flight.run(&org.slug, &source, build).await
    }

    async fn build_database_mode(
        &self,
        org: &Org,
        source: PoolSource,
        of: PoolUse,
    ) -> Result<Arc<sqlx::Pool<DB>>, TenancyError> {
        // A flight that started after another finished finds its pool here.
        if let Some(pool) = self.cached_database_pool(&org.slug, &source, of).await {
            return Ok(pool);
        }
        // Cache miss — instrument so the cold path is visible in
        // tracing output. (#60, v0.27.7)
        let span = tracing::info_span!("tenant_pool_init", slug = %org.slug, mode = "database");
        // `.instrument`, not `enter()`: a guard held across `.await`
        // tags other tasks' events with this tenant (#1884).
        async {
            let resolve_start = std::time::Instant::now();
            // Resolve + connect outside the write lock so vault calls
            // don't block other tenants' lookups.
            let reference = org.database_url.as_deref().ok_or_else(|| {
                TenancyError::Validation(format!(
                    "org `{}` is `storage_mode = database` but has no `database_url`",
                    org.slug
                ))
            })?;
            let url = self.secrets.resolve(reference).await?;
            tracing::debug!(
                target: "rustango::tenancy::pools",
                slug = %org.slug,
                elapsed_ms = resolve_start.elapsed().as_millis() as u64,
                "secrets resolver resolved tenant URL",
            );
            let connect_start = std::time::Instant::now();
            let tag = org.id.get().map(|id| tenant_session_tag(*id));
            let url = tag_postgres_url(&url, tag.as_deref());
            // Held connections keep no idle ones: `min` is the queries' pool's.
            let min = match of {
                PoolUse::Queries => self.config.database_pool_min_connections,
                PoolUse::Held => 0,
            };
            let pool = build_database_pool::<DB>(&url, &self.config, min).await?;
            tracing::info!(
                target: "rustango::tenancy::pools",
                slug = %org.slug,
                elapsed_ms = connect_start.elapsed().as_millis() as u64,
                min_conn = self.config.database_pool_min_connections,
                max_conn = self.config.database_pool_max_connections,
                "tenant pool connected (database mode)",
            );
            let pool = Arc::new(pool);

            // Insert under write lock; check for race, then make room.
            let mut cache = self.database_cache_for(of).write().await;
            if let Some(existing) = CachedPool::lookup(&cache, &org.slug, &source) {
                existing.touch(self.next_tick());
                return Ok(Arc::clone(&existing.pool));
            }
            // A pool built from an older source is replaced, not kept.
            cache.remove(&org.slug);
            // Evict rather than refuse: refusing left tenant 65 down until
            // restart (#1527).
            for slug in evict_to_fit(&mut cache, self.config.max_cached_database_pools) {
                tracing::info!(
                    target: "rustango::tenancy::pools",
                    evicted = %slug,
                    for_slug = %org.slug,
                    cap = self.config.max_cached_database_pools,
                    "evicted the least recently used tenant pool to make room",
                );
            }
            if self.config.max_cached_database_pools == 0 {
                // Caching disabled: hand back the pool without storing it.
                return Ok(pool);
            }
            cache.insert(
                org.slug.clone(),
                CachedPool::new(Arc::clone(&pool), source, self.next_tick()),
            );
            if of == PoolUse::Queries {
                self.warn_if_near_cap(
                    cache.len(),
                    self.config.max_cached_database_pools,
                    "database",
                );
            }
            Ok(pool)
        }
        .instrument(span)
        .await
    }
}

impl<DB: Database> TenantPools<DB>
where
    crate::sql::Pool: From<sqlx::Pool<DB>>,
{
    /// v0.38 — backend-agnostic counterpart of
    /// [`Self::scoped_pool`] (PG-only). For schema-mode tenants on
    /// Postgres this returns `Pool::Postgres(scoped_pool)` where the
    /// pool has `search_path` baked into its connect options. For
    /// database-mode tenants (any backend) it wraps the cached
    /// tenant pool as a `crate::sql::Pool` enum. The schema-mode
    /// branch can only fire when `DB = sqlx::Postgres`; on other
    /// backends a schema-mode org returns the same
    /// [`TenancyError::Validation`] [`Self::database_pool_for_org`]
    /// would emit.
    ///
    /// # Errors
    /// As [`Self::database_pool_for_org`].
    pub async fn scoped_pool_dyn(&self, org: &Org) -> Result<crate::sql::Pool, TenancyError> {
        let mode = StorageMode::parse(&org.storage_mode).map_err(|got| {
            TenancyError::Validation(format!(
                "org `{}` has unknown storage_mode `{got}` (expected `schema` or `database`)",
                org.slug
            ))
        })?;
        match mode {
            StorageMode::Schema => {
                #[cfg(feature = "postgres")]
                {
                    // Only PG TenantPools<Postgres> can build a
                    // schema-mode scoped pool; on other backends
                    // schema-mode is forbidden by `database_pool_for_org`.
                    // Erase to `Pool::Postgres` if our DB happens to be PG.
                    if let Some(pg_pools) =
                        (self as &dyn std::any::Any).downcast_ref::<TenantPools<sqlx::Postgres>>()
                    {
                        let scoped = pg_pools.scoped_pool(org).await?;
                        return Ok(crate::sql::Pool::Postgres(scoped));
                    }
                }
                Err(TenancyError::Validation(format!(
                    "org `{}` has `storage_mode = 'schema'` but TenantPools<{dbname}> is \
                     non-Postgres. Schema-mode is a Postgres-only optimization (uses \
                     `SET search_path` — no equivalent on MySQL/SQLite). Switch this org to \
                     `storage_mode = 'database'` and set `database_url` to its dedicated \
                     database / file; isolation semantics are equivalent.",
                    org.slug,
                    dbname = std::any::type_name::<DB>(),
                )))
            }
            StorageMode::Database => {
                let pool = self.pool_for_database_mode(org).await?;
                Ok(crate::sql::Pool::from((*pool).clone()))
            }
        }
    }

    /// [`Self::scoped_pool_dyn`], but a SQLite file is opened with `mode=rw`,
    /// which never creates it: a missing file is unreadable, not empty
    /// (#2393, #2569). `true` when the pool is this call's own, to close.
    pub(crate) async fn existing_pool_dyn(
        &self,
        org: &Org,
    ) -> Result<(crate::sql::Pool, bool), TenancyError> {
        if org.storage_mode == "database" && org.database_url.is_some() {
            let url = self.resolved_database_url(org).await?;
            if url.starts_with("sqlite:") {
                let pool = crate::sql::Pool::connect(&sqlite_without_create(&url))
                    .await
                    .map_err(|e| TenancyError::Validation(e.to_string()))?;
                return Ok((pool, true));
            }
        }
        Ok((self.scoped_pool_dyn(org).await?, false))
    }

    /// Pre-warm pools for every active database-mode tenant. Useful
    /// at boot so the *first* request per tenant doesn't pay TCP +
    /// TLS + auth + sqlx-ramp-up on the hot path. Bounded by
    /// `config.max_cached_database_pools` — extras beyond the cap
    /// are skipped with a `tracing::warn!`. Schema-mode tenants
    /// share the registry pool and are never pre-warmed.
    ///
    /// Failures on individual tenants don't abort the rest — the
    /// returned report counts successes / failures. (#60, v0.27.7)
    ///
    /// # Errors
    /// Returns [`TenancyError`] only for the registry-side `Org`
    /// query that lists active tenants. Per-tenant connect failures
    /// are surfaced in [`PrewarmReport`] without aborting the loop.
    pub async fn prewarm_database_tenants(&self) -> Result<PrewarmReport, TenancyError> {
        use crate::core::Column as _;
        use crate::sql::FetcherPool as _;
        let span = tracing::info_span!("tenant_pools_prewarm");
        async {
            let started = std::time::Instant::now();
            let registry_pool = self.registry_pool();
            let orgs: Vec<Org> = Org::objects()
                .where_(Org::storage_mode.eq("database".to_owned()))
                .where_(Org::active.eq(true))
                .fetch(&registry_pool)
                .await?;
            let total = orgs.len();
            let mut report = PrewarmReport {
                total_active: total,
                warmed: 0,
                failed: 0,
                skipped_cap: 0,
            };
            for org in orgs {
                if self.cache.read().await.len() >= self.config.max_cached_database_pools {
                    tracing::warn!(
                        target: "rustango::tenancy::pools",
                        slug = %org.slug,
                        cap = self.config.max_cached_database_pools,
                        "skipping pre-warm: cache cap reached",
                    );
                    report.skipped_cap += 1;
                    continue;
                }
                match self.pool_for_database_mode(&org).await {
                    Ok(_) => report.warmed += 1,
                    Err(e) => {
                        tracing::warn!(
                            target: "rustango::tenancy::pools",
                            slug = %org.slug,
                            error = %e,
                            "pre-warm failed for tenant",
                        );
                        report.failed += 1;
                    }
                }
            }
            tracing::info!(
                target: "rustango::tenancy::pools",
                elapsed_ms = started.elapsed().as_millis() as u64,
                total = report.total_active,
                warmed = report.warmed,
                failed = report.failed,
                skipped_cap = report.skipped_cap,
                "prewarm complete",
            );
            Ok(report)
        }
        .instrument(span)
        .await
    }
}

// ============================================================ PG-only schema-mode methods

#[cfg(feature = "postgres")]
impl TenantPools<sqlx::Postgres> {
    /// Build (or fetch from cache) the pool for `org`. Schema-mode
    /// resolves immediately to the shared registry pool; database-mode
    /// reaches into the cache and builds-on-miss.
    ///
    /// PG-only because schema mode requires `SET search_path` which
    /// only Postgres has. For non-PG apps, call
    /// [`Self::database_pool_for_org`] directly.
    ///
    /// # Errors
    /// As [`Self::database_pool_for_org`].
    pub async fn pool_for_org(
        &self,
        org: &Org,
    ) -> Result<TenantPool<sqlx::Postgres>, TenancyError> {
        let mode = StorageMode::parse(&org.storage_mode).map_err(|got| {
            TenancyError::Validation(format!(
                "org `{}` has unknown storage_mode `{got}` (expected `schema` or `database`)",
                org.slug
            ))
        })?;
        match mode {
            StorageMode::Schema => {
                let schema = org.effective_schema().to_owned();
                Ok(TenantPool::Schema {
                    schema,
                    registry: self.registry.clone(),
                })
            }
            StorageMode::Database => {
                let pool = self.pool_for_database_mode(org).await?;
                Ok(TenantPool::Database { pool })
            }
        }
    }

    /// Acquire a connection scoped to the tenant. For schema mode it
    /// comes from a per-tenant pool with `search_path` in its connect
    /// options, separate from [`Self::scoped_pool`]'s, so one busy
    /// tenant can block neither the others nor its own `t.pool()`.
    /// With `max_cached_scoped_pools = 0` it is a registry connection
    /// with `SET search_path`, reset on release.
    /// For database mode it comes from the tenant's second pool, apart
    /// from the one `t.pool()` uses, for the same reason.
    ///
    /// # Errors
    /// As [`Self::pool_for_org`] plus a [`TenancyError::Driver`] for
    /// the schema-mode pool build.
    pub async fn acquire(&self, org: &Org) -> Result<TenantConn<sqlx::Postgres>, TenancyError> {
        match self.pool_for_org(org).await? {
            // No cache: a pool per call would connect per request.
            TenantPool::Schema { schema, registry } if self.config.max_cached_scoped_pools == 0 => {
                let conn = registry.acquire().await?;
                // Reset installed before the `SET`, so a cancel cannot
                // return it to the shared pool still scoped.
                let mut tc = TenantConn {
                    inner: Some(conn),
                    schema: Some(schema.clone()),
                    reset: Some(reset_pg_registry_conn),
                };
                // Statements prepared under another `search_path` keep its
                // result type: reused here they fail with 0A000.
                sqlx::Connection::clear_cached_statements(&mut **tc).await?;
                let stmt = format!("SET search_path TO {}", search_path(&schema));
                rustango::sql::sqlx::query(&stmt).execute(&mut **tc).await?;
                Ok(tc)
            }
            TenantPool::Schema { schema, registry } => {
                let pool = self
                    .schema_mode_pool(org, schema.clone(), registry, PoolUse::Held)
                    .await?;
                // The reset restores the connect-time `search_path`,
                // undoing a handler's own `SET` before the next borrower.
                Ok(TenantConn {
                    inner: Some(pool.acquire().await?),
                    schema: Some(schema),
                    reset: Some(reset_pg_search_path),
                })
            }
            // Uncached, each call builds its own pool, so none is shared.
            TenantPool::Database { pool } if self.config.max_cached_database_pools == 0 => {
                Ok(TenantConn::database(pool.acquire().await?))
            }
            TenantPool::Database { .. } => {
                let held = self.database_mode_pool(org, PoolUse::Held).await?;
                Ok(TenantConn::database(held.acquire().await?))
            }
        }
    }

    /// Owned, tenant-scoped [`PgPool`]. In schema mode the underlying
    /// registry pool is shared and has no `search_path` set, so handing
    /// it to ORM helpers that take `&PgPool` would route queries to
    /// `public` instead of the tenant schema. This builds a small
    /// dedicated pool with `search_path` baked into connect options so
    /// every checkout is correctly scoped. Database mode just clones
    /// the cached pool.
    ///
    /// Scoped pools are **cached per tenant** (#1235). They were built
    /// fresh on every call before, and the `Tenant` extractor calls
    /// this once per request — so a schema-mode app paid a TCP
    /// connect, TLS handshake and auth round-trip per request, and
    /// `PgPoolOptions::connect_with` is eager, so even a handler that
    /// only ever touched `Tenant::conn` paid it. That inverted the
    /// point of schema mode, which exists to *reduce* per-tenant
    /// connection overhead relative to database mode.
    ///
    /// Past `max_cached_scoped_pools` this evicts the least recently
    /// used scoped pool to make room — see that field for the
    /// connection arithmetic.
    ///
    /// Its connections are never reset on release: a handler that runs
    /// its own `SET search_path` (or other session `SET`) on one leaks it
    /// to the next borrower. Use [`Self::acquire`] for session state.
    ///
    /// # Errors
    /// As [`Self::pool_for_org`] plus [`TenancyError::Driver`] for
    /// the schema-mode dedicated pool build.
    pub async fn scoped_pool(&self, org: &Org) -> Result<PgPool, TenancyError> {
        match self.pool_for_org(org).await? {
            TenantPool::Schema { schema, registry } => {
                self.schema_mode_pool(org, schema, registry, PoolUse::Queries)
                    .await
            }
            TenantPool::Database { pool } => Ok((*pool).clone()),
        }
    }

    fn scoped_cache_for(
        &self,
        of: PoolUse,
    ) -> &RwLock<HashMap<String, CachedPool<sqlx::Postgres>>> {
        match of {
            PoolUse::Queries => &self.scoped_cache,
            PoolUse::Held => &self.held_cache,
        }
    }

    /// The tenant's cached `of` pool, built on a miss.
    async fn schema_mode_pool(
        &self,
        org: &Org,
        schema: String,
        registry: PgPool,
        of: PoolUse,
    ) -> Result<PgPool, TenancyError> {
        // Fast path and single-flight, as in `pool_for_database_mode`.
        let source = PoolSource::Schema(schema.clone());
        if let Some(pool) = self.cached_scoped_pool(&org.slug, &source, of).await {
            return Ok(pool);
        }
        let build = self.build_schema_mode(org, schema, registry, source.clone(), of);
        if self.config.max_cached_scoped_pools == 0 {
            return build.await;
        }
        let flight = match of {
            PoolUse::Queries => &self.building_scoped,
            PoolUse::Held => &self.building_held,
        };
        flight.run(&org.slug, &source, build).await
    }

    async fn build_schema_mode(
        &self,
        org: &Org,
        schema: String,
        registry: PgPool,
        source: PoolSource,
        of: PoolUse,
    ) -> Result<PgPool, TenancyError> {
        if let Some(pool) = self.cached_scoped_pool(&org.slug, &source, of).await {
            return Ok(pool);
        }
        let span = tracing::info_span!("tenant_pool_init", slug = %org.slug, mode = "schema");
        async {
            let connect_start = std::time::Instant::now();
            let scoped = self.build_scoped_pool(&schema, &registry).await?;
            // Uncached, this runs per call: skip it rather than warn per request.
            if of == PoolUse::Queries && self.config.max_cached_scoped_pools > 0 {
                warn_on_public_fallthrough(&registry, &org.slug, &schema).await;
            }
            tracing::info!(
                target: "rustango::tenancy::pools",
                slug = %org.slug,
                schema = %schema,
                elapsed_ms = connect_start.elapsed().as_millis() as u64,
                max_conn = self.config.scoped_pool_max_connections,
                "tenant pool connected (schema mode)",
            );

            // Insert under write lock; check for race, then make room.
            let mut cache = self.scoped_cache_for(of).write().await;
            if let Some(existing) = CachedPool::lookup(&cache, &org.slug, &source) {
                existing.touch(self.next_tick());
                return Ok((*existing.pool).clone());
            }
            cache.remove(&org.slug);
            // Evict rather than skip the cache: skipping built a
            // fresh pool per request, uncapped (#1528). Safe here
            // because a scoped pool is cheap to rebuild.
            for slug in evict_to_fit(&mut cache, self.config.max_cached_scoped_pools) {
                tracing::info!(
                    target: "rustango::tenancy::pools",
                    evicted = %slug,
                    for_slug = %org.slug,
                    cap = self.config.max_cached_scoped_pools,
                    "evicted the least recently used scoped pool to make room",
                );
            }
            if self.config.max_cached_scoped_pools == 0 {
                return Ok(scoped);
            }
            cache.insert(
                org.slug.clone(),
                CachedPool::new(Arc::new(scoped.clone()), source, self.next_tick()),
            );
            self.warn_if_near_cap(cache.len(), self.config.max_cached_scoped_pools, "schema");
            Ok(scoped)
        }
        .instrument(span)
        .await
    }

    async fn cached_scoped_pool(
        &self,
        slug: &str,
        source: &PoolSource,
        of: PoolUse,
    ) -> Option<PgPool> {
        let cache = self.scoped_cache_for(of).read().await;
        let entry = CachedPool::lookup(&cache, slug, source)?;
        entry.touch(self.next_tick());
        Some((*entry.pool).clone())
    }

    /// Build one `search_path`-scoped pool against the registry
    /// server. Split out of [`Self::scoped_pool`] so the cache-miss
    /// path stays readable.
    async fn build_scoped_pool(
        &self,
        schema: &str,
        registry: &PgPool,
    ) -> Result<PgPool, TenancyError> {
        let mut opts = (*registry.connect_options()).clone();
        opts = opts.options([("search_path", search_path_option(schema))]);
        Ok(scoped_pool_options(&self.config).connect_with(opts).await?)
    }
}

/// Warn when `public` has tenant tables `schema` lacks: `search_path` ends
/// in `public`, so the tenant reads and writes those shared copies.
#[cfg(feature = "postgres")]
async fn warn_on_public_fallthrough(registry: &PgPool, slug: &str, schema: &str) {
    match tables_read_from_public(registry, schema).await {
        Ok(tables) if tables.is_empty() => {}
        Ok(tables) => tracing::warn!(
            target: "rustango::tenancy::pools",
            slug,
            schema,
            tables = %tables.join(", "),
            "the tenant's schema lacks tables that `public` has, so its queries read and \
             write those shared copies; run `migrate-tenants` for it or deactivate it. \
             A later release stops falling through to `public`",
        ),
        Err(e) => tracing::debug!(
            target: "rustango::tenancy::pools",
            slug,
            error = %e,
            "could not compare the tenant's tables with `public`",
        ),
    }
}

/// The tenant-scoped model tables in `public` but not in `schema`.
#[cfg(feature = "postgres")]
async fn tables_read_from_public(
    registry: &PgPool,
    schema: &str,
) -> Result<Vec<String>, sqlx::Error> {
    let tenant: Vec<String> = inventory::iter::<crate::core::ModelEntry>
        .into_iter()
        .map(|e| e.schema)
        .filter(|s| s.scope == crate::core::ModelScope::Tenant && s.managed && !s.is_view)
        .map(|s| s.table.to_owned())
        .collect();
    sqlx::query_scalar(
        "SELECT c.relname::text FROM pg_catalog.pg_class c \
         JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
         WHERE n.nspname = 'public' AND c.relname = ANY($2) AND c.relkind IN ('r', 'p') \
         AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class t \
           JOIN pg_catalog.pg_namespace tn ON tn.oid = t.relnamespace \
           WHERE tn.nspname = $1 AND t.relname = c.relname) \
         ORDER BY 1",
    )
    .bind(schema)
    .bind(tenant)
    .fetch_all(registry)
    .await
}

/// A short-lived pool of at most `max` connections to the registry
/// server, scoped to `schema`. For migrations and manage commands.
///
/// `search_path` is a `SET` on connect, not a startup option, which
/// PgBouncer's transaction mode refuses; the pool is tagged so
/// [`crate::sql::Pool::scope_key`] still tells schemas apart.
#[cfg(feature = "postgres")]
pub(crate) async fn connect_schema_scoped(
    registry_url: &str,
    schema: &str,
    max: u32,
) -> Result<PgPool, TenancyError> {
    let stmt: Arc<str> = Arc::from(set_search_path_sql(schema));
    let pool = PgPoolOptions::new()
        .max_connections(max)
        .after_connect(move |conn, _meta| {
            let stmt = Arc::clone(&stmt);
            Box::pin(async move {
                sqlx::query(&stmt).execute(conn).await?;
                Ok(())
            })
        })
        .connect(registry_url)
        .await?;
    crate::sql::tag_schema_scope(&pool, schema);
    Ok(pool)
}

/// `SET search_path TO "<schema>", public`, the schema quoted.
#[cfg(feature = "postgres")]
fn set_search_path_sql(schema: &str) -> String {
    format!(
        "SET search_path TO {}, public",
        crate::sql::quote_with(schema, '"')
    )
}

/// Options of a schema-mode tenant pool.
#[cfg(feature = "postgres")]
pub(crate) fn scoped_pool_options(config: &TenantPoolsConfig) -> PgPoolOptions {
    // Min 0: these are cached and all point at the registry server, so
    // warm connections per tenant would make caching them expensive.
    tenant_pool_options(config, config.scoped_pool_max_connections, 0)
}

/// The one place a tenant pool's options are made, so none skips
/// `checkout_check`.
pub(crate) fn tenant_pool_options<DB: Database>(
    config: &TenantPoolsConfig,
    max: u32,
    min: u32,
) -> sqlx::pool::PoolOptions<DB> {
    let mut opts = sqlx::pool::PoolOptions::<DB>::new()
        .max_connections(max)
        .min_connections(min)
        .acquire_timeout(config.database_pool_acquire_timeout);
    if let Some(idle) = config.database_pool_idle_timeout {
        opts = opts.idle_timeout(idle);
    }
    if let Some(lifetime) = config.database_pool_max_lifetime {
        opts = opts.max_lifetime(lifetime);
    }
    crate::sql::checkout_check(opts, &crate::sql::pool_tuning())
}

/// Build a single database-mode tenant pool with the timeout /
/// keepalive / lifetime settings from `config`. Generic over the
/// backend — uses sqlx's generic `PoolOptions<DB>` so PG / MySQL /
/// SQLite all build through the same code path.
pub(crate) async fn build_database_pool<DB: Database>(
    url: &str,
    config: &TenantPoolsConfig,
    min: u32,
) -> Result<sqlx::Pool<DB>, TenancyError> {
    let opts = tenant_pool_options::<DB>(config, config.database_pool_max_connections, min);
    let url = ensure_sqlite_creates(url);
    Ok(opts.connect(&url).await?)
}

/// `url` with its `mode=` replaced by `rw`: open an existing file, never make one.
fn sqlite_without_create(url: &str) -> String {
    let (base, query) = url.split_once('?').unwrap_or((url, ""));
    let mut params: Vec<&str> = query
        .split('&')
        .filter(|p| !p.is_empty() && !p.starts_with("mode="))
        .collect();
    params.push("mode=rw");
    format!("{base}?{}", params.join("&"))
}

#[cfg(test)]
mod sqlite_without_create_tests {
    use super::sqlite_without_create;

    #[test]
    fn any_mode_becomes_rw() {
        assert_eq!(
            sqlite_without_create("sqlite://a.db"),
            "sqlite://a.db?mode=rw"
        );
        assert_eq!(
            sqlite_without_create("sqlite://a.db?mode=rwc&journal_mode=wal"),
            "sqlite://a.db?journal_mode=wal&mode=rw"
        );
    }
}

/// The `application_name` a tenant's PG pool connects with. A purge ends
/// only sessions carrying it (#2291). The id keeps it under PG's 63 bytes.
pub(crate) fn tenant_session_tag(org_id: i64) -> String {
    format!("rustango-tenant:{org_id}")
}

/// Add `application_name=<tag>` to a Postgres URL: a startup parameter, not
/// a session `SET`, so it never leaks. Last in the query, so it wins.
fn tag_postgres_url<'a>(url: &'a str, tag: Option<&str>) -> std::borrow::Cow<'a, str> {
    let pg = url.starts_with("postgres:") || url.starts_with("postgresql:");
    match tag {
        Some(tag) if pg => {
            let sep = if url.contains('?') { '&' } else { '?' };
            std::borrow::Cow::Owned(format!("{url}{sep}application_name={tag}"))
        }
        _ => std::borrow::Cow::Borrowed(url),
    }
}

/// #560 — provisioning a database-mode SQLite tenant against a URL
/// like `sqlite:///var/data/<slug>.db` failed because the generic
/// `PoolOptions<DB>::connect` path has no hook to set
/// `SqliteConnectOptions::create_if_missing(true)`. Operators had to
/// append `?mode=rwc` manually to every tenant URL.
///
/// Fix in URL space: append `?mode=rwc` (or `&mode=rwc` if other
/// params already present) when the URL is a SQLite file path and
/// has no explicit `mode=` setting. sqlx-sqlite honors this exactly
/// like `create_if_missing(true)`. `:memory:`, URIs that already
/// pin `mode=`, and non-SQLite URLs pass through unchanged.
fn ensure_sqlite_creates(url: &str) -> std::borrow::Cow<'_, str> {
    // SQLite scheme is `sqlite:` or `sqlite://`; PG is `postgres:`/
    // `postgresql:`; MySQL is `mysql:`/`mariadb:`. Match strictly so
    // we don't accidentally rewrite a non-SQLite URL that happens to
    // contain "sqlite" in a password.
    if !(url.starts_with("sqlite:") || url.starts_with("sqlite://")) {
        return std::borrow::Cow::Borrowed(url);
    }
    // In-memory DB has no file to create; sqlx accepts it directly.
    if url.contains(":memory:") {
        return std::borrow::Cow::Borrowed(url);
    }
    // Honor an operator-supplied `mode=` query param verbatim.
    // Match against `?mode=` or `&mode=` so we don't trigger on
    // adjacent params like `journal_mode=wal`.
    if url.contains("?mode=") || url.contains("&mode=") {
        return std::borrow::Cow::Borrowed(url);
    }
    let sep = if url.contains('?') { '&' } else { '?' };
    std::borrow::Cow::Owned(format!("{url}{sep}mode=rwc"))
}

#[cfg(test)]
mod tag_postgres_url_tests {
    use super::tag_postgres_url;

    #[test]
    fn tags_only_postgres_urls() {
        assert_eq!(
            tag_postgres_url("postgres://h/db?sslmode=require", Some("t")),
            "postgres://h/db?sslmode=require&application_name=t"
        );
        assert_eq!(
            tag_postgres_url("postgresql://h/db", Some("t")),
            "postgresql://h/db?application_name=t"
        );
        assert_eq!(tag_postgres_url("mysql://h/db", Some("t")), "mysql://h/db");
        assert_eq!(tag_postgres_url("postgres://h/db", None), "postgres://h/db");
    }
}

#[cfg(test)]
mod ensure_sqlite_creates_tests {
    use super::ensure_sqlite_creates;

    #[test]
    fn appends_mode_rwc_to_bare_sqlite_path() {
        let out = ensure_sqlite_creates("sqlite:///var/data/x.db");
        assert_eq!(&*out, "sqlite:///var/data/x.db?mode=rwc");
    }

    #[test]
    fn appends_with_ampersand_when_other_params_present() {
        let out = ensure_sqlite_creates("sqlite:///x.db?journal_mode=wal");
        assert_eq!(&*out, "sqlite:///x.db?journal_mode=wal&mode=rwc");
    }

    #[test]
    fn passes_explicit_mode_unchanged() {
        let out = ensure_sqlite_creates("sqlite:///x.db?mode=ro");
        assert_eq!(&*out, "sqlite:///x.db?mode=ro");
    }

    #[test]
    fn passes_memory_url_unchanged() {
        let out = ensure_sqlite_creates("sqlite::memory:");
        assert_eq!(&*out, "sqlite::memory:");
    }

    #[test]
    fn passes_non_sqlite_url_unchanged() {
        let out = ensure_sqlite_creates("postgres://u@h/db");
        assert_eq!(&*out, "postgres://u@h/db");
        let out = ensure_sqlite_creates("mysql://u@h/db");
        assert_eq!(&*out, "mysql://u@h/db");
    }
}

/// A connection scoped to a tenant. Generic over the backend
/// (`DB = sqlx::Postgres` default — keeps existing call sites
/// compiling). For schema mode the connection comes from a per-tenant
/// pool with `search_path` set, and reset on drop (PG-only);
/// for database mode it comes from the tenant's dedicated pool.
///
/// Implements `Deref` to the inner [`sqlx::pool::PoolConnection`] for
/// use as a sqlx executor.
pub struct TenantConn<DB: Database = DefaultTenantDb> {
    /// `Option` only so [`Drop`] can move the connection into the
    /// reset task. It is `Some` for the whole observable lifetime.
    inner: Option<sqlx::pool::PoolConnection<DB>>,
    schema: Option<String>,
    /// Session-state teardown, installed only by the schema-mode
    /// branch of [`TenantPools::acquire`]. `None` means "this
    /// connection carries no per-tenant session state" — the
    /// database-mode and non-PG paths, which need no reset.
    reset: Option<ResetFn<DB>>,
}

/// Undo whatever session state the acquire path installed, then let the
/// connection fall back to its pool. Takes ownership so the pool cannot
/// hand the connection to anyone else until the reset has landed.
type ResetFn<DB> = fn(
    sqlx::pool::PoolConnection<DB>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>;

impl<DB: Database> TenantConn<DB> {
    /// A database-mode connection. Per-tenant pools carry no session
    /// state, so there is nothing to reset on drop.
    pub(crate) fn database(conn: sqlx::pool::PoolConnection<DB>) -> Self {
        Self {
            inner: Some(conn),
            schema: None,
            reset: None,
        }
    }

    /// `Some(schema)` for schema-mode connections, `None` for
    /// database-mode. Useful for diagnostics / logging.
    #[must_use]
    pub fn schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }
}

impl<DB: Database> std::ops::Deref for TenantConn<DB> {
    type Target = sqlx::pool::PoolConnection<DB>;
    fn deref(&self) -> &Self::Target {
        self.inner.as_ref().expect("connection taken only on drop")
    }
}

impl<DB: Database> std::ops::DerefMut for TenantConn<DB> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.as_mut().expect("connection taken only on drop")
    }
}

/// A handler may run its own session-level `SET search_path` on a
/// schema-mode connection. sqlx does not reset session state on
/// release — it only pings — so without this the connection goes back
/// to the pool still pointing where the handler left it, and the next
/// request silently inherits it.
///
/// The reset runs in a spawned task because `Drop` cannot be async, but
/// it is not racy: the task owns the `PoolConnection`, so the pool
/// cannot hand it out again until the reset has completed and the task
/// drops it.
///
/// The one residual case is a reset task cancelled by a runtime that is
/// shutting down. That is benign in practice — the pool is being torn
/// down with the runtime, so there is no later borrower to leak to.
impl<DB: Database> Drop for TenantConn<DB> {
    fn drop(&mut self) {
        let (Some(reset), Some(mut conn)) = (self.reset, self.inner.take()) else {
            return;
        };
        // No runtime (a sync teardown, or the runtime is already gone)
        // means nothing can run the reset. Fail **closed**: mark the
        // connection to be closed on drop rather than returned, so a
        // connection with a handler's `search_path` can never rejoin
        // its pool. Losing one connection is cheap; handing the next
        // borrower another tenant's `search_path` is a cross-tenant read.
        let Ok(handle) = tokio::runtime::Handle::try_current() else {
            conn.close_on_drop();
            return;
        };
        handle.spawn(reset(conn));
    }
}

/// The [`ResetFn`] for schema-mode Postgres connections. On failure the
/// connection is closed rather than returned, so a dirty one can never
/// be reused.
#[cfg(feature = "postgres")]
fn reset_pg_search_path(
    mut conn: sqlx::pool::PoolConnection<sqlx::Postgres>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
    Box::pin(async move {
        match sqlx::query("RESET search_path").execute(&mut *conn).await {
            Ok(_) => drop(conn),
            Err(error) => {
                tracing::warn!(
                    target: "rustango::tenancy::pools",
                    %error,
                    "could not reset search_path on release; closing the connection \
                     rather than returning it to its pool",
                );
                let _ = conn.close().await;
            }
        }
    })
}

/// [`reset_pg_search_path`] for a registry connection a tenant borrowed:
/// also drops the statements it prepared in the tenant's schema.
#[cfg(feature = "postgres")]
fn reset_pg_registry_conn(
    mut conn: sqlx::pool::PoolConnection<sqlx::Postgres>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
    Box::pin(async move {
        match sqlx::Connection::clear_cached_statements(&mut *conn).await {
            Ok(()) => reset_pg_search_path(conn).await,
            Err(error) => {
                tracing::warn!(
                    target: "rustango::tenancy::pools",
                    %error,
                    "could not drop a tenant's prepared statements on release; closing the \
                     connection rather than returning it to its pool",
                );
                let _ = conn.close().await;
            }
        }
    })
}

/// A tenant's `search_path`, quoted: unquoted, `Acme` folds into `acme`'s schema (#2325).
#[cfg(feature = "postgres")]
fn search_path(schema: &str) -> String {
    format!("{},public", crate::sql::quote_with(schema, '"'))
}

/// [`search_path`] as a startup option, which PG splits on unescaped whitespace.
#[cfg(feature = "postgres")]
fn search_path_option(schema: &str) -> String {
    let mut out = String::new();
    for c in search_path(schema).chars() {
        if c == '\\' || c.is_ascii_whitespace() {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

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

    /// A SQLite registry opens through the framework: a missing file is
    /// created, the journal is WAL and the pool takes `[database]` tuning.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_sqlite_registry_gets_the_framework_setup() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("registry.db");
        let url = format!("sqlite:{}", file.display());
        // First call wins; nextest runs each test in its own process.
        let mut tuning = crate::sql::PoolTuning::default();
        tuning.max_connections = Some(3);
        crate::sql::configure_pools(tuning);
        let pool = <sqlx::Sqlite as RegistryConnect>::connect_registry(&url)
            .await
            .expect("a missing registry file is created");
        assert!(file.exists());
        let (mode,): (String,) = sqlx::query_as("PRAGMA journal_mode")
            .fetch_one(&pool)
            .await
            .unwrap();
        assert_eq!(mode.to_ascii_lowercase(), "wal");
        let want = crate::sql::pool_tuning().max_connections.expect("tuned");
        assert_eq!(
            pool.options().get_max_connections(),
            want,
            "[database] pool size"
        );
    }

    /// Counts lookups and parks each one briefly, so concurrent misses overlap.
    #[cfg(feature = "sqlite")]
    struct CountingSecrets(Arc<std::sync::atomic::AtomicUsize>);

    #[cfg(feature = "sqlite")]
    #[async_trait::async_trait]
    impl SecretsResolver for CountingSecrets {
        async fn resolve(&self, r: &str) -> Result<String, super::super::secrets::SecretsError> {
            self.0.fetch_add(1, Ordering::SeqCst);
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
            if r == "fail" {
                return Err(super::super::secrets::SecretsError::NotFound(r.to_owned()));
            }
            Ok(r.to_owned())
        }
    }

    /// Lets a lookup through only once `n` of them run at the same time.
    #[cfg(feature = "sqlite")]
    struct BarrierSecrets(Arc<tokio::sync::Barrier>);

    #[cfg(feature = "sqlite")]
    #[async_trait::async_trait]
    impl SecretsResolver for BarrierSecrets {
        async fn resolve(&self, r: &str) -> Result<String, super::super::secrets::SecretsError> {
            self.0.wait().await;
            Ok(r.to_owned())
        }
    }

    /// A tenant whose secret lookup fails.
    #[cfg(feature = "sqlite")]
    fn failing_sqlite_org() -> Org {
        Org {
            database_url: Some("fail".into()),
            ..cold_sqlite_org()
        }
    }

    /// Waiters get the first build's error instead of each retrying in turn.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_failed_cold_build_fails_every_waiter_once() {
        let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let pools: TenantPools<sqlx::Sqlite> = TenantPools::with_secrets(
            sqlx::SqlitePool::connect_lazy("sqlite::memory:").expect("lazy"),
            CountingSecrets(n.clone()),
        );
        let org = failing_sqlite_org();
        let got =
            futures_util::future::join_all((0..32).map(|_| pools.pool_for_database_mode(&org)))
                .await;
        assert!(got.iter().all(Result::is_err));
        assert_eq!(
            n.load(Ordering::SeqCst),
            1,
            "one build for 32 failing requests"
        );
        // The failure is not cached: the next request tries again.
        assert!(pools.pool_for_database_mode(&org).await.is_err());
        assert_eq!(n.load(Ordering::SeqCst), 2);
    }

    /// The same for the database-only registry.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_failed_cold_build_fails_every_waiter_once_in_database_pools() {
        use super::super::{BackendKind, DatabasePools};
        let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let pools: DatabasePools<sqlx::Sqlite> =
            DatabasePools::with_secrets(BackendKind::Sqlite, CountingSecrets(n.clone()));
        let org = failing_sqlite_org();
        let got = futures_util::future::join_all((0..32).map(|_| pools.pool_for_org(&org))).await;
        assert!(got.iter().all(Result::is_err));
        assert_eq!(
            n.load(Ordering::SeqCst),
            1,
            "one build for 32 failing requests"
        );
    }

    /// With caching off there is nothing to share, so builds run side by side.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn with_caching_off_cold_builds_run_in_parallel() {
        use super::super::{BackendKind, DatabasePools};
        let config = TenantPoolsConfig {
            max_cached_database_pools: 0,
            ..TenantPoolsConfig::default()
        };
        let org = cold_sqlite_org();
        let tenant = TenantPools::<sqlx::Sqlite>::with_secrets(
            sqlx::SqlitePool::connect_lazy("sqlite::memory:").expect("lazy"),
            BarrierSecrets(Arc::new(tokio::sync::Barrier::new(4))),
        )
        .config(config.clone());
        let db = DatabasePools::<sqlx::Sqlite>::with_secrets(
            BackendKind::Sqlite,
            BarrierSecrets(Arc::new(tokio::sync::Barrier::new(4))),
        )
        .config(config);
        let both = async {
            futures_util::future::join_all((0..4).map(|_| tenant.pool_for_database_mode(&org)))
                .await;
            futures_util::future::join_all((0..4).map(|_| db.pool_for_org(&org))).await;
        };
        tokio::time::timeout(std::time::Duration::from_secs(5), both)
            .await
            .expect("cap 0 builds must not wait for each other");
    }

    /// A flight dropped mid-build leaves no entry behind.
    #[tokio::test]
    async fn abandoned_flights_are_pruned() {
        let flights = SingleFlight::<u32>::default();
        let source = PoolSource::Database(None);
        for slug in ["a", "b", "c", "d"] {
            let pending = flights.run(slug, &source, std::future::pending());
            assert!(
                tokio::time::timeout(std::time::Duration::from_millis(5), pending)
                    .await
                    .is_err()
            );
        }
        assert_eq!(
            flights.run("e", &source, async { Ok(1) }).await.ok(),
            Some(1)
        );
        assert_eq!(flights.len(), 0, "dead and finished flights are dropped");
    }

    #[cfg(feature = "sqlite")]
    fn cold_sqlite_org() -> Org {
        Org {
            slug: "cold".into(),
            storage_mode: "database".into(),
            backend_kind: "sqlite".into(),
            database_url: Some("sqlite::memory:".into()),
            ..crate::testkit::org()
        }
    }

    /// A cold tenant hit by many requests at once resolves and connects once.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_cold_tenant_builds_its_pool_once() {
        let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let pools: TenantPools<sqlx::Sqlite> = TenantPools::with_secrets(
            sqlx::SqlitePool::connect_lazy("sqlite::memory:").expect("lazy"),
            CountingSecrets(n.clone()),
        );
        let org = cold_sqlite_org();
        let got =
            futures_util::future::join_all((0..32).map(|_| pools.pool_for_database_mode(&org)))
                .await;
        assert!(got.iter().all(Result::is_ok));
        assert_eq!(
            n.load(Ordering::SeqCst),
            1,
            "one build for 32 cold requests"
        );
    }

    /// The same for the database-only registry.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_cold_tenant_builds_its_pool_once_in_database_pools() {
        use super::super::{BackendKind, DatabasePools};
        let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let pools: DatabasePools<sqlx::Sqlite> =
            DatabasePools::with_secrets(BackendKind::Sqlite, CountingSecrets(n.clone()));
        let org = cold_sqlite_org();
        let got = futures_util::future::join_all((0..32).map(|_| pools.pool_for_org(&org))).await;
        assert!(got.iter().all(Result::is_ok));
        assert_eq!(
            n.load(Ordering::SeqCst),
            1,
            "one build for 32 cold requests"
        );
    }

    /// Holds the lookup of a URL naming `old`, so a second build overlaps it.
    #[cfg(feature = "sqlite")]
    struct SlowOldSecrets;

    #[cfg(feature = "sqlite")]
    #[async_trait::async_trait]
    impl SecretsResolver for SlowOldSecrets {
        async fn resolve(&self, r: &str) -> Result<String, super::super::secrets::SecretsError> {
            if r.contains("old") {
                tokio::time::sleep(std::time::Duration::from_millis(300)).await;
            }
            Ok(r.to_owned())
        }
    }

    /// The same slug before and after a move to another database file.
    #[cfg(feature = "sqlite")]
    fn moved_sqlite_orgs(dir: &std::path::Path) -> (Org, Org, String, String) {
        let file = |name: &str| dir.join(name).to_string_lossy().into_owned();
        let (old, new) = (file("old.db"), file("new.db"));
        let org = |path: &str| Org {
            slug: "moved".into(),
            database_url: Some(format!("sqlite:{path}?mode=rwc")),
            ..cold_sqlite_org()
        };
        (org(&old), org(&new), old, new)
    }

    #[cfg(feature = "sqlite")]
    fn sqlite_file(pool: &sqlx::SqlitePool) -> String {
        pool.connect_options()
            .get_filename()
            .to_string_lossy()
            .into_owned()
    }

    /// A request for a moved tenant never joins a build for its old database.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_build_for_another_source_is_not_shared() {
        let dir = tempfile::tempdir().unwrap();
        let (old_org, new_org, old, new) = moved_sqlite_orgs(dir.path());
        let pools: TenantPools<sqlx::Sqlite> = TenantPools::with_secrets(
            sqlx::SqlitePool::connect_lazy("sqlite::memory:").expect("lazy"),
            SlowOldSecrets,
        );
        let late_new = async {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            pools.pool_for_database_mode(&new_org).await
        };
        let (a, b) = tokio::join!(pools.pool_for_database_mode(&old_org), late_new);
        assert_eq!(sqlite_file(&a.unwrap()), old);
        assert_eq!(sqlite_file(&b.unwrap()), new, "new org got the old pool");
    }

    /// The same for the database-only registry.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_build_for_another_source_is_not_shared_in_database_pools() {
        use super::super::{BackendKind, DatabasePools};
        let dir = tempfile::tempdir().unwrap();
        let (old_org, new_org, old, new) = moved_sqlite_orgs(dir.path());
        let pools: DatabasePools<sqlx::Sqlite> =
            DatabasePools::with_secrets(BackendKind::Sqlite, SlowOldSecrets);
        let late_new = async {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            pools.pool_for_org(&new_org).await
        };
        let (a, b) = tokio::join!(pools.pool_for_org(&old_org), late_new);
        assert_eq!(sqlite_file(a.unwrap().pool()), old);
        assert_eq!(
            sqlite_file(b.unwrap().pool()),
            new,
            "new org got the old pool"
        );
    }

    /// Schema mode: a tenant moved to another schema builds its own
    /// pool instead of waiting on the old schema's connect.
    #[cfg(feature = "postgres")]
    #[tokio::test]
    async fn a_schema_build_for_another_schema_is_not_shared() {
        let (addr, accepted, server) = silent_pg_server().await;
        let pools = Arc::new(TenantPools::new(lazy_pg(addr)));
        let calls: Vec<_> = ["cold", "cold_v2"]
            .into_iter()
            .map(|schema| {
                let org = Org {
                    schema_name: Some(schema.into()),
                    ..cold_schema_org()
                };
                let p = pools.clone();
                tokio::spawn(async move { p.scoped_pool(&org).await })
            })
            .collect();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while accepted.load(Ordering::SeqCst) < 2 && std::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        let seen = accepted.load(Ordering::SeqCst);
        for c in calls {
            c.abort();
        }
        server.abort();
        assert_eq!(seen, 2, "two schemas opened {seen} connections");
    }

    /// Schema mode too: a server that never answers sees one connect,
    /// not one per waiting request.
    #[cfg(feature = "postgres")]
    #[tokio::test]
    async fn a_cold_schema_tenant_connects_once() {
        let (addr, accepted, server) = silent_pg_server().await;
        let pools = Arc::new(TenantPools::new(lazy_pg(addr)));
        let org = cold_schema_org();
        let calls: Vec<_> = (0..16)
            .map(|_| {
                let (p, o) = (pools.clone(), org.clone());
                tokio::spawn(async move { p.scoped_pool(&o).await })
            })
            .collect();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while accepted.load(Ordering::SeqCst) == 0 && std::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        // Grace for any extra connect a waiter would open.
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        let seen = accepted.load(Ordering::SeqCst);
        for c in calls {
            c.abort();
        }
        server.abort();
        assert_eq!(seen, 1, "16 cold requests opened {seen} connections");
    }

    /// Waiters behind a connect that times out fail with it, not one
    /// timeout after another.
    #[cfg(feature = "postgres")]
    #[tokio::test]
    async fn a_timed_out_schema_build_fails_every_waiter_together() {
        let (addr, _accepted, server) = silent_pg_server().await;
        let timeout = std::time::Duration::from_millis(300);
        let pools = Arc::new(TenantPools::new(lazy_pg(addr)).config(TenantPoolsConfig {
            database_pool_acquire_timeout: timeout,
            ..TenantPoolsConfig::default()
        }));
        let org = cold_schema_org();
        let start = std::time::Instant::now();
        let calls = (0..8).map(|_| {
            let (p, o) = (pools.clone(), org.clone());
            tokio::spawn(async move { p.scoped_pool(&o).await })
        });
        let got = futures_util::future::join_all(calls).await;
        let took = start.elapsed();
        server.abort();
        assert!(got.into_iter().all(|r| r.expect("task").is_err()));
        assert!(took < timeout * 3, "8 waiters took {took:?}");
    }

    /// A Postgres address that accepts connections and never answers.
    #[cfg(feature = "postgres")]
    async fn silent_pg_server() -> (
        std::net::SocketAddr,
        Arc<std::sync::atomic::AtomicUsize>,
        tokio::task::JoinHandle<()>,
    ) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let n = accepted.clone();
        let server = tokio::spawn(async move {
            let mut held = Vec::new();
            while let Ok((sock, _)) = listener.accept().await {
                n.fetch_add(1, Ordering::SeqCst);
                held.push(sock);
            }
        });
        (addr, accepted, server)
    }

    #[cfg(feature = "postgres")]
    fn lazy_pg(addr: std::net::SocketAddr) -> PgPool {
        PgPoolOptions::new()
            .connect_lazy(&format!("postgres://u:p@{addr}/db"))
            .unwrap()
    }

    #[cfg(feature = "postgres")]
    fn cold_schema_org() -> Org {
        Org {
            slug: "cold".into(),
            storage_mode: "schema".into(),
            schema_name: Some("cold".into()),
            ..crate::testkit::org()
        }
    }

    /// `new` is what the builder, CLI and console use, so it must resolve
    /// `env://` references, not hand them to the driver.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn new_resolves_env_references() {
        let pools: TenantPools<sqlx::Sqlite> =
            TenantPools::new(sqlx::SqlitePool::connect_lazy("sqlite::memory:").expect("lazy"));
        let path = std::env::var("PATH").expect("PATH");
        assert_eq!(pools.resolve_secret("env://PATH").await.unwrap(), path);
    }

    /// The near-cap warning fires on the crossing, not on every
    /// insert. A cache sitting at its cap inserts on every miss, so an
    /// unbounded warn there floods the log with the very message meant
    /// to be noticed (#1528).
    ///
    /// Asserts the latch rather than the log line: the state machine
    /// is what decides whether the warn repeats, and a test that
    /// captured one `warn!` would pass either way.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn the_near_cap_warning_latches_and_resets() {
        use std::sync::atomic::Ordering;
        let pools: TenantPools<sqlx::Sqlite> =
            TenantPools::new(sqlx::SqlitePool::connect_lazy("sqlite::memory:").expect("lazy"));
        // Below the threshold: no warning.
        assert!(!pools.claim_near_cap_warning(7, 10), "70% is not near");

        // The crossing warns exactly once. Every insert after it, while
        // the cache stays full, must stay silent — this is the assertion
        // that fails against an unbounded warn.
        assert!(pools.claim_near_cap_warning(8, 10), "80% warns");
        assert!(!pools.claim_near_cap_warning(9, 10), "no repeat at 90%");
        assert!(!pools.claim_near_cap_warning(10, 10), "no repeat at cap");
        assert!(!pools.claim_near_cap_warning(10, 10), "still no repeat");

        // Falling back below re-arms it for the next genuine crossing.
        assert!(!pools.claim_near_cap_warning(3, 10), "back under: silent");
        assert!(pools.claim_near_cap_warning(9, 10), "second crossing warns");

        // `cap == 0` means caching is off; it must never warn.
        pools.warned_near_cap.store(false, Ordering::Relaxed);
        assert!(!pools.claim_near_cap_warning(0, 0), "cap 0 must not warn");
    }

    /// The cold-path span must not stay entered across `.await`, or
    /// other work on the thread logs under this tenant (#1884).
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn the_pool_init_span_does_not_leak_onto_other_tasks() {
        struct Parked(Arc<tokio::sync::Notify>);
        #[async_trait::async_trait]
        impl SecretsResolver for Parked {
            async fn resolve(
                &self,
                r: &str,
            ) -> Result<String, super::super::secrets::SecretsError> {
                self.0.notified().await;
                Err(super::super::secrets::SecretsError::NotFound(r.to_owned()))
            }
        }
        let buf = crate::testkit::CaptureWriter::default();
        let subscriber = tracing_subscriber::fmt()
            .with_writer(buf.clone())
            .with_ansi(false)
            .finish();
        let _g = tracing::subscriber::set_default(subscriber);
        let gate = Arc::new(tokio::sync::Notify::new());
        let pools: TenantPools<sqlx::Sqlite> = TenantPools::with_secrets(
            sqlx::SqlitePool::connect_lazy("sqlite::memory:").expect("lazy"),
            Parked(gate.clone()),
        );
        let org = Org {
            slug: "leaky".into(),
            storage_mode: "database".into(),
            database_url: Some("ref".into()),
            ..crate::testkit::org()
        };
        let (res, ()) = tokio::join!(pools.pool_for_database_mode(&org), async {
            tokio::task::yield_now().await;
            tracing::info!("other-task-event");
            gate.notify_one();
        });
        assert!(res.is_err());
        let out = buf.contents();
        let line = out
            .lines()
            .find(|l| l.contains("other-task-event"))
            .expect("logged");
        assert!(!line.contains("tenant_pool_init"), "span leaked: {line}");
    }

    #[cfg(feature = "postgres")]
    #[test]
    fn set_search_path_quotes_odd_schema_names() {
        assert_eq!(
            set_search_path_sql("a\"b c\\d\x0Be"),
            "SET search_path TO \"a\"\"b c\\d\x0Be\", public"
        );
    }

    #[test]
    fn config_defaults_are_sane() {
        let c = TenantPoolsConfig::default();
        assert!(c.max_cached_database_pools >= 16);
        assert!(c.database_pool_max_connections >= 1);
    }

    // v0.27.7 (#60) — guard the new pool-timeout fields'
    // backward-compatible defaults. Pre-warm must default off so
    // upgrading apps don't add boot-time latency surprise; min
    // connections must default 0 so existing pools don't get
    // chatty against tiny PG instances; acquire timeout must be
    // a non-trivial duration so apps don't see PoolTimedOut on
    // a slow first connect.
    #[test]
    fn config_pool_timeout_defaults_preserve_pre_0_27_7_behavior() {
        let c = TenantPoolsConfig::default();
        assert!(!c.prewarm_active_tenants);
        assert_eq!(c.database_pool_min_connections, 0);
        assert!(c.database_pool_acquire_timeout >= std::time::Duration::from_secs(5));
        assert!(c.database_pool_idle_timeout.is_some());
        assert!(c.database_pool_max_lifetime.is_some());
    }

    #[cfg(feature = "postgres")]
    #[test]
    fn prewarm_report_zeroed_default() {
        let r = PrewarmReport::default();
        assert_eq!(r.total_active, 0);
        assert_eq!(r.warmed, 0);
        assert_eq!(r.failed, 0);
        assert_eq!(r.skipped_cap, 0);
    }
}