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