dependency-injector 1.0.0

High-performance, lock-free dependency injection container for Rust
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
//! High-performance dependency injection container
//!
//! The `Container` is the core of the DI system. It stores services and
//! resolves dependencies with minimal overhead.

use crate::factory::AnyFactory;
use crate::storage::{ServiceStorage, downcast_arc_unchecked};
use crate::{DiError, Injectable, Result};
use std::any::{Any, TypeId};
use std::cell::UnsafeCell;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

#[cfg(feature = "logging")]
use tracing::{debug, trace};

// =============================================================================
// Thread-Local Hot Cache (Phase 5 optimization)
// =============================================================================

/// Number of slots in the thread-local hot cache (power of 2 for fast indexing)
/// 4 slots fits in a single cache line and provides good hit rates for typical apps.
const HOT_CACHE_SLOTS: usize = 4;

/// A cached service entry
///
/// Phase 13 optimization: Stores pre-computed u64 hash instead of TypeId
/// to avoid transmute on every comparison.
struct CacheEntry {
    /// Pre-computed hash of TypeId (avoids transmute on lookup)
    type_hash: u64,
    /// Pointer to the storage this was resolved from (for scope identity)
    storage_ptr: usize,
    /// The cached service
    service: Arc<dyn Any + Send + Sync>,
}

/// Thread-local cache for frequently accessed services.
///
/// This provides ~8-10ns speedup for hot services by avoiding DashMap lookups.
/// Uses a simple direct-mapped cache with TypeId + storage pointer as key.
struct HotCache {
    entries: [Option<CacheEntry>; HOT_CACHE_SLOTS],
}

impl HotCache {
    const fn new() -> Self {
        Self {
            entries: [const { None }; HOT_CACHE_SLOTS],
        }
    }

    /// Get a cached service if present for a specific container
    ///
    /// Phase 12+13 optimization: Uses UnsafeCell (no RefCell borrow check)
    /// and pre-computed type_hash (no transmute on lookup).
    #[inline(always)]
    fn get<T: Send + Sync + 'static>(&self, storage_ptr: usize) -> Option<Arc<T>> {
        let type_hash = Self::type_hash::<T>();
        let slot = Self::slot_for_hash(type_hash, storage_ptr);

        if let Some(entry) = &self.entries[slot] {
            // Phase 13: Compare u64 hash directly (faster than TypeId comparison)
            if entry.type_hash == type_hash && entry.storage_ptr == storage_ptr {
                // Cache hit - clone and downcast (unchecked since type_hash matches)
                // SAFETY: We verified type_hash matches, so the Arc contains type T
                let arc = entry.service.clone();
                return Some(unsafe { downcast_arc_unchecked(arc) });
            }
        }
        None
    }

    /// Insert a service into the cache for a specific container
    #[inline]
    fn insert<T: Injectable>(&mut self, storage_ptr: usize, service: Arc<T>) {
        let type_hash = Self::type_hash::<T>();
        let slot = Self::slot_for_hash(type_hash, storage_ptr);

        self.entries[slot] = Some(CacheEntry {
            type_hash,
            storage_ptr,
            service: service as Arc<dyn Any + Send + Sync>,
        });
    }

    /// Clear the cache (call when container is modified)
    #[inline]
    fn clear(&mut self) {
        self.entries = [const { None }; HOT_CACHE_SLOTS];
    }

    /// Extract u64 hash from TypeId (computed once per type at compile time via monomorphization)
    #[inline(always)]
    fn type_hash<T: 'static>() -> u64 {
        let type_id = TypeId::of::<T>();
        // SAFETY: TypeId is #[repr(transparent)] wrapper around u128
        unsafe { std::mem::transmute_copy(&type_id) }
    }

    /// Calculate slot index from pre-computed type hash and storage pointer
    #[inline(always)]
    fn slot_for_hash(type_hash: u64, storage_ptr: usize) -> usize {
        // Fast bit mixing: XOR with rotated storage_ptr for good distribution
        let mixed = type_hash ^ (storage_ptr as u64).rotate_left(32);

        // Use golden ratio multiplication for final mixing (fast & good distribution)
        let slot = mixed.wrapping_mul(0x9e3779b97f4a7c15);

        (slot as usize) & (HOT_CACHE_SLOTS - 1)
    }
}

thread_local! {
    /// Thread-local hot cache for frequently accessed services
    ///
    /// Phase 12 optimization: Uses UnsafeCell instead of RefCell to eliminate
    /// borrow checking overhead. This is safe because thread_local! guarantees
    /// single-threaded access.
    static HOT_CACHE: UnsafeCell<HotCache> = const { UnsafeCell::new(HotCache::new()) };
}

/// Helper to access the hot cache without RefCell overhead
///
/// SAFETY: thread_local! guarantees single-threaded access, so we can use
/// UnsafeCell without data races. We ensure no aliasing by limiting access
/// to immutable borrows for reads and brief mutable borrows for writes.
#[inline(always)]
fn with_hot_cache<F, R>(f: F) -> R
where
    F: FnOnce(&HotCache) -> R,
{
    HOT_CACHE.with(|cell| {
        // SAFETY: thread_local guarantees single-threaded access
        let cache = unsafe { &*cell.get() };
        f(cache)
    })
}

