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