zccache 1.11.0

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
//! Integration tests for static library (.a) caching.
//!
//! Tests the full flow: compile .o files → `ar rcsD` → cache hit/miss.

use zccache::daemon::DaemonServer;
use zccache::protocol::{Request, Response};

/// Helper: start a daemon server on a unique endpoint.
async fn start_daemon() -> (
    String,
    tokio::task::JoinHandle<()>,
    std::sync::Arc<tokio::sync::Notify>,
) {
    let endpoint = zccache::ipc::unique_test_endpoint();
    let mut server = DaemonServer::bind(&endpoint).unwrap();
    let shutdown = server.shutdown_handle();
    let handle = tokio::spawn(async move {
        server.run(0).await.unwrap();
    });
    (endpoint, handle, shutdown)
}

/// Create fake object files (ar doesn't validate content).
fn write_fake_objects(dir: &std::path::Path, names: &[&str]) {
    for (i, name) in names.iter().enumerate() {
        let content = format!("fake object file {} content {}", name, i);
        std::fs::write(dir.join(name), content).unwrap();
    }
}

fn run_test_command(cmd: &mut std::process::Command, description: &str) -> Result<(), String> {
    let output = cmd
        .output()
        .map_err(|e| format!("failed to run {description}: {e}"))?;
    if output.status.success() {
        return Ok(());
    }

    Err(format!(
        "{description} failed with status {}\nstdout:\n{}\nstderr:\n{}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    ))
}

fn setup_equivalent_c_root(
    compiler: &std::path::Path,
    archiver: &std::path::Path,
    root: &std::path::Path,
) -> Result<(), String> {
    std::fs::create_dir_all(root.join(".git")).unwrap();
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::create_dir_all(root.join("build")).unwrap();
    std::fs::create_dir_all(root.join("lib")).unwrap();
    std::fs::write(
        root.join("src/main.c"),
        "int dep(void);\nint main(void) { return dep(); }\n",
    )
    .unwrap();
    std::fs::write(root.join("src/dep.c"), "int dep(void) { return 0; }\n").unwrap();

    let mut cmd = std::process::Command::new(compiler);
    cmd.args(["-g0", "-c", "src/main.c", "-o", "build/main.o"])
        .current_dir(root);
    run_test_command(&mut cmd, "compile test object")?;

    let mut cmd = std::process::Command::new(compiler);
    cmd.args(["-g0", "-c", "src/dep.c", "-o", "build/dep.o"])
        .current_dir(root);
    run_test_command(&mut cmd, "compile test library object")?;

    let mut cmd = std::process::Command::new(archiver);
    cmd.args(["rcsD", "lib/libdep.a", "build/dep.o"])
        .current_dir(root);
    if run_test_command(&mut cmd, "archive test library").is_ok() {
        return Ok(());
    }

    let mut cmd = std::process::Command::new(archiver);
    cmd.args(["rcs", "lib/libdep.a", "build/dep.o"])
        .current_dir(root);
    run_test_command(&mut cmd, "archive test library")
}

fn linked_binary_name(stem: &str) -> String {
    if cfg!(windows) {
        format!("{stem}.exe")
    } else {
        stem.to_string()
    }
}

fn compiler_driver_link_args(root: &std::path::Path, output: &std::path::Path) -> Vec<String> {
    vec![
        "-o".to_string(),
        output.to_string_lossy().into_owned(),
        "build/main.o".to_string(),
        format!("-L{}", root.join("lib").to_string_lossy()),
        "-ldep".to_string(),
    ]
}

fn compiler_driver_link_is_feasible(
    compiler: &std::path::Path,
    archiver: &std::path::Path,
) -> Result<(), String> {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("repo");
    setup_equivalent_c_root(compiler, archiver, &root)?;

    let output = root.join("build").join(linked_binary_name("probe"));
    let args = compiler_driver_link_args(&root, &output);
    let mut cmd = std::process::Command::new(compiler);
    cmd.args(&args).current_dir(&root);
    run_test_command(&mut cmd, "probe compiler-driver link")?;
    std::fs::remove_file(output).ok();
    Ok(())
}

fn client_env_with_path_remap_auto() -> Vec<(String, String)> {
    let mut env: Vec<(String, String)> = std::env::vars_os()
        .filter_map(|(key, value)| {
            let key = key.into_string().ok()?;
            let value = value.into_string().ok()?;
            let zccache_root_var = key.eq_ignore_ascii_case("ZCCACHE_WORKTREE_ROOT");
            let zccache_remap_var = key.eq_ignore_ascii_case("ZCCACHE_PATH_REMAP");
            (!zccache_root_var && !zccache_remap_var).then_some((key, value))
        })
        .collect();
    env.push(("ZCCACHE_PATH_REMAP".to_string(), "auto".to_string()));
    env
}

#[tokio::test]
#[ignore] // Integration test — starts a real daemon. Run with `test --full`.
async fn test_ar_cache_miss_then_hit() {
    let ar_path = match zccache::test_support::find_on_path("ar") {
        Some(p) => p,
        None => {
            eprintln!("skipping test: ar not found on PATH");
            return;
        }
    };

    let tmp = tempfile::tempdir().unwrap();
    write_fake_objects(tmp.path(), &["a.o", "b.o"]);

    let output_lib = tmp.path().join("libfoo.a");

    let (endpoint, server_handle, shutdown) = start_daemon().await;
    let mut client = zccache::ipc::connect(&endpoint).await.unwrap();

    // First link — should be a cache miss
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),

            tool: ar_path.to_string_lossy().into_owned().into(),
            args: vec![
                "rcsD".to_string(),
                output_lib.to_string_lossy().into_owned(),
                tmp.path().join("a.o").to_string_lossy().into_owned(),
                tmp.path().join("b.o").to_string_lossy().into_owned(),
            ],
            cwd: tmp.path().to_string_lossy().into_owned().into(),
            env: None,
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::LinkResult {
            exit_code,
            cached,
            warning,
            ..
        }) => {
            assert_eq!(exit_code, 0, "ar should succeed");
            assert!(!cached, "first link should be a cache miss");
            assert!(warning.is_none(), "D flag present — no warning expected");
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    assert!(
        output_lib.exists(),
        "libfoo.a should exist after first link"
    );
    let first_size = std::fs::metadata(&output_lib).unwrap().len();
    assert!(first_size > 0, "archive should not be empty");
    let first_contents = std::fs::read(&output_lib).unwrap();

    // Delete the output so we can verify cache restores it
    std::fs::remove_file(&output_lib).unwrap();
    assert!(!output_lib.exists(), "libfoo.a should be deleted");

    // Second link — should be a cache hit
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),

            tool: ar_path.to_string_lossy().into_owned().into(),
            args: vec![
                "rcsD".to_string(),
                output_lib.to_string_lossy().into_owned(),
                tmp.path().join("a.o").to_string_lossy().into_owned(),
                tmp.path().join("b.o").to_string_lossy().into_owned(),
            ],
            cwd: tmp.path().to_string_lossy().into_owned().into(),
            env: None,
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::LinkResult {
            exit_code, cached, ..
        }) => {
            assert_eq!(exit_code, 0, "cached ar should succeed");
            assert!(cached, "second link should be a cache hit");
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    // Verify the cached output was restored
    assert!(
        output_lib.exists(),
        "cache hit should restore the archive file"
    );
    let second_contents = std::fs::read(&output_lib).unwrap();
    assert_eq!(
        first_contents, second_contents,
        "cached archive should be byte-identical"
    );

    shutdown.notify_one();
    server_handle.await.unwrap();
}

