camel-core 0.30.0

Core engine for rust-camel
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
//! Redb-backed persistent cache repository.
//!
//! Mirrors `idempotent/redb_repository.rs`: all redb I/O is offloaded to
//! `tokio::task::spawn_blocking` because `redb::Database` is blocking. Values
//! are `serde_json`-serialized [`CacheEntry`] blobs.
//!
//! # Sweep
//!
//! A background task wakes every `sweep_interval` and reclaims entries whose
//! `expires_at + stale_retention < now`. It is bound to the context's
//! [`CancellationToken`]: when the context shuts down, the sweep exits. The
//! token is context-owned — dropping this repository aborts only the sweep
//! task handle, never the token (cancelling it would tear down the whole
//! context).

use std::fmt;
use std::ops::Bound;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::SystemTime;

use async_trait::async_trait;
use camel_api::CamelError;
use camel_api::cache::CacheEntry;
use camel_api::cache::CacheRepository;
use camel_api::cache::CacheStats;
use parking_lot::Mutex;
use redb::ReadableDatabase;
use redb::ReadableTable;
use redb::ReadableTableMetadata;
use redb::TableDefinition;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

// ── Table definition ──────────────────────────────────────────────────────────

/// `key → serde_json(CacheEntry)`. Mirrors the table-definition style of
/// `idempotent/redb_repository.rs`.
const CACHE_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("cache_entries");

// ── Repository ────────────────────────────────────────────────────────────────

/// Redb-backed implementation of [`CacheRepository`].
///
/// All counters are `Arc<AtomicU64>` so the spawned sweep task can update
/// them via cloned references. `cache_size`, `sweep_interval`, and
/// `stale_retention` are retained so the propagation seam required by the
/// eip-cache spec can expose them via accessors.
pub struct RedbCacheRepository {
    name: String,
    db: Arc<redb::Database>,
    stale_retention: Duration,
    max_entries: Option<usize>,
    /// redb page-cache size in bytes, passed to `redb::Builder::set_cache_size`.
    cache_size: usize,
    /// Recorded background-sweep interval, consumed by the spawned sweep task.
    sweep_interval: Duration,
    hits: Arc<AtomicU64>,
    misses: Arc<AtomicU64>,
    evictions: Arc<AtomicU64>,
    peek_stale_served: Arc<AtomicU64>,
    invalidations: Arc<AtomicU64>,
    /// Best-effort approximation of `table.len()` for stats display.
    /// The authoritative count is `table.len()` inside write transactions,
    /// used for capacity enforcement. Sweep and invalidate decrement via
    /// saturating-fetch-sub to prevent underflow.
    entries: Arc<AtomicU64>,
    /// Context-owned shutdown token. Cloned into the sweep task; never
    /// cancelled by this repository (doing so would shut down the entire
    /// context when a single repo is dropped).
    shutdown_token: CancellationToken,
    sweep_handle: Mutex<Option<JoinHandle<()>>>,
}

