hitbox-backend 0.2.1

Backend trait for asynchronous caching framework in 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
//! Tests for nested CompositionBackend (composition of compositions).
//!
//! This tests that CompositionBackend can be composed with other CompositionBackends,
//! creating multi-level cache hierarchies.

use chrono::Utc;
use std::sync::Arc;

use hitbox_backend::{CacheBackend, CompositionBackend, SyncBackend};
use hitbox_core::{
    BoxContext, CacheContext, CacheKey, CacheValue, CacheableResponse, EntityPolicyConfig,
    Predicate,
};
use serde::{Deserialize, Serialize};

#[cfg(feature = "rkyv_format")]
use rkyv::{Archive, Serialize as RkyvSerialize};

use crate::common::{TestBackend, TestOffloadManager};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "rkyv_format",
    derive(Archive, RkyvSerialize, rkyv::Deserialize)
)]
pub(super) struct TestValue {
    pub data: String,
}

impl CacheableResponse for TestValue {
    type Cached = Self;
    type Subject = Self;
    type IntoCachedFuture = std::future::Ready<hitbox_core::CachePolicy<Self::Cached, Self>>;
    type FromCachedFuture = std::future::Ready<Self>;

    async fn cache_policy<P: Predicate<Subject = Self::Subject> + Send + Sync>(
        self,
        _predicate: P,
        _config: &EntityPolicyConfig,
    ) -> hitbox_core::ResponseCachePolicy<Self> {
        unimplemented!()
    }

    fn into_cached(self) -> Self::IntoCachedFuture {
        unimplemented!()
    }

    fn from_cached(_cached: Self::Cached) -> Self::FromCachedFuture {
        unimplemented!()
    }
}

// =============================================================================
// Static Dispatch Tests (Concrete Types)
// =============================================================================

