zlayer-registry 0.14.3

OCI container registry client with blob caching
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
//! Persistent blob cache for OCI images using `SQLx` with `SQLite`
//!
//! This module provides a persistent blob cache backed by `SQLite` for durability.
//! Uses WAL mode for concurrent multi-process access.
//! Blobs are stored with metadata for LRU eviction.

use crate::cache::{compute_digest, validate_digest, BlobCacheBackend};
use crate::error::{CacheError, Result};
use async_trait::async_trait;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::SqlitePool;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{debug, info, warn};

/// Default database filename used when a directory is provided
const DEFAULT_DB_FILENAME: &str = "blob_cache.sqlite";

/// Values at or below this size are stored inline in the `SQLite` `data` column;
/// anything larger spills to a content-addressed file in
/// [`PersistentBlobCache::blobs_dir`] and the row keeps a zero-length sentinel
/// in `data`.
///
/// **Phase 2 (metadata-only reads).** This threshold was lowered from 8 MiB to
/// 4 KiB so that every *real blob body* — OCI layer, image config, and manifest
/// body — spills to a file. The READ hot path (`get` / `get_path` / `contains`)
/// then resolves a cached body purely from the filesystem via
/// [`PersistentBlobCache::blob_file_path`], with **no `SELECT` / DB lock**: the
/// spill path is deterministic from the digest, so the DB is never consulted to
/// find or read a body. The DB stays metadata-only on reads (eviction
/// accounting + LRU recency); `last_accessed` touches are deferred off the read
/// path (see [`PersistentBlobCache::pending_access`]).
///
/// Why not `0`? A handful of *non-body control entries* are stored under this
/// same table — the manifest digest sidecar (`manifest:digest-<ref>`, a ~71-byte
/// digest string) and the original-reference sidecar (`manifest-orig:<ref>`).
/// These are tiny, not content-addressed by their own bytes, and there are many
/// of them; keeping them inline avoids littering the spill dir with hundreds of
/// sub-100-byte files. 4 KiB keeps those sidecars inline while still spilling
/// every layer/config/manifest body (manifest bodies — especially multi-arch
/// index manifests and large configs — routinely exceed 4 KiB). Sub-threshold
/// control entries are the ONLY ones that still take a DB read on a hit; blob
/// bodies never do.
///
/// `SQLite` caps a single cell at `2^31-1` (~2 GB) and defaults
/// `SQLITE_MAX_LENGTH` to 1 GB, so the inline path can never trip
/// `SQLITE_TOOBIG` (error 18) at this size.
const INLINE_MAX_BYTES: usize = 4096;

/// Monotonic counter making spill temp-file names unique across concurrent writers.
static SPILL_TEMP_SEQ: AtomicU64 = AtomicU64::new(0);

#[allow(clippy::cast_possible_wrap)]
fn current_timestamp() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i64)
}

/// Persistent blob cache for OCI images backed by `SQLite`
pub struct PersistentBlobCache {
    pool: SqlitePool,
    max_size_bytes: u64,
    /// Directory holding spilled (large) blob files, alongside the `SQLite` DB.
    blobs_dir: PathBuf,
    /// In-memory buffer of `digest -> last_accessed` touches recorded by the
    /// lock-free read path. Reads NEVER write `last_accessed` to the DB; instead
    /// they stamp recency here, and the next `put` / `put_path` / eviction pass
    /// flushes the accumulated touches into the DB in one batch
    /// (see [`PersistentBlobCache::flush_pending_access`]). This keeps the read
    /// hot path free of any DB lock while still feeding LRU eviction an accurate
    /// recency signal.
    pending_access: Mutex<HashMap<String, i64>>,
}

impl PersistentBlobCache {
    /// Create a new persistent cache at the given path
    ///
    /// If `path` is a directory, the cache database will be created as
    /// `blob_cache.sqlite` inside that directory. If `path` is a file path,
    /// it will be used directly as the database file.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened or the schema cannot be initialized.
    pub async fn open<P: AsRef<Path>>(path: P) -> Result<Self, CacheError> {
        let path = path.as_ref();

        // If the path is an existing directory, append the default database filename
        let db_path = if path.is_dir() {
            path.join(DEFAULT_DB_FILENAME)
        } else {
            path.to_path_buf()
        };

        // Ensure parent directory exists
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Directory for spilled large-blob files, alongside the DB file
        // (e.g. `cache/blobs.redb` -> `cache/blobs.blobs`). Distinct from the
        // local registry's own `blobs/` tree, so the two never collide.
        let blobs_dir = db_path.with_extension("blobs");
        std::fs::create_dir_all(&blobs_dir)?;

        // Build connection options with WAL mode and busy timeout
        let connect_options =
            SqliteConnectOptions::from_str(&format!("sqlite:{}?mode=rwc", db_path.display()))
                .map_err(|e| CacheError::Database(format!("invalid database path: {e}")))?
                .pragma("journal_mode", "WAL")
                .pragma("busy_timeout", "5000")
                .pragma("synchronous", "NORMAL")
                // Track freed pages on a freelist that `incremental_vacuum` can
                // return to the OS. New DBs are created in INCREMENTAL mode; a
                // legacy DB created with auto_vacuum=0 keeps reporting 0 until a
                // one-time full VACUUM (see `compact`) converts it — otherwise
                // deleted inline blobs leave the file permanently bloated.
                .pragma("auto_vacuum", "INCREMENTAL")
                .create_if_missing(true);

        // Create connection pool
        let pool = SqlitePoolOptions::new()
            .max_connections(5)
            .connect_with(connect_options)
            .await
            .map_err(|e| CacheError::Database(format!("failed to open database: {e}")))?;

        // Initialize schema
        sqlx::query(
            r"
            CREATE TABLE IF NOT EXISTS blobs (
                digest TEXT PRIMARY KEY NOT NULL,
                data BLOB NOT NULL,
                size_bytes INTEGER NOT NULL,
                created_at INTEGER NOT NULL,
                last_accessed INTEGER NOT NULL
            )
            ",
        )
        .execute(&pool)
        .await
        .map_err(|e| CacheError::Database(format!("failed to create blobs table: {e}")))?;

        sqlx::query(
            r"
            CREATE INDEX IF NOT EXISTS idx_blobs_last_accessed ON blobs(last_accessed)
            ",
        )
        .execute(&pool)
        .await
        .map_err(|e| CacheError::Database(format!("failed to create index: {e}")))?;

        info!("Opened persistent blob cache at {:?}", db_path);

        Ok(Self {
            pool,
            max_size_bytes: 10 * 1024 * 1024 * 1024, // 10GB default
            blobs_dir,
            pending_access: Mutex::new(HashMap::new()),
        })
    }

