atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
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
//! A content-addressed cache for blobs.
//!
//! An AT Protocol blob CID is `CIDv1 / raw / sha-256` over the bytes, and that
//! makes this cache unusually simple to reason about:
//!
//! - **The key is the content's identity.** Two repositories referencing the
//!   same bytes share one entry, correctly. The DID in a blob URI is a
//!   *locator*, used only on a miss.
//! - **A hit is verifiable rather than assumed.** Every read re-hashes the
//!   bytes and compares them against the key, so a corrupted or tampered file
//!   is detected and discarded instead of served. That is what lets the cache
//!   live in a directory on disk without becoming a trust boundary.
//! - **There is no expiry.** A hash cannot go stale. A TTL here would only
//!   force a refetch of bytes already proven identical. The `ttlMs` this
//!   server puts on a `resources/read` result is a hint to the *client* about
//!   when to ask again, which is a different question and is bounded because a
//!   blob can be deleted upstream.
//!
//! The cache is disk-only. An in-memory tier would save a local read of at
//! most a few megabytes, at the cost of a second eviction policy to get wrong.
//!
//! Each blob is stored as two files: `<cid>` holding the bytes and
//! `<cid>.type` holding the content type decided when it was stored: the one
//! the repository served, or for an `application/octet-stream` answer the
//! blob reference's or the sniffed one ([`crate::mime::resolve_served`]), or
//! for an upload the one recorded on it. The content type is metadata —
//! asserted, not verified, and deliberately not part of the key. Eviction treats the two as one entry, counted against
//! the budget together and removed together, and it recognises them by name
//! ([`entry_kind`]): a file of any other name in the directory is neither
//! counted nor removed.
//!
//! A third, transient kind, `<cid>.partial-<pid>-<n>`, exists only while a
//! write is streaming in ([`BlobCache::prepare_write`]). It is never treated
//! as part of the cache's content: eviction excludes it from both the budget
//! calculation and the candidates it can remove, so a fetch that is still
//! writing one can never have it deleted out from under it by an unrelated
//! `put` or commit running eviction at the same time. A blob is never handed
//! out under that name: one the cache will not take moves out to a scratch
//! file. One left behind by a process that stopped mid-write is removed at
//! the next startup once it is a day old ([`BlobCache::sweep`]). Under a
//! budget of zero the startup sweep removes every committed entry as well,
//! and under any other it prunes the cache to that budget.
//!
//! **A commit never evicts what it has just written.** A commit prunes the
//! cache back under its budget, and the entry it has just written is not one
//! of the candidates, so `download_blob` can return its path. A blob larger
//! than the whole budget is never committed at all, whether its size was
//! declared before the write or learned only once it was written
//! ([`BlobCache::admits`]), and a budget of zero makes the cache store
//! nothing: the caller keeps such a blob in its own scratch space. A commit
//! used to be able to evict its own entry, and with a budget of zero it always
//! did. A later commit can still evict it, so a path handed out is as durable
//! as any cache entry, and no more.

use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::errors::{ConfigError, ResourceError};

/// How old a `.partial` file must be before [`BlobCache::sweep`] removes it.
///
/// A write in progress touches its file with every chunk, and the blob client
/// gives up on a request after 120 seconds, so a file a day old is not being
/// written. Another atpmcp sharing the directory may be writing a younger
/// one, so a younger one is left alone.
const STALE_PARTIAL_AGE: Duration = Duration::from_secs(24 * 60 * 60);

/// A blob found in the cache and verified against its key.
///
/// It names the file rather than holding the bytes. It held them, read whole
/// into memory to be hashed, so every concurrent cache hit kept an entire
/// blob resident -- up to the transfer ceiling each -- whether or not the
/// caller wanted the bytes or only the path.
#[derive(Debug)]
pub struct CachedBlob {
    /// Where the verified bytes are.
    pub path: PathBuf,
    /// Their size in bytes.
    pub size: u64,
    /// The content type recorded alongside them, if any.
    pub mime_type: Option<String>,
    /// The handle the bytes were hashed through, still open. It goes on
    /// reading the same file after `path` is unlinked by an eviction or
    /// replaced by a rename, so a caller that reads the bytes back reads the
    /// file that was verified, or learns by hashing again that it changed.
    pub file: tokio::fs::File,
}

/// A content-addressed blob cache rooted at a directory.
#[derive(Debug)]
pub struct BlobCache {
    /// The directory entries are read from and written to; `None` when the
    /// cache is disabled.
    dir: Option<PathBuf>,
    /// The directory configured, whether or not the cache is enabled, for
    /// [`Self::sweep`] to clear what an earlier budget left in it.
    configured: Option<PathBuf>,
    max_bytes: u64,
}

impl BlobCache {
    /// Build a cache rooted at `dir`, pruned to `max_bytes`.
    ///
    /// A `max_bytes` of zero is a cache that stores nothing, so it is built
    /// disabled, as if there were no directory: nothing is read from `dir` or
    /// written to it, and a blob goes to its caller's scratch space. It used
    /// to write each blob into `dir` and delete it at once. The one exception
    /// is [`Self::sweep`], which removes the entries an earlier, larger budget
    /// left in `dir`.
    #[must_use]
    pub fn new(dir: Option<PathBuf>, max_bytes: u64) -> Self {
        let configured = dir.clone();
        let dir = dir.filter(|_| max_bytes > 0);
        Self {
            dir,
            configured,
            max_bytes,
        }
    }

