From 1bdf81b054337b6bb3d59d94d56a56fcf154caa9 Mon Sep 17 00:00:00 2001 From: Joshua Cartu Date: Thu, 3 Dec 2026 22:44:56 +0100 Subject: [PATCH] fix(flare-cli,helios): release page cache with O_DIRECT peer serving, inherit orbit memory reserve, and log integrated MemInfo Why - On Linux unified-memory GPUs (such as GB10), CUDA allocations and context creation can respond to Linux `MemFree` rather than `MemAvailable` when tens of gigabytes of clean page cache accumulate from core distribution and buffered cache I/O (NVIDIA/hyperflare-inference#630). - `flare-cli`'s peer-serving path (`distribution::serve_source`) streamed core shards via buffered `RangeReader` before dropping page cache, leaving multi-GiB bursts in the page cache during transfer, and four buffered I/O sites across `flare-cli` and `helios` omitted `release_page_cache`. - `flare orbit run` did not inherit `[memory] reserve` from host configuration (`config.rs`), unlike `flare run`, while persistent groups still needed their stored `--memory-limit` preserved unless overridden on the command line and must not freeze config defaults into saved `GroupSpec.serving` definitions. - When integrated-GPU cache planning was memory-limited or `cuDevicePrimaryCtxRetain` / `cuCtxCreate_v2` returned `CUDA_ERROR_OUT_OF_MEMORY`, diagnostics did not surface Linux `MemFree / MemAvailable / Cached` or hint when reclaimable page cache was likely blocking allocation. What changed - Direct peer serving and missed `release_page_cache` sites: - Re-exported `eos` direct-I/O helpers (`FileReadAt`, `allocate_aligned`, `direct_reopen`, `free_aligned`) from `helios/src/lib.rs`. - Updated `flare-cli/src/distribution.rs::serve_source` to reopen files with `direct_reopen` on Unix and stream 4 MiB aligned chunks from a zero-initialized `AlignedBuffer` (handling arbitrary unaligned offsets, multi-range requests, and unaligned EOF byte-for-byte identically to `cache::RangeReader`), falling back cleanly to buffered `RangeReader` when `O_DIRECT` is unsupported or returns `EINVAL`, and executing one unconditional post-branch `release_page_cache_range` loop in `copy_source_ranges` for every served range (including on error). - Added `release_page_cache` / `release_page_cache_range` at the four missed buffered I/O sites: `flare-cli/src/orbit/controller.rs`, `flare-cli/src/core_cache.rs`, `flare-cli/src/orbit/agent.rs::get`, and `helios/src/core/cache.rs` (`write_stream`, `verify_file`, `hash_file`, `import_legacy_into`, and non-Windows `copy_file`). Collapsed `verify_file` onto `hash_file(path, release: bool)` so `import_legacy_into` hashes with `release = false` (avoiding double storage reads before `insert_legacy_container`) and releases the source file unconditionally after `insert_legacy_container` returns. - Orbit `[memory] reserve` propagation: - Added `#[arg(skip)] pub config_memory_limit: Option` to `OrbitRun` (`flare-cli/src/cli.rs`) and `RunOptions` (`flare-cli/src/orbit/controller.rs`), populated from `[memory] reserve` in `flare-cli/src/config.rs` only when `--memory-limit` is unset on the command line. - Kept config-derived `--memory-limit` out of `OrbitRun::rank_options` and `GroupSpec.serving` so persistent groups never freeze config defaults; applied it only at launch via `apply_config_memory_limit` when neither the saved group nor the CLI specifies `--memory-limit`. - Added a persistent-group round-trip unit test through `save_group` / `Orbit::save` / `Orbit::load` verifying config reserve edits take effect on reload while explicit saved and CLI `--memory-limit` values retain precedence. - Linux integrated-GPU `/proc/meminfo` diagnostics: - Added `LinuxMemInfo { free, available, cached }` parser and `CUDA_ERROR_OUT_OF_MEMORY` constant in `helios/src/runtime_core/`. - Appended `MemFree / MemAvailable / Cached` to the `Plan cache` summary on Linux integrated GPUs and emitted a concise stderr warning when `MemAvailable - MemFree > 10 GiB` and KV sizing is limited by memory (without repeating the triple already logged in `Plan cache`). - Enriched `cuDevicePrimaryCtxRetain` and `cuCtxCreate_v2` `CUDA_ERROR_OUT_OF_MEMORY` failures on Linux integrated GPUs via `enrich_integrated_ctx_oom(error, meminfo: Option)` with `MemFree / MemAvailable / Cached` (and a `drop_caches` hint when `MemAvailable - MemFree > 4 GiB`) while preserving the structured `ExecutionError::Driver(CudaError { code: 2, .. })` error. - Documentation: - Documented `orbit run` `[memory] reserve` inheritance, non-persistence, and saved/CLI `--memory-limit` precedence in `docs/orbit.md` and `docs/cli-design.md`, and integrated-GPU `Plan cache` / context-OOM `/proc/meminfo` diagnostics in `docs/cli-design.md`. Verification - Rebased onto `origin/main` (`f705086b`, including `#720` and `#721`). - CPU-only verification on Linux x86_64 (no live GB10 run yet): - Verified `.githooks/commit-msg` passes on the staged diff and message. - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`: 254 passed (228 bin + 9 cache_commands + 6 cli + 4 inspect + 7 unverified_payload), 0 failed, 3 ignored. - `cargo test --locked --release --manifest-path flare/Cargo.toml`: 255 passed (247 lib + 7 packed_canonical_download + 1 reference_workflows), 0 failed, 4 ignored. - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib`: `core::cache` 106 passed, 0 failed, 2 ignored; `runtime_core::` 206 passed (including `runtime_core::memory` 30 passed), 0 failed, 13 ignored. - `rustfmt --edition 2024`: clean on all touched lines across all 12 Rust files. Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b Signed-off-by: Joshua Cartu --- docs/cli-design.md | 14 +- docs/orbit.md | 15 +- flare-cli/src/cli.rs | 6 + flare-cli/src/config.rs | 109 ++++++++++++- flare-cli/src/core_cache.rs | 4 +- flare-cli/src/distribution.rs | 248 +++++++++++++++++++++++++++- flare-cli/src/main.rs | 57 +++---- flare-cli/src/orbit/agent.rs | 4 +- flare-cli/src/orbit/controller.rs | 202 ++++++++++++++++++++++- helios/src/core/cache.rs | 47 +++--- helios/src/lib.rs | 5 +- helios/src/runtime_core/driver.rs | 2 + helios/src/runtime_core/memory.rs | 263 ++++++++++++++++++++++++++++++ helios/src/runtime_core/mod.rs | 15 +- 14 files changed, 920 insertions(+), 71 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index e9c861f53..73808feb7 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -914,7 +914,12 @@ These are startup sizing budgets, not OS-enforced quotas. Pools stay fixed during serving; Flare does not resize them as other processes allocate memory. Startup reports the requested policies, loaded footprint, per-rank cache budgets, allocated KV tokens, and whether memory, the selected KV ceiling, or -prepared virtual extents limited the pool. TP ranks agree on a capacity each +prepared virtual extents limited the pool. On Linux integrated GPUs, the `Plan +cache` summary also appends `MemFree / MemAvailable / Cached` from +`/proc/meminfo`, emits a stderr warning when KV sizing is limited by memory and +`MemAvailable - MemFree` exceeds 10 GiB, and attaches those counts (with a +`drop_caches` hint when the reclaimable gap exceeds 4 GiB) to +`CUDA_ERROR_OUT_OF_MEMORY` failures during CUDA context creation. TP ranks agree on a capacity each can back. Runtime memory flags reuse the same prepared core and do not alter preparation or captured graphs. They are absent from `ignition export` and the diagnostic `ignition debug-serve` commands. @@ -1458,8 +1463,11 @@ The request controls the seed. `memory.reserve` exists for one case: a process that starts after Flare and needs GPU memory. Processes already running when Flare starts need no setting, because supply is free memory rather than card size. Preparation records -it as the core's serving reserve. Native serving uses an explicit host configuration -value in preference to that recorded reserve. +it as the core's serving reserve. Native serving (`flare run` and `flare orbit +run`) uses an explicit host configuration value in preference to that recorded +reserve; on `orbit run`, the inherited value applies at launch when neither the +command line nor a saved persistent group sets `--memory-limit`, and is never +persisted into the group definition. The GPU prefix cache is derived. It holds model states at instruction, prompt, and answer boundaries so that later requests repeating a prefix skip diff --git a/docs/orbit.md b/docs/orbit.md index f1affff04..8be8cb5b6 100644 --- a/docs/orbit.md +++ b/docs/orbit.md @@ -395,8 +395,14 @@ Local core, executable, and verification paths are saved as absolute paths. The definition is written after placement validation and before starting ranks, so a startup failure can be retried. `--dry-run` saves nothing. A later run uses the saved configuration; overrides affect that launch -only unless `--persistent` is passed again. An existing running group with the -same saved name on the candidate nodes prevents another launch. +only unless `--persistent` is passed again. When neither the command line nor +the saved group specifies `--memory-limit`, `orbit run` inherits `[memory] +reserve` from the controller's Flare configuration at launch without writing +it into the saved `serving` list, so later `[memory] reserve` edits take effect +automatically while a saved explicit `--memory-limit` still takes precedence +over configuration (and a CLI `--memory-limit` overrides both). An existing +running group with the same saved name on the candidate nodes prevents another +launch. `flare orbit ls` keeps saved groups visible when stopped. An unreachable node makes an inactive saved group's state unknown. Saved definitions belong to the @@ -464,8 +470,9 @@ serve. It applies these rules in order: The controller prints the placement, one member per line with its node, GPU and whether the node already holds its rank, before transferring payloads. `--dry-run` stops there after metadata verification and node queries. The planner -does not set `--memory-limit`; groups on disjoint GPUs retain their own serving -memory settings. Placement does not check ring adjacency; routing follows the +does not set `--memory-limit`; groups on disjoint GPUs keep their own explicit +or saved serving memory settings (inheriting the controller's `[memory] reserve` +when neither specifies `--memory-limit`). Placement does not check ring adjacency; routing follows the selected rank order. ## Core caching diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 9acad3372..6fe2fd4bf 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -665,6 +665,12 @@ pub struct OrbitRun { #[command(flatten)] pub serving: ServingOptions, + + /// `[memory] reserve` inherited from host configuration; kept separate from + /// `serving.memory_limit` so it is never persisted into a group's saved options and + /// applies at launch only when neither a saved group nor the CLI specifies `--memory-limit`. + #[arg(skip)] + pub config_memory_limit: Option, } impl OrbitRun { diff --git a/flare-cli/src/config.rs b/flare-cli/src/config.rs index 5b33be280..c75e95c91 100644 --- a/flare-cli/src/config.rs +++ b/flare-cli/src/config.rs @@ -36,7 +36,7 @@ impl Configuration { )?)) } #[cfg(test)] - fn parse(text: &str) -> Result { + pub(crate) fn parse(text: &str) -> Result { Ok(Self(flare::configuration::Configuration::parse(text)?)) } pub(crate) fn apply( @@ -169,6 +169,11 @@ impl Configuration { }, cli::Command::Orbit(args) => match &mut args.command { cli::OrbitCommand::Run(run) => { + if run.serving.memory_limit.is_none() { + run.config_memory_limit = + size(self.memory.reserve.as_deref(), "memory.reserve")? + .map(MemoryLimit::Reserve); + } run.serving.hub.core_cache.get_or_insert(cache); run.serving.hub.hub_cache = Some(hub_cache.clone()); } @@ -961,4 +966,106 @@ namespace = "publisher" ); } } + + #[test] + fn orbit_run_inherits_memory_reserve_unless_explicit_limit_is_set() { + let home = Path::new("/home/test-user"); + let configured = Configuration::parse("[memory]\nreserve = '12 GiB'\n").unwrap(); + + let parse_orbit_run = + |args: &[&str], cfg: &Configuration| -> (cli::OrbitRun, Vec) { + let matches = cli::Cli::command().try_get_matches_from(args).unwrap(); + let mut parsed = cli::Cli::from_arg_matches(&matches).unwrap(); + cfg.apply(&mut parsed, &matches, home).unwrap(); + let cli::Command::Orbit(orbit) = parsed.command else { + panic!("expected orbit command"); + }; + let cli::OrbitCommand::Run(run) = orbit.command else { + panic!("expected orbit run"); + }; + let run_matches = matches + .subcommand_matches("orbit") + .unwrap() + .subcommand_matches("run") + .unwrap(); + let options = run.rank_options(run_matches); + (*run, options) + }; + + // Omitted --memory-limit inherits [memory] reserve into config_memory_limit, keeping it + // out of rank_options so persistent groups never freeze the config default. + let (inherited, options) = + parse_orbit_run(&["flare", "orbit", "run", "model.safetensors"], &configured); + assert_eq!(inherited.serving.memory_limit, None); + assert_eq!( + inherited.config_memory_limit, + Some(MemoryLimit::Reserve(12 << 30)) + ); + assert!( + !options.iter().any(|arg| arg.starts_with("--memory-limit")), + "{options:?}" + ); + + // Explicit --memory-limit takes precedence over [memory] reserve and enters rank_options. + let (explicit_fraction, options) = parse_orbit_run( + &[ + "flare", + "orbit", + "run", + "model.safetensors", + "--memory-limit=0.8", + ], + &configured, + ); + assert_eq!( + explicit_fraction.serving.memory_limit, + Some(MemoryLimit::Fraction(0.8)) + ); + assert_eq!(explicit_fraction.config_memory_limit, None); + assert!( + options + .iter() + .any(|arg| arg == &format!("--memory-limit={}", MemoryLimit::Fraction(0.8))), + "{options:?}" + ); + + let (explicit_reserve, options) = parse_orbit_run( + &[ + "flare", + "orbit", + "run", + "model.safetensors", + "--memory-limit=-4G", + ], + &configured, + ); + assert_eq!( + explicit_reserve.serving.memory_limit, + Some(MemoryLimit::Reserve(4 << 30)) + ); + assert_eq!(explicit_reserve.config_memory_limit, None); + assert!( + options + .iter() + .any(|arg| arg == &format!("--memory-limit={}", MemoryLimit::Reserve(4 << 30))), + "{options:?}" + ); + + // Unset config leaves both memory_limit and config_memory_limit None. + let empty = Configuration::default(); + let (unset, options) = + parse_orbit_run(&["flare", "orbit", "run", "model.safetensors"], &empty); + assert_eq!(unset.serving.memory_limit, None); + assert_eq!(unset.config_memory_limit, None); + assert!( + !options.iter().any(|arg| arg.starts_with("--memory-limit")), + "{options:?}" + ); + + // Invalid [memory] reserve is rejected when loading configuration. + let err = Configuration::parse("[memory]\nreserve = 'not-a-size'\n") + .err() + .expect("invalid memory.reserve should fail"); + assert!(err.to_string().contains("memory.reserve"), "{err}"); + } } diff --git a/flare-cli/src/core_cache.rs b/flare-cli/src/core_cache.rs index d0d67c7f0..fff6314b8 100644 --- a/flare-cli/src/core_cache.rs +++ b/flare-cli/src/core_cache.rs @@ -501,7 +501,9 @@ fn store_entry( return Err("invalid cached payload blob".into()); } let mut digest = Sha256::new(); - std::io::copy(&mut source, &mut digest)?; + let copied = std::io::copy(&mut source, &mut digest); + flare_helios::release_page_cache(&source); + copied?; if format!("{}.safetensors", hex(&digest.finalize())) != blob { return Err("cached payload digest mismatch".into()); } diff --git a/flare-cli/src/distribution.rs b/flare-cli/src/distribution.rs index e3fb73192..69958802f 100644 --- a/flare-cli/src/distribution.rs +++ b/flare-cli/src/distribution.rs @@ -1213,12 +1213,124 @@ fn serve_source( } socket.write_all(&cache::range_bytes(&request.ranges).to_le_bytes())?; let file = &files[rank][request.file]; - let copied = io::copy(&mut cache::RangeReader::new(file, &request.ranges), &mut socket); - for &(offset, size) in &request.ranges { - flare_helios::release_page_cache_range(file, offset, size); + copy_source_ranges(file, &request.ranges, &mut socket)?; + } +} + +#[cfg(unix)] +const DIRECT_BLOCK: usize = 4096; +#[cfg(unix)] +const DIRECT_CHUNK: usize = 4 << 20; + +#[cfg(unix)] +struct AlignedBuffer { + address: usize, + bytes: usize, +} + +#[cfg(unix)] +impl AlignedBuffer { + fn new(bytes: usize) -> io::Result { + let address = flare_helios::allocate_aligned(bytes)?; + // SAFETY: `address` points to `bytes` allocated writable bytes; zeroing initializes them + // before exposing `&mut [u8]`. + unsafe { std::ptr::write_bytes(address as *mut u8, 0, bytes) }; + Ok(Self { address, bytes }) + } + + fn as_mut_slice(&mut self) -> &mut [u8] { + // SAFETY: `address` owns `bytes` initialized writable bytes until `Drop`. + unsafe { std::slice::from_raw_parts_mut(self.address as *mut u8, self.bytes) } + } +} + +#[cfg(unix)] +impl Drop for AlignedBuffer { + fn drop(&mut self) { + // SAFETY: `address` and `bytes` came from `allocate_aligned`. + unsafe { flare_helios::free_aligned(self.address, self.bytes) }; + } +} + +fn copy_ranges_buffered( + file: &File, + ranges: &[(u64, u64)], + writer: &mut impl Write, +) -> io::Result { + io::copy(&mut cache::RangeReader::new(file, ranges), writer) +} + +#[cfg(unix)] +fn copy_ranges_direct( + buffered: &File, + direct: &R, + ranges: &[(u64, u64)], + writer: &mut impl Write, + chunk_bytes: usize, +) -> io::Result { + debug_assert!(chunk_bytes >= DIRECT_BLOCK && chunk_bytes.is_multiple_of(DIRECT_BLOCK)); + let mut buffer = AlignedBuffer::new(chunk_bytes)?; + let slice = buffer.as_mut_slice(); + let mut total = 0u64; + + for (index, &(offset, size)) in ranges.iter().enumerate() { + let mut position = offset; + let mut remaining = size; + while remaining > 0 { + let skip = (position % DIRECT_BLOCK as u64) as usize; + let aligned_offset = position - skip as u64; + let take = remaining.min((chunk_bytes - skip) as u64) as usize; + let read_len = (skip + take).next_multiple_of(DIRECT_BLOCK); + let read = loop { + match direct.read_at(&mut slice[..read_len], aligned_offset) { + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + result => break result, + } + }; + match read { + Ok(count) => { + if count <= skip { + return Err(io::Error::other("file ended inside a requested range")); + } + let available = (count - skip).min(take); + writer.write_all(&slice[skip..skip + available])?; + position += available as u64; + remaining -= available as u64; + total += available as u64; + } + Err(error) if error.kind() == io::ErrorKind::InvalidInput => { + let mut rest = Vec::with_capacity(ranges.len() - index); + rest.push((position, remaining)); + rest.extend_from_slice(&ranges[index + 1..]); + let copied = copy_ranges_buffered(buffered, &rest, writer)?; + return Ok(total + copied); + } + Err(error) => return Err(error), + } } - copied?; } + Ok(total) +} + +fn copy_source_ranges( + file: &File, + ranges: &[(u64, u64)], + writer: &mut impl Write, +) -> io::Result { + if ranges.is_empty() || ranges.iter().all(|&(_, size)| size == 0) { + return Ok(0); + } + #[cfg(unix)] + let result = match flare_helios::direct_reopen(file) { + Ok(direct) => copy_ranges_direct(file, &direct, ranges, writer, DIRECT_CHUNK), + Err(_) => copy_ranges_buffered(file, ranges, writer), + }; + #[cfg(not(unix))] + let result = copy_ranges_buffered(file, ranges, writer); + for &(offset, size) in ranges { + flare_helios::release_page_cache_range(file, offset, size); + } + result } #[cfg(test)] @@ -1705,6 +1817,134 @@ mod tests { fs::write(root.join("weights/a.safetensors"), b"companion-a-mutated").unwrap(); assert!(!verified_marker_matches(root, &plan, 1)); } + + #[test] + fn copy_source_ranges_matches_range_reader_across_unaligned_and_multi_range_inputs() { + let len: usize = (5 << 20) + 123; + let payload: Vec = (0..len) + .map(|i| ((i.wrapping_mul(31) ^ (i >> 7)) & 0xff) as u8) + .collect(); + let ranges: &[(u64, u64)] = &[ + (0, 1), + (13, 4095), + (4095, 2), + (4096, 8192), + (12_345, (4 << 20) + 777), + (len as u64 - 5000, 5000), + ]; + + // Default tempdir exercises `copy_source_ranges` end-to-end (buffered fallback is covered separately below). + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("payload.bin"); + fs::write(&path, &payload).unwrap(); + let file = File::open(&path).unwrap(); + + let mut expected = Vec::new(); + let expected_len = + io::copy(&mut cache::RangeReader::new(&file, ranges), &mut expected).unwrap(); + + let mut actual = Vec::new(); + let actual_len = copy_source_ranges(&file, ranges, &mut actual).unwrap(); + assert_eq!(actual_len, expected_len); + assert_eq!(actual, expected); + + // Empty and zero-length requests copy zero bytes. + let mut empty = Vec::new(); + assert_eq!(copy_source_ranges(&file, &[], &mut empty).unwrap(), 0); + assert_eq!( + copy_source_ranges(&file, &[(17, 0), (4096, 0)], &mut empty).unwrap(), + 0 + ); + assert!(empty.is_empty()); + + // Real O_DIRECT path when backed by a filesystem that supports O_DIRECT (e.g. /var/tmp). + #[cfg(unix)] + if let Ok(disk_dir) = tempfile::tempdir_in("/var/tmp") { + let disk_path = disk_dir.path().join("direct-payload.bin"); + fs::write(&disk_path, &payload).unwrap(); + let disk_file = File::open(&disk_path).unwrap(); + if let Ok(direct) = flare_helios::direct_reopen(&disk_file) { + let mut direct_out = Vec::new(); + let direct_len = + copy_ranges_direct(&disk_file, &direct, ranges, &mut direct_out, DIRECT_CHUNK) + .unwrap(); + assert_eq!(direct_len, expected_len); + assert_eq!(direct_out, expected); + + // Also test small aligned chunk size (8 KiB) to stress multi-chunk unaligned loops. + let mut small_chunk_out = Vec::new(); + let small_len = + copy_ranges_direct(&disk_file, &direct, ranges, &mut small_chunk_out, 8192) + .unwrap(); + assert_eq!(small_len, expected_len); + assert_eq!(small_chunk_out, expected); + + // Range past EOF fails cleanly just like RangeReader. + let mut err_out = Vec::new(); + let err = copy_ranges_direct( + &disk_file, + &direct, + &[(len as u64 - 16, 32)], + &mut err_out, + 8192, + ) + .unwrap_err(); + assert!( + err.to_string() + .contains("file ended inside a requested range"), + "{err}" + ); + } + } + } + + #[cfg(unix)] + #[test] + fn copy_ranges_direct_falls_back_cleanly_on_invalid_input() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct FailAfter { + file: File, + fail_on_call: usize, + calls: AtomicUsize, + } + + impl flare_helios::FileReadAt for FailAfter { + fn read_at(&self, bytes: &mut [u8], offset: u64) -> io::Result { + if self.calls.fetch_add(1, Ordering::Relaxed) >= self.fail_on_call { + return Err(io::Error::from_raw_os_error(libc::EINVAL)); + } + self.file.read_at(bytes, offset) + } + } + + let payload: Vec = (0..40_000).map(|i| ((i * 19 + 7) & 0xff) as u8).collect(); + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("fallback.bin"); + fs::write(&path, &payload).unwrap(); + let buffered = File::open(&path).unwrap(); + let ranges: &[(u64, u64)] = &[(3, 12_000), (15_001, 17_777), (39_900, 100)]; + + let mut expected = Vec::new(); + let expected_len = io::copy( + &mut cache::RangeReader::new(&buffered, ranges), + &mut expected, + ) + .unwrap(); + + // Fail immediately (call 0) and mid-stream (call 2): both must be byte-exact. + for fail_on_call in [0, 1, 2, 3] { + let reader = FailAfter { + file: File::open(&path).unwrap(), + fail_on_call, + calls: AtomicUsize::new(0), + }; + let mut out = Vec::new(); + let copied = copy_ranges_direct(&buffered, &reader, ranges, &mut out, 8192).unwrap(); + assert_eq!(copied, expected_len, "fail_on_call={fail_on_call}"); + assert_eq!(out, expected, "fail_on_call={fail_on_call}"); + } + } } #[cfg(test)] diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index 19db02a58..a93383743 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -517,35 +517,36 @@ fn orbit_command(args: cli::OrbitArgs, matches: &clap::ArgMatches) -> Result<(), push.transfer_streams, ), cli::OrbitCommand::Cores { cluster } => controller.cores(cluster.as_deref()), - cli::OrbitCommand::Run(run) => controller.run( - run.core.as_deref(), - run.cluster.as_deref(), - orbit::controller::RunOptions { - name: run.name.clone(), - persistent: run.persistent, - nodes: run.nodes.clone(), - dry_run: run.dry_run, - gpus: if matches - .subcommand_matches("run") - .unwrap() - .value_source("gpus") - != Some(clap::parser::ValueSource::CommandLine) - { - Vec::new() - } else { - run.serving.gpus.iter().map(|&g| g as u32).collect() + cli::OrbitCommand::Run(run) => { + let run_matches = matches.subcommand_matches("run").unwrap(); + controller.run( + run.core.as_deref(), + run.cluster.as_deref(), + orbit::controller::RunOptions { + name: run.name.clone(), + persistent: run.persistent, + nodes: run.nodes.clone(), + dry_run: run.dry_run, + gpus: if run_matches.value_source("gpus") + != Some(clap::parser::ValueSource::CommandLine) + { + Vec::new() + } else { + run.serving.gpus.iter().map(|&g| g as u32).collect() + }, + serving: run.rank_options(run_matches), + config_memory_limit: run.config_memory_limit, + rank_zero: run.rank_zero_options(), + roce_ring: run.roce_ring, + transfer_streams: run.transfer_streams, + roce_chain: run.roce_chain, + executable: run.executable.clone(), + detach: run.detach, + verify_weights: run.serving.verify_weights, + run_args: run.run_args(), }, - serving: run.rank_options(matches.subcommand_matches("run").unwrap()), - rank_zero: run.rank_zero_options(), - roce_ring: run.roce_ring, - transfer_streams: run.transfer_streams, - roce_chain: run.roce_chain, - executable: run.executable.clone(), - detach: run.detach, - verify_weights: run.serving.verify_weights, - run_args: run.run_args(), - }, - ), + ) + } } } diff --git a/flare-cli/src/orbit/agent.rs b/flare-cli/src/orbit/agent.rs index f7e85ceca..91d4fde07 100644 --- a/flare-cli/src/orbit/agent.rs +++ b/flare-cli/src/orbit/agent.rs @@ -2064,7 +2064,9 @@ fn get(session: &mut Session, request: &Value) -> Result<(), Failure> { let ranges = [(offset, nbytes)]; cache::validate_ranges(size, &ranges)?; let mut reader = cache::RangeReader::new(&file, &ranges); - session.write_frame_from(frame::OK, nbytes, &mut reader) + let result = session.write_frame_from(frame::OK, nbytes, &mut reader); + flare_helios::release_page_cache_range(&file, offset, nbytes); + result } /// A core's primary file size and its companions with their sizes. diff --git a/flare-cli/src/orbit/controller.rs b/flare-cli/src/orbit/controller.rs index 27dddba3e..99ad8e34f 100644 --- a/flare-cli/src/orbit/controller.rs +++ b/flare-cli/src/orbit/controller.rs @@ -29,7 +29,7 @@ use std::thread; use std::time::{Duration, Instant}; use flare_helios::core::progress::{self, Rate}; -use flare_helios::runtime_core::{self, AuthorizedCore, Publisher}; +use flare_helios::runtime_core::{self, AuthorizedCore, MemoryLimit, Publisher}; use flare_helios::startup::StartupProgress; use serde::Deserialize; use serde_json::{Value, json}; @@ -164,6 +164,10 @@ pub struct RunOptions { pub dry_run: bool, /// Serving options every rank loads with. pub serving: Vec, + /// `[memory] reserve` inherited from host configuration; applied at launch only when + /// neither the saved group nor the command line specifies `--memory-limit`, and never + /// persisted into a group's saved `serving` options. + pub config_memory_limit: Option, /// Options for rank zero alone: the HTTP bind and request handling. pub rank_zero: Vec, pub roce_ring: bool, @@ -906,6 +910,7 @@ impl Controller { ); } let members: Vec = placements.iter().map(|p| nodes[p.node].clone()).collect(); + let launch_serving = apply_config_memory_limit(serving, options.config_memory_limit); let launch = self.launch( &label, &members, @@ -914,7 +919,7 @@ impl Controller { &LaunchOptions { name: name.clone(), placements: placements.iter().map(|p| p.gpus.clone()).collect(), - serving, + serving: launch_serving, rank_zero: rank_zero.clone(), roce_ring, transfer_streams, @@ -1455,7 +1460,9 @@ impl Controller { path.display(), gib(size) ); - put(session, "core", &name, size, &mut source)?; + let result = put(session, "core", &name, size, &mut source); + flare_helios::release_page_cache(&source); + result?; } Ok(()) })() @@ -1956,6 +1963,20 @@ fn have( Ok(reply == [1]) } +fn apply_config_memory_limit( + mut serving: Vec, + config_memory_limit: Option, +) -> Vec { + if let Some(limit) = config_memory_limit + && !serving + .iter() + .any(|arg| arg == "--memory-limit" || arg.starts_with("--memory-limit=")) + { + serving.push(format!("--memory-limit={limit}")); + } + serving +} + /// Retain only the final `--tensor-parallel` occurrence in `args` and return its value. fn deduplicate_tensor_parallel(args: &mut Vec) -> Option { let mut last: Option = None; @@ -3749,4 +3770,179 @@ mod tests { vec!["--max-concurrency", "8", "--tensor-parallel", "4"] ); } + + #[test] + fn persistent_group_tracks_config_reserve_edits_and_preserves_explicit_limit() { + use clap::{CommandFactory, FromArgMatches}; + + let dir = tempfile::tempdir().unwrap(); + let orbit_path = dir.path().join("orbit.toml"); + let home = Path::new("/home/test-user"); + + let parse_run = |args: &[&str], config_toml: &str| -> (Vec, Option) { + let cfg = crate::config::Configuration::parse(config_toml).unwrap(); + let matches = crate::cli::Cli::command() + .try_get_matches_from(args) + .unwrap(); + let mut parsed = crate::cli::Cli::from_arg_matches(&matches).unwrap(); + cfg.apply(&mut parsed, &matches, home).unwrap(); + let crate::cli::Command::Orbit(orbit) = parsed.command else { + panic!("expected orbit command"); + }; + let crate::cli::OrbitCommand::Run(run) = orbit.command else { + panic!("expected orbit run"); + }; + let run_matches = matches + .subcommand_matches("orbit") + .unwrap() + .subcommand_matches("run") + .unwrap(); + (run.rank_options(run_matches), run.config_memory_limit) + }; + + // 1. Persist a group with [memory] reserve = "12 GiB" and no CLI --memory-limit. + let (cli_serving, config_limit) = parse_run( + &[ + "flare", + "orbit", + "run", + "--name", + "g", + "--persistent", + "model.safetensors", + "--verify-weights", + ], + "[memory]\nreserve = '12 GiB'\n", + ); + let mut orbit = Orbit::default(); + orbit.save_group(GroupSpec { + name: "g".into(), + core: "/models/model.safetensors".into(), + serving: cli_serving.clone(), + rank_zero: Vec::new(), + nodes: Vec::new(), + gpus: Vec::new(), + roce_ring: false, + transfer_streams: None, + roce_chain: false, + executable: None, + publisher_keys: Vec::new(), + trust_store: None, + }); + orbit.save(&orbit_path).unwrap(); + let first_launch = apply_config_memory_limit(cli_serving, config_limit); + assert_eq!( + first_launch, + vec![ + "--verify-weights".to_owned(), + format!("--memory-limit={}", MemoryLimit::Reserve(12 << 30)), + ] + ); + + // 2. Reload after changing [memory] reserve to "7 GiB": saved GroupSpec.serving must not + // contain --memory-limit, so the new 7 GiB reserve takes effect on launch. + let reloaded = Orbit::load(&orbit_path).unwrap(); + let saved = reloaded.group("g").expect("saved group g"); + assert!( + !saved + .serving + .iter() + .any(|arg| arg == "--memory-limit" || arg.starts_with("--memory-limit=")), + "config-derived --memory-limit must not be persisted: {:?}", + saved.serving + ); + let (cli_serving, config_limit) = parse_run( + &["flare", "orbit", "run", "--name", "g"], + "[memory]\nreserve = '7 GiB'\n", + ); + let mut merged = saved.serving.clone(); + merged.extend(cli_serving); + let second_launch = apply_config_memory_limit(merged, config_limit); + assert_eq!( + second_launch, + vec![ + "--verify-weights".to_owned(), + format!("--memory-limit={}", MemoryLimit::Reserve(7 << 30)), + ] + ); + + // 3. Persist a group with an explicit CLI --memory-limit: it IS saved and wins over + // subsequent [memory] reserve edits. + let (cli_serving, config_limit) = parse_run( + &[ + "flare", + "orbit", + "run", + "--name", + "explicit", + "--persistent", + "model.safetensors", + "--memory-limit=0.8", + ], + "[memory]\nreserve = '12 GiB'\n", + ); + assert_eq!(config_limit, None); + let mut orbit = Orbit::load(&orbit_path).unwrap(); + orbit.save_group(GroupSpec { + name: "explicit".into(), + core: "/models/model.safetensors".into(), + serving: cli_serving, + rank_zero: Vec::new(), + nodes: Vec::new(), + gpus: Vec::new(), + roce_ring: false, + transfer_streams: None, + roce_chain: false, + executable: None, + publisher_keys: Vec::new(), + trust_store: None, + }); + orbit.save(&orbit_path).unwrap(); + + let reloaded = Orbit::load(&orbit_path).unwrap(); + let saved = reloaded.group("explicit").expect("saved group explicit"); + assert_eq!(saved.serving, vec!["--memory-limit=0.8".to_owned()]); + + let (cli_serving, config_limit) = parse_run( + &["flare", "orbit", "run", "--name", "explicit"], + "[memory]\nreserve = '7 GiB'\n", + ); + let mut merged = saved.serving.clone(); + merged.extend(cli_serving); + assert_eq!( + apply_config_memory_limit(merged, config_limit), + vec!["--memory-limit=0.8".to_owned()] + ); + + // Two-token `--memory-limit ` form saved in orbit.toml is also respected. + assert_eq!( + apply_config_memory_limit( + vec!["--memory-limit".into(), "0.8".into()], + Some(MemoryLimit::Reserve(7 << 30)), + ), + vec!["--memory-limit".to_owned(), "0.8".to_owned()] + ); + + // Explicit CLI --memory-limit still overrides a saved group's stored limit. + let (cli_serving, config_limit) = parse_run( + &[ + "flare", + "orbit", + "run", + "--name", + "explicit", + "--memory-limit=-4G", + ], + "[memory]\nreserve = '7 GiB'\n", + ); + let mut merged = saved.serving.clone(); + merged.extend(cli_serving); + assert_eq!( + apply_config_memory_limit(merged, config_limit), + vec![ + "--memory-limit=0.8".to_owned(), + format!("--memory-limit={}", MemoryLimit::Reserve(4 << 30)), + ] + ); + } } diff --git a/helios/src/core/cache.rs b/helios/src/core/cache.rs index 48a0b9dc9..f6f798a9b 100644 --- a/helios/src/core/cache.rs +++ b/helios/src/core/cache.rs @@ -1899,11 +1899,13 @@ impl Root { files.dedup(); for name in &files { let path = directory.join(name); - // Hash the file by streaming, then store it from a pinned handle so a - // companion far larger than memory is never buffered. - let digest = hash_file(&path)?; + // Hash the file by streaming without evicting the page cache yet so the + // immediate copy reads warm pages, then release the source handle afterward. + let digest = hash_file(&path, false)?; let file = File::open(&path).map_err(failure)?; - let object = self.insert_legacy_container(digest, file)?; + let inserted = self.insert_legacy_container(digest, &file); + crate::os::release_page_cache(&file); + let object = inserted?; // The primary is stored under the canonical name; signed bytes are unchanged and // companions keep their digest basenames. let placed = if name == &primary_name { @@ -4395,6 +4397,7 @@ fn write_stream(path: &Path, mut source: impl Read) -> Result<(PayloadId, u64)> written += count as u64; } file.sync_all().map_err(failure)?; + crate::os::release_page_cache(&file); drop(file); if written == 0 { let _ = fs::remove_file(path); @@ -4425,19 +4428,7 @@ fn validate_hit( /// Hash a complete file and compare it with a declared container identity. fn verify_file(path: &Path, declared: PayloadId) -> Result<()> { - let mut file = File::open(path).map_err(failure)?; - let mut context = DigestContext::new(&SHA256); - let mut buffer = vec![0; 1 << 20]; - loop { - let count = match file.read(&mut buffer) { - Ok(0) => break, - Ok(count) => count, - Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, - Err(error) => return Err(failure(error)), - }; - context.update(&buffer[..count]); - } - if PayloadId::from_digest(context.finish()) != declared { + if hash_file(path, true)? != declared { return Err(format!("container {declared} does not match its stored bytes").into()); } Ok(()) @@ -4491,20 +4482,24 @@ fn verify_stream(declared: PayloadId, length: u64, mut source: impl Read) -> Res Ok(()) } -/// Hash one file by streaming it. -fn hash_file(path: &Path) -> Result { +/// Hash one file by streaming it, optionally releasing its page cache afterward. +fn hash_file(path: &Path, release: bool) -> Result { let mut file = File::open(path).map_err(failure)?; let mut context = DigestContext::new(&SHA256); let mut buffer = vec![0; 1 << 20]; - loop { + let read = loop { let count = match file.read(&mut buffer) { - Ok(0) => break, + Ok(0) => break Ok(()), Ok(count) => count, Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, - Err(error) => return Err(failure(error)), + Err(error) => break Err(failure(error)), }; context.update(&buffer[..count]); + }; + if release || read.is_err() { + crate::os::release_page_cache(&file); } + read?; Ok(PayloadId::from_digest(context.finish())) } @@ -4762,7 +4757,13 @@ fn make_immutable(path: &Path) -> Result<()> { #[cfg(not(windows))] pub(crate) fn copy_file(source: &Path, destination: &Path) -> io::Result<()> { fs::copy(source, destination)?; - super::container::sync_file(destination) + let output = File::open(destination)?; + output.sync_all()?; + crate::os::release_page_cache(&output); + if let Ok(input) = File::open(source) { + crate::os::release_page_cache(&input); + } + Ok(()) } /// Copy one file to a new destination with the source's permissions, and flush the copy. diff --git a/helios/src/lib.rs b/helios/src/lib.rs index a023e4b58..412dc006d 100644 --- a/helios/src/lib.rs +++ b/helios/src/lib.rs @@ -36,7 +36,10 @@ pub mod startup; pub mod frontend; pub use cuda::current_context; -pub use flare_eos::{raise_open_file_limit, release_page_cache, release_page_cache_range}; +pub use flare_eos::{ + FileReadAt, allocate_aligned, direct_reopen, free_aligned, raise_open_file_limit, + release_page_cache, release_page_cache_range, +}; pub use replay::{BufferSpan, Completion, GraphBundle, ReplayWorker, Shutdown}; pub use error::{AdmissionError, CudaError, Error, ExecutionError, Failure, FrontendError}; diff --git a/helios/src/runtime_core/driver.rs b/helios/src/runtime_core/driver.rs index 2ad55f5ca..23fcf3b9c 100644 --- a/helios/src/runtime_core/driver.rs +++ b/helios/src/runtime_core/driver.rs @@ -106,6 +106,8 @@ pub const CU_STREAM_WRITE_VALUE_DEFAULT: c_uint = 0x0; pub const CU_MEMHOSTREGISTER_PORTABLE: c_uint = 0x1; /// `CU_MEMHOSTREGISTER_DEVICEMAP`: map registered host memory into the device address space. pub const CU_MEMHOSTREGISTER_DEVICEMAP: c_uint = 0x2; +/// `CUDA_ERROR_OUT_OF_MEMORY`: device or unified-memory allocation failed. +pub const CUDA_ERROR_OUT_OF_MEMORY: c_int = 2; /// `CUDA_ERROR_NOT_READY`: asynchronous stream or event operation has not completed. pub const CUDA_ERROR_NOT_READY: c_int = 600; /// `CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE`: primary context flags were already fixed by an active user. diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index c1a46ae0e..c629f4b29 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -177,6 +177,114 @@ pub(super) fn shared_available(meminfo: &str, total: usize) -> Result { Ok(flare_selene::offload::available_memory(meminfo, total)?) } +/// Reclaimable page-cache gap (`MemAvailable - MemFree`) above which a memory-limited +/// integrated-GPU `Plan cache` emits a stderr warning. Kept high (10 GiB) to avoid noisy +/// startup warnings when ordinary OS caching is present. +#[cfg(any(target_os = "linux", test))] +pub(super) const PAGE_CACHE_WARN_THRESHOLD: u64 = 10 << 30; +/// Reclaimable page-cache gap above which a failed integrated-GPU context-creation OOM +/// attaches a `drop_caches` hint. Lower than [`PAGE_CACHE_WARN_THRESHOLD`] (4 GiB) because +/// context creation has already failed and even a few GiB of cached pages can block it. +#[cfg(any(target_os = "linux", test))] +pub(super) const CTX_OOM_DROP_CACHES_THRESHOLD: u64 = 4 << 30; + +#[cfg(any(target_os = "linux", test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct LinuxMemInfo { + pub(super) free: u64, + pub(super) available: u64, + pub(super) cached: u64, +} + +#[cfg(any(target_os = "linux", test))] +impl LinuxMemInfo { + pub(super) fn parse(meminfo: &str) -> Option { + let mut free = None; + let mut available = None; + let mut cached = None; + for line in meminfo.lines() { + let mut fields = line.split_whitespace(); + let Some(key) = fields.next() else { + continue; + }; + let target = match key { + "MemFree:" => &mut free, + "MemAvailable:" => &mut available, + "Cached:" => &mut cached, + _ => continue, + }; + let kib = fields.next()?.parse::().ok()?; + if fields.next()? != "kB" || fields.next().is_some() { + return None; + } + *target = Some(kib.checked_mul(1024)?); + } + Some(Self { + free: free?, + available: available?, + cached: cached?, + }) + } + + #[cfg(target_os = "linux")] + pub(super) fn read() -> Option { + let text = std::fs::read_to_string("/proc/meminfo").ok()?; + Self::parse(&text) + } + + pub(super) fn reclaimable_gap(&self) -> u64 { + self.available.saturating_sub(self.free) + } + + pub(super) fn summary(&self) -> String { + let gib = |bytes: u64| bytes as f64 / (1u64 << 30) as f64; + format!( + "MemFree {:.2} GiB / MemAvailable {:.2} GiB / Cached {:.2} GiB", + gib(self.free), + gib(self.available), + gib(self.cached), + ) + } +} + +#[cfg(any(target_os = "linux", test))] +pub(super) fn append_integrated_meminfo( + summary: &mut String, + meminfo: LinuxMemInfo, + limited_by_memory: bool, +) -> Option { + summary.push_str(&format!(" · {}", meminfo.summary())); + if limited_by_memory && meminfo.reclaimable_gap() > PAGE_CACHE_WARN_THRESHOLD { + let gap_gib = meminfo.reclaimable_gap() as f64 / (1u64 << 30) as f64; + Some(format!( + "warning: integrated GPU KV cache is limited by memory while {gap_gib:.2} GiB is held in reclaimable Linux page cache; CUDA allocations may observe MemFree rather than MemAvailable", + )) + } else { + None + } +} + +/// Enrich a CUDA context-creation OOM error on a Linux integrated GPU with `/proc/meminfo` +/// details when the caller supplies `Some(meminfo)`. +#[cfg(any(target_os = "linux", test))] +pub(super) fn enrich_integrated_ctx_oom( + mut error: crate::Error, + meminfo: Option, +) -> crate::Error { + let Some(info) = meminfo else { + return error; + }; + if let crate::Error::Execution(crate::ExecutionError::Driver(ref mut cuda)) = error { + cuda.description.push_str(&format!(" ({})", info.summary())); + if info.reclaimable_gap() > CTX_OOM_DROP_CACHES_THRESHOLD { + cuda.description.push_str( + "; reclaimable Linux page cache may be blocking unified-memory context creation (try `sync && echo 3 | sudo tee /proc/sys/vm/drop_caches`)", + ); + } + } + error +} + /// Memory this process can commit once every page file reaches its maximum size. /// /// WDDM charges CUDA allocations on an integrated GPU, including the dedicated carveout, @@ -1449,7 +1557,19 @@ impl NativeModel { None }; summary.push_str(&format!(" · {pages} KV pages · {} shared snapshot slots", rows - execution)); + #[cfg(target_os = "linux")] + let meminfo_warning = if self.ranks.iter().any(|rank| rank.integrated) { + LinuxMemInfo::read().and_then(|info| { + append_integrated_meminfo(&mut summary, info, limiting == "memory") + }) + } else { + None + }; progress.phase("Plan cache", None).finish(summary); + #[cfg(target_os = "linux")] + if let Some(warning) = meminfo_warning { + eprintln!("{warning}"); + } unsafe { self.allocate_cache_capacity( cores, @@ -2737,4 +2857,147 @@ mod tests { .contains("different number") ); } + + #[test] + fn linux_meminfo_parses_valid_and_rejects_missing_or_malformed() { + let valid = "MemTotal: 131072000 kB +MemFree: 2097152 kB +MemAvailable: 98566144 kB +Buffers: 524288 kB +Cached: 94371840 kB +SwapTotal: 0 kB +"; + assert_eq!( + LinuxMemInfo::parse(valid), + Some(LinuxMemInfo { + free: 2 << 30, + available: 94 << 30, + cached: 90 << 30, + }) + ); + + let zeros = "MemFree: 0 kB\nMemAvailable: 0 kB\nCached: 0 kB\n"; + assert_eq!( + LinuxMemInfo::parse(zeros), + Some(LinuxMemInfo { + free: 0, + available: 0, + cached: 0, + }) + ); + + for invalid in [ + "", + "MemFree: 1024 kB\nMemAvailable: 2048 kB\n", + "MemFree: 1024 kB\nCached: 2048 kB\n", + "MemAvailable: 1024 kB\nCached: 2048 kB\n", + "MemFree: -1 kB\nMemAvailable: 2048 kB\nCached: 1024 kB\n", + "MemFree: 1024 MB\nMemAvailable: 2048 kB\nCached: 1024 kB\n", + "MemFree: 1024 kB extra\nMemAvailable: 2048 kB\nCached: 1024 kB\n", + "MemFree: 18446744073709551615 kB\nMemAvailable: 2048 kB\nCached: 1024 kB\n", + "MemFree: abc kB\nMemAvailable: 2048 kB\nCached: 1024 kB\n", + ] { + assert_eq!(LinuxMemInfo::parse(invalid), None, "input={invalid:?}"); + } + } + + #[test] + fn integrated_plan_cache_summary_and_page_cache_warning() { + let polluted = LinuxMemInfo { + free: 2 << 30, + available: (12 << 30) + (1 << 20), + cached: 11 << 30, + }; + let mut summary = "per GPU: 50.00 GiB loaded · 40.00 GiB cache budget".to_owned(); + let warning = append_integrated_meminfo(&mut summary, polluted, true) + .expect("expected warning when reclaimable gap exceeds 10 GiB and memory-limited"); + assert!( + summary.contains("MemFree 2.00 GiB / MemAvailable 12.00 GiB / Cached 11.00 GiB"), + "{summary}" + ); + assert!( + warning.contains("reclaimable Linux page cache"), + "{warning}" + ); + assert!(warning.contains("10.00 GiB"), "{warning}"); + assert!( + !warning.contains("MemFree 2.00 GiB"), + "warning should not duplicate the MemInfo triple already printed in Plan cache: {warning}" + ); + + // Not memory-limited -> still appends summary, no warning. + let mut uncapped_summary = "per GPU: 50.00 GiB loaded".to_owned(); + assert_eq!( + append_integrated_meminfo(&mut uncapped_summary, polluted, false), + None + ); + assert!( + uncapped_summary + .contains("MemFree 2.00 GiB / MemAvailable 12.00 GiB / Cached 11.00 GiB"), + "{uncapped_summary}" + ); + + // Exactly 10 GiB reclaimable gap does not cross the >10 GiB threshold. + let at_threshold = LinuxMemInfo { + free: 2 << 30, + available: 12 << 30, + cached: 10 << 30, + }; + let mut threshold_summary = "per GPU: 50.00 GiB loaded".to_owned(); + assert_eq!( + append_integrated_meminfo(&mut threshold_summary, at_threshold, true), + None + ); + } + + #[test] + fn integrated_ctx_oom_enrichment_and_drop_caches_hint() { + let oom = |op: &str| { + crate::Error::Execution(crate::ExecutionError::Driver(crate::CudaError { + operation: op.into(), + code: super::super::driver::CUDA_ERROR_OUT_OF_MEMORY, + name: "CUDA_ERROR_OUT_OF_MEMORY".into(), + description: "out of memory".into(), + })) + }; + let polluted = LinuxMemInfo { + free: 1 << 30, + available: 16 << 30, + cached: 14 << 30, + }; + + for op in ["cuCtxCreate_v2", "cuDevicePrimaryCtxRetain"] { + let enriched = enrich_integrated_ctx_oom(oom(op), Some(polluted)); + assert!(matches!( + &enriched, + crate::Error::Execution(crate::ExecutionError::Driver(cuda)) + if cuda.code == super::super::driver::CUDA_ERROR_OUT_OF_MEMORY + )); + let text = enriched.to_string(); + assert!(text.contains(op), "{text}"); + assert!( + text.contains("MemFree 1.00 GiB / MemAvailable 16.00 GiB / Cached 14.00 GiB"), + "{text}" + ); + assert!(text.contains("drop_caches"), "{text}"); + } + + // Gap <= 4 GiB attaches meminfo without the drop_caches hint. + let clean = LinuxMemInfo { + free: 4 << 30, + available: 8 << 30, + cached: 3 << 30, + }; + let enriched_clean = enrich_integrated_ctx_oom(oom("cuCtxCreate_v2"), Some(clean)); + let clean_text = enriched_clean.to_string(); + assert!( + clean_text.contains("MemFree 4.00 GiB / MemAvailable 8.00 GiB / Cached 3.00 GiB"), + "{clean_text}" + ); + assert!(!clean_text.contains("drop_caches"), "{clean_text}"); + + // Missing meminfo (including discrete GPU / non-OOM caller paths) leaves the error unchanged. + let no_info = enrich_integrated_ctx_oom(oom("cuCtxCreate_v2"), None); + assert!(!no_info.to_string().contains("MemFree"), "{no_info}"); + } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index e794e3732..56b1d9f2f 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -374,6 +374,17 @@ impl NativeResources { .execution .as_ref() .and_then(|execution| execution.persistent_workers.first()); + let check_ctx = |operation: &str, status| -> Result<()> { + let result = driver.check(operation, status); + #[cfg(target_os = "linux")] + let result = result.map_err(|error| { + let meminfo = (integrated != 0 && status == driver::CUDA_ERROR_OUT_OF_MEMORY) + .then(memory::LinuxMemInfo::read) + .flatten(); + memory::enrich_integrated_ctx_oom(error, meminfo) + }); + result + }; let mut context = null_mut(); let primary_context = if wants_worker.is_some() { if driver.green_ctx.is_none() { @@ -392,13 +403,13 @@ impl NativeResources { driver.check("cuDevicePrimaryCtxSetFlags_v2", status)?; } } - driver.check( + check_ctx( "cuDevicePrimaryCtxRetain", (driver.primary_ctx_retain)(&mut context, device), )?; true } else { - driver.check( + check_ctx( "cuCtxCreate_v2", (driver.context_create)(&mut context, core.context.flags, device), )?;