zccache 1.12.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
//! Tests for the in-memory request / response / fast-hit cache trim
//! routines: age-based eviction, hard-cap clears, freshness checks, and
//! cross-root resolution of cached input paths.

use std::path::Path;

use super::super::*;

fn test_context_key(source: &str) -> ContextKey {
    CompileContext {
        source_file: source.into(),
        include_search: crate::depgraph::IncludeSearchPaths::default(),
        defines: Vec::new(),
        flags: Vec::new(),
        force_includes: Vec::new(),
        unknown_flags: Vec::new(),
    }
    .context_key()
}

fn test_request_entry(cached_at: std::time::Instant) -> RequestCacheEntry {
    let context_key = test_context_key("/tmp/source.c");
    let source_path: NormalizedPath = "/tmp/source.c".into();
    let output_path: NormalizedPath = "/tmp/source.o".into();
    RequestCacheEntry {
        context_key,
        root: None,
        source_path: CachedRequestPath::capture(&source_path, None),
        output_path: CachedRequestPath::capture(&output_path, None),
        depfile_path: None,
        input_paths: vec![CachedRequestPath::capture(&source_path, None)],
        cross_root_shareable: false,
        cached_at,
    }
}

fn test_rsp_entry(cached_at: std::time::Instant) -> RspCacheEntry {
    RspCacheEntry {
        expanded: Vec::new(),
        dependencies: Vec::new(),
        cached_at,
    }
}

fn test_fast_hit_entry(cached_at: std::time::Instant) -> FastHitEntry {
    FastHitEntry {
        clock: Clock::ZERO,
        artifact_key_hex: "artifact".to_string(),
        cached_at,
    }
}

fn test_content_hash(index: usize) -> ContentHash {
    let mut bytes = [0; 32];
    bytes[..8].copy_from_slice(&(index as u64).to_le_bytes());
    ContentHash::from_bytes(bytes)
}

fn test_request_validation_key(index: usize, root: &Path) -> RequestValidationKey {
    RequestValidationKey {
        request_fp: test_content_hash(index),
        root: NormalizedPath::new(root),
    }
}

fn test_request_validation_entry(cached_at: std::time::Instant) -> RequestValidationEntry {
    RequestValidationEntry {
        artifact_key_hex: "artifact".to_string(),
        clock: Clock::ZERO,
        cached_at,
    }
}

#[test]
fn trim_request_cache_removes_old_entries() {
    let cache = DashMap::new();
    let max_age = std::time::Duration::from_millis(10);
    let old_at = std::time::Instant::now();
    let now = old_at.checked_add(max_age * 2).unwrap();
    cache.insert(ContentHash::from_bytes([2; 32]), test_request_entry(old_at));
    cache.insert(ContentHash::from_bytes([1; 32]), test_request_entry(now));

    let removed = trim_request_cache_at(&cache, max_age, now);

    assert_eq!(removed, 1);
    assert_eq!(cache.len(), 1);
    assert!(cache.contains_key(&ContentHash::from_bytes([1; 32])));
}

#[test]
fn cache_entry_freshness_uses_supplied_timestamp() {
    let max_age = std::time::Duration::from_millis(10);
    let cached_at = std::time::Instant::now();
    let compile_start = cached_at.checked_add(max_age / 2).unwrap();
    let later_check = cached_at.checked_add(max_age * 2).unwrap();

    assert!(cache_entry_fresh_at(compile_start, cached_at, max_age));
    assert!(!cache_entry_fresh_at(later_check, cached_at, max_age));
}

#[test]
fn trim_request_cache_keeps_future_entries() {
    let cache = DashMap::new();
    let max_age = std::time::Duration::from_millis(10);
    let now = std::time::Instant::now();
    let future = now.checked_add(max_age * 2).unwrap();
    cache.insert(ContentHash::from_bytes([1; 32]), test_request_entry(future));

    let removed = trim_request_cache_at(&cache, max_age, now);

    assert_eq!(removed, 0);
    assert_eq!(cache.len(), 1);
}

#[test]
fn trim_request_cache_clears_when_over_hard_cap() {
    let cache = DashMap::new();
    let now = std::time::Instant::now();
    for i in 0..=REQUEST_CACHE_MAX_ENTRIES {
        cache.insert(test_content_hash(i), test_request_entry(now));
    }

    let removed = trim_request_cache_at(&cache, EPHEMERAL_CACHE_MAX_AGE, now);

    assert_eq!(removed, REQUEST_CACHE_MAX_ENTRIES + 1);
    assert!(cache.is_empty());
}

#[test]
fn trim_request_validation_cache_removes_old_entries() {
    let cache = DashMap::new();
    let tmp = tempfile::tempdir().unwrap();
    let max_age = std::time::Duration::from_millis(10);
    let old_at = std::time::Instant::now();
    let now = old_at.checked_add(max_age * 2).unwrap();
    cache.insert(
        test_request_validation_key(1, &tmp.path().join("old-root")),
        test_request_validation_entry(old_at),
    );
    cache.insert(
        test_request_validation_key(2, &tmp.path().join("fresh-root")),
        test_request_validation_entry(now),
    );

    let removed = trim_request_validation_cache_at(&cache, max_age, now);

    assert_eq!(removed, 1);
    assert_eq!(cache.len(), 1);
    assert!(cache.contains_key(&test_request_validation_key(
        2,
        &tmp.path().join("fresh-root")
    )));
}