impl RedbCacheRepository {
    /// Open (or create) the redb database at `path`, seed the `entries`
    /// counter from `table.len()`, and spawn the background sweep task.
    ///
    /// `shutdown_token` is the **context's** token — binding the sweep to
    /// context shutdown. The whole open sequence runs in
    /// `spawn_blocking` because `redb::Database::create` is blocking.
    #[allow(clippy::too_many_arguments)]
    pub async fn new(
        name: impl Into<String>,
        path: impl Into<PathBuf>,
        stale_retention: Duration,
        max_entries: Option<usize>,
        cache_size: usize,
        sweep_interval: Duration,
        shutdown_token: CancellationToken,
    ) -> Result<Self, CamelError> {
        let name = name.into();
        let path: PathBuf = path.into();
        let path_for_db = path.clone();
        let (db, initial_len) = tokio::task::spawn_blocking(move || {
            if let Some(parent) = path_for_db.parent() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| CamelError::Io(format!("redb create_dir_all: {e}")))?;
            }
            let db = redb::Builder::new()
                .set_cache_size(cache_size)
                .create(&path_for_db)
                .map_err(|e| CamelError::Io(format!("redb open: {e}")))?;
            // Create the table on first open AND read the persisted entry
            // count in a single write txn so the counter survives reopen.
            let len = {
                let wtx = db
                    .begin_write()
                    .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
                // `table` borrows `wtx` mutably, so it must drop before
                // `wtx.commit()` (which moves `wtx`). Read `len` then drop.
                let len = {
                    let table = wtx
                        .open_table(CACHE_TABLE)
                        .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                    table
                        .len()
                        .map_err(|e| CamelError::Io(format!("redb len: {e}")))?
                };
                wtx.commit()
                    .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
                len
            };
            Ok::<_, CamelError>((Arc::new(db), len))
        })
        .await
        .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;

        let hits = Arc::new(AtomicU64::new(0));
        let misses = Arc::new(AtomicU64::new(0));
        let evictions = Arc::new(AtomicU64::new(0));
        let peek_stale_served = Arc::new(AtomicU64::new(0));
        let invalidations = Arc::new(AtomicU64::new(0));
        let entries = Arc::new(AtomicU64::new(initial_len));

        // Container memory guardrail — diagnostic only, never fails
        // construction. Warns once when the redb page cache cannot fit within
        // the container's cgroup memory limit.
        emit_memory_guardrail(
            cache_size,
            Path::new("/sys/fs/cgroup/memory.max"),
            Path::new("/sys/fs/cgroup/memory/memory.limit_in_bytes"),
        );

        // Spawn the sweep loop. All shared state is captured as cloned Arcs;
        // the context token clone drives termination.
        let db_clone = Arc::clone(&db);
        let evictions_clone = Arc::clone(&evictions);
        let entries_clone = Arc::clone(&entries);
        let token_clone = shutdown_token.clone();
        let retention = stale_retention;
        let handle = tokio::spawn(async move {
            let mut ticker = tokio::time::interval(sweep_interval);
            loop {
                tokio::select! {
                    _ = ticker.tick() => {
                        let db = Arc::clone(&db_clone);
                        let reclaimed = tokio::task::spawn_blocking(move || {
                            sweep_reclaim(&db, retention).unwrap_or(0)
                        })
                        .await
                        .unwrap_or(0);
                        evictions_clone.fetch_add(reclaimed, Ordering::Relaxed);
                        let current = entries_clone.load(Ordering::Relaxed);
                        let sub = std::cmp::min(current, reclaimed);
                        entries_clone.fetch_sub(sub, Ordering::Relaxed);
                    }
                    _ = token_clone.cancelled() => break,
                }
            }
        });

        Ok(Self {
            name,
            db,
            stale_retention,
            max_entries,
            cache_size,
            sweep_interval,
            hits,
            misses,
            evictions,
            peek_stale_served,
            invalidations,
            entries,
            shutdown_token,
            sweep_handle: Mutex::new(Some(handle)),
        })
    }

    /// Recorded redb page-cache size in bytes (propagation seam for the
    /// eip-cache spec).
    pub fn cache_size(&self) -> usize {
        self.cache_size
    }

    /// Recorded background-sweep interval.
    pub fn sweep_interval(&self) -> std::time::Duration {
        self.sweep_interval
    }

    /// Recorded stale-retention window.
    pub fn stale_retention(&self) -> std::time::Duration {
        self.stale_retention
    }

    /// Run a single reclamation pass and return the number of entries
    /// reclaimed. Tests call this directly for deterministic sweep coverage
    /// without waiting on the background ticker.
    #[cfg(test)]
    pub(crate) async fn sweep_once(&self) -> Result<u64, CamelError> {
        let db = Arc::clone(&self.db);
        let retention = self.stale_retention;
        let reclaimed = tokio::task::spawn_blocking(move || sweep_reclaim(&db, retention))
            .await
            .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;
        self.evictions.fetch_add(reclaimed, Ordering::Relaxed);
        let current = self.entries.load(Ordering::Relaxed);
        let sub = std::cmp::min(current, reclaimed);
        self.entries.fetch_sub(sub, Ordering::Relaxed);
        Ok(reclaimed)
    }
}

// ── Memory guardrail ──────────────────────────────────────────────────────────

/// Read the container memory limit (bytes) from the cgroup filesystem,
/// preferring cgroup v2 (`memory.max`) with cgroup v1
/// (`memory.limit_in_bytes`) as fallback.
///
/// v2 `"max"` (unlimited) or unparseable content falls through to v1; a v1
/// value above 16 TiB is the v1 "unlimited" sentinel and is reported as no
/// limit. Missing/unreadable files at either path fall through to `None`.
/// All reads are best-effort (`std::fs::read_to_string(...).ok()`) — this is a
/// diagnostic seam, never a failure path.
pub(crate) fn memory_limit_from_paths(v2: &Path, v1: &Path) -> Option<u64> {
    if let Ok(content) = std::fs::read_to_string(v2)
        && let Ok(bytes) = content.trim().parse::<u64>()
    {
        return Some(bytes);
    }
    if let Ok(content) = std::fs::read_to_string(v1)
        && let Ok(bytes) = content.trim().parse::<u64>()
        // cgroup v1 "unlimited" sentinel: anything above 16 TiB.
        && bytes <= 17_592_186_044_416
    {
        return Some(bytes);
    }
    None
}

/// Diagnostic-only guardrail: when the configured redb cache size exceeds the
/// container's cgroup memory limit, emit a single warning naming both values.
/// Never fails — a missing limit or unreadable files simply skip the warning.
pub(crate) fn emit_memory_guardrail(cache_size: usize, v2: &Path, v1: &Path) {
    let cache_size = cache_size as u64;
    if let Some(limit) = memory_limit_from_paths(v2, v1)
        && cache_size > limit
    {
        tracing::warn!(
            "redb cache_size ({cache_size} bytes) exceeds container memory limit ({limit} bytes)"
        );
    }
}

/// Reclaim entries whose `expires_at + stale_retention < now`.
///
/// Entries with `expires_at = None` (no expiry) are never reclaimed. Returns
/// the reclaimed count. Used by both the background sweep loop (errors mapped
/// to `0`) and [`RedbCacheRepository::sweep_once`] (errors propagated).
fn sweep_reclaim(db: &redb::Database, stale_retention: Duration) -> Result<u64, CamelError> {
    let txn = db
        .begin_write()
        .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
    let reclaimed = {
        let mut table = txn
            .open_table(CACHE_TABLE)
            .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
        let now = SystemTime::now();
        // Collect keys first — `table.iter()` borrows the table immutably and
        // would conflict with `remove` (mirrors `idempotent/redb_repository`
        // clear pattern).
        let mut to_delete: Vec<String> = Vec::new();
        for row in table
            .iter()
            .map_err(|e| CamelError::Io(format!("redb iter: {e}")))?
        {
            let (k, v) = row.map_err(|e| CamelError::Io(format!("redb iter item: {e}")))?;
            let entry: CacheEntry = serde_json::from_slice(v.value())
                .map_err(|e| CamelError::Io(format!("cache deserialization: {e}")))?;
            let should_delete = match entry.expires_at {
                Some(exp) => match exp.checked_add(stale_retention) {
                    // Threshold in the past → past stale-retention window.
                    Some(threshold) => threshold < now,
                    // SystemTime addition overflowed → treat as reclaimable.
                    None => true,
                },
                None => false,
            };
            if should_delete {
                to_delete.push(k.value().to_string());
            }
        }
        for k in &to_delete {
            let _ = table
                .remove(k.as_str())
                .map_err(|e| CamelError::Io(format!("redb remove: {e}")))?;
        }
        to_delete.len() as u64
    };
    txn.commit()
        .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
    Ok(reclaimed)
}