/// Helper to mutably access the hot cache
#[inline(always)]
fn with_hot_cache_mut<F, R>(f: F) -> R
where
    F: FnOnce(&mut HotCache) -> R,
{
    HOT_CACHE.with(|cell| {
        // SAFETY: thread_local guarantees single-threaded access
        let cache = unsafe { &mut *cell.get() };
        f(cache)
    })
}

/// High-performance dependency injection container.
///
/// Uses lock-free data structures for maximum concurrent throughput.
/// Supports hierarchical scopes with full parent chain resolution.
///
/// # Examples
///
/// ```rust
/// use dependency_injector::Container;
///
/// #[derive(Clone)]
/// struct MyService { name: String }
///
/// let container = Container::new();
/// container.singleton(MyService { name: "test".into() });
///
/// let service = container.get::<MyService>().unwrap();
/// assert_eq!(service.name, "test");
/// ```
#[derive(Clone)]
pub struct Container {
    /// Service storage (lock-free)
    storage: Arc<ServiceStorage>,
    /// Parent storage - strong reference for fast resolution (Phase 2 optimization)
    /// This avoids Weak::upgrade() cost on every parent resolution
    parent_storage: Option<Arc<ServiceStorage>>,
    /// Lock state - uses AtomicBool for fast lock checking (no contention)
    locked: Arc<AtomicBool>,
    /// Scope depth for debugging
    depth: u32,
}

impl Container {
    /// Create a new root container.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    /// let container = Container::new();
    /// ```
    #[inline]
    pub fn new() -> Self {
        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            depth = 0,
            "Creating new root DI container"
        );