    /// Build a cache from the environment.
    ///
    /// `ATPMCP_BLOB_CACHE_DIR` overrides the location;
    /// `ATPMCP_BLOB_CACHE_MAX_BYTES` the ceiling. A cache directory that
    /// cannot be determined disables caching rather than failing startup: a
    /// missing cache costs latency, and refusing to run costs the user their
    /// whole server.
    ///
    /// # Errors
    ///
    /// [`ConfigError::NotANumber`] when `ATPMCP_BLOB_CACHE_MAX_BYTES` is not a
    /// whole number. The server refuses to start on it rather than cache up to
    /// a ceiling the operator did not choose.
    pub fn from_env() -> Result<Self, ConfigError> {
        Self::from_lookup(crate::context::env_value)
    }

    /// [`Self::from_env`], with the variables read through `lookup`. See
    /// [`crate::context::Limits::from_lookup`] for why the seam exists.
    ///
    /// # Errors
    ///
    /// As [`Self::from_env`].
    pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
        // Zero is accepted, and turns the cache off; see `new`.
        let max_bytes = crate::context::parse_number(
            "ATPMCP_BLOB_CACHE_MAX_BYTES",
            lookup("ATPMCP_BLOB_CACHE_MAX_BYTES").as_deref(),
            0,
            crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES,
        )?
        .unwrap_or(crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES);

        let dir = lookup("ATPMCP_BLOB_CACHE_DIR")
            .map(PathBuf::from)
            .or_else(|| dirs::cache_dir().map(|dir| dir.join("atpmcp").join("blobs")));

        if dir.is_none() {
            tracing::warn!("No cache directory available; blob caching is disabled.");
        }

