kache 0.18.0

Zero-copy, content-addressed build cache for Rust, C/C++ and more, with S3 and shared-filesystem remotes.
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
//! Layout probe for `kache doctor`: can the build tree hardlink into
//! `<store>/staging`, and if not, why (#835)?
//!
//! On ext4 CI 0% of store blobs are multi-link. The most likely cause is
//! `link(2)` returning EXDEV across two bind mounts of one filesystem (same
//! `st_dev`, different vfsmounts), with both ingest and restore falling
//! silently to a byte copy. This probe makes that visible: a temp file in the
//! build tree linked into `<store>/staging`, reporting EXDEV with both mount
//! roots (from `/proc/self/mountinfo`), EPERM with `protected_hardlinks` +
//! uid/owner, and FICLONE support.
//!
//! Observability only: the probe creates and removes two temp files, never
//! changing what gets linked.

use std::path::Path;

/// Outcome of [`probe_link_layout`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkLayoutReport {
    /// Whether `link(source_tmp, staging_tmp)` succeeded.
    pub hardlink_supported: bool,
    /// `io::ErrorKind` name on failure (`CrossesDevices`, …), else `None`.
    pub error_kind: Option<String>,
    /// Full io error on failure, else `None`.
    pub error_message: Option<String>,
    /// Mount point containing the build-tree temp, if determinable (Linux).
    pub source_mount: Option<String>,
    /// Mount point containing `<store>/staging`, if determinable (Linux).
    pub dest_mount: Option<String>,
    /// Content of `/proc/sys/fs/protected_hardlinks` (`0`/`1`), if readable.
    pub protected_hardlinks: Option<String>,
    /// Current uid, if determinable (unix).
    pub uid: Option<u32>,
    /// Owner uid of the build-tree temp, if determinable (unix).
    pub source_owner: Option<u32>,
    /// Owner uid of the staging dir, if determinable (unix).
    pub dest_owner: Option<u32>,
    /// Whether FICLONE (CoW reflink) works in `<store>/staging`: `Some(true)`
    /// on CoW filesystems, `Some(false)` where the ioctl fails (ext4), `None`
    /// when the probe could not run.
    pub ficlone_supported: Option<bool>,
}

/// Probe whether a build-tree file can be hardlinked into `<store>/staging`.
///
/// Creates a temp file in `build_dir`, links it into `staging_dir`, then
/// removes both. On success reports `hardlink_supported = true`; on failure
/// classifies the errno and gathers mount/owner/FICLONE context. Best-effort:
/// missing context is `None`, never an error.
pub fn probe_link_layout(build_dir: &Path, staging_dir: &Path) -> LinkLayoutReport {
    let pid = std::process::id();
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    let source_tmp = build_dir.join(format!(".kache-link-probe-{pid}-{nonce}"));
    let dest_tmp = staging_dir.join(format!(".kache-link-probe-{pid}-{nonce}.link"));

    let mut report = LinkLayoutReport {
        hardlink_supported: false,
        error_kind: None,
        error_message: None,
        source_mount: find_mount_for_path(build_dir),
        dest_mount: find_mount_for_path(staging_dir),
        protected_hardlinks: read_protected_hardlinks(),
        uid: current_uid(),
        source_owner: None,
        dest_owner: None,
        ficlone_supported: ficlone_supported_in(staging_dir),
    };

    // The build dir may not exist in a fresh doctor run (e.g. cwd deleted);
    // surface that as an Other failure rather than panicking.
    if let Err(e) = std::fs::create_dir_all(staging_dir) {
        report.error_kind = Some("CreateDirFailed".to_string());
        report.error_message = Some(format!(
            "creating staging dir {}: {e}",
            staging_dir.display()
        ));
        return report;
    }
    if let Err(e) = std::fs::write(&source_tmp, b"kache-link-probe") {
        report.error_kind = Some(io_kind_name(&e));
        report.error_message = Some(format!("creating probe file {}: {e}", source_tmp.display()));
        let _ = std::fs::remove_file(&source_tmp);
        return report;
    }
    report.source_owner = file_owner(&source_tmp);
    report.dest_owner = file_owner(staging_dir);

    match std::fs::hard_link(&source_tmp, &dest_tmp) {
        Ok(()) => {
            report.hardlink_supported = true;
            let _ = std::fs::remove_file(&dest_tmp);
            let _ = std::fs::remove_file(&source_tmp);
        }
        Err(e) => {
            report.error_kind = Some(io_kind_name(&e));
            report.error_message = Some(format!(
                "linking {} into {}: {e}",
                source_tmp.display(),
                dest_tmp.display()
            ));
            let _ = std::fs::remove_file(&dest_tmp);
            let _ = std::fs::remove_file(&source_tmp);
        }
    }
    report
}