        Self {
            storage: Arc::new(ServiceStorage::new()),
            parent_storage: None,
            locked: Arc::new(AtomicBool::new(false)),
            depth: 0,
        }
    }

    /// Create a container with pre-allocated capacity.
    ///
    /// Use this when you know approximately how many services will be registered.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            storage: Arc::new(ServiceStorage::with_capacity(capacity)),
            parent_storage: None,
            locked: Arc::new(AtomicBool::new(false)),
            depth: 0,
        }
    }

    /// Create a child scope that inherits from this container.
    ///
    /// Child scopes can:
    /// - Access all services from parent scopes
    /// - Override parent services with local registrations
    /// - Have their own transient/scoped services
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct AppConfig { debug: bool }
    ///
    /// #[derive(Clone)]
    /// struct RequestId(String);
    ///
    /// let root = Container::new();
    /// root.singleton(AppConfig { debug: true });
    ///
    /// let request = root.scope();
    /// request.singleton(RequestId("req-123".into()));
    ///
    /// // Request scope can access root config
    /// assert!(request.contains::<AppConfig>());
    /// ```
    #[inline]
    pub fn scope(&self) -> Self {
        let child_depth = self.depth + 1;

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            parent_depth = self.depth,
            child_depth = child_depth,
            parent_services = self.storage.len(),
            "Creating child scope from parent container"
        );

        Self {
            // Phase 9: Storage now holds parent reference for deep chain resolution
            storage: Arc::new(ServiceStorage::with_parent(Arc::clone(&self.storage))),
            parent_storage: Some(Arc::clone(&self.storage)), // Keep for quick parent access
            locked: Arc::new(AtomicBool::new(false)),
            depth: child_depth,
        }
    }

    /// Alias for `scope()` - creates a child container.
    #[inline]
    pub fn create_scope(&self) -> Self {
        self.scope()
    }

    // =========================================================================
    // Registration Methods
    // =========================================================================

    /// Register a singleton service (eager).
    ///
    /// The instance is stored immediately and shared across all resolves.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct Database { url: String }
    ///
    /// let container = Container::new();
    /// container.singleton(Database { url: "postgres://localhost".into() });
    /// ```
    #[inline]
    pub fn singleton<T: Injectable>(&self, instance: T) {
        self.check_not_locked();

        let type_id = TypeId::of::<T>();
        let type_name = std::any::type_name::<T>();

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            service = type_name,
            lifetime = "singleton",
            depth = self.depth,
            service_count = self.storage.len() + 1,
            "Registering singleton service"
        );

        // Phase 2: Use enum-based AnyFactory directly
        self.storage
            .insert(type_id, AnyFactory::singleton(instance));
    }

    /// Register a lazy singleton service.
    ///
    /// The factory is called once on first access, then the instance is cached.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct ExpensiveService { data: Vec<u8> }
    ///
    /// let container = Container::new();
    /// container.lazy(|| ExpensiveService {
    ///     data: vec![0; 1024 * 1024], // Only allocated on first use
    /// });
    /// ```
    #[inline]
    pub fn lazy<T: Injectable, F>(&self, factory: F)
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.check_not_locked();

        let type_id = TypeId::of::<T>();
        let type_name = std::any::type_name::<T>();

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            service = type_name,
            lifetime = "lazy_singleton",
            depth = self.depth,
            service_count = self.storage.len() + 1,
            "Registering lazy singleton service (will be created on first access)"
        );

        // Phase 2: Use enum-based AnyFactory directly
        self.storage.insert(type_id, AnyFactory::lazy(factory));
    }

    /// Register a transient service.
    ///
    /// A new instance is created on every resolve.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    /// use std::sync::atomic::{AtomicU64, Ordering};
    ///
    /// static COUNTER: AtomicU64 = AtomicU64::new(0);
    ///
    /// #[derive(Clone)]
    /// struct RequestId(u64);
    ///
    /// let container = Container::new();
    /// container.transient(|| RequestId(COUNTER.fetch_add(1, Ordering::SeqCst)));
    ///
    /// let id1 = container.get::<RequestId>().unwrap();
    /// let id2 = container.get::<RequestId>().unwrap();
    /// assert_ne!(id1.0, id2.0); // Different instances
    /// ```
    #[inline]
    pub fn transient<T: Injectable, F>(&self, factory: F)
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.check_not_locked();

        let type_id = TypeId::of::<T>();
        let type_name = std::any::type_name::<T>();

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            service = type_name,
            lifetime = "transient",
            depth = self.depth,
            service_count = self.storage.len() + 1,
            "Registering transient service (new instance on every resolve)"
        );

        // Phase 2: Use enum-based AnyFactory directly
        self.storage.insert(type_id, AnyFactory::transient(factory));
    }

    /// Register using a factory (alias for `lazy`).
    #[inline]
    pub fn register_factory<T: Injectable, F>(&self, factory: F)
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.lazy(factory);
    }

    /// Register an instance (alias for `singleton`).
    #[inline]
    pub fn register<T: Injectable>(&self, instance: T) {
        self.singleton(instance);
    }

    /// Register a boxed instance.
    #[inline]
    #[allow(clippy::boxed_local)]
    pub fn register_boxed<T: Injectable>(&self, instance: Box<T>) {
        self.singleton(*instance);
    }

    /// Register by TypeId directly (advanced use).
    #[inline]
    pub fn register_by_id(&self, type_id: TypeId, instance: Arc<dyn Any + Send + Sync>) {
        self.check_not_locked();

        // Phase 2: Use the singleton factory with pre-erased Arc directly
        self.storage.insert(
            type_id,
            AnyFactory::Singleton(crate::factory::SingletonFactory { instance }),
        );
    }

    // =========================================================================
    // Resolution Methods
    // =========================================================================

    /// Resolve a service by type.
    ///
    /// Returns `Arc<T>` for zero-copy sharing. Walks the parent chain if
    /// not found in the current scope.
    ///
    /// # Performance
    ///
    /// Uses thread-local caching for frequently accessed services (~8ns vs ~19ns).
    /// The cache is automatically populated on first access.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct MyService;
    ///
    /// let container = Container::new();
    /// container.singleton(MyService);
    ///
    /// let service = container.get::<MyService>().unwrap();
    /// ```
    #[inline]
    pub fn get<T: Injectable>(&self) -> Result<Arc<T>> {
        // Get storage pointer for cache key (unique per container scope)
        let storage_ptr = Arc::as_ptr(&self.storage) as usize;

        // Phase 5+12: Check thread-local hot cache first (UnsafeCell, no RefCell overhead)
        // Note: Transients won't be in cache, so they'll fall through to get_and_cache
        if let Some(cached) = with_hot_cache(|cache| cache.get::<T>(storage_ptr)) {
            #[cfg(feature = "logging")]
            trace!(
                target: "dependency_injector",
                service = std::any::type_name::<T>(),
                depth = self.depth,
                location = "hot_cache",
                "Service resolved from thread-local cache"
            );
            return Ok(cached);
        }

        // Cache miss - resolve normally and cache the result (unless transient)
        self.get_and_cache::<T>(storage_ptr)
    }

    /// Internal: Resolve and cache a service
    ///
    /// Phase 15 optimization: Fast path for root containers (depth == 0) avoids
    /// function call overhead to resolve_from_parents when there are no parents.
    #[inline]
    fn get_and_cache<T: Injectable>(&self, storage_ptr: usize) -> Result<Arc<T>> {
        let type_id = TypeId::of::<T>();

        #[cfg(feature = "logging")]
        let type_name = std::any::type_name::<T>();

        #[cfg(feature = "logging")]
        trace!(
            target: "dependency_injector",
            service = type_name,
            depth = self.depth,
            "Resolving service (cache miss)"
        );

        // Try local storage first (most common case)
        // Use get_with_transient_flag to avoid second DashMap lookup for is_transient
        if let Some((service, is_transient)) = self.storage.get_with_transient_flag::<T>() {
            #[cfg(feature = "logging")]
            trace!(
                target: "dependency_injector",
                service = type_name,
                depth = self.depth,
                location = "local",
                "Service resolved from current scope"
            );

            // Cache non-transient services (transients create new instances each time)
            if !is_transient {
                with_hot_cache_mut(|cache| cache.insert(storage_ptr, Arc::clone(&service)));
            }

            return Ok(service);
        }

        // Phase 15: Fast path for root containers - no parents to walk
        if self.depth == 0 {
            #[cfg(feature = "logging")]
            debug!(
                target: "dependency_injector",
                service = std::any::type_name::<T>(),
                "Service not found in root container"
            );
            return Err(DiError::not_found::<T>());
        }

        // Walk parent chain (cold path)
        self.resolve_from_parents::<T>(&type_id, storage_ptr)
    }

    /// Resolve from parent chain (internal)
    ///
    /// Phase 9 optimization: Walks the full parent chain via ServiceStorage.parent.
    /// This allows services to be resolved from any ancestor scope.
    ///
    /// Phase 14 optimization: Marked as cold to improve branch prediction in the
    /// hot path - most resolutions hit the cache and don't need parent traversal.
    #[cold]
    fn resolve_from_parents<T: Injectable>(
        &self,
        type_id: &TypeId,
        storage_ptr: usize,
    ) -> Result<Arc<T>> {
        let type_name = std::any::type_name::<T>();

        #[cfg(feature = "logging")]
        trace!(
            target: "dependency_injector",
            service = type_name,
            depth = self.depth,
            "Service not in local scope, walking parent chain"
        );

        // Walk the full parent chain via storage's parent references
        let mut current = self.storage.parent();
        let mut ancestor_depth = self.depth.saturating_sub(1);

        while let Some(storage) = current {
            if let Some(arc) = storage.resolve(type_id) {
                // SAFETY: We resolved by TypeId::of::<T>(), so the factory
                // was registered with the same TypeId and stores type T.
                let typed: Arc<T> = unsafe { downcast_arc_unchecked(arc) };

                #[cfg(feature = "logging")]
                trace!(
                    target: "dependency_injector",
                    service = type_name,
                    depth = self.depth,
                    ancestor_depth = ancestor_depth,
                    location = "ancestor",
                    "Service resolved from ancestor scope"
                );

                // Cache non-transient services from parent (using child's storage ptr as key)
                if !storage.is_transient(type_id) {
                    with_hot_cache_mut(|cache| cache.insert(storage_ptr, Arc::clone(&typed)));
                }

                return Ok(typed);
            }
            current = storage.parent();
            ancestor_depth = ancestor_depth.saturating_sub(1);
        }

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            service = type_name,
            depth = self.depth,
            "Service not found in container or parent chain"
        );

        Err(DiError::not_found::<T>())
    }

    /// Clear the thread-local hot cache.
    ///
    /// Call this after modifying the container (registering/removing services)
    /// if you want subsequent resolutions to see the changes immediately.
    ///
    /// Note: The cache is automatically invalidated when services are
    /// re-registered, but this method can be used for explicit control.
    #[inline]
    pub fn clear_cache(&self) {
        with_hot_cache_mut(|cache| cache.clear());
    }

    /// Pre-warm the thread-local cache with a specific service type.
    ///
    /// This can be useful at the start of request handling to ensure
    /// hot services are already in the cache.
    ///
    /// # Example
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct Database;
    ///
    /// let container = Container::new();
    /// container.singleton(Database);
    ///
    /// // Pre-warm cache for hot services
    /// container.warm_cache::<Database>();
    /// ```
    #[inline]
    pub fn warm_cache<T: Injectable>(&self) {
        // Simply resolve the service to populate the cache
        let _ = self.get::<T>();
    }

    /// Alias for `get` - resolve a service.
    #[inline]
    pub fn resolve<T: Injectable>(&self) -> Result<Arc<T>> {
        self.get::<T>()
    }

    /// Try to resolve, returning None if not found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct OptionalService;
    ///
    /// let container = Container::new();
    /// assert!(container.try_get::<OptionalService>().is_none());
    /// ```
    #[inline]
    pub fn try_get<T: Injectable>(&self) -> Option<Arc<T>> {
        self.get::<T>().ok()
    }

    /// Alias for `try_get`.
    #[inline]
    pub fn try_resolve<T: Injectable>(&self) -> Option<Arc<T>> {
        self.try_get::<T>()
    }

    // =========================================================================
    // Query Methods
    // =========================================================================

    /// Check if a service is registered.
    ///
    /// Checks both current scope and parent scopes.
    #[inline]
    pub fn contains<T: Injectable>(&self) -> bool {
        let type_id = TypeId::of::<T>();
        self.contains_type_id(&type_id)
    }

    /// Alias for `contains`.
    #[inline]
    pub fn has<T: Injectable>(&self) -> bool {
        self.contains::<T>()
    }

    /// Check by TypeId
    /// Phase 9 optimization: Uses storage's parent chain for deep hierarchy support
    fn contains_type_id(&self, type_id: &TypeId) -> bool {
        // Check local storage and full parent chain
        self.storage.contains_in_chain(type_id)
    }

    /// Get the number of services in this scope (not including parents).
    #[inline]
    pub fn len(&self) -> usize {
        self.storage.len()
    }

    /// Check if this scope is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.storage.is_empty()
    }

    /// Get all registered TypeIds in this scope.
    pub fn registered_types(&self) -> Vec<TypeId> {
        self.storage.type_ids()
    }

    /// Get the scope depth (0 = root).
    #[inline]
    pub fn depth(&self) -> u32 {
        self.depth
    }

    // =========================================================================
    // Lifecycle Methods
    // =========================================================================

    /// Lock the container to prevent further registrations.
    ///
    /// Useful for ensuring no services are registered after app initialization.
    #[inline]
    pub fn lock(&self) {
        self.locked.store(true, Ordering::Release);

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            depth = self.depth,
            service_count = self.storage.len(),
            "Container locked - no further registrations allowed"
        );
    }

    /// Check if the container is locked.
    #[inline]
    pub fn is_locked(&self) -> bool {
        self.locked.load(Ordering::Acquire)
    }

    /// Freeze the container into an immutable, perfectly-hashed storage.
    ///
    /// This creates a `FrozenStorage` that uses minimal perfect hashing for
    /// O(1) lookups without hash collisions, providing ~5ns faster resolution.
    ///
    /// Note: This also locks the container to prevent further registrations.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use dependency_injector::Container;
    ///
    /// let container = Container::new();
    /// container.singleton(MyService { ... });
    ///
    /// let frozen = container.freeze();
    /// // Use frozen.resolve(&type_id) for faster lookups
    /// ```
    #[cfg(feature = "perfect-hash")]
    #[inline]
    pub fn freeze(&self) -> crate::storage::FrozenStorage {
        self.lock();
        crate::storage::FrozenStorage::from_storage(&self.storage)
    }

    /// Clear all services from this scope.
    ///
    /// Does not affect parent scopes.
    #[inline]
    pub fn clear(&self) {
        let count = self.storage.len();
        self.storage.clear();

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            depth = self.depth,
            services_removed = count,
            "Container cleared - all services removed from this scope"
        );
    }

    /// Panic if locked (internal helper).
    /// Uses relaxed ordering for fast path - we only need eventual consistency
    /// since registration is not a hot path and locking is rare.
    #[inline]
    fn check_not_locked(&self) {
        if self.locked.load(Ordering::Relaxed) {
            panic!("Cannot register services: container is locked");
        }
    }

    // =========================================================================
    // Batch Registration (Phase 3)
    // =========================================================================

    /// Register multiple services in a single batch operation.
    ///
    /// This is more efficient than individual registrations when registering
    /// many services at once, as it:
    /// - Performs a single lock check at the start
    /// - Minimizes per-call overhead
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct Database { url: String }
    /// #[derive(Clone)]
    /// struct Cache { size: usize }
    /// #[derive(Clone)]
    /// struct Logger { level: String }
    ///
    /// let container = Container::new();
    /// container.batch(|batch| {
    ///     batch.singleton(Database { url: "postgres://localhost".into() });
    ///     batch.singleton(Cache { size: 1024 });
    ///     batch.singleton(Logger { level: "info".into() });
    /// });
    ///
    /// assert!(container.contains::<Database>());
    /// assert!(container.contains::<Cache>());
    /// assert!(container.contains::<Logger>());
    /// ```
    ///
    /// Note: For maximum performance with many services, prefer the builder API:
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct A;
    /// #[derive(Clone)]
    /// struct B;
    ///
    /// let container = Container::new();
    /// container.register_batch()
    ///     .singleton(A)
    ///     .singleton(B)
    ///     .done();
    /// ```
    #[inline]
    pub fn batch<F>(&self, f: F)
    where
        F: FnOnce(BatchRegistrar<'_>),
    {
        self.check_not_locked();

        #[cfg(feature = "logging")]
        let start_count = self.storage.len();

        // Create a zero-cost batch registrar that wraps the storage
        f(BatchRegistrar {
            storage: &self.storage,
        });

        #[cfg(feature = "logging")]
        {
            let end_count = self.storage.len();
            debug!(
                target: "dependency_injector",
                depth = self.depth,
                services_registered = end_count - start_count,
                "Batch registration completed"
            );
        }
    }

    /// Start a fluent batch registration.
    ///
    /// This is faster than the closure-based `batch()` for many services
    /// because it avoids closure overhead.
    ///
    /// # Example
    ///
    /// ```rust
    /// use dependency_injector::Container;
    ///
    /// #[derive(Clone)]
    /// struct Database { url: String }
    /// #[derive(Clone)]
    /// struct Cache { size: usize }
    ///
    /// let container = Container::new();
    /// container.register_batch()
    ///     .singleton(Database { url: "postgres://localhost".into() })
    ///     .singleton(Cache { size: 1024 })
    ///     .done();
    ///
    /// assert!(container.contains::<Database>());
    /// assert!(container.contains::<Cache>());
    /// ```
    #[inline]
    pub fn register_batch(&self) -> BatchBuilder<'_> {
        self.check_not_locked();
        BatchBuilder {
            storage: &self.storage,
            #[cfg(feature = "logging")]
            count: 0,
        }
    }
}

