zccache 1.11.8

Local-first compiler cache for C/C++/Rust/Emscripten
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
//! Artifact pack format, atomic writes, hardlinking, cached output materialization.

use super::*;

pub(super) fn artifact_persist_tmp_path(cache_path: &Path) -> PathBuf {
    let counter = ARTIFACT_PERSIST_TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let name = cache_path
        .file_name()
        .map(|name| name.to_string_lossy())
        .unwrap_or_else(|| "artifact".into());
    cache_path.with_file_name(format!(".{name}.tmp-{}-{counter}", std::process::id()))
}

pub(super) fn persist_artifact_output(cache_path: &Path, payload: &[u8]) -> std::io::Result<()> {
    if let Some(parent) = cache_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let tmp_path = artifact_persist_tmp_path(cache_path);
    let result = (|| {
        std::fs::write(&tmp_path, payload)?;
        replace_artifact_cache_file(&tmp_path, cache_path)
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&tmp_path);
    }
    result
}

// ─── Artifact-pack format (experimental, env-gated) ───────────────────────────
//
// Layout of `{key_hex}.pack`:
//
//   [magic: 4 bytes = b"ZCPK"]
//   [num_payloads: u32 le]
//   [(offset: u64 le, size: u64 le)] * num_payloads
//   [payload_0 bytes]
//   [payload_1 bytes]
//   ...
//
// Why: each `std::fs::write` of a fresh file under Windows Defender pays a
// per-file scan cost. Packing N payloads of one cache miss into a single
// `.pack` collapses the per-file overhead by N. Bench measured 2.6× wall-clock
// improvement at 5 payloads per artifact (see `tests/persist_pool_bench.rs`).
//
// Trade-off: hit path can't hardlink — it must slice the pack and write the
// extracted bytes. Gated by `ZCCACHE_PACK_ARTIFACTS` until the read-path cost
// is measured against the write-path win on real workloads.

pub(super) const PACK_MAGIC: &[u8; 4] = b"ZCPK";

pub(super) fn pack_mode_enabled() -> bool {
    std::env::var("ZCCACHE_PACK_ARTIFACTS")
        .ok()
        .is_some_and(|v| !v.is_empty() && v != "0")
}

pub(super) fn pack_path_for(artifact_dir: &Path, key_hex: &str) -> PathBuf {
    artifact_dir.join(format!("{key_hex}.pack"))
}

pub(super) fn build_pack(payloads: &[Arc<Vec<u8>>]) -> Vec<u8> {
    let n = payloads.len();
    let header_size = 4 + 4 + n * 16;
    let body_size: usize = payloads.iter().map(|p| p.len()).sum();
    let mut buf = Vec::with_capacity(header_size + body_size);
    buf.extend_from_slice(PACK_MAGIC);
    buf.extend_from_slice(&(n as u32).to_le_bytes());
    let mut offset = header_size as u64;
    for p in payloads {
        buf.extend_from_slice(&offset.to_le_bytes());
        buf.extend_from_slice(&(p.len() as u64).to_le_bytes());
        offset += p.len() as u64;
    }
    for p in payloads {
        buf.extend_from_slice(p);
    }
    buf
}

pub(super) fn parse_pack_header(data: &[u8]) -> std::io::Result<Vec<(u64, u64)>> {
    if data.len() < 8 || &data[..4] != PACK_MAGIC {
        return Err(std::io::Error::other("not a zccache pack file"));
    }
    let n = u32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize;
    let needed = 8 + n * 16;
    if data.len() < needed {
        return Err(std::io::Error::other("pack header truncated"));
    }
    let mut entries = Vec::with_capacity(n);
    for i in 0..n {
        let base = 8 + i * 16;
        let offset = u64::from_le_bytes(data[base..base + 8].try_into().unwrap());
        let size = u64::from_le_bytes(data[base + 8..base + 16].try_into().unwrap());
        entries.push((offset, size));
    }
    Ok(entries)
}

