fastapi-core 0.3.0

Core types and traits for the FastAPI Rust framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
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
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
//! Dependency injection support.
//!
//! This module provides the `Depends` extractor and supporting types for
//! request-scoped dependency resolution with optional caching and overrides.
//!
//! # Circular Dependency Detection
//!
//! The DI system detects circular dependencies at runtime. If a dependency
//! graph contains a cycle (e.g., A -> B -> C -> A), the resolution will fail
//! with a [`CircularDependencyError`] containing the full cycle path.
//!
//! ```text
//! Circular dependency detected: DbPool -> UserService -> AuthService -> DbPool
//! ```
//!
//! # Configuration Errors Cause Panics
//!
//! Circular dependencies and scope violations are **configuration errors**
//! that indicate a bug in the dependency graph setup. These errors cause
//! panics rather than returning `Result` for the following reasons:
//!
//! 1. **Type safety**: The error type is `T::Error` (the dependency's error type),
//!    which may not be constructible from internal errors like `CircularDependencyError`.
//!
//! 2. **Fail fast**: Configuration errors should crash early during development/testing,
//!    not be silently caught and potentially ignored.
//!
//! 3. **Invariant violation**: A circular dependency means the dependency graph
//!    is fundamentally broken and cannot be satisfied.
//!
//! To debug circular dependencies:
//! - Review the panic message which shows the full cycle path
//! - Check for unintended transitive dependencies
//! - Consider using scoped dependencies to break cycles

use crate::context::RequestContext;
use crate::extract::FromRequest;
use crate::request::Request;
use crate::response::{IntoResponse, Response, ResponseBody, StatusCode};
use parking_lot::Mutex;
use parking_lot::RwLock;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::sync::Arc;

/// Dependency resolution scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependencyScope {
    /// No request-level caching; resolve on each call.
    Function,
    /// Cache for the lifetime of the request.
    Request,
}

// ============================================================================
// Cleanup Stack (for Generator-style Dependencies)
// ============================================================================

/// Type alias for cleanup functions.
///
/// A cleanup function is an async closure that performs teardown work after
/// the request handler completes. Cleanup functions run in LIFO (last-in,
/// first-out) order, similar to Python's `contextlib.ExitStack`.
pub type CleanupFn = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>;

/// Stack of cleanup functions to run after handler completion.
///
/// `CleanupStack` provides generator-style dependency lifecycle management
/// similar to FastAPI's `yield` dependencies. Cleanup functions are registered
/// during dependency resolution and run in LIFO order after the handler
/// completes, even on error or panic.
///
/// # Example
///
/// ```ignore
/// // Dependency with cleanup
/// impl FromDependencyWithCleanup for DbConnection {
///     type Value = DbConnection;
///     type Error = HttpError;
///
///     async fn setup(ctx: &RequestContext, req: &mut Request)
///         -> Result<(Self::Value, Option<CleanupFn>), Self::Error>
///     {
///         let conn = DbPool::get_connection().await?;
///         let cleanup = {
///             let conn = conn.clone();
///             Box::new(move || {
///                 Box::pin(async move {
///                     conn.release().await;
///                 }) as Pin<Box<dyn Future<Output = ()> + Send>>
///             }) as CleanupFn
///         };
///         Ok((conn, Some(cleanup)))
///     }
/// }
/// ```
///
/// # Cleanup Order
///
/// Cleanup functions run in LIFO order (last registered runs first):
///
/// ```text
/// Setup order:   A -> B -> C
/// Cleanup order: C -> B -> A
/// ```
///
/// This ensures that dependencies are cleaned up in the reverse order
/// of their setup, maintaining proper resource lifecycle semantics.
pub struct CleanupStack {
    /// Cleanup functions in registration order (will be reversed when running).
    cleanups: Mutex<Vec<CleanupFn>>,
}

impl CleanupStack {
    /// Create an empty cleanup stack.
    #[must_use]
    pub fn new() -> Self {
        Self {
            cleanups: Mutex::new(Vec::new()),
        }
    }

    /// Register a cleanup function to run after handler completion.
    ///
    /// Cleanup functions are run in LIFO order (last registered runs first).
    pub fn push(&self, cleanup: CleanupFn) {
        let mut guard = self.cleanups.lock();
        guard.push(cleanup);
    }

    /// Take all cleanup functions for execution.
    ///
    /// Returns cleanups in LIFO order (reversed from registration order).
    /// After calling this, the stack is empty.
    pub fn take_cleanups(&self) -> Vec<CleanupFn> {
        let mut guard = self.cleanups.lock();
        let mut cleanups = std::mem::take(&mut *guard);
        cleanups.reverse(); // LIFO order
        cleanups
    }

    /// Returns the number of registered cleanup functions.
    #[must_use]
    pub fn len(&self) -> usize {
        let guard = self.cleanups.lock();
        guard.len()
    }

    /// Returns true if no cleanup functions are registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Run all cleanup functions in LIFO order.
    ///
    /// This consumes all registered cleanup functions. Each cleanup is
    /// awaited in sequence. If a cleanup function panics (either during
    /// creation or execution), the remaining cleanups are still attempted.
    ///
    /// # Returns
    ///
    /// The number of cleanup functions that completed successfully.
    pub async fn run_cleanups(&self) -> usize {
        let cleanups = self.take_cleanups();
        let mut completed = 0;

        for cleanup in cleanups {
            // Call the cleanup function to get the future, catching panics during creation
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (cleanup)()));
            match result {
                Ok(future) => {
                    // Run the future, catching any panics during execution
                    if Self::run_cleanup_future(future).await {
                        completed += 1;
                    }
                    // If cleanup panicked during execution, continue with remaining
                }
                Err(_) => {
                    // Cleanup panicked during creation, continue with remaining cleanups
                }
            }
        }

        completed
    }

    /// Run a single cleanup future, catching any panics during execution.
    ///
    /// Returns `true` if the cleanup completed successfully, `false` if it panicked.
    async fn run_cleanup_future(mut future: Pin<Box<dyn Future<Output = ()> + Send>>) -> bool {
        use std::panic::{AssertUnwindSafe, catch_unwind};
        use std::task::Poll;

        std::future::poll_fn(move |cx| {
            match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
                Ok(Poll::Ready(())) => Poll::Ready(true),
                Ok(Poll::Pending) => Poll::Pending,
                Err(_) => Poll::Ready(false), // Cleanup panicked, treat as failed
            }
        })
        .await
    }
}

impl Default for CleanupStack {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for CleanupStack {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CleanupStack")
            .field("count", &self.len())
            .finish()
    }
}

/// Trait for dependencies that require cleanup after handler completion.
///
/// This is similar to FastAPI's `yield` dependencies. Dependencies implementing
/// this trait can perform setup logic and register cleanup functions that
/// run after the request handler completes.
///
/// # Example
///
/// ```ignore
/// struct DbTransaction {
///     tx: Transaction,
/// }
///
/// impl FromDependencyWithCleanup for DbTransaction {
///     type Value = DbTransaction;
///     type Error = HttpError;
///
///     async fn setup(ctx: &RequestContext, req: &mut Request)
///         -> Result<(Self::Value, Option<CleanupFn>), Self::Error>
///     {
///         let pool = Depends::<DbPool>::from_request(ctx, req).await?;
///         let tx = pool.begin().await.map_err(|_| HttpError::internal())?;
///
///         let cleanup_tx = tx.clone();
///         let cleanup = Box::new(move || {
///             Box::pin(async move {
///                 // Commit or rollback happens here
///                 cleanup_tx.commit().await.ok();
///             }) as Pin<Box<dyn Future<Output = ()> + Send>>
///         }) as CleanupFn;
///
///         Ok((DbTransaction { tx }, Some(cleanup)))
///     }
/// }
/// ```
pub trait FromDependencyWithCleanup: Clone + Send + Sync + 'static {
    /// The value type produced by setup.
    type Value: Clone + Send + Sync + 'static;
    /// Error type when setup fails.
    type Error: IntoResponse + Send + Sync + 'static;

    /// Set up the dependency and optionally return a cleanup function.
    ///
    /// The cleanup function (if provided) will run after the request handler
    /// completes, even on error or panic.
    fn setup(
        ctx: &RequestContext,
        req: &mut Request,
    ) -> impl Future<Output = Result<(Self::Value, Option<CleanupFn>), Self::Error>> + Send;
}

/// Wrapper for dependencies that have cleanup callbacks.
///
/// `DependsCleanup` works like `Depends` but for types implementing
/// `FromDependencyWithCleanup`. It automatically registers cleanup
/// functions with the request's cleanup stack.
#[derive(Debug, Clone)]
pub struct DependsCleanup<T, C = DefaultDependencyConfig>(pub T, PhantomData<C>);

impl<T, C> DependsCleanup<T, C> {
    /// Create a new `DependsCleanup` wrapper.
    #[must_use]
    pub fn new(value: T) -> Self {
        Self(value, PhantomData)
    }