#[tokio::test]
#[ignore] // Integration test — starts a real daemon + compiler driver. Run with `test --full`.
async fn test_link_path_remap_auto_hits_across_sibling_git_roots() {
    let archiver = match zccache::test_support::find_on_path("ar")
        .or_else(|| zccache::test_support::find_on_path("llvm-ar"))
    {
        Some(path) => path,
        None => {
            eprintln!("skipping test: neither ar nor llvm-ar found on PATH");
            return;
        }
    };
    let mut skipped = Vec::new();
    let mut selected_compiler = None;
    for name in ["clang", "gcc"] {
        let Some(path) = zccache::test_support::find_on_path(name) else {
            skipped.push(format!("{name}: not found on PATH"));
            continue;
        };
        match compiler_driver_link_is_feasible(&path, &archiver) {
            Ok(()) => {
                selected_compiler = Some(path);
                break;
            }
            Err(e) => skipped.push(format!("{name}: {e}")),
        }
    }

    let compiler_path = match selected_compiler {
        Some(path) => path,
        None => {
            eprintln!(
                "skipping test: no usable clang/gcc compiler-driver link found\n{}",
                skipped.join("\n")
            );
            return;
        }
    };

    let tmp = tempfile::tempdir().unwrap();
    let root_a = tmp.path().join("workspace-a");
    let root_b = tmp.path().join("workspace-b");
    setup_equivalent_c_root(&compiler_path, &archiver, &root_a).unwrap();
    setup_equivalent_c_root(&compiler_path, &archiver, &root_b).unwrap();

    let object_a = std::fs::read(root_a.join("build/main.o")).unwrap();
    let object_b = std::fs::read(root_b.join("build/main.o")).unwrap();
    if object_a != object_b {
        eprintln!("skipping test: compiler produced root-specific object bytes");
        return;
    }
    let lib_a = std::fs::read(root_a.join("lib/libdep.a")).unwrap();
    let lib_b = std::fs::read(root_b.join("lib/libdep.a")).unwrap();
    if lib_a != lib_b {
        eprintln!("skipping test: archiver produced root-specific library bytes");
        return;
    }

    let output_a = root_a.join("build").join(linked_binary_name("app"));
    let output_b = root_b.join("build").join(linked_binary_name("app"));
    assert_ne!(
        output_a, output_b,
        "test must use distinct physical output paths"
    );

    let (endpoint, server_handle, shutdown) = start_daemon().await;
    let mut client = zccache::ipc::connect(&endpoint).await.unwrap();

    // Clear persisted artifacts to ensure test isolation from prior runs.
    client.send(&Request::Clear).await.unwrap();
    let _: Option<Response> = client.recv().await.unwrap();

    let remap_env = client_env_with_path_remap_auto();

    // First root: populate the link cache. The absolute -L path is under root A.
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),
            tool: compiler_path.to_string_lossy().into_owned().into(),
            args: compiler_driver_link_args(&root_a, &output_a),
            cwd: root_a.to_string_lossy().into_owned().into(),
            env: Some(remap_env.clone()),
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::LinkResult {
            exit_code,
            cached,
            warning,
            ..
        }) => {
            assert_eq!(exit_code, 0, "first compiler-driver link should succeed");
            assert!(!cached, "first link in root A should be a cache miss");
            assert!(
                warning.is_none(),
                "deterministic compiler-driver link should not warn"
            );
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    assert!(output_a.exists(), "root A output should exist after miss");
    assert!(
        !output_b.exists(),
        "root B output should not exist before its link"
    );
    let first_contents = std::fs::read(&output_a).unwrap();

    // Second root: same object bytes and root-equivalent -L path should hit.
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),
            tool: compiler_path.to_string_lossy().into_owned().into(),
            args: compiler_driver_link_args(&root_b, &output_b),
            cwd: root_b.to_string_lossy().into_owned().into(),
            env: Some(remap_env),
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::LinkResult {
            exit_code, cached, ..
        }) => {
            assert_eq!(exit_code, 0, "cached compiler-driver link should succeed");
            assert!(
                cached,
                "ZCCACHE_PATH_REMAP=auto should make root-equivalent -L flags hit"
            );
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    assert!(
        output_a.exists(),
        "cache hit in root B should preserve root A output"
    );
    assert!(
        output_b.exists(),
        "cache hit should restore output at root B's physical path"
    );
    assert_eq!(
        first_contents,
        std::fs::read(&output_b).unwrap(),
        "root B hit should restore the cached root A link output"
    );

    shutdown.notify_one();
    server_handle.await.unwrap();
}