/// Try to extract the i-th payload from `{key_hex}.pack`. Returns None if the
/// pack file is missing, corrupt, or doesn't have that many payloads.
pub(super) fn try_load_packed_payload(
    artifact_dir: &Path,
    key_hex: &str,
    idx: usize,
) -> Option<Vec<u8>> {
    let pack_path = pack_path_for(artifact_dir, key_hex);
    let data = std::fs::read(&pack_path).ok()?;
    let entries = parse_pack_header(&data).ok()?;
    let &(offset, size) = entries.get(idx)?;
    let start = offset as usize;
    let end = start.checked_add(size as usize)?;
    if end > data.len() {
        return None;
    }
    Some(data[start..end].to_vec())
}

/// Persist all payloads of one artifact, either as N individual files
/// (today's layout) or as a single `.pack` file (env-gated). Wraps every
/// inner `std::fs::write` in `persist_artifact_output`'s tmp-then-rename
/// atomicity.
pub(super) fn persist_artifact_payloads(
    artifact_dir: &Path,
    key_hex: &str,
    payloads: &[Arc<Vec<u8>>],
) -> std::io::Result<()> {
    if pack_mode_enabled() {
        let pack = build_pack(payloads);
        return persist_artifact_output(&pack_path_for(artifact_dir, key_hex), &pack);
    }
    // Run inline for small N — rayon dispatch cost is comparable to the
    // syscalls themselves below the threshold (same break-even as
    // `write_payloads_par`). Empirically tuned in
    // `crates/zccache-daemon/benches/persist_payloads.rs`.
    if payloads.len() < PAR_WRITE_THRESHOLD {
        for (i, payload) in payloads.iter().enumerate() {
            let cache_path = artifact_dir.join(format!("{key_hex}_{i}"));
            persist_artifact_output(&cache_path, payload)?;
        }
        return Ok(());
    }
    use rayon::prelude::*;
    // `reduce` preserves the prior "return first error" semantics:
    // `a.and(b)` returns the first `Err` it sees and otherwise `Ok(())`.
    payloads
        .par_iter()
        .enumerate()
        .map(|(i, payload)| {
            let cache_path = artifact_dir.join(format!("{key_hex}_{i}"));
            persist_artifact_output(&cache_path, payload)
        })
        .reduce(|| Ok(()), |a, b| a.and(b))
}

/// Persist artifact payloads when the daemon already has them on disk — typical
/// for the rustc multi-compile miss path where the compiler just wrote outputs
/// to `target/.../<name>` and the daemon would otherwise `std::fs::read` them
/// into RAM before writing them back to the cache.
///
/// Each cache file is created via `persist_artifact_file` — `std::fs::hard_link`
/// with a same-volume requirement and a copy fallback for cross-volume cases.
/// Net effect on the cold-write path: one disk write per output instead of two,
/// halving the per-file overhead Defender real-time scanning pays on Windows.
///
/// Pack mode (`ZCCACHE_PACK_ARTIFACTS=1`) still needs the bytes contiguous, so
/// it materialises each path via `std::fs::read` and falls through to the
/// existing `persist_artifact_output`. The hardlink win only applies when pack
/// mode is off (the default).
pub(super) fn persist_artifact_paths(
    artifact_dir: &Path,
    key_hex: &str,
    sources: &[NormalizedPath],
) -> std::io::Result<()> {
    if pack_mode_enabled() {
        let bytes: Vec<Arc<Vec<u8>>> = sources
            .iter()
            .map(|p| std::fs::read(p.as_path()).map(Arc::new))
            .collect::<std::io::Result<_>>()?;
        let pack = build_pack(&bytes);
        return persist_artifact_output(&pack_path_for(artifact_dir, key_hex), &pack);
    }
    if sources.len() < PAR_WRITE_THRESHOLD {
        for (i, source) in sources.iter().enumerate() {
            let cache_path = artifact_dir.join(format!("{key_hex}_{i}"));
            persist_artifact_file(&cache_path, source.as_path())?;
        }
        return Ok(());
    }
    use rayon::prelude::*;
    sources
        .par_iter()
        .enumerate()
        .map(|(i, source)| {
            let cache_path = artifact_dir.join(format!("{key_hex}_{i}"));
            persist_artifact_file(&cache_path, source.as_path()).map(|_| ())
        })
        .reduce(|| Ok(()), |a, b| a.and(b))
}