fn io_kind_name(e: &std::io::Error) -> String {
    format!("{:?}", e.kind())
}

/// Human detail for an EXDEV probe failure, with both mount roots.
pub(crate) fn format_exdev_detail(source_mount: Option<&str>, dest_mount: Option<&str>) -> String {
    match (source_mount, dest_mount) {
        (Some(src), Some(dst)) if exdev_mounts_differ(src, dst) => format!(
            "EXDEV: build tree is on mount `{src}` but `<store>/staging` is on mount `{dst}` — \
             Linux refuses link() across mounts, including two bind mounts of one filesystem. \
             Put the cache and build tree on the SAME mount for zero-copy sharing"
        ),
        (Some(mnt), Some(_)) => format!(
            "EXDEV even though both paths resolve under mount `{mnt}` — the two directories \
             are on different vfsmounts (e.g. separate bind mounts of one filesystem). Put the \
             cache and build tree on the SAME mount for zero-copy sharing"
        ),
        _ => "EXDEV: hardlink across mounts refused — put the cache and build tree on the SAME \
              mount for zero-copy sharing (mount roots could not be determined)"
            .to_string(),
    }
}

fn exdev_mounts_differ(src: &str, dst: &str) -> bool {
    src != dst
}

/// Human detail for an EPERM probe failure, with hardening + ownership.
pub(crate) fn format_eperm_detail(
    protected_hardlinks: Option<&str>,
    uid: Option<u32>,
    source_owner: Option<u32>,
    dest_owner: Option<u32>,
) -> String {
    let hardening = protected_hardlinks.unwrap_or("unknown");
    format!(
        "EPERM: hardlink refused (fs.protected_hardlinks={hardening}, uid={} owner, source owner={}, staging owner={}) — \
         under protected_hardlinks the caller must own the source. Ensure one uid owns the cache",
        uid.map_or("?".to_string(), |u| u.to_string()),
        source_owner.map_or("?".to_string(), |u| u.to_string()),
        dest_owner.map_or("?".to_string(), |u| u.to_string()),
    )
}

/// Human summary for the doctor check, dispatching on the probe outcome.
/// Pure so each arm is unit-testable without bind mounts.
pub(crate) fn format_probe_detail(report: &LinkLayoutReport) -> String {
    if report.hardlink_supported {
        let ficlone = match report.ficlone_supported {
            Some(true) => "FICLONE supported",
            Some(false) => "FICLONE unsupported (expected on ext4)",
            None => "FICLONE unknown",
        };
        return format!("hardlink build-tree → <store>/staging works ({ficlone})");
    }
    let kind = report.error_kind.as_deref().unwrap_or("Unknown");
    if kind == "CrossesDevices" {
        format_exdev_detail(report.source_mount.as_deref(), report.dest_mount.as_deref())
    } else if kind == "PermissionDenied" {
        format_eperm_detail(
            report.protected_hardlinks.as_deref(),
            report.uid,
            report.source_owner,
            report.dest_owner,
        )
    } else {
        format!(
            "hardlink build-tree → <store>/staging failed ({kind}): {}",
            report.error_message.as_deref().unwrap_or("unknown error")
        )
    }
}

/// Mount point containing `path`, if determinable. Linux parses
/// `/proc/self/mountinfo`; elsewhere returns `None`.
fn find_mount_for_path(path: &Path) -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        let content = std::fs::read_to_string("/proc/self/mountinfo").ok()?;
        let abs = absolute_path(path)?;
        find_mount_root(&abs, &content)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = path;
        None
    }
}