#[tokio::test]
#[ignore] // Integration test — starts a real daemon. Run with `test --full`.
async fn test_ar_cache_invalidated_on_input_change() {
    let ar_path = match zccache::test_support::find_on_path("ar") {
        Some(p) => p,
        None => {
            eprintln!("skipping test: ar not found on PATH");
            return;
        }
    };

    let tmp = tempfile::tempdir().unwrap();
    write_fake_objects(tmp.path(), &["x.o", "y.o"]);

    let output_lib = tmp.path().join("libbar.a");

    let (endpoint, server_handle, shutdown) = start_daemon().await;
    let mut client = zccache::ipc::connect(&endpoint).await.unwrap();

    let make_args = |lib: &std::path::Path, dir: &std::path::Path| -> Vec<String> {
        vec![
            "rcsD".to_string(),
            lib.to_string_lossy().into_owned(),
            dir.join("x.o").to_string_lossy().into_owned(),
            dir.join("y.o").to_string_lossy().into_owned(),
        ]
    };

    // First link — cache miss
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),

            tool: ar_path.to_string_lossy().into_owned().into(),
            args: make_args(&output_lib, tmp.path()),
            cwd: tmp.path().to_string_lossy().into_owned().into(),
            env: None,
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match &resp {
        Some(Response::LinkResult {
            exit_code, cached, ..
        }) => {
            assert_eq!(*exit_code, 0);
            assert!(!cached, "first link should miss");
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    let original_archive = std::fs::read(&output_lib).unwrap();

    // Modify one input file
    std::fs::write(tmp.path().join("x.o"), "MODIFIED content for x.o").unwrap();

    // Delete output so we can verify it gets recreated
    std::fs::remove_file(&output_lib).unwrap();

    // Third link — should be a cache miss (input changed)
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),

            tool: ar_path.to_string_lossy().into_owned().into(),
            args: make_args(&output_lib, tmp.path()),
            cwd: tmp.path().to_string_lossy().into_owned().into(),
            env: None,
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::LinkResult {
            exit_code, cached, ..
        }) => {
            assert_eq!(exit_code, 0);
            assert!(!cached, "link after input change should be a cache miss");
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    // The new archive should differ from the original
    let new_archive = std::fs::read(&output_lib).unwrap();
    assert_ne!(
        original_archive, new_archive,
        "archive should differ after input change"
    );

    shutdown.notify_one();
    server_handle.await.unwrap();
}