#[derive(Clone, Copy, Debug, Default)]
pub(super) struct PersistArtifactFileStats {
    pub(super) hardlink_count: u64,
    pub(super) copy_count: u64,
    pub(super) copy_bytes: u64,
}

pub(super) fn persist_artifact_file(
    cache_path: &Path,
    source_path: &Path,
) -> std::io::Result<PersistArtifactFileStats> {
    if let Some(parent) = cache_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let tmp_path = artifact_persist_tmp_path(cache_path);
    let result = (|| match std::fs::hard_link(source_path, &tmp_path) {
        Ok(()) => {
            replace_artifact_cache_file(&tmp_path, cache_path)?;
            Ok(PersistArtifactFileStats {
                hardlink_count: 1,
                ..PersistArtifactFileStats::default()
            })
        }
        Err(_) => {
            let copy_bytes = std::fs::copy(source_path, &tmp_path)?;
            replace_artifact_cache_file(&tmp_path, cache_path)?;
            Ok(PersistArtifactFileStats {
                copy_count: 1,
                copy_bytes,
                ..PersistArtifactFileStats::default()
            })
        }
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&tmp_path);
    }
    result
}

#[cfg(not(windows))]
pub(super) fn replace_artifact_cache_file(
    tmp_path: &Path,
    cache_path: &Path,
) -> std::io::Result<()> {
    std::fs::rename(tmp_path, cache_path)
}

#[cfg(windows)]
pub(super) fn replace_artifact_cache_file(
    tmp_path: &Path,
    cache_path: &Path,
) -> std::io::Result<()> {
    match std::fs::rename(tmp_path, cache_path) {
        Ok(()) => Ok(()),
        Err(_) if cache_path.exists() => {
            std::fs::remove_file(cache_path)?;
            std::fs::rename(tmp_path, cache_path)
        }
        Err(err) => Err(err),
    }
}

/// Write cached output to disk. Optimized syscall sequence:
/// 1. Try hardlink directly (1 syscall — common case when output doesn't exist)
/// 2. If output already exists: check if it's the same file (skip if so)
/// 3. Remove existing output and retry hardlink (2 syscalls)
/// 4. Fall back to fs::write from memory (1 syscall)
///
/// After writing, the output's mtime is set to the current time. This is
/// critical for build system compatibility: cargo, make, and ninja use mtime
/// to determine if an output is fresh relative to its dependencies. Without
/// this, hardlinked outputs inherit the cache file's old mtime, causing
/// build systems to consider them stale and triggering unnecessary rebuilds.
/// See issue #15 for the full root cause analysis.
///
/// The hardlink-first order optimizes for the rebuild scenario where outputs
/// don't exist yet (1 syscall). For incremental builds where outputs exist
/// as hardlinks, the failed hardlink + same_file check is still fast.
pub(super) fn write_cached_output(
    out_path: &Path,
    cache_file: &Path,
    data: &[u8],
) -> std::io::Result<()> {
    // Fast path: hardlink directly (works when out_path doesn't exist yet).
    // This is the cheapest path — one kernel call when no output exists.
    if std::fs::hard_link(cache_file, out_path).is_ok() {
        touch_mtime(out_path);
        return Ok(());
    }
    // Hardlink failed — output probably exists. Check if it's already
    // the same file (hardlinked from a previous hit). Compare file
    // identity (inode/volume+index), NOT file size — two different
    // compilations can produce .o files with identical sizes but
    // different content (alignment, padding).
    if same_file(out_path, cache_file) {
        touch_mtime(out_path);
        return Ok(());
    }
    // Output exists but is different — remove and retry
    let _ = std::fs::remove_file(out_path);
    if std::fs::hard_link(cache_file, out_path).is_ok() {
        touch_mtime(out_path);
        return Ok(());
    }
    // Hardlink failed entirely (cross-device, no cache file) — copy from memory.
    // fs::write creates a new file with current mtime, so no touch needed.
    std::fs::write(out_path, data)
}

