Memory-aware job admission so a runner never over-commits its RAM
Browse files at this commit69c5821af1dc70e2eb012f513f2573c07c362e1fParent: baf3aea- feat
- memory-aware job admission so a runner never over-commits its RAM
26 changed files +1467 -30
- .forge/ci.toml +10 -1
- Cargo.lock +1 -0
- crates/forge-ci/src/config.rs +82 -0
- crates/forge-ci/src/error.rs +3 -0
- crates/forge-ci/src/lib.rs +1 -0
- crates/forge-ci/src/proto.rs +35 -0
- crates/forge-ci/src/size.rs +96 -0
- crates/forge-core/Cargo.toml +1 -0
- crates/forge-core/migrations/0060_runner_memory.sql +7 -0
- crates/forge-core/src/ci.rs +162 -0
- crates/forge-core/src/store/ci.rs +250 -12
- crates/forge-core/src/store/migrate.rs +1 -0
- crates/forge-runner/src/cache.rs +1 -0
- crates/forge-runner/src/client.rs +35 -3
- crates/forge-runner/src/config.rs +150 -0
- crates/forge-runner/src/executor.rs +20 -2
- crates/forge-runner/src/lib.rs +1 -0
- crates/forge-runner/src/memory.rs +311 -0
- crates/forge-runner/src/runner.rs +20 -0
- crates/forge-runner/src/sandbox/spec.rs +9 -0
- crates/forge-runner/tests/builtin.rs +1 -0
- crates/forge-runner/tests/flow.rs +1 -0
- crates/forge-web/src/ci/api.rs +52 -8
- crates/forge-web/src/ci/api_tests.rs +115 -0
- crates/forge-web/src/pages/admin_runners.rs +38 -1
- docs/ci.md +64 -3
.forge/ci.tomlmodified+10 -1
| @@ -2,7 +2,12 @@ | |||
| 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 allows | 4 | # 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). The build job's artifacts are still only used | 5 | +# (two runners, or one runner with concurrency = 2). Capacity includes memory: each job declares its |
| 6 | +# peak in `memory`, and a runner admits a job only while the declared memory of its running jobs | ||
| 7 | +# fits its budget. On the 7.6 GiB runner host the budget is about 6.5 GiB, and test plus build | ||
| 8 | +# declare 4g each, so they do NOT run together there: one heavy job at a time is the point. An | ||
| 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 used | ||
| 6 | # once the whole run is green: a tag push matching "v*" publishes a release with the build job's | 11 | # once the whole run is green: a tag push matching "v*" publishes a release with the build job's |
| 7 | # binaries and SHA256SUMS, and self-update deploys dist/forge, only when every job in the run, | 12 | # binaries and SHA256SUMS, and self-update deploys dist/forge, only when every job in the run, |
| 8 | # including test, succeeded. | 13 | # including test, succeeded. |
| @@ -16,6 +21,8 @@ tags = ["v*"] | |||
| 16 | [jobs.test] | 21 | [jobs.test] |
| 17 | image = "docker.io/library/rust:1" | 22 | image = "docker.io/library/rust:1" |
| 18 | # 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. | 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. |
| 24 | +# memory: rustc peaked at 3.1 to 3.6 GB RSS in the OOM data, so 4g is the expected peak, and the job's cgroup is capped at 4g plus slack. | ||
| 25 | +memory = "4g" | ||
| 19 | env = { CARGO_BUILD_JOBS = "1", CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" } | 26 | env = { CARGO_BUILD_JOBS = "1", CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" } |
| 20 | run = """ | 27 | run = """ |
| 21 | cargo test --workspace | 28 | cargo test --workspace |
| @@ -26,6 +33,8 @@ timeout_minutes = 120 | |||
| 26 | [jobs.build] | 33 | [jobs.build] |
| 27 | image = "docker.io/library/rust:1" | 34 | image = "docker.io/library/rust:1" |
| 28 | # 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. | 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. |
| 36 | +# memory: the dist profile uses thin LTO, whose link step peaks like the test build (3.1 to 3.6 GB RSS seen), so 4g. | ||
| 37 | +memory = "4g" | ||
| 29 | env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" } | 38 | env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" } |
| 30 | run = """ | 39 | run = """ |
| 31 | cargo build --profile dist -p forge-web -p forge-runner | 40 | cargo build --profile dist -p forge-web -p forge-runner |
Cargo.lockmodified+1 -0
| @@ -1985,6 +1985,7 @@ dependencies = [ | |||
| 1985 | "argon2", | 1985 | "argon2", |
| 1986 | "base64 0.23.1", | 1986 | "base64 0.23.1", |
| 1987 | "chacha20poly1305", | 1987 | "chacha20poly1305", |
| 1988 | + "forge-ci", | ||
| 1988 | "hex", | 1989 | "hex", |
| 1989 | "hmac 0.13.0", | 1990 | "hmac 0.13.0", |
| 1990 | "image", | 1991 | "image", |
crates/forge-ci/src/config.rsmodified+82 -0
| @@ -196,6 +196,15 @@ pub struct JobSpec { | |||
| 196 | pub timeout_minutes: u32, | 196 | pub timeout_minutes: u32, |
| 197 | #[serde(default = "default_network")] | 197 | #[serde(default = "default_network")] |
| 198 | pub network: bool, | 198 | pub network: bool, |
| 199 | + /// The job's expected peak memory, as `4g` or `512m` in ci.toml. Stored as bytes. The runner | ||
| 200 | + /// admits the job only when this much is free, and caps the job's cgroup near it. Absent | ||
| 201 | + /// means the runner's default reservation. See docs/ci.md, Memory. | ||
| 202 | + #[serde( | ||
| 203 | + default, | ||
| 204 | + deserialize_with = "deserialize_memory", | ||
| 205 | + skip_serializing_if = "Option::is_none" | ||
| 206 | + )] | ||
| 207 | + pub memory: Option<u64>, | ||
| 199 | /// The `matrix` table. Only present before expansion: [`parse_config`] replaces a matrix job | 208 | /// The `matrix` table. Only present before expansion: [`parse_config`] replaces a matrix job |
| 200 | /// with one job per combination, and those have no matrix. | 209 | /// with one job per combination, and those have no matrix. |
| 201 | #[serde(default, skip_serializing_if = "Option::is_none")] | 210 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| @@ -243,6 +252,28 @@ pub struct MatrixSpec { | |||
| 243 | pub axes: BTreeMap<String, Vec<MatrixValue>>, | 252 | pub axes: BTreeMap<String, Vec<MatrixValue>>, |
| 244 | } | 253 | } |
| 245 | 254 | ||
| 255 | +/// Smallest and largest `memory` a job may declare, in bytes. | ||
| 256 | +pub const MEMORY_RANGE_BYTES: std::ops::RangeInclusive<u64> = (64 << 20)..=(1024 << 30); | ||
| 257 | + | ||
| 258 | +/// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds). | ||
| 259 | +fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> { | ||
| 260 | + #[derive(Deserialize)] | ||
| 261 | + #[serde(untagged)] | ||
| 262 | + enum Raw { | ||
| 263 | + Bytes(u64), | ||
| 264 | + Text(String), | ||
| 265 | + } | ||
| 266 | + match Option::<Raw>::deserialize(d)? { | ||
| 267 | + None => Ok(None), | ||
| 268 | + Some(Raw::Bytes(n)) => Ok(Some(n)), | ||
| 269 | + Some(Raw::Text(text)) => crate::size::parse_size(&text).map(Some).ok_or_else(|| { | ||
| 270 | + serde::de::Error::custom(format!( | ||
| 271 | + "memory must be a size such as 4g or 512m, got {text:?}" | ||
| 272 | + )) | ||
| 273 | + }), | ||
| 274 | + } | ||
| 275 | +} | ||
| 276 | + | ||
| 246 | fn default_timeout_minutes() -> u32 { | 277 | fn default_timeout_minutes() -> u32 { |
| 247 | DEFAULT_TIMEOUT_MINUTES | 278 | DEFAULT_TIMEOUT_MINUTES |
| 248 | } | 279 | } |
| @@ -953,6 +984,14 @@ fn validate_job( | |||
| 953 | value: job.timeout_minutes, | 984 | value: job.timeout_minutes, |
| 954 | }); | 985 | }); |
| 955 | } | 986 | } |
| 987 | + if let Some(memory) = job.memory | ||
| 988 | + && !MEMORY_RANGE_BYTES.contains(&memory) | ||
| 989 | + { | ||
| 990 | + return Err(ConfigError::InvalidMemory { | ||
| 991 | + job: name.to_string(), | ||
| 992 | + value: crate::size::format_size(memory), | ||
| 993 | + }); | ||
| 994 | + } | ||
| 956 | Ok(()) | 995 | Ok(()) |
| 957 | } | 996 | } |
| 958 | 997 | ||
| @@ -1087,6 +1126,49 @@ artifacts = ["target/release/forge"] | |||
| 1087 | )); | 1126 | )); |
| 1088 | } | 1127 | } |
| 1089 | 1128 | ||
| 1129 | + #[test] | ||
| 1130 | + fn memory_is_parsed_to_bytes() { | ||
| 1131 | + let cfg = parse_config(&job_toml("memory = \"4g\"")).unwrap(); | ||
| 1132 | + assert_eq!(cfg.jobs["build"].memory, Some(4 << 30)); | ||
| 1133 | + let cfg = parse_config(&job_toml("memory = \"512M\"")).unwrap(); | ||
| 1134 | + assert_eq!(cfg.jobs["build"].memory, Some(512 << 20)); | ||
| 1135 | + assert_eq!( | ||
| 1136 | + parse_config(&job_toml("")).unwrap().jobs["build"].memory, | ||
| 1137 | + None | ||
| 1138 | + ); | ||
| 1139 | + // The stored spec holds bytes and reads back the same. | ||
| 1140 | + let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"]; | ||
| 1141 | + let json = serde_json::to_string(job).unwrap(); | ||
| 1142 | + assert!(json.contains("\"memory\":4294967296"), "{json}"); | ||
| 1143 | + let back: JobSpec = serde_json::from_str(&json).unwrap(); | ||
| 1144 | + assert_eq!(back.memory, Some(4 << 30)); | ||
| 1145 | + // A spec stored before the field existed has none. | ||
| 1146 | + let old = json.replace(",\"memory\":4294967296", ""); | ||
| 1147 | + assert_eq!(serde_json::from_str::<JobSpec>(&old).unwrap().memory, None); | ||
| 1148 | + } | ||
| 1149 | + | ||
| 1150 | + #[test] | ||
| 1151 | + fn bad_memory_is_an_error() { | ||
| 1152 | + for bad in ["\"lots\"", "\"0\"", "\"-1g\"", "true"] { | ||
| 1153 | + assert!( | ||
| 1154 | + matches!( | ||
| 1155 | + err_of(&job_toml(&format!("memory = {bad}"))), | ||
| 1156 | + ConfigError::Toml(_) | ||
| 1157 | + ), | ||
| 1158 | + "{bad}" | ||
| 1159 | + ); | ||
| 1160 | + } | ||
| 1161 | + for bad in ["\"1m\"", "\"2t\""] { | ||
| 1162 | + assert!( | ||
| 1163 | + matches!( | ||
| 1164 | + err_of(&job_toml(&format!("memory = {bad}"))), | ||
| 1165 | + ConfigError::InvalidMemory { .. } | ||
| 1166 | + ), | ||
| 1167 | + "{bad}" | ||
| 1168 | + ); | ||
| 1169 | + } | ||
| 1170 | + } | ||
| 1171 | + | ||
| 1090 | #[test] | 1172 | #[test] |
| 1091 | fn no_jobs_is_an_error() { | 1173 | fn no_jobs_is_an_error() { |
| 1092 | assert_eq!(err_of("[on]\nmanual = true\n"), ConfigError::NoJobs); | 1174 | assert_eq!(err_of("[on]\nmanual = true\n"), ConfigError::NoJobs); |
crates/forge-ci/src/error.rsmodified+3 -0
| @@ -69,6 +69,9 @@ pub enum ConfigError { | |||
| 69 | #[error("job {job:?}: timeout_minutes must be between 1 and 360, got {value}")] | 69 | #[error("job {job:?}: timeout_minutes must be between 1 and 360, got {value}")] |
| 70 | InvalidTimeout { job: String, value: u32 }, | 70 | InvalidTimeout { job: String, value: u32 }, |
| 71 | 71 | ||
| 72 | + #[error("job {job:?}: memory must be between 64m and 1024g, got {value}")] | ||
| 73 | + InvalidMemory { job: String, value: String }, | ||
| 74 | + | ||
| 72 | #[error("job {job:?}: invalid cache path {path:?}: {reason}")] | 75 | #[error("job {job:?}: invalid cache path {path:?}: {reason}")] |
| 73 | InvalidCachePath { | 76 | InvalidCachePath { |
| 74 | job: String, | 77 | job: String, |
crates/forge-ci/src/lib.rsmodified+1 -0
| @@ -7,5 +7,6 @@ pub mod cron; | |||
| 7 | pub mod error; | 7 | pub mod error; |
| 8 | pub mod mask; | 8 | pub mod mask; |
| 9 | pub mod proto; | 9 | pub mod proto; |
| 10 | +pub mod size; | ||
| 10 | 11 | ||
| 11 | pub use error::ConfigError; | 12 | pub use error::ConfigError; |
crates/forge-ci/src/proto.rsmodified+35 -0
| @@ -71,6 +71,18 @@ pub struct ClaimRequest { | |||
| 71 | /// build, so the forge gates features on this list. Absent from an older runner. | 71 | /// build, so the forge gates features on this list. Absent from an older runner. |
| 72 | #[serde(default, skip_serializing_if = "Vec::is_empty")] | 72 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 73 | pub capabilities: Vec<String>, | 73 | pub capabilities: Vec<String>, |
| 74 | + /// Memory the runner can admit right now: its budget minus what running jobs reserved, in | ||
| 75 | + /// bytes. The forge hands out only a job whose reservation fits. Absent from an older runner, | ||
| 76 | + /// which gets the first job in the queue as before. | ||
| 77 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 78 | + pub free_memory_bytes: Option<u64>, | ||
| 79 | + /// The runner's whole memory budget for jobs, in bytes. A job that reserves more than this | ||
| 80 | + /// still runs when the runner is idle. | ||
| 81 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 82 | + pub memory_budget_bytes: Option<u64>, | ||
| 83 | + /// What the runner reserves for a job that declares no `memory`, in bytes. | ||
| 84 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 85 | + pub reserve_memory_bytes: Option<u64>, | ||
| 74 | } | 86 | } |
| 75 | 87 | ||
| 76 | /// The capability of a runner that obeys [`RESTART_HEADER`]. | 88 | /// The capability of a runner that obeys [`RESTART_HEADER`]. |
| @@ -117,6 +129,14 @@ pub const BUILD_HEADER: &str = "Forge-Runner-Build"; | |||
| 117 | /// when there is no override, which means the runner uses the value from its own `runner.toml`. | 129 | /// when there is no override, which means the runner uses the value from its own `runner.toml`. |
| 118 | pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency"; | 130 | pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency"; |
| 119 | 131 | ||
| 132 | +/// Response header on a claim: the memory budget an admin set for this runner in the web UI | ||
| 133 | +/// (`6g`). Absent means no override. Live, like [`CONCURRENCY_HEADER`]. | ||
| 134 | +pub const MEMORY_BUDGET_HEADER: &str = "Forge-Runner-Memory-Budget"; | ||
| 135 | + | ||
| 136 | +/// Response header on a claim: the default memory reservation an admin set (`1g`). Absent means no | ||
| 137 | +/// override. | ||
| 138 | +pub const RESERVE_MEMORY_HEADER: &str = "Forge-Runner-Reserve-Memory"; | ||
| 139 | + | ||
| 120 | /// The smallest and largest job concurrency a runner accepts. | 140 | /// The smallest and largest job concurrency a runner accepts. |
| 121 | pub const MIN_CONCURRENCY: u32 = 1; | 141 | pub const MIN_CONCURRENCY: u32 = 1; |
| 122 | pub const MAX_CONCURRENCY: u32 = 64; | 142 | pub const MAX_CONCURRENCY: u32 = 64; |
| @@ -152,6 +172,10 @@ pub struct JobAssignment { | |||
| 152 | /// Read-only fallback scopes, tried in order when `cache_key` has no entry. Never written. | 172 | /// Read-only fallback scopes, tried in order when `cache_key` has no entry. Never written. |
| 153 | #[serde(default, skip_serializing_if = "Vec::is_empty")] | 173 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 154 | pub cache_restore_keys: Vec<String>, | 174 | pub cache_restore_keys: Vec<String>, |
| 175 | + /// The job's declared peak memory in bytes (`memory` in ci.toml). Absent when the job did not | ||
| 176 | + /// declare one, and from an older forge: the runner then reserves its default. | ||
| 177 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 178 | + pub memory_bytes: Option<u64>, | ||
| 155 | } | 179 | } |
| 156 | 180 | ||
| 157 | impl fmt::Debug for JobAssignment { | 181 | impl fmt::Debug for JobAssignment { |
| @@ -174,6 +198,7 @@ impl fmt::Debug for JobAssignment { | |||
| 174 | .field("cache", &self.cache) | 198 | .field("cache", &self.cache) |
| 175 | .field("cache_key", &self.cache_key) | 199 | .field("cache_key", &self.cache_key) |
| 176 | .field("cache_restore_keys", &self.cache_restore_keys) | 200 | .field("cache_restore_keys", &self.cache_restore_keys) |
| 201 | + .field("memory_bytes", &self.memory_bytes) | ||
| 177 | .finish() | 202 | .finish() |
| 178 | } | 203 | } |
| 179 | } | 204 | } |
| @@ -239,6 +264,11 @@ mod tests { | |||
| 239 | fn old_and_new_claim_and_heartbeat_bodies_parse() { | 264 | fn old_and_new_claim_and_heartbeat_bodies_parse() { |
| 240 | let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap(); | 265 | let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap(); |
| 241 | assert_eq!(old.concurrency, None); | 266 | assert_eq!(old.concurrency, None); |
| 267 | + // An old runner sends no memory fields, so the forge applies no memory filter. | ||
| 268 | + assert_eq!(old.free_memory_bytes, None); | ||
| 269 | + assert_eq!(old.reserve_memory_bytes, None); | ||
| 270 | + let json = serde_json::to_string(&old).unwrap(); | ||
| 271 | + assert!(!json.contains("memory"), "{json}"); | ||
| 242 | let new = ClaimRequest { | 272 | let new = ClaimRequest { |
| 243 | labels: vec![], | 273 | labels: vec![], |
| 244 | concurrency: Some(2), | 274 | concurrency: Some(2), |
| @@ -248,6 +278,9 @@ mod tests { | |||
| 248 | capabilities: vec![CAP_RESTART.into()], | 278 | capabilities: vec![CAP_RESTART.into()], |
| 249 | memory_bytes: Some(1 << 33), | 279 | memory_bytes: Some(1 << 33), |
| 250 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), | 280 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), |
| 281 | + free_memory_bytes: Some(6 << 30), | ||
| 282 | + memory_budget_bytes: Some(6 << 30), | ||
| 283 | + reserve_memory_bytes: Some(1 << 30), | ||
| 251 | }; | 284 | }; |
| 252 | let back: ClaimRequest = | 285 | let back: ClaimRequest = |
| 253 | serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap(); | 286 | serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap(); |
| @@ -298,6 +331,7 @@ mod tests { | |||
| 298 | cache: vec![], | 331 | cache: vec![], |
| 299 | cache_key: String::new(), | 332 | cache_key: String::new(), |
| 300 | cache_restore_keys: vec![], | 333 | cache_restore_keys: vec![], |
| 334 | + memory_bytes: None, | ||
| 301 | }; | 335 | }; |
| 302 | let json = serde_json::to_string(&job).unwrap(); | 336 | let json = serde_json::to_string(&job).unwrap(); |
| 303 | assert!(!json.contains("cache"), "{json}"); | 337 | assert!(!json.contains("cache"), "{json}"); |
| @@ -328,6 +362,7 @@ mod tests { | |||
| 328 | cache: vec![], | 362 | cache: vec![], |
| 329 | cache_key: String::new(), | 363 | cache_key: String::new(), |
| 330 | cache_restore_keys: vec![], | 364 | cache_restore_keys: vec![], |
| 365 | + memory_bytes: None, | ||
| 331 | }; | 366 | }; |
| 332 | let dbg = format!("{job:?}"); | 367 | let dbg = format!("{job:?}"); |
| 333 | assert!(!dbg.contains("hunter2-value")); | 368 | assert!(!dbg.contains("hunter2-value")); |
crates/forge-ci/src/size.rsadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +//! Byte sizes such as `4g` or `512m`, for `memory` in ci.toml and the runner's memory settings. | ||
| 2 | + | ||
| 3 | +/// Parses `4g`, `512m`, `1.5g`, `64k`, `4gb`, `4GiB`, `1t` or a plain byte count. Units are | ||
| 4 | +/// powers of 1024. `None` for anything else, for zero and for a size that overflows. | ||
| 5 | +pub fn parse_size(text: &str) -> Option<u64> { | ||
| 6 | + let lower = text.trim().to_ascii_lowercase(); | ||
| 7 | + let split = lower | ||
| 8 | + .find(|c: char| !(c.is_ascii_digit() || c == '.')) | ||
| 9 | + .unwrap_or(lower.len()); | ||
| 10 | + let (number, unit) = lower.split_at(split); | ||
| 11 | + let multiplier: u64 = match unit.trim() { | ||
| 12 | + "" | "b" => 1, | ||
| 13 | + "k" | "kb" | "kib" => 1 << 10, | ||
| 14 | + "m" | "mb" | "mib" => 1 << 20, | ||
| 15 | + "g" | "gb" | "gib" => 1 << 30, | ||
| 16 | + "t" | "tb" | "tib" => 1 << 40, | ||
| 17 | + _ => return None, | ||
| 18 | + }; | ||
| 19 | + if number.is_empty() || number.starts_with('.') || number.ends_with('.') { | ||
| 20 | + return None; | ||
| 21 | + } | ||
| 22 | + let bytes = match number.split_once('.') { | ||
| 23 | + None => number.parse::<u64>().ok()?.checked_mul(multiplier)?, | ||
| 24 | + Some((whole, frac)) => { | ||
| 25 | + if multiplier == 1 || frac.contains('.') || frac.len() > 6 { | ||
| 26 | + return None; | ||
| 27 | + } | ||
| 28 | + let whole = whole.parse::<u64>().ok()?.checked_mul(multiplier)?; | ||
| 29 | + let frac_value = frac.parse::<u64>().ok()?; | ||
| 30 | + let scale = 10_u64.pow(frac.len() as u32); | ||
| 31 | + whole.checked_add(frac_value.checked_mul(multiplier)? / scale)? | ||
| 32 | + } | ||
| 33 | + }; | ||
| 34 | + (bytes > 0).then_some(bytes) | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// Formats a byte count the way an admin would type it: `4g`, `512m`, or plain bytes when it is | ||
| 38 | +/// not a whole number of MiB. | ||
| 39 | +pub fn format_size(bytes: u64) -> String { | ||
| 40 | + const GIB: u64 = 1 << 30; | ||
| 41 | + const MIB: u64 = 1 << 20; | ||
| 42 | + if bytes >= GIB && bytes.is_multiple_of(GIB) { | ||
| 43 | + format!("{}g", bytes / GIB) | ||
| 44 | + } else if bytes >= MIB && bytes.is_multiple_of(MIB) { | ||
| 45 | + format!("{}m", bytes / MIB) | ||
| 46 | + } else { | ||
| 47 | + bytes.to_string() | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +#[cfg(test)] | ||
| 52 | +mod tests { | ||
| 53 | + use super::*; | ||
| 54 | + | ||
| 55 | + #[test] | ||
| 56 | + fn parses_units() { | ||
| 57 | + assert_eq!(parse_size("4g"), Some(4 << 30)); | ||
| 58 | + assert_eq!(parse_size(" 4G "), Some(4 << 30)); | ||
| 59 | + assert_eq!(parse_size("512m"), Some(512 << 20)); | ||
| 60 | + assert_eq!(parse_size("64k"), Some(64 << 10)); | ||
| 61 | + assert_eq!(parse_size("4GiB"), Some(4 << 30)); | ||
| 62 | + assert_eq!(parse_size("1t"), Some(1 << 40)); | ||
| 63 | + assert_eq!(parse_size("1024"), Some(1024)); | ||
| 64 | + assert_eq!(parse_size("1.5g"), Some(3 << 29)); | ||
| 65 | + assert_eq!(parse_size("0.5m"), Some(1 << 19)); | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + #[test] | ||
| 69 | + fn rejects_bad_sizes() { | ||
| 70 | + for bad in [ | ||
| 71 | + "", | ||
| 72 | + "g", | ||
| 73 | + "0", | ||
| 74 | + "0g", | ||
| 75 | + "-1g", | ||
| 76 | + "4x", | ||
| 77 | + "1.5", | ||
| 78 | + "1.5b", | ||
| 79 | + ".5g", | ||
| 80 | + "5.g", | ||
| 81 | + "1..5g", | ||
| 82 | + "4 g g", | ||
| 83 | + "99999999999999t", | ||
| 84 | + ] { | ||
| 85 | + assert_eq!(parse_size(bad), None, "{bad:?}"); | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + #[test] | ||
| 90 | + fn formats_round_trip() { | ||
| 91 | + assert_eq!(format_size(4 << 30), "4g"); | ||
| 92 | + assert_eq!(format_size(1536 << 20), "1536m"); | ||
| 93 | + assert_eq!(format_size(1000), "1000"); | ||
| 94 | + assert_eq!(parse_size(&format_size(3 << 29)), Some(3 << 29)); | ||
| 95 | + } | ||
| 96 | +} | ||
crates/forge-core/Cargo.tomlmodified+1 -0
| @@ -8,6 +8,7 @@ publish = false | |||
| 8 | 8 | ||
| 9 | [dependencies] | 9 | [dependencies] |
| 10 | thiserror.workspace = true | 10 | thiserror.workspace = true |
| 11 | +forge-ci.workspace = true | ||
| 11 | ipnet.workspace = true | 12 | ipnet.workspace = true |
| 12 | serde.workspace = true | 13 | serde.workspace = true |
| 13 | toml.workspace = true | 14 | toml.workspace = true |
crates/forge-core/migrations/0060_runner_memory.sqladded+7 -0
| @@ -0,0 +1,7 @@ | |||
| 1 | +-- Memory-aware admission. A runner reports its job memory budget, what is still free for | ||
| 2 | +-- admission, and its default reservation for a job that declares none, all in bytes. Applied by | ||
| 3 | +-- store/migrate.rs. | ||
| 4 | + | ||
| 5 | +ALTER TABLE ci_runners ADD COLUMN reported_memory_budget INTEGER NULL; | ||
| 6 | +ALTER TABLE ci_runners ADD COLUMN reported_memory_free INTEGER NULL; | ||
| 7 | +ALTER TABLE ci_runners ADD COLUMN reported_memory_reserve INTEGER NULL; | ||
crates/forge-core/src/ci.rsmodified+162 -0
| @@ -225,6 +225,14 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[ | |||
| 225 | key: "limits.memory", | 225 | key: "limits.memory", |
| 226 | kind: FieldKind::Restart, | 226 | kind: FieldKind::Restart, |
| 227 | }, | 227 | }, |
| 228 | + RunnerField { | ||
| 229 | + key: "limits.reserve_memory", | ||
| 230 | + kind: FieldKind::Live, | ||
| 231 | + }, | ||
| 232 | + RunnerField { | ||
| 233 | + key: "limits.memory_budget", | ||
| 234 | + kind: FieldKind::Live, | ||
| 235 | + }, | ||
| 228 | RunnerField { | 236 | RunnerField { |
| 229 | key: "limits.cpus", | 237 | key: "limits.cpus", |
| 230 | kind: FieldKind::Restart, | 238 | kind: FieldKind::Restart, |
| @@ -352,6 +360,20 @@ pub fn validate_runner_field( | |||
| 352 | Err("memory looks like 4g, 512m or a byte count".into()) | 360 | Err("memory looks like 4g, 512m or a byte count".into()) |
| 353 | } | 361 | } |
| 354 | } | 362 | } |
| 363 | + "limits.reserve_memory" => { | ||
| 364 | + if size_in_range(raw, 64 << 20, 1 << 40) { | ||
| 365 | + Ok(Value::from(raw)) | ||
| 366 | + } else { | ||
| 367 | + Err("reserve_memory looks like 1g or 512m, from 64m to 1024g".into()) | ||
| 368 | + } | ||
| 369 | + } | ||
| 370 | + "limits.memory_budget" => { | ||
| 371 | + if raw == "auto" || size_in_range(raw, 256 << 20, 1 << 50) { | ||
| 372 | + Ok(Value::from(raw)) | ||
| 373 | + } else { | ||
| 374 | + Err("memory_budget is auto, or looks like 6g or 6144m".into()) | ||
| 375 | + } | ||
| 376 | + } | ||
| 355 | "limits.cpus" => { | 377 | "limits.cpus" => { |
| 356 | let ok = raw.parse::<f64>().is_ok_and(|n| n > 0.0 && n <= 1024.0) | 378 | let ok = raw.parse::<f64>().is_ok_and(|n| n > 0.0 && n <= 1024.0) |
| 357 | && raw.chars().all(|c| c.is_ascii_digit() || c == '.'); | 379 | && raw.chars().all(|c| c.is_ascii_digit() || c == '.'); |
| @@ -385,6 +407,74 @@ pub struct RunnerReport { | |||
| 385 | /// Features the runner says it has. The crate version never changes between builds, so the | 407 | /// Features the runner says it has. The crate version never changes between builds, so the |
| 386 | /// forge gates features on these and not on the version. | 408 | /// forge gates features on these and not on the version. |
| 387 | pub capabilities: Vec<String>, | 409 | pub capabilities: Vec<String>, |
| 410 | + /// The runner's memory budget for jobs, in bytes. | ||
| 411 | + pub memory_budget: Option<u64>, | ||
| 412 | + /// Budget minus what running jobs reserved, as of the runner's last claim. | ||
| 413 | + pub memory_free: Option<u64>, | ||
| 414 | + /// What the runner reserves for a job that declares no `memory`. | ||
| 415 | + pub memory_reserve: Option<u64>, | ||
| 416 | +} | ||
| 417 | + | ||
| 418 | +impl RunnerReport { | ||
| 419 | + /// Memory the running jobs reserved, when the runner reports a budget. | ||
| 420 | + pub fn memory_reserved(&self) -> Option<u64> { | ||
| 421 | + Some(self.memory_budget?.saturating_sub(self.memory_free?)) | ||
| 422 | + } | ||
| 423 | +} | ||
| 424 | + | ||
| 425 | +/// How long a queued job that does not fit a runner may wait before smaller jobs stop passing it. | ||
| 426 | +/// See [`pick_by_memory`]. | ||
| 427 | +pub const STARVE_AFTER_SECS: u64 = 300; | ||
| 428 | + | ||
| 429 | +/// What a runner can admit right now, from its claim. | ||
| 430 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 431 | +pub struct MemoryOffer { | ||
| 432 | + /// Budget minus what running jobs reserved, in bytes. | ||
| 433 | + pub free: u64, | ||
| 434 | + /// The runner's whole budget. A job that reserves more than this is treated as reserving the | ||
| 435 | + /// whole budget, so it still runs when the runner is idle instead of waiting forever. | ||
| 436 | + pub budget: Option<u64>, | ||
| 437 | + /// The reservation of a job that declares no `memory`. | ||
| 438 | + pub default_reserve: u64, | ||
| 439 | +} | ||
| 440 | + | ||
| 441 | +impl MemoryOffer { | ||
| 442 | + /// What a job reserves on this runner: its declared memory or the default, capped at the | ||
| 443 | + /// budget. | ||
| 444 | + pub fn reservation(&self, declared: Option<u64>) -> u64 { | ||
| 445 | + let want = declared.unwrap_or(self.default_reserve); | ||
| 446 | + self.budget.map_or(want, |budget| want.min(budget)) | ||
| 447 | + } | ||
| 448 | + | ||
| 449 | + /// True when a job with this declared memory fits in the free memory. | ||
| 450 | + pub fn fits(&self, declared: Option<u64>) -> bool { | ||
| 451 | + self.reservation(declared) <= self.free | ||
| 452 | + } | ||
| 453 | +} | ||
| 454 | + | ||
| 455 | +/// Picks which of the label-compatible queued jobs, oldest first, a runner with `offer` takes. | ||
| 456 | +/// Each candidate is `(declared memory, seconds waited)`. Returns the index of the first job that | ||
| 457 | +/// fits. A job that does not fit is skipped so smaller jobs behind it can run, but only while it | ||
| 458 | +/// has waited less than `starve_after` seconds. Once an unfit job has waited that long, nothing | ||
| 459 | +/// behind it is handed out: the runner drains its running jobs until the old job fits. | ||
| 460 | +pub fn pick_by_memory( | ||
| 461 | + candidates: &[(Option<u64>, u64)], | ||
| 462 | + offer: &MemoryOffer, | ||
| 463 | + starve_after: u64, | ||
| 464 | +) -> Option<usize> { | ||
| 465 | + for (i, (declared, waited)) in candidates.iter().enumerate() { | ||
| 466 | + if offer.fits(*declared) { | ||
| 467 | + return Some(i); | ||
| 468 | + } | ||
| 469 | + if *waited >= starve_after { | ||
| 470 | + return None; | ||
| 471 | + } | ||
| 472 | + } | ||
| 473 | + None | ||
| 474 | +} | ||
| 475 | + | ||
| 476 | +fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool { | ||
| 477 | + forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n)) | ||
| 388 | } | 478 | } |
| 389 | 479 | ||
| 390 | /// The capability of a runner that restarts when the forge asks. | 480 | /// The capability of a runner that restarts when the forge asks. |
| @@ -456,3 +546,75 @@ pub struct NewJob<'a> { | |||
| 456 | pub spec_json: &'a str, | 546 | pub spec_json: &'a str, |
| 457 | pub needs: &'a [String], | 547 | pub needs: &'a [String], |
| 458 | } | 548 | } |
| 549 | + | ||
| 550 | +#[cfg(test)] | ||
| 551 | +mod memory_tests { | ||
| 552 | + use super::*; | ||
| 553 | + | ||
| 554 | + const GIB: u64 = 1 << 30; | ||
| 555 | + | ||
| 556 | + fn offer(free: u64) -> MemoryOffer { | ||
| 557 | + MemoryOffer { | ||
| 558 | + free: free * GIB, | ||
| 559 | + budget: Some(6 * GIB), | ||
| 560 | + default_reserve: GIB, | ||
| 561 | + } | ||
| 562 | + } | ||
| 563 | + | ||
| 564 | + #[test] | ||
| 565 | + fn the_first_job_that_fits_is_picked() { | ||
| 566 | + let queue = [(Some(4 * GIB), 10), (Some(GIB), 5), (None, 1)]; | ||
| 567 | + assert_eq!(pick_by_memory(&queue, &offer(6), 300), Some(0)); | ||
| 568 | + assert_eq!(pick_by_memory(&queue, &offer(2), 300), Some(1)); | ||
| 569 | + assert_eq!(pick_by_memory(&queue, &offer(1), 300), Some(1)); | ||
| 570 | + assert_eq!(pick_by_memory(&queue, &offer(0), 300), None); | ||
| 571 | + assert_eq!(pick_by_memory(&[], &offer(6), 300), None); | ||
| 572 | + } | ||
| 573 | + | ||
| 574 | + #[test] | ||
| 575 | + fn a_job_without_memory_reserves_the_runners_default() { | ||
| 576 | + let queue = [(None, 0)]; | ||
| 577 | + assert_eq!(pick_by_memory(&queue, &offer(1), 300), Some(0)); | ||
| 578 | + let big_default = MemoryOffer { | ||
| 579 | + default_reserve: 2 * GIB, | ||
| 580 | + ..offer(1) | ||
| 581 | + }; | ||
| 582 | + assert_eq!(pick_by_memory(&queue, &big_default, 300), None); | ||
| 583 | + } | ||
| 584 | + | ||
| 585 | + #[test] | ||
| 586 | + fn an_oversized_job_counts_as_the_whole_budget() { | ||
| 587 | + let queue = [(Some(64 * GIB), 0)]; | ||
| 588 | + assert_eq!(pick_by_memory(&queue, &offer(6), 300), Some(0)); | ||
| 589 | + assert_eq!(pick_by_memory(&queue, &offer(5), 300), None); | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + #[test] | ||
| 593 | + fn a_waiting_job_is_passed_only_until_the_threshold() { | ||
| 594 | + let young = [(Some(4 * GIB), 299), (Some(GIB), 0)]; | ||
| 595 | + assert_eq!(pick_by_memory(&young, &offer(2), 300), Some(1)); | ||
| 596 | + let old = [(Some(4 * GIB), 300), (Some(GIB), 0)]; | ||
| 597 | + assert_eq!(pick_by_memory(&old, &offer(2), 300), None); | ||
| 598 | + assert_eq!(pick_by_memory(&old, &offer(4), 300), Some(0)); | ||
| 599 | + } | ||
| 600 | + | ||
| 601 | + #[test] | ||
| 602 | + fn memory_fields_are_validated() { | ||
| 603 | + for ok in ["1g", "512m", "2G"] { | ||
| 604 | + assert!(validate_runner_field("limits.reserve_memory", ok).is_ok()); | ||
| 605 | + } | ||
| 606 | + for bad in ["", "0", "lots", "1k", "2t"] { | ||
| 607 | + assert!(validate_runner_field("limits.reserve_memory", bad).is_err()); | ||
| 608 | + } | ||
| 609 | + for ok in ["auto", "6g", "6144m"] { | ||
| 610 | + assert!(validate_runner_field("limits.memory_budget", ok).is_ok()); | ||
| 611 | + } | ||
| 612 | + for bad in ["", "0", "-1", "big"] { | ||
| 613 | + assert!(validate_runner_field("limits.memory_budget", bad).is_err()); | ||
| 614 | + } | ||
| 615 | + assert_eq!( | ||
| 616 | + runner_field("limits.memory_budget").map(|f| f.kind), | ||
| 617 | + Some(FieldKind::Live) | ||
| 618 | + ); | ||
| 619 | + } | ||
| 620 | +} | ||
crates/forge-core/src/store/ci.rsmodified+250 -12
| @@ -15,12 +15,12 @@ use super::{ | |||
| 15 | }; | 15 | }; |
| 16 | use crate::ci::{ | 16 | use crate::ci::{ |
| 17 | CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, | 17 | CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, |
| 18 | - MIN_RUNNER_CONCURRENCY, NewJob, RestartMode, RunState, RunnerReport, RunnerRestart, | 18 | + MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, RestartMode, RunState, RunnerReport, |
| 19 | - validate_runner_field, | 19 | + RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field, |
| 20 | }; | 20 | }; |
| 21 | use crate::error::{Error, Result}; | 21 | use crate::error::{Error, Result}; |
| 22 | use crate::secret; | 22 | use crate::secret; |
| 23 | -use crate::time::{now_stamp, stamp_after}; | 23 | +use crate::time::{now_stamp, stamp_after, stamp_to_unix}; |
| 24 | use crate::token::{generate_token, hash_token}; | 24 | use crate::token::{generate_token, hash_token}; |
| 25 | 25 | ||
| 26 | const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \ | 26 | const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \ |
| @@ -31,7 +31,8 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, | |||
| 31 | concurrency_override, reported_concurrency, reported_version, reported_cpus, \ | 31 | concurrency_override, reported_concurrency, reported_version, reported_cpus, \ |
| 32 | reported_memory_bytes, reported_config, config_overrides, \ | 32 | reported_memory_bytes, reported_config, config_overrides, \ |
| 33 | (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ | 33 | (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ |
| 34 | - reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities"; | 34 | + reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \ |
| 35 | + reported_memory_budget, reported_memory_free, reported_memory_reserve"; | ||
| 35 | const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at"; | 36 | const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at"; |
| 36 | 37 | ||
| 37 | /// Longest runner name, in bytes. | 38 | /// Longest runner name, in bytes. |
| @@ -88,6 +89,9 @@ fn map_runner(row: &Row) -> Result<CiRunner> { | |||
| 88 | .collect() | 89 | .collect() |
| 89 | }) | 90 | }) |
| 90 | .unwrap_or_default(), | 91 | .unwrap_or_default(), |
| 92 | + memory_budget: opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()), | ||
| 93 | + memory_free: opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()), | ||
| 94 | + memory_reserve: opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()), | ||
| 91 | }, | 95 | }, |
| 92 | restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) { | 96 | restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) { |
| 93 | (Some(mode), Some(requested_at)) => mode | 97 | (Some(mode), Some(requested_at)) => mode |
| @@ -191,6 +195,14 @@ fn spec_needs(spec: &str) -> Vec<String> { | |||
| 191 | 195 | ||
| 192 | /// True when every label in the spec's `runs_on` is one of the runner's labels. A missing | 196 | /// True when every label in the spec's `runs_on` is one of the runner's labels. A missing |
| 193 | /// `runs_on` means no requirement. A malformed spec is never claimable. | 197 | /// `runs_on` means no requirement. A malformed spec is never claimable. |
| 198 | +/// The `memory` a job's stored spec declares, in bytes. | ||
| 199 | +fn declared_memory(spec: &str) -> Option<u64> { | ||
| 200 | + serde_json::from_str::<serde_json::Value>(spec) | ||
| 201 | + .ok()? | ||
| 202 | + .get("memory")? | ||
| 203 | + .as_u64() | ||
| 204 | +} | ||
| 205 | + | ||
| 194 | fn runs_on_covered(spec: &str, labels: &[String]) -> bool { | 206 | fn runs_on_covered(spec: &str, labels: &[String]) -> bool { |
| 195 | let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else { | 207 | let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else { |
| 196 | return false; | 208 | return false; |
| @@ -725,6 +737,20 @@ impl Store { | |||
| 725 | Ok(found.flatten()) | 737 | Ok(found.flatten()) |
| 726 | } | 738 | } |
| 727 | 739 | ||
| 740 | + /// The text an admin set for a runner field, read fresh. `None` when unset or the runner is | ||
| 741 | + /// gone. | ||
| 742 | + pub async fn runner_field_override(&self, id: &str, key: &str) -> Result<Option<String>> { | ||
| 743 | + let conn = self.read_conn().await; | ||
| 744 | + let found = fetch_opt( | ||
| 745 | + &conn, | ||
| 746 | + "SELECT config_overrides FROM ci_runners WHERE id = ?1", | ||
| 747 | + (id.to_string(),), | ||
| 748 | + |row| json_map(row, 0), | ||
| 749 | + ) | ||
| 750 | + .await?; | ||
| 751 | + Ok(found.and_then(|map| map.get(key).and_then(|v| v.as_str().map(str::to_owned)))) | ||
| 752 | + } | ||
| 753 | + | ||
| 728 | /// Stores what a runner reported about itself. Fields that are `None` keep their stored | 754 | /// Stores what a runner reported about itself. Fields that are `None` keep their stored |
| 729 | /// value. Returns true when a stored value changed, so the caller can tell live pages. | 755 | /// value. Returns true when a stored value changed, so the caller can tell live pages. |
| 730 | pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> { | 756 | pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> { |
| @@ -751,6 +777,9 @@ impl Store { | |||
| 751 | } else { | 777 | } else { |
| 752 | report.capabilities.clone() | 778 | report.capabilities.clone() |
| 753 | }, | 779 | }, |
| 780 | + memory_budget: report.memory_budget.or(current.reported.memory_budget), | ||
| 781 | + memory_free: report.memory_free.or(current.reported.memory_free), | ||
| 782 | + memory_reserve: report.memory_reserve.or(current.reported.memory_reserve), | ||
| 754 | }; | 783 | }; |
| 755 | if merged == current.reported { | 784 | if merged == current.reported { |
| 756 | return Ok(false); | 785 | return Ok(false); |
| @@ -768,7 +797,8 @@ impl Store { | |||
| 768 | conn.execute( | 797 | conn.execute( |
| 769 | "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \ | 798 | "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \ |
| 770 | reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6, \ | 799 | reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6, \ |
| 771 | - reported_boot_id = ?7, reported_capabilities = ?8 WHERE id = ?1", | 800 | + reported_boot_id = ?7, reported_capabilities = ?8, reported_memory_budget = ?9, \ |
| 801 | + reported_memory_free = ?10, reported_memory_reserve = ?11 WHERE id = ?1", | ||
| 772 | ( | 802 | ( |
| 773 | id.to_string(), | 803 | id.to_string(), |
| 774 | opt_int_value(merged.concurrency.map(i64::from)), | 804 | opt_int_value(merged.concurrency.map(i64::from)), |
| @@ -778,6 +808,9 @@ impl Store { | |||
| 778 | opt_text(merged.build.as_deref()), | 808 | opt_text(merged.build.as_deref()), |
| 779 | opt_text(merged.boot_id.as_deref()), | 809 | opt_text(merged.boot_id.as_deref()), |
| 780 | merged.capabilities.join(","), | 810 | merged.capabilities.join(","), |
| 811 | + opt_int_value(merged.memory_budget.and_then(|n| i64::try_from(n).ok())), | ||
| 812 | + opt_int_value(merged.memory_free.and_then(|n| i64::try_from(n).ok())), | ||
| 813 | + opt_int_value(merged.memory_reserve.and_then(|n| i64::try_from(n).ok())), | ||
| 781 | ), | 814 | ), |
| 782 | ) | 815 | ) |
| 783 | .await | 816 | .await |
| @@ -953,6 +986,17 @@ impl Store { | |||
| 953 | /// UPDATE guarded by `state = 'queued'`, so only one claimer can win a job. Returns the job, | 986 | /// UPDATE guarded by `state = 'queued'`, so only one claimer can win a job. Returns the job, |
| 954 | /// its run and the plaintext job token, which is shown once. A disabled runner gets nothing. | 987 | /// its run and the plaintext job token, which is shown once. A disabled runner gets nothing. |
| 955 | pub async fn claim_job(&self, runner: &CiRunner) -> Result<Option<(CiJob, CiRun, String)>> { | 988 | pub async fn claim_job(&self, runner: &CiRunner) -> Result<Option<(CiJob, CiRun, String)>> { |
| 989 | + self.claim_job_fitting(runner, None).await | ||
| 990 | + } | ||
| 991 | + | ||
| 992 | + /// Like [`Store::claim_job`], and when `offer` is set only claims a job whose memory | ||
| 993 | + /// reservation fits the runner's free memory, see [`pick_by_memory`]. Without an offer, which | ||
| 994 | + /// is an older runner, the oldest compatible job is taken. | ||
| 995 | + pub async fn claim_job_fitting( | ||
| 996 | + &self, | ||
| 997 | + runner: &CiRunner, | ||
| 998 | + offer: Option<MemoryOffer>, | ||
| 999 | + ) -> Result<Option<(CiJob, CiRun, String)>> { | ||
| 956 | if runner.disabled { | 1000 | if runner.disabled { |
| 957 | return Ok(None); | 1001 | return Ok(None); |
| 958 | } | 1002 | } |
| @@ -962,17 +1006,36 @@ impl Store { | |||
| 962 | let conn = self.inner.conn.lock().await; | 1006 | let conn = self.inner.conn.lock().await; |
| 963 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 1007 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 964 | let outcome: Result<Option<(CiJob, CiRun)>> = async { | 1008 | let outcome: Result<Option<(CiJob, CiRun)>> = async { |
| 965 | - let queued: Vec<(String, String)> = fetch_all( | 1009 | + let queued: Vec<(String, String, Option<String>)> = fetch_all( |
| 966 | &tx, | 1010 | &tx, |
| 967 | - "SELECT id, spec FROM ci_jobs WHERE state = 'queued' ORDER BY queued_at, id", | 1011 | + "SELECT id, spec, queued_at FROM ci_jobs WHERE state = 'queued' \ |
| 1012 | + ORDER BY queued_at, id", | ||
| 968 | (), | 1013 | (), |
| 969 | - |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | 1014 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_opt_text(row, 2)?)), |
| 970 | ) | 1015 | ) |
| 971 | .await?; | 1016 | .await?; |
| 972 | - for (job_id, spec) in queued { | 1017 | + let mut compatible: Vec<(String, String, Option<String>)> = queued |
| 973 | - if !runs_on_covered(&spec, &runner.labels) { | 1018 | + .into_iter() |
| 974 | - continue; | 1019 | + .filter(|(_, spec, _)| runs_on_covered(spec, &runner.labels)) |
| 975 | - } | 1020 | + .collect(); |
| 1021 | + if let Some(offer) = offer { | ||
| 1022 | + let now = stamp_to_unix(&now).unwrap_or(0); | ||
| 1023 | + let candidates: Vec<(Option<u64>, u64)> = compatible | ||
| 1024 | + .iter() | ||
| 1025 | + .map(|(_, spec, queued_at)| { | ||
| 1026 | + let waited = queued_at | ||
| 1027 | + .as_deref() | ||
| 1028 | + .and_then(stamp_to_unix) | ||
| 1029 | + .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)); | ||
| 1030 | + (declared_memory(spec), waited) | ||
| 1031 | + }) | ||
| 1032 | + .collect(); | ||
| 1033 | + compatible = pick_by_memory(&candidates, &offer, STARVE_AFTER_SECS) | ||
| 1034 | + .map(|i| compatible.swap_remove(i)) | ||
| 1035 | + .into_iter() | ||
| 1036 | + .collect(); | ||
| 1037 | + } | ||
| 1038 | + for (job_id, _spec, _) in compatible { | ||
| 976 | let won = tx | 1039 | let won = tx |
| 977 | .execute( | 1040 | .execute( |
| 978 | "UPDATE ci_jobs SET state = 'running', runner_id = ?2, job_token_hash = ?3, \ | 1041 | "UPDATE ci_jobs SET state = 'running', runner_id = ?2, job_token_hash = ?3, \ |
| @@ -2079,7 +2142,11 @@ mod tests { | |||
| 2079 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), | 2142 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), |
| 2080 | boot_id: Some("boot-1".into()), | 2143 | boot_id: Some("boot-1".into()), |
| 2081 | capabilities: vec!["restart".into()], | 2144 | capabilities: vec!["restart".into()], |
| 2145 | + memory_budget: Some(6 << 30), | ||
| 2146 | + memory_free: Some(2 << 30), | ||
| 2147 | + memory_reserve: Some(1 << 30), | ||
| 2082 | }; | 2148 | }; |
| 2149 | + assert_eq!(full.memory_reserved(), Some(4 << 30)); | ||
| 2083 | assert!( | 2150 | assert!( |
| 2084 | fx.store | 2151 | fx.store |
| 2085 | .record_runner_report(&runner.id, &full) | 2152 | .record_runner_report(&runner.id, &full) |
| @@ -2328,6 +2395,177 @@ mod tests { | |||
| 2328 | )); | 2395 | )); |
| 2329 | } | 2396 | } |
| 2330 | 2397 | ||
| 2398 | + fn mem_job(name: &str, memory: Option<u64>) -> Job { | ||
| 2399 | + let mut spec = serde_json::json!({ | ||
| 2400 | + "image": "alpine", "run": "true", "needs": [], "runs_on": [], | ||
| 2401 | + }); | ||
| 2402 | + if let Some(bytes) = memory { | ||
| 2403 | + spec["memory"] = bytes.into(); | ||
| 2404 | + } | ||
| 2405 | + Job { | ||
| 2406 | + name: name.to_string(), | ||
| 2407 | + spec: spec.to_string(), | ||
| 2408 | + needs: Vec::new(), | ||
| 2409 | + } | ||
| 2410 | + } | ||
| 2411 | + | ||
| 2412 | + fn offer(free_gib: u64) -> Option<MemoryOffer> { | ||
| 2413 | + Some(MemoryOffer { | ||
| 2414 | + free: free_gib << 30, | ||
| 2415 | + budget: Some(6 << 30), | ||
| 2416 | + default_reserve: 1 << 30, | ||
| 2417 | + }) | ||
| 2418 | + } | ||
| 2419 | + | ||
| 2420 | + #[tokio::test] | ||
| 2421 | + async fn claim_picks_the_first_job_that_fits_the_free_memory() { | ||
| 2422 | + let fx = fixture().await; | ||
| 2423 | + create( | ||
| 2424 | + &fx.store, | ||
| 2425 | + &fx.repo.id, | ||
| 2426 | + &fx.tahinli.id, | ||
| 2427 | + &[ | ||
| 2428 | + mem_job("big", Some(4 << 30)), | ||
| 2429 | + mem_job("small", Some(1 << 30)), | ||
| 2430 | + mem_job("plain", None), | ||
| 2431 | + ], | ||
| 2432 | + false, | ||
| 2433 | + ) | ||
| 2434 | + .await; | ||
| 2435 | + let runner = bare_runner(&["linux"]); | ||
| 2436 | + // 2 GiB free: the 4 GiB job is skipped (it is young), the 1 GiB one runs. | ||
| 2437 | + let first = fx | ||
| 2438 | + .store | ||
| 2439 | + .claim_job_fitting(&runner, offer(2)) | ||
| 2440 | + .await | ||
| 2441 | + .unwrap() | ||
| 2442 | + .unwrap(); | ||
| 2443 | + assert_eq!(first.0.name, "small"); | ||
| 2444 | + // 1 GiB left: a job with no memory reserves the default 1 GiB and fits. | ||
| 2445 | + let second = fx | ||
| 2446 | + .store | ||
| 2447 | + .claim_job_fitting(&runner, offer(1)) | ||
| 2448 | + .await | ||
| 2449 | + .unwrap() | ||
| 2450 | + .unwrap(); | ||
| 2451 | + assert_eq!(second.0.name, "plain"); | ||
| 2452 | + // Nothing fits in 0 GiB, and the big job is still queued. | ||
| 2453 | + assert!( | ||
| 2454 | + fx.store | ||
| 2455 | + .claim_job_fitting(&runner, offer(0)) | ||
| 2456 | + .await | ||
| 2457 | + .unwrap() | ||
| 2458 | + .is_none() | ||
| 2459 | + ); | ||
| 2460 | + // An idle runner takes it. | ||
| 2461 | + let big = fx | ||
| 2462 | + .store | ||
| 2463 | + .claim_job_fitting(&runner, offer(6)) | ||
| 2464 | + .await | ||
| 2465 | + .unwrap() | ||
| 2466 | + .unwrap(); | ||
| 2467 | + assert_eq!(big.0.name, "big"); | ||
| 2468 | + } | ||
| 2469 | + | ||
| 2470 | + #[tokio::test] | ||
| 2471 | + async fn a_runner_without_an_offer_gets_the_oldest_job_as_before() { | ||
| 2472 | + let fx = fixture().await; | ||
| 2473 | + create( | ||
| 2474 | + &fx.store, | ||
| 2475 | + &fx.repo.id, | ||
| 2476 | + &fx.tahinli.id, | ||
| 2477 | + &[mem_job("big", Some(64 << 30)), mem_job("small", None)], | ||
| 2478 | + false, | ||
| 2479 | + ) | ||
| 2480 | + .await; | ||
| 2481 | + let claimed = fx | ||
| 2482 | + .store | ||
| 2483 | + .claim_job(&bare_runner(&["linux"])) | ||
| 2484 | + .await | ||
| 2485 | + .unwrap() | ||
| 2486 | + .unwrap(); | ||
| 2487 | + assert_eq!(claimed.0.name, "big"); | ||
| 2488 | + } | ||
| 2489 | + | ||
| 2490 | + #[tokio::test] | ||
| 2491 | + async fn a_job_bigger_than_the_budget_runs_when_the_runner_is_idle() { | ||
| 2492 | + let fx = fixture().await; | ||
| 2493 | + create( | ||
| 2494 | + &fx.store, | ||
| 2495 | + &fx.repo.id, | ||
| 2496 | + &fx.tahinli.id, | ||
| 2497 | + &[mem_job("huge", Some(64 << 30))], | ||
| 2498 | + false, | ||
| 2499 | + ) | ||
| 2500 | + .await; | ||
| 2501 | + let runner = bare_runner(&["linux"]); | ||
| 2502 | + assert!( | ||
| 2503 | + fx.store | ||
| 2504 | + .claim_job_fitting(&runner, offer(3)) | ||
| 2505 | + .await | ||
| 2506 | + .unwrap() | ||
| 2507 | + .is_none(), | ||
| 2508 | + "not while something else holds memory" | ||
| 2509 | + ); | ||
| 2510 | + let claimed = fx | ||
| 2511 | + .store | ||
| 2512 | + .claim_job_fitting(&runner, offer(6)) | ||
| 2513 | + .await | ||
| 2514 | + .unwrap() | ||
| 2515 | + .unwrap(); | ||
| 2516 | + assert_eq!(claimed.0.name, "huge"); | ||
| 2517 | + } | ||
| 2518 | + | ||
| 2519 | + #[tokio::test] | ||
| 2520 | + async fn a_job_that_waited_too_long_stops_smaller_jobs_passing_it() { | ||
| 2521 | + let fx = fixture().await; | ||
| 2522 | + create( | ||
| 2523 | + &fx.store, | ||
| 2524 | + &fx.repo.id, | ||
| 2525 | + &fx.tahinli.id, | ||
| 2526 | + &[ | ||
| 2527 | + mem_job("big", Some(4 << 30)), | ||
| 2528 | + mem_job("small", Some(1 << 30)), | ||
| 2529 | + ], | ||
| 2530 | + false, | ||
| 2531 | + ) | ||
| 2532 | + .await; | ||
| 2533 | + let old = crate::time::stamp_before(Duration::from_secs(STARVE_AFTER_SECS + 60)); | ||
| 2534 | + { | ||
| 2535 | + let conn = fx.store.inner.conn.lock().await; | ||
| 2536 | + conn.execute( | ||
| 2537 | + "UPDATE ci_jobs SET queued_at = ?1 WHERE name = 'big'", | ||
| 2538 | + (old,), | ||
| 2539 | + ) | ||
| 2540 | + .await | ||
| 2541 | + .unwrap(); | ||
| 2542 | + } | ||
| 2543 | + let runner = bare_runner(&["linux"]); | ||
| 2544 | + assert!( | ||
| 2545 | + fx.store | ||
| 2546 | + .claim_job_fitting(&runner, offer(2)) | ||
| 2547 | + .await | ||
| 2548 | + .unwrap() | ||
| 2549 | + .is_none(), | ||
| 2550 | + "the old big job holds the line" | ||
| 2551 | + ); | ||
| 2552 | + // Once enough memory is free the big job goes first. | ||
| 2553 | + let claimed = fx | ||
| 2554 | + .store | ||
| 2555 | + .claim_job_fitting(&runner, offer(5)) | ||
| 2556 | + .await | ||
| 2557 | + .unwrap() | ||
| 2558 | + .unwrap(); | ||
| 2559 | + assert_eq!(claimed.0.name, "big"); | ||
| 2560 | + let next = fx | ||
| 2561 | + .store | ||
| 2562 | + .claim_job_fitting(&runner, offer(2)) | ||
| 2563 | + .await | ||
| 2564 | + .unwrap() | ||
| 2565 | + .unwrap(); | ||
| 2566 | + assert_eq!(next.0.name, "small"); | ||
| 2567 | + } | ||
| 2568 | + | ||
| 2331 | #[tokio::test] | 2569 | #[tokio::test] |
| 2332 | async fn claim_matches_labels_and_skips_disabled() { | 2570 | async fn claim_matches_labels_and_skips_disabled() { |
| 2333 | let fx = fixture().await; | 2571 | let fx = fixture().await; |
crates/forge-core/src/store/migrate.rsmodified+1 -0
| @@ -99,6 +99,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 99 | (57, include_str!("../../migrations/0057_runner_restart.sql")), | 99 | (57, include_str!("../../migrations/0057_runner_restart.sql")), |
| 100 | (58, include_str!("../../migrations/0058_passkeys.sql")), | 100 | (58, include_str!("../../migrations/0058_passkeys.sql")), |
| 101 | (59, include_str!("../../migrations/0059_admin_alerts.sql")), | 101 | (59, include_str!("../../migrations/0059_admin_alerts.sql")), |
| 102 | + (60, include_str!("../../migrations/0060_runner_memory.sql")), | ||
| 102 | ]; | 103 | ]; |
| 103 | 104 | ||
| 104 | /// The highest migration version this binary knows about. | 105 | /// The highest migration version this binary knows about. |
crates/forge-runner/src/cache.rsmodified+1 -0
| @@ -767,6 +767,7 @@ mod tests { | |||
| 767 | cache: cache.iter().map(|s| (*s).to_owned()).collect(), | 767 | cache: cache.iter().map(|s| (*s).to_owned()).collect(), |
| 768 | cache_key: key.to_owned(), | 768 | cache_key: key.to_owned(), |
| 769 | cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(), | 769 | cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(), |
| 770 | + memory_bytes: None, | ||
| 770 | } | 771 | } |
| 771 | } | 772 | } |
| 772 | 773 | ||
crates/forge-runner/src/client.rsmodified+35 -3
| @@ -8,8 +8,8 @@ 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_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, |
| 11 | - JobAssignment, RESTART_HEADER, RegisterRequest, RegisterResponse, RestartMode, | 11 | + JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest, |
| 12 | - RunnerConfigOverrides, RunnerConfigReport, | 12 | + RegisterResponse, RestartMode, RunnerConfigOverrides, RunnerConfigReport, |
| 13 | }; | 13 | }; |
| 14 | use reqwest::StatusCode; | 14 | use reqwest::StatusCode; |
| 15 | use reqwest::header::{CONTENT_LENGTH, HeaderMap}; | 15 | use reqwest::header::{CONTENT_LENGTH, HeaderMap}; |
| @@ -66,6 +66,20 @@ pub struct ClaimReply { | |||
| 66 | pub concurrency: Option<u32>, | 66 | pub concurrency: Option<u32>, |
| 67 | /// A restart an admin asked for, from the `Forge-Runner-Restart` header. | 67 | /// A restart an admin asked for, from the `Forge-Runner-Restart` header. |
| 68 | pub restart: Option<RestartMode>, | 68 | pub restart: Option<RestartMode>, |
| 69 | + /// The memory budget an admin set (`6g`). `None` means no override. | ||
| 70 | + pub memory_budget: Option<String>, | ||
| 71 | + /// The default reservation an admin set (`1g`). `None` means no override. | ||
| 72 | + pub reserve_memory: Option<String>, | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// What a claim tells the forge about the runner's memory. | ||
| 76 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 77 | +pub struct MemoryClaim { | ||
| 78 | + /// Budget minus running reservations: the forge hands out only a job that fits. | ||
| 79 | + pub free: u64, | ||
| 80 | + pub budget: u64, | ||
| 81 | + /// What a job without `memory` reserves. | ||
| 82 | + pub reserve: u64, | ||
| 69 | } | 83 | } |
| 70 | 84 | ||
| 71 | /// A client for one forge base URL. | 85 | /// A client for one forge base URL. |
| @@ -110,7 +124,7 @@ impl ForgeClient { | |||
| 110 | runner_secret: &str, | 124 | runner_secret: &str, |
| 111 | labels: &[String], | 125 | labels: &[String], |
| 112 | ) -> Result<ClaimReply, ClientError> { | 126 | ) -> Result<ClaimReply, ClientError> { |
| 113 | - self.claim_with(runner_secret, labels, None).await | 127 | + self.claim_with(runner_secret, labels, None, None).await |
| 114 | } | 128 | } |
| 115 | 129 | ||
| 116 | /// Like [`ForgeClient::claim`], and also reports the runner's live `concurrency` and its host | 130 | /// Like [`ForgeClient::claim`], and also reports the runner's live `concurrency` and its host |
| @@ -120,6 +134,7 @@ impl ForgeClient { | |||
| 120 | runner_secret: &str, | 134 | runner_secret: &str, |
| 121 | labels: &[String], | 135 | labels: &[String], |
| 122 | concurrency: Option<usize>, | 136 | concurrency: Option<usize>, |
| 137 | + memory: Option<MemoryClaim>, | ||
| 123 | ) -> Result<ClaimReply, ClientError> { | 138 | ) -> Result<ClaimReply, ClientError> { |
| 124 | let host = host_facts(); | 139 | let host = host_facts(); |
| 125 | let req = ClaimRequest { | 140 | let req = ClaimRequest { |
| @@ -131,6 +146,9 @@ impl ForgeClient { | |||
| 131 | build: Some(forge_ci::build::display()), | 146 | build: Some(forge_ci::build::display()), |
| 132 | boot_id: Some(crate::restart::boot_id().to_owned()), | 147 | boot_id: Some(crate::restart::boot_id().to_owned()), |
| 133 | capabilities: vec![CAP_RESTART.to_owned()], | 148 | capabilities: vec![CAP_RESTART.to_owned()], |
| 149 | + free_memory_bytes: memory.map(|m| m.free), | ||
| 150 | + memory_budget_bytes: memory.map(|m| m.budget), | ||
| 151 | + reserve_memory_bytes: memory.map(|m| m.reserve), | ||
| 134 | }; | 152 | }; |
| 135 | let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); | 153 | let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); |
| 136 | let resp = self | 154 | let resp = self |
| @@ -145,18 +163,24 @@ impl ForgeClient { | |||
| 145 | let binary_sha256 = advertised_sha256(resp.headers()); | 163 | let binary_sha256 = advertised_sha256(resp.headers()); |
| 146 | let concurrency = advertised_concurrency(resp.headers()); | 164 | let concurrency = advertised_concurrency(resp.headers()); |
| 147 | let restart = advertised_restart(resp.headers()); | 165 | let restart = advertised_restart(resp.headers()); |
| 166 | + let memory_budget = header_text(resp.headers(), MEMORY_BUDGET_HEADER); | ||
| 167 | + let reserve_memory = header_text(resp.headers(), RESERVE_MEMORY_HEADER); | ||
| 148 | match resp.status() { | 168 | match resp.status() { |
| 149 | StatusCode::NO_CONTENT => Ok(ClaimReply { | 169 | StatusCode::NO_CONTENT => Ok(ClaimReply { |
| 150 | job: None, | 170 | job: None, |
| 151 | binary_sha256, | 171 | binary_sha256, |
| 152 | concurrency, | 172 | concurrency, |
| 153 | restart, | 173 | restart, |
| 174 | + memory_budget, | ||
| 175 | + reserve_memory, | ||
| 154 | }), | 176 | }), |
| 155 | status if status.is_success() => Ok(ClaimReply { | 177 | status if status.is_success() => Ok(ClaimReply { |
| 156 | job: Some(resp.json().await?), | 178 | job: Some(resp.json().await?), |
| 157 | binary_sha256, | 179 | binary_sha256, |
| 158 | concurrency, | 180 | concurrency, |
| 159 | restart, | 181 | restart, |
| 182 | + memory_budget, | ||
| 183 | + reserve_memory, | ||
| 160 | }), | 184 | }), |
| 161 | _ => Err(status_error(resp).await), | 185 | _ => Err(status_error(resp).await), |
| 162 | } | 186 | } |
| @@ -367,6 +391,14 @@ struct HostFacts { | |||
| 367 | memory_bytes: Option<u64>, | 391 | memory_bytes: Option<u64>, |
| 368 | } | 392 | } |
| 369 | 393 | ||
| 394 | +fn header_text(headers: &HeaderMap, name: &str) -> Option<String> { | ||
| 395 | + headers | ||
| 396 | + .get(name) | ||
| 397 | + .and_then(|v| v.to_str().ok()) | ||
| 398 | + .map(|v| v.trim().to_owned()) | ||
| 399 | + .filter(|v| !v.is_empty() && v.len() <= 32) | ||
| 400 | +} | ||
| 401 | + | ||
| 370 | fn host_facts() -> HostFacts { | 402 | fn host_facts() -> HostFacts { |
| 371 | let cpus = std::thread::available_parallelism() | 403 | let cpus = std::thread::available_parallelism() |
| 372 | .ok() | 404 | .ok() |
crates/forge-runner/src/config.rsmodified+150 -0
| @@ -40,6 +40,29 @@ pub struct Limits { | |||
| 40 | /// The cap on the unpacked size of one image, in GB. Used by the builtin executor. | 40 | /// The cap on the unpacked size of one image, in GB. Used by the builtin executor. |
| 41 | #[serde(default = "default_image_max_gb")] | 41 | #[serde(default = "default_image_max_gb")] |
| 42 | pub image_max_gb: u64, | 42 | pub image_max_gb: u64, |
| 43 | + /// What a job that declares no `memory` reserves when it is admitted, and the floor for its | ||
| 44 | + /// cgroup limit. Live: an admin can change it from the forge without a restart. | ||
| 45 | + #[serde(default = "default_reserve_memory")] | ||
| 46 | + pub reserve_memory: String, | ||
| 47 | + /// The memory all running jobs may reserve together, like `6g`. Absent or `auto` means the | ||
| 48 | + /// host's MemTotal minus the headroom. Live, like `reserve_memory`. | ||
| 49 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 50 | + pub memory_budget: Option<String>, | ||
| 51 | + /// Memory kept for the host in `auto` mode, as a size. The larger of this and 10% of MemTotal | ||
| 52 | + /// is kept free. | ||
| 53 | + #[serde(default = "default_memory_headroom")] | ||
| 54 | + pub memory_headroom: String, | ||
| 55 | + /// Percent of the host's swap that counts toward the `auto` budget. 0 means swap is ignored. | ||
| 56 | + #[serde(default)] | ||
| 57 | + pub budget_swap_percent: u32, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +fn default_reserve_memory() -> String { | ||
| 61 | + "1g".to_owned() | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +fn default_memory_headroom() -> String { | ||
| 65 | + "1g".to_owned() | ||
| 43 | } | 66 | } |
| 44 | 67 | ||
| 45 | impl Default for Limits { | 68 | impl Default for Limits { |
| @@ -49,10 +72,49 @@ impl Default for Limits { | |||
| 49 | cpus: "2".to_owned(), | 72 | cpus: "2".to_owned(), |
| 50 | pids: 4096, | 73 | pids: 4096, |
| 51 | image_max_gb: default_image_max_gb(), | 74 | image_max_gb: default_image_max_gb(), |
| 75 | + reserve_memory: default_reserve_memory(), | ||
| 76 | + memory_budget: None, | ||
| 77 | + memory_headroom: default_memory_headroom(), | ||
| 78 | + budget_swap_percent: 0, | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +impl Limits { | ||
| 84 | + /// The limits for one job: `memory` becomes the cgroup limit of that job, in bytes. A job | ||
| 85 | + /// that declared `memory` gets it plus a little slack, so the job is OOM-killed in its own | ||
| 86 | + /// cgroup and not by the host. A job that did not gets the larger of `limits.memory` and the | ||
| 87 | + /// default reservation, so it never runs under what the runner reserved for it. | ||
| 88 | + pub fn for_job(&self, declared: Option<u64>) -> Limits { | ||
| 89 | + let mut limits = self.clone(); | ||
| 90 | + let configured = forge_ci::size::parse_size(&self.memory); | ||
| 91 | + match self.job_memory_limit(declared) { | ||
| 92 | + // The configured text stays as it is when it already is the limit. | ||
| 93 | + Some(bytes) if declared.is_some() || Some(bytes) != configured => { | ||
| 94 | + limits.memory = bytes.to_string(); | ||
| 95 | + } | ||
| 96 | + _ => {} | ||
| 97 | + } | ||
| 98 | + limits | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + /// The cgroup `memory.max` of a job in bytes, see [`Limits::for_job`]. `None` when | ||
| 102 | + /// `limits.memory` does not parse, which the sandbox reports itself. | ||
| 103 | + pub fn job_memory_limit(&self, declared: Option<u64>) -> Option<u64> { | ||
| 104 | + if let Some(declared) = declared { | ||
| 105 | + return Some(declared.saturating_add(memory_slack(declared))); | ||
| 52 | } | 106 | } |
| 107 | + let memory = forge_ci::size::parse_size(&self.memory)?; | ||
| 108 | + let reserve = forge_ci::size::parse_size(&self.reserve_memory).unwrap_or(0); | ||
| 109 | + Some(memory.max(reserve)) | ||
| 53 | } | 110 | } |
| 54 | } | 111 | } |
| 55 | 112 | ||
| 113 | +/// Room above a declared `memory` before the job's cgroup kills it: 1/16, at least 256 MiB. | ||
| 114 | +pub fn memory_slack(declared: u64) -> u64 { | ||
| 115 | + (declared / 16).max(256 << 20) | ||
| 116 | +} | ||
| 117 | + | ||
| 56 | /// Which executor runs jobs. `builtin` needs no external tool. `podman` runs them with rootless | 118 | /// Which executor runs jobs. `builtin` needs no external tool. `podman` runs them with rootless |
| 57 | /// podman. | 119 | /// podman. |
| 58 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] | 120 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| @@ -239,6 +301,14 @@ impl RunnerConfig { | |||
| 239 | ); | 301 | ); |
| 240 | m.insert("concurrency".into(), json!(self.concurrency)); | 302 | m.insert("concurrency".into(), json!(self.concurrency)); |
| 241 | m.insert("limits.memory".into(), json!(self.limits.memory)); | 303 | m.insert("limits.memory".into(), json!(self.limits.memory)); |
| 304 | + m.insert( | ||
| 305 | + "limits.reserve_memory".into(), | ||
| 306 | + json!(self.limits.reserve_memory), | ||
| 307 | + ); | ||
| 308 | + m.insert( | ||
| 309 | + "limits.memory_budget".into(), | ||
| 310 | + json!(self.limits.memory_budget.as_deref().unwrap_or("auto")), | ||
| 311 | + ); | ||
| 242 | m.insert("limits.cpus".into(), json!(self.limits.cpus)); | 312 | m.insert("limits.cpus".into(), json!(self.limits.cpus)); |
| 243 | m.insert("limits.pids".into(), json!(self.limits.pids)); | 313 | m.insert("limits.pids".into(), json!(self.limits.pids)); |
| 244 | m.insert( | 314 | m.insert( |
| @@ -289,6 +359,18 @@ impl RunnerConfig { | |||
| 289 | .as_str() | 359 | .as_str() |
| 290 | .map(|v| self.limits.memory = v.to_owned()) | 360 | .map(|v| self.limits.memory = v.to_owned()) |
| 291 | .is_some(), | 361 | .is_some(), |
| 362 | + "limits.reserve_memory" => value | ||
| 363 | + .as_str() | ||
| 364 | + .filter(|v| forge_ci::size::parse_size(v).is_some()) | ||
| 365 | + .map(|v| self.limits.reserve_memory = v.to_owned()) | ||
| 366 | + .is_some(), | ||
| 367 | + "limits.memory_budget" => value | ||
| 368 | + .as_str() | ||
| 369 | + .filter(|v| *v == "auto" || forge_ci::size::parse_size(v).is_some()) | ||
| 370 | + .map(|v| { | ||
| 371 | + self.limits.memory_budget = (v != "auto").then(|| v.to_owned()); | ||
| 372 | + }) | ||
| 373 | + .is_some(), | ||
| 292 | "limits.cpus" => value | 374 | "limits.cpus" => value |
| 293 | .as_str() | 375 | .as_str() |
| 294 | .map(|v| self.limits.cpus = v.to_owned()) | 376 | .map(|v| self.limits.cpus = v.to_owned()) |
| @@ -545,6 +627,74 @@ mod tests { | |||
| 545 | assert_eq!(config.cache_max_gib, 20); | 627 | assert_eq!(config.cache_max_gib, 20); |
| 546 | } | 628 | } |
| 547 | 629 | ||
| 630 | + #[test] | ||
| 631 | + fn cgroup_memory_is_the_declared_memory_plus_slack() { | ||
| 632 | + let limits = Limits::default(); | ||
| 633 | + let gib = 1u64 << 30; | ||
| 634 | + // Declared 4g: 4g plus 1/16, which is the 256 MiB minimum here. | ||
| 635 | + assert_eq!( | ||
| 636 | + limits.job_memory_limit(Some(4 * gib)), | ||
| 637 | + Some(4 * gib + (256 << 20)) | ||
| 638 | + ); | ||
| 639 | + // Slack grows with big jobs and has a floor for small ones. | ||
| 640 | + assert_eq!(memory_slack(32 * gib), 2 * gib); | ||
| 641 | + assert_eq!(memory_slack(512 << 20), 256 << 20); | ||
| 642 | + // The declared value wins over limits.memory, in both directions. | ||
| 643 | + let small = Limits { | ||
| 644 | + memory: "8g".into(), | ||
| 645 | + ..Limits::default() | ||
| 646 | + }; | ||
| 647 | + assert_eq!(small.job_memory_limit(Some(gib)), Some(gib + (256 << 20))); | ||
| 648 | + assert_eq!( | ||
| 649 | + small.for_job(Some(gib)).memory, | ||
| 650 | + (gib + (256 << 20)).to_string() | ||
| 651 | + ); | ||
| 652 | + } | ||
| 653 | + | ||
| 654 | + #[test] | ||
| 655 | + fn cgroup_memory_without_a_declaration_is_the_larger_of_limit_and_reserve() { | ||
| 656 | + let gib = 1u64 << 30; | ||
| 657 | + let limits = Limits::default(); | ||
| 658 | + assert_eq!(limits.job_memory_limit(None), Some(4 * gib)); | ||
| 659 | + // The configured text is kept as it is. | ||
| 660 | + assert_eq!(limits.for_job(None).memory, "4g"); | ||
| 661 | + let big_reserve = Limits { | ||
| 662 | + reserve_memory: "6g".into(), | ||
| 663 | + ..Limits::default() | ||
| 664 | + }; | ||
| 665 | + assert_eq!(big_reserve.job_memory_limit(None), Some(6 * gib)); | ||
| 666 | + assert_eq!(big_reserve.for_job(None).memory, (6 * gib).to_string()); | ||
| 667 | + let bad = Limits { | ||
| 668 | + memory: "lots".into(), | ||
| 669 | + ..Limits::default() | ||
| 670 | + }; | ||
| 671 | + assert_eq!(bad.job_memory_limit(None), None); | ||
| 672 | + assert_eq!(bad.for_job(None).memory, "lots"); | ||
| 673 | + } | ||
| 674 | + | ||
| 675 | + #[test] | ||
| 676 | + fn memory_settings_are_reported_and_overridable() { | ||
| 677 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 678 | + let mut config = sample(dir.path()); | ||
| 679 | + let report = config.report(); | ||
| 680 | + assert_eq!(report["limits.reserve_memory"], "1g"); | ||
| 681 | + assert_eq!(report["limits.memory_budget"], "auto"); | ||
| 682 | + let mut ov = BTreeMap::new(); | ||
| 683 | + ov.insert("limits.reserve_memory".to_owned(), serde_json::json!("2g")); | ||
| 684 | + ov.insert("limits.memory_budget".to_owned(), serde_json::json!("6g")); | ||
| 685 | + config.apply_overrides(&ov); | ||
| 686 | + assert_eq!(config.limits.reserve_memory, "2g"); | ||
| 687 | + assert_eq!(config.limits.memory_budget.as_deref(), Some("6g")); | ||
| 688 | + ov.insert("limits.memory_budget".to_owned(), serde_json::json!("auto")); | ||
| 689 | + ov.insert( | ||
| 690 | + "limits.reserve_memory".to_owned(), | ||
| 691 | + serde_json::json!("nope"), | ||
| 692 | + ); | ||
| 693 | + config.apply_overrides(&ov); | ||
| 694 | + assert_eq!(config.limits.memory_budget, None); | ||
| 695 | + assert_eq!(config.limits.reserve_memory, "2g", "a bad value is skipped"); | ||
| 696 | + } | ||
| 697 | + | ||
| 548 | #[test] | 698 | #[test] |
| 549 | fn cache_cap_can_be_set_and_turned_off() { | 699 | fn cache_cap_can_be_set_and_turned_off() { |
| 550 | let dir = tempfile::tempdir().expect("tempdir"); | 700 | let dir = tempfile::tempdir().expect("tempdir"); |
crates/forge-runner/src/executor.rsmodified+20 -2
| @@ -137,6 +137,7 @@ pub fn podman_invocation( | |||
| 137 | ) -> Result<PodmanInvocation, ExecError> { | 137 | ) -> Result<PodmanInvocation, ExecError> { |
| 138 | validate_job_id(&job.job_id).map_err(|e| ExecError::Invalid(e.to_string()))?; | 138 | validate_job_id(&job.job_id).map_err(|e| ExecError::Invalid(e.to_string()))?; |
| 139 | check_image(&job.image)?; | 139 | check_image(&job.image)?; |
| 140 | + let limits = &limits.for_job(job.memory_bytes); | ||
| 140 | check_limit(&limits.memory, "memory")?; | 141 | check_limit(&limits.memory, "memory")?; |
| 141 | check_limit(&limits.cpus, "cpus")?; | 142 | check_limit(&limits.cpus, "cpus")?; |
| 142 | let ws = workspace | 143 | let ws = workspace |
| @@ -157,6 +158,8 @@ pub fn podman_invocation( | |||
| 157 | &format!("--network={network}"), | 158 | &format!("--network={network}"), |
| 158 | "--memory", | 159 | "--memory", |
| 159 | &limits.memory, | 160 | &limits.memory, |
| 161 | + "--memory-swap", | ||
| 162 | + &limits.memory, | ||
| 160 | "--cpus", | 163 | "--cpus", |
| 161 | &limits.cpus, | 164 | &limits.cpus, |
| 162 | "--pids-limit", | 165 | "--pids-limit", |
| @@ -622,7 +625,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 622 | env, | 625 | env, |
| 623 | run: job.run.clone(), | 626 | run: job.run.clone(), |
| 624 | network: job.network, | 627 | network: job.network, |
| 625 | - limits: self.limits.clone(), | 628 | + limits: self.limits.for_job(job.memory_bytes), |
| 626 | idmap: self.idmap.clone(), | 629 | idmap: self.idmap.clone(), |
| 627 | }; | 630 | }; |
| 628 | // The request holds the secrets. It goes to the helper's stdin and nowhere else. | 631 | // The request holds the secrets. It goes to the helper's stdin and nowhere else. |
| @@ -803,6 +806,7 @@ mod tests { | |||
| 803 | cache: Vec::new(), | 806 | cache: Vec::new(), |
| 804 | cache_key: String::new(), | 807 | cache_key: String::new(), |
| 805 | cache_restore_keys: Vec::new(), | 808 | cache_restore_keys: Vec::new(), |
| 809 | + memory_bytes: None, | ||
| 806 | } | 810 | } |
| 807 | } | 811 | } |
| 808 | 812 | ||
| @@ -839,7 +843,7 @@ mod tests { | |||
| 839 | let joined = inv.args.join(" "); | 843 | let joined = inv.args.join(" "); |
| 840 | assert!(joined.starts_with("run --rm --name forge-job-job_01 --pull=newer")); | 844 | assert!(joined.starts_with("run --rm --name forge-job-job_01 --pull=newer")); |
| 841 | assert!(joined.contains("--network=none")); | 845 | assert!(joined.contains("--network=none")); |
| 842 | - assert!(joined.contains("--memory 4g --cpus 2 --pids-limit 4096")); | 846 | + assert!(joined.contains("--memory 4g --memory-swap 4g --cpus 2 --pids-limit 4096")); |
| 843 | assert!(joined.contains("--security-opt no-new-privileges --cap-drop ALL")); | 847 | assert!(joined.contains("--security-opt no-new-privileges --cap-drop ALL")); |
| 844 | assert!(joined.contains("-v /work/job_01:/workspace:Z -w /workspace")); | 848 | assert!(joined.contains("-v /work/job_01:/workspace:Z -w /workspace")); |
| 845 | assert!(joined.ends_with("docker.io/library/alpine:3 sh -eu -c true")); | 849 | assert!(joined.ends_with("docker.io/library/alpine:3 sh -eu -c true")); |
| @@ -853,6 +857,20 @@ mod tests { | |||
| 853 | assert!(inv.args.contains(&"--network=slirp4netns".to_owned())); | 857 | assert!(inv.args.contains(&"--network=slirp4netns".to_owned())); |
| 854 | } | 858 | } |
| 855 | 859 | ||
| 860 | + #[test] | ||
| 861 | + fn a_declared_memory_sets_the_podman_limit() { | ||
| 862 | + let mut job = fixture_job("true"); | ||
| 863 | + job.memory_bytes = Some(4 << 30); | ||
| 864 | + let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv"); | ||
| 865 | + let joined = inv.args.join(" "); | ||
| 866 | + // 4 GiB plus the 256 MiB slack, and no swap on top. | ||
| 867 | + let limit = (4u64 << 30) + (256 << 20); | ||
| 868 | + assert!( | ||
| 869 | + joined.contains(&format!("--memory {limit} --memory-swap {limit}")), | ||
| 870 | + "{joined}" | ||
| 871 | + ); | ||
| 872 | + } | ||
| 873 | + | ||
| 856 | #[test] | 874 | #[test] |
| 857 | fn hostile_values_are_refused() { | 875 | fn hostile_values_are_refused() { |
| 858 | let ws = Path::new("/w"); | 876 | let ws = Path::new("/w"); |
crates/forge-runner/src/lib.rsmodified+1 -0
| @@ -13,6 +13,7 @@ pub mod config; | |||
| 13 | pub mod executor; | 13 | pub mod executor; |
| 14 | pub mod limiter; | 14 | pub mod limiter; |
| 15 | pub mod logs; | 15 | pub mod logs; |
| 16 | +pub mod memory; | ||
| 16 | pub mod oci; | 17 | pub mod oci; |
| 17 | pub mod restart; | 18 | pub mod restart; |
| 18 | pub mod runner; | 19 | pub mod runner; |
crates/forge-runner/src/memory.rsadded+311 -0
| @@ -0,0 +1,311 @@ | |||
| 1 | +//! Memory-aware admission. The runner has a memory budget for jobs and every running job holds a | ||
| 2 | +//! reservation against it. A claim tells the forge how much is free, so the forge hands out only a | ||
| 3 | +//! job that fits. The concurrency limit stays as a second cap, see [`crate::limiter`]. | ||
| 4 | +//! | ||
| 5 | +//! Reservations are promises, not measurements: nothing reads what a job really uses. Each job's | ||
| 6 | +//! cgroup limit (see `Limits::for_job`) is what makes the promise hold, so a job that exceeds | ||
| 7 | +//! its reservation is OOM-killed inside its own cgroup and not by the host. | ||
| 8 | + | ||
| 9 | +use std::sync::{Arc, Mutex, PoisonError}; | ||
| 10 | + | ||
| 11 | +use forge_ci::size::{format_size, parse_size}; | ||
| 12 | + | ||
| 13 | +use crate::config::Limits; | ||
| 14 | + | ||
| 15 | +/// Used when a configured size does not parse. `Limits::default` carries the same value. | ||
| 16 | +const FALLBACK_RESERVE: u64 = 1 << 30; | ||
| 17 | +/// The smallest budget the runner will run with, so a typo cannot stop it from taking any job. | ||
| 18 | +const MIN_BUDGET: u64 = 256 << 20; | ||
| 19 | + | ||
| 20 | +/// Pure admission rule: a job fits when the running jobs' reservations plus its own stay within | ||
| 21 | +/// the budget. | ||
| 22 | +pub fn fits(reserved: u64, request: u64, budget: u64) -> bool { | ||
| 23 | + reserved.saturating_add(request) <= budget | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// What a job reserves: its declared memory or the default, never more than the budget. A job | ||
| 27 | +/// bigger than the whole budget therefore still runs, alone, instead of waiting forever. | ||
| 28 | +pub fn reservation(declared: Option<u64>, default_reserve: u64, budget: u64) -> u64 { | ||
| 29 | + declared.unwrap_or(default_reserve).min(budget).max(1) | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// The budget when none is configured: MemTotal minus the headroom, plus `swap_percent` of the | ||
| 33 | +/// swap. The headroom is the larger of `headroom` and 10% of MemTotal. Never below half of | ||
| 34 | +/// MemTotal or [`MIN_BUDGET`], so a small host still takes jobs. | ||
| 35 | +pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent: u32) -> u64 { | ||
| 36 | + let keep = headroom.max(mem_total / 10); | ||
| 37 | + let ram = mem_total.saturating_sub(keep).max(mem_total / 2); | ||
| 38 | + let swap = (u128::from(swap_total) * u128::from(swap_percent.min(100)) / 100) as u64; | ||
| 39 | + ram.saturating_add(swap).max(MIN_BUDGET) | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// `(MemTotal, SwapTotal)` of a `/proc/meminfo` text, in bytes. | ||
| 43 | +pub fn parse_meminfo(text: &str) -> (Option<u64>, Option<u64>) { | ||
| 44 | + let find = |key: &str| { | ||
| 45 | + let line = text.lines().find(|l| l.starts_with(key))?; | ||
| 46 | + let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; | ||
| 47 | + kib.checked_mul(1024) | ||
| 48 | + }; | ||
| 49 | + (find("MemTotal:"), find("SwapTotal:")) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +fn host_memory() -> (Option<u64>, Option<u64>) { | ||
| 53 | + std::fs::read_to_string("/proc/meminfo") | ||
| 54 | + .map(|t| parse_meminfo(&t)) | ||
| 55 | + .unwrap_or((None, None)) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// The budget `limits` asks for on a host with this much memory and swap. | ||
| 59 | +fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 { | ||
| 60 | + match limits.memory_budget.as_deref() { | ||
| 61 | + None | Some("auto") => { | ||
| 62 | + let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); | ||
| 63 | + auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) | ||
| 64 | + } | ||
| 65 | + Some(text) => parse_size(text).map_or_else( | ||
| 66 | + || { | ||
| 67 | + let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); | ||
| 68 | + auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) | ||
| 69 | + }, | ||
| 70 | + |n| n.max(MIN_BUDGET), | ||
| 71 | + ), | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +struct State { | ||
| 76 | + budget: u64, | ||
| 77 | + reserve: u64, | ||
| 78 | + reserved: u64, | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// The runner's memory budget and the reservations against it. Cheap to share: clone the `Arc`. | ||
| 82 | +pub struct MemoryGate { | ||
| 83 | + limits: Limits, | ||
| 84 | + mem_total: u64, | ||
| 85 | + swap_total: u64, | ||
| 86 | + state: Mutex<State>, | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// A job's reservation. Dropping it gives the memory back. | ||
| 90 | +pub struct Reservation { | ||
| 91 | + bytes: u64, | ||
| 92 | + gate: Arc<MemoryGate>, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +impl Reservation { | ||
| 96 | + pub fn bytes(&self) -> u64 { | ||
| 97 | + self.bytes | ||
| 98 | + } | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +impl Drop for Reservation { | ||
| 102 | + fn drop(&mut self) { | ||
| 103 | + let mut state = self.gate.lock(); | ||
| 104 | + state.reserved = state.reserved.saturating_sub(self.bytes); | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +impl MemoryGate { | ||
| 109 | + /// A gate for this host, read from `/proc/meminfo`. Without it the host is assumed to have | ||
| 110 | + /// 8 GiB. | ||
| 111 | + pub fn for_host(limits: &Limits) -> Arc<Self> { | ||
| 112 | + let (mem, swap) = host_memory(); | ||
| 113 | + Self::new(limits, mem.unwrap_or(8 << 30), swap.unwrap_or(0)) | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + pub fn new(limits: &Limits, mem_total: u64, swap_total: u64) -> Arc<Self> { | ||
| 117 | + let budget = configured_budget(limits, mem_total, swap_total); | ||
| 118 | + let reserve = parse_size(&limits.reserve_memory).unwrap_or(FALLBACK_RESERVE); | ||
| 119 | + Arc::new(Self { | ||
| 120 | + limits: limits.clone(), | ||
| 121 | + mem_total, | ||
| 122 | + swap_total, | ||
| 123 | + state: Mutex::new(State { | ||
| 124 | + budget, | ||
| 125 | + reserve, | ||
| 126 | + reserved: 0, | ||
| 127 | + }), | ||
| 128 | + }) | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + fn lock(&self) -> std::sync::MutexGuard<'_, State> { | ||
| 132 | + self.state.lock().unwrap_or_else(PoisonError::into_inner) | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + pub fn budget(&self) -> u64 { | ||
| 136 | + self.lock().budget | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + pub fn default_reserve(&self) -> u64 { | ||
| 140 | + self.lock().reserve | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + pub fn reserved(&self) -> u64 { | ||
| 144 | + self.lock().reserved | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + /// What a new claim may admit: the budget minus the running jobs' reservations. | ||
| 148 | + pub fn free(&self) -> u64 { | ||
| 149 | + let state = self.lock(); | ||
| 150 | + state.budget.saturating_sub(state.reserved) | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + /// Reserves memory for a claimed job. This always succeeds: the forge has already checked the | ||
| 154 | + /// job fits, and a job that was handed out must run. An older forge that does not check can | ||
| 155 | + /// leave the runner over its budget, and `free` then reads 0 until jobs finish. | ||
| 156 | + pub fn reserve(self: &Arc<Self>, declared: Option<u64>) -> Reservation { | ||
| 157 | + let mut state = self.lock(); | ||
| 158 | + let bytes = reservation(declared, state.reserve, state.budget); | ||
| 159 | + state.reserved = state.reserved.saturating_add(bytes); | ||
| 160 | + Reservation { | ||
| 161 | + bytes, | ||
| 162 | + gate: self.clone(), | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + /// Applies what the forge asked for, the way `Limiter::apply` does for concurrency: `Some` | ||
| 167 | + /// is an override, `None` brings back the `runner.toml` value. A value that does not parse | ||
| 168 | + /// counts as no override. Returns a log line when something changed. | ||
| 169 | + pub fn apply(&self, budget: Option<&str>, reserve: Option<&str>) -> Option<String> { | ||
| 170 | + let mut limits = self.limits.clone(); | ||
| 171 | + if let Some(text) = budget.filter(|t| *t == "auto" || parse_size(t).is_some()) { | ||
| 172 | + limits.memory_budget = (text != "auto").then(|| text.to_owned()); | ||
| 173 | + } | ||
| 174 | + if let Some(text) = reserve.filter(|t| parse_size(t).is_some()) { | ||
| 175 | + limits.reserve_memory = text.to_owned(); | ||
| 176 | + } | ||
| 177 | + let new_budget = configured_budget(&limits, self.mem_total, self.swap_total); | ||
| 178 | + let new_reserve = parse_size(&limits.reserve_memory).unwrap_or(FALLBACK_RESERVE); | ||
| 179 | + let mut state = self.lock(); | ||
| 180 | + if (state.budget, state.reserve) == (new_budget, new_reserve) { | ||
| 181 | + return None; | ||
| 182 | + } | ||
| 183 | + let line = format!( | ||
| 184 | + "runner: memory budget {} -> {}, default reservation {} -> {}", | ||
| 185 | + format_size(state.budget), | ||
| 186 | + format_size(new_budget), | ||
| 187 | + format_size(state.reserve), | ||
| 188 | + format_size(new_reserve), | ||
| 189 | + ); | ||
| 190 | + state.budget = new_budget; | ||
| 191 | + state.reserve = new_reserve; | ||
| 192 | + Some(line) | ||
| 193 | + } | ||
| 194 | + | ||
| 195 | + /// Like [`MemoryGate::apply`], and logs the change. | ||
| 196 | + pub fn apply_logged(&self, budget: Option<&str>, reserve: Option<&str>) { | ||
| 197 | + if let Some(line) = self.apply(budget, reserve) { | ||
| 198 | + tracing::info!("{line}"); | ||
| 199 | + } | ||
| 200 | + } | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +#[cfg(test)] | ||
| 204 | +mod tests { | ||
| 205 | + use super::*; | ||
| 206 | + | ||
| 207 | + const GIB: u64 = 1 << 30; | ||
| 208 | + | ||
| 209 | + #[test] | ||
| 210 | + fn a_job_fits_when_the_sum_stays_within_the_budget() { | ||
| 211 | + // 6.5 GiB budget, one 4 GiB job running. | ||
| 212 | + let budget = 6 * GIB + GIB / 2; | ||
| 213 | + assert!(fits(0, 4 * GIB, budget)); | ||
| 214 | + assert!(fits(4 * GIB, 2 * GIB, budget)); | ||
| 215 | + assert!( | ||
| 216 | + fits(4 * GIB, 2 * GIB + GIB / 2, budget), | ||
| 217 | + "exactly the budget" | ||
| 218 | + ); | ||
| 219 | + assert!(!fits(4 * GIB, 4 * GIB, budget), "second heavy job waits"); | ||
| 220 | + assert!(!fits(budget, 1, budget)); | ||
| 221 | + assert!(!fits(u64::MAX, 1, budget), "no overflow"); | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + #[test] | ||
| 225 | + fn a_job_without_memory_reserves_the_default() { | ||
| 226 | + assert_eq!(reservation(None, GIB, 6 * GIB), GIB); | ||
| 227 | + assert_eq!(reservation(Some(4 * GIB), GIB, 6 * GIB), 4 * GIB); | ||
| 228 | + // Bigger than the whole budget: capped, so it still runs when the runner is idle. | ||
| 229 | + assert_eq!(reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB); | ||
| 230 | + assert!(fits(0, reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB)); | ||
| 231 | + } | ||
| 232 | + | ||
| 233 | + #[test] | ||
| 234 | + fn auto_budget_is_mem_total_minus_headroom() { | ||
| 235 | + // The production host: 7.6 GiB RAM, 8 GiB swap, 1 GiB headroom, swap ignored. | ||
| 236 | + let total = 7 * GIB + 6 * GIB / 10; | ||
| 237 | + let budget = auto_budget(total, 8 * GIB, GIB, 0); | ||
| 238 | + assert_eq!(budget, total - GIB); | ||
| 239 | + assert!(budget > 6 * GIB && budget < 7 * GIB); | ||
| 240 | + // On a big host 10% wins over 1 GiB. | ||
| 241 | + assert_eq!(auto_budget(64 * GIB, 0, GIB, 0), 64 * GIB - 64 * GIB / 10); | ||
| 242 | + // Half of the swap counted. | ||
| 243 | + assert_eq!(auto_budget(total, 8 * GIB, GIB, 50), total - GIB + 4 * GIB); | ||
| 244 | + // A tiny host keeps at least half. | ||
| 245 | + assert_eq!(auto_budget(GIB, 0, 2 * GIB, 0), GIB / 2); | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + #[test] | ||
| 249 | + fn meminfo_is_parsed() { | ||
| 250 | + let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nSwapTotal: 8388604 kB\n"; | ||
| 251 | + assert_eq!( | ||
| 252 | + parse_meminfo(text), | ||
| 253 | + (Some(7_971_680 * 1024), Some(8_388_604 * 1024)) | ||
| 254 | + ); | ||
| 255 | + assert_eq!(parse_meminfo(""), (None, None)); | ||
| 256 | + } | ||
| 257 | + | ||
| 258 | + #[test] | ||
| 259 | + fn the_gate_tracks_reservations() { | ||
| 260 | + let limits = Limits { | ||
| 261 | + memory_budget: Some("6g".into()), | ||
| 262 | + ..Limits::default() | ||
| 263 | + }; | ||
| 264 | + let gate = MemoryGate::new(&limits, 8 * GIB, 0); | ||
| 265 | + assert_eq!(gate.budget(), 6 * GIB); | ||
| 266 | + assert_eq!(gate.free(), 6 * GIB); | ||
| 267 | + let heavy = gate.reserve(Some(4 * GIB)); | ||
| 268 | + assert_eq!(gate.free(), 2 * GIB); | ||
| 269 | + let light = gate.reserve(None); | ||
| 270 | + assert_eq!(gate.reserved(), 5 * GIB); | ||
| 271 | + assert_eq!(gate.free(), GIB); | ||
| 272 | + drop(heavy); | ||
| 273 | + assert_eq!(gate.free(), 5 * GIB); | ||
| 274 | + drop(light); | ||
| 275 | + assert_eq!(gate.free(), 6 * GIB); | ||
| 276 | + } | ||
| 277 | + | ||
| 278 | + #[test] | ||
| 279 | + fn an_old_forge_cannot_push_free_below_zero() { | ||
| 280 | + let limits = Limits { | ||
| 281 | + memory_budget: Some("2g".into()), | ||
| 282 | + ..Limits::default() | ||
| 283 | + }; | ||
| 284 | + let gate = MemoryGate::new(&limits, 8 * GIB, 0); | ||
| 285 | + let a = gate.reserve(Some(2 * GIB)); | ||
| 286 | + let b = gate.reserve(Some(2 * GIB)); | ||
| 287 | + assert_eq!(gate.free(), 0); | ||
| 288 | + drop(a); | ||
| 289 | + assert_eq!(gate.free(), 0); | ||
| 290 | + drop(b); | ||
| 291 | + assert_eq!(gate.free(), 2 * GIB); | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + #[test] | ||
| 295 | + fn the_forge_can_change_budget_and_reserve_live() { | ||
| 296 | + let gate = MemoryGate::new(&Limits::default(), 8 * GIB, 0); | ||
| 297 | + assert_eq!(gate.budget(), 7 * GIB); | ||
| 298 | + let line = gate.apply(Some("5g"), Some("2g")); | ||
| 299 | + assert!(line.is_some()); | ||
| 300 | + assert_eq!(gate.budget(), 5 * GIB); | ||
| 301 | + assert_eq!(gate.default_reserve(), 2 * GIB); | ||
| 302 | + assert_eq!(gate.apply(Some("5g"), Some("2g")), None, "no change"); | ||
| 303 | + // No override brings the runner.toml values back. | ||
| 304 | + gate.apply(None, None); | ||
| 305 | + assert_eq!(gate.default_reserve(), GIB); | ||
| 306 | + assert_ne!(gate.budget(), 5 * GIB); | ||
| 307 | + // Nonsense is ignored. | ||
| 308 | + gate.apply(Some("lots"), Some("0")); | ||
| 309 | + assert_eq!(gate.default_reserve(), GIB); | ||
| 310 | + } | ||
| 311 | +} | ||
crates/forge-runner/src/runner.rsmodified+20 -0
| @@ -13,11 +13,13 @@ use tokio_util::sync::CancellationToken; | |||
| 13 | 13 | ||
| 14 | use crate::artifacts; | 14 | use crate::artifacts; |
| 15 | use crate::cache::CacheStore; | 15 | use crate::cache::CacheStore; |
| 16 | +use crate::client::MemoryClaim; | ||
| 16 | use crate::client::{ClientError, ForgeClient}; | 17 | use crate::client::{ClientError, ForgeClient}; |
| 17 | use crate::config::RunnerConfig; | 18 | use crate::config::RunnerConfig; |
| 18 | use crate::executor::{ExecRequest, ExecResult, Executor}; | 19 | use crate::executor::{ExecRequest, ExecResult, Executor}; |
| 19 | use crate::limiter::Limiter; | 20 | use crate::limiter::Limiter; |
| 20 | use crate::logs::{self, PumpConfig}; | 21 | use crate::logs::{self, PumpConfig}; |
| 22 | +use crate::memory::MemoryGate; | ||
| 21 | use crate::restart::{self, RestartState, Step}; | 23 | use crate::restart::{self, RestartState, Step}; |
| 22 | use crate::update::{self, Installed, UpdateState}; | 24 | use crate::update::{self, Installed, UpdateState}; |
| 23 | use crate::workspace; | 25 | use crate::workspace; |
| @@ -73,6 +75,8 @@ pub struct Runner { | |||
| 73 | cache: Option<Arc<CacheStore>>, | 75 | cache: Option<Arc<CacheStore>>, |
| 74 | /// The live job limit. Starts at `runner.toml` and follows the forge's override. | 76 | /// The live job limit. Starts at `runner.toml` and follows the forge's override. |
| 75 | limiter: Arc<Limiter>, | 77 | limiter: Arc<Limiter>, |
| 78 | + /// The memory budget and the running jobs' reservations, see [`crate::memory`]. | ||
| 79 | + memory: Arc<MemoryGate>, | ||
| 76 | /// A restart an admin asked for, see [`restart`]. | 80 | /// A restart an admin asked for, see [`restart`]. |
| 77 | restart: Arc<RestartState>, | 81 | restart: Arc<RestartState>, |
| 78 | } | 82 | } |
| @@ -85,6 +89,7 @@ impl Runner { | |||
| 85 | ) -> Result<Self, ClientError> { | 89 | ) -> Result<Self, ClientError> { |
| 86 | let client = ForgeClient::new(&config.url)?; | 90 | let client = ForgeClient::new(&config.url)?; |
| 87 | let limiter = Limiter::new(config.concurrency); | 91 | let limiter = Limiter::new(config.concurrency); |
| 92 | + let memory = MemoryGate::for_host(&config.limits); | ||
| 88 | Ok(Self { | 93 | Ok(Self { |
| 89 | client, | 94 | client, |
| 90 | config: Arc::new(config), | 95 | config: Arc::new(config), |
| @@ -92,6 +97,7 @@ impl Runner { | |||
| 92 | options, | 97 | options, |
| 93 | cache: None, | 98 | cache: None, |
| 94 | limiter, | 99 | limiter, |
| 100 | + memory, | ||
| 95 | restart: Arc::new(RestartState::default()), | 101 | restart: Arc::new(RestartState::default()), |
| 96 | }) | 102 | }) |
| 97 | } | 103 | } |
| @@ -133,6 +139,8 @@ impl Runner { | |||
| 133 | tracing::info!( | 139 | tracing::info!( |
| 134 | name = %self.config.name, | 140 | name = %self.config.name, |
| 135 | concurrency = self.limiter.current(), | 141 | concurrency = self.limiter.current(), |
| 142 | + memory_budget = %forge_ci::size::format_size(self.memory.budget()), | ||
| 143 | + reserve_memory = %forge_ci::size::format_size(self.memory.default_reserve()), | ||
| 136 | auto_update = updates.enabled(), | 144 | auto_update = updates.enabled(), |
| 137 | "runner started" | 145 | "runner started" |
| 138 | ); | 146 | ); |
| @@ -219,12 +227,21 @@ impl Runner { | |||
| 219 | &self.config.runner_secret, | 227 | &self.config.runner_secret, |
| 220 | &self.config.labels, | 228 | &self.config.labels, |
| 221 | Some(self.limiter.current()), | 229 | Some(self.limiter.current()), |
| 230 | + Some(MemoryClaim { | ||
| 231 | + free: self.memory.free(), | ||
| 232 | + budget: self.memory.budget(), | ||
| 233 | + reserve: self.memory.default_reserve(), | ||
| 234 | + }), | ||
| 222 | ) => r, | 235 | ) => r, |
| 223 | }; | 236 | }; |
| 224 | match claimed { | 237 | match claimed { |
| 225 | Ok(reply) => { | 238 | Ok(reply) => { |
| 226 | // No header means no override: back to the runner.toml value. | 239 | // No header means no override: back to the runner.toml value. |
| 227 | self.limiter.apply_logged(reply.concurrency); | 240 | self.limiter.apply_logged(reply.concurrency); |
| 241 | + self.memory.apply_logged( | ||
| 242 | + reply.memory_budget.as_deref(), | ||
| 243 | + reply.reserve_memory.as_deref(), | ||
| 244 | + ); | ||
| 228 | self.restart.observe(reply.restart); | 245 | self.restart.observe(reply.restart); |
| 229 | if updates.observe(reply.binary_sha256.as_deref()) | 246 | if updates.observe(reply.binary_sha256.as_deref()) |
| 230 | && let Some(sha) = updates.pending() | 247 | && let Some(sha) = updates.pending() |
| @@ -241,8 +258,11 @@ impl Runner { | |||
| 241 | ); | 258 | ); |
| 242 | let runner = self.clone(); | 259 | let runner = self.clone(); |
| 243 | let cancel = jobs_cancel.child_token(); | 260 | let cancel = jobs_cancel.child_token(); |
| 261 | + // Reserved before the next claim, so that claim sees less free memory. | ||
| 262 | + let reservation = self.memory.reserve(job.memory_bytes); | ||
| 244 | jobs.spawn(async move { | 263 | jobs.spawn(async move { |
| 245 | let _permit = permit; | 264 | let _permit = permit; |
| 265 | + let _reservation = reservation; | ||
| 246 | runner.process(job, cancel).await; | 266 | runner.process(job, cancel).await; |
| 247 | }); | 267 | }); |
| 248 | } | 268 | } |
crates/forge-runner/src/sandbox/spec.rsmodified+9 -0
| @@ -282,6 +282,9 @@ fn build_resources(limits: &Limits) -> Result<oci_spec::runtime::LinuxResources, | |||
| 282 | .memory( | 282 | .memory( |
| 283 | LinuxMemoryBuilder::default() | 283 | LinuxMemoryBuilder::default() |
| 284 | .limit(memory) | 284 | .limit(memory) |
| 285 | + // Memory plus swap equals memory: a job at its limit is OOM-killed inside its own | ||
| 286 | + // cgroup instead of pushing the host into swap (memory.swap.max = 0). | ||
| 287 | + .swap(memory) | ||
| 285 | .build() | 288 | .build() |
| 286 | .map_err(spec_err)?, | 289 | .map_err(spec_err)?, |
| 287 | ) | 290 | ) |
| @@ -462,6 +465,7 @@ mod tests { | |||
| 462 | cpus: "1.5".to_owned(), | 465 | cpus: "1.5".to_owned(), |
| 463 | pids: 512, | 466 | pids: 512, |
| 464 | image_max_gb: 20, | 467 | image_max_gb: 20, |
| 468 | + ..Limits::default() | ||
| 465 | }, | 469 | }, |
| 466 | idmap: IdMap::single(), | 470 | idmap: IdMap::single(), |
| 467 | } | 471 | } |
| @@ -629,6 +633,11 @@ mod tests { | |||
| 629 | res.memory().as_ref().and_then(|m| m.limit()), | 633 | res.memory().as_ref().and_then(|m| m.limit()), |
| 630 | Some(2 * 1024 * 1024 * 1024) | 634 | Some(2 * 1024 * 1024 * 1024) |
| 631 | ); | 635 | ); |
| 636 | + // Memory plus swap equals memory, so the cgroup gets memory.swap.max = 0. | ||
| 637 | + assert_eq!( | ||
| 638 | + res.memory().as_ref().and_then(|m| m.swap()), | ||
| 639 | + Some(2 * 1024 * 1024 * 1024) | ||
| 640 | + ); | ||
| 632 | let cpu = res.cpu().as_ref().expect("cpu"); | 641 | let cpu = res.cpu().as_ref().expect("cpu"); |
| 633 | assert_eq!(cpu.period(), Some(CPU_PERIOD_US)); | 642 | assert_eq!(cpu.period(), Some(CPU_PERIOD_US)); |
| 634 | assert_eq!(cpu.quota(), Some(150_000)); | 643 | assert_eq!(cpu.quota(), Some(150_000)); |
crates/forge-runner/tests/builtin.rsmodified+1 -0
| @@ -86,6 +86,7 @@ fn job(run: &str) -> JobAssignment { | |||
| 86 | cache: Vec::new(), | 86 | cache: Vec::new(), |
| 87 | cache_key: String::new(), | 87 | cache_key: String::new(), |
| 88 | cache_restore_keys: Vec::new(), | 88 | cache_restore_keys: Vec::new(), |
| 89 | + memory_bytes: None, | ||
| 89 | } | 90 | } |
| 90 | } | 91 | } |
| 91 | 92 | ||
crates/forge-runner/tests/flow.rsmodified+1 -0
| @@ -311,6 +311,7 @@ fn job(job_id: &str, commit: &str, clone_url: &str, run: &str) -> JobAssignment | |||
| 311 | cache: Vec::new(), | 311 | cache: Vec::new(), |
| 312 | cache_key: String::new(), | 312 | cache_key: String::new(), |
| 313 | cache_restore_keys: Vec::new(), | 313 | cache_restore_keys: Vec::new(), |
| 314 | + memory_bytes: None, | ||
| 314 | } | 315 | } |
| 315 | } | 316 | } |
| 316 | 317 | ||
crates/forge-web/src/ci/api.rsmodified+52 -8
| @@ -10,11 +10,12 @@ use forge_ci::config::JobSpec; | |||
| 10 | use forge_ci::mask::Masker; | 10 | use forge_ci::mask::Masker; |
| 11 | use forge_ci::proto::{ | 11 | use forge_ci::proto::{ |
| 12 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, | 12 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, |
| 13 | - JobAssignment, Outcome, RESTART_HEADER, RegisterRequest, RegisterResponse, | 13 | + JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER, |
| 14 | - RestartMode as WireRestart, RunnerConfigOverrides, RunnerConfigReport, | 14 | + RegisterRequest, RegisterResponse, RestartMode as WireRestart, RunnerConfigOverrides, |
| 15 | + RunnerConfigReport, | ||
| 15 | }; | 16 | }; |
| 16 | use forge_core::Error as CoreError; | 17 | use forge_core::Error as CoreError; |
| 17 | -use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState, RunnerReport}; | 18 | +use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport}; |
| 18 | use futures_util::StreamExt; | 19 | use futures_util::StreamExt; |
| 19 | use http::header::HeaderValue; | 20 | use http::header::HeaderValue; |
| 20 | use serde_json::json; | 21 | use serde_json::json; |
| @@ -46,6 +47,8 @@ const MAX_JSON_BODY: usize = 64 * 1024; | |||
| 46 | const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_secs(25); | 47 | const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_secs(25); |
| 47 | #[cfg(test)] | 48 | #[cfg(test)] |
| 48 | const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_millis(50); | 49 | const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_millis(50); |
| 50 | +/// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say. | ||
| 51 | +const DEFAULT_RESERVE: u64 = 1 << 30; | ||
| 49 | /// Longest runner name or label, in bytes. | 52 | /// Longest runner name or label, in bytes. |
| 50 | const MAX_NAME_BYTES: usize = 64; | 53 | const MAX_NAME_BYTES: usize = 64; |
| 51 | /// Most labels a runner may register. | 54 | /// Most labels a runner may register. |
| @@ -188,10 +191,19 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 188 | Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(), | 191 | Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(), |
| 189 | Err(_) => ClaimRequest::default(), | 192 | Err(_) => ClaimRequest::default(), |
| 190 | }; | 193 | }; |
| 194 | + // An older runner sends no free memory, and then the oldest compatible job is handed out. | ||
| 195 | + let offer = request.free_memory_bytes.map(|free| MemoryOffer { | ||
| 196 | + free, | ||
| 197 | + budget: request.memory_budget_bytes, | ||
| 198 | + default_reserve: request.reserve_memory_bytes.unwrap_or(DEFAULT_RESERVE), | ||
| 199 | + }); | ||
| 191 | note_report( | 200 | note_report( |
| 192 | state, | 201 | state, |
| 193 | &runner.id, | 202 | &runner.id, |
| 194 | &RunnerReport { | 203 | &RunnerReport { |
| 204 | + memory_budget: request.memory_budget_bytes, | ||
| 205 | + memory_free: request.free_memory_bytes, | ||
| 206 | + memory_reserve: request.reserve_memory_bytes, | ||
| 195 | concurrency: request.concurrency, | 207 | concurrency: request.concurrency, |
| 196 | version: request.version.filter(|v| v.len() <= 64), | 208 | version: request.version.filter(|v| v.len() <= 64), |
| 197 | cpus: request.cpus, | 209 | cpus: request.cpus, |
| @@ -207,9 +219,10 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 207 | }, | 219 | }, |
| 208 | ) | 220 | ) |
| 209 | .await; | 221 | .await; |
| 210 | - let mut res = claim_work(state, &runner).await?; | 222 | + let mut res = claim_work(state, &runner, offer).await?; |
| 211 | // The override can change during the long poll, so it is read at answer time. | 223 | // The override can change during the long poll, so it is read at answer time. |
| 212 | set_concurrency_header(state, &runner.id, &mut res).await; | 224 | set_concurrency_header(state, &runner.id, &mut res).await; |
| 225 | + set_memory_headers(state, &runner.id, &mut res).await; | ||
| 213 | set_restart_header(state, &runner.id, &mut res).await; | 226 | set_restart_header(state, &runner.id, &mut res).await; |
| 214 | // Advertises the binary sha256 when self-update is on and the runner asked for this target. | 227 | // Advertises the binary sha256 when self-update is on and the runner asked for this target. |
| 215 | self_update::advertise(state, headers(cx), &mut res); | 228 | self_update::advertise(state, headers(cx), &mut res); |
| @@ -237,6 +250,24 @@ async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Res | |||
| 237 | } | 250 | } |
| 238 | } | 251 | } |
| 239 | 252 | ||
| 253 | +/// Adds the admin's memory budget and default reservation to a claim answer. No header means no | ||
| 254 | +/// override. An older runner ignores both. | ||
| 255 | +async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Response) { | ||
| 256 | + if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) { | ||
| 257 | + return; | ||
| 258 | + } | ||
| 259 | + for (key, header) in [ | ||
| 260 | + ("limits.memory_budget", MEMORY_BUDGET_HEADER), | ||
| 261 | + ("limits.reserve_memory", RESERVE_MEMORY_HEADER), | ||
| 262 | + ] { | ||
| 263 | + if let Ok(Some(text)) = state.store.runner_field_override(runner_id, key).await | ||
| 264 | + && let Ok(value) = HeaderValue::from_str(&text) | ||
| 265 | + { | ||
| 266 | + res.headers_mut().insert(header, value); | ||
| 267 | + } | ||
| 268 | + } | ||
| 269 | +} | ||
| 270 | + | ||
| 240 | /// The restart an admin asked for, in the wire type. `None` when nothing is pending. | 271 | /// The restart an admin asked for, in the wire type. `None` when nothing is pending. |
| 241 | async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> { | 272 | async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> { |
| 242 | let mode = state.store.runner_restart(runner_id).await.ok().flatten()?; | 273 | let mode = state.store.runner_restart(runner_id).await.ok().flatten()?; |
| @@ -304,7 +335,11 @@ fn overrides_response(runner: &CiRunner) -> Response { | |||
| 304 | ) | 335 | ) |
| 305 | } | 336 | } |
| 306 | 337 | ||
| 307 | -async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result<Response> { | 338 | +async fn claim_work( |
| 339 | + state: &AppState, | ||
| 340 | + runner: &CiRunner, | ||
| 341 | + offer: Option<MemoryOffer>, | ||
| 342 | +) -> topcoat::Result<Response> { | ||
| 308 | // Arm the wake-up before each attempt, so a job queued during the attempt is not missed. | 343 | // Arm the wake-up before each attempt, so a job queued during the attempt is not missed. |
| 309 | // Producers use notify_waiters, which wakes every claimer, so a runner whose labels | 344 | // Producers use notify_waiters, which wakes every claimer, so a runner whose labels |
| 310 | // don't match a job re-arms and keeps waiting for the rest of CLAIM_WAIT. | 345 | // don't match a job re-arms and keeps waiting for the rest of CLAIM_WAIT. |
| @@ -319,7 +354,7 @@ async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result<Resp | |||
| 319 | if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) { | 354 | if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) { |
| 320 | return Ok(empty(StatusCode::NO_CONTENT)); | 355 | return Ok(empty(StatusCode::NO_CONTENT)); |
| 321 | } | 356 | } |
| 322 | - match try_claim(state, runner).await { | 357 | + match try_claim(state, runner, offer).await { |
| 323 | Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), | 358 | Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), |
| 324 | Ok(None) => {} | 359 | Ok(None) => {} |
| 325 | Err(res) => return Ok(*res), | 360 | Err(res) => return Ok(*res), |
| @@ -369,8 +404,16 @@ fn empty(status: StatusCode) -> Response { | |||
| 369 | } | 404 | } |
| 370 | 405 | ||
| 371 | /// One claim attempt. Builds the assignment, including the secrets the job may see. | 406 | /// One claim attempt. Builds the assignment, including the secrets the job may see. |
| 372 | -async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssignment>, Refusal> { | 407 | +async fn try_claim( |
| 373 | - let Some((job, run, job_token)) = state.store.claim_job(runner).await.map_err(api::internal)? | 408 | + state: &AppState, |
| 409 | + runner: &CiRunner, | ||
| 410 | + offer: Option<MemoryOffer>, | ||
| 411 | +) -> Result<Option<JobAssignment>, Refusal> { | ||
| 412 | + let Some((job, run, job_token)) = state | ||
| 413 | + .store | ||
| 414 | + .claim_job_fitting(runner, offer) | ||
| 415 | + .await | ||
| 416 | + .map_err(api::internal)? | ||
| 374 | else { | 417 | else { |
| 375 | return Ok(None); | 418 | return Ok(None); |
| 376 | }; | 419 | }; |
| @@ -417,6 +460,7 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssi | |||
| 417 | cache: spec.cache, | 460 | cache: spec.cache, |
| 418 | cache_key, | 461 | cache_key, |
| 419 | cache_restore_keys, | 462 | cache_restore_keys, |
| 463 | + memory_bytes: spec.memory, | ||
| 420 | })) | 464 | })) |
| 421 | } | 465 | } |
| 422 | 466 | ||
crates/forge-web/src/ci/api_tests.rsmodified+115 -0
| @@ -528,6 +528,121 @@ async fn claim_and_heartbeat_carry_the_concurrency_round_trip() { | |||
| 528 | assert!(beat.json().get("concurrency").is_none()); | 528 | assert!(beat.json().get("concurrency").is_none()); |
| 529 | } | 529 | } |
| 530 | 530 | ||
| 531 | +/// A spec with a declared `memory`, in bytes. | ||
| 532 | +fn spec_with_memory(bytes: u64) -> String { | ||
| 533 | + let mut value: Value = serde_json::from_str(&spec(&[], &[])).unwrap(); | ||
| 534 | + value["memory"] = bytes.into(); | ||
| 535 | + value.to_string() | ||
| 536 | +} | ||
| 537 | + | ||
| 538 | +async fn claim_with_memory(router: &Router, secret: &str, free_gib: u64) -> Sent { | ||
| 539 | + let body = json!({ | ||
| 540 | + "labels": [], | ||
| 541 | + "free_memory_bytes": free_gib << 30, | ||
| 542 | + "memory_budget_bytes": 6u64 << 30, | ||
| 543 | + "reserve_memory_bytes": 1u64 << 30, | ||
| 544 | + }); | ||
| 545 | + send( | ||
| 546 | + router, | ||
| 547 | + "POST", | ||
| 548 | + "/api/v1/ci/runners/claim", | ||
| 549 | + &[bearer(secret)], | ||
| 550 | + json_body(&body), | ||
| 551 | + ) | ||
| 552 | + .await | ||
| 553 | +} | ||
| 554 | + | ||
| 555 | +#[tokio::test] | ||
| 556 | +async fn claim_hands_out_only_a_job_that_fits_the_free_memory() { | ||
| 557 | + let env = bare(|_| {}).await; | ||
| 558 | + let (runner, secret) = runner(&env, &[]).await; | ||
| 559 | + make_run( | ||
| 560 | + &env, | ||
| 561 | + "push", | ||
| 562 | + None, | ||
| 563 | + COMMIT, | ||
| 564 | + &[ | ||
| 565 | + job("big", spec_with_memory(4 << 30)), | ||
| 566 | + job("small", spec_with_memory(1 << 30)), | ||
| 567 | + ], | ||
| 568 | + ) | ||
| 569 | + .await; | ||
| 570 | + | ||
| 571 | + // 2 GiB free: the small job passes the big one, and the assignment carries its memory. | ||
| 572 | + let sent = claim_with_memory(&env.router, &secret, 2).await; | ||
| 573 | + assert_eq!(sent.status, 200); | ||
| 574 | + assert_eq!(sent.json()["job_name"], "small"); | ||
| 575 | + assert_eq!(sent.json()["memory_bytes"], 1u64 << 30); | ||
| 576 | + // Nothing else fits in 1 GiB. | ||
| 577 | + let sent = claim_with_memory(&env.router, &secret, 1).await; | ||
| 578 | + assert_eq!(sent.status, 204); | ||
| 579 | + // The runner's figures are stored for the admin page. | ||
| 580 | + let listed = env.store.list_runners().await.unwrap().remove(0); | ||
| 581 | + assert_eq!(listed.id, runner.id); | ||
| 582 | + assert_eq!(listed.reported.memory_budget, Some(6 << 30)); | ||
| 583 | + assert_eq!(listed.reported.memory_free, Some(1 << 30)); | ||
| 584 | + assert_eq!(listed.reported.memory_reserve, Some(1 << 30)); | ||
| 585 | + assert_eq!(listed.reported.memory_reserved(), Some(5 << 30)); | ||
| 586 | + // With enough room the big job runs. | ||
| 587 | + let sent = claim_with_memory(&env.router, &secret, 5).await; | ||
| 588 | + assert_eq!(sent.json()["job_name"], "big"); | ||
| 589 | + assert_eq!(sent.json()["memory_bytes"], 4u64 << 30); | ||
| 590 | +} | ||
| 591 | + | ||
| 592 | +#[tokio::test] | ||
| 593 | +async fn an_old_runner_without_memory_fields_still_gets_jobs() { | ||
| 594 | + let env = bare(|_| {}).await; | ||
| 595 | + let (_runner, secret) = runner(&env, &[]).await; | ||
| 596 | + make_run( | ||
| 597 | + &env, | ||
| 598 | + "push", | ||
| 599 | + None, | ||
| 600 | + COMMIT, | ||
| 601 | + &[ | ||
| 602 | + job("big", spec_with_memory(64 << 30)), | ||
| 603 | + job("plain", spec(&[], &[])), | ||
| 604 | + ], | ||
| 605 | + ) | ||
| 606 | + .await; | ||
| 607 | + // An old runner sends a body with labels only, or nothing parseable at all. | ||
| 608 | + let sent = claim(&env.router, &secret).await; | ||
| 609 | + assert_eq!(sent.status, 200); | ||
| 610 | + assert_eq!(sent.json()["job_name"], "big"); | ||
| 611 | + // The assignment of a job without memory has no memory field, which an old runner ignores. | ||
| 612 | + let sent = claim(&env.router, &secret).await; | ||
| 613 | + assert_eq!(sent.json()["job_name"], "plain"); | ||
| 614 | + assert!(sent.json().get("memory_bytes").is_none()); | ||
| 615 | + // And the stored figures stay empty. | ||
| 616 | + let listed = env.store.list_runners().await.unwrap().remove(0); | ||
| 617 | + assert_eq!(listed.reported.memory_budget, None); | ||
| 618 | +} | ||
| 619 | + | ||
| 620 | +#[tokio::test] | ||
| 621 | +async fn memory_overrides_from_the_admin_travel_on_the_claim_answer() { | ||
| 622 | + let env = bare(|_| {}).await; | ||
| 623 | + let (runner, secret) = runner(&env, &[]).await; | ||
| 624 | + let sent = claim_with_memory(&env.router, &secret, 6).await; | ||
| 625 | + assert!(sent.headers.get("Forge-Runner-Memory-Budget").is_none()); | ||
| 626 | + assert!(sent.headers.get("Forge-Runner-Reserve-Memory").is_none()); | ||
| 627 | + env.store | ||
| 628 | + .set_runner_field(&runner.id, "limits.memory_budget", Some("5g")) | ||
| 629 | + .await | ||
| 630 | + .unwrap(); | ||
| 631 | + env.store | ||
| 632 | + .set_runner_field(&runner.id, "limits.reserve_memory", Some("2g")) | ||
| 633 | + .await | ||
| 634 | + .unwrap(); | ||
| 635 | + let sent = claim_with_memory(&env.router, &secret, 6).await; | ||
| 636 | + assert_eq!( | ||
| 637 | + sent.headers.get("Forge-Runner-Memory-Budget").unwrap(), | ||
| 638 | + "5g" | ||
| 639 | + ); | ||
| 640 | + assert_eq!( | ||
| 641 | + sent.headers.get("Forge-Runner-Reserve-Memory").unwrap(), | ||
| 642 | + "2g" | ||
| 643 | + ); | ||
| 644 | +} | ||
| 645 | + | ||
| 531 | async fn post_claim(router: &Router, secret: &str, boot: &str) -> Sent { | 646 | async fn post_claim(router: &Router, secret: &str, boot: &str) -> Sent { |
| 532 | let body = serde_json::json!({ "labels": [], "boot_id": boot, "capabilities": ["restart"] }); | 647 | let body = serde_json::json!({ "labels": [], "boot_id": boot, "capabilities": ["restart"] }); |
| 533 | send( | 648 | send( |
crates/forge-web/src/pages/admin_runners.rsmodified+38 -1
| @@ -729,7 +729,16 @@ const TABS: [(&str, &[&str]); 5] = [ | |||
| 729 | "general", | 729 | "general", |
| 730 | &["concurrency", "labels", "executor", "auto_update"], | 730 | &["concurrency", "labels", "executor", "auto_update"], |
| 731 | ), | 731 | ), |
| 732 | - ("limits", &["limits.memory", "limits.cpus", "limits.pids"]), | 732 | + ( |
| 733 | + "limits", | ||
| 734 | + &[ | ||
| 735 | + "limits.memory", | ||
| 736 | + "limits.reserve_memory", | ||
| 737 | + "limits.memory_budget", | ||
| 738 | + "limits.cpus", | ||
| 739 | + "limits.pids", | ||
| 740 | + ], | ||
| 741 | + ), | ||
| 733 | ( | 742 | ( |
| 734 | "storage", | 743 | "storage", |
| 735 | &[ | 744 | &[ |
| @@ -809,6 +818,22 @@ fn field_text(lang: Lang, key: &str) -> (&'static str, &'static str) { | |||
| 809 | "İş başına, örneğin 2g veya 512m.", | 818 | "İş başına, örneğin 2g veya 512m.", |
| 810 | ), | 819 | ), |
| 811 | ), | 820 | ), |
| 821 | + "limits.reserve_memory" => ( | ||
| 822 | + s(lang, "Default reservation", "Varsayılan ayırma"), | ||
| 823 | + s( | ||
| 824 | + lang, | ||
| 825 | + "Memory held for a job that declares no memory, for example 1g.", | ||
| 826 | + "Bellek bildirmeyen bir iş için ayrılan bellek, örneğin 1g.", | ||
| 827 | + ), | ||
| 828 | + ), | ||
| 829 | + "limits.memory_budget" => ( | ||
| 830 | + s(lang, "Memory budget", "Bellek bütçesi"), | ||
| 831 | + s( | ||
| 832 | + lang, | ||
| 833 | + "All running jobs together may reserve this much: auto, or a size such as 6g.", | ||
| 834 | + "Çalışan işlerin toplamda ayırabileceği bellek: auto veya 6g gibi bir boyut.", | ||
| 835 | + ), | ||
| 836 | + ), | ||
| 812 | "limits.cpus" => ( | 837 | "limits.cpus" => ( |
| 813 | s(lang, "CPU limit", "CPU sınırı"), | 838 | s(lang, "CPU limit", "CPU sınırı"), |
| 814 | s( | 839 | s( |
| @@ -1049,6 +1074,15 @@ async fn runner_detail_view( | |||
| 1049 | .map(bytes_text) | 1074 | .map(bytes_text) |
| 1050 | .unwrap_or_default(), | 1075 | .unwrap_or_default(), |
| 1051 | ); | 1076 | ); |
| 1077 | + let reported = &runner.reported; | ||
| 1078 | + let budget_text = or_dash(reported.memory_budget.map(bytes_text).unwrap_or_default()); | ||
| 1079 | + let reserved_text = or_dash( | ||
| 1080 | + reported | ||
| 1081 | + .memory_reserved() | ||
| 1082 | + .map(bytes_text) | ||
| 1083 | + .unwrap_or_default(), | ||
| 1084 | + ); | ||
| 1085 | + let free_text = or_dash(reported.memory_free.map(bytes_text).unwrap_or_default()); | ||
| 1052 | let in_use = if row.concurrency.is_empty() { | 1086 | let in_use = if row.concurrency.is_empty() { |
| 1053 | row.running.to_string() | 1087 | row.running.to_string() |
| 1054 | } else { | 1088 | } else { |
| @@ -1093,6 +1127,9 @@ async fn runner_detail_view( | |||
| 1093 | <div class="srv-field"><span class="srv-label">(s(lang, "Runner version", "Çalıştırıcı sürümü"))</span><strong>(version.as_str())</strong></div> | 1127 | <div class="srv-field"><span class="srv-label">(s(lang, "Runner version", "Çalıştırıcı sürümü"))</span><strong>(version.as_str())</strong></div> |
| 1094 | <div class="srv-field"><span class="srv-label">(s(lang, "CPUs", "CPU sayısı"))</span><strong>(cpus.as_str())</strong></div> | 1128 | <div class="srv-field"><span class="srv-label">(s(lang, "CPUs", "CPU sayısı"))</span><strong>(cpus.as_str())</strong></div> |
| 1095 | <div class="srv-field"><span class="srv-label">(s(lang, "Memory", "Bellek"))</span><strong>(memory.as_str())</strong></div> | 1129 | <div class="srv-field"><span class="srv-label">(s(lang, "Memory", "Bellek"))</span><strong>(memory.as_str())</strong></div> |
| 1130 | + <div class="srv-field"><span class="srv-label">(s(lang, "Memory budget", "Bellek bütçesi"))</span><strong>(budget_text.as_str())</strong></div> | ||
| 1131 | + <div class="srv-field"><span class="srv-label">(s(lang, "Reserved", "Ayrılan"))</span><strong>(reserved_text.as_str())</strong></div> | ||
| 1132 | + <div class="srv-field"><span class="srv-label">(s(lang, "Free to admit", "Alınabilir"))</span><strong>(free_text.as_str())</strong></div> | ||
| 1096 | </div> | 1133 | </div> |
| 1097 | </section> | 1134 | </section> |
| 1098 | <nav class="subnav" aria-label=(s(lang, "Configuration", "Yapılandırma"))> | 1135 | <nav class="subnav" aria-label=(s(lang, "Configuration", "Yapılandırma"))> |
docs/ci.mdmodified+64 -3
| @@ -55,6 +55,7 @@ There must be at least one job, and at most 20. | |||
| 55 | | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. | | 55 | | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. | |
| 56 | | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | | 56 | | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | |
| 57 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | | 57 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | |
| 58 | +| `memory` | string | none | The job's expected peak memory, such as `4g` or `512m`. 64m to 1024g. See [Memory](#memory). | | ||
| 58 | | `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | | 59 | | `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | |
| 59 | | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). | | 60 | | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). | |
| 60 | 61 | ||
| @@ -63,6 +64,41 @@ Job names match `^[a-z0-9][a-z0-9_-]{0,39}$`. | |||
| 63 | The job's workspace is a fresh checkout of the exact commit, at `/workspace`. The job starts in that | 64 | The job's workspace is a fresh checkout of the exact commit, at `/workspace`. The job starts in that |
| 64 | directory. | 65 | directory. |
| 65 | 66 | ||
| 67 | +### Memory | ||
| 68 | + | ||
| 69 | +`memory` is the job's expected peak, not a limit you hope it stays under. A runner counts the | ||
| 70 | +`memory` of its running jobs against its memory budget and takes a new job only when the sum still | ||
| 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 | + | ||
| 75 | +```toml | ||
| 76 | +[jobs.build] | ||
| 77 | +image = "docker.io/library/rust:1" | ||
| 78 | +run = "cargo build --release" | ||
| 79 | +memory = "4g" | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +How it is used: | ||
| 83 | + | ||
| 84 | +- Admission. The runner tells the forge how much memory it can still admit with every claim, and the | ||
| 85 | + forge hands out the first queued job whose reservation fits. A smaller job may run before a bigger | ||
| 86 | + one that has to wait, so a small job is not stuck behind a big one. To keep the big job from | ||
| 87 | + starving, a job that does not fit and has waited 5 minutes stops smaller jobs from passing it on | ||
| 88 | + that runner: the runner runs down its current jobs until the big one fits. A job that asks for | ||
| 89 | + more than the runner's whole budget is treated as asking for the whole budget, so it runs alone | ||
| 90 | + instead of waiting forever. | ||
| 91 | +- Limit. The job's cgroup `memory.max` (podman `--memory`) is `memory` plus slack (1/16, at least | ||
| 92 | + 256 MiB), and swap is off for the job (`memory.swap.max` is 0). A job that goes over is | ||
| 93 | + OOM-killed inside its own cgroup. Without `memory`, the limit is the larger of the runner's | ||
| 94 | + `limits.memory` and `limits.reserve_memory`. | ||
| 95 | +- It is the same for every job in a matrix. | ||
| 96 | + | ||
| 97 | +Runners and forges that predate `memory` still work together. A runner that does not report free | ||
| 98 | +memory gets the oldest queued job as before, and a runner that gets a job with no `memory` field | ||
| 99 | +reserves its default. Upgrade the runner together with the forge: a forge that predates this | ||
| 100 | +hands out jobs without looking at memory, and the runner then cannot refuse them. | ||
| 101 | + | ||
| 66 | ### Example | 102 | ### Example |
| 67 | 103 | ||
| 68 | ```toml | 104 | ```toml |
| @@ -497,7 +533,11 @@ executor = "builtin" # or "podman" | |||
| 497 | auto_update = true # replace the runner binary with the forge's when idle | 533 | auto_update = true # replace the runner binary with the forge's when idle |
| 498 | 534 | ||
| 499 | [limits] | 535 | [limits] |
| 500 | -memory = "4g" # the job cgroup's memory.max, or podman --memory | 536 | +memory = "4g" # the job cgroup's memory.max when the job declares no `memory`, or podman --memory |
| 537 | +reserve_memory = "1g" # what a job without `memory` reserves, and the floor of its cgroup limit (live) | ||
| 538 | +memory_budget = "auto" # all running jobs together may reserve this much (live), or a size like "6g" | ||
| 539 | +memory_headroom = "1g" # in auto mode: kept for the host, the larger of this and 10% of MemTotal | ||
| 540 | +budget_swap_percent = 0 # in auto mode: percent of swap that counts toward the budget | ||
| 501 | cpus = "2" # the job cgroup's cpu.max, or podman --cpus | 541 | cpus = "2" # the job cgroup's cpu.max, or podman --cpus |
| 502 | pids = 4096 # the job cgroup's pids.max, or podman --pids-limit | 542 | pids = 4096 # the job cgroup's pids.max, or podman --pids-limit |
| 503 | image_max_gb = 20 # cap on the unpacked size of one image (builtin) | 543 | image_max_gb = 20 # cap on the unpacked size of one image (builtin) |
| @@ -532,11 +572,25 @@ second Rust build alongside the first needs several more GB even with `CARGO_BUI | |||
| 532 | capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp | 572 | capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp |
| 533 | profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`. | 573 | profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`. |
| 534 | 574 | ||
| 575 | +Memory-aware admission. Concurrency only counts jobs, and several Rust compiles at once can need | ||
| 576 | +more RAM than the host has, which ends in the kernel's OOM killer picking a victim, often `rustc` | ||
| 577 | +in the middle of a build. So a runner also has a memory budget. By default the budget is the | ||
| 578 | +host's `MemTotal` minus a headroom, the larger of `memory_headroom` and 10%: a 7.6 GiB host gets | ||
| 579 | +about 6.6 GiB. Swap does not count unless `budget_swap_percent` says so, because a build that | ||
| 580 | +runs in swap is slower than one that waits. Each running job holds a reservation (its `memory` | ||
| 581 | +from `ci.toml`, see [Memory](#memory), or `reserve_memory`), and a job starts only when the | ||
| 582 | +reservations of the running jobs plus its own fit the budget. `concurrency` stays as a second cap, so | ||
| 583 | +both must have room. The runner page shows the budget, what is reserved and what is free to admit. | ||
| 584 | +The budget and `reserve_memory` are live: an admin can change them on the runner's Limits tab and | ||
| 585 | +the runner applies them on its next claim, logging `runner: memory budget ...`. Reservations are | ||
| 586 | +promises and nothing measures real use; the per-job cgroup limit is what holds a job to its word. | ||
| 587 | + | ||
| 535 | Every `runner.toml` field is visible on the runner's page (`/admin/runners/<id>`), with its value and | 588 | Every `runner.toml` field is visible on the runner's page (`/admin/runners/<id>`), with its value and |
| 536 | whether it comes from `runner.toml` or the UI. The runner reports its effective config when it | 589 | whether it comes from `runner.toml` or the UI. The runner reports its effective config when it |
| 537 | starts, with the secret and registry passwords left out. Fields come in three kinds: | 590 | starts, with the secret and registry passwords left out. Fields come in three kinds: |
| 538 | 591 | ||
| 539 | -- Live: `concurrency` and `labels`, applied on the runner's next check-in. | 592 | +- Live: `concurrency`, `labels`, `limits.reserve_memory` and `limits.memory_budget`, applied on the |
| 593 | + runner's next check-in. | ||
| 540 | - Restart needed: `auto_update`, `executor`, `work_dir`, `sandbox.userns`, the `limits.*` values, | 594 | - Restart needed: `auto_update`, `executor`, `work_dir`, `sandbox.userns`, the `limits.*` values, |
| 541 | `images.keep_days` and `cache_max_gib`. The forge stores the value now and the runner applies it to | 595 | `images.keep_days` and `cache_max_gib`. The forge stores the value now and the runner applies it to |
| 542 | its in-memory config when it next starts, so `runner.toml` on disk is never rewritten. The row says | 596 | its in-memory config when it next starts, so `runner.toml` on disk is never rewritten. The row says |
| @@ -693,7 +747,14 @@ The runner talks to the forge only over HTTPS. JSON bodies are defined in `forge | |||
| 693 | 747 | ||
| 694 | The claim response (`JobAssignment`) carries the repository, the commit, the job's run script, | 748 | The claim response (`JobAssignment`) carries the repository, the commit, the job's run script, |
| 695 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull | 749 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull |
| 696 | -request runs. | 750 | +request runs, and `memory_bytes` when the job declares `memory`. |
| 751 | + | ||
| 752 | +A claim body also carries the runner's host facts and, for memory-aware admission, | ||
| 753 | +`free_memory_bytes` (budget minus the running jobs' reservations), `memory_budget_bytes` and | ||
| 754 | +`reserve_memory_bytes`. All of these are optional. Without `free_memory_bytes` the forge takes the | ||
| 755 | +oldest queued job whose labels match, as before. The claim response may carry the headers | ||
| 756 | +`Forge-Runner-Memory-Budget` and `Forge-Runner-Reserve-Memory` when an admin changed those | ||
| 757 | +settings. | ||
| 697 | 758 | ||
| 698 | For the workspace, the runner runs `git fetch --depth=1` on the clone URL with the job token, then | 759 | For the workspace, the runner runs `git fetch --depth=1` on the clone URL with the job token, then |
| 699 | `git checkout --detach <commit>`. The token goes in an HTTP header, never on the command line. | 760 | `git checkout --detach <commit>`. The token goes in an HTTP header, never on the command line. |