zccache 1.12.14

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
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
//! Helpers for daemon-owned child processes.

use std::io;
use std::process::Output;
use std::sync::{
    atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},
    Arc, OnceLock,
};

use arc_swap::ArcSwap;

#[cfg(windows)]
use std::os::windows::io::AsRawHandle;

pub(crate) const COMPILE_PRIORITY_ENV: &str = "ZCCACHE_COMPILE_PRIORITY";
pub const ZCCACHE_COMPILE_PRIORITY_LINK: &str = "ZCCACHE_COMPILE_PRIORITY_LINK";
const AUTO_PRIORITY_SATURATED_CPU_PERCENT: f32 = 95.0;

/// Env vars that, when set to a truthy value, indicate the daemon is
/// running on a CI runner rather than an interactive developer host.
/// First match wins. Documented in the issue #813 epic.
const CI_DETECT_ENV_VARS: &[&str] = &[
    "GITHUB_ACTIONS",
    "CI",
    "BUILDKITE",
    "CIRCLECI",
    "GITLAB_CI",
    "TF_BUILD",
    "TEAMCITY_VERSION",
    "JENKINS_URL",
];

/// True when the daemon appears to be running on a CI runner. Inspects
/// the standard env-var set [`CI_DETECT_ENV_VARS`]. The check is cheap
/// (a small number of `getenv` calls), safe to call per-resolution.
///
/// Returns the name of the detected env var as the second tuple element
/// when CI is detected, so startup logs can surface the source.
pub(crate) fn is_ci_host() -> Option<&'static str> {
    is_ci_host_with_env(|name| std::env::var(name).ok())
}

/// Testable variant of [`is_ci_host`] that takes an env lookup closure
/// so tests do not need to mutate the global process env.
pub(crate) fn is_ci_host_with_env<F>(lookup: F) -> Option<&'static str>
where
    F: Fn(&str) -> Option<String>,
{
    for &var in CI_DETECT_ENV_VARS {
        if let Some(value) = lookup(var) {
            if is_truthy(&value) {
                return Some(var);
            }
        }
    }
    None
}

fn is_truthy(value: &str) -> bool {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return false;
    }
    !matches!(
        trimmed.to_ascii_lowercase().as_str(),
        "0" | "false" | "no" | "off" | "n"
    )
}

/// Run a CPU/IO-heavy **synchronous** section without stalling the async
/// runtime (issue #955 — daemon-side root cause).
///
/// The miss-store tail of a full-codegen compile does two size-scaling
/// synchronous things on the tokio worker thread: a rayon parallel hash of
/// the source + the whole extern set, and the artifact persist (a large
/// `.rlib` copy when it can't be hardlinked cross-volume). For the
/// consolidated `zccache` crate the extern set is the entire workspace, so
/// each miss parks a worker for a long time. Under several concurrent
/// `cargo test` invocations this can park *every* worker at once — the
/// runtime then can't drive the reply I/O for any in-flight compile, so
/// the daemon "never responds" (0 rustc alive, since rustc already exited)
/// and the client wedges. That is the #955 wedge.
///
/// On the multi-thread daemon runtime, [`tokio::task::block_in_place`] tells
/// tokio to spin up a replacement worker for the duration of `f`, so the
/// runtime keeps servicing other compiles' I/O (including sending their
/// replies) while this section runs. On a current-thread runtime (the
/// embedded host path) `block_in_place` would panic, so `f` runs inline —
/// the pre-#955 status quo, no worse than before.
pub(crate) fn run_cpu_blocking<F, R>(f: F) -> R
where
    F: FnOnce() -> R,
{
    let is_multi_thread = matches!(
        tokio::runtime::Handle::try_current().map(|h| h.runtime_flavor()),
        Ok(tokio::runtime::RuntimeFlavor::MultiThread)
    );
    if is_multi_thread {
        tokio::task::block_in_place(f)
    } else {
        f()
    }
}

/// Priority policy for compiler/linker child processes owned by the daemon.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum CompilePriority {
    #[default]
    Auto,
    Normal,
    Low,
    Idle,
    High,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct CompilePriorityDecision {
    pub(crate) requested: CompilePriority,
    pub(crate) effective: CompilePriority,
    pub(crate) cpu_usage_percent: Option<f32>,
}

impl CompilePriority {
    pub(crate) fn parse(value: &str) -> Result<Self, CompilePriorityParseError> {
        match value.trim().to_ascii_lowercase().as_str() {
            "auto" => Ok(Self::Auto),
            "normal" => Ok(Self::Normal),
            "low" => Ok(Self::Low),
            "idle" => Ok(Self::Idle),
            "high" => Ok(Self::High),
            other => Err(CompilePriorityParseError {
                value: other.to_string(),
            }),
        }
    }

    pub(crate) fn from_client_env(env: Option<&[(String, String)]>) -> Self {
        let daemon_value = std::env::var(COMPILE_PRIORITY_ENV).ok();
        Self::from_client_env_with_daemon_env(env, daemon_value.as_deref())
    }

    fn from_client_env_with_daemon_env(
        env: Option<&[(String, String)]>,
        daemon_value: Option<&str>,
    ) -> Self {
        if let Some(value) = Self::client_env_value(env, COMPILE_PRIORITY_ENV) {
            return Self::parse_or_warn(value, COMPILE_PRIORITY_ENV);
        }

        match daemon_value {
            Some(value) => Self::parse_or_warn(value, COMPILE_PRIORITY_ENV),
            None => Self::Auto,
        }
    }

    pub(crate) fn from_client_env_for_link_like(
        env: Option<&[(String, String)]>,
        is_link_like: bool,
    ) -> Self {
        let daemon_link_value = std::env::var(ZCCACHE_COMPILE_PRIORITY_LINK).ok();
        let daemon_compile_value = std::env::var(COMPILE_PRIORITY_ENV).ok();
        Self::from_client_env_for_link_like_with_daemon_env(
            env,
            is_link_like,
            daemon_link_value.as_deref(),
            daemon_compile_value.as_deref(),
        )
    }

    fn from_client_env_for_link_like_with_daemon_env(
        env: Option<&[(String, String)]>,
        is_link_like: bool,
        daemon_link_value: Option<&str>,
        daemon_compile_value: Option<&str>,
    ) -> Self {
        Self::from_client_env_for_link_like_with_daemon_env_ci(
            env,
            is_link_like,
            daemon_link_value,
            daemon_compile_value,
            is_ci_host().is_some(),
        )
    }

    fn from_client_env_for_link_like_with_daemon_env_ci(
        env: Option<&[(String, String)]>,
        is_link_like: bool,
        daemon_link_value: Option<&str>,
        daemon_compile_value: Option<&str>,
        is_ci: bool,
    ) -> Self {
        if is_link_like {
            if let Some(value) = Self::client_env_value(env, ZCCACHE_COMPILE_PRIORITY_LINK) {
                return Self::parse_or_warn(value, ZCCACHE_COMPILE_PRIORITY_LINK);
            }

            if let Some(value) = daemon_link_value {
                return Self::parse_or_warn(value, ZCCACHE_COMPILE_PRIORITY_LINK);
            }

            // Issue #813 / #810: linker priority is the single biggest UI
            // win on Windows (link.exe is the worst single-thread hog).
            // Interactive hosts default to `Low`; CI keeps the historical
            // `Normal` so dedicated runners don't yield.
            return if is_ci { Self::Normal } else { Self::Low };
        }

        Self::from_client_env_with_daemon_env(env, daemon_compile_value)
    }

    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Normal => "normal",
            Self::Low => "low",
            Self::Idle => "idle",
            Self::High => "high",
        }
    }

    /// Observation variant — samples the in-flight counter without
    /// incrementing it. Spawn sites must call [`Self::resolve_and_track`]
    /// instead so the decision is race-free against concurrent spawns.
    pub(crate) fn resolve_for_current_load(self) -> CompilePriorityDecision {
        let cpu_usage_percent = matches!(self, Self::Auto)
            .then(current_cpu_usage_percent)
            .flatten();
        let in_flight = current_in_flight_compiles().saturating_add(current_host_in_flight());
        self.resolve_with_cpu_usage_and_ci(cpu_usage_percent, is_ci_host().is_some(), in_flight)
    }

    /// Spawn-site resolution. Acquires an [`InFlightCompileTicket`] so the
    /// `Auto` decision uses the pre-increment count (race-free under
    /// parallel spawns) and the counter accurately reflects in-flight work
    /// for the next caller. The ticket **must** be held by the caller for
    /// the lifetime of the spawned process.
    ///
    /// When an embedded host has registered an in-flight counter via
    /// [`crate::embedded::ServiceLimits::host_in_flight`] (zccache#924),
    /// its current value is added to the pre-increment count before the
    /// decision is made. This keeps wave-priority semantics correct
    /// across both products' subprocess pressure on the same machine —
    /// otherwise zccache would see `in_flight = 0` and pick `Normal`
    /// even when the host already has dozens of its own rustc children
    /// hammering the CPU.
    pub(crate) fn resolve_and_track(self) -> (CompilePriorityDecision, InFlightCompileTicket) {
        let ticket = InFlightCompileTicket::acquire();
        let cpu_usage_percent = matches!(self, Self::Auto)
            .then(current_cpu_usage_percent)
            .flatten();
        let in_flight = ticket
            .in_flight_before()
            .saturating_add(current_host_in_flight());
        let decision = self.resolve_with_cpu_usage_and_ci(
            cpu_usage_percent,
            is_ci_host().is_some(),
            in_flight,
        );
        (decision, ticket)
    }

    fn resolve_with_cpu_usage_and_ci(
        self,
        cpu_usage_percent: Option<f32>,
        is_ci: bool,
        in_flight_before: usize,
    ) -> CompilePriorityDecision {
        let effective = match self {
            Self::Auto => Self::auto_effective_priority(cpu_usage_percent, is_ci, in_flight_before),
            priority => priority,
        };
        CompilePriorityDecision {
            requested: self,
            effective,
            cpu_usage_percent,
        }
    }

    /// Resolves what `Auto` actually means for a given CPU sample + host
    /// kind + in-flight count. Issue #813 / #810 changed the interactive
    /// default from `Normal` to `Low`; this refinement (master-profile
    /// 2026-06-25 ISSUE-001) restores `Normal` for the case the original
    /// patch overshot — single/idle compiles — while keeping the wave
    /// case at `Low`.
    ///
    /// - **CI host** (any env in [`CI_DETECT_ENV_VARS`] truthy): the
    ///   historical behavior — `Normal` until system CPU is ≥ 95%, then
    ///   `Low`. CI runners are dedicated to compilation; no foreground
    ///   workload to yield to.
    /// - **Interactive host** (no CI env): `Normal` when no other compile
    ///   is in flight (`in_flight_before == 0`), `Low` otherwise. A
    ///   parallel cargo wave of N rustcs all calling `fetch_add(1)` sees
    ///   counts `0, 1, …, N-1` deterministically — one `Normal` leader
    ///   plus `N-1` `Low` followers. The leader at `Normal` runs at
    ///   bare-rustc speed (the cold-bench win); the `N-1` followers stay
    ///   `Low`, bounding the CPU spike #813 was protecting against. When
    ///   the wave finishes and a single rustc returns (e.g. last compile
    ///   in a cargo dep tree, or a one-off check), the counter drops back
    ///   to 0 and the next spawn is again `Normal`.
    fn auto_effective_priority(
        cpu_usage_percent: Option<f32>,
        is_ci: bool,
        in_flight_before: usize,
    ) -> Self {
        if !is_ci {
            if in_flight_before == 0 {
                return Self::Normal;
            }
            return Self::Low;
        }
        match cpu_usage_percent {
            Some(cpu) if cpu >= AUTO_PRIORITY_SATURATED_CPU_PERCENT => Self::Low,
            Some(_) | None => Self::Normal,
        }
    }

    fn parse_or_warn(value: &str, env_name: &str) -> Self {
        match Self::parse(value) {
            Ok(priority) => priority,
            Err(e) => {
                tracing::warn!(
                    env = env_name,
                    value = %e.value,
                    "invalid compiler child priority; using low"
                );
                Self::Low
            }
        }
    }

    fn client_env_value<'a>(env: Option<&'a [(String, String)]>, key: &str) -> Option<&'a str> {
        env.and_then(|vars| {
            vars.iter()
                .find(|(candidate, _)| candidate == key)
                .map(|(_, value)| value.as_str())
        })
    }

    #[cfg(test)]
    fn parse_optional(value: Option<&str>) -> Result<Self, CompilePriorityParseError> {
        match value {
            Some(value) => Self::parse(value),
            None => Ok(Self::Auto),
        }
    }

    #[cfg(unix)]
    fn unix_nice_value(self) -> Option<i32> {
        match self {
            Self::Auto | Self::Normal => None,
            Self::Low => Some(10),
            Self::Idle => Some(19),
            // Higher priorities commonly require extra privileges; failures are
            // logged and compilation continues at the inherited priority.
            Self::High => Some(-5),
        }
    }

    #[cfg(windows)]
    fn windows_priority_class(self) -> Option<u32> {
        use windows_sys::Win32::System::Threading::{
            BELOW_NORMAL_PRIORITY_CLASS, HIGH_PRIORITY_CLASS, IDLE_PRIORITY_CLASS,
        };

        match self {
            Self::Auto | Self::Normal => None,
            Self::Low => Some(BELOW_NORMAL_PRIORITY_CLASS),
            Self::Idle => Some(IDLE_PRIORITY_CLASS),
            Self::High => Some(HIGH_PRIORITY_CLASS),
        }
    }
}

const CPU_USAGE_UNKNOWN_BITS: u32 = u32::MAX;

struct CpuUsageMonitor {
    sampler_started: AtomicBool,
    last_usage_percent_bits: AtomicU32,
}

impl Default for CpuUsageMonitor {
    fn default() -> Self {
        Self::new()
    }
}

impl CpuUsageMonitor {
    fn new() -> Self {
        Self {
            sampler_started: AtomicBool::new(false),
            last_usage_percent_bits: AtomicU32::new(CPU_USAGE_UNKNOWN_BITS),
        }
    }

    fn sample(&'static self) -> Option<f32> {
        self.ensure_sampler_started();
        match self.last_usage_percent_bits.load(Ordering::Relaxed) {
            CPU_USAGE_UNKNOWN_BITS => None,
            usage_bits => Some(f32::from_bits(usage_bits)),
        }
    }

    fn ensure_sampler_started(&'static self) {
        if self
            .sampler_started
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return;
        }

        if let Err(error) = std::thread::Builder::new()
            .name("zccache-cpu-usage-sampler".to_string())
            .spawn(move || self.run_sampler())
        {
            self.sampler_started.store(false, Ordering::Release);
            tracing::debug!(%error, "failed to start CPU usage sampler");
        }
    }

    fn run_sampler(&'static self) {
        let mut system = sysinfo::System::new();
        system.refresh_cpu_usage();

        loop {
            std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
            system.refresh_cpu_usage();
            let usage = system.global_cpu_usage().clamp(0.0, 100.0);
            self.last_usage_percent_bits
                .store(usage.to_bits(), Ordering::Relaxed);
        }
    }
}

fn current_cpu_usage_percent() -> Option<f32> {
    static CPU_USAGE_MONITOR: OnceLock<CpuUsageMonitor> = OnceLock::new();
    CPU_USAGE_MONITOR.get_or_init(CpuUsageMonitor::new).sample()
}

/// Global counter of daemon-owned compiler children currently spawned and
/// not yet reaped. Used by `Auto` priority to decide whether a new spawn
/// is the first/only one (use `Normal`, restoring near-bare-rustc speed)
/// or part of an in-flight wave (demote to `Low` to preserve UI
/// responsiveness per issues #813 / #810).
static IN_FLIGHT_COMPILES: AtomicUsize = AtomicUsize::new(0);

/// Optional host-supplied in-flight counter (zccache#924). When an
/// embedded `ZccacheService` runs inside a larger host daemon (soldr,
/// fbuild), that host may spawn its own subprocess children that
/// zccache's local counter never sees. If the host clones a shared
/// counter into [`crate::embedded::ServiceLimits::host_in_flight`],
/// `ZccacheService::start` registers it here and
/// [`CompilePriority::auto_effective_priority`] sums its current value
/// into the in-flight count used to decide `Normal` vs `Low`.
///
/// Stored as `ArcSwap<Option<Arc<AtomicUsize>>>` so reads on the hot
/// path are wait-free and the registration / deregistration cost is
/// only paid at service start / shutdown. The contract is single-slot:
/// only one embedded service per process can have its counter
/// registered at a time, matching the canonical "one host + one
/// embedded zccache" deployment. A second registration overwrites the
/// first (with a `tracing::warn!` so the double-register case is
/// debuggable).
static HOST_IN_FLIGHT: OnceLock<ArcSwap<Option<Arc<AtomicUsize>>>> = OnceLock::new();

fn host_in_flight_slot() -> &'static ArcSwap<Option<Arc<AtomicUsize>>> {
    HOST_IN_FLIGHT.get_or_init(|| ArcSwap::from_pointee(None))
}

/// Read the current host-side in-flight count, or 0 if no host counter
/// has been registered. Hot path — wait-free read of the `ArcSwap`
/// guard then an `Acquire` load on the inner atomic.
fn current_host_in_flight() -> usize {
    host_in_flight_slot()
        .load()
        .as_ref()
        .as_ref()
        .map(|counter| counter.load(Ordering::Acquire))
        .unwrap_or(0)
}

/// Register a host-supplied in-flight counter (zccache#924). Called
/// from [`crate::embedded::ZccacheService::start`] when the caller
/// populated [`crate::embedded::ServiceLimits::host_in_flight`].
///
/// Returns an RAII guard that clears the slot on drop, so a host that
/// drops its `ZccacheService` automatically deregisters its counter and
/// the priority decision falls back to the zccache-internal counter
/// only. Multiple registrations from the same process race; the latest
/// wins and a warning is logged.
pub(crate) fn register_host_in_flight_counter(counter: Arc<AtomicUsize>) -> HostInFlightGuard {
    let slot = host_in_flight_slot();
    let previous = slot.swap(Arc::new(Some(counter)));
    if previous.is_some() {
        tracing::warn!(
            "host in-flight counter already registered; overwriting (zccache#924). \
             Only one embedded ZccacheService should run per process."
        );
    }
    HostInFlightGuard { _marker: () }
}

/// RAII guard returned by [`register_host_in_flight_counter`]. Drop
/// clears the slot, restoring the zccache-internal-only Auto priority
/// behavior.
#[must_use = "the guard clears the host counter slot on drop — hold it for the service lifetime"]
pub(crate) struct HostInFlightGuard {
    _marker: (),
}

impl Drop for HostInFlightGuard {
    fn drop(&mut self) {
        host_in_flight_slot().store(Arc::new(None));
    }
}

/// Observation-only sampler. `Auto` resolution at *spawn sites* must use
/// the pre-increment value returned by [`InFlightCompileTicket::acquire`]
/// instead, so concurrent decisions are race-free (fetch-add ordering).
pub(crate) fn current_in_flight_compiles() -> usize {
    IN_FLIGHT_COMPILES.load(Ordering::Acquire)
}

/// RAII ticket representing one in-flight compile spawn. Acquire **before**
/// resolving `Auto` priority; the pre-increment count is exposed via
/// [`Self::in_flight_before`] and is the deterministic input for the
/// priority decision (a wave of N simultaneous fetch-adds yields counts
/// `0, 1, 2, …, N-1` — one `Normal` followed by `N-1` `Low`, bounding the
/// CPU spike #813 was protecting against).
///
/// Drop decrements the counter; the ticket must be held until the spawned
/// process is fully waited on.
#[must_use = "the ticket decrements on drop — hold it until the child is reaped"]
pub(crate) struct InFlightCompileTicket {
    in_flight_before: usize,
}

impl InFlightCompileTicket {
    pub(crate) fn acquire() -> Self {
        let in_flight_before = IN_FLIGHT_COMPILES.fetch_add(1, Ordering::AcqRel);
        Self { in_flight_before }
    }

    pub(crate) fn in_flight_before(&self) -> usize {
        self.in_flight_before
    }
}

impl Drop for InFlightCompileTicket {
    fn drop(&mut self) {
        IN_FLIGHT_COMPILES.fetch_sub(1, Ordering::AcqRel);
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CompilePriorityParseError {
    value: String,
}

/// Windows process creation flags applied to daemon-spawned children.
///
/// Currently always returns `CREATE_NO_WINDOW` (`0x08000000`). When the
/// daemon is launched detached (no console attached), spawning a
/// console-subsystem child like rustc / cl / clang without this flag
/// causes Windows to allocate a fresh console window for the child —
/// a visible flash per cache-miss compile in the soldr + rustc +
/// zccache call chain. Setting `CREATE_NO_WINDOW` suppresses that
/// allocation; stdio already flows through the pipes the helpers
/// attach, so no output is lost.
///
/// `priority` is a parameter so future priority bits (`IDLE_PRIORITY_CLASS`,
/// `BELOW_NORMAL_PRIORITY_CLASS`, etc.) can be OR'd in directly at the
/// `CreateProcessW` call rather than via the separate post-spawn
/// `SetPriorityClass` we use today. Unused today — kept for API
/// stability so the call sites don't change shape later.
#[cfg(windows)]
fn child_creation_flags(_priority: CompilePriority) -> u32 {
    /// `CREATE_NO_WINDOW` from `windows_sys::Win32::System::Threading`.
    /// Hardcoded here because the daemon doesn't otherwise pull in
    /// `windows-sys` and a single u32 constant doesn't justify the dep.
    /// Value verified against the Windows SDK header `winbase.h`.
    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
    CREATE_NO_WINDOW
}

/// Apply the daemon's console-suppression creation flag (`CREATE_NO_WINDOW`)
/// to a child spawned OUTSIDE the priority-aware `command_output_*` helpers.
///
/// The compiler-identity probe (`rustc -vV` in [`super::server`]'s
/// `compiler_hash`) builds a `Command` and calls `.output()` directly, so it
/// never reached [`child_creation_flags`]. Since the daemon runs detached
/// (no console), that made every cold-path identity probe flash a console
/// window on Windows — the exact symptom `child_creation_flags` was added to
/// fix for the compile path. This routes those probes through the same flag.
/// No-op on non-Windows.
pub(crate) fn suppress_child_console(cmd: &mut std::process::Command) {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(child_creation_flags(CompilePriority::Normal));
    }
    #[cfg(not(windows))]
    let _ = cmd;
}

/// `tokio::process::Command` variant of [`suppress_child_console`].
///
/// `tokio::process::Command::creation_flags` is an inherent method (unlike
/// `std`'s, which comes from `CommandExt`), so no trait import is needed.
pub(crate) fn suppress_child_console_tokio(cmd: &mut tokio::process::Command) {
    #[cfg(windows)]
    cmd.creation_flags(child_creation_flags(CompilePriority::Normal));
    #[cfg(not(windows))]
    let _ = cmd;
}

/// Wait for a synchronous command after applying a compiler child priority.
///
/// Convenience wrapper that pipes `Stdio::null()` for stdin. Callers that
/// need to forward bytes from the client's stdin (e.g. `rustc -`) use
/// [`command_output_with_priority_stdin`] instead.
pub(crate) fn command_output_with_priority(
    cmd: &mut std::process::Command,
    priority: CompilePriority,
) -> io::Result<Output> {
    command_output_with_priority_stdin(cmd, priority, None)
}

/// Sync variant that pipes `stdin_bytes` into the child's stdin when the
/// slice is `Some` and non-empty. `None` or empty = `Stdio::null()` (the
/// previous behaviour). Use this in the non-cacheable / direct-run path
/// where the wrapper might be ferrying client stdin over IPC.
pub(crate) fn command_output_with_priority_stdin(
    cmd: &mut std::process::Command,
    priority: CompilePriority,
    stdin_bytes: Option<&[u8]>,
) -> io::Result<Output> {
    let (decision, _ticket) = priority.resolve_and_track();
    let priority = decision.effective;
    let pipe_stdin = matches!(stdin_bytes, Some(b) if !b.is_empty());

    #[cfg(windows)]
    {
        use std::io::Write;
        use std::os::windows::process::CommandExt;
        use std::process::Stdio;

        if pipe_stdin {
            cmd.stdin(Stdio::piped());
        } else {
            cmd.stdin(Stdio::null());
        }
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.creation_flags(child_creation_flags(priority));
        let mut child = cmd.spawn()?;
        assign_child_to_daemon_job(child.as_raw_handle());
        apply_priority_to_child_windows(child.as_raw_handle(), priority);
        if pipe_stdin {
            if let Some(mut stdin) = child.stdin.take() {
                // Best-effort: stdin write failures land in the child's
                // own error path (it reads EOF / partial input). We still
                // wait_with_output so the caller sees the exit code.
                let _ = stdin.write_all(stdin_bytes.unwrap_or(&[]));
                // Drop closes the pipe — signals EOF to the child.
            }
        }
        child.wait_with_output()
    }

    #[cfg(unix)]
    {
        use std::io::Write;
        use std::process::Stdio;

        if pipe_stdin {
            cmd.stdin(Stdio::piped());
        } else {
            cmd.stdin(Stdio::null());
        }
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        let mut child = cmd.spawn()?;
        apply_priority_to_child_unix(child.id(), priority);
        if pipe_stdin {
            if let Some(mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(stdin_bytes.unwrap_or(&[]));
            }
        }
        child.wait_with_output()
    }

    #[cfg(not(any(unix, windows)))]
    {
        if priority != CompilePriority::Normal {
            tracing::debug!(
                ?priority,
                "compiler child priority is unsupported on this platform"
            );
        }
        let _ = stdin_bytes; // No piping on pure-stub platforms.
        cmd.output()
    }
}

/// Wait for an async command after applying a compiler child priority.
///
/// Convenience wrapper that pipes `Stdio::null()` for stdin. Callers that
/// need to forward client stdin use [`tokio_command_output_with_priority_stdin`].
pub(crate) async fn tokio_command_output_with_priority(
    cmd: &mut tokio::process::Command,
    priority: CompilePriority,
) -> io::Result<Output> {
    tokio_command_output_with_priority_stdin(cmd, priority, None).await
}

/// Wait for an async command after applying compiler child priority, killing
/// the child and returning `TimedOut` when `timeout` elapses.
pub(crate) async fn tokio_command_output_with_priority_timeout(
    cmd: &mut tokio::process::Command,
    priority: CompilePriority,
    timeout: std::time::Duration,
) -> io::Result<Output> {
    let wait = tokio_command_output_with_priority_stdin(cmd, priority, None);
    match tokio::time::timeout(timeout, wait).await {
        Ok(result) => result,
        Err(_) => Err(io::Error::new(
            io::ErrorKind::TimedOut,
            format!("child process timed out after {timeout:?}"),
        )),
    }
}

/// Async variant that pipes `stdin_bytes` into the child's stdin when the
/// slice is `Some` and non-empty. See [`command_output_with_priority_stdin`].
pub(crate) async fn tokio_command_output_with_priority_stdin(
    cmd: &mut tokio::process::Command,
    priority: CompilePriority,
    stdin_bytes: Option<&[u8]>,
) -> io::Result<Output> {
    let (decision, _ticket) = priority.resolve_and_track();
    let priority = decision.effective;
    let pipe_stdin = matches!(stdin_bytes, Some(b) if !b.is_empty());

    #[cfg(windows)]
    {
        use std::process::Stdio;
        use tokio::io::AsyncWriteExt;

        if pipe_stdin {
            cmd.stdin(Stdio::piped());
        } else {
            cmd.stdin(Stdio::null());
        }
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.kill_on_drop(true);
        cmd.creation_flags(child_creation_flags(priority));
        let mut child = cmd.spawn()?;
        if let Some(handle) = child.raw_handle() {
            assign_child_to_daemon_job(handle);
            apply_priority_to_child_windows(handle, priority);
        }
        if pipe_stdin {
            if let Some(mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(stdin_bytes.unwrap_or(&[])).await;
                let _ = stdin.shutdown().await;
            }
        }
        child.wait_with_output().await
    }

    #[cfg(unix)]
    {
        use std::process::Stdio;
        use tokio::io::AsyncWriteExt;

        if pipe_stdin {
            cmd.stdin(Stdio::piped());
        } else {
            cmd.stdin(Stdio::null());
        }
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.kill_on_drop(true);
        let mut child = cmd.spawn()?;
        if let Some(pid) = child.id() {
            apply_priority_to_child_unix(pid, priority);
        }
        if pipe_stdin {
            if let Some(mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(stdin_bytes.unwrap_or(&[])).await;
                let _ = stdin.shutdown().await;
            }
        }
        child.wait_with_output().await
    }

    #[cfg(not(any(unix, windows)))]
    {
        let _ = stdin_bytes;
        cmd.output().await
    }
}

#[cfg(windows)]
fn assign_child_to_daemon_job(raw_handle: std::os::windows::io::RawHandle) {
    let Some(job) = DAEMON_JOB.get_or_init(WindowsJob::new).as_ref() else {
        return;
    };

    if let Err(e) = job.assign(raw_handle) {
        tracing::debug!("failed to assign child process to daemon job: {e}");
    }
}

#[cfg(unix)]
fn apply_priority_to_child_unix(pid: u32, priority: CompilePriority) {
    let Some(nice) = priority.unix_nice_value() else {
        return;
    };

    let rc = unsafe { libc::setpriority(libc::PRIO_PROCESS, pid as libc::id_t, nice) };
    if rc != 0 {
        tracing::debug!(
            ?priority,
            pid,
            nice,
            error = %io::Error::last_os_error(),
            "failed to set compiler child priority"
        );
    }
}

#[cfg(windows)]
fn apply_priority_to_child_windows(
    raw_handle: std::os::windows::io::RawHandle,
    priority: CompilePriority,
) {
    let Some(priority_class) = priority.windows_priority_class() else {
        return;
    };

    use windows_sys::Win32::System::Threading::SetPriorityClass;

    let ok = unsafe { SetPriorityClass(raw_handle.cast::<std::ffi::c_void>(), priority_class) };
    if ok == 0 {
        tracing::debug!(
            ?priority,
            error = %io::Error::last_os_error(),
            "failed to set compiler child priority"
        );
    }
}

#[cfg(windows)]
static DAEMON_JOB: OnceLock<Option<WindowsJob>> = OnceLock::new();

#[cfg(windows)]
struct WindowsJob {
    handle: usize,
}

#[cfg(windows)]
impl WindowsJob {
    fn new() -> Option<Self> {
        use std::mem::size_of;
        use windows_sys::Win32::Foundation::CloseHandle;
        use windows_sys::Win32::System::JobObjects::{
            CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject,
            JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
        };

        let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        if handle.is_null() {
            tracing::debug!(
                "failed to create daemon job object: {}",
                io::Error::last_os_error()
            );
            return None;
        }

        let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
        info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

        let ok = unsafe {
            SetInformationJobObject(
                handle,
                JobObjectExtendedLimitInformation,
                (&info as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
                size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
            )
        };
        if ok == 0 {
            tracing::debug!(
                "failed to configure daemon job object: {}",
                io::Error::last_os_error()
            );
            unsafe {
                CloseHandle(handle);
            }
            return None;
        }

        tracing::debug!("created daemon child-process job object");
        Some(Self {
            handle: handle as usize,
        })
    }

    fn assign(&self, raw_handle: std::os::windows::io::RawHandle) -> io::Result<()> {
        use windows_sys::Win32::Foundation::HANDLE;
        use windows_sys::Win32::System::JobObjects::AssignProcessToJobObject;

        let ok = unsafe {
            AssignProcessToJobObject(self.handle as HANDLE, raw_handle.cast::<std::ffi::c_void>())
        };
        if ok == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }
}

#[cfg(windows)]
impl Drop for WindowsJob {
    fn drop(&mut self) {
        use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
        unsafe {
            CloseHandle(self.handle as HANDLE);
        }
    }
}

#[cfg(windows)]
unsafe impl Send for WindowsJob {}

#[cfg(windows)]
unsafe impl Sync for WindowsJob {}

#[cfg(test)]
mod tests {
    use super::*;

    // ── run_cpu_blocking (#955) ──

    #[test]
    fn run_cpu_blocking_no_runtime_runs_inline() {
        // Outside any tokio runtime the section runs inline and returns
        // the closure's value.
        assert_eq!(run_cpu_blocking(|| 40 + 2), 42);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn run_cpu_blocking_multi_thread_ok() {
        // On the daemon's real (multi-thread) runtime this takes the
        // block_in_place branch and must still return the value.
        assert_eq!(run_cpu_blocking(|| "ok"), "ok");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_cpu_blocking_current_thread_does_not_panic() {
        // Regression guard: block_in_place panics on a current-thread
        // runtime (the embedded-host path), so run_cpu_blocking MUST fall
        // back to running inline there rather than aborting the compile.
        assert_eq!(run_cpu_blocking(|| 123), 123);
    }

    #[test]
    fn parse_compile_priority_values() {
        assert_eq!(
            CompilePriority::parse("auto").unwrap(),
            CompilePriority::Auto
        );
        assert_eq!(
            CompilePriority::parse("normal").unwrap(),
            CompilePriority::Normal
        );
        assert_eq!(CompilePriority::parse("LOW").unwrap(), CompilePriority::Low);
        assert_eq!(
            CompilePriority::parse(" idle ").unwrap(),
            CompilePriority::Idle
        );
        assert_eq!(
            CompilePriority::parse("high").unwrap(),
            CompilePriority::High
        );
        assert!(CompilePriority::parse("fast").is_err());
    }

    #[test]
    fn formats_compile_priority_for_profiles() {
        assert_eq!(CompilePriority::Auto.as_str(), "auto");
        assert_eq!(CompilePriority::Normal.as_str(), "normal");
        assert_eq!(CompilePriority::Low.as_str(), "low");
        assert_eq!(CompilePriority::Idle.as_str(), "idle");
        assert_eq!(CompilePriority::High.as_str(), "high");
    }

    #[test]
    fn absent_compile_priority_defaults_to_auto() {
        assert_eq!(
            CompilePriority::parse_optional(None).unwrap(),
            CompilePriority::Auto
        );
    }

    #[test]
    fn ci_auto_priority_uses_normal_until_cpu_is_saturated() {
        // CI host (is_ci=true) preserves the historical heuristic:
        // Normal until 95% CPU, then Low. CI runners are dedicated to
        // compilation; no foreground workload to yield to. In-flight
        // count is ignored on CI — the CPU gate is sufficient.
        let is_ci = true;
        assert_eq!(
            CompilePriority::auto_effective_priority(None, is_ci, 0),
            CompilePriority::Normal
        );
        assert_eq!(
            CompilePriority::auto_effective_priority(Some(94.9), is_ci, 32),
            CompilePriority::Normal
        );
        assert_eq!(
            CompilePriority::auto_effective_priority(Some(95.0), is_ci, 0),
            CompilePriority::Low
        );
        assert_eq!(
            CompilePriority::auto_effective_priority(Some(100.0), is_ci, 32),
            CompilePriority::Low
        );
    }

    #[test]
    fn interactive_auto_priority_adapts_to_in_flight_count() {
        // Master-profile 2026-06-25 ISSUE-001: interactive hosts get
        // Normal when no other compile is in flight (single/idle case —
        // bare-rustc speed), Low once a wave is detected. Preserves
        // #813's UI-win on parallel waves while restoring near-bare-rustc
        // speed on the single-compile cases that the unconditional Low
        // was overshooting.
        let is_ci = false;
        // No others in flight → Normal regardless of CPU.
        assert_eq!(
            CompilePriority::auto_effective_priority(None, is_ci, 0),
            CompilePriority::Normal
        );
        assert_eq!(
            CompilePriority::auto_effective_priority(Some(0.0), is_ci, 0),
            CompilePriority::Normal
        );
        assert_eq!(
            CompilePriority::auto_effective_priority(Some(100.0), is_ci, 0),
            CompilePriority::Normal
        );
        // One or more others in flight → Low (yield to UI).
        assert_eq!(
            CompilePriority::auto_effective_priority(None, is_ci, 1),
            CompilePriority::Low
        );
        assert_eq!(
            CompilePriority::auto_effective_priority(Some(50.0), is_ci, 7),
            CompilePriority::Low
        );
    }

    #[test]
    fn auto_priority_decision_records_effective_priority_on_ci() {
        let decision = CompilePriority::Auto.resolve_with_cpu_usage_and_ci(Some(96.0), true, 0);
        assert_eq!(decision.requested, CompilePriority::Auto);
        assert_eq!(decision.effective, CompilePriority::Low);
        assert_eq!(decision.cpu_usage_percent, Some(96.0));
    }

    #[test]
    fn auto_priority_decision_low_on_interactive_when_wave_in_flight() {
        let decision = CompilePriority::Auto.resolve_with_cpu_usage_and_ci(Some(10.0), false, 3);
        assert_eq!(decision.requested, CompilePriority::Auto);
        assert_eq!(decision.effective, CompilePriority::Low);
        assert_eq!(decision.cpu_usage_percent, Some(10.0));
    }

    #[test]
    fn auto_priority_decision_normal_on_interactive_when_idle() {
        let decision = CompilePriority::Auto.resolve_with_cpu_usage_and_ci(Some(10.0), false, 0);
        assert_eq!(decision.requested, CompilePriority::Auto);
        assert_eq!(decision.effective, CompilePriority::Normal);
        assert_eq!(decision.cpu_usage_percent, Some(10.0));
    }

    #[test]
    fn in_flight_ticket_returns_pre_increment_count_atomically() {
        let baseline = current_in_flight_compiles();
        let t1 = InFlightCompileTicket::acquire();
        assert_eq!(t1.in_flight_before(), baseline);
        assert_eq!(current_in_flight_compiles(), baseline + 1);
        let t2 = InFlightCompileTicket::acquire();
        assert_eq!(t2.in_flight_before(), baseline + 1);
        assert_eq!(current_in_flight_compiles(), baseline + 2);
        drop(t2);
        assert_eq!(current_in_flight_compiles(), baseline + 1);
        drop(t1);
        assert_eq!(current_in_flight_compiles(), baseline);
    }

    /// zccache#924: serialize tests that touch the process-wide host
    /// in-flight slot. Without this, parallel test execution sees the
    /// "single-slot, last-write-wins" contract collide between cases.
    static HOST_INFLIGHT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn host_counter_zero_when_unregistered() {
        let _guard = HOST_INFLIGHT_TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // No registration: `current_host_in_flight()` returns 0 and
        // auto-priority falls back to today's behavior.
        assert_eq!(current_host_in_flight(), 0);
        let decision = CompilePriority::Auto.resolve_with_cpu_usage_and_ci(Some(10.0), false, 0);
        assert_eq!(decision.effective, CompilePriority::Normal);
    }

    #[test]
    fn host_counter_summed_into_auto_priority_decision() {
        let _serial = HOST_INFLIGHT_TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // zccache#924 acceptance criterion: configure a host counter
        // showing 5 in-flight host spawns and assert the read of
        // `current_host_in_flight()` reflects it. Feed that value into
        // `resolve_with_cpu_usage_and_ci(_, is_ci=false, _)` directly so
        // the assertion holds regardless of the test runner — CI
        // detection on GitHub Actions routes Auto through the CI branch
        // that ignores `in_flight_before`, so a test that calls
        // `resolve_for_current_load` would be non-portable.
        let counter = Arc::new(AtomicUsize::new(5));
        let _registration_guard = register_host_in_flight_counter(Arc::clone(&counter));
        assert_eq!(current_host_in_flight(), 5);

        let summed = current_in_flight_compiles().saturating_add(current_host_in_flight());
        assert!(summed >= 5, "host counter must be summed into in-flight");
        let decision =
            CompilePriority::Auto.resolve_with_cpu_usage_and_ci(Some(10.0), false, summed);
        assert_eq!(
            decision.effective,
            CompilePriority::Low,
            "Auto must demote to Low when host counter says the box is busy",
        );

        // Bring the host counter back to 0 and confirm the next read
        // sees the change.
        counter.store(0, Ordering::Release);
        assert_eq!(current_host_in_flight(), 0);
        let summed = current_in_flight_compiles().saturating_add(current_host_in_flight());
        let decision =
            CompilePriority::Auto.resolve_with_cpu_usage_and_ci(Some(10.0), false, summed);
        // With host_in_flight = 0 and no concurrent zccache ticket held,
        // the summed count is 0 and interactive Auto picks Normal.
        assert_eq!(
            decision.effective,
            CompilePriority::Normal,
            "after host counter drops to 0 the interactive Auto decision must be Normal",
        );
    }

    #[test]
    fn host_inflight_guard_clears_slot_on_drop() {
        let _serial = HOST_INFLIGHT_TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let counter = Arc::new(AtomicUsize::new(7));
        {
            let _guard = register_host_in_flight_counter(Arc::clone(&counter));
            assert_eq!(current_host_in_flight(), 7);
        }
        // RAII guard dropped — slot must be empty again so subsequent
        // tests / future starts see the clean state.
        assert_eq!(
            current_host_in_flight(),
            0,
            "dropping the host-inflight guard must restore the zccache-internal-only baseline"
        );
    }

    #[test]
    fn host_counter_saturates_without_overflow() {
        let _serial = HOST_INFLIGHT_TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // Defensive: a pathological host counter near usize::MAX must
        // not overflow when summed with the ticket's pre-increment
        // count. The implementation uses `saturating_add` for exactly
        // this case — guard the contract here so a refactor cannot
        // regress to wrapping arithmetic.
        //
        // Use explicit `is_ci = false` so the assertion holds on both
        // CI runners and interactive hosts.
        let counter = Arc::new(AtomicUsize::new(usize::MAX));
        let _guard = register_host_in_flight_counter(Arc::clone(&counter));
        let summed = 1usize.saturating_add(current_host_in_flight());
        assert_eq!(
            summed,
            usize::MAX,
            "saturating_add must clamp at usize::MAX"
        );
        let decision =
            CompilePriority::Auto.resolve_with_cpu_usage_and_ci(Some(10.0), false, summed);
        assert_eq!(decision.effective, CompilePriority::Low);
    }

    #[test]
    fn auto_priority_can_sample_current_load() {
        let decision = CompilePriority::Auto.resolve_for_current_load();
        assert_eq!(decision.requested, CompilePriority::Auto);
        assert!(matches!(
            decision.effective,
            CompilePriority::Normal | CompilePriority::Low
        ));
        if let Some(cpu_usage_percent) = decision.cpu_usage_percent {
            assert!((0.0..=100.0).contains(&cpu_usage_percent));
        }
    }

    #[test]
    fn client_env_selects_high_mode() {
        let env = vec![(COMPILE_PRIORITY_ENV.to_string(), "high".to_string())];
        assert_eq!(
            CompilePriority::from_client_env(Some(&env)),
            CompilePriority::High
        );
    }

    #[test]
    fn client_env_invalid_value_falls_back_to_low() {
        let env = vec![(COMPILE_PRIORITY_ENV.to_string(), "fast".to_string())];
        assert_eq!(
            CompilePriority::from_client_env(Some(&env)),
            CompilePriority::Low
        );
    }

    #[test]
    fn link_priority_env_overrides_link_like_compile_priority() {
        let env = vec![
            (COMPILE_PRIORITY_ENV.to_string(), "low".to_string()),
            (
                ZCCACHE_COMPILE_PRIORITY_LINK.to_string(),
                "high".to_string(),
            ),
        ];

        assert_eq!(
            CompilePriority::from_client_env_for_link_like_with_daemon_env(
                Some(&env),
                true,
                None,
                None
            ),
            CompilePriority::High
        );
    }

    #[test]
    fn daemon_link_priority_env_overrides_link_like_compile_priority() {
        let env = vec![(COMPILE_PRIORITY_ENV.to_string(), "low".to_string())];

        assert_eq!(
            CompilePriority::from_client_env_for_link_like_with_daemon_env(
                Some(&env),
                true,
                Some("high"),
                None
            ),
            CompilePriority::High
        );
    }

    #[test]
    fn link_like_compile_priority_on_ci_defaults_to_normal_without_link_override() {
        let env = vec![(COMPILE_PRIORITY_ENV.to_string(), "idle".to_string())];

        assert_eq!(
            CompilePriority::from_client_env_for_link_like_with_daemon_env_ci(
                Some(&env),
                true,
                None,
                None,
                true, // is_ci
            ),
            CompilePriority::Normal
        );
    }

    #[test]
    fn link_like_compile_priority_on_interactive_defaults_to_low_without_link_override() {
        // Issue #813 / #810: link.exe is the single worst single-thread
        // hog on Windows MSVC. Interactive hosts demote it to Low so the
        // late-build link step doesn't lock up the UI.
        let env = vec![(COMPILE_PRIORITY_ENV.to_string(), "idle".to_string())];

        assert_eq!(
            CompilePriority::from_client_env_for_link_like_with_daemon_env_ci(
                Some(&env),
                true,
                None,
                None,
                false, // interactive
            ),
            CompilePriority::Low
        );
    }

    #[test]
    fn is_ci_host_detects_known_env_vars() {
        let make_lookup = |hit: &'static str| {
            move |name: &str| {
                if name == hit {
                    Some("true".to_string())
                } else {
                    None
                }
            }
        };
        for var in CI_DETECT_ENV_VARS {
            let detected = is_ci_host_with_env(make_lookup(var));
            assert_eq!(
                detected,
                Some(*var),
                "is_ci_host_with_env failed to detect {var}",
            );
        }
    }

    #[test]
    fn is_ci_host_treats_falsy_values_as_interactive() {
        for falsy in ["0", "false", "FALSE", "no", "off", "n", "", "   "] {
            let lookup = |_name: &str| Some(falsy.to_string());
            assert_eq!(
                is_ci_host_with_env(lookup),
                None,
                "value {falsy:?} should NOT be treated as CI",
            );
        }
    }

    #[test]
    fn is_ci_host_returns_none_when_no_env_set() {
        let lookup = |_name: &str| None;
        assert_eq!(is_ci_host_with_env(lookup), None);
    }

    #[test]
    fn non_link_compile_priority_preserves_existing_auto_behavior() {
        let env = vec![
            (
                ZCCACHE_COMPILE_PRIORITY_LINK.to_string(),
                "high".to_string(),
            ),
            (COMPILE_PRIORITY_ENV.to_string(), "auto".to_string()),
        ];

        assert_eq!(
            CompilePriority::from_client_env_for_link_like_with_daemon_env(
                Some(&env),
                false,
                Some("idle"),
                None
            ),
            CompilePriority::Auto
        );
    }

    #[test]
    fn invalid_link_priority_env_falls_back_to_low() {
        let env = vec![(
            ZCCACHE_COMPILE_PRIORITY_LINK.to_string(),
            "fast".to_string(),
        )];

        assert_eq!(
            CompilePriority::from_client_env_for_link_like_with_daemon_env(
                Some(&env),
                true,
                None,
                None
            ),
            CompilePriority::Low
        );
    }

    #[cfg(unix)]
    #[test]
    fn unix_priority_mapping_is_explicit() {
        assert_eq!(CompilePriority::Auto.unix_nice_value(), None);
        assert_eq!(CompilePriority::Normal.unix_nice_value(), None);
        assert_eq!(CompilePriority::Low.unix_nice_value(), Some(10));
        assert_eq!(CompilePriority::Idle.unix_nice_value(), Some(19));
        assert_eq!(CompilePriority::High.unix_nice_value(), Some(-5));
    }

    #[cfg(windows)]
    #[test]
    fn windows_priority_mapping_is_explicit() {
        use windows_sys::Win32::System::Threading::{
            BELOW_NORMAL_PRIORITY_CLASS, HIGH_PRIORITY_CLASS, IDLE_PRIORITY_CLASS,
        };

        assert_eq!(CompilePriority::Auto.windows_priority_class(), None);
        assert_eq!(CompilePriority::Normal.windows_priority_class(), None);
        assert_eq!(
            CompilePriority::Low.windows_priority_class(),
            Some(BELOW_NORMAL_PRIORITY_CLASS)
        );
        assert_eq!(
            CompilePriority::Idle.windows_priority_class(),
            Some(IDLE_PRIORITY_CLASS)
        );
        assert_eq!(
            CompilePriority::High.windows_priority_class(),
            Some(HIGH_PRIORITY_CLASS)
        );
    }

    // ── Console-window suppression (Windows only) ───────────────────────
    //
    // When the daemon is launched detached (no console attached) and then
    // spawns a console-subsystem child like rustc / cl / clang via
    // `command_output_with_priority` or `tokio_command_output_with_priority`,
    // Windows allocates a fresh console window for the child *unless* the
    // creation flags include `CREATE_NO_WINDOW`. The console window flashes
    // for the lifetime of the child — visible whenever cargo hits a cache
    // miss and the daemon executes the compiler inline. Reported by the
    // soldr + rustc + zccache workflow.
    //
    // The end-to-end behavior (child having no console window) is hard to
    // test inside `cargo test` because the test runner's own stdio
    // capture makes the test binary console-less, so a child spawned
    // without `CREATE_NO_WINDOW` reads as console-less too — false green.
    // Instead we unit-test the helper that *computes* the creation flags
    // the spawn site applies. If that helper returns the right bits,
    // `cmd.creation_flags(...)` puts them on the CreateProcessW call.

    /// `child_creation_flags` must include `CREATE_NO_WINDOW` (`0x08000000`)
    /// regardless of priority. Without that bit set, a detached daemon's
    /// `command_output_with_priority` spawn allocates a console window per
    /// child (the soldr + rustc cache-miss flash).
    #[cfg(windows)]
    #[test]
    fn child_creation_flags_includes_create_no_window() {
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        for priority in [
            CompilePriority::Normal,
            CompilePriority::Low,
            CompilePriority::Idle,
            CompilePriority::High,
        ] {
            let flags = child_creation_flags(priority);
            assert_eq!(
                flags & CREATE_NO_WINDOW,
                CREATE_NO_WINDOW,
                "child_creation_flags({priority:?}) = 0x{flags:08x} must set CREATE_NO_WINDOW (0x08000000) \
                 to suppress the per-child console flash a detached daemon would otherwise produce"
            );
        }
    }
}