zccache 1.12.5

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
//! Unit tests for the `ipc` module. Split out of `mod.rs` to keep that
//! file under the repo per-file LOC ceiling; included via `#[path]` from
//! `mod.rs` so `super` still resolves to the `ipc` module.

use super::test_env::ENV_LOCK;
use super::*;
use std::ffi::OsString;
use std::sync::MutexGuard;

struct EnvGuard {
    _lock: MutexGuard<'static, ()>,
    previous_cache_dir: Option<OsString>,
    previous_namespace: Option<OsString>,
    previous_running_process_disable: Option<OsString>,
}

impl EnvGuard {
    fn set_cache_dir(value: &std::path::Path) -> Self {
        let lock = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let previous_cache_dir = std::env::var_os(crate::core::config::CACHE_DIR_ENV);
        let previous_namespace = std::env::var_os(crate::core::config::DAEMON_NAMESPACE_ENV);
        let previous_running_process_disable = std::env::var_os(RUNNING_PROCESS_DISABLE_ENV);
        std::env::set_var(crate::core::config::CACHE_DIR_ENV, value);
        std::env::remove_var(crate::core::config::DAEMON_NAMESPACE_ENV);
        Self {
            _lock: lock,
            previous_cache_dir,
            previous_namespace,
            previous_running_process_disable,
        }
    }

    fn set_cache_dir_and_namespace(value: &std::path::Path, namespace: &str) -> Self {
        let lock = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let previous_cache_dir = std::env::var_os(crate::core::config::CACHE_DIR_ENV);
        let previous_namespace = std::env::var_os(crate::core::config::DAEMON_NAMESPACE_ENV);
        let previous_running_process_disable = std::env::var_os(RUNNING_PROCESS_DISABLE_ENV);
        std::env::set_var(crate::core::config::CACHE_DIR_ENV, value);
        std::env::set_var(crate::core::config::DAEMON_NAMESPACE_ENV, namespace);
        Self {
            _lock: lock,
            previous_cache_dir,
            previous_namespace,
            previous_running_process_disable,
        }
    }

    fn isolate_running_process_disable() -> Self {
        let lock = ENV_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let previous_cache_dir = std::env::var_os(crate::core::config::CACHE_DIR_ENV);
        let previous_namespace = std::env::var_os(crate::core::config::DAEMON_NAMESPACE_ENV);
        let previous_running_process_disable = std::env::var_os(RUNNING_PROCESS_DISABLE_ENV);
        std::env::remove_var(RUNNING_PROCESS_DISABLE_ENV);
        Self {
            _lock: lock,
            previous_cache_dir,
            previous_namespace,
            previous_running_process_disable,
        }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        match &self.previous_cache_dir {
            Some(value) => std::env::set_var(crate::core::config::CACHE_DIR_ENV, value),
            None => std::env::remove_var(crate::core::config::CACHE_DIR_ENV),
        }
        match &self.previous_namespace {
            Some(value) => std::env::set_var(crate::core::config::DAEMON_NAMESPACE_ENV, value),
            None => std::env::remove_var(crate::core::config::DAEMON_NAMESPACE_ENV),
        }
        match &self.previous_running_process_disable {
            Some(value) => std::env::set_var(RUNNING_PROCESS_DISABLE_ENV, value),
            None => std::env::remove_var(RUNNING_PROCESS_DISABLE_ENV),
        }
    }
}

fn test_daemon_status(endpoint: &str) -> crate::protocol::DaemonStatus {
    crate::protocol::DaemonStatus {
        version: crate::core::VERSION.to_string(),
        daemon_namespace: "test".to_string(),
        endpoint: endpoint.to_string(),
        private_daemon: crate::protocol::PrivateDaemonStatus::shared(),
        artifact_count: 0,
        cache_size_bytes: 0,
        metadata_entries: 0,
        uptime_secs: 1,
        cache_hits: 0,
        cache_misses: 0,
        total_compilations: 0,
        non_cacheable: 0,
        compile_errors: 0,
        compile_errors_cached: 0,
        time_saved_ms: 0,
        total_links: 0,
        link_hits: 0,
        link_misses: 0,
        link_non_cacheable: 0,
        dep_graph_contexts: 0,
        dep_graph_files: 0,
        sessions_total: 0,
        sessions_active: 0,
        cache_dir: std::env::temp_dir().into(),
        dep_graph_version: crate::depgraph::DEPGRAPH_VERSION,
        dep_graph_disk_size: 0,
        dep_graph_persisted: false,
    }
}