#[tokio::test]
async fn test_nested_composition_static_dispatch() {
    // Create a 3-level cache hierarchy:
    // Level 1 (fastest): L1
    // Level 2 (medium):  L2
    // Level 3 (slowest): L3
    //
    // Structure: CompositionBackend(L1, CompositionBackend(L2, L3))

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    // Create inner composition: L2 + L3
    let l2_l3 = CompositionBackend::new(l2.clone(), l3.clone(), TestOffloadManager);

    // Create outer composition: L1 + (L2 + L3)
    let cache = CompositionBackend::new(l1.clone(), l2_l3, TestOffloadManager);

    let key = CacheKey::from_str("test", "key1");
    let value = CacheValue::new(
        TestValue {
            data: "test_value".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Write through nested composition - should populate all 3 levels
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Verify all 3 levels have the data
    assert!(l1.has(&key), "L1 should have the value");
    assert!(l2.has(&key), "L2 should have the value");
    assert!(l3.has(&key), "L3 should have the value");

    // Read should return the value (from L1)
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some());
    assert_eq!(
        *result.unwrap().data(),
        TestValue {
            data: "test_value".to_string()
        }
    );
}

// =============================================================================
// Deep Nested Refill Tests - Shared Test Logic
// =============================================================================

/// Shared test logic for 3-level refill with Always policy
async fn run_refill_3_levels_test<B: CacheBackend + Send + Sync>(
    cache: B,
    l1: &TestBackend,
    l2: &TestBackend,
    l3: &TestBackend,
    key_suffix: &str,
) {
    let key = CacheKey::from_str("test", &format!("deep_refill_{}", key_suffix));
    let value = CacheValue::new(
        TestValue {
            data: "from_l3".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Step 1: Write through composition (populates all 3 levels in correct format)
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Verify all levels have data after write
    assert!(l1.has(&key), "L1 should have data after write");
    assert!(l2.has(&key), "L2 should have data after write");
    assert!(l3.has(&key), "L3 should have data after write");

    // Step 2: Clear L1 and L2 to simulate miss scenario
    l1.clear();
    l2.clear();
    assert!(!l1.has(&key), "L1 should be empty after clear");
    assert!(!l2.has(&key), "L2 should be empty after clear");

    // Step 3: Read through composition (should hit L3)
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    let cached_value = result.expect("Should get value from L3");
    assert_eq!(cached_value.data().data, "from_l3");

    // Step 4: Simulate CacheFuture calling set() with the wrapped context
    cache
        .set::<TestValue>(&key, &cached_value, &mut ctx)
        .await
        .unwrap();

    // Step 5: Verify L1 and L2 are refilled
    assert!(l1.has(&key), "L1 should be refilled after set()");
    assert!(l2.has(&key), "L2 should be refilled after set()");
    assert!(l3.has(&key), "L3 should still have data");

    // Step 6: Verify data can be read from L1 now (proving refill worked)
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some());
    assert_eq!(result.unwrap().data().data, "from_l3");
}

/// Shared test logic for 4-level refill with Always policy
async fn run_refill_4_levels_test<B: CacheBackend + Send + Sync>(
    cache: B,
    l1: &TestBackend,
    l2: &TestBackend,
    l3: &TestBackend,
    l4: &TestBackend,
    key_suffix: &str,
) {
    let key = CacheKey::from_str("test", &format!("very_deep_refill_{}", key_suffix));
    let value = CacheValue::new(
        TestValue {
            data: "from_l4".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Write through composition
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Clear L1, L2, L3 to simulate miss scenario (only L4 has data)
    l1.clear();
    l2.clear();
    l3.clear();

    // Read through composition (should hit L4)
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    let cached_value = result.expect("Should get value from L4");
    assert_eq!(cached_value.data().data, "from_l4");

    // Simulate CacheFuture calling set() to trigger refill cascade
    cache
        .set::<TestValue>(&key, &cached_value, &mut ctx)
        .await
        .unwrap();

    // Verify all levels are refilled
    assert!(l1.has(&key), "L1 should be refilled");
    assert!(l2.has(&key), "L2 should be refilled");
    assert!(l3.has(&key), "L3 should be refilled");
    assert!(l4.has(&key), "L4 should still have data");
}

/// Shared test logic for Never policy preventing refill
async fn run_no_refill_never_policy_test<B: CacheBackend + Send + Sync>(
    cache: B,
    l1: &TestBackend,
    l2: &TestBackend,
    _l3: &TestBackend,
    key_suffix: &str,
) {
    use hitbox_core::ReadMode;

    let key = CacheKey::from_str("test", &format!("no_refill_{}", key_suffix));
    let value = CacheValue::new(
        TestValue {
            data: "from_l3".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Write through composition
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Clear L1 and L2
    l1.clear();
    l2.clear();

    // Read through composition (should hit L3)
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some(), "Should get value from L3");

    // With Never policy, read_mode should NOT be Refill
    assert_eq!(
        ctx.read_mode(),
        ReadMode::Direct,
        "With Never policy, read_mode should be Direct (not Refill)"
    );

    // L1 and L2 should NOT be refilled
    assert!(!l1.has(&key), "L1 should NOT be refilled with Never policy");
    assert!(!l2.has(&key), "L2 should NOT be refilled with Never policy");
}

/// Shared test logic for Never policy skipping refill even with Refill mode
async fn run_never_policy_skips_refill_test<B: CacheBackend + Send + Sync>(
    cache: B,
    l1: &TestBackend,
    l2: &TestBackend,
    _l3: &TestBackend,
    key_suffix: &str,
) {
    use hitbox_core::ReadMode;

    let key = CacheKey::from_str("test", &format!("no_refill_forced_{}", key_suffix));
    let value = CacheValue::new(
        TestValue {
            data: "from_l3".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Write through composition
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Clear L1 and L2
    l1.clear();
    l2.clear();

    // Read through composition (should hit L3)
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    let cached_value = result.expect("Should get value from L3");

    // Manually set Refill mode to simulate edge case
    ctx.set_read_mode(ReadMode::Refill);

    // Call set() with Refill mode - should still NOT refill due to Never policy
    cache
        .set::<TestValue>(&key, &cached_value, &mut ctx)
        .await
        .unwrap();

    // L1 and L2 should NOT be refilled (Never policy overrides Refill mode)
    assert!(
        !l1.has(&key),
        "L1 should NOT be refilled - Never policy should prevent it"
    );
    assert!(
        !l2.has(&key),
        "L2 should NOT be refilled - Never policy should prevent it"
    );
}

// =============================================================================
// Deep Nested Refill Tests - Concrete Types (Static Dispatch)
// =============================================================================

#[tokio::test]
async fn test_deep_nested_refill_3_levels() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let inner = CompositionBackend::new(l2.clone(), l3.clone(), TestOffloadManager)
        .refill(RefillPolicy::Always);
    let outer =
        CompositionBackend::new(l1.clone(), inner, TestOffloadManager).refill(RefillPolicy::Always);

    run_refill_3_levels_test(outer, &l1, &l2, &l3, "static").await;
}

#[tokio::test]
async fn test_deep_nested_refill_4_levels() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();
    let l4 = TestBackend::new();

    let innermost = CompositionBackend::new(l3.clone(), l4.clone(), TestOffloadManager)
        .refill(RefillPolicy::Always);
    let middle = CompositionBackend::new(l2.clone(), innermost, TestOffloadManager)
        .refill(RefillPolicy::Always);
    let outer = CompositionBackend::new(l1.clone(), middle, TestOffloadManager)
        .refill(RefillPolicy::Always);

    run_refill_4_levels_test(outer, &l1, &l2, &l3, &l4, "static").await;
}

#[tokio::test]
async fn test_deep_nested_no_refill_with_never_policy() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let inner = CompositionBackend::new(l2.clone(), l3.clone(), TestOffloadManager)
        .refill(RefillPolicy::Never);
    let outer =
        CompositionBackend::new(l1.clone(), inner, TestOffloadManager).refill(RefillPolicy::Never);

    run_no_refill_never_policy_test(outer, &l1, &l2, &l3, "static").await;
}

#[tokio::test]
async fn test_never_policy_skips_refill_even_with_refill_mode() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let inner = CompositionBackend::new(l2.clone(), l3.clone(), TestOffloadManager)
        .refill(RefillPolicy::Never);
    let outer =
        CompositionBackend::new(l1.clone(), inner, TestOffloadManager).refill(RefillPolicy::Never);

    run_never_policy_skips_refill_test(outer, &l1, &l2, &l3, "static").await;
}

// =============================================================================
// Deep Nested Refill Tests - Arc<SyncBackend> (Dynamic Dispatch)
// =============================================================================

#[tokio::test]
async fn test_deep_nested_refill_3_levels_arc_sync() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let l1_arc: Arc<SyncBackend> = Arc::new(l1.clone());
    let l2_arc: Arc<SyncBackend> = Arc::new(l2.clone());
    let l3_arc: Arc<SyncBackend> = Arc::new(l3.clone());

    let inner =
        CompositionBackend::new(l2_arc, l3_arc, TestOffloadManager).refill(RefillPolicy::Always);
    let outer =
        CompositionBackend::new(l1_arc, inner, TestOffloadManager).refill(RefillPolicy::Always);

    run_refill_3_levels_test(outer, &l1, &l2, &l3, "arc_sync").await;
}

#[tokio::test]
async fn test_deep_nested_refill_4_levels_arc_sync() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();
    let l4 = TestBackend::new();

    let l1_arc: Arc<SyncBackend> = Arc::new(l1.clone());
    let l2_arc: Arc<SyncBackend> = Arc::new(l2.clone());
    let l3_arc: Arc<SyncBackend> = Arc::new(l3.clone());
    let l4_arc: Arc<SyncBackend> = Arc::new(l4.clone());

    let innermost =
        CompositionBackend::new(l3_arc, l4_arc, TestOffloadManager).refill(RefillPolicy::Always);
    let middle =
        CompositionBackend::new(l2_arc, innermost, TestOffloadManager).refill(RefillPolicy::Always);
    let outer =
        CompositionBackend::new(l1_arc, middle, TestOffloadManager).refill(RefillPolicy::Always);

    run_refill_4_levels_test(outer, &l1, &l2, &l3, &l4, "arc_sync").await;
}

#[tokio::test]
async fn test_deep_nested_no_refill_with_never_policy_arc_sync() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let l1_arc: Arc<SyncBackend> = Arc::new(l1.clone());
    let l2_arc: Arc<SyncBackend> = Arc::new(l2.clone());
    let l3_arc: Arc<SyncBackend> = Arc::new(l3.clone());

    let inner =
        CompositionBackend::new(l2_arc, l3_arc, TestOffloadManager).refill(RefillPolicy::Never);
    let outer =
        CompositionBackend::new(l1_arc, inner, TestOffloadManager).refill(RefillPolicy::Never);

    run_no_refill_never_policy_test(outer, &l1, &l2, &l3, "arc_sync").await;
}

