返回 CodeWhale
resource_admission.rs
根目录 / crates / engine / src / tools / resource_admission.rs
1 //! Cross-process admission for expensive local commands.
2 //!
3 //! Fleet and Workflow workers execute in separate Codewhale processes, so an
4 //! in-process semaphore cannot protect the host. Heavy shell commands instead
5 //! take one of a small number of filesystem-backed permits under
6 //! `CODEWHALE_HOME`. The default of two permits is deliberately conservative
7 //! for the 36 GiB laptop class from #4864.
8
9 use std::fs::{File, OpenOptions};
10 use std::io;
11 use std::path::{Path, PathBuf};
12 use std::time::{Duration, Instant};
13
14 use anyhow::{Context, Result, anyhow};
15 use fd_lock::{RwLock, RwLockWriteGuard};
16 use tokio_util::sync::CancellationToken;
17
18 pub const DEFAULT_HEAVY_COMMAND_LIMIT: usize = 2;
19 const MAX_HEAVY_COMMAND_LIMIT: usize = 16;
20 const ADMISSION_POLL_INTERVAL: Duration = Duration::from_millis(50);
21
22 const ADMISSION_MAX_WAIT: Duration = Duration::from_secs(30);
23
24 /// When the host free-RAM fraction drops to/below these thresholds the
25 /// effective heavy-command admission limit tightens so a saturated host stops
26 /// admitting new link graphs (#4864 req 7). Values are deliberately generous
27 /// because the measurement is advisory, not authoritative.
28 const CONSTRAINED_FREE_FRACTION: f64 = 0.30;
29 const CRITICAL_FREE_FRACTION: f64 = 0.15;
30
31 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
32 pub enum CommandExpense {
33 Normal,
34 Heavy,
35 }
36
37 /// Measured host memory pressure used to tighten heavy-command admission.
38 ///
39 /// `Unknown` means "could not be measured"; admission then fails open (uses the
40 /// configured limit) rather than risk blocking on an unmeasurable host. This
41 /// keeps the gate safe on any CI runner where the probe is unavailable.
42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
43 pub enum MemoryPressure {
44 Unknown,
45 Nominal,
46 Constrained,
47 Critical,
48 }
49
50 /// Pluggable memory probe so the admission policy is unit-testable without
51 /// having to drive the host into real memory pressure.
52 pub trait MemoryProbe: Send + Sync {
53 /// Free-RAM fraction in `0.0..=1.0`, or `None` when it cannot be measured.
54 fn free_fraction(&self) -> Option<f64>;
55 }
56
57 struct HostMemoryProbe;
58
59 impl MemoryProbe for HostMemoryProbe {
60 fn free_fraction(&self) -> Option<f64> {
61 host_memory_free_fraction()
62 }
63 }
64
65 fn classify_memory_pressure(free_fraction: Option<f64>) -> MemoryPressure {
66 match free_fraction {
67 None => MemoryPressure::Unknown,
68 Some(fraction) if fraction <= CRITICAL_FREE_FRACTION => MemoryPressure::Critical,
69 Some(fraction) if fraction <= CONSTRAINED_FREE_FRACTION => MemoryPressure::Constrained,
70 Some(_) => MemoryPressure::Nominal,
71 }
72 }
73
74 /// Effective admission limit after applying host memory pressure. `Critical`
75 /// yields zero so queued heavy commands wait for the host to recover instead of
76 /// snowballing; `Constrained` halves the budget (never below one).
77 fn effective_admission_limit(configured: usize, pressure: MemoryPressure) -> usize {
78 match pressure {
79 MemoryPressure::Critical => 0,
80 MemoryPressure::Constrained => configured.div_ceil(2).max(1),
81 MemoryPressure::Nominal | MemoryPressure::Unknown => configured,
82 }
83 }
84
85 #[derive(Debug)]
86 struct HeavyPermitSlot {
87 _guard: RwLockWriteGuard<'static, File>,
88 // The guard borrows the lock. Keeping the boxed lock here makes that
89 // allocation outlive the guard; field drop order is guard, then lock.
90 _lock: Box<RwLock<File>>,
91 }
92
93 /// A held cross-process heavy-command permit.
94 #[derive(Debug)]
95 pub struct HeavyCommandPermit {
96 _slot: Option<HeavyPermitSlot>,
97 queued_for: Duration,
98 limit: usize,
99 memory_pressure: MemoryPressure,
100 }
101
102 impl HeavyCommandPermit {
103 pub fn queued_for(&self) -> Duration {
104 self.queued_for
105 }
106
107 pub fn limit(&self) -> usize {
108 self.limit
109 }
110
111 pub fn memory_pressure(&self) -> MemoryPressure {
112 self.memory_pressure
113 }
114 }
115
116 pub fn infer_command_expense(command: &str) -> CommandExpense {
117 let heavy = command
118 .split(['\n', '\r', ';', '|', '&'])
119 .any(segment_is_heavy);
120
121 if heavy {
122 CommandExpense::Heavy
123 } else {
124 CommandExpense::Normal
125 }
126 }
127
128 /// Commands that run another command from their arguments. The classifier
129 /// looks through them (#6560 D01-11): `sudo cargo build`, `timeout 600
130 /// cargo test`, `xargs cargo check` and `bash -c "cargo build"` compile
131 /// exactly like the bare command and need the same permit. This is resource
132 /// admission, not a security boundary: shell policy still judges the whole
133 /// command.
134 const COMMAND_WRAPPERS: &[&str] = &[
135 "sudo",
136 "doas",
137 "env",
138 "nice",
139 "nohup",
140 "time",
141 "timeout",
142 "gtimeout",
143 "xargs",
144 "command",
145 "exec",
146 "stdbuf",
147 "ionice",
148 "caffeinate",
149 "watch",
150 "eval",
151 "bash",
152 "sh",
153 "zsh",
154 "dash",
155 ];
156
157 fn segment_is_heavy(segment: &str) -> bool {
158 let tokens: Vec<String> = segment
159 .split_whitespace()
160 .map(|token| {
161 token
162 .trim_matches(['"', '\'', '(', ')', '{', '}', '`', '$'])
163 .to_string()
164 })
165 .collect();
166 let stem = |token: &str| {
167 Path::new(token)
168 .file_stem()
169 .and_then(|name| name.to_str())
170 .unwrap_or_default()
171 .to_ascii_lowercase()
172 };
173 let Some(mut index) = tokens
174 .iter()
175 .position(|token| !token.is_empty() && !token.contains('=') && token != "env")
176 else {
177 return false;
178 };
179 if COMMAND_WRAPPERS.contains(&stem(&tokens[index]).as_str()) {
180 // Wrapper options and their values (`-u user`, `600`, `-n1`) sit
181 // between the wrapper and the wrapped command; take the first
182 // compiler that follows.
183 let Some(offset) = tokens[index + 1..].iter().position(|token| {
184 matches!(
185 stem(token).as_str(),
186 "cargo" | "rustc" | "dev-test" | "dev-cargo"
187 )
188 }) else {
189 return false;
190 };
191 index += 1 + offset;
192 }
193 let executable = stem(&tokens[index]);
194 if matches!(executable.as_str(), "dev-test" | "dev-cargo") {
195 return true;
196 }
197 if !matches!(executable.as_str(), "cargo" | "rustc") {
198 return false;
199 }
200 if executable == "rustc" {
201 return true;
202 }
203 tokens[index + 1..]
204 .iter()
205 .map(|arg| arg.trim().to_ascii_lowercase())
206 .find(|arg| !arg.is_empty() && !arg.starts_with(['-', '+']) && !arg.contains('='))
207 .is_some_and(|subcommand| {
208 matches!(
209 subcommand.as_str(),
210 "build" | "test" | "check" | "clippy" | "rustc"
211 )
212 })
213 }
214
215 pub async fn acquire_heavy_command_permit(
216 command: &str,
217 cancel: Option<&CancellationToken>,
218 ) -> Result<Option<HeavyCommandPermit>> {
219 if infer_command_expense(command) == CommandExpense::Normal {
220 return Ok(None);
221 }
222
223 let limit = configured_heavy_command_limit();
224 let root = admission_root();
225 let probe = HostMemoryProbe;
226 acquire_heavy_command_permit_at(&root, limit, cancel, &probe)
227 .await
228 .map(Some)
229 }
230
231 async fn acquire_heavy_command_permit_at(
232 root: &Path,
233 limit: usize,
234 cancel: Option<&CancellationToken>,
235 probe: &dyn MemoryProbe,
236 ) -> Result<HeavyCommandPermit> {
237 tokio::fs::create_dir_all(root)
238 .await
239 .with_context(|| format!("creating resource admission directory {}", root.display()))?;
240 let started = Instant::now();
241
242 loop {
243 if cancel.is_some_and(|token| token.is_cancelled()) {
244 return Err(anyhow!(
245 "heavy command canceled while queued for resource admission"
246 ));
247 }
248 // Re-measure each iteration: under memory pressure the effective limit
249 // tightens so a saturated host stops admitting new heavy link graphs
250 // (#4864 req 7). Critical pressure yields zero slots, so the command
251 // waits for recovery instead of snowballing.
252 let pressure = classify_memory_pressure(probe.free_fraction());
253 let effective = effective_admission_limit(limit, pressure);
254 for slot in 0..effective {
255 let path = root.join(format!("heavy-{slot}.lock"));
256 match try_lock_slot(&path) {
257 Ok(Some(slot)) => {
258 return Ok(HeavyCommandPermit {
259 _slot: Some(slot),
260 queued_for: started.elapsed(),
261 limit,
262 memory_pressure: pressure,
263 });
264 }
265 Ok(None) => {}
266 Err(error) => {
267 return Err(error).with_context(|| {
268 format!("acquiring heavy command permit {}", path.display())
269 });
270 }
271 }
272 }
273 tokio::time::sleep(ADMISSION_POLL_INTERVAL).await;
274 if started.elapsed() >= ADMISSION_MAX_WAIT {
275 tracing::warn!(
276 waited_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
277 effective_slots = effective,
278 ?pressure,
279 "heavy command admission wait expired; running without a permit"
280 );
281 return Ok(HeavyCommandPermit {
282 _slot: None,
283 queued_for: started.elapsed(),
284 limit,
285 memory_pressure: pressure,
286 });
287 }
288 }
289 }
290
291 fn try_lock_slot(path: &Path) -> io::Result<Option<HeavyPermitSlot>> {
292 let file = OpenOptions::new()
293 .create(true)
294 .read(true)
295 .write(true)
296 .truncate(false)
297 .open(path)?;
298 let lock = Box::new(RwLock::new(file));
299 let lock_ptr = Box::into_raw(lock);
300 // SAFETY: `lock_ptr` remains allocated in `HeavyPermitSlot::_lock` for the
301 // lifetime of `_guard`, and the guard is dropped before that box.
302 let guard = match unsafe { (&mut *lock_ptr).try_write() } {
303 Ok(guard) => guard,
304 Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
305 // SAFETY: no guard was created, so reclaim the allocation now.
306 unsafe { drop(Box::from_raw(lock_ptr)) };
307 return Ok(None);
308 }
309 Err(error) => {
310 // SAFETY: no guard was created, so reclaim the allocation now.
311 unsafe { drop(Box::from_raw(lock_ptr)) };
312 return Err(error);
313 }
314 };
315 // SAFETY: the allocation is owned exactly once by this box and is stable on
316 // the heap even if `HeavyPermitSlot` moves.
317 let lock = unsafe { Box::from_raw(lock_ptr) };
318 // SAFETY: the boxed lock remains alive until after `_guard` is dropped.
319 let guard = unsafe {
320 std::mem::transmute::<RwLockWriteGuard<'_, File>, RwLockWriteGuard<'static, File>>(guard)
321 };
322 Ok(Some(HeavyPermitSlot {
323 _guard: guard,
324 _lock: lock,
325 }))
326 }
327
328 fn configured_heavy_command_limit() -> usize {
329 std::env::var("CODEWHALE_HEAVY_COMMAND_LIMIT")
330 .ok()
331 .and_then(|value| value.trim().parse::<usize>().ok())
332 .filter(|limit| *limit > 0)
333 .unwrap_or(DEFAULT_HEAVY_COMMAND_LIMIT)
334 .min(MAX_HEAVY_COMMAND_LIMIT)
335 }
336
337 fn admission_root() -> PathBuf {
338 if let Some(home) = codewhale_paths::codewhale_home_override().ok().flatten() {
339 return home.join("resource-admission");
340 }
341 if let Some(home) = codewhale_paths::user_home() {
342 return home.join(".codewhale").join("resource-admission");
343 }
344 std::env::temp_dir().join("codewhale-resource-admission")
345 }
346
347 /// Host free-RAM fraction in `0.0..=1.0`, or `None` when it cannot be measured.
348 ///
349 /// Each implementation shells out to a standard, always-present tool so no new
350 /// crate or build-feature dependency is introduced, and every error path returns
351 /// `None` so admission fails open (never blocks on an unmeasurable host). This
352 /// keeps the gate safe on any CI runner, while protecting the macOS dogfood host
353 /// and Linux/Windows machines where the tool exists.
354 #[cfg(target_os = "linux")]
355 fn host_memory_free_fraction() -> Option<f64> {
356 let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
357 let total = parse_meminfo_kb(&meminfo, "MemTotal:")?;
358 let available = parse_meminfo_kb(&meminfo, "MemAvailable:")?;
359 (total > 0).then(|| (available as f64 / total as f64).clamp(0.0, 1.0))
360 }
361
362 #[cfg(target_os = "linux")]
363 fn parse_meminfo_kb(meminfo: &str, prefix: &str) -> Option<u64> {
364 meminfo
365 .lines()
366 .find(|line| line.starts_with(prefix))
367 .and_then(|line| line.split_whitespace().nth(1))
368 .and_then(|value| value.parse::<u64>().ok())
369 }
370
371 #[cfg(target_os = "macos")]
372 fn host_memory_free_fraction() -> Option<f64> {
373 let total = run_capture("/usr/sbin/sysctl", &["-n", "hw.memsize"])
374 .and_then(|bytes| bytes.trim().parse::<u64>().ok())?;
375 let page_size = run_capture("/usr/bin/pagesize", &[])?
376 .trim()
377 .parse::<u64>()
378 .ok()?;
379 let stats = run_capture("/usr/bin/vm_stat", &[])?;
380 let free_pages = memory_pages_from_vm_stat(
381 &stats,
382 &[
383 "Pages free:",
384 "Pages inactive:",
385 "Pages speculative:",
386 "Pages purgeable:",
387 ],
388 )?;
389 let free_bytes = free_pages.checked_mul(page_size)?;
390 (total > 0).then(|| (free_bytes as f64 / total as f64).clamp(0.0, 1.0))
391 }
392
393 #[cfg(target_os = "macos")]
394 fn memory_pages_from_vm_stat(vm_stat: &str, prefixes: &[&str]) -> Option<u64> {
395 let mut total = 0u64;
396 for prefix in prefixes {
397 let pages = vm_stat
398 .lines()
399 .find(|line| line.trim_start().starts_with(prefix))
400 .and_then(|line| {
401 line.split('.')
402 .nth(1)
403 .and_then(|rest| rest.trim().parse::<u64>().ok())
404 })?;
405 total = total.checked_add(pages)?;
406 }
407 Some(total)
408 }
409
410 #[cfg(windows)]
411 fn host_memory_free_fraction() -> Option<f64> {
412 // `wmic` is deprecated but present on every supported Windows runner and
413 // avoids adding a GlobalMemoryStatusEx build dependency. Fail open on error.
414 let out = run_capture(
415 "C:\\Windows\\System32\\wbem\\wmic.exe",
416 &[
417 "OS",
418 "get",
419 "FreePhysicalMemory,TotalVisibleMemorySize",
420 "/value",
421 ],
422 )?;
423 let free_kb = wmic_value(&out, "FreePhysicalMemory=")?;
424 let total_kb = wmic_value(&out, "TotalVisibleMemorySize=")?;
425 (total_kb > 0).then(|| (free_kb as f64 / total_kb as f64).clamp(0.0, 1.0))
426 }
427
428 #[cfg(windows)]
429 fn wmic_value(output: &str, key: &str) -> Option<u64> {
430 output
431 .lines()
432 .find_map(|line| line.trim().strip_prefix(key))
433 .and_then(|value| value.trim().parse::<u64>().ok())
434 }
435
436 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
437 fn host_memory_free_fraction() -> Option<f64> {
438 None
439 }
440
441 #[cfg(any(target_os = "macos", target_os = "windows"))]
442 fn run_capture(program: &str, args: &[&str]) -> Option<String> {
443 let output = std::process::Command::new(program)
444 .args(args)
445 .output()
446 .ok()?;
447 if !output.status.success() {
448 return None;
449 }
450 String::from_utf8(output.stdout).ok()
451 }
452
453 #[cfg(test)]
454 mod tests {
455 use std::sync::Arc;
456 use std::sync::atomic::{AtomicUsize, Ordering};
457
458 use super::*;
459
460 /// Deterministic probe returning a fixed fraction so admission behavior is
461 /// independent of the host running the test suite.
462 struct StaticMemoryProbe(Option<f64>);
463 impl MemoryProbe for StaticMemoryProbe {
464 fn free_fraction(&self) -> Option<f64> {
465 self.0
466 }
467 }
468
469 const NOMINAL_PROBE: StaticMemoryProbe = StaticMemoryProbe(Some(0.9));
470
471 #[test]
472 fn whitespace_codewhale_home_uses_shared_user_home_for_admission_state() {
473 let _lock = crate::test_support::lock_test_env();
474 let tmp = tempfile::tempdir().expect("temporary root");
475 let home = tmp.path().join("home");
476 let userprofile = tmp.path().join("userprofile");
477 let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
478 let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &userprofile);
479 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", " \t ");
480
481 assert_eq!(
482 admission_root(),
483 home.join(".codewhale").join("resource-admission")
484 );
485 }
486
487 #[test]
488 fn memory_pressure_classification_and_effective_limit() {
489 // Unknown (unmeasurable) fails open to the configured limit.
490 assert_eq!(classify_memory_pressure(None), MemoryPressure::Unknown);
491 assert_eq!(effective_admission_limit(2, MemoryPressure::Unknown), 2);
492 assert_eq!(classify_memory_pressure(Some(0.9)), MemoryPressure::Nominal);
493 assert_eq!(
494 classify_memory_pressure(Some(0.30)),
495 MemoryPressure::Constrained
496 );
497 assert_eq!(
498 classify_memory_pressure(Some(0.15)),
499 MemoryPressure::Critical
500 );
501 assert_eq!(
502 classify_memory_pressure(Some(0.0)),
503 MemoryPressure::Critical
504 );
505 assert_eq!(effective_admission_limit(4, MemoryPressure::Nominal), 4);
506 assert_eq!(effective_admission_limit(4, MemoryPressure::Constrained), 2);
507 assert_eq!(effective_admission_limit(1, MemoryPressure::Constrained), 1);
508 assert_eq!(effective_admission_limit(4, MemoryPressure::Critical), 0);
509 }
510
511 #[test]
512 fn infers_only_expensive_rust_compilation_commands() {
513 for command in [
514 "cargo test -p codewhale-tui shell::tests",
515 "env CARGO_BUILD_JOBS=2 cargo build --workspace",
516 "cargo check",
517 "cargo clippy --all-targets",
518 "/usr/bin/rustc src/main.rs",
519 "printf ok && cargo rustc -- --emit=metadata",
520 // #6560 D01-11: wrappers run the same compilation.
521 "sudo cargo build --release",
522 "sudo -u builder cargo test",
523 "timeout 600 cargo test --workspace",
524 "nice -n 10 cargo check",
525 "bash -c \"cargo build\"",
526 "sh -c 'cargo clippy --all-targets'",
527 "git ls-files | xargs cargo check",
528 "(cargo build)",
529 "env RUSTFLAGS=-Dwarnings nohup cargo build",
530 ] {
531 assert_eq!(
532 infer_command_expense(command),
533 CommandExpense::Heavy,
534 "{command}"
535 );
536 }
537 for command in [
538 "cargo fmt --check",
539 "cargo metadata",
540 "git status",
541 "echo cargo test",
542 "sudo cargo fmt",
543 "timeout 5 git status",
544 "bash -c \"ls\"",
545 "xargs rm",
546 ] {
547 assert_eq!(
548 infer_command_expense(command),
549 CommandExpense::Normal,
550 "{command}"
551 );
552 }
553 }
554
555 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
556 async fn cross_task_heavy_admission_never_exceeds_limit() {
557 let temp = tempfile::tempdir().expect("tempdir");
558 let active = Arc::new(AtomicUsize::new(0));
559 let peak = Arc::new(AtomicUsize::new(0));
560 let mut tasks = Vec::new();
561
562 for _ in 0..12 {
563 let root = temp.path().to_path_buf();
564 let active = Arc::clone(&active);
565 let peak = Arc::clone(&peak);
566 tasks.push(tokio::spawn(async move {
567 let _permit = acquire_heavy_command_permit_at(&root, 2, None, &NOMINAL_PROBE)
568 .await
569 .expect("permit");
570 let current = active.fetch_add(1, Ordering::SeqCst) + 1;
571 peak.fetch_max(current, Ordering::SeqCst);
572 tokio::time::sleep(Duration::from_millis(30)).await;
573 active.fetch_sub(1, Ordering::SeqCst);
574 }));
575 }
576 for task in tasks {
577 task.await.expect("admission task");
578 }
579
580 assert_eq!(active.load(Ordering::SeqCst), 0);
581 assert_eq!(peak.load(Ordering::SeqCst), 2);
582 }
583
584 #[tokio::test]
585 async fn queued_admission_observes_cancellation() {
586 let temp = tempfile::tempdir().expect("tempdir");
587 let _held = acquire_heavy_command_permit_at(temp.path(), 1, None, &NOMINAL_PROBE)
588 .await
589 .expect("initial permit");
590 let cancel = CancellationToken::new();
591 let wait_cancel = cancel.clone();
592 let root = temp.path().to_path_buf();
593 let waiter = tokio::spawn(async move {
594 acquire_heavy_command_permit_at(&root, 1, Some(&wait_cancel), &NOMINAL_PROBE).await
595 });
596
597 tokio::time::sleep(Duration::from_millis(75)).await;
598 cancel.cancel();
599 let error = tokio::time::timeout(Duration::from_secs(1), waiter)
600 .await
601 .expect("bounded cancellation")
602 .expect("waiter task")
603 .expect_err("queued command must cancel");
604 assert!(error.to_string().contains("canceled while queued"));
605 }
606
607 #[tokio::test]
608 async fn critical_memory_pressure_queues_without_admitting() {
609 let temp = tempfile::tempdir().expect("tempdir");
610 // Critical pressure -> zero effective slots -> the command cannot be
611 // admitted and must observe cancellation rather than spin forever.
612 let critical = StaticMemoryProbe(Some(0.05));
613 let cancel = CancellationToken::new();
614 let wait_cancel = cancel.clone();
615 let root = temp.path().to_path_buf();
616 let waiter = tokio::spawn(async move {
617 acquire_heavy_command_permit_at(&root, 2, Some(&wait_cancel), &critical).await
618 });
619 tokio::time::sleep(Duration::from_millis(120)).await;
620 cancel.cancel();
621 let error = tokio::time::timeout(Duration::from_secs(2), waiter)
622 .await
623 .expect("bounded cancellation")
624 .expect("waiter task")
625 .expect_err("critical-pressure command must not be admitted");
626 assert!(error.to_string().contains("canceled while queued"));
627 }
628
629 #[test]
630 fn host_memory_probe_is_fail_safe() {
631 // On any supported host the probe either measures a plausible fraction
632 // or admits it cannot; it must never panic or return an out-of-range.
633 if let Some(fraction) = host_memory_free_fraction() {
634 assert!(
635 (0.0..=1.0).contains(&fraction),
636 "measured free fraction out of range: {fraction}"
637 );
638 }
639 }
640
641 /// Opt-in real cargo acceptance (#4864 req 8): drive an actual heavy-class
642 /// cargo invocation through the admission path end to end. `cargo check
643 /// --version` classifies as heavy (subcommand `check`) but exits instantly,
644 /// so this is fast. Gated behind an env var so CI never runs a real cargo.
645 #[cfg(unix)]
646 #[tokio::test]
647 async fn real_cargo_command_is_admitted_and_released() {
648 if std::env::var_os("CODEWHALE_RESOURCE_ADMISSION_RUST_ACCEPTANCE").is_none() {
649 tracing::info!(
650 "skipping opt-in real-rust admission acceptance; \
651 set CODEWHALE_RESOURCE_ADMISSION_RUST_ACCEPTANCE=1 to run"
652 );
653 return;
654 }
655 let temp = tempfile::tempdir().expect("tempdir");
656 let permit = acquire_heavy_command_permit_at(temp.path(), 2, None, &NOMINAL_PROBE)
657 .await
658 .expect("heavy permit for real cargo");
659 assert_eq!(permit.limit(), 2);
660 assert_eq!(permit.memory_pressure(), MemoryPressure::Nominal);
661 let cargo = std::process::Command::new("cargo")
662 .arg("check")
663 .arg("--version")
664 .output()
665 .expect("run cargo");
666 assert!(cargo.status.success(), "cargo check --version failed");
667 drop(permit);
668 let _again = acquire_heavy_command_permit_at(temp.path(), 2, None, &NOMINAL_PROBE)
669 .await
670 .expect("re-acquire after release");
671 }
672 }
673
673 lines RUST