#[tokio::test]
async fn daemon_control_roundtrip_auto_prefers_prost_for_status() {
    let endpoint = unique_test_endpoint();
    let mut listener = IpcListener::bind(&endpoint).unwrap();
    let expected_endpoint = endpoint.clone();

    let server = tokio::spawn(async move {
        let mut conn = listener.accept().await.unwrap();
        let msg: Option<
            crate::protocol::DecodedWireMessage<
                crate::protocol::Request,
                crate::protocol::wire_prost::zccache_v1::Request,
            >,
        > = conn.recv_wire().await.unwrap();
        match msg {
            Some(crate::protocol::DecodedWireMessage::ProstV16(request)) => {
                assert_eq!(request.request_id, "control-status");
                assert!(matches!(
                    request.body,
                    Some(crate::protocol::wire_prost::zccache_v1::request::Body::Status(_))
                ));
                let response = Response::Status(test_daemon_status(&expected_endpoint));
                let response =
                    wire_prost::supported_control_response_to_prost(&response, &request.request_id)
                        .unwrap();
                conn.send_prost(&response).await.unwrap();
            }
            other => panic!("expected prost status request, got {other:?}"),
        }
    });

    let response = daemon_control_roundtrip_with_selection(
        &endpoint,
        DaemonControlRequest::Status,
        None,
        wire_prost::ClientWireSelection::Auto,
    )
    .await
    .unwrap();

    match response {
        Some(Response::Status(status)) => assert_eq!(status.endpoint, endpoint),
        other => panic!("expected Status response, got {other:?}"),
    }

    server.await.unwrap();
}

#[tokio::test]
async fn daemon_control_roundtrip_auto_prefers_prost_for_clear() {
    let endpoint = unique_test_endpoint();
    let mut listener = IpcListener::bind(&endpoint).unwrap();

    let server = tokio::spawn(async move {
        let mut conn = listener.accept().await.unwrap();
        let msg: Option<
            crate::protocol::DecodedWireMessage<
                crate::protocol::Request,
                crate::protocol::wire_prost::zccache_v1::Request,
            >,
        > = conn.recv_wire().await.unwrap();
        match msg {
            Some(crate::protocol::DecodedWireMessage::ProstV16(request)) => {
                assert_eq!(request.request_id, "control-clear");
                assert!(matches!(
                    request.body,
                    Some(crate::protocol::wire_prost::zccache_v1::request::Body::Clear(_))
                ));
                let response = Response::Cleared {
                    artifacts_removed: 1,
                    metadata_cleared: 2,
                    dep_graph_contexts_cleared: 3,
                    on_disk_bytes_freed: 4,
                };
                let response =
                    wire_prost::supported_control_response_to_prost(&response, &request.request_id)
                        .unwrap();
                conn.send_prost(&response).await.unwrap();
            }
            other => panic!("expected prost clear request, got {other:?}"),
        }
    });

    let response = daemon_control_roundtrip_with_selection(
        &endpoint,
        DaemonControlRequest::Clear,
        None,
        wire_prost::ClientWireSelection::Auto,
    )
    .await
    .unwrap();

    match response {
        Some(Response::Cleared {
            artifacts_removed,
            metadata_cleared,
            dep_graph_contexts_cleared,
            on_disk_bytes_freed,
        }) => {
            assert_eq!(artifacts_removed, 1);
            assert_eq!(metadata_cleared, 2);
            assert_eq!(dep_graph_contexts_cleared, 3);
            assert_eq!(on_disk_bytes_freed, 4);
        }
        other => panic!("expected Cleared response, got {other:?}"),
    }

    server.await.unwrap();
}

