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 line that ended
80/// 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 while the line moves, up to `greengate.timeout`, then defer the
182    /// check to CI (ADR-0022): 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 while the line
272    /// moves, at most `greengate.warnSlotWait`, then defers (ADR-0022). Set
273    /// by [`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(end: &greenharness_slots::LineEnd, policy: BusyPolicy) -> String {
398    use greenharness_slots::LineEnd;
399    let human = |d: Duration| crate::hooks::common::human_secs(d.as_secs());
400    match end {
401        LineEnd::Stalled { window, position } => format!(
402            "deferred to CI: the host slot line made no progress for {} (position {})",
403            human(*window),
404            position + 1
405        ),
406        LineEnd::PollFailed { error } => {
407            format!("deferred to CI: the host slot files failed: {error}")
408        }
409        LineEnd::Ceiling { waited } => match policy {
410            BusyPolicy::Defer { .. } => format!(
411                "deferred to CI: no host slot freed in {} (greengate.onBusy defer)",
412                human(*waited)
413            ),
414            BusyPolicy::Wait | BusyPolicy::Now => {
415                format!("deferred to CI: no host slot within {}", human(*waited))
416            }
417        },
418    }
419}
420
421/// How one heavy check waits for a slot (ADR-0022): it skips the queue, or
422/// it waits in line within bounds. Whatever ends the wait, the check defers.
423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
424enum WaitPlan {
425    Now,
426    Queue(greenharness_slots::WaitBounds),
427}
428
429/// The [`WaitPlan`] for a check: one row of the plan's table per arm.
430/// `ceiling` is `greengate.timeout` (3600 s when 0), `stall` the stall
431/// window, `seen` whether this run already deferred on a busy host.
432fn wait_plan(
433    slot_wait: SlotWait,
434    policy: BusyPolicy,
435    ceiling: Duration,
436    warn_wait: Duration,
437    stall: Duration,
438    seen: HostSeen,
439) -> WaitPlan {
440    let queue =
441        |window, ceiling| WaitPlan::Queue(greenharness_slots::WaitBounds { window, ceiling });
442    match (slot_wait, policy) {
443        (_, BusyPolicy::Now) => WaitPlan::Now,
444        (SlotWait::NeverWaits, _) => queue(None, Duration::ZERO),
445        (SlotWait::BoundedForWarn, _) => queue(Some(stall), warn_wait.min(ceiling)),
446        (SlotWait::Policy, BusyPolicy::Wait) => queue(Some(stall), ceiling),
447        (SlotWait::Policy, BusyPolicy::Defer { slot_wait }) => match seen {
448            // The host was already measured busy by this run: defer now.
449            HostSeen::Busy => queue(None, Duration::ZERO),
450            HostSeen::NotYet => queue(None, slot_wait),
451        },
452    }
453}
454
455/// The bounds of the second wait an `onBusy defer` check takes after its
456/// `slotWait` ran out: while a sibling check of this process holds a slot,
457/// the host is busy with this commit's own work, which is not a reason to
458/// defer, so it waits as `wait` does, while the line moves, up to the
459/// ceiling; else one more pass, as a sibling may have released between the
460/// last poll and now.
461fn sibling_bounds(
462    slot_wait: SlotWait,
463    held_in_process: usize,
464    ceiling: Duration,
465    elapsed: Duration,
466    stall: Duration,
467) -> greenharness_slots::WaitBounds {
468    let waits_on_sibling = held_in_process > 0 && !matches!(slot_wait, SlotWait::NeverWaits);
469    if waits_on_sibling {
470        greenharness_slots::WaitBounds {
471            window: Some(stall),
472            ceiling: ceiling.saturating_sub(elapsed),
473        }
474    } else {
475        greenharness_slots::WaitBounds {
476            window: None,
477            ceiling: Duration::ZERO,
478        }
479    }
480}
481
482/// The stall window, read from [`greenharness_slots::STALL_ENV`] here, at the
483/// binary's edge, its warning said once.
484fn stall_window() -> Duration {
485    let setting = std::env::var(greenharness_slots::STALL_ENV).ok();
486    let (window, warning) = greenharness_slots::Stall::window_from(setting.as_deref());
487    if let Some(warning) = warning {
488        say_once(&warning);
489    }
490    window
491}
492
493impl Drop for CheckGuard {
494    fn drop(&mut self) {
495        let finished = CURRENT.with(RefCell::take);
496        if let Some(lease) = finished.held {
497            if parking() {
498                park(lease, finished.jobs, finished.sized);
499            }
500        }
501    }
502}
503
504/// Keep `lease` for the next heavy check of this pre-push, its record
505/// renamed so no waiter's line names the gate that finished.
506fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
507    if let Err(error) = lease.rename(&between_gates()) {
508        crate::hooks::common::say(&format!(
509            "  host slot kept, but `{BIN} slots` may still name the previous check: {error}"
510        ));
511    }
512    let earlier = parked().replace(Parked { lease, jobs, sized });
513    drop(earlier);
514}
515
516/// The dispatcher is about to run `name`, of `weight`, on this thread. The
517/// weight comes from the check (`Check::weight`), not the name: a declared
518/// check is Heavy by its line, which no name says.
519pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
520    CURRENT.with(|c| {
521        *c.borrow_mut() = Current {
522            name: name.to_string(),
523            heavy: weight == Weight::Heavy,
524            ..Current::default()
525        }
526    });
527    CheckGuard
528}
529
530/// The check running on this thread cannot block (its severity is `warn`):
531/// on a busy host it takes a free slot or defers to CI at once, under either
532/// busy policy, instead of holding the commit, or the push and its open
533/// connection to the remote, while it queues for a verdict that stops
534/// nothing. Not called inside a rehearsal snapshot: there nothing is held
535/// open and land's pre-stage needs the gate's evidence, so the check follows
536/// the busy policy the rehearsal sets.
537pub fn never_waits() {
538    CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
539}
540
541/// The check running on this thread is a heavy `warn` check of land's
542/// pre-stage, where somebody waits for its evidence: it waits for a slot at
543/// most `greengate.warnSlotWait` (and never longer than `greengate.timeout`), under
544/// either busy policy, while its line moves, then defers (ADR-0022).
545pub fn wait_bounded_for_warn() {
546    CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
547}
548
549/// `greengate.warnSlotWait`: how long a heavy `warn` check of land's pre-stage
550/// waits for a slot. Git config, then a trusted `amont.conf`, then 600 s.
551fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
552    Duration::from_secs(
553        crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
554    )
555}
556
557/// The name of the check running on this thread, without its stage
558/// prefix (`clippy`), when the dispatcher installed one.
559pub fn current_check() -> Option<String> {
560    CURRENT.with(|c| {
561        let c = c.borrow();
562        (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
563    })
564}
565
566/// Whether this process was started by an amont that holds a slot.
567fn nested() -> bool {
568    std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
569}
570
571/// Called before a tool is spawned. For the first tool of a heavy check,
572/// waits for a slot, showing the wait in the check's row. Returns whether
573/// this thread holds a slot, so the caller exports [`HELD_ENV`]; an `Err`
574/// when the busy policy deferred the check, so the caller does not spawn.
575pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
576    let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
577        let current = current.borrow();
578        (
579            current.heavy && !current.settled,
580            current.deferred.is_some(),
581            current.name.clone(),
582            current.slot_wait,
583        )
584    });
585    // A check that caught the first refusal and tries another tool is
586    // refused at once, not after a second wait.
587    if deferred {
588        return Err(refusal());
589    }
590    if pending {
591        if let Some(handed) = parking().then(|| parked().take()).flatten() {
592            return Ok(take_handed(handed, &name));
593        }
594        // Nested first: a nested amont must not pay the host-key scan for a
595        // slot count it is about to ignore. Neither answer queues, so neither
596        // can defer.
597        let (sizing, machine) = if nested() {
598            (None, greenharness_slots::Machine::detect())
599        } else {
600            sizing_and_machine(settings)
601        };
602        let Some(sizing) = sizing else {
603            CURRENT.with(|c| c.borrow_mut().settled = true);
604            return Ok(false);
605        };
606        if !greenharness_slots::SUPPORTED {
607            CURRENT.with(|c| c.borrow_mut().settled = true);
608            return Ok(false);
609        }
610        let policy = match slot_wait {
611            SlotWait::NeverWaits => BusyPolicy::Defer {
612                slot_wait: Duration::ZERO,
613            },
614            SlotWait::BoundedForWarn => BusyPolicy::Wait,
615            SlotWait::Policy => busy_policy(settings),
616        };
617        let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
618            0 => 3600,
619            s => s,
620        });
621        let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
622            HostSeen::Busy
623        } else {
624            HostSeen::NotYet
625        };
626        let plan = wait_plan(
627            slot_wait,
628            policy,
629            ceiling,
630            warn_slot_wait(settings),
631            stall_window(),
632            seen,
633        );
634        let slot_cap = sizing.cap_for(machine.cores);
635        let cap = u64::from(slot_cap);
636        // Hook checks take one slot; the width is set whether a slot is
637        // granted or the check runs unqueued.
638        let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
639        let bounds = match plan {
640            WaitPlan::Queue(bounds) => bounds,
641            WaitPlan::Now => {
642                // Skipping the queue is a choice made up front (ADR-0022),
643                // said and journalled as such.
644                crate::hooks::common::say(&format!(
645                    "  running unqueued: {}=now skips the host slot queue",
646                    crate::ui::highlight(ON_BUSY_ENV)
647                ));
648                record_acquisition(
649                    &name,
650                    Some(jobs),
651                    Some((slot_cap, machine.cores)),
652                    Duration::ZERO,
653                    "now",
654                    None,
655                );
656                CURRENT.with(|c| {
657                    let mut c = c.borrow_mut();
658                    c.settled = true;
659                    c.jobs = Some(jobs);
660                    c.sized = Some((slot_cap, machine.cores));
661                });
662                return Ok(false);
663            }
664        };
665        let sink = crate::live::current_sink();
666        if let Some((stage, idx)) = &sink {
667            stage.queue(*idx, Some((Instant::now(), cap)));
668        }
669        let started = Instant::now();
670        let holder = holder_for(&name);
671        let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
672        if let (
673            BusyPolicy::Defer { .. },
674            Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
675        ) = (policy, &got)
676        {
677            let more = sibling_bounds(
678                slot_wait,
679                greenharness_slots::held_in_process(),
680                ceiling,
681                started.elapsed(),
682                stall_window(),
683            );
684            got = wait_for_slot(sizing, machine, holder, more);
685        }
686        if let Some((stage, idx)) = &sink {
687            stage.queue(*idx, None);
688        }
689        let waited = started.elapsed();
690        CURRENT.with(|c| c.borrow_mut().queued += waited);
691        // Piped output never shows the region, and a heartbeat only comes
692        // after a minute: say once where the time went.
693        if got.is_ok() && waited >= Duration::from_secs(1) {
694            crate::hooks::common::say(&format!(
695                "  (waited {} for a host slot, {} {cap})",
696                crate::hooks::common::human_secs(waited.as_secs()),
697                crate::ui::highlight("greengate.hostSlots")
698            ));
699        }
700        // A wait that ended in line defers, whatever the policy: nothing
701        // runs outside the queue because a wait ended (ADR-0022).
702        let ended = got.as_ref().err().and_then(Reason::ended);
703        let defer = ended.is_some();
704        let end = ended.map(greenharness_slots::LineEnd::end);
705        let cause = ended.map_or(String::new(), |end| defer_cause(end, policy));
706        let by_slot_wait = matches!(
707            (policy, ended),
708            (
709                BusyPolicy::Defer { .. },
710                Some(greenharness_slots::LineEnd::Ceiling { .. })
711            )
712        );
713        let outcome = match (&got, defer) {
714            (Ok(_), _) => "admitted",
715            (Err(_), true) => "deferred",
716            (Err(_), false) => "unqueued",
717        };
718        record_acquisition(
719            &name,
720            Some(jobs),
721            Some((slot_cap, machine.cores)),
722            waited,
723            outcome,
724            end,
725        );
726        let held = match got {
727            Ok(lease) => Some(lease),
728            // The deferral line is the dispatcher's, not this note.
729            Err(Reason::Ended(_)) => None,
730            Err(reason) => {
731                note(&reason);
732                None
733            }
734        };
735        if defer {
736            BUSY_SEEN.store(true, Ordering::SeqCst);
737            if by_slot_wait {
738                DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
739            }
740        }
741        CURRENT.with(|c| {
742            let mut c = c.borrow_mut();
743            c.held = held;
744            c.settled = true;
745            c.jobs = Some(jobs);
746            c.sized = Some((slot_cap, machine.cores));
747            if defer {
748                c.deferred = Some(waited);
749                c.deferred_cause = cause;
750            }
751        });
752        if defer {
753            return Err(refusal());
754        }
755    }
756    // A light check run while a slot is parked between two heavy gates: its
757    // tools run under that slot (a child `amont slot run` must not queue for
758    // its parent's slot).
759    Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
760}
761
762/// The next heavy check takes the slot the previous one parked: renamed to
763/// itself, recorded as a wait of nothing, its width applied as a grant's is.
764fn take_handed(handed: Parked, name: &str) -> bool {
765    let Parked { lease, jobs, sized } = handed;
766    if let Err(error) = lease.rename(&holder_for(name)) {
767        crate::hooks::common::say(&format!(
768            "  host slot kept, but `{BIN} slots` may still name the previous check: {error}"
769        ));
770    }
771    record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
772    CURRENT.with(|current| {
773        let mut current = current.borrow_mut();
774        current.held = Some(lease);
775        current.settled = true;
776        current.jobs = jobs;
777        current.sized = sized;
778    });
779    true
780}
781
782/// One line of `waits.jsonl` for the check `name`, with where it ran.
783/// `sized` is the (cap, cores) the waiter was sized for, when known.
784fn record_acquisition(
785    name: &str,
786    jobs: Option<u32>,
787    sized: Option<(u32, u32)>,
788    waited: Duration,
789    outcome: &str,
790    end: Option<greenharness_slots::WaitEnd>,
791) {
792    let short = crate::short_name(name);
793    greenharness_slots::record_wait_named(
794        &greenharness_slots::dir(),
795        crate::names::SLOT_HOLDER,
796        greenharness_slots::WaitContext {
797            name: Some(short),
798            place: if crate::rehearsal::in_prestage() {
799                greenharness_slots::WaitPlace::Prestage
800            } else if crate::rehearsal::in_snapshot() {
801                greenharness_slots::WaitPlace::Rehearsal
802            } else {
803                greenharness_slots::WaitPlace::Push
804            },
805            cap: sized.map(|(cap, _)| cap),
806            cores: sized.map(|(_, cores)| cores),
807            end,
808        },
809        1,
810        jobs,
811        waited.as_millis(),
812        outcome,
813    );
814}
815
816/// Bound `cmd` to the width this thread's heavy check was given (see
817/// `Current::jobs`); a light check, or slots off, sets nothing. Called by
818/// every runner after [`before_spawn`].
819pub fn bound(cmd: &mut std::process::Command) {
820    let own = CURRENT.with(|c| c.borrow().jobs);
821    // A light check between two heavy gates runs under the parked slot.
822    if let Some(jobs) = own.or_else(|| {
823        parking()
824            .then(|| parked().as_ref().and_then(|p| p.jobs))
825            .flatten()
826    }) {
827        greenharness_slots::bound_width(cmd, jobs);
828    }
829}
830
831/// Wait in line for one slot within `bounds`, saying once whom the check
832/// waits behind (ADR-0022: the crate's [`greenharness_slots::wait_in_line`]).
833/// Failing to join the queue at all says the slots are unusable.
834fn wait_for_slot(
835    sizing: greenharness_slots::Sizing,
836    machine: greenharness_slots::Machine,
837    holder: greenharness_slots::Holder,
838    bounds: greenharness_slots::WaitBounds,
839) -> Result<greenharness_slots::Lease, Reason> {
840    let waiter = match greenharness_slots::Waiter::new_in_on(
841        &greenharness_slots::dir(),
842        sizing,
843        1,
844        holder,
845        machine,
846    ) {
847        Ok(w) => w,
848        Err(e) if e.kind() == std::io::ErrorKind::Other => {
849            return Err(Reason::DirUnsafe(e.to_string()))
850        }
851        Err(e) => return Err(Reason::Io(e.to_string())),
852    };
853    let mut said = false;
854    greenharness_slots::wait_in_line(waiter, bounds, |queue| {
855        if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
856            said = true;
857            crate::hooks::common::say(&format!("  {}", behind(queue)));
858            crate::hooks::common::say(&format!("  see: {BIN} slots"));
859        }
860    })
861    .map_err(Reason::Ended)
862}
863
864/// `queued behind relais: cargo test (greengate-wt-x, 4m) · 2 waiting`.
865pub fn behind(queue: &greenharness_slots::Queue) -> String {
866    let now = greenharness_slots::now_ms();
867    let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
868    if queue.unknown > 0 {
869        who.push(format!("{} unknown (old client)", queue.unknown));
870    }
871    let reason = queue
872        .reason
873        .map_or(String::new(), |r| format!(" ({})", r.describe()));
874    format!(
875        "queued behind {}{reason} · {} waiting",
876        who.join(", "),
877        queue.waiting.max(1)
878    )
879}
880
881/// One line for the reasons a person can act on; nothing for the normal
882/// case (the platform). A wait that ended in line defers, and the dispatcher
883/// says so; these are the slots being unusable.
884fn note(reason: &Reason) {
885    match reason {
886        Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
887            "host slots are off for this check: {why}. Remove it, or set {} to a directory \
888             only you own",
889            crate::ui::highlight(DIR_ENV)
890        )),
891        Reason::Io(why) => {
892            crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
893        }
894        Reason::Ended(_) | Reason::Unsupported => {}
895    }
896}
897
898#[cfg(all(test, unix))]
899mod tests {
900    use super::*;
901
902    fn settings_from(conf: &str) -> crate::config::Settings {
903        let lines = crate::manifest::parse_lines(conf);
904        let (policy, _) = crate::policy::Policy::from_lines(&lines);
905        crate::config::Settings::new(policy)
906    }
907
908    /// `GREENGATE_ON_BUSY`, then `amont.conf`, then `wait`; a bad environment
909    /// value is ignored for the file's.
910    #[test]
911    fn the_busy_policy_is_env_then_file_then_wait() {
912        let none = settings_from("");
913        let defer = settings_from("set onBusy defer\nset slotWait 5\n");
914        assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
915        assert_eq!(
916            resolve_busy(None, &defer),
917            BusyPolicy::Defer {
918                slot_wait: Duration::from_secs(5)
919            }
920        );
921        assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
922        assert_eq!(
923            resolve_busy(Some("DEFER"), &none),
924            BusyPolicy::Defer {
925                slot_wait: Duration::from_secs(60)
926            }
927        );
928        assert_eq!(
929            resolve_busy(Some("later"), &defer),
930            BusyPolicy::Defer {
931                slot_wait: Duration::from_secs(5)
932            }
933        );
934        assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
935        // ADR-0022: `now` skips the queue for one run, from the environment
936        // only; the file and git config keep `wait|defer`.
937        assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
938        let committed = settings_from("set onBusy now\n");
939        assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
940    }
941
942    /// ADR-0022, one row of the plan's table per assertion: skip the
943    /// queue, or wait in line within these bounds.
944    #[test]
945    fn each_caller_waits_by_its_row_of_the_table() {
946        use greenharness_slots::WaitBounds;
947        let s = |n| Duration::from_secs(n);
948        let (ceiling, warn, stall) = (s(3600), s(600), s(300));
949        let defer = BusyPolicy::Defer { slot_wait: s(60) };
950        let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
951        let row = |slot_wait, policy, ceiling, seen| {
952            wait_plan(slot_wait, policy, ceiling, warn, stall, seen)
953        };
954        // `onBusy wait`, the default (rehearsal and pre-stage too).
955        assert_eq!(
956            row(
957                SlotWait::Policy,
958                BusyPolicy::Wait,
959                ceiling,
960                HostSeen::NotYet
961            ),
962            queue(Some(stall), ceiling)
963        );
964        // A `warn` check of land's pre-stage: the stall, under warnSlotWait,
965        // which never outlasts the ceiling.
966        assert_eq!(
967            row(
968                SlotWait::BoundedForWarn,
969                BusyPolicy::Wait,
970                ceiling,
971                HostSeen::NotYet
972            ),
973            queue(Some(stall), warn)
974        );
975        assert_eq!(
976            row(
977                SlotWait::BoundedForWarn,
978                BusyPolicy::Wait,
979                s(100),
980                HostSeen::NotYet
981            ),
982            queue(Some(stall), s(100))
983        );
984        // `onBusy defer`: slotWait stays hard, with no stall rule; none at
985        // all once this run measured the host busy.
986        assert_eq!(
987            row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
988            queue(None, s(60))
989        );
990        assert_eq!(
991            row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
992            queue(None, Duration::ZERO)
993        );
994        // A `warn` check outside a rehearsal never waits.
995        assert_eq!(
996            row(
997                SlotWait::NeverWaits,
998                BusyPolicy::Wait,
999                ceiling,
1000                HostSeen::NotYet
1001            ),
1002            queue(None, Duration::ZERO)
1003        );
1004        // `GREENGATE_ON_BUSY=now`: no wait at all.
1005        assert_eq!(
1006            row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1007            WaitPlan::Now
1008        );
1009    }
1010
1011    /// The sibling-holder extension: with a sibling of this process holding
1012    /// a slot, the second wait goes on while the line moves, to the rest of
1013    /// the ceiling; without one it is a single last poll.
1014    #[test]
1015    fn the_sibling_extension_waits_while_the_line_moves() {
1016        let s = |n| Duration::from_secs(n);
1017        let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60), s(300));
1018        assert_eq!(with_sibling.window, Some(s(300)));
1019        assert_eq!(with_sibling.ceiling, s(3540));
1020        let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60), s(300));
1021        assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1022        let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60), s(300));
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        );
1042        assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1043        assert!(cause.contains("(position 2)"), "{cause}");
1044        let slot_wait = defer_cause(
1045            &LineEnd::Ceiling {
1046                waited: Duration::from_secs(60),
1047            },
1048            BusyPolicy::Defer {
1049                slot_wait: Duration::from_secs(60),
1050            },
1051        );
1052        assert!(
1053            slot_wait.ends_with("(greengate.onBusy defer)"),
1054            "{slot_wait}"
1055        );
1056        let ceiling = defer_cause(
1057            &LineEnd::Ceiling {
1058                waited: Duration::from_secs(3600),
1059            },
1060            BusyPolicy::Wait,
1061        );
1062        assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1063        let failed = defer_cause(
1064            &LineEnd::PollFailed {
1065                error: std::io::Error::other("busy disk"),
1066            },
1067            BusyPolicy::Wait,
1068        );
1069        assert!(failed.contains("busy disk"), "{failed}");
1070    }
1071
1072    /// Every end of a wait in line defers; only failing to join the queue
1073    /// means the slots are unusable.
1074    #[test]
1075    fn every_end_of_a_wait_in_line_defers() {
1076        let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1077            waited: Duration::from_secs(1),
1078        });
1079        assert!(ended.ended().is_some());
1080        for reason in [
1081            Reason::Io("x".into()),
1082            Reason::DirUnsafe("x".into()),
1083            Reason::Unsupported,
1084        ] {
1085            assert!(reason.ended().is_none(), "{reason:?}");
1086        }
1087    }
1088
1089    #[test]
1090    fn heavy_is_the_list() {
1091        assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1092        assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1093    }
1094
1095    /// Every heavy name is a built-in: a renamed check must not silently
1096    /// stop queueing.
1097    #[test]
1098    fn every_heavy_name_is_a_builtin() {
1099        for name in HEAVY {
1100            assert!(
1101                crate::registry::CHECKS.iter().any(|c| c.name == *name),
1102                "{name} is not a built-in check"
1103            );
1104        }
1105    }
1106
1107    /// `.cargo/config.toml` reaches the test binaries: without it the
1108    /// integration fixtures would queue on the real host slots.
1109    #[test]
1110    fn cargo_pins_the_host_knobs_for_tests() {
1111        assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
1112        assert_eq!(
1113            std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1114            Ok("1")
1115        );
1116    }
1117
1118    /// A light check never asks. A heavy one run by an amont that holds a
1119    /// slot (the test process has `GREENHARNESS_HOST_SLOT=held` from
1120    /// `.cargo/config.toml`) is nested: it settles without a slot.
1121    #[test]
1122    fn a_light_check_never_takes_a_slot() {
1123        let settings = crate::config::Settings::default();
1124        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1125        assert!(!before_spawn(&settings).unwrap());
1126    }
1127
1128    #[test]
1129    fn a_nested_heavy_check_settles_without_a_slot() {
1130        let settings = crate::config::Settings::default();
1131        let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1132        assert_eq!(current_check().as_deref(), Some("clippy"));
1133        assert!(!before_spawn(&settings).unwrap());
1134        assert!(CURRENT.with(|c| c.borrow().settled));
1135        // Nested: the parent's bounds are inherited, so none is set here.
1136        let mut cmd = std::process::Command::new("true");
1137        bound(&mut cmd);
1138        assert_eq!(cmd.get_envs().count(), 0);
1139    }
1140
1141    /// A scope dropped on an early return releases the parked slot: nothing
1142    /// stays held, and no holder record stays on disk.
1143    #[test]
1144    fn a_park_scope_dropped_early_releases_the_parked_slot() {
1145        let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1146        let _ = std::fs::remove_dir_all(&dir); // best-effort: a fresh scratch dir
1147        let early = || {
1148            let _scope = ParkScope::begin();
1149            let mut waiter = greenharness_slots::Waiter::new_in(
1150                &dir,
1151                greenharness_slots::Sizing::Fixed(1),
1152                1,
1153                greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1154            )
1155            .unwrap();
1156            let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1157                panic!("the empty directory grants the slot");
1158            };
1159            assert!(dir.join("holders/slot-0.who").exists());
1160            park(lease, Some(2), Some((3, 6)));
1161            assert!(dir.join("holders/slot-0.who").exists());
1162        };
1163        early();
1164        assert!(!dir.join("holders/slot-0.who").exists());
1165        let _ = std::fs::remove_dir_all(&dir); // best-effort: scratch
1166    }
1167
1168    #[test]
1169    fn a_light_check_sets_no_width() {
1170        let settings = crate::config::Settings::default();
1171        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1172        before_spawn(&settings).unwrap();
1173        let mut cmd = std::process::Command::new("true");
1174        bound(&mut cmd);
1175        assert_eq!(cmd.get_envs().count(), 0);
1176    }
1177}