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