    /// Unwrap the inner value.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T, C> Deref for DependsCleanup<T, C> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T, C> DerefMut for DependsCleanup<T, C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T, C> FromRequest for DependsCleanup<T, C>
where
    T: FromDependencyWithCleanup<Value = T>,
    C: DependsConfig,
{
    type Error = T::Error;

    async fn from_request(ctx: &RequestContext, req: &mut Request) -> Result<Self, Self::Error> {
        // Check cancellation before resolving dependency
        let _ = ctx.checkpoint();

        let scope = C::SCOPE.unwrap_or(DependencyScope::Request);
        let use_cache = C::USE_CACHE && scope == DependencyScope::Request;

        // Check cache first
        if use_cache {
            if let Some(cached) = ctx.dependency_cache().get::<T::Value>() {
                return Ok(DependsCleanup::new(cached));
            }
        }

        // Check for circular dependency (bd-276p: intentional panic for config errors)
        let type_name = std::any::type_name::<T>();
        if let Some(cycle) = ctx.resolution_stack().check_cycle::<T>(type_name) {
            handle_circular_dependency(cycle);
        }

        // Check for scope violation: request-scoped cannot depend on function-scoped
        if let Some(scope_err) = ctx
            .resolution_stack()
            .check_scope_violation(type_name, scope)
        {
            handle_scope_violation(scope_err);
        }

        // Push onto resolution stack
        ctx.resolution_stack().push::<T>(type_name, scope);
        let _guard = ResolutionGuard::new(ctx.resolution_stack());

        // Setup the dependency
        let _ = ctx.checkpoint();
        let (value, cleanup) = T::setup(ctx, req).await?;

        // Register cleanup if provided
        if let Some(cleanup_fn) = cleanup {
            ctx.cleanup_stack().push(cleanup_fn);
        }

        // Cache if needed
        if use_cache {
            ctx.dependency_cache().insert::<T::Value>(value.clone());
        }

        Ok(DependsCleanup::new(value))
    }
}

/// Configuration for `Depends` resolution.
pub trait DependsConfig {
    /// Whether to use caching.
    const USE_CACHE: bool;
    /// Optional scope override.
    const SCOPE: Option<DependencyScope>;
}

/// Default dependency configuration (cache per request).
#[derive(Debug, Clone, Copy)]
pub struct DefaultDependencyConfig;

/// Backwards-friendly alias for the default config.
pub type DefaultConfig = DefaultDependencyConfig;

impl DependsConfig for DefaultDependencyConfig {
    const USE_CACHE: bool = true;
    const SCOPE: Option<DependencyScope> = None;
}

/// Disable caching for this dependency.
#[derive(Debug, Clone, Copy)]
pub struct NoCache;

impl DependsConfig for NoCache {
    const USE_CACHE: bool = false;
    const SCOPE: Option<DependencyScope> = Some(DependencyScope::Function);
}

// ============================================================================
// Circular Dependency Detection
// ============================================================================

/// Error returned when a circular dependency is detected.
///
/// This error contains the full cycle path showing which types form the cycle.
/// For example, if `DbPool` depends on `UserService` which depends on `DbPool`,
/// the cycle is: `["DbPool", "UserService", "DbPool"]`.
///
/// # Example
///
/// ```text
/// Circular dependency detected: DbPool -> UserService -> DbPool
/// ```
#[derive(Debug, Clone)]
pub struct CircularDependencyError {
    /// The names of the types forming the cycle, in resolution order.
    /// The first and last element are the same type (completing the cycle).
    pub cycle: Vec<String>,
}

/// Error returned when a dependency scope constraint is violated.
///
/// This occurs when a request-scoped dependency depends on a function-scoped
/// dependency. Since request-scoped dependencies are cached for the lifetime
/// of the request, they hold stale values from function-scoped
/// dependencies (which should be resolved fresh on each call).
///
/// # Example
///
/// ```text
/// Dependency scope violation: request-scoped 'CachedUser' depends on
/// function-scoped 'DbConnection'. Request-scoped dependencies cannot
/// depend on function-scoped dependencies because the cached value
/// becomes stale.
/// ```
///
/// # Why This Matters
///
/// Consider this scenario:
/// - `CachedUser` is request-scoped (cached for the request)
/// - `DbConnection` is function-scoped (fresh connection each call)
///
/// If `CachedUser` depends on `DbConnection`:
/// 1. First request: `CachedUser` resolved, caches `DbConnection` value
/// 2. Later in same request: `CachedUser` retrieved from cache
/// 3. Problem: The cached `CachedUser` holds a stale `DbConnection`
///
/// This violates the contract that function-scoped dependencies are fresh.
#[derive(Debug, Clone)]
pub struct DependencyScopeError {
    /// The name of the request-scoped dependency (the outer one).
    pub request_scoped_type: String,
    /// The name of the function-scoped dependency (the inner one).
    pub function_scoped_type: String,
}

impl CircularDependencyError {
    /// Create a new circular dependency error with the given cycle path.
    #[must_use]
    pub fn new(cycle: Vec<String>) -> Self {
        Self { cycle }
    }

    /// Get a human-readable representation of the cycle.
    #[must_use]
    pub fn cycle_path(&self) -> String {
        self.cycle.join(" -> ")
    }
}

impl std::fmt::Display for CircularDependencyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Circular dependency detected: {}", self.cycle_path())
    }
}

impl std::error::Error for CircularDependencyError {}

impl IntoResponse for CircularDependencyError {
    fn into_response(self) -> Response {
        let body = format!(
            r#"{{"detail":"Circular dependency detected: {}"}}"#,
            self.cycle_path()
        );
        Response::with_status(StatusCode::INTERNAL_SERVER_ERROR)
            .header("content-type", b"application/json".to_vec())
            .body(ResponseBody::Bytes(body.into_bytes()))
    }
}

impl DependencyScopeError {
    /// Create a new scope violation error.
    #[must_use]
    pub fn new(request_scoped_type: String, function_scoped_type: String) -> Self {
        Self {
            request_scoped_type,
            function_scoped_type,
        }
    }
}

impl std::fmt::Display for DependencyScopeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Dependency scope violation: request-scoped '{}' depends on function-scoped '{}'. \
             Request-scoped dependencies cannot depend on function-scoped dependencies \
             because the cached value becomes stale.",
            self.request_scoped_type, self.function_scoped_type
        )
    }
}

impl std::error::Error for DependencyScopeError {}

impl IntoResponse for DependencyScopeError {
    fn into_response(self) -> Response {
        let body = format!(
            r#"{{"detail":"Dependency scope violation: request-scoped '{}' depends on function-scoped '{}'. Request-scoped dependencies cannot depend on function-scoped dependencies."}}"#,
            self.request_scoped_type, self.function_scoped_type
        );
        Response::with_status(StatusCode::INTERNAL_SERVER_ERROR)
            .header("content-type", b"application/json".to_vec())
            .body(ResponseBody::Bytes(body.into_bytes()))
    }
}

/// Handle a detected circular dependency by panicking with a helpful message.
///
/// This is marked `#[cold]` to hint to the compiler that this path is unlikely,
/// and `#[inline(never)]` to keep the panic code out of the hot path.
///
/// # Panics
///
/// Always panics with a detailed error message including the cycle path and debugging hints.
#[cold]
#[inline(never)]
fn handle_circular_dependency(cycle: Vec<String>) -> ! {
    let err = CircularDependencyError::new(cycle);
    panic!(
        "\n\n\
        ╔══════════════════════════════════════════════════════════════════════╗\n\
        ║                    CIRCULAR DEPENDENCY DETECTED                      ║\n\
        ╠══════════════════════════════════════════════════════════════════════╣\n\
        ║ {}\n\
        ╠══════════════════════════════════════════════════════════════════════╣\n\
        ║ This is a configuration error in your dependency graph.              ║\n\
        ║                                                                      ║\n\
        ║ To fix:                                                              ║\n\
        ║ 1. Review the cycle path above                                       ║\n\
        ║ 2. Break the cycle by removing or refactoring one dependency         ║\n\
        ║ 3. Consider using lazy initialization or scoped dependencies         ║\n\
        ╚══════════════════════════════════════════════════════════════════════╝\n",
        err
    );
}

/// Handle a detected scope violation by panicking with a helpful message.
///
/// This is marked `#[cold]` to hint to the compiler that this path is unlikely,
/// and `#[inline(never)]` to keep the panic code out of the hot path.
///
/// # Panics
///
/// Always panics with a detailed error message explaining the scope violation.
#[cold]
#[inline(never)]
fn handle_scope_violation(scope_err: DependencyScopeError) -> ! {
    panic!(
        "\n\n\
        ╔══════════════════════════════════════════════════════════════════════╗\n\
        ║                    DEPENDENCY SCOPE VIOLATION                        ║\n\
        ╠══════════════════════════════════════════════════════════════════════╣\n\
        ║ {}\n\
        ╠══════════════════════════════════════════════════════════════════════╣\n\
        ║ Request-scoped dependencies are cached per-request and must not      ║\n\
        ║ depend on function-scoped dependencies (which are created fresh      ║\n\
        ║ each time).                                                          ║\n\
        ║                                                                      ║\n\
        ║ To fix:                                                              ║\n\
        ║ 1. Change the inner dependency to request scope                      ║\n\
        ║ 2. Or change the outer dependency to function scope                  ║\n\
        ║ 3. Or restructure to avoid the dependency                            ║\n\
        ╚══════════════════════════════════════════════════════════════════════╝\n",
        scope_err
    );
}

/// Tracks which types are currently being resolved to detect cycles and scope violations.
///
/// This uses a stack-based approach: when we start resolving a type, we push
/// its `TypeId`, name, and scope onto the stack. If we see the same `TypeId` again
/// before finishing, we have a cycle. Additionally, if a request-scoped dependency
/// tries to resolve a function-scoped dependency, we detect a scope violation.
pub struct ResolutionStack {
    /// Stack of (TypeId, type_name, scope) tuples currently being resolved.
    stack: RwLock<Vec<(TypeId, String, DependencyScope)>>,
}

impl ResolutionStack {
    /// Create an empty resolution stack.
    #[must_use]
    pub fn new() -> Self {
        Self {
            stack: RwLock::new(Vec::new()),
        }
    }

    /// Check if a type is currently being resolved (forms a cycle).
    ///
    /// Returns `Some(cycle_path)` if the type is already on the stack,
    /// or `None` if it's safe to proceed.
    pub fn check_cycle<T: 'static>(&self, type_name: &str) -> Option<Vec<String>> {
        let type_id = TypeId::of::<T>();
        let guard = self.stack.read();

        // Check if this type is already being resolved
        if let Some(pos) = guard.iter().position(|(id, _, _)| *id == type_id) {
            // Build the cycle path from the position where we first saw this type
            let mut cycle: Vec<String> = guard[pos..]
                .iter()
                .map(|(_, name, _)| name.clone())
                .collect();
            // Add the current type to complete the cycle
            cycle.push(type_name.to_owned());
            return Some(cycle);
        }