#[tokio::test]
async fn daemon_control_roundtrip_bincode_selection_stays_v15_for_status() {
    let endpoint = unique_test_endpoint();
    let mut listener = IpcListener::bind(&endpoint).unwrap();
    let expected_endpoint = endpoint.clone();

    let server = tokio::spawn(async move {
        let mut conn = listener.accept().await.unwrap();
        let request: Option<crate::protocol::Request> = conn.recv().await.unwrap();
        assert_eq!(request, Some(crate::protocol::Request::Status));
        conn.send(&Response::Status(test_daemon_status(&expected_endpoint)))
            .await
            .unwrap();
    });

    let response = daemon_control_roundtrip_with_selection(
        &endpoint,
        DaemonControlRequest::Status,
        None,
        wire_prost::ClientWireSelection::BincodeV15,
    )
    .await
    .unwrap();

    match response {
        Some(Response::Status(status)) => assert_eq!(status.endpoint, endpoint),
        other => panic!("expected bincode Status response, got {other:?}"),
    }

    server.await.unwrap();
}

#[tokio::test]
async fn daemon_control_roundtrip_auto_falls_back_to_bincode_for_old_daemon() {
    let endpoint = unique_test_endpoint();
    let mut listener = IpcListener::bind(&endpoint).unwrap();
    let expected_endpoint = endpoint.clone();

    let server = tokio::spawn(async move {
        let mut first = listener.accept().await.unwrap();
        let err = first
            .recv::<crate::protocol::Request>()
            .await
            .expect_err("v16 prost request must not decode as v15 bincode");
        assert!(matches!(
            err,
            IpcError::Protocol(crate::protocol::ProtocolError::VersionMismatch {
                expected: crate::protocol::BINCODE_PROTOCOL_VERSION,
                received: crate::protocol::PROST_PROTOCOL_VERSION,
            })
        ));
        first
            .send(&Response::Error {
                message: "protocol version mismatch: expected v15, received v16".to_string(),
            })
            .await
            .unwrap();

        let mut second = listener.accept().await.unwrap();
        let request: Option<crate::protocol::Request> = second.recv().await.unwrap();
        assert_eq!(request, Some(crate::protocol::Request::Status));
        second
            .send(&Response::Status(test_daemon_status(&expected_endpoint)))
            .await
            .unwrap();
    });

    let response = daemon_control_roundtrip_with_selection(
        &endpoint,
        DaemonControlRequest::Status,
        None,
        wire_prost::ClientWireSelection::Auto,
    )
    .await
    .unwrap();

    match response {
        Some(Response::Status(status)) => assert_eq!(status.endpoint, endpoint),
        other => panic!("expected fallback Status response, got {other:?}"),
    }

    server.await.unwrap();
}

/// Issue #720 Phase 1: with the broker lane active (here via the
/// fake-backend seam, which yields a `Broker` route), the control
/// roundtrip must carry real traffic over the version-checked 0x7A63
/// FrameV1 envelope rather than resolve-and-drop to a bincode re-dial.
/// The server asserts it decodes a `FrameV1` request and echoes a
/// FrameV1 response on the frame correlation id.
#[tokio::test]
async fn broker_lane_control_roundtrip_uses_frame_v1() {
    use super::broker::RUNNING_PROCESS_FAKE_BACKEND_ENV;
    use super::test_env::EnvVarGuard;

    let endpoint = unique_test_endpoint();
    let _env = EnvVarGuard::set_all(&[
        (RUNNING_PROCESS_DISABLE_ENV, None),
        (
            RUNNING_PROCESS_FAKE_BACKEND_ENV,
            Some(to_running_process_endpoint(&endpoint)),
        ),
        (ZCCACHE_BROKER_CONNECT_ENV, Some("1".to_string())),
    ]);

    let mut listener = IpcListener::bind(&endpoint).unwrap();
    let expected_endpoint = endpoint.clone();

    // The broker resolution dial connects and is dropped before the data
    // connection arrives, so keep accepting until the FrameV1 request lands.
    let server = tokio::spawn(async move {
        loop {
            let mut conn = match listener.accept().await {
                Ok(conn) => conn,
                Err(_) => return false,
            };
            let msg: Option<
                crate::protocol::DecodedWireMessage<
                    crate::protocol::Request,
                    wire_prost::zccache_v1::Request,
                >,
            > = match conn.recv_wire().await {
                Ok(msg) => msg,
                // Resolution dial closed without a payload; keep waiting.
                Err(_) => continue,
            };
            match msg {
                Some(crate::protocol::DecodedWireMessage::FrameV1 {
                    message,
                    request_id,
                }) => {
                    assert_eq!(message.request_id, "control-status");
                    assert!(matches!(
                        message.body,
                        Some(wire_prost::zccache_v1::request::Body::Status(_))
                    ));
                    let response = Response::Status(test_daemon_status(&expected_endpoint));
                    let response = wire_prost::supported_control_response_to_prost(
                        &response,
                        &message.request_id,
                    )
                    .unwrap();
                    conn.send_frame_v1_response(&response, request_id)
                        .await
                        .unwrap();
                    return true;
                }
                None => continue,
                Some(other) => panic!("expected FrameV1 status request, got {other:?}"),
            }
        }
    });

    let response = daemon_control_roundtrip_with_selection(
        &endpoint,
        DaemonControlRequest::Status,
        None,
        wire_prost::ClientWireSelection::Auto,
    )
    .await
    .unwrap();

    match response {
        Some(Response::Status(status)) => assert_eq!(status.endpoint, endpoint),
        other => panic!("expected Status response, got {other:?}"),
    }
    assert!(
        server.await.unwrap(),
        "server must have decoded a FrameV1 control request"
    );
}

