Skip to main content

magi/
disk.rs

1//! Disk accounting: how much magi's own directories occupy, how much space is
2//! left on the volume they live on, and how the shared build cache is pruned.
3//!
4//! The whole module grew out of one incident: a machine with 951.8 GB of disk
5//! ran a handful of competitions and ended up with 6.7 GB free and a pile of
6//! multi-gigabyte `target/` directories. Every function here exists to keep
7//! that from being a discovery, and every number is substituted at a pure
8//! boundary so the policy can be tested without asking the OS anything.
9
10use std::path::{Path, PathBuf};
11
12use anyhow::{Context as _, Result};
13
14#[cfg(unix)]
15use {crate::proc::Quiet as _, anyhow::bail};
16
17/// Are `free` bytes above the floor for starting a run?
18///
19/// Pure on purpose: the threshold logic is asserted against injected numbers,
20/// and the only place the machine is actually asked anything is [`free_bytes`].
21pub fn enough_space(free: u64, min_free: u64) -> bool {
22    free >= min_free
23}
24
25/// Why a run must not start, given measured free bytes and the floor —
26/// `None` means the gate is open. Pure, so the policy is asserted directly.
27///
28/// A gate that cannot measure also closes (see [`crate::daemon::disk_gate`]):
29/// starting a run on a disk that may already be full is the incident this
30/// whole module exists to prevent.
31pub fn gate(free: u64, min_free: u64) -> Option<String> {
32    gate_in(free, min_free, "en")
33}
34
35/// Prefix of [`gate_in`]'s reason, per language. [`is_gate_reason`] matches
36/// both, so translating the text cannot stop triage's auto-requeue.
37const SHORT_EN: &str = "not enough free space to start a run:";
38const SHORT_JA: &str = "run を開始するための空き容量が不足しています:";
39/// Prefix of a resource hold after emergency writer termination.
40pub const RUNNING_PRESSURE: &str = "disk pressure while a run was writing: ";
41/// Prefix of a failed free-space measurement.
42pub const UNMEASURED_EN: &str = "could not measure free space on ";
43/// See [`UNMEASURED_EN`].
44pub const UNMEASURED_JA: &str = "空き容量を測定できませんでした: ";
45
46/// [`gate`], with the reason in `language` (`en`, or Japanese; anything else
47/// is English).
48pub fn gate_in(free: u64, min_free: u64, language: &str) -> Option<String> {
49    if enough_space(free, min_free) {
50        None
51    } else if crate::lang::is_japanese(language) {
52        Some(format!(
53            "{SHORT_JA} 空き {free} バイト、`[disk] min_free_bytes` の要求は {min_free} バイト"
54        ))
55    } else {
56        Some(format!(
57            "{SHORT_EN} {free} bytes free, \
58             {min_free} required by `[disk] min_free_bytes`"
59        ))
60    }
61}
62
63/// The reason for a measurement that failed, in `language`.
64pub fn unmeasured_in(
65    path: &std::path::Path,
66    err: &dyn std::fmt::Display,
67    language: &str,
68) -> String {
69    if crate::lang::is_japanese(language) {
70        format!(
71            "{UNMEASURED_JA}{} ({err}); ディスクゲートは測定できないまま run を開始させません",
72            path.display()
73        )
74    } else {
75        format!(
76            "{UNMEASURED_EN}{} ({err}); the disk gate refuses \
77             to let a run start blind",
78            path.display()
79        )
80    }
81}
82
83/// Is `reason` one of this module's disk-gate reasons, in either language?
84/// What triage reads back to decide a hold is disk pressure.
85pub fn is_gate_reason(reason: &str) -> bool {
86    fn numbers(text: &str, middle: &str, suffix: &str) -> bool {
87        text.strip_suffix(suffix)
88            .and_then(|s| s.split_once(middle))
89            .is_some_and(|(a, b)| {
90                !a.is_empty()
91                    && !b.is_empty()
92                    && a.bytes().all(|c| c.is_ascii_digit())
93                    && b.bytes().all(|c| c.is_ascii_digit())
94                    && matches!((a.parse::<u64>(), b.parse::<u64>()), (Ok(free), Ok(required)) if free < required)
95            })
96    }
97    reason
98        .strip_prefix(&format!("{SHORT_EN} "))
99        .is_some_and(|s| numbers(s, " bytes free, ", " required by `[disk] min_free_bytes`"))
100        || reason
101            .strip_prefix(&format!("{SHORT_JA} 空き "))
102            .is_some_and(|s| numbers(s, " バイト、`[disk] min_free_bytes` の要求は ", " バイト"))
103        || [
104            (
105                UNMEASURED_EN,
106                "); the disk gate refuses to let a run start blind",
107            ),
108            (
109                UNMEASURED_JA,
110                "); ディスクゲートは測定できないまま run を開始させません",
111            ),
112        ]
113        .iter()
114        .any(|(prefix, suffix)| {
115            reason
116                .strip_prefix(prefix)
117                .and_then(|s| s.strip_suffix(suffix))
118                .is_some_and(|s| {
119                    s.split_once(" (").is_some_and(|(path, error)| {
120                        !path.is_empty() && !error.is_empty() && !s.contains('\n')
121                    })
122                })
123        })
124}
125
126/// Is `size` past `limit`? One comparison, shared by the janitor and the
127/// health view, so both answer "is the cache over its cap" identically.
128pub fn over_limit(size: u64, limit: u64) -> bool {
129    size > limit
130}
131
132/// A cache's target size under its cap and the volume's free space: the one
133/// rule every caller of pressure collection goes through.
134///
135/// Three bands, by `free` against the admission floor `min_free` and the
136/// collection threshold `threshold`
137/// ([`Disk::reclaim_threshold`](crate::config::Disk::reclaim_threshold)):
138///
139/// * `free >= threshold`: nothing is short; the limit is the configured cap
140///   (never more than `size`, so nothing is asked to shrink).
141/// * `min_free <= free < threshold`: the limit shrinks by the deficit
142///   (`threshold - free`) but never below a **reserve**, half of `cap`
143///   (see [`pressure_reserve`]; never above the cache's own `size`, so a cache
144///   at or below its reserve is left alone). A build cache is only worth
145///   anything while some of it is left: on a disk whose free space other
146///   software controls, a rule without a reserve would empty every cache on
147///   every pass and start every build cold. The ratio is fixed on purpose,
148///   not a setting. The limit alone does not keep the reserve: the pruning
149///   routine is also given the reserve as a bound ([`prune_dir_keeping`]) and
150///   refuses any removal that would cross it.
151/// * `free < min_free`: below the admission floor work is held anyway and
152///   getting space back outranks a warm cache, so this is exactly the rule
153///   from before the threshold existed: the limit shrinks by the deficit
154///   against `min_free`, down to zero if need be.
155///
156/// A zero `cap` yields zero here; callers that treat a zero cap as "pruning
157/// off" check it before asking. The limit is an *estimate*: the caller removes
158/// that many logical bytes oldest-first and does not re-measure within the
159/// pass (see [`PressureOutcome`]).
160pub fn pressure_limit(size: u64, cap: u64, min_free: u64, threshold: u64, free: u64) -> u64 {
161    if free >= threshold {
162        return cap.min(size);
163    }
164    if free < min_free {
165        return cap.min(size.saturating_sub(min_free - free));
166    }
167    let reserve = pressure_reserve(cap, min_free, threshold, free).min(size);
168    cap.min(reserve.max(size.saturating_sub(threshold - free)))
169}
170
171/// The size a build cache must keep while free space is between the admission
172/// floor and the collection threshold: half its configured `cap`. Zero in
173/// every other band (at or above the threshold nothing is collected beyond the
174/// cap; below the floor getting space back outranks a warm cache), which is
175/// also what makes manual `magi cache prune` and the plain cap unchanged.
176pub fn pressure_reserve(cap: u64, min_free: u64, threshold: u64, free: u64) -> u64 {
177    if free >= min_free && free < threshold {
178        cap / 2
179    } else {
180        0
181    }
182}
183
184/// How a shared-cache pressure pass that ran to completion ended, as its log
185/// line says it. None of them is an error: a pass that cannot make progress
186/// says so and the service's next period tries again.
187///
188/// A pass is *estimated-deficit collection*: it measures free space once,
189/// computes the deficit against the collection threshold, and removes that
190/// many *logical* bytes oldest-first, bounded by [`pressure_limit`]. It does
191/// not re-measure in a loop. Hard links and other writers mean the space
192/// actually freed can be less (or more); the next pass measures again and
193/// continues.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub enum PressureOutcome {
196    /// Files were removed.
197    Collected,
198    /// Nothing needed removing, because the cache is at or below the reserve
199    /// it keeps while free space is below the collection threshold.
200    AtReserve,
201    /// The cache was over its limit but no file could be removed: none left,
202    /// all of them protected by the reserve, or every removal failed.
203    NothingEligible,
204    /// The cache was within its limit; nothing needed removing.
205    WithinLimit,
206}
207
208impl PressureOutcome {
209    /// The wording of the log line.
210    pub fn as_str(self) -> &'static str {
211        match self {
212            PressureOutcome::Collected => "collected",
213            PressureOutcome::AtReserve => "at reserve",
214            PressureOutcome::NothingEligible => "nothing eligible",
215            PressureOutcome::WithinLimit => "within limit",
216        }
217    }
218}
219
220/// Classify a pass: `removed` is the logical bytes it removed; `size` the
221/// cache's size going into the deletion (the pruning routine's own inventory);
222/// `limit` what [`pressure_limit`] allowed; `keep` the reserve the pruning was
223/// bounded by ([`pressure_reserve`]).
224pub fn pressure_outcome(removed: u64, size: u64, limit: u64, keep: u64) -> PressureOutcome {
225    if removed > 0 {
226        PressureOutcome::Collected
227    } else if size > limit {
228        PressureOutcome::NothingEligible
229    } else if keep > 0 && size > 0 && size <= keep {
230        PressureOutcome::AtReserve
231    } else {
232        PressureOutcome::WithinLimit
233    }
234}
235
236/// The path a rendered command sets `CARGO_TARGET_DIR=` to, if any.
237///
238/// magi never computes the cache path itself. The operator's `magi.toml` is
239/// the only place that knows it, and by the time a [`crate::config::Config`]
240/// exists that template has been rendered — so the concrete path is read back
241/// out of the verify commands (`CARGO_TARGET_DIR={{ vars.cache }}/magi-target
242/// cargo …` becomes `C:\…\Temp\magi-target`). This is what lets the janitor
243/// prune exactly the directory the gate and the seats build into. `None` when
244/// no command sets the variable: there is then no cache to aggregate or prune,
245/// and agents build wherever the repository's own defaults put them.
246///
247/// The value may be quoted with `'` or `"`; both are understood, as is no
248/// quoting (up to the next whitespace).
249pub fn extract_cargo_target_dir(command: &str) -> Option<PathBuf> {
250    const KEY: &str = "CARGO_TARGET_DIR=";
251    let rest = command.split_once(KEY)?.1.trim_start();
252    let value = if let Some(s) = rest.strip_prefix('\'') {
253        s.split('\'').next().unwrap_or("")
254    } else if let Some(s) = rest.strip_prefix('"') {
255        s.split('"').next().unwrap_or("")
256    } else {
257        let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
258        &rest[..end]
259    };
260    if value.is_empty() {
261        None
262    } else {
263        Some(PathBuf::from(value))
264    }
265}
266
267/// Free bytes on the volume containing `path`.
268///
269/// Unix parses `df`; Windows asks the volume directly through kernel32, without
270/// starting a subprocess on the synchronous health-request path.
271pub fn free_bytes(path: &Path) -> Result<u64> {
272    free_bytes_by_os(path)
273}
274
275/// Free bytes on the volume containing `path`.
276#[cfg(unix)]
277fn free_bytes_by_os(path: &Path) -> Result<u64> {
278    let out = std::process::Command::new("df")
279        .args(["-k", "-P"])
280        .arg(path)
281        .quiet()
282        .output()
283        .with_context(|| format!("run `df` for {}", path.display()))?;
284    if !out.status.success() {
285        bail!(
286            "`df` failed: {}",
287            String::from_utf8_lossy(&out.stderr).trim()
288        );
289    }
290    let text = String::from_utf8_lossy(&out.stdout);
291    text.lines()
292        .skip(1)
293        .find_map(parse_df_available)
294        .with_context(|| format!("parse `df` output for {}", path.display()))
295}
296
297/// Free bytes on the volume containing `path`.
298#[cfg(windows)]
299fn free_bytes_by_os(path: &Path) -> Result<u64> {
300    let abs = std::path::absolute(path)
301        .with_context(|| format!("absolute path for {}", path.display()))?;
302    let root = volume_root(&abs)
303        .with_context(|| format!("no volume root in {} to measure", abs.display()))?;
304    windows_free_bytes(Path::new(&root))
305}
306
307pub(crate) fn managed_free_bytes(path: &Path) -> Result<u64> {
308    #[cfg(windows)]
309    return windows_free_bytes(path);
310    #[cfg(not(windows))]
311    free_bytes(path)
312}
313
314#[cfg(windows)]
315fn windows_free_bytes(path: &Path) -> Result<u64> {
316    use std::os::windows::ffi::OsStrExt as _;
317    #[link(name = "kernel32")]
318    unsafe extern "system" {
319        fn GetDiskFreeSpaceExW(
320            directory: *const u16,
321            available: *mut u64,
322            total: *mut u64,
323            free: *mut u64,
324        ) -> i32;
325    }
326    let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
327    let mut available = 0_u64;
328    // SAFETY: wide is a live NUL-terminated UTF-16 root, available is writable,
329    // and the optional totals are null. The API retains none of these pointers.
330    if unsafe {
331        GetDiskFreeSpaceExW(
332            wide.as_ptr(),
333            &mut available,
334            std::ptr::null_mut(),
335            std::ptr::null_mut(),
336        )
337    } == 0
338    {
339        let error = std::io::Error::last_os_error();
340        return Err(error).with_context(|| format!("query free bytes for {}", path.display()));
341    }
342    // Caller-available bytes, not total free bytes: preserve quota semantics.
343    Ok(available)
344}
345
346/// One `df -k -P` data row: `Filesystem 1024-blocks Used Available …`.
347///
348/// The value is 1024-byte blocks, so the parse returns bytes.
349pub fn parse_df_available(line: &str) -> Option<u64> {
350    let mut fields = line.split_whitespace();
351    fields.next()?; // filesystem
352    fields.next()?; // 1024-blocks
353    fields.next()?; // used
354    let blocks: u64 = fields.next()?.parse().ok()?;
355    Some(blocks.saturating_mul(1024))
356}
357
358/// The drive root used for querying an absolute Windows path:
359/// `C:\`, never `C:\Users\...` and never a verbatim `\\?\C:\...`.
360///
361/// Pure and platform-independent so the verbatim form - which is what the
362/// queue stores and what closed the disk gate on every task - is asserted
363/// without a Windows runner. `None` when there is no drive letter to name:
364/// UNC shares remain unsupported, rather than inventing a drive volume.
365pub fn volume_root(path: &Path) -> Option<String> {
366    let text = path.to_str()?;
367    // Verbatim (`\\?\C:\x`) and verbatim-UNC (`\\?\UNC\server\share`) prefixes.
368    let bare = text
369        .strip_prefix(r"\\?\")
370        .or_else(|| text.strip_prefix("//?/"))
371        .unwrap_or(text);
372    let mut chars = bare.chars();
373    let letter = chars.next()?;
374    if !letter.is_ascii_alphabetic() || chars.next()? != ':' {
375        return None;
376    }
377    Some(format!(r"{letter}:\"))
378}
379
380/// Total bytes under `path`, without following symlinks.
381///
382/// A symlinked directory counts as the link itself, not its contents: mutable
383/// worktrees are real directories, and following an accidental link into a
384/// clone of the repository would count the same bytes twice.
385pub fn dir_size(path: &Path) -> u64 {
386    let Ok(meta) = std::fs::symlink_metadata(path) else {
387        return 0;
388    };
389    if meta.is_file() {
390        return meta.len();
391    }
392    if !meta.is_dir() {
393        return 0;
394    }
395    let mut total = 0u64;
396    let mut stack = vec![path.to_path_buf()];
397    while let Some(dir) = stack.pop() {
398        let Ok(rd) = std::fs::read_dir(&dir) else {
399            continue;
400        };
401        for entry in rd.flatten() {
402            // `DirEntry::metadata` reports the entry itself, so a symlink is
403            // never traversed.
404            let Ok(meta) = entry.metadata() else {
405                continue;
406            };
407            if meta.is_dir() {
408                stack.push(entry.path());
409            } else if meta.is_file() {
410                total += meta.len();
411            }
412        }
413    }
414    total
415}
416
417/// What a prune removed, for the report.
418#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
419pub struct Prune {
420    /// Bytes actually freed.
421    pub freed: u64,
422    /// Files deleted.
423    pub files: usize,
424    /// Bytes still under the directory afterwards.
425    pub remaining: u64,
426}
427
428/// What [`plan_prune`] would remove, without removing it.
429///
430/// Oldest-first, the same order [`prune_dir`] deletes in — a caller previewing
431/// the plan (`magi cache prune --dry-run`) must see exactly what an immediate
432/// `prune_dir` call would do, not an approximation of it.
433#[derive(Debug, Clone, Default, PartialEq, Eq)]
434pub struct PrunePlan {
435    /// Files this plan would delete, oldest-first, paired with their size.
436    pub files: Vec<(PathBuf, u64)>,
437    /// Bytes this plan would free, assuming every listed file is removable.
438    pub freed: u64,
439    /// Bytes that would remain under the directory once the plan applies
440    /// cleanly.
441    pub remaining: u64,
442}
443
444/// The selection [`prune_dir`] would act on *if every one of these deletions
445/// succeeds*, computed without touching disk.
446///
447/// Read-only on purpose: a preview must never take the cache's lease (see
448/// `cache::maintenance_prune`'s doc) — it does not write anything, so it
449/// cannot race a build the way a real prune would, and a caller only wanting
450/// to show an operator a plan should not have to wait out contention to do
451/// it. This is necessarily an idealized selection, not a prediction of every
452/// file [`prune_dir`] will end up touching: a build finishing between the
453/// preview and a real prune can change what gets deleted, and so can a single
454/// locked file on the real pass, which - unlike this preview - has to keep
455/// reaching past its own plan for another (newer) file when an older one it
456/// counted on turns out to be unremovable. The CLI surface that shows this
457/// preview says so.
458#[must_use]
459pub fn plan_prune(dir: &Path, limit: u64) -> PrunePlan {
460    let Some(tree) = Tree::of(dir) else {
461        return PrunePlan::default();
462    };
463    let mut total = tree.total;
464    if !over_limit(total, limit) {
465        return PrunePlan {
466            files: Vec::new(),
467            freed: 0,
468            remaining: total,
469        };
470    }
471    let mut freed = 0u64;
472    let mut files = Vec::new();
473    for (_, size, path) in &tree.files {
474        if !over_limit(total, limit) {
475            break;
476        }
477        total = total.saturating_sub(*size);
478        freed += *size;
479        files.push((path.clone(), *size));
480    }
481    PrunePlan {
482        files,
483        freed,
484        remaining: total,
485    }
486}
487
488/// Delete files under `dir` oldest-first until its size is at or below `limit`.
489///
490/// The comparison is [`over_limit`], so a directory exactly at the cap is left
491/// alone. Oldest-first keeps the newest generation of artifacts — the one the
492/// next run reuses — and sheds the generations that only compile history. A
493/// deleted file costs the next build a rebuild of that one unit; deleting the
494/// whole directory would cost it everything, which is precisely the work
495/// [`prune_dir`] is keeping for it.
496///
497/// Empty directories left behind are swept depth-first, so cargo's deep
498/// `fingerprint`/`deps` trees do not outlive the files that made them.
499///
500/// Nothing is deleted when the directory is missing.
501pub fn prune_dir(dir: &Path, limit: u64) -> Result<Prune> {
502    prune_dir_keeping(dir, limit, 0)
503}
504
505/// [`prune_dir`] that never takes the directory below `keep` bytes.
506///
507/// Pressure collection between the admission floor and the collection
508/// threshold keeps a reserve of a build cache ([`pressure_reserve`]): a limit
509/// alone cannot do that, because files are removed whole and one large
510/// artifact can be larger than `size - reserve`. A file whose removal would
511/// leave less than `keep` is *skipped*, and the walk goes on to later (newer)
512/// candidates while the directory is still over `limit`. The inventory is the
513/// one this call takes itself, under whatever maintenance locks the caller
514/// holds. `keep == 0` is exactly [`prune_dir`].
515pub fn prune_dir_keeping(dir: &Path, limit: u64, keep: u64) -> Result<Prune> {
516    let Some(tree) = Tree::of(dir) else {
517        return Ok(Prune {
518            freed: 0,
519            files: 0,
520            remaining: 0,
521        });
522    };
523    let mut total = tree.total;
524    if !over_limit(total, limit) {
525        return Ok(Prune {
526            freed: 0,
527            files: 0,
528            remaining: total,
529        });
530    }
531    let mut freed = 0u64;
532    let mut removed = 0usize;
533    // Deliberately walks every file in `tree`, not a fixed plan computed up
534    // front: `total` only drops on a successful removal, so a file that is
535    // being read elsewhere (a concurrent build, a snapshot) and fails to
536    // delete on Windows costs this pass nothing but that one file - it is
537    // skipped, and the loop keeps reaching for the next-oldest file until the
538    // real, achieved total is at or below `limit` or there is nothing left to
539    // try. A version of this that instead deleted only a pre-computed
540    // selection would stop short of the cap on the first locked file, every
541    // pass, on exactly the machines where locked files are common.
542    for (_, size, path) in &tree.files {
543        if !over_limit(total, limit) {
544            break;
545        }
546        if total.saturating_sub(*size) < keep {
547            continue;
548        }
549        if std::fs::remove_file(path).is_ok() {
550            total = total.saturating_sub(*size);
551            freed += *size;
552            removed += 1;
553        }
554    }
555    strip_empty_dirs(&tree.dirs);
556    Ok(Prune {
557        freed,
558        files: removed,
559        remaining: total,
560    })
561}
562
563/// The one file a prune never selects, when it sits directly in the pruned root.
564///
565/// cargo writes `CACHEDIR.TAG` once, when it creates a target directory, so in
566/// a long-lived cache it is the oldest file and an oldest-first prune reaches it
567/// first. Without it `cargo clean -p` refuses ("missing or invalid
568/// `CACHEDIR.TAG` file"). The tag belongs to the cargo that made it, not to the
569/// prune. It still counts toward the directory's size; a same-named file in a
570/// subdirectory is an ordinary candidate.
571const PRESERVED_AT_ROOT: &str = "CACHEDIR.TAG";
572
573/// Files and directories under one root, walked up-front.
574///
575/// `files` are the deletion candidates; `total` also counts what is preserved.
576struct Tree {
577    total: u64,
578    files: Vec<(u128, u64, PathBuf)>,
579    dirs: Vec<(usize, PathBuf)>,
580}
581
582impl Tree {
583    /// Walk `dir`, collecting files (mtime-nanoseconds, size, path) and
584    /// directories (depth, path). `None` when the directory does not exist.
585    fn of(dir: &Path) -> Option<Tree> {
586        if dir.symlink_metadata().ok()?.is_dir() {
587            Some(Tree::from_dir(dir))
588        } else {
589            None
590        }
591    }
592
593    fn from_dir(dir: &Path) -> Tree {
594        let mut total = 0u64;
595        let mut files = Vec::new();
596        let mut dirs = Vec::new();
597        // Depth-first so directories are recorded before their contents; the
598        // dir list is then sorted by descending depth for the sweep.
599        let mut stack: Vec<(usize, PathBuf)> = vec![(0, dir.to_path_buf())];
600        while let Some((depth, d)) = stack.pop() {
601            let Ok(rd) = std::fs::read_dir(&d) else {
602                continue;
603            };
604            for entry in rd.flatten() {
605                let path = entry.path();
606                let Ok(meta) = path.symlink_metadata() else {
607                    continue;
608                };
609                #[cfg(windows)]
610                {
611                    use std::os::windows::fs::MetadataExt as _;
612                    if meta.file_attributes() & 0x400 != 0 {
613                        continue;
614                    }
615                }
616                if meta.is_dir() {
617                    dirs.push((depth + 1, path.clone()));
618                    stack.push((depth + 1, path));
619                } else if meta.is_file() {
620                    let size = meta.len();
621                    total += size;
622                    if depth == 0
623                        && (entry.file_name() == PRESERVED_AT_ROOT
624                            || entry.file_name() == crate::build_target::TARGET_PROOF)
625                    {
626                        continue;
627                    }
628                    let mtime = meta
629                        .modified()
630                        .ok()
631                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
632                        .map(|d| d.as_nanos())
633                        .unwrap_or(0);
634                    files.push((mtime, size, path));
635                }
636            }
637        }
638        // Oldest first, and on a tie the larger file: a whole generation of
639        // cargo artifacts is written within one filesystem timestamp tick, so
640        // mtime alone leaves the order to `read_dir` and the sort's
641        // instability - the same cache pruned twice would shed different
642        // files, and a test over two same-tick files passed on one platform
643        // and failed on another. Larger-first also reaches the cap in fewer
644        // deletions, which is fewer rebuilt units for the next run.
645        files.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
646        Tree { total, files, dirs }
647    }
648}
649
650/// Remove empty directories, deepest first, never the root itself.
651fn strip_empty_dirs(dirs: &[(usize, PathBuf)]) {
652    let mut by_depth: Vec<&PathBuf> = dirs.iter().map(|(_, d)| d).collect();
653    by_depth.sort_unstable_by_key(|d| std::cmp::Reverse(d.iter().count()));
654    for d in by_depth {
655        let _ = std::fs::remove_dir(d);
656    }
657}
658
659#[cfg(test)]
660mod tests {
661    #[test]
662    fn gate_reasons_follow_the_language_and_stay_recognisable() {
663        let en = gate_in(1, 10, "en").unwrap();
664        let ja = gate_in(1, 10, "日本語").unwrap();
665        assert_eq!(gate_in(1, 10, "fr").unwrap(), en);
666        assert_eq!(en, gate(1, 10).unwrap());
667        assert!(ja.starts_with("run を開始"), "{ja}");
668        assert!(is_gate_reason(&en) && is_gate_reason(&ja));
669        let p = std::path::Path::new("/x");
670        let m_ja = unmeasured_in(p, &"boom", "ja");
671        assert!(m_ja.contains("測定できませんでした") && is_gate_reason(&m_ja));
672        assert!(is_gate_reason(&unmeasured_in(p, &"boom", "en")));
673        assert!(!is_gate_reason("something else"));
674    }
675
676    #[test]
677    fn disk_wait_legacy_reasons_require_the_complete_gate_format() {
678        let observed = "run を開始するための空き容量が不足しています: 空き 1477050368 バイト、`[disk] min_free_bytes` の要求は 3221225472 バイト";
679        assert!(is_gate_reason(observed));
680        assert!(is_gate_reason(
681            &gate_in(1477050368, 3221225472, "en").unwrap()
682        ));
683        for ambiguous in [
684            format!("{observed}\nowner: hold"),
685            format!("{SHORT_EN} inspect manually"),
686            format!("{RUNNING_PRESSURE}unknown"),
687            format!("{UNMEASURED_EN}/tmp (error)"),
688        ] {
689            assert!(!is_gate_reason(&ambiguous), "{ambiguous}");
690        }
691    }
692
693    use super::*;
694    use std::fs;
695
696    #[test]
697    fn the_free_space_predicate_is_the_boundary() {
698        assert!(enough_space(100, 100));
699        assert!(enough_space(101, 100));
700        assert!(!enough_space(99, 100));
701        // A zero floor disables the gate: the operator opted out.
702        assert!(enough_space(0, 0));
703    }
704
705    #[test]
706    fn the_gate_text_conveys_both_numbers_and_opens_with_room() {
707        assert_eq!(
708            gate(9, 10).expect("closed"),
709            "not enough free space to start a run: 9 bytes free, 10 required by `[disk] min_free_bytes`"
710        );
711        assert_eq!(gate(10, 10), None, "exactly at the floor is open");
712        assert_eq!(gate(10_000, 0), None, "a zero floor is an opt-out");
713    }
714
715    #[test]
716    fn over_limit_uses_strict_greater_than() {
717        assert!(over_limit(11, 10));
718        assert!(!over_limit(10, 10));
719        assert!(!over_limit(9, 10));
720    }
721
722    #[test]
723    fn df_row_parses_1024_blocks_into_bytes() {
724        let row = "/dev/sda1 976762584 808522388 168240196 83% /home";
725        assert_eq!(parse_df_available(row), Some(168_240_196 * 1024));
726        assert_eq!(parse_df_available("garbage"), None);
727        assert_eq!(parse_df_available("a b c x"), None);
728    }
729
730    /// The volume query takes a drive root; the queue hands out verbatim paths.
731    #[test]
732    fn the_volume_root_is_a_drive_not_the_path_it_came_from() {
733        // The form that closed the gate on every queued task: the queue
734        // records the repo as `\\?\C:\...`.
735        assert_eq!(
736            volume_root(Path::new(
737                r"\\?\C:\Users\yukimemi\src\github.com\yukimemi\magi"
738            )),
739            Some(r"C:\".to_owned())
740        );
741        assert_eq!(
742            volume_root(Path::new(r"C:\Users\yukimemi")),
743            Some(r"C:\".to_owned())
744        );
745        assert_eq!(volume_root(Path::new(r"D:\")), Some(r"D:\".to_owned()));
746        // Forward slashes reach magi from configs written by hand.
747        assert_eq!(
748            volume_root(Path::new("C:/Users/yukimemi/src")),
749            Some(r"C:\".to_owned())
750        );
751        // No drive to name: UNC shares are unsupported, and a POSIX path has no
752        // drive volume. The caller has to report that it cannot measure.
753        assert_eq!(volume_root(Path::new(r"\\server\share\dir")), None);
754        assert_eq!(volume_root(Path::new(r"\\?\UNC\server\share")), None);
755        assert_eq!(volume_root(Path::new("/home/yukimemi")), None);
756    }
757
758    #[test]
759    fn the_cache_dir_is_read_back_out_of_a_rendered_command() {
760        let cmd = r"CARGO_TARGET_DIR=C:\Users\me\Temp\magi-target cargo make check";
761        assert_eq!(
762            extract_cargo_target_dir(cmd),
763            Some(PathBuf::from(r"C:\Users\me\Temp\magi-target"))
764        );
765        // Quoted forms survive spaces; a config with none stays None.
766        assert_eq!(
767            extract_cargo_target_dir(r"CARGO_TARGET_DIR='/tmp/a b' cargo test"),
768            Some(PathBuf::from("/tmp/a b"))
769        );
770        assert_eq!(
771            extract_cargo_target_dir(r#"CARGO_TARGET_DIR="/tmp/qq" cargo test"#),
772            Some(PathBuf::from("/tmp/qq"))
773        );
774        assert_eq!(extract_cargo_target_dir("cargo make check"), None);
775        assert_eq!(extract_cargo_target_dir("CARGO_TARGET_DIR="), None);
776        // Second occurrence is irrelevant: the first is what the build used
777        // (a command's environment applies once).
778        let two = "CARGO_TARGET_DIR=/first and CARGO_TARGET_DIR=/second cargo x";
779        assert_eq!(extract_cargo_target_dir(two), Some(PathBuf::from("/first")));
780    }
781
782    #[test]
783    fn dir_size_is_zero_for_missing_and_counts_files_without_following_links() {
784        let t = tempfile::TempDir::new().expect("temp");
785        assert_eq!(dir_size(&t.path().join("nope")), 0);
786        fs::write(t.path().join("a"), b"12345").expect("write");
787        fs::create_dir(t.path().join("sub")).expect("dir");
788        fs::write(t.path().join("sub").join("b"), b"678").expect("write");
789        assert_eq!(dir_size(t.path()), 8);
790        #[cfg(unix)]
791        {
792            std::os::unix::fs::symlink(t.path().join("sub"), t.path().join("link"))
793                .expect("symlink");
794            assert_eq!(dir_size(t.path()), 8, "a link is counted as a link");
795        }
796    }
797
798    #[test]
799    fn prune_deletes_oldest_first_until_the_cap_is_met() {
800        let t = tempfile::TempDir::new().expect("temp");
801        let old = t.path().join("old");
802        fs::write(&old, b"yyyy").expect("write");
803        // Give the older file a measurably older mtime; a second is past the
804        // granularity of the filesystems magi runs on.
805        std::thread::sleep(std::time::Duration::from_millis(1_200));
806        fs::write(t.path().join("new"), b"xxxxx").expect("write");
807
808        // Cap above the total: nothing moves.
809        let keep = prune_dir(t.path(), 9).expect("prune");
810        assert_eq!(
811            keep,
812            Prune {
813                freed: 0,
814                files: 0,
815                remaining: 9
816            }
817        );
818
819        // Cap below: the oldest file goes, the new one stays.
820        let pruned = prune_dir(t.path(), 6).expect("prune");
821        assert!(pruned.freed > 0);
822        assert_eq!(pruned.files, 1);
823        assert_eq!(pruned.remaining, 5);
824        assert!(!old.exists(), "the older file is the one shed");
825        assert!(t.path().join("new").exists());
826    }
827
828    #[test]
829    fn plan_prune_selects_what_prune_dir_would_delete_without_deleting_it() {
830        let t = tempfile::TempDir::new().expect("temp");
831        let old = t.path().join("old");
832        fs::write(&old, b"yyyy").expect("write");
833        std::thread::sleep(std::time::Duration::from_millis(1_200));
834        fs::write(t.path().join("new"), b"xxxxx").expect("write");
835
836        let plan = plan_prune(t.path(), 6);
837        assert_eq!(plan.files, vec![(old.clone(), 4)]);
838        assert_eq!(plan.freed, 4);
839        assert_eq!(plan.remaining, 5);
840        assert!(old.exists(), "a plan never deletes anything");
841        assert!(t.path().join("new").exists());
842
843        // Applying `prune_dir` afterwards removes exactly what the plan named.
844        let pruned = prune_dir(t.path(), 6).expect("prune");
845        assert_eq!(pruned.freed, plan.freed);
846        assert_eq!(pruned.remaining, plan.remaining);
847        assert!(!old.exists());
848    }
849
850    #[test]
851    fn a_root_cachedir_tag_survives_even_as_the_oldest_file() {
852        // cargo writes the tag once, so in a long-lived cache it is the oldest
853        // file and used to be the first thing an over-cap prune deleted.
854        let t = tempfile::TempDir::new().expect("temp");
855        let tag = t.path().join("CACHEDIR.TAG");
856        fs::write(&tag, b"Signature: x").expect("write");
857        let f = fs::File::options().write(true).open(&tag).expect("open");
858        f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1))
859            .expect("mtime");
860        drop(f);
861        fs::write(t.path().join("a"), b"aaaa").expect("write");
862        fs::create_dir(t.path().join("sub")).expect("mkdir");
863        // A same-named file below the root is an ordinary candidate.
864        let nested = t.path().join("sub").join("CACHEDIR.TAG");
865        fs::write(&nested, b"nn").expect("write");
866
867        let limit = 12; // exactly the tag: every other file must go
868        let plan = plan_prune(t.path(), limit);
869        assert!(plan.files.iter().all(|(p, _)| p != &tag));
870        assert!(plan.remaining <= limit);
871
872        let pruned = prune_dir(t.path(), limit).expect("prune");
873        assert!(tag.exists(), "the root tag is never pruned");
874        assert!(pruned.remaining <= limit);
875        assert_eq!(pruned.freed, plan.freed);
876        assert_eq!(pruned.remaining, plan.remaining);
877        assert!(!nested.exists());
878    }
879
880    #[test]
881    fn plan_prune_is_empty_under_the_cap_and_for_a_missing_dir() {
882        let t = tempfile::TempDir::new().expect("temp");
883        fs::write(t.path().join("a"), b"12345").expect("write");
884        let plan = plan_prune(t.path(), 100);
885        assert_eq!(
886            plan,
887            PrunePlan {
888                files: Vec::new(),
889                freed: 0,
890                remaining: 5,
891            }
892        );
893
894        assert_eq!(
895            plan_prune(&t.path().join("absent"), 0),
896            PrunePlan::default()
897        );
898    }
899
900    /// A file `prune_dir` cannot delete - locked by a concurrent reader on
901    /// Windows, the exact scenario the function's own doc calls out - must
902    /// not make the pass stop short of the cap. The achieved total only
903    /// drops on a successful removal, so the loop has to keep reaching for
904    /// newer files until *that* total clears `limit`, not stop once a
905    /// precomputed selection runs out.
906    #[cfg(windows)]
907    #[test]
908    fn prune_keeps_reaching_past_an_undeletable_file_to_still_reach_the_cap() {
909        use std::os::windows::fs::OpenOptionsExt as _;
910
911        let t = tempfile::TempDir::new().expect("temp");
912        let old = t.path().join("old");
913        fs::write(&old, b"yyyy").expect("write");
914        std::thread::sleep(std::time::Duration::from_millis(1_200));
915        let mid = t.path().join("mid");
916        fs::write(&mid, b"zzzz").expect("write");
917        std::thread::sleep(std::time::Duration::from_millis(1_200));
918        let new = t.path().join("new");
919        fs::write(&new, b"xxxxx").expect("write");
920
921        // A share mode of 0 denies every other handle, including a delete -
922        // standing in for a file a concurrent build still has open, which is
923        // exactly the case `prune_dir`'s own doc calls out.
924        let lock = std::fs::OpenOptions::new()
925            .read(true)
926            .share_mode(0)
927            .open(&old)
928            .expect("lock the old file exclusively");
929
930        let pruned = prune_dir(t.path(), 8).expect("prune");
931        drop(lock);
932
933        assert!(old.exists(), "the locked file could not be deleted");
934        assert!(!mid.exists(), "the next-oldest file was tried and removed");
935        assert!(
936            !new.exists(),
937            "pruning kept reaching for newer files until the cap was actually met, \
938             not just until a fixed selection ran out"
939        );
940        assert!(
941            pruned.remaining <= 8,
942            "the achieved total must reach the cap: {pruned:?}"
943        );
944    }
945
946    #[test]
947    fn prune_leaves_a_missing_dir_alone() {
948        let t = tempfile::TempDir::new().expect("temp");
949        let out = prune_dir(&t.path().join("absent"), 1).expect("prune");
950        assert_eq!(out, Prune::default());
951    }
952
953    #[test]
954    fn prune_sweeps_directories_the_files_leave_empty() {
955        let t = tempfile::TempDir::new().expect("temp");
956        let deep = t.path().join("a").join("b").join("c");
957        fs::create_dir_all(&deep).expect("dirs");
958        fs::write(deep.join("f"), b"1234").expect("write");
959        let out = prune_dir(t.path(), 0).expect("prune");
960        assert_eq!(out.files, 1);
961        assert_eq!(out.remaining, 0);
962        assert!(!t.path().join("a").exists(), "empty chain swept");
963    }
964}
965
966#[cfg(test)]
967mod pressure_tests {
968    use super::{
969        PressureOutcome as O, Prune, dir_size, pressure_limit, pressure_outcome, pressure_reserve,
970        prune_dir, prune_dir_keeping,
971    };
972    use std::fs;
973    use std::path::Path;
974    use std::time::{Duration, SystemTime};
975
976    #[test]
977    fn a_threshold_equal_to_the_floor_is_the_rule_from_before_the_threshold() {
978        assert_eq!(pressure_limit(100, 200, 80, 80, 30), 50);
979        assert_eq!(pressure_limit(100, 200, 80, 80, 100), 100);
980        assert_eq!(pressure_limit(100, 200, 800, 800, 0), 0);
981        assert_eq!(pressure_limit(100, 50, 0, 0, 0), 50);
982        // Free at the floor with threshold == floor: no deficit, no reserve.
983        assert_eq!(pressure_limit(100, 200, 10, 10, 10), 100);
984    }
985
986    #[test]
987    fn above_the_threshold_the_limit_is_the_cap_or_the_size() {
988        // floor 8, threshold 16, cap 10 (units: GiB)
989        assert_eq!(pressure_limit(9, 10, 8, 16, 16), 9);
990        assert_eq!(pressure_limit(9, 10, 8, 16, 500), 9);
991        assert_eq!(
992            pressure_limit(12, 10, 8, 16, 16),
993            10,
994            "over the cap still shrinks"
995        );
996    }
997
998    #[test]
999    fn between_the_floor_and_the_threshold_a_cache_keeps_half_its_cap() {
1000        // floor 8, threshold 16, cap 10, so the reserve is 5.
1001        // A cache of 4 is below its reserve: untouched (limit == size).
1002        assert_eq!(pressure_limit(4, 10, 8, 16, 10), 4);
1003        // 9 with free 10: the deficit would leave 3, the reserve keeps 5.
1004        assert_eq!(pressure_limit(9, 10, 8, 16, 10), 5);
1005        // 9 with free 15: a deficit of 1 leaves 8, above the reserve.
1006        assert_eq!(pressure_limit(9, 10, 8, 16, 15), 8);
1007        // Exactly at the floor is still this band.
1008        assert_eq!(pressure_limit(9, 10, 8, 16, 8), 5);
1009        // The cap still bounds from above, and an odd cap rounds the reserve down.
1010        assert_eq!(pressure_limit(100, 60, 10, 20, 11), 60);
1011        assert_eq!(pressure_limit(9, 11, 8, 16, 8), 5);
1012        // The reserve is a fixed ratio of the cap: it does not move with size.
1013        assert_eq!(
1014            pressure_limit(40, 10, 8, 16, 8),
1015            10,
1016            "cap bounds the shrink"
1017        );
1018    }
1019
1020    #[test]
1021    fn below_the_floor_the_rule_is_the_one_from_before_the_threshold() {
1022        // floor 8, threshold 16, cap 10: size 9, free 7 -> one short of the floor.
1023        assert_eq!(pressure_limit(9, 10, 8, 16, 7), 8);
1024        assert_eq!(pressure_limit(9, 10, 8, 16, 0), 1);
1025        // No reserve here: a deficit larger than the cache empties it.
1026        assert_eq!(pressure_limit(4, 10, 8, 16, 0), 0);
1027        assert_eq!(pressure_limit(5, 200, 20, 20, 0), 0);
1028    }
1029
1030    #[test]
1031    fn a_zero_cap_stays_zero_in_every_band() {
1032        for free in [0, 7, 8, 10, 15, 16, 500] {
1033            assert_eq!(pressure_limit(100, 0, 8, 16, free), 0, "free {free}");
1034        }
1035    }
1036
1037    #[test]
1038    fn repeated_passes_with_free_space_pinned_converge() {
1039        // Free space stays at 10 whatever is removed (another program owns the
1040        // disk). The first pass takes the cache to its reserve, the second
1041        // removes nothing.
1042        let mut size = 9;
1043        let first = pressure_limit(size, 10, 8, 16, 10);
1044        assert_eq!(first, 5);
1045        size = size.min(first);
1046        let second = pressure_limit(size, 10, 8, 16, 10);
1047        assert_eq!(second, size, "nothing left to remove");
1048    }
1049
1050    #[test]
1051    fn the_reserve_exists_only_between_the_floor_and_the_threshold() {
1052        // floor 8, threshold 16, cap 10
1053        assert_eq!(pressure_reserve(10, 8, 16, 7), 0, "below the floor");
1054        assert_eq!(pressure_reserve(10, 8, 16, 8), 5);
1055        assert_eq!(pressure_reserve(10, 8, 16, 15), 5);
1056        assert_eq!(pressure_reserve(10, 8, 16, 16), 0, "at the threshold");
1057        assert_eq!(pressure_reserve(11, 8, 16, 10), 5, "odd caps round down");
1058        assert_eq!(
1059            pressure_reserve(0, 8, 16, 10),
1060            0,
1061            "a zero cap keeps nothing"
1062        );
1063        // The collection threshold equal to the floor leaves no band at all.
1064        assert_eq!(pressure_reserve(10, 8, 8, 8), 0);
1065    }
1066
1067    #[test]
1068    fn the_limit_handles_a_small_cap_a_disabled_floor_and_a_cache_at_its_reserve() {
1069        // Cap 4 (reserve 2) is smaller than the deficit: the cap bounds it.
1070        assert_eq!(pressure_limit(4, 4, 8, 16, 8), 2);
1071        // Admission disabled (floor 0) with a positive threshold still collects.
1072        assert_eq!(pressure_limit(9, 10, 0, 16, 0), 5);
1073        // Size exactly at the reserve is left alone.
1074        assert_eq!(pressure_limit(5, 10, 8, 16, 10), 5);
1075    }
1076
1077    #[test]
1078    fn the_outcome_names_why_a_pass_removed_nothing() {
1079        // (removed, size, limit, keep)
1080        assert_eq!(pressure_outcome(4, 9, 5, 5), O::Collected);
1081        assert_eq!(pressure_outcome(2, 12, 10, 0), O::Collected);
1082        // Within the limit with no reserve involved (above the threshold).
1083        assert_eq!(pressure_outcome(0, 9, 9, 0), O::WithinLimit);
1084        assert_eq!(pressure_outcome(0, 0, 0, 0), O::WithinLimit);
1085        // At or below the reserve the band keeps.
1086        assert_eq!(pressure_outcome(0, 4, 4, 5), O::AtReserve);
1087        assert_eq!(pressure_outcome(0, 5, 5, 5), O::AtReserve);
1088        // Over the limit and everything is protected by the reserve (one 6 GiB
1089        // artifact, reserve 5): nothing eligible, not "at reserve".
1090        assert_eq!(pressure_outcome(0, 6, 5, 5), O::NothingEligible);
1091        // Over the cap, above the collection threshold, nothing removable.
1092        let limit = pressure_limit(12, 10, 8, 16, 20);
1093        assert_eq!(limit, 10);
1094        assert_eq!(pressure_outcome(0, 12, limit, 0), O::NothingEligible);
1095    }
1096
1097    /// Write `size` bytes at `dir/name`, `age` seconds old.
1098    fn put(dir: &Path, name: &str, size: usize, age: u64) {
1099        let path = dir.join(name);
1100        fs::write(&path, vec![b'x'; size]).expect("write");
1101        fs::OpenOptions::new()
1102            .write(true)
1103            .open(&path)
1104            .expect("open")
1105            .set_modified(SystemTime::now() - Duration::from_secs(age))
1106            .expect("set mtime");
1107    }
1108
1109    /// One pass the way the pressure paths run it: the limit and the reserve
1110    /// from `free`, the reserve enforced where files are removed.
1111    fn pass(dir: &Path, cap: u64, free: u64) -> Prune {
1112        let size = dir_size(dir);
1113        let limit = pressure_limit(size, cap, 8, 16, free);
1114        prune_dir_keeping(dir, limit, pressure_reserve(cap, 8, 16, free)).expect("prune")
1115    }
1116
1117    #[test]
1118    fn an_artifact_larger_than_size_minus_reserve_is_kept_and_never_rebuilt_in_a_loop() {
1119        // cap 10, reserve 5, one 6-byte artifact, free pinned at 10 (floor 8,
1120        // threshold 16). The limit (5) alone would delete the whole artifact.
1121        let t = tempfile::TempDir::new().expect("temp");
1122        put(t.path(), "big", 6, 100);
1123        assert_eq!(
1124            prune_dir(t.path(), 5).expect("prune").files,
1125            1,
1126            "without the bound the limit empties the cache"
1127        );
1128        for _ in 0..3 {
1129            // The simulated rebuild between passes.
1130            put(t.path(), "big", 6, 100);
1131            let out = pass(t.path(), 10, 10);
1132            assert_eq!(out.files, 0, "{out:?}");
1133            assert_eq!(out.remaining, 6);
1134            assert!(t.path().join("big").exists());
1135        }
1136    }
1137
1138    #[test]
1139    fn the_reserve_skips_a_file_that_would_cross_it_and_removes_only_small_ones() {
1140        // total 10 (one 6-byte artifact, oldest, and four 1-byte files), cap 10,
1141        // free 10: limit 5, reserve 5.
1142        let t = tempfile::TempDir::new().expect("temp");
1143        put(t.path(), "big", 6, 100);
1144        for (i, name) in ["a", "b", "c", "d"].iter().enumerate() {
1145            put(t.path(), name, 1, 50 - i as u64);
1146        }
1147        let out = pass(t.path(), 10, 10);
1148        assert_eq!((out.files, out.freed, out.remaining), (4, 4, 6), "{out:?}");
1149        assert!(t.path().join("big").exists());
1150        assert!(out.remaining >= 5, "never below the reserve");
1151        // A second pass with free space still pinned removes nothing.
1152        assert_eq!(pass(t.path(), 10, 10).files, 0);
1153    }
1154
1155    #[test]
1156    fn the_reserve_stops_a_walk_that_would_cross_it_where_the_plain_limit_would_not() {
1157        // Three 3-byte files, total 9, limit 5: the plain limit removes two
1158        // (to 3); the reserve of 5 lets only the oldest go (to 6).
1159        let t = tempfile::TempDir::new().expect("temp");
1160        for (i, name) in ["a", "b", "c"].iter().enumerate() {
1161            put(t.path(), name, 3, 90 - i as u64 * 10);
1162        }
1163        let out = pass(t.path(), 10, 10);
1164        assert_eq!((out.files, out.remaining), (1, 6), "{out:?}");
1165        assert!(!t.path().join("a").exists());
1166        assert!(t.path().join("b").exists() && t.path().join("c").exists());
1167
1168        let plain = tempfile::TempDir::new().expect("temp");
1169        for (i, name) in ["a", "b", "c"].iter().enumerate() {
1170            put(plain.path(), name, 3, 90 - i as u64 * 10);
1171        }
1172        assert_eq!(prune_dir(plain.path(), 5).expect("prune").remaining, 3);
1173    }
1174
1175    #[test]
1176    fn below_the_floor_the_bound_is_off_and_the_cache_can_be_emptied() {
1177        let t = tempfile::TempDir::new().expect("temp");
1178        put(t.path(), "big", 6, 100);
1179        // free 0 < floor 8: exactly the rule from before the threshold.
1180        let out = pass(t.path(), 10, 0);
1181        assert_eq!((out.files, out.remaining), (1, 0), "{out:?}");
1182    }
1183}