#[tokio::test]
async fn test_never_policy_skips_refill_even_with_refill_mode_arc_sync() {
    use hitbox_backend::composition::policy::RefillPolicy;

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let l1_arc: Arc<SyncBackend> = Arc::new(l1.clone());
    let l2_arc: Arc<SyncBackend> = Arc::new(l2.clone());
    let l3_arc: Arc<SyncBackend> = Arc::new(l3.clone());

    let inner =
        CompositionBackend::new(l2_arc, l3_arc, TestOffloadManager).refill(RefillPolicy::Never);
    let outer =
        CompositionBackend::new(l1_arc, inner, TestOffloadManager).refill(RefillPolicy::Never);

    run_never_policy_skips_refill_test(outer, &l1, &l2, &l3, "arc_sync").await;
}

// =============================================================================
// Dynamic Dispatch Tests (Trait Objects)
// =============================================================================

#[tokio::test]
async fn test_nested_composition_dynamic_dispatch() {
    // Test nested composition with Arc<SyncBackend>

    let l1: Arc<SyncBackend> = Arc::new(TestBackend::new());
    let l2: Arc<SyncBackend> = Arc::new(TestBackend::new());
    let l3: Arc<SyncBackend> = Arc::new(TestBackend::new());

    // Create inner composition as trait object
    let l2_l3: Arc<SyncBackend> = Arc::new(CompositionBackend::new(l2, l3, TestOffloadManager));

    // Create outer composition with trait object
    let cache = CompositionBackend::new(l1, l2_l3, TestOffloadManager);

    let key = CacheKey::from_str("test", "dyn_key");
    let value = CacheValue::new(
        TestValue {
            data: "dynamic_value".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Write and read through dynamic dispatch
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some());
    assert_eq!(
        *result.unwrap().data(),
        TestValue {
            data: "dynamic_value".to_string()
        }
    );
}

#[tokio::test]
async fn test_nested_composition_dynamic_as_trait_object() {
    // Test that the nested composition itself can be used as a trait object

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let key = CacheKey::from_str("test", "nested_trait");
    let value = CacheValue::new(
        TestValue {
            data: "trait_object_value".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Create nested composition
    let l2_l3 = CompositionBackend::new(l2, l3, TestOffloadManager);
    let nested = CompositionBackend::new(l1, l2_l3, TestOffloadManager);

    // Use the entire nested composition as a trait object
    let backend: Arc<SyncBackend> = Arc::new(nested);

    // Operations through trait object
    let mut ctx: BoxContext = CacheContext::default().boxed();
    backend
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = backend.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some());
    assert_eq!(
        *result.unwrap().data(),
        TestValue {
            data: "trait_object_value".to_string()
        }
    );
}

// =============================================================================
// TTL/Stale Metadata Tests - Shared Test Logic
// =============================================================================

/// Helper struct to hold backends for TTL/stale testing with inspection capability.
struct TtlTestBackends {
    l1: TestBackend,
    l2: TestBackend,
}

impl TtlTestBackends {
    fn two_level() -> Self {
        Self {
            l1: TestBackend::new(),
            l2: TestBackend::new(),
        }
    }
}

/// Test TTL preservation through write/read cycle.
async fn run_ttl_preserved_test<B: CacheBackend + Send + Sync>(
    cache: B,
    l1: &TestBackend,
    l2: &TestBackend,
) {
    let key = CacheKey::from_str("test", "ttl_key");
    let expire_time = Utc::now() + chrono::Duration::seconds(300);
    let value = CacheValue::new(
        TestValue {
            data: "ttl_test".to_string(),
        },
        Some(expire_time),
        None,
    );

    // Write through composition
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Verify TTL is preserved in L1
    let l1_raw = l1.get_raw(&key).expect("L1 should have the value");
    assert!(l1_raw.expire().is_some(), "L1 should have expire time");
    assert_eq!(
        l1_raw.expire(),
        Some(expire_time),
        "L1 expire time should match"
    );

    // Verify TTL is preserved in L2
    let l2_raw = l2.get_raw(&key).expect("L2 should have the value");
    assert!(l2_raw.expire().is_some(), "L2 should have expire time");
    assert_eq!(
        l2_raw.expire(),
        Some(expire_time),
        "L2 expire time should match"
    );

    // Read back and verify TTL is preserved
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some());
    let cache_value = result.unwrap();
    assert_eq!(
        cache_value.expire(),
        Some(expire_time),
        "Read expire time should match"
    );
}

/// Test stale preservation through write/read cycle.
async fn run_stale_preserved_test<B: CacheBackend + Send + Sync>(
    cache: B,
    l1: &TestBackend,
    l2: &TestBackend,
) {
    let key = CacheKey::from_str("test", "stale_key");
    let expire_time = Utc::now() + chrono::Duration::seconds(300);
    let stale_time = Utc::now() + chrono::Duration::seconds(60);
    let value = CacheValue::new(
        TestValue {
            data: "stale_test".to_string(),
        },
        Some(expire_time),
        Some(stale_time),
    );

    // Write through composition
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Verify stale is preserved in L1
    let l1_raw = l1.get_raw(&key).expect("L1 should have the value");
    assert!(l1_raw.stale().is_some(), "L1 should have stale time");
    assert_eq!(
        l1_raw.stale(),
        Some(stale_time),
        "L1 stale time should match"
    );

    // Verify stale is preserved in L2
    let l2_raw = l2.get_raw(&key).expect("L2 should have the value");
    assert!(l2_raw.stale().is_some(), "L2 should have stale time");
    assert_eq!(
        l2_raw.stale(),
        Some(stale_time),
        "L2 stale time should match"
    );

    // Read back and verify stale is preserved
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some());
    let cache_value = result.unwrap();
    assert_eq!(
        cache_value.stale(),
        Some(stale_time),
        "Read stale time should match"
    );
    assert_eq!(
        cache_value.expire(),
        Some(expire_time),
        "Read expire time should match"
    );
}