/// Fluent batch registration builder.
///
/// Provides a chainable API for registering multiple services without closure overhead.
pub struct BatchBuilder<'a> {
    storage: &'a ServiceStorage,
    #[cfg(feature = "logging")]
    count: usize,
}

impl<'a> BatchBuilder<'a> {
    /// Register a singleton and continue the chain
    #[inline]
    pub fn singleton<T: Injectable>(self, instance: T) -> Self {
        self.storage
            .insert(TypeId::of::<T>(), AnyFactory::singleton(instance));
        Self {
            storage: self.storage,
            #[cfg(feature = "logging")]
            count: self.count + 1,
        }
    }

    /// Register a lazy singleton and continue the chain
    #[inline]
    pub fn lazy<T: Injectable, F>(self, factory: F) -> Self
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.storage
            .insert(TypeId::of::<T>(), AnyFactory::lazy(factory));
        Self {
            storage: self.storage,
            #[cfg(feature = "logging")]
            count: self.count + 1,
        }
    }

    /// Register a transient and continue the chain
    #[inline]
    pub fn transient<T: Injectable, F>(self, factory: F) -> Self
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.storage
            .insert(TypeId::of::<T>(), AnyFactory::transient(factory));
        Self {
            storage: self.storage,
            #[cfg(feature = "logging")]
            count: self.count + 1,
        }
    }

    /// Finish the batch registration
    #[inline]
    pub fn done(self) {
        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            services_registered = self.count,
            "Batch registration completed"
        );
    }
}

