Skip to main content

greengate_runtime/
host_slots.rs

1//! Host slots for heavy checks (ADR-0014, `hooks.host-concurrency`).
2//!
3//! Several worktrees, sessions and agents on one machine each run their own
4//! clippy, test suite and type checker, and each of those already uses every
5//! core. A check that compiles or executes the product is therefore Heavy,
6//! and takes a host slot before its first tool runs. The protocol (the slot
7//! directory, the lock, the queue, admission, the holder record) is the
8//! `amont-slots` crate, the one implementation relais links too; this module
9//! is the hook's half: which checks are Heavy, the busy policy, deferral, and
10//! the queue row.
11//!
12//! The slot is taken LAZILY, at the first tool spawn of a heavy check, not
13//! when the check starts: a clippy with no Rust staged returns at once and
14//! must not wait behind somebody else's suite to do nothing.
15
16use crate::names::BIN;
17use std::cell::RefCell;
18use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
19use std::sync::Mutex;
20use std::time::{Duration, Instant};
21
22pub use greenharness_slots::{DIR_ENV, HELD_ENV};
23
24/// The checks that compile or execute the product. Pinned by a registry
25/// test: every name here is a built-in.
26pub const HEAVY: &[&str] = &[
27    "pre-commit-clippy",
28    "pre-commit-go-vet",
29    "pre-commit-pyright",
30    "pre-push-run-tests-js",
31    "pre-push-cargo-test",
32    "pre-push-go-test",
33    "pre-push-pytest",
34];
35
36/// Whether a check is Heavy.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Weight {
39    Light,
40    Heavy,
41}
42
43pub fn weight_of(name: &str) -> Weight {
44    if HEAVY.contains(&name) {
45        Weight::Heavy
46    } else {
47        Weight::Light
48    }
49}
50
51/// Why a heavy check ran without a slot.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Reason {
54    /// The slot directory is not one this user alone owns.
55    DirUnsafe(String),
56    /// No `flock` here: Windows, the stated divergence.
57    Unsupported,
58    /// No slot freed within the budget.
59    TimedOut(Duration),
60    /// A slot file could not be opened or locked for a reason other than
61    /// "another holder has it".
62    Io(String),
63}
64
65/// Set once a check of this process deferred: the host was measured busy,
66/// and a later Heavy check of the same run defers without waiting again, so
67/// a push waits at most one `slotWait`.
68static BUSY_SEEN: AtomicBool = AtomicBool::new(false);
69
70/// `amont.hostSlots`, a host key: unset sizes the slots from the machine
71/// (`Sizing::Auto`), N fixes them, `0` turns them off (`None`).
72pub fn sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
73    match crate::config::host_integer_or(settings, "amont.hostSlots", -1, 0..=64) {
74        0 => None,
75        n if n < 0 => Some(greenharness_slots::Sizing::Auto),
76        n => Some(greenharness_slots::Sizing::Fixed(n as u32)),
77    }
78}
79
80/// The environment override of `amont.onBusy`, for one run:
81/// `AMONT_ON_BUSY=wait git push` runs a gate the file would defer.
82pub const ON_BUSY_ENV: &str = "AMONT_ON_BUSY";
83
84/// What a Heavy check does when no slot frees in time (ADR-0013,
85/// `hooks.busy-policy`).
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum BusyPolicy {
88    /// Wait up to `amont.timeout`, then run unqueued with a note: ADR-0009's
89    /// behaviour, and the default.
90    Wait,
91    /// Wait up to `slot_wait`, then defer the check to CI.
92    Defer { slot_wait: Duration },
93}
94
95/// The busy policy in force: `AMONT_ON_BUSY`, then `amont.onBusy` (git
96/// config, or `set onBusy` in a trusted `amont.conf`), then `wait`.
97pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
98    resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
99}
100
101/// [`busy_policy`] with the environment value handed in: the testable seam,
102/// because setting a variable in a threaded test binary races its siblings.
103fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
104    let from_env = from_env.filter(|v| !v.is_empty());
105    let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
106        Some("wait") => "wait",
107        Some("defer") => "defer",
108        Some(other) => {
109            crate::config::complain(
110                ON_BUSY_ENV,
111                &format!("{other:?} is not one of wait, defer"),
112                "amont.onBusy",
113            );
114            crate::config::enumerated_or(settings, "amont.onBusy", &["wait", "defer"], "wait")
115        }
116        None => crate::config::enumerated_or(settings, "amont.onBusy", &["wait", "defer"], "wait"),
117    };
118    if mode == "defer" {
119        let secs = crate::config::integer_or(settings, "amont.slotWait", 60, 1..=3600) as u64;
120        BusyPolicy::Defer {
121            slot_wait: Duration::from_secs(secs),
122        }
123    } else {
124        BusyPolicy::Wait
125    }
126}
127
128/// What the check running on THIS thread is, as far as slots go.
129#[derive(Default)]
130struct Current {
131    /// The check's name, for the messages its tools' runners print.
132    name: String,
133    heavy: bool,
134    /// The slot question has been answered for this check (held, or
135    /// unqueued for a reason).
136    settled: bool,
137    held: Option<greenharness_slots::Lease>,
138    queued: Duration,
139    /// Set when the busy policy deferred this check (ADR-0013): how long it
140    /// waited. Read by the dispatcher through [`CheckGuard::deferred`], and it
141    /// overrides whatever the check returned, so a check whose own error
142    /// handling turns the refused spawn into `Unavailable` or `Failed` still
143    /// ends Deferred.
144    deferred: Option<Duration>,
145    /// How many jobs this heavy check's tools may run
146    /// (`greenharness_slots::parallelism`), held or unqueued; `None` when slots are
147    /// off, unsupported, or nested under a holder whose bounds it inherits.
148    jobs: Option<u32>,
149    /// How this check waits for a slot.
150    slot_wait: SlotWait,
151}
152
153/// How a heavy check waits for a slot.
154#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
155enum SlotWait {
156    /// The busy policy in force.
157    #[default]
158    Policy,
159    /// The check's severity cannot block the commit or push (`warn`): a
160    /// finding it might make never stops anything, so it never waits for a
161    /// slot, except inside a rehearsal snapshot (no open push connection, no
162    /// waiting commit, and land's pre-stage needs the evidence). Set by
163    /// [`never_waits`].
164    NeverWaits,
165    /// A heavy `warn` check of land's pre-stage: it waits at most
166    /// `amont.warnSlotWait`, then runs unqueued (ADR-0013). Set by
167    /// [`wait_bounded_for_warn`].
168    BoundedForWarn,
169}
170
171/// A slot kept between two heavy gates of one rehearsal pre-push (ADR-0014):
172/// the lease and the width its tools were given.
173struct Parked {
174    lease: greenharness_slots::Lease,
175    jobs: Option<u32>,
176}
177
178/// The slot parked between gates. Process-wide, because the next gate may
179/// run on another thread than the one that finished; a `static` is never
180/// dropped, so [`ParkScope`] releases it.
181static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
182
183/// How many [`ParkScope`]s are alive: an inner scope's drop never stops
184/// parking for an outer one.
185static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
186
187fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
188    PARKED
189        .lock()
190        .unwrap_or_else(|poisoned| poisoned.into_inner())
191}
192
193/// Whether a finished heavy check parks its slot rather than release it: a
194/// pre-push in a rehearsal snapshot, inside its [`ParkScope`]. The other
195/// callers of [`enter_check`] release as they always did.
196fn parking() -> bool {
197    PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
198}
199
200/// Held by `dispatch::pre_push` around its gate loop. While it lives, a slot
201/// a heavy gate held is handed to the next heavy gate instead of released;
202/// when the outermost one drops, on any exit, the parked slot is released.
203#[must_use = "the scope releases the parked slot when dropped"]
204pub struct ParkScope {
205    _private: (),
206}
207
208impl ParkScope {
209    #[must_use = "the scope releases the parked slot when dropped"]
210    pub fn begin() -> ParkScope {
211        PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
212        ParkScope { _private: () }
213    }
214}
215
216impl Drop for ParkScope {
217    fn drop(&mut self) {
218        if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
219            release_parked();
220        }
221    }
222}
223
224/// Release the slot parked between gates, if any. A gate that runs on the
225/// cluster executor takes no host slot (ADR-0016), so it calls this where it
226/// claims its Job: a slot parked for the next local gate would sit idle for
227/// the whole cluster run.
228pub fn release_parked() {
229    let leftover = parked().take();
230    drop(leftover);
231}
232
233/// The holder record of a slot parked between gates.
234fn between_gates() -> greenharness_slots::Holder {
235    holder_for("pre-push, between checks")
236}
237
238/// amont's holder record for `command`. A push rehearsal runs in a temporary
239/// snapshot: the record names the worktree it was taken from, which is what a
240/// reader of `amont slots` knows, whether the slot was granted, parked or
241/// handed on.
242fn holder_for(command: &str) -> greenharness_slots::Holder {
243    let mut holder = greenharness_slots::Holder::here("amont", command);
244    if let Some(src) = crate::rehearsal::source_worktree() {
245        holder.repo = src.display().to_string();
246    }
247    holder
248}
249
250thread_local! {
251    static CURRENT: RefCell<Current> = RefCell::new(Current::default());
252}
253
254/// Installed by the dispatcher around one check's `run`; clears this
255/// thread's slot state, and releases a held slot, when dropped.
256pub struct CheckGuard;
257
258impl CheckGuard {
259    /// How long this check waited for a slot so far.
260    pub fn queued(&self) -> Duration {
261        CURRENT.with(|c| c.borrow().queued)
262    }
263
264    /// Whether the busy policy deferred this check, and after how long a
265    /// wait. Read before the guard drops.
266    pub fn deferred(&self) -> Option<Duration> {
267        CURRENT.with(|c| c.borrow().deferred)
268    }
269}
270
271/// Whether the check running on this thread was deferred by the busy
272/// policy: what it says after that is about its refused spawn.
273pub fn deferred_here() -> bool {
274    CURRENT.with(|c| c.borrow().deferred.is_some())
275}
276
277/// The error a refused spawn returns. Only a way to stop the spawn: what the
278/// check makes of it does not matter, because [`CheckGuard::deferred`] wins.
279fn refusal() -> std::io::Error {
280    std::io::Error::other("deferred to CI: no host slot freed (amont.onBusy defer)")
281}
282
283impl Drop for CheckGuard {
284    fn drop(&mut self) {
285        let finished = CURRENT.with(RefCell::take);
286        if let Some(lease) = finished.held {
287            if parking() {
288                park(lease, finished.jobs);
289            }
290        }
291    }
292}
293
294/// Keep `lease` for the next heavy check of this pre-push, its record
295/// renamed so no waiter's line names the gate that finished.
296fn park(lease: greenharness_slots::Lease, jobs: Option<u32>) {
297    if let Err(error) = lease.rename(&between_gates()) {
298        crate::hooks::common::say(&format!(
299            "  host slot kept, but `{BIN} slots` may still name the previous check: {error}"
300        ));
301    }
302    let earlier = parked().replace(Parked { lease, jobs });
303    drop(earlier);
304}
305
306/// The dispatcher is about to run `name`, of `weight`, on this thread. The
307/// weight comes from the check (`Check::weight`), not the name: a declared
308/// check is Heavy by its line, which no name says.
309pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
310    CURRENT.with(|c| {
311        *c.borrow_mut() = Current {
312            name: name.to_string(),
313            heavy: weight == Weight::Heavy,
314            ..Current::default()
315        }
316    });
317    CheckGuard
318}
319
320/// The check running on this thread cannot block (its severity is `warn`):
321/// on a busy host it takes a free slot or defers to CI at once, under either
322/// busy policy, instead of holding the commit, or the push and its open
323/// connection to the remote, while it queues for a verdict that stops
324/// nothing. Not called inside a rehearsal snapshot: there nothing is held
325/// open and land's pre-stage needs the gate's evidence, so the check follows
326/// the busy policy the rehearsal sets.
327pub fn never_waits() {
328    CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
329}
330
331/// The check running on this thread is a heavy `warn` check of land's
332/// pre-stage, where somebody waits for its evidence: it waits for a slot at
333/// most `amont.warnSlotWait` (and never longer than `amont.timeout`), under
334/// either busy policy, then runs unqueued, never deferred.
335pub fn wait_bounded_for_warn() {
336    CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
337}
338
339/// `amont.warnSlotWait`: how long a heavy `warn` check of land's pre-stage
340/// waits for a slot. Git config, then a trusted `amont.conf`, then 600 s.
341fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
342    Duration::from_secs(
343        crate::config::integer_or(settings, "amont.warnSlotWait", 600, 1..=3600) as u64,
344    )
345}
346
347/// The name of the check running on this thread, without its stage
348/// prefix (`clippy`), when the dispatcher installed one.
349pub fn current_check() -> Option<String> {
350    CURRENT.with(|c| {
351        let c = c.borrow();
352        (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
353    })
354}
355
356/// Whether this process was started by an amont that holds a slot.
357fn nested() -> bool {
358    std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
359}
360
361/// Called before a tool is spawned. For the first tool of a heavy check,
362/// waits for a slot, showing the wait in the check's row. Returns whether
363/// this thread holds a slot, so the caller exports [`HELD_ENV`]; an `Err`
364/// when the busy policy deferred the check, so the caller does not spawn.
365pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
366    let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
367        let current = current.borrow();
368        (
369            current.heavy && !current.settled,
370            current.deferred.is_some(),
371            current.name.clone(),
372            current.slot_wait,
373        )
374    });
375    // A check that caught the first refusal and tries another tool is
376    // refused at once, not after a second wait.
377    if deferred {
378        return Err(refusal());
379    }
380    if pending {
381        if let Some(handed) = parking().then(|| parked().take()).flatten() {
382            return Ok(take_handed(handed, &name));
383        }
384        // Nested first: a nested amont must not pay the host-key scan for a
385        // slot count it is about to ignore. Neither answer queues, so neither
386        // can defer.
387        let sizing = if nested() { None } else { sizing(settings) };
388        let Some(sizing) = sizing else {
389            CURRENT.with(|c| c.borrow_mut().settled = true);
390            return Ok(false);
391        };
392        if !greenharness_slots::SUPPORTED {
393            CURRENT.with(|c| c.borrow_mut().settled = true);
394            return Ok(false);
395        }
396        let policy = match slot_wait {
397            SlotWait::NeverWaits => BusyPolicy::Defer {
398                slot_wait: Duration::ZERO,
399            },
400            SlotWait::BoundedForWarn => BusyPolicy::Wait,
401            SlotWait::Policy => busy_policy(settings),
402        };
403        let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
404            0 => 3600,
405            s => s,
406        });
407        let warn_wait = warn_slot_wait(settings);
408        let cut_by_warn_wait =
409            matches!(slot_wait, SlotWait::BoundedForWarn) && warn_wait <= ceiling;
410        let budget = match policy {
411            BusyPolicy::Wait if matches!(slot_wait, SlotWait::BoundedForWarn) => {
412                warn_wait.min(ceiling)
413            }
414            BusyPolicy::Wait => ceiling,
415            // The host was already measured busy by this run: defer now.
416            BusyPolicy::Defer { .. } if BUSY_SEEN.load(Ordering::SeqCst) => Duration::ZERO,
417            BusyPolicy::Defer { slot_wait } => slot_wait,
418        };
419        let cap = u64::from(sizing.cap());
420        // Hook checks take one slot; the width is set whether a slot is
421        // granted or the check runs unqueued, which happens at peak load.
422        let jobs = greenharness_slots::parallelism(1, greenharness_slots::cores(), sizing.cap());
423        let sink = crate::live::current_sink();
424        if let Some((stage, idx)) = &sink {
425            stage.queue(*idx, Some((Instant::now(), cap)));
426        }
427        let started = Instant::now();
428        let holder = holder_for(&name);
429        let mut got = wait_for_slot(sizing, holder.clone(), budget);
430        if let (BusyPolicy::Defer { .. }, Err(Reason::TimedOut(_))) = (policy, &got) {
431            // A sibling check of this process holds a slot: the host is busy
432            // with this commit's own work, which is not a reason to defer.
433            // Wait as `wait` does, up to the ceiling; else one more pass, as a
434            // sibling may have released between the last poll and now.
435            let rest = if greenharness_slots::held_in_process() > 0
436                && !matches!(slot_wait, SlotWait::NeverWaits)
437            {
438                ceiling.saturating_sub(started.elapsed())
439            } else {
440                Duration::ZERO
441            };
442            got = wait_for_slot(sizing, holder, rest);
443        }
444        if let Some((stage, idx)) = &sink {
445            stage.queue(*idx, None);
446        }
447        let waited = started.elapsed();
448        CURRENT.with(|c| c.borrow_mut().queued += waited);
449        // Piped output never shows the region, and a heartbeat only comes
450        // after a minute: say once where the time went.
451        if got.is_ok() && waited >= Duration::from_secs(1) {
452            crate::hooks::common::say(&format!(
453                "  (waited {} for a host slot, {} {cap})",
454                crate::hooks::common::human_secs(waited.as_secs()),
455                crate::ui::highlight("amont.hostSlots")
456            ));
457        }
458        let defer =
459            matches!(policy, BusyPolicy::Defer { .. }) && matches!(got, Err(Reason::TimedOut(_)));
460        let outcome = match (&got, defer) {
461            (Ok(_), _) => "admitted",
462            (Err(_), true) => "deferred",
463            (Err(_), false) => "unqueued",
464        };
465        record_acquisition(&name, Some(jobs), waited, outcome);
466        let held = match got {
467            Ok(lease) => Some(lease),
468            // The deferral line is the dispatcher's, not this note.
469            Err(_) if defer => None,
470            Err(reason) => {
471                note(&reason, cap, cut_by_warn_wait.then_some(warn_wait));
472                None
473            }
474        };
475        if defer {
476            BUSY_SEEN.store(true, Ordering::SeqCst);
477        }
478        CURRENT.with(|c| {
479            let mut c = c.borrow_mut();
480            c.held = held;
481            c.settled = true;
482            c.jobs = Some(jobs);
483            if defer {
484                c.deferred = Some(waited);
485            }
486        });
487        if defer {
488            return Err(refusal());
489        }
490    }
491    // A light check run while a slot is parked between two heavy gates: its
492    // tools run under that slot (a child `amont slot run` must not queue for
493    // its parent's slot).
494    Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
495}
496
497/// The next heavy check takes the slot the previous one parked: renamed to
498/// itself, recorded as a wait of nothing, its width applied as a grant's is.
499fn take_handed(handed: Parked, name: &str) -> bool {
500    let Parked { lease, jobs } = handed;
501    if let Err(error) = lease.rename(&holder_for(name)) {
502        crate::hooks::common::say(&format!(
503            "  host slot kept, but `{BIN} slots` may still name the previous check: {error}"
504        ));
505    }
506    record_acquisition(name, jobs, Duration::ZERO, "handed");
507    CURRENT.with(|current| {
508        let mut current = current.borrow_mut();
509        current.held = Some(lease);
510        current.settled = true;
511        current.jobs = jobs;
512    });
513    true
514}
515
516/// One line of `waits.jsonl` for the check `name`, with where it ran.
517fn record_acquisition(name: &str, jobs: Option<u32>, waited: Duration, outcome: &str) {
518    let short = crate::short_name(name);
519    greenharness_slots::record_wait_named(
520        &greenharness_slots::dir(),
521        "amont",
522        greenharness_slots::WaitContext {
523            name: Some(short),
524            place: if crate::rehearsal::in_prestage() {
525                greenharness_slots::WaitPlace::Prestage
526            } else if crate::rehearsal::in_snapshot() {
527                greenharness_slots::WaitPlace::Rehearsal
528            } else {
529                greenharness_slots::WaitPlace::Push
530            },
531        },
532        1,
533        jobs,
534        waited.as_millis(),
535        outcome,
536    );
537}
538
539/// Bound `cmd` to the width this thread's heavy check was given (see
540/// `Current::jobs`); a light check, or slots off, sets nothing. Called by
541/// every runner after [`before_spawn`].
542pub fn bound(cmd: &mut std::process::Command) {
543    let own = CURRENT.with(|c| c.borrow().jobs);
544    // A light check between two heavy gates runs under the parked slot.
545    if let Some(jobs) = own.or_else(|| {
546        parking()
547            .then(|| parked().as_ref().and_then(|p| p.jobs))
548            .flatten()
549    }) {
550        greenharness_slots::bound_width(cmd, jobs);
551    }
552}
553
554/// Wait up to `budget` for one slot, saying once whom the check waits
555/// behind.
556fn wait_for_slot(
557    sizing: greenharness_slots::Sizing,
558    holder: greenharness_slots::Holder,
559    budget: Duration,
560) -> Result<greenharness_slots::Lease, Reason> {
561    let started = Instant::now();
562    let mut waiter = match greenharness_slots::Waiter::new(sizing, 1, holder) {
563        Ok(w) => w,
564        Err(e) if e.kind() == std::io::ErrorKind::Other => {
565            return Err(Reason::DirUnsafe(e.to_string()))
566        }
567        Err(e) => return Err(Reason::Io(e.to_string())),
568    };
569    let mut said = false;
570    loop {
571        match waiter.poll() {
572            Ok(greenharness_slots::Poll::Granted(lease)) => return Ok(lease),
573            Ok(greenharness_slots::Poll::Waiting(queue)) => {
574                if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
575                    said = true;
576                    crate::hooks::common::say(&format!("  {}", behind(&queue)));
577                }
578            }
579            Err(e) => return Err(Reason::Io(e.to_string())),
580        }
581        if started.elapsed() >= budget {
582            return Err(Reason::TimedOut(started.elapsed()));
583        }
584        std::thread::sleep(Duration::from_millis(200));
585    }
586}
587
588/// `queued behind relais: cargo test (amont-wt-x, 4m) · 2 waiting`.
589pub fn behind(queue: &greenharness_slots::Queue) -> String {
590    let now = greenharness_slots::now_ms();
591    let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
592    if queue.unknown > 0 {
593        who.push(format!("{} unknown (old client)", queue.unknown));
594    }
595    format!(
596        "queued behind {} · {} waiting",
597        who.join(", "),
598        queue.waiting.max(1)
599    )
600}
601
602/// One line for the reasons a person can act on; nothing for the normal
603/// case (the platform).
604///
605/// `warn_wait` is set when `amont.warnSlotWait` cut the wait: the note names
606/// that key rather than `amont.hostSlots`.
607fn note(reason: &Reason, cap: u64, warn_wait: Option<Duration>) {
608    match reason {
609        Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
610            "host slots are off for this check: {why}. Remove it, or set {} to a directory \
611             only you own",
612            crate::ui::highlight(DIR_ENV)
613        )),
614        Reason::TimedOut(waited) if warn_wait.is_some() => crate::hooks::common::warn(&format!(
615            "no host slot in {} (land: {}={}s); running it anyway",
616            crate::hooks::common::human_secs(waited.as_secs()),
617            crate::ui::highlight("amont.warnSlotWait"),
618            warn_wait.map_or(0, |limit| limit.as_secs())
619        )),
620        Reason::TimedOut(waited) => crate::hooks::common::warn(&format!(
621            "no host slot freed in {} ({} {cap}); running it anyway",
622            crate::hooks::common::human_secs(waited.as_secs()),
623            crate::ui::highlight("amont.hostSlots")
624        )),
625        Reason::Io(why) => {
626            crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
627        }
628        Reason::Unsupported => {}
629    }
630}
631
632#[cfg(all(test, unix))]
633mod tests {
634    use super::*;
635
636    fn settings_from(conf: &str) -> crate::config::Settings {
637        let lines = crate::manifest::parse_lines(conf);
638        let (policy, _) = crate::policy::Policy::from_lines(&lines);
639        crate::config::Settings::new(policy)
640    }
641
642    /// `AMONT_ON_BUSY`, then `amont.conf`, then `wait`; a bad environment
643    /// value is ignored for the file's.
644    #[test]
645    fn the_busy_policy_is_env_then_file_then_wait() {
646        let none = settings_from("");
647        let defer = settings_from("set onBusy defer\nset slotWait 5\n");
648        assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
649        assert_eq!(
650            resolve_busy(None, &defer),
651            BusyPolicy::Defer {
652                slot_wait: Duration::from_secs(5)
653            }
654        );
655        assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
656        assert_eq!(
657            resolve_busy(Some("DEFER"), &none),
658            BusyPolicy::Defer {
659                slot_wait: Duration::from_secs(60)
660            }
661        );
662        assert_eq!(
663            resolve_busy(Some("later"), &defer),
664            BusyPolicy::Defer {
665                slot_wait: Duration::from_secs(5)
666            }
667        );
668        assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
669    }
670
671    #[test]
672    fn heavy_is_the_list() {
673        assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
674        assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
675    }
676
677    /// Every heavy name is a built-in: a renamed check must not silently
678    /// stop queueing.
679    #[test]
680    fn every_heavy_name_is_a_builtin() {
681        for name in HEAVY {
682            assert!(
683                crate::registry::CHECKS.iter().any(|c| c.name == *name),
684                "{name} is not a built-in check"
685            );
686        }
687    }
688
689    /// `.cargo/config.toml` reaches the test binaries: without it the
690    /// integration fixtures would queue on the real host slots.
691    #[test]
692    fn cargo_pins_the_host_knobs_for_tests() {
693        assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
694        assert_eq!(std::env::var("AMONT_IDLE_LOAD_SCALE").as_deref(), Ok("1"));
695    }
696
697    /// A light check never asks. A heavy one run by an amont that holds a
698    /// slot (the test process has `AMONT_HOST_SLOT=held` from
699    /// `.cargo/config.toml`) is nested: it settles without a slot.
700    #[test]
701    fn a_light_check_never_takes_a_slot() {
702        let settings = crate::config::Settings::default();
703        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
704        assert!(!before_spawn(&settings).unwrap());
705    }
706
707    #[test]
708    fn a_nested_heavy_check_settles_without_a_slot() {
709        let settings = crate::config::Settings::default();
710        let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
711        assert_eq!(current_check().as_deref(), Some("clippy"));
712        assert!(!before_spawn(&settings).unwrap());
713        assert!(CURRENT.with(|c| c.borrow().settled));
714        // Nested: the parent's bounds are inherited, so none is set here.
715        let mut cmd = std::process::Command::new("true");
716        bound(&mut cmd);
717        assert_eq!(cmd.get_envs().count(), 0);
718    }
719
720    /// A scope dropped on an early return releases the parked slot: nothing
721    /// stays held, and no holder record stays on disk.
722    #[test]
723    fn a_park_scope_dropped_early_releases_the_parked_slot() {
724        let dir = std::env::temp_dir().join(format!("amont-park-{}", std::process::id()));
725        let _ = std::fs::remove_dir_all(&dir); // best-effort: a fresh scratch dir
726        let early = || {
727            let _scope = ParkScope::begin();
728            let mut waiter = greenharness_slots::Waiter::new_in(
729                &dir,
730                greenharness_slots::Sizing::Fixed(1),
731                1,
732                greenharness_slots::Holder::here("amont", "gate"),
733            )
734            .unwrap();
735            let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
736                panic!("the empty directory grants the slot");
737            };
738            assert!(dir.join("holders/slot-0.who").exists());
739            park(lease, Some(2));
740            assert!(dir.join("holders/slot-0.who").exists());
741        };
742        early();
743        assert!(!dir.join("holders/slot-0.who").exists());
744        let _ = std::fs::remove_dir_all(&dir); // best-effort: scratch
745    }
746
747    #[test]
748    fn a_light_check_sets_no_width() {
749        let settings = crate::config::Settings::default();
750        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
751        before_spawn(&settings).unwrap();
752        let mut cmd = std::process::Command::new("true");
753        bound(&mut cmd);
754        assert_eq!(cmd.get_envs().count(), 0);
755    }
756}