Skip to content

Commit 5fb9f54

Browse files
zackeesclaude
andauthored
fix(daemon): restore depfile on cache hit (closes #643) (#644)
* test(daemon): failing test for depfile restoration on hit (#643) Pins the bug: when zccache wraps `clang++ -MD -MF <depfile>` (the shape emitted by build systems with `deps = gcc`), a cache hit currently restores only the `.obj` — the user's `.d` is silently absent. The downstream build tool then records zero dependencies for the object and stops recompiling when included headers change, producing stale objects and `undefined symbol` link errors after `git pull`. Wires `current_depfile_dest: Option<NormalizedPath>` into `CachedHitMaterializeRequest` so the caller can supply *this build's* `-MF` destination on a hit (independent of where the depfile lived when the miss recorded it). The handler body intentionally does not yet consume the field — the next commit implements the restore and flips this test from RED to GREEN. Refs #643. * fix(daemon): restore depfile on cache hit (#643) When zccache wraps `clang++ -MD -MF <depfile>` (the shape build systems emit for `deps = gcc`), the miss path now captures the user's depfile bytes as a second artifact output, and the hit path writes them back alongside the `.obj` to the *current* build's `-MF` destination. Before this fix, only the `.obj` was restored on a hit. The build tool then read an absent depfile, recorded zero dependencies for the object, and stopped recompiling when included headers changed — silently producing stale objects and `undefined symbol` link errors after `git pull`. The depfile destination on hit is derived from the current request's dep_flags (not the cached basename), so renamed-output / cross-worktree hits restore the depfile to the correct place. Legacy single-output artifacts cached before this fix keep working unchanged: the hit-path materializer only consults `current_depfile_dest` when the artifact actually has a second payload. Cache-file mtime preservation is unchanged — the depfile write goes through the same `write_payloads_par_with_mtime_floor` path the `.obj` already used. Touched layers: - `depgraph::depfile::user_depfile_destination` — single source of truth for "where does the current build want its depfile?" - `pipeline::handle_compile_request` — on miss, after parse_depfile_path succeeds in `UserSpecified` / `UserDefault`, also reads the depfile bytes and threads them into `MissArtifactStoreRequest::user_depfile`. - `miss_store::store_single_output` — extends the artifact with a second output when `user_depfile` is `Some`. - `cached_hit::materialize_cached_compile_hit` — extra `current_depfile_dest` field; routes payloads[1] to it when both the artifact has two outputs and the field is `Some`. - `hit_branches::{try_fast_hit, try_depgraph_cached_hit}` — derive `current_depfile_dest` from passed-in `dep_flags`, also stamp it into the new `RequestCacheEntry::depfile_path` so the ultra-fast request cache path restores the depfile on subsequent hits. - `request_cache::RequestCacheEntry` + `keys::request_cache_entry` — store the depfile destination as a `CachedRequestPath` so cross-worktree fast-path hits rebase it to the new root. Coordinated with FastLED/FastLED — downstream stale-build investigation. Closes #643. * chore(tasks): revert unrelated tasks/todo.md rewrite The depfile-fix work accidentally overwrote the in-progress Static Library (.a) Caching planning content with its own scratch notes. This commit restores tasks/todo.md to main's content so the PR is scoped only to the depfile-on-cache-hit fix. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 67d1533 commit 5fb9f54

8 files changed

Lines changed: 402 additions & 6 deletions

File tree

‎crates/zccache/src/daemon/server/handle_compile/cached_hit.rs‎

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,16 @@ pub(super) struct CachedHitMaterializeRequest<'a> {
3333
pub(super) source_path: &'a NormalizedPath,
3434
pub(super) output_path: &'a NormalizedPath,
3535
pub(super) secondary_output_dir: NormalizedPath,
36+
/// Issue #643: where the current build wants its depfile restored.
37+
///
38+
/// When the user's compile line carries `-MD -MF <path>` (or `-MD` with
39+
/// an implicit `<output>.d`) and the cached artifact carries the
40+
/// depfile as its second payload, write payloads[1] to this path
41+
/// alongside writing payloads[0] to `output_path`. `None` on hits
42+
/// from compiles without depfile flags, and on artifacts cached before
43+
/// this fix landed (legacy single-output entries are honoured even
44+
/// when `Some(_)` is passed).
45+
pub(super) current_depfile_dest: Option<NormalizedPath>,
3646
pub(super) compile_start: Instant,
3747
pub(super) hit_label: &'static str,
3848
pub(super) cached_error_label: &'static str,
@@ -52,6 +62,7 @@ pub(super) fn materialize_cached_compile_hit(
5262
source_path,
5363
output_path,
5464
secondary_output_dir,
65+
current_depfile_dest,
5566
compile_start,
5667
hit_label,
5768
cached_error_label,
@@ -82,10 +93,25 @@ pub(super) fn materialize_cached_compile_hit(
8293
let artifact_bytes = cached_ref.meta.total_size;
8394
drop(cached_ref);
8495

96+
// Issue #643: when the miss path stashed the user's depfile bytes as a
97+
// second output and the current request supplies a `-MF` destination,
98+
// restore index 1 to *that* destination — not to the cached basename
99+
// under `secondary_output_dir`. The two paths are deliberately
100+
// independent: the cached name is just a payload identifier (preserved
101+
// for legacy / non-depfile multi-output artifacts), while the on-disk
102+
// destination must come from the current build's args. Restoring to
103+
// the cached path would write a stale-named depfile that no current
104+
// build tool is looking for, leaving the user's `-MF` target absent
105+
// and reproducing the exact stale-incremental-build bug this fix
106+
// closes.
85107
let targets: Vec<(NormalizedPath, NormalizedPath)> = (0..payloads.len())
86108
.map(|i| {
87109
let out: NormalizedPath = if i == 0 {
88110
output_path.clone()
111+
} else if i == 1 && payloads.len() == 2 {
112+
current_depfile_dest
113+
.clone()
114+
.unwrap_or_else(|| secondary_output_dir.join(&names[i]))
89115
} else {
90116
secondary_output_dir.join(&names[i])
91117
};
@@ -217,6 +243,7 @@ mod tests {
217243
source_path: &source_path,
218244
output_path: &output_path,
219245
secondary_output_dir: dir.path().into(),
246+
current_depfile_dest: None,
220247
compile_start: Instant::now(),
221248
hit_label: "HIT_TEST",
222249
cached_error_label: "CACHED_ERROR_TEST",
@@ -246,6 +273,192 @@ mod tests {
246273
assert_eq!(state.stats.snapshot().hits, 1);
247274
}
248275

276+
/// Issue #643: when zccache wraps `clang++ -MD -MF <depfile>` the user's
277+
/// depfile is part of the build-system's incremental-rebuild contract
278+
/// (e.g. `deps = gcc` in ninja). On a cache hit we currently restore
279+
/// only the `.obj` — the `.d` is silently absent, the build tool records
280+
/// zero dependencies for the object, and from then on it never
281+
/// recompiles when included headers change. Result: stale objects and
282+
/// mysterious `undefined symbol` link errors after `git pull`.
283+
///
284+
/// This test pins the fix: a cached artifact with two payloads (`.obj`
285+
/// at index 0, `.d` at index 1) plus an explicit current-build depfile
286+
/// destination must restore BOTH files. The cached `name` of the
287+
/// depfile output is just an identifier — the real destination on hit
288+
/// is supplied by the caller (it comes from the current compile's
289+
/// `-MF` argument, not from where the depfile happened to live when
290+
/// the cache miss recorded it).
291+
#[tokio::test(flavor = "current_thread")]
292+
async fn cached_hit_restores_user_depfile_alongside_object() {
293+
let dir = tempfile::tempdir().unwrap();
294+
let server = DaemonServer::bind(&crate::ipc::unique_test_endpoint()).unwrap();
295+
let state = server.state.as_ref();
296+
let cache_dir = state.artifact_dir.clone();
297+
298+
let source_path: NormalizedPath = dir.path().join("source.cc").into();
299+
let output_path: NormalizedPath = dir.path().join("source.o").into();
300+
// Critical: the destination depfile path used by *this* build is
301+
// not necessarily the cached basename. The caller derives it from
302+
// the current invocation's `-MF` (or default `<output>.d`) and
303+
// passes it in. Use a different filename to prove the fix routes
304+
// bytes by request, not by stored name.
305+
let depfile_dest: NormalizedPath = dir.path().join("build/out/source.o.d").into();
306+
307+
let obj_payload = Arc::new(b"compiled object bytes".to_vec());
308+
let dep_payload = Arc::new(
309+
b"source.o: source.cc header_a.h header_b.h\n\nheader_a.h:\n\nheader_b.h:\n".to_vec(),
310+
);
311+
let obj_cache_path = cache_dir.join("depfile-key_0");
312+
let dep_cache_path = cache_dir.join("depfile-key_1");
313+
std::fs::write(&obj_cache_path, obj_payload.as_slice()).unwrap();
314+
std::fs::write(&dep_cache_path, dep_payload.as_slice()).unwrap();
315+
316+
let sid = state.sessions.create(crate::depgraph::SessionConfig {
317+
client_pid: std::process::id(),
318+
working_dir: dir.path().into(),
319+
log_file: None,
320+
track_stats: true,
321+
journal_path: None,
322+
profile: false,
323+
private_env: Vec::new(),
324+
owner_pids: Vec::new(),
325+
});
326+
327+
// The cached `name[1]` is the basename from the original miss
328+
// (e.g. "source.o.d"). The destination on hit is independent and
329+
// comes from the current request.
330+
let meta = ArtifactIndex::new(
331+
vec!["source.o".to_string(), "source.o.d".to_string()],
332+
vec![obj_payload.len() as u64, dep_payload.len() as u64],
333+
Arc::new(Vec::new()),
334+
Arc::new(Vec::new()),
335+
0,
336+
);
337+
state.artifacts.insert(
338+
"depfile-key".to_string(),
339+
CachedArtifact::from_file_payloads(meta, vec![obj_cache_path, dep_cache_path]),
340+
);
341+
342+
let response = materialize_cached_compile_hit(CachedHitMaterializeRequest {
343+
state,
344+
sid: &sid,
345+
artifact_key_hex: "depfile-key",
346+
source_path: &source_path,
347+
output_path: &output_path,
348+
secondary_output_dir: dir.path().into(),
349+
current_depfile_dest: Some(depfile_dest.clone()),
350+
compile_start: Instant::now(),
351+
hit_label: "HIT_TEST",
352+
cached_error_label: "CACHED_ERROR_TEST",
353+
record_compilation: true,
354+
downgrade_output_metadata: true,
355+
mtime_floor_paths: Vec::new(),
356+
phases: CachedHitPhases::request_cache(0, 0),
357+
})
358+
.expect("materialize_cached_compile_hit must succeed");
359+
assert!(matches!(
360+
response,
361+
Response::CompileResult {
362+
cached: true,
363+
exit_code: 0,
364+
..
365+
}
366+
));
367+
368+
assert_eq!(
369+
std::fs::read(&output_path).unwrap(),
370+
obj_payload.as_slice(),
371+
"cache hit must restore the object at its destination",
372+
);
373+
assert!(
374+
depfile_dest.as_path().exists(),
375+
"cache hit must restore the depfile at the *current* build's -MF \
376+
destination ({}), not the cached basename — this is the #643 \
377+
stale-incremental-build fix",
378+
depfile_dest.display(),
379+
);
380+
assert_eq!(
381+
std::fs::read(depfile_dest.as_path()).unwrap(),
382+
dep_payload.as_slice(),
383+
"restored depfile bytes must match the cached payload",
384+
);
385+
}
386+
387+
/// Legacy contract: a 1-output cached artifact (no depfile recorded
388+
/// at miss time, e.g. compiles without `-MD`/`-MF`) must keep working
389+
/// even when the current request happens to supply a
390+
/// `current_depfile_dest`. The fix must not regress the
391+
/// pre-#643-store-format hit path.
392+
#[tokio::test(flavor = "current_thread")]
393+
async fn cached_hit_object_only_artifact_ignores_depfile_dest() {
394+
let dir = tempfile::tempdir().unwrap();
395+
let server = DaemonServer::bind(&crate::ipc::unique_test_endpoint()).unwrap();
396+
let state = server.state.as_ref();
397+
let cache_dir = state.artifact_dir.clone();
398+
399+
let source_path: NormalizedPath = dir.path().join("source.cc").into();
400+
let output_path: NormalizedPath = dir.path().join("source.o").into();
401+
let depfile_dest: NormalizedPath = dir.path().join("source.o.d").into();
402+
403+
let obj_payload = Arc::new(b"object only".to_vec());
404+
let cache_path = cache_dir.join("legacy-key_0");
405+
std::fs::write(&cache_path, obj_payload.as_slice()).unwrap();
406+
407+
let sid = state.sessions.create(crate::depgraph::SessionConfig {
408+
client_pid: std::process::id(),
409+
working_dir: dir.path().into(),
410+
log_file: None,
411+
track_stats: true,
412+
journal_path: None,
413+
profile: false,
414+
private_env: Vec::new(),
415+
owner_pids: Vec::new(),
416+
});
417+
418+
let meta = ArtifactIndex::new(
419+
vec!["source.o".to_string()],
420+
vec![obj_payload.len() as u64],
421+
Arc::new(Vec::new()),
422+
Arc::new(Vec::new()),
423+
0,
424+
);
425+
state.artifacts.insert(
426+
"legacy-key".to_string(),
427+
CachedArtifact::from_file_payloads(meta, vec![cache_path]),
428+
);
429+
430+
let response = materialize_cached_compile_hit(CachedHitMaterializeRequest {
431+
state,
432+
sid: &sid,
433+
artifact_key_hex: "legacy-key",
434+
source_path: &source_path,
435+
output_path: &output_path,
436+
secondary_output_dir: dir.path().into(),
437+
current_depfile_dest: Some(depfile_dest.clone()),
438+
compile_start: Instant::now(),
439+
hit_label: "HIT_TEST",
440+
cached_error_label: "CACHED_ERROR_TEST",
441+
record_compilation: true,
442+
downgrade_output_metadata: false,
443+
mtime_floor_paths: Vec::new(),
444+
phases: CachedHitPhases::request_cache(0, 0),
445+
})
446+
.expect("legacy single-output hit must still succeed");
447+
assert!(matches!(
448+
response,
449+
Response::CompileResult {
450+
cached: true,
451+
exit_code: 0,
452+
..
453+
}
454+
));
455+
assert_eq!(std::fs::read(&output_path).unwrap(), obj_payload.as_slice());
456+
assert!(
457+
!depfile_dest.as_path().exists(),
458+
"legacy single-output artifact must NOT manufacture a depfile",
459+
);
460+
}
461+
249462
/// Issue #460: warm-hit materialization should stay under budget — the
250463
/// fix collapsed 9 clock reads per hit to 4. A future regression that
251464
/// reintroduces a syscall-per-phase pattern (or worse, a synchronous I/O
@@ -297,6 +510,7 @@ mod tests {
297510
source_path: &source_path,
298511
output_path: &output_path,
299512
secondary_output_dir: dir.path().into(),
513+
current_depfile_dest: None,
300514
compile_start: Instant::now(),
301515
hit_label: "HIT_TEST",
302516
cached_error_label: "CACHED_ERROR_TEST",

‎crates/zccache/src/daemon/server/handle_compile/hit_branches.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ use super::super::*;
44
use super::cached_hit::{
55
materialize_cached_compile_hit, CachedHitMaterializeRequest, CachedHitPhases,
66
};
7+
use crate::depgraph::depfile::user_depfile_destination;
8+
use crate::depgraph::UserDepFlags;
79

810
pub(super) struct RequestCacheHitProbe<'a> {
911
pub(super) state: &'a SharedState,
@@ -55,6 +57,15 @@ pub(super) fn try_request_cache_hit(probe: RequestCacheHitProbe<'_>) -> Option<R
5557
let output_path = req_entry
5658
.output_path
5759
.resolve(request_cache_key_root.as_deref());
60+
// Issue #643: rebase the cached depfile destination to the current
61+
// request's key root. For cross-worktree (`HIT_WORKTREE_REQUEST`)
62+
// hits, this routes the depfile to worktree B's path even though the
63+
// entry was created from worktree A — same semantics as
64+
// `source_path` / `output_path`.
65+
let current_depfile_dest: Option<NormalizedPath> = req_entry
66+
.depfile_path
67+
.as_ref()
68+
.map(|path| path.resolve(request_cache_key_root.as_deref()));
5869
let mtime_floor_paths: Vec<NormalizedPath> = req_entry
5970
.input_paths
6071
.iter()
@@ -99,6 +110,7 @@ pub(super) fn try_request_cache_hit(probe: RequestCacheHitProbe<'_>) -> Option<R
99110
source_path: &source_path,
100111
output_path: &output_path,
101112
secondary_output_dir: output_path.parent().unwrap_or(cwd).into(),
113+
current_depfile_dest,
102114
compile_start,
103115
hit_label,
104116
cached_error_label: "CACHED_ERROR_REQUEST",
@@ -122,6 +134,11 @@ pub(super) struct FastHitProbe<'a> {
122134
pub(super) cwd: &'a Path,
123135
pub(super) request_cache_key_root: &'a Option<NormalizedPath>,
124136
pub(super) client_env: Option<&'a [(String, String)]>,
137+
/// Issue #643: the user's parsed depfile flags. `None` for rustc (which
138+
/// uses its own dep-info mechanism); for C/C++ it carries the user's
139+
/// `-MD` / `-MF` so the hit can restore the depfile to the current
140+
/// build's destination.
141+
pub(super) dep_flags: Option<&'a UserDepFlags>,
125142
pub(super) is_rustc: bool,
126143
pub(super) worktree_equivalent_context: bool,
127144
pub(super) worktree_bound: bool,
@@ -144,6 +161,7 @@ pub(super) fn try_fast_hit(probe: FastHitProbe<'_>) -> Option<Response> {
144161
cwd,
145162
request_cache_key_root,
146163
client_env,
164+
dep_flags,
147165
is_rustc,
148166
worktree_equivalent_context,
149167
worktree_bound,
@@ -180,13 +198,16 @@ pub(super) fn try_fast_hit(probe: FastHitProbe<'_>) -> Option<Response> {
180198
"HIT_FAST"
181199
};
182200
let input_paths = request_cache_input_paths(state, &context_key, source_path, ctx);
201+
let current_depfile_dest: Option<NormalizedPath> =
202+
dep_flags.and_then(|flags| user_depfile_destination(flags, output_path.as_path()));
183203
let response = materialize_cached_compile_hit(CachedHitMaterializeRequest {
184204
state,
185205
sid,
186206
artifact_key_hex: &entry.artifact_key_hex,
187207
source_path,
188208
output_path,
189209
secondary_output_dir,
210+
current_depfile_dest: current_depfile_dest.clone(),
190211
compile_start,
191212
hit_label,
192213
cached_error_label: "CACHED_ERROR_FAST",
@@ -217,6 +238,7 @@ pub(super) fn try_fast_hit(probe: FastHitProbe<'_>) -> Option<Response> {
217238
context_key,
218239
source_path,
219240
output_path,
241+
current_depfile_dest.as_ref(),
220242
input_paths,
221243
request_cache_key_root.as_ref(),
222244
worktree_bound,
@@ -239,6 +261,11 @@ pub(super) struct DepgraphHitProbe<'a> {
239261
pub(super) cwd: &'a Path,
240262
pub(super) request_cache_key_root: &'a Option<NormalizedPath>,
241263
pub(super) client_env: Option<&'a [(String, String)]>,
264+
/// Issue #643: the user's parsed depfile flags. `None` for rustc.
265+
/// Used to derive `current_depfile_dest` for the cache hit and to
266+
/// stamp the request-cache entry so subsequent fast-path hits also
267+
/// restore the depfile.
268+
pub(super) dep_flags: Option<&'a UserDepFlags>,
242269
pub(super) is_rustc: bool,
243270
pub(super) worktree_equivalent_context: bool,
244271
pub(super) worktree_bound: bool,
@@ -265,6 +292,7 @@ pub(super) fn try_depgraph_cached_hit(probe: DepgraphHitProbe<'_>) -> Option<Res
265292
cwd,
266293
request_cache_key_root,
267294
client_env,
295+
dep_flags,
268296
is_rustc,
269297
worktree_equivalent_context,
270298
worktree_bound,
@@ -287,13 +315,16 @@ pub(super) fn try_depgraph_cached_hit(probe: DepgraphHitProbe<'_>) -> Option<Res
287315
"HIT"
288316
};
289317
let input_paths = request_cache_input_paths(state, &context_key, source_path, ctx);
318+
let current_depfile_dest: Option<NormalizedPath> =
319+
dep_flags.and_then(|flags| user_depfile_destination(flags, output_path.as_path()));
290320
let response = materialize_cached_compile_hit(CachedHitMaterializeRequest {
291321
state,
292322
sid,
293323
artifact_key_hex,
294324
source_path,
295325
output_path,
296326
secondary_output_dir,
327+
current_depfile_dest: current_depfile_dest.clone(),
297328
compile_start,
298329
hit_label,
299330
cached_error_label: "CACHED_ERROR",
@@ -336,6 +367,7 @@ pub(super) fn try_depgraph_cached_hit(probe: DepgraphHitProbe<'_>) -> Option<Res
336367
context_key,
337368
source_path,
338369
output_path,
370+
current_depfile_dest.as_ref(),
339371
input_paths,
340372
request_cache_key_root.as_ref(),
341373
worktree_bound,

0 commit comments

Comments
 (0)