/// Compute the smallest string that sorts after every string beginning with
/// `prefix`, as the exclusive upper [`Bound`] of a range scan.
///
/// The successor is `prefix` with its last Unicode scalar value incremented by
/// one, skipping the UTF-16 surrogate gap (U+D7FF → U+E000). A trailing
/// U+10FFFF carries into the preceding scalar; an empty or all-U+10FFFF
/// prefix has no successor, so the bound is [`Bound::Unbounded`].
fn successor_bound(prefix: &str) -> Bound<String> {
    match prefix.chars().last() {
        // Empty string has no scalar to increment — match every key.
        None => Bound::Unbounded,
        Some(last) => {
            let rest = &prefix[..prefix.len() - last.len_utf8()];
            match increment_scalar(last) {
                Some(next) => {
                    let mut s = String::with_capacity(rest.len() + next.len_utf8());
                    s.push_str(rest);
                    s.push(next);
                    Bound::Excluded(s)
                }
                // U+10FFFF has no successor scalar — carry into the rest.
                None => successor_bound(rest),
            }
        }
    }
}

/// Increment a Unicode scalar value by one, skipping the surrogate range.
///
/// Returns `None` for U+10FFFF (the maximum scalar has no successor).
fn increment_scalar(c: char) -> Option<char> {
    match c {
        // U+D7FF jumps over the surrogate range to U+E000.
        '\u{D7FF}' => Some('\u{E000}'),
        // U+10FFFF is the maximum scalar value.
        '\u{10FFFF}' => None,
        // Surrogates are not valid `char`, so every remaining scalar +1 is valid.
        _ => char::from_u32(c as u32 + 1),
    }
}

// ── CacheRepository impl ──────────────────────────────────────────────────────

#[async_trait]
impl CacheRepository for RedbCacheRepository {
    fn name(&self) -> &str {
        &self.name
    }