/// Batch registrar for closure-based bulk registration.
///
/// A zero-cost wrapper that provides direct storage access.
/// The lock check is done once in `Container::batch()`.
#[repr(transparent)]
pub struct BatchRegistrar<'a> {
    storage: &'a ServiceStorage,
}

impl<'a> BatchRegistrar<'a> {
    /// Register a singleton service (inserted immediately)
    #[inline]
    pub fn singleton<T: Injectable>(&self, instance: T) {
        self.storage
            .insert(TypeId::of::<T>(), AnyFactory::singleton(instance));
    }

    /// Register a lazy singleton service (inserted immediately)
    #[inline]
    pub fn lazy<T: Injectable, F>(&self, factory: F)
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.storage
            .insert(TypeId::of::<T>(), AnyFactory::lazy(factory));
    }

    /// Register a transient service (inserted immediately)
    #[inline]
    pub fn transient<T: Injectable, F>(&self, factory: F)
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.storage
            .insert(TypeId::of::<T>(), AnyFactory::transient(factory));
    }
}

// =============================================================================
// Scope Pooling (Phase 6 optimization)
// =============================================================================

use std::sync::Mutex;

/// A pool of pre-allocated scopes for high-throughput scenarios.
///
/// Creating a scope involves allocating a DashMap (~134ns). For web servers
/// handling thousands of requests per second, this adds up. ScopePool pre-allocates
/// scopes and reuses them, reducing per-request overhead to near-zero.
///
/// # Example
///
/// ```rust
/// use dependency_injector::{Container, ScopePool};
///
/// #[derive(Clone)]
/// struct AppConfig { name: String }
///
/// #[derive(Clone)]
/// struct RequestId(String);
///
/// // Create root container with app-wide services
/// let root = Container::new();
/// root.singleton(AppConfig { name: "MyApp".into() });
///
/// // Create a pool of reusable scopes (pre-allocates 4 scopes)
/// let pool = ScopePool::new(&root, 4);
///
/// // In request handler: acquire a pooled scope
/// {
///     let scope = pool.acquire();
///     scope.singleton(RequestId("req-123".into()));
///
///     // Can access parent services
///     assert!(scope.contains::<AppConfig>());
///     assert!(scope.contains::<RequestId>());
///
///     // Scope automatically released when dropped
/// }
///
/// // Next request reuses the same scope allocation
/// {
///     let scope = pool.acquire();
///     // Previous RequestId is cleared, fresh scope
///     assert!(!scope.contains::<RequestId>());
/// }
/// ```
///
/// # Performance
///
/// - First acquisition: ~134ns (creates new scope if pool is empty)
/// - Subsequent acquisitions: ~20ns (reuses pooled scope)
/// - Release: ~10ns (clears and returns to pool)
pub struct ScopePool {
    /// Parent storage to create scopes from
    parent_storage: Arc<ServiceStorage>,
    /// Pool of available scopes (storage + lock state pairs)
    available: Mutex<Vec<ScopeSlot>>,
    /// Parent depth for child scope depth calculation
    parent_depth: u32,
}