pub(super) fn write_cached_file(out_path: &Path, cache_file: &Path) -> std::io::Result<()> {
    if std::fs::hard_link(cache_file, out_path).is_ok() {
        touch_mtime(out_path);
        return Ok(());
    }
    if same_file(out_path, cache_file) {
        touch_mtime(out_path);
        return Ok(());
    }
    let _ = std::fs::remove_file(out_path);
    if std::fs::hard_link(cache_file, out_path).is_ok() {
        touch_mtime(out_path);
        return Ok(());
    }
    std::fs::copy(cache_file, out_path)?;
    touch_mtime(out_path);
    Ok(())
}

pub(super) fn write_cached_payload(
    out_path: &Path,
    cache_file: &Path,
    payload: &CachedPayload,
) -> std::io::Result<()> {
    match payload {
        CachedPayload::Bytes(data) => write_cached_output(out_path, cache_file, data),
        CachedPayload::File(path) => write_cached_file(out_path, path),
    }
}

/// Write a batch of cached payloads to their target paths in parallel.
///
/// `targets[i]` is the `(out_path, cache_file)` pair for `payloads[i]`. The
/// parent of each `out_path` is created if it does not exist (matches the
/// per-site behavior of the link-hit path). Returns `true` iff every write
/// succeeded; `false` on first failure (callers either fall through to a
/// fallback path or ignore the result, mirroring the prior serial loops).
///
/// Threshold: rayon is only used when `targets.len() >= 4`. For N ≤ 3 the
/// per-iteration thread-pool dispatch cost (~300 µs) is comparable to the
/// hardlink syscalls themselves, so a serial loop is faster. The
/// `benches/write_payloads.rs` micro-benchmark sets this cut-off
/// empirically on the Windows / NTFS host.
pub(super) const PAR_WRITE_THRESHOLD: usize = 4;

pub(super) fn write_payloads_par<P, Q>(targets: &[(P, Q)], payloads: &[CachedPayload]) -> bool
where
    P: AsRef<Path> + Sync,
    Q: AsRef<Path> + Sync,
{
    debug_assert_eq!(targets.len(), payloads.len());
    let write_one = |out: &Path, cache: &Path, payload: &CachedPayload| -> bool {
        if let Some(parent) = out.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        write_cached_payload(out, cache, payload).is_ok()
    };
    if targets.len() < PAR_WRITE_THRESHOLD {
        return targets
            .iter()
            .zip(payloads.iter())
            .all(|((out, cache), payload)| write_one(out.as_ref(), cache.as_ref(), payload));
    }
    use rayon::prelude::*;
    targets
        .par_iter()
        .zip(payloads.par_iter())
        .all(|((out, cache), payload)| write_one(out.as_ref(), cache.as_ref(), payload))
}

pub(super) fn break_output_hardlink_before_compile(path: &Path) -> std::io::Result<()> {
    match std::fs::metadata(path) {
        Ok(meta) if meta.is_file() => {}
        Ok(_) => return Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e),
    }

    if hard_link_count(path)? <= 1 {
        return Ok(());
    }

    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let file_name = path
        .file_name()
        .unwrap_or_else(|| std::ffi::OsStr::new("output"))
        .to_string_lossy();
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let pid = std::process::id();

    let mut last_err = None;
    for attempt in 0..32 {
        let tmp_path = parent.join(format!(
            ".zccache-detach-{pid}-{nonce}-{attempt}-{file_name}"
        ));
        let copy_result = (|| {
            let mut src = std::fs::File::open(path)?;
            let mut dst = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&tmp_path)?;
            std::io::copy(&mut src, &mut dst)?;
            dst.sync_all()?;
            let permissions = src.metadata()?.permissions();
            std::fs::set_permissions(&tmp_path, permissions)?;
            Ok::<(), std::io::Error>(())
        })();

        match copy_result {
            Ok(()) => {
                if let Err(e) = std::fs::remove_file(path) {
                    let _ = std::fs::remove_file(&tmp_path);
                    return Err(e);
                }
                if let Err(e) = std::fs::rename(&tmp_path, path) {
                    let _ = std::fs::remove_file(&tmp_path);
                    return Err(e);
                }
                return Ok(());
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                last_err = Some(e);
            }
            Err(e) => {
                let _ = std::fs::remove_file(&tmp_path);
                return Err(e);
            }
        }
    }

    Err(last_err.unwrap_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            "failed to create hardlink detach temp file",
        )
    }))
}