    async fn get(&self, key: &str) -> Result<Option<CacheEntry>, CamelError> {
        let db = Arc::clone(&self.db);
        let key = key.to_string();
        let result =
            tokio::task::spawn_blocking(move || -> Result<Option<CacheEntry>, CamelError> {
                let rtx = db
                    .begin_read()
                    .map_err(|e| CamelError::Io(format!("redb begin_read: {e}")))?;
                let table = rtx
                    .open_table(CACHE_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                match table
                    .get(key.as_str())
                    .map_err(|e| CamelError::Io(format!("redb get: {e}")))?
                {
                    Some(guard) => {
                        let entry: CacheEntry = serde_json::from_slice(guard.value())
                            .map_err(|e| CamelError::Io(format!("cache deserialization: {e}")))?;
                        Ok(Some(entry))
                    }
                    None => Ok(None),
                }
            })
            .await
            .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;
        // Expiry check happens outside the blocking closure, mirroring
        // `MemoryCacheRepository::get` semantics.
        match result {
            Some(entry) => {
                let expired = entry
                    .expires_at
                    .map(|e| e <= SystemTime::now())
                    .unwrap_or(false);
                if expired {
                    self.misses.fetch_add(1, Ordering::Relaxed);
                    Ok(None)
                } else {
                    self.hits.fetch_add(1, Ordering::Relaxed);
                    Ok(Some(entry))
                }
            }
            None => {
                self.misses.fetch_add(1, Ordering::Relaxed);
                Ok(None)
            }
        }
    }

    async fn set(
        &self,
        key: &str,
        mut value: CacheEntry,
        ttl: Option<Duration>,
    ) -> Result<(), CamelError> {
        value.expires_at = ttl.map(|d| SystemTime::now() + d);
        let serialized = serde_json::to_vec(&value)
            .map_err(|e| CamelError::Io(format!("cache serialization: {e}")))?;
        let db = Arc::clone(&self.db);
        let key = key.to_string();
        let max_entries = self.max_entries;
        let was_new = tokio::task::spawn_blocking(move || {
            let txn = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            let was_new = {
                let mut table = txn
                    .open_table(CACHE_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                // Scope `prior` so its immutable borrow of `table` ends before
                // the mutable `insert` below (redb guards borrow the table).
                let is_new = {
                    let prior = table
                        .get(key.as_str())
                        .map_err(|e| CamelError::Io(format!("redb get: {e}")))?;
                    // Capacity check only applies to genuinely new keys —
                    // overwrites don't grow the table.
                    if prior.is_none()
                        && let Some(max) = max_entries
                    {
                        let count = table
                            .len()
                            .map_err(|e| CamelError::Io(format!("redb len: {e}")))?
                            as usize;
                        if count >= max {
                            return Err(CamelError::Config(format!(
                                "cache: max_entries ({max}) exceeded"
                            )));
                        }
                    }
                    prior.is_none()
                };
                table
                    .insert(key.as_str(), serialized.as_slice())
                    .map_err(|e| CamelError::Io(format!("redb insert: {e}")))?;
                is_new
            };
            txn.commit()
                .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
            Ok::<bool, CamelError>(was_new)
        })
        .await
        .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;
        if was_new {
            self.entries.fetch_add(1, Ordering::Relaxed);
        }
        Ok(())
    }

    async fn peek_stale(&self, key: &str) -> Result<Option<CacheEntry>, CamelError> {
        let db = Arc::clone(&self.db);
        let key = key.to_string();
        let result =
            tokio::task::spawn_blocking(move || -> Result<Option<CacheEntry>, CamelError> {
                let rtx = db
                    .begin_read()
                    .map_err(|e| CamelError::Io(format!("redb begin_read: {e}")))?;
                let table = rtx
                    .open_table(CACHE_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                match table
                    .get(key.as_str())
                    .map_err(|e| CamelError::Io(format!("redb get: {e}")))?
                {
                    Some(guard) => {
                        let entry: CacheEntry = serde_json::from_slice(guard.value())
                            .map_err(|e| CamelError::Io(format!("cache deserialization: {e}")))?;
                        Ok(Some(entry))
                    }
                    None => Ok(None),
                }
            })
            .await
            .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;
        if result.is_some() {
            self.peek_stale_served.fetch_add(1, Ordering::Relaxed);
        }
        Ok(result)
    }

    async fn invalidate(&self, key: &str) -> Result<(), CamelError> {
        let db = Arc::clone(&self.db);
        let key = key.to_string();
        let was_present = tokio::task::spawn_blocking(move || {
            let txn = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            let was_present = {
                let mut table = txn
                    .open_table(CACHE_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                // `remove` is idempotent per the trait contract; the returned
                // Option tells us whether a value was actually present. Read
                // `.is_some()` now so the guard (borrowing `table`) drops
                // before `commit` moves `txn`.
                table
                    .remove(key.as_str())
                    .map_err(|e| CamelError::Io(format!("redb remove: {e}")))?
                    .is_some()
            };
            txn.commit()
                .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
            Ok::<bool, CamelError>(was_present)
        })
        .await
        .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;
        if was_present {
            let current = self.entries.load(Ordering::Relaxed);
            let sub = std::cmp::min(current, 1);
            self.entries.fetch_sub(sub, Ordering::Relaxed);
        }
        self.invalidations.fetch_add(1, Ordering::Relaxed);
        Ok(())
    }

    async fn invalidate_prefix(&self, prefix: &str) -> Result<u64, CamelError> {
        let db = Arc::clone(&self.db);
        let prefix = prefix.to_string();
        let deleted = tokio::task::spawn_blocking(move || -> Result<u64, CamelError> {
            // Collect matching keys in a read txn, then delete in one write
            // txn (mirrors the collect-then-remove pattern of `clear`).
            let keys: Vec<String> = {
                let rtx = db
                    .begin_read()
                    .map_err(|e| CamelError::Io(format!("redb begin_read: {e}")))?;
                let table = rtx
                    .open_table(CACHE_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                // `successor_bound` yields an owned bound; redb's range needs
                // `&str` bounds for `&str` keys (`String` is not `Borrow<&str>`).
                let upper: Bound<String> = successor_bound(&prefix);
                let upper_ref: Bound<&str> = match &upper {
                    Bound::Included(s) => Bound::Included(s.as_str()),
                    Bound::Excluded(s) => Bound::Excluded(s.as_str()),
                    Bound::Unbounded => Bound::Unbounded,
                };
                let mut keys = Vec::new();
                for row in table
                    .range::<&str>((Bound::Included(prefix.as_str()), upper_ref))
                    .map_err(|e| CamelError::Io(format!("redb range: {e}")))?
                {
                    let (k, _v) =
                        row.map_err(|e| CamelError::Io(format!("redb range item: {e}")))?;
                    keys.push(k.value().to_string());
                }
                keys
            };
            let wtx = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            {
                let mut table = wtx
                    .open_table(CACHE_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                for k in &keys {
                    let _ = table
                        .remove(k.as_str())
                        .map_err(|e| CamelError::Io(format!("redb remove: {e}")))?;
                }
            }
            wtx.commit()
                .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
            Ok(keys.len() as u64)
        })
        .await
        .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;
        self.invalidations.fetch_add(1, Ordering::Relaxed);
        if deleted > 0 {
            let current = self.entries.load(Ordering::Relaxed);
            let sub = std::cmp::min(current, deleted);
            self.entries.fetch_sub(sub, Ordering::Relaxed);
        }
        Ok(deleted)
    }

    async fn clear(&self) -> Result<(), CamelError> {
        let db = Arc::clone(&self.db);
        tokio::task::spawn_blocking(move || {
            let txn = db
                .begin_write()
                .map_err(|e| CamelError::Io(format!("redb begin_write: {e}")))?;
            {
                let mut table = txn
                    .open_table(CACHE_TABLE)
                    .map_err(|e| CamelError::Io(format!("redb open_table: {e}")))?;
                // Collect-then-remove: `iter()` borrows immutably and cannot
                // coexist with `remove`. Mirrors `idempotent/redb_repository`
                // clear pattern.
                let keys: Vec<String> = table
                    .iter()
                    .map_err(|e| CamelError::Io(format!("redb iter: {e}")))?
                    .map(|r| {
                        r.map(|(k, _v)| k.value().to_string())
                            .map_err(|e| CamelError::Io(format!("redb iter item: {e}")))
                    })
                    .collect::<Result<_, _>>()?;
                for k in &keys {
                    let _ = table
                        .remove(k.as_str())
                        .map_err(|e| CamelError::Io(format!("redb remove: {e}")))?;
                }
            }
            txn.commit()
                .map_err(|e| CamelError::Io(format!("redb commit: {e}")))?;
            Ok::<_, CamelError>(())
        })
        .await
        .map_err(|e| CamelError::Io(format!("spawn_blocking join: {e}")))??;
        self.entries.store(0, Ordering::Relaxed);
        Ok(())
    }

    async fn stats(&self) -> CacheStats {
        let db = Arc::clone(&self.db);
        let bytes = tokio::task::spawn_blocking(move || total_bytes(&db))
            .await
            .unwrap_or_default();
        CacheStats {
            hits: self.hits.load(Ordering::Relaxed),
            misses: self.misses.load(Ordering::Relaxed),
            evictions: self.evictions.load(Ordering::Relaxed),
            entries: self.entries.load(Ordering::Relaxed),
            peek_stale_served: self.peek_stale_served.load(Ordering::Relaxed),
            invalidations: self.invalidations.load(Ordering::Relaxed),
            bytes,
        }
    }
}

/// Sum every entry's `bytes.len()` over the full table range.
///
/// Called only inside `spawn_blocking` from `stats()`; `None` when the table
/// cannot be read or any entry fails to deserialize — the `bytes` field is a
/// best-effort report, never an error.
fn total_bytes(db: &redb::Database) -> Option<u64> {
    let rtx = db.begin_read().ok()?;
    let table = rtx.open_table(CACHE_TABLE).ok()?;
    let mut total: u64 = 0;
    for row in table.iter().ok()? {
        let (_key, value) = row.ok()?;
        let entry: CacheEntry = serde_json::from_slice(value.value()).ok()?;
        total = total.saturating_add(entry.bytes.len() as u64);
    }
    Some(total)
}

impl fmt::Debug for RedbCacheRepository {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RedbCacheRepository")
            .field("name", &self.name)
            .field("stale_retention", &self.stale_retention)
            .field("max_entries", &self.max_entries)
            .field("cache_size", &self.cache_size)
            .field("sweep_interval", &self.sweep_interval)
            .field("shutdown_cancelled", &self.shutdown_token.is_cancelled())
            .finish()
    }
}

impl Drop for RedbCacheRepository {
    fn drop(&mut self) {
        // Abort ONLY the sweep task. Never cancel the context-owned token —
        // that would shut down the entire context when one repo drops.
        if let Some(handle) = self.sweep_handle.lock().take() {
            handle.abort();
        }
    }
}

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

    fn entry() -> CacheEntry {
        CacheEntry {
            bytes: vec![1, 2, 3],
            content_type: camel_api::cache::ContentType::Bytes,
            expires_at: None,
        }
    }

    /// Open a repo at `<tmp>/cache.redb` with a 60s stale-retention, no cap,
    /// a 256 MiB cache size, and a 1h sweep interval (so the background loop
    /// stays dormant during sequential tests).
    async fn new_repo(tmp: &TempDir, shutdown_token: CancellationToken) -> RedbCacheRepository {
        new_repo_with(
            tmp,
            shutdown_token,
            Duration::from_secs(60),
            None,
            256 * 1024 * 1024,
            Duration::from_secs(3600),
        )
        .await
    }

    /// Full-parameter variant of [`new_repo`] for tests that need custom
    /// stale-retention, cap, cache size, or sweep interval values.
    async fn new_repo_with(
        tmp: &TempDir,
        shutdown_token: CancellationToken,
        stale_retention: Duration,
        max_entries: Option<usize>,
        cache_size: usize,
        sweep_interval: Duration,
    ) -> RedbCacheRepository {
        let path = tmp.path().join("cache.redb");
        RedbCacheRepository::new(
            "redb",
            path,
            stale_retention,
            max_entries,
            cache_size,
            sweep_interval,
            shutdown_token,
        )
        .await
        .expect("open redb cache repo")
    }

    #[tokio::test]
    async fn cache_size_recorded_and_accessible() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo_with(
            &dir,
            token,
            Duration::from_secs(60),
            None,
            536_870_912,
            Duration::from_secs(3600),
        )
        .await;
        assert_eq!(repo.cache_size(), 536_870_912);
    }

    #[tokio::test]
    async fn sweep_interval_recorded_and_accessible() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo_with(
            &dir,
            token,
            Duration::from_secs(60),
            None,
            256 * 1024 * 1024,
            Duration::from_secs(1800),
        )
        .await;
        assert_eq!(repo.sweep_interval(), Duration::from_secs(1800));
    }

    #[tokio::test]
    async fn stale_retention_recorded_and_accessible() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo_with(
            &dir,
            token,
            Duration::from_secs(3600),
            None,
            256 * 1024 * 1024,
            Duration::from_secs(3600),
        )
        .await;
        assert_eq!(repo.stale_retention(), Duration::from_secs(3600));
    }

    #[tokio::test]
    async fn explicit_cache_size_round_trip() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo_with(
            &dir,
            token,
            Duration::from_secs(60),
            None,
            512 * 1024 * 1024,
            Duration::from_secs(3600),
        )
        .await;
        repo.set("k", entry(), Some(Duration::from_secs(3600)))
            .await
            .expect("set");
        let found = repo.get("k").await.expect("get");
        assert!(
            found.is_some(),
            "entry must round-trip through the builder-opened database"
        );
    }

