diff --git a/.forge/ci.toml b/.forge/ci.toml index eb85025..4addd32 100644 --- a/.forge/ci.toml +++ b/.forge/ci.toml @@ -2,11 +2,10 @@ # # The workflow has no branch condition, so the build job also runs for pull requests. # test and build have no `needs` between them, so they run in parallel when runner capacity allows -# (two runners, or one runner with concurrency = 2). Capacity includes memory: each job declares its -# peak in `memory`, and a runner admits a job only while the declared memory of its running jobs -# fits its budget. On the 7.6 GiB runner host the budget is about 6.5 GiB, and test plus build -# declare 5g each, so they do NOT run together there: one heavy job at a time is the point. An -# earlier run with concurrency 4 hit a host-wide OOM and the kernel killed rustc mid-build. +# (two runners, or one runner with concurrency = 2). Memory is not declared: when two jobs together +# near the runner's memory budget, the runner pauses the younger one and parks it in swap until the +# other finishes (docs/ci.md, Memory). An earlier run with concurrency 4 hit a host-wide OOM and +# the kernel killed rustc mid-build. # The build job's artifacts are still only used # once the whole run is green: a tag push matching "v*" publishes a release with the build job's # binaries and SHA256SUMS, and self-update deploys dist/forge, only when every job in the run, @@ -21,8 +20,6 @@ tags = ["v*"] [jobs.test] image = "docker.io/library/rust:1" # Runner has a few GB RAM and 2 CPUs: rustc runs one crate at a time because a single forge-web compile needs several GB. Also drops debuginfo. -# memory: rustc peaked at 3.1 to 3.6 GB RSS in the OOM data. Jobs cannot swap, so 5g leaves room for cargo and the linker on top; only one heavy job fits the budget either way. -memory = "5g" env = { CARGO_BUILD_JOBS = "1", CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" } run = """ cargo test --workspace @@ -33,8 +30,6 @@ timeout_minutes = 120 [jobs.build] image = "docker.io/library/rust:1" # Runner has a few GB RAM and 2 CPUs: rustc runs one crate at a time because a single forge-web compile needs several GB. -# memory: the dist profile uses thin LTO, whose link step peaks like the test build (3.1 to 3.6 GB RSS seen). 5g for the same headroom reason. -memory = "5g" env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" } run = """ cargo build --profile dist -p forge-web -p forge-runner diff --git a/Cargo.toml b/Cargo.toml index c15ca24..d80f3d8 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"] } +nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify"] } # build and test grass = "0.13.4" diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index 6c1084f..e2d93f8 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -19,6 +19,7 @@ use crate::client::ForgeClient; use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode}; use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor}; use crate::oci::ImageStore; +use crate::pressure::Pressure; use crate::runner::{RunEnd, RunOptions, Runner}; use crate::sandbox::idmap::IdMap; use crate::update; @@ -226,6 +227,19 @@ async fn run(cli: Cli) -> Result> { let mut cfg = config::load(&path)?; sync_config_with_forge(&mut cfg).await; let shutdown = CancellationToken::new(); + // Only the builtin executor puts its jobs under the box. With the box, a lone job may + // use all of it, so an undeclared job's cgroup limit is the box budget. + let pressure = match cfg.executor { + ExecutorKind::Builtin => { + let budget = crate::memory::MemoryGate::for_host(&cfg.limits).budget(); + let pressure = Pressure::start(budget, shutdown.clone()).await; + if let Some(p) = &pressure { + cfg.limits.memory = p.budget().to_string(); + } + pressure + } + ExecutorKind::Podman => None, + }; let cache_root = cfg.work_dir.join(".cache"); let cache_cap = cfg.cache_max_gib; // The id map is what the executor's jobs run under. The cache removes its dirs with it. @@ -258,7 +272,8 @@ async fn run(cli: Cli) -> Result> { (Arc::new(executor), map) } }; - let mut runner = Runner::new(cfg, executor, RunOptions::default())?; + let mut runner = + Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure); if cache_cap > 0 { let cache = CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?); diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 1db2d71..8877082 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -7,9 +7,10 @@ use std::path::Path; use std::time::Duration; use forge_ci::proto::{ - BUILD_HEADER, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, - JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest, - RegisterResponse, RestartMode, RunnerConfigOverrides, RunnerConfigReport, + BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, + HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER, + RegisterRequest, RegisterResponse, RequeueRequest, RestartMode, RunnerConfigOverrides, + RunnerConfigReport, }; use reqwest::StatusCode; use reqwest::header::{CONTENT_LENGTH, HeaderMap}; @@ -145,7 +146,7 @@ impl ForgeClient { memory_bytes: host.memory_bytes, build: Some(forge_ci::build::display()), boot_id: Some(crate::restart::boot_id().to_owned()), - capabilities: vec![CAP_RESTART.to_owned()], + capabilities: vec![CAP_RESTART.to_owned(), CAP_REQUEUE.to_owned()], free_memory_bytes: memory.map(|m| m.free), memory_budget_bytes: memory.map(|m| m.budget), reserve_memory_bytes: memory.map(|m| m.reserve), @@ -357,6 +358,30 @@ impl ForgeClient { Err(status_error(resp).await) } } + + /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place. + pub async fn requeue( + &self, + job_id: &str, + job_token: &str, + reason: &str, + ) -> Result<(), ClientError> { + let resp = self + .http + .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/requeue"))) + .bearer_auth(job_token) + .json(&RequeueRequest { + reason: reason.to_owned(), + }) + .timeout(REQUEST_TIMEOUT) + .send() + .await?; + if resp.status().is_success() { + Ok(()) + } else { + Err(status_error(resp).await) + } + } } /// The `Forge-Binary-Sha256` header, trimmed and lowercased. An empty value counts as absent. diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index d09d684..96cde84 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -738,7 +738,7 @@ const REAP_POLLS: u32 = 50; /// Kills every process in a job cgroup. `cgroup.kill` does it in one write (Linux 5.14 and up). /// Older kernels get a SIGKILL to each pid in `cgroup.procs`. -fn kill_cgroup(dir: &Path) { +pub(crate) fn kill_cgroup(dir: &Path) { if fs::write(dir.join("cgroup.kill"), "1").is_ok() { return; } diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 89eb0ed..91b0aec 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -16,6 +16,7 @@ pub mod logs; pub mod memory; pub mod oci; pub mod oom; +pub mod pressure; pub mod restart; pub mod runner; pub mod sandbox; diff --git a/crates/forge-runner/src/pressure.rs b/crates/forge-runner/src/pressure.rs new file mode 100644 index 0000000..8bde511 --- /dev/null +++ b/crates/forge-runner/src/pressure.rs @@ -0,0 +1,1041 @@ +//! Reactive memory control. The runner puts every job cgroup inside one box cgroup +//! (`forge-jobs`) that is capped at the memory budget. When two or more jobs run and the box nears +//! its cap, the youngest job is frozen and its memory is pushed to swap, so the other job keeps +//! its RAM and nothing is OOM-killed. The parked job thaws when there is room again. When parking +//! does not work, the job is killed and queued again on the forge. A lone job is never paused: it +//! may use the whole box, and a real OOM there is reported as before (see [`crate::oom`]). +//! +//! Nothing here polls. The box's `memory.events` is watched with inotify (the `high` counter +//! moves the moment an allocation is held back by `memory.high`), the box's `memory.pressure` has +//! a PSI trigger as a second signal, and jobs starting and ending wake the controller too. +//! +//! `memory.high` is a brake that never lets go by itself: with swap off for the jobs, allocations +//! above it stall for minutes. So it is only set while 2+ jobs run unfrozen, and the controller +//! relaxes it the moment the stalled job is the only one left. +//! +//! The cgroup files are read and written through plain paths, so tests use a temp dir as a fake +//! cgroup. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; +use std::os::fd::AsFd; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +use nix::errno::Errno; +use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; +use tokio::io::Interest; +use tokio::io::unix::AsyncFd; +use tokio::sync::{Notify, mpsc}; +use tokio_util::sync::CancellationToken; + +use crate::executor::kill_cgroup; +use crate::sandbox::{BOX_NAME, job_cgroup_base}; + +/// Where cgroup2 is mounted. +const CGROUP_ROOT: &str = "/sys/fs/cgroup"; +/// The controllers jobs need, enabled on the box and on its parent. +const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"]; +/// The PSI trigger: 150 ms of stall in a 2 s window. Unprivileged users need a multiple of 2 s. +const PSI_TRIGGER: &str = "some 150000 2000000"; +/// `memory.high` sits below the box cap by the larger of this and 5% of the cap. +const HIGH_MARGIN_MIN: u64 = 512 << 20; +/// How hard a parked job's pages are pushed to swap. +const SWAPPINESS: u32 = 200; +/// How many reclaim writes to try on a frozen job. One write may reclaim only part of it. +const RECLAIM_ATTEMPTS: u32 = 4; +/// How long a leftover job cgroup from an earlier runner gets to die at startup. +const LEFTOVER_POLLS: u32 = 50; +const LEFTOVER_POLL: Duration = Duration::from_millis(100); + +/// What woke the controller. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cause { + /// The box is short of memory: `high` moved in `memory.events`, or the PSI trigger fired. + Pressure, + /// A job started or ended, or the box changed in a way that is no pressure signal. + Jobs, +} + +// ----- pure rules ----- + +/// The `high` counter of a `memory.events` text. Missing means 0. +pub fn parse_high(text: &str) -> u64 { + text.lines() + .find_map(|line| { + let (key, value) = line.split_once(' ')?; + (key == "high").then(|| value.trim().parse().ok())? + }) + .unwrap_or(0) +} + +/// `memory.high` of the box, or `None` for `max`. Only set while two or more jobs run unfrozen: +/// a lone job runs up to the box's `memory.max`. +pub fn high_value(unfrozen: usize, budget: u64) -> Option { + if unfrozen < 2 { + return None; + } + let margin = HIGH_MARGIN_MIN.max(budget / 20); + Some(budget.saturating_sub(margin)) +} + +/// A running job, as far as victim choice cares. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Running { + /// Start order: higher is younger. + pub seq: u64, + pub frozen: bool, +} + +/// The job to park: the youngest unfrozen one, and only while at least two are unfrozen. +pub fn pick_victim(jobs: &[Running]) -> Option { + let unfrozen = || jobs.iter().enumerate().filter(|(_, j)| !j.frozen); + if unfrozen().count() < 2 { + return None; + } + unfrozen().max_by_key(|(_, j)| j.seq).map(|(i, _)| i) +} + +/// A parked job, as far as thaw choice cares. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Parked { + pub seq: u64, + /// Bytes of the job that sit in swap. + pub swap: u64, +} + +/// The parked job to thaw: the oldest, once the box has room for what is in its swap or nothing +/// else runs. +pub fn pick_thaw(parked: &[Parked], unfrozen_running: usize, headroom: u64) -> Option { + let (index, oldest) = parked.iter().enumerate().min_by_key(|(_, p)| p.seq)?; + (unfrozen_running == 0 || headroom >= oldest.swap).then_some(index) +} + +/// Whether the box is marked as under pressure after a pass. Pressure signals set it. Any other +/// wake clears it, unless the box still sits at `memory.high`. +pub fn hot_after(cause: Cause, over_high: bool) -> bool { + cause == Cause::Pressure || over_high +} + +/// The admission gate: the runner claims a new job only while it is open. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Gate { + pub frozen: usize, + pub hot: bool, +} + +impl Gate { + pub fn open(&self) -> bool { + self.frozen == 0 && !self.hot + } +} + +// ----- the jobs the controller knows ----- + +#[derive(Default)] +struct PauseClock { + total: Duration, + since: Option, +} + +/// One registered job, shared between its runner task and the controller. +pub struct JobHandle { + id: String, + name: String, + log: Mutex>>>, + requeued: AtomicBool, + clock: Mutex, +} + +impl JobHandle { + /// Appends a line to the job's log. A full or closed log drops it. + fn log_line(&self, line: &str) { + let guard = self.log.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(tx) = guard.as_ref() { + let mut bytes = format!("runner: {line}").into_bytes(); + bytes.push(b'\n'); + let _ = tx.try_send(bytes); + } + } + + /// How long the job has spent frozen so far. + pub fn paused(&self) -> Duration { + let clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); + clock.total + clock.since.map(|s| s.elapsed()).unwrap_or_default() + } + + fn pause(&self) { + let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); + clock.since.get_or_insert_with(Instant::now); + } + + /// Ends a pause and returns how long it lasted. + fn resume(&self) -> Duration { + let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); + let lasted = clock.since.take().map(|s| s.elapsed()).unwrap_or_default(); + clock.total += lasted; + lasted + } +} + +/// A job's registration. Dropping it takes the job out of the controller's view. +pub struct Registration { + handle: Arc, + owner: Arc, +} + +impl Registration { + /// True when the controller killed the job to give it back to the queue. + pub fn requeued(&self) -> bool { + self.handle.requeued.load(Ordering::SeqCst) + } + + /// How long the job has spent frozen so far. Its timeout does not count that time. + pub fn paused(&self) -> Duration { + self.handle.paused() + } + + /// A handle for reading [`Registration::paused`] from another task. + pub fn pause_clock(&self) -> Arc { + self.handle.clone() + } +} + +impl Drop for Registration { + fn drop(&mut self) { + // The log sender must go now, or the log shipper would wait for it. + *self + .handle + .log + .lock() + .unwrap_or_else(PoisonError::into_inner) = None; + self.owner.remove(&self.handle); + } +} + +struct Entry { + handle: Arc, + seq: u64, + /// The job's cgroup, once the sandbox has created it. + dir: Option, + frozen: Option, +} + +struct Frozen { + swap: u64, +} + +#[derive(Default)] +struct State { + entries: Vec, + gate: Gate, + /// The `memory.high` last written, to skip repeated writes. + high: Option>, +} + +/// The box and the controller of the jobs in it. +pub struct Pressure { + dir: PathBuf, + budget: u64, + state: Mutex, + seq: AtomicU64, + /// Wakes the watcher: a job registered or ended. + kick: Notify, + /// Wakes the claim loop: the gate may have changed. + changed: Notify, +} + +impl Pressure { + /// Creates the box and starts the watcher. Returns `None`, after one log line, when the host + /// can't do it: cgroup controllers not delegated, no inotify, and so on. The runner then + /// works as before, without the box and without pausing. + pub async fn start(budget: u64, shutdown: CancellationToken) -> Option> { + let setup = tokio::task::spawn_blocking(move || { + let base = job_cgroup_base().map_err(|e| e.to_string())?; + let parent = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); + create_box(&parent, budget) + }) + .await; + let dir = match setup { + Ok(Ok(dir)) => dir, + Ok(Err(e)) => { + tracing::warn!("memory control is off: {e}"); + return None; + } + Err(e) => { + tracing::warn!("memory control is off: {e}"); + return None; + } + }; + let this = Arc::new(Self::at(dir, budget)); + match Watcher::open(&this.dir) { + Ok(watcher) => { + tokio::spawn(this.clone().watch(watcher, shutdown)); + tracing::info!( + box_dir = %this.dir.display(), + budget = %forge_ci::size::format_size(budget), + "memory control is on" + ); + Some(this) + } + Err(e) => { + tracing::warn!("memory control is off, cannot watch the box: {e}"); + None + } + } + } + + fn at(dir: PathBuf, budget: u64) -> Self { + Self { + dir, + budget, + state: Mutex::new(State::default()), + seq: AtomicU64::new(0), + kick: Notify::new(), + changed: Notify::new(), + } + } + + /// The memory the box may use: the budget it was created with. + pub fn budget(&self) -> u64 { + self.budget + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Puts a job under control. `log` receives the pause and resume lines. + pub fn register( + self: &Arc, + job_id: &str, + job_name: &str, + log: mpsc::Sender>, + ) -> Registration { + let handle = Arc::new(JobHandle { + id: job_id.to_owned(), + name: job_name.to_owned(), + log: Mutex::new(Some(log)), + requeued: AtomicBool::new(false), + clock: Mutex::new(PauseClock::default()), + }); + self.lock().entries.push(Entry { + handle: handle.clone(), + seq: self.seq.fetch_add(1, Ordering::SeqCst), + dir: None, + frozen: None, + }); + self.kick.notify_one(); + Registration { + handle, + owner: self.clone(), + } + } + + fn remove(&self, handle: &Arc) { + self.lock() + .entries + .retain(|e| !Arc::ptr_eq(&e.handle, handle)); + self.kick.notify_one(); + } + + /// 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); + Some(max.saturating_sub(box_usage(&self.dir)?)) + } + + /// Resolves once the runner may claim: no job is parked and the box is not under pressure. + /// Woken by the controller, never by a timer. + pub async fn wait_open(&self) { + loop { + let notified = self.changed.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if self.lock().gate.open() { + return; + } + notified.await; + } + } + + 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); + 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; + } + }; + 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 + } + () = self.kick.notified() => Cause::Jobs, + }; + let this = self.clone(); + if let Err(e) = tokio::task::spawn_blocking(move || this.settle(cause)).await { + tracing::error!("memory control pass panicked: {e}"); + } + } + } + + /// One pass: park a job if the box is short of memory, thaw one if there is room, and set + /// `memory.high` for what runs now. Blocks, so it runs off the async runtime. + fn settle(&self, cause: Cause) { + let mut state = self.lock(); + for entry in &mut state.entries { + if entry.dir.is_none() + && let Some(dir) = find_job_dir(&self.dir, &entry.handle.id) + { + // A real OOM then takes the whole job, not one of its processes. + let _ = fs::write(dir.join("memory.oom.group"), "1"); + entry.dir = Some(dir); + } + } + let mut parked_now = false; + if cause == Cause::Pressure { + let live: Vec = (0..state.entries.len()) + .filter(|&i| is_live(&state.entries[i])) + .collect(); + let running: Vec = live + .iter() + .map(|&i| Running { + seq: state.entries[i].seq, + frozen: false, + }) + .collect(); + if let Some(pick) = pick_victim(&running) { + let victim = live[pick]; + let waiting_for = live + .iter() + .filter(|&&i| i != victim) + .min_by_key(|&&i| state.entries[i].seq) + .map(|&i| state.entries[i].handle.name.clone()) + .unwrap_or_default(); + park(&mut state.entries[victim], &waiting_for); + parked_now = true; + } + } + if !parked_now { + self.thaw_one(&mut state); + } + let unfrozen = state.entries.iter().filter(|e| is_live(e)).count(); + 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) { + Ok(()) => state.high = Some(high), + Err(e) => tracing::warn!("cannot set memory.high of the box: {e}"), + } + } + let over_high = high.is_some_and(|h| box_usage(&self.dir).is_some_and(|u| u >= h)); + state.gate = Gate { + frozen: state.entries.iter().filter(|e| e.frozen.is_some()).count(), + hot: hot_after(cause, over_high), + }; + drop(state); + self.changed.notify_waiters(); + } + + fn thaw_one(&self, state: &mut State) { + let parked: Vec<(usize, Parked)> = state + .entries + .iter() + .enumerate() + .filter_map(|(i, e)| { + let frozen = e.frozen.as_ref()?; + let swap = e.dir.as_deref().and_then(job_swap).unwrap_or(frozen.swap); + Some((i, Parked { seq: e.seq, swap })) + }) + .collect(); + let running = state.entries.iter().filter(|e| is_live(e)).count(); + let headroom = self.headroom().unwrap_or(0); + let list: Vec = parked.iter().map(|(_, p)| *p).collect(); + let Some(pick) = pick_thaw(&list, running, headroom) else { + return; + }; + let entry = &mut state.entries[parked[pick].0]; + let Some(dir) = entry.dir.clone() else { + return; + }; + // Swap stays where it is. Nothing new goes out, and pages come back as the job touches them. + let _ = fs::write(dir.join("memory.swap.max"), "0"); + if let Err(e) = fs::write(dir.join("cgroup.freeze"), "0") { + tracing::warn!(job_id = %entry.handle.id, "cannot thaw job: {e}"); + return; + } + entry.frozen = None; + let lasted = entry.handle.resume(); + entry + .handle + .log_line(&format!("resumed after {}", format_duration(lasted))); + tracing::info!(job_id = %entry.handle.id, "job resumed"); + } +} + +/// Whether the entry counts as running and unfrozen: it has a cgroup, is not parked and was not +/// killed for requeueing. +fn is_live(entry: &Entry) -> bool { + entry.dir.is_some() && entry.frozen.is_none() && !entry.handle.requeued.load(Ordering::SeqCst) +} + +/// Freezes the job and pushes its memory to swap. When that does not work, kills the job so the +/// forge queues it again. +fn park(entry: &mut Entry, waiting_for: &str) { + let Some(dir) = entry.dir.clone() else { + return; + }; + let handle = entry.handle.clone(); + let before = read_u64(&dir, "memory.current").unwrap_or(0); + let anon = stat_field(&dir, "anon").unwrap_or(before); + let swap_free = swap_free_bytes(); + if swap_free.is_some_and(|free| free < anon) { + give_back(entry, "the host has no swap room for it"); + return; + } + // The job's own cgroup may swap now. Its swap.max was 0 so it never swapped by itself. + let _ = fs::write(dir.join("memory.swap.max"), "max"); + if let Err(e) = fs::write(dir.join("cgroup.freeze"), "1") { + tracing::warn!(job_id = %handle.id, "cannot freeze job: {e}"); + give_back(entry, "it cannot be frozen"); + return; + } + handle.pause(); + handle.log_line(&format!( + "paused: memory pressure, waiting for {waiting_for}" + )); + let mut after = before; + for _ in 0..RECLAIM_ATTEMPTS { + reclaim(&dir, before); + after = read_u64(&dir, "memory.current").unwrap_or(before); + if after <= before / 2 { + break; + } + } + if after > before / 2 { + let _ = fs::write(dir.join("cgroup.freeze"), "0"); + handle.resume(); + give_back(entry, "its memory would not go to swap"); + return; + } + let swap = job_swap(&dir).unwrap_or(0); + handle.log_line(&format!("parked {} MiB in swap", swap >> 20)); + tracing::info!(job_id = %handle.id, swap, "job parked in swap"); + entry.frozen = Some(Frozen { swap }); +} + +/// Writes the reclaim request. A rejected `swappiness` key falls back to the plain amount. The +/// return code is not trusted: EAGAIN comes back on success too, so callers read `memory.current`. +fn reclaim(dir: &Path, bytes: u64) { + let file = dir.join("memory.reclaim"); + match fs::write(&file, format!("{bytes} swappiness={SWAPPINESS}")) { + Err(e) if e.kind() == io::ErrorKind::InvalidInput => { + let _ = fs::write(&file, bytes.to_string()); + } + _ => {} + } +} + +/// Kills the job and marks it for requeueing. The job's task sees the mark and queues it again +/// instead of reporting a result. +fn give_back(entry: &mut Entry, why: &str) { + entry.handle.requeued.store(true, Ordering::SeqCst); + entry.handle.log_line(&format!( + "memory pressure and {why}: stopping this job to run it again later" + )); + tracing::warn!(job_id = %entry.handle.id, "{why}, killing job to requeue it"); + if let Some(dir) = &entry.dir { + // A frozen cgroup is killed too, but thaw first so the kill takes effect at once. + let _ = fs::write(dir.join("cgroup.freeze"), "0"); + kill_cgroup(dir); + } +} + +// ----- cgroup files ----- + +/// The job's cgroup under the box: `forge-job--`. +fn find_job_dir(box_dir: &Path, job_id: &str) -> Option { + let prefix = format!("forge-job-{job_id}-"); + fs::read_dir(box_dir) + .ok()? + .flatten() + .find(|e| e.file_name().to_string_lossy().starts_with(&prefix)) + .map(|e| e.path()) +} + +/// A single-number cgroup file. `None` when missing or `max`. +fn read_u64(dir: &Path, file: &str) -> Option { + fs::read_to_string(dir.join(file)).ok()?.trim().parse().ok() +} + +fn stat_field(dir: &Path, key: &str) -> Option { + let text = fs::read_to_string(dir.join("memory.stat")).ok()?; + text.lines().find_map(|line| { + let (k, v) = line.split_once(' ')?; + (k == key).then(|| v.trim().parse().ok())? + }) +} + +fn job_swap(dir: &Path) -> Option { + read_u64(dir, "memory.swap.current") +} + +/// What the box really holds: its charge minus inactive page cache, which the kernel gives up +/// first. `None` when the charge is unreadable. +fn box_usage(dir: &Path) -> Option { + let current = read_u64(dir, "memory.current")?; + Some(current.saturating_sub(stat_field(dir, "inactive_file").unwrap_or(0))) +} + +/// `SwapFree` of `/proc/meminfo` in bytes. +fn swap_free_bytes() -> Option { + let text = fs::read_to_string("/proc/meminfo").ok()?; + let line = text.lines().find(|l| l.starts_with("SwapFree:"))?; + line.split_whitespace() + .nth(1)? + .parse::() + .ok()? + .checked_mul(1024) +} + +fn format_duration(d: Duration) -> String { + let secs = d.as_secs(); + if secs >= 60 { + format!("{}m {}s", secs / 60, secs % 60) + } else { + format!("{secs}s") + } +} + +// ----- the box ----- + +/// Creates or adopts the box under `parent`, enables the controllers, and sets its limits. Job +/// cgroups left by a runner that died are killed and removed. Returns the box directory. +pub fn create_box(parent: &Path, budget: u64) -> Result { + let dir = parent.join(BOX_NAME); + match fs::create_dir(&dir) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(format!("cannot create {}: {e}", dir.display())), + } + remove_leftovers(&dir); + enable_controllers(parent)?; + enable_controllers(&dir)?; + let set = |file: &str, value: String| { + fs::write(dir.join(file), value).map_err(|e| format!("cannot set {file} on the box: {e}")) + }; + set("memory.max", budget.to_string())?; + // Only a parked job swaps, and its own swap.max says when. The box allows it. + set("memory.swap.max", budget.to_string())?; + set("memory.high", "max".to_owned())?; + Ok(dir) +} + +/// Kills and removes the job cgroups a previous runner left in the box. Frozen ones are thawed +/// first, or the kill would wait for them. +fn remove_leftovers(box_dir: &Path) { + let Ok(children) = fs::read_dir(box_dir) else { + return; + }; + for child in children.flatten() { + let path = child.path(); + if !path.is_dir() { + continue; + } + let _ = fs::write(path.join("cgroup.freeze"), "0"); + kill_cgroup(&path); + for _ in 0..LEFTOVER_POLLS { + if fs::remove_dir(&path).is_ok() || !path.exists() { + break; + } + std::thread::sleep(LEFTOVER_POLL); + } + } +} + +/// Makes sure `dir` passes the job controllers on to its children. +fn enable_controllers(dir: &Path) -> Result<(), String> { + let file = dir.join("cgroup.subtree_control"); + let have = + fs::read_to_string(&file).map_err(|e| format!("cannot read {}: {e}", file.display()))?; + let missing: Vec = CONTROLLERS + .iter() + .filter(|c| !have.split_whitespace().any(|h| h == **c)) + .map(|c| format!("+{c}")) + .collect(); + if missing.is_empty() { + return Ok(()); + } + fs::write(&file, missing.join(" ")).map_err(|e| { + format!( + "cannot enable {} in {} (the controllers are not delegated): {e}", + missing.join(" "), + file.display() + ) + }) +} + +// ----- the watcher ----- + +struct Watcher { + inotify: Inotify, + events: AsyncFd, + psi: Option>, +} + +impl Watcher { + fn open(box_dir: &Path) -> Result { + let inotify = Inotify::init(InitFlags::IN_NONBLOCK | InitFlags::IN_CLOEXEC) + .map_err(|e| format!("inotify: {e}"))?; + inotify + .add_watch(&box_dir.join("memory.events"), AddWatchFlags::IN_MODIFY) + .map_err(|e| format!("watching memory.events: {e}"))?; + // A new or removed job cgroup is how the controller learns where a job lives. + 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), + Err(e) => { + tracing::warn!("no PSI trigger on the box, using memory.events only: {e}"); + None + } + }; + Ok(Self { + inotify, + events, + psi, + }) + } +} + +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, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const GIB: u64 = 1 << 30; + + #[test] + fn parses_the_high_counter() { + let text = "low 0\nhigh 8\nmax 0\noom 0\noom_kill 0\n"; + assert_eq!(parse_high(text), 8); + assert_eq!(parse_high("low 0\nmax 1\n"), 0); + assert_eq!(parse_high(""), 0); + assert_eq!(parse_high("high x\n"), 0); + } + + #[test] + fn high_applies_only_to_two_or_more_unfrozen_jobs() { + assert_eq!(high_value(0, 6 * GIB), None); + assert_eq!(high_value(1, 6 * GIB), None); + // 5% of 6 GiB is under 512 MiB, so the minimum margin applies. + assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN)); + // 5% of 20 GiB is 1 GiB. + assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB)); + } + + #[test] + fn victim_is_the_youngest_unfrozen_with_a_partner() { + let job = |seq, frozen| Running { seq, frozen }; + assert_eq!(pick_victim(&[]), None); + assert_eq!(pick_victim(&[job(1, false)]), None); + assert_eq!(pick_victim(&[job(1, false), job(2, false)]), Some(1)); + assert_eq!( + pick_victim(&[job(5, false), job(2, false), job(9, true)]), + Some(0) + ); + // One unfrozen job left: nothing to pause. + assert_eq!(pick_victim(&[job(1, false), job(2, true)]), None); + } + + #[test] + fn thaw_is_the_oldest_when_there_is_room_or_nothing_runs() { + let parked = [ + Parked { seq: 7, swap: GIB }, + Parked { + seq: 3, + swap: 2 * GIB, + }, + ]; + assert_eq!(pick_thaw(&[], 0, 10 * GIB), None); + // The oldest is index 1 and needs 2 GiB. + assert_eq!(pick_thaw(&parked, 1, 3 * GIB), Some(1)); + assert_eq!(pick_thaw(&parked, 1, GIB), None); + // Nothing else runs: always thaw, whatever the headroom. + assert_eq!(pick_thaw(&parked, 0, 0), Some(1)); + } + + #[test] + fn gate_closes_for_parked_jobs_and_pressure() { + assert!(Gate::default().open()); + assert!( + !Gate { + frozen: 1, + hot: false + } + .open() + ); + assert!( + !Gate { + frozen: 0, + hot: true + } + .open() + ); + // A pressure signal heats the box, a job event cools it unless it is still at high. + assert!(hot_after(Cause::Pressure, false)); + assert!(!hot_after(Cause::Jobs, false)); + assert!(hot_after(Cause::Jobs, true)); + } + + /// A fake box: a temp dir with the files the controller reads. + fn fake_box(budget: u64) -> (tempfile::TempDir, Arc) { + let tmp = tempfile::tempdir().expect("tempdir"); + let dir = tmp.path().to_path_buf(); + fs::write(dir.join("memory.max"), budget.to_string()).expect("max"); + fs::write(dir.join("memory.current"), "0").expect("current"); + (tmp, Arc::new(Pressure::at(dir, budget))) + } + + fn fake_job(box_dir: &Path, id: &str, current: u64) -> PathBuf { + let dir = box_dir.join(format!("forge-job-{id}-1")); + fs::create_dir(&dir).expect("job dir"); + fs::write(dir.join("memory.current"), current.to_string()).expect("current"); + fs::write(dir.join("memory.stat"), format!("anon {current}\n")).expect("stat"); + dir + } + + #[test] + fn settle_sets_high_for_two_jobs_and_relaxes_it_for_one() { + let (tmp, pressure) = fake_box(6 * GIB); + let (tx, _rx) = mpsc::channel(8); + let a = pressure.register("a", "build", tx.clone()); + let b = pressure.register("b", "test", tx); + fake_job(tmp.path(), "a", GIB); + fake_job(tmp.path(), "b", GIB); + pressure.settle(Cause::Jobs); + let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high"); + assert_eq!(high, (6 * GIB - HIGH_MARGIN_MIN).to_string()); + drop(b); + pressure.settle(Cause::Jobs); + let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high"); + assert_eq!(high, "max"); + assert!(!a.requeued()); + } + + #[test] + fn pressure_with_a_lone_job_does_nothing_but_close_the_gate() { + let (tmp, pressure) = fake_box(6 * GIB); + let (tx, mut rx) = mpsc::channel(8); + let a = pressure.register("a", "build", tx); + let dir = fake_job(tmp.path(), "a", GIB); + pressure.settle(Cause::Pressure); + assert!(!a.requeued()); + assert!(!dir.join("cgroup.freeze").exists()); + assert!(rx.try_recv().is_err()); + assert!(!pressure.lock().gate.open()); + // The job ending cools the box. + drop(a); + pressure.settle(Cause::Jobs); + assert!(pressure.lock().gate.open()); + } + + #[test] + fn a_job_that_cannot_be_parked_is_killed_for_requeue() { + // In a fake cgroup memory.current never drops, so parking fails the way a full swap does. + let (tmp, pressure) = fake_box(6 * GIB); + let (tx_a, _rx_a) = mpsc::channel(8); + let (tx_b, mut rx_b) = mpsc::channel(8); + let a = pressure.register("a", "build", tx_a); + let b = pressure.register("b", "test", tx_b); + fake_job(tmp.path(), "a", 2 * GIB); + let dir_b = fake_job(tmp.path(), "b", 2 * GIB); + // A tiny anon size, so the host's real SwapFree does not decide this test. + fs::write(dir_b.join("memory.stat"), "anon 1\n").expect("stat"); + pressure.settle(Cause::Jobs); + pressure.settle(Cause::Pressure); + // The youngest job is the victim, the older one keeps running. + assert!(b.requeued()); + assert!(!a.requeued()); + assert_eq!( + fs::read_to_string(dir_b.join("cgroup.kill")).expect("kill"), + "1" + ); + let mut lines = String::new(); + while let Ok(bytes) = rx_b.try_recv() { + lines.push_str(&String::from_utf8_lossy(&bytes)); + } + assert!(lines.contains("paused: memory pressure, waiting for build")); + assert!(lines.contains("run it again later")); + // A killed job no longer counts as running, so memory.high relaxes. + assert_eq!( + fs::read_to_string(tmp.path().join("memory.high")).expect("high"), + "max" + ); + } + + #[test] + fn a_registration_tracks_pause_time_and_drops_its_log() { + let (_tmp, pressure) = fake_box(GIB); + let (tx, mut rx) = mpsc::channel(8); + let reg = pressure.register("a", "build", tx); + assert_eq!(reg.paused(), Duration::ZERO); + reg.handle.pause(); + std::thread::sleep(Duration::from_millis(5)); + assert!(reg.paused() > Duration::ZERO); + let lasted = reg.handle.resume(); + assert!(lasted > Duration::ZERO); + assert!(reg.paused() >= lasted); + drop(reg); + // The sender is gone with the registration, so the log shipper can finish. + assert!(matches!( + rx.try_recv(), + Err(mpsc::error::TryRecvError::Disconnected) + )); + } + + #[test] + fn create_box_enables_controllers_and_sets_limits() { + let tmp = tempfile::tempdir().expect("tempdir"); + let parent = tmp.path(); + fs::write(parent.join("cgroup.subtree_control"), "memory pids\n").expect("parent"); + fs::create_dir(parent.join(BOX_NAME)).expect("box dir"); + fs::write(parent.join(BOX_NAME).join("cgroup.subtree_control"), "").expect("box"); + let dir = create_box(parent, 4 * GIB).expect("box"); + assert_eq!(dir, parent.join(BOX_NAME)); + // The fake files stand in for the kernel: the write replaced them with the new text. + assert_eq!( + fs::read_to_string(dir.join("memory.max")).expect("max"), + (4 * GIB).to_string() + ); + assert_eq!( + fs::read_to_string(dir.join("memory.swap.max")).expect("swap"), + (4 * GIB).to_string() + ); + assert_eq!( + fs::read_to_string(dir.join("memory.high")).expect("high"), + "max" + ); + assert_eq!( + fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"), + "+cpu" + ); + // A second call adopts the existing box. + assert!(create_box(parent, 4 * GIB).is_ok()); + } + + #[tokio::test] + async fn wait_open_returns_at_once_on_an_open_gate_and_wakes_on_change() { + let (_tmp, pressure) = fake_box(GIB); + pressure.wait_open().await; + pressure.lock().gate.hot = true; + let waiter = { + let p = pressure.clone(); + tokio::spawn(async move { p.wait_open().await }) + }; + tokio::task::yield_now().await; + assert!(!waiter.is_finished()); + pressure.lock().gate.hot = false; + pressure.changed.notify_waiters(); + tokio::time::timeout(Duration::from_secs(5), waiter) + .await + .expect("woken") + .expect("join"); + } + + /// Needs a delegated memory controller, so it only runs on request: + /// `cargo test -p forge-runner real_box -- --ignored`. Builds a real box next to this + /// process, checks the watcher can arm inotify and the PSI trigger, and removes the box. + #[tokio::test] + #[ignore = "needs delegated cgroup v2 controllers"] + async fn real_box_starts_and_reports_headroom() { + let shutdown = CancellationToken::new(); + let Some(pressure) = Pressure::start(2 * GIB, shutdown.clone()).await else { + eprintln!("no delegated memory controller, skipping"); + return; + }; + assert!(pressure.headroom().is_some()); + pressure.wait_open().await; + shutdown.cancel(); + // The watcher is gone once cancelled; the empty box can be removed. + tokio::time::sleep(Duration::from_millis(100)).await; + let _ = fs::remove_dir(&pressure.dir); + } +} diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index 2ef1cf3..f6d465a 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -21,6 +21,7 @@ use crate::limiter::Limiter; use crate::logs::{self, PumpConfig}; use crate::memory::MemoryGate; use crate::oom::OomSink; +use crate::pressure::Pressure; use crate::restart::{self, RestartState, Step}; use crate::update::{self, Installed, UpdateState}; use crate::workspace; @@ -80,6 +81,8 @@ pub struct Runner { memory: Arc, /// A restart an admin asked for, see [`restart`]. restart: Arc, + /// The memory box and its controller, when the host allows it, see [`crate::pressure`]. + pressure: Option>, } impl Runner { @@ -100,9 +103,17 @@ impl Runner { limiter, memory, restart: Arc::new(RestartState::default()), + pressure: None, }) } + /// Turns on reactive memory control: jobs are paused under pressure, and no job is claimed + /// while one is parked. + pub fn with_pressure(mut self, pressure: Option>) -> Self { + self.pressure = pressure; + self + } + /// Turns on the build cache for every job this runner runs. pub fn with_cache(mut self, cache: CacheStore) -> Self { self.cache = Some(Arc::new(cache)); @@ -211,6 +222,15 @@ impl Runner { continue; } + if let Some(pressure) = &self.pressure { + // A parked job or a box under pressure means no new job. The controller wakes + // this when that changes. + tokio::select! { + _ = shutdown.cancelled() => break RunEnd::Stopped, + () = self.restart.changed() => continue, + () = pressure.wait_open() => {} + } + } let permit = tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, () = self.restart.changed() => continue, @@ -229,7 +249,12 @@ impl Runner { &self.config.labels, Some(self.limiter.current()), Some(MemoryClaim { - free: self.memory.free(), + // Real room in the box when memory control is on, else what is promised. + free: self + .pressure + .as_ref() + .and_then(|p| p.headroom()) + .unwrap_or_else(|| self.memory.free()), budget: self.memory.budget(), reserve: self.memory.default_reserve(), }), @@ -332,11 +357,26 @@ impl Runner { let job_cancel = shutdown.child_token(); let timed_out = Arc::new(AtomicBool::new(false)); let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone()); + let registration = self + .pressure + .as_ref() + .map(|p| p.register(&job.job_id, &job.job_name, tx.clone())); let timer = { let cancel = job_cancel.clone(); let flag = timed_out.clone(); + let pause = registration.as_ref().map(|r| r.pause_clock()); tokio::spawn(async move { - tokio::time::sleep(timeout).await; + // Time spent frozen does not count, so the deadline moves out by the pauses. + let started = Instant::now(); + loop { + let paused = pause.as_ref().map(|p| p.paused()).unwrap_or_default(); + let due = timeout + paused; + let elapsed = started.elapsed(); + if elapsed >= due { + break; + } + tokio::time::sleep(due - elapsed).await; + } flag.store(true, Ordering::SeqCst); cancel.cancel(); }) @@ -372,6 +412,39 @@ impl Runner { }, }; + // The memory controller killed this job to run it again later: give it back to the queue + // without a result. + if registration.as_ref().is_some_and(|r| r.requeued()) { + heartbeat.abort(); + timer.abort(); + drop(registration); + drop(tx); + let _ = pump.await; + let reason = "killed under memory pressure on the runner"; + if let Err(e) = self + .client + .requeue(&job.job_id, &job.job_token, reason) + .await + { + tracing::warn!(job_id = %job.job_id, error = %e, "requeue failed, failing the job"); + let failed = ExecResult { + outcome: Outcome::Error, + exit_code: None, + message: Some(format!( + "out of memory, and the forge could not requeue it: {e}" + )), + }; + self.finish(&job, &failed, None).await; + } + if let Some(dir) = workspace_dir + && let Err(e) = workspace::cleanup(&dir).await + { + tracing::warn!(job_id = %job.job_id, error = %e, "workspace cleanup failed"); + } + tracing::info!(job_id = %job.job_id, "job requeued after memory pressure"); + return Outcome::Cancelled; + } + // Artifacts only come from a successful run. let upload_error = match workspace_dir.as_deref() { Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { @@ -389,6 +462,8 @@ impl Runner { heartbeat.abort(); timer.abort(); + // The log sender it holds must go before the log shipper can finish. + drop(registration); if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { result = ExecResult { outcome: Outcome::Failure, diff --git a/crates/forge-runner/src/sandbox/helper.rs b/crates/forge-runner/src/sandbox/helper.rs index 9412364..d8ee730 100644 --- a/crates/forge-runner/src/sandbox/helper.rs +++ b/crates/forge-runner/src/sandbox/helper.rs @@ -335,6 +335,23 @@ fn run_job(req: &SandboxRequest, layout: &Layout, rootfs: &Path) -> Result Result { + let base = job_cgroup_base()?; + // With the runner's box in place (see `crate::pressure`), jobs live inside it. + let base = if box_ready(&base) { + base.join(BOX_NAME) + } else { + base + }; + // The helper's pid keeps the name unique even if two helpers share a job id. + Ok(base.join(format!("forge-job-{job_id}-{helper_pid}"))) +} + +/// The name of the runner's box cgroup, the parent of every job cgroup when memory control is on. +pub const BOX_NAME: &str = "forge-jobs"; + +/// The cgroup that holds the job cgroups, or the box under it: the runner's parent cgroup when it +/// is a plain domain cgroup, else the runner's own. Absolute, relative to the cgroup2 mount. +pub fn job_cgroup_base() -> Result { let text = fs::read_to_string("/proc/self/cgroup") .map_err(SandboxError::io("cannot read /proc/self/cgroup"))?; let own = text @@ -342,12 +359,19 @@ pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result parent.to_path_buf(), _ => own, - }; - // The helper's pid keeps the name unique even if two helpers share a job id. - Ok(base.join(format!("forge-job-{job_id}-{helper_pid}"))) + }) +} + +/// Whether the box exists under `base` with the memory controller enabled for its children. +fn box_ready(base: &Path) -> bool { + let dir = Path::new("/sys/fs/cgroup") + .join(base.strip_prefix("/").unwrap_or(base)) + .join(BOX_NAME); + fs::read_to_string(dir.join("cgroup.subtree_control")) + .is_ok_and(|t| t.split_whitespace().any(|c| c == "memory")) } /// Whether `cgroup` (absolute, inside the cgroup2 mount) is a normal domain cgroup. A threaded diff --git a/crates/forge-runner/src/sandbox/mod.rs b/crates/forge-runner/src/sandbox/mod.rs index 1878d23..faa0123 100644 --- a/crates/forge-runner/src/sandbox/mod.rs +++ b/crates/forge-runner/src/sandbox/mod.rs @@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize}; use crate::config::Limits; use idmap::IdMap; -pub use helper::{helper_main, job_cgroup_path}; +pub use helper::{BOX_NAME, helper_main, job_cgroup_base, job_cgroup_path}; pub use spec::build_spec; /// What the runner sends the helper on stdin. It carries the secrets, so it is never written to diff --git a/docs/ci.md b/docs/ci.md index e76dc20..83c64cc 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -66,46 +66,64 @@ directory. ### Memory -`memory` is the job's expected peak, not a limit you hope it stays under. A runner counts the -`memory` of its running jobs against its memory budget and takes a new job only when the sum still -fits, so two jobs that each peak at 4g never run together on a 7.6 GiB host and the kernel never -has to kill one of them for lack of RAM. A job without `memory` reserves the runner's default -(`limits.reserve_memory`, 1g unless an admin changed it). +`memory` is optional. You do not need it: the runner reacts to real memory use instead of trusting a +number. When you set it, it is a hint for admission and an explicit cap for the job. ```toml [jobs.build] image = "docker.io/library/rust:1" run = "cargo build --release" -memory = "4g" +memory = "4g" # optional ``` -How it is used: - -- Admission. The runner tells the forge how much memory it can still admit with every claim, and the - forge hands out the first queued job whose reservation fits. A smaller job may run before a bigger - one that has to wait, so a small job is not stuck behind a big one. To keep the big job from - starving, a job that does not fit and has waited 5 minutes stops smaller jobs from passing it on - that runner: the runner runs down its current jobs until the big one fits. A job that asks for - more than the runner's whole budget is treated as asking for the whole budget, so it runs alone - instead of waiting forever. -- Limit. The job's cgroup `memory.max` (podman `--memory`) is `memory` plus slack (1/16, at least - 256 MiB), and swap is off for the job (`memory.swap.max` is 0). A job that goes over is - OOM-killed inside its own cgroup. Without `memory`, the limit is the larger of the runner's - `limits.memory` and `limits.reserve_memory`. +What the runner does without it: + +- Optimistic admission. A job without `memory` reserves the runner's default (`limits.reserve_memory`, + 1g unless an admin changed it) and may use up to the whole memory budget of the runner. The + runner tells the forge how much memory its box has left with every claim, and the forge hands out + the first queued job whose reservation fits. A smaller job may run before a bigger one that has + to wait. To keep the big job from starving, a job that does not fit and has waited 5 minutes + stops smaller jobs from passing it on that runner. A job that asks for more than the runner's + whole budget runs alone. +- Pause and park. The runner puts all job cgroups in one box (`forge-jobs`) capped at the memory + budget. When two or more jobs run and the box nears its cap, the runner freezes the youngest + job and pushes its memory to swap, and logs `runner: paused: memory pressure, waiting for ` + and `runner: parked MiB in swap` in that job. The older job keeps its RAM and finishes. The + parked job thaws when the box has room for what is in its swap or nothing else runs, and logs + `runner: resumed after