zccache 1.12.9

Local-first compiler cache for C/C++/Rust/Emscripten
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
//! End-to-end IPC-based daemon tests: a real `DaemonServer` is started
//! on a unique endpoint, a client connects, and protocol roundtrips
//! (Ping, Status, Clear, Shutdown, SessionStart/End, Compile) are
//! validated. All marked `#[ignore]` so the default unit-test run stays
//! fast; the integration entrypoint opts them back in.

use super::super::*;
use super::CacheDirEnvGuard;

async fn start_daemon() -> (String, tokio::task::JoinHandle<()>, Arc<Notify>) {
    let endpoint = crate::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)
}

#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + file watcher
async fn test_server_ping_pong() {
    crate::test_support::test_timeout(async {
        let (endpoint, server_task, shutdown) = start_daemon().await;

        let mut client = crate::ipc::connect(&endpoint).await.unwrap();
        client.send(&Request::Ping).await.unwrap();
        let resp: Option<Response> = client.recv().await.unwrap();
        assert_eq!(resp, Some(Response::Pong));

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

#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + file watcher
async fn test_server_shutdown_request() {
    crate::test_support::test_timeout(async {
        let (endpoint, server_task, shutdown) = start_daemon().await;

        let mut client = crate::ipc::connect(&endpoint).await.unwrap();
        client.send(&Request::Shutdown).await.unwrap();
        let resp: Option<Response> = client.recv().await.unwrap();
        assert_eq!(resp, Some(Response::ShuttingDown));

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

#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + file watcher
async fn test_server_clear_empty() {
    crate::test_support::test_timeout(async {
        let (endpoint, server_task, shutdown) = start_daemon().await;

        let mut client = crate::ipc::connect(&endpoint).await.unwrap();
        client.send(&Request::Clear).await.unwrap();
        let resp: Option<Response> = client.recv().await.unwrap();
        match resp {
            Some(Response::Cleared {
                metadata_cleared,
                dep_graph_contexts_cleared,
                ..
            }) => {
                // artifacts_removed may be >0 if persistent cache has entries
                // from a prior run. Metadata and dep graph are always fresh.
                assert_eq!(metadata_cleared, 0);
                assert_eq!(dep_graph_contexts_cleared, 0);
            }
            other => panic!("expected Cleared, got: {other:?}"),
        }

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

#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + file watcher
async fn test_server_status() {
    crate::test_support::test_timeout(async {
        let tmp = tempfile::tempdir().unwrap();
        let _env = CacheDirEnvGuard::set(tmp.path());
        let (endpoint, server_task, shutdown) = start_daemon().await;

        let mut client = crate::ipc::connect(&endpoint).await.unwrap();
        client.send(&Request::Status).await.unwrap();
        let resp: Option<Response> = client.recv().await.unwrap();
        match resp {
            Some(Response::Status(status)) => {
                assert_eq!(status.endpoint, endpoint);
                assert_eq!(
                    status.daemon_namespace,
                    crate::core::config::DEFAULT_DAEMON_NAMESPACE
                );
            }
            other => panic!("expected Status, got: {other:?}"),
        }

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

// ── CLI session flow tests (IPC-based) ──────────────────────────────

/// Full session lifecycle: start → compile (miss) → compile (hit) → end.
#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + file watcher
async fn test_server_status_reports_explicit_daemon_namespace() {
    crate::test_support::test_timeout(async {
        let tmp = tempfile::tempdir().unwrap();
        let _env = CacheDirEnvGuard::set_with_namespace(tmp.path(), "soldr-dev");
        let (endpoint, server_task, shutdown) = start_daemon().await;

        let mut client = crate::ipc::connect(&endpoint).await.unwrap();
        client.send(&Request::Status).await.unwrap();
        let resp: Option<Response> = client.recv().await.unwrap();
        match resp {
            Some(Response::Status(status)) => {
                assert_eq!(status.endpoint, endpoint);
                assert_eq!(status.daemon_namespace, "soldr-dev");
            }
            other => panic!("expected Status, got: {other:?}"),
        }

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

#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + file watcher
async fn private_session_start_registers_redacted_status_and_owner_refs() {
    crate::test_support::test_timeout(async {
        let tmp = tempfile::tempdir().unwrap();
        let _env = CacheDirEnvGuard::set_with_namespace(tmp.path(), "soldr-dev");
        let (endpoint, server_task, shutdown) = start_daemon().await;

        let mut client = crate::ipc::connect(&endpoint).await.unwrap();
        client
            .send(&Request::SessionStart {
                client_pid: std::process::id(),
                working_dir: tmp.path().into(),
                log_file: None,
                track_stats: false,
                journal_path: None,
                profile: false,
                private_daemon: Some(crate::protocol::PrivateDaemonSessionOptions {
                    daemon_name: Some("soldr-dev".to_string()),
                    endpoint: Some(endpoint.clone()),
                    cache_dir: Some(crate::core::config::default_cache_dir()),
                    owner_pids: vec![std::process::id()],
                    env: vec![("ZCCACHE_PATH_REMAP".to_string(), "secret".to_string())],
                }),
            })
            .await
            .unwrap();
        let session_id = match client.recv().await.unwrap() {
            Some(Response::SessionStarted { session_id, .. }) => session_id,
            other => panic!("expected SessionStarted, got: {other:?}"),
        };

        client.send(&Request::Status).await.unwrap();
        match client.recv().await.unwrap() {
            Some(Response::Status(status)) => {
                assert!(status.private_daemon.enabled);
                assert_eq!(
                    status.private_daemon.private_env_keys,
                    vec!["ZCCACHE_PATH_REMAP"]
                );
                assert_eq!(status.private_daemon.owners.len(), 1);
                assert_eq!(status.private_daemon.owners[0].pid, std::process::id());
                assert_eq!(status.private_daemon.owners[0].ref_count, 1);
            }
            other => panic!("expected Status, got: {other:?}"),
        }

        client
            .send(&Request::SessionEnd { session_id })
            .await
            .unwrap();
        let _: Option<Response> = client.recv().await.unwrap();

        client.send(&Request::Status).await.unwrap();
        match client.recv().await.unwrap() {
            Some(Response::Status(status)) => {
                assert!(status.private_daemon.enabled);
                assert!(status.private_daemon.owners.is_empty());
            }
            other => panic!("expected Status, got: {other:?}"),
        }

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

#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + file watcher
async fn private_session_start_accepts_top_level_cache_root() {
    crate::test_support::test_timeout(async {
        let tmp = tempfile::tempdir().unwrap();
        let _env = CacheDirEnvGuard::set_with_namespace(tmp.path(), "soldr-dev-parent-root");
        let (endpoint, server_task, shutdown) = start_daemon().await;

        let mut client = crate::ipc::connect(&endpoint).await.unwrap();
        client
            .send(&Request::SessionStart {
                client_pid: std::process::id(),
                working_dir: tmp.path().into(),
                log_file: None,
                track_stats: false,
                journal_path: None,
                profile: false,
                private_daemon: Some(crate::protocol::PrivateDaemonSessionOptions {
                    daemon_name: Some("soldr-dev-parent-root".to_string()),
                    endpoint: Some(endpoint.clone()),
                    cache_dir: Some(tmp.path().into()),
                    owner_pids: vec![std::process::id()],
                    env: Vec::new(),
                }),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::SessionStarted { .. }) => {}
            other => panic!("expected SessionStarted for top-level cache root, got: {other:?}"),
        }

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

#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + compiler
async fn cli_session_lifecycle() {
    let clang = match crate::test_support::find_clang() {
        Some(p) => p,
        None => return,
    };
    crate::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("hello.cpp");
        let obj = tmp.path().join("hello.o");
        let log = tmp.path().join("session.log");
        let cwd = tmp.path().to_string_lossy().into_owned();

        std::fs::write(
            &src,
            "#include <stdio.h>\nint main() { printf(\"hello\\n\"); return 0; }\n",
        )
        .unwrap();

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

        // session-start
        client
            .send(&Request::SessionStart {
                client_pid: std::process::id(),
                working_dir: cwd.clone().into(),
                log_file: Some(log.to_string_lossy().into_owned().into()),
                track_stats: false,
                journal_path: None,
                profile: false,
                private_daemon: None,
            })
            .await
            .unwrap();

        let session_id = match client.recv().await.unwrap() {
            Some(Response::SessionStarted { session_id, .. }) => session_id,
            other => panic!("expected SessionStarted, got: {other:?}"),
        };

        // first compile (cache miss)
        client
            .send(&Request::Compile {
                session_id: session_id.clone(),
                args: vec![
                    "-c".to_string(),
                    src.to_string_lossy().into_owned(),
                    "-o".to_string(),
                    obj.to_string_lossy().into_owned(),
                ],
                cwd: cwd.clone().into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::CompileResult {
                exit_code, cached, ..
            }) => {
                assert_eq!(exit_code, 0, "first compile should succeed");
                assert!(!cached, "first compile should be a miss");
            }
            other => panic!("expected CompileResult, got: {other:?}"),
        }

        assert!(obj.exists(), ".o should exist after first compile");
        let obj_data = std::fs::read(&obj).unwrap();

        // second compile (cache hit)
        std::fs::remove_file(&obj).unwrap();

        client
            .send(&Request::Compile {
                session_id: session_id.clone(),
                args: vec![
                    "-c".to_string(),
                    src.to_string_lossy().into_owned(),
                    "-o".to_string(),
                    obj.to_string_lossy().into_owned(),
                ],
                cwd: cwd.clone().into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

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

        assert!(obj.exists(), ".o should exist after cached compile");
        let cached_data = std::fs::read(&obj).unwrap();
        assert_eq!(obj_data.len(), cached_data.len(), "cached .o should match");

        // session-end
        client
            .send(&Request::SessionEnd {
                session_id: session_id.clone(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::SessionEnded { .. }) => {}
            other => panic!("expected SessionEnded, got: {other:?}"),
        }

        // compile after session-end should fail
        client
            .send(&Request::Compile {
                session_id,
                args: vec!["-c".to_string(), src.to_string_lossy().into_owned()],
                cwd: cwd.clone().into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::Error { message }) => {
                assert!(
                    message.contains("unknown session"),
                    "should report unknown session after end: {message}"
                );
            }
            other => panic!("expected Error after session-end, got: {other:?}"),
        }

        // verify log
        let log_text = std::fs::read_to_string(&log).unwrap();
        assert!(log_text.contains("[MISS]"), "log should show miss");
        assert!(log_text.contains("[HIT]"), "log should show hit");

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

/// Ending a session with a malformed (non-UUID) ID returns an error.
#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC
async fn cli_session_end_invalid_id() {
    crate::test_support::test_timeout(async {
        let (endpoint, server_handle, shutdown) = start_daemon().await;
        let mut client = crate::ipc::connect(&endpoint).await.unwrap();

        client
            .send(&Request::SessionEnd {
                session_id: 999999.to_string(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::Error { message }) => {
                assert!(
                    message.contains("unknown session") || message.contains("invalid session"),
                    "expected session error, got: {message}"
                );
            }
            other => panic!("expected Error, got: {other:?}"),
        }

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

/// Ending an unknown session (well-formed UUID, but daemon has no record
/// of it) is idempotent and returns SessionEnded { stats: None }.
///
/// This simulates the scenario where the daemon was restarted between
/// `session-start` and `session-end` (e.g. zccache-ci kills the daemon
/// mid-build to unlock target binaries on Windows). Build wrappers like
/// soldr call `session-end` at process exit and must not see a spurious
/// failure when the in-memory session is gone.
#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC
async fn cli_session_end_unknown_uuid_is_idempotent() {
    crate::test_support::test_timeout(async {
        let (endpoint, server_handle, shutdown) = start_daemon().await;
        let mut client = crate::ipc::connect(&endpoint).await.unwrap();

        client
            .send(&Request::SessionEnd {
                // A well-formed UUID that the daemon has never seen.
                session_id: "00000000-0000-0000-0000-000000000000".to_string(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::SessionEnded { stats }) => {
                assert!(
                    stats.is_none(),
                    "no stats expected for unknown session, got: {stats:?}"
                );
            }
            other => panic!("expected SessionEnded for unknown UUID, got: {other:?}"),
        }

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

/// Regression for #166 — Compile on an unknown session must not fail with
/// "unknown session", mirroring #137's SessionEnd idempotency. Triggered
/// when zccache-ci kills the daemon mid-build (#167).
///
/// The daemon used to short-circuit Compile with `Response::Error` if the
/// session UUID was unknown. After a daemon restart, soldr-managed rustc
/// wrappers keep using the old session UUID and would all fail; soldr in
/// turn exits 1 and the whole build breaks. We now let the compile
/// proceed; only per-session stats are lost.
#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC
async fn cli_compile_unknown_uuid_is_idempotent() {
    crate::test_support::test_timeout(async {
        let tmp = tempfile::tempdir().unwrap();
        // Use an isolated cache dir so we don't clash with any
        // production daemon writing the global index blob.
        let _cache_dir = CacheDirEnvGuard::set(&tmp.path().join("zccache-cache"));

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

        let cwd = tmp.path().to_string_lossy().into_owned();

        // Send a Compile with a well-formed UUID the daemon has never
        // seen. We intentionally pass a bogus compiler path and trivial
        // args — the only assertion is that we don't get the
        // "unknown session" Error response that the pre-#166 code emitted
        // before any real compilation work began.
        client
            .send(&Request::Compile {
                session_id: "00000000-0000-0000-0000-000000000000".to_string(),
                args: vec!["--version".to_string()],
                cwd: cwd.clone().into(),
                compiler: "/nonexistent/compiler".to_string().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        // Any non-Error response is acceptable — typically a
        // CompileResult with a non-zero exit code because the compiler
        // path is bogus. The key invariant is the absence of the
        // pre-#166 "unknown session" hard error.
        if let Some(Response::Error { message }) = client.recv().await.unwrap() {
            assert!(
                !message.contains("unknown session"),
                "Compile must not fail with 'unknown session' on an unknown UUID, got: {message}"
            );
        }

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

/// Cache clear resets: miss → hit → clear → miss again.
#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + compiler
async fn cli_clear_resets_cache() {
    let clang = match crate::test_support::find_clang() {
        Some(p) => p,
        None => return,
    };

    crate::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("clear_test.cpp");
        let obj = tmp.path().join("clear_test.o");
        let cwd = tmp.path().to_string_lossy().into_owned();

        std::fs::write(&src, "int main() { return 0; }\n").unwrap();

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

        // Start session
        client
            .send(&Request::SessionStart {
                client_pid: std::process::id(),
                working_dir: cwd.clone().into(),
                log_file: None,
                track_stats: false,
                journal_path: None,
                profile: false,
                private_daemon: None,
            })
            .await
            .unwrap();

        let session_id = match client.recv().await.unwrap() {
            Some(Response::SessionStarted { session_id, .. }) => session_id,
            other => panic!("expected SessionStarted, got: {other:?}"),
        };

        let compile_args = vec![
            "-c".to_string(),
            src.to_string_lossy().into_owned(),
            "-o".to_string(),
            obj.to_string_lossy().into_owned(),
        ];

        // First compile → miss
        client
            .send(&Request::Compile {
                session_id: session_id.clone(),
                args: compile_args.clone(),
                cwd: cwd.clone().into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::CompileResult {
                exit_code, cached, ..
            }) => {
                assert_eq!(exit_code, 0);
                assert!(!cached, "first compile should be a miss");
            }
            other => panic!("expected CompileResult, got: {other:?}"),
        }

        // Second compile → hit
        std::fs::remove_file(&obj).unwrap();
        client
            .send(&Request::Compile {
                session_id: session_id.clone(),
                args: compile_args.clone(),
                cwd: cwd.clone().into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::CompileResult {
                exit_code, cached, ..
            }) => {
                assert_eq!(exit_code, 0);
                assert!(cached, "second compile should be a hit");
            }
            other => panic!("expected CompileResult, got: {other:?}"),
        }

        // Clear the cache
        client.send(&Request::Clear).await.unwrap();
        match client.recv().await.unwrap() {
            Some(Response::Cleared {
                artifacts_removed, ..
            }) => {
                assert!(
                    artifacts_removed > 0,
                    "should have cleared at least one artifact"
                );
            }
            other => panic!("expected Cleared, got: {other:?}"),
        }

        // End old session and start a new one
        client
            .send(&Request::SessionEnd { session_id })
            .await
            .unwrap();
        let _: Option<Response> = client.recv().await.unwrap();

        client
            .send(&Request::SessionStart {
                client_pid: std::process::id(),
                working_dir: cwd.clone().into(),
                log_file: None,
                track_stats: false,
                journal_path: None,
                profile: false,
                private_daemon: None,
            })
            .await
            .unwrap();

        let session_id2 = match client.recv().await.unwrap() {
            Some(Response::SessionStarted { session_id, .. }) => session_id,
            other => panic!("expected SessionStarted, got: {other:?}"),
        };

        // Compile again → should be a miss (cache was cleared)
        std::fs::remove_file(&obj).unwrap();
        client
            .send(&Request::Compile {
                session_id: session_id2,
                args: compile_args,
                cwd: cwd.into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::CompileResult {
                exit_code, cached, ..
            }) => {
                assert_eq!(exit_code, 0);
                assert!(!cached, "compile after clear should be a miss");
            }
            other => panic!("expected CompileResult, got: {other:?}"),
        }

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

/// Multi-file compilations fall back to running the compiler directly.
#[tokio::test]
#[ignore] // integration-level: starts real daemon with IPC + compiler
async fn cli_multi_file_compilation_runs_directly() {
    let clang = match crate::test_support::find_clang() {
        Some(p) => p,
        None => return,
    };

    crate::test_support::test_timeout(async move {
        let tmp = tempfile::tempdir().unwrap();
        let src_a = tmp.path().join("multi_a.cpp");
        let src_b = tmp.path().join("multi_b.cpp");
        let cwd = tmp.path().to_string_lossy().into_owned();

        std::fs::write(&src_a, "int foo() { return 1; }\n").unwrap();
        std::fs::write(&src_b, "int bar() { return 2; }\n").unwrap();

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

        // Start session
        client
            .send(&Request::SessionStart {
                client_pid: std::process::id(),
                working_dir: cwd.clone().into(),
                log_file: None,
                track_stats: true,
                journal_path: None,
                profile: false,
                private_daemon: None,
            })
            .await
            .unwrap();

        let session_id = match client.recv().await.unwrap() {
            Some(Response::SessionStarted { session_id, .. }) => session_id,
            other => panic!("expected SessionStarted, got: {other:?}"),
        };

        // First compile: multi-file → both are cache misses
        let multi_args = vec![
            "-c".to_string(),
            src_a.to_string_lossy().into_owned(),
            src_b.to_string_lossy().into_owned(),
        ];
        client
            .send(&Request::Compile {
                session_id: session_id.clone(),
                args: multi_args.clone(),
                cwd: cwd.clone().into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::CompileResult {
                exit_code, cached, ..
            }) => {
                assert_eq!(exit_code, 0, "multi-file compile should succeed");
                assert!(!cached, "first multi-file compile should be a miss");
            }
            other => panic!("expected CompileResult, got: {other:?}"),
        }

        // Verify both .o files were produced
        let obj_a = tmp.path().join("multi_a.o");
        let obj_b = tmp.path().join("multi_b.o");
        assert!(obj_a.exists(), "multi_a.o should exist");
        assert!(obj_b.exists(), "multi_b.o should exist");

        // Second compile: same files → should be all cache hits
        client
            .send(&Request::Compile {
                session_id: session_id.clone(),
                args: multi_args,
                cwd: cwd.clone().into(),
                compiler: clang.to_string_lossy().into_owned().into(),
                env: None,
                stdin: Vec::new(),
            })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::CompileResult {
                exit_code, cached, ..
            }) => {
                assert_eq!(exit_code, 0, "second multi-file compile should succeed");
                assert!(cached, "second multi-file compile should be all cache hits");
            }
            other => panic!("expected CompileResult, got: {other:?}"),
        }

        // End session and verify stats
        client
            .send(&Request::SessionEnd { session_id })
            .await
            .unwrap();

        match client.recv().await.unwrap() {
            Some(Response::SessionEnded { stats }) => {
                if let Some(s) = stats {
                    assert!(
                        s.misses >= 2,
                        "first multi-file compile should have 2 misses, got: {}",
                        s.misses
                    );
                    assert!(
                        s.hits >= 2,
                        "second multi-file compile should have 2 hits, got: {}",
                        s.hits
                    );
                }
            }
            other => panic!("expected SessionEnded, got: {other:?}"),
        }

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