Review: PR #699 — Avoid double-counting preallocated /dev/shm selene-manager regions against Linux MemAvailable
Head 135633f, base main, 5 files, +175/−12, no CI checks on the head commit, no reviews. Charter placement is right (goal: share prefix-cache checkpoints across Flare instances via Selene) and the mechanism diagnosis is real: selene-manager does preallocate with libc::fallocate at selene-manager/src/local.rs:583-602.
Key findings
| # | Severity | Finding | Where |
|---|---|---|---|
| 1 | Major | Backed bytes are measured from the paths before the map that actually validates the files, so a stale/larger preallocated file can pass approval and then fail at map with a byte-mismatch instead of a budget message | selene/src/pool/conn.rs:774-779, conn.rs:813-829, selene/src/pool/shm.rs:49-57 |
| 2 | Major | A reclaimable kernel estimate (st_blocks) is converted into a hard admission fact, with zero margin for the approve→first-touch window, on a region shared by every attaching instance |
conn.rs:696-698, selene/src/pool/budget.rs:19 |
| 3 | Major | Undeclared public source break (PlannedRegion/RegisteredRegion gain a required backed_bytes) and a behaviour change on integrated GPUs that contradicts two design docs, with no owner sign-off |
selene/src/pool/startup.rs:19-46, selene/src/pool/mod.rs:60 (not opened), budget.rs:30-42, docs/runtime-core-design.md:768-771, docs/cli-design.md:884-891 |
| 4 | Major | The only new syscall path and the whole attachment path are never executed by any test; the new tests restate the arithmetic | conn.rs:682-704, selene/src/pool/budget/tests.rs:92-186 |
| 5 | Minor | Two operator-visible numbers now disagree: startup still prints the full byte sum, summary() prints the reduced one |
conn.rs:865-870, selene/src/pool/builder.rs:246-249 |
Areas verified sound are listed at the end; I did not invent issues there.
Finding 1 — Major — the measurement precedes the map that is the real authority
register_memory measures backing from the host path, then approves, then maps:
// selene/src/pool/conn.rs:774-779
let shared_backed = shared.map(|shared| {
(
backed_shm_bytes(&shared.arena_path, shared.arena_bytes),
backed_shm_bytes(&shared.staging_path, shared.staging_bytes),
)
});
// selene/src/pool/conn.rs:801-815
if let Some(approve) = approve
&& let Err(reason) = approve(&plan)
{ ... }
let regions = shared
.map(|shared| {
Regions::map(shared)
Regions::map independently re-stats the same files and is the only code that validates them:
// selene/src/pool/shm.rs:49-57
let size = file
.metadata()
.map_err(|e| Error::caused_by(format!("cannot stat {path}"), e))?
.len();
if len == 0 || size < bytes {
return Err(Error::new(format!(
"shared memory {path} has {size} bytes, expected {bytes}"
)));
}
Impact. The manager can replace its regions between (or before) these two calls: Regions::Recreate removes arena/staging/generation/holders and creates fresh ones (selene-manager/src/local.rs:194-206), printing "running instances must restart to use the pool". Because the new plan charges bytes - backed_bytes, a file whose st_blocks already cover the new size yields backed == declared and host charge 0 (via conn.rs:686-698, budget.rs:19), so the budget no longer stops the attach; the operator now reaches shm.rs:53-57 and gets shared memory ... has N bytes, expected M instead of the pre-patch the pool's host memory (...) was not approved ...; free host/device memory or reduce the manager's --memory and --staging sizes (conn.rs:809-811). That is a strictly worse failure diagnostic for a case the old full-byte charge caught first, and it is a general class: approval is now decided from a snapshot that a different process may invalidate before the snapshot's consumer runs. (The specific sparse-extension detail — fallocate growing st_size without blocks over an old preallocated file — is inference from fallocate semantics, not executed in-repo; the ordering hazard itself is directly visible in the code above.)
Fix. Take backed bytes from the same metadata/fd that Region::map uses — shm.rs:43-57 already opens the file and holds the descriptor — i.e. return the block count from Regions::map and approve on it, or move approval after map's size validation. One stat, one authority.
Finding 2 — Major — a reclaimable estimate is now treated as a hard admission fact with zero margin
// selene/src/pool/conn.rs:696-698
std::fs::metadata(path)
.map(|meta| meta.blocks().saturating_mul(512).min(declared_bytes))
.unwrap_or(0)
// selene/src/pool/budget.rs:19
let additional_host = bytes.saturating_sub(backed_bytes.min(bytes));
Impact. tmpfs pages are not pinned: there is no mlock anywhere in the tree (verified by search), and the regions are drop-and-unmap-able (Region::Drop, selene/src/pool/shm.rs:139-153). /dev/shm contents are reclaimable under memory pressure and re-fault on first touch, and the manager itself can drop the backing by recreating the regions (local.rs:194-206). After this change, the entire arena + staging of a preallocated pool counts as 0 host bytes, so there is no longer any reserved margin covering the window between approval and registration/first touch. For a shared region — the PR body itself notes (N + 1)× when multiple instances map the same files — the budget moves from "cannot overcommit" to "trusts a kernel-defined, revocable estimate". On the reported 494.5 GiB unified host these pages are also the same physical DRAM the GPU KV cache allocates from, which is precisely where an overcommit hurts.
Fix. Either keep a bounded fraction of the region charged (or charge bytes - backed plus a reclaim bound), or make the semantic change explicit: document that the pool budget is now an advisory estimate rather than an admission guarantee, and say so where the number is consumed (builder.rs:246-249).
Finding 3 — Major — public contract break plus a documented invariant relaxed without owner sign-off
3a. Source break, undeclared in the body. Both structs are publicly re-exported and gain a required field:
// selene/src/pool/startup.rs:19-46 (excerpt)
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RegisteredRegion {
pub name: &'static str,
pub address: usize,
pub bytes: usize,
/// Bytes of this region already backed in memory-resident shared storage
pub backed_bytes: u64,
}
// selene/src/pool/mod.rs:60 (not opened)
pub use startup::{Approve, PlannedRegion, RegisteredRegion};
Neither type is #[non_exhaustive] and neither has a Default, so any out-of-tree constructor of PlannedRegion/RegisteredRegion stops compiling. In-tree constructors had to be edited (registered_region, conn.rs:706-717). The PR description lists the new field but not the break; it should be called out as a breaking API change.
3b. Unified-memory accounting moved, and the docs still say the opposite. charges apportions the host term onto integrated devices, so zeroing host bytes also removes the per-GPU shared-host charge:
// selene/src/pool/budget.rs:30-42
pub fn charges(&self, host: u64, device: u64) -> Vec<u64> {
let integrated = self.devices.iter().filter(|(_, shared)| *shared).count() as u64;
self.devices
.iter()
.map(|(_, shared)| device.saturating_add(if *shared { host.div_ceil(integrated) } else { 0 }))
.collect()
}
The new test pins exactly that for the unified case:
// selene/src/pool/budget/tests.rs:118-123
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]);
Two design docs state the invariant this changes:
docs/runtime-core-design.md:768-771— "On integrated GPUs such as GB10, that budget is LinuxMemAvailable, capped by CUDA's device total. CPU allocations, registered buffers, and GPU allocations share physical DRAM; ..."
docs/cli-design.md:884-891— "Integrated GPUs also count resident host tables, embedding row caches, and prefix-cache host pools in the same physical budget. Shared host memory is charged once per host."
AGENTS.md:182-186 requires "Do not ... relax references, workloads, or numerical bounds to obtain passing checks" and AGENTS.md:171-175 requires an explicit maintainer decision before changing an invariant this kind of scope touches. Impact: on the exact host in the report (494.5 GiB unified) arena + staging leaves the physical budget entirely, even though GPU KV cache competes for the same DRAM. That may be the right call, but it is an owner decision, not a side effect.
Fix. Update the docs in the same PR, and either restrict the exemption to the discrete-GPU host term or state explicitly that tmpfs-backed pool pages no longer count against the integrated device budget. Get yatesdr's (the area owner of all five files: #92, #365, #609, #611) sign-off on that specific point.
Finding 4 — Major — the new code path has no coverage
backed_shm_bytes (conn.rs:682-704) is never called by a test. The two new tests hand-construct PlannedRegion values and assert arithmetic:
// selene/src/pool/budget/tests.rs:97-102
let plan = vec![
PlannedRegion {
name: "arena",
bytes: arena,
backed_bytes: arena,
},
The existing conn tests pass None/(1, 4096) with a ClosedRegistrar, and the live-manager harness never leaves the budget unconstrained in a way that exercises approval (helios/src/offload/pool/tests.rs: host: Ok(u64::MAX), host: Ok(1)). The PR body confirms it: "they do not directly execute the statfs helper or a fresh manager attachment reproduction." AGENTS.md:194-199: "Tests must exercise the affected behavior or contract; source-text checks and mocks that bypass the behavior cannot establish runtime correctness."
Impact. The single branch that decides the whole fix — is this file on tmpfs, and how many of its blocks are backed — has zero coverage, and the reported result also has no CI backing (cargo test -p flare-selene pool::budget is author-reported only, no checks on 135633f).
Fix. Use the existing selene_manager::testing::Manager dev-dependency (regions really live under /dev/shm/selene, local.rs:26) and assert backed_shm_bytes(arena_path, arena_bytes) == arena_bytes on a tmpfs host, plus a partially-backed case and a non-tmpfs (e.g. /tmp) case that returns 0. Attribute the 0 results explicitly in the PR body if the host lacks tmpfs.
Finding 5 — Minor — two operator-visible memory numbers now disagree
// selene/src/pool/conn.rs:865-870
let bytes: usize = registered.iter().map(|region| region.bytes).sum();
eprintln!(
"registered {:.1} GiB of pool memory in {:.1} s",
bytes as f64 / (1u64 << 30) as f64,
started.elapsed().as_secs_f64()
);
versus
// selene/src/pool/builder.rs:246-249
pub fn summary(&self) -> Result<String> {
let (host, device) = self.registration_costs()?;
Ok(format!("{host} host bytes · {device} device bytes per GPU"))
}
summary() and charges (builder.rs:188-193) now exclude backed bytes; the startup line still sums full bytes and never mentions backed_bytes. Impact: the startup line reports more pool memory than the budget approved, which reads as a contradiction during exactly the diagnosis this PR is about. Fix. Print the split, e.g. registered {bytes} ({backed} already backed), or report both figures on one line.
Sound in this area (no issue raised)
- Arithmetic.
bytes.saturating_sub(backed_bytes.min(bytes))(budget.rs:19) cannot underflow or exceedbytes; the device termbytes.div_ceil(512)is unchanged (budget.rs:24); both overflow checks survive (budget.rs:21-25). The clamp is covered (budget/tests.rs:152-168,backed_bytes: 8 << 20over4 << 20). - Error propagation. Host
Err(...)still becomescannot budget pool host memory: ...(budget.rs:49-52), theGPU {rank}message is intact (budget.rs:66-69), and both are asserted (budget/tests.rs:124-141). - Platform parity. The non-Linux stub returns 0 (
conn.rs:701-704), so Windows/macOS Selene builds keep the pre-patch conservative charge (relevant since #171 made Selene build/test on Windows). Every failure mode — NUL path,statfs != 0, non-TMPFS_MAGIC,metadataerror — fails closed to a full charge. - Remote staging. Anonymous
data-stagingcorrectly getsbacked_bytes: 0(conn.rs:794-800). - No new contention or hot-path cost. The measurement happens once, on the first connect only (
conn.rs:638-650, "The first connect: the only time anything is registered"), insidetokio::task::spawn_blocking(conn.rs:748-757). No locks, channels, threads, or additional retention were added; the steady-state serving path is untouched; memory amplification is nil (two extrastatfs+statcalls at startup). Approval-failure handling and registration close are unchanged (conn.rs:653-656).
Open questions / could not verify
- Right layer? The reader named as step 1 in the PR body —
host_pool_budget/host_pool_budget_with_reserve(selene/src/offload.rs:923-985, called atoffload.rs:170,181) — is untouched; the exemption is applied only inside the pool budget (selene/src/pool/budget.rs:15-28). WhetherMemAvailableitself should learn about tmpfs-backed pool pages is a reviewer judgement the PR does not discuss. - Unified-memory intent — whether "0 additional host charge" for tmpfs arena pages the GPU KV cache also competes for is intended; the description is silent and the new test pins the shrink.
- No measurement artifact — the PR contains no
Shmem/MemAvailablebefore/after capture, only "verified against live/proc/meminfo"; the kernel-accounting half of the claim is unbacked in-repo. - No in-tree end-to-end harness for the approval path:
offload::Startup::start_pool(selene/src/offload.rs:994) has no call site, so nothing in-repo reproduces the reported failure. - Docs restating the budget were not updated beyond the two quoted above, e.g.
docs/model-preparation.md:490(not opened) and the in-tree restatement inhelios/src/frontend/mod.rs:1400-1402("HOST_SERVICE_HEADROOM_BYTES(2 GiB) plus one twentieth of total memory"). - Merge ordering: open #674 (area owner
yatesdr, same day) rewrites large parts ofselene/src/pool/conn.rsandbuilder.rs; nothing indicates conflict today (no commits on the default branch sincecc0a49dtouch these files), but sequencing deserves a look. - PR-body nit that does not affect the code: the reserve is not "2 GiB + 5% MemTotal" — service headroom is
min(2 GiB, total/32)collapsed to 64 MiB on ≤16 GiB hosts (selene/src/offload.rs:901-919).