#[test]
fn cache_dir_override_moves_endpoint_and_lock_file() {
    let root = tempfile::tempdir().unwrap();
    let cache_dir = root.path().join("zc");
    let _env = EnvGuard::set_cache_dir(&cache_dir);

    let endpoint = default_endpoint();
    #[cfg(unix)]
    assert_eq!(
        endpoint,
        cache_dir.join("daemon.sock").to_string_lossy().into_owned()
    );
    #[cfg(windows)]
    {
        assert!(endpoint.starts_with(r"\\.\pipe\zccache-"));
        assert!(endpoint.ends_with(&crate::core::stable_path_id(&cache_dir)));
    }

    assert_eq!(lock_file_path(), cache_dir.join("daemon.lock"));
}

#[test]
fn different_cache_roots_get_different_endpoints() {
    let a = NormalizedPath::from("/tmp/zccache-a");
    let b = NormalizedPath::from("/tmp/zccache-b");
    assert_ne!(
        endpoint_for_cache_dir(&a, None),
        endpoint_for_cache_dir(&b, None)
    );
}

#[test]
fn daemon_namespace_moves_endpoint_and_lock_file() {
    let root = tempfile::tempdir().unwrap();
    let cache_dir = root.path().join("zc");
    let _env = EnvGuard::set_cache_dir_and_namespace(&cache_dir, "soldr-dev");

    let endpoint = default_endpoint();
    #[cfg(unix)]
    assert_eq!(
        endpoint,
        cache_dir
            .join("daemon-soldr-dev.sock")
            .to_string_lossy()
            .into_owned()
    );
    #[cfg(windows)]
    {
        assert!(endpoint.starts_with(r"\\.\pipe\zccache-"));
        assert!(endpoint.ends_with("-soldr-dev"));
        assert!(endpoint.contains(&crate::core::stable_path_id(&cache_dir)));
    }

    assert_eq!(lock_file_path(), cache_dir.join("daemon-soldr-dev.lock"));
}

#[test]
fn same_cache_root_different_daemon_namespaces_do_not_share_identity() {
    let root = tempfile::tempdir().unwrap();
    let cache_dir = root.path().join("zc");

    let (endpoint_a, lock_a) = {
        let _env = EnvGuard::set_cache_dir_and_namespace(&cache_dir, "soldr-dev-a");
        (default_endpoint(), lock_file_path())
    };
    let (endpoint_b, lock_b) = {
        let _env = EnvGuard::set_cache_dir_and_namespace(&cache_dir, "soldr-dev-b");
        (default_endpoint(), lock_file_path())
    };

    assert_ne!(endpoint_a, endpoint_b);
    assert_ne!(lock_a, lock_b);
}