#[test]
fn trim_request_validation_cache_uses_its_own_larger_hard_cap_not_request_cache_max() {
    // #453: validation cache should have its own bound separate from the
    // request cache, sized larger (lighter per-entry → can hold more).
    // Filling it with REQUEST_CACHE_MAX_ENTRIES + 100 entries (4196) must
    // NOT trigger the hard-cap clear, because the validation cap is 8192.
    let cache = DashMap::new();
    let tmp = tempfile::tempdir().unwrap();
    let now = std::time::Instant::now();
    for i in 0..(REQUEST_CACHE_MAX_ENTRIES + 100) {
        cache.insert(
            test_request_validation_key(i, &tmp.path().join(format!("root-{i}"))),
            test_request_validation_entry(now),
        );
    }

    let removed = trim_request_validation_cache_at(&cache, EPHEMERAL_CACHE_MAX_AGE, now);

    assert_eq!(
        removed, 0,
        "validation cap is 8192, holding 4196 must not evict"
    );
    assert_eq!(cache.len(), REQUEST_CACHE_MAX_ENTRIES + 100);
    // Sanity: the new cap really is larger than the old shared one.
    const _: () = assert!(REQUEST_VALIDATION_CACHE_MAX_ENTRIES > REQUEST_CACHE_MAX_ENTRIES);
}

#[test]
fn trim_request_validation_cache_clears_when_over_validation_hard_cap() {
    // #453: when filled past the validation-specific cap (8192), the cache
    // is wiped just like request_cache is past its own cap.
    let cache = DashMap::new();
    let tmp = tempfile::tempdir().unwrap();
    let now = std::time::Instant::now();
    for i in 0..=REQUEST_VALIDATION_CACHE_MAX_ENTRIES {
        cache.insert(
            test_request_validation_key(i, &tmp.path().join(format!("root-{i}"))),
            test_request_validation_entry(now),
        );
    }

    let removed = trim_request_validation_cache_at(&cache, EPHEMERAL_CACHE_MAX_AGE, now);

    assert_eq!(removed, REQUEST_VALIDATION_CACHE_MAX_ENTRIES + 1);
    assert!(cache.is_empty());
}

#[test]
fn request_cache_resolved_inputs_requires_cross_root_shareable_entry() {
    let tmp = tempfile::tempdir().unwrap();
    let root_a = tmp.path().join("workspace-a");
    let root_b = tmp.path().join("workspace-b");
    let source_a: NormalizedPath = root_a.join("src/main.cc").into();
    let header_a: NormalizedPath = root_a.join("include/common.h").into();
    let output_a: NormalizedPath = root_a.join("build/main.o").into();
    let entry = request_cache_entry(
        test_context_key("src/main.cc"),
        &source_a,
        &output_a,
        None,
        vec![source_a.clone(), header_a],
        Some(&NormalizedPath::new(&root_a)),
        false,
    );

    let resolved = request_cache_resolved_inputs(&entry, &NormalizedPath::new(&root_b)).unwrap();

    assert_eq!(
        resolved,
        vec![
            NormalizedPath::new(root_b.join("src/main.cc")),
            NormalizedPath::new(root_b.join("include/common.h")),
        ]
    );
}

// Issue #489: PCH (and MSVC) artifacts bake absolute include paths into the
// compiled output. `path_remap=off` does not change that — there is no
// `-ffile-prefix-map` family of scrubbers that touches the PCH AST table. So
// even when every captured path looks root-relative, a request-level cache
// entry tagged `worktree_bound` must NEVER be served across worktrees, or the
// HIT serves a PCH whose embedded paths reference the original worktree.
//
// Before the fix, `cross_root_shareable` was derived solely from "are all
// paths root-relative?" — which is `true` for PCH (the `.h` lives inside the
// worktree), so a stale fastled10 PCH leaked into a fastled7 build and
// produced compiler diagnostics referencing `fastled10` paths + downstream
// DLL load failures (Windows error 126).
#[test]
fn request_cache_entry_worktree_bound_rejects_cross_worktree_match() {
    let tmp = tempfile::tempdir().unwrap();
    let root_a = NormalizedPath::new(tmp.path().join("fastled10"));
    let root_b = NormalizedPath::new(tmp.path().join("fastled7"));
    let source_a: NormalizedPath = root_a.as_path().join("src/FastLED.h").into();
    let output_a: NormalizedPath = root_a
        .as_path()
        .join(".build/meson-quick/ci/meson/native/FastLED.h.pch")
        .into();

    let pch_entry = request_cache_entry(
        test_context_key("src/FastLED.h"),
        &source_a,
        &output_a,
        None,
        vec![source_a.clone()],
        Some(&root_a),
        true,
    );

    // Same-root lookup: still HITs (sanity).
    assert!(request_cache_entry_matches_root(&pch_entry, Some(&root_a)));

    // Cross-root lookup: MUST NOT hit, even though every captured path was
    // root-relative when the entry was built.
    assert!(
        !request_cache_entry_matches_root(&pch_entry, Some(&root_b)),
        "PCH entries are worktree-bound and must not match across worktrees",
    );
    assert!(
        !pch_entry.cross_root_shareable,
        "worktree-bound entries must opt out of cross-root sharing entirely",
    );

    // Sanity contrast: an otherwise-identical NON-PCH entry (`worktree_bound = false`)
    // remains cross-root-shareable. The flag is the single discriminator.
    let object_entry = request_cache_entry(
        test_context_key("src/main.cc"),
        &source_a,
        &output_a,
        None,
        vec![source_a.clone()],
        Some(&root_a),
        false,
    );
    assert!(request_cache_entry_matches_root(
        &object_entry,
        Some(&root_b)
    ));
    assert!(object_entry.cross_root_shareable);
}