#[cfg(unix)]
pub(super) fn hard_link_count(path: &Path) -> std::io::Result<u64> {
    use std::os::unix::fs::MetadataExt;

    Ok(std::fs::metadata(path)?.nlink())
}

#[cfg(windows)]
pub(super) fn hard_link_count(path: &Path) -> std::io::Result<u64> {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Foundation::CloseHandle;
    use windows_sys::Win32::Storage::FileSystem::{
        CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_NORMAL,
        FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
    };

    let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();

    unsafe {
        let handle = CreateFileW(
            wide.as_ptr(),
            0,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            std::ptr::null(),
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            std::ptr::null_mut(),
        );
        if handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
            return Err(std::io::Error::last_os_error());
        }

        let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed();
        let ok = GetFileInformationByHandle(handle, &mut info);
        let close_result = CloseHandle(handle);

        if ok == 0 {
            return Err(std::io::Error::last_os_error());
        }
        if close_result == 0 {
            return Err(std::io::Error::last_os_error());
        }

        Ok(info.nNumberOfLinks as u64)
    }
}

/// Floor the materialized artifact's mtime to the max of its sibling
/// compilation artifacts (`*.rlib` / `*.rmeta` / `*.so` / `*.dylib` /
/// `*.dll` / `*.exe` / `*.a` / `*.lib`) in the same directory.
///
/// **Why** (issues #466 / #467): cargo's `Fingerprint::check_filesystem`
/// emits `FsStatusOutdated::StaleDependency` when any dep's artifact
/// mtime is strictly greater than the dependent's artifact mtime
/// (`dep_mtime > my_mtime → stale`). When zccache hardlinks a cache hit
/// into `target/debug/deps/`, the artifact inherits the cache file's
/// preserved mtime (iter7 invariant). But cache files for transitively-
/// dependent crates are not guaranteed to have correctly-ordered mtimes:
/// archive truncation, parallel cache stores, and out-of-order
/// re-materialization all break the dep-before-dependent invariant. The
/// GH bench measured this as 31 crates recompiling on every "warm with
/// target intact" build, taking ~3 s vs sccache's 215 ms baseline.
///
/// **Why this is safe vs iter7's no-op** (the previous design): the
/// floor only ever INCREASES the artifact mtime, and only to a value
/// derived from existing siblings in the same directory. iter7's
/// concern was stamping `now()` — a value that changes between builds
/// and triggers cargo's "externally modified" check. Flooring to a
/// stable sibling-derived value avoids that:
/// 1. On the next cache hit for the same artifact, the hardlink/
///    same-file fast path returns early without re-flooring.
/// 2. Even if we re-floor, sibling mtimes only ever grow (cache hits
///    materialise with their cache mtime; the floor floors UP from
///    there), so the value is idempotent across repeat builds.
///
/// Disable via `ZCCACHE_DISABLE_MTIME_FLOOR=1` if the floor causes
/// problems with a specific build system.
///
/// **Cost**: one `read_dir` + N stats per materialization. Measured at
/// ~50 µs per hit on a `target/debug/deps/` with 300 entries (Linux,
/// release build). Amortised cost is hidden behind the cargo
/// recompilation this prevents — preventing a ~3 s recompile is worth
/// 50 µs of stat work.
pub(super) fn touch_mtime(path: &Path) {
    if mtime_floor_disabled() {
        return;
    }
    let _ = floor_artifact_mtime_to_sibling_max(path);
}