#[test]
fn running_process_disable_requires_exact_one() {
    let _env = EnvGuard::isolate_running_process_disable();

    assert!(!running_process_disabled());

    std::env::set_var(RUNNING_PROCESS_DISABLE_ENV, "true");
    assert!(!running_process_disabled());

    std::env::set_var(RUNNING_PROCESS_DISABLE_ENV, "1");
    assert!(running_process_disabled());
}

#[test]
fn private_daemon_name_derives_endpoint_from_cache_root() {
    let root = tempfile::tempdir().unwrap();
    let cache_dir = root.path().join("zc");
    let endpoint = endpoint_for_private_daemon_name(Some(&cache_dir), "soldr dev");

    #[cfg(unix)]
    assert_eq!(
        endpoint,
        cache_dir
            .join("daemon-soldr_dev.sock")
            .to_string_lossy()
            .into_owned()
    );
    #[cfg(windows)]
    {
        assert!(endpoint.starts_with(r"\\.\pipe\zccache-"));
        assert!(endpoint.ends_with("-soldr_dev"));
        assert!(endpoint.contains(&crate::core::stable_path_id(&cache_dir)));
    }
}

#[cfg(windows)]
#[test]
fn pipe_name_keeps_safe_username_endpoint_unchanged() {
    assert_eq!(pipe_name("zackees", None), r"\\.\pipe\zccache-zackees");
}

#[cfg(windows)]
#[test]
fn pipe_name_sanitizes_username_spaces() {
    let endpoint = pipe_name("Zach Vorhies", None);
    assert!(endpoint.starts_with(r"\\.\pipe\zccache-Zach_Vorhies-"));
    assert!(!endpoint.contains(' '));
}

#[cfg(unix)]
#[test]
fn cache_dir_endpoint_falls_back_to_short_unix_socket_path() {
    let root = tempfile::tempdir().unwrap();
    let cache_dir = root
        .path()
        .join("this")
        .join("is")
        .join("a")
        .join("deep")
        .join("private")
        .join("zccache")
        .join("cache")
        .join("directory")
        .join("that")
        .join("would")
        .join("exceed")
        .join("sockaddr_un")
        .join("path")
        .join("limits");

    let endpoint = endpoint_for_cache_dir(&cache_dir, Some("soldr-dev"));

    assert!(
        endpoint.len() <= MAX_PORTABLE_UNIX_SOCKET_PATH_BYTES,
        "endpoint too long: {endpoint}"
    );
    assert!(endpoint.starts_with("/tmp/zccache-"));
    assert!(endpoint.contains(&crate::core::stable_path_id(&cache_dir)));
    assert!(endpoint.ends_with("-daemon-soldr-dev.sock"));
}

/// On macOS, `daemon_exe_for_pid` must reject a PID whose
/// executable is something other than `zccache-daemon`. Until
/// `proc_pidpath` was wired up, this returned `None` and
/// `verify_pid_exe_stem` fell back to alive-only — which meant a
/// recycled PID in `daemon.lock` could keep the CLI talking to a
/// random process on a shared CI runner. This test would have
/// failed before that fix.
#[cfg(target_os = "macos")]
#[test]
fn recycled_pid_is_rejected_on_macos() {
    use std::process::Stdio;

    // `/bin/sleep 60` — guaranteed-alive, not zccache-daemon.
    let mut sleeper = std::process::Command::new("sleep")
        .arg("60")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn /bin/sleep");
    let pid = sleeper.id();

    let exe = daemon_exe_for_pid(pid);
    let verified = verify_pid_exe_stem(pid, "zccache-daemon");

    // Clean up before assertions so a panic doesn't orphan the child.
    let _ = sleeper.kill();
    let _ = sleeper.wait();

    let exe = exe.expect("proc_pidpath must succeed for an alive child");
    let basename = exe
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_owned();
    assert_eq!(
        basename, "sleep",
        "proc_pidpath should report `sleep` as the executable"
    );
    assert!(
        !verified,
        "verify_pid_exe_stem must reject a /bin/sleep PID even though it is alive"
    );
}

