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)]
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    /// The queue could not be joined: a slot file could not be opened or
59    /// locked for a reason other than "another holder has it". The slots are
60    /// unusable, as if off.
61    Io(String),
62    /// The wait in line ended (ADR-0022): a stall, the ceiling, or failed
63    /// polls. Nothing runs unqueued because of it: the check defers.
64    Ended(greenharness_slots::LineEnd),
65}
66
67impl Reason {
68    /// How the wait in line ended, when it did; `None` when the slots were
69    /// unusable.
70    fn ended(&self) -> Option<&greenharness_slots::LineEnd> {
71        match self {
72            Reason::Ended(end) => Some(end),
73            Reason::DirUnsafe(_) | Reason::Unsupported | Reason::Io(_) => None,
74        }
75    }
76}
77
78/// What a deferral of this run came from, for the roll-up: only an `onBusy
79/// defer` `slotWait` is stopped by `set onBusy wait`; a ceiling or a failed
80/// poll defers under either policy.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum DeferredBy {
83    SlotWait,
84    LineEnded,
85}
86
87/// Set once a check deferred because `onBusy defer`'s `slotWait` ran out.
88static DEFERRED_BY_SLOT_WAIT: AtomicBool = AtomicBool::new(false);
89
90/// What this run's deferrals came from.
91pub fn deferred_by() -> DeferredBy {
92    if DEFERRED_BY_SLOT_WAIT.load(Ordering::SeqCst) {
93        DeferredBy::SlotWait
94    } else {
95        DeferredBy::LineEnded
96    }
97}
98
99/// Whether this run already deferred on a busy host.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101enum HostSeen {
102    Busy,
103    NotYet,
104}
105
106/// Set once a check of this process deferred: the host was measured busy,
107/// and a later Heavy check of the same run defers without waiting again, so
108/// a push waits at most one `slotWait`.
109static BUSY_SEEN: AtomicBool = AtomicBool::new(false);
110
111/// Both host sizing keys, `greengate.hostCores` and `greengate.hostSlots`,
112/// resolved by the slots crate from the environment and this `Settings`'
113/// cached rows: one implementation, shared with relais, and no extra git
114/// spawn. Each warning is printed once.
115pub fn host_sizing(settings: &crate::config::Settings) -> greenharness_slots::host::HostSizing {
116    let rows = crate::config::host_rows(settings);
117    let mut sizing = greenharness_slots::host::resolve(
118        |name| std::env::var(name).ok(),
119        rows.unwrap_or(&[]),
120        greenharness_slots::detect_cores(),
121    );
122    if rows.is_none() {
123        sizing
124            .warnings
125            .push(greenharness_slots::host::NO_SCOPES_WARNING.to_string());
126    }
127    for warning in &sizing.warnings {
128        say_once(warning);
129    }
130    sizing
131}
132
133/// A sizing warning on stderr, once per process. Plain text: the warning
134/// sign's colour follows stdout, and this line is on stderr.
135fn say_once(warning: &str) {
136    use std::collections::BTreeSet;
137    use std::sync::{Mutex, OnceLock};
138    static SAID: OnceLock<Mutex<BTreeSet<String>>> = OnceLock::new();
139    let said = SAID.get_or_init(|| Mutex::new(BTreeSet::new()));
140    let fresh = match said.lock() {
141        Ok(mut set) => set.insert(warning.to_string()),
142        Err(_) => true,
143    };
144    if fresh {
145        eprintln!("{}: warning: {warning}", crate::names::BIN);
146    }
147}
148
149/// The slot sizing and the machine it is computed for, from one resolution:
150/// `greengate.hostSlots` (`None` when `0` turns slots off) and
151/// `greengate.hostCores`, else the detected physical core count.
152pub fn sizing_and_machine(
153    settings: &crate::config::Settings,
154) -> (
155    Option<greenharness_slots::Sizing>,
156    greenharness_slots::Machine,
157) {
158    let host = host_sizing(settings);
159    (
160        host.slots.value,
161        greenharness_slots::Machine {
162            cores: host.cores.value.max(1),
163        },
164    )
165}
166
167/// `greengate.hostSlots`: unset sizes the slots from the machine
168/// (`Sizing::Auto`), N fixes them, `0` turns them off (`None`).
169pub fn sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
170    sizing_and_machine(settings).0
171}
172
173/// The environment override of `greengate.onBusy`, for one run:
174/// `GREENGATE_ON_BUSY=wait git push` runs a gate the file would defer.
175pub const ON_BUSY_ENV: &str = "GREENGATE_ON_BUSY";
176
177/// What a Heavy check does when no slot frees in time (ADR-0013,
178/// `hooks.busy-policy`).
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum BusyPolicy {
181    /// Wait in line, with no stall end, up to `greengate.timeout`, then defer
182    /// the check to CI (ADR-0022, amended for the hook path): the default.
183    Wait,
184    /// Wait up to `slot_wait`, then defer the check to CI.
185    Defer { slot_wait: Duration },
186    /// Skip the queue: run unqueued at once, journalled `now` (ADR-0022).
187    /// Only `GREENGATE_ON_BUSY=now` sets it, for one run: no committed file
188    /// can make every clone skip the queue.
189    Now,
190}
191
192/// The busy policy in force: `GREENGATE_ON_BUSY` (`wait`, `defer` or `now`),
193/// then `greengate.onBusy` (git config, or `set onBusy` in a trusted
194/// `amont.conf`; `wait` or `defer`), then `wait`.
195pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
196    resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
197}
198
199/// [`busy_policy`] with the environment value handed in: the testable seam,
200/// because setting a variable in a threaded test binary races its siblings.
201fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
202    let from_env = from_env.filter(|v| !v.is_empty());
203    let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
204        Some("wait") => "wait",
205        Some("defer") => "defer",
206        Some("now") => return BusyPolicy::Now,
207        Some(other) => {
208            crate::config::complain(
209                ON_BUSY_ENV,
210                &format!("{other:?} is not one of wait, defer, now"),
211                "greengate.onBusy",
212            );
213            crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
214        }
215        None => {
216            crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
217        }
218    };
219    if mode == "defer" {
220        let secs = crate::config::integer_or(settings, "greengate.slotWait", 60, 1..=3600) as u64;
221        BusyPolicy::Defer {
222            slot_wait: Duration::from_secs(secs),
223        }
224    } else {
225        BusyPolicy::Wait
226    }
227}
228
229/// What the check running on THIS thread is, as far as slots go.
230#[derive(Default)]
231struct Current {
232    /// The check's name, for the messages its tools' runners print.
233    name: String,
234    heavy: bool,
235    /// The slot question has been answered for this check (held, or
236    /// unqueued for a reason).
237    settled: bool,
238    held: Option<greenharness_slots::Lease>,
239    queued: Duration,
240    /// Set when the busy policy deferred this check (ADR-0013): how long it
241    /// waited. Read by the dispatcher through [`CheckGuard::deferred`], and it
242    /// overrides whatever the check returned, so a check whose own error
243    /// handling turns the refused spawn into `Unavailable` or `Failed` still
244    /// ends Deferred.
245    deferred: Option<Duration>,
246    /// Why it deferred, for the refused spawn's error.
247    deferred_cause: String,
248    /// How many jobs this heavy check's tools may run
249    /// (`greenharness_slots::parallelism`), held or unqueued; `None` when slots are
250    /// off, unsupported, or nested under a holder whose bounds it inherits.
251    jobs: Option<u32>,
252    /// The (cap, cores) this check was sized for, carried to a handed slot's
253    /// `waits.jsonl` line.
254    sized: Option<(u32, u32)>,
255    /// How this check waits for a slot.
256    slot_wait: SlotWait,
257}
258
259/// How a heavy check waits for a slot.
260#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
261enum SlotWait {
262    /// The busy policy in force.
263    #[default]
264    Policy,
265    /// The check's severity cannot block the commit or push (`warn`): a
266    /// finding it might make never stops anything, so it never waits for a
267    /// slot, except inside a rehearsal snapshot (no open push connection, no
268    /// waiting commit, and land's pre-stage needs the evidence). Set by
269    /// [`never_waits`].
270    NeverWaits,
271    /// A heavy `warn` check of land's pre-stage: it waits, with no stall end,
272    /// at most `greengate.warnSlotWait`, then defers (ADR-0022). Set by
273    /// [`wait_bounded_for_warn`].
274    BoundedForWarn,
275}
276
277/// A slot kept between two heavy gates of one rehearsal pre-push (ADR-0014):
278/// the lease and the width its tools were given.
279struct Parked {
280    lease: greenharness_slots::Lease,
281    jobs: Option<u32>,
282    sized: Option<(u32, u32)>,
283}
284
285/// The slot parked between gates. Process-wide, because the next gate may
286/// run on another thread than the one that finished; a `static` is never
287/// dropped, so [`ParkScope`] releases it.
288static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
289
290/// How many [`ParkScope`]s are alive: an inner scope's drop never stops
291/// parking for an outer one.
292static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
293
294fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
295    PARKED
296        .lock()
297        .unwrap_or_else(|poisoned| poisoned.into_inner())
298}
299
300/// Whether a finished heavy check parks its slot rather than release it: a
301/// pre-push in a rehearsal snapshot, inside its [`ParkScope`]. The other
302/// callers of [`enter_check`] release as they always did.
303fn parking() -> bool {
304    PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
305}
306
307/// Held by `dispatch::pre_push` around its gate loop. While it lives, a slot
308/// a heavy gate held is handed to the next heavy gate instead of released;
309/// when the outermost one drops, on any exit, the parked slot is released.
310#[must_use = "the scope releases the parked slot when dropped"]
311pub struct ParkScope {
312    _private: (),
313}
314
315impl ParkScope {
316    #[must_use = "the scope releases the parked slot when dropped"]
317    pub fn begin() -> ParkScope {
318        PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
319        ParkScope { _private: () }
320    }
321}
322
323impl Drop for ParkScope {
324    fn drop(&mut self) {
325        if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
326            release_parked();
327        }
328    }
329}
330
331/// Release the slot parked between gates, if any. A gate that runs on the
332/// cluster executor takes no host slot (ADR-0016), so it calls this where it
333/// claims its Job: a slot parked for the next local gate would sit idle for
334/// the whole cluster run.
335pub fn release_parked() {
336    let leftover = parked().take();
337    drop(leftover);
338}
339
340/// The holder record of a slot parked between gates.
341fn between_gates() -> greenharness_slots::Holder {
342    holder_for("pre-push, between checks")
343}
344
345/// amont's holder record for `command`. A push rehearsal runs in a temporary
346/// snapshot: the record names the worktree it was taken from, which is what a
347/// reader of `amont slots` knows, whether the slot was granted, parked or
348/// handed on.
349fn holder_for(command: &str) -> greenharness_slots::Holder {
350    let mut holder = greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, command);
351    if let Some(src) = crate::rehearsal::source_worktree() {
352        holder.repo = src.display().to_string();
353    }
354    holder
355}
356
357thread_local! {
358    static CURRENT: RefCell<Current> = RefCell::new(Current::default());
359}
360
361/// Installed by the dispatcher around one check's `run`; clears this
362/// thread's slot state, and releases a held slot, when dropped.
363pub struct CheckGuard;
364
365impl CheckGuard {
366    /// How long this check waited for a slot so far.
367    pub fn queued(&self) -> Duration {
368        CURRENT.with(|c| c.borrow().queued)
369    }
370
371    /// Whether the busy policy deferred this check, and after how long a
372    /// wait. Read before the guard drops.
373    pub fn deferred(&self) -> Option<Duration> {
374        CURRENT.with(|c| c.borrow().deferred)
375    }
376}
377
378/// Whether the check running on this thread was deferred by the busy
379/// policy: what it says after that is about its refused spawn.
380pub fn deferred_here() -> bool {
381    CURRENT.with(|c| c.borrow().deferred.is_some())
382}
383
384/// The error a refused spawn returns, naming why the check deferred. Only a
385/// way to stop the spawn: what the check makes of it does not matter, because
386/// [`CheckGuard::deferred`] wins.
387fn refusal() -> std::io::Error {
388    let cause = CURRENT.with(|c| c.borrow().deferred_cause.clone());
389    std::io::Error::other(if cause.is_empty() {
390        "deferred to CI: the host is busy".to_string()
391    } else {
392        cause
393    })
394}
395
396/// Why a wait that ended in line defers, as the refused spawn says it.
397fn defer_cause(
398    end: &greenharness_slots::LineEnd,
399    policy: BusyPolicy,
400    slot_wait: SlotWait,
401) -> String {
402    use greenharness_slots::LineEnd;
403    let human = |d: Duration| crate::hooks::common::human_secs(d.as_secs());
404    match end {
405        // The hook path sets no stall window, so this arm fires only if a
406        // caller passes one.
407        LineEnd::Stalled { window, position } => format!(
408            "deferred to CI: the host slot line made no progress for {} (position {})",
409            human(*window),
410            position + 1
411        ),
412        LineEnd::PollFailed { error } => {
413            format!("deferred to CI: the host slot files failed: {error}")
414        }
415        LineEnd::Ceiling { waited } => match policy {
416            BusyPolicy::Defer { .. } => format!(
417                "deferred to CI: no host slot freed in {} (greengate.onBusy defer)",
418                human(*waited)
419            ),
420            BusyPolicy::Wait | BusyPolicy::Now => {
421                // `NeverWaits` always arrives as `Defer`; it is listed so the
422                // match covers every case.
423                let setting = match slot_wait {
424                    SlotWait::BoundedForWarn => "greengate.warnSlotWait",
425                    SlotWait::Policy | SlotWait::NeverWaits => "greengate.timeout",
426                };
427                format!(
428                    "deferred to CI: no host slot within {} ({setting})",
429                    human(*waited)
430                )
431            }
432        },
433    }
434}
435
436/// How one heavy check waits for a slot (ADR-0022): it skips the queue, or
437/// it waits in line within bounds. Whatever ends the wait, the check defers.
438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439enum WaitPlan {
440    Now,
441    Queue(greenharness_slots::WaitBounds),
442}
443
444/// The [`WaitPlan`] for a check: one row of the plan's table per arm.
445/// `ceiling` is `greengate.timeout` (3600 s when 0), `seen` whether this run
446/// already deferred on a busy host. A hook check has no stall window: it waits
447/// until its ceiling, as a commit or a push can, and defers there (ADR-0022,
448/// amended for the hook path in 5.1.1); the stall end belongs to `slot run`
449/// and relais.
450fn wait_plan(
451    slot_wait: SlotWait,
452    policy: BusyPolicy,
453    ceiling: Duration,
454    warn_wait: Duration,
455    seen: HostSeen,
456) -> WaitPlan {
457    let queue =
458        |window, ceiling| WaitPlan::Queue(greenharness_slots::WaitBounds { window, ceiling });
459    match (slot_wait, policy) {
460        (_, BusyPolicy::Now) => WaitPlan::Now,
461        (SlotWait::NeverWaits, _) => queue(None, Duration::ZERO),
462        (SlotWait::BoundedForWarn, _) => queue(None, warn_wait.min(ceiling)),
463        (SlotWait::Policy, BusyPolicy::Wait) => queue(None, ceiling),
464        (SlotWait::Policy, BusyPolicy::Defer { slot_wait }) => match seen {
465            // The host was already measured busy by this run: defer now.
466            HostSeen::Busy => queue(None, Duration::ZERO),
467            HostSeen::NotYet => queue(None, slot_wait),
468        },
469    }
470}
471
472/// The bounds of the second wait an `onBusy defer` check takes after its
473/// `slotWait` ran out: while a sibling check of this process holds a slot,
474/// the host is busy with this commit's own work, which is not a reason to
475/// defer, so it waits as `wait` does, with no stall window, up to the
476/// ceiling; else one more pass, as a sibling may have released between the
477/// last poll and now.
478fn sibling_bounds(
479    slot_wait: SlotWait,
480    held_in_process: usize,
481    ceiling: Duration,
482    elapsed: Duration,
483) -> greenharness_slots::WaitBounds {
484    let waits_on_sibling = held_in_process > 0 && !matches!(slot_wait, SlotWait::NeverWaits);
485    if waits_on_sibling {
486        greenharness_slots::WaitBounds {
487            window: None,
488            ceiling: ceiling.saturating_sub(elapsed),
489        }
490    } else {
491        greenharness_slots::WaitBounds {
492            window: None,
493            ceiling: Duration::ZERO,
494        }
495    }
496}
497
498impl Drop for CheckGuard {
499    fn drop(&mut self) {
500        let finished = CURRENT.with(RefCell::take);
501        if let Some(lease) = finished.held {
502            if parking() {
503                park(lease, finished.jobs, finished.sized);
504            }
505        }
506    }
507}
508
509/// Keep `lease` for the next heavy check of this pre-push, its record
510/// renamed so no waiter's line names the gate that finished.
511fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
512    if let Err(error) = lease.rename(&between_gates()) {
513        crate::hooks::common::say(&format!(
514            "  host slot kept, but `{BIN} slots` may still name the previous check: {error}"
515        ));
516    }
517    let earlier = parked().replace(Parked { lease, jobs, sized });
518    drop(earlier);
519}
520
521/// The dispatcher is about to run `name`, of `weight`, on this thread. The
522/// weight comes from the check (`Check::weight`), not the name: a declared
523/// check is Heavy by its line, which no name says.
524pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
525    CURRENT.with(|c| {
526        *c.borrow_mut() = Current {
527            name: name.to_string(),
528            heavy: weight == Weight::Heavy,
529            ..Current::default()
530        }
531    });
532    CheckGuard
533}
534
535/// The check running on this thread cannot block (its severity is `warn`):
536/// on a busy host it takes a free slot or defers to CI at once, under either
537/// busy policy, instead of holding the commit, or the push and its open
538/// connection to the remote, while it queues for a verdict that stops
539/// nothing. Not called inside a rehearsal snapshot: there nothing is held
540/// open and land's pre-stage needs the gate's evidence, so the check follows
541/// the busy policy the rehearsal sets.
542pub fn never_waits() {
543    CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
544}
545
546/// The check running on this thread is a heavy `warn` check of land's
547/// pre-stage, where somebody waits for its evidence: it waits for a slot at
548/// most `greengate.warnSlotWait` (and never longer than `greengate.timeout`), under
549/// either busy policy, with no stall end, then defers (ADR-0022).
550pub fn wait_bounded_for_warn() {
551    CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
552}
553
554/// `greengate.warnSlotWait`: how long a heavy `warn` check of land's pre-stage
555/// waits for a slot. Git config, then a trusted `amont.conf`, then 600 s.
556fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
557    Duration::from_secs(
558        crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
559    )
560}
561
562/// The name of the check running on this thread, without its stage
563/// prefix (`clippy`), when the dispatcher installed one.
564pub fn current_check() -> Option<String> {
565    CURRENT.with(|c| {
566        let c = c.borrow();
567        (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
568    })
569}
570
571/// Whether this process was started by an amont that holds a slot.
572fn nested() -> bool {
573    std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
574}
575
576/// Called before a tool is spawned. For the first tool of a heavy check,
577/// waits for a slot, showing the wait in the check's row. Returns whether
578/// this thread holds a slot, so the caller exports [`HELD_ENV`]; an `Err`
579/// when the busy policy deferred the check, so the caller does not spawn.
580pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
581    let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
582        let current = current.borrow();
583        (
584            current.heavy && !current.settled,
585            current.deferred.is_some(),
586            current.name.clone(),
587            current.slot_wait,
588        )
589    });
590    // A check that caught the first refusal and tries another tool is
591    // refused at once, not after a second wait.
592    if deferred {
593        return Err(refusal());
594    }
595    if pending {
596        if let Some(handed) = parking().then(|| parked().take()).flatten() {
597            return Ok(take_handed(handed, &name));
598        }
599        // Nested first: a nested amont must not pay the host-key scan for a
600        // slot count it is about to ignore. Neither answer queues, so neither
601        // can defer.
602        let (sizing, machine) = if nested() {
603            (None, greenharness_slots::Machine::detect())
604        } else {
605            sizing_and_machine(settings)
606        };
607        let Some(sizing) = sizing else {
608            CURRENT.with(|c| c.borrow_mut().settled = true);
609            return Ok(false);
610        };
611        if !greenharness_slots::SUPPORTED {
612            CURRENT.with(|c| c.borrow_mut().settled = true);
613            return Ok(false);
614        }
615        let policy = match slot_wait {
616            SlotWait::NeverWaits => BusyPolicy::Defer {
617                slot_wait: Duration::ZERO,
618            },
619            SlotWait::BoundedForWarn => BusyPolicy::Wait,
620            SlotWait::Policy => busy_policy(settings),
621        };
622        let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
623            0 => 3600,
624            s => s,
625        });
626        let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
627            HostSeen::Busy
628        } else {
629            HostSeen::NotYet
630        };
631        let plan = wait_plan(slot_wait, policy, ceiling, warn_slot_wait(settings), seen);
632        let slot_cap = sizing.cap_for(machine.cores);
633        let cap = u64::from(slot_cap);
634        // Hook checks take one slot; the width is set whether a slot is
635        // granted or the check runs unqueued.
636        let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
637        let bounds = match plan {
638            WaitPlan::Queue(bounds) => bounds,
639            WaitPlan::Now => {
640                // Skipping the queue is a choice made up front (ADR-0022),
641                // said and journalled as such.
642                crate::hooks::common::say(&format!(
643                    "  running unqueued: {}=now skips the host slot queue",
644                    crate::ui::highlight(ON_BUSY_ENV)
645                ));
646                record_acquisition(
647                    &name,
648                    Some(jobs),
649                    Some((slot_cap, machine.cores)),
650                    Duration::ZERO,
651                    "now",
652                    None,
653                );
654                CURRENT.with(|c| {
655                    let mut c = c.borrow_mut();
656                    c.settled = true;
657                    c.jobs = Some(jobs);
658                    c.sized = Some((slot_cap, machine.cores));
659                });
660                return Ok(false);
661            }
662        };
663        let sink = crate::live::current_sink();
664        if let Some((stage, idx)) = &sink {
665            stage.queue(*idx, Some((Instant::now(), cap)));
666        }
667        let started = Instant::now();
668        let holder = holder_for(&name);
669        let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
670        if let (
671            BusyPolicy::Defer { .. },
672            Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
673        ) = (policy, &got)
674        {
675            let more = sibling_bounds(
676                slot_wait,
677                greenharness_slots::held_in_process(),
678                ceiling,
679                started.elapsed(),
680            );
681            got = wait_for_slot(sizing, machine, holder, more);
682        }
683        if let Some((stage, idx)) = &sink {
684            stage.queue(*idx, None);
685        }
686        let waited = started.elapsed();
687        CURRENT.with(|c| c.borrow_mut().queued += waited);
688        // Piped output never shows the region, and a heartbeat only comes
689        // after a minute: say once where the time went.
690        if got.is_ok() && waited >= Duration::from_secs(1) {
691            crate::hooks::common::say(&format!(
692                "  (waited {} for a host slot, {} {cap})",
693                crate::hooks::common::human_secs(waited.as_secs()),
694                crate::ui::highlight("greengate.hostSlots")
695            ));
696        }
697        // A wait that ended in line defers, whatever the policy: nothing
698        // runs outside the queue because a wait ended (ADR-0022).
699        let ended = got.as_ref().err().and_then(Reason::ended);
700        let defer = ended.is_some();
701        let end = ended.map(greenharness_slots::LineEnd::end);
702        let cause = ended.map_or(String::new(), |end| defer_cause(end, policy, slot_wait));
703        let by_slot_wait = matches!(
704            (policy, ended),
705            (
706                BusyPolicy::Defer { .. },
707                Some(greenharness_slots::LineEnd::Ceiling { .. })
708            )
709        );
710        let outcome = match (&got, defer) {
711            (Ok(_), _) => "admitted",
712            (Err(_), true) => "deferred",
713            (Err(_), false) => "unqueued",
714        };
715        record_acquisition(
716            &name,
717            Some(jobs),
718            Some((slot_cap, machine.cores)),
719            waited,
720            outcome,
721            end,
722        );
723        let held = match got {
724            Ok(lease) => Some(lease),
725            // The deferral line is the dispatcher's, not this note.
726            Err(Reason::Ended(_)) => None,
727            Err(reason) => {
728                note(&reason);
729                None
730            }
731        };
732        if defer {
733            BUSY_SEEN.store(true, Ordering::SeqCst);
734            if by_slot_wait {
735                DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
736            }
737        }
738        CURRENT.with(|c| {
739            let mut c = c.borrow_mut();
740            c.held = held;
741            c.settled = true;
742            c.jobs = Some(jobs);
743            c.sized = Some((slot_cap, machine.cores));
744            if defer {
745                c.deferred = Some(waited);
746                c.deferred_cause = cause;
747            }
748        });
749        if defer {
750            return Err(refusal());
751        }
752    }
753    // A light check run while a slot is parked between two heavy gates: its
754    // tools run under that slot (a child `amont slot run` must not queue for
755    // its parent's slot).
756    Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
757}
758
759/// The next heavy check takes the slot the previous one parked: renamed to
760/// itself, recorded as a wait of nothing, its width applied as a grant's is.
761fn take_handed(handed: Parked, name: &str) -> bool {
762    let Parked { lease, jobs, sized } = handed;
763    if let Err(error) = lease.rename(&holder_for(name)) {
764        crate::hooks::common::say(&format!(
765            "  host slot kept, but `{BIN} slots` may still name the previous check: {error}"
766        ));
767    }
768    record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
769    CURRENT.with(|current| {
770        let mut current = current.borrow_mut();
771        current.held = Some(lease);
772        current.settled = true;
773        current.jobs = jobs;
774        current.sized = sized;
775    });
776    true
777}
778
779/// One line of `waits.jsonl` for the check `name`, with where it ran.
780/// `sized` is the (cap, cores) the waiter was sized for, when known.
781fn record_acquisition(
782    name: &str,
783    jobs: Option<u32>,
784    sized: Option<(u32, u32)>,
785    waited: Duration,
786    outcome: &str,
787    end: Option<greenharness_slots::WaitEnd>,
788) {
789    let short = crate::short_name(name);
790    greenharness_slots::record_wait_named(
791        &greenharness_slots::dir(),
792        crate::names::SLOT_HOLDER,
793        greenharness_slots::WaitContext {
794            name: Some(short),
795            place: if crate::rehearsal::in_prestage() {
796                greenharness_slots::WaitPlace::Prestage
797            } else if crate::rehearsal::in_snapshot() {
798                greenharness_slots::WaitPlace::Rehearsal
799            } else {
800                greenharness_slots::WaitPlace::Push
801            },
802            cap: sized.map(|(cap, _)| cap),
803            cores: sized.map(|(_, cores)| cores),
804            end,
805        },
806        1,
807        jobs,
808        waited.as_millis(),
809        outcome,
810    );
811}
812
813/// Bound `cmd` to the width this thread's heavy check was given (see
814/// `Current::jobs`); a light check, or slots off, sets nothing. Called by
815/// every runner after [`before_spawn`].
816pub fn bound(cmd: &mut std::process::Command) {
817    let own = CURRENT.with(|c| c.borrow().jobs);
818    // A light check between two heavy gates runs under the parked slot.
819    if let Some(jobs) = own.or_else(|| {
820        parking()
821            .then(|| parked().as_ref().and_then(|p| p.jobs))
822            .flatten()
823    }) {
824        greenharness_slots::bound_width(cmd, jobs);
825    }
826}
827
828/// Wait in line for one slot within `bounds`, saying once whom the check
829/// waits behind (ADR-0022: the crate's [`greenharness_slots::wait_in_line`]).
830/// Failing to join the queue at all says the slots are unusable.
831fn wait_for_slot(
832    sizing: greenharness_slots::Sizing,
833    machine: greenharness_slots::Machine,
834    holder: greenharness_slots::Holder,
835    bounds: greenharness_slots::WaitBounds,
836) -> Result<greenharness_slots::Lease, Reason> {
837    let waiter = match greenharness_slots::Waiter::new_in_on(
838        &greenharness_slots::dir(),
839        sizing,
840        1,
841        holder,
842        machine,
843    ) {
844        Ok(w) => w,
845        Err(e) if e.kind() == std::io::ErrorKind::Other => {
846            return Err(Reason::DirUnsafe(e.to_string()))
847        }
848        Err(e) => return Err(Reason::Io(e.to_string())),
849    };
850    let mut said = false;
851    greenharness_slots::wait_in_line(waiter, bounds, |queue| {
852        if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
853            said = true;
854            crate::hooks::common::say(&format!("  {}", behind(queue)));
855            crate::hooks::common::say(&format!("  see: {BIN} slots"));
856        }
857    })
858    .map_err(Reason::Ended)
859}
860
861/// `queued behind relais: cargo test (greengate-wt-x, 4m) · 2 waiting`.
862pub fn behind(queue: &greenharness_slots::Queue) -> String {
863    let now = greenharness_slots::now_ms();
864    let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
865    if queue.unknown > 0 {
866        who.push(format!("{} unknown (old client)", queue.unknown));
867    }
868    let reason = queue
869        .reason
870        .map_or(String::new(), |r| format!(" ({})", r.describe()));
871    format!(
872        "queued behind {}{reason} · {} waiting",
873        who.join(", "),
874        queue.waiting.max(1)
875    )
876}
877
878/// One line for the reasons a person can act on; nothing for the normal
879/// case (the platform). A wait that ended in line defers, and the dispatcher
880/// says so; these are the slots being unusable.
881fn note(reason: &Reason) {
882    match reason {
883        Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
884            "host slots are off for this check: {why}. Remove it, or set {} to a directory \
885             only you own",
886            crate::ui::highlight(DIR_ENV)
887        )),
888        Reason::Io(why) => {
889            crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
890        }
891        Reason::Ended(_) | Reason::Unsupported => {}
892    }
893}
894
895#[cfg(all(test, unix))]
896mod tests {
897    use super::*;
898
899    fn settings_from(conf: &str) -> crate::config::Settings {
900        let lines = crate::manifest::parse_lines(conf);
901        let (policy, _) = crate::policy::Policy::from_lines(&lines);
902        crate::config::Settings::new(policy)
903    }
904
905    /// `GREENGATE_ON_BUSY`, then `amont.conf`, then `wait`; a bad environment
906    /// value is ignored for the file's.
907    #[test]
908    fn the_busy_policy_is_env_then_file_then_wait() {
909        let none = settings_from("");
910        let defer = settings_from("set onBusy defer\nset slotWait 5\n");
911        assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
912        assert_eq!(
913            resolve_busy(None, &defer),
914            BusyPolicy::Defer {
915                slot_wait: Duration::from_secs(5)
916            }
917        );
918        assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
919        assert_eq!(
920            resolve_busy(Some("DEFER"), &none),
921            BusyPolicy::Defer {
922                slot_wait: Duration::from_secs(60)
923            }
924        );
925        assert_eq!(
926            resolve_busy(Some("later"), &defer),
927            BusyPolicy::Defer {
928                slot_wait: Duration::from_secs(5)
929            }
930        );
931        assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
932        // ADR-0022: `now` skips the queue for one run, from the environment
933        // only; the file and git config keep `wait|defer`.
934        assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
935        let committed = settings_from("set onBusy now\n");
936        assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
937    }
938
939    /// ADR-0022, one row of the plan's table per assertion: skip the
940    /// queue, or wait in line within these bounds.
941    #[test]
942    fn each_caller_waits_by_its_row_of_the_table() {
943        use greenharness_slots::WaitBounds;
944        let s = |n| Duration::from_secs(n);
945        let (ceiling, warn) = (s(3600), s(600));
946        let defer = BusyPolicy::Defer { slot_wait: s(60) };
947        let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
948        let row =
949            |slot_wait, policy, ceiling, seen| wait_plan(slot_wait, policy, ceiling, warn, seen);
950        // `onBusy wait`, the default (rehearsal and pre-stage too): no stall
951        // window on the hook path, only the ceiling.
952        assert_eq!(
953            row(
954                SlotWait::Policy,
955                BusyPolicy::Wait,
956                ceiling,
957                HostSeen::NotYet
958            ),
959            queue(None, ceiling)
960        );
961        // A `warn` check of land's pre-stage: no stall window, under
962        // warnSlotWait, which never outlasts the ceiling.
963        assert_eq!(
964            row(
965                SlotWait::BoundedForWarn,
966                BusyPolicy::Wait,
967                ceiling,
968                HostSeen::NotYet
969            ),
970            queue(None, warn)
971        );
972        assert_eq!(
973            row(
974                SlotWait::BoundedForWarn,
975                BusyPolicy::Wait,
976                s(100),
977                HostSeen::NotYet
978            ),
979            queue(None, s(100))
980        );
981        // `onBusy defer`: slotWait stays hard, with no stall rule; none at
982        // all once this run measured the host busy.
983        assert_eq!(
984            row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
985            queue(None, s(60))
986        );
987        assert_eq!(
988            row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
989            queue(None, Duration::ZERO)
990        );
991        // A `warn` check outside a rehearsal never waits.
992        assert_eq!(
993            row(
994                SlotWait::NeverWaits,
995                BusyPolicy::Wait,
996                ceiling,
997                HostSeen::NotYet
998            ),
999            queue(None, Duration::ZERO)
1000        );
1001        // `GREENGATE_ON_BUSY=now`: no wait at all.
1002        assert_eq!(
1003            row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1004            WaitPlan::Now
1005        );
1006    }
1007
1008    /// The sibling-holder extension: with a sibling of this process holding
1009    /// a slot, the second wait goes on, with no stall window, to the rest of
1010    /// the ceiling; without one it is a single last poll.
1011    #[test]
1012    fn the_sibling_extension_waits_to_the_ceiling() {
1013        let s = |n| Duration::from_secs(n);
1014        let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60));
1015        assert_eq!(
1016            with_sibling.window, None,
1017            "no stall window on the hook path"
1018        );
1019        assert_eq!(with_sibling.ceiling, s(3540));
1020        let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60));
1021        assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1022        let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60));
1023        assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1024    }
1025
1026    /// The refused spawn names why: a stall names its own window (the
1027    /// sibling extension's too) and the place; `slotWait` keeps naming
1028    /// `onBusy defer`; a failed poll names the error.
1029    #[test]
1030    fn a_deferral_names_its_cause() {
1031        use greenharness_slots::LineEnd;
1032        let stalled = LineEnd::Stalled {
1033            window: Duration::from_secs(300),
1034            position: 1,
1035        };
1036        let cause = defer_cause(
1037            &stalled,
1038            BusyPolicy::Defer {
1039                slot_wait: Duration::from_secs(60),
1040            },
1041            SlotWait::Policy,
1042        );
1043        assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1044        assert!(cause.contains("(position 2)"), "{cause}");
1045        let slot_wait = defer_cause(
1046            &LineEnd::Ceiling {
1047                waited: Duration::from_secs(60),
1048            },
1049            BusyPolicy::Defer {
1050                slot_wait: Duration::from_secs(60),
1051            },
1052            SlotWait::Policy,
1053        );
1054        assert!(
1055            slot_wait.ends_with("(greengate.onBusy defer)"),
1056            "{slot_wait}"
1057        );
1058        let ceiling = defer_cause(
1059            &LineEnd::Ceiling {
1060                waited: Duration::from_secs(3600),
1061            },
1062            BusyPolicy::Wait,
1063            SlotWait::Policy,
1064        );
1065        assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1066        assert!(ceiling.ends_with("(greengate.timeout)"), "{ceiling}");
1067        let warn = defer_cause(
1068            &LineEnd::Ceiling {
1069                waited: Duration::from_secs(600),
1070            },
1071            BusyPolicy::Wait,
1072            SlotWait::BoundedForWarn,
1073        );
1074        assert!(warn.ends_with("(greengate.warnSlotWait)"), "{warn}");
1075        let failed = defer_cause(
1076            &LineEnd::PollFailed {
1077                error: std::io::Error::other("busy disk"),
1078            },
1079            BusyPolicy::Wait,
1080            SlotWait::Policy,
1081        );
1082        assert!(failed.contains("busy disk"), "{failed}");
1083    }
1084
1085    /// Every end of a wait in line defers; only failing to join the queue
1086    /// means the slots are unusable.
1087    #[test]
1088    fn every_end_of_a_wait_in_line_defers() {
1089        let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1090            waited: Duration::from_secs(1),
1091        });
1092        assert!(ended.ended().is_some());
1093        for reason in [
1094            Reason::Io("x".into()),
1095            Reason::DirUnsafe("x".into()),
1096            Reason::Unsupported,
1097        ] {
1098            assert!(reason.ended().is_none(), "{reason:?}");
1099        }
1100    }
1101
1102    #[test]
1103    fn heavy_is_the_list() {
1104        assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1105        assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1106    }
1107
1108    /// Every heavy name is a built-in: a renamed check must not silently
1109    /// stop queueing.
1110    #[test]
1111    fn every_heavy_name_is_a_builtin() {
1112        for name in HEAVY {
1113            assert!(
1114                crate::registry::CHECKS.iter().any(|c| c.name == *name),
1115                "{name} is not a built-in check"
1116            );
1117        }
1118    }
1119
1120    /// `.cargo/config.toml` reaches the test binaries: without it the
1121    /// integration fixtures would queue on the real host slots.
1122    #[test]
1123    fn cargo_pins_the_host_knobs_for_tests() {
1124        assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
1125        assert_eq!(
1126            std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1127            Ok("1")
1128        );
1129    }
1130
1131    /// A light check never asks. A heavy one run by an amont that holds a
1132    /// slot (the test process has `GREENHARNESS_HOST_SLOT=held` from
1133    /// `.cargo/config.toml`) is nested: it settles without a slot.
1134    #[test]
1135    fn a_light_check_never_takes_a_slot() {
1136        let settings = crate::config::Settings::default();
1137        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1138        assert!(!before_spawn(&settings).unwrap());
1139    }
1140
1141    #[test]
1142    fn a_nested_heavy_check_settles_without_a_slot() {
1143        let settings = crate::config::Settings::default();
1144        let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1145        assert_eq!(current_check().as_deref(), Some("clippy"));
1146        assert!(!before_spawn(&settings).unwrap());
1147        assert!(CURRENT.with(|c| c.borrow().settled));
1148        // Nested: the parent's bounds are inherited, so none is set here.
1149        let mut cmd = std::process::Command::new("true");
1150        bound(&mut cmd);
1151        assert_eq!(cmd.get_envs().count(), 0);
1152    }
1153
1154    /// A scope dropped on an early return releases the parked slot: nothing
1155    /// stays held, and no holder record stays on disk.
1156    #[test]
1157    fn a_park_scope_dropped_early_releases_the_parked_slot() {
1158        let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1159        let _ = std::fs::remove_dir_all(&dir); // best-effort: a fresh scratch dir
1160        let early = || {
1161            let _scope = ParkScope::begin();
1162            let mut waiter = greenharness_slots::Waiter::new_in(
1163                &dir,
1164                greenharness_slots::Sizing::Fixed(1),
1165                1,
1166                greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1167            )
1168            .unwrap();
1169            let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1170                panic!("the empty directory grants the slot");
1171            };
1172            assert!(dir.join("holders/slot-0.who").exists());
1173            park(lease, Some(2), Some((3, 6)));
1174            assert!(dir.join("holders/slot-0.who").exists());
1175        };
1176        early();
1177        assert!(!dir.join("holders/slot-0.who").exists());
1178        let _ = std::fs::remove_dir_all(&dir); // best-effort: scratch
1179    }
1180
1181    #[test]
1182    fn a_light_check_sets_no_width() {
1183        let settings = crate::config::Settings::default();
1184        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1185        before_spawn(&settings).unwrap();
1186        let mut cmd = std::process::Command::new("true");
1187        bound(&mut cmd);
1188        assert_eq!(cmd.get_envs().count(), 0);
1189    }
1190}