PR #625 — Correctness, Contracts & System-Level Consequences review
Head 9639e57 · base main · branch fix/issue-616-host-slab-thp-fallback-timings · fixes #616 · six files, +1,471/−111.
Reviewed in full: eos/src/unix.rs (new map_host, parsers, adaptive population, ~440 lines of tests), selene/src/offload.rs, selene/src/offload/tests.rs, helios/src/offload/mod.rs, helios/src/runtime_core/model.rs:922-982, plus direct callers/contracts selene/src/slab.rs:160-180, selene/src/pool/shm.rs:74-86, selene/src/pool/net.rs:82-105, helios/src/cuda.rs:1599,1665, eos/src/lib.rs:9-16, eos/src/windows.rs:166-195, helios/src/startup.rs:41,82,325-328, docs/prefix-cache-offload.md §2.5/§2.11, and the pre-change main version of map_host (main:eos/src/unix.rs:85-119).
Key findings
- Major — the
/proc/buddyinfohuge-page guard is node-blind: every NUMA node'sNormal/Movablefree blocks are summed into one total, and that total decides whether a PMD chunk is huge-page-faulted. On exactly the two-NUMA host from #616 this can keep the guard satisfied while the faulting node is exhausted, so the compaction stall the PR exists to prevent still happens. - Major — the second guard samples
/proc/vmstat compact_stall, a system-wide, since-boot counter. Any co-tenant process compacting during a chunk is attributed to this allocation and forcesfell_back, after which the entire 119 GiB mapping permanently receivesMADV_NOHUGEPAGE. - Major — the error contract is reversed and undeclared:
maindegraded to volatile zero writes on any failedmadvise; the new code propagates every errno exceptEINTR/EINVAL/ENOSYS,MappingGuard::dropmunmaps, andSlabPool::newturns it into a fatalallocate host slots:startup error. A transientENOMEMnow abortsflare run. - Minor — Unix/Windows contract divergence:
EINVALon zero bytes and all policy awareness exist only ineos/src/unix.rs;eos/src/windows.rsis unchanged and the rewritten doc paragraph now describes Linux only. - Minor — the single-VMA assertions read process-global
/proc/self/smapsinside a multi-threaded test binary (plausible flake, not proven; the failing CI job on9639e57could not be retrieved). - Minor — three of four population modes and the fatal-errno path have no end-to-end test;
PrepareTimings.slab_populateis overloaded as both "allocate" and "populate". - Charter — the headline 128.56 s → 30.99 s is a standalone harness number with no committed script or log, and there is still no served-workload A/B, which #210 requires for a performance PR (the PR admits this).
1. Correctness, safety & platform parity
Finding A — Node-blind buddyinfo guard (Major)
eos/src/unix.rs:272-328 parses /proc/buddyinfo lines of the form Node N, zone Normal … but never records N; it accumulates every Normal/Movable zone into a single preferred_total:
if matches!(zone_name, "Normal" | "Movable") {
saw_preferred = true;
preferred_total = preferred_total.saturating_add(zone_total);
}
}
if saw_preferred { Some(preferred_total) } else if saw_any { Some(all_total) } else { None }
The adaptive loop then gates every PMD chunk on that global total (eos/src/unix.rs:564-571):
while offset < interior_end {
let len = (interior_end - offset).min(chunk_bytes);
let chunk_hugepages = (len / hpage_size) as u64;
let required = buddyinfo_required_hugepages(chunk_hugepages, total_hugepages);
if read_free_hugepages().is_some_and(|free| free < required) {
fell_back = true;
break;
}
Impact. #616's host is two-NUMA (2× RTX PRO 6000, Node 0 Normal order-10=1,860 vs Node 1 order-10=311). Huge pages are allocated from the node the faulting CPU belongs to (first-touch / MPOL_PREFERRED behaviour), so node-1 supply can keep free >= required true while the node actually being faulted has no order-9 blocks left — the guard passes, MADV_HUGEPAGE is issued per chunk, and MADV_POPULATE_WRITE enters synchronous direct reclaim + compaction exactly as before the fix. The PR's own measured baseline shows the two nodes' supplies differ by ~6x, so the masking window is wide. The failure mode is silent: latency classification (:581-595) may still catch it, but only after the stall has already begun, which is the thing being avoided.
Fix. Parse the Node N, prefix into per-node totals and compare against the node set the slab will be faulted on (the process's cpuset/NUMA policy nodes, or conservatively the minimum across nodes when the policy is unknown). A cheap version: keep per-node totals and require min over allowed nodes >= required rather than sum >= required. Add a unit test with a two-node buddyinfo fixture where node 1 is rich and node 0 is empty and assert the chunk falls back.
Finding B — compact_stall is a host-wide counter, so concurrent load forces a permanent fallback (Major)
eos/src/unix.rs:406-410 and :587-594:
fn read_compact_stall() -> Option<u64> {
let contents = std::fs::read_to_string("/proc/vmstat").ok()?;
parse_vmstat_counter(&contents, "compact_stall")
}
ChunkStallCheck::CheckCompactStall => {
if let (Some(before), Some(after)) = (stall_before, read_compact_stall())
&& after > before
{
fell_back = true;
break;
}
}
and the consequence is whole-mapping (:611-616):
let final_advice = if fell_back {
libc::MADV_NOHUGEPAGE
} else {
libc::MADV_HUGEPAGE
};
advise_range(base_ptr, bytes, final_advice);
Impact. compact_stall in /proc/vmstat is system-wide and monotonic since boot, not per-mm. Flare shares a workstation with the user's desktop, other Flare ranks, and any co-tenant process. A single unrelated compaction event inside the few-hundred-millisecond window of one chunk (>, not a delta threshold) sets fell_back, and the whole subsequent mapping is populated in 64 MiB base-page chunks and finally advised MADV_NOHUGEPAGE. For a 119 GiB slab this converts a transient neighbour event into permanently halved TLB reach and higher page-walk cost for the life of the process, and the outcome depends on unrelated load at startup — i.e. non-deterministic serving performance from the same config. Note the asymmetry: the guard is after > before, so one event is enough, and there is no way to clear fell_back afterwards even if later chunks are healthy.
Fix. Require corroboration before falling back: sample both compact_stall and compact_fail and require the pair to advance across two consecutive chunks, or require a delta above a noise floor (e.g. > 2), or tolerate the first strike and only fall back on the second. Alternatively derive stall evidence from the latency classification only (which is per-map_host and thus attributable) and drop the counter sample entirely.
Finding C — Error handling reversed: transient populate failures now abort startup (Major)
main:eos/src/unix.rs:105-117 degraded on any failure:
#[cfg(target_os = "linux")]
let populated = unsafe { libc::madvise(ptr, bytes, libc::MADV_POPULATE_WRITE) == 0 };
#[cfg(not(target_os = "linux"))]
let populated = false;
if !populated {
…then the per-page volatile zero loop, still returning Ok(ptr).
The new code (eos/src/unix.rs:445-453) treats only two errnos as recoverable:
let error = io::Error::last_os_error();
match error.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::EINVAL) | Some(libc::ENOSYS) => {
populate_chunk_volatile(ptr, len, page_size);
return Ok(());
}
_ => return Err(error),
}
and the error is now fatal, because map_host_with (:659-661) only commits after population succeeds and MappingGuard::drop (:173-180) munmaps:
let guard = MappingGuard::map(bytes)?;
populate(&guard)?;
Ok(guard.commit())
selene/src/slab.rs:164-165 converts it into a startup failure:
let base = flare_eos::map_host(mapping_bytes)
.map_err(|error| invalid(format!("allocate host slots: {error}")))?;
Impact. Under the exact condition this PR targets — fragmented physical memory on a large host slab — MADV_POPULATE_WRITE can return ENOMEM (and can also return EAGAIN/EBUSY from a raced mmap_lock-adjacent path on some kernels). Previously Flare degraded to a slow byte loop and started; now flare run dies at Prepare host prefix cache with allocate host slots: Cannot allocate memory. That is a strictly worse user outcome than the 15-minute stall #616 complains about, and it is not mentioned anywhere in the PR's "Compatibility & lifetimes" section, which claims "Every returned slab mapping remains zeroed, prefaulted writable…". No end-to-end test covers the new fatal path; the only coverage is the synthetic ENOMEM injected in mapping_guard_unmaps_on_population_error (eos/src/unix.rs:822-831), which asserts the munmap and the error, i.e. it pins the new behaviour rather than the old degradation.
Fix. Either (a) restore best-effort degradation for ENOMEM specifically — retry the failing chunk in base pages (populate_chunk_volatile) and only propagate if that also fails; or (b) declare the stricter contract explicitly in the description's compatibility section, add a docs/TODO.txt note per AGENTS.md:52-59 (not opened), and add a test that drives populate_chunk with an injected ENOMEM (not just MappingGuard drop) so the whole map_host → SlabPool::new path is covered.
Finding D — Zero-length rejection and all THP policy handling are Unix-only; Windows silently diverges (Minor)
eos/src/unix.rs:656-658 rejects bytes == 0 with EINVAL, and eos/src/lib.rs:9-16 selects unix.rs vs windows.rs per platform. eos/src/windows.rs:166-195 is unchanged: VirtualAlloc then a monolithic step_by(page_size()) zero loop, no chunking, no policy detection, and no EINVAL-on-zero contract. The docs were updated to describe only the Linux strategy (docs/prefix-cache-offload.md:516-535), dropping the previous sentence that also described the Windows/non-Linux path.
Impact. The public contract of eos::map_host is now platform-divergent in a way no doc or test states: callers (all in this repo, but the crate is one of the "in-process Rust SDK" deliverables on the roadmap) cannot rely on EINVAL-on-zero or on chunked population cross-platform, and the Windows monolithic zero loop keeps the exact behaviour (one long uninterruptible fault sweep, mmap_lock-equivalent UI stall) the PR identifies as harmful for responsiveness. Low user impact today given the SM120/SM121 Linux target, but it is an undeclared contract split.
Fix. Add a sentence to docs/prefix-cache-offload.md §2.5 stating that the policy-aware strategy is Linux-only and that Windows/non-Linux Unix populate in bounded chunks without THP advice; either mirror the bytes == 0 → EINVAL check in eos/src/windows.rs or document the difference.
Finding E — Single-VMA assertions test a process-global property (Minor, plausible flake)
eos/src/unix.rs:1184-1191:
if let Ok(smaps) = std::fs::read_to_string("/proc/self/smaps") {
let vmas = parse_smaps_intersecting_vmas(&smaps, address, address + bytes);
assert_eq!(
vmas.len(),
1,
"expected single merged VMA after fallback (fallback_needs_nohugepage={fallback_needs_nohugepage}), got: {vmas:?}"
);
/proc/self/smaps is the whole process, and the crate's test binary runs test functions on multiple threads by default. parse_smaps_intersecting_vmas (:780-812) returns any VMA overlapping the range, so an adjacent anonymous mapping created by a concurrent test that touches the page right below address produces a distinct-but-adjacent VMA and a spurious len() == 2. map_host_advises_hugepages_and_prefaults_zeroed_pages (:1077-1141) contains the same class of assertion.
Impact. Intermittent CI failures on eos unit tests, which are part of every native-serving.yml (not opened) leg. I could not retrieve the failing job/log for 9639e57, so I state this as a plausible source, not as proven causation.
Fix. Take a process-wide lock in these tests (or gate on --test-threads=1), or assert on the mapping's own /proc/self/smaps entry by matching the exact start address rather than "any intersecting VMA", and skip the assertion when a neighbour is detected adjacent.
Finding F — Untested population branches (Minor)
population_mode_decision_table_covers_all_policy_combinations (eos/src/unix.rs:866-930) only asserts the selector output. No test drives populate_linux (:620-650) through PopulationMode::BasePages, EagerHugepage, or KernelDefaultOpportunistic — only the adaptive branch is exercised end to end (map_host_advises_hugepages_and_prefaults_zeroed_pages :1077-1141, adaptive_mid_mapping_fallback_merges_into_single_vma :1143-1202). The fatal non-EINVAL/ENOSYS propagation is covered only by the synthetic ENOMEM in mapping_guard_unmaps_on_population_error (:822-831), which bypasses populate_chunk.
Impact. The three non-adaptive branches are the ones that run on most hosts (enabled=never on many distros, enabled=always+defer is common), and a regression there would be caught by nothing but a live serve. Combined with Finding C, the most impactful new failure mode is also the least tested.
Fix. Add parameterised tests calling populate_linux with synthesised ThpPolicy values and asserting a zeroed mapping plus the expected VmFlags (hg only for EagerHugepage, none for BasePages), and a populate_chunk test with an injected errno.
Areas verified sound (no findings)
pub fn map_host(bytes: usize) -> io::Result<usize>unchanged (eos/src/unix.rs:664);unmap_hostunchanged (:687-691).MappingGuardcommit/forget discipline correct (:139-181): no double munmap on success, munmap on every error path.EINTRretry loop does not spin on other errnos (:439-454).- Policy parsing is defensive: power-of-two validation and portable 2/32/512 MiB fallbacks (
:228-240),Unknownroutes to the conservative adaptive mode (:259-263), 24-cell matrix test (:866-930). - Adaptive geometry is internally consistent: PMD-aligned interior with the one-PMD shrink and anchor page when both ends align (
:502-550), chunk doublinghpage_pmd_size → max(16 MiB, hpage_pmd_size)(:558,:596), single-PMD shortcut (:513-525), tail tile covers[offset, bytes)exactly (:599-607) — every page populated exactly once, none skipped or double-faulted. - Final whole-range
madvisedoes letvma_mergecollapse sub-VMAs (:609-616), which is required bycuMemHostRegister_v2/ibv_reg_mr. phase.detailis a pre-existing primitive (helios/src/startup.rs:325-328); 3-5 step updates per start, no throttling concern; phase label andStartupStage::PrepareHostPrefixCacheuntouched (helios/src/runtime_core/model.rs:934,helios/src/startup.rs:41,82).
2. System-level consequences
- Hot-path scope creep.
map_hostnow does three/sysreads plus/proc/buddyinfo+/proc/vmstatreads (eos/src/unix.rs:383-398,:401-410,:572), and during the adaptive loop/proc/buddyinfois re-read before every chunk (:568) with the file growing as the slab grows. Every caller inherits this, not just the prefix cache:SlabPool::new(selene/src/slab.rs:162-165), pool staging viaRegion::anonymous(selene/src/pool/shm.rs:78), and CUDA tests (helios/src/cuda.rs:1599,1665). For a 4 KiB/8 KiB test pool this is ~5 extra file reads per allocation for no benefit; for the 119 GiB slab it is ~1,900 buddyinfo parses of a file that grows with node count. This is bounded and not a hot path in serving (startup only), so I rate it Minor, but it is an undeclared layer inversion: a general-purpose allocator now embeds a kernel-allocation-policy heuristic. - Failure-propagation blast radius. Before this PR a populate failure could not fail startup at all; now a single errno from one 64 MiB chunk aborts the whole
Prepare host prefix cachephase, and becausemap_host_withreturns the error afterMappingGuardhas munmapped, the entire 119 GiB reservation is released and retried from scratch by the operator. There is no partial-progress retention and no retry (Finding C). - Contention/ordering. No new locks;
phase.detailis called from the same thread that already held the phase. No head-of-line blocking introduced. The one ordering hazard I checked — the anchor page fault before sub-rangeMADV_HUGEPAGE— is implemented correctly and in the stated order (:527-550), which is what makes the single-VMA merge work. - Invariants of recently merged work. #589's intent (huge pages when available) is preserved, and #497's headroom/checkpoint/intake logic is preserved verbatim; the pool-construction body is restructured from a
then(...).transpose()closure into anifblock with identical semantics (selene/src/offload.rs:702-735vs base). I found no reversed invariant. - Out of scope but relevant:
selene-manager/src/arena.rs:93(not opened) still issues an unconditionalmadvise(MADV_HUGEPAGE)on its own mapping and remains exposed to #616's pathology. Not required for this PR, but worth adocs/TODO.txtline.
3. Architecture, contracts & charter compliance
Finding G — PrepareTimings.slab_populate is overloaded across two different measurements (Minor)
selene/src/offload.rs:331-340 declares one field for two spans:
pub struct PrepareTimings {
/// Time spent allocating a split pool or populating a contiguous host slab.
pub slab_populate: Option<Duration>,
and the two call sites measure different things into it — :706-712 times SlabPool::try_sized_by_rank (HOST_NUMA VMM cuMemCreate, genuinely allocation, no faulting), :726-733 times SlabPool::sized (contiguous map_host, genuinely population). summary() relabels by rank_parts() (:419-431). Tests pin the emitted strings: selene/src/offload/tests.rs:1192 (split by rank, allocate 1.2s), :1249 (populate 2.4s, register 0.7s), :1308 (populate 12.3s, register 4.8s) · disk … scan 0.9s).
Impact. (a) Metric-scope confusion: a downstream dashboard or grep that sums slab_populate mixes "VMM allocation" with "anonymous population", which are not comparable quantities. (b) The summary text shape changes in place — memory X GiB (N slots) becomes memory X GiB (N slots, populate 12.3s, register 4.8s) — so any external parser keyed on the old parenthetical breaks. No in-repo test asserts the old text (the Python server test only asserts the phase is absent when disabled, tests/server/test_prefix_cache_offload.py:135 (not opened)), but the PR description does not call out the log-format change as a compatibility item.
Fix. Split into slab_allocate and slab_populate (both Option<Duration>), or keep one field but name it slab_ready and document that its meaning depends on rank_parts(); mention the summary-text change explicitly in the description's compatibility section.
Finding H — Charter #210 evidence gap (Major, process)
The claimed result is:
"populating a 48 GiB anonymous host slab dropped from 128.56 s … to 30.99 s … (4.15x faster …)"
and the PR's own benefit section says:
"Expected benefit (not yet timed inside a live
flare runlaunch): Operators runningflare run… see live sub-step progress updates and separateallocate/populate/register/scandurations"
No benchmark script, raw log, or harness source is committed; the numbers come from a standalone eos::map_host + cuMemHostRegister_v2 program on the author's two machines. The charter requires "Performance PRs need benchmarks showing an actual speedup over main on a served workload (#210)". #616's own measurement (914.6 s vs 71.1 s in Prepare host prefix cache) is the natural served-workload A/B and was not run on this branch.
Impact. The change is a plausible and well-reasoned fix, but as filed the register that decides it lacks the evidence class the project requires for performance work — and the reviewer cannot distinguish "fixes #616" from "fixes a synthetic variant of #616". Combined with Findings A and B, an unmeasured change to a host-policy heuristic goes into the default path for every Linux operator with no override.
Fix required before merge. Run flare run <exported-core> --prefix-cache-memory 128G --prefix-cache-disk <dir> (or the reporter's exact config) on main and on this branch with THP enabled=madvise, defrag=madvise, and paste the Prepare host prefix cache line plus wall-clock for both; commit the harness if it is reused. If that is genuinely impossible in this environment, add the docs/TODO.txt entry AGENTS.md:52-59 (not opened) asks for, so the unrun served check is recorded in the repo rather than only in the PR body.
Charter-adjacent note: "Be explicit and pin everything. No magic defaults" (#215). Every threshold is a compile-time constant with no CLI flag, config key, env var or metric — 64 MiB (:88), 16 MiB (:92), 15 ms / 50 ms / 1 GiB/s / 256 MiB/s (:348-360), total/16 min 32 (:343). The PR argues this deliberately (avoiding sysctls and switches), and I agree the argument is reasonable for a default-on heuristic, but it means an operator who hits a wrong classification has no recourse except a kernel sysctl change — the very thing this PR set out to avoid.
4. Tests & claim accuracy
Claims checked against the diff, all accurate: signature preserved (:664); bytes == 0 → EINVAL (:656-658); MappingGuard munmap (:173, test :822-831); EINTR retry and EINVAL/ENOSYS-only fallback (:446-453); sysfs parsing and 2/32/512 MiB defaults (:228-240, :383-398); 24-cell matrix (:866-930); growing PMD chunks (:558, :596); stall_floor/hard_ceiling (:348-360); compact_stall re-sampled only inside the latency band (:581-595); fallback reserve (:343); final merge advice (:611-616); PrepareTimings fields (selene/src/offload.rs:331-340, :368); prepare_with_inputs_budget_with_progress (:594; wrapper helios/src/offload/mod.rs:101-120); step/timer resets on the split→contiguous fallback (selene/src/offload.rs:713-723, asserted selene/src/offload/tests.rs:1230-1240); summary additions (tests:1189-1193, :1242-1250, :1304-1310); restore-only and disabled summaries byte-identical (tests:1345-1376, :255); no proto/model-core/serving-ABI change (pr_files touches no .proto, no core-format code).
What the description does not disclose:
- The 64 MiB chunking is universal, not part of the synchronous-compaction strategy —
POPULATE_CHUNK_BYTES(:88) applies in all four modes (:626-632) and on non-Linux Unix (:671-679). The "What Changed" bullet frames chunking as adefrag=defer|neverdetail, which understates how much of the old path changed on every host. - The fatal error path (Finding C) is missing from the compatibility section.
- The
map_hostscope of effect (pool staging, CUDA tests, every 4 KiB test pool) and the per-call/sys+/procI/O (Finding D/scope-creep) are not mentioned. - After a mid-slab fallback, the final whole-range advice is
MADV_NOHUGEPAGEeven when the policy did not need it (Finding B), so a head that did obtain huge pages shares a slab whose growth path is now base-page only. The PR's measuredAnonHugePages=2,046 MiBretention shows populated huge pages are not split back, but the effect on subsequent growth is neither measured nor discussed. - When both endpoints are PMD-aligned the code shrinks the interior by one PMD (
:542-550), so the last PMD of such slabs is always base pages — deliberate and documented in the comment, but not in the description. docs/prefix-cache-offload.md:985-986still says[prefix_cache]rejects unknown keys, consistent with there being no new knob — fine, but no doc tells an operator what the allocator now does when they see the new timing strings.
Open questions / not found
- Which CI job failed on
9639e57, and why. Bothnative-serving.yml(not opened) andhelios-lifecycle.yml(not opened) apply; nocargo fmt/clippy gate exists in any workflow. Not retrievable with the tools available. My earlier Windows-test hypothesis is disproved —eos/src/unix.rsis#[cfg(unix)]-only (eos/src/lib.rs:9-16), so the new tests do not build onwindows-2022. Finding E is a plausible Linux-side flake source but unproven. - Whether the strict error propagation can convert a recoverable
ENOMEMinto a startup failure in practice. No end-to-end test, no documentation, and the description is silent (Finding C). - What the served-workload effect is. No
flare runtiming exists formainor the branch; #210 unmet by the evidence as filed (Finding H). - Whether the node-blind guard (Finding A) or the system-wide counter (Finding B) actually bites on the reporter's host — needs a two-NUMA run with a co-tenant to demonstrate, which is precisely the run that would have answered Finding H.
- Whether
selene-manager/src/arena.rs:93(not opened)'s unconditionalMADV_HUGEPAGEwill be brought in line; out of this PR's scope and unmentioned. - Interaction with #323 (open; refactors the same
prepare_with_inputs*signature family anddocs/prefix-cache-offload.md) and #576 (open; adds toeos/src/unix.rs). Neither reconciled; #323's recommended shape (move the value ontoPrefixCacheOffload, drop the positional parameter) collides directly with the parameter this PR added beforeon_step.
Merge verdict. The design is sound and the mechanism matches the description, but I would not merge as-is: Findings A, B and C are concrete defects in the code this PR adds (two of which can leave #616 unfixed or make startup fail outright), and Finding H is the charter's evidence bar. A and B are small, local fixes in parse_buddyinfo_free_hugepages/read_compact_stall; C needs a decision (restore degradation or declare it); H needs one served A/B or a docs/TODO.txt entry.