/// A reusable scope slot containing pre-allocated storage and lock state
struct ScopeSlot {
    /// Pre-allocated storage with parent reference
    storage: Arc<ServiceStorage>,
    locked: Arc<AtomicBool>,
}

impl ScopePool {
    /// Create a new scope pool with pre-allocated capacity.
    ///
    /// # Arguments
    ///
    /// * `parent` - The parent container that scopes will inherit from
    /// * `capacity` - Number of scopes to pre-allocate
    ///
    /// # Example
    ///
    /// ```rust
    /// use dependency_injector::{Container, ScopePool};
    ///
    /// let root = Container::new();
    /// // Pre-allocate 8 scopes for concurrent request handling
    /// let pool = ScopePool::new(&root, 8);
    /// ```
    pub fn new(parent: &Container, capacity: usize) -> Self {
        let mut available = Vec::with_capacity(capacity);

        // Pre-allocate storage with parent reference and lock states
        for _ in 0..capacity {
            available.push(ScopeSlot {
                storage: Arc::new(ServiceStorage::with_parent(Arc::clone(&parent.storage))),
                locked: Arc::new(AtomicBool::new(false)),
            });
        }

        #[cfg(feature = "logging")]
        debug!(
            target: "dependency_injector",
            capacity = capacity,
            parent_depth = parent.depth,
            "Created scope pool with pre-allocated scopes"
        );

        Self {
            parent_storage: Arc::clone(&parent.storage),
            available: Mutex::new(available),
            parent_depth: parent.depth,
        }
    }

    /// Acquire a scope from the pool.
    ///
    /// Returns a `PooledScope` that automatically returns to the pool when dropped.
    /// If the pool is empty, creates a new scope.
    ///
    /// # Example
    ///
    /// ```rust
    /// use dependency_injector::{Container, ScopePool};
    ///
    /// #[derive(Clone)]
    /// struct RequestData { id: u64 }
    ///
    /// let root = Container::new();
    /// let pool = ScopePool::new(&root, 4);
    ///
    /// let scope = pool.acquire();
    /// scope.singleton(RequestData { id: 123 });
    /// let data = scope.get::<RequestData>().unwrap();
    /// assert_eq!(data.id, 123);
    /// ```
    #[inline]
    pub fn acquire(&self) -> PooledScope<'_> {
        let slot = self.available.lock().unwrap().pop();