fn mtime_floor_disabled() -> bool {
    use std::sync::OnceLock;
    static CACHED: OnceLock<bool> = OnceLock::new();
    *CACHED.get_or_init(|| {
        std::env::var("ZCCACHE_DISABLE_MTIME_FLOOR")
            .ok()
            .is_some_and(|v| !v.is_empty() && v != "0")
    })
}

fn floor_artifact_mtime_to_sibling_max(path: &Path) -> std::io::Result<()> {
    let parent = match path.parent() {
        Some(p) => p,
        None => return Ok(()),
    };
    let my_mtime = std::fs::metadata(path)?.modified()?;
    let mut max_mtime = my_mtime;
    for entry in std::fs::read_dir(parent)?.flatten() {
        let p = entry.path();
        // Skip self — comparing against our own mtime is a no-op but
        // would waste a stat.
        if p == path {
            continue;
        }
        // Filter to artifact extensions cargo's `Fingerprint::outputs`
        // tracks. Other entries (.d depfiles, .json metadata,
        // .fingerprint state) don't participate in the StaleDependency
        // comparison.
        let ext = match p.extension().and_then(|s| s.to_str()) {
            Some(e) => e,
            None => continue,
        };
        if !matches!(
            ext,
            "rlib" | "rmeta" | "so" | "dylib" | "dll" | "exe" | "a" | "lib"
        ) {
            continue;
        }
        if let Ok(m) = entry.metadata().and_then(|md| md.modified()) {
            if m > max_mtime {
                max_mtime = m;
            }
        }
    }
    if max_mtime > my_mtime {
        let ft = filetime::FileTime::from_system_time(max_mtime);
        let _ = filetime::set_file_mtime(path, ft);
    }
    Ok(())
}

/// Check if two paths refer to the same file (hardlink check).
///
/// Returns `false` if either file doesn't exist or the check fails.
#[cfg(unix)]
pub(super) fn same_file(a: &Path, b: &Path) -> bool {
    use std::os::unix::fs::MetadataExt;
    match (std::fs::metadata(a), std::fs::metadata(b)) {
        (Ok(ma), Ok(mb)) => ma.dev() == mb.dev() && ma.ino() == mb.ino(),
        _ => false,
    }
}

#[cfg(windows)]
pub(super) fn same_file(a: &Path, b: &Path) -> bool {
    get_file_id(a)
        .zip(get_file_id(b))
        .map(|(ia, ib)| ia == ib)
        .unwrap_or(false)
}

/// Returns (volume_serial, file_index_high, file_index_low) for a path.
#[cfg(windows)]
pub(super) fn get_file_id(path: &Path) -> Option<(u32, u32, u32)> {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Foundation::CloseHandle;
    use windows_sys::Win32::Storage::FileSystem::{
        CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_NORMAL,
        FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
    };

    let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();

    unsafe {
        let handle = CreateFileW(
            wide.as_ptr(),
            0, // no access needed, just metadata
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            std::ptr::null(),
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            std::ptr::null_mut(),
        );
        if handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
            return None;
        }

        let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed();
        let ok = GetFileInformationByHandle(handle, &mut info);
        CloseHandle(handle);

        if ok == 0 {
            return None;
        }

        Some((
            info.dwVolumeSerialNumber,
            info.nFileIndexHigh,
            info.nFileIndexLow,
        ))
    }
}

#[cfg(test)]
mod tests {
    //! Tests for `floor_artifact_mtime_to_sibling_max` (issues #466 / #467).
    //!
    //! These exercise the dep-mtime-ordering fix in isolation, without
    //! standing up a full daemon. The function is private; the tests live
    //! in the same module so they can call it directly.

    use super::*;
    use std::time::{Duration, SystemTime};

    fn write_with_mtime(path: &Path, contents: &[u8], mtime: SystemTime) {
        std::fs::write(path, contents).unwrap();
        let ft = filetime::FileTime::from_system_time(mtime);
        filetime::set_file_mtime(path, ft).unwrap();
    }