/// Test no TTL/stale preservation.
async fn run_no_ttl_no_stale_test<B: CacheBackend + Send + Sync>(cache: B, l1: &TestBackend) {
    let key = CacheKey::from_str("test", "no_ttl_key");
    let value = CacheValue::new(
        TestValue {
            data: "no_ttl_test".to_string(),
        },
        None,
        None,
    );

    // Write through composition
    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache
        .set::<TestValue>(&key, &value, &mut ctx)
        .await
        .unwrap();

    // Verify no TTL/stale in L1
    let l1_raw = l1.get_raw(&key).expect("L1 should have the value");
    assert!(l1_raw.expire().is_none(), "L1 should have no expire time");
    assert!(l1_raw.stale().is_none(), "L1 should have no stale time");

    // Read back and verify
    let mut ctx: BoxContext = CacheContext::default().boxed();
    let result = cache.get::<TestValue>(&key, &mut ctx).await.unwrap();
    assert!(result.is_some());
    let cache_value = result.unwrap();
    assert!(
        cache_value.expire().is_none(),
        "Read should have no expire time"
    );
    assert!(
        cache_value.stale().is_none(),
        "Read should have no stale time"
    );
}

// =============================================================================
// TTL/Stale Tests - Concrete Types (TestBackend)
// =============================================================================