        None
    }

    /// Check for scope violations.
    ///
    /// Returns `Some(DependencyScopeError)` if there is a request-scoped dependency
    /// on the stack and we're trying to resolve a function-scoped dependency.
    ///
    /// # Scope Rules
    ///
    /// - Request-scoped can depend on request-scoped (both cached, OK)
    /// - Function-scoped can depend on function-scoped (both fresh, OK)
    /// - Function-scoped can depend on request-scoped (inner cached, outer fresh, OK)
    /// - Request-scoped CANNOT depend on function-scoped (outer cached with stale inner, BAD)
    pub fn check_scope_violation(
        &self,
        type_name: &str,
        scope: DependencyScope,
    ) -> Option<DependencyScopeError> {
        // Only check if we're resolving a function-scoped dependency
        if scope != DependencyScope::Function {
            return None;
        }

        let guard = self.stack.read();

        // Find any request-scoped dependency on the stack
        // (i.e., an outer request-scoped dependency trying to use this function-scoped one)
        for (_, name, dep_scope) in guard.iter().rev() {
            if *dep_scope == DependencyScope::Request {
                return Some(DependencyScopeError::new(
                    name.clone(),
                    type_name.to_owned(),
                ));
            }
        }

        None
    }

    /// Push a type onto the resolution stack with its scope.
    ///
    /// Call this when starting to resolve a dependency.
    pub fn push<T: 'static>(&self, type_name: &str, scope: DependencyScope) {
        let mut guard = self.stack.write();
        guard.push((TypeId::of::<T>(), type_name.to_owned(), scope));
    }

    /// Pop a type from the resolution stack.
    ///
    /// Call this when done resolving a dependency (success or error).
    pub fn pop(&self) {
        let mut guard = self.stack.write();
        guard.pop();
    }

    /// Get the current depth of the resolution stack.
    #[must_use]
    pub fn depth(&self) -> usize {
        let guard = self.stack.read();
        guard.len()
    }

    /// Check if the stack is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.depth() == 0
    }
}

impl Default for ResolutionStack {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for ResolutionStack {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let guard = self.stack.read();
        f.debug_struct("ResolutionStack")
            .field("depth", &guard.len())
            .field(
                "types",
                &guard
                    .iter()
                    .map(|(_, name, scope)| format!("{}({:?})", name, scope))
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

/// RAII guard that automatically pops from the resolution stack on drop.
///
/// This ensures the stack is always properly maintained, even if the
/// resolution fails or panics.
pub struct ResolutionGuard<'a> {
    stack: &'a ResolutionStack,
}

impl<'a> ResolutionGuard<'a> {
    /// Create a new guard that will pop from the stack when dropped.
    fn new(stack: &'a ResolutionStack) -> Self {
        Self { stack }
    }
}

impl Drop for ResolutionGuard<'_> {
    fn drop(&mut self) {
        self.stack.pop();
    }
}

/// Dependency injection extractor.
#[derive(Debug, Clone)]
pub struct Depends<T, C = DefaultDependencyConfig>(pub T, PhantomData<C>);

impl<T, C> Depends<T, C> {
    /// Create a new `Depends` wrapper.
    #[must_use]
    pub fn new(value: T) -> Self {
        Self(value, PhantomData)
    }

    /// Unwrap the inner value.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T, C> Deref for Depends<T, C> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T, C> DerefMut for Depends<T, C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Trait for types that can be injected as dependencies.
pub trait FromDependency: Clone + Send + Sync + 'static {
    /// Error type when dependency resolution fails.
    type Error: IntoResponse + Send + Sync + 'static;

    /// Resolve the dependency.
    fn from_dependency(
        ctx: &RequestContext,
        req: &mut Request,
    ) -> impl Future<Output = Result<Self, Self::Error>> + Send;
}

impl<T, C> FromRequest for Depends<T, C>
where
    T: FromDependency,
    C: DependsConfig,
{
    type Error = T::Error;

    async fn from_request(ctx: &RequestContext, req: &mut Request) -> Result<Self, Self::Error> {
        // Check cancellation before resolving dependency (overrides or normal)
        let _ = ctx.checkpoint();

        // Check overrides first (testing support)
        if let Some(result) = ctx.dependency_overrides().resolve::<T>(ctx, req).await {
            return result.map(Depends::new);
        }

        let scope = C::SCOPE.unwrap_or(DependencyScope::Request);
        let use_cache = C::USE_CACHE && scope == DependencyScope::Request;

        // Check cache - if already resolved, no cycle possible
        if use_cache {
            if let Some(cached) = ctx.dependency_cache().get::<T>() {
                return Ok(Depends::new(cached));
            }
        }

        // Check for circular dependency before attempting resolution
        // (bd-276p: intentional panic for config errors - see module docs)
        let type_name = std::any::type_name::<T>();
        if let Some(cycle) = ctx.resolution_stack().check_cycle::<T>(type_name) {
            handle_circular_dependency(cycle);
        }

        // Check for scope violation: request-scoped cannot depend on function-scoped
        if let Some(scope_err) = ctx
            .resolution_stack()
            .check_scope_violation(type_name, scope)
        {
            handle_scope_violation(scope_err);
        }

        // Push onto resolution stack and create guard for automatic cleanup
        ctx.resolution_stack().push::<T>(type_name, scope);
        let _guard = ResolutionGuard::new(ctx.resolution_stack());

        // Resolve the dependency
        let _ = ctx.checkpoint();
        let value = T::from_dependency(ctx, req).await?;

        // Cache if needed (guard will pop stack when dropped)
        if use_cache {
            ctx.dependency_cache().insert::<T>(value.clone());
        }

        Ok(Depends::new(value))
    }
}

/// Request-scoped dependency cache.
pub struct DependencyCache {
    inner: RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>,
}

impl DependencyCache {
    /// Create an empty cache.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: RwLock::new(HashMap::new()),
        }
    }

    /// Get a cached dependency by type.
    #[must_use]
    pub fn get<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
        let guard = self.inner.read();
        guard
            .get(&TypeId::of::<T>())
            .and_then(|boxed| boxed.downcast_ref::<T>())
            .cloned()
    }

    /// Insert a dependency into the cache.
    pub fn insert<T: Clone + Send + Sync + 'static>(&self, value: T) {
        let mut guard = self.inner.write();
        guard.insert(TypeId::of::<T>(), Box::new(value));
    }

    /// Clear all cached dependencies.
    pub fn clear(&self) {
        let mut guard = self.inner.write();
        guard.clear();
    }

    /// Return the number of cached dependencies.
    #[must_use]
    pub fn len(&self) -> usize {
        let guard = self.inner.read();
        guard.len()
    }

    /// Returns true if no dependencies are cached.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Default for DependencyCache {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for DependencyCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DependencyCache")
            .field("size", &self.len())
            .finish()
    }
}

type OverrideBox = Box<dyn Any + Send + Sync>;
type OverrideFuture = Pin<Box<dyn Future<Output = Result<OverrideBox, OverrideBox>> + Send>>;
type OverrideFn = Arc<dyn Fn(&RequestContext, &mut Request) -> OverrideFuture + Send + Sync>;

/// Dependency override registry (primarily for testing).
pub struct DependencyOverrides {
    inner: RwLock<HashMap<TypeId, OverrideFn>>,
}