        let (storage, locked) = match slot {
            Some(slot) => {
                #[cfg(feature = "logging")]
                trace!(
                    target: "dependency_injector",
                    "Acquired scope from pool (reusing storage)"
                );
                (slot.storage, slot.locked)
            }
            None => {
                #[cfg(feature = "logging")]
                trace!(
                    target: "dependency_injector",
                    "Pool empty, creating new scope"
                );
                (
                    Arc::new(ServiceStorage::with_parent(Arc::clone(
                        &self.parent_storage,
                    ))),
                    Arc::new(AtomicBool::new(false)),
                )
            }
        };

        let container = Container {
            storage,
            parent_storage: Some(Arc::clone(&self.parent_storage)),
            locked,
            depth: self.parent_depth + 1,
        };

        PooledScope {
            container: Some(container),
            pool: self,
        }
    }

    /// Return a scope to the pool (internal use).
    #[inline]
    fn release(&self, container: Container) {
        // Clear storage for reuse (parent reference is preserved)
        container.storage.clear();
        // Reset lock state
        container.locked.store(false, Ordering::Relaxed);

        // Return to pool
        self.available.lock().unwrap().push(ScopeSlot {
            storage: container.storage,
            locked: container.locked,
        });

        #[cfg(feature = "logging")]
        trace!(
            target: "dependency_injector",
            "Released scope back to pool"
        );
    }

    /// Get the current number of available scopes in the pool.
    #[inline]
    pub fn available_count(&self) -> usize {
        self.available.lock().unwrap().len()
    }
}

/// A scope acquired from a pool that automatically returns when dropped.
///
/// This provides RAII-style management of pooled scopes, ensuring they're
/// always returned to the pool even if the code panics.
pub struct PooledScope<'a> {
    container: Option<Container>,
    pool: &'a ScopePool,
}

impl PooledScope<'_> {
    /// Get a reference to the underlying container.
    #[inline]
    pub fn container(&self) -> &Container {
        self.container.as_ref().unwrap()
    }
}

impl std::ops::Deref for PooledScope<'_> {
    type Target = Container;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.container.as_ref().unwrap()
    }
}

impl Drop for PooledScope<'_> {
    fn drop(&mut self) {
        if let Some(container) = self.container.take() {
            self.pool.release(container);
        }
    }
}

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

impl std::fmt::Debug for Container {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Container")
            .field("service_count", &self.len())
            .field("depth", &self.depth)
            .field("has_parent", &self.parent_storage.is_some())
            .field("locked", &self.is_locked())
            .finish_non_exhaustive()
    }
}

// =========================================================================
// Thread Safety
// =========================================================================