#[tokio::test]
async fn test_ttl_preserved_concrete() {
    let backends = TtlTestBackends::two_level();
    let cache =
        CompositionBackend::new(backends.l1.clone(), backends.l2.clone(), TestOffloadManager);
    run_ttl_preserved_test(cache, &backends.l1, &backends.l2).await;
}

#[tokio::test]
async fn test_stale_preserved_concrete() {
    let backends = TtlTestBackends::two_level();
    let cache =
        CompositionBackend::new(backends.l1.clone(), backends.l2.clone(), TestOffloadManager);
    run_stale_preserved_test(cache, &backends.l1, &backends.l2).await;
}

#[tokio::test]
async fn test_no_ttl_no_stale_concrete() {
    let backends = TtlTestBackends::two_level();
    let cache =
        CompositionBackend::new(backends.l1.clone(), backends.l2.clone(), TestOffloadManager);
    run_no_ttl_no_stale_test(cache, &backends.l1).await;
}

// =============================================================================
// TTL/Stale Tests - Arc<SyncBackend> (Dynamic Dispatch)
// =============================================================================

#[tokio::test]
async fn test_ttl_preserved_arc_sync() {
    let backends = TtlTestBackends::two_level();
    let l1: Arc<SyncBackend> = Arc::new(backends.l1.clone());
    let l2: Arc<SyncBackend> = Arc::new(backends.l2.clone());
    let cache = CompositionBackend::new(l1, l2, TestOffloadManager);
    run_ttl_preserved_test(cache, &backends.l1, &backends.l2).await;
}