impl DependencyOverrides {
    /// Create an empty overrides registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: RwLock::new(HashMap::new()),
        }
    }

    /// Register an override resolver for a dependency type.
    pub fn insert<T, F, Fut>(&self, f: F)
    where
        T: FromDependency,
        F: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<T, T::Error>> + Send + 'static,
    {
        let wrapper: OverrideFn = Arc::new(move |ctx, req| {
            let fut = f(ctx, req);
            Box::pin(async move {
                match fut.await {
                    Ok(value) => Ok(Box::new(value) as OverrideBox),
                    Err(err) => Err(Box::new(err) as OverrideBox),
                }
            })
        });

        let mut guard = self.inner.write();
        guard.insert(TypeId::of::<T>(), wrapper);
    }

    /// Register a fixed override value for a dependency type.
    pub fn insert_value<T>(&self, value: T)
    where
        T: FromDependency,
    {
        self.insert::<T, _, _>(move |_ctx, _req| {
            let value = value.clone();
            async move { Ok(value) }
        });
    }

    /// Clear all overrides.
    pub fn clear(&self) {
        let mut guard = self.inner.write();
        guard.clear();
    }

    /// Resolve an override if one exists for `T`.
    ///
    /// # Type Safety
    ///
    /// The override is looked up by `TypeId::of::<T>()`, which should guarantee
    /// that the stored closure returns the correct types. If a type mismatch
    /// occurs despite the TypeId matching:
    /// - In debug builds: panics via `debug_assert!` to catch bugs early
    /// - In release builds: returns `None` to fall back to normal resolution
    pub async fn resolve<T>(
        &self,
        ctx: &RequestContext,
        req: &mut Request,
    ) -> Option<Result<T, T::Error>>
    where
        T: FromDependency,
    {
        let override_fn = {
            let guard = self.inner.read();
            guard.get(&TypeId::of::<T>()).cloned()
        };

        let override_fn = override_fn?;
        match override_fn(ctx, req).await {
            Ok(value) => match value.downcast::<T>() {
                Ok(value) => Some(Ok(*value)),
                Err(_) => {
                    // Type mismatch should never happen due to TypeId matching.
                    // Panic in debug builds to catch bugs early.
                    debug_assert!(
                        false,
                        "dependency override type mismatch: expected {}, stored override returned wrong type",
                        std::any::type_name::<T>()
                    );
                    // In release builds, fall back to normal resolution.
                    None
                }
            },
            Err(err) => match err.downcast::<T::Error>() {
                Ok(err) => Some(Err(*err)),
                Err(_) => {
                    // Error type mismatch should never happen due to TypeId matching.
                    // Panic in debug builds to catch bugs early.
                    debug_assert!(
                        false,
                        "dependency override error type mismatch: expected {}, stored override returned wrong error type",
                        std::any::type_name::<T::Error>()
                    );
                    // In release builds, fall back to normal resolution.
                    None
                }
            },
        }
    }

    /// Return the number of overrides registered.
    #[must_use]
    pub fn len(&self) -> usize {
        let guard = self.inner.read();
        guard.len()
    }

    /// Returns true if no overrides are registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Default for DependencyOverrides {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for DependencyOverrides {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DependencyOverrides")
            .field("size", &self.len())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::HttpError;
    use crate::request::Method;
    use asupersync::Cx;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    fn test_context(overrides: Option<Arc<DependencyOverrides>>) -> RequestContext {
        let cx = Cx::for_testing();
        let request_id = 1;
        if let Some(overrides) = overrides {
            RequestContext::with_overrides(cx, request_id, overrides)
        } else {
            RequestContext::new(cx, request_id)
        }
    }

    fn empty_request() -> Request {
        Request::new(Method::Get, "/")
    }

    #[derive(Clone)]
    struct CounterDep {
        value: usize,
    }

    impl FromDependency for CounterDep {
        type Error = HttpError;

        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(CounterDep { value: 1 })
        }
    }

    #[test]
    fn depends_basic_resolution() {
        let ctx = test_context(None);
        let mut req = empty_request();
        let dep = futures_executor::block_on(Depends::<CounterDep>::from_request(&ctx, &mut req))
            .expect("dependency resolution failed");
        assert_eq!(dep.value, 1);
    }

    #[derive(Clone)]
    struct CountingDep;

    impl FromDependency for CountingDep {
        type Error = HttpError;

        async fn from_dependency(
            ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            let count = ctx
                .dependency_cache()
                .get::<Arc<AtomicUsize>>()
                .unwrap_or_else(|| Arc::new(AtomicUsize::new(0)));
            count.fetch_add(1, Ordering::SeqCst);
            ctx.dependency_cache().insert(Arc::clone(&count));
            Ok(CountingDep)
        }
    }

    #[test]
    fn depends_caches_per_request() {
        let ctx = test_context(None);
        let mut req = empty_request();

        let _ = futures_executor::block_on(Depends::<CountingDep>::from_request(&ctx, &mut req))
            .expect("first resolution failed");
        let _ = futures_executor::block_on(Depends::<CountingDep>::from_request(&ctx, &mut req))
            .expect("second resolution failed");

        let counter = ctx
            .dependency_cache()
            .get::<Arc<AtomicUsize>>()
            .expect("missing counter");
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn depends_no_cache_config() {
        let ctx = test_context(None);
        let mut req = empty_request();

        let _ = futures_executor::block_on(Depends::<CountingDep, NoCache>::from_request(
            &ctx, &mut req,
        ))
        .expect("first resolution failed");
        let _ = futures_executor::block_on(Depends::<CountingDep, NoCache>::from_request(
            &ctx, &mut req,
        ))
        .expect("second resolution failed");

        let counter = ctx
            .dependency_cache()
            .get::<Arc<AtomicUsize>>()
            .expect("missing counter");
        assert_eq!(counter.load(Ordering::SeqCst), 2);
    }

    #[derive(Clone)]
    struct DepB;

    impl FromDependency for DepB {
        type Error = HttpError;

        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(DepB)
        }
    }

    #[derive(Clone)]
    struct DepA;

    impl FromDependency for DepA {
        type Error = HttpError;

        async fn from_dependency(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<Self, Self::Error> {
            let _ = Depends::<DepB>::from_request(ctx, req).await?;
            Ok(DepA)
        }
    }

    #[test]
    fn depends_nested_resolution() {
        let ctx = test_context(None);
        let mut req = empty_request();
        let _ = futures_executor::block_on(Depends::<DepA>::from_request(&ctx, &mut req))
            .expect("nested resolution failed");
    }

    #[derive(Clone, Debug)]
    struct OverrideDep {
        value: usize,
    }

    impl FromDependency for OverrideDep {
        type Error = HttpError;

        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(OverrideDep { value: 1 })
        }
    }

    #[test]
    fn depends_override_substitution() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 42 });
        let ctx = test_context(Some(overrides));
        let mut req = empty_request();

        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect("override resolution failed");
        assert_eq!(dep.value, 42);
    }

    #[derive(Clone, Debug)]
    struct ErrorDep;

    impl FromDependency for ErrorDep {
        type Error = HttpError;

        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Err(HttpError::bad_request().with_detail("boom"))
        }
    }

    #[test]
    fn depends_error_propagation() {
        let ctx = test_context(None);
        let mut req = empty_request();
        let err = futures_executor::block_on(Depends::<ErrorDep>::from_request(&ctx, &mut req))
            .expect_err("expected dependency error");
        assert_eq!(err.status.as_u16(), 400);
    }

    #[derive(Clone)]
    struct DepC;

    impl FromDependency for DepC {
        type Error = HttpError;

        async fn from_dependency(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<Self, Self::Error> {
            let _ = Depends::<DepA>::from_request(ctx, req).await?;
            let _ = Depends::<DepB>::from_request(ctx, req).await?;
            Ok(DepC)
        }
    }

    #[test]
    fn depends_complex_graph() {
        let ctx = test_context(None);
        let mut req = empty_request();
        let _ = futures_executor::block_on(Depends::<DepC>::from_request(&ctx, &mut req))
            .expect("complex graph resolution failed");
    }

    // ========================================================================
    // Circular Dependency Detection Tests
    // ========================================================================
    //
    // NOTE: Testing actual runtime circular dependencies between types is
    // difficult because Rust's async trait machinery detects type-level
    // cycles at compile time. Instead, we test:
    // 1. The ResolutionStack directly (the core mechanism)
    // 2. CircularDependencyError formatting
    // 3. Diamond patterns (no false positives)
    // ========================================================================

    // Test: ResolutionStack detects simple A -> B -> A cycle
    #[test]
    fn resolution_stack_detects_simple_cycle() {
        // Create unique marker types for cycle detection
        struct TypeA;
        struct TypeB;

        let stack = ResolutionStack::new();

        // Simulate: A starts resolving
        // Before pushing, check that TypeA is not on stack
        assert!(stack.check_cycle::<TypeA>("TypeA").is_none());
        stack.push::<TypeA>("TypeA", DependencyScope::Request);

        // Simulate: A resolves B (different type, should not detect cycle)
        assert!(stack.check_cycle::<TypeB>("TypeB").is_none());
        stack.push::<TypeB>("TypeB", DependencyScope::Request);

        // Simulate: B tries to resolve A (cycle!)
        let cycle = stack.check_cycle::<TypeA>("TypeA");
        assert!(cycle.is_some(), "Should detect A -> B -> A cycle");
        let cycle_path = cycle.unwrap();
        assert_eq!(cycle_path.len(), 3); // TypeA, TypeB, TypeA
        assert_eq!(cycle_path[0], "TypeA");
        assert_eq!(cycle_path[1], "TypeB");
        assert_eq!(cycle_path[2], "TypeA");
    }

    // Test: ResolutionStack detects long cycle A -> B -> C -> D -> A
    #[test]
    fn resolution_stack_detects_long_cycle() {
        // Create unique marker types for the test
        struct TypeA;
        struct TypeB;
        struct TypeC;
        struct TypeD;

        let stack = ResolutionStack::new();

        // Simulate: A -> B -> C -> D -> A
        stack.push::<TypeA>("TypeA", DependencyScope::Request);
        stack.push::<TypeB>("TypeB", DependencyScope::Request);
        stack.push::<TypeC>("TypeC", DependencyScope::Request);
        stack.push::<TypeD>("TypeD", DependencyScope::Request);

        // D tries to resolve A (cycle!)
        let cycle = stack.check_cycle::<TypeA>("TypeA");
        assert!(cycle.is_some(), "Should detect A -> B -> C -> D -> A cycle");
        let cycle_path = cycle.unwrap();
        assert_eq!(cycle_path.len(), 5); // TypeA, TypeB, TypeC, TypeD, TypeA
        assert_eq!(cycle_path[0], "TypeA");
        assert_eq!(cycle_path[4], "TypeA");
    }

    // Test: ResolutionStack allows diamond pattern (no false positive)
    #[test]
    fn resolution_stack_allows_diamond() {
        struct Top;
        struct Left;
        struct Right;
        struct Bottom;

        let stack = ResolutionStack::new();

        // Simulate: Top -> Left -> Bottom (complete Left branch)
        stack.push::<Top>("Top", DependencyScope::Request);
        stack.push::<Left>("Left", DependencyScope::Request);
        stack.push::<Bottom>("Bottom", DependencyScope::Request);
        stack.pop(); // Bottom done
        stack.pop(); // Left done

        // Simulate: Top -> Right -> Bottom (Right branch)
        stack.push::<Right>("Right", DependencyScope::Request);
        // Bottom again - but it's NOT a cycle because we popped it
        assert!(
            stack.check_cycle::<Bottom>("Bottom").is_none(),
            "Diamond pattern should not be detected as a cycle"
        );
        stack.push::<Bottom>("Bottom", DependencyScope::Request);
        stack.pop(); // Bottom done
        stack.pop(); // Right done
        stack.pop(); // Top done

        assert!(stack.is_empty());
    }

    // Test: ResolutionStack detects self-dependency
    #[test]
    fn resolution_stack_detects_self_dependency() {
        struct SelfRef;

        let stack = ResolutionStack::new();
        stack.push::<SelfRef>("SelfRef", DependencyScope::Request);

        // Try to resolve same type again (self-cycle!)
        let cycle = stack.check_cycle::<SelfRef>("SelfRef");
        assert!(cycle.is_some(), "Should detect self-dependency");
        let cycle_path = cycle.unwrap();
        assert_eq!(cycle_path.len(), 2); // SelfRef, SelfRef
        assert_eq!(cycle_path[0], "SelfRef");
        assert_eq!(cycle_path[1], "SelfRef");
    }

    // Test: ResolutionStack basic functionality
    #[test]
    fn resolution_stack_basic() {
        let stack = ResolutionStack::new();
        assert!(stack.is_empty());
        assert_eq!(stack.depth(), 0);

        stack.push::<CounterDep>("CounterDep", DependencyScope::Request);
        assert!(!stack.is_empty());
        assert_eq!(stack.depth(), 1);

        // No cycle yet - different type
        assert!(stack.check_cycle::<ErrorDep>("ErrorDep").is_none());

        // Push another type
        stack.push::<ErrorDep>("ErrorDep", DependencyScope::Request);
        assert_eq!(stack.depth(), 2);

        // Check for cycle with first type - should detect it
        let cycle = stack.check_cycle::<CounterDep>("CounterDep");
        assert!(cycle.is_some());
        let cycle_path = cycle.unwrap();
        assert!(cycle_path.contains(&"CounterDep".to_string()));

        // Pop and verify
        stack.pop();
        assert_eq!(stack.depth(), 1);
        stack.pop();
        assert!(stack.is_empty());
    }

    // Test: CircularDependencyError formatting
    #[test]
    fn circular_dependency_error_formatting() {
        let err = CircularDependencyError::new(vec![
            "DbPool".to_string(),
            "UserService".to_string(),
            "AuthService".to_string(),
            "DbPool".to_string(),
        ]);
        let msg = err.to_string();
        assert!(msg.contains("Circular dependency detected"));
        assert!(msg.contains("DbPool -> UserService -> AuthService -> DbPool"));
        assert_eq!(
            err.cycle_path(),
            "DbPool -> UserService -> AuthService -> DbPool"
        );
    }

    // Test: CircularDependencyError into_response
    #[test]
    fn circular_dependency_error_into_response() {
        let err =
            CircularDependencyError::new(vec!["A".to_string(), "B".to_string(), "A".to_string()]);
        let response = err.into_response();
        assert_eq!(response.status().as_u16(), 500);
    }

    // Test: Diamond dependency graph resolves correctly (runtime test)
    #[derive(Clone)]
    struct DiamondBottom {
        id: u32,
    }
    #[derive(Clone)]
    struct DiamondLeft {
        bottom_id: u32,
    }
    #[derive(Clone)]
    struct DiamondRight {
        bottom_id: u32,
    }
    #[derive(Clone)]
    struct DiamondTop {
        left_id: u32,
        right_id: u32,
    }

    impl FromDependency for DiamondBottom {
        type Error = HttpError;
        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(DiamondBottom { id: 42 })
        }
    }

    impl FromDependency for DiamondLeft {
        type Error = HttpError;
        async fn from_dependency(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<Self, Self::Error> {
            let bottom = Depends::<DiamondBottom>::from_request(ctx, req).await?;
            Ok(DiamondLeft {
                bottom_id: bottom.id,
            })
        }
    }

    impl FromDependency for DiamondRight {
        type Error = HttpError;
        async fn from_dependency(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<Self, Self::Error> {
            let bottom = Depends::<DiamondBottom>::from_request(ctx, req).await?;
            Ok(DiamondRight {
                bottom_id: bottom.id,
            })
        }
    }

    impl FromDependency for DiamondTop {
        type Error = HttpError;
        async fn from_dependency(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<Self, Self::Error> {
            let left = Depends::<DiamondLeft>::from_request(ctx, req).await?;
            let right = Depends::<DiamondRight>::from_request(ctx, req).await?;
            Ok(DiamondTop {
                left_id: left.bottom_id,
                right_id: right.bottom_id,
            })
        }
    }

    #[test]
    fn diamond_pattern_resolves_correctly() {
        let ctx = test_context(None);
        let mut req = empty_request();
        // Diamond pattern should NOT trigger circular dependency detection
        let result =
            futures_executor::block_on(Depends::<DiamondTop>::from_request(&ctx, &mut req));
        assert!(result.is_ok(), "Diamond pattern should not be a cycle");
        let top = result.unwrap();
        assert_eq!(top.left_id, 42);
        assert_eq!(top.right_id, 42);
    }

    // ========================================================================
    // Additional DI Tests for Coverage (fastapi_rust-zf4)
    // ========================================================================

    // Test: Override affects nested dependencies
    #[derive(Clone)]
    struct NestedInnerDep {
        value: String,
    }

    impl FromDependency for NestedInnerDep {
        type Error = HttpError;
        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(NestedInnerDep {
                value: "original".to_string(),
            })
        }
    }

    #[derive(Clone)]
    struct NestedOuterDep {
        inner_value: String,
    }

    impl FromDependency for NestedOuterDep {
        type Error = HttpError;
        async fn from_dependency(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<Self, Self::Error> {
            let inner = Depends::<NestedInnerDep>::from_request(ctx, req).await?;
            Ok(NestedOuterDep {
                inner_value: inner.value.clone(),
            })
        }
    }

    #[test]
    fn override_affects_nested_dependencies() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(NestedInnerDep {
            value: "overridden".to_string(),
        });
        let ctx = test_context(Some(overrides));
        let mut req = empty_request();

        let result =
            futures_executor::block_on(Depends::<NestedOuterDep>::from_request(&ctx, &mut req))
                .expect("nested override resolution failed");

        assert_eq!(
            result.inner_value, "overridden",
            "Override should propagate to nested dependencies"
        );
    }

    // Test: Clear overrides works
    #[test]
    fn clear_overrides_restores_original() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 99 });
        assert_eq!(overrides.len(), 1);

        overrides.clear();
        assert_eq!(overrides.len(), 0);
        assert!(overrides.is_empty());

        // After clear, should return None (no override)
        let ctx = test_context(Some(overrides));
        let mut req = empty_request();
        let result =
            futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
                .expect("resolution after clear failed");

        // Should get original value (1) not overridden value (99)
        assert_eq!(result.value, 1, "After clear, should resolve to original");
    }

    // Test: Multiple dependencies in handler simulation
    #[derive(Clone)]
    struct DepX {
        x: i32,
    }
    #[derive(Clone)]
    struct DepY {
        y: i32,
    }
    #[derive(Clone)]
    struct DepZ {
        z: i32,
    }

    impl FromDependency for DepX {
        type Error = HttpError;
        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(DepX { x: 10 })
        }
    }

    impl FromDependency for DepY {
        type Error = HttpError;
        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(DepY { y: 20 })
        }
    }

    impl FromDependency for DepZ {
        type Error = HttpError;
        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            Ok(DepZ { z: 30 })
        }
    }

    #[test]
    fn multiple_independent_dependencies() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // Simulate a handler that needs X, Y, and Z
        let dep_x =
            futures_executor::block_on(Depends::<DepX>::from_request(&ctx, &mut req)).unwrap();
        let dep_y =
            futures_executor::block_on(Depends::<DepY>::from_request(&ctx, &mut req)).unwrap();
        let dep_z =
            futures_executor::block_on(Depends::<DepZ>::from_request(&ctx, &mut req)).unwrap();

        assert_eq!(dep_x.x, 10);
        assert_eq!(dep_y.y, 20);
        assert_eq!(dep_z.z, 30);
    }

    // Test: Request scope isolation (different contexts have independent caches)
    #[test]
    fn request_scope_isolation() {
        // Request 1
        let ctx1 = test_context(None);
        let mut req1 = empty_request();

        let _ = futures_executor::block_on(Depends::<CountingDep>::from_request(&ctx1, &mut req1))
            .unwrap();
        let counter1 = ctx1.dependency_cache().get::<Arc<AtomicUsize>>().unwrap();

        // Request 2 - fresh context, fresh cache
        let ctx2 = test_context(None);
        let mut req2 = empty_request();

        let _ = futures_executor::block_on(Depends::<CountingDep>::from_request(&ctx2, &mut req2))
            .unwrap();
        let counter2 = ctx2.dependency_cache().get::<Arc<AtomicUsize>>().unwrap();

        // Each request should have its own counter
        assert_eq!(counter1.load(Ordering::SeqCst), 1);
        assert_eq!(counter2.load(Ordering::SeqCst), 1);

        // They should be different Arc instances
        assert!(!Arc::ptr_eq(&counter1, &counter2));
    }

    // Test: Function scope (NoCache) creates fresh instance each time
    #[test]
    fn function_scope_no_caching() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // First call with NoCache
        let _ = futures_executor::block_on(Depends::<CountingDep, NoCache>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        // Second call with NoCache - should create new instance
        let _ = futures_executor::block_on(Depends::<CountingDep, NoCache>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        // Third call with NoCache
        let _ = futures_executor::block_on(Depends::<CountingDep, NoCache>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        let counter = ctx.dependency_cache().get::<Arc<AtomicUsize>>().unwrap();
        assert_eq!(
            counter.load(Ordering::SeqCst),
            3,
            "NoCache should resolve 3 times"
        );
    }

    // Test: Async dependency execution (verifies async works correctly)
    #[derive(Clone)]
    struct AsyncDep {
        computed: u64,
    }

    impl FromDependency for AsyncDep {
        type Error = HttpError;
        async fn from_dependency(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<Self, Self::Error> {
            // Simulate some async computation
            let result = async {
                let a = 21u64;
                let b = 21u64;
                a + b
            }
            .await;
            Ok(AsyncDep { computed: result })
        }
    }

    #[test]
    fn async_dependency_resolution() {
        let ctx = test_context(None);
        let mut req = empty_request();

        let dep = futures_executor::block_on(Depends::<AsyncDep>::from_request(&ctx, &mut req))
            .expect("async dependency resolution failed");

        assert_eq!(dep.computed, 42);
    }

    // Test: Error in nested dependency propagates correctly
    #[derive(Clone, Debug)]
    struct DepThatDependsOnError;

    impl FromDependency for DepThatDependsOnError {
        type Error = HttpError;
        async fn from_dependency(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<Self, Self::Error> {
            // This will fail because ErrorDep always returns an error
            let _ = Depends::<ErrorDep>::from_request(ctx, req).await?;
            Ok(DepThatDependsOnError)
        }
    }

    #[test]
    fn nested_error_propagation() {
        let ctx = test_context(None);
        let mut req = empty_request();

        let result = futures_executor::block_on(Depends::<DepThatDependsOnError>::from_request(
            &ctx, &mut req,
        ));

        assert!(result.is_err(), "Nested error should propagate");
        let err = result.unwrap_err();
        assert_eq!(err.status.as_u16(), 400);
    }

    // Test: DependencyCache clear and len methods
    #[test]
    fn dependency_cache_operations() {
        let cache = DependencyCache::new();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);

        cache.insert::<String>("test".to_string());
        assert!(!cache.is_empty());
        assert_eq!(cache.len(), 1);

        cache.insert::<i32>(42);
        assert_eq!(cache.len(), 2);

        let retrieved = cache.get::<String>().unwrap();
        assert_eq!(retrieved, "test");

        cache.clear();
        assert!(cache.is_empty());
        assert!(cache.get::<String>().is_none());
    }

    // Test: DependencyOverrides dynamic resolver
    #[test]
    fn dynamic_override_resolver() {
        let overrides = Arc::new(DependencyOverrides::new());

        // Register a dynamic resolver that computes value based on context
        overrides.insert::<OverrideDep, _, _>(|_ctx, _req| async move {
            // Could use ctx/req to compute different values
            Ok(OverrideDep { value: 100 })
        });

        let ctx = test_context(Some(overrides));
        let mut req = empty_request();

        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect("dynamic override failed");

        assert_eq!(dep.value, 100);
    }

    // ---- Comprehensive DependencyOverrides tests (bd-3pbd) ----

    #[test]
    fn overrides_new_is_empty() {
        let overrides = DependencyOverrides::new();
        assert!(overrides.is_empty());
        assert_eq!(overrides.len(), 0);
    }

    #[test]
    fn overrides_default_is_empty() {
        let overrides = DependencyOverrides::default();
        assert!(overrides.is_empty());
        assert_eq!(overrides.len(), 0);
    }

    #[test]
    fn overrides_debug_format() {
        let overrides = DependencyOverrides::new();
        let debug = format!("{:?}", overrides);
        assert!(debug.contains("DependencyOverrides"));
        assert!(debug.contains("size"));
    }

    #[test]
    fn overrides_insert_value_increments_len() {
        let overrides = DependencyOverrides::new();
        assert_eq!(overrides.len(), 0);

        overrides.insert_value(OverrideDep { value: 42 });
        assert_eq!(overrides.len(), 1);
        assert!(!overrides.is_empty());
    }

    #[test]
    fn overrides_multiple_types_registered() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 10 });
        overrides.insert_value(NestedInnerDep {
            value: "mocked".to_string(),
        });
        assert_eq!(overrides.len(), 2);

        // Resolve each type independently
        let ctx = test_context(Some(overrides.clone()));
        let mut req = empty_request();

        let dep1 = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect("OverrideDep override failed");
        assert_eq!(dep1.value, 10);

        let mut req2 = empty_request();
        let dep2 =
            futures_executor::block_on(Depends::<NestedInnerDep>::from_request(&ctx, &mut req2))
                .expect("NestedInnerDep override failed");
        assert_eq!(dep2.value, "mocked");
    }

    #[test]
    fn overrides_replace_same_type() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 1 });
        assert_eq!(overrides.len(), 1);

        // Replace with a different value
        overrides.insert_value(OverrideDep { value: 999 });
        assert_eq!(overrides.len(), 1); // Still 1, replaced

        let ctx = test_context(Some(overrides));
        let mut req = empty_request();

        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect("override resolution failed");
        assert_eq!(dep.value, 999);
    }

    #[test]
    fn overrides_clear_removes_all() {
        let overrides = DependencyOverrides::new();
        overrides.insert_value(OverrideDep { value: 42 });
        overrides.insert_value(NestedInnerDep {
            value: "mock".to_string(),
        });
        assert_eq!(overrides.len(), 2);

        overrides.clear();
        assert!(overrides.is_empty());
        assert_eq!(overrides.len(), 0);
    }

    #[test]
    fn overrides_resolve_returns_none_for_unregistered_type() {
        let overrides = Arc::new(DependencyOverrides::new());
        // Only register OverrideDep
        overrides.insert_value(OverrideDep { value: 42 });

        let ctx = test_context(Some(overrides.clone()));
        let mut req = empty_request();

        // NestedInnerDep is NOT overridden, resolve should return None
        let result =
            futures_executor::block_on(overrides.resolve::<NestedInnerDep>(&ctx, &mut req));
        assert!(result.is_none(), "Unregistered type should resolve to None");
    }

    #[test]
    fn overrides_resolve_some_for_registered_type() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 77 });

        let ctx = test_context(Some(overrides.clone()));
        let mut req = empty_request();

        let result = futures_executor::block_on(overrides.resolve::<OverrideDep>(&ctx, &mut req));
        assert!(result.is_some());
        let dep = result.unwrap().expect("resolve should succeed");
        assert_eq!(dep.value, 77);
    }

    #[test]
    fn overrides_not_affect_unrelated_dependency() {
        let overrides = Arc::new(DependencyOverrides::new());
        // Override only NestedInnerDep
        overrides.insert_value(NestedInnerDep {
            value: "overridden".to_string(),
        });

        let ctx = test_context(Some(overrides));
        let mut req = empty_request();

        // OverrideDep should still use its real implementation (returns value: 1)
        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect("should resolve from real implementation");
        assert_eq!(
            dep.value, 1,
            "Unoverridden dep should use real implementation"
        );
    }

    #[test]
    fn overrides_take_precedence_over_cache() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 42 });
        let ctx = test_context(Some(overrides));

        // Pre-populate cache with a different value
        ctx.dependency_cache().insert(OverrideDep { value: 999 });

        let mut req = empty_request();
        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect("override should take precedence");

        // Override should win over cache
        assert_eq!(dep.value, 42, "Override should take precedence over cache");
    }

    #[test]
    fn overrides_dynamic_resolver_can_return_error() {
        let overrides = Arc::new(DependencyOverrides::new());

        overrides.insert::<OverrideDep, _, _>(|_ctx, _req| async move {
            Err(
                HttpError::new(crate::response::StatusCode::INTERNAL_SERVER_ERROR)
                    .with_detail("override error"),
            )
        });

        let ctx = test_context(Some(overrides));
        let mut req = empty_request();

        let err = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect_err("override should return error");
        assert_eq!(err.status.as_u16(), 500);
    }

    #[test]
    fn overrides_insert_value_works_for_multiple_resolves() {
        // insert_value uses Clone, so the value should work for multiple resolves
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 7 });

        let ctx = test_context(Some(overrides));

        for _ in 0..5 {
            let mut req = empty_request();
            let dep =
                futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
                    .expect("repeated resolve should work");
            assert_eq!(dep.value, 7);
        }
    }

    #[test]
    fn overrides_dynamic_resolver_accesses_request() {
        let overrides = Arc::new(DependencyOverrides::new());

        // Dynamic resolver that reads from request extensions
        overrides.insert::<OverrideDep, _, _>(|_ctx, req| {
            let value = req.get_extension::<usize>().copied().unwrap_or(0);
            async move { Ok(OverrideDep { value }) }
        });

        let ctx = test_context(Some(overrides));
        let mut req = empty_request();
        req.insert_extension(42usize);

        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .expect("dynamic resolver with request access failed");
        assert_eq!(dep.value, 42, "Dynamic resolver should read from request");
    }

    #[test]
    fn overrides_after_clear_fall_back_to_real_dependency() {
        let overrides = Arc::new(DependencyOverrides::new());
        overrides.insert_value(OverrideDep { value: 999 });

        // Verify override works
        let ctx = test_context(Some(overrides.clone()));
        let mut req = empty_request();
        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .unwrap();
        assert_eq!(dep.value, 999);

        // Clear and verify fallback to real dependency
        overrides.clear();
        let ctx2 = test_context(Some(overrides));
        let mut req2 = empty_request();
        let dep2 =
            futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx2, &mut req2))
                .unwrap();
        assert_eq!(dep2.value, 1, "After clear, real dependency should be used");
    }

    #[test]
    fn overrides_without_overrides_use_real_dependency() {
        // No overrides at all
        let ctx = test_context(None);
        let mut req = empty_request();

        let dep = futures_executor::block_on(Depends::<OverrideDep>::from_request(&ctx, &mut req))
            .unwrap();
        assert_eq!(
            dep.value, 1,
            "Without overrides, real dependency should be used"
        );
    }

    // Test: ResolutionGuard properly cleans up on drop
    #[test]
    fn resolution_guard_cleanup() {
        let stack = ResolutionStack::new();
        stack.push::<CounterDep>("CounterDep", DependencyScope::Request);
        assert_eq!(stack.depth(), 1);

        {
            // Create guard within a scope
            let _guard = ResolutionGuard::new(&stack);
            stack.push::<ErrorDep>("ErrorDep", DependencyScope::Request);
            assert_eq!(stack.depth(), 2);
            // _guard will pop when dropped
        }

        // After guard drops, one item should be popped
        // Note: guard pops, but we still have CounterDep
        assert_eq!(stack.depth(), 1);
    }

    // ========================================================================
    // CleanupStack Tests (fastapi_rust-9ps)
    // ========================================================================

    #[test]
    fn cleanup_stack_basic() {
        let stack = CleanupStack::new();
        assert!(stack.is_empty());
        assert_eq!(stack.len(), 0);

        // Register a cleanup
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = Arc::clone(&counter);
        stack.push(Box::new(move || {
            Box::pin(async move {
                counter_clone.fetch_add(1, Ordering::SeqCst);
            }) as Pin<Box<dyn Future<Output = ()> + Send>>
        }));

        assert!(!stack.is_empty());
        assert_eq!(stack.len(), 1);

        // Run cleanups
        let completed = futures_executor::block_on(stack.run_cleanups());
        assert_eq!(completed, 1);
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        // Stack should be empty after running
        assert!(stack.is_empty());
    }

    #[test]
    fn cleanup_stack_lifo_order() {
        // Track cleanup execution order
        let order = Arc::new(parking_lot::Mutex::new(Vec::<i32>::new()));

        let stack = CleanupStack::new();

        // Register cleanups: 1, 2, 3
        for i in 1..=3 {
            let order_clone = Arc::clone(&order);
            stack.push(Box::new(move || {
                Box::pin(async move {
                    order_clone.lock().push(i);
                }) as Pin<Box<dyn Future<Output = ()> + Send>>
            }));
        }

        // Run cleanups - should execute in LIFO order: 3, 2, 1
        futures_executor::block_on(stack.run_cleanups());

        let executed_order = order.lock().clone();
        assert_eq!(
            executed_order,
            vec![3, 2, 1],
            "Cleanups should run in LIFO order"
        );
    }

    #[test]
    fn cleanup_stack_take_cleanups() {
        let stack = CleanupStack::new();

        // Register 3 cleanups
        for _ in 0..3 {
            stack.push(Box::new(|| {
                Box::pin(async {}) as Pin<Box<dyn Future<Output = ()> + Send>>
            }));
        }

        assert_eq!(stack.len(), 3);

        // Take cleanups
        let cleanups = stack.take_cleanups();
        assert_eq!(cleanups.len(), 3);

        // Stack should be empty
        assert!(stack.is_empty());
    }

    #[test]
    fn cleanup_stack_multiple_runs() {
        let counter = Arc::new(AtomicUsize::new(0));
        let stack = CleanupStack::new();

        // First batch
        let counter_clone = Arc::clone(&counter);
        stack.push(Box::new(move || {
            Box::pin(async move {
                counter_clone.fetch_add(1, Ordering::SeqCst);
            }) as Pin<Box<dyn Future<Output = ()> + Send>>
        }));
        futures_executor::block_on(stack.run_cleanups());

        // Second batch
        let counter_clone = Arc::clone(&counter);
        stack.push(Box::new(move || {
            Box::pin(async move {
                counter_clone.fetch_add(10, Ordering::SeqCst);
            }) as Pin<Box<dyn Future<Output = ()> + Send>>
        }));
        futures_executor::block_on(stack.run_cleanups());

        assert_eq!(counter.load(Ordering::SeqCst), 11);
    }

    #[test]
    fn cleanup_stack_panic_continues() {
        // Test that if one cleanup panics, remaining cleanups still run (bd-35r4)
        let order = Arc::new(parking_lot::Mutex::new(Vec::<i32>::new()));

        let stack = CleanupStack::new();

        // First cleanup: runs normally
        let order_clone = Arc::clone(&order);
        stack.push(Box::new(move || {
            Box::pin(async move {
                order_clone.lock().push(1);
            }) as Pin<Box<dyn Future<Output = ()> + Send>>
        }));

        // Second cleanup: panics during creation
        stack.push(Box::new(|| -> Pin<Box<dyn Future<Output = ()> + Send>> {
            panic!("cleanup 2 panics");
        }));

        // Third cleanup: runs normally
        let order_clone = Arc::clone(&order);
        stack.push(Box::new(move || {
            Box::pin(async move {
                order_clone.lock().push(3);
            }) as Pin<Box<dyn Future<Output = ()> + Send>>
        }));

        // Run cleanups - LIFO order: 3, 2 (panics), 1
        let completed = futures_executor::block_on(stack.run_cleanups());

        // Only 2 should complete (cleanup 2 panicked)
        assert_eq!(completed, 2, "Should report 2 successful cleanups");

        let executed_order = order.lock().clone();
        // Should still run cleanup 3 and 1 despite cleanup 2 panicking
        assert_eq!(
            executed_order,
            vec![3, 1],
            "Cleanups should continue after panic"
        );
    }

    #[test]
    fn cleanup_runs_after_handler_error() {
        // Test that cleanups run even when handler returns an error (bd-35r4)
        // This simulates the server calling run_cleanups after any handler result

        let cleanup_ran = Arc::new(AtomicBool::new(false));
        let cleanup_ran_clone = Arc::clone(&cleanup_ran);

        let ctx = test_context(None);

        // Register a cleanup
        ctx.cleanup_stack().push(Box::new(move || {
            Box::pin(async move {
                cleanup_ran_clone.store(true, Ordering::SeqCst);
            }) as Pin<Box<dyn Future<Output = ()> + Send>>
        }));

        // Simulate handler returning an error (we just don't use the result)
        let handler_result: Result<(), HttpError> =
            Err(HttpError::new(StatusCode::INTERNAL_SERVER_ERROR).with_detail("handler failed"));

        // Server always runs cleanups after handler, regardless of result
        futures_executor::block_on(ctx.cleanup_stack().run_cleanups());

        assert!(
            cleanup_ran.load(Ordering::SeqCst),
            "Cleanup should run even after handler error"
        );

        // The handler error is still propagated
        assert!(handler_result.is_err());
    }

    // ========================================================================
    // DependsCleanup Tests (fastapi_rust-9ps)
    // ========================================================================

    /// A dependency that tracks setup and cleanup
    #[derive(Clone)]
    struct TrackedResource {
        id: u32,
    }

    impl FromDependencyWithCleanup for TrackedResource {
        type Value = TrackedResource;
        type Error = HttpError;

        async fn setup(
            ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<(Self::Value, Option<CleanupFn>), Self::Error> {
            // Get or create a tracker in the dependency cache
            let tracker = ctx
                .dependency_cache()
                .get::<Arc<parking_lot::Mutex<Vec<String>>>>()
                .unwrap_or_else(|| {
                    let t = Arc::new(parking_lot::Mutex::new(Vec::new()));
                    ctx.dependency_cache().insert(Arc::clone(&t));
                    t
                });

            tracker.lock().push("setup:resource".to_string());

            let cleanup_tracker = Arc::clone(&tracker);
            let cleanup = Box::new(move || {
                Box::pin(async move {
                    cleanup_tracker.lock().push("cleanup:resource".to_string());
                }) as Pin<Box<dyn Future<Output = ()> + Send>>
            }) as CleanupFn;

            Ok((TrackedResource { id: 42 }, Some(cleanup)))
        }
    }

    #[test]
    fn depends_cleanup_registers_cleanup() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // Resolve the dependency
        let dep = futures_executor::block_on(DependsCleanup::<TrackedResource>::from_request(
            &ctx, &mut req,
        ))
        .expect("cleanup dependency resolution failed");

        assert_eq!(dep.id, 42);

        // Cleanup should be registered
        assert_eq!(ctx.cleanup_stack().len(), 1);

        // Get tracker
        let tracker = ctx
            .dependency_cache()
            .get::<Arc<parking_lot::Mutex<Vec<String>>>>()
            .unwrap();

        // Only setup should have run
        let events = tracker.lock().clone();
        assert_eq!(events, vec!["setup:resource"]);

        // Run cleanups
        futures_executor::block_on(ctx.cleanup_stack().run_cleanups());

        // Now cleanup should have run too
        let events = tracker.lock().clone();
        assert_eq!(events, vec!["setup:resource", "cleanup:resource"]);
    }

    /// A dependency without cleanup
    #[derive(Clone)]
    struct NoCleanupResource {
        value: String,
    }

    impl FromDependencyWithCleanup for NoCleanupResource {
        type Value = NoCleanupResource;
        type Error = HttpError;

        async fn setup(
            _ctx: &RequestContext,
            _req: &mut Request,
        ) -> Result<(Self::Value, Option<CleanupFn>), Self::Error> {
            Ok((
                NoCleanupResource {
                    value: "no cleanup".to_string(),
                },
                None, // No cleanup needed
            ))
        }
    }

    #[test]
    fn depends_cleanup_no_cleanup_fn() {
        let ctx = test_context(None);
        let mut req = empty_request();

        let dep = futures_executor::block_on(DependsCleanup::<NoCleanupResource>::from_request(
            &ctx, &mut req,
        ))
        .expect("no cleanup dependency resolution failed");

        assert_eq!(dep.value, "no cleanup");

        // No cleanup should be registered
        assert!(ctx.cleanup_stack().is_empty());
    }

    /// Nested dependencies with cleanup
    #[derive(Clone)]
    struct OuterWithCleanup {
        inner_id: u32,
    }

    impl FromDependencyWithCleanup for OuterWithCleanup {
        type Value = OuterWithCleanup;
        type Error = HttpError;

        async fn setup(
            ctx: &RequestContext,
            req: &mut Request,
        ) -> Result<(Self::Value, Option<CleanupFn>), Self::Error> {
            // Resolve inner dependency first
            let inner = DependsCleanup::<TrackedResource>::from_request(ctx, req).await?;

            // Get tracker
            let tracker = ctx
                .dependency_cache()
                .get::<Arc<parking_lot::Mutex<Vec<String>>>>()
                .unwrap();

            tracker.lock().push("setup:outer".to_string());

            let cleanup_tracker = Arc::clone(&tracker);
            let cleanup = Box::new(move || {
                Box::pin(async move {
                    cleanup_tracker.lock().push("cleanup:outer".to_string());
                }) as Pin<Box<dyn Future<Output = ()> + Send>>
            }) as CleanupFn;

            Ok((OuterWithCleanup { inner_id: inner.id }, Some(cleanup)))
        }
    }

    #[test]
    fn depends_cleanup_nested_lifo() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // Resolve outer (which resolves inner)
        let dep = futures_executor::block_on(DependsCleanup::<OuterWithCleanup>::from_request(
            &ctx, &mut req,
        ))
        .expect("nested cleanup dependency resolution failed");

        assert_eq!(dep.inner_id, 42);

        // Both cleanups should be registered
        assert_eq!(ctx.cleanup_stack().len(), 2);

        // Get tracker
        let tracker = ctx
            .dependency_cache()
            .get::<Arc<parking_lot::Mutex<Vec<String>>>>()
            .unwrap();

        // Setup order: inner, then outer
        let events_before = tracker.lock().clone();
        assert_eq!(events_before, vec!["setup:resource", "setup:outer"]);

        // Run cleanups - LIFO order: outer first, then inner
        futures_executor::block_on(ctx.cleanup_stack().run_cleanups());

        let events_after = tracker.lock().clone();
        assert_eq!(
            events_after,
            vec![
                "setup:resource",
                "setup:outer",
                "cleanup:outer",
                "cleanup:resource"
            ],
            "Cleanups should run in LIFO order"
        );
    }

    #[test]
    fn depends_cleanup_caching() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // First resolution
        let _dep1 = futures_executor::block_on(DependsCleanup::<TrackedResource>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        // Second resolution - should use cache
        let _dep2 = futures_executor::block_on(DependsCleanup::<TrackedResource>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        // Only one cleanup should be registered (due to caching)
        assert_eq!(ctx.cleanup_stack().len(), 1);

        // Get tracker
        let tracker = ctx
            .dependency_cache()
            .get::<Arc<parking_lot::Mutex<Vec<String>>>>()
            .unwrap();

        // Setup should only run once
        let events = tracker.lock().clone();
        assert_eq!(events, vec!["setup:resource"]);
    }

    // ========================================================================
    // Scope Constraint Validation Tests (fastapi_rust-kpe)
    // ========================================================================

    // Test: DependencyScopeError formatting
    #[test]
    fn scope_error_formatting() {
        let err = DependencyScopeError::new("CachedUser".to_string(), "DbConnection".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Dependency scope violation"));
        assert!(msg.contains("request-scoped 'CachedUser'"));
        assert!(msg.contains("function-scoped 'DbConnection'"));
        assert!(msg.contains("cached value becomes stale"));
    }

    // Test: DependencyScopeError into_response
    #[test]
    fn scope_error_into_response() {
        let err = DependencyScopeError::new("A".to_string(), "B".to_string());
        let response = err.into_response();
        assert_eq!(response.status().as_u16(), 500);
    }

    // Test: ResolutionStack detects request -> function scope violation
    #[test]
    fn resolution_stack_detects_scope_violation() {
        #[allow(dead_code)]
        struct RequestScoped;
        #[allow(dead_code)]
        struct FunctionScoped;

        let stack = ResolutionStack::new();

        // Push request-scoped dependency
        stack.push::<RequestScoped>("RequestScoped", DependencyScope::Request);

        // Now try to resolve function-scoped - should detect violation
        let violation = stack.check_scope_violation("FunctionScoped", DependencyScope::Function);
        assert!(
            violation.is_some(),
            "Should detect request -> function scope violation"
        );
        let err = violation.unwrap();
        assert_eq!(err.request_scoped_type, "RequestScoped");
        assert_eq!(err.function_scoped_type, "FunctionScoped");
    }

    // Test: ResolutionStack allows request -> request (valid)
    #[test]
    fn resolution_stack_allows_request_to_request() {
        #[allow(dead_code)]
        struct RequestA;
        #[allow(dead_code)]
        struct RequestB;

        let stack = ResolutionStack::new();

        // Push request-scoped dependency
        stack.push::<RequestA>("RequestA", DependencyScope::Request);

        // Another request-scoped is OK
        let violation = stack.check_scope_violation("RequestB", DependencyScope::Request);
        assert!(violation.is_none(), "Request -> Request should be allowed");
    }

    // Test: ResolutionStack allows function -> function (valid)
    #[test]
    fn resolution_stack_allows_function_to_function() {
        #[allow(dead_code)]
        struct FunctionA;
        #[allow(dead_code)]
        struct FunctionB;

        let stack = ResolutionStack::new();

        // Push function-scoped dependency
        stack.push::<FunctionA>("FunctionA", DependencyScope::Function);

        // Another function-scoped is OK
        let violation = stack.check_scope_violation("FunctionB", DependencyScope::Function);
        assert!(
            violation.is_none(),
            "Function -> Function should be allowed"
        );
    }

    // Test: ResolutionStack allows function -> request (valid)
    #[test]
    fn resolution_stack_allows_function_to_request() {
        #[allow(dead_code)]
        struct FunctionScoped;
        #[allow(dead_code)]
        struct RequestScoped;

        let stack = ResolutionStack::new();

        // Push function-scoped dependency
        stack.push::<FunctionScoped>("FunctionScoped", DependencyScope::Function);

        // Request-scoped inner is OK (cached inner is fine for fresh outer)
        let violation = stack.check_scope_violation("RequestScoped", DependencyScope::Request);
        assert!(violation.is_none(), "Function -> Request should be allowed");
    }

    // Test: Nested scope violation detection (A(request) -> B(request) -> C(function))
    #[test]
    fn resolution_stack_nested_scope_violation() {
        #[allow(dead_code)]
        struct OuterRequest;
        #[allow(dead_code)]
        struct MiddleRequest;
        #[allow(dead_code)]
        struct InnerFunction;

        let stack = ResolutionStack::new();

        // Push request -> request -> function
        stack.push::<OuterRequest>("OuterRequest", DependencyScope::Request);
        stack.push::<MiddleRequest>("MiddleRequest", DependencyScope::Request);

        // Inner function-scoped should fail because there's a request-scoped in the chain
        let violation = stack.check_scope_violation("InnerFunction", DependencyScope::Function);
        assert!(violation.is_some(), "Should detect nested scope violation");
        let err = violation.unwrap();
        // Should report the closest request-scoped (MiddleRequest)
        assert_eq!(err.request_scoped_type, "MiddleRequest");
        assert_eq!(err.function_scoped_type, "InnerFunction");
    }

    // Test: Empty stack has no scope violation
    #[test]
    fn resolution_stack_empty_no_scope_violation() {
        let stack = ResolutionStack::new();

        // Empty stack should allow any scope
        let violation_fn = stack.check_scope_violation("SomeDep", DependencyScope::Function);
        let violation_req = stack.check_scope_violation("SomeDep", DependencyScope::Request);

        assert!(
            violation_fn.is_none(),
            "Empty stack should allow function scope"
        );
        assert!(
            violation_req.is_none(),
            "Empty stack should allow request scope"
        );
    }

    // Test: Scope violation in runtime dependency resolution (integration test)
    // This test verifies the actual panic behavior when scope rules are violated.
    //
    // NOTE: We can't easily test the panic in normal unit tests because catch_unwind
    // doesn't work well with async. Instead, we test the check_scope_violation method
    // directly in the tests above. The actual panic behavior is tested via the
    // Depends::from_request implementation.

    // Test: Function-scoped dependency works correctly (NoCache config)
    #[test]
    fn function_scoped_resolves_fresh_each_time() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // Use NoCache (function scope)
        let _ = futures_executor::block_on(Depends::<CountingDep, NoCache>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        let _ = futures_executor::block_on(Depends::<CountingDep, NoCache>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        let counter = ctx.dependency_cache().get::<Arc<AtomicUsize>>().unwrap();
        assert_eq!(
            counter.load(Ordering::SeqCst),
            2,
            "Function-scoped should resolve 2 times (not cached)"
        );
    }

    // Test: Request-scoped dependency is cached correctly
    #[test]
    fn request_scoped_cached_within_request() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // Use default config (request scope)
        let _ = futures_executor::block_on(Depends::<CountingDep>::from_request(&ctx, &mut req))
            .unwrap();

        let _ = futures_executor::block_on(Depends::<CountingDep>::from_request(&ctx, &mut req))
            .unwrap();

        let counter = ctx.dependency_cache().get::<Arc<AtomicUsize>>().unwrap();
        assert_eq!(
            counter.load(Ordering::SeqCst),
            1,
            "Request-scoped should resolve only once (cached)"
        );
    }

    // ========================================================================
    // Scope and Cleanup Integration Tests (bd-2290)
    // ========================================================================

    /// Test that request-scoped dependencies with cleanup are only cleaned up once
    /// even when resolved multiple times
    #[test]
    fn request_scope_cleanup_only_once() {
        let ctx = test_context(None);
        let mut req = empty_request();

        // Resolve the same cleanup dependency multiple times
        let _ = futures_executor::block_on(DependsCleanup::<TrackedResource>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        let _ = futures_executor::block_on(DependsCleanup::<TrackedResource>::from_request(
            &ctx, &mut req,
        ))
        .unwrap();

        // Only one cleanup should be registered due to caching
        assert_eq!(
            ctx.cleanup_stack().len(),
            1,
            "Request-scoped should only register cleanup once"
        );

        let tracker = ctx
            .dependency_cache()
            .get::<Arc<parking_lot::Mutex<Vec<String>>>>()
            .unwrap();

        // Setup only called once
        assert_eq!(tracker.lock().len(), 1);
        assert_eq!(tracker.lock()[0], "setup:resource");

        // Run cleanups
        futures_executor::block_on(ctx.cleanup_stack().run_cleanups());

        // Only one cleanup ran
        let events = tracker.lock().clone();
        assert_eq!(
            events,
            vec!["setup:resource", "cleanup:resource"],
            "Cleanup should run exactly once for cached dependency"
        );
    }

    /// Test that function-scoped cleanup dependencies register cleanup for each resolution
    #[test]
    fn function_scope_cleanup_each_time() {
        // Create a function-scoped cleanup dependency
        #[derive(Clone)]
        #[allow(dead_code)]
        struct FunctionScopedWithCleanup {
            id: u32,
        }

        impl FromDependencyWithCleanup for FunctionScopedWithCleanup {
            type Value = FunctionScopedWithCleanup;
            type Error = HttpError;

            async fn setup(
                ctx: &RequestContext,
                _req: &mut Request,
            ) -> Result<(Self::Value, Option<CleanupFn>), Self::Error> {
                // Get or create a cleanup counter
                let counter = ctx
                    .dependency_cache()
                    .get::<Arc<AtomicUsize>>()
                    .unwrap_or_else(|| {
                        let c = Arc::new(AtomicUsize::new(0));
                        ctx.dependency_cache().insert(Arc::clone(&c));
                        c
                    });

                let cleanup_counter = Arc::clone(&counter);
                let cleanup = Box::new(move || {
                    Box::pin(async move {
                        cleanup_counter.fetch_add(1, Ordering::SeqCst);
                    }) as Pin<Box<dyn Future<Output = ()> + Send>>
                }) as CleanupFn;

                Ok((FunctionScopedWithCleanup { id: 42 }, Some(cleanup)))
            }
        }

        let ctx = test_context(None);
        let mut req = empty_request();

        // Resolve 3 times with NoCache
        let _ = futures_executor::block_on(
            DependsCleanup::<FunctionScopedWithCleanup, NoCache>::from_request(&ctx, &mut req),
        )
        .unwrap();

        let _ = futures_executor::block_on(
            DependsCleanup::<FunctionScopedWithCleanup, NoCache>::from_request(&ctx, &mut req),
        )
        .unwrap();

        let _ = futures_executor::block_on(
            DependsCleanup::<FunctionScopedWithCleanup, NoCache>::from_request(&ctx, &mut req),
        )
        .unwrap();

        // Should have 3 cleanups registered
        assert_eq!(
            ctx.cleanup_stack().len(),
            3,
            "Function-scoped should register cleanup each time"
        );

        // Run all cleanups
        futures_executor::block_on(ctx.cleanup_stack().run_cleanups());

        // Verify all 3 cleanups ran
        let counter = ctx.dependency_cache().get::<Arc<AtomicUsize>>().unwrap();
        assert_eq!(
            counter.load(Ordering::SeqCst),
            3,
            "All 3 cleanups should have run"
        );
    }
}