forge
Explore
Log in

Don't you dare go Hollow

The runner parks the youngest job in swap under memory pressure instead of letting the kernel kill

Browse files at this commit

197fa34b66f337bbf3fbb62fe04972c5b751a8eaAhmet Kaan GümüşParent: 8d8258b
  • feat
    • the runner parks the youngest job in swap under memory pressure instead of letting the kernel kill
Show full message
✨ feat: the runner parks the youngest job in swap under memory pressure instead of letting the kernel kill

Jobs now live in a runner-owned box cgroup capped at the memory budget. An inotify watch on
memory.events and a PSI trigger wake a controller that freezes the youngest job, pushes it to swap,
and thaws it when there is room. A job that cannot be parked is killed and requeued. Admission waits
on the controller instead of a timer, memory declarations in ci.toml are now optional.
.forge/ci.tomlmodified+4 -9
@@ -2,11 +2,10 @@
2 #2 #
3 # The workflow has no branch condition, so the build job also runs for pull requests.3 # The workflow has no branch condition, so the build job also runs for pull requests.
4 # test and build have no `needs` between them, so they run in parallel when runner capacity allows4 # test and build have no `needs` between them, so they run in parallel when runner capacity allows
5-# (two runners, or one runner with concurrency = 2). Capacity includes memory: each job declares its5+# (two runners, or one runner with concurrency = 2). Memory is not declared: when two jobs together
6-# peak in `memory`, and a runner admits a job only while the declared memory of its running jobs6+# near the runner's memory budget, the runner pauses the younger one and parks it in swap until the
7-# fits its budget. On the 7.6 GiB runner host the budget is about 6.5 GiB, and test plus build7+# other finishes (docs/ci.md, Memory). An earlier run with concurrency 4 hit a host-wide OOM and
8-# declare 5g each, so they do NOT run together there: one heavy job at a time is the point. An8+# the kernel killed rustc mid-build.
9-# earlier run with concurrency 4 hit a host-wide OOM and the kernel killed rustc mid-build.
10 # The build job's artifacts are still only used9 # The build job's artifacts are still only used
11 # once the whole run is green: a tag push matching "v*" publishes a release with the build job's10 # once the whole run is green: a tag push matching "v*" publishes a release with the build job's
12 # binaries and SHA256SUMS, and self-update deploys dist/forge, only when every job in the run,11 # binaries and SHA256SUMS, and self-update deploys dist/forge, only when every job in the run,
@@ -21,8 +20,6 @@ tags = ["v*"]
21 [jobs.test]20 [jobs.test]
22 image = "docker.io/library/rust:1"21 image = "docker.io/library/rust:1"
23 # 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.22 # 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.
24-# 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.
25-memory = "5g"
26 env = { CARGO_BUILD_JOBS = "1", CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" }23 env = { CARGO_BUILD_JOBS = "1", CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" }
27 run = """24 run = """
28 cargo test --workspace25 cargo test --workspace
@@ -33,8 +30,6 @@ timeout_minutes = 120
33 [jobs.build]30 [jobs.build]
34 image = "docker.io/library/rust:1"31 image = "docker.io/library/rust:1"
35 # 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.32 # 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.
36-# 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.
37-memory = "5g"
38 env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" }33 env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" }
39 run = """34 run = """
40 cargo build --profile dist -p forge-web -p forge-runner35 cargo build --profile dist -p forge-web -p forge-runner
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"] }104+nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify"] }
105 105
106 # build and test106 # build and test
107 grass = "0.13.4"107 grass = "0.13.4"
crates/forge-runner/src/cli.rsmodified+16 -1
@@ -19,6 +19,7 @@ use crate::client::ForgeClient;
19 use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode};19 use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode};
20 use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor};20 use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor};
21 use crate::oci::ImageStore;21 use crate::oci::ImageStore;
22+use crate::pressure::Pressure;
22 use crate::runner::{RunEnd, RunOptions, Runner};23 use crate::runner::{RunEnd, RunOptions, Runner};
23 use crate::sandbox::idmap::IdMap;24 use crate::sandbox::idmap::IdMap;
24 use crate::update;25 use crate::update;
@@ -226,6 +227,19 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
226 let mut cfg = config::load(&path)?;227 let mut cfg = config::load(&path)?;
227 sync_config_with_forge(&mut cfg).await;228 sync_config_with_forge(&mut cfg).await;
228 let shutdown = CancellationToken::new();229 let shutdown = CancellationToken::new();
230+ // Only the builtin executor puts its jobs under the box. With the box, a lone job may
231+ // use all of it, so an undeclared job's cgroup limit is the box budget.
232+ let pressure = match cfg.executor {
233+ ExecutorKind::Builtin => {
234+ let budget = crate::memory::MemoryGate::for_host(&cfg.limits).budget();
235+ let pressure = Pressure::start(budget, shutdown.clone()).await;
236+ if let Some(p) = &pressure {
237+ cfg.limits.memory = p.budget().to_string();
238+ }
239+ pressure
240+ }
241+ ExecutorKind::Podman => None,
242+ };
229 let cache_root = cfg.work_dir.join(".cache");243 let cache_root = cfg.work_dir.join(".cache");
230 let cache_cap = cfg.cache_max_gib;244 let cache_cap = cfg.cache_max_gib;
231 // The id map is what the executor's jobs run under. The cache removes its dirs with it.245 // 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<ExitCode, Box<dyn std::error::Error>> {
258 (Arc::new(executor), map)272 (Arc::new(executor), map)
259 }273 }
260 };274 };
261- let mut runner = Runner::new(cfg, executor, RunOptions::default())?;275+ let mut runner =
276+ Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure);
262 if cache_cap > 0 {277 if cache_cap > 0 {
263 let cache =278 let cache =
264 CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?);279 CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?);
crates/forge-runner/src/client.rsmodified+29 -4
@@ -7,9 +7,10 @@ use std::path::Path;
7 use std::time::Duration;7 use std::time::Duration;
8 8
9 use forge_ci::proto::{9 use forge_ci::proto::{
10- BUILD_HEADER, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,10+ BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest,
11- JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest,11+ HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER,
12- RegisterResponse, RestartMode, RunnerConfigOverrides, RunnerConfigReport,12+ RegisterRequest, RegisterResponse, RequeueRequest, RestartMode, RunnerConfigOverrides,
13+ RunnerConfigReport,
13 };14 };
14 use reqwest::StatusCode;15 use reqwest::StatusCode;
15 use reqwest::header::{CONTENT_LENGTH, HeaderMap};16 use reqwest::header::{CONTENT_LENGTH, HeaderMap};
@@ -145,7 +146,7 @@ impl ForgeClient {
145 memory_bytes: host.memory_bytes,146 memory_bytes: host.memory_bytes,
146 build: Some(forge_ci::build::display()),147 build: Some(forge_ci::build::display()),
147 boot_id: Some(crate::restart::boot_id().to_owned()),148 boot_id: Some(crate::restart::boot_id().to_owned()),
148- capabilities: vec![CAP_RESTART.to_owned()],149+ capabilities: vec![CAP_RESTART.to_owned(), CAP_REQUEUE.to_owned()],
149 free_memory_bytes: memory.map(|m| m.free),150 free_memory_bytes: memory.map(|m| m.free),
150 memory_budget_bytes: memory.map(|m| m.budget),151 memory_budget_bytes: memory.map(|m| m.budget),
151 reserve_memory_bytes: memory.map(|m| m.reserve),152 reserve_memory_bytes: memory.map(|m| m.reserve),
@@ -357,6 +358,30 @@ impl ForgeClient {
357 Err(status_error(resp).await)358 Err(status_error(resp).await)
358 }359 }
359 }360 }
361+
362+ /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place.
363+ pub async fn requeue(
364+ &self,
365+ job_id: &str,
366+ job_token: &str,
367+ reason: &str,
368+ ) -> Result<(), ClientError> {
369+ let resp = self
370+ .http
371+ .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/requeue")))
372+ .bearer_auth(job_token)
373+ .json(&RequeueRequest {
374+ reason: reason.to_owned(),
375+ })
376+ .timeout(REQUEST_TIMEOUT)
377+ .send()
378+ .await?;
379+ if resp.status().is_success() {
380+ Ok(())
381+ } else {
382+ Err(status_error(resp).await)
383+ }
384+ }
360 }385 }
361 386
362 /// The `Forge-Binary-Sha256` header, trimmed and lowercased. An empty value counts as absent.387 /// The `Forge-Binary-Sha256` header, trimmed and lowercased. An empty value counts as absent.
crates/forge-runner/src/executor.rsmodified+1 -1
@@ -738,7 +738,7 @@ const REAP_POLLS: u32 = 50;
738 738
739 /// Kills every process in a job cgroup. `cgroup.kill` does it in one write (Linux 5.14 and up).739 /// Kills every process in a job cgroup. `cgroup.kill` does it in one write (Linux 5.14 and up).
740 /// Older kernels get a SIGKILL to each pid in `cgroup.procs`.740 /// Older kernels get a SIGKILL to each pid in `cgroup.procs`.
741-fn kill_cgroup(dir: &Path) {741+pub(crate) fn kill_cgroup(dir: &Path) {
742 if fs::write(dir.join("cgroup.kill"), "1").is_ok() {742 if fs::write(dir.join("cgroup.kill"), "1").is_ok() {
743 return;743 return;
744 }744 }
crates/forge-runner/src/lib.rsmodified+1 -0
@@ -16,6 +16,7 @@ pub mod logs;
16 pub mod memory;16 pub mod memory;
17 pub mod oci;17 pub mod oci;
18 pub mod oom;18 pub mod oom;
19+pub mod pressure;
19 pub mod restart;20 pub mod restart;
20 pub mod runner;21 pub mod runner;
21 pub mod sandbox;22 pub mod sandbox;
crates/forge-runner/src/pressure.rsadded+1041 -0
@@ -0,0 +1,1041 @@
1+//! Reactive memory control. The runner puts every job cgroup inside one box cgroup
2+//! (`forge-jobs`) that is capped at the memory budget. When two or more jobs run and the box nears
3+//! its cap, the youngest job is frozen and its memory is pushed to swap, so the other job keeps
4+//! its RAM and nothing is OOM-killed. The parked job thaws when there is room again. When parking
5+//! does not work, the job is killed and queued again on the forge. A lone job is never paused: it
6+//! may use the whole box, and a real OOM there is reported as before (see [`crate::oom`]).
7+//!
8+//! Nothing here polls. The box's `memory.events` is watched with inotify (the `high` counter
9+//! moves the moment an allocation is held back by `memory.high`), the box's `memory.pressure` has
10+//! a PSI trigger as a second signal, and jobs starting and ending wake the controller too.
11+//!
12+//! `memory.high` is a brake that never lets go by itself: with swap off for the jobs, allocations
13+//! above it stall for minutes. So it is only set while 2+ jobs run unfrozen, and the controller
14+//! relaxes it the moment the stalled job is the only one left.
15+//!
16+//! The cgroup files are read and written through plain paths, so tests use a temp dir as a fake
17+//! cgroup.
18+
19+use std::fs::{self, File, OpenOptions};
20+use std::io::{self, Write};
21+use std::os::fd::AsFd;
22+use std::os::unix::fs::OpenOptionsExt;
23+use std::path::{Path, PathBuf};
24+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
25+use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
26+use std::time::{Duration, Instant};
27+
28+use nix::errno::Errno;
29+use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify};
30+use tokio::io::Interest;
31+use tokio::io::unix::AsyncFd;
32+use tokio::sync::{Notify, mpsc};
33+use tokio_util::sync::CancellationToken;
34+
35+use crate::executor::kill_cgroup;
36+use crate::sandbox::{BOX_NAME, job_cgroup_base};
37+
38+/// Where cgroup2 is mounted.
39+const CGROUP_ROOT: &str = "/sys/fs/cgroup";
40+/// The controllers jobs need, enabled on the box and on its parent.
41+const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"];
42+/// The PSI trigger: 150 ms of stall in a 2 s window. Unprivileged users need a multiple of 2 s.
43+const PSI_TRIGGER: &str = "some 150000 2000000";
44+/// `memory.high` sits below the box cap by the larger of this and 5% of the cap.
45+const HIGH_MARGIN_MIN: u64 = 512 << 20;
46+/// How hard a parked job's pages are pushed to swap.
47+const SWAPPINESS: u32 = 200;
48+/// How many reclaim writes to try on a frozen job. One write may reclaim only part of it.
49+const RECLAIM_ATTEMPTS: u32 = 4;
50+/// How long a leftover job cgroup from an earlier runner gets to die at startup.
51+const LEFTOVER_POLLS: u32 = 50;
52+const LEFTOVER_POLL: Duration = Duration::from_millis(100);
53+
54+/// What woke the controller.
55+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56+pub enum Cause {
57+ /// The box is short of memory: `high` moved in `memory.events`, or the PSI trigger fired.
58+ Pressure,
59+ /// A job started or ended, or the box changed in a way that is no pressure signal.
60+ Jobs,
61+}
62+
63+// ----- pure rules -----
64+
65+/// The `high` counter of a `memory.events` text. Missing means 0.
66+pub fn parse_high(text: &str) -> u64 {
67+ text.lines()
68+ .find_map(|line| {
69+ let (key, value) = line.split_once(' ')?;
70+ (key == "high").then(|| value.trim().parse().ok())?
71+ })
72+ .unwrap_or(0)
73+}
74+
75+/// `memory.high` of the box, or `None` for `max`. Only set while two or more jobs run unfrozen:
76+/// a lone job runs up to the box's `memory.max`.
77+pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> {
78+ if unfrozen < 2 {
79+ return None;
80+ }
81+ let margin = HIGH_MARGIN_MIN.max(budget / 20);
82+ Some(budget.saturating_sub(margin))
83+}
84+
85+/// A running job, as far as victim choice cares.
86+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87+pub struct Running {
88+ /// Start order: higher is younger.
89+ pub seq: u64,
90+ pub frozen: bool,
91+}
92+
93+/// The job to park: the youngest unfrozen one, and only while at least two are unfrozen.
94+pub fn pick_victim(jobs: &[Running]) -> Option<usize> {
95+ let unfrozen = || jobs.iter().enumerate().filter(|(_, j)| !j.frozen);
96+ if unfrozen().count() < 2 {
97+ return None;
98+ }
99+ unfrozen().max_by_key(|(_, j)| j.seq).map(|(i, _)| i)
100+}
101+
102+/// A parked job, as far as thaw choice cares.
103+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104+pub struct Parked {
105+ pub seq: u64,
106+ /// Bytes of the job that sit in swap.
107+ pub swap: u64,
108+}
109+
110+/// The parked job to thaw: the oldest, once the box has room for what is in its swap or nothing
111+/// else runs.
112+pub fn pick_thaw(parked: &[Parked], unfrozen_running: usize, headroom: u64) -> Option<usize> {
113+ let (index, oldest) = parked.iter().enumerate().min_by_key(|(_, p)| p.seq)?;
114+ (unfrozen_running == 0 || headroom >= oldest.swap).then_some(index)
115+}
116+
117+/// Whether the box is marked as under pressure after a pass. Pressure signals set it. Any other
118+/// wake clears it, unless the box still sits at `memory.high`.
119+pub fn hot_after(cause: Cause, over_high: bool) -> bool {
120+ cause == Cause::Pressure || over_high
121+}
122+
123+/// The admission gate: the runner claims a new job only while it is open.
124+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
125+pub struct Gate {
126+ pub frozen: usize,
127+ pub hot: bool,
128+}
129+
130+impl Gate {
131+ pub fn open(&self) -> bool {
132+ self.frozen == 0 && !self.hot
133+ }
134+}
135+
136+// ----- the jobs the controller knows -----
137+
138+#[derive(Default)]
139+struct PauseClock {
140+ total: Duration,
141+ since: Option<Instant>,
142+}
143+
144+/// One registered job, shared between its runner task and the controller.
145+pub struct JobHandle {
146+ id: String,
147+ name: String,
148+ log: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
149+ requeued: AtomicBool,
150+ clock: Mutex<PauseClock>,
151+}
152+
153+impl JobHandle {
154+ /// Appends a line to the job's log. A full or closed log drops it.
155+ fn log_line(&self, line: &str) {
156+ let guard = self.log.lock().unwrap_or_else(PoisonError::into_inner);
157+ if let Some(tx) = guard.as_ref() {
158+ let mut bytes = format!("runner: {line}").into_bytes();
159+ bytes.push(b'\n');
160+ let _ = tx.try_send(bytes);
161+ }
162+ }
163+
164+ /// How long the job has spent frozen so far.
165+ pub fn paused(&self) -> Duration {
166+ let clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
167+ clock.total + clock.since.map(|s| s.elapsed()).unwrap_or_default()
168+ }
169+
170+ fn pause(&self) {
171+ let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
172+ clock.since.get_or_insert_with(Instant::now);
173+ }
174+
175+ /// Ends a pause and returns how long it lasted.
176+ fn resume(&self) -> Duration {
177+ let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
178+ let lasted = clock.since.take().map(|s| s.elapsed()).unwrap_or_default();
179+ clock.total += lasted;
180+ lasted
181+ }
182+}
183+
184+/// A job's registration. Dropping it takes the job out of the controller's view.
185+pub struct Registration {
186+ handle: Arc<JobHandle>,
187+ owner: Arc<Pressure>,
188+}
189+
190+impl Registration {
191+ /// True when the controller killed the job to give it back to the queue.
192+ pub fn requeued(&self) -> bool {
193+ self.handle.requeued.load(Ordering::SeqCst)
194+ }
195+
196+ /// How long the job has spent frozen so far. Its timeout does not count that time.
197+ pub fn paused(&self) -> Duration {
198+ self.handle.paused()
199+ }
200+
201+ /// A handle for reading [`Registration::paused`] from another task.
202+ pub fn pause_clock(&self) -> Arc<JobHandle> {
203+ self.handle.clone()
204+ }
205+}
206+
207+impl Drop for Registration {
208+ fn drop(&mut self) {
209+ // The log sender must go now, or the log shipper would wait for it.
210+ *self
211+ .handle
212+ .log
213+ .lock()
214+ .unwrap_or_else(PoisonError::into_inner) = None;
215+ self.owner.remove(&self.handle);
216+ }
217+}
218+
219+struct Entry {
220+ handle: Arc<JobHandle>,
221+ seq: u64,
222+ /// The job's cgroup, once the sandbox has created it.
223+ dir: Option<PathBuf>,
224+ frozen: Option<Frozen>,
225+}
226+
227+struct Frozen {
228+ swap: u64,
229+}
230+
231+#[derive(Default)]
232+struct State {
233+ entries: Vec<Entry>,
234+ gate: Gate,
235+ /// The `memory.high` last written, to skip repeated writes.
236+ high: Option<Option<u64>>,
237+}
238+
239+/// The box and the controller of the jobs in it.
240+pub struct Pressure {
241+ dir: PathBuf,
242+ budget: u64,
243+ state: Mutex<State>,
244+ seq: AtomicU64,
245+ /// Wakes the watcher: a job registered or ended.
246+ kick: Notify,
247+ /// Wakes the claim loop: the gate may have changed.
248+ changed: Notify,
249+}
250+
251+impl Pressure {
252+ /// Creates the box and starts the watcher. Returns `None`, after one log line, when the host
253+ /// can't do it: cgroup controllers not delegated, no inotify, and so on. The runner then
254+ /// works as before, without the box and without pausing.
255+ pub async fn start(budget: u64, shutdown: CancellationToken) -> Option<Arc<Self>> {
256+ let setup = tokio::task::spawn_blocking(move || {
257+ let base = job_cgroup_base().map_err(|e| e.to_string())?;
258+ let parent = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base));
259+ create_box(&parent, budget)
260+ })
261+ .await;
262+ let dir = match setup {
263+ Ok(Ok(dir)) => dir,
264+ Ok(Err(e)) => {
265+ tracing::warn!("memory control is off: {e}");
266+ return None;
267+ }
268+ Err(e) => {
269+ tracing::warn!("memory control is off: {e}");
270+ return None;
271+ }
272+ };
273+ let this = Arc::new(Self::at(dir, budget));
274+ match Watcher::open(&this.dir) {
275+ Ok(watcher) => {
276+ tokio::spawn(this.clone().watch(watcher, shutdown));
277+ tracing::info!(
278+ box_dir = %this.dir.display(),
279+ budget = %forge_ci::size::format_size(budget),
280+ "memory control is on"
281+ );
282+ Some(this)
283+ }
284+ Err(e) => {
285+ tracing::warn!("memory control is off, cannot watch the box: {e}");
286+ None
287+ }
288+ }
289+ }
290+
291+ fn at(dir: PathBuf, budget: u64) -> Self {
292+ Self {
293+ dir,
294+ budget,
295+ state: Mutex::new(State::default()),
296+ seq: AtomicU64::new(0),
297+ kick: Notify::new(),
298+ changed: Notify::new(),
299+ }
300+ }
301+
302+ /// The memory the box may use: the budget it was created with.
303+ pub fn budget(&self) -> u64 {
304+ self.budget
305+ }
306+
307+ fn lock(&self) -> MutexGuard<'_, State> {
308+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
309+ }
310+
311+ /// Puts a job under control. `log` receives the pause and resume lines.
312+ pub fn register(
313+ self: &Arc<Self>,
314+ job_id: &str,
315+ job_name: &str,
316+ log: mpsc::Sender<Vec<u8>>,
317+ ) -> Registration {
318+ let handle = Arc::new(JobHandle {
319+ id: job_id.to_owned(),
320+ name: job_name.to_owned(),
321+ log: Mutex::new(Some(log)),
322+ requeued: AtomicBool::new(false),
323+ clock: Mutex::new(PauseClock::default()),
324+ });
325+ self.lock().entries.push(Entry {
326+ handle: handle.clone(),
327+ seq: self.seq.fetch_add(1, Ordering::SeqCst),
328+ dir: None,
329+ frozen: None,
330+ });
331+ self.kick.notify_one();
332+ Registration {
333+ handle,
334+ owner: self.clone(),
335+ }
336+ }
337+
338+ fn remove(&self, handle: &Arc<JobHandle>) {
339+ self.lock()
340+ .entries
341+ .retain(|e| !Arc::ptr_eq(&e.handle, handle));
342+ self.kick.notify_one();
343+ }
344+
345+ /// Memory the box has left, counting reclaimable page cache as free. `None` when unreadable.
346+ pub fn headroom(&self) -> Option<u64> {
347+ let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget);
348+ Some(max.saturating_sub(box_usage(&self.dir)?))
349+ }
350+
351+ /// Resolves once the runner may claim: no job is parked and the box is not under pressure.
352+ /// Woken by the controller, never by a timer.
353+ pub async fn wait_open(&self) {
354+ loop {
355+ let notified = self.changed.notified();
356+ tokio::pin!(notified);
357+ notified.as_mut().enable();
358+ if self.lock().gate.open() {
359+ return;
360+ }
361+ notified.await;
362+ }
363+ }
364+
365+ async fn watch(self: Arc<Self>, 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 {
375+ let cause = tokio::select! {
376+ () = shutdown.cancelled() => return,
377+ ready = events.readable() => {
378+ let mut guard = match ready {
379+ Ok(guard) => guard,
380+ Err(e) => {
381+ tracing::warn!("memory control stopped, inotify failed: {e}");
382+ return;
383+ }
384+ };
385+ let mut modified = false;
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+ }
415+ () = self.kick.notified() => Cause::Jobs,
416+ };
417+ let this = self.clone();
418+ if let Err(e) = tokio::task::spawn_blocking(move || this.settle(cause)).await {
419+ tracing::error!("memory control pass panicked: {e}");
420+ }
421+ }
422+ }
423+
424+ /// One pass: park a job if the box is short of memory, thaw one if there is room, and set
425+ /// `memory.high` for what runs now. Blocks, so it runs off the async runtime.
426+ fn settle(&self, cause: Cause) {
427+ let mut state = self.lock();
428+ for entry in &mut state.entries {
429+ if entry.dir.is_none()
430+ && let Some(dir) = find_job_dir(&self.dir, &entry.handle.id)
431+ {
432+ // A real OOM then takes the whole job, not one of its processes.
433+ let _ = fs::write(dir.join("memory.oom.group"), "1");
434+ entry.dir = Some(dir);
435+ }
436+ }
437+ let mut parked_now = false;
438+ if cause == Cause::Pressure {
439+ let live: Vec<usize> = (0..state.entries.len())
440+ .filter(|&i| is_live(&state.entries[i]))
441+ .collect();
442+ let running: Vec<Running> = live
443+ .iter()
444+ .map(|&i| Running {
445+ seq: state.entries[i].seq,
446+ frozen: false,
447+ })
448+ .collect();
449+ if let Some(pick) = pick_victim(&running) {
450+ let victim = live[pick];
451+ let waiting_for = live
452+ .iter()
453+ .filter(|&&i| i != victim)
454+ .min_by_key(|&&i| state.entries[i].seq)
455+ .map(|&i| state.entries[i].handle.name.clone())
456+ .unwrap_or_default();
457+ park(&mut state.entries[victim], &waiting_for);
458+ parked_now = true;
459+ }
460+ }
461+ if !parked_now {
462+ self.thaw_one(&mut state);
463+ }
464+ let unfrozen = state.entries.iter().filter(|e| is_live(e)).count();
465+ let high = high_value(unfrozen, self.budget);
466+ if state.high != Some(high) {
467+ let text = high.map_or_else(|| "max".to_owned(), |b| b.to_string());
468+ match fs::write(self.dir.join("memory.high"), text) {
469+ Ok(()) => state.high = Some(high),
470+ Err(e) => tracing::warn!("cannot set memory.high of the box: {e}"),
471+ }
472+ }
473+ let over_high = high.is_some_and(|h| box_usage(&self.dir).is_some_and(|u| u >= h));
474+ state.gate = Gate {
475+ frozen: state.entries.iter().filter(|e| e.frozen.is_some()).count(),
476+ hot: hot_after(cause, over_high),
477+ };
478+ drop(state);
479+ self.changed.notify_waiters();
480+ }
481+
482+ fn thaw_one(&self, state: &mut State) {
483+ let parked: Vec<(usize, Parked)> = state
484+ .entries
485+ .iter()
486+ .enumerate()
487+ .filter_map(|(i, e)| {
488+ let frozen = e.frozen.as_ref()?;
489+ let swap = e.dir.as_deref().and_then(job_swap).unwrap_or(frozen.swap);
490+ Some((i, Parked { seq: e.seq, swap }))
491+ })
492+ .collect();
493+ let running = state.entries.iter().filter(|e| is_live(e)).count();
494+ let headroom = self.headroom().unwrap_or(0);
495+ let list: Vec<Parked> = parked.iter().map(|(_, p)| *p).collect();
496+ let Some(pick) = pick_thaw(&list, running, headroom) else {
497+ return;
498+ };
499+ let entry = &mut state.entries[parked[pick].0];
500+ let Some(dir) = entry.dir.clone() else {
501+ return;
502+ };
503+ // Swap stays where it is. Nothing new goes out, and pages come back as the job touches them.
504+ let _ = fs::write(dir.join("memory.swap.max"), "0");
505+ if let Err(e) = fs::write(dir.join("cgroup.freeze"), "0") {
506+ tracing::warn!(job_id = %entry.handle.id, "cannot thaw job: {e}");
507+ return;
508+ }
509+ entry.frozen = None;
510+ let lasted = entry.handle.resume();
511+ entry
512+ .handle
513+ .log_line(&format!("resumed after {}", format_duration(lasted)));
514+ tracing::info!(job_id = %entry.handle.id, "job resumed");
515+ }
516+}
517+
518+/// Whether the entry counts as running and unfrozen: it has a cgroup, is not parked and was not
519+/// killed for requeueing.
520+fn is_live(entry: &Entry) -> bool {
521+ entry.dir.is_some() && entry.frozen.is_none() && !entry.handle.requeued.load(Ordering::SeqCst)
522+}
523+
524+/// Freezes the job and pushes its memory to swap. When that does not work, kills the job so the
525+/// forge queues it again.
526+fn park(entry: &mut Entry, waiting_for: &str) {
527+ let Some(dir) = entry.dir.clone() else {
528+ return;
529+ };
530+ let handle = entry.handle.clone();
531+ let before = read_u64(&dir, "memory.current").unwrap_or(0);
532+ let anon = stat_field(&dir, "anon").unwrap_or(before);
533+ let swap_free = swap_free_bytes();
534+ if swap_free.is_some_and(|free| free < anon) {
535+ give_back(entry, "the host has no swap room for it");
536+ return;
537+ }
538+ // The job's own cgroup may swap now. Its swap.max was 0 so it never swapped by itself.
539+ let _ = fs::write(dir.join("memory.swap.max"), "max");
540+ if let Err(e) = fs::write(dir.join("cgroup.freeze"), "1") {
541+ tracing::warn!(job_id = %handle.id, "cannot freeze job: {e}");
542+ give_back(entry, "it cannot be frozen");
543+ return;
544+ }
545+ handle.pause();
546+ handle.log_line(&format!(
547+ "paused: memory pressure, waiting for {waiting_for}"
548+ ));
549+ let mut after = before;
550+ for _ in 0..RECLAIM_ATTEMPTS {
551+ reclaim(&dir, before);
552+ after = read_u64(&dir, "memory.current").unwrap_or(before);
553+ if after <= before / 2 {
554+ break;
555+ }
556+ }
557+ if after > before / 2 {
558+ let _ = fs::write(dir.join("cgroup.freeze"), "0");
559+ handle.resume();
560+ give_back(entry, "its memory would not go to swap");
561+ return;
562+ }
563+ let swap = job_swap(&dir).unwrap_or(0);
564+ handle.log_line(&format!("parked {} MiB in swap", swap >> 20));
565+ tracing::info!(job_id = %handle.id, swap, "job parked in swap");
566+ entry.frozen = Some(Frozen { swap });
567+}
568+
569+/// Writes the reclaim request. A rejected `swappiness` key falls back to the plain amount. The
570+/// return code is not trusted: EAGAIN comes back on success too, so callers read `memory.current`.
571+fn reclaim(dir: &Path, bytes: u64) {
572+ let file = dir.join("memory.reclaim");
573+ match fs::write(&file, format!("{bytes} swappiness={SWAPPINESS}")) {
574+ Err(e) if e.kind() == io::ErrorKind::InvalidInput => {
575+ let _ = fs::write(&file, bytes.to_string());
576+ }
577+ _ => {}
578+ }
579+}
580+
581+/// Kills the job and marks it for requeueing. The job's task sees the mark and queues it again
582+/// instead of reporting a result.
583+fn give_back(entry: &mut Entry, why: &str) {
584+ entry.handle.requeued.store(true, Ordering::SeqCst);
585+ entry.handle.log_line(&format!(
586+ "memory pressure and {why}: stopping this job to run it again later"
587+ ));
588+ tracing::warn!(job_id = %entry.handle.id, "{why}, killing job to requeue it");
589+ if let Some(dir) = &entry.dir {
590+ // A frozen cgroup is killed too, but thaw first so the kill takes effect at once.
591+ let _ = fs::write(dir.join("cgroup.freeze"), "0");
592+ kill_cgroup(dir);
593+ }
594+}
595+
596+// ----- cgroup files -----
597+
598+/// The job's cgroup under the box: `forge-job-<id>-<pid>`.
599+fn find_job_dir(box_dir: &Path, job_id: &str) -> Option<PathBuf> {
600+ let prefix = format!("forge-job-{job_id}-");
601+ fs::read_dir(box_dir)
602+ .ok()?
603+ .flatten()
604+ .find(|e| e.file_name().to_string_lossy().starts_with(&prefix))
605+ .map(|e| e.path())
606+}
607+
608+/// A single-number cgroup file. `None` when missing or `max`.
609+fn read_u64(dir: &Path, file: &str) -> Option<u64> {
610+ fs::read_to_string(dir.join(file)).ok()?.trim().parse().ok()
611+}
612+
613+fn stat_field(dir: &Path, key: &str) -> Option<u64> {
614+ let text = fs::read_to_string(dir.join("memory.stat")).ok()?;
615+ text.lines().find_map(|line| {
616+ let (k, v) = line.split_once(' ')?;
617+ (k == key).then(|| v.trim().parse().ok())?
618+ })
619+}
620+
621+fn job_swap(dir: &Path) -> Option<u64> {
622+ read_u64(dir, "memory.swap.current")
623+}
624+
625+/// What the box really holds: its charge minus inactive page cache, which the kernel gives up
626+/// first. `None` when the charge is unreadable.
627+fn box_usage(dir: &Path) -> Option<u64> {
628+ let current = read_u64(dir, "memory.current")?;
629+ Some(current.saturating_sub(stat_field(dir, "inactive_file").unwrap_or(0)))
630+}
631+
632+/// `SwapFree` of `/proc/meminfo` in bytes.
633+fn swap_free_bytes() -> Option<u64> {
634+ let text = fs::read_to_string("/proc/meminfo").ok()?;
635+ let line = text.lines().find(|l| l.starts_with("SwapFree:"))?;
636+ line.split_whitespace()
637+ .nth(1)?
638+ .parse::<u64>()
639+ .ok()?
640+ .checked_mul(1024)
641+}
642+
643+fn format_duration(d: Duration) -> String {
644+ let secs = d.as_secs();
645+ if secs >= 60 {
646+ format!("{}m {}s", secs / 60, secs % 60)
647+ } else {
648+ format!("{secs}s")
649+ }
650+}
651+
652+// ----- the box -----
653+
654+/// Creates or adopts the box under `parent`, enables the controllers, and sets its limits. Job
655+/// cgroups left by a runner that died are killed and removed. Returns the box directory.
656+pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> {
657+ let dir = parent.join(BOX_NAME);
658+ match fs::create_dir(&dir) {
659+ Ok(()) => {}
660+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
661+ Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
662+ }
663+ remove_leftovers(&dir);
664+ enable_controllers(parent)?;
665+ enable_controllers(&dir)?;
666+ let set = |file: &str, value: String| {
667+ fs::write(dir.join(file), value).map_err(|e| format!("cannot set {file} on the box: {e}"))
668+ };
669+ set("memory.max", budget.to_string())?;
670+ // Only a parked job swaps, and its own swap.max says when. The box allows it.
671+ set("memory.swap.max", budget.to_string())?;
672+ set("memory.high", "max".to_owned())?;
673+ Ok(dir)
674+}
675+
676+/// Kills and removes the job cgroups a previous runner left in the box. Frozen ones are thawed
677+/// first, or the kill would wait for them.
678+fn remove_leftovers(box_dir: &Path) {
679+ let Ok(children) = fs::read_dir(box_dir) else {
680+ return;
681+ };
682+ for child in children.flatten() {
683+ let path = child.path();
684+ if !path.is_dir() {
685+ continue;
686+ }
687+ let _ = fs::write(path.join("cgroup.freeze"), "0");
688+ kill_cgroup(&path);
689+ for _ in 0..LEFTOVER_POLLS {
690+ if fs::remove_dir(&path).is_ok() || !path.exists() {
691+ break;
692+ }
693+ std::thread::sleep(LEFTOVER_POLL);
694+ }
695+ }
696+}
697+
698+/// Makes sure `dir` passes the job controllers on to its children.
699+fn enable_controllers(dir: &Path) -> Result<(), String> {
700+ let file = dir.join("cgroup.subtree_control");
701+ let have =
702+ fs::read_to_string(&file).map_err(|e| format!("cannot read {}: {e}", file.display()))?;
703+ let missing: Vec<String> = CONTROLLERS
704+ .iter()
705+ .filter(|c| !have.split_whitespace().any(|h| h == **c))
706+ .map(|c| format!("+{c}"))
707+ .collect();
708+ if missing.is_empty() {
709+ return Ok(());
710+ }
711+ fs::write(&file, missing.join(" ")).map_err(|e| {
712+ format!(
713+ "cannot enable {} in {} (the controllers are not delegated): {e}",
714+ missing.join(" "),
715+ file.display()
716+ )
717+ })
718+}
719+
720+// ----- the watcher -----
721+
722+struct Watcher {
723+ inotify: Inotify,
724+ events: AsyncFd<std::os::fd::OwnedFd>,
725+ psi: Option<AsyncFd<File>>,
726+}
727+
728+impl Watcher {
729+ fn open(box_dir: &Path) -> Result<Self, String> {
730+ let inotify = Inotify::init(InitFlags::IN_NONBLOCK | InitFlags::IN_CLOEXEC)
731+ .map_err(|e| format!("inotify: {e}"))?;
732+ inotify
733+ .add_watch(&box_dir.join("memory.events"), AddWatchFlags::IN_MODIFY)
734+ .map_err(|e| format!("watching memory.events: {e}"))?;
735+ // A new or removed job cgroup is how the controller learns where a job lives.
736+ inotify
737+ .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE)
738+ .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) {
748+ Ok(fd) => Some(fd),
749+ Err(e) => {
750+ tracing::warn!("no PSI trigger on the box, using memory.events only: {e}");
751+ None
752+ }
753+ };
754+ Ok(Self {
755+ inotify,
756+ events,
757+ psi,
758+ })
759+ }
760+}
761+
762+fn arm_psi(box_dir: &Path) -> io::Result<AsyncFd<File>> {
763+ let mut file = OpenOptions::new()
764+ .read(true)
765+ .write(true)
766+ .custom_flags(nix::libc::O_NONBLOCK)
767+ .open(box_dir.join("memory.pressure"))?;
768+ 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
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+}
788+
789+#[cfg(test)]
790+mod tests {
791+ use super::*;
792+
793+ const GIB: u64 = 1 << 30;
794+
795+ #[test]
796+ fn parses_the_high_counter() {
797+ let text = "low 0\nhigh 8\nmax 0\noom 0\noom_kill 0\n";
798+ assert_eq!(parse_high(text), 8);
799+ assert_eq!(parse_high("low 0\nmax 1\n"), 0);
800+ assert_eq!(parse_high(""), 0);
801+ assert_eq!(parse_high("high x\n"), 0);
802+ }
803+
804+ #[test]
805+ fn high_applies_only_to_two_or_more_unfrozen_jobs() {
806+ assert_eq!(high_value(0, 6 * GIB), None);
807+ assert_eq!(high_value(1, 6 * GIB), None);
808+ // 5% of 6 GiB is under 512 MiB, so the minimum margin applies.
809+ assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN));
810+ // 5% of 20 GiB is 1 GiB.
811+ assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB));
812+ }
813+
814+ #[test]
815+ fn victim_is_the_youngest_unfrozen_with_a_partner() {
816+ let job = |seq, frozen| Running { seq, frozen };
817+ assert_eq!(pick_victim(&[]), None);
818+ assert_eq!(pick_victim(&[job(1, false)]), None);
819+ assert_eq!(pick_victim(&[job(1, false), job(2, false)]), Some(1));
820+ assert_eq!(
821+ pick_victim(&[job(5, false), job(2, false), job(9, true)]),
822+ Some(0)
823+ );
824+ // One unfrozen job left: nothing to pause.
825+ assert_eq!(pick_victim(&[job(1, false), job(2, true)]), None);
826+ }
827+
828+ #[test]
829+ fn thaw_is_the_oldest_when_there_is_room_or_nothing_runs() {
830+ let parked = [
831+ Parked { seq: 7, swap: GIB },
832+ Parked {
833+ seq: 3,
834+ swap: 2 * GIB,
835+ },
836+ ];
837+ assert_eq!(pick_thaw(&[], 0, 10 * GIB), None);
838+ // The oldest is index 1 and needs 2 GiB.
839+ assert_eq!(pick_thaw(&parked, 1, 3 * GIB), Some(1));
840+ assert_eq!(pick_thaw(&parked, 1, GIB), None);
841+ // Nothing else runs: always thaw, whatever the headroom.
842+ assert_eq!(pick_thaw(&parked, 0, 0), Some(1));
843+ }
844+
845+ #[test]
846+ fn gate_closes_for_parked_jobs_and_pressure() {
847+ assert!(Gate::default().open());
848+ assert!(
849+ !Gate {
850+ frozen: 1,
851+ hot: false
852+ }
853+ .open()
854+ );
855+ assert!(
856+ !Gate {
857+ frozen: 0,
858+ hot: true
859+ }
860+ .open()
861+ );
862+ // A pressure signal heats the box, a job event cools it unless it is still at high.
863+ assert!(hot_after(Cause::Pressure, false));
864+ assert!(!hot_after(Cause::Jobs, false));
865+ assert!(hot_after(Cause::Jobs, true));
866+ }
867+
868+ /// A fake box: a temp dir with the files the controller reads.
869+ fn fake_box(budget: u64) -> (tempfile::TempDir, Arc<Pressure>) {
870+ let tmp = tempfile::tempdir().expect("tempdir");
871+ let dir = tmp.path().to_path_buf();
872+ fs::write(dir.join("memory.max"), budget.to_string()).expect("max");
873+ fs::write(dir.join("memory.current"), "0").expect("current");
874+ (tmp, Arc::new(Pressure::at(dir, budget)))
875+ }
876+
877+ fn fake_job(box_dir: &Path, id: &str, current: u64) -> PathBuf {
878+ let dir = box_dir.join(format!("forge-job-{id}-1"));
879+ fs::create_dir(&dir).expect("job dir");
880+ fs::write(dir.join("memory.current"), current.to_string()).expect("current");
881+ fs::write(dir.join("memory.stat"), format!("anon {current}\n")).expect("stat");
882+ dir
883+ }
884+
885+ #[test]
886+ fn settle_sets_high_for_two_jobs_and_relaxes_it_for_one() {
887+ let (tmp, pressure) = fake_box(6 * GIB);
888+ let (tx, _rx) = mpsc::channel(8);
889+ let a = pressure.register("a", "build", tx.clone());
890+ let b = pressure.register("b", "test", tx);
891+ fake_job(tmp.path(), "a", GIB);
892+ fake_job(tmp.path(), "b", GIB);
893+ pressure.settle(Cause::Jobs);
894+ let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high");
895+ assert_eq!(high, (6 * GIB - HIGH_MARGIN_MIN).to_string());
896+ drop(b);
897+ pressure.settle(Cause::Jobs);
898+ let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high");
899+ assert_eq!(high, "max");
900+ assert!(!a.requeued());
901+ }
902+
903+ #[test]
904+ fn pressure_with_a_lone_job_does_nothing_but_close_the_gate() {
905+ let (tmp, pressure) = fake_box(6 * GIB);
906+ let (tx, mut rx) = mpsc::channel(8);
907+ let a = pressure.register("a", "build", tx);
908+ let dir = fake_job(tmp.path(), "a", GIB);
909+ pressure.settle(Cause::Pressure);
910+ assert!(!a.requeued());
911+ assert!(!dir.join("cgroup.freeze").exists());
912+ assert!(rx.try_recv().is_err());
913+ assert!(!pressure.lock().gate.open());
914+ // The job ending cools the box.
915+ drop(a);
916+ pressure.settle(Cause::Jobs);
917+ assert!(pressure.lock().gate.open());
918+ }
919+
920+ #[test]
921+ fn a_job_that_cannot_be_parked_is_killed_for_requeue() {
922+ // In a fake cgroup memory.current never drops, so parking fails the way a full swap does.
923+ let (tmp, pressure) = fake_box(6 * GIB);
924+ let (tx_a, _rx_a) = mpsc::channel(8);
925+ let (tx_b, mut rx_b) = mpsc::channel(8);
926+ let a = pressure.register("a", "build", tx_a);
927+ let b = pressure.register("b", "test", tx_b);
928+ fake_job(tmp.path(), "a", 2 * GIB);
929+ let dir_b = fake_job(tmp.path(), "b", 2 * GIB);
930+ // A tiny anon size, so the host's real SwapFree does not decide this test.
931+ fs::write(dir_b.join("memory.stat"), "anon 1\n").expect("stat");
932+ pressure.settle(Cause::Jobs);
933+ pressure.settle(Cause::Pressure);
934+ // The youngest job is the victim, the older one keeps running.
935+ assert!(b.requeued());
936+ assert!(!a.requeued());
937+ assert_eq!(
938+ fs::read_to_string(dir_b.join("cgroup.kill")).expect("kill"),
939+ "1"
940+ );
941+ let mut lines = String::new();
942+ while let Ok(bytes) = rx_b.try_recv() {
943+ lines.push_str(&String::from_utf8_lossy(&bytes));
944+ }
945+ assert!(lines.contains("paused: memory pressure, waiting for build"));
946+ assert!(lines.contains("run it again later"));
947+ // A killed job no longer counts as running, so memory.high relaxes.
948+ assert_eq!(
949+ fs::read_to_string(tmp.path().join("memory.high")).expect("high"),
950+ "max"
951+ );
952+ }
953+
954+ #[test]
955+ fn a_registration_tracks_pause_time_and_drops_its_log() {
956+ let (_tmp, pressure) = fake_box(GIB);
957+ let (tx, mut rx) = mpsc::channel(8);
958+ let reg = pressure.register("a", "build", tx);
959+ assert_eq!(reg.paused(), Duration::ZERO);
960+ reg.handle.pause();
961+ std::thread::sleep(Duration::from_millis(5));
962+ assert!(reg.paused() > Duration::ZERO);
963+ let lasted = reg.handle.resume();
964+ assert!(lasted > Duration::ZERO);
965+ assert!(reg.paused() >= lasted);
966+ drop(reg);
967+ // The sender is gone with the registration, so the log shipper can finish.
968+ assert!(matches!(
969+ rx.try_recv(),
970+ Err(mpsc::error::TryRecvError::Disconnected)
971+ ));
972+ }
973+
974+ #[test]
975+ fn create_box_enables_controllers_and_sets_limits() {
976+ let tmp = tempfile::tempdir().expect("tempdir");
977+ let parent = tmp.path();
978+ fs::write(parent.join("cgroup.subtree_control"), "memory pids\n").expect("parent");
979+ fs::create_dir(parent.join(BOX_NAME)).expect("box dir");
980+ fs::write(parent.join(BOX_NAME).join("cgroup.subtree_control"), "").expect("box");
981+ let dir = create_box(parent, 4 * GIB).expect("box");
982+ assert_eq!(dir, parent.join(BOX_NAME));
983+ // The fake files stand in for the kernel: the write replaced them with the new text.
984+ assert_eq!(
985+ fs::read_to_string(dir.join("memory.max")).expect("max"),
986+ (4 * GIB).to_string()
987+ );
988+ assert_eq!(
989+ fs::read_to_string(dir.join("memory.swap.max")).expect("swap"),
990+ (4 * GIB).to_string()
991+ );
992+ assert_eq!(
993+ fs::read_to_string(dir.join("memory.high")).expect("high"),
994+ "max"
995+ );
996+ assert_eq!(
997+ fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"),
998+ "+cpu"
999+ );
1000+ // A second call adopts the existing box.
1001+ assert!(create_box(parent, 4 * GIB).is_ok());
1002+ }
1003+
1004+ #[tokio::test]
1005+ async fn wait_open_returns_at_once_on_an_open_gate_and_wakes_on_change() {
1006+ let (_tmp, pressure) = fake_box(GIB);
1007+ pressure.wait_open().await;
1008+ pressure.lock().gate.hot = true;
1009+ let waiter = {
1010+ let p = pressure.clone();
1011+ tokio::spawn(async move { p.wait_open().await })
1012+ };
1013+ tokio::task::yield_now().await;
1014+ assert!(!waiter.is_finished());
1015+ pressure.lock().gate.hot = false;
1016+ pressure.changed.notify_waiters();
1017+ tokio::time::timeout(Duration::from_secs(5), waiter)
1018+ .await
1019+ .expect("woken")
1020+ .expect("join");
1021+ }
1022+
1023+ /// Needs a delegated memory controller, so it only runs on request:
1024+ /// `cargo test -p forge-runner real_box -- --ignored`. Builds a real box next to this
1025+ /// process, checks the watcher can arm inotify and the PSI trigger, and removes the box.
1026+ #[tokio::test]
1027+ #[ignore = "needs delegated cgroup v2 controllers"]
1028+ async fn real_box_starts_and_reports_headroom() {
1029+ let shutdown = CancellationToken::new();
1030+ let Some(pressure) = Pressure::start(2 * GIB, shutdown.clone()).await else {
1031+ eprintln!("no delegated memory controller, skipping");
1032+ return;
1033+ };
1034+ assert!(pressure.headroom().is_some());
1035+ pressure.wait_open().await;
1036+ shutdown.cancel();
1037+ // The watcher is gone once cancelled; the empty box can be removed.
1038+ tokio::time::sleep(Duration::from_millis(100)).await;
1039+ let _ = fs::remove_dir(&pressure.dir);
1040+ }
1041+}
crates/forge-runner/src/runner.rsmodified+77 -2
@@ -21,6 +21,7 @@ use crate::limiter::Limiter;
21 use crate::logs::{self, PumpConfig};21 use crate::logs::{self, PumpConfig};
22 use crate::memory::MemoryGate;22 use crate::memory::MemoryGate;
23 use crate::oom::OomSink;23 use crate::oom::OomSink;
24+use crate::pressure::Pressure;
24 use crate::restart::{self, RestartState, Step};25 use crate::restart::{self, RestartState, Step};
25 use crate::update::{self, Installed, UpdateState};26 use crate::update::{self, Installed, UpdateState};
26 use crate::workspace;27 use crate::workspace;
@@ -80,6 +81,8 @@ pub struct Runner {
80 memory: Arc<MemoryGate>,81 memory: Arc<MemoryGate>,
81 /// A restart an admin asked for, see [`restart`].82 /// A restart an admin asked for, see [`restart`].
82 restart: Arc<RestartState>,83 restart: Arc<RestartState>,
84+ /// The memory box and its controller, when the host allows it, see [`crate::pressure`].
85+ pressure: Option<Arc<Pressure>>,
83 }86 }
84 87
85 impl Runner {88 impl Runner {
@@ -100,9 +103,17 @@ impl Runner {
100 limiter,103 limiter,
101 memory,104 memory,
102 restart: Arc::new(RestartState::default()),105 restart: Arc::new(RestartState::default()),
106+ pressure: None,
103 })107 })
104 }108 }
105 109
110+ /// Turns on reactive memory control: jobs are paused under pressure, and no job is claimed
111+ /// while one is parked.
112+ pub fn with_pressure(mut self, pressure: Option<Arc<Pressure>>) -> Self {
113+ self.pressure = pressure;
114+ self
115+ }
116+
106 /// Turns on the build cache for every job this runner runs.117 /// Turns on the build cache for every job this runner runs.
107 pub fn with_cache(mut self, cache: CacheStore) -> Self {118 pub fn with_cache(mut self, cache: CacheStore) -> Self {
108 self.cache = Some(Arc::new(cache));119 self.cache = Some(Arc::new(cache));
@@ -211,6 +222,15 @@ impl Runner {
211 continue;222 continue;
212 }223 }
213 224
225+ if let Some(pressure) = &self.pressure {
226+ // A parked job or a box under pressure means no new job. The controller wakes
227+ // this when that changes.
228+ tokio::select! {
229+ _ = shutdown.cancelled() => break RunEnd::Stopped,
230+ () = self.restart.changed() => continue,
231+ () = pressure.wait_open() => {}
232+ }
233+ }
214 let permit = tokio::select! {234 let permit = tokio::select! {
215 _ = shutdown.cancelled() => break RunEnd::Stopped,235 _ = shutdown.cancelled() => break RunEnd::Stopped,
216 () = self.restart.changed() => continue,236 () = self.restart.changed() => continue,
@@ -229,7 +249,12 @@ impl Runner {
229 &self.config.labels,249 &self.config.labels,
230 Some(self.limiter.current()),250 Some(self.limiter.current()),
231 Some(MemoryClaim {251 Some(MemoryClaim {
232- free: self.memory.free(),252+ // Real room in the box when memory control is on, else what is promised.
253+ free: self
254+ .pressure
255+ .as_ref()
256+ .and_then(|p| p.headroom())
257+ .unwrap_or_else(|| self.memory.free()),
233 budget: self.memory.budget(),258 budget: self.memory.budget(),
234 reserve: self.memory.default_reserve(),259 reserve: self.memory.default_reserve(),
235 }),260 }),
@@ -332,11 +357,26 @@ impl Runner {
332 let job_cancel = shutdown.child_token();357 let job_cancel = shutdown.child_token();
333 let timed_out = Arc::new(AtomicBool::new(false));358 let timed_out = Arc::new(AtomicBool::new(false));
334 let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone());359 let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone());
360+ let registration = self
361+ .pressure
362+ .as_ref()
363+ .map(|p| p.register(&job.job_id, &job.job_name, tx.clone()));
335 let timer = {364 let timer = {
336 let cancel = job_cancel.clone();365 let cancel = job_cancel.clone();
337 let flag = timed_out.clone();366 let flag = timed_out.clone();
367+ let pause = registration.as_ref().map(|r| r.pause_clock());
338 tokio::spawn(async move {368 tokio::spawn(async move {
339- tokio::time::sleep(timeout).await;369+ // Time spent frozen does not count, so the deadline moves out by the pauses.
370+ let started = Instant::now();
371+ loop {
372+ let paused = pause.as_ref().map(|p| p.paused()).unwrap_or_default();
373+ let due = timeout + paused;
374+ let elapsed = started.elapsed();
375+ if elapsed >= due {
376+ break;
377+ }
378+ tokio::time::sleep(due - elapsed).await;
379+ }
340 flag.store(true, Ordering::SeqCst);380 flag.store(true, Ordering::SeqCst);
341 cancel.cancel();381 cancel.cancel();
342 })382 })
@@ -372,6 +412,39 @@ impl Runner {
372 },412 },
373 };413 };
374 414
415+ // The memory controller killed this job to run it again later: give it back to the queue
416+ // without a result.
417+ if registration.as_ref().is_some_and(|r| r.requeued()) {
418+ heartbeat.abort();
419+ timer.abort();
420+ drop(registration);
421+ drop(tx);
422+ let _ = pump.await;
423+ let reason = "killed under memory pressure on the runner";
424+ if let Err(e) = self
425+ .client
426+ .requeue(&job.job_id, &job.job_token, reason)
427+ .await
428+ {
429+ tracing::warn!(job_id = %job.job_id, error = %e, "requeue failed, failing the job");
430+ let failed = ExecResult {
431+ outcome: Outcome::Error,
432+ exit_code: None,
433+ message: Some(format!(
434+ "out of memory, and the forge could not requeue it: {e}"
435+ )),
436+ };
437+ self.finish(&job, &failed, None).await;
438+ }
439+ if let Some(dir) = workspace_dir
440+ && let Err(e) = workspace::cleanup(&dir).await
441+ {
442+ tracing::warn!(job_id = %job.job_id, error = %e, "workspace cleanup failed");
443+ }
444+ tracing::info!(job_id = %job.job_id, "job requeued after memory pressure");
445+ return Outcome::Cancelled;
446+ }
447+
375 // Artifacts only come from a successful run.448 // Artifacts only come from a successful run.
376 let upload_error = match workspace_dir.as_deref() {449 let upload_error = match workspace_dir.as_deref() {
377 Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => {450 Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => {
@@ -389,6 +462,8 @@ impl Runner {
389 462
390 heartbeat.abort();463 heartbeat.abort();
391 timer.abort();464 timer.abort();
465+ // The log sender it holds must go before the log shipper can finish.
466+ drop(registration);
392 if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled {467 if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled {
393 result = ExecResult {468 result = ExecResult {
394 outcome: Outcome::Failure,469 outcome: Outcome::Failure,
crates/forge-runner/src/sandbox/helper.rsmodified+28 -4
@@ -335,6 +335,23 @@ fn run_job(req: &SandboxRequest, layout: &Layout, rootfs: &Path) -> Result<i32,
335 /// parent slice. The path is relative to the cgroup2 mount, so the directory is335 /// parent slice. The path is relative to the cgroup2 mount, so the directory is
336 /// `/sys/fs/cgroup` joined with it.336 /// `/sys/fs/cgroup` joined with it.
337 pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, SandboxError> {337 pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, SandboxError> {
338+ let base = job_cgroup_base()?;
339+ // With the runner's box in place (see `crate::pressure`), jobs live inside it.
340+ let base = if box_ready(&base) {
341+ base.join(BOX_NAME)
342+ } else {
343+ base
344+ };
345+ // The helper's pid keeps the name unique even if two helpers share a job id.
346+ Ok(base.join(format!("forge-job-{job_id}-{helper_pid}")))
347+}
348+
349+/// The name of the runner's box cgroup, the parent of every job cgroup when memory control is on.
350+pub const BOX_NAME: &str = "forge-jobs";
351+
352+/// The cgroup that holds the job cgroups, or the box under it: the runner's parent cgroup when it
353+/// is a plain domain cgroup, else the runner's own. Absolute, relative to the cgroup2 mount.
354+pub fn job_cgroup_base() -> Result<PathBuf, SandboxError> {
338 let text = fs::read_to_string("/proc/self/cgroup")355 let text = fs::read_to_string("/proc/self/cgroup")
339 .map_err(SandboxError::io("cannot read /proc/self/cgroup"))?;356 .map_err(SandboxError::io("cannot read /proc/self/cgroup"))?;
340 let own = text357 let own = text
@@ -342,12 +359,19 @@ pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, Sandbox
342 .find_map(|line| line.strip_prefix("0::"))359 .find_map(|line| line.strip_prefix("0::"))
343 .ok_or_else(|| SandboxError::Setup("cgroup v2 is not available".into()))?;360 .ok_or_else(|| SandboxError::Setup("cgroup v2 is not available".into()))?;
344 let own = PathBuf::from(own.trim());361 let own = PathBuf::from(own.trim());
345- let base = match own.parent() {362+ Ok(match own.parent() {
346 Some(parent) if is_plain_domain(parent) => parent.to_path_buf(),363 Some(parent) if is_plain_domain(parent) => parent.to_path_buf(),
347 _ => own,364 _ => own,
348- };365+ })
349- // The helper's pid keeps the name unique even if two helpers share a job id.366+}
350- Ok(base.join(format!("forge-job-{job_id}-{helper_pid}")))367+
368+/// Whether the box exists under `base` with the memory controller enabled for its children.
369+fn box_ready(base: &Path) -> bool {
370+ let dir = Path::new("/sys/fs/cgroup")
371+ .join(base.strip_prefix("/").unwrap_or(base))
372+ .join(BOX_NAME);
373+ fs::read_to_string(dir.join("cgroup.subtree_control"))
374+ .is_ok_and(|t| t.split_whitespace().any(|c| c == "memory"))
351 }375 }
352 376
353 /// Whether `cgroup` (absolute, inside the cgroup2 mount) is a normal domain cgroup. A threaded377 /// Whether `cgroup` (absolute, inside the cgroup2 mount) is a normal domain cgroup. A threaded
crates/forge-runner/src/sandbox/mod.rsmodified+1 -1
@@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
18 use crate::config::Limits;18 use crate::config::Limits;
19 use idmap::IdMap;19 use idmap::IdMap;
20 20
21-pub use helper::{helper_main, job_cgroup_path};21+pub use helper::{BOX_NAME, helper_main, job_cgroup_base, job_cgroup_path};
22 pub use spec::build_spec;22 pub use spec::build_spec;
23 23
24 /// What the runner sends the helper on stdin. It carries the secrets, so it is never written to24 /// What the runner sends the helper on stdin. It carries the secrets, so it is never written to
docs/ci.mdmodified+50 -32
@@ -66,46 +66,64 @@ directory.
66 66
67 ### Memory67 ### Memory
68 68
69-`memory` is the job's expected peak, not a limit you hope it stays under. A runner counts the69+`memory` is optional. You do not need it: the runner reacts to real memory use instead of trusting a
70-`memory` of its running jobs against its memory budget and takes a new job only when the sum still70+number. When you set it, it is a hint for admission and an explicit cap for the job.
71-fits, so two jobs that each peak at 4g never run together on a 7.6 GiB host and the kernel never
72-has to kill one of them for lack of RAM. A job without `memory` reserves the runner's default
73-(`limits.reserve_memory`, 1g unless an admin changed it).
74 71
75 ```toml72 ```toml
76 [jobs.build]73 [jobs.build]
77 image = "docker.io/library/rust:1"74 image = "docker.io/library/rust:1"
78 run = "cargo build --release"75 run = "cargo build --release"
79-memory = "4g"76+memory = "4g" # optional
80 ```77 ```
81 78
82-How it is used:79+What the runner does without it:
83-80+
84-- Admission. The runner tells the forge how much memory it can still admit with every claim, and the81+- Optimistic admission. A job without `memory` reserves the runner's default (`limits.reserve_memory`,
85- forge hands out the first queued job whose reservation fits. A smaller job may run before a bigger82+ 1g unless an admin changed it) and may use up to the whole memory budget of the runner. The
86- one that has to wait, so a small job is not stuck behind a big one. To keep the big job from83+ runner tells the forge how much memory its box has left with every claim, and the forge hands out
87- starving, a job that does not fit and has waited 5 minutes stops smaller jobs from passing it on84+ the first queued job whose reservation fits. A smaller job may run before a bigger one that has
88- that runner: the runner runs down its current jobs until the big one fits. A job that asks for85+ to wait. To keep the big job from starving, a job that does not fit and has waited 5 minutes
89- more than the runner's whole budget is treated as asking for the whole budget, so it runs alone86+ stops smaller jobs from passing it on that runner. A job that asks for more than the runner's
90- instead of waiting forever.87+ whole budget runs alone.
91-- Limit. The job's cgroup `memory.max` (podman `--memory`) is `memory` plus slack (1/16, at least88+- Pause and park. The runner puts all job cgroups in one box (`forge-jobs`) capped at the memory
92- 256 MiB), and swap is off for the job (`memory.swap.max` is 0). A job that goes over is89+ budget. When two or more jobs run and the box nears its cap, the runner freezes the youngest
93- OOM-killed inside its own cgroup. Without `memory`, the limit is the larger of the runner's90+ job and pushes its memory to swap, and logs `runner: paused: memory pressure, waiting for <job>`
94- `limits.memory` and `limits.reserve_memory`.91+ and `runner: parked <n> MiB in swap` in that job. The older job keeps its RAM and finishes. The
92+ parked job thaws when the box has room for what is in its swap or nothing else runs, and logs
93+ `runner: resumed after <time>`. The time a job spent frozen does not count toward its
94+ `timeout_minutes`. While a job is parked the runner claims no new job.
95+- Requeue. If the parked job's memory does not go to swap (the host has no free swap, or the
96+ kernel refuses), the runner kills it and gives it back to the queue, keeping its place. It is
97+ not reported as failed.
98+- A lone job is never paused. It may use the whole box, and if it runs out of memory it is
99+ OOM-killed and reported as below.
100+
101+With `memory` set:
102+
103+- The job's cgroup `memory.max` (podman `--memory`) is `memory` plus slack (1/16, at least
104+ 256 MiB), and swap is off for the job (`memory.swap.max` is 0) while it runs. A job that goes over
105+ is OOM-killed inside its own cgroup. Without `memory`, the limit is the box budget. Podman
106+ jobs keep the larger of the runner's `limits.memory` and `limits.reserve_memory`.
107+- The reservation is `memory` instead of the default, which keeps a job that you know is heavy from
108+ being started next to another one.
95 - It is the same for every job in a matrix.109 - It is the same for every job in a matrix.
96-- OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's110+
97- `memory.events` before the cgroup is deleted, and the runner sends `oom_killed` and `oom_kills`111+Host requirements for pausing: swap must be present (a parked job lives in swap), and the user the
98- in the finish request. A job where rustc was killed still ends with exit 101 and only a112+runner runs as needs the `memory`, `cpu` and `pids` cgroup v2 controllers delegated (see
99- `signal: 9` line in its log, so the exit code never showed it. The job page then says "killed:113+[Check the host](#1-check-the-host)). Without delegated controllers, or on the podman executor, the runner
100- out of memory", and the admin alert for killed jobs fires. The counters are the kernel's114+works as before: no box, no pausing.
101- `oom_kill` (processes of the cgroup killed by any OOM killer, a host-wide one included, since115+
102- Linux 4.13) and `oom` (the cgroup hit its own limit). A process killed outside the job's cgroup is116+OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's `memory.events`
103- not counted. The podman executor does not report this.117+before the cgroup is deleted, and the runner sends `oom_killed` and `oom_kills` in the finish
104-118+request. A job where rustc was killed still ends with exit 101 and only a `signal: 9` line in its
105-Runners and forges that predate `memory` still work together. A runner that does not report free119+log, so the exit code never showed it. The job page then says "killed: out of memory", and the
106-memory gets the oldest queued job as before, and a runner that gets a job with no `memory` field120+admin alert for killed jobs fires. The counters are the kernel's `oom_kill` (processes of the
107-reserves its default. Upgrade the runner together with the forge: a forge that predates this121+cgroup killed by any OOM killer, a host-wide one included, since Linux 4.13) and `oom` (the cgroup
108-hands out jobs without looking at memory, and the runner then cannot refuse them.122+hit its own limit). A process killed outside the job's cgroup is not counted. The podman executor
123+does not report this.
124+
125+A forge that predates requeue answers the runner's requeue call with an error. The runner then
126+fails that job instead.
109 127
110 ### Example128 ### Example
111 129