/// Longest mount point in `mountinfo` that contains `abs_path`.
/// `abs_path` must be absolute; `mountinfo` is `/proc/self/mountinfo` content.
/// Pure so bind-mount EXDEV reporting is unit-testable without mounts.
#[cfg(any(test, target_os = "linux"))]
pub(crate) fn find_mount_root(abs_path: &Path, mountinfo: &str) -> Option<String> {
    let path_str = abs_path.to_string_lossy();
    if !path_str.starts_with('/') {
        return None;
    }
    let mut best: Option<String> = None;
    for line in mountinfo.lines() {
        let Some(mount_point) = parse_mountinfo_mount_point(line) else {
            continue;
        };
        if !path_is_under_mount(&path_str, &mount_point) {
            continue;
        }
        let longer = best
            .as_ref()
            .is_none_or(|current: &String| mount_point_is_longer(&mount_point, current));
        if longer {
            best = Some(mount_point);
        }
    }
    best
}

/// Whether `path` lives on `mount_point`. `/` is a prefix of every absolute
/// path; concatenating `"/" + "/"` would look for `//` and miss `/tmp`.
#[cfg(any(test, target_os = "linux"))]
fn path_is_under_mount(path: &str, mount_point: &str) -> bool {
    path == mount_point
        || (mount_point == "/" && path.starts_with('/'))
        || path.starts_with(&format!("{mount_point}/"))
}

#[cfg(any(test, target_os = "linux"))]
fn mount_point_is_longer(candidate: &str, current: &str) -> bool {
    candidate.len() > current.len()
}

/// Mount point field (5th) of one `/proc/self/mountinfo` line, unescaping
/// octal spaces. Returns `None` for malformed lines.
#[cfg(any(test, target_os = "linux"))]
fn parse_mountinfo_mount_point(line: &str) -> Option<String> {
    let mut parts = line.split(' ');
    // mountinfo: id parent major:minor root mount-point options …
    let _id = parts.next()?;
    let _parent = parts.next()?;
    let _dev = parts.next()?;
    let _root = parts.next()?;
    let mount_point = parts.next()?;
    if mount_point.is_empty() {
        return None;
    }
    Some(mount_point.replace("\\040", " ").replace("\\012", "\n"))
}

#[cfg(target_os = "linux")]
fn absolute_path(path: &Path) -> Option<std::path::PathBuf> {
    if path.is_absolute() {
        return Some(path.to_path_buf());
    }
    std::env::current_dir().ok().map(|cwd| cwd.join(path))
}

/// Content of `/proc/sys/fs/protected_hardlinks` (`0`/`1`), trimmed.
fn read_protected_hardlinks() -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        std::fs::read_to_string("/proc/sys/fs/protected_hardlinks")
            .ok()
            .and_then(|s| parse_protected_hardlinks(&s))
    }
    #[cfg(not(target_os = "linux"))]
    {
        None
    }
}

/// Parse `/proc/sys/fs/protected_hardlinks` content.
#[cfg(any(test, target_os = "linux"))]
pub(crate) fn parse_protected_hardlinks(content: &str) -> Option<String> {
    let trimmed = content.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(trimmed.to_string())
}

fn current_uid() -> Option<u32> {
    #[cfg(unix)]
    {
        // SAFETY: getuid is async-signal-safe and has no failure mode.
        Some(unsafe { libc::getuid() })
    }
    #[cfg(not(unix))]
    {
        None
    }
}

fn file_owner(path: &Path) -> Option<u32> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        std::fs::metadata(path).ok().map(|m| m.uid())
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        None
    }
}

