forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

pressure.rs1310 lines, 49.3 KiBHistoryRawDownload
1//! Reactive memory control. The runner puts every job cgroup inside one box cgroup
2//! (`forge-jobs`) that is capped at the memory budget. When two or more jobs run and the box nears
3//! its cap, the youngest job is frozen and its memory is pushed to swap, so the other job keeps
4//! its RAM and nothing is OOM-killed. The parked job thaws when there is room again. When parking
5//! does not work, the job is killed and queued again on the forge. A lone job is never paused: it
6//! may use the whole box, and a real OOM there is reported as before (see [`crate::oom`]).
7//!
8//! Nothing here polls. The box's `memory.events` is watched with inotify (the `high` counter
9//! moves the moment an allocation is held back by `memory.high`), the box's `memory.pressure` has
10//! a PSI trigger as a second signal, and jobs starting and ending wake the controller too.
11//!
12//! `memory.high` is a brake that never lets go by itself: with swap off for the jobs, allocations
13//! above it stall for minutes. So it is only set while 2+ jobs run unfrozen, and the controller
14//! relaxes it the moment the stalled job is the only one left.
15//!
16//! The cgroup files are read and written through plain paths, so tests use a temp dir as a fake
17//! cgroup.
18
19use std::fs::{self, File, OpenOptions};
20use std::io::{self, Write};
21use std::os::fd::{AsFd, OwnedFd};
22use std::os::unix::fs::OpenOptionsExt;
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
25use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
26use std::time::{Duration, Instant};
27
28use nix::errno::Errno;
29use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
30use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify};
31use nix::unistd::pipe;
32use tokio::sync::{Notify, mpsc};
33use tokio_util::sync::CancellationToken;
34
35use crate::executor::kill_cgroup;
36use crate::sandbox::{BOX_NAME, job_cgroup_base};
37
38/// Where cgroup2 is mounted.
39const CGROUP_ROOT: &str = "/sys/fs/cgroup";
40/// The controllers jobs need, enabled on the box and on its parent.
41const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"];
42/// The PSI trigger: 150 ms of stall in a 2 s window. Unprivileged users need a multiple of 2 s.
43const PSI_TRIGGER: &str = "some 150000 2000000";
44/// `memory.high` sits below the box cap by the larger of this and 5% of the cap.
45const HIGH_MARGIN_MIN: u64 = 512 << 20;
46/// How hard a parked job's pages are pushed to swap.
47const SWAPPINESS: u32 = 200;
48/// How many reclaim writes to try on a frozen job. One write may reclaim only part of it.
49const RECLAIM_ATTEMPTS: u32 = 4;
50/// How long a leftover job cgroup from an earlier runner gets to die at startup.
51const LEFTOVER_POLLS: u32 = 50;
52const LEFTOVER_POLL: Duration = Duration::from_millis(100);
53/// How long a pressure signal holds the gate shut. Pressure is a moment, not a state: without a
54/// later look the gate would stay shut when the last signal came after the last job ended.
55const PRESSURE_COOLDOWN: Duration = Duration::from_secs(10);
56
57/// What woke the controller.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum Cause {
60 /// The box is short of memory: `high` moved in `memory.events`, or the PSI trigger fired.
61 Pressure,
62 /// A job started or ended, or the box changed in a way that is no pressure signal.
63 Jobs,
64}
65
66// ----- pure rules -----
67
68/// The `high` counter of a `memory.events` text. Missing means 0.
69pub fn parse_high(text: &str) -> u64 {
70 text.lines()
71 .find_map(|line| {
72 let (key, value) = line.split_once(' ')?;
73 (key == "high").then(|| value.trim().parse().ok())?
74 })
75 .unwrap_or(0)
76}
77
78/// `memory.high` of the box, or `None` for `max`. Only set while two or more jobs run unfrozen:
79/// a lone job runs up to the box's `memory.max`.
80pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> {
81 if unfrozen < 2 {
82 return None;
83 }
84 let margin = HIGH_MARGIN_MIN.max(budget / 20);
85 Some(budget.saturating_sub(margin))
86}
87
88/// A running job, as far as victim choice cares.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct Running {
91 /// Start order: higher is younger.
92 pub seq: u64,
93 pub frozen: bool,
94}
95
96/// The job to park: the youngest unfrozen one, and only while at least two are unfrozen.
97pub fn pick_victim(jobs: &[Running]) -> Option<usize> {
98 let unfrozen = || jobs.iter().enumerate().filter(|(_, j)| !j.frozen);
99 if unfrozen().count() < 2 {
100 return None;
101 }
102 unfrozen().max_by_key(|(_, j)| j.seq).map(|(i, _)| i)
103}
104
105/// A parked job, as far as thaw choice cares.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub struct Parked {
108 pub seq: u64,
109 /// Bytes of the job that sit in swap.
110 pub swap: u64,
111}
112
113/// The parked job to thaw: the oldest, once the box has room for what is in its swap or nothing
114/// else runs.
115pub fn pick_thaw(parked: &[Parked], unfrozen_running: usize, headroom: u64) -> Option<usize> {
116 let (index, oldest) = parked.iter().enumerate().min_by_key(|(_, p)| p.seq)?;
117 (unfrozen_running == 0 || headroom >= oldest.swap).then_some(index)
118}
119
120/// Whether the box is marked as under pressure after a pass. Pressure signals set it. Any other
121/// wake clears it, unless the box still sits at `memory.high`.
122pub fn hot_after(cause: Cause, over_high: bool, jobs: usize) -> bool {
123 // An empty box has nothing to hold back, so nothing keeps the runner from claiming.
124 jobs > 0 && (cause == Cause::Pressure || over_high)
125}
126
127/// The admission gate: the runner claims a new job only while it is open.
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129pub struct Gate {
130 pub frozen: usize,
131 pub hot: bool,
132}
133
134impl Gate {
135 pub fn open(&self) -> bool {
136 self.frozen == 0 && !self.hot
137 }
138}
139
140// ----- the jobs the controller knows -----
141
142#[derive(Default)]
143struct PauseClock {
144 total: Duration,
145 since: Option<Instant>,
146}
147
148/// One registered job, shared between its runner task and the controller.
149pub struct JobHandle {
150 id: String,
151 name: String,
152 log: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
153 requeued: AtomicBool,
154 clock: Mutex<PauseClock>,
155}
156
157impl JobHandle {
158 /// Appends a line to the job's log. A full or closed log drops it.
159 fn log_line(&self, line: &str) {
160 let guard = self.log.lock().unwrap_or_else(PoisonError::into_inner);
161 if let Some(tx) = guard.as_ref() {
162 let mut bytes = format!("runner: {line}").into_bytes();
163 bytes.push(b'\n');
164 let _ = tx.try_send(bytes);
165 }
166 }
167
168 /// How long the job has spent frozen so far.
169 pub fn paused(&self) -> Duration {
170 let clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
171 clock.total + clock.since.map(|s| s.elapsed()).unwrap_or_default()
172 }
173
174 fn pause(&self) {
175 let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
176 clock.since.get_or_insert_with(Instant::now);
177 }
178
179 /// Ends a pause and returns how long it lasted.
180 fn resume(&self) -> Duration {
181 let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
182 let lasted = clock.since.take().map(|s| s.elapsed()).unwrap_or_default();
183 clock.total += lasted;
184 lasted
185 }
186}
187
188/// A job's registration. Dropping it takes the job out of the controller's view.
189pub struct Registration {
190 handle: Arc<JobHandle>,
191 owner: Arc<Pressure>,
192}
193
194impl Registration {
195 /// True when the controller killed the job to give it back to the queue.
196 pub fn requeued(&self) -> bool {
197 self.handle.requeued.load(Ordering::SeqCst)
198 }
199
200 /// How long the job has spent frozen so far. Its timeout does not count that time.
201 pub fn paused(&self) -> Duration {
202 self.handle.paused()
203 }
204
205 /// A handle for reading [`Registration::paused`] from another task.
206 pub fn pause_clock(&self) -> Arc<JobHandle> {
207 self.handle.clone()
208 }
209}
210
211impl Drop for Registration {
212 fn drop(&mut self) {
213 // The log sender must go now, or the log shipper would wait for it.
214 *self
215 .handle
216 .log
217 .lock()
218 .unwrap_or_else(PoisonError::into_inner) = None;
219 self.owner.remove(&self.handle);
220 }
221}
222
223struct Entry {
224 handle: Arc<JobHandle>,
225 seq: u64,
226 /// The job's cgroup, once the sandbox has created it.
227 dir: Option<PathBuf>,
228 frozen: Option<Frozen>,
229}
230
231struct Frozen {
232 swap: u64,
233}
234
235#[derive(Default)]
236struct State {
237 entries: Vec<Entry>,
238 gate: Gate,
239 /// The `memory.high` last written, to skip repeated writes.
240 high: Option<Option<u64>>,
241}
242
243/// The box and the controller of the jobs in it.
244pub struct Pressure {
245 dir: PathBuf,
246 budget: AtomicU64,
247 state: Mutex<State>,
248 seq: AtomicU64,
249 /// Wakes the watcher: a job registered or ended.
250 kick: Notify,
251 /// Wakes the claim loop: the gate may have changed.
252 changed: Notify,
253}
254
255impl Pressure {
256 /// Creates the box and starts the watcher. Returns `None`, after one log line, when the host
257 /// can't do it: cgroup controllers not delegated, no inotify, and so on. The runner then
258 /// works as before, without the box and without pausing.
259 pub async fn start(budget: u64, shutdown: CancellationToken) -> Option<Arc<Self>> {
260 let setup = tokio::task::spawn_blocking(move || {
261 let base = job_cgroup_base().map_err(|e| e.to_string())?;
262 let parent = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base));
263 create_box(&parent, budget)
264 })
265 .await;
266 let dir = match setup {
267 Ok(Ok(dir)) => dir,
268 Ok(Err(e)) => {
269 tracing::warn!("memory control is off: {e}");
270 return None;
271 }
272 Err(e) => {
273 tracing::warn!("memory control is off: {e}");
274 return None;
275 }
276 };
277 let this = Arc::new(Self::at(dir, budget));
278 match Watcher::open(&this.dir) {
279 Ok(watcher) => {
280 let psi = watcher.psi_armed;
281 tokio::spawn(this.clone().watch(watcher, shutdown));
282 tracing::info!(
283 box_dir = %this.dir.display(),
284 budget = %forge_ci::size::format_size(budget),
285 psi,
286 "memory control is on"
287 );
288 Some(this)
289 }
290 Err(e) => {
291 tracing::warn!("memory control is off, cannot watch the box: {e}");
292 None
293 }
294 }
295 }
296
297 fn at(dir: PathBuf, budget: u64) -> Self {
298 Self {
299 dir,
300 budget: AtomicU64::new(budget),
301 state: Mutex::new(State::default()),
302 seq: AtomicU64::new(0),
303 kick: Notify::new(),
304 changed: Notify::new(),
305 }
306 }
307
308 /// The memory the box may use: the budget it was created with.
309 pub fn budget(&self) -> u64 {
310 self.budget.load(Ordering::SeqCst)
311 }
312
313 /// Follows a changed memory budget: resizes the box's `memory.max` and `memory.swap.max` and
314 /// lets the controller recompute `memory.high`. Does nothing when the budget is the same.
315 /// Blocks while the kernel reclaims on a shrink, so call it off the async runtime.
316 pub fn resize(&self, budget: u64) {
317 if self.budget.swap(budget, Ordering::SeqCst) == budget {
318 return;
319 }
320 // Growing: raise max first. Shrinking: lower high first (it is recomputed below).
321 for file in ["memory.max", "memory.swap.max"] {
322 if let Err(e) = fs::write(self.dir.join(file), budget.to_string()) {
323 tracing::warn!("cannot resize {file} of the box: {e}");
324 }
325 }
326 // Force the next pass to write memory.high for the new budget.
327 self.lock().high = None;
328 self.kick.notify_one();
329 tracing::info!(
330 budget = %forge_ci::size::format_size(budget),
331 "memory box resized"
332 );
333 }
334
335 fn lock(&self) -> MutexGuard<'_, State> {
336 self.state.lock().unwrap_or_else(PoisonError::into_inner)
337 }
338
339 /// Puts a job under control. `log` receives the pause and resume lines.
340 pub fn register(
341 self: &Arc<Self>,
342 job_id: &str,
343 job_name: &str,
344 log: mpsc::Sender<Vec<u8>>,
345 ) -> Registration {
346 let handle = Arc::new(JobHandle {
347 id: job_id.to_owned(),
348 name: job_name.to_owned(),
349 log: Mutex::new(Some(log)),
350 requeued: AtomicBool::new(false),
351 clock: Mutex::new(PauseClock::default()),
352 });
353 self.lock().entries.push(Entry {
354 handle: handle.clone(),
355 seq: self.seq.fetch_add(1, Ordering::SeqCst),
356 dir: None,
357 frozen: None,
358 });
359 self.kick.notify_one();
360 Registration {
361 handle,
362 owner: self.clone(),
363 }
364 }
365
366 fn remove(&self, handle: &Arc<JobHandle>) {
367 self.lock()
368 .entries
369 .retain(|e| !Arc::ptr_eq(&e.handle, handle));
370 self.kick.notify_one();
371 }
372
373 /// Memory the box has left, counting reclaimable page cache as free. `None` when unreadable.
374 pub fn headroom(&self) -> Option<u64> {
375 let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget());
376 Some(max.saturating_sub(box_usage(&self.dir)?))
377 }
378
379 /// The admission gate as it is now: how many jobs are parked and whether the box is hot.
380 pub fn gate(&self) -> Gate {
381 self.lock().gate
382 }
383
384 /// Resolves once the runner may claim: no job is parked and the box is not under pressure.
385 /// Woken by the controller, never by a timer.
386 pub async fn wait_open(&self) {
387 loop {
388 let notified = self.changed.notified();
389 tokio::pin!(notified);
390 notified.as_mut().enable();
391 if self.lock().gate.open() {
392 return;
393 }
394 notified.await;
395 }
396 }
397
398 async fn watch(self: Arc<Self>, mut watcher: Watcher, shutdown: CancellationToken) {
399 // Set while the gate is hot: when no new signal came by then, the box is looked at again.
400 let mut recheck: Option<tokio::time::Instant> = None;
401 loop {
402 let cause = tokio::select! {
403 () = shutdown.cancelled() => return,
404 () = tokio::time::sleep_until(recheck.unwrap_or_else(tokio::time::Instant::now)),
405 if recheck.is_some() => Cause::Jobs,
406 cause = watcher.rx.recv() => {
407 let Some(cause) = cause else {
408 tracing::warn!("memory control stopped, the watcher thread ended");
409 return;
410 };
411 cause
412 }
413 () = self.kick.notified() => Cause::Jobs,
414 };
415 let this = self.clone();
416 if let Err(e) = tokio::task::spawn_blocking(move || this.settle(cause)).await {
417 tracing::error!("memory control pass panicked: {e}");
418 }
419 recheck = self
420 .lock()
421 .gate
422 .hot
423 .then(|| tokio::time::Instant::now() + PRESSURE_COOLDOWN);
424 }
425 }
426
427 /// One pass: park a job if the box is short of memory, thaw one if there is room, and set
428 /// `memory.high` for what runs now. Blocks, so it runs off the async runtime.
429 fn settle(&self, cause: Cause) {
430 let mut state = self.lock();
431 // A job given back and claimed again keeps its id, and the killed run's cgroup can still
432 // be there, so a directory another entry holds is not this entry's.
433 let mut taken: Vec<PathBuf> = state.entries.iter().filter_map(|e| e.dir.clone()).collect();
434 for entry in &mut state.entries {
435 if entry.dir.is_none()
436 && let Some(dir) = find_job_dir(&self.dir, &entry.handle.id, &taken)
437 {
438 taken.push(dir.clone());
439 // A real OOM then takes the whole job, not one of its processes.
440 let _ = fs::write(dir.join("memory.oom.group"), "1");
441 entry.dir = Some(dir);
442 }
443 }
444 let mut parked_now = false;
445 if cause == Cause::Pressure {
446 let live: Vec<usize> = (0..state.entries.len())
447 .filter(|&i| is_live(&state.entries[i]))
448 .collect();
449 let running: Vec<Running> = live
450 .iter()
451 .map(|&i| Running {
452 seq: state.entries[i].seq,
453 frozen: false,
454 })
455 .collect();
456 if let Some(pick) = pick_victim(&running) {
457 let victim = live[pick];
458 let waiting_for = live
459 .iter()
460 .filter(|&&i| i != victim)
461 .min_by_key(|&&i| state.entries[i].seq)
462 .map(|&i| state.entries[i].handle.name.clone())
463 .unwrap_or_default();
464 park(&mut state.entries[victim], &waiting_for);
465 parked_now = true;
466 }
467 }
468 if !parked_now {
469 self.thaw_one(&mut state);
470 }
471 let unfrozen = state.entries.iter().filter(|e| is_live(e)).count();
472 let high = high_value(unfrozen, self.budget());
473 if state.high != Some(high) {
474 let text = high.map_or_else(|| "max".to_owned(), |b| b.to_string());
475 match fs::write(self.dir.join("memory.high"), text) {
476 Ok(()) => state.high = Some(high),
477 Err(e) => tracing::warn!("cannot set memory.high of the box: {e}"),
478 }
479 }
480 let over_high = high.is_some_and(|h| box_usage(&self.dir).is_some_and(|u| u >= h));
481 state.gate = Gate {
482 frozen: state.entries.iter().filter(|e| e.frozen.is_some()).count(),
483 hot: hot_after(cause, over_high, state.entries.len()),
484 };
485 drop(state);
486 self.changed.notify_waiters();
487 }
488
489 fn thaw_one(&self, state: &mut State) {
490 let parked: Vec<(usize, Parked)> = state
491 .entries
492 .iter()
493 .enumerate()
494 .filter_map(|(i, e)| {
495 let frozen = e.frozen.as_ref()?;
496 let swap = e.dir.as_deref().and_then(job_swap).unwrap_or(frozen.swap);
497 Some((i, Parked { seq: e.seq, swap }))
498 })
499 .collect();
500 let running = state.entries.iter().filter(|e| is_live(e)).count();
501 // A thawed job starts touching its pages again, so it needs room below the level where
502 // `memory.high` would hold two jobs back, plus a margin to grow. Otherwise it would be
503 // parked again at once.
504 let below_high = high_value(running + 1, self.budget()).unwrap_or(0);
505 let headroom = box_usage(&self.dir)
506 .map_or(0, |usage| below_high.saturating_sub(usage))
507 .saturating_sub(HIGH_MARGIN_MIN);
508 let list: Vec<Parked> = parked.iter().map(|(_, p)| *p).collect();
509 let Some(pick) = pick_thaw(&list, running, headroom) else {
510 return;
511 };
512 let entry = &mut state.entries[parked[pick].0];
513 let Some(dir) = entry.dir.clone() else {
514 return;
515 };
516 // Swap stays where it is. Nothing new goes out, and pages come back as the job touches them.
517 let _ = fs::write(dir.join("memory.swap.max"), "0");
518 if let Err(e) = fs::write(dir.join("cgroup.freeze"), "0") {
519 tracing::warn!(job_id = %entry.handle.id, "cannot thaw job: {e}");
520 return;
521 }
522 entry.frozen = None;
523 let lasted = entry.handle.resume();
524 entry
525 .handle
526 .log_line(&format!("resumed after {}", format_duration(lasted)));
527 tracing::info!(job_id = %entry.handle.id, "job resumed");
528 }
529}
530
531/// Whether the entry counts as running and unfrozen: it has a cgroup, is not parked and was not
532/// killed for requeueing.
533fn is_live(entry: &Entry) -> bool {
534 entry.dir.is_some() && entry.frozen.is_none() && !entry.handle.requeued.load(Ordering::SeqCst)
535}
536
537/// Freezes the job and pushes its memory to swap. When that does not work, kills the job so the
538/// forge queues it again.
539fn park(entry: &mut Entry, waiting_for: &str) {
540 let Some(dir) = entry.dir.clone() else {
541 return;
542 };
543 let handle = entry.handle.clone();
544 let before = read_u64(&dir, "memory.current").unwrap_or(0);
545 let anon = stat_field(&dir, "anon").unwrap_or(before);
546 let swap_free = swap_free_bytes();
547 if swap_free.is_some_and(|free| free < anon) {
548 give_back(entry, "the host has no swap room for it");
549 return;
550 }
551 // The job's own cgroup may swap now. Its swap.max was 0 so it never swapped by itself.
552 let _ = fs::write(dir.join("memory.swap.max"), "max");
553 if let Err(e) = fs::write(dir.join("cgroup.freeze"), "1") {
554 tracing::warn!(job_id = %handle.id, "cannot freeze job: {e}");
555 give_back(entry, "it cannot be frozen");
556 return;
557 }
558 handle.pause();
559 handle.log_line(&format!(
560 "paused: memory pressure, waiting for {waiting_for}"
561 ));
562 let mut after = before;
563 for _ in 0..RECLAIM_ATTEMPTS {
564 reclaim(&dir, before);
565 after = read_u64(&dir, "memory.current").unwrap_or(before);
566 if after <= before / 2 {
567 break;
568 }
569 }
570 if after > before / 2 {
571 let _ = fs::write(dir.join("cgroup.freeze"), "0");
572 handle.resume();
573 give_back(entry, "its memory would not go to swap");
574 return;
575 }
576 let swap = job_swap(&dir).unwrap_or(0);
577 handle.log_line(&format!("parked {} MiB in swap", swap >> 20));
578 tracing::info!(job_id = %handle.id, swap, "job parked in swap");
579 entry.frozen = Some(Frozen { swap });
580}
581
582/// Writes the reclaim request. A rejected `swappiness` key falls back to the plain amount. The
583/// return code is not trusted: EAGAIN comes back on success too, so callers read `memory.current`.
584fn reclaim(dir: &Path, bytes: u64) {
585 let file = dir.join("memory.reclaim");
586 match fs::write(&file, format!("{bytes} swappiness={SWAPPINESS}")) {
587 Err(e) if e.kind() == io::ErrorKind::InvalidInput => {
588 let _ = fs::write(&file, bytes.to_string());
589 }
590 _ => {}
591 }
592}
593
594/// Kills the job and marks it for requeueing. The job's task sees the mark and queues it again
595/// instead of reporting a result.
596fn give_back(entry: &mut Entry, why: &str) {
597 entry.handle.requeued.store(true, Ordering::SeqCst);
598 entry.handle.log_line(&format!(
599 "memory pressure and {why}: stopping this job to run it again later"
600 ));
601 tracing::warn!(job_id = %entry.handle.id, "{why}, killing job to requeue it");
602 if let Some(dir) = &entry.dir {
603 // A frozen cgroup is killed too, but thaw first so the kill takes effect at once.
604 let _ = fs::write(dir.join("cgroup.freeze"), "0");
605 kill_cgroup(dir);
606 }
607}
608
609// ----- cgroup files -----
610
611/// The job's cgroup under the box: `forge-job-<id>-<pid>`.
612fn find_job_dir(box_dir: &Path, job_id: &str, taken: &[PathBuf]) -> Option<PathBuf> {
613 let prefix = format!("forge-job-{job_id}-");
614 fs::read_dir(box_dir)
615 .ok()?
616 .flatten()
617 .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
618 .map(|e| e.path())
619 .find(|path| !taken.contains(path))
620}
621
622/// A single-number cgroup file. `None` when missing or `max`.
623fn read_u64(dir: &Path, file: &str) -> Option<u64> {
624 fs::read_to_string(dir.join(file)).ok()?.trim().parse().ok()
625}
626
627fn stat_field(dir: &Path, key: &str) -> Option<u64> {
628 let text = fs::read_to_string(dir.join("memory.stat")).ok()?;
629 text.lines().find_map(|line| {
630 let (k, v) = line.split_once(' ')?;
631 (k == key).then(|| v.trim().parse().ok())?
632 })
633}
634
635fn job_swap(dir: &Path) -> Option<u64> {
636 read_u64(dir, "memory.swap.current")
637}
638
639/// What the box really holds: its charge minus inactive page cache, which the kernel gives up
640/// first. `None` when the charge is unreadable.
641fn box_usage(dir: &Path) -> Option<u64> {
642 let current = read_u64(dir, "memory.current")?;
643 Some(current.saturating_sub(stat_field(dir, "inactive_file").unwrap_or(0)))
644}
645
646/// `SwapFree` of `/proc/meminfo` in bytes.
647fn swap_free_bytes() -> Option<u64> {
648 let text = fs::read_to_string("/proc/meminfo").ok()?;
649 let line = text.lines().find(|l| l.starts_with("SwapFree:"))?;
650 line.split_whitespace()
651 .nth(1)?
652 .parse::<u64>()
653 .ok()?
654 .checked_mul(1024)
655}
656
657fn format_duration(d: Duration) -> String {
658 let secs = d.as_secs();
659 if secs >= 60 {
660 format!("{}m {}s", secs / 60, secs % 60)
661 } else {
662 format!("{secs}s")
663 }
664}
665
666// ----- the box -----
667
668/// Creates or adopts the box under `parent`, enables the controllers, and sets its limits. Job
669/// cgroups left by a runner that died are killed and removed. Returns the box directory.
670pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> {
671 let dir = parent.join(BOX_NAME);
672 match fs::create_dir(&dir) {
673 Ok(()) => {}
674 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
675 Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
676 }
677 remove_leftovers(&dir);
678 enable_controllers(parent)?;
679 enable_controllers(&dir)?;
680 let set = |file: &str, value: String| {
681 fs::write(dir.join(file), value).map_err(|e| format!("cannot set {file} on the box: {e}"))
682 };
683 set("memory.max", budget.to_string())?;
684 // Only a parked job swaps, and its own swap.max says when. The box allows it.
685 set("memory.swap.max", budget.to_string())?;
686 set("memory.high", "max".to_owned())?;
687 Ok(dir)
688}
689
690/// Kills and removes the job cgroups a previous runner left in the box. Frozen ones are thawed
691/// first, or the kill would wait for them.
692fn remove_leftovers(box_dir: &Path) {
693 let Ok(children) = fs::read_dir(box_dir) else {
694 return;
695 };
696 for child in children.flatten() {
697 let path = child.path();
698 if !path.is_dir() {
699 continue;
700 }
701 let _ = fs::write(path.join("cgroup.freeze"), "0");
702 kill_cgroup(&path);
703 for _ in 0..LEFTOVER_POLLS {
704 if fs::remove_dir(&path).is_ok() || !path.exists() {
705 break;
706 }
707 std::thread::sleep(LEFTOVER_POLL);
708 }
709 }
710}
711
712/// Makes sure `dir` passes the job controllers on to its children.
713fn enable_controllers(dir: &Path) -> Result<(), String> {
714 let file = dir.join("cgroup.subtree_control");
715 let have =
716 fs::read_to_string(&file).map_err(|e| format!("cannot read {}: {e}", file.display()))?;
717 let missing: Vec<String> = CONTROLLERS
718 .iter()
719 .filter(|c| !have.split_whitespace().any(|h| h == **c))
720 .map(|c| format!("+{c}"))
721 .collect();
722 if missing.is_empty() {
723 return Ok(());
724 }
725 fs::write(&file, missing.join(" ")).map_err(|e| {
726 format!(
727 "cannot enable {} in {} (the controllers are not delegated): {e}",
728 missing.join(" "),
729 file.display()
730 )
731 })
732}
733
734// ----- the watcher -----
735
736/// The watcher thread and its channel. The thread blocks in `poll(2)` on the inotify fd, the PSI
737/// trigger and a stop pipe, with no timeout. Dropping the `Watcher` closes the write end of the
738/// stop pipe, which wakes the thread and ends it.
739struct Watcher {
740 rx: mpsc::UnboundedReceiver<Cause>,
741 psi_armed: bool,
742 _stop: OwnedFd,
743}
744
745impl Watcher {
746 fn open(box_dir: &Path) -> Result<Self, String> {
747 let inotify = Inotify::init(InitFlags::IN_NONBLOCK | InitFlags::IN_CLOEXEC)
748 .map_err(|e| format!("inotify: {e}"))?;
749 inotify
750 .add_watch(&box_dir.join("memory.events"), AddWatchFlags::IN_MODIFY)
751 .map_err(|e| format!("watching memory.events: {e}"))?;
752 // A new or removed job cgroup is how the controller learns where a job lives.
753 inotify
754 .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE)
755 .map_err(|e| format!("watching the box: {e}"))?;
756 let psi = match arm_psi(box_dir) {
757 Ok(file) => Some(file),
758 Err(e) => {
759 tracing::warn!("no PSI trigger on the box, using memory.events only: {e}");
760 None
761 }
762 };
763 let psi_armed = psi.is_some();
764 let (stop_rx, stop_tx) = pipe().map_err(|e| format!("stop pipe: {e}"))?;
765 let (tx, rx) = mpsc::unbounded_channel();
766 let events_path = box_dir.join("memory.events");
767 std::thread::Builder::new()
768 .name("forge-memory-watch".to_owned())
769 .spawn(move || watch_thread(&inotify, psi, &stop_rx, &events_path, &tx))
770 .map_err(|e| format!("watcher thread: {e}"))?;
771 Ok(Self {
772 rx,
773 psi_armed,
774 _stop: stop_tx,
775 })
776 }
777}
778
779fn watch_thread(
780 inotify: &Inotify,
781 mut psi: Option<File>,
782 stop: &OwnedFd,
783 events_path: &Path,
784 tx: &mpsc::UnboundedSender<Cause>,
785) {
786 let read_high = || fs::read_to_string(events_path).map(|t| parse_high(&t)).ok();
787 let mut last_high = read_high().unwrap_or(0);
788 loop {
789 let (stopped, inotify_ready, psi_ready, psi_broken) = {
790 let mut fds = vec![
791 PollFd::new(inotify.as_fd(), PollFlags::POLLIN),
792 PollFd::new(stop.as_fd(), PollFlags::POLLIN),
793 ];
794 if let Some(file) = &psi {
795 fds.push(PollFd::new(file.as_fd(), PollFlags::POLLPRI));
796 }
797 match poll(&mut fds, PollTimeout::NONE) {
798 Ok(_) => {}
799 Err(Errno::EINTR) => continue,
800 Err(e) => {
801 tracing::warn!("memory control stopped, poll failed: {e}");
802 return;
803 }
804 }
805 let flags = |i: usize| {
806 fds.get(i)
807 .and_then(PollFd::revents)
808 .unwrap_or_else(PollFlags::empty)
809 };
810 (
811 !flags(1).is_empty(),
812 flags(0).contains(PollFlags::POLLIN),
813 flags(2).contains(PollFlags::POLLPRI),
814 flags(2).intersects(PollFlags::POLLERR | PollFlags::POLLNVAL),
815 )
816 };
817 if stopped {
818 return;
819 }
820 let mut cause = None;
821 if inotify_ready {
822 let mut modified = false;
823 loop {
824 match inotify.read_events() {
825 Ok(batch) => {
826 modified |= batch
827 .iter()
828 .any(|e| e.mask.contains(AddWatchFlags::IN_MODIFY));
829 }
830 Err(Errno::EAGAIN) => break,
831 Err(e) => {
832 tracing::warn!("cannot read inotify events: {e}");
833 break;
834 }
835 }
836 }
837 let high = read_high().unwrap_or(last_high);
838 let moved = modified && high > last_high;
839 last_high = high;
840 cause = Some(if moved { Cause::Pressure } else { Cause::Jobs });
841 }
842 if psi_broken {
843 tracing::warn!("memory pressure trigger failed, using memory.events only");
844 psi = None;
845 } else if psi_ready {
846 cause = Some(Cause::Pressure);
847 }
848 if let Some(cause) = cause
849 && tx.send(cause).is_err()
850 {
851 return;
852 }
853 }
854}
855
856fn arm_psi(box_dir: &Path) -> io::Result<File> {
857 let mut file = OpenOptions::new()
858 .read(true)
859 .write(true)
860 .custom_flags(nix::libc::O_NONBLOCK)
861 .open(box_dir.join("memory.pressure"))?;
862 file.write_all(format!("{PSI_TRIGGER}\0").as_bytes())?;
863 Ok(file)
864}
865
866#[cfg(test)]
867mod tests {
868 use super::*;
869
870 const GIB: u64 = 1 << 30;
871
872 #[test]
873 fn parses_the_high_counter() {
874 let text = "low 0\nhigh 8\nmax 0\noom 0\noom_kill 0\n";
875 assert_eq!(parse_high(text), 8);
876 assert_eq!(parse_high("low 0\nmax 1\n"), 0);
877 assert_eq!(parse_high(""), 0);
878 assert_eq!(parse_high("high x\n"), 0);
879 }
880
881 #[test]
882 fn resize_follows_a_changed_budget() {
883 let (_tmp, pressure) = fake_box(2 * GIB);
884 fs::write(pressure.dir.join("memory.swap.max"), "0").expect("swap");
885 pressure.resize(3 * GIB);
886 assert_eq!(pressure.budget(), 3 * GIB);
887 assert_eq!(read_u64(&pressure.dir, "memory.max"), Some(3 * GIB));
888 assert_eq!(read_u64(&pressure.dir, "memory.swap.max"), Some(3 * GIB));
889 assert_eq!(pressure.lock().high, None);
890 }
891
892 #[test]
893 fn high_applies_only_to_two_or_more_unfrozen_jobs() {
894 assert_eq!(high_value(0, 6 * GIB), None);
895 assert_eq!(high_value(1, 6 * GIB), None);
896 // 5% of 6 GiB is under 512 MiB, so the minimum margin applies.
897 assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN));
898 // 5% of 20 GiB is 1 GiB.
899 assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB));
900 }
901
902 #[test]
903 fn victim_is_the_youngest_unfrozen_with_a_partner() {
904 let job = |seq, frozen| Running { seq, frozen };
905 assert_eq!(pick_victim(&[]), None);
906 assert_eq!(pick_victim(&[job(1, false)]), None);
907 assert_eq!(pick_victim(&[job(1, false), job(2, false)]), Some(1));
908 assert_eq!(
909 pick_victim(&[job(5, false), job(2, false), job(9, true)]),
910 Some(0)
911 );
912 // One unfrozen job left: nothing to pause.
913 assert_eq!(pick_victim(&[job(1, false), job(2, true)]), None);
914 }
915
916 #[test]
917 fn thaw_is_the_oldest_when_there_is_room_or_nothing_runs() {
918 let parked = [
919 Parked { seq: 7, swap: GIB },
920 Parked {
921 seq: 3,
922 swap: 2 * GIB,
923 },
924 ];
925 assert_eq!(pick_thaw(&[], 0, 10 * GIB), None);
926 // The oldest is index 1 and needs 2 GiB.
927 assert_eq!(pick_thaw(&parked, 1, 3 * GIB), Some(1));
928 assert_eq!(pick_thaw(&parked, 1, GIB), None);
929 // Nothing else runs: always thaw, whatever the headroom.
930 assert_eq!(pick_thaw(&parked, 0, 0), Some(1));
931 }
932
933 #[test]
934 fn gate_closes_for_parked_jobs_and_pressure() {
935 assert!(Gate::default().open());
936 assert!(
937 !Gate {
938 frozen: 1,
939 hot: false
940 }
941 .open()
942 );
943 assert!(
944 !Gate {
945 frozen: 0,
946 hot: true
947 }
948 .open()
949 );
950 // A pressure signal heats the box, a job event cools it unless it is still at high.
951 assert!(hot_after(Cause::Pressure, false, 1));
952 assert!(!hot_after(Cause::Jobs, false, 1));
953 assert!(hot_after(Cause::Jobs, true, 1));
954 assert!(!hot_after(Cause::Pressure, false, 0));
955 }
956
957 /// A fake box: a temp dir with the files the controller reads.
958 fn fake_box(budget: u64) -> (tempfile::TempDir, Arc<Pressure>) {
959 let tmp = tempfile::tempdir().expect("tempdir");
960 let dir = tmp.path().to_path_buf();
961 fs::write(dir.join("memory.max"), budget.to_string()).expect("max");
962 fs::write(dir.join("memory.current"), "0").expect("current");
963 (tmp, Arc::new(Pressure::at(dir, budget)))
964 }
965
966 fn fake_job(box_dir: &Path, id: &str, current: u64) -> PathBuf {
967 let dir = box_dir.join(format!("forge-job-{id}-1"));
968 fs::create_dir(&dir).expect("job dir");
969 fs::write(dir.join("memory.current"), current.to_string()).expect("current");
970 fs::write(dir.join("memory.stat"), format!("anon {current}\n")).expect("stat");
971 dir
972 }
973
974 #[test]
975 fn settle_sets_high_for_two_jobs_and_relaxes_it_for_one() {
976 let (tmp, pressure) = fake_box(6 * GIB);
977 let (tx, _rx) = mpsc::channel(8);
978 let a = pressure.register("a", "build", tx.clone());
979 let b = pressure.register("b", "test", tx);
980 fake_job(tmp.path(), "a", GIB);
981 fake_job(tmp.path(), "b", GIB);
982 pressure.settle(Cause::Jobs);
983 let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high");
984 assert_eq!(high, (6 * GIB - HIGH_MARGIN_MIN).to_string());
985 drop(b);
986 pressure.settle(Cause::Jobs);
987 let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high");
988 assert_eq!(high, "max");
989 assert!(!a.requeued());
990 }
991
992 #[test]
993 fn pressure_with_a_lone_job_does_nothing_but_close_the_gate() {
994 let (tmp, pressure) = fake_box(6 * GIB);
995 let (tx, mut rx) = mpsc::channel(8);
996 let a = pressure.register("a", "build", tx);
997 let dir = fake_job(tmp.path(), "a", GIB);
998 pressure.settle(Cause::Pressure);
999 assert!(!a.requeued());
1000 assert!(!dir.join("cgroup.freeze").exists());
1001 assert!(rx.try_recv().is_err());
1002 assert!(!pressure.lock().gate.open());
1003 // The job ending cools the box.
1004 drop(a);
1005 pressure.settle(Cause::Jobs);
1006 assert!(pressure.lock().gate.open());
1007 }
1008
1009 #[test]
1010 fn a_job_that_cannot_be_parked_is_killed_for_requeue() {
1011 // In a fake cgroup memory.current never drops, so parking fails the way a full swap does.
1012 let (tmp, pressure) = fake_box(6 * GIB);
1013 let (tx_a, _rx_a) = mpsc::channel(8);
1014 let (tx_b, mut rx_b) = mpsc::channel(8);
1015 let a = pressure.register("a", "build", tx_a);
1016 let b = pressure.register("b", "test", tx_b);
1017 fake_job(tmp.path(), "a", 2 * GIB);
1018 let dir_b = fake_job(tmp.path(), "b", 2 * GIB);
1019 // A tiny anon size, so the host's real SwapFree does not decide this test.
1020 fs::write(dir_b.join("memory.stat"), "anon 1\n").expect("stat");
1021 pressure.settle(Cause::Jobs);
1022 pressure.settle(Cause::Pressure);
1023 // The youngest job is the victim, the older one keeps running.
1024 assert!(b.requeued());
1025 assert!(!a.requeued());
1026 assert_eq!(
1027 fs::read_to_string(dir_b.join("cgroup.kill")).expect("kill"),
1028 "1"
1029 );
1030 let mut lines = String::new();
1031 while let Ok(bytes) = rx_b.try_recv() {
1032 lines.push_str(&String::from_utf8_lossy(&bytes));
1033 }
1034 assert!(lines.contains("paused: memory pressure, waiting for build"));
1035 assert!(lines.contains("run it again later"));
1036 // A killed job no longer counts as running, so memory.high relaxes.
1037 assert_eq!(
1038 fs::read_to_string(tmp.path().join("memory.high")).expect("high"),
1039 "max"
1040 );
1041 }
1042
1043 #[test]
1044 fn a_registration_tracks_pause_time_and_drops_its_log() {
1045 let (_tmp, pressure) = fake_box(GIB);
1046 let (tx, mut rx) = mpsc::channel(8);
1047 let reg = pressure.register("a", "build", tx);
1048 assert_eq!(reg.paused(), Duration::ZERO);
1049 reg.handle.pause();
1050 std::thread::sleep(Duration::from_millis(5));
1051 assert!(reg.paused() > Duration::ZERO);
1052 let lasted = reg.handle.resume();
1053 assert!(lasted > Duration::ZERO);
1054 assert!(reg.paused() >= lasted);
1055 drop(reg);
1056 // The sender is gone with the registration, so the log shipper can finish.
1057 assert!(matches!(
1058 rx.try_recv(),
1059 Err(mpsc::error::TryRecvError::Disconnected)
1060 ));
1061 }
1062
1063 #[test]
1064 fn create_box_enables_controllers_and_sets_limits() {
1065 let tmp = tempfile::tempdir().expect("tempdir");
1066 let parent = tmp.path();
1067 fs::write(parent.join("cgroup.subtree_control"), "memory pids\n").expect("parent");
1068 fs::create_dir(parent.join(BOX_NAME)).expect("box dir");
1069 fs::write(parent.join(BOX_NAME).join("cgroup.subtree_control"), "").expect("box");
1070 let dir = create_box(parent, 4 * GIB).expect("box");
1071 assert_eq!(dir, parent.join(BOX_NAME));
1072 // The fake files stand in for the kernel: the write replaced them with the new text.
1073 assert_eq!(
1074 fs::read_to_string(dir.join("memory.max")).expect("max"),
1075 (4 * GIB).to_string()
1076 );
1077 assert_eq!(
1078 fs::read_to_string(dir.join("memory.swap.max")).expect("swap"),
1079 (4 * GIB).to_string()
1080 );
1081 assert_eq!(
1082 fs::read_to_string(dir.join("memory.high")).expect("high"),
1083 "max"
1084 );
1085 assert_eq!(
1086 fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"),
1087 "+cpu"
1088 );
1089 // A second call adopts the existing box.
1090 assert!(create_box(parent, 4 * GIB).is_ok());
1091 }
1092
1093 #[tokio::test]
1094 async fn wait_open_returns_at_once_on_an_open_gate_and_wakes_on_change() {
1095 let (_tmp, pressure) = fake_box(GIB);
1096 pressure.wait_open().await;
1097 pressure.lock().gate.hot = true;
1098 let waiter = {
1099 let p = pressure.clone();
1100 tokio::spawn(async move { p.wait_open().await })
1101 };
1102 tokio::task::yield_now().await;
1103 assert!(!waiter.is_finished());
1104 pressure.lock().gate.hot = false;
1105 pressure.changed.notify_waiters();
1106 tokio::time::timeout(Duration::from_secs(5), waiter)
1107 .await
1108 .expect("woken")
1109 .expect("join");
1110 }
1111
1112 /// Needs a delegated memory controller, so it only runs on request:
1113 /// `cargo test -p forge-runner real_box -- --ignored`. Builds a real box next to this
1114 /// process, checks the watcher can arm inotify and the PSI trigger, and removes the box.
1115 #[tokio::test]
1116 #[ignore = "needs delegated cgroup v2 controllers"]
1117 async fn real_box_starts_and_reports_headroom() {
1118 let shutdown = CancellationToken::new();
1119 let Some(pressure) = Pressure::start(2 * GIB, shutdown.clone()).await else {
1120 eprintln!("no delegated memory controller, skipping");
1121 return;
1122 };
1123 assert!(pressure.headroom().is_some());
1124 pressure.wait_open().await;
1125 shutdown.cancel();
1126 // The watcher is gone once cancelled; the empty box can be removed.
1127 tokio::time::sleep(Duration::from_millis(100)).await;
1128 let _ = fs::remove_dir(&pressure.dir);
1129 }
1130
1131 /// Python allocator for the end-to-end test: waits for "go", touches `mib` MiB in 50 MiB
1132 /// steps, sleeps between steps, then re-reads everything and checks a checksum.
1133 const ALLOCATOR: &str = r#"
1134import sys, time, hashlib
1135mib = int(sys.argv[1]); step = 50
1136sys.stdin.readline()
1137chunks = []; sums = []
1138done = 0
1139while done < mib:
1140 n = min(step, mib - done)
1141 pat = bytes(((done + j * 7) % 251) for j in range(4096))
1142 c = bytearray(pat * (n * 256))
1143 chunks.append(c); sums.append(hashlib.sha256(c).hexdigest())
1144 done += n
1145 time.sleep(0.25)
1146# hold the memory for a while, then verify every chunk
1147time.sleep(float(sys.argv[2]))
1148for c, s in zip(chunks, sums):
1149 if hashlib.sha256(c).hexdigest() != s:
1150 print("CHECKSUM MISMATCH"); sys.exit(3)
1151print("ok")
1152"#;
1153
1154 fn mib(bytes: Option<u64>) -> u64 {
1155 bytes.unwrap_or(0) >> 20
1156 }
1157
1158 /// End to end on a real box: two allocators of ~700 MiB under a 1 GiB budget. The youngest is
1159 /// frozen and parked in swap, the first completes, the parked one thaws and completes with its
1160 /// data intact, and nothing is OOM-killed. Needs delegated cgroup controllers, swap and
1161 /// python3: `cargo test -p forge-runner real_two_jobs -- --ignored --nocapture`.
1162 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1163 #[ignore = "needs delegated cgroup v2 controllers, swap and python3"]
1164 async fn real_two_jobs_one_is_parked_in_swap_and_both_finish() {
1165 use std::process::Stdio;
1166 use tokio::io::AsyncWriteExt;
1167 use tokio::process::Command;
1168
1169 let started = Instant::now();
1170 let shutdown = CancellationToken::new();
1171 let Some(pressure) = Pressure::start(GIB, shutdown.clone()).await else {
1172 eprintln!("no delegated memory controller, skipping");
1173 return;
1174 };
1175 // The PSI trigger arms on the real box.
1176 let probe = Watcher::open(&pressure.dir).expect("watcher");
1177 let psi_armed = probe.psi_armed;
1178 drop(probe);
1179 eprintln!("PSI trigger armed: {psi_armed}");
1180 assert!(psi_armed, "PSI trigger must arm on this host");
1181
1182 let mut jobs = Vec::new();
1183 for (id, hold) in [("e2e1", "6"), ("e2e2", "1")] {
1184 let (tx, mut rx) = mpsc::channel::<Vec<u8>>(64);
1185 tokio::spawn(async move {
1186 while let Some(line) = rx.recv().await {
1187 eprint!("[log] {}", String::from_utf8_lossy(&line));
1188 }
1189 });
1190 let registration = pressure.register(id, id, tx);
1191 let dir = pressure.dir.join(format!("forge-job-{id}-1"));
1192 fs::create_dir(&dir).expect("job cgroup");
1193 fs::write(dir.join("memory.swap.max"), "0").expect("swap.max");
1194 let mut child = Command::new("python3")
1195 .args(["-I", "-c", ALLOCATOR, "700", hold])
1196 .stdin(Stdio::piped())
1197 .stdout(Stdio::piped())
1198 .kill_on_drop(true)
1199 .spawn()
1200 .expect("python3");
1201 let pid = child.id().expect("pid");
1202 fs::write(dir.join("cgroup.procs"), pid.to_string()).expect("join cgroup");
1203 let mut stdin = child.stdin.take().expect("stdin");
1204 stdin.write_all(b"go\n").await.expect("go");
1205 jobs.push((id, dir, child, Some(registration), stdin));
1206 // The second job starts a little later, so it is the youngest and the other has grown.
1207 tokio::time::sleep(Duration::from_secs(2)).await;
1208 }
1209
1210 // Watch both jobs until they end.
1211 let mut parked_seen = false;
1212 let mut before_park = 0;
1213 let mut at_park = (0, 0);
1214 let mut park_at = None;
1215 let mut thaw_at = None;
1216 let mut peak_box = 0;
1217 let mut results: Vec<Option<std::process::ExitStatus>> = vec![None, None];
1218 let deadline = Instant::now() + Duration::from_secs(150);
1219 while results.iter().any(Option::is_none) {
1220 assert!(Instant::now() < deadline, "jobs did not finish in time");
1221 let box_cur = read_u64(&pressure.dir, "memory.current").unwrap_or(0);
1222 peak_box = peak_box.max(box_cur);
1223 for (i, (id, dir, child, registration, _)) in jobs.iter_mut().enumerate() {
1224 if results[i].is_none()
1225 && let Some(status) = child.try_wait().expect("wait")
1226 {
1227 eprintln!("{} job {id} exited: {status}", started.elapsed().as_secs());
1228 results[i] = Some(status);
1229 // Like the runner: the finished job leaves the controller, which thaws the other.
1230 drop(registration.take());
1231 }
1232 if i == 1 && results[i].is_none() {
1233 let frozen = fs::read_to_string(dir.join("cgroup.events"))
1234 .is_ok_and(|t| t.contains("frozen 1"));
1235 let cur = read_u64(dir, "memory.current");
1236 if frozen && !parked_seen && mib(cur) < 350 {
1237 parked_seen = true;
1238 park_at = Some(Instant::now());
1239 at_park = (mib(cur), mib(job_swap(dir)));
1240 eprintln!(
1241 "{}s job2 parked: memory.current {} MiB, swap {} MiB (was {} MiB)",
1242 started.elapsed().as_secs(),
1243 at_park.0,
1244 at_park.1,
1245 before_park
1246 );
1247 }
1248 if !frozen && parked_seen && thaw_at.is_none() {
1249 thaw_at = Some(Instant::now());
1250 eprintln!("{}s job2 thawed", started.elapsed().as_secs());
1251 }
1252 if !frozen && !parked_seen {
1253 before_park = before_park.max(mib(cur));
1254 }
1255 }
1256 }
1257 tokio::time::sleep(Duration::from_millis(100)).await;
1258 }
1259 eprintln!(
1260 "peak box memory.current {} MiB, parked for {:?}",
1261 peak_box >> 20,
1262 park_at.zip(thaw_at).map(|(a, b)| b - a)
1263 );
1264
1265 let mut oom = Vec::new();
1266 for (id, dir, _, _, _) in &jobs {
1267 let events = fs::read_to_string(dir.join("memory.events")).unwrap_or_default();
1268 eprintln!("job {id} memory.events: {}", events.replace('\n', " "));
1269 if events
1270 .lines()
1271 .any(|l| l.starts_with("oom_kill ") && !l.ends_with(" 0"))
1272 {
1273 oom.push(id.to_string());
1274 }
1275 }
1276 let box_events = fs::read_to_string(pressure.dir.join("memory.events")).unwrap_or_default();
1277 eprintln!("box memory.events: {}", box_events.replace('\n', " "));
1278
1279 // Clean up before asserting, so a failure leaves no cgroups behind.
1280 shutdown.cancel();
1281 for (_, dir, mut child, registration, _) in jobs {
1282 let _ = child.start_kill();
1283 let _ = child.wait().await;
1284 drop(registration);
1285 for _ in 0..50 {
1286 if fs::remove_dir(&dir).is_ok() {
1287 break;
1288 }
1289 tokio::time::sleep(Duration::from_millis(50)).await;
1290 }
1291 }
1292 tokio::time::sleep(Duration::from_millis(200)).await;
1293 let _ = fs::remove_dir(&pressure.dir);
1294
1295 assert!(oom.is_empty(), "oom_kill in {oom:?}");
1296 assert!(parked_seen, "the youngest job was never parked in swap");
1297 assert!(
1298 at_park.1 > 100,
1299 "parked job holds {} MiB in swap",
1300 at_park.1
1301 );
1302 assert!(thaw_at.is_some(), "the parked job never thawed");
1303 for r in results {
1304 assert!(
1305 r.expect("exited").success(),
1306 "a job failed or its checksum broke"
1307 );
1308 }
1309 }
1310}