    /// Filesystem path of the spill file for `digest` (colons/slashes sanitized
    /// so the key is a safe single filename component).
    fn blob_file_path(&self, digest: &str) -> PathBuf {
        self.blobs_dir.join(sanitize_key(digest))
    }

    /// Write `data` to the spill file for `digest` atomically (unique temp +
    /// rename). Content-addressed, so an existing file of the same length is
    /// assumed identical and left in place.
    async fn write_spill(&self, digest: &str, data: &[u8]) -> Result<(), CacheError> {
        let final_path = self.blob_file_path(digest);
        if let Ok(meta) = tokio::fs::metadata(&final_path).await {
            if meta.len() == data.len() as u64 {
                return Ok(());
            }
        }
        let tmp = self.spill_temp_path(digest);
        tokio::fs::write(&tmp, data).await?;
        tokio::fs::rename(&tmp, &final_path).await?;
        Ok(())
    }

    /// A unique temp path in `blobs_dir` for an in-progress spill write.
    fn spill_temp_path(&self, digest: &str) -> PathBuf {
        let seq = SPILL_TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
        self.blobs_dir.join(format!(
            "{}.tmp.{}.{}",
            sanitize_key(digest),
            std::process::id(),
            seq
        ))
    }

    /// Best-effort removal of a spilled blob file (ignores "not found").
    async fn remove_spill(&self, digest: &str) {
        let path = self.blob_file_path(digest);
        if let Err(e) = tokio::fs::remove_file(&path).await {
            if e.kind() != std::io::ErrorKind::NotFound {
                warn!(digest = %digest, error = %e, "failed to remove spilled blob file");
            }
        }
    }

    /// Set maximum cache size in bytes
    #[must_use]
    pub fn with_max_size(mut self, max_size_bytes: u64) -> Self {
        self.max_size_bytes = max_size_bytes;
        self
    }

    /// Get a blob by digest.
    ///
    /// **Lock-free hot path.** A cached blob body is always spilled to a
    /// content-addressed file (`INLINE_MAX_BYTES` is small enough that every
    /// real layer/config/manifest body spills), so a hit resolves by reading
    /// `blob_file_path(digest)` directly — **no `SELECT`, no DB lock**. Recency
    /// is recorded in memory (deferred touch) instead of issuing a DB write.
    ///
    /// Only when the spill file is absent do we fall back to a single DB read,
    /// which covers the small inline control entries (e.g. the manifest digest
    /// sidecar) and genuine cache misses.
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid or the (fallback) database
    /// query fails.
    pub async fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError> {
        validate_digest(digest)?;

        // Fast path: spilled body. Read straight from the deterministic path
        // with no DB access at all.
        let path = self.blob_file_path(digest);
        match tokio::fs::read(&path).await {
            Ok(bytes) => {
                self.touch(digest);
                return Ok(Some(bytes));
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // Not spilled — fall through to the inline/miss DB lookup below.
            }
            Err(e) => {
                warn!(
                    digest = %digest,
                    path = ?path,
                    error = %e,
                    "spilled blob file unreadable; treating as cache miss"
                );
                return Ok(None);
            }
        }

        // Slow path (inline control entries + misses): one DB read. Blob bodies
        // never reach here because they always spill to a file.
        let result: Option<Vec<u8>> = sqlx::query_scalar("SELECT data FROM blobs WHERE digest = ?")
            .bind(digest)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| CacheError::Database(format!("failed to get blob: {e}")))?;