    fn mtime_of(path: &Path) -> SystemTime {
        std::fs::metadata(path).unwrap().modified().unwrap()
    }

    fn epoch_plus(secs: u64) -> SystemTime {
        SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
    }

    #[test]
    fn floor_noop_when_target_dir_is_empty() {
        // Single artifact, no siblings — mtime must be preserved (iter7
        // invariant). The floor must not invent a value out of thin air.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("only.rlib");
        let before = epoch_plus(1_000_000);
        write_with_mtime(&target, b"x", before);

        floor_artifact_mtime_to_sibling_max(&target).unwrap();

        assert_eq!(mtime_of(&target), before);
    }

    #[test]
    fn floor_noop_when_already_newest() {
        // Target artifact already has the highest mtime among siblings —
        // floor must not lower it (this is the "fresh build" case).
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("newer.rlib");
        let older = dir.path().join("older.rlib");
        write_with_mtime(&target, b"t", epoch_plus(2_000_000));
        write_with_mtime(&older, b"o", epoch_plus(1_000_000));

        floor_artifact_mtime_to_sibling_max(&target).unwrap();

        assert_eq!(mtime_of(&target), epoch_plus(2_000_000));
    }

    #[test]
    fn floor_bumps_when_sibling_is_newer() {
        // The "cache hit out of order" case: zccache materialised the
        // dependent first (older cache mtime), the dep second (newer cache
        // mtime). Cargo's strict `dep_mtime > my_mtime → stale` would fire.
        // After floor, `my_mtime == dep_mtime`, satisfying `dep > my == false`.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("dependent.rlib");
        let dep = dir.path().join("dep.rlib");
        write_with_mtime(&target, b"t", epoch_plus(1_000_000));
        write_with_mtime(&dep, b"d", epoch_plus(2_000_000));

        floor_artifact_mtime_to_sibling_max(&target).unwrap();

        // Floored UP to the dep's mtime — cargo's check passes.
        assert_eq!(mtime_of(&target), epoch_plus(2_000_000));
        // Dep was not touched.
        assert_eq!(mtime_of(&dep), epoch_plus(2_000_000));
    }

    #[test]
    fn floor_ignores_non_artifact_files() {
        // Cargo's StaleDependency check looks at output artifacts only
        // (rlib/rmeta/so/dylib/dll/exe/a/lib). The floor must skip
        // depfiles (.d), fingerprint state, JSON sidecars, etc., so a
        // newer .d file doesn't artificially bump the artifact's mtime.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("art.rlib");
        let dep_file = dir.path().join("dep.d");
        let json_sidecar = dir.path().join("meta.json");
        write_with_mtime(&target, b"t", epoch_plus(1_000_000));
        write_with_mtime(&dep_file, b"d", epoch_plus(5_000_000));
        write_with_mtime(&json_sidecar, b"j", epoch_plus(5_000_000));

        floor_artifact_mtime_to_sibling_max(&target).unwrap();

        // .d and .json are filtered out — target mtime stays at its
        // original value.
        assert_eq!(mtime_of(&target), epoch_plus(1_000_000));
    }

    #[test]
    fn floor_idempotent_under_repeated_application() {
        // Subsequent cache hits for the same artifact must converge to a
        // stable mtime — otherwise cargo's "externally modified" check
        // (the original iter7 concern) would fire on repeat builds.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("art.rlib");
        let dep = dir.path().join("dep.rlib");
        write_with_mtime(&target, b"t", epoch_plus(1_000_000));
        write_with_mtime(&dep, b"d", epoch_plus(2_000_000));

        floor_artifact_mtime_to_sibling_max(&target).unwrap();
        let first = mtime_of(&target);
        floor_artifact_mtime_to_sibling_max(&target).unwrap();
        let second = mtime_of(&target);
        floor_artifact_mtime_to_sibling_max(&target).unwrap();
        let third = mtime_of(&target);

        assert_eq!(first, epoch_plus(2_000_000));
        assert_eq!(second, first);
        assert_eq!(third, first);
    }
}