1use 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
24pub 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#[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#[derive(Debug)]
53pub enum Reason {
54 DirUnsafe(String),
56 Unsupported,
58 Io(String),
62 Ended(greenharness_slots::LineEnd),
65}
66
67impl Reason {
68 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum DeferredBy {
83 SlotWait,
84 LineEnded,
85}
86
87static DEFERRED_BY_SLOT_WAIT: AtomicBool = AtomicBool::new(false);
89
90pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101enum HostSeen {
102 Busy,
103 NotYet,
104}
105
106static BUSY_SEEN: AtomicBool = AtomicBool::new(false);
110
111pub 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
133fn 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
149pub 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
167pub fn sizing(settings: &crate::config::Settings) -> Option<greenharness_slots::Sizing> {
170 sizing_and_machine(settings).0
171}
172
173pub const ON_BUSY_ENV: &str = "GREENGATE_ON_BUSY";
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum BusyPolicy {
181 Wait,
184 Defer { slot_wait: Duration },
186 Now,
190}
191
192pub fn busy_policy(settings: &crate::config::Settings) -> BusyPolicy {
196 resolve_busy(std::env::var(ON_BUSY_ENV).ok().as_deref(), settings)
197}
198
199fn resolve_busy(from_env: Option<&str>, settings: &crate::config::Settings) -> BusyPolicy {
202 let from_env = from_env.filter(|v| !v.is_empty());
203 let mode = match from_env.map(str::to_ascii_lowercase).as_deref() {
204 Some("wait") => "wait",
205 Some("defer") => "defer",
206 Some("now") => return BusyPolicy::Now,
207 Some(other) => {
208 crate::config::complain(
209 ON_BUSY_ENV,
210 &format!("{other:?} is not one of wait, defer, now"),
211 "greengate.onBusy",
212 );
213 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
214 }
215 None => {
216 crate::config::enumerated_or(settings, "greengate.onBusy", &["wait", "defer"], "wait")
217 }
218 };
219 if mode == "defer" {
220 let secs = crate::config::integer_or(settings, "greengate.slotWait", 60, 1..=3600) as u64;
221 BusyPolicy::Defer {
222 slot_wait: Duration::from_secs(secs),
223 }
224 } else {
225 BusyPolicy::Wait
226 }
227}
228
229#[derive(Default)]
231struct Current {
232 name: String,
234 heavy: bool,
235 settled: bool,
238 held: Option<greenharness_slots::Lease>,
239 queued: Duration,
240 deferred: Option<Duration>,
246 deferred_cause: String,
248 jobs: Option<u32>,
252 sized: Option<(u32, u32)>,
255 slot_wait: SlotWait,
257}
258
259#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
261enum SlotWait {
262 #[default]
264 Policy,
265 NeverWaits,
271 BoundedForWarn,
275}
276
277struct Parked {
280 lease: greenharness_slots::Lease,
281 jobs: Option<u32>,
282 sized: Option<(u32, u32)>,
283}
284
285static PARKED: Mutex<Option<Parked>> = Mutex::new(None);
289
290static PARK_SCOPE_DEPTH: AtomicUsize = AtomicUsize::new(0);
293
294fn parked() -> std::sync::MutexGuard<'static, Option<Parked>> {
295 PARKED
296 .lock()
297 .unwrap_or_else(|poisoned| poisoned.into_inner())
298}
299
300fn parking() -> bool {
304 PARK_SCOPE_DEPTH.load(Ordering::SeqCst) > 0 && crate::rehearsal::in_snapshot()
305}
306
307#[must_use = "the scope releases the parked slot when dropped"]
311pub struct ParkScope {
312 _private: (),
313}
314
315impl ParkScope {
316 #[must_use = "the scope releases the parked slot when dropped"]
317 pub fn begin() -> ParkScope {
318 PARK_SCOPE_DEPTH.fetch_add(1, Ordering::SeqCst);
319 ParkScope { _private: () }
320 }
321}
322
323impl Drop for ParkScope {
324 fn drop(&mut self) {
325 if PARK_SCOPE_DEPTH.fetch_sub(1, Ordering::SeqCst) == 1 {
326 release_parked();
327 }
328 }
329}
330
331pub fn release_parked() {
336 let leftover = parked().take();
337 drop(leftover);
338}
339
340fn between_gates() -> greenharness_slots::Holder {
342 holder_for("pre-push, between checks")
343}
344
345fn holder_for(command: &str) -> greenharness_slots::Holder {
350 let mut holder = greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, command);
351 if let Some(src) = crate::rehearsal::source_worktree() {
352 holder.repo = src.display().to_string();
353 }
354 holder
355}
356
357thread_local! {
358 static CURRENT: RefCell<Current> = RefCell::new(Current::default());
359}
360
361pub struct CheckGuard;
364
365impl CheckGuard {
366 pub fn queued(&self) -> Duration {
368 CURRENT.with(|c| c.borrow().queued)
369 }
370
371 pub fn deferred(&self) -> Option<Duration> {
374 CURRENT.with(|c| c.borrow().deferred)
375 }
376}
377
378pub fn deferred_here() -> bool {
381 CURRENT.with(|c| c.borrow().deferred.is_some())
382}
383
384fn refusal() -> std::io::Error {
388 let cause = CURRENT.with(|c| c.borrow().deferred_cause.clone());
389 std::io::Error::other(if cause.is_empty() {
390 "deferred to CI: the host is busy".to_string()
391 } else {
392 cause
393 })
394}
395
396fn defer_cause(
398 end: &greenharness_slots::LineEnd,
399 policy: BusyPolicy,
400 slot_wait: SlotWait,
401) -> String {
402 use greenharness_slots::LineEnd;
403 let human = |d: Duration| crate::hooks::common::human_secs(d.as_secs());
404 match end {
405 LineEnd::Stalled { window, position } => format!(
408 "deferred to CI: the host slot line made no progress for {} (position {})",
409 human(*window),
410 position + 1
411 ),
412 LineEnd::PollFailed { error } => {
413 format!("deferred to CI: the host slot files failed: {error}")
414 }
415 LineEnd::Ceiling { waited } => match policy {
416 BusyPolicy::Defer { .. } => format!(
417 "deferred to CI: no host slot freed in {} (greengate.onBusy defer)",
418 human(*waited)
419 ),
420 BusyPolicy::Wait | BusyPolicy::Now => {
421 let setting = match slot_wait {
424 SlotWait::BoundedForWarn => "greengate.warnSlotWait",
425 SlotWait::Policy | SlotWait::NeverWaits => "greengate.timeout",
426 };
427 format!(
428 "deferred to CI: no host slot within {} ({setting})",
429 human(*waited)
430 )
431 }
432 },
433 }
434}
435
436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439enum WaitPlan {
440 Now,
441 Queue(greenharness_slots::WaitBounds),
442}
443
444fn wait_plan(
451 slot_wait: SlotWait,
452 policy: BusyPolicy,
453 ceiling: Duration,
454 warn_wait: Duration,
455 seen: HostSeen,
456) -> WaitPlan {
457 let queue =
458 |window, ceiling| WaitPlan::Queue(greenharness_slots::WaitBounds { window, ceiling });
459 match (slot_wait, policy) {
460 (_, BusyPolicy::Now) => WaitPlan::Now,
461 (SlotWait::NeverWaits, _) => queue(None, Duration::ZERO),
462 (SlotWait::BoundedForWarn, _) => queue(None, warn_wait.min(ceiling)),
463 (SlotWait::Policy, BusyPolicy::Wait) => queue(None, ceiling),
464 (SlotWait::Policy, BusyPolicy::Defer { slot_wait }) => match seen {
465 HostSeen::Busy => queue(None, Duration::ZERO),
467 HostSeen::NotYet => queue(None, slot_wait),
468 },
469 }
470}
471
472fn sibling_bounds(
479 slot_wait: SlotWait,
480 held_in_process: usize,
481 ceiling: Duration,
482 elapsed: Duration,
483) -> greenharness_slots::WaitBounds {
484 let waits_on_sibling = held_in_process > 0 && !matches!(slot_wait, SlotWait::NeverWaits);
485 if waits_on_sibling {
486 greenharness_slots::WaitBounds {
487 window: None,
488 ceiling: ceiling.saturating_sub(elapsed),
489 }
490 } else {
491 greenharness_slots::WaitBounds {
492 window: None,
493 ceiling: Duration::ZERO,
494 }
495 }
496}
497
498impl Drop for CheckGuard {
499 fn drop(&mut self) {
500 let finished = CURRENT.with(RefCell::take);
501 if let Some(lease) = finished.held {
502 if parking() {
503 park(lease, finished.jobs, finished.sized);
504 }
505 }
506 }
507}
508
509fn park(lease: greenharness_slots::Lease, jobs: Option<u32>, sized: Option<(u32, u32)>) {
512 if let Err(error) = lease.rename(&between_gates()) {
513 crate::hooks::common::say(&format!(
514 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
515 ));
516 }
517 let earlier = parked().replace(Parked { lease, jobs, sized });
518 drop(earlier);
519}
520
521pub fn enter_check(name: &str, weight: Weight) -> CheckGuard {
525 CURRENT.with(|c| {
526 *c.borrow_mut() = Current {
527 name: name.to_string(),
528 heavy: weight == Weight::Heavy,
529 ..Current::default()
530 }
531 });
532 CheckGuard
533}
534
535pub fn never_waits() {
543 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::NeverWaits);
544}
545
546pub fn wait_bounded_for_warn() {
551 CURRENT.with(|current| current.borrow_mut().slot_wait = SlotWait::BoundedForWarn);
552}
553
554fn warn_slot_wait(settings: &crate::config::Settings) -> Duration {
557 Duration::from_secs(
558 crate::config::integer_or(settings, "greengate.warnSlotWait", 600, 1..=3600) as u64,
559 )
560}
561
562pub fn current_check() -> Option<String> {
565 CURRENT.with(|c| {
566 let c = c.borrow();
567 (!c.name.is_empty()).then(|| crate::short_name(&c.name).to_string())
568 })
569}
570
571fn nested() -> bool {
573 std::env::var_os(HELD_ENV).is_some_and(|v| !v.is_empty())
574}
575
576pub fn before_spawn(settings: &crate::config::Settings) -> std::io::Result<bool> {
581 let (pending, deferred, name, slot_wait) = CURRENT.with(|current| {
582 let current = current.borrow();
583 (
584 current.heavy && !current.settled,
585 current.deferred.is_some(),
586 current.name.clone(),
587 current.slot_wait,
588 )
589 });
590 if deferred {
593 return Err(refusal());
594 }
595 if pending {
596 if let Some(handed) = parking().then(|| parked().take()).flatten() {
597 return Ok(take_handed(handed, &name));
598 }
599 let (sizing, machine) = if nested() {
603 (None, greenharness_slots::Machine::detect())
604 } else {
605 sizing_and_machine(settings)
606 };
607 let Some(sizing) = sizing else {
608 CURRENT.with(|c| c.borrow_mut().settled = true);
609 return Ok(false);
610 };
611 if !greenharness_slots::SUPPORTED {
612 CURRENT.with(|c| c.borrow_mut().settled = true);
613 return Ok(false);
614 }
615 let policy = match slot_wait {
616 SlotWait::NeverWaits => BusyPolicy::Defer {
617 slot_wait: Duration::ZERO,
618 },
619 SlotWait::BoundedForWarn => BusyPolicy::Wait,
620 SlotWait::Policy => busy_policy(settings),
621 };
622 let ceiling = Duration::from_secs(match crate::hooks::common::check_timeout(settings) {
623 0 => 3600,
624 s => s,
625 });
626 let seen = if BUSY_SEEN.load(Ordering::SeqCst) {
627 HostSeen::Busy
628 } else {
629 HostSeen::NotYet
630 };
631 let plan = wait_plan(slot_wait, policy, ceiling, warn_slot_wait(settings), seen);
632 let slot_cap = sizing.cap_for(machine.cores);
633 let cap = u64::from(slot_cap);
634 let jobs = greenharness_slots::parallelism(1, machine.cores, slot_cap);
637 let bounds = match plan {
638 WaitPlan::Queue(bounds) => bounds,
639 WaitPlan::Now => {
640 crate::hooks::common::say(&format!(
643 " running unqueued: {}=now skips the host slot queue",
644 crate::ui::highlight(ON_BUSY_ENV)
645 ));
646 record_acquisition(
647 &name,
648 Some(jobs),
649 Some((slot_cap, machine.cores)),
650 Duration::ZERO,
651 "now",
652 None,
653 );
654 CURRENT.with(|c| {
655 let mut c = c.borrow_mut();
656 c.settled = true;
657 c.jobs = Some(jobs);
658 c.sized = Some((slot_cap, machine.cores));
659 });
660 return Ok(false);
661 }
662 };
663 let sink = crate::live::current_sink();
664 if let Some((stage, idx)) = &sink {
665 stage.queue(*idx, Some((Instant::now(), cap)));
666 }
667 let started = Instant::now();
668 let holder = holder_for(&name);
669 let mut got = wait_for_slot(sizing, machine, holder.clone(), bounds);
670 if let (
671 BusyPolicy::Defer { .. },
672 Err(Reason::Ended(greenharness_slots::LineEnd::Ceiling { .. })),
673 ) = (policy, &got)
674 {
675 let more = sibling_bounds(
676 slot_wait,
677 greenharness_slots::held_in_process(),
678 ceiling,
679 started.elapsed(),
680 );
681 got = wait_for_slot(sizing, machine, holder, more);
682 }
683 if let Some((stage, idx)) = &sink {
684 stage.queue(*idx, None);
685 }
686 let waited = started.elapsed();
687 CURRENT.with(|c| c.borrow_mut().queued += waited);
688 if got.is_ok() && waited >= Duration::from_secs(1) {
691 crate::hooks::common::say(&format!(
692 " (waited {} for a host slot, {} {cap})",
693 crate::hooks::common::human_secs(waited.as_secs()),
694 crate::ui::highlight("greengate.hostSlots")
695 ));
696 }
697 let ended = got.as_ref().err().and_then(Reason::ended);
700 let defer = ended.is_some();
701 let end = ended.map(greenharness_slots::LineEnd::end);
702 let cause = ended.map_or(String::new(), |end| defer_cause(end, policy, slot_wait));
703 let by_slot_wait = matches!(
704 (policy, ended),
705 (
706 BusyPolicy::Defer { .. },
707 Some(greenharness_slots::LineEnd::Ceiling { .. })
708 )
709 );
710 let outcome = match (&got, defer) {
711 (Ok(_), _) => "admitted",
712 (Err(_), true) => "deferred",
713 (Err(_), false) => "unqueued",
714 };
715 record_acquisition(
716 &name,
717 Some(jobs),
718 Some((slot_cap, machine.cores)),
719 waited,
720 outcome,
721 end,
722 );
723 let held = match got {
724 Ok(lease) => Some(lease),
725 Err(Reason::Ended(_)) => None,
727 Err(reason) => {
728 note(&reason);
729 None
730 }
731 };
732 if defer {
733 BUSY_SEEN.store(true, Ordering::SeqCst);
734 if by_slot_wait {
735 DEFERRED_BY_SLOT_WAIT.store(true, Ordering::SeqCst);
736 }
737 }
738 CURRENT.with(|c| {
739 let mut c = c.borrow_mut();
740 c.held = held;
741 c.settled = true;
742 c.jobs = Some(jobs);
743 c.sized = Some((slot_cap, machine.cores));
744 if defer {
745 c.deferred = Some(waited);
746 c.deferred_cause = cause;
747 }
748 });
749 if defer {
750 return Err(refusal());
751 }
752 }
753 Ok(CURRENT.with(|c| c.borrow().held.is_some()) || (parking() && parked().is_some()))
757}
758
759fn take_handed(handed: Parked, name: &str) -> bool {
762 let Parked { lease, jobs, sized } = handed;
763 if let Err(error) = lease.rename(&holder_for(name)) {
764 crate::hooks::common::say(&format!(
765 " host slot kept, but `{BIN} slots` may still name the previous check: {error}"
766 ));
767 }
768 record_acquisition(name, jobs, sized, Duration::ZERO, "handed", None);
769 CURRENT.with(|current| {
770 let mut current = current.borrow_mut();
771 current.held = Some(lease);
772 current.settled = true;
773 current.jobs = jobs;
774 current.sized = sized;
775 });
776 true
777}
778
779fn record_acquisition(
782 name: &str,
783 jobs: Option<u32>,
784 sized: Option<(u32, u32)>,
785 waited: Duration,
786 outcome: &str,
787 end: Option<greenharness_slots::WaitEnd>,
788) {
789 let short = crate::short_name(name);
790 greenharness_slots::record_wait_named(
791 &greenharness_slots::dir(),
792 crate::names::SLOT_HOLDER,
793 greenharness_slots::WaitContext {
794 name: Some(short),
795 place: if crate::rehearsal::in_prestage() {
796 greenharness_slots::WaitPlace::Prestage
797 } else if crate::rehearsal::in_snapshot() {
798 greenharness_slots::WaitPlace::Rehearsal
799 } else {
800 greenharness_slots::WaitPlace::Push
801 },
802 cap: sized.map(|(cap, _)| cap),
803 cores: sized.map(|(_, cores)| cores),
804 end,
805 },
806 1,
807 jobs,
808 waited.as_millis(),
809 outcome,
810 );
811}
812
813pub fn bound(cmd: &mut std::process::Command) {
817 let own = CURRENT.with(|c| c.borrow().jobs);
818 if let Some(jobs) = own.or_else(|| {
820 parking()
821 .then(|| parked().as_ref().and_then(|p| p.jobs))
822 .flatten()
823 }) {
824 greenharness_slots::bound_width(cmd, jobs);
825 }
826}
827
828fn wait_for_slot(
832 sizing: greenharness_slots::Sizing,
833 machine: greenharness_slots::Machine,
834 holder: greenharness_slots::Holder,
835 bounds: greenharness_slots::WaitBounds,
836) -> Result<greenharness_slots::Lease, Reason> {
837 let waiter = match greenharness_slots::Waiter::new_in_on(
838 &greenharness_slots::dir(),
839 sizing,
840 1,
841 holder,
842 machine,
843 ) {
844 Ok(w) => w,
845 Err(e) if e.kind() == std::io::ErrorKind::Other => {
846 return Err(Reason::DirUnsafe(e.to_string()))
847 }
848 Err(e) => return Err(Reason::Io(e.to_string())),
849 };
850 let mut said = false;
851 greenharness_slots::wait_in_line(waiter, bounds, |queue| {
852 if !said && (!queue.holders.is_empty() || queue.unknown > 0) {
853 said = true;
854 crate::hooks::common::say(&format!(" {}", behind(queue)));
855 crate::hooks::common::say(&format!(" see: {BIN} slots"));
856 }
857 })
858 .map_err(Reason::Ended)
859}
860
861pub fn behind(queue: &greenharness_slots::Queue) -> String {
863 let now = greenharness_slots::now_ms();
864 let mut who: Vec<String> = queue.holders.iter().map(|h| h.describe(now)).collect();
865 if queue.unknown > 0 {
866 who.push(format!("{} unknown (old client)", queue.unknown));
867 }
868 let reason = queue
869 .reason
870 .map_or(String::new(), |r| format!(" ({})", r.describe()));
871 format!(
872 "queued behind {}{reason} · {} waiting",
873 who.join(", "),
874 queue.waiting.max(1)
875 )
876}
877
878fn note(reason: &Reason) {
882 match reason {
883 Reason::DirUnsafe(why) => crate::hooks::common::warn(&format!(
884 "host slots are off for this check: {why}. Remove it, or set {} to a directory \
885 only you own",
886 crate::ui::highlight(DIR_ENV)
887 )),
888 Reason::Io(why) => {
889 crate::hooks::common::warn(&format!("host slots are off for this check: {why}"))
890 }
891 Reason::Ended(_) | Reason::Unsupported => {}
892 }
893}
894
895#[cfg(all(test, unix))]
896mod tests {
897 use super::*;
898
899 fn settings_from(conf: &str) -> crate::config::Settings {
900 let lines = crate::manifest::parse_lines(conf);
901 let (policy, _) = crate::policy::Policy::from_lines(&lines);
902 crate::config::Settings::new(policy)
903 }
904
905 #[test]
908 fn the_busy_policy_is_env_then_file_then_wait() {
909 let none = settings_from("");
910 let defer = settings_from("set onBusy defer\nset slotWait 5\n");
911 assert_eq!(resolve_busy(None, &none), BusyPolicy::Wait);
912 assert_eq!(
913 resolve_busy(None, &defer),
914 BusyPolicy::Defer {
915 slot_wait: Duration::from_secs(5)
916 }
917 );
918 assert_eq!(resolve_busy(Some("wait"), &defer), BusyPolicy::Wait);
919 assert_eq!(
920 resolve_busy(Some("DEFER"), &none),
921 BusyPolicy::Defer {
922 slot_wait: Duration::from_secs(60)
923 }
924 );
925 assert_eq!(
926 resolve_busy(Some("later"), &defer),
927 BusyPolicy::Defer {
928 slot_wait: Duration::from_secs(5)
929 }
930 );
931 assert_eq!(resolve_busy(Some(""), &none), BusyPolicy::Wait);
932 assert_eq!(resolve_busy(Some("now"), &defer), BusyPolicy::Now);
935 let committed = settings_from("set onBusy now\n");
936 assert_eq!(resolve_busy(None, &committed), BusyPolicy::Wait);
937 }
938
939 #[test]
942 fn each_caller_waits_by_its_row_of_the_table() {
943 use greenharness_slots::WaitBounds;
944 let s = |n| Duration::from_secs(n);
945 let (ceiling, warn) = (s(3600), s(600));
946 let defer = BusyPolicy::Defer { slot_wait: s(60) };
947 let queue = |window, ceiling| WaitPlan::Queue(WaitBounds { window, ceiling });
948 let row =
949 |slot_wait, policy, ceiling, seen| wait_plan(slot_wait, policy, ceiling, warn, seen);
950 assert_eq!(
953 row(
954 SlotWait::Policy,
955 BusyPolicy::Wait,
956 ceiling,
957 HostSeen::NotYet
958 ),
959 queue(None, ceiling)
960 );
961 assert_eq!(
964 row(
965 SlotWait::BoundedForWarn,
966 BusyPolicy::Wait,
967 ceiling,
968 HostSeen::NotYet
969 ),
970 queue(None, warn)
971 );
972 assert_eq!(
973 row(
974 SlotWait::BoundedForWarn,
975 BusyPolicy::Wait,
976 s(100),
977 HostSeen::NotYet
978 ),
979 queue(None, s(100))
980 );
981 assert_eq!(
984 row(SlotWait::Policy, defer, ceiling, HostSeen::NotYet),
985 queue(None, s(60))
986 );
987 assert_eq!(
988 row(SlotWait::Policy, defer, ceiling, HostSeen::Busy),
989 queue(None, Duration::ZERO)
990 );
991 assert_eq!(
993 row(
994 SlotWait::NeverWaits,
995 BusyPolicy::Wait,
996 ceiling,
997 HostSeen::NotYet
998 ),
999 queue(None, Duration::ZERO)
1000 );
1001 assert_eq!(
1003 row(SlotWait::Policy, BusyPolicy::Now, ceiling, HostSeen::NotYet),
1004 WaitPlan::Now
1005 );
1006 }
1007
1008 #[test]
1012 fn the_sibling_extension_waits_to_the_ceiling() {
1013 let s = |n| Duration::from_secs(n);
1014 let with_sibling = sibling_bounds(SlotWait::Policy, 1, s(3600), s(60));
1015 assert_eq!(
1016 with_sibling.window, None,
1017 "no stall window on the hook path"
1018 );
1019 assert_eq!(with_sibling.ceiling, s(3540));
1020 let alone = sibling_bounds(SlotWait::Policy, 0, s(3600), s(60));
1021 assert_eq!((alone.window, alone.ceiling), (None, Duration::ZERO));
1022 let never = sibling_bounds(SlotWait::NeverWaits, 1, s(3600), s(60));
1023 assert_eq!((never.window, never.ceiling), (None, Duration::ZERO));
1024 }
1025
1026 #[test]
1030 fn a_deferral_names_its_cause() {
1031 use greenharness_slots::LineEnd;
1032 let stalled = LineEnd::Stalled {
1033 window: Duration::from_secs(300),
1034 position: 1,
1035 };
1036 let cause = defer_cause(
1037 &stalled,
1038 BusyPolicy::Defer {
1039 slot_wait: Duration::from_secs(60),
1040 },
1041 SlotWait::Policy,
1042 );
1043 assert!(cause.contains("made no progress for 5m00s"), "{cause}");
1044 assert!(cause.contains("(position 2)"), "{cause}");
1045 let slot_wait = defer_cause(
1046 &LineEnd::Ceiling {
1047 waited: Duration::from_secs(60),
1048 },
1049 BusyPolicy::Defer {
1050 slot_wait: Duration::from_secs(60),
1051 },
1052 SlotWait::Policy,
1053 );
1054 assert!(
1055 slot_wait.ends_with("(greengate.onBusy defer)"),
1056 "{slot_wait}"
1057 );
1058 let ceiling = defer_cause(
1059 &LineEnd::Ceiling {
1060 waited: Duration::from_secs(3600),
1061 },
1062 BusyPolicy::Wait,
1063 SlotWait::Policy,
1064 );
1065 assert!(ceiling.contains("no host slot within 1h00m"), "{ceiling}");
1066 assert!(ceiling.ends_with("(greengate.timeout)"), "{ceiling}");
1067 let warn = defer_cause(
1068 &LineEnd::Ceiling {
1069 waited: Duration::from_secs(600),
1070 },
1071 BusyPolicy::Wait,
1072 SlotWait::BoundedForWarn,
1073 );
1074 assert!(warn.ends_with("(greengate.warnSlotWait)"), "{warn}");
1075 let failed = defer_cause(
1076 &LineEnd::PollFailed {
1077 error: std::io::Error::other("busy disk"),
1078 },
1079 BusyPolicy::Wait,
1080 SlotWait::Policy,
1081 );
1082 assert!(failed.contains("busy disk"), "{failed}");
1083 }
1084
1085 #[test]
1088 fn every_end_of_a_wait_in_line_defers() {
1089 let ended = Reason::Ended(greenharness_slots::LineEnd::Ceiling {
1090 waited: Duration::from_secs(1),
1091 });
1092 assert!(ended.ended().is_some());
1093 for reason in [
1094 Reason::Io("x".into()),
1095 Reason::DirUnsafe("x".into()),
1096 Reason::Unsupported,
1097 ] {
1098 assert!(reason.ended().is_none(), "{reason:?}");
1099 }
1100 }
1101
1102 #[test]
1103 fn heavy_is_the_list() {
1104 assert_eq!(weight_of("pre-commit-clippy"), Weight::Heavy);
1105 assert_eq!(weight_of("pre-commit-cargo-fmt"), Weight::Light);
1106 }
1107
1108 #[test]
1111 fn every_heavy_name_is_a_builtin() {
1112 for name in HEAVY {
1113 assert!(
1114 crate::registry::CHECKS.iter().any(|c| c.name == *name),
1115 "{name} is not a built-in check"
1116 );
1117 }
1118 }
1119
1120 #[test]
1123 fn cargo_pins_the_host_knobs_for_tests() {
1124 assert_eq!(std::env::var(HELD_ENV).as_deref(), Ok("held"));
1125 assert_eq!(
1126 std::env::var("GREENGATE_IDLE_LOAD_SCALE").as_deref(),
1127 Ok("1")
1128 );
1129 }
1130
1131 #[test]
1135 fn a_light_check_never_takes_a_slot() {
1136 let settings = crate::config::Settings::default();
1137 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1138 assert!(!before_spawn(&settings).unwrap());
1139 }
1140
1141 #[test]
1142 fn a_nested_heavy_check_settles_without_a_slot() {
1143 let settings = crate::config::Settings::default();
1144 let _g = enter_check("pre-commit-clippy", weight_of("pre-commit-clippy"));
1145 assert_eq!(current_check().as_deref(), Some("clippy"));
1146 assert!(!before_spawn(&settings).unwrap());
1147 assert!(CURRENT.with(|c| c.borrow().settled));
1148 let mut cmd = std::process::Command::new("true");
1150 bound(&mut cmd);
1151 assert_eq!(cmd.get_envs().count(), 0);
1152 }
1153
1154 #[test]
1157 fn a_park_scope_dropped_early_releases_the_parked_slot() {
1158 let dir = std::env::temp_dir().join(format!("greengate-park-{}", std::process::id()));
1159 let _ = std::fs::remove_dir_all(&dir); let early = || {
1161 let _scope = ParkScope::begin();
1162 let mut waiter = greenharness_slots::Waiter::new_in(
1163 &dir,
1164 greenharness_slots::Sizing::Fixed(1),
1165 1,
1166 greenharness_slots::Holder::here(crate::names::SLOT_HOLDER, "gate"),
1167 )
1168 .unwrap();
1169 let greenharness_slots::Poll::Granted(lease) = waiter.poll().unwrap() else {
1170 panic!("the empty directory grants the slot");
1171 };
1172 assert!(dir.join("holders/slot-0.who").exists());
1173 park(lease, Some(2), Some((3, 6)));
1174 assert!(dir.join("holders/slot-0.who").exists());
1175 };
1176 early();
1177 assert!(!dir.join("holders/slot-0.who").exists());
1178 let _ = std::fs::remove_dir_all(&dir); }
1180
1181 #[test]
1182 fn a_light_check_sets_no_width() {
1183 let settings = crate::config::Settings::default();
1184 let _g = enter_check("pre-commit-cargo-fmt", weight_of("pre-commit-cargo-fmt"));
1185 before_spawn(&settings).unwrap();
1186 let mut cmd = std::process::Command::new("true");
1187 bound(&mut cmd);
1188 assert_eq!(cmd.get_envs().count(), 0);
1189 }
1190}