#[test]
fn exe_stem_matches_strips_exe_suffix_and_compares_basename() {
    use std::path::Path;
    assert!(exe_stem_matches(
        Path::new("/usr/bin/zccache-daemon"),
        "zccache-daemon"
    ));
    // A different binary at the same PID must not be accepted.
    assert!(!exe_stem_matches(
        Path::new("/usr/bin/bash"),
        "zccache-daemon"
    ));
    assert!(!exe_stem_matches(
        Path::new("/usr/bin/zccache-daemon-x"),
        "zccache-daemon"
    ));
}

/// Windows-only: backslash-separated paths require the OS-native
/// `Path::file_name` semantics. On Unix `\` is a regular filename
/// character, so the same assertion would fail there (issue #143).
#[cfg(windows)]
#[test]
fn exe_stem_matches_strips_exe_suffix_on_windows() {
    use std::path::Path;
    assert!(exe_stem_matches(
        Path::new(r"C:\bin\zccache-daemon.exe"),
        "zccache-daemon"
    ));
}

/// Regression test for issue #132: a stale `daemon.lock` restored from a
/// CI cache can carry a PID that's been recycled by an unrelated process
/// on a fresh runner. `check_running_daemon` must NOT report that process
/// as our daemon — otherwise `zccache stop` would `force_kill_process`
/// the unrelated process.
///
/// We use the test's own PID, which is guaranteed alive but is clearly
/// not zccache-daemon, then assert the lock file is treated as stale.
#[test]
fn stale_lock_with_recycled_pid_is_rejected() {
    let root = tempfile::tempdir().unwrap();
    let cache_dir = root.path().join("zc");
    let _env = EnvGuard::set_cache_dir(&cache_dir);

    let lock = lock_file_path();
    write_lock_file(std::process::id()).unwrap();
    assert!(lock.exists());

    // The test process is alive but is not zccache-daemon — must be rejected.
    // (On macOS we can't read the exe path, so this test relaxes there: see
    // `daemon_exe_for_pid` for the platform fallback.)
    #[cfg(any(target_os = "linux", windows))]
    {
        assert!(check_running_daemon().is_none());
        assert!(!lock.exists(), "stale lock file should have been removed");
    }
}

// ─── #640 probe_existing_daemon ───────────────────────────────────────

#[tokio::test]
async fn probe_returns_false_when_no_lock_file() {
    let cache = tempfile::tempdir().unwrap();
    let _env = EnvGuard::set_cache_dir(cache.path());
    // No lock file written.
    assert!(!probe_existing_daemon("anything", std::time::Duration::from_millis(50)).await);
}

#[tokio::test]
async fn probe_returns_false_when_lock_file_records_self_pid() {
    let cache = tempfile::tempdir().unwrap();
    let _env = EnvGuard::set_cache_dir(cache.path());
    // Self-PID early-out: we must NEVER probe our own process —
    // otherwise a sibling racing-init thread that wrote our PID
    // into the lock file would cause us to deadlock waiting for
    // ourselves to accept.
    write_lock_file(std::process::id()).unwrap();
    assert!(!probe_existing_daemon("anything", std::time::Duration::from_millis(50)).await);
}

#[tokio::test]
async fn probe_returns_false_when_lock_file_pid_is_not_a_daemon() {
    let cache = tempfile::tempdir().unwrap();
    let _env = EnvGuard::set_cache_dir(cache.path());
    // PID 1 exists everywhere (init / System) but is definitely not
    // zccache-daemon, so verify_daemon_pid rejects it. The probe
    // must short-circuit at the PID-verification step BEFORE
    // attempting any IPC connect — otherwise we'd waste the
    // timeout budget on a doomed handshake against init.
    write_lock_file(1).unwrap();
    let start = std::time::Instant::now();
    let result = probe_existing_daemon(
        "garbage-endpoint-that-could-never-exist",
        std::time::Duration::from_millis(500),
    )
    .await;
    let elapsed = start.elapsed();
    assert!(!result);
    // Short-circuit means we returned faster than the connect
    // timeout — proves we never attempted the connect.
    assert!(
        elapsed < std::time::Duration::from_millis(250),
        "probe should have short-circuited via verify_daemon_pid, \
             not waited for the connect timeout — elapsed {elapsed:?}"
    );
}