Resize the memory box with the budget, poll-based safe watcher thread, e2e swap test
Browse files at this commitc9518e06068fffdba84ce9f2bd187cff4b1d0e58Parent: 197fa34- feat
- resize the memory box with the budget, poll-based safe watcher thread, e2e swap test
4 changed files +340 -90
- Cargo.toml +1 -1
- crates/forge-runner/Cargo.toml +1 -1
- crates/forge-runner/src/pressure.rs +331 -88
- crates/forge-runner/src/runner.rs +7 -0
Cargo.tomlmodified+1 -1
| @@ -101,7 +101,7 @@ hyper-util = { version = "0.1.21", features = ["tokio"] } | |||
| 101 | libcontainer = { version = "0.7.0", default-features = false, features = ["v2"] } | 101 | libcontainer = { version = "0.7.0", default-features = false, features = ["v2"] } |
| 102 | seccompiler = { version = "0.5.0", features = ["json"] } | 102 | seccompiler = { version = "0.5.0", features = ["json"] } |
| 103 | oci-spec = "0.10.0" | 103 | oci-spec = "0.10.0" |
| 104 | -nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify"] } | 104 | +nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify", "poll"] } |
| 105 | 105 | ||
| 106 | # build and test | 106 | # build and test |
| 107 | grass = "0.13.4" | 107 | grass = "0.13.4" |
crates/forge-runner/Cargo.tomlmodified+1 -1
| @@ -11,7 +11,7 @@ publish = false | |||
| 11 | test-host-executor = [] | 11 | test-host-executor = [] |
| 12 | 12 | ||
| 13 | [dependencies] | 13 | [dependencies] |
| 14 | -clap = { workspace = true } | 14 | +clap = { workspace = true, features = ["string"] } |
| 15 | forge-ci.workspace = true | 15 | forge-ci.workspace = true |
| 16 | reqwest = { workspace = true, features = ["json"] } | 16 | reqwest = { workspace = true, features = ["json"] } |
| 17 | serde = { workspace = true } | 17 | serde = { workspace = true } |
crates/forge-runner/src/pressure.rsmodified+331 -88
| @@ -18,7 +18,7 @@ | |||
| 18 | 18 | ||
| 19 | use std::fs::{self, File, OpenOptions}; | 19 | use std::fs::{self, File, OpenOptions}; |
| 20 | use std::io::{self, Write}; | 20 | use std::io::{self, Write}; |
| 21 | -use std::os::fd::AsFd; | 21 | +use std::os::fd::{AsFd, OwnedFd}; |
| 22 | use std::os::unix::fs::OpenOptionsExt; | 22 | use std::os::unix::fs::OpenOptionsExt; |
| 23 | use std::path::{Path, PathBuf}; | 23 | use std::path::{Path, PathBuf}; |
| 24 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | 24 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| @@ -26,9 +26,9 @@ use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; | |||
| 26 | use std::time::{Duration, Instant}; | 26 | use std::time::{Duration, Instant}; |
| 27 | 27 | ||
| 28 | use nix::errno::Errno; | 28 | use nix::errno::Errno; |
| 29 | +use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; | ||
| 29 | use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; | 30 | use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; |
| 30 | -use tokio::io::Interest; | 31 | +use nix::unistd::pipe; |
| 31 | -use tokio::io::unix::AsyncFd; | ||
| 32 | use tokio::sync::{Notify, mpsc}; | 32 | use tokio::sync::{Notify, mpsc}; |
| 33 | use tokio_util::sync::CancellationToken; | 33 | use tokio_util::sync::CancellationToken; |
| 34 | 34 | ||
| @@ -239,7 +239,7 @@ struct State { | |||
| 239 | /// The box and the controller of the jobs in it. | 239 | /// The box and the controller of the jobs in it. |
| 240 | pub struct Pressure { | 240 | pub struct Pressure { |
| 241 | dir: PathBuf, | 241 | dir: PathBuf, |
| 242 | - budget: u64, | 242 | + budget: AtomicU64, |
| 243 | state: Mutex<State>, | 243 | state: Mutex<State>, |
| 244 | seq: AtomicU64, | 244 | seq: AtomicU64, |
| 245 | /// Wakes the watcher: a job registered or ended. | 245 | /// Wakes the watcher: a job registered or ended. |
| @@ -291,7 +291,7 @@ impl Pressure { | |||
| 291 | fn at(dir: PathBuf, budget: u64) -> Self { | 291 | fn at(dir: PathBuf, budget: u64) -> Self { |
| 292 | Self { | 292 | Self { |
| 293 | dir, | 293 | dir, |
| 294 | - budget, | 294 | + budget: AtomicU64::new(budget), |
| 295 | state: Mutex::new(State::default()), | 295 | state: Mutex::new(State::default()), |
| 296 | seq: AtomicU64::new(0), | 296 | seq: AtomicU64::new(0), |
| 297 | kick: Notify::new(), | 297 | kick: Notify::new(), |
| @@ -301,7 +301,29 @@ impl Pressure { | |||
| 301 | 301 | ||
| 302 | /// The memory the box may use: the budget it was created with. | 302 | /// The memory the box may use: the budget it was created with. |
| 303 | pub fn budget(&self) -> u64 { | 303 | pub fn budget(&self) -> u64 { |
| 304 | - self.budget | 304 | + self.budget.load(Ordering::SeqCst) |
| 305 | + } | ||
| 306 | + | ||
| 307 | + /// Follows a changed memory budget: resizes the box's `memory.max` and `memory.swap.max` and | ||
| 308 | + /// lets the controller recompute `memory.high`. Does nothing when the budget is the same. | ||
| 309 | + /// Blocks while the kernel reclaims on a shrink, so call it off the async runtime. | ||
| 310 | + pub fn resize(&self, budget: u64) { | ||
| 311 | + if self.budget.swap(budget, Ordering::SeqCst) == budget { | ||
| 312 | + return; | ||
| 313 | + } | ||
| 314 | + // Growing: raise max first. Shrinking: lower high first (it is recomputed below). | ||
| 315 | + for file in ["memory.max", "memory.swap.max"] { | ||
| 316 | + if let Err(e) = fs::write(self.dir.join(file), budget.to_string()) { | ||
| 317 | + tracing::warn!("cannot resize {file} of the box: {e}"); | ||
| 318 | + } | ||
| 319 | + } | ||
| 320 | + // Force the next pass to write memory.high for the new budget. | ||
| 321 | + self.lock().high = None; | ||
| 322 | + self.kick.notify_one(); | ||
| 323 | + tracing::info!( | ||
| 324 | + budget = %forge_ci::size::format_size(budget), | ||
| 325 | + "memory box resized" | ||
| 326 | + ); | ||
| 305 | } | 327 | } |
| 306 | 328 | ||
| 307 | fn lock(&self) -> MutexGuard<'_, State> { | 329 | fn lock(&self) -> MutexGuard<'_, State> { |
| @@ -344,7 +366,7 @@ impl Pressure { | |||
| 344 | 366 | ||
| 345 | /// Memory the box has left, counting reclaimable page cache as free. `None` when unreadable. | 367 | /// Memory the box has left, counting reclaimable page cache as free. `None` when unreadable. |
| 346 | pub fn headroom(&self) -> Option<u64> { | 368 | pub fn headroom(&self) -> Option<u64> { |
| 347 | - let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget); | 369 | + let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget()); |
| 348 | Some(max.saturating_sub(box_usage(&self.dir)?)) | 370 | Some(max.saturating_sub(box_usage(&self.dir)?)) |
| 349 | } | 371 | } |
| 350 | 372 | ||
| @@ -362,55 +384,16 @@ impl Pressure { | |||
| 362 | } | 384 | } |
| 363 | } | 385 | } |
| 364 | 386 | ||
| 365 | - async fn watch(self: Arc<Self>, watcher: Watcher, shutdown: CancellationToken) { | 387 | + async fn watch(self: Arc<Self>, mut watcher: Watcher, shutdown: CancellationToken) { |
| 366 | - let Watcher { | ||
| 367 | - inotify, | ||
| 368 | - events, | ||
| 369 | - mut psi, | ||
| 370 | - } = watcher; | ||
| 371 | - let mut last_high = fs::read_to_string(self.dir.join("memory.events")) | ||
| 372 | - .map(|t| parse_high(&t)) | ||
| 373 | - .unwrap_or(0); | ||
| 374 | loop { | 388 | loop { |
| 375 | let cause = tokio::select! { | 389 | let cause = tokio::select! { |
| 376 | () = shutdown.cancelled() => return, | 390 | () = shutdown.cancelled() => return, |
| 377 | - ready = events.readable() => { | 391 | + cause = watcher.rx.recv() => { |
| 378 | - let mut guard = match ready { | 392 | + let Some(cause) = cause else { |
| 379 | - Ok(guard) => guard, | 393 | + tracing::warn!("memory control stopped, the watcher thread ended"); |
| 380 | - Err(e) => { | 394 | + return; |
| 381 | - tracing::warn!("memory control stopped, inotify failed: {e}"); | ||
| 382 | - return; | ||
| 383 | - } | ||
| 384 | }; | 395 | }; |
| 385 | - let mut modified = false; | 396 | + cause |
| 386 | - loop { | ||
| 387 | - match inotify.read_events() { | ||
| 388 | - Ok(batch) => { | ||
| 389 | - modified |= batch | ||
| 390 | - .iter() | ||
| 391 | - .any(|e| e.mask.contains(AddWatchFlags::IN_MODIFY)); | ||
| 392 | - } | ||
| 393 | - Err(Errno::EAGAIN) => break, | ||
| 394 | - Err(e) => { | ||
| 395 | - tracing::warn!("cannot read inotify events: {e}"); | ||
| 396 | - break; | ||
| 397 | - } | ||
| 398 | - } | ||
| 399 | - } | ||
| 400 | - guard.clear_ready(); | ||
| 401 | - let high = fs::read_to_string(self.dir.join("memory.events")) | ||
| 402 | - .map(|t| parse_high(&t)) | ||
| 403 | - .unwrap_or(last_high); | ||
| 404 | - let moved = modified && high > last_high; | ||
| 405 | - last_high = high; | ||
| 406 | - if moved { Cause::Pressure } else { Cause::Jobs } | ||
| 407 | - } | ||
| 408 | - fired = psi_fired(psi.as_ref()) => { | ||
| 409 | - if !fired { | ||
| 410 | - tracing::warn!("memory pressure trigger failed, using memory.events only"); | ||
| 411 | - psi = None; | ||
| 412 | - } | ||
| 413 | - Cause::Pressure | ||
| 414 | } | 397 | } |
| 415 | () = self.kick.notified() => Cause::Jobs, | 398 | () = self.kick.notified() => Cause::Jobs, |
| 416 | }; | 399 | }; |
| @@ -462,7 +445,7 @@ impl Pressure { | |||
| 462 | self.thaw_one(&mut state); | 445 | self.thaw_one(&mut state); |
| 463 | } | 446 | } |
| 464 | let unfrozen = state.entries.iter().filter(|e| is_live(e)).count(); | 447 | let unfrozen = state.entries.iter().filter(|e| is_live(e)).count(); |
| 465 | - let high = high_value(unfrozen, self.budget); | 448 | + let high = high_value(unfrozen, self.budget()); |
| 466 | if state.high != Some(high) { | 449 | if state.high != Some(high) { |
| 467 | let text = high.map_or_else(|| "max".to_owned(), |b| b.to_string()); | 450 | let text = high.map_or_else(|| "max".to_owned(), |b| b.to_string()); |
| 468 | match fs::write(self.dir.join("memory.high"), text) { | 451 | match fs::write(self.dir.join("memory.high"), text) { |
| @@ -491,7 +474,13 @@ impl Pressure { | |||
| 491 | }) | 474 | }) |
| 492 | .collect(); | 475 | .collect(); |
| 493 | let running = state.entries.iter().filter(|e| is_live(e)).count(); | 476 | let running = state.entries.iter().filter(|e| is_live(e)).count(); |
| 494 | - let headroom = self.headroom().unwrap_or(0); | 477 | + // A thawed job starts touching its pages again, so it needs room below the level where |
| 478 | + // `memory.high` would hold two jobs back, plus a margin to grow. Otherwise it would be | ||
| 479 | + // parked again at once. | ||
| 480 | + let below_high = high_value(running + 1, self.budget()).unwrap_or(0); | ||
| 481 | + let headroom = box_usage(&self.dir) | ||
| 482 | + .map_or(0, |usage| below_high.saturating_sub(usage)) | ||
| 483 | + .saturating_sub(HIGH_MARGIN_MIN); | ||
| 495 | let list: Vec<Parked> = parked.iter().map(|(_, p)| *p).collect(); | 484 | let list: Vec<Parked> = parked.iter().map(|(_, p)| *p).collect(); |
| 496 | let Some(pick) = pick_thaw(&list, running, headroom) else { | 485 | let Some(pick) = pick_thaw(&list, running, headroom) else { |
| 497 | return; | 486 | return; |
| @@ -719,10 +708,13 @@ fn enable_controllers(dir: &Path) -> Result<(), String> { | |||
| 719 | 708 | ||
| 720 | // ----- the watcher ----- | 709 | // ----- the watcher ----- |
| 721 | 710 | ||
| 711 | +/// The watcher thread and its channel. The thread blocks in `poll(2)` on the inotify fd, the PSI | ||
| 712 | +/// trigger and a stop pipe, with no timeout. Dropping the `Watcher` closes the write end of the | ||
| 713 | +/// stop pipe, which wakes the thread and ends it. | ||
| 722 | struct Watcher { | 714 | struct Watcher { |
| 723 | - inotify: Inotify, | 715 | + rx: mpsc::UnboundedReceiver<Cause>, |
| 724 | - events: AsyncFd<std::os::fd::OwnedFd>, | 716 | + psi_armed: bool, |
| 725 | - psi: Option<AsyncFd<File>>, | 717 | + _stop: OwnedFd, |
| 726 | } | 718 | } |
| 727 | 719 | ||
| 728 | impl Watcher { | 720 | impl Watcher { |
| @@ -736,54 +728,114 @@ impl Watcher { | |||
| 736 | inotify | 728 | inotify |
| 737 | .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE) | 729 | .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE) |
| 738 | .map_err(|e| format!("watching the box: {e}"))?; | 730 | .map_err(|e| format!("watching the box: {e}"))?; |
| 739 | - // A duplicate of the inotify fd: same instance, so readiness and reads agree. | ||
| 740 | - let owned = inotify | ||
| 741 | - .as_fd() | ||
| 742 | - .try_clone_to_owned() | ||
| 743 | - .map_err(|e| format!("inotify fd: {e}"))?; | ||
| 744 | - // SAFETY: `owned` is an open fd that it keeps until the AsyncFd drops it, and | ||
| 745 | - // `as_raw_fd` returns the same fd every time. | ||
| 746 | - let events = unsafe { AsyncFd::register(owned) }.map_err(|e| format!("inotify fd: {e}"))?; | ||
| 747 | let psi = match arm_psi(box_dir) { | 731 | let psi = match arm_psi(box_dir) { |
| 748 | - Ok(fd) => Some(fd), | 732 | + Ok(file) => Some(file), |
| 749 | Err(e) => { | 733 | Err(e) => { |
| 750 | tracing::warn!("no PSI trigger on the box, using memory.events only: {e}"); | 734 | tracing::warn!("no PSI trigger on the box, using memory.events only: {e}"); |
| 751 | None | 735 | None |
| 752 | } | 736 | } |
| 753 | }; | 737 | }; |
| 738 | + let psi_armed = psi.is_some(); | ||
| 739 | + let (stop_rx, stop_tx) = pipe().map_err(|e| format!("stop pipe: {e}"))?; | ||
| 740 | + let (tx, rx) = mpsc::unbounded_channel(); | ||
| 741 | + let events_path = box_dir.join("memory.events"); | ||
| 742 | + std::thread::Builder::new() | ||
| 743 | + .name("forge-memory-watch".to_owned()) | ||
| 744 | + .spawn(move || watch_thread(&inotify, psi, &stop_rx, &events_path, &tx)) | ||
| 745 | + .map_err(|e| format!("watcher thread: {e}"))?; | ||
| 754 | Ok(Self { | 746 | Ok(Self { |
| 755 | - inotify, | 747 | + rx, |
| 756 | - events, | 748 | + psi_armed, |
| 757 | - psi, | 749 | + _stop: stop_tx, |
| 758 | }) | 750 | }) |
| 759 | } | 751 | } |
| 760 | } | 752 | } |
| 761 | 753 | ||
| 762 | -fn arm_psi(box_dir: &Path) -> io::Result<AsyncFd<File>> { | 754 | +fn watch_thread( |
| 755 | + inotify: &Inotify, | ||
| 756 | + mut psi: Option<File>, | ||
| 757 | + stop: &OwnedFd, | ||
| 758 | + events_path: &Path, | ||
| 759 | + tx: &mpsc::UnboundedSender<Cause>, | ||
| 760 | +) { | ||
| 761 | + let read_high = || fs::read_to_string(events_path).map(|t| parse_high(&t)).ok(); | ||
| 762 | + let mut last_high = read_high().unwrap_or(0); | ||
| 763 | + loop { | ||
| 764 | + let (stopped, inotify_ready, psi_ready, psi_broken) = { | ||
| 765 | + let mut fds = vec![ | ||
| 766 | + PollFd::new(inotify.as_fd(), PollFlags::POLLIN), | ||
| 767 | + PollFd::new(stop.as_fd(), PollFlags::POLLIN), | ||
| 768 | + ]; | ||
| 769 | + if let Some(file) = &psi { | ||
| 770 | + fds.push(PollFd::new(file.as_fd(), PollFlags::POLLPRI)); | ||
| 771 | + } | ||
| 772 | + match poll(&mut fds, PollTimeout::NONE) { | ||
| 773 | + Ok(_) => {} | ||
| 774 | + Err(Errno::EINTR) => continue, | ||
| 775 | + Err(e) => { | ||
| 776 | + tracing::warn!("memory control stopped, poll failed: {e}"); | ||
| 777 | + return; | ||
| 778 | + } | ||
| 779 | + } | ||
| 780 | + let flags = |i: usize| { | ||
| 781 | + fds.get(i) | ||
| 782 | + .and_then(PollFd::revents) | ||
| 783 | + .unwrap_or_else(PollFlags::empty) | ||
| 784 | + }; | ||
| 785 | + ( | ||
| 786 | + !flags(1).is_empty(), | ||
| 787 | + flags(0).contains(PollFlags::POLLIN), | ||
| 788 | + flags(2).contains(PollFlags::POLLPRI), | ||
| 789 | + flags(2).intersects(PollFlags::POLLERR | PollFlags::POLLNVAL), | ||
| 790 | + ) | ||
| 791 | + }; | ||
| 792 | + if stopped { | ||
| 793 | + return; | ||
| 794 | + } | ||
| 795 | + let mut cause = None; | ||
| 796 | + if inotify_ready { | ||
| 797 | + let mut modified = false; | ||
| 798 | + loop { | ||
| 799 | + match inotify.read_events() { | ||
| 800 | + Ok(batch) => { | ||
| 801 | + modified |= batch | ||
| 802 | + .iter() | ||
| 803 | + .any(|e| e.mask.contains(AddWatchFlags::IN_MODIFY)); | ||
| 804 | + } | ||
| 805 | + Err(Errno::EAGAIN) => break, | ||
| 806 | + Err(e) => { | ||
| 807 | + tracing::warn!("cannot read inotify events: {e}"); | ||
| 808 | + break; | ||
| 809 | + } | ||
| 810 | + } | ||
| 811 | + } | ||
| 812 | + let high = read_high().unwrap_or(last_high); | ||
| 813 | + let moved = modified && high > last_high; | ||
| 814 | + last_high = high; | ||
| 815 | + cause = Some(if moved { Cause::Pressure } else { Cause::Jobs }); | ||
| 816 | + } | ||
| 817 | + if psi_broken { | ||
| 818 | + tracing::warn!("memory pressure trigger failed, using memory.events only"); | ||
| 819 | + psi = None; | ||
| 820 | + } else if psi_ready { | ||
| 821 | + cause = Some(Cause::Pressure); | ||
| 822 | + } | ||
| 823 | + if let Some(cause) = cause | ||
| 824 | + && tx.send(cause).is_err() | ||
| 825 | + { | ||
| 826 | + return; | ||
| 827 | + } | ||
| 828 | + } | ||
| 829 | +} | ||
| 830 | + | ||
| 831 | +fn arm_psi(box_dir: &Path) -> io::Result<File> { | ||
| 763 | let mut file = OpenOptions::new() | 832 | let mut file = OpenOptions::new() |
| 764 | .read(true) | 833 | .read(true) |
| 765 | .write(true) | 834 | .write(true) |
| 766 | .custom_flags(nix::libc::O_NONBLOCK) | 835 | .custom_flags(nix::libc::O_NONBLOCK) |
| 767 | .open(box_dir.join("memory.pressure"))?; | 836 | .open(box_dir.join("memory.pressure"))?; |
| 768 | file.write_all(format!("{PSI_TRIGGER}\0").as_bytes())?; | 837 | file.write_all(format!("{PSI_TRIGGER}\0").as_bytes())?; |
| 769 | - // SAFETY: `file` is open and owns its fd until the AsyncFd drops it, and `as_raw_fd` returns | 838 | + Ok(file) |
| 770 | - // the same fd every time. | ||
| 771 | - unsafe { AsyncFd::register_with_interest(file, Interest::PRIORITY) }.map_err(io::Error::from) | ||
| 772 | -} | ||
| 773 | - | ||
| 774 | -/// Resolves when the PSI trigger fires. Without a trigger it never resolves. `false` means the | ||
| 775 | -/// trigger broke and the caller should stop waiting on it. | ||
| 776 | -async fn psi_fired(psi: Option<&AsyncFd<File>>) -> bool { | ||
| 777 | - let Some(psi) = psi else { | ||
| 778 | - return std::future::pending().await; | ||
| 779 | - }; | ||
| 780 | - match psi.ready(Interest::PRIORITY).await { | ||
| 781 | - Ok(mut guard) => { | ||
| 782 | - guard.clear_ready(); | ||
| 783 | - true | ||
| 784 | - } | ||
| 785 | - Err(_) => false, | ||
| 786 | - } | ||
| 787 | } | 839 | } |
| 788 | 840 | ||
| 789 | #[cfg(test)] | 841 | #[cfg(test)] |
| @@ -801,6 +853,17 @@ mod tests { | |||
| 801 | assert_eq!(parse_high("high x\n"), 0); | 853 | assert_eq!(parse_high("high x\n"), 0); |
| 802 | } | 854 | } |
| 803 | 855 | ||
| 856 | + #[test] | ||
| 857 | + fn resize_follows_a_changed_budget() { | ||
| 858 | + let (_tmp, pressure) = fake_box(2 * GIB); | ||
| 859 | + fs::write(pressure.dir.join("memory.swap.max"), "0").expect("swap"); | ||
| 860 | + pressure.resize(3 * GIB); | ||
| 861 | + assert_eq!(pressure.budget(), 3 * GIB); | ||
| 862 | + assert_eq!(read_u64(&pressure.dir, "memory.max"), Some(3 * GIB)); | ||
| 863 | + assert_eq!(read_u64(&pressure.dir, "memory.swap.max"), Some(3 * GIB)); | ||
| 864 | + assert_eq!(pressure.lock().high, None); | ||
| 865 | + } | ||
| 866 | + | ||
| 804 | #[test] | 867 | #[test] |
| 805 | fn high_applies_only_to_two_or_more_unfrozen_jobs() { | 868 | fn high_applies_only_to_two_or_more_unfrozen_jobs() { |
| 806 | assert_eq!(high_value(0, 6 * GIB), None); | 869 | assert_eq!(high_value(0, 6 * GIB), None); |
| @@ -1038,4 +1101,184 @@ mod tests { | |||
| 1038 | tokio::time::sleep(Duration::from_millis(100)).await; | 1101 | tokio::time::sleep(Duration::from_millis(100)).await; |
| 1039 | let _ = fs::remove_dir(&pressure.dir); | 1102 | let _ = fs::remove_dir(&pressure.dir); |
| 1040 | } | 1103 | } |
| 1104 | + | ||
| 1105 | + /// Python allocator for the end-to-end test: waits for "go", touches `mib` MiB in 50 MiB | ||
| 1106 | + /// steps, sleeps between steps, then re-reads everything and checks a checksum. | ||
| 1107 | + const ALLOCATOR: &str = r#" | ||
| 1108 | +import sys, time, hashlib | ||
| 1109 | +mib = int(sys.argv[1]); step = 50 | ||
| 1110 | +sys.stdin.readline() | ||
| 1111 | +chunks = []; sums = [] | ||
| 1112 | +done = 0 | ||
| 1113 | +while done < mib: | ||
| 1114 | + n = min(step, mib - done) | ||
| 1115 | + pat = bytes(((done + j * 7) % 251) for j in range(4096)) | ||
| 1116 | + c = bytearray(pat * (n * 256)) | ||
| 1117 | + chunks.append(c); sums.append(hashlib.sha256(c).hexdigest()) | ||
| 1118 | + done += n | ||
| 1119 | + time.sleep(0.25) | ||
| 1120 | +# hold the memory for a while, then verify every chunk | ||
| 1121 | +time.sleep(float(sys.argv[2])) | ||
| 1122 | +for c, s in zip(chunks, sums): | ||
| 1123 | + if hashlib.sha256(c).hexdigest() != s: | ||
| 1124 | + print("CHECKSUM MISMATCH"); sys.exit(3) | ||
| 1125 | +print("ok") | ||
| 1126 | +"#; | ||
| 1127 | + | ||
| 1128 | + fn mib(bytes: Option<u64>) -> u64 { | ||
| 1129 | + bytes.unwrap_or(0) >> 20 | ||
| 1130 | + } | ||
| 1131 | + | ||
| 1132 | + /// End to end on a real box: two allocators of ~700 MiB under a 1 GiB budget. The youngest is | ||
| 1133 | + /// frozen and parked in swap, the first completes, the parked one thaws and completes with its | ||
| 1134 | + /// data intact, and nothing is OOM-killed. Needs delegated cgroup controllers, swap and | ||
| 1135 | + /// python3: `cargo test -p forge-runner real_two_jobs -- --ignored --nocapture`. | ||
| 1136 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 1137 | + #[ignore = "needs delegated cgroup v2 controllers, swap and python3"] | ||
| 1138 | + async fn real_two_jobs_one_is_parked_in_swap_and_both_finish() { | ||
| 1139 | + use std::process::Stdio; | ||
| 1140 | + use tokio::io::AsyncWriteExt; | ||
| 1141 | + use tokio::process::Command; | ||
| 1142 | + | ||
| 1143 | + let started = Instant::now(); | ||
| 1144 | + let shutdown = CancellationToken::new(); | ||
| 1145 | + let Some(pressure) = Pressure::start(GIB, shutdown.clone()).await else { | ||
| 1146 | + eprintln!("no delegated memory controller, skipping"); | ||
| 1147 | + return; | ||
| 1148 | + }; | ||
| 1149 | + // The PSI trigger arms on the real box. | ||
| 1150 | + let probe = Watcher::open(&pressure.dir).expect("watcher"); | ||
| 1151 | + let psi_armed = probe.psi_armed; | ||
| 1152 | + drop(probe); | ||
| 1153 | + eprintln!("PSI trigger armed: {psi_armed}"); | ||
| 1154 | + assert!(psi_armed, "PSI trigger must arm on this host"); | ||
| 1155 | + | ||
| 1156 | + let mut jobs = Vec::new(); | ||
| 1157 | + for (id, hold) in [("e2e1", "6"), ("e2e2", "1")] { | ||
| 1158 | + let (tx, mut rx) = mpsc::channel::<Vec<u8>>(64); | ||
| 1159 | + tokio::spawn(async move { | ||
| 1160 | + while let Some(line) = rx.recv().await { | ||
| 1161 | + eprint!("[log] {}", String::from_utf8_lossy(&line)); | ||
| 1162 | + } | ||
| 1163 | + }); | ||
| 1164 | + let registration = pressure.register(id, id, tx); | ||
| 1165 | + let dir = pressure.dir.join(format!("forge-job-{id}-1")); | ||
| 1166 | + fs::create_dir(&dir).expect("job cgroup"); | ||
| 1167 | + fs::write(dir.join("memory.swap.max"), "0").expect("swap.max"); | ||
| 1168 | + let mut child = Command::new("python3") | ||
| 1169 | + .args(["-I", "-c", ALLOCATOR, "700", hold]) | ||
| 1170 | + .stdin(Stdio::piped()) | ||
| 1171 | + .stdout(Stdio::piped()) | ||
| 1172 | + .kill_on_drop(true) | ||
| 1173 | + .spawn() | ||
| 1174 | + .expect("python3"); | ||
| 1175 | + let pid = child.id().expect("pid"); | ||
| 1176 | + fs::write(dir.join("cgroup.procs"), pid.to_string()).expect("join cgroup"); | ||
| 1177 | + let mut stdin = child.stdin.take().expect("stdin"); | ||
| 1178 | + stdin.write_all(b"go\n").await.expect("go"); | ||
| 1179 | + jobs.push((id, dir, child, Some(registration), stdin)); | ||
| 1180 | + // The second job starts a little later, so it is the youngest and the other has grown. | ||
| 1181 | + tokio::time::sleep(Duration::from_secs(2)).await; | ||
| 1182 | + } | ||
| 1183 | + | ||
| 1184 | + // Watch both jobs until they end. | ||
| 1185 | + let mut parked_seen = false; | ||
| 1186 | + let mut before_park = 0; | ||
| 1187 | + let mut at_park = (0, 0); | ||
| 1188 | + let mut park_at = None; | ||
| 1189 | + let mut thaw_at = None; | ||
| 1190 | + let mut peak_box = 0; | ||
| 1191 | + let mut results: Vec<Option<std::process::ExitStatus>> = vec![None, None]; | ||
| 1192 | + let deadline = Instant::now() + Duration::from_secs(150); | ||
| 1193 | + while results.iter().any(Option::is_none) { | ||
| 1194 | + assert!(Instant::now() < deadline, "jobs did not finish in time"); | ||
| 1195 | + let box_cur = read_u64(&pressure.dir, "memory.current").unwrap_or(0); | ||
| 1196 | + peak_box = peak_box.max(box_cur); | ||
| 1197 | + for (i, (id, dir, child, registration, _)) in jobs.iter_mut().enumerate() { | ||
| 1198 | + if results[i].is_none() | ||
| 1199 | + && let Some(status) = child.try_wait().expect("wait") | ||
| 1200 | + { | ||
| 1201 | + eprintln!("{} job {id} exited: {status}", started.elapsed().as_secs()); | ||
| 1202 | + results[i] = Some(status); | ||
| 1203 | + // Like the runner: the finished job leaves the controller, which thaws the other. | ||
| 1204 | + drop(registration.take()); | ||
| 1205 | + } | ||
| 1206 | + if i == 1 && results[i].is_none() { | ||
| 1207 | + let frozen = fs::read_to_string(dir.join("cgroup.events")) | ||
| 1208 | + .is_ok_and(|t| t.contains("frozen 1")); | ||
| 1209 | + let cur = read_u64(dir, "memory.current"); | ||
| 1210 | + if frozen && !parked_seen && mib(cur) < 350 { | ||
| 1211 | + parked_seen = true; | ||
| 1212 | + park_at = Some(Instant::now()); | ||
| 1213 | + at_park = (mib(cur), mib(job_swap(dir))); | ||
| 1214 | + eprintln!( | ||
| 1215 | + "{}s job2 parked: memory.current {} MiB, swap {} MiB (was {} MiB)", | ||
| 1216 | + started.elapsed().as_secs(), | ||
| 1217 | + at_park.0, | ||
| 1218 | + at_park.1, | ||
| 1219 | + before_park | ||
| 1220 | + ); | ||
| 1221 | + } | ||
| 1222 | + if !frozen && parked_seen && thaw_at.is_none() { | ||
| 1223 | + thaw_at = Some(Instant::now()); | ||
| 1224 | + eprintln!("{}s job2 thawed", started.elapsed().as_secs()); | ||
| 1225 | + } | ||
| 1226 | + if !frozen && !parked_seen { | ||
| 1227 | + before_park = before_park.max(mib(cur)); | ||
| 1228 | + } | ||
| 1229 | + } | ||
| 1230 | + } | ||
| 1231 | + tokio::time::sleep(Duration::from_millis(100)).await; | ||
| 1232 | + } | ||
| 1233 | + eprintln!( | ||
| 1234 | + "peak box memory.current {} MiB, parked for {:?}", | ||
| 1235 | + peak_box >> 20, | ||
| 1236 | + park_at.zip(thaw_at).map(|(a, b)| b - a) | ||
| 1237 | + ); | ||
| 1238 | + | ||
| 1239 | + let mut oom = Vec::new(); | ||
| 1240 | + for (id, dir, _, _, _) in &jobs { | ||
| 1241 | + let events = fs::read_to_string(dir.join("memory.events")).unwrap_or_default(); | ||
| 1242 | + eprintln!("job {id} memory.events: {}", events.replace('\n', " ")); | ||
| 1243 | + if events | ||
| 1244 | + .lines() | ||
| 1245 | + .any(|l| l.starts_with("oom_kill ") && !l.ends_with(" 0")) | ||
| 1246 | + { | ||
| 1247 | + oom.push(id.to_string()); | ||
| 1248 | + } | ||
| 1249 | + } | ||
| 1250 | + let box_events = fs::read_to_string(pressure.dir.join("memory.events")).unwrap_or_default(); | ||
| 1251 | + eprintln!("box memory.events: {}", box_events.replace('\n', " ")); | ||
| 1252 | + | ||
| 1253 | + // Clean up before asserting, so a failure leaves no cgroups behind. | ||
| 1254 | + shutdown.cancel(); | ||
| 1255 | + for (_, dir, mut child, registration, _) in jobs { | ||
| 1256 | + let _ = child.start_kill(); | ||
| 1257 | + let _ = child.wait().await; | ||
| 1258 | + drop(registration); | ||
| 1259 | + for _ in 0..50 { | ||
| 1260 | + if fs::remove_dir(&dir).is_ok() { | ||
| 1261 | + break; | ||
| 1262 | + } | ||
| 1263 | + tokio::time::sleep(Duration::from_millis(50)).await; | ||
| 1264 | + } | ||
| 1265 | + } | ||
| 1266 | + tokio::time::sleep(Duration::from_millis(200)).await; | ||
| 1267 | + let _ = fs::remove_dir(&pressure.dir); | ||
| 1268 | + | ||
| 1269 | + assert!(oom.is_empty(), "oom_kill in {oom:?}"); | ||
| 1270 | + assert!(parked_seen, "the youngest job was never parked in swap"); | ||
| 1271 | + assert!( | ||
| 1272 | + at_park.1 > 100, | ||
| 1273 | + "parked job holds {} MiB in swap", | ||
| 1274 | + at_park.1 | ||
| 1275 | + ); | ||
| 1276 | + assert!(thaw_at.is_some(), "the parked job never thawed"); | ||
| 1277 | + for r in results { | ||
| 1278 | + assert!( | ||
| 1279 | + r.expect("exited").success(), | ||
| 1280 | + "a job failed or its checksum broke" | ||
| 1281 | + ); | ||
| 1282 | + } | ||
| 1283 | + } | ||
| 1041 | } | 1284 | } |
crates/forge-runner/src/runner.rsmodified+7 -0
| @@ -268,6 +268,13 @@ impl Runner { | |||
| 268 | reply.memory_budget.as_deref(), | 268 | reply.memory_budget.as_deref(), |
| 269 | reply.reserve_memory.as_deref(), | 269 | reply.reserve_memory.as_deref(), |
| 270 | ); | 270 | ); |
| 271 | + if let Some(pressure) = &self.pressure | ||
| 272 | + && pressure.budget() != self.memory.budget() | ||
| 273 | + { | ||
| 274 | + let pressure = pressure.clone(); | ||
| 275 | + let budget = self.memory.budget(); | ||
| 276 | + let _ = tokio::task::spawn_blocking(move || pressure.resize(budget)).await; | ||
| 277 | + } | ||
| 271 | self.restart.observe(reply.restart); | 278 | self.restart.observe(reply.restart); |
| 272 | if updates.observe(reply.binary_sha256.as_deref()) | 279 | if updates.observe(reply.binary_sha256.as_deref()) |
| 273 | && let Some(sha) = updates.pending() | 280 | && let Some(sha) = updates.pending() |