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