// Container is Send + Sync because:
// - ServiceStorage uses DashMap (thread-safe)
// - parent is Weak<...> which is Send + Sync
// - locked uses AtomicBool (Send + Sync)
unsafe impl Send for Container {}
unsafe impl Sync for Container {}

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

    #[derive(Clone)]
    struct TestService {
        value: String,
    }

    #[allow(dead_code)]
    #[derive(Clone)]
    struct AnotherService {
        name: String,
    }

    #[test]
    fn test_singleton() {
        let container = Container::new();
        container.singleton(TestService {
            value: "test".into(),
        });

        let s1 = container.get::<TestService>().unwrap();
        let s2 = container.get::<TestService>().unwrap();

        assert_eq!(s1.value, "test");
        assert!(Arc::ptr_eq(&s1, &s2));
    }

    #[test]
    fn test_lazy() {
        use std::sync::atomic::{AtomicBool, Ordering};

        static CREATED: AtomicBool = AtomicBool::new(false);

        let container = Container::new();
        container.lazy(|| {
            CREATED.store(true, Ordering::SeqCst);
            TestService {
                value: "lazy".into(),
            }
        });

        assert!(!CREATED.load(Ordering::SeqCst));

        let s = container.get::<TestService>().unwrap();
        assert!(CREATED.load(Ordering::SeqCst));
        assert_eq!(s.value, "lazy");
    }

    #[test]
    fn test_transient() {
        use std::sync::atomic::{AtomicU32, Ordering};

        static COUNTER: AtomicU32 = AtomicU32::new(0);

        #[derive(Clone)]
        struct Counter(u32);

        let container = Container::new();
        container.transient(|| Counter(COUNTER.fetch_add(1, Ordering::SeqCst)));

        let c1 = container.get::<Counter>().unwrap();
        let c2 = container.get::<Counter>().unwrap();

        assert_ne!(c1.0, c2.0);
    }

    #[test]
    fn test_scope_inheritance() {
        let root = Container::new();
        root.singleton(TestService {
            value: "root".into(),
        });

        let child = root.scope();
        child.singleton(AnotherService {
            name: "child".into(),
        });

        // Child sees both
        assert!(child.contains::<TestService>());
        assert!(child.contains::<AnotherService>());

        // Root only sees its own
        assert!(root.contains::<TestService>());
        assert!(!root.contains::<AnotherService>());
    }

    #[test]
    fn test_scope_override() {
        let root = Container::new();
        root.singleton(TestService {
            value: "root".into(),
        });

        let child = root.scope();
        child.singleton(TestService {
            value: "child".into(),
        });

        let root_service = root.get::<TestService>().unwrap();
        let child_service = child.get::<TestService>().unwrap();

        assert_eq!(root_service.value, "root");
        assert_eq!(child_service.value, "child");
    }

    #[test]
    fn test_not_found() {
        let container = Container::new();
        let result = container.get::<TestService>();
        assert!(result.is_err());
    }

    #[test]
    fn test_lock() {
        let container = Container::new();
        assert!(!container.is_locked());

        container.lock();
        assert!(container.is_locked());
    }

    #[test]
    #[should_panic(expected = "Cannot register services: container is locked")]
    fn test_register_after_lock() {
        let container = Container::new();
        container.lock();
        container.singleton(TestService {
            value: "fail".into(),
        });
    }

    #[test]
    fn test_batch_registration() {
        #[derive(Clone)]
        struct ServiceA(i32);
        #[allow(dead_code)]
        #[derive(Clone)]
        struct ServiceB(String);

        let container = Container::new();
        container.batch(|batch| {
            batch.singleton(ServiceA(42));
            batch.singleton(ServiceB("test".into()));
            batch.lazy(|| TestService {
                value: "lazy".into(),
            });
        });

        assert!(container.contains::<ServiceA>());
        assert!(container.contains::<ServiceB>());
        assert!(container.contains::<TestService>());

        let a = container.get::<ServiceA>().unwrap();
        assert_eq!(a.0, 42);
    }

    #[test]
    fn test_scope_pool_basic() {
        #[derive(Clone)]
        struct RequestId(u64);

        let root = Container::new();
        root.singleton(TestService {
            value: "root".into(),
        });

        // Create pool with 2 pre-allocated scopes
        let pool = ScopePool::new(&root, 2);
        assert_eq!(pool.available_count(), 2);

        // Acquire a scope
        {
            let scope = pool.acquire();
            assert_eq!(pool.available_count(), 1);

            // Can access parent services
            assert!(scope.contains::<TestService>());

            // Register request-specific service
            scope.singleton(RequestId(123));
            assert!(scope.contains::<RequestId>());

            let id = scope.get::<RequestId>().unwrap();
            assert_eq!(id.0, 123);
        }
        // Scope released back to pool
        assert_eq!(pool.available_count(), 2);
    }

    #[test]
    fn test_scope_pool_reuse() {
        #[derive(Clone)]
        struct RequestId(u64);

        let root = Container::new();
        let pool = ScopePool::new(&root, 1);

        // First request
        {
            let scope = pool.acquire();
            scope.singleton(RequestId(1));
            assert!(scope.contains::<RequestId>());
        }

        // Second request - should reuse the same scope (cleared)
        {
            let scope = pool.acquire();
            // Previous RequestId should be cleared
            assert!(!scope.contains::<RequestId>());

            scope.singleton(RequestId(2));
            let id = scope.get::<RequestId>().unwrap();
            assert_eq!(id.0, 2);
        }
    }

    #[test]
    fn test_scope_pool_expansion() {
        let root = Container::new();
        let pool = ScopePool::new(&root, 1);

        // Acquire more scopes than pre-allocated
        let _s1 = pool.acquire();
        let _s2 = pool.acquire(); // Creates new scope

        assert_eq!(pool.available_count(), 0);

        // Both should work
        drop(_s1);
        drop(_s2);

        // Both return to pool
        assert_eq!(pool.available_count(), 2);
    }

    #[test]
    fn test_deep_parent_chain() {
        // Test that services can be resolved from grandparent and beyond
        #[derive(Clone)]
        struct RootService(i32);
        #[derive(Clone)]
        struct MiddleService(i32);
        #[derive(Clone)]
        struct LeafService(i32);

        // Create 4-level hierarchy: root -> middle1 -> middle2 -> leaf
        let root = Container::new();
        root.singleton(RootService(1));

        let middle1 = root.scope();
        middle1.singleton(MiddleService(2));

        let middle2 = middle1.scope();
        // No service in middle2

        let leaf = middle2.scope();
        leaf.singleton(LeafService(4));

        // Leaf should be able to access all ancestor services
        assert!(
            leaf.contains::<RootService>(),
            "Should find root service in leaf"
        );
        assert!(
            leaf.contains::<MiddleService>(),
            "Should find middle service in leaf"
        );
        assert!(
            leaf.contains::<LeafService>(),
            "Should find leaf service in leaf"
        );

        // Verify resolution works
        let root_svc = leaf.get::<RootService>().unwrap();
        assert_eq!(root_svc.0, 1);

        let middle_svc = leaf.get::<MiddleService>().unwrap();
        assert_eq!(middle_svc.0, 2);

        let leaf_svc = leaf.get::<LeafService>().unwrap();
        assert_eq!(leaf_svc.0, 4);

        // Middle2 should also access ancestor services
        assert!(middle2.contains::<RootService>());
        assert!(middle2.contains::<MiddleService>());
        assert!(!middle2.contains::<LeafService>()); // Leaf service not in parent
    }
}