From c9518e06068fffdba84ce9f2bd187cff4b1d0e58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 21 Oct 2026 06:45:47 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20resize=20the=20memory=20box?= =?UTF-8?q?=20with=20the=20budget,=20poll-based=20safe=20watcher=20thread,?= =?UTF-8?q?=20e2e=20swap=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 2 +- crates/forge-runner/Cargo.toml | 2 +- crates/forge-runner/src/pressure.rs | 419 ++++++++++++++++++++++------ crates/forge-runner/src/runner.rs | 7 + 4 files changed, 340 insertions(+), 90 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d80f3d8..f04c116 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -101,7 +101,7 @@ hyper-util = { version = "0.1.21", features = ["tokio"] } libcontainer = { version = "0.7.0", default-features = false, features = ["v2"] } seccompiler = { version = "0.5.0", features = ["json"] } oci-spec = "0.10.0" -nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify"] } +nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify", "poll"] } # build and test grass = "0.13.4" diff --git a/crates/forge-runner/Cargo.toml b/crates/forge-runner/Cargo.toml index 538317b..424d922 100644 --- a/crates/forge-runner/Cargo.toml +++ b/crates/forge-runner/Cargo.toml @@ -11,7 +11,7 @@ publish = false test-host-executor = [] [dependencies] -clap = { workspace = true } +clap = { workspace = true, features = ["string"] } forge-ci.workspace = true reqwest = { workspace = true, features = ["json"] } serde = { workspace = true } diff --git a/crates/forge-runner/src/pressure.rs b/crates/forge-runner/src/pressure.rs index 8bde511..3b1e1f2 100644 --- a/crates/forge-runner/src/pressure.rs +++ b/crates/forge-runner/src/pressure.rs @@ -18,7 +18,7 @@ use std::fs::{self, File, OpenOptions}; use std::io::{self, Write}; -use std::os::fd::AsFd; +use std::os::fd::{AsFd, OwnedFd}; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -26,9 +26,9 @@ use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; use nix::errno::Errno; +use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; -use tokio::io::Interest; -use tokio::io::unix::AsyncFd; +use nix::unistd::pipe; use tokio::sync::{Notify, mpsc}; use tokio_util::sync::CancellationToken; @@ -239,7 +239,7 @@ struct State { /// The box and the controller of the jobs in it. pub struct Pressure { dir: PathBuf, - budget: u64, + budget: AtomicU64, state: Mutex, seq: AtomicU64, /// Wakes the watcher: a job registered or ended. @@ -291,7 +291,7 @@ impl Pressure { fn at(dir: PathBuf, budget: u64) -> Self { Self { dir, - budget, + budget: AtomicU64::new(budget), state: Mutex::new(State::default()), seq: AtomicU64::new(0), kick: Notify::new(), @@ -301,7 +301,29 @@ impl Pressure { /// The memory the box may use: the budget it was created with. pub fn budget(&self) -> u64 { - self.budget + self.budget.load(Ordering::SeqCst) + } + + /// Follows a changed memory budget: resizes the box's `memory.max` and `memory.swap.max` and + /// lets the controller recompute `memory.high`. Does nothing when the budget is the same. + /// Blocks while the kernel reclaims on a shrink, so call it off the async runtime. + pub fn resize(&self, budget: u64) { + if self.budget.swap(budget, Ordering::SeqCst) == budget { + return; + } + // Growing: raise max first. Shrinking: lower high first (it is recomputed below). + for file in ["memory.max", "memory.swap.max"] { + if let Err(e) = fs::write(self.dir.join(file), budget.to_string()) { + tracing::warn!("cannot resize {file} of the box: {e}"); + } + } + // Force the next pass to write memory.high for the new budget. + self.lock().high = None; + self.kick.notify_one(); + tracing::info!( + budget = %forge_ci::size::format_size(budget), + "memory box resized" + ); } fn lock(&self) -> MutexGuard<'_, State> { @@ -344,7 +366,7 @@ impl Pressure { /// Memory the box has left, counting reclaimable page cache as free. `None` when unreadable. pub fn headroom(&self) -> Option { - let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget); + let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget()); Some(max.saturating_sub(box_usage(&self.dir)?)) } @@ -362,55 +384,16 @@ impl Pressure { } } - async fn watch(self: Arc, watcher: Watcher, shutdown: CancellationToken) { - let Watcher { - inotify, - events, - mut psi, - } = watcher; - let mut last_high = fs::read_to_string(self.dir.join("memory.events")) - .map(|t| parse_high(&t)) - .unwrap_or(0); + async fn watch(self: Arc, mut watcher: Watcher, shutdown: CancellationToken) { loop { let cause = tokio::select! { () = shutdown.cancelled() => return, - ready = events.readable() => { - let mut guard = match ready { - Ok(guard) => guard, - Err(e) => { - tracing::warn!("memory control stopped, inotify failed: {e}"); - return; - } + cause = watcher.rx.recv() => { + let Some(cause) = cause else { + tracing::warn!("memory control stopped, the watcher thread ended"); + return; }; - let mut modified = false; - loop { - match inotify.read_events() { - Ok(batch) => { - modified |= batch - .iter() - .any(|e| e.mask.contains(AddWatchFlags::IN_MODIFY)); - } - Err(Errno::EAGAIN) => break, - Err(e) => { - tracing::warn!("cannot read inotify events: {e}"); - break; - } - } - } - guard.clear_ready(); - let high = fs::read_to_string(self.dir.join("memory.events")) - .map(|t| parse_high(&t)) - .unwrap_or(last_high); - let moved = modified && high > last_high; - last_high = high; - if moved { Cause::Pressure } else { Cause::Jobs } - } - fired = psi_fired(psi.as_ref()) => { - if !fired { - tracing::warn!("memory pressure trigger failed, using memory.events only"); - psi = None; - } - Cause::Pressure + cause } () = self.kick.notified() => Cause::Jobs, }; @@ -462,7 +445,7 @@ impl Pressure { self.thaw_one(&mut state); } let unfrozen = state.entries.iter().filter(|e| is_live(e)).count(); - let high = high_value(unfrozen, self.budget); + let high = high_value(unfrozen, self.budget()); if state.high != Some(high) { let text = high.map_or_else(|| "max".to_owned(), |b| b.to_string()); match fs::write(self.dir.join("memory.high"), text) { @@ -491,7 +474,13 @@ impl Pressure { }) .collect(); let running = state.entries.iter().filter(|e| is_live(e)).count(); - let headroom = self.headroom().unwrap_or(0); + // A thawed job starts touching its pages again, so it needs room below the level where + // `memory.high` would hold two jobs back, plus a margin to grow. Otherwise it would be + // parked again at once. + let below_high = high_value(running + 1, self.budget()).unwrap_or(0); + let headroom = box_usage(&self.dir) + .map_or(0, |usage| below_high.saturating_sub(usage)) + .saturating_sub(HIGH_MARGIN_MIN); let list: Vec = parked.iter().map(|(_, p)| *p).collect(); let Some(pick) = pick_thaw(&list, running, headroom) else { return; @@ -719,10 +708,13 @@ fn enable_controllers(dir: &Path) -> Result<(), String> { // ----- the watcher ----- +/// The watcher thread and its channel. The thread blocks in `poll(2)` on the inotify fd, the PSI +/// trigger and a stop pipe, with no timeout. Dropping the `Watcher` closes the write end of the +/// stop pipe, which wakes the thread and ends it. struct Watcher { - inotify: Inotify, - events: AsyncFd, - psi: Option>, + rx: mpsc::UnboundedReceiver, + psi_armed: bool, + _stop: OwnedFd, } impl Watcher { @@ -736,54 +728,114 @@ impl Watcher { inotify .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE) .map_err(|e| format!("watching the box: {e}"))?; - // A duplicate of the inotify fd: same instance, so readiness and reads agree. - let owned = inotify - .as_fd() - .try_clone_to_owned() - .map_err(|e| format!("inotify fd: {e}"))?; - // SAFETY: `owned` is an open fd that it keeps until the AsyncFd drops it, and - // `as_raw_fd` returns the same fd every time. - let events = unsafe { AsyncFd::register(owned) }.map_err(|e| format!("inotify fd: {e}"))?; let psi = match arm_psi(box_dir) { - Ok(fd) => Some(fd), + Ok(file) => Some(file), Err(e) => { tracing::warn!("no PSI trigger on the box, using memory.events only: {e}"); None } }; + let psi_armed = psi.is_some(); + let (stop_rx, stop_tx) = pipe().map_err(|e| format!("stop pipe: {e}"))?; + let (tx, rx) = mpsc::unbounded_channel(); + let events_path = box_dir.join("memory.events"); + std::thread::Builder::new() + .name("forge-memory-watch".to_owned()) + .spawn(move || watch_thread(&inotify, psi, &stop_rx, &events_path, &tx)) + .map_err(|e| format!("watcher thread: {e}"))?; Ok(Self { - inotify, - events, - psi, + rx, + psi_armed, + _stop: stop_tx, }) } } -fn arm_psi(box_dir: &Path) -> io::Result> { +fn watch_thread( + inotify: &Inotify, + mut psi: Option, + stop: &OwnedFd, + events_path: &Path, + tx: &mpsc::UnboundedSender, +) { + let read_high = || fs::read_to_string(events_path).map(|t| parse_high(&t)).ok(); + let mut last_high = read_high().unwrap_or(0); + loop { + let (stopped, inotify_ready, psi_ready, psi_broken) = { + let mut fds = vec![ + PollFd::new(inotify.as_fd(), PollFlags::POLLIN), + PollFd::new(stop.as_fd(), PollFlags::POLLIN), + ]; + if let Some(file) = &psi { + fds.push(PollFd::new(file.as_fd(), PollFlags::POLLPRI)); + } + match poll(&mut fds, PollTimeout::NONE) { + Ok(_) => {} + Err(Errno::EINTR) => continue, + Err(e) => { + tracing::warn!("memory control stopped, poll failed: {e}"); + return; + } + } + let flags = |i: usize| { + fds.get(i) + .and_then(PollFd::revents) + .unwrap_or_else(PollFlags::empty) + }; + ( + !flags(1).is_empty(), + flags(0).contains(PollFlags::POLLIN), + flags(2).contains(PollFlags::POLLPRI), + flags(2).intersects(PollFlags::POLLERR | PollFlags::POLLNVAL), + ) + }; + if stopped { + return; + } + let mut cause = None; + if inotify_ready { + let mut modified = false; + loop { + match inotify.read_events() { + Ok(batch) => { + modified |= batch + .iter() + .any(|e| e.mask.contains(AddWatchFlags::IN_MODIFY)); + } + Err(Errno::EAGAIN) => break, + Err(e) => { + tracing::warn!("cannot read inotify events: {e}"); + break; + } + } + } + let high = read_high().unwrap_or(last_high); + let moved = modified && high > last_high; + last_high = high; + cause = Some(if moved { Cause::Pressure } else { Cause::Jobs }); + } + if psi_broken { + tracing::warn!("memory pressure trigger failed, using memory.events only"); + psi = None; + } else if psi_ready { + cause = Some(Cause::Pressure); + } + if let Some(cause) = cause + && tx.send(cause).is_err() + { + return; + } + } +} + +fn arm_psi(box_dir: &Path) -> io::Result { let mut file = OpenOptions::new() .read(true) .write(true) .custom_flags(nix::libc::O_NONBLOCK) .open(box_dir.join("memory.pressure"))?; file.write_all(format!("{PSI_TRIGGER}\0").as_bytes())?; - // SAFETY: `file` is open and owns its fd until the AsyncFd drops it, and `as_raw_fd` returns - // the same fd every time. - unsafe { AsyncFd::register_with_interest(file, Interest::PRIORITY) }.map_err(io::Error::from) -} - -/// Resolves when the PSI trigger fires. Without a trigger it never resolves. `false` means the -/// trigger broke and the caller should stop waiting on it. -async fn psi_fired(psi: Option<&AsyncFd>) -> bool { - let Some(psi) = psi else { - return std::future::pending().await; - }; - match psi.ready(Interest::PRIORITY).await { - Ok(mut guard) => { - guard.clear_ready(); - true - } - Err(_) => false, - } + Ok(file) } #[cfg(test)] @@ -801,6 +853,17 @@ mod tests { assert_eq!(parse_high("high x\n"), 0); } + #[test] + fn resize_follows_a_changed_budget() { + let (_tmp, pressure) = fake_box(2 * GIB); + fs::write(pressure.dir.join("memory.swap.max"), "0").expect("swap"); + pressure.resize(3 * GIB); + assert_eq!(pressure.budget(), 3 * GIB); + assert_eq!(read_u64(&pressure.dir, "memory.max"), Some(3 * GIB)); + assert_eq!(read_u64(&pressure.dir, "memory.swap.max"), Some(3 * GIB)); + assert_eq!(pressure.lock().high, None); + } + #[test] fn high_applies_only_to_two_or_more_unfrozen_jobs() { assert_eq!(high_value(0, 6 * GIB), None); @@ -1038,4 +1101,184 @@ mod tests { tokio::time::sleep(Duration::from_millis(100)).await; let _ = fs::remove_dir(&pressure.dir); } + + /// Python allocator for the end-to-end test: waits for "go", touches `mib` MiB in 50 MiB + /// steps, sleeps between steps, then re-reads everything and checks a checksum. + const ALLOCATOR: &str = r#" +import sys, time, hashlib +mib = int(sys.argv[1]); step = 50 +sys.stdin.readline() +chunks = []; sums = [] +done = 0 +while done < mib: + n = min(step, mib - done) + pat = bytes(((done + j * 7) % 251) for j in range(4096)) + c = bytearray(pat * (n * 256)) + chunks.append(c); sums.append(hashlib.sha256(c).hexdigest()) + done += n + time.sleep(0.25) +# hold the memory for a while, then verify every chunk +time.sleep(float(sys.argv[2])) +for c, s in zip(chunks, sums): + if hashlib.sha256(c).hexdigest() != s: + print("CHECKSUM MISMATCH"); sys.exit(3) +print("ok") +"#; + + fn mib(bytes: Option) -> u64 { + bytes.unwrap_or(0) >> 20 + } + + /// End to end on a real box: two allocators of ~700 MiB under a 1 GiB budget. The youngest is + /// frozen and parked in swap, the first completes, the parked one thaws and completes with its + /// data intact, and nothing is OOM-killed. Needs delegated cgroup controllers, swap and + /// python3: `cargo test -p forge-runner real_two_jobs -- --ignored --nocapture`. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs delegated cgroup v2 controllers, swap and python3"] + async fn real_two_jobs_one_is_parked_in_swap_and_both_finish() { + use std::process::Stdio; + use tokio::io::AsyncWriteExt; + use tokio::process::Command; + + let started = Instant::now(); + let shutdown = CancellationToken::new(); + let Some(pressure) = Pressure::start(GIB, shutdown.clone()).await else { + eprintln!("no delegated memory controller, skipping"); + return; + }; + // The PSI trigger arms on the real box. + let probe = Watcher::open(&pressure.dir).expect("watcher"); + let psi_armed = probe.psi_armed; + drop(probe); + eprintln!("PSI trigger armed: {psi_armed}"); + assert!(psi_armed, "PSI trigger must arm on this host"); + + let mut jobs = Vec::new(); + for (id, hold) in [("e2e1", "6"), ("e2e2", "1")] { + let (tx, mut rx) = mpsc::channel::>(64); + tokio::spawn(async move { + while let Some(line) = rx.recv().await { + eprint!("[log] {}", String::from_utf8_lossy(&line)); + } + }); + let registration = pressure.register(id, id, tx); + let dir = pressure.dir.join(format!("forge-job-{id}-1")); + fs::create_dir(&dir).expect("job cgroup"); + fs::write(dir.join("memory.swap.max"), "0").expect("swap.max"); + let mut child = Command::new("python3") + .args(["-I", "-c", ALLOCATOR, "700", hold]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .expect("python3"); + let pid = child.id().expect("pid"); + fs::write(dir.join("cgroup.procs"), pid.to_string()).expect("join cgroup"); + let mut stdin = child.stdin.take().expect("stdin"); + stdin.write_all(b"go\n").await.expect("go"); + jobs.push((id, dir, child, Some(registration), stdin)); + // The second job starts a little later, so it is the youngest and the other has grown. + tokio::time::sleep(Duration::from_secs(2)).await; + } + + // Watch both jobs until they end. + let mut parked_seen = false; + let mut before_park = 0; + let mut at_park = (0, 0); + let mut park_at = None; + let mut thaw_at = None; + let mut peak_box = 0; + let mut results: Vec> = vec![None, None]; + let deadline = Instant::now() + Duration::from_secs(150); + while results.iter().any(Option::is_none) { + assert!(Instant::now() < deadline, "jobs did not finish in time"); + let box_cur = read_u64(&pressure.dir, "memory.current").unwrap_or(0); + peak_box = peak_box.max(box_cur); + for (i, (id, dir, child, registration, _)) in jobs.iter_mut().enumerate() { + if results[i].is_none() + && let Some(status) = child.try_wait().expect("wait") + { + eprintln!("{} job {id} exited: {status}", started.elapsed().as_secs()); + results[i] = Some(status); + // Like the runner: the finished job leaves the controller, which thaws the other. + drop(registration.take()); + } + if i == 1 && results[i].is_none() { + let frozen = fs::read_to_string(dir.join("cgroup.events")) + .is_ok_and(|t| t.contains("frozen 1")); + let cur = read_u64(dir, "memory.current"); + if frozen && !parked_seen && mib(cur) < 350 { + parked_seen = true; + park_at = Some(Instant::now()); + at_park = (mib(cur), mib(job_swap(dir))); + eprintln!( + "{}s job2 parked: memory.current {} MiB, swap {} MiB (was {} MiB)", + started.elapsed().as_secs(), + at_park.0, + at_park.1, + before_park + ); + } + if !frozen && parked_seen && thaw_at.is_none() { + thaw_at = Some(Instant::now()); + eprintln!("{}s job2 thawed", started.elapsed().as_secs()); + } + if !frozen && !parked_seen { + before_park = before_park.max(mib(cur)); + } + } + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + eprintln!( + "peak box memory.current {} MiB, parked for {:?}", + peak_box >> 20, + park_at.zip(thaw_at).map(|(a, b)| b - a) + ); + + let mut oom = Vec::new(); + for (id, dir, _, _, _) in &jobs { + let events = fs::read_to_string(dir.join("memory.events")).unwrap_or_default(); + eprintln!("job {id} memory.events: {}", events.replace('\n', " ")); + if events + .lines() + .any(|l| l.starts_with("oom_kill ") && !l.ends_with(" 0")) + { + oom.push(id.to_string()); + } + } + let box_events = fs::read_to_string(pressure.dir.join("memory.events")).unwrap_or_default(); + eprintln!("box memory.events: {}", box_events.replace('\n', " ")); + + // Clean up before asserting, so a failure leaves no cgroups behind. + shutdown.cancel(); + for (_, dir, mut child, registration, _) in jobs { + let _ = child.start_kill(); + let _ = child.wait().await; + drop(registration); + for _ in 0..50 { + if fs::remove_dir(&dir).is_ok() { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + tokio::time::sleep(Duration::from_millis(200)).await; + let _ = fs::remove_dir(&pressure.dir); + + assert!(oom.is_empty(), "oom_kill in {oom:?}"); + assert!(parked_seen, "the youngest job was never parked in swap"); + assert!( + at_park.1 > 100, + "parked job holds {} MiB in swap", + at_park.1 + ); + assert!(thaw_at.is_some(), "the parked job never thawed"); + for r in results { + assert!( + r.expect("exited").success(), + "a job failed or its checksum broke" + ); + } + } } diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index f6d465a..d185ab2 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -268,6 +268,13 @@ impl Runner { reply.memory_budget.as_deref(), reply.reserve_memory.as_deref(), ); + if let Some(pressure) = &self.pressure + && pressure.budget() != self.memory.budget() + { + let pressure = pressure.clone(); + let budget = self.memory.budget(); + let _ = tokio::task::spawn_blocking(move || pressure.resize(budget)).await; + } self.restart.observe(reply.restart); if updates.observe(reply.binary_sha256.as_deref()) && let Some(sha) = updates.pending()