/// Whether FICLONE works in `dir`: create two temps and try to clone one into
/// the other. `Some(true)` on CoW filesystems, `Some(false)` where the ioctl
/// fails (ext4), `None` when the probe could not run.
fn ficlone_supported_in(dir: &Path) -> Option<bool> {
    if !dir.exists() {
        return None;
    }
    let pid = std::process::id();
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    let src = dir.join(format!(".kache-ficlone-probe-{pid}-{nonce}.src"));
    let dst = dir.join(format!(".kache-ficlone-probe-{pid}-{nonce}.dst"));
    let probed = (|| -> Option<bool> {
        std::fs::write(&src, b"kache-ficlone-probe").ok()?;
        match crate::link::try_reflink(&src, &dst) {
            Ok(()) => Some(true),
            Err(_) => {
                // `try_reflink` on Linux removes a failed dst; on other
                // platforms ensure no litter remains.
                let _ = std::fs::remove_file(&dst);
                Some(false)
            }
        }
    })();
    let _ = std::fs::remove_file(&src);
    let _ = std::fs::remove_file(&dst);
    probed
}

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

    fn empty_report() -> LinkLayoutReport {
        LinkLayoutReport {
            hardlink_supported: false,
            error_kind: None,
            error_message: None,
            source_mount: None,
            dest_mount: None,
            protected_hardlinks: None,
            uid: None,
            source_owner: None,
            dest_owner: None,
            ficlone_supported: None,
        }
    }

    #[test]
    fn io_kind_name_names_the_errno() {
        let cross = std::io::Error::new(std::io::ErrorKind::CrossesDevices, "x");
        let missing = std::io::Error::new(std::io::ErrorKind::NotFound, "x");
        assert_eq!(io_kind_name(&cross), "CrossesDevices");
        assert_eq!(io_kind_name(&missing), "NotFound");
    }

    /// uid/owner observations come from real syscalls: a file this process
    /// just created is owned by this process's uid.
    #[test]
    #[cfg(unix)]
    fn file_owner_matches_current_uid_for_own_files() {
        use std::os::unix::fs::MetadataExt;
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("owned");
        std::fs::write(&file, b"x").unwrap();
        let owner = file_owner(&file);
        let expected = std::fs::metadata(&file).unwrap().uid();
        assert_eq!(owner, Some(expected));
        assert_eq!(owner, current_uid());
        assert_eq!(current_uid(), Some(unsafe { libc::getuid() }));
        assert_eq!(
            file_owner(&dir.path().join("missing")),
            None,
            "a missing path has no owner"
        );
    }

    /// `/proc/sys/fs/protected_hardlinks` holds `0`, `1`, or `2` on every
    /// Linux kernel: assert the read parses to one of those, never a guess.
    #[test]
    #[cfg(target_os = "linux")]
    fn read_protected_hardlinks_reports_the_kernel_value() {
        let value = read_protected_hardlinks();
        assert!(
            matches!(value.as_deref(), Some("0") | Some("1") | Some("2")),
            "unexpected protected_hardlinks content: {value:?}"
        );
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn absolute_path_passes_absolute_paths_through() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(absolute_path(dir.path()), Some(dir.path().to_path_buf()));
        let relative = Path::new("rel-link-probe");
        let got = absolute_path(relative).expect("cwd is resolvable");
        assert!(got.is_absolute(), "relative paths must be joined onto cwd");
        assert!(got.ends_with("rel-link-probe"));
        assert!(!got.as_os_str().is_empty());
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn find_mount_for_path_resolves_a_real_mount() {
        let dir = tempfile::tempdir().unwrap();
        let root =
            find_mount_for_path(dir.path()).expect("mountinfo always resolves a tempdir on Linux");
        assert!(
            !root.is_empty() && dir.path().starts_with(&root),
            "mount root {root:?} must prefix {}",
            dir.path().display()
        );
    }

    #[test]
    fn find_mount_root_prefers_the_longest_prefix() {
        let mountinfo = "1 1 8:1 / / rw - ext4 /dev/sda1 rw\n\
                         2 1 8:1 / /foo rw - ext4 /dev/sda1 rw\n\
                         3 1 8:2 / /foo/bar rw - ext4 /dev/sda2 rw\n";
        assert_eq!(
            find_mount_root(Path::new("/foo/bar/x"), mountinfo).as_deref(),
            Some("/foo/bar"),
            "nested mounts resolve to the longest match"
        );
        assert_eq!(
            find_mount_root(Path::new("/foo/other"), mountinfo).as_deref(),
            Some("/foo")
        );
    }

    #[test]
    fn find_mount_root_matches_exact_mount_point() {
        let mountinfo = "23 28 0:20 / /sys/fs/cgroup ro shared:4 - cgroup2 cgroup2 rw\n\
                         30 1 8:1 / /mnt/data rw - ext4 /dev/sda1 rw\n";
        let got = find_mount_root(Path::new("/mnt/data"), mountinfo).unwrap();
        assert_eq!(got, "/mnt/data");
    }

    #[test]
    fn find_mount_root_prefers_longest_prefix() {
        let mountinfo = "1 0 8:1 / / rw - ext4 /dev/sda1 rw\n\
                         2 1 8:1 /sub /mnt/data rw - ext4 /dev/sda1 rw\n";
        let got = find_mount_root(Path::new("/mnt/data/sub/file"), mountinfo).unwrap();
        assert_eq!(got, "/mnt/data");
    }

    #[test]
    fn find_mount_root_returns_none_without_match() {
        let mountinfo = "1 0 8:1 / / rw - ext4 /dev/sda1 rw\n";
        // Relative path can never match an absolute mount point.
        assert!(find_mount_root(Path::new("relative/path"), mountinfo).is_none());
    }

    #[test]
    fn find_mount_root_uses_slash_for_paths_with_no_nested_mount() {
        let mountinfo = "1 0 8:1 / / rw - ext4 /dev/sda1 rw\n";
        assert_eq!(
            find_mount_root(Path::new("/tmp/foo"), mountinfo).as_deref(),
            Some("/"),
            "the root mount must prefix every absolute path"
        );
    }

    #[test]
    fn find_mount_root_skips_malformed_lines() {
        let mountinfo = "garbage\n1 0 8:1 / / rw - ext4 /dev/sda1 rw\n";
        assert_eq!(
            find_mount_root(Path::new("/tmp/foo"), mountinfo).as_deref(),
            Some("/")
        );
    }

    #[test]
    fn path_is_under_mount_treats_slash_as_prefix_of_every_absolute_path() {
        assert!(path_is_under_mount("/tmp/foo", "/"));
        assert!(path_is_under_mount("/", "/"));
        assert!(path_is_under_mount("/mnt/data/x", "/mnt/data"));
        assert!(!path_is_under_mount("/mnt/data", "/mnt/data/x"));
        assert!(!path_is_under_mount("/mnt/other", "/mnt/data"));
    }

    #[test]
    fn find_mount_root_unescapes_octal_space() {
        let mountinfo = "1 0 8:1 / /mnt/my\\040data rw - ext4 /dev/sda1 rw\n";
        let got = find_mount_root(Path::new("/mnt/my data/file"), mountinfo).unwrap();
        assert_eq!(got, "/mnt/my data");
    }

    #[test]
    fn parse_mountinfo_mount_point_rejects_malformed_line() {
        assert!(parse_mountinfo_mount_point("").is_none());
        assert!(parse_mountinfo_mount_point("1 2 3").is_none());
    }

    #[test]
    fn parse_mountinfo_mount_point_accepts_well_formed_line() {
        let line = "23 28 0:20 / /sys/fs/cgroup ro shared:4 - cgroup2 cgroup2 rw";
        assert_eq!(
            parse_mountinfo_mount_point(line).as_deref(),
            Some("/sys/fs/cgroup")
        );
    }

    #[test]
    fn parse_protected_hardlinks_trims_and_rejects_empty() {
        assert_eq!(parse_protected_hardlinks("1\n").as_deref(), Some("1"));
        assert_eq!(parse_protected_hardlinks("0\n").as_deref(), Some("0"));
        assert!(parse_protected_hardlinks("  \n").is_none());
        assert!(parse_protected_hardlinks("").is_none());
    }

    #[test]
    fn format_exdev_detail_reports_both_mounts_when_different() {
        let got = format_exdev_detail(Some("/mnt/workspace"), Some("/mnt/cache"));
        assert!(got.contains("/mnt/workspace"));
        assert!(got.contains("/mnt/cache"));
        assert!(got.contains("build tree is on mount"));
        assert!(!got.contains("vfsmounts"));
    }

    #[test]
    fn format_exdev_detail_reports_bind_mount_when_same() {
        let got = format_exdev_detail(Some("/mnt/data"), Some("/mnt/data"));
        assert!(got.contains("vfsmounts"));
        assert!(!got.contains("build tree is on mount"));
    }

    #[test]
    fn exdev_mounts_differ_is_string_inequality() {
        assert!(exdev_mounts_differ("/a", "/b"));
        assert!(!exdev_mounts_differ("/a", "/a"));
    }

    #[test]
    #[cfg(any(test, target_os = "linux"))]
    fn mount_point_is_longer_compares_lengths() {
        assert!(mount_point_is_longer("/foo/bar", "/foo"));
        assert!(!mount_point_is_longer("/foo", "/foo"));
        assert!(!mount_point_is_longer("/a", "/bbb"));
    }

    #[test]
    fn format_exdev_detail_reports_unknown_mounts() {
        let got = format_exdev_detail(None, None);
        assert!(got.contains("could not be determined"));
    }

    #[test]
    fn format_eperm_detail_reports_hardening_and_owners() {
        let got = format_eperm_detail(Some("1"), Some(1000), Some(0), Some(0));
        assert!(got.contains("protected_hardlinks=1"));
        assert!(got.contains("1000"));
    }

    #[test]
    fn format_probe_detail_reports_success_with_ficlone() {
        let mut report = empty_report();
        report.hardlink_supported = true;
        report.ficlone_supported = Some(true);
        let got = format_probe_detail(&report);
        assert!(got.contains("works"));
        assert!(got.contains("FICLONE supported"));
    }

    #[test]
    fn format_probe_detail_reports_success_without_ficlone() {
        let mut report = empty_report();
        report.hardlink_supported = true;
        report.ficlone_supported = Some(false);
        let got = format_probe_detail(&report);
        assert!(got.contains("FICLONE unsupported"));
    }

    #[test]
    fn format_probe_detail_reports_success_with_unknown_ficlone() {
        let mut report = empty_report();
        report.hardlink_supported = true;
        report.ficlone_supported = None;
        let got = format_probe_detail(&report);
        assert!(got.contains("FICLONE unknown"));
    }

    #[test]
    fn format_probe_detail_reports_exdev_with_mounts() {
        let mut report = empty_report();
        report.error_kind = Some("CrossesDevices".to_string());
        report.source_mount = Some("/mnt/a".to_string());
        report.dest_mount = Some("/mnt/b".to_string());
        let got = format_probe_detail(&report);
        assert!(got.contains("EXDEV"));
        assert!(got.contains("/mnt/a"));
    }

    #[test]
    fn format_probe_detail_reports_eperm_with_hardening() {
        let mut report = empty_report();
        report.error_kind = Some("PermissionDenied".to_string());
        report.protected_hardlinks = Some("1".to_string());
        report.uid = Some(1000);
        let got = format_probe_detail(&report);
        assert!(got.contains("EPERM"));
    }

    #[test]
    fn format_probe_detail_reports_other_failure() {
        let mut report = empty_report();
        report.error_kind = Some("NotFound".to_string());
        report.error_message = Some("no such file".to_string());
        let got = format_probe_detail(&report);
        assert!(got.contains("NotFound"));
        assert!(got.contains("no such file"));
    }

    #[test]
    fn probe_succeeds_on_same_device_tempdir() {
        let dir = tempfile::tempdir().unwrap();
        let build_dir = dir.path().join("build");
        let staging_dir = dir.path().join("store").join("staging");
        std::fs::create_dir_all(&build_dir).unwrap();
        std::fs::create_dir_all(&staging_dir).unwrap();
        let report = probe_link_layout(&build_dir, &staging_dir);
        assert!(
            report.hardlink_supported,
            "same-device tempdir must hardlink: {report:?}"
        );
        assert!(report.error_kind.is_none());
    }

    #[test]
    fn probe_reports_other_for_missing_build_dir_file() {
        // A regular file as `build_dir` cannot hold the probe temp: write
        // fails with `NotADirectory`/`Other`, exercising the failure arm
        // without bind mounts.
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("not-a-dir");
        std::fs::write(&file, b"x").unwrap();
        let staging_dir = dir.path().join("staging");
        std::fs::create_dir_all(&staging_dir).unwrap();
        let report = probe_link_layout(&file, &staging_dir);
        assert!(!report.hardlink_supported);
        assert!(report.error_kind.is_some());
    }

    #[test]
    fn ficlone_probe_returns_determinate_for_existing_dir() {
        let dir = tempfile::tempdir().unwrap();
        // CoW or not, an existing dir yields a determinate answer; a missing
        // dir yields None. Do not assert true/false: that varies by
        // filesystem (APFS vs ext4) and would flake.
        assert!(ficlone_supported_in(dir.path()).is_some());
    }

    #[test]
    fn ficlone_probe_returns_none_for_missing_dir() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("no-such-dir");
        assert!(ficlone_supported_in(&missing).is_none());
    }
}