    #[tokio::test]
    async fn entries_survive_handle_drop_and_reopen() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("cache.redb");
        let token = CancellationToken::new();
        // Keep a clone so the sweep can be stopped via the real shutdown path
        // (token cancellation) before reopening the same file. redb rejects
        // reopening a file whose in-process handle is still alive, and the
        // sweep task holds a cloned Arc<Database> until it exits.
        let token_for_shutdown = token.clone();
        {
            let repo = RedbCacheRepository::new(
                "redb",
                path.clone(),
                Duration::from_secs(60),
                None,
                256 * 1024 * 1024,
                Duration::from_secs(3600),
                token,
            )
            .await
            .expect("open repo");
            repo.set("k", entry(), Some(Duration::from_secs(3600)))
                .await
                .expect("set");
            assert_eq!(
                repo.stats().await.entries,
                1,
                "entries counter must be 1 after first insert"
            );
            // Stop the sweep via its bound token and await the task so its
            // cloned Arc<Database> releases before the repo drops. Bind the
            // handle separately so the MutexGuard drops before the `.await`
            // (clippy::await-holding-lock).
            token_for_shutdown.cancel();
            let sweep_handle = repo.sweep_handle.lock().take();
            if let Some(handle) = sweep_handle {
                handle
                    .await
                    .expect("sweep task must exit cleanly on token cancel");
            }
            // repo dropped here — handle already taken; self.db Arc → 0 → DB
            // closes → redb frees its in-process lock.
        }
        // Reopen with a fresh token; entries must be reloaded from table.len().
        let token2 = CancellationToken::new();
        let repo = RedbCacheRepository::new(
            "redb",
            path,
            Duration::from_secs(60),
            None,
            256 * 1024 * 1024,
            Duration::from_secs(3600),
            token2,
        )
        .await
        .expect("reopen repo");
        let found = repo.get("k").await.expect("get after reopen");
        assert!(
            found.is_some(),
            "persisted entry must survive drop + reopen"
        );
        assert_eq!(
            repo.stats().await.entries,
            1,
            "entries counter must be restored from table.len() on reopen"
        );
    }

    #[tokio::test]
    async fn peek_stale_returns_post_expiry_entry_on_redb() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        repo.set("k", entry(), Some(Duration::from_millis(1)))
            .await
            .expect("set");
        tokio::time::sleep(Duration::from_millis(10)).await;
        let stale = repo.peek_stale("k").await.expect("peek_stale");
        assert!(
            stale.is_some(),
            "peek_stale must return the expired-but-present entry"
        );
    }

    #[tokio::test]
    async fn sweep_once_removes_entries_past_stale_retention() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let path = dir.path().join("cache.redb");
        // stale_retention=10ms; entry expires at +1ms; sleep 50ms so
        // (expires_at + 10ms) is well in the past → reclaimable.
        let repo = RedbCacheRepository::new(
            "redb",
            path,
            Duration::from_millis(10),
            None,
            256 * 1024 * 1024,
            Duration::from_secs(3600),
            token,
        )
        .await
        .expect("open repo");
        // Neutralize the background sweep so its immediate first tick (which
        // fires whenever the runtime next polls it) cannot steal the reclaim
        // from sweep_once. This makes the test deterministic: sweep_once is
        // the sole reclaimer.
        if let Some(handle) = repo.sweep_handle.lock().take() {
            handle.abort();
        }
        repo.set("k", entry(), Some(Duration::from_millis(1)))
            .await
            .expect("set");
        tokio::time::sleep(Duration::from_millis(50)).await;
        let reclaimed = repo.sweep_once().await.expect("sweep_once");
        assert!(
            reclaimed >= 1,
            "sweep_once must reclaim at least 1 entry, got {reclaimed}"
        );
        let stale = repo.peek_stale("k").await.expect("peek_stale after sweep");
        assert!(
            stale.is_none(),
            "entry must be gone after sweep_once reclaimed it"
        );
    }

    #[tokio::test]
    async fn sweep_stops_on_context_shutdown() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let path = dir.path().join("cache.redb");
        // Short sweep interval so the loop is definitely armed.
        let repo = RedbCacheRepository::new(
            "redb",
            path,
            Duration::from_secs(60),
            None,
            256 * 1024 * 1024,
            Duration::from_millis(10),
            token.clone(),
        )
        .await
        .expect("open repo");
        token.cancel();
        // Take the handle out so we can await it directly; Drop will see None.
        let handle = repo
            .sweep_handle
            .lock()
            .take()
            .expect("sweep handle must be present after construct");
        let completed = tokio::time::timeout(Duration::from_secs(5), handle).await;
        assert!(
            completed.is_ok(),
            "sweep task must complete within 5s of context shutdown"
        );
    }

    #[tokio::test]
    async fn redb_errors_surface_as_err() {
        let dir = tempdir().expect("tempdir");
        // A regular file where a directory is required — `create_dir_all`
        // must fail, surfacing as Err(CamelError::Io(_)).
        let blocker = dir.path().join("blocker");
        std::fs::write(&blocker, b"not a dir").expect("write blocker");
        let path = blocker.join("cache.redb");
        let result = RedbCacheRepository::new(
            "redb",
            path,
            Duration::from_secs(60),
            None,
            256 * 1024 * 1024,
            Duration::from_secs(3600),
            CancellationToken::new(),
        )
        .await;
        assert!(
            matches!(result, Err(CamelError::Io(_))),
            "expected Err(CamelError::Io(_)), got {result:?}"
        );
    }

    #[tokio::test]
    async fn overwrite_does_not_inflate_entries() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        repo.set("k", entry(), None).await.expect("first set");
        repo.set("k", entry(), None).await.expect("second set");
        assert_eq!(
            repo.stats().await.entries,
            1,
            "overwriting an existing key must not inflate the entries counter"
        );
    }

    #[tokio::test]
    async fn stats_reports_bytes_sum() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        let a = CacheEntry {
            bytes: vec![1, 2, 3],
            content_type: camel_api::cache::ContentType::Bytes,
            expires_at: None,
        };
        let b = CacheEntry {
            bytes: vec![1, 2, 3, 4, 5],
            content_type: camel_api::cache::ContentType::Bytes,
            expires_at: None,
        };
        repo.set("a", a, None).await.expect("set a");
        repo.set("b", b, None).await.expect("set b");
        assert_eq!(repo.stats().await.bytes, Some(8));
    }

    #[tokio::test]
    async fn stats_counters_reported_alongside_bytes() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        let a = CacheEntry {
            bytes: vec![1, 2, 3],
            content_type: camel_api::cache::ContentType::Bytes,
            expires_at: None,
        };
        repo.set("a", a, None).await.expect("set a");
        let s = repo.stats().await;
        assert_eq!(s.entries, 1);
        assert_eq!(s.bytes, Some(3));
    }

    #[tokio::test]
    async fn max_entries_rejects_new_key_allows_overwrite() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let path = dir.path().join("cache.redb");
        let repo = RedbCacheRepository::new(
            "redb",
            path,
            Duration::from_secs(60),
            Some(2),
            256 * 1024 * 1024,
            Duration::from_secs(3600),
            token,
        )
        .await
        .expect("open repo");
        repo.set("a", entry(), None).await.expect("set a");
        repo.set("b", entry(), None).await.expect("set b");
        let over = repo.set("c", entry(), None).await;
        assert!(
            over.is_err(),
            "third distinct key must be rejected at max_entries, got {over:?}"
        );
        let overw = repo.set("a", entry(), None).await;
        assert!(
            overw.is_ok(),
            "overwrite of an existing key must succeed at max_entries, got {overw:?}"
        );
    }

    #[tokio::test]
    async fn invalidate_prefix_removes_namespace_only() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        repo.set("rainviewer:a", entry(), None)
            .await
            .expect("set rainviewer:a");
        repo.set("rainviewer:b", entry(), None)
            .await
            .expect("set rainviewer:b");
        repo.set("gibs:a", entry(), None).await.expect("set gibs:a");
        let deleted = repo
            .invalidate_prefix("rainviewer:")
            .await
            .expect("invalidate_prefix");
        assert_eq!(deleted, 2, "only the rainviewer namespace must be removed");
        assert!(
            repo.get("rainviewer:a").await.expect("get").is_none(),
            "rainviewer:a must be gone"
        );
        assert!(
            repo.get("rainviewer:b").await.expect("get").is_none(),
            "rainviewer:b must be gone"
        );
        assert!(
            repo.get("gibs:a").await.expect("get").is_some(),
            "gibs:a must survive"
        );
    }

    #[tokio::test]
    async fn invalidate_prefix_does_not_delete_successor_key() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        repo.set("ns:", entry(), None).await.expect("set ns:");
        repo.set("ns;", entry(), None).await.expect("set ns;");
        let deleted = repo
            .invalidate_prefix("ns:")
            .await
            .expect("invalidate_prefix");
        assert_eq!(deleted, 1, "only the ns: key must be removed");
        assert!(
            repo.get("ns:").await.expect("get").is_none(),
            "ns: must be gone"
        );
        assert!(
            repo.get("ns;").await.expect("get").is_some(),
            "successor key ns; must survive"
        );
    }

    // ── cgroup memory-limit guardrail ─────────────────────────────────────────

    /// Runs `f` under a thread-local default `fmt` subscriber that appends into
    /// a shared buffer, then returns the captured text.
    fn capture_guardrail(f: impl FnOnce()) -> String {
        let buf = Arc::new(Mutex::new(Vec::new()));
        let subscriber = tracing_subscriber::fmt::Subscriber::builder()
            .with_writer(TestWriter {
                buf: Arc::clone(&buf),
            })
            .with_ansi(false)
            .finish();
        tracing::subscriber::with_default(subscriber, f);
        let captured = buf.lock().clone();
        String::from_utf8(captured).expect("captured output must be UTF-8")
    }

    /// `fmt` writer that appends into a shared `Arc<Mutex<Vec<u8>>>`.
    struct TestWriter {
        buf: Arc<Mutex<Vec<u8>>>,
    }

    impl std::io::Write for TestWriter {
        fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
            self.buf.lock().extend_from_slice(data);
            Ok(data.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TestWriter {
        type Writer = TestWriter;

        fn make_writer(&'a self) -> Self::Writer {
            TestWriter {
                buf: Arc::clone(&self.buf),
            }
        }
    }

    #[test]
    fn cgroup_v2_limit_parsed() {
        let dir = tempdir().expect("tempdir");
        let v2 = dir.path().join("memory.max");
        std::fs::write(&v2, "805306368\n").expect("write v2");
        let missing_v1 = dir.path().join("missing-v1");
        assert_eq!(memory_limit_from_paths(&v2, &missing_v1), Some(805_306_368));
    }

    #[test]
    fn cgroup_v2_max_means_unlimited() {
        let dir = tempdir().expect("tempdir");
        let v2 = dir.path().join("memory.max");
        std::fs::write(&v2, "max").expect("write v2");
        let missing_v1 = dir.path().join("missing-v1");
        assert_eq!(memory_limit_from_paths(&v2, &missing_v1), None);
    }

    #[test]
    fn cgroup_v2_malformed_falls_through() {
        let dir = tempdir().expect("tempdir");
        let v2 = dir.path().join("memory.max");
        std::fs::write(&v2, "not-a-number").expect("write v2");
        let v1 = dir.path().join("memory.limit_in_bytes");
        std::fs::write(&v1, "1073741824").expect("write v1");
        assert_eq!(memory_limit_from_paths(&v2, &v1), Some(1_073_741_824));
    }

    #[test]
    fn cgroup_v1_sentinel_unlimited() {
        let dir = tempdir().expect("tempdir");
        let missing_v2 = dir.path().join("missing-v2");
        let v1 = dir.path().join("memory.limit_in_bytes");
        std::fs::write(&v1, "9223372036854771712").expect("write v1");
        assert_eq!(memory_limit_from_paths(&missing_v2, &v1), None);
    }

    #[test]
    fn cgroup_v1_exactly_16tib_is_a_limit() {
        let dir = tempdir().expect("tempdir");
        let missing_v2 = dir.path().join("missing-v2");
        let v1 = dir.path().join("memory.limit_in_bytes");
        std::fs::write(&v1, "17592186044416\n").expect("write v1");
        assert_eq!(
            memory_limit_from_paths(&missing_v2, &v1),
            Some(17_592_186_044_416)
        );
    }

    #[test]
    fn successor_bound_unit_tests() {
        assert_eq!(
            successor_bound("ns:"),
            std::ops::Bound::Excluded("ns;".to_string())
        );
        // Prefix ending U+D7FF must jump the surrogate gap to U+E000.
        assert_eq!(
            successor_bound("a\u{D7FF}"),
            std::ops::Bound::Excluded("a\u{E000}".to_string())
        );
        // Prefix ending U+E000 increments to U+E001.
        assert_eq!(
            successor_bound("a\u{E000}"),
            std::ops::Bound::Excluded("a\u{E001}".to_string())
        );
        // Trailing U+10FFFF carries into the preceding scalar: "a…" → "b".
        assert_eq!(
            successor_bound("a\u{10FFFF}"),
            std::ops::Bound::Excluded("b".to_string())
        );
        // A prefix of only U+10FFFF has no successor.
        assert_eq!(
            successor_bound("\u{10FFFF}\u{10FFFF}"),
            std::ops::Bound::Unbounded
        );
    }

    #[tokio::test]
    async fn invalidate_prefix_empty_prefix_removes_all_seeded() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        repo.set("ns:a", entry(), None).await.expect("set ns:a");
        repo.set("ns:b", entry(), None).await.expect("set ns:b");
        repo.set("other:c", entry(), None)
            .await
            .expect("set other:c");
        let deleted = repo.invalidate_prefix("").await.expect("invalidate_prefix");
        assert_eq!(deleted, 3, "empty prefix must remove every entry");
    }

    #[tokio::test]
    async fn invalidate_prefix_empty_namespace_returns_zero() {
        let dir = tempdir().expect("tempdir");
        let token = CancellationToken::new();
        let repo = new_repo(&dir, token).await;
        let deleted = repo
            .invalidate_prefix("ns:")
            .await
            .expect("invalidate_prefix");
        assert_eq!(deleted, 0, "absent namespace must report zero removals");
    }

    #[test]
    fn cgroup_files_missing() {
        let dir = tempdir().expect("tempdir");
        let missing_v2 = dir.path().join("missing-v2");
        let missing_v1 = dir.path().join("missing-v1");
        assert_eq!(memory_limit_from_paths(&missing_v2, &missing_v1), None);
    }

    #[test]
    fn guardrail_warns_when_exceeds() {
        let dir = tempdir().expect("tempdir");
        let v2 = dir.path().join("memory.max");
        std::fs::write(&v2, "805306368\n").expect("write v2");
        let missing_v1 = dir.path().join("missing-v1");
        let output = capture_guardrail(|| {
            emit_memory_guardrail(1_073_741_824, &v2, &missing_v1);
        });
        assert!(output.contains("1073741824"), "output: {output}");
        assert!(output.contains("805306368"), "output: {output}");
        assert_eq!(
            output.matches("exceeds container memory limit").count(),
            1,
            "warn line must appear exactly once: {output}"
        );
    }

    #[test]
    fn guardrail_silent_when_fits() {
        let dir = tempdir().expect("tempdir");
        let v2 = dir.path().join("memory.max");
        std::fs::write(&v2, "805306368\n").expect("write v2");
        let missing_v1 = dir.path().join("missing-v1");
        let output = capture_guardrail(|| {
            emit_memory_guardrail(268_435_456, &v2, &missing_v1);
        });
        assert!(output.is_empty(), "expected no output, got: {output}");
    }

    #[test]
    fn guardrail_silent_when_files_missing() {
        let dir = tempdir().expect("tempdir");
        let missing_v2 = dir.path().join("missing-v2");
        let missing_v1 = dir.path().join("missing-v1");
        let output = capture_guardrail(|| {
            emit_memory_guardrail(1_073_741_824, &missing_v2, &missing_v1);
        });
        assert!(output.is_empty(), "expected no output, got: {output}");
    }
}