        Ok(Self::new(dir, max_bytes))
    }

    /// Whether this cache stores anything.
    #[must_use]
    pub fn is_enabled(&self) -> bool {
        self.dir.is_some()
    }

    /// Whether a blob of `size` bytes may be committed: the cache is enabled
    /// and `size` is within its whole budget.
    ///
    /// A blob larger than the budget could only be kept by evicting every
    /// other entry, and still be over it. [`Self::prepare_write`] asks this of
    /// a size declared before the write, and the caller must ask it again of
    /// the size it wrote before calling [`Self::commit_write`], since a
    /// response that declared none can turn out to be any size.
    #[must_use]
    pub fn admits(&self, size: u64) -> bool {
        self.is_enabled() && size <= self.max_bytes
    }

    /// The directory this cache is rooted at, if any.
    #[must_use]
    pub fn dir(&self) -> Option<&Path> {
        self.dir.as_deref()
    }

    /// Find a blob and verify it against its key.
    ///
    /// Returns `None` on a miss, and also on a *failed* verification — a
    /// corrupt entry is indistinguishable from an absent one as far as the
    /// caller is concerned, and both are answered by fetching again.
    ///
    /// The file is hashed as it is read, a chunk at a time, as a fresh fetch
    /// is, so verifying a hit costs one buffer of memory whatever the blob's
    /// size.
    pub async fn get(&self, cid: &str) -> Option<CachedBlob> {
        let path = self.path_for(cid)?;

        let (size, computed, file) = hash_file(&path).await.ok()?;
        if computed != cid {
            tracing::warn!(
                expected = %cid,
                computed = %computed,
                "Cached blob failed verification; discarding."
            );
            let _ = tokio::fs::remove_file(&path).await;
            let _ = tokio::fs::remove_file(path.with_extension("type")).await;
            return None;
        }

        let mime_type = tokio::fs::read_to_string(path.with_extension("type"))
            .await
            .ok()
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());

        Some(CachedBlob {
            path,
            size,
            mime_type,
            file,
        })
    }

    /// Store a blob under its content address.
    ///
    /// The caller is responsible for having verified `data` against `cid`
    /// first; writing unverified bytes would put the cache ahead of the check
    /// that makes it safe.
    ///
    /// # Errors
    ///
    /// Returns [`ResourceError::CacheFailure`] when the directory or files
    /// cannot be written.
    pub async fn put(
        &self,
        cid: &str,
        data: &[u8],
        mime_type: Option<&str>,
    ) -> Result<(), ResourceError> {
        let Some(target) = self.prepare_write(cid, Some(data.len() as u64)).await? else {
            return Ok(());
        };

        // Write to a temporary name and rename, so a concurrent reader never
        // sees a half-written blob and throws it away as corrupt.
        tokio::fs::write(&target.temp_path, data)
            .await
            .map_err(|error| ResourceError::CacheFailure {
                reason: format!("could not write {}: {error}", target.temp_path.display()),
            })?;

        self.commit_write(&target, mime_type).await
    }

    /// Prepare to stream a write for `cid`: ensure the cache directory exists
    /// and hand back a unique temporary path to write into.
    ///
    /// Returns `Ok(None)` when caching is disabled, the key is unsafe, or
    /// `size` is known and not [admitted](Self::admits) — the caller should
    /// fall back to its own scratch location and must not call
    /// [`commit_write`](Self::commit_write) or [`abort_write`](Self::abort_write).
    /// `size` is `None` when it is not known yet, as for a response that
    /// declares no length. The caller then checks the size it wrote with
    /// [`admits`](Self::admits) before committing, and moves a blob that is
    /// not admitted out of the cache directory. A commit used to keep such an
    /// entry whatever its size, and its prune evicted every other entry
    /// trying to get back under a budget the new one alone exceeded.
    ///
    /// The temporary name is unique to this call, not derived from `cid`
    /// alone: two concurrent writers of the same not-yet-cached blob (two
    /// callers racing a first fetch, say) would otherwise share one file name
    /// and each could truncate the other's in-progress bytes out from under
    /// it. If both finish and both call [`commit_write`](Self::commit_write),
    /// the second rename simply replaces the first with an identical file,
    /// since both are the same content under the same CID.
    ///
    /// # Errors
    ///
    /// Returns [`ResourceError::CacheFailure`] if the cache directory cannot
    /// be created.
    pub async fn prepare_write(
        &self,
        cid: &str,
        size: Option<u64>,
    ) -> Result<Option<WriteTarget>, ResourceError> {
        if size.is_some_and(|size| !self.admits(size)) {
            return Ok(None);
        }
        let Some(final_path) = self.path_for(cid) else {
            return Ok(None);
        };
        let Some(parent) = final_path.parent() else {
            return Ok(None);
        };

        tokio::fs::create_dir_all(parent)
            .await
            .map_err(|error| ResourceError::CacheFailure {
                reason: format!("could not create {}: {error}", parent.display()),
            })?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ =
                tokio::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).await;
        }

        let temp_path = parent.join(temp_name(cid));
        Ok(Some(WriteTarget {
            temp_path,
            final_path,
        }))
    }

    /// Publish a verified write: rename the temp file into place, record its
    /// content type, and prune the cache back under budget.
    ///
    /// The prune never evicts the entry just written, so its path still
    /// exists when this returns. It used to be a candidate like any other,
    /// and as the newest it went only when nothing else was left to evict,
    /// which for a blob larger than the budget is every time.
    ///
    /// Only call this once `target.temp_path` has been proven to hash to the
    /// CID `target` was prepared for — this performs no verification of its
    /// own, and a caller that skips the check is what `put`'s doc comment
    /// warns against — and its size is [admitted](Self::admits). An entry
    /// over budget would stay, and the prune would evict every other one.
    ///
    /// # Errors
    ///
    /// Returns [`ResourceError::CacheFailure`] if the rename fails. The temp
    /// file is left in place on failure: the caller decides whether to use it
    /// where it is or delete it via [`abort_write`](Self::abort_write).
    pub async fn commit_write(
        &self,
        target: &WriteTarget,
        mime_type: Option<&str>,
    ) -> Result<(), ResourceError> {
        tokio::fs::rename(&target.temp_path, &target.final_path)
            .await
            .map_err(|error| ResourceError::CacheFailure {
                reason: format!(
                    "could not rename into {}: {error}",
                    target.final_path.display()
                ),
            })?;

        if let Some(mime_type) = mime_type {
            let _ = tokio::fs::write(target.final_path.with_extension("type"), mime_type).await;
        }

        self.prune(Some(&target.final_path)).await;
        Ok(())
    }

    /// Discard a write that failed or did not verify, deleting the temp file.
    pub async fn abort_write(&self, target: &WriteTarget) {
        let _ = tokio::fs::remove_file(&target.temp_path).await;
    }

    /// The path a blob is stored at, when the key is usable as a filename.
    ///
    /// Callers reach here with a CID already parsed and validated, but this
    /// builds a filesystem path from it, so the character check is repeated
    /// rather than assumed.
    #[must_use]
    pub fn path_for(&self, cid: &str) -> Option<PathBuf> {
        let dir = self.dir.as_ref()?;
        if !is_safe_key(cid) {
            tracing::warn!(cid = %cid, "Refusing to build a cache path from an unsafe key.");
            return None;
        }
        Some(dir.join(cid))
    }

    /// Remove what earlier runs left in the cache directory. Run once, at
    /// startup, and returns how many files it removed.
    ///
    /// Whatever the budget, that is atpmcp's own `.partial` files older than
    /// [`STALE_PARTIAL_AGE`]. `prune` never counts or evicts one, since it
    /// might be a write in progress, so one abandoned by a process that
    /// stopped mid-write, or a blob an earlier build handed out in place after
    /// a failed commit, stayed forever.
    ///
    /// Under a budget of zero it is also every committed entry, blob and
    /// content type alike. A disabled cache never commits, so the prune that
    /// enforces the budget never runs, and what was cached under an earlier,
    /// larger budget, up to 512 MiB by default, stayed on disk for good. The
    /// directory itself is kept, since it may be one the operator made.
    ///
    /// Under any other budget it then prunes the cache to that budget, as a
    /// commit does. A prune ran only after a commit, so a budget lowered since
    /// the last run left the directory at its old size until a blob was next
    /// stored, which for a server answering only from the cache is never.
    ///
    /// Only a name atpmcp writes is removed ([`entry_kind`]); anything else in
    /// the directory, a subdirectory included, is left alone.
    pub async fn sweep(&self) -> usize {
        let Some(dir) = self.configured.as_ref() else {
            return 0;
        };
        let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
            return 0;
        };
        let clear = !self.is_enabled();

        let (mut partials, mut committed) = (0usize, 0usize);
        while let Ok(Some(entry)) = entries.next_entry().await {
            let name = entry.file_name();
            let Some(kind) = name.to_str().and_then(entry_kind) else {
                continue;
            };
            let Ok(metadata) = entry.metadata().await else {
                continue;
            };
            if !metadata.is_file() {
                continue;
            }
            let remove = match kind {
                EntryKind::Partial => metadata
                    .modified()
                    .ok()
                    .and_then(|modified| modified.elapsed().ok())
                    .is_some_and(|age| age > STALE_PARTIAL_AGE),
                EntryKind::Blob | EntryKind::ContentType => clear,
            };
            if !remove || tokio::fs::remove_file(entry.path()).await.is_err() {
                continue;
            }
            if kind == EntryKind::Partial {
                partials += 1;
            } else {
                committed += 1;
            }
        }

        if partials > 0 {
            tracing::info!(
                removed = partials,
                directory = %dir.display(),
                "Removed abandoned partial writes from the blob cache."
            );
        }
        if committed > 0 {
            tracing::info!(
                removed = committed,
                directory = %dir.display(),
                "ATPMCP_BLOB_CACHE_MAX_BYTES is 0; removed the blob cache's entries."
            );
        }

        let pruned = if clear { 0 } else { self.prune(None).await };
        if pruned > 0 {
            tracing::info!(
                removed = pruned,
                directory = %dir.display(),
                max_bytes = self.max_bytes,
                "Pruned the blob cache to ATPMCP_BLOB_CACHE_MAX_BYTES."
            );
        }
        partials + committed + pruned
    }

    /// Evict least-recently-modified entries until the cache is under budget,
    /// and return how many files it removed.
    ///
    /// Only atpmcp's committed entries take part ([`entry_kind`]): a `<cid>`
    /// blob and its `<cid>.type` are one entry, counted together, dated by the
    /// blob and evicted together. Anything else in the directory neither
    /// counts toward the budget nor is removed, so a directory shared with
    /// other files keeps them and is not taken for fuller than it is. It used
    /// to count and evict every file that was not a partial write, oldest
    /// first. A partial write is left out too: the task that owns it may still
    /// be writing.
    ///
    /// `keep`, the entry a commit has just written, counts toward the budget
    /// but is never evicted.
    async fn prune(&self, keep: Option<&Path>) -> usize {
        let Some(dir) = self.dir.as_ref() else {
            return 0;
        };

        let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
            return 0;
        };

        // Keyed by the blob's path, which is also `keep`'s form, and ordered
        // so that entries of the same age are evicted in a fixed order.
        let mut candidates: std::collections::BTreeMap<PathBuf, Candidate> =
            std::collections::BTreeMap::new();
        let mut total: u64 = 0;

        while let Ok(Some(entry)) = entries.next_entry().await {
            let name = entry.file_name();
            let Some(kind) = name.to_str().and_then(entry_kind) else {
                continue;
            };
            if kind == EntryKind::Partial {
                continue;
            }
            let Ok(metadata) = entry.metadata().await else {
                continue;
            };
            if !metadata.is_file() {
                continue;
            }
            let modified = metadata
                .modified()
                .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
            let path = entry.path();
            let candidate = if kind == EntryKind::ContentType {
                let candidate = candidates.entry(path.with_extension("")).or_default();
                candidate.content_type = Some(modified);
                candidate
            } else {
                let candidate = candidates.entry(path).or_default();
                candidate.blob = Some(modified);
                candidate
            };
            candidate.size += metadata.len();
            total += metadata.len();
        }

        if total <= self.max_bytes {
            return 0;
        }

        let mut candidates: Vec<(PathBuf, Candidate)> = candidates.into_iter().collect();
        candidates.sort_by_key(|(_, candidate)| candidate.modified());

        let mut removed = 0usize;
        for (blob, candidate) in candidates {
            if total <= self.max_bytes {
                break;
            }
            if keep.is_some_and(|keep| keep == blob) {
                continue;
            }
            let content_type = blob.with_extension("type");
            if candidate.blob.is_some() {
                if tokio::fs::remove_file(&blob).await.is_err() {
                    continue;
                }
                removed += 1;
                // Its content type goes with it, listed or written since.
                if tokio::fs::remove_file(&content_type).await.is_ok() {
                    removed += 1;
                }
            } else {
                // A content type whose blob is gone. The blob is not
                // removed, since this prune never saw it: a commit may have
                // just renamed it into place.
                if tokio::fs::remove_file(&content_type).await.is_err() {
                    continue;
                }
                removed += 1;
            }
            total = total.saturating_sub(candidate.size);
        }
        removed
    }
}