#[tokio::test]
async fn test_stale_preserved_arc_sync() {
    let backends = TtlTestBackends::two_level();
    let l1: Arc<SyncBackend> = Arc::new(backends.l1.clone());
    let l2: Arc<SyncBackend> = Arc::new(backends.l2.clone());
    let cache = CompositionBackend::new(l1, l2, TestOffloadManager);
    run_stale_preserved_test(cache, &backends.l1, &backends.l2).await;
}

#[tokio::test]
async fn test_no_ttl_no_stale_arc_sync() {
    let backends = TtlTestBackends::two_level();
    let l1: Arc<SyncBackend> = Arc::new(backends.l1.clone());
    let l2: Arc<SyncBackend> = Arc::new(backends.l2.clone());
    let cache = CompositionBackend::new(l1, l2, TestOffloadManager);
    run_no_ttl_no_stale_test(cache, &backends.l1).await;
}

#[tokio::test]
async fn test_nested_composition_delete_cascades() {
    // Test that delete operations cascade through nested compositions

    let l1 = TestBackend::new();
    let l2 = TestBackend::new();
    let l3 = TestBackend::new();

    let key = CacheKey::from_str("test", "delete_key");
    let value = CacheValue::new(
        TestValue {
            data: "to_delete".to_string(),
        },
        Some(Utc::now() + chrono::Duration::seconds(60)),
        None,
    );

    // Populate all levels
    let mut ctx: BoxContext = CacheContext::default().boxed();
    l1.set::<TestValue>(&key, &value, &mut ctx).await.unwrap();
    let mut ctx: BoxContext = CacheContext::default().boxed();
    l2.set::<TestValue>(&key, &value, &mut ctx).await.unwrap();
    let mut ctx: BoxContext = CacheContext::default().boxed();
    l3.set::<TestValue>(&key, &value, &mut ctx).await.unwrap();

    // Verify all have the data
    assert!(l1.has(&key));
    assert!(l2.has(&key));
    assert!(l3.has(&key));

    // Create nested composition and delete
    let l2_l3 = CompositionBackend::new(l2.clone(), l3.clone(), TestOffloadManager);
    let cache = CompositionBackend::new(l1.clone(), l2_l3, TestOffloadManager);

    let mut ctx: BoxContext = CacheContext::default().boxed();
    cache.delete(&key, &mut ctx).await.unwrap();

    // Verify all levels no longer have the data
    assert!(!l1.has(&key), "L1 should be deleted");
    assert!(!l2.has(&key), "L2 should be deleted");
    assert!(!l3.has(&key), "L3 should be deleted");
}