#[tokio::test]
#[ignore] // Integration test — starts a real daemon. Run with `test --full`.
async fn test_ar_non_deterministic_warning() {
    let ar_path = match zccache::test_support::find_on_path("ar") {
        Some(p) => p,
        None => {
            eprintln!("skipping test: ar not found on PATH");
            return;
        }
    };

    let tmp = tempfile::tempdir().unwrap();
    write_fake_objects(tmp.path(), &["a.o"]);

    let output_lib = tmp.path().join("libwarn.a");

    let (endpoint, server_handle, shutdown) = start_daemon().await;
    let mut client = zccache::ipc::connect(&endpoint).await.unwrap();

    // ar rcs (no D flag) — should warn about non-determinism
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),

            tool: ar_path.to_string_lossy().into_owned().into(),
            args: vec![
                "rcs".to_string(),
                output_lib.to_string_lossy().into_owned(),
                tmp.path().join("a.o").to_string_lossy().into_owned(),
            ],
            cwd: tmp.path().to_string_lossy().into_owned().into(),
            env: None,
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::LinkResult {
            exit_code,
            cached,
            warning,
            ..
        }) => {
            assert_eq!(exit_code, 0, "ar should succeed even without D flag");
            assert!(!cached, "first invocation should be a cache miss");
            assert!(
                warning.is_some(),
                "should warn about non-deterministic invocation"
            );
            let w = warning.unwrap();
            assert!(
                w.contains("non-deterministic"),
                "warning should mention non-determinism: {w}"
            );
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    // The archive should still be produced
    assert!(output_lib.exists(), "ar should produce output");

    shutdown.notify_one();
    server_handle.await.unwrap();
}