#[test]
fn request_cache_inputs_fresh_since_uses_journal_tracking() {
    let journal = crate::fscache::ChangeJournal::new();
    let path: NormalizedPath = "/tmp/request-cache-input.cc".into();
    let clock = journal.current_clock();

    assert!(!request_cache_inputs_fresh_since(
        &journal,
        std::slice::from_ref(&path),
        clock
    ));

    journal.register(path.clone());
    let validation_clock = journal.current_clock();
    assert!(request_cache_inputs_fresh_since(
        &journal,
        std::slice::from_ref(&path),
        validation_clock
    ));

    journal.advance(vec![path.clone()]);
    assert!(!request_cache_inputs_fresh_since(
        &journal,
        std::slice::from_ref(&path),
        validation_clock
    ));
}

#[test]
fn trim_rsp_cache_removes_old_entries() {
    let cache = DashMap::new();
    let max_age = std::time::Duration::from_millis(10);
    let old_at = std::time::Instant::now();
    let now = old_at.checked_add(max_age * 2).unwrap();
    cache.insert(NormalizedPath::from("/tmp/old.rsp"), test_rsp_entry(old_at));
    cache.insert(NormalizedPath::from("/tmp/fresh.rsp"), test_rsp_entry(now));

    let removed = trim_rsp_cache_at(&cache, max_age, now);

    assert_eq!(removed, 1);
    assert_eq!(cache.len(), 1);
    assert!(cache.contains_key(&NormalizedPath::from("/tmp/fresh.rsp")));
}

#[test]
fn trim_rsp_cache_keeps_future_entries() {
    let cache = DashMap::new();
    let max_age = std::time::Duration::from_millis(10);
    let now = std::time::Instant::now();
    let future = now.checked_add(max_age * 2).unwrap();
    cache.insert(
        NormalizedPath::from("/tmp/future.rsp"),
        test_rsp_entry(future),
    );

    let removed = trim_rsp_cache_at(&cache, max_age, now);

    assert_eq!(removed, 0);
    assert_eq!(cache.len(), 1);
}

#[test]
fn trim_rsp_cache_clears_when_over_hard_cap() {
    let cache = DashMap::new();
    let now = std::time::Instant::now();
    for i in 0..=RSP_CACHE_MAX_ENTRIES {
        cache.insert(
            NormalizedPath::from(format!("/tmp/args{i}.rsp")),
            test_rsp_entry(now),
        );
    }

    let removed = trim_rsp_cache_at(&cache, EPHEMERAL_CACHE_MAX_AGE, now);

    assert_eq!(removed, RSP_CACHE_MAX_ENTRIES + 1);
    assert!(cache.is_empty());
}

#[test]
fn trim_fast_hit_cache_removes_old_entries() {
    let cache = DashMap::new();
    let max_age = std::time::Duration::from_millis(10);
    let old_at = std::time::Instant::now();
    let now = old_at.checked_add(max_age * 2).unwrap();
    let old_key = test_context_key("/tmp/old.c");
    let fresh_key = test_context_key("/tmp/fresh.c");
    cache.insert(old_key, test_fast_hit_entry(old_at));
    cache.insert(fresh_key, test_fast_hit_entry(now));

    let removed = trim_fast_hit_cache_at(&cache, max_age, now);

    assert_eq!(removed, 1);
    assert_eq!(cache.len(), 1);
    assert!(cache.contains_key(&fresh_key));
}

#[test]
fn trim_fast_hit_cache_keeps_future_entries() {
    let cache = DashMap::new();
    let max_age = std::time::Duration::from_millis(10);
    let now = std::time::Instant::now();
    let future = now.checked_add(max_age * 2).unwrap();
    let key = test_context_key("/tmp/future.c");
    cache.insert(key, test_fast_hit_entry(future));

    let removed = trim_fast_hit_cache_at(&cache, max_age, now);

    assert_eq!(removed, 0);
    assert_eq!(cache.len(), 1);
}