        match result {
            // Inline blob (non-empty `data`).
            Some(v) if !v.is_empty() => {
                self.touch(digest);
                Ok(Some(v))
            }
            // No row, or a spilled-sentinel row whose file we already found
            // missing above — both are effectively a miss.
            _ => Ok(None),
        }
    }

    /// Size in bytes of a cached blob, read from metadata without loading the
    /// blob body. Returns `None` if the blob is not cached.
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid or the database query fails.
    #[allow(clippy::cast_sign_loss)]
    pub async fn get_size(&self, digest: &str) -> Result<Option<u64>, CacheError> {
        validate_digest(digest)?;
        let sz: Option<i64> = sqlx::query_scalar("SELECT size_bytes FROM blobs WHERE digest = ?")
            .bind(digest)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| CacheError::Database(format!("failed to get blob size: {e}")))?;
        Ok(sz.map(|v| v as u64))
    }

    /// Filesystem path of a cached blob's bytes, when the blob is stored as a
    /// spill file. Returns `None` for inline (small) or absent blobs — the
    /// caller should fall back to [`PersistentBlobCache::get`].
    ///
    /// **Lock-free hot path.** The spill path is deterministic from the digest,
    /// so this is a pure filesystem existence check — **no `SELECT`, no DB
    /// lock**. If the content-addressed file exists, its path is returned (and
    /// recency stamped in memory); otherwise `None`. Because every real blob
    /// body spills to a file, this resolves the streaming-pull consumer
    /// (`client.rs::pull_blob_to_file`) entirely from the filesystem.
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid.
    pub async fn get_path(&self, digest: &str) -> Result<Option<PathBuf>, CacheError> {
        validate_digest(digest)?;
        let path = self.blob_file_path(digest);
        if tokio::fs::metadata(&path).await.is_ok() {
            self.touch(digest);
            Ok(Some(path))
        } else {
            Ok(None)
        }
    }

    /// Ingest an already-on-disk file as the blob `digest` without buffering it
    /// in memory. Hardlinks `src` into the spill dir when possible (same
    /// filesystem, O(1)); falls back to a streamed copy across devices. Stores
    /// only metadata + the zero-length sentinel in `SQLite`.
    ///
    /// The caller is responsible for digest integrity (the streaming pull path
    /// verifies the SHA-256 as it writes `src`); `put_path` does not re-hash.
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid, the source cannot be read, or
    /// the database write fails.
    #[allow(clippy::cast_possible_wrap)]
    pub async fn put_path(&self, digest: &str, src: &Path) -> Result<(), CacheError> {
        validate_digest(digest)?;

        let size_bytes = tokio::fs::metadata(src).await?.len() as i64;
        let final_path = self.blob_file_path(digest);

        // Materialize the spill file (skip if already content-addressed present);
        // hardlink first, falling back to copy across devices / on a writer race.
        if tokio::fs::metadata(&final_path).await.is_err()
            && tokio::fs::hard_link(src, &final_path).await.is_err()
        {
            // Cross-device, or a concurrent writer won the race: copy via a
            // unique temp then atomic rename.
            let tmp = self.spill_temp_path(digest);
            tokio::fs::copy(src, &tmp).await?;
            if let Err(e) = tokio::fs::rename(&tmp, &final_path).await {
                let _ = tokio::fs::remove_file(&tmp).await;
                return Err(CacheError::Io(e));
            }
        }

        let now = current_timestamp();
        sqlx::query(
            r"
            INSERT OR REPLACE INTO blobs (digest, data, size_bytes, created_at, last_accessed)
            VALUES (?, ?, ?, ?, ?)
            ",
        )
        .bind(digest)
        .bind(&[][..])
        .bind(size_bytes)
        .bind(now)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(|e| CacheError::Database(format!("failed to insert blob metadata: {e}")))?;

        debug!("Ingested blob {} from path ({} bytes)", digest, size_bytes);

        // Fold any buffered read-recency touches into the DB before eviction so
        // LRU ordering reflects recent reads.
        self.flush_pending_access().await?;
        self.evict_if_needed().await?;

        Ok(())
    }

    /// Record a read of `digest` in the in-memory recency buffer.
    ///
    /// This is the deferred-touch primitive that keeps the read hot path free
    /// of any DB write: instead of issuing `UPDATE blobs SET last_accessed`, a
    /// read stamps the current timestamp here. The buffered touches are folded
    /// into the DB later by [`PersistentBlobCache::flush_pending_access`] on the
    /// next `put` / `put_path` / eviction pass. A poisoned lock is non-fatal —
    /// recency is best-effort, never a reason to fail a read.
    fn touch(&self, digest: &str) {
        let now = current_timestamp();
        if let Ok(mut pending) = self.pending_access.lock() {
            pending.insert(digest.to_string(), now);
        }
    }

    /// Flush buffered read-recency touches into the DB `last_accessed` column.
    ///
    /// Called from the write/eviction paths (never from a read), so the LRU
    /// ordering used by [`PersistentBlobCache::evict_if_needed`] reflects recent
    /// reads without any read ever taking the DB lock. Touches for rows that no
    /// longer exist are harmless no-op `UPDATE`s. The buffer is drained up front
    /// so a concurrent read's touch isn't lost (it simply lands in the next
    /// flush).
    async fn flush_pending_access(&self) -> Result<(), CacheError> {
        let drained: Vec<(String, i64)> = match self.pending_access.lock() {
            Ok(mut pending) => {
                if pending.is_empty() {
                    return Ok(());
                }
                pending.drain().collect()
            }
            // Poisoned lock: skip the flush, recency is best-effort.
            Err(_) => return Ok(()),
        };

        for (digest, ts) in drained {
            sqlx::query("UPDATE blobs SET last_accessed = ? WHERE digest = ?")
                .bind(ts)
                .bind(&digest)
                .execute(&self.pool)
                .await
                .map_err(|e| CacheError::Database(format!("failed to flush access time: {e}")))?;
        }

        Ok(())
    }

    /// Put a blob into the cache
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid, mismatches the data, or the database write fails.
    #[allow(clippy::cast_possible_wrap)]
    pub async fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError> {
        validate_digest(digest)?;

        // Verify digest matches data (skip for manifest cache keys)
        if !digest.starts_with("manifest:") {
            let actual_digest = compute_digest(data);
            if actual_digest != digest {
                return Err(CacheError::Corrupted(format!(
                    "digest mismatch: expected {digest}, got {actual_digest}"
                )));
            }
        }

        let now = current_timestamp();
        let size_bytes = data.len() as i64;

        // Large values spill to a file (SQLite can't hold a multi-GB cell); the
        // row keeps a zero-length `data` sentinel. Small values stay inline.
        let inline: &[u8] = if data.len() > INLINE_MAX_BYTES {
            self.write_spill(digest, data).await?;
            &[]
        } else {
            data
        };

        sqlx::query(
            r"
            INSERT OR REPLACE INTO blobs (digest, data, size_bytes, created_at, last_accessed)
            VALUES (?, ?, ?, ?, ?)
            ",
        )
        .bind(digest)
        .bind(inline)
        .bind(size_bytes)
        .bind(now)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(|e| CacheError::Database(format!("failed to insert blob: {e}")))?;

        debug!("Stored blob {} ({} bytes)", digest, data.len());

        // Fold any buffered read-recency touches into the DB before eviction so
        // LRU ordering reflects recent reads.
        self.flush_pending_access().await?;

        // Evict if needed (after insert to avoid holding transaction too long)
        self.evict_if_needed().await?;

        Ok(())
    }

    /// Check if a blob exists in the cache.
    ///
    /// **Lock-free hot path.** A spilled blob body is detected by the existence
    /// of its content-addressed file — **no `SELECT`, no DB lock**. Only when
    /// the file is absent do we fall back to a single DB existence check, which
    /// covers the small inline control entries and genuine misses.
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid or the (fallback) database
    /// query fails.
    pub async fn contains(&self, digest: &str) -> Result<bool, CacheError> {
        validate_digest(digest)?;

        // Fast path: spilled body present on disk.
        if tokio::fs::metadata(self.blob_file_path(digest))
            .await
            .is_ok()
        {
            return Ok(true);
        }

        // Slow path: inline control entry, or a real miss.
        let exists: bool = sqlx::query_scalar(
            "SELECT EXISTS(SELECT 1 FROM blobs WHERE digest = ? AND length(data) > 0)",
        )
        .bind(digest)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| CacheError::Database(format!("failed to check blob: {e}")))?;

        Ok(exists)
    }

    /// Delete a blob from the cache
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid or the database delete fails.
    pub async fn delete(&self, digest: &str) -> Result<(), CacheError> {
        validate_digest(digest)?;

        sqlx::query("DELETE FROM blobs WHERE digest = ?")
            .bind(digest)
            .execute(&self.pool)
            .await
            .map_err(|e| CacheError::Database(format!("failed to delete blob: {e}")))?;

        self.remove_spill(digest).await;

        // Drop any buffered recency touch so a later flush can't resurrect
        // stale ordering for this (now absent) digest.
        if let Ok(mut pending) = self.pending_access.lock() {
            pending.remove(digest);
        }

        debug!("Deleted blob {}", digest);

        Ok(())
    }

    /// Return every `digest` column value whose name starts with `prefix`.
    ///
    /// # Errors
    ///
    /// Returns `CacheError::Database` on SQL failure.
    pub async fn keys_with_prefix(&self, prefix: &str) -> Result<Vec<String>, CacheError> {
        let pattern = format!("{prefix}%");
        let rows: Vec<(String,)> =
            sqlx::query_as("SELECT digest FROM blobs WHERE digest LIKE ? ESCAPE '\\'")
                .bind(pattern)
                .fetch_all(&self.pool)
                .await
                .map_err(|e| CacheError::Database(format!("failed to list keys: {e}")))?;
        Ok(rows.into_iter().map(|(s,)| s).collect())
    }

    /// Get current cache size in bytes
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails.
    #[allow(clippy::cast_sign_loss)]
    pub async fn size(&self) -> Result<u64, CacheError> {
        let total: Option<i64> = sqlx::query_scalar("SELECT SUM(size_bytes) FROM blobs")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| CacheError::Database(format!("failed to get cache size: {e}")))?;

        Ok(total.unwrap_or(0) as u64)
    }

    /// Reclaim freelist space to the OS.
    ///
    /// A DB created before INCREMENTAL auto-vacuum (i.e. `auto_vacuum = 0`)
    /// accumulates freed pages on disk forever — deleting/evicting inline blobs
    /// shrinks the live row set but not the file (this is how `blobs.redb` grew
    /// to multiple GB while holding only a few hundred MB of live data). The
    /// fix needs a one-time full `VACUUM`, which both reclaims the freelist AND
    /// converts the DB to the connection's INCREMENTAL setting. Once converted
    /// (or for DBs created INCREMENTAL), the cheap `PRAGMA incremental_vacuum`
    /// returns freed pages without a full rewrite.
    ///
    /// `VACUUM` rewrites the whole database and takes a write lock, so this is
    /// expensive on a large legacy DB — call it only from prune / maintenance
    /// paths, never on the hot read/write path.
    ///
    /// # Errors
    ///
    /// Returns `CacheError::Database` if the vacuum query fails.
    pub async fn compact(&self) -> Result<(), CacheError> {
        let mode: i64 = sqlx::query_scalar("PRAGMA auto_vacuum")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| CacheError::Database(format!("failed to read auto_vacuum: {e}")))?;
        if mode == 0 {
            // Legacy DB: full VACUUM reclaims the freelist and converts to the
            // INCREMENTAL mode set on the connection so future vacuums are cheap.
            sqlx::query("VACUUM")
                .execute(&self.pool)
                .await
                .map_err(|e| CacheError::Database(format!("VACUUM failed: {e}")))?;
        } else {
            sqlx::query("PRAGMA incremental_vacuum")
                .execute(&self.pool)
                .await
                .map_err(|e| CacheError::Database(format!("incremental_vacuum failed: {e}")))?;
        }
        Ok(())
    }

    /// Get number of blobs in the cache
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails.
    #[allow(clippy::cast_sign_loss)]
    pub async fn blob_count(&self) -> Result<u64, CacheError> {
        let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM blobs")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| CacheError::Database(format!("failed to get blob count: {e}")))?;

        Ok(count as u64)
    }

    /// Clear all blobs from the cache
    ///
    /// # Errors
    ///
    /// Returns an error if the database delete fails.
    pub async fn clear(&self) -> Result<(), CacheError> {
        sqlx::query("DELETE FROM blobs")
            .execute(&self.pool)
            .await
            .map_err(|e| CacheError::Database(format!("failed to clear cache: {e}")))?;

        // Drop every spilled blob file, then recreate the (now empty) dir.
        let _ = tokio::fs::remove_dir_all(&self.blobs_dir).await;
        tokio::fs::create_dir_all(&self.blobs_dir).await?;

        // Drop all buffered recency touches — every row is gone.
        if let Ok(mut pending) = self.pending_access.lock() {
            pending.clear();
        }

        info!("Cleared all blobs from cache");

        Ok(())
    }

    /// Evict blobs using LRU if cache is over size limit
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss
    )]
    async fn evict_if_needed(&self) -> Result<(), CacheError> {
        let current_size = self.size().await?;
        if current_size <= self.max_size_bytes {
            return Ok(());
        }

        // Target: evict until we're at 90% capacity
        let target_size = (self.max_size_bytes as f64 * 0.9) as u64;
        let to_evict = current_size.saturating_sub(target_size);

        info!(
            "Cache size {} exceeds limit {}, evicting {} bytes",
            current_size, self.max_size_bytes, to_evict
        );

        // Get oldest entries sorted by last_accessed
        let entries: Vec<(String, i64)> =
            sqlx::query_as("SELECT digest, size_bytes FROM blobs ORDER BY last_accessed ASC")
                .fetch_all(&self.pool)
                .await
                .map_err(|e| {
                    CacheError::Database(format!("failed to get blobs for eviction: {e}"))
                })?;

        // Evict oldest entries until we reach target
        let mut evicted_size = 0u64;
        let mut evicted_count = 0u64;
        let mut digests_to_delete = Vec::new();

        for (digest, size_bytes) in entries {
            if evicted_size >= to_evict {
                break;
            }

            digests_to_delete.push(digest);
            #[allow(clippy::cast_sign_loss)]
            {
                evicted_size += size_bytes as u64;
            }
            evicted_count += 1;
        }

        // Delete in batch for efficiency
        for digest in &digests_to_delete {
            sqlx::query("DELETE FROM blobs WHERE digest = ?")
                .bind(digest)
                .execute(&self.pool)
                .await
                .map_err(|e| CacheError::Database(format!("failed to delete blob: {e}")))?;
            self.remove_spill(digest).await;
        }

        // Return the pages just freed by eviction to the OS. Cheap no-op on a
        // legacy auto_vacuum=0 DB until `compact` converts it; the one-time full
        // reclaim of legacy bloat is handled by `compact` from the prune path.
        if evicted_count > 0 {
            let _ = sqlx::query("PRAGMA incremental_vacuum")
                .execute(&self.pool)
                .await;
        }

        info!(
            "Evicted {} blobs ({} bytes) from cache",
            evicted_count, evicted_size
        );

        Ok(())
    }
}

/// Turn a cache key (a `sha256:<hex>` digest or a `manifest:<ref>` key) into a
/// single safe filename component by replacing path-significant characters.
fn sanitize_key(key: &str) -> String {
    key.replace([':', '/'], "_")
}

#[async_trait]
impl BlobCacheBackend for PersistentBlobCache {
    async fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError> {
        PersistentBlobCache::get(self, digest).await
    }

    async fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError> {
        PersistentBlobCache::put(self, digest, data).await
    }

    async fn contains(&self, digest: &str) -> Result<bool, CacheError> {
        PersistentBlobCache::contains(self, digest).await
    }

    async fn delete(&self, digest: &str) -> Result<(), CacheError> {
        // Delegate to the inherent method (already async).
        PersistentBlobCache::delete(self, digest).await
    }

    async fn keys_with_prefix(&self, prefix: &str) -> Result<Vec<String>, CacheError> {
        PersistentBlobCache::keys_with_prefix(self, prefix).await
    }

    async fn get_size(&self, digest: &str) -> Result<Option<u64>, CacheError> {
        PersistentBlobCache::get_size(self, digest).await
    }

    async fn get_path(&self, digest: &str) -> Result<Option<PathBuf>, CacheError> {
        PersistentBlobCache::get_path(self, digest).await
    }

    async fn put_path(&self, digest: &str, src: &Path) -> Result<(), CacheError> {
        PersistentBlobCache::put_path(self, digest, src).await
    }

    async fn compact(&self) -> Result<(), CacheError> {
        PersistentBlobCache::compact(self).await
    }
}

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

    async fn create_test_cache() -> (PersistentBlobCache, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let cache_path = temp_dir.path().join("test_cache.sqlite");
        let cache = PersistentBlobCache::open(&cache_path).await.unwrap();
        (cache, temp_dir)
    }

    #[tokio::test]
    async fn test_put_get() {
        let (cache, _temp) = create_test_cache().await;

        let data = b"test data";
        let digest = compute_digest(data);

        cache.put(&digest, data).await.unwrap();
        let retrieved = cache.get(&digest).await.unwrap();
        assert_eq!(retrieved, Some(data.to_vec()));
    }

    #[tokio::test]
    async fn test_contains() {
        let (cache, _temp) = create_test_cache().await;

        let data = b"test data";
        let digest = compute_digest(data);

        assert!(!cache.contains(&digest).await.unwrap());
        cache.put(&digest, data).await.unwrap();
        assert!(cache.contains(&digest).await.unwrap());
    }

    #[tokio::test]
    async fn test_delete() {
        let (cache, _temp) = create_test_cache().await;

        let data = b"test data";
        let digest = compute_digest(data);

        cache.put(&digest, data).await.unwrap();
        assert!(cache.contains(&digest).await.unwrap());

        cache.delete(&digest).await.unwrap();
        assert!(!cache.contains(&digest).await.unwrap());
    }

    #[tokio::test]
    async fn test_size() {
        let (cache, _temp) = create_test_cache().await;

        let data1 = b"test data 1";
        let digest1 = compute_digest(data1);
        let data2 = b"test data 2";
        let digest2 = compute_digest(data2);

        cache.put(&digest1, data1).await.unwrap();
        cache.put(&digest2, data2).await.unwrap();

        let size = cache.size().await.unwrap();
        assert_eq!(size, data1.len() as u64 + data2.len() as u64);
    }

    #[tokio::test]
    async fn test_clear() {
        let (cache, _temp) = create_test_cache().await;

        let data = b"test data";
        let digest = compute_digest(data);

        cache.put(&digest, data).await.unwrap();
        assert!(cache.contains(&digest).await.unwrap());

        cache.clear().await.unwrap();
        assert!(!cache.contains(&digest).await.unwrap());
        assert_eq!(cache.size().await.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let cache_path = temp_dir.path().join("persist_cache.sqlite");

        let data = b"persistent data";
        let digest = compute_digest(data);

        // Write data
        {
            let cache = PersistentBlobCache::open(&cache_path).await.unwrap();
            cache.put(&digest, data).await.unwrap();
        }

        // Reopen and verify data persists
        {
            let cache = PersistentBlobCache::open(&cache_path).await.unwrap();
            let retrieved = cache.get(&digest).await.unwrap();
            assert_eq!(retrieved, Some(data.to_vec()));
        }
    }

    #[tokio::test]
    async fn test_eviction() {
        let (cache, _temp) = create_test_cache().await;
        let cache = cache.with_max_size(100); // 100 bytes max

        // Insert data that exceeds limit
        for i in 0..20 {
            let data = format!("data_{i:02}");
            let digest = compute_digest(data.as_bytes());
            cache.put(&digest, data.as_bytes()).await.unwrap();

            // Add small delay to ensure different timestamps
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        // Cache should have evicted some entries
        let size = cache.size().await.unwrap();
        assert!(size <= 100, "Cache size {size} should be <= 100");
    }

    #[tokio::test]
    async fn test_invalid_digest() {
        let (cache, _temp) = create_test_cache().await;

        let result = cache.get("invalid_digest").await;
        assert!(result.is_err());

        let result = cache.put("md5:abc", b"data").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_digest_mismatch() {
        let (cache, _temp) = create_test_cache().await;

        let data = b"test data";
        let wrong_digest =
            "sha256:0000000000000000000000000000000000000000000000000000000000000000";

        let result = cache.put(wrong_digest, data).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_open_with_directory_path() {
        // Test that opening with a directory path works (appends default filename)
        let temp_dir = TempDir::new().unwrap();

        // Pass the directory path instead of a file path
        let cache = PersistentBlobCache::open(temp_dir.path()).await.unwrap();

        // Verify cache works
        let data = b"test data for directory path";
        let digest = compute_digest(data);

        cache.put(&digest, data).await.unwrap();
        let retrieved = cache.get(&digest).await.unwrap();
        assert_eq!(retrieved, Some(data.to_vec()));

        // Verify the database file was created with the default name
        let expected_db_path = temp_dir.path().join(DEFAULT_DB_FILENAME);
        assert!(
            expected_db_path.exists(),
            "Database file should be created at {expected_db_path:?}"
        );
    }

    #[tokio::test]
    async fn test_lru_access_time_update() {
        let (cache, _temp) = create_test_cache().await;
        let cache = cache.with_max_size(150); // 150 bytes max

        // Create three blobs of 60 bytes each
        let data1 = vec![1u8; 60];
        let digest1 = compute_digest(&data1);
        let data2 = vec![2u8; 60];
        let digest2 = compute_digest(&data2);
        let data3 = vec![3u8; 60];
        let digest3 = compute_digest(&data3);

        // Add first two blobs (120 bytes total, under limit)
        cache.put(&digest1, &data1).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_secs(1)).await; // Use full second sleeps for timestamp resolution
        cache.put(&digest2, &data2).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;

        // Verify both exist
        assert!(cache.contains(&digest1).await.unwrap());
        assert!(cache.contains(&digest2).await.unwrap());

        // Access digest1 to update its access time (making it more recent than data2)
        let result = cache.get(&digest1).await.unwrap();
        assert!(result.is_some(), "data1 should exist");
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;

        // Adding third blob brings us to 180 bytes (over 150 limit)
        // Eviction target is 90% of 150 = 135 bytes
        // Need to evict 180 - 135 = 45 bytes
        // Should evict data2 (60 bytes, the oldest), leaving data1 and data3
        cache.put(&digest3, &data3).await.unwrap();

        // Verify the eviction happened correctly
        let has_data1 = cache.contains(&digest1).await.unwrap();
        let has_data2 = cache.contains(&digest2).await.unwrap();
        let has_data3 = cache.contains(&digest3).await.unwrap();
        let final_size = cache.size().await.unwrap();

        // data3 (just added) should always remain
        assert!(
            has_data3,
            "data3 should remain (just added). data1={has_data1}, data2={has_data2}, data3={has_data3}, size={final_size}"
        );

        // At least one should be evicted
        assert!(
            !has_data1 || !has_data2,
            "At least one of data1 or data2 should be evicted. data1={has_data1}, data2={has_data2}, data3={has_data3}, size={final_size}"
        );

        // data2 (oldest) should be evicted before data1 (accessed recently)
        assert!(
            has_data1 || !has_data2,
            "LRU eviction failed: data1 (recently accessed) was evicted but data2 (oldest) was kept. data1={has_data1}, data2={has_data2}, data3={has_data3}, size={final_size}"
        );
    }

    #[tokio::test]
    async fn test_blob_count() {
        let (cache, _temp) = create_test_cache().await;

        assert_eq!(cache.blob_count().await.unwrap(), 0);

        let data1 = b"test data 1";
        let digest1 = compute_digest(data1);
        cache.put(&digest1, data1).await.unwrap();
        assert_eq!(cache.blob_count().await.unwrap(), 1);

        let data2 = b"test data 2";
        let digest2 = compute_digest(data2);
        cache.put(&digest2, data2).await.unwrap();
        assert_eq!(cache.blob_count().await.unwrap(), 2);

        cache.delete(&digest1).await.unwrap();
        assert_eq!(cache.blob_count().await.unwrap(), 1);
    }

    /// A blob larger than [`INLINE_MAX_BYTES`] spills to a file (no `SQLITE_TOOBIG`),
    /// round-trips byte-for-byte, accounts its size, and cleans up on delete.
    /// This exercises the exact code path a multi-GB layer takes — there is no
    /// size branch above the threshold, so 8 MiB+1 and 4.3 GB are the same path.
    #[tokio::test]
    async fn large_blob_spills_to_disk() {
        let (cache, _temp) = create_test_cache().await;

        // Distinct, compressible-but-non-trivial bytes just over the threshold.
        let mut data = vec![0u8; INLINE_MAX_BYTES + 1];
        for (i, b) in data.iter_mut().enumerate() {
            *b = u8::try_from(i % 251).unwrap();
        }
        let digest = compute_digest(&data);

        cache.put(&digest, &data).await.unwrap();

        // A spill file exists for this digest (proves it did NOT go inline).
        let spill = cache.blob_file_path(&digest);
        assert!(spill.exists(), "expected spill file at {spill:?}");

        // The inline `data` column is the empty sentinel.
        let inline: Option<Vec<u8>> = sqlx::query_scalar("SELECT data FROM blobs WHERE digest = ?")
            .bind(&digest)
            .fetch_optional(&cache.pool)
            .await
            .unwrap();
        assert_eq!(
            inline,
            Some(Vec::new()),
            "spilled row must hold x'' sentinel"
        );

        // Round-trips byte-for-byte.
        let got = cache.get(&digest).await.unwrap();
        assert_eq!(got.as_deref(), Some(data.as_slice()));

        // Size + path metadata are correct without loading the body.
        assert_eq!(
            cache.get_size(&digest).await.unwrap(),
            Some(data.len() as u64)
        );
        assert_eq!(cache.get_path(&digest).await.unwrap(), Some(spill.clone()));
        assert_eq!(cache.size().await.unwrap(), data.len() as u64);
        assert_eq!(cache.blob_count().await.unwrap(), 1);

        // Delete removes both the row and the spill file.
        cache.delete(&digest).await.unwrap();
        assert!(!cache.contains(&digest).await.unwrap());
        assert!(!spill.exists(), "spill file should be gone after delete");
    }

    /// Lowering `INLINE_MAX_BYTES` to 4 KiB makes a modest blob body (just over
    /// the threshold — far smaller than the old 8 MiB cutoff) spill to a
    /// content-addressed file, and `get` still round-trips it byte-for-byte.
    /// This is the Phase-2 behavior change: real layer/config/manifest bodies
    /// become files instead of inline DB cells.
    #[tokio::test]
    async fn small_body_now_spills_to_file() {
        let (cache, _temp) = create_test_cache().await;

        // A body of 8 KiB: comfortably over the 4 KiB threshold, but a tiny
        // fraction of the old 8 MiB inline limit — under the old code this
        // lived inline; now it must be a file.
        assert_eq!(
            INLINE_MAX_BYTES, 4096,
            "threshold lowered to 4 KiB in Phase 2"
        );
        let mut data = vec![0u8; 8 * 1024];
        for (i, b) in data.iter_mut().enumerate() {
            *b = u8::try_from(i % 251).unwrap();
        }
        let digest = compute_digest(&data);

        cache.put(&digest, &data).await.unwrap();

        // It spilled: a content-addressed file exists, the inline column is the
        // empty sentinel, and `get_path` returns the file path.
        let spill = cache.blob_file_path(&digest);
        assert!(
            spill.exists(),
            "8 KiB body must spill to a file under the 4 KiB threshold"
        );
        let inline: Option<Vec<u8>> = sqlx::query_scalar("SELECT data FROM blobs WHERE digest = ?")
            .bind(&digest)
            .fetch_optional(&cache.pool)
            .await
            .unwrap();
        assert_eq!(
            inline,
            Some(Vec::new()),
            "spilled row holds the x'' sentinel"
        );
        assert_eq!(cache.get_path(&digest).await.unwrap(), Some(spill));

        // And `get` round-trips the body straight from the file.
        assert_eq!(
            cache.get(&digest).await.unwrap().as_deref(),
            Some(data.as_slice())
        );
        assert!(cache.contains(&digest).await.unwrap());
    }

    /// A spilled-blob cache HIT must perform ZERO DB queries on the read path.
    ///
    /// We prove it by closing the `SQLite` pool after the blob is stored: any
    /// `SELECT`/`UPDATE` against the pool now errors. If `get`, `get_path`, or
    /// `contains` still succeed for the cached digest, they could not have
    /// touched the DB — they resolved purely from the filesystem.
    #[tokio::test]
    async fn spilled_hit_is_db_lock_free() {
        let (cache, _temp) = create_test_cache().await;

        // A real blob body (over the 4 KiB threshold → spilled to a file).
        let mut data = vec![0u8; 16 * 1024];
        for (i, b) in data.iter_mut().enumerate() {
            *b = u8::try_from((i * 7) % 251).unwrap();
        }
        let digest = compute_digest(&data);
        cache.put(&digest, &data).await.unwrap();

        // Confirm it really spilled, then a digest of an absent blob for the
        // negative-path checks.
        assert!(
            cache.blob_file_path(&digest).exists(),
            "body must be a spill file"
        );
        let absent = compute_digest(b"this blob was never stored");

        // Close the pool: every subsequent DB statement will error.
        cache.pool.close().await;
        assert!(
            cache.pool.is_closed(),
            "pool must be closed for the assertion to be meaningful"
        );

        // Sanity: a statement against the closed pool DOES fail — so if the
        // read methods below succeed, they provably did NOT hit the DB.
        let db_probe: Result<i64, _> = sqlx::query_scalar("SELECT 1").fetch_one(&cache.pool).await;
        assert!(db_probe.is_err(), "closed pool must reject queries");

        // HIT path, all lock-free / DB-free:
        // contains -> filesystem existence check.
        assert!(
            cache.contains(&digest).await.unwrap(),
            "contains must resolve a spilled hit from the filesystem with no DB"
        );
        // get_path -> deterministic content-addressed path.
        assert_eq!(
            cache.get_path(&digest).await.unwrap(),
            Some(cache.blob_file_path(&digest)),
            "get_path must return the file path with no DB"
        );
        // get -> reads the file body, byte-for-byte, no DB.
        assert_eq!(
            cache.get(&digest).await.unwrap().as_deref(),
            Some(data.as_slice()),
            "get must read the spilled body from disk with no DB"
        );

        // MISS path for a blob with no spill file: `get`/`get_path` fall through
        // to the DB. With the pool closed, `get_path` (filesystem-only) reports
        // a clean miss, while `get`/`contains` surface the DB error from the
        // fallback — confirming the fallback path is the ONLY one that touches
        // the DB. (We don't assert the exact variant; just that get_path is the
        // DB-free one.)
        assert_eq!(
            cache.get_path(&absent).await.unwrap(),
            None,
            "get_path on an absent blob is a pure filesystem miss, no DB"
        );
    }

    /// A small blob stays inline: no spill file, `get_path` is `None`.
    #[tokio::test]
    async fn inline_small_blob_no_spill() {
        let (cache, _temp) = create_test_cache().await;

        let data = b"small inline blob";
        let digest = compute_digest(data);
        cache.put(&digest, data).await.unwrap();

        let spill = cache.blob_file_path(&digest);
        assert!(!spill.exists(), "small blob must not spill to disk");
        assert_eq!(cache.get_path(&digest).await.unwrap(), None);
        assert_eq!(
            cache.get(&digest).await.unwrap().as_deref(),
            Some(&data[..])
        );
    }

    /// `put_path` ingests an on-disk file (hardlink) and `get`/`get_path` read it back.
    #[tokio::test]
    async fn put_path_ingests_file() {
        let (cache, temp) = create_test_cache().await;

        let mut data = vec![7u8; INLINE_MAX_BYTES + 32];
        for (i, b) in data.iter_mut().enumerate() {
            *b = u8::try_from(i % 97).unwrap();
        }
        let digest = compute_digest(&data);

        let src = temp.path().join("incoming.blob");
        tokio::fs::write(&src, &data).await.unwrap();

        cache.put_path(&digest, &src).await.unwrap();

        assert!(cache.contains(&digest).await.unwrap());
        assert_eq!(
            cache.get_size(&digest).await.unwrap(),
            Some(data.len() as u64)
        );
        let path = cache
            .get_path(&digest)
            .await
            .unwrap()
            .expect("spilled path");
        assert!(path.exists());
        assert_eq!(
            cache.get(&digest).await.unwrap().as_deref(),
            Some(data.as_slice())
        );
    }

    /// Inserting then deleting many inline blobs leaves freed pages on the DB
    /// freelist; `compact()` must reclaim them. Asserts the freelist drops to a
    /// small number after compaction (the primary, WAL-robust invariant) and
    /// that the on-disk main DB file does not grow as a result.
    #[tokio::test]
    async fn compact_reclaims_freelist() {
        // ~50 distinct 64 KiB inline blobs (each well under INLINE_MAX_BYTES,
        // but together big enough to grow the DB file by many pages).
        const BLOB_LEN: usize = 64 * 1024;
        const BLOB_COUNT: usize = 50;

        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("compact_cache.sqlite");
        let cache = PersistentBlobCache::open(&db_path).await.unwrap();

        let mut digests = Vec::with_capacity(BLOB_COUNT);
        for n in 0..BLOB_COUNT {
            // Distinct bytes per blob so each gets a unique content digest.
            let mut data = vec![0u8; BLOB_LEN];
            let seed = u8::try_from(n % 256).unwrap();
            for (i, b) in data.iter_mut().enumerate() {
                *b = seed ^ u8::try_from(i % 251).unwrap();
            }
            let digest = compute_digest(&data);
            cache.put(&digest, &data).await.unwrap();
            digests.push(digest);
        }
        assert_eq!(cache.blob_count().await.unwrap(), BLOB_COUNT as u64);

        // Checkpoint the WAL into the main DB so the on-disk size reflects the
        // populated state, then record the populated file size.
        sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
            .execute(&cache.pool)
            .await
            .unwrap();
        let size_populated = tokio::fs::metadata(&db_path).await.unwrap().len();

        // Delete every blob — this frees their pages onto the freelist.
        for digest in &digests {
            cache.delete(digest).await.unwrap();
        }
        assert_eq!(cache.blob_count().await.unwrap(), 0);

        // After deletion (pre-compact) the freelist must be non-trivial:
        // many freed pages are sitting in the file waiting to be reclaimed.
        sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
            .execute(&cache.pool)
            .await
            .unwrap();
        let freelist_before: i64 = sqlx::query_scalar("PRAGMA freelist_count")
            .fetch_one(&cache.pool)
            .await
            .unwrap();
        assert!(
            freelist_before > 0,
            "deleting {BLOB_COUNT} inline blobs should leave freed pages on the freelist \
             (got freelist_count={freelist_before})"
        );

        // Compact: the DB was created with INCREMENTAL auto_vacuum, so this runs
        // `PRAGMA incremental_vacuum`, returning all freed pages to the OS.
        cache.compact().await.unwrap();

        // Primary invariant: the freelist is reclaimed (drops to a small number).
        let freelist_after: i64 = sqlx::query_scalar("PRAGMA freelist_count")
            .fetch_one(&cache.pool)
            .await
            .unwrap();
        assert!(
            freelist_after < freelist_before,
            "compact() must reclaim freelist pages (before={freelist_before}, after={freelist_after})"
        );
        assert!(
            freelist_after <= 1,
            "compact() should drain the freelist to ~0 (after={freelist_after})"
        );

        // Secondary check: the on-disk DB file did not grow as a result of the
        // delete+compact cycle — the reclaimed pages were not re-bloated.
        sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
            .execute(&cache.pool)
            .await
            .unwrap();
        let size_after = tokio::fs::metadata(&db_path).await.unwrap().len();
        assert!(
            size_after <= size_populated,
            "DB file must not grow after delete+compact \
             (populated={size_populated}, after_compact={size_after})"
        );
    }
}