#[tokio::test]
#[ignore] // Integration test — starts a real daemon. Run with `test --full`.
async fn test_ar_non_cacheable_passthrough() {
    let ar_path = match zccache::test_support::find_on_path("ar") {
        Some(p) => p,
        None => {
            eprintln!("skipping test: ar not found on PATH");
            return;
        }
    };

    let tmp = tempfile::tempdir().unwrap();
    write_fake_objects(tmp.path(), &["a.o"]);

    // First, create an archive we can list
    let lib_path = tmp.path().join("liblist.a");
    let status = std::process::Command::new(&ar_path)
        .args([
            "rcsD",
            &lib_path.to_string_lossy(),
            &tmp.path().join("a.o").to_string_lossy(),
        ])
        .status()
        .unwrap();
    assert!(status.success(), "ar rcsD should succeed");

    let (endpoint, server_handle, shutdown) = start_daemon().await;
    let mut client = zccache::ipc::connect(&endpoint).await.unwrap();

    // ar t (list operation) — non-cacheable, should pass through
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),

            tool: ar_path.to_string_lossy().into_owned().into(),
            args: vec!["t".to_string(), lib_path.to_string_lossy().into_owned()],
            cwd: tmp.path().to_string_lossy().into_owned().into(),
            env: None,
        })
        .await
        .unwrap();

    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::LinkResult {
            exit_code,
            cached,
            stdout,
            ..
        }) => {
            assert_eq!(exit_code, 0, "ar t should succeed");
            assert!(!cached, "non-cacheable operation should not be cached");
            let output = String::from_utf8_lossy(&stdout);
            assert!(
                output.contains("a.o"),
                "ar t should list archive members: {output}"
            );
        }
        other => panic!("expected LinkResult, got: {other:?}"),
    }

    shutdown.notify_one();
    server_handle.await.unwrap();
}

#[tokio::test]
#[ignore] // Integration test — starts a real daemon. Run with `test --full`.
async fn test_link_stats_in_status() {
    let ar_path = match zccache::test_support::find_on_path("ar") {
        Some(p) => p,
        None => {
            eprintln!("skipping test: ar not found on PATH");
            return;
        }
    };

    let tmp = tempfile::tempdir().unwrap();
    write_fake_objects(tmp.path(), &["s.o"]);

    let output_lib = tmp.path().join("libstats.a");

    let (endpoint, server_handle, shutdown) = start_daemon().await;
    let mut client = zccache::ipc::connect(&endpoint).await.unwrap();

    // One deterministic link — cache miss
    client
        .send(&Request::LinkEphemeral {
            client_pid: std::process::id(),

            tool: ar_path.to_string_lossy().into_owned().into(),
            args: vec![
                "rcsD".to_string(),
                output_lib.to_string_lossy().into_owned(),
                tmp.path().join("s.o").to_string_lossy().into_owned(),
            ],
            cwd: tmp.path().to_string_lossy().into_owned().into(),
            env: None,
        })
        .await
        .unwrap();
    let _: Option<Response> = client.recv().await.unwrap(); // consume response

    // Check status — should show link stats
    client.send(&Request::Status).await.unwrap();
    let resp = client.recv().await.unwrap();
    match resp {
        Some(Response::Status(s)) => {
            assert!(
                s.total_links >= 1,
                "status should show at least 1 link: total_links={}",
                s.total_links
            );
            assert!(
                s.link_misses >= 1,
                "status should show at least 1 link miss: link_misses={}",
                s.link_misses
            );
        }
        other => panic!("expected Status response, got: {other:?}"),
    }

    shutdown.notify_one();
    server_handle.await.unwrap();
}