/// One cache entry as [`BlobCache::prune`] sees it: the modification times of
/// the files of it that were listed, and their combined size.
#[derive(Debug, Default)]
struct Candidate {
    /// The blob's modification time, when the blob was listed.
    blob: Option<std::time::SystemTime>,
    /// The content type's, when it was listed.
    content_type: Option<std::time::SystemTime>,
    /// The size of every listed file of the entry.
    size: u64,
}

impl Candidate {
    /// When the entry was written, for eviction order: the blob's time, or
    /// the content type's for one whose blob is gone.
    fn modified(&self) -> std::time::SystemTime {
        self.blob
            .or(self.content_type)
            .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
    }
}

/// The size of the file at `path`, the raw CID of its contents, read in
/// fixed-size chunks, and the handle they were read through.
async fn hash_file(path: &Path) -> std::io::Result<(u64, String, tokio::fs::File)> {
    use tokio::io::AsyncReadExt as _;

    let mut file = tokio::fs::File::open(path).await?;
    let mut hasher = atproto_dasl::cid::RawCidHasher::new();
    let mut buffer = vec![0u8; 64 * 1024];
    let mut size: u64 = 0;
    loop {
        let read = file.read(&mut buffer).await?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
        size += read as u64;
    }
    Ok((size, hasher.finalize().to_string(), file))
}

/// Paths for a streamed write: where bytes land while unverified, and where
/// they belong once they are proven to match their key.
#[derive(Debug, Clone)]
pub struct WriteTarget {
    /// Write here first. Nothing ever looks up a blob by this name, so
    /// partial content here can never be mistaken for a cache hit.
    pub temp_path: PathBuf,
    /// Rename here — via [`BlobCache::commit_write`] — only once the bytes
    /// are verified.
    pub final_path: PathBuf,
}

/// A temp filename for a streamed write of `cid`, unique to this call. See
/// [`BlobCache::prepare_write`] for why uniqueness matters.
fn temp_name(cid: &str) -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    format!(
        "{cid}.partial-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    )
}

/// Which of atpmcp's own files a cache directory entry is, by its name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EntryKind {
    /// `<cid>`, the verified bytes.
    Blob,
    /// `<cid>.type`, their content type.
    ContentType,
    /// `<cid>.partial-<pid>-<n>`, a streamed write ([`temp_name`]).
    Partial,
}

/// Which of atpmcp's own files `name` is, or `None` for a name atpmcp never
/// writes. `<cid>` must be a blob CID in its canonical form, which is all a
/// cache key can be, so a file of someone else's is not mistaken for one.
fn entry_kind(name: &str) -> Option<EntryKind> {
    let (cid, suffix) = match name.split_once('.') {
        Some((cid, suffix)) => (cid, Some(suffix)),
        None => (name, None),
    };
    crate::blob::validate_blob_cid(cid).ok()?;
    match suffix {
        None => Some(EntryKind::Blob),
        Some("type") => Some(EntryKind::ContentType),
        Some(suffix) => {
            let (pid, counter) = suffix.strip_prefix("partial-")?.split_once('-')?;
            let digits = |part: &str| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit());
            (digits(pid) && digits(counter)).then_some(EntryKind::Partial)
        }
    }
}

/// Whether a cache key is safe to use as a single filename component.
///
/// A base32 CID is lowercase alphanumeric, so anything else — a separator, a
/// dot, an empty string — is rejected rather than sanitized.
fn is_safe_key(key: &str) -> bool {
    !key.is_empty()
        && key.len() <= 128
        && key
            .chars()
            .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit())
}

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

    /// A directory no other test in this process will pick.
    ///
    /// `SystemTime::now()` is only microsecond-resolution on some platforms, so
    /// two tests starting in the same microsecond got the same path — and the
    /// first to finish deleted the other's files mid-run.
    fn unique_temp_dir(prefix: &str) -> std::path::PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        std::env::temp_dir().join(format!(
            "{prefix}-{}-{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        ))
    }

    /// A ceiling written with a unit used to be dropped for the 512 MiB
    /// default; it is refused now, naming the variable. Unset keeps the
    /// default, and zero is accepted.
    #[test]
    fn the_cache_ceiling_is_a_whole_number_or_refused() {
        let with = |value: &'static str| {
            move |name: &str| (name == "ATPMCP_BLOB_CACHE_MAX_BYTES").then(|| value.to_string())
        };

        let error = BlobCache::from_lookup(with("512MiB")).expect_err("a unit is refused");
        assert!(
            matches!(
                error,
                ConfigError::NotANumber {
                    name: "ATPMCP_BLOB_CACHE_MAX_BYTES",
                    ..
                }
            ),
            "{error}"
        );

        let cache = BlobCache::from_lookup(with("0")).expect("zero is a setting");
        assert_eq!(cache.max_bytes, 0);
        assert!(!cache.is_enabled(), "and a setting that caches nothing");

        let cache = BlobCache::from_lookup(|_| None).expect("unset keeps the default");
        assert_eq!(
            cache.max_bytes,
            crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES
        );
    }

    fn temp_cache() -> (BlobCache, PathBuf) {
        let dir = unique_temp_dir("atpmcp-cache-test");
        (BlobCache::new(Some(dir.clone()), 1024 * 1024), dir)
    }

    #[tokio::test]
    async fn round_trips_a_blob_with_its_content_type() {
        let (cache, dir) = temp_cache();
        let data = b"hello blob".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();

        cache.put(&cid, &data, Some("text/plain")).await.unwrap();
        let cached = cache.get(&cid).await.expect("blob is cached");

        assert_eq!(std::fs::read(&cached.path).unwrap(), data);
        assert_eq!(cached.size, data.len() as u64);
        assert_eq!(cached.mime_type.as_deref(), Some("text/plain"));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// Verification reads the file in chunks, so an entry larger than one
    /// chunk is hashed across the boundaries and still matches its key, and
    /// one tampered past the first chunk is still caught.
    #[tokio::test]
    async fn an_entry_larger_than_one_read_verifies_across_chunks() {
        let (cache, dir) = temp_cache();
        let data: Vec<u8> = (0..200_000u32).map(|index| (index % 251) as u8).collect();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        cache.put(&cid, &data, None).await.unwrap();

        let cached = cache.get(&cid).await.expect("a multi-chunk entry verifies");
        assert_eq!(cached.size, data.len() as u64);

        let mut tampered = data.clone();
        tampered[150_000] ^= 1;
        std::fs::write(cache.path_for(&cid).unwrap(), &tampered).unwrap();
        assert!(
            cache.get(&cid).await.is_none(),
            "a change past the first chunk is caught"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn a_miss_returns_none() {
        let (cache, dir) = temp_cache();
        let cid = atproto_dasl::compute_raw_cid(b"absent").to_string();
        assert!(cache.get(&cid).await.is_none());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn a_corrupted_entry_is_rejected_and_removed() {
        let (cache, dir) = temp_cache();
        let data = b"original bytes".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        cache.put(&cid, &data, None).await.unwrap();

        // Someone edits the file on disk under the same name.
        let path = cache.path_for(&cid).unwrap();
        std::fs::write(&path, b"tampered bytes").unwrap();

        assert!(
            cache.get(&cid).await.is_none(),
            "verification must reject bytes that do not hash to the key"
        );
        assert!(!path.exists(), "a failed entry is discarded, not kept");
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn eviction_brings_the_cache_under_budget() {
        let (_, dir) = temp_cache();
        let cache = BlobCache::new(Some(dir.clone()), 2048);

        for index in 0..8u8 {
            let data = vec![index; 512];
            let cid = atproto_dasl::compute_raw_cid(&data).to_string();
            cache.put(&cid, &data, None).await.unwrap();
            // Distinct mtimes so the eviction order is deterministic.
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        let total: u64 = std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(Result::ok)
            .filter_map(|entry| entry.metadata().ok())
            .map(|metadata| metadata.len())
            .sum();
        assert!(
            total <= 2048,
            "cache should be pruned to budget, got {total}"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn a_disabled_cache_is_inert() {
        let cache = BlobCache::new(None, 0);
        assert!(!cache.is_enabled());
        assert!(cache.put("bafkrei", b"x", None).await.is_ok());
        assert!(cache.get("bafkrei").await.is_none());
    }

    #[test]
    fn unsafe_keys_never_become_paths() {
        let cache = BlobCache::new(Some(PathBuf::from("/tmp/atpmcp-test")), 1024);
        for key in ["", "../escape", "a/b", "UPPER", "with.dot", "sp ace"] {
            assert!(
                cache.path_for(key).is_none(),
                "key {key:?} must not produce a path"
            );
        }
        assert!(cache.path_for("bafkreiabc123").is_some());
    }

    #[tokio::test]
    async fn a_prepared_write_is_invisible_until_committed() {
        let (cache, dir) = temp_cache();
        let data = b"streamed bytes".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();

        let target = cache.prepare_write(&cid, None).await.unwrap().unwrap();
        assert_ne!(target.temp_path, target.final_path);
        tokio::fs::write(&target.temp_path, &data).await.unwrap();

        // Written, but not yet committed: a reader must see a miss, not a
        // half-verified hit.
        assert!(
            cache.get(&cid).await.is_none(),
            "an uncommitted write must not be visible as a cache hit"
        );
        assert!(target.temp_path.exists());
        assert!(!target.final_path.exists());

        cache
            .commit_write(&target, Some("text/plain"))
            .await
            .unwrap();

        assert!(!target.temp_path.exists(), "the temp file is renamed away");
        let cached = cache.get(&cid).await.expect("now visible");
        assert_eq!(cached.path, target.final_path);
        assert_eq!(std::fs::read(&cached.path).unwrap(), data);
        assert_eq!(cached.mime_type.as_deref(), Some("text/plain"));

        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn aborting_a_write_deletes_only_the_temp_file() {
        let (cache, dir) = temp_cache();
        let cid = atproto_dasl::compute_raw_cid(b"never committed").to_string();

        let target = cache.prepare_write(&cid, None).await.unwrap().unwrap();
        tokio::fs::write(&target.temp_path, b"never committed")
            .await
            .unwrap();
        assert!(target.temp_path.exists());

        cache.abort_write(&target).await;

        assert!(!target.temp_path.exists());
        assert!(cache.get(&cid).await.is_none());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn two_concurrent_writes_of_the_same_cid_do_not_share_a_temp_name() {
        let (cache, dir) = temp_cache();
        let cid = atproto_dasl::compute_raw_cid(b"raced content").to_string();

        let first = cache.prepare_write(&cid, None).await.unwrap().unwrap();
        let second = cache.prepare_write(&cid, None).await.unwrap().unwrap();

        assert_ne!(
            first.temp_path, second.temp_path,
            "concurrent writers of one CID must not collide on a temp name"
        );
        assert_eq!(first.final_path, second.final_path);
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A budget of zero wrote every blob and deleted it in the same commit,
    /// so a path handed out from the write was already gone. It stores
    /// nothing now, and says so.
    #[tokio::test]
    async fn a_zero_budget_stores_nothing() {
        let dir = unique_temp_dir("atpmcp-cache-zero");
        let cache = BlobCache::new(Some(dir.clone()), 0);
        assert!(!cache.is_enabled());
        assert!(cache.dir().is_none());

        let data = b"nowhere to go".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        assert!(cache.prepare_write(&cid, None).await.unwrap().is_none());
        cache.put(&cid, &data, None).await.unwrap();
        assert!(!dir.exists(), "nothing is written for a zero budget");
    }

    /// A blob known to be larger than the whole budget could only be evicted
    /// to make room for itself, so it is never let in.
    #[tokio::test]
    async fn a_write_known_to_exceed_the_budget_is_not_prepared() {
        let (_, dir) = temp_cache();
        let cache = BlobCache::new(Some(dir.clone()), 16);
        let cid = atproto_dasl::compute_raw_cid(b"sized").to_string();

        assert!(cache.prepare_write(&cid, Some(17)).await.unwrap().is_none());
        assert!(cache.prepare_write(&cid, Some(16)).await.unwrap().is_some());
        assert!(
            cache.prepare_write(&cid, None).await.unwrap().is_some(),
            "an unknown size is let in, to be checked with `admits` once written"
        );
        assert!(cache.admits(16));
        assert!(!cache.admits(17), "and a written size over budget is not");
        assert!(
            !BlobCache::new(Some(dir.clone()), 0).admits(0),
            "a disabled cache admits nothing"
        );

        let data = vec![7u8; 17];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        cache.put(&cid, &data, None).await.unwrap();
        assert!(
            !cache.path_for(&cid).unwrap().exists(),
            "a put larger than the budget is not stored"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The finding: a commit pruned the cache and could pick the entry it had
    /// just written, which for one larger than the budget it always did. It
    /// keeps that entry now, and the next commit's prune evicts it.
    #[tokio::test]
    async fn a_commit_never_evicts_its_own_entry() {
        let (_, dir) = temp_cache();
        let cache = BlobCache::new(Some(dir.clone()), 16);

        let commit = |data: Vec<u8>| {
            let cache = &cache;
            async move {
                let cid = atproto_dasl::compute_raw_cid(&data).to_string();
                // Committed past the `admits` check a fetch makes, so the
                // entry alone is over budget and only the prune's own rule
                // keeps it.
                let target = cache.prepare_write(&cid, None).await.unwrap().unwrap();
                tokio::fs::write(&target.temp_path, &data).await.unwrap();
                cache.commit_write(&target, None).await.unwrap();
                target.final_path
            }
        };

        let first = commit(vec![1u8; 32]).await;
        assert!(first.exists(), "a commit keeps what it has just written");

        let second = commit(vec![2u8; 32]).await;
        assert!(second.exists(), "and so does the next one");
        assert!(
            !first.exists(),
            "the next commit's prune still evicts an older entry over budget"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The finding: a prune counted every file in the directory but a partial
    /// write against the budget, and evicted the oldest of them, whoever
    /// wrote it. It takes only atpmcp's entries now, each blob with its
    /// content type.
    #[tokio::test]
    async fn a_prune_counts_and_evicts_only_atpmcps_entries() {
        let (_, dir) = temp_cache();
        std::fs::create_dir_all(&dir).unwrap();

        // Someone else's files, older than every entry and each larger than
        // the whole budget. `notes.type` has a content type's extension.
        let other = atproto_dasl::compute_raw_cid(b"not an entry").to_string();
        let unrelated = [
            dir.join("notes.txt"),
            dir.join("notes.type"),
            dir.join("bafkreinotacid"),
            dir.join(format!("{other}.bak")),
        ];
        for path in &unrelated {
            std::fs::write(path, vec![0u8; 4096]).unwrap();
            age(path, Duration::from_secs(2 * 24 * 60 * 60));
        }

        // Room for four entries, blob and content type, and no more.
        let entry = 512 + "text/plain".len() as u64;
        let cache = BlobCache::new(Some(dir.clone()), 4 * entry);
        let mut cids = Vec::new();
        for index in 0..5u8 {
            let data = vec![index; 512];
            let cid = atproto_dasl::compute_raw_cid(&data).to_string();
            cache.put(&cid, &data, Some("text/plain")).await.unwrap();
            // Oldest first and each distinct, so the eviction order is fixed.
            let written = Duration::from_secs(60 * (10 - u64::from(index)));
            age(&dir.join(&cid), written);
            age(&dir.join(format!("{cid}.type")), written);
            cids.push(cid);
        }

        for path in &unrelated {
            assert!(path.exists(), "{} is not atpmcp's", path.display());
        }
        assert!(
            !dir.join(&cids[0]).exists(),
            "the fifth commit evicts the oldest entry"
        );
        assert!(
            !dir.join(format!("{}.type", cids[0])).exists(),
            "and its content type with it"
        );
        for cid in &cids[1..] {
            assert!(
                cache.get(cid).await.is_some(),
                "{cid} is within the budget once only atpmcp's entries count"
            );
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    /// Only names atpmcp writes are its own, and only with a canonical blob
    /// CID in front: a file of someone else's is never taken for one.
    #[test]
    fn only_atpmcps_own_names_are_entries() {
        let cid = atproto_dasl::compute_raw_cid(b"an entry").to_string();
        assert_eq!(entry_kind(&cid), Some(EntryKind::Blob));
        assert_eq!(
            entry_kind(&format!("{cid}.type")),
            Some(EntryKind::ContentType)
        );
        assert_eq!(entry_kind(&temp_name(&cid)), Some(EntryKind::Partial));

        let record = atproto_dasl::compute_cid_for(&serde_json::json!({ "a": 1 }))
            .unwrap()
            .to_string();
        for name in [
            "notes.txt".to_string(),
            "bafkreinotacid".to_string(),
            cid.to_uppercase(),
            record.clone(),
            format!("{record}.partial-1-2"),
            format!("{cid}.txt"),
            format!("{cid}.partial"),
            format!("{cid}.partial-1"),
            format!("{cid}.partial-x-2"),
            format!("{cid}.partial-1-2.bak"),
            format!("{cid}.type.bak"),
        ] {
            assert_eq!(entry_kind(&name), None, "{name} is not atpmcp's");
        }
    }

    /// Set `path`'s modification time to `age` ago.
    fn age(path: &Path, age: Duration) {
        std::fs::File::options()
            .write(true)
            .open(path)
            .unwrap()
            .set_modified(std::time::SystemTime::now() - age)
            .unwrap();
    }

    /// The finding: nothing removed a `.partial` file left behind, since
    /// `prune` skips them as writes that might be in progress. The startup
    /// sweep removes atpmcp's own once they are a day old, and nothing else.
    #[tokio::test]
    async fn the_startup_sweep_removes_only_stale_partial_writes() {
        let (cache, dir) = temp_cache();
        let data = b"a committed entry".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        cache.put(&cid, &data, Some("text/plain")).await.unwrap();
        let two_days = Duration::from_secs(2 * 24 * 60 * 60);
        age(&dir.join(&cid), two_days);
        age(&dir.join(format!("{cid}.type")), two_days);

        let stale = dir.join(temp_name(&cid));
        let fresh = dir.join(temp_name(&cid));
        let unrelated = dir.join("notes.partial-1-2");
        for path in [&stale, &fresh, &unrelated] {
            std::fs::write(path, b"partial bytes").unwrap();
        }
        age(&stale, two_days);
        age(&unrelated, two_days);

        assert_eq!(cache.sweep().await, 1);
        assert!(!stale.exists(), "a day-old partial write is removed");
        assert!(fresh.exists(), "a younger one may still be being written");
        assert!(
            unrelated.exists(),
            "a name atpmcp never writes is left alone"
        );
        assert!(
            cache.get(&cid).await.is_some(),
            "and so is a committed entry, however old"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The finding: a budget of zero built the cache disabled, and nothing
    /// removed what an earlier, larger budget had cached, since the prune
    /// that enforces the budget runs only after a commit. The startup sweep
    /// removes atpmcp's own entries under a budget of zero, and only those.
    #[tokio::test]
    async fn a_zero_budget_sweep_clears_only_atpmcps_entries() {
        let (cache, dir) = temp_cache();
        let mut cids = Vec::new();
        for data in [b"first".to_vec(), b"second".to_vec()] {
            let cid = atproto_dasl::compute_raw_cid(&data).to_string();
            cache.put(&cid, &data, Some("text/plain")).await.unwrap();
            cids.push(cid);
        }
        let stale = dir.join(temp_name(&cids[0]));
        let fresh = dir.join(temp_name(&cids[0]));
        std::fs::write(&stale, b"partial").unwrap();
        std::fs::write(&fresh, b"partial").unwrap();
        age(&stale, Duration::from_secs(2 * 24 * 60 * 60));

        let other = atproto_dasl::compute_raw_cid(b"a directory").to_string();
        let unrelated = [
            dir.join("notes.txt"),
            dir.join("bafkreinotacid"),
            dir.join(format!("{}.bak", cids[1])),
        ];
        for path in &unrelated {
            std::fs::write(path, b"someone else's").unwrap();
        }
        std::fs::create_dir(dir.join(&other)).unwrap();

        let disabled = BlobCache::new(Some(dir.clone()), 0);
        assert_eq!(disabled.sweep().await, 5, "two blobs, two types, a partial");

        for cid in &cids {
            assert!(!dir.join(cid).exists(), "the blob {cid} is removed");
            assert!(!dir.join(format!("{cid}.type")).exists());
        }
        assert!(!stale.exists(), "and a stale partial write");
        assert!(fresh.exists(), "a fresh one may be another process's write");
        for path in &unrelated {
            assert!(path.exists(), "{} is not atpmcp's", path.display());
        }
        assert!(dir.join(&other).is_dir(), "nor is a directory");
        assert!(dir.is_dir(), "the directory itself is kept");

        assert_eq!(
            BlobCache::new(None, 0).sweep().await,
            0,
            "with no directory there is nothing to sweep"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The finding: a lowered budget took effect only at the next commit,
    /// since the startup sweep did not prune, and a server answering only from
    /// the cache never commits. The sweep prunes to the budget now, touching
    /// only atpmcp's entries.
    #[tokio::test]
    async fn the_startup_sweep_prunes_to_a_lowered_budget() {
        let (cache, dir) = temp_cache();
        let mut cids = Vec::new();
        for index in 0..4u8 {
            let data = vec![index; 512];
            let cid = atproto_dasl::compute_raw_cid(&data).to_string();
            cache.put(&cid, &data, Some("text/plain")).await.unwrap();
            // Oldest first and each distinct, so the eviction order is fixed.
            let written = Duration::from_secs(60 * (10 - u64::from(index)));
            age(&dir.join(&cid), written);
            age(&dir.join(format!("{cid}.type")), written);
            cids.push(cid);
        }
        let unrelated = dir.join("notes.txt");
        std::fs::write(&unrelated, vec![0u8; 4096]).unwrap();
        age(&unrelated, Duration::from_secs(2 * 24 * 60 * 60));

        // Room for two of the four entries.
        let entry = 512 + "text/plain".len() as u64;
        let lowered = BlobCache::new(Some(dir.clone()), 2 * entry);
        assert_eq!(lowered.sweep().await, 4, "two blobs and their types");

        for cid in &cids[..2] {
            assert!(!dir.join(cid).exists(), "the older entry {cid} is evicted");
            assert!(!dir.join(format!("{cid}.type")).exists(), "with its type");
        }
        for cid in &cids[2..] {
            assert!(
                lowered.get(cid).await.is_some(),
                "{cid} is within the lowered budget"
            );
        }
        assert!(
            unrelated.exists(),
            "a file atpmcp never writes is left alone"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn eviction_ignores_an_in_progress_write() {
        let (_, dir) = temp_cache();
        let cache = BlobCache::new(Some(dir.clone()), 512);

        // One committed blob already at the budget...
        let data = vec![1u8; 512];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        cache.put(&cid, &data, None).await.unwrap();

        // ...and a large in-progress write sitting alongside it.
        let other_cid = atproto_dasl::compute_raw_cid(b"in flight").to_string();
        let target = cache
            .prepare_write(&other_cid, None)
            .await
            .unwrap()
            .unwrap();
        tokio::fs::write(&target.temp_path, vec![2u8; 4096])
            .await
            .unwrap();

        // A prune triggered by some unrelated activity must not touch the
        // in-progress file, and must not count it toward the budget either
        // (a real cache hit above budget is still evicted only if it, alone,
        // is over budget).
        cache.prune(None).await;

        assert!(
            target.temp_path.exists(),
            "an in-progress write must survive a prune triggered elsewhere"
        );
        assert!(
            cache.get(&cid).await.is_some(),
            "the committed entry at budget should not be evicted because of an unrelated in-flight write"
        );

        let _ = std::fs::remove_dir_all(dir);
    }
}