From 135633fea62b0f1401b6cdf69928fbce2d35c193 Mon Sep 17 00:00:00 2001 From: Eduardo Fonseca Date: Wed, 2 Dec 2026 17:57:50 -0500 Subject: [PATCH 1/2] fix(selene): avoid double-counting preallocated shm Linux MemAvailable already excludes fallocated tmpfs arena and staging bytes, but pool approval subtracted the same bytes again. Track physically backed bytes on planned regions and charge the host only the unbacked remainder while preserving full per-GPU registration metadata cost. This prevents valid shared-pool attachments from being rejected without weakening GPU budget accounting or host observation failures. Validation: cargo test -p flare-selene pool::budget on Hades Linux aarch64: 4 passed, 0 failed, 551 filtered out. The Linux backed_shm_bytes branch compiled but its statfs helper was not directly executed by these tests; no fresh manager attachment reproduction was run for this submission. Signed-off-by: Eduardo Fonseca Design-Signed-Off-By: Iris; design-review=2e5b Signed-off-by: Iris (Eduardo's coding agent) --- selene/src/pool/budget.rs | 13 ++-- selene/src/pool/budget/tests.rs | 112 +++++++++++++++++++++++++++++++- selene/src/pool/builder.rs | 2 +- selene/src/pool/conn.rs | 52 +++++++++++++-- selene/src/pool/startup.rs | 8 +++ 5 files changed, 175 insertions(+), 12 deletions(-) diff --git a/selene/src/pool/budget.rs b/selene/src/pool/budget.rs index 6d55425f8..6dff52ac3 100644 --- a/selene/src/pool/budget.rs +++ b/selene/src/pool/budget.rs @@ -13,11 +13,13 @@ pub struct Budget { impl Budget { pub(super) fn costs( - mut bytes: impl Iterator, + mut regions: impl Iterator, ) -> std::result::Result<(u64, u64), String> { - bytes.try_fold((0u64, 0u64), |(host, device), bytes| { + regions.try_fold((0u64, 0u64), |(host, device), (bytes, backed_bytes)| { + let additional_host = bytes.saturating_sub(backed_bytes.min(bytes)); Ok(( - host.checked_add(bytes).ok_or("pool host bytes overflow")?, + host.checked_add(additional_host) + .ok_or("pool host bytes overflow")?, device .checked_add(bytes.div_ceil(512)) .ok_or("pool device bytes overflow")?, @@ -40,7 +42,10 @@ impl Budget { } pub(super) fn approve(&self, plan: &[PlannedRegion]) -> std::result::Result<(), String> { - let (host, device) = Self::costs(plan.iter().map(|region| region.bytes))?; + let (host, device) = Self::costs( + plan.iter() + .map(|region| (region.bytes, region.backed_bytes)), + )?; let available_host = self .host .as_ref() diff --git a/selene/src/pool/budget/tests.rs b/selene/src/pool/budget/tests.rs index 1234dcc9c..d80c61d66 100644 --- a/selene/src/pool/budget/tests.rs +++ b/selene/src/pool/budget/tests.rs @@ -9,10 +9,12 @@ fn plan(arena: u64, staging: u64) -> Vec { PlannedRegion { name: "arena", bytes: arena, + backed_bytes: 0, }, PlannedRegion { name: "staging", bytes: staging, + backed_bytes: 0, }, ] } @@ -20,7 +22,7 @@ fn plan(arena: u64, staging: u64) -> Vec { #[test] fn approval_charges_whole_regions_and_each_gpu_before_registration() { let plan = plan(1 << 30, 1 << 29); - let (host, device) = Budget::costs(plan.iter().map(|region| region.bytes)).unwrap(); + let (host, device) = Budget::costs(plan.iter().map(|region| (region.bytes, region.backed_bytes))).unwrap(); assert_eq!((host, device), (3 << 29, 3 << 20)); let budget = Budget { host: Ok(host), @@ -42,7 +44,14 @@ fn approval_charges_whole_regions_and_each_gpu_before_registration() { devices: vec![(device, false), (device - 1, false)], }; assert!(budget.approve(&plan).unwrap_err().contains("GPU 1")); - assert!(Budget::costs(self::plan(u64::MAX, 1).iter().map(|region| region.bytes)).is_err()); + assert!( + Budget::costs( + self::plan(u64::MAX, 1) + .iter() + .map(|region| (region.bytes, region.backed_bytes)) + ) + .is_err() + ); } #[test] @@ -50,9 +59,10 @@ fn remote_staging_and_shared_memory_use_the_same_budget() { let plan = vec![PlannedRegion { name: "data-staging", bytes: 4097, + backed_bytes: 0, }]; assert_eq!( - Budget::costs(plan.iter().map(|region| region.bytes)).unwrap(), + Budget::costs(plan.iter().map(|region| (region.bytes, region.backed_bytes))).unwrap(), (4097, 9) ); let budget = Budget { @@ -79,3 +89,99 @@ fn remote_staging_and_shared_memory_use_the_same_budget() { .contains("no memory observation") ); } + +#[test] +fn preallocated_shm_skips_host_double_count_but_keeps_device_charge() { + let arena = 32u64 << 30; + let staging = 8u64 << 30; + let plan = vec![ + PlannedRegion { + name: "arena", + bytes: arena, + backed_bytes: arena, + }, + PlannedRegion { + name: "staging", + bytes: staging, + backed_bytes: staging, + }, + ]; + let (host, device) = Budget::costs( + plan.iter() + .map(|region| (region.bytes, region.backed_bytes)), + ) + .unwrap(); + assert_eq!(host, 0); + assert_eq!(device, (arena + staging) / 512); + // Remaining host budget below 40 GiB approves because tmpfs blocks are already + // deducted from MemAvailable, while GPU registration metadata is still charged. + let budget = Budget { + host: Ok(25u64 << 30), + devices: vec![(device, false), (device, true)], + }; + assert!(budget.approve(&plan).is_ok()); + assert_eq!(budget.charges(host, device), vec![device, device]); + assert!( + Budget { + host: Ok(25u64 << 30), + devices: vec![(device - 1, false)], + } + .approve(&plan) + .unwrap_err() + .contains("GPU 0") + ); + assert!( + Budget { + host: Err("no memory observation".into()), + devices: vec![(device, false)], + } + .approve(&plan) + .unwrap_err() + .contains("no memory observation") + ); +} + +#[test] +fn partially_backed_shm_charges_only_unbacked_remainder() { + let plan = vec![ + PlannedRegion { + name: "arena", + bytes: 16 << 20, + backed_bytes: 12 << 20, + }, + PlannedRegion { + name: "staging", + bytes: 4 << 20, + backed_bytes: 8 << 20, // clamped to region.bytes + }, + PlannedRegion { + name: "data-staging", + bytes: 2 << 20, + backed_bytes: 0, + }, + ]; + let (host, device) = Budget::costs( + plan.iter() + .map(|region| (region.bytes, region.backed_bytes)), + ) + .unwrap(); + assert_eq!(host, 6 << 20); + assert_eq!(device, (22 << 20) / 512); + assert!( + Budget { + host: Ok(6 << 20), + devices: vec![(device, false)], + } + .approve(&plan) + .is_ok() + ); + assert!( + Budget { + host: Ok((6 << 20) - 1), + devices: vec![(device, false)], + } + .approve(&plan) + .unwrap_err() + .contains("host budget") + ); +} diff --git a/selene/src/pool/builder.rs b/selene/src/pool/builder.rs index 974190e74..4c61d1ce7 100644 --- a/selene/src/pool/builder.rs +++ b/selene/src/pool/builder.rs @@ -240,7 +240,7 @@ impl PreparedPool { Ok(Budget::costs( self.registered_regions() .iter() - .map(|region| region.bytes as u64), + .map(|region| (region.bytes as u64, region.backed_bytes)), )?) } pub fn summary(&self) -> Result { diff --git a/selene/src/pool/conn.rs b/selene/src/pool/conn.rs index f874ba8a0..d0bf6eb5d 100644 --- a/selene/src/pool/conn.rs +++ b/selene/src/pool/conn.rs @@ -675,14 +675,44 @@ async fn attach( } } +/// Bytes of `path` already physically backed in memory-resident tmpfs +/// blocks (and therefore already deducted from Linux `MemAvailable`). +/// Returns 0 on error, on non-Linux hosts, or for non-tmpfs filesystems so +/// budget admission fails conservatively. +#[cfg(target_os = "linux")] +fn backed_shm_bytes(path: &str, declared_bytes: u64) -> u64 { + use std::ffi::CString; + use std::os::unix::fs::MetadataExt; + let Ok(cpath) = CString::new(path) else { + return 0; + }; + let mut statfs: libc::statfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statfs(cpath.as_ptr(), &mut statfs) } != 0 { + return 0; + } + if statfs.f_type as u64 != libc::TMPFS_MAGIC as u64 { + return 0; + } + std::fs::metadata(path) + .map(|meta| meta.blocks().saturating_mul(512).min(declared_bytes)) + .unwrap_or(0) +} + +#[cfg(not(target_os = "linux"))] +fn backed_shm_bytes(_path: &str, _declared_bytes: u64) -> u64 { + 0 +} + pub(crate) fn registered_region( name: &'static str, region: &super::shm::Region, + backed_bytes: u64, ) -> RegisteredRegion { RegisteredRegion { name, address: region.base(), bytes: region.len(), + backed_bytes, } } @@ -741,15 +771,23 @@ pub(crate) fn register_memory( )> { let started = Instant::now(); let mut plan = Vec::new(); - if let Some(shared) = shared { + let shared_backed = shared.map(|shared| { + ( + backed_shm_bytes(&shared.arena_path, shared.arena_bytes), + backed_shm_bytes(&shared.staging_path, shared.staging_bytes), + ) + }); + if let (Some(shared), Some((arena_backed, staging_backed))) = (shared, shared_backed) { plan.extend([ PlannedRegion { name: ARENA_FILE, bytes: shared.arena_bytes, + backed_bytes: arena_backed, }, PlannedRegion { name: STAGING_FILE, bytes: shared.staging_bytes, + backed_bytes: staging_backed, }, ]); } @@ -757,6 +795,7 @@ pub(crate) fn register_memory( plan.push(PlannedRegion { name: "data-staging", bytes: net::Staging::planned_bytes(slots, bytes), + backed_bytes: 0, }); } if let Some(approve) = approve @@ -812,11 +851,16 @@ pub(crate) fn register_memory( } let mut registered = Vec::new(); if let Some(regions) = ®ions { - registered.push(registered_region(ARENA_FILE, ®ions.arena)); - registered.push(registered_region(STAGING_FILE, ®ions.staging)); + let (arena_backed, staging_backed) = shared_backed.unwrap_or((0, 0)); + registered.push(registered_region(ARENA_FILE, ®ions.arena, arena_backed)); + registered.push(registered_region( + STAGING_FILE, + ®ions.staging, + staging_backed, + )); } if let Some(staging) = &staging { - registered.push(registered_region("data-staging", staging.region())); + registered.push(registered_region("data-staging", staging.region(), 0)); } let bytes: usize = registered.iter().map(|region| region.bytes).sum(); eprintln!( diff --git a/selene/src/pool/startup.rs b/selene/src/pool/startup.rs index 4f16f4e20..0728dcfb9 100644 --- a/selene/src/pool/startup.rs +++ b/selene/src/pool/startup.rs @@ -26,6 +26,10 @@ pub struct RegisteredRegion { pub address: usize, /// Its length in bytes. pub bytes: usize, + /// Bytes of this region already backed in memory-resident shared storage + /// (for example, pre-`fallocate`d tmpfs blocks in `/dev/shm` already deducted + /// from Linux `MemAvailable`). + pub backed_bytes: u64, } /// A range the client is about to register, offered to the approval callback before any is. @@ -35,6 +39,10 @@ pub struct PlannedRegion { pub name: &'static str, /// Its length in bytes. pub bytes: u64, + /// As [`RegisteredRegion::backed_bytes`]. Only `bytes - backed_bytes` draws + /// additional host RAM when registered; GPU registration metadata still scales + /// with the full `bytes`. + pub backed_bytes: u64, } /// Judges the complete registration plan. `Err(reason)` registers nothing. From 1e785d70311ebca679b919a377dd1b3f39a3f23e Mon Sep 17 00:00:00 2001 From: Eduardo Fonseca Date: Thu, 3 Dec 2026 10:18:32 -0500 Subject: [PATCH 2/2] test(selene): cover real tmpfs-backed pool accounting Derive manager integration expectations from actual arena and staging backing, approve zero-host-budget pools when fully backed, and preserve device-budget rejection coverage. Add a direct tmpfs test using the host page size so partial backing and declared-size clamping are measured on 4 KiB and 64 KiB systems. Validation on Hades Linux aarch64 with 64 KiB pages: - full selene suite: 556 passed, 0 failed - manager builder: 3 passed; manager offload: 2 passed - Helios peer registration budget: 1 passed - selene pool::budget: 4 passed The manager host-rejection branch is unexercised on Hades because fallocate fully backs both regions. No GPU admission or RDMA test was run. Signed-off-by: Eduardo Fonseca Design-Signed-Off-By: Iris; design-review=2e5b Signed-off-by: Iris (Eduardo's coding agent) --- helios/src/offload/pool/tests.rs | 18 ++++++++++- selene-manager/tests/builder.rs | 53 ++++++++++++++++++++++---------- selene-manager/tests/offload.rs | 17 ++++++++-- selene/src/pool/conn.rs | 40 ++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 20 deletions(-) diff --git a/helios/src/offload/pool/tests.rs b/helios/src/offload/pool/tests.rs index b79dbdc5d..42e0e177f 100644 --- a/helios/src/offload/pool/tests.rs +++ b/helios/src/offload/pool/tests.rs @@ -24,8 +24,24 @@ fn peer_registration_budget_fails_startup() { let mut manager = Manager::new(); manager.run(); + #[cfg(target_os = "linux")] + let host_bytes = ["arena", "staging"] + .into_iter() + .map(|name| { + use std::os::unix::fs::MetadataExt; + let metadata = std::fs::metadata(manager.shm_directory().join(name)).unwrap(); + let bytes = metadata.len(); + bytes.saturating_sub(metadata.blocks().saturating_mul(512).min(bytes)) + }) + .sum::(); + #[cfg(not(target_os = "linux"))] + let host_bytes = 16 << 20; for rejection in 0..3 { - let reject = rejection != 2; + let reject = match rejection { + 0 => host_bytes > 1, + 1 => true, + _ => false, + }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let peer_stream = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); let zero_stream = listener.accept().unwrap().0; diff --git a/selene-manager/tests/builder.rs b/selene-manager/tests/builder.rs index 6340baa4c..935b6c6fd 100644 --- a/selene-manager/tests/builder.rs +++ b/selene-manager/tests/builder.rs @@ -79,31 +79,50 @@ fn start( fn over_budget_startup_fails_before_registering_memory() { let mut manager = Manager::new(); manager.run(); - for (budget, expected) in [ - ( - Budget { - host: Ok(0), - ..unlimited() - }, - "host budget has 0 bytes left", - ), - ( - Budget { - devices: vec![(1, false)], - ..unlimited() - }, - "budget has 1 bytes left", - ), - ] { + #[cfg(target_os = "linux")] + let host_bytes = ["arena", "staging"] + .into_iter() + .map(|name| { + use std::os::unix::fs::MetadataExt; + let metadata = std::fs::metadata(manager.shm_directory().join(name)).unwrap(); + let bytes = metadata.len(); + bytes.saturating_sub(metadata.blocks().saturating_mul(512).min(bytes)) + }) + .sum::(); + #[cfg(not(target_os = "linux"))] + let host_bytes = 16 << 20; + let device_case = ( + Budget { + devices: vec![(1, false)], + ..unlimited() + }, + "budget has 1 bytes left", + ); + let cases = if host_bytes > 0 { + vec![ + ( + Budget { + host: Ok(0), + ..unlimited() + }, + "host budget has 0 bytes left", + ), + device_case, + ] + } else { + vec![device_case] + }; + for (budget, expected) in cases { let registrar = Arc::new(Registrar::default()); let reason = start(&manager, registrar.clone(), budget) .err() .expect("an unapproved pool must fail startup") .to_string(); + let needs = format!("needs {host_bytes} host bytes"); for text in [ "arena 8388608 bytes", "staging 8388608 bytes", - "needs 16777216 host bytes", + needs.as_str(), expected, "free host/device memory", "remove --prefix-cache-pool", diff --git a/selene-manager/tests/offload.rs b/selene-manager/tests/offload.rs index 92680554f..8f7183df1 100644 --- a/selene-manager/tests/offload.rs +++ b/selene-manager/tests/offload.rs @@ -17,7 +17,20 @@ fn startup_fails_and_releases_registration_when_a_rank_rejects_the_pool() { let mut manager = selene_manager::testing::Manager::new(); manager.run(); - for local_approved in [true, false] { + #[cfg(target_os = "linux")] + let host_bytes = ["arena", "staging"] + .into_iter() + .map(|name| { + use std::os::unix::fs::MetadataExt; + let metadata = std::fs::metadata(manager.shm_directory().join(name)).unwrap(); + let bytes = metadata.len(); + bytes.saturating_sub(metadata.blocks().saturating_mul(512).min(bytes)) + }) + .sum::(); + #[cfg(not(target_os = "linux"))] + let host_bytes = 16 << 20; + for zero_host in [false, true] { + let local_approved = !zero_host || host_bytes == 0; let options = pool(&manager.address()); let geometry = vec![geometry(64, &[("kv", 4096)], 4096)]; let registrar = Arc::new(TrackingRegistrar::default()); @@ -32,7 +45,7 @@ fn startup_fails_and_releases_registration_when_a_rank_rejects_the_pool() { gpu_uuids: vec![[1; 16]], registration_context: 0, budget: Budget { - host: Ok(if local_approved { u64::MAX } else { 0 }), + host: Ok(if zero_host { 0 } else { u64::MAX }), devices: vec![(u64::MAX, false), (u64::MAX, true)], }, peers: None, diff --git a/selene/src/pool/conn.rs b/selene/src/pool/conn.rs index d0bf6eb5d..7b20c2180 100644 --- a/selene/src/pool/conn.rs +++ b/selene/src/pool/conn.rs @@ -1010,6 +1010,46 @@ fn drain_out( mod tests { use super::*; + #[cfg(target_os = "linux")] + #[test] + fn backed_shm_bytes_measures_real_tmpfs_pages() { + use std::io::{Seek, SeekFrom, Write}; + + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + // SAFETY: sysconf only queries the process-independent page size. + let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + assert!(page_size > 0); + let page_size = page_size as usize; + let page = vec![0x5a; page_size]; + let path = std::path::PathBuf::from(format!( + "/dev/shm/flare-backed-shm-test-{}", + std::process::id() + )); + let _cleanup = Cleanup(path.clone()); + let mut file = std::fs::File::create(&path).unwrap(); + file.write_all(&page).unwrap(); + file.set_len((2 * page_size) as u64).unwrap(); + file.seek(SeekFrom::Start((2 * page_size) as u64)) + .unwrap(); + file.write_all(&page).unwrap(); + let path = path.to_str().unwrap(); + assert_eq!( + backed_shm_bytes(path, (3 * page_size) as u64), + (2 * page_size) as u64 + ); + assert_eq!(backed_shm_bytes(path, page_size as u64), page_size as u64); + assert_eq!(backed_shm_bytes(path, 0), 0); + drop(file); + assert_eq!(backed_shm_bytes("/dev/shm/not-present", 4096), 0); + assert_eq!(backed_shm_bytes("/proc/version", 4096), 0); + } + #[test] fn missing_shared_memory_names_container_access_causes() { let reason = register_memory(None, None, &super::super::startup::ClosedRegistrar, 0, None)