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/// The held marker of this run, read once on `settings` (t15): every check
572/// and thread of one run gets the same answer, so a parent lease ending
573/// midway cannot admit some checks and queue others.
574fn marker(settings: &crate::config::Settings) -> &greenharness_slots::Marker {
575    settings.marker.get_or_init(greenharness_slots::held_marker)
576}
577
578/// Whether an ancestor holds a slot for this run: its `GREENHARNESS_HOST_SLOT`
579/// names a live lease (`greenharness_slots::held_marker`).
580pub(crate) fn nested(settings: &crate::config::Settings) -> bool {
581    marker(settings).is_held()
582}
583
584/// For a command about to queue: when its marker was refused, the journal's
585/// `marker_refused` row and the lines to print, the first time only.
586pub(crate) fn marker_refused_note(settings: &crate::config::Settings) -> Option<String> {
587    let marker = marker(settings);
588    settings
589        .marker_log
590        .record(
591            &greenharness_slots::dir(),
592            crate::names::SLOT_HOLDER,
593            marker,
594        )
595        .then(|| greenharness_slots::refused_line(BIN, marker))
596        .flatten()
597}
598
599/// Print a refusal's lines: into the check's output when a stage is
600/// watching it, else on stderr, never on stdout (which a caller may read as
601/// data).
602fn say_refusal(line: &str) {
603    if crate::live::current_sink().is_some() {
604        crate::hooks::common::say(line);
605    } else {
606        eprintln!("{line}");
607    }
608}
609
610/// Called before a tool is spawned. For the first tool of a heavy check,
611/// waits for a slot, showing the wait in the check's row. Returns whether
612/// this thread holds a slot, so the caller exports [`HELD_ENV`]; an `Err`
613/// when the busy policy deferred the check, so the caller does not spawn.
614pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
615    let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
616        let current = current.borrow();
617        (
618            current.heavy && !current.settled,
619            current.deferred.is_some(),
620            current.name.clone(),
621            current.slot_wait,
622        )
623    });
624    // A check that caught the first refusal and tries another tool is
625    // refused at once, not after a second wait.
626    if deferred {
627        return Err(refusal());
628    }
629    if pending {
630        if let Some(handed) = parking().then(|| parked().take()).flatten() {
631            return Ok(take_handed(handed, &name));
632        }
633        // Nested first: a nested amont must not pay the host-key scan for a
634        // slot count it is about to ignore. Neither answer queues, so neither
635        // can defer.
636        let (sizing, machine) = if nested(settings) {
637            (None, greenharness_slots::Machine::detect())
638        } else {
639            sizing_and_machine(settings)
640        };
641        let Some(sizing) = sizing else {
642            CURRENT.with(|c| c.borrow_mut().settled = true);
643            return Ok(false);
644        };
645        if !greenharness_slots::SUPPORTED {
646            CURRENT.with(|c| c.borrow_mut().settled = true);
647            return Ok(false);
648        }
649        let policy = match slot_wait {
650            SlotWait::NeverWaits => BusyPolicy::Defer {
651                slot_wait: Duration::ZERO,
652            },
653            SlotWait::BoundedForWarn => BusyPolicy::Wait,
654            SlotWait::Policy => busy_policy(settings),
655        };
656        let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
657            0 => 3600,
658            s => s,
659        });
660        let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
661            HostSeen::Busy
662        } else {
663            HostSeen::NotYet
664        };
665        let plan = wait_plan(slot_wait, policy, ceiling, warn_slot_wait(settings), seen);
666        let slot_cap = sizing.cap_for(machine.cores);
667        let cap = u64::from(slot_cap);
668        // Hook checks take one slot; the width is set whether a slot is
669        // granted or the check runs unqueued.
670        let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
671        let bounds = match plan {
672            WaitPlan::Queue(bounds) => bounds,
673            WaitPlan::Now => {
674                // Skipping the queue is a choice made up front (ADR-0022),
675                // said and journalled as such.
676                crate::hooks::common::say(&format!(
677                    "  running unqueued: {}=now skips the host slot queue",
678                    crate::ui::highlight(ON_BUSY_ENV)
679                ));
680                record_acquisition(
681                    &name,
682                    Some(jobs),
683                    Some((slot_cap, machine.cores)),
684                    Duration::ZERO,
685                    "now",
686                    None,
687                );
688                CURRENT.with(|c| {
689                    let mut c = c.borrow_mut();
690                    c.settled = true;
691                    c.jobs = Some(jobs);
692                    c.sized = Some((slot_cap, machine.cores));
693                });
694                return Ok(false);
695            }
696        };
697        // A marker that names no live lease queues like none, said once.
698        if let Some(line) = marker_refused_note(settings) {
699            say_refusal(&line);
700        }
701        let sink = crate::live::current_sink();
702        if let Some((stage, idx)) = &sink {
703            stage.queue(*idx, Some((Instant::now(), cap)));
704        }
705        let started = Instant::now();
706        let holder = holder_for(&name);
707        let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
708        if let (
709            BusyPolicy::Defer { .. },
710            Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
711        ) = (policy, &got)
712        {
713            let more = sibling_bounds(
714                slot_wait,
715                greenharness_slots::held_in_process(),
716                ceiling,
717                started.elapsed(),
718            );
719            got = wait_for_slot(sizing, machine, holder, more);
720        }
721        if let Some((stage, idx)) = &sink {
722            stage.queue(*idx, None);
723        }
724        let waited = started.elapsed();
725        CURRENT.with(|c| c.borrow_mut().queued += waited);
726        // Piped output never shows the region, and a heartbeat only comes
727        // after a minute: say once where the time went.
728        if got.is_ok() && waited >= Duration::from_secs(1) {
729            crate::hooks::common::say(&format!(
730                "  (waited {} for a host slot, {} {cap})",
731                crate::hooks::common::human_secs(waited.as_secs()),
732                crate::ui::highlight("greengate.hostSlots")
733            ));
734        }
735        // A wait that ended in line defers, whatever the policy: nothing
736        // runs outside the queue because a wait ended (ADR-0022).
737        let ended = got.as_ref().err().and_then(Reason::ended);
738        let defer = ended.is_some();
739        let end = ended.map(greenharness_slots::LineEnd::end);
740        let cause = ended.map_or(String::new(), |end| defer_cause(end, policy, slot_wait));
741        let by_slot_wait = matches!(
742            (policy, ended),
743            (
744                BusyPolicy::Defer { .. },
745                Some(greenharness_slots::LineEnd::Ceiling { .. })
746            )
747        );
748        let outcome = match (&got, defer) {
749            (Ok(_), _) => "admitted",
750            (Err(_), true) => "deferred",
751            (Err(_), false) => "unqueued",
752        };
753        record_acquisition(
754            &name,
755            Some(jobs),
756            Some((slot_cap, machine.cores)),
757            waited,
758            outcome,
759            end,
760        );
761        let held = match got {
762            Ok(lease) => Some(lease),
763            // The deferral line is the dispatcher's, not this note.
764            Err(Reason::Ended(_)) => None,
765            Err(reason) => {
766                note(&reason);
767                None
768            }
769        };
770        if defer {
771            BUSY_SEEN.store(true, Ordering::SeqCst);
772            if by_slot_wait {
773                DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
774            }
775        }
776        CURRENT.with(|c| {
777            let mut c = c.borrow_mut();
778            c.held = held;
779            c.settled = true;
780            c.jobs = Some(jobs);
781            c.sized = Some((slot_cap, machine.cores));
782            if defer {
783                c.deferred = Some(waited);
784                c.deferred_cause = cause;
785            }
786        });
787        if defer {
788            return Err(refusal());
789        }
790    }
791    // A light check run while a slot is parked between two heavy gates: its
792    // tools run under that slot (a child `amont slot run` must not queue for
793    // its parent's slot).
794    Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
795}
796
797/// The next heavy check takes the slot the previous one parked: renamed to
798/// itself, recorded as a wait of nothing, its width applied as a grant's is.
799fn take_handed(handed: Parked, name: &str) -> bool {
800    let Parked { lease, jobs, sized } = handed;
801    if let Err(error) = lease.rename(&holder_for(name)) {
802        crate::hooks::common::say(&format!(
803            "  host slot kept, but `{BIN} slots` may still name the previous check: {error}"
804        ));
805    }
806    record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
807    CURRENT.with(|current| {
808        let mut current = current.borrow_mut();
809        current.held = Some(lease);
810        current.settled = true;
811        current.jobs = jobs;
812        current.sized = sized;
813    });
814    true
815}
816
817/// One line of `waits.jsonl` for the check `name`, with where it ran.
818/// `sized` is the (cap, cores) the waiter was sized for, when known.
819fn record_acquisition(
820    name: &str,
821    jobs: Option<u32>,
822    sized: Option<(u32, u32)>,
823    waited: Duration,
824    outcome: &str,
825    end: Option<greenharness_slots::WaitEnd>,
826) {
827    let short = crate::short_name(name);
828    greenharness_slots::record_wait_named(
829        &greenharness_slots::dir(),
830        crate::names::SLOT_HOLDER,
831        greenharness_slots::WaitContext {
832            name: Some(short),
833            place: if crate::rehearsal::in_prestage() {
834                greenharness_slots::WaitPlace::Prestage
835            } else if crate::rehearsal::in_snapshot() {
836                greenharness_slots::WaitPlace::Rehearsal
837            } else {
838                greenharness_slots::WaitPlace::Push
839            },
840            cap: sized.map(|(cap, _)| cap),
841            cores: sized.map(|(_, cores)| cores),
842            end,
843        },
844        1,
845        jobs,
846        waited.as_millis(),
847        outcome,
848    );
849}
850
851/// Bound `cmd` to the width this thread's heavy check was given (see
852/// `Current::jobs`); a light check, or slots off, sets nothing. Called by
853/// every runner after [`before_spawn`].
854pub fn bound(cmd: &mut std::process::Command) {
855    let own = CURRENT.with(|c| c.borrow().jobs);
856    // A light check between two heavy gates runs under the parked slot.
857    if let Some(jobs) = own.or_else(|| {
858        parking()
859            .then(|| parked().as_ref().and_then(|p| p.jobs))
860            .flatten()
861    }) {
862        greenharness_slots::bound_width(cmd, jobs);
863    }
864}
865
866/// Wait in line for one slot within `bounds`, saying once whom the check
867/// waits behind (ADR-0022: the crate's [`greenharness_slots::wait_in_line`]).
868/// Failing to join the queue at all says the slots are unusable.
869fn wait_for_slot(
870    sizing: greenharness_slots::Sizing,
871    machine: greenharness_slots::Machine,
872    holder: greenharness_slots::Holder,
873    bounds: greenharness_slots::WaitBounds,
874) -> Result<greenharness_slots::Lease, Reason> {
875    let waiter = match greenharness_slots::Waiter::new_in_on(
876        &greenharness_slots::dir(),
877        sizing,
878        1,
879        holder,
880        machine,
881    ) {
882        Ok(w) => w,
883        Err(e) if e.kind() == std::io::ErrorKind::Other => {
884            return Err(Reason::DirUnsafe(e.to_string()))
885        }
886        Err(e) => return Err(Reason::Io(e.to_string())),
887    };
888    let mut said = false;
889    greenharness_slots::wait_in_line(waiter, bounds, |queue| {
890        if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
891            said = true;
892            crate::hooks::common::say(&format!("  {}", behind(queue)));
893            crate::hooks::common::say(&format!("  see: {BIN} slots"));
894        }
895    })
896    .map_err(Reason::Ended)
897}
898
899/// `queued behind relais: cargo test (greengate-wt-x, 4m) · 2 waiting`.
900pub fn behind(queue: &greenharness_slots::Queue) -> String {
901    let now = greenharness_slots::now_ms();
902    let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
903    if queue.unknown > 0 {
904        who.push(format!("{} unknown (old client)", queue.unknown));
905    }
906    let reason = queue
907        .reason
908        .map_or(String::new(), |r| format!(" ({})", r.describe()));
909    format!(
910        "queued behind {}{reason} · {} waiting",
911        who.join(", "),
912        queue.waiting.max(1)
913    )
914}
915
916/// One line for the reasons a person can act on; nothing for the normal
917/// case (the platform). A wait that ended in line defers, and the dispatcher
918/// says so; these are the slots being unusable.
919fn note(reason: &Reason) {
920    match reason {
921        Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
922            "host slots are off for this check: {why}. Remove it, or set {} to a directory \
923             only you own",
924            crate::ui::highlight(DIR_ENV)
925        )),
926        Reason::Io(why) => {
927            crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
928        }
929        Reason::Ended(_) | Reason::Unsupported => {}
930    }
931}
932
933#[cfg(all(test, unix))]
934mod tests {
935    use super::*;
936
937    fn settings_from(conf: &str) -> crate::config::Settings {
938        let lines = crate::manifest::parse_lines(conf);
939        let (policy, _) = crate::policy::Policy::from_lines(&lines);
940        crate::config::Settings::new(policy)
941    }
942
943    /// `GREENGATE_ON_BUSY`, then `amont.conf`, then `wait`; a bad environment
944    /// value is ignored for the file's.
945    #[test]
946    fn the_busy_policy_is_env_then_file_then_wait() {
947        let none = settings_from("");
948        let defer = settings_from("set onBusy defer\nset slotWait 5\n");
949        assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
950        assert_eq!(
951            resolve_busy(None, &defer),
952            BusyPolicy::Defer {
953                slot_wait: Duration::from_secs(5)
954            }
955        );
956        assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
957        assert_eq!(
958            resolve_busy(Some("DEFER"), &none),
959            BusyPolicy::Defer {
960                slot_wait: Duration::from_secs(60)
961            }
962        );
963        assert_eq!(
964            resolve_busy(Some("later"), &defer),
965            BusyPolicy::Defer {
966                slot_wait: Duration::from_secs(5)
967            }
968        );
969        assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
970        // ADR-0022: `now` skips the queue for one run, from the environment
971        // only; the file and git config keep `wait|defer`.
972        assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
973        let committed = settings_from("set onBusy now\n");
974        assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
975    }
976
977    /// ADR-0022, one row of the plan's table per assertion: skip the
978    /// queue, or wait in line within these bounds.
979    #[test]
980    fn each_caller_waits_by_its_row_of_the_table() {
981        use greenharness_slots::WaitBounds;
982        let s = |n| Duration::from_secs(n);
983        let (ceiling, warn) = (s(3600), s(600));
984        let defer = BusyPolicy::Defer { slot_wait: s(60) };
985        let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
986        let row =
987            |slot_wait, policy, ceiling, seen| wait_plan(slot_wait, policy, ceiling, warn, seen);
988        // `onBusy wait`, the default (rehearsal and pre-stage too): no stall
989        // window on the hook path, only the ceiling.
990        assert_eq!(
991            row(
992                SlotWait::Policy,
993                BusyPolicy::Wait,
994                ceiling,
995                HostSeen::NotYet
996            ),
997            queue(None, ceiling)
998        );
999        // A `warn` check of land's pre-stage: no stall window, under
1000        // warnSlotWait, which never outlasts the ceiling.
1001        assert_eq!(
1002            row(
1003                SlotWait::BoundedForWarn,
1004                BusyPolicy::Wait,
1005                ceiling,
1006                HostSeen::NotYet
1007            ),
1008            queue(None, warn)
1009        );
1010        assert_eq!(
1011            row(
1012                SlotWait::BoundedForWarn,
1013                BusyPolicy::Wait,
1014                s(100),
1015                HostSeen::NotYet
1016            ),
1017            queue(None, s(100))
1018        );
1019        // `onBusy defer`: slotWait stays hard, with no stall rule; none at
1020        // all once this run measured the host busy.
1021        assert_eq!(
1022            row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
1023            queue(None, s(60))
1024        );
1025        assert_eq!(
1026            row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
1027            queue(None, Duration::ZERO)
1028        );
1029        // A `warn` check outside a rehearsal never waits.
1030        assert_eq!(
1031            row(
1032                SlotWait::NeverWaits,
1033                BusyPolicy::Wait,
1034                ceiling,
1035                HostSeen::NotYet
1036            ),
1037            queue(None, Duration::ZERO)
1038        );
1039        // `GREENGATE_ON_BUSY=now`: no wait at all.
1040        assert_eq!(
1041            row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1042            WaitPlan::Now
1043        );
1044    }
1045
1046    /// The sibling-holder extension: with a sibling of this process holding
1047    /// a slot, the second wait goes on, with no stall window, to the rest of
1048    /// the ceiling; without one it is a single last poll.
1049    #[test]
1050    fn the_sibling_extension_waits_to_the_ceiling() {
1051        let s = |n| Duration::from_secs(n);
1052        let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60));
1053        assert_eq!(
1054            with_sibling.window, None,
1055            "no stall window on the hook path"
1056        );
1057        assert_eq!(with_sibling.ceiling, s(3540));
1058        let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60));
1059        assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1060        let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60));
1061        assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1062    }
1063
1064    /// The refused spawn names why: a stall names its own window (the
1065    /// sibling extension's too) and the place; `slotWait` keeps naming
1066    /// `onBusy defer`; a failed poll names the error.
1067    #[test]
1068    fn a_deferral_names_its_cause() {
1069        use greenharness_slots::LineEnd;
1070        let stalled = LineEnd::Stalled {
1071            window: Duration::from_secs(300),
1072            position: 1,
1073        };
1074        let cause = defer_cause(
1075            &stalled,
1076            BusyPolicy::Defer {
1077                slot_wait: Duration::from_secs(60),
1078            },
1079            SlotWait::Policy,
1080        );
1081        assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1082        assert!(cause.contains("(position 2)"), "{cause}");
1083        let slot_wait = defer_cause(
1084            &LineEnd::Ceiling {
1085                waited: Duration::from_secs(60),
1086            },
1087            BusyPolicy::Defer {
1088                slot_wait: Duration::from_secs(60),
1089            },
1090            SlotWait::Policy,
1091        );
1092        assert!(
1093            slot_wait.ends_with("(greengate.onBusy defer)"),
1094            "{slot_wait}"
1095        );
1096        let ceiling = defer_cause(
1097            &LineEnd::Ceiling {
1098                waited: Duration::from_secs(3600),
1099            },
1100            BusyPolicy::Wait,
1101            SlotWait::Policy,
1102        );
1103        assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1104        assert!(ceiling.ends_with("(greengate.timeout)"), "{ceiling}");
1105        let warn = defer_cause(
1106            &LineEnd::Ceiling {
1107                waited: Duration::from_secs(600),
1108            },
1109            BusyPolicy::Wait,
1110            SlotWait::BoundedForWarn,
1111        );
1112        assert!(warn.ends_with("(greengate.warnSlotWait)"), "{warn}");
1113        let failed = defer_cause(
1114            &LineEnd::PollFailed {
1115                error: std::io::Error::other("busy disk"),
1116            },
1117            BusyPolicy::Wait,
1118            SlotWait::Policy,
1119        );
1120        assert!(failed.contains("busy disk"), "{failed}");
1121    }
1122
1123    /// Every end of a wait in line defers; only failing to join the queue
1124    /// means the slots are unusable.
1125    #[test]
1126    fn every_end_of_a_wait_in_line_defers() {
1127        let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1128            waited: Duration::from_secs(1),
1129        });
1130        assert!(ended.ended().is_some());
1131        for reason in [
1132            Reason::Io("x".into()),
1133            Reason::DirUnsafe("x".into()),
1134            Reason::Unsupported,
1135        ] {
1136            assert!(reason.ended().is_none(), "{reason:?}");
1137        }
1138    }
1139
1140    #[test]
1141    fn heavy_is_the_list() {
1142        assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1143        assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1144    }
1145
1146    /// Every heavy name is a built-in: a renamed check must not silently
1147    /// stop queueing.
1148    #[test]
1149    fn every_heavy_name_is_a_builtin() {
1150        for name in HEAVY {
1151            assert!(
1152                crate::registry::CHECKS.iter().any(|c| c.name == *name),
1153                "{name} is not a built-in check"
1154            );
1155        }
1156    }
1157
1158    /// `.cargo/config.toml` reaches the test binaries: without it the
1159    /// integration fixtures would queue on the real host slots. Slots are
1160    /// off, not a bare held marker, which the reader refuses once the
1161    /// rollout ends (host-slot-admission t15); the marker is forced empty so
1162    /// a real holder's `held:<lease>` does not leak in.
1163    #[test]
1164    fn cargo_pins_the_host_knobs_for_tests() {
1165        assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok(""));
1166        assert_eq!(
1167            std::env::var(greenharness_slots::host::SLOTS_ENV).as_deref(),
1168            Ok("0")
1169        );
1170        assert_eq!(
1171            std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1172            Ok("1")
1173        );
1174    }
1175
1176    /// A light check never asks. A heavy one with slots off (the test
1177    /// process has `GREENGATE_HOST_SLOTS=0` from `.cargo/config.toml`)
1178    /// settles without a slot.
1179    #[test]
1180    fn a_light_check_never_takes_a_slot() {
1181        let settings = crate::config::Settings::default();
1182        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1183        assert!(!before_spawn(&settings).unwrap());
1184    }
1185
1186    #[test]
1187    fn a_heavy_check_with_slots_off_settles_without_a_slot() {
1188        let settings = crate::config::Settings::default();
1189        let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1190        assert_eq!(current_check().as_deref(), Some("clippy"));
1191        assert!(!before_spawn(&settings).unwrap());
1192        assert!(CURRENT.with(|c| c.borrow().settled));
1193        // No slot: no width is set here.
1194        let mut cmd = std::process::Command::new("true");
1195        bound(&mut cmd);
1196        assert_eq!(cmd.get_envs().count(), 0);
1197    }
1198
1199    /// A scope dropped on an early return releases the parked slot: nothing
1200    /// stays held, and no holder record stays on disk.
1201    #[test]
1202    fn a_park_scope_dropped_early_releases_the_parked_slot() {
1203        let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1204        let _ = std::fs::remove_dir_all(&dir); // best-effort: a fresh scratch dir
1205        let early = || {
1206            let _scope = ParkScope::begin();
1207            let mut waiter = greenharness_slots::Waiter::new_in(
1208                &dir,
1209                greenharness_slots::Sizing::Fixed(1),
1210                1,
1211                greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1212            )
1213            .unwrap();
1214            let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1215                panic!("the empty directory grants the slot");
1216            };
1217            assert!(dir.join("holders/slot-0.who").exists());
1218            park(lease, Some(2), Some((3, 6)));
1219            assert!(dir.join("holders/slot-0.who").exists());
1220        };
1221        early();
1222        assert!(!dir.join("holders/slot-0.who").exists());
1223        let _ = std::fs::remove_dir_all(&dir); // best-effort: scratch
1224    }
1225
1226    #[test]
1227    fn a_light_check_sets_no_width() {
1228        let settings = crate::config::Settings::default();
1229        let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1230        before_spawn(&settings).unwrap();
1231        let mut cmd = std::process::Command::new("true");
1232        bound(&mut cmd);
1233        assert_eq!(cmd.get_envs().count(), 0);
1234    }
1235}