Opened by a workflow run, Dec 4, 2026 10:10 AM EST. decide malicious: all_clear (100%): No malicious content found
explore
Author: original-el8 (COLLABORATOR; charter-named priority contributor; recent work is a GB300/SM103 host-tiered series; Discord el8)
Motivation: Model startup used to run allocation, weight loading, kernel/graph/cache preparation and tokenizer loading strictly one after another, so the NVMe array idled while the host pre-faulted and pinned memory and the GPU idled while host-tier weights streamed. This PR overlaps those steps and reads mapped-host weights straight into host memory instead of copying them through pinned CUDA staging buffers.
Scale: +1886 / −385 lines in 8 files
Proposal:
- Split
allocate()intoallocate_deviceplus coalesced,MADV_HUGEPAGE-hinted, ordered 2 MiB pre-faultedMappedHostVMAs prepared on a CUDA-lock-free thread while device weights upload (helios/src/runtime_core/mod.rs). - Pin host memory in 512 MiB windows racing ahead of readers, gated per chunk by a new
RegistrationGate, then prepare kernels/execution/engram/caches/prefix cache on a background thread and replay its progress rows (replay_completed). - Replace fixed
SLOTS=4/READERS=4/CHUNK=4 MiBwith a runtimeIoPlanderived from CPUs, ranks, sysfsoptimal_io_sizeandMemAvailable. - Read
MappedHostpayload bytes viaO_DIRECTpreaddirectly into mapped host memory, staging only unaligned edges. - Pre-load the frontend tokenizer/chat template on a
flare-frontend-preloadthread, reused inBootstrap::load_with_preloadedwhen the cache key matches. Touches: - helios/src/runtime_core/payload.rs (+689/−80): zero-copy I/O and
IoPlan. - helios/src/runtime_core/mod.rs (+618/−86): VMA coalescing/THP/pre-fault, chunked registration, new teardown.
- helios/src/runtime_core/model.rs (+402/−152) and helios/src/startup.rs (+31/−8): overlapped startup pipeline and progress replay. Related items:
- #710 Coalesce mapped host VMAs for THP… (open, draft, same author): already contains this PR's VMA/THP/pre-fault half; superseded silently.
- #711 AsyncTransfer + runtime-sized DEVICE_POOL (merged): inherited base visible in the rendered diff.
- #721 AsyncTransfer hardening (merged): source of one of the "6 new tests".
- #696 helios: parallelize engram loading and report startup progress (open): same files, same startup-latency goal, no cross-reference.
- #723 fleet-wide codec green contexts (open): same three runtime_core files, collision risk in kernel/graph preparation.
Link: https://github.com/NVIDIA/hyperflare-inference/pull/726
Autobot comments: The 75.0 s → 45.5 s (−39.3 %) result was measured, by the PR's own admission, on "the equivalent
feat/gb300-tiered-runtimebuild prior to rebasing cleanly ontomain" — that is open draft #710's branch, not the head and not againstmain, which charter line 40 (#210) requires of performance PRs; no numbers exist for the rebased head. Open draft #710 by the same author already carries the identical coalesce/MADV_HUGEPAGE/ordered-2 MiB-pre-fault design forhelios/src/runtime_core/mod.rs, and #726 neither mentions nor closes it. Undeclared behaviour:MADV_HUGEPAGEis applied unconditionally (mod.rs:2264) against the standing caution in docs/TODO.txt:1-6 and merged #625's THP-stall fix;StartupObservationloses its#[cfg(test)]gate so productionflare runnow re-emits phases with " · overlapped";mod hostbecomespubon all platforms; teardown moves to reverse-orderedhost_registrations/host_mmap_spans; and the overlap only engages for mixed device+host cores (model.rs:850), so "across every GPU architecture" is narrower than claimed. Only 5 of the "6 new unit tests" are new (the sixth is #721's), all CPU-only, with no GPU or hardware test; preload errors are silently swallowed; no docs are updated; and much of the rendered diff outside the described scope is inherited from merged #709/#711/#721 because the diff base predates them —pr_files' 8 files are authoritative.
Value Proposition
Value Proposition — PR #726 (helios: startup overlap + zero-copy weight loading)
Charter alignment — right problem, right layer. This is generic runtime I/O/allocation work in helios/src/runtime_core: no per-model branches, no recipe/alias changes, no package-format or ABI change (format.rs ±1). That matches "Solve the right problem in the right place" and "Keep the runtime small and model-agnostic." The description carries the required four parts plus a limitations section. Two tensions: the headline 75.0 s → 45.5 s was measured on the author's feat/gb300-tiered-runtime build before rebasing onto main, so it does not meet #210's "actual speedup over main on a served workload"; and choose_io_plan adds environment-derived defaults (chunk 1–8 MiB, up to 8 readers, staging = MemAvailable/200 clamped 16–128 MiB) with no operator control — close to the "no magic defaults" rule.
Novelty & status — additive. Nothing merged addresses serial startup; #625/#616 concerned eos::map_host prefix-cache latency, not MappedHost weights, so not obsolete. The host-VMA half (coalescing, THP hint, ordered 2 MiB pre-fault) duplicates the author's own open draft #710, which #726 neither cites nor closes — real duplication to resolve, but #710 is only a third of #726, so not superseded. Live collision risk with #696 (same model.rs/startup.rs, same goal) and #723 in prepare_kernels/prepare_graphs.
Value vs cost. The problem is real and structural, and the benefit is plausible — but overlap engages only for mixed device+host cores (overlap_host_alloc), so "every GPU architecture" overstates reach; pure-GPU cores still get unflagged staging and tokenizer changes. Cost is high: +1886/−385 across the shared startup path, 5 genuinely new CPU-only tests (the sixth is #721's), and self-declared untested paths (host_vmm/Windows, integrated-GPU mlock, async_transfers, multi-rank TP). Undeclared behaviours: unconditional MADV_HUGEPAGE (the hazard retired by #625), removal of the #[cfg(test)] gate with " · overlapped" rows changing startup log output, and an unreachable! non-Unix branch. Docs untouched.
Verdict: Worth it with changes. Priority contributor; don't close. Before merge: (1) re-benchmark the rebased head against main with attached output; (2) settle VMA ownership with #710 and coordinate with #696; (3) gate or justify MADV_HUGEPAGE per #625 and document the log-format change; (4) update runtime/CLI docs; (5) hardware-validate multi-rank and host_vmm, or get explicit sign-off to defer.
Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.
Classify intake
Selected: triage:review, performance
Threshold: 65%
Triage
- [✓]
triage:review: 91.8% -
triage:validation: 6.7% -
triage:design-review: 1.3% -
triage:investigate: 0.1% -
none: 0.1% -
triage:integration: 0.0% -
triage:partial: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Priority
-
none: 100.0% -
priority:P1: 0.0% -
priority:P2: 0.0%
Type
- [✓]
performance: 98.9% -
community: 53.1% -
duplicate: 43.8% -
enhancement: 43.8% -
documentation: 0.2% -
bug: 0.1%
Area
-
area:memory: 62.2% -
area:preparation: 56.2% -
area:engram: 10.7% -
area:caching: 8.5% -
area:rocenante: 5.3% -
area:selene: 4.7% -
area:api: 3.7% -
area:packaging: 3.3% -
area:scheduling: 1.6% -
area:kernels: 0.7% -
area:orbit: 0.2%
Model
-
model:muse-glimmer: 0.8% -
model:qwen3.8-flash-next: 0.3% -
model:kimi-k3.1: 0.2% -
model:nemotron-3.5-bolt: 0.2% -
model:deepseek-v4: 0.2% -
model:mimo-v2.6: 0.2% -
model:inkling-small: 0.1% -
model:glm-5.3: 0.1% -
model:deepseek-v4.1: 0.1% -
model:qwen3.8-27b: 0.0% -
model:gemma4: 0.0%
Apply Labels (Intake)
Applied: +triage:review, +performance
Subtraction and simplicity
Subtraction & Simplicity audit — PR #726 (helios startup overlap)
Verdict: not lean. The functional kernel (overlap host VMA prep with device upload, chunked registration gate, zero-copy MappedHost reads) is legitimate, but the diff carries a substantial amount of avoidable surface: state encoded three ways in the load path, a dead second scan of the allocation table, a duplicated paged-read loop, duplicated validation, four copy-pasted cleanup sites in an unsafe fn, and a #[cfg] fork per platform arm for a struct that is always empty off-Unix. Two behaviour-relevant dead/over-broad edges also fall out of this lens (prepare_mapped_host_vmas's cancel is never observable on one path; pub mod host widens API for one function).
Ordered by value. Line numbers are at head 60d1b6b.
1. Verbatim-duplicated post-load sequence in both arms of load_agreeing (~10 lines, zero risk)
helios/src/runtime_core/model.rs:1182-1192 (overlap arm) and model.rs:1208-1217 (else arm) contain the same four statements:
model.parallel(&cores, &files, |rank, core, _| {
rank.apply_payload_relocations(core)
})?;
if model.ranks.iter().any(|rank| rank.integrated) {
Files::release_page_cache(&files);
}
load_phase.finish(format!(
"{:.1} GiB",
payload_bytes as f64 / (1u64 << 30) as f64
));
The only divergences between arms are host_load_result?; let caps = runtime_result?; / progress.replay_completed(...) (overlap) versus prepare_runtime(&mut model, &mut cores, progress)? (else). Hoist the shared four statements after the if/else block, binding caps inside the arms. Also note load_phase.finish(...) is computed from the same payload_bytes in both arms — it is a property of the load, not of the branch.
2. pending_registrations is encoded three different ways in one function
model.rs:882-906— first materialised as aVec<PendingHostRegistration>ofdefault()for every device, then replaced wholesale by aMutex<Vec<Option<PendingHostRegistration>>>filled fromcollected.lock().unwrap()[rank.rank] = Some(pending)and mapped back with.map(|p| p.unwrap_or_default()).model.rs:1146-1151— converted again toMutex<Vec<Option<…>>>via.into_iter().map(Some).collect().model.rs:1196-1201— the same conversion repeated verbatim in the else arm.
Option + unwrap_or_default() buys nothing: the Option can only be None if model.parallel visited a rank twice, and unwrap_or_default() silently converts that bug into "no host registration, gate closed, zero-copy reads into unregistered pages". Build one Vec<Option<PendingHostRegistration>> per rank (the first site already produces exactly that shape), pass it by reference as &Mutex<Vec<Option<_>>> to both branches, and use .take().ok_or_else(|| invalid("rank {i} prepared no host registration"))? — deleting ~20 lines and one silent-failure mode. Better still, since model.parallel already hands each closure its rank.rank, fold registration into the same closure that produced the pending value and drop the cross-thread vector entirely.
3. Chunk::read and Chunk::read_direct_into_host are the same short-read loop twice
helios/src/runtime_core/payload.rs:363-389 and payload.rs:396-422 — both implement identical read_at retry semantics with the identical three error strings:
Ok(0) => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "short model payload read")),
Ok(n) => { done += n; if done < required && done % BLOCK != 0 { /* same error */ } }
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Only the sink differs (&mut buffer[done..nbytes] returning &buffer[skip..skip + self.nbytes], versus &mut dst[done..]). Extract one fn read_full_at(file: &File, offset: u64, dst: &mut [u8]) -> io::Result<()> and let read be read_full_at(file, offset, &mut buffer[..required])?; Ok(&buffer[skip..skip + self.nbytes]), with read_direct_into_host reduced to one unsafe slice construction plus a call. Removes ~25 lines and one place for the EOF/alignment contract to drift.
4. tier_io_plan's second return value is dead at both call sites, and it re-walks the allocation table
// payload.rs:640
let (plan, _) = tier_io_plan(files, core, ranks, Memory::MappedHost)?;
// payload.rs:792
let (plan, _) = tier_io_plan(files, core, ranks, Memory::Device)?;
tier_io_plan (payload.rs:482-522) does a full pass over core.allocations to sum stored_bytes() and to find first_file; collect_tier_chunks (payload.rs:524-578) then does the same pass with the same allocation.memory != memory_filter filter and the same files.span/files.source lookups. Neither caller wants the u64. Two fixes, either acceptable: change the signature to Result<IoPlan> (deleting the dead tuple), or have tier_io_plan return the chunk list so one pass does both. As written, each payload::load performs the scan three times (device plan, device collect, host plan, host collect) and re-reads /proc/meminfo and two /sys/dev/block/... files twice per rank.
5. Overlapping I/O-size validation in detect_optimal_io_size and choose_io_plan
payload.rs:172-177:
&& bytes >= BLOCK
&& bytes <= MAX_CHUNK
&& bytes % BLOCK == 0
payload.rs:222:
if optimal_io_size >= BLOCK && optimal_io_size <= MAX_CHUNK && optimal_io_size % BLOCK == 0 {
The second check re-validates a value the first function is contractually guaranteed to have returned (0 or a value already satisfying all three predicates — the #[cfg(not(target_os = "linux"))] stub returns 0, which fails >= BLOCK and is a no-op). Delete one. Keeping it in detect_optimal_io_size is the right side, because that is where the untrusted sysfs string is parsed.
6. IoPlan.slots = 0 encodes "not a device load" in a field, and the test asserts the sentinel
payload.rs:156 (slots: usize), payload.rs:234-244 (let slots = if !needs_staging { 0 } else { … }), asserted at payload.rs:1004-1006:
let host_only = choose_io_plan(1, 72, 1 << 20, Some(512 << 30), 300 << 30, false);
assert_eq!(host_only.slots, 0);
needs_staging is exactly matches!(memory_filter, Memory::Device) (payload.rs:519) — i.e. the caller already knows, and the plan stores a zero that every consumer must special-case (payload.rs:796: plan.slots.min(chunks.len()).max(1)). Make it slots: Option<NonZeroUsize> (or leave slots out of IoPlan and compute it only in load_device), which makes "a host plan has staging slots" unrepresentable rather than merely untrue, and drops the slots: 0 assertion.
7. RegistrationGate's empty-vector special cases are unreachable through its only constructor, and three types encode the same emptiness
helios/src/runtime_core/mod.rs:2138-2162—PendingHostRegistration::is_empty()andchunk_ends(), each with a#[cfg(unix)]body and a#[cfg(not(unix))]body returningtrue/Vec::new().model.rs:1049-1058— the only construction site:
so alet gates: Vec<Option<super::payload::RegistrationGate>> = pending_registrations .iter() .map(|pending| (!pending.is_empty()).then(|| super::payload::RegistrationGate::new(pending.chunk_ends())))RegistrationGatewithchunk_ends.is_empty()is never built.- Yet
RegistrationGate::required_index(payload.rs:599) andwait_for(payload.rs:621) both branch onself.chunk_ends.is_empty(), andregister_pending_mapped_host(mod.rs:797) branches onpending.chunks.is_empty()a third time.
Pick one representation. Either drop the Option in model.rs and let an empty gate be the natural no-op (delete PendingHostRegistration::is_empty, keep the payload.rs fast paths), or keep the Option and delete the chunk_ends.is_empty() branches in payload.rs:599,621. As it stands all three sites must agree forever, and is_empty() duplicates a fact already computable from chunks.
Related dead surface in the same struct: chunks: Vec<(u64, usize, u32)> is #[cfg(unix)] in PendingHostRegistration (mod.rs:2132-2135), which forces the #[cfg] fork of both methods and the #[cfg(not(unix))] arms in register_pending_mapped_host (mod.rs:849-856, ending in let _ = (core, pending, cancel);) and in load_device_overlapping_mapped_host (mod.rs:777-780, unreachable!("non-unix platforms always set host_vmm = true")). (u64, usize, u32) is platform-neutral; making the field unconditional and default-empty Vec deletes three #[cfg] forks, one unreachable!, and one tuple-discard.
8. &AtomicBool is plumbed into paths where nothing can ever set it
mod.rs:877:let cancel = std::sync::atomic::AtomicBool::new(false);passed toprepare_mapped_host_vmasandregister_pending_mapped_host, where it can never readtrue— so the cancel checks atmod.rs:2237-2243(pre-mmap), the post-pre-fault cancel block, andmod.rs:807are dead on that path.payload.rs:928-944(load) constructs anotherAtomicBool::new(false)forload_mapped_host_chunks, where the only setters are the readers' own error paths (payload.rs:754-755) — and those paths alreadybreakunconditionally in the same iteration. So for the standalone path,canceladds a parameter, two dummy constructions, and a!cancel.load(...)conjunct inRegistrationGate::wait_for(payload.rs:622,628) that is redundant withclose()(which already setsstate.1and wakes the condvar).
Give load_mapped_host_chunks the cancel only through the multi-rank coordinator (make it Option<&AtomicBool>, or move the cross-rank cancellation into the gate alone — close() already covers every wait). That removes both dummy AtomicBool constructions and simplifies wait_for to state.0 > required.
9. Four copy-pasted cleanup-and-return sites in one unsafe fn
prepare_mapped_host_vmas (mod.rs:2175-…), with the teardown closure at mod.rs:2230-2234:
let cleanup = |outcome: &mut MappedHostAllocation| {
for (addr, bytes) in outcome.mappings.drain(..).rev() {
libc::munmap(addr as Handle, bytes);
}
};
is invoked at four sites with the same three lines each:
mod.rs:2237-2243(cancel before mmap) →cleanup(&mut outcome); return Ok((MappedHostAllocation::default(), PendingHostRegistration::default()));mod.rs:2252-2257(mmap collision) →cleanup(...); return Err(...)- the post-pre-fault cancel check (after the
prefault_slicesblock, ~mod.rs:2440) → identicalOk((default, default))pair - the
integratedmlockfailure (~mod.rs:2470) →cleanup(...); return Err(invalid("cannot lock … RLIMIT_MEMLOCK"))
Every one of the four exists because MappedHostAllocation has no Drop. Implement Drop for MappedHostAllocation that unmaps mappings in reverse unless a commit() (or moving the fields out in attach_mapped_host, mod.rs:860-867) disarms it; the four sites then collapse to plain return/?, the cleanup closure disappears, and the "SAFETY: Any partial mappings are unmapped before returning on error or cancellation" assumption becomes mechanically enforced instead of reviewed by eye. This also removes the need for the two "return an empty MappedHostAllocation to signal cancellation" idioms, which currently make a cancelled run indistinguishable from a no-op one.
10. StartupObservation.completed retention is now unconditional in production, and State.elapsed exists only for replay
helios/src/startup.rs:111-113 + :136-138: completed: Arc<Mutex<Vec<StartupSnapshot>>> is pushed for every completed phase in every build — a clone() of two Strings up to 512 chars each per phase, retained for the process lifetime — and it is read only by replay_completed (startup.rs:178-203) and by unit tests. Every load that is not the mixed-core overlap path (all pure-GPU cores, all load_prepared in-process loads) accumulates this vec and never reads it.
startup.rs:134: elapsed: state.elapsed.unwrap_or_else(|| state.started.elapsed()) — State.elapsed is set in exactly one place, replay_completed (startup.rs:189); every other State literal sets it to None. So an Option field and an unwrap_or_else exist purely to smuggle a replayed duration through publish.
Cleanest shape: keep completion retention opt-in — a second constructor (observed_retaining()) used by the single call site at model.rs that needs replay — and have replay_completed push StartupSnapshots straight into the observation and write its rows, instead of round-tripping through State. That deletes the elapsed: Option<Duration> field, the unwrap_or_else, and the unconditional retention. The " · overlapped" string building (startup.rs:183-187) belongs with the row writer either way.
11. Frontend preload: three layers of plumbing and three silent error swallows
model.rs:702-718:.spawn(move || crate::server::preload_frontend(&snapshot).ok()).ok().flatten()— two.ok()/.flatten()in one expression.model.rs:1222-1225:model.preloaded_frontend = handle.join().ok().flatten();— a third swallow, withpreload_frontend's ownResultalready discarded at the thread body.config.rs:PreloadedFrontend+frontend_cache_key+preload_frontend+load_with_preloaded+ apreloaded: Option<PreloadedFrontend>parameter threaded throughBootstrap::load,load_inner(config.rs:149-151makesBootstrap::loada pure pass-through toload_with_preloaded(…, None)).server.rs:32-33:pub(crate) use config::{PreloadedFrontend, preload_frontend};— a re-export whose only purpose is lettingruntime_core::modelname a type it does not construct or inspect.
The functional consequence of the triple .ok(): a tokenizer that fails to preload is indistinguishable from one that was never preloaded, so a config error surfaces only as a mystery 0.8 s startup regression — and that is the entire feature. Collapse to one Result (fail fast, or log once), drop the Option-of-Option shape at model.rs:702-718, and check whether Bootstrap::load still has any caller now that session.rs:34 uses load_with_preloaded — if not, delete the wrapper rather than keeping both entry points.
12. AlignedBuffer duplicates engram::reader::Aligned
helios/src/runtime_core/payload.rs:253-278 (struct + as_mut_slice + Drop calling crate::os::free_aligned) and helios/src/engram/reader.rs:130-141 (Aligned(usize, usize) over crate::os::allocate_aligned) are two hand-rolled RAII wrappers over the same os::{allocate_aligned, free_aligned} pair, in the same crate, one file apart. Note Aligned (engram) has no Drop at all — it leaks on every path unless the caller frees it — so the two are not merely duplicated but inconsistent. One crate::os::AlignedBuffer with as_mut_slice(), len(), and Drop serves both; this PR's version is already the correct one to hoist.
13. pub mod host; widens crate API for one function
helios/src/runtime_core/mod.rs:22: mod host; → pub mod host;, replacing #[cfg(any(windows, test))]. The only new external use is host::use_host_vmm(&driver, device)? (mod.rs:369), and host.rs also exposes pub(super) unsafe fn allocate_host alongside other internals. Use pub(crate) mod host; (or pub(super)) plus pub(crate) unsafe fn use_host_vmm. Note the module now also compiles on all platforms, which is what makes the #[cfg(not(unix))] arms in item 7 necessary in the first place — narrowing the module back to where it is used is the subtraction, not the addition.
Deliberately checked and found lean
push_span_chunks(payload.rs:425-480) — the head/aligned-body/tail split is the minimum needed to make the zero-copy span rule explicit; no reduction available.choose_io_plan's arithmetic (payload.rs:213-244) — dense but each clamp is load-bearing; the only waste is item 6's sentinel.registration_chunks/prefault_slices(mod.rs, both under#[cfg(any(unix, test))]/#[cfg(any(target_os = "linux", test))]) — small, pure, and directly unit-tested; nothing to delete.prefork-style worker fan-out inload_mapped_host_chunks(payload.rs:667-772) — thenextcursor +first_error+cancelshape is the smallest correct form; the only waste is item 8's cancel.config.rs'sload_frontend_innerextraction is a genuine improvement (one body, two callers); the subtraction there is item 11's plumbing around it, not the extraction.format.rs's change is additive data (external_extents) plus a validation range; it is inherited-adjacent and lean as shown.
Highest-leverage single change
Item 9 (RAII on MappedHostAllocation) plus item 2 (one per-rank representation of PendingHostRegistration): together they remove the four duplicated unsafe teardown sites and the three-way state re-encoding in the load path, which are the two places a future edit is most likely to leak a VMA or read into unpinned memory. Neither changes behaviour or performance.
Gates and contracts
Contracts, Charter & Verification Gates Audit — PR #726
Scope: the 4 hard gates only. Algorithm correctness is out of scope. Everything below was verified against the head (60d1b6b) and against merged pr/721 where the PR's diff base makes inheritance ambiguous.
Gate 1 — Signed core-format / wire / captured-graph / public contracts
No new proto, wire, enum, or captured-graph operation contract is added by #726. pr_files shows 8 files, none under helios/proto/, heliopause/, or ignition/. The Memory enum (Device / MappedHost / Peer) is unchanged; only a derive is added (format.rs:51 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]), matching the +1/−1 in pr_files. No PreparedContract field changes. No owner-approval dependency under Principle 1.
Base-artifact warning for reviewers (not a defect): the rendered diff of format.rs shows ExternalExtentTable, Core.external_extents, validate_async_transfers, and ![0, 1, 2].contains(&s.capacity) — all of these already exist at merged pr/721 (helios/src/runtime_core/format.rs:15-21,35,316). None of them are #726's. Likewise prepare_async_transfers, PoolMemoryLimit, and map_device_pool in the mod.rs/model.rs hunks are inherited from merged #709/#711/#721. #726's true format.rs delta is the one-line derive, and its true runtime_core delta is the startup pipeline.
Major M1 — shipped default contradicts normative runtime/format design docs, with no doc update
docs/runtime-core-design.md:1006-1018 and docs/core-format-design.md:853-861 state the loader contract in specific, normative numbers, and #726 replaces all of them unconditionally (no flag, no opt-in):
| Normative text | #726 shipped default |
|---|---|
"Each rank uses four file-reader threads and four pinned staging buffers of 4 MiB / rank_count" (runtime-core-design.md:1010-1011) |
READERS = 8, MAX_CHUNK = 8 MiB, MIN_CHUNK = 1 MiB (payload.rs:143-147) |
| "Total staging is 16 MiB plus at most one 4 KiB alignment block per buffer" (runtime-core-design.md:1011-1012); "Loading retains a process-wide 16 MiB pinned staging bound" (runtime-core-design.md:1095); "The staging bound is process-wide" (core-format-design.md:857-858) | staging = MemAvailable / 200 clamped to 16–128 MiB, divided per rank (payload.rs:148-149,255-262) |
| "Host-resident payloads are copied from staging into their final mapped allocations" (runtime-core-design.md:1016-1017) | zero-copy O_DIRECT pread direct into mapped host memory (payload.rs:355-401, push_span_chunks, load_mapped_host_chunks) |
These are load-path invariants, not TODO bookkeeping: the 16 MiB process-wide staging bound and the staging-copy rule for host payloads are stated as design in two documents and are silently tripled-to-octupled on every core. Per Principle 10 / AGENTS "Use explicit configuration" the new sizes are also derived from environment (/proc/meminfo, /sys/dev/block/*/queue/optimal_io_size) rather than a recipe/config/flag setting, and choose_io_plan exposes no operator control. No documentation file is touched by this PR.
A related, smaller divergence: startup.rs:174-201 re-emits completed phases into normal flare run output with a " · overlapped" suffix appended to the detail, and Allocate model memory's detail now reads "… GiB GPU · … GiB host (overlapping)" in the overlap branch (model.rs:857-864). docs/cli-design.md:1589-1607 and docs/runtime-core-design.md:983-986 describe the stage rows without either; the #[cfg(test)] gate on StartupObservation::completed is also removed (startup.rs:110-125), so production builds now retain every completed snapshot. Undeclared in the PR body.
Major M2 — unconditional MADV_HUGEPAGE contradicts the documented host-mapping THP policy
helios/src/runtime_core/mod.rs:2260-2265 applies libc::madvise(mapped, span_bytes, libc::MADV_HUGEPAGE) with let _ = to every coalesced MappedHost span, with no sysfs policy probe and no fallback.
This is exactly the pattern docs/prefix-cache-offload.md:540-557 documents as not acceptable for host mappings: eos::map_host inspects /sys/kernel/mm/transparent_hugepage/{enabled,defrag,hpage_pmd_size} and deliberately avoids MADV_HUGEPAGE under policies that can trigger synchronous direct compaction, falling back to base pages when huge pages are scarce. That policy was introduced by merged #625 after #616 (a >15-minute host-cache preparation). Here the hazard is re-applied unconditionally to a much larger surface — the 316.6 GiB of MappedHost weights in the PR's own configuration — on a shipped default, and the PR body discloses it only as "coalesced, THP-hinted VMA preparation" and reports AnonHugePages: 94.0 GiB (up from 91.0 GiB) as a benefit. No maintainer decision on deviating from the #625 policy is recorded anywhere in the PR. (I am flagging the contradicted documented policy, not the docs/TODO.txt:1-6 bookkeeping entry.)
Gate 2 — Vendored upstream dependencies & cross-PR conflicts
Clean. No vendored upstream files are touched: no helios/native/roce_proxy.c (not opened), no FlashInfer pin change, no new crate. libc = "0.2.189" is already a pinned dependency (helios/Cargo.toml:50) and the PR reuses crate::os::{allocate_aligned, free_aligned, direct_reopen}. The PR depends on merged #709/#711/#721 and introduces no unmerged dependency without a reference — the body states the measurement build explicitly.
Info / Nit (explicitly not a Blocker): open draft #710 by the same author already contains this PR's coalesced-VMA / MADV_HUGEPAGE / ordered-2 MiB-pre-fault half; #726 neither references nor closes #710. That is PR-description overlap, not a vendored-file or contract violation. It should be resolved (declare an owner for the VMA work) but it is not a gate failure.
Gate 3 — Mandatory verification evidence
Blocker B1 — the performance claim has no attributable main-vs-branch served-workload A/B.
This is a real Layer-3 / Principle 12 failure, on the PR's own words: the 75.0 s → 45.5 s result was measured "via flare run on 1× NVIDIA GB300 (SM103) on the equivalent feat/gb300-tiered-runtime build prior to rebasing cleanly onto main". That means:
- It was not measured on the head
60d1b6b; the body itself says the rebased head has no per-phase numbers. - The baseline is not
main, but a stack branch that also carries #710's VMA/THP/pre-fault work, GB300 AOT compile-pool changes and scheduler hardening. Charter line 40 (#210) requires "benchmarks showing an actual speedup overmainon a served workload", andAGENTS.md:100requires distinguishing "isolated changes from combined-stack results" and "Never attribute a combined result to one PR."
Because the VMA/THP/pre-fault half is also present in #710 on that same branch, the PR's headline — attributed by the body to this change — is not separable from #710. Fix is cheap and mechanical: re-run the per-phase cold startup on 60d1b6b against main (same 552.1 GiB core, same 2× SN850X RAID0, same flare run path) and attach the raw output. Until then the claimed result cannot be checked.
Layer 1 (crate tests): satisfied as reported. helios --features runtime-core,server --lib 1,919 pass / 0 fail / 49 ignored; flare 255/0/4; flare-cli 250/0/3; clean release build. Matches .github/workflows/native-serving.yml (not opened)'s --locked --release matrix per crate, and the counts are internally consistent with #721's 1,904/6-failed (template-gated) run on a slightly older base.
No failing CI or failing tests are reported anywhere in the PR description or the Discovery Dossier — CI on 60d1b6b is pending, not failing, and I do not flag unobservable check runs.
Layer 3 formal/simulator checks: #726 does not touch admission, fences, generations, cancellation, speculation accounting, cache compaction, snapshot aliases, response ownership, offload aggregation, readiness, or rank coordination, and it changes no scheduling/graph-selection/pricing policy, so the TLA+/Kani/scheduling-simulator clauses do not trigger on this diff. The one adjacent reordering — allocate_caches/prepare_offload now run on a background thread and prepare_async_transfers runs at the end of load — is startup allocation ordering rather than lifecycle transitions, but note that docs/runtime-core-design.md:705-740 ties the pinned HOST_POOL clamp to the allocate_caches host ceiling, so a reviewer on the Code Correctness lens should confirm that ordering; it is not a formal-model gate hit.
Core-format gate: no format/wire change, so live export/re-export and legacy-core replay are not newly required; existing fixture replay is covered by the Layer 1 suite.
Gate 4 — Material scope / claim contradictions
Major M3 — the "6 new unit tests" count is wrong; 5 are new. The five genuinely new tests are payload.rs:989, payload.rs:1013, payload.rs:1071, mod.rs:2433, mod.rs:2460 (startup_overlap_tests). The sixth claimed test, model.rs::async_transfers_reject_peer_copy_graphs_at_load_time, already exists at merged pr/721 (helios/src/runtime_core/model.rs:1517) — verified directly at that ref. The evidence section presents it as new work for this PR.
No bundled unrelated tooling, no fabricated artifacts. All 8 changed files are in scope (server/config.rs (not opened)'s PreloadedFrontend/frontend_cache_key work is described in prose even though it is missing from the "What Changed" file inventory). No invented benchmark or test is claimed to exist that is absent from the diff — the sole miscount is M3.
Info / Nit: mod.rs:22 changes #[cfg(any(windows, test))] mod host; to pub mod host;, expanding helios's public API on all platforms; mod.rs:779 uses unreachable!("non-unix platforms always set host_vmm = true") on the non-Unix branch — an assertion, not a fallback, on the Windows path that the PR declares unexecuted on hardware. Both are worth a note in the PR body rather than a gate failure.
Verdict
Not mergeable as-is: 1 Blocker, 3 Majors.
- Blocker B1: Re-measure the rebased head
60d1b6bagainstmainon a servedflare runworkload and attach raw output. The current numbers are pre-rebase, on a different branch, and inseparable from #710's VMA/THP work — this violates Principle 12 andAGENTS.md:100, and charter #210. - Major M1: Update
docs/runtime-core-design.md:1006-1018, 1095anddocs/core-format-design.md:853-861for 8 readers / 8 MiB chunks / 16–128 MiB runtime-sized staging / zero-copy host payloads, and document the new stagedflare runrows (" · overlapped") and theAllocate model memorysplit indocs/cli-design.md:1589-1607. Or make the plan sizes operator-configurable per Principle 10. - Major M2: Gate or justify the unconditional
MADV_HUGEPAGE(mod.rs:2264) against the documented policy indocs/prefix-cache-offload.md:540-557and merged #625, and declare it in the PR body as a THP-policy change. - Major M3: Correct "6 new unit tests" to 5; the sixth is #721's.
Gate 2 is clean (no vendored files, no unmerged external dependencies, libc already pinned). #710 overlap and the pub mod host / unreachable! items are Info/Nit, not blockers.
Code correctness
Deep Code Correctness / Invariants / Hot-Path Audit — PR #726 @ 60d1b6b
Partitioning: PR is ~1,885 changed lines over 8 files in 2 subsystems, so it was split into 3 concurrent slices: (s1) runtime_core/payload.rs + format.rs, (s2) runtime_core/mod.rs, (self) runtime_core/model.rs + server/{config,session,server}.rs + startup.rs. Findings below were re-verified by me at 60d1b6b with direct read_file (quotes are verbatim from the verified reads).
Finding 1 — Major: register_pending_mapped_host returns from inside its unsafe block, so RegistrationGate::close() is skipped on every error path
Diff site: helios/src/runtime_core/mod.rs:786-847
Callee definitions: helios/src/runtime_core/payload.rs:583-630 (RegistrationGate; advance 608-612, close 614-618, wait_for 620-629)
Consumer of the gate: payload.rs:691-696 (reader park), caller model.rs:1152-1170
// mod.rs:804-818, 831-847 (verbatim)
let result = unsafe {
driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?;
for (chunk_addr, chunk_bytes, flags) in pending.chunks {
if cancel.load(Ordering::Relaxed) {
break;
}
driver.check(
"cuMemHostRegister_v2",
(driver.host_register)(chunk_addr as Handle, chunk_bytes, flags),
)?;
self.host_registrations.push(chunk_addr);
if let Some(gate) = gate {
gate.advance();
}
}
...
driver.check(
"cuMemHostGetDevicePointer_v2",
(driver.host_device)(&mut gpu, address as Handle, 0),
)?;
if gpu != address {
return Err(invalid(
"mapped host address differs from recorded CUDA address",
));
}
...
};
if let Some(gate) = gate {
gate.close();
}
result
Why it is a defect: an unsafe { ... } block is not a closure. Every ? (lines 805, 810-813, 831-834) and the explicit return Err(...) at 836-839 return from register_pending_mapped_host, not from the block — they bypass the unconditional gate.close() at 844-846, and result is never bound. The function is the only party that can publish "no more registration chunks are coming", so its failure path is exactly the path where readers need that signal.
// payload.rs:620-629 (verbatim, callee)
fn wait_for(&self, required: usize, cancel: &AtomicBool) -> bool {
if self.chunk_ends.is_empty() {
return !cancel.load(Ordering::Relaxed);
}
let mut state = self.state.lock().unwrap();
while state.0 <= required && !state.1 && !cancel.load(Ordering::Relaxed) {
state = self.ready.wait(state).unwrap();
}
state.0 > required && !cancel.load(Ordering::Relaxed)
}
wait_for unblocks only on state.0 > required, state.1 == true (i.e. close()), or cancel.
Concrete counterexample: the PR's own measured workload — 316.6 GiB of MappedHost on one GPU → ~620 × 512 MiB registration chunks. cuMemHostRegister_v2 fails on chunk 3 (pinned-memory exhaustion / RLIMIT_MEMLOCK, a realistic risk at 316 GiB of pinning). The function returns Err with state == (2, false) and no close(). Host readers assigned a chunk whose required_index >= 2 (readers at payload.rs:691-696; the chunk list is pre-sorted by required_index at payload.rs:646) park in Condvar::wait forever. Today the hang does not materialize only because the sole gated caller model.rs:1152-1170 reacts to the propagated Err with cancel.store(true) + for gate in gates_ref.iter().flatten() { gate.close(); }; payload.rs:206's second gated call site passes None at model.rs:1206. So the correctness requirement is undocumented and unenforced at the site that documents it (the unconditional close plus the "signaling gate after each chunk" contract).
Fix: make the cleanup structurally unconditional, e.g.
let result = (|| -> Result<()> { unsafe { /* ...existing body... */ } })();
if let Some(gate) = gate { gate.close(); }
result
or use a Drop scope guard so close() also runs on unwind.
Finding 2 — Major: load_mapped_host_chunks reports Ok(()) after silently dropping unread MappedHost chunks, and the Load weights total under-counts
Diff site: helios/src/runtime_core/payload.rs:682-696 (reader break), :751 (advance_bytes), :774-777 (return)
Callees: payload.rs:620-629 (wait_for, cited above); caller model.rs:1096-1142, model.rs:1180, model.rs:1188-1191
// payload.rs:682-696 (verbatim)
loop {
if cancel.load(Ordering::Relaxed) {
break;
}
let idx = next.fetch_add(1, Ordering::Relaxed);
if idx >= chunks.len() {
break;
}
let chunk = &chunks[idx];
if let Some(gate) = gate {
let required = gate.required_index(chunk.destination, chunk.nbytes);
if !gate.wait_for(required, cancel) {
break;
}
}
// payload.rs:774-777 (verbatim)
if let Some(error) = first_error.into_inner().unwrap() {
return Err(error);
}
Ok(())
Why it is a defect: a worker that leaves via break at line 694 records no error; first_error stays None and the function returns Ok(()). wait_for returns false not only on cancel but also when the gate was merely closed (line 628: state.0 > required && !cancel.load(...) is false when state.1 short-circuited the loop while state.0 <= required). Unread chunks therefore vanish behind a success return, and phase.advance_bytes(chunk.nbytes) at 751 is never reached for them, so load_phase.finish(...) at model.rs:1188-1191 prints a Load weights byte total (payload_bytes) that the readers did not actually stream.
Also note the same root cause produces the exact stall described in Finding 1: after register_pending_mapped_host returns early at mod.rs:807-809 (if cancel.load(...) { break; }), the loop exits with gate.close() at 844 reached but state.0 never covering the remaining chunks — those readers then break here and are counted as success.
Concrete counterexample: chunk_ends = [e0, e1, e2], cancel set after 2 registrations. Reader idx with required == 2 calls wait_for(2, cancel); gate closes with state == (2, true); wait_for returns false; reader breaks; first_error == None; load_mapped_host_chunks returns Ok(()) while every chunk mapped into registration window 2 is never read — a partially populated MappedHost weight region presented as a successful load. Currently masked only because model.rs:1112-1141 sets cancel from a different failing worker and model.rs:1165-1170 turns the sibling runtime_result into an Err.
Fix: (a) return an error instead of break for !wait_for(...) (or set first_error there), and (b) after the joins, verify completeness against an AtomicUsize of completed chunks and fail with e.g. invalid("mapped host payload load incomplete") if it is less than chunks.len(). That also restores the honesty of the Load weights byte total.
Finding 3 — Minor: Load weights progress accounting mixes a pre-computed total with per-chunk increments from N threads
Site: helios/src/runtime_core/model.rs:838-856 (total payload_bytes = device_payload_bytes + host_payload_bytes), model.rs:1096-1104 (readers), payload.rs:751 (phase.advance_bytes)
payload_bytes is computed once as device_payload_bytes + host_payload_bytes, but the host half is advanced by up to plan.readers (8) concurrent reader threads per rank (payload.rs:667, model.rs:1096-1104), while the device half is advanced by load_device's staging path. Combined with Finding 2 (dropped chunks never advance), the phase total can end at a value below the declared maximum with no error — visible as a stalled/incorrect progress row in StartupProgress::replay_completed (startup.rs:178, fed at model.rs:1192). Fix follows from Finding 2; additionally summing per-tier byte totals (device vs host) as separate phases would make the row self-checking. Not a data-correctness bug on its own.
Functions audited and cleared (with the counterexamples applied)
choose_io_plan(payload.rs:205-251) —ranks = 0/cpus = 0handled viamax(1);ranks = 3→8 MiB/3re-rounded bynext_multiple_of(BLOCK)(227);optimal_io_size∈ {0, 1, 4095, non-power-of-two 1.5 MiB, > MAX_CHUNK} all safe (guards 220-231); budgetsaturating_mul/add, clamped to[16 MiB, 128 MiB];slots ≥ 2whenever staging is used (242), so noSLOTS = 2*READERSunderflow.- Zero-copy alignment split (
Chunk::read_range346-389,can_read_direct_into_host355-361,push_span_chunks425-480) — the "unaligned O_DIRECT tail" hypothesis is not a bug:chunk_bytesis unconditionally rounded to 4096 (227), so every body chunk hasnbytes % BLOCK == 0; head (< 4096) and sub-block tails always take the staged path;file_offset % BLOCK != destination % BLOCKfalls back to staged (slower, correct); zero-byte spans rejected atformat.rs:332. Chunk::readshort-read handling (377) —done % BLOCK != 0 ⇒ UnexpectedEofonly seesO_DIRECT/FILE_FLAG_NO_BUFFERINGhandles (crate::os::direct_reopen, used atpayload.rs:701/839), where short reads are block multiples; thedone..nbytesslice is always inside the buffer sized fromread_range().2.RegistrationGate::required_index(598-606) — correct fornbytes == 0(→0), emptychunk_ends(→0), a chunk straddling two 512 MiB windows (higher index required; matches the unit test at 1075), andpartition_pointon monotone ascending ends;state.0is monotone so no ABA;advance/closemutate+notify_allunder the same mutexwait_forwaits on, so no lost wakeup.collect_tier_chunks/tier_io_plan(482-578),load_device(785-929) — Device/MappedHost filters are disjoint so nothing is loaded twice;checked_addguards source-offset math (542-544); sizing allocations (stored_bytes() == 0) skipped; slot/sync-channel direction,count == 1single-slot case, and the early-?path (both channel ends drop, so the scope join cannot hang) re-traced; removing theMappedHostbranch is safe because the chunk list is Device-only.allocate_device(mod.rs:553-673) —Memory::MappedHostfiltered at 580 so theunreachable!()at 631 is genuinely unreachable; device footprint useschecked_add; mappings recorded only forDevice+fixed.prepare_mapped_host_vmas(mod.rs:2175-2376) — span coalescing is a sorted single pass (not O(n²));checked_addon the merge;cleanupmunmaps in reverse; cancellation returnsOk(default)after cleanup;prefault_slicesstarts at the next 2 MiB boundary and stops beforeend_addr(no write past the mapping, including0x2000_0000 + 1 MiB);workers = (cpus / ranks.clamp(1)).clamp(1,8).min(slices.len().max(1))bounds fan-out (no thread-per-2 MiB on a 300 GiB tier); the function makes no driver call at all, so the claimed "no CUDA context lock held during host VMA prep" holds.registration_chunks(mod.rs:2408-2426) —checked_addon ends,saturating_add + & !(align-1), never emits zero-length chunks, handles span < 512 MiB and exactly 512 MiB; callers pass onlyspan_bytes > 0.flagsbranch at 2204-2208 is dead (peer readers are keyed byDeviceaddresses only) but harmless.- Teardown order (
mod.rs:2015-2042) — reverse order is correct: per-allocation storage →host_registrationsreversecuMemHostUnregister→host_mmap_spansreversemunmap→host_mappingsreversecuMemUnmap;host_vmmnever populates the new vectors, so nothing is double-freed.pushintohost_registrationshappens only after a successful register (814), so a failed chunk is never recorded unregistered. format.rs:316(|| ![0,1,2].contains(&s.capacity)) — widening validation toCapacity::DEVICE_POOLis consistent:Allocation::extent()(99-103, bounded 321-324) still correct; cache geometry only treats capacities 0/1 as KV planes and rejectsDEVICE_POOLexplicitly; no defect.model.rsoverlap wiring (1090-1226) —collect_mapped_host_chunkssorts byrequired_index(646) and destination ranges are built per coalesced span in ascending order, sochunk_endsis monotone; readers are joined beforehost_load_result?/runtime_result?;pending_slotsMutex<Vec<Option<..>>>indexing byrank.rankis 1:1 with(0..devices.len());replay_completed(startup.rs:178) re-emits completed stage rows so the canonical order is preserved; no double-free or use-after-join.- Tokenizer pre-load (
model.rs:702-720,1222-1225) —is_none_or(|c| c.rank == 0)plusspawn().ok()means a spawn failure degrades toNoneandLoadedSession::newrecomputes;join().ok().flatten()swallows a panicked preload thread without poisoning startup. No defect.
Not confirmed (flagged for the author, not claimed as verified findings)
mod.rs:721-781+2274-2331: device-payload failure sets aRelaxedcancelthat the pre-fault workers only observe at slice granularity; if observed after the slice loop but beforecleanup(&mut outcome), or afterhost_resultreturnsOk, thedevice_result?at 768 can tear downNativeResources(munmappinghost_mmap_spansat 2037-2039) while astd::ptr::write_volatile(cur as *mut u8, 0)fault write (2292) is still in flight — a write-after-unmap window. I did not independently re-read those exact lines before the deadline, so this is reported as needs-verification, not as a proven finding; the fix would be per-2 MiBcancelchecks plus joining active fault threads beforecleanup.
Bottom line
Two verified defects (both Major, both in the new gate/error contract between register_pending_mapped_host and load_mapped_host_chunks): the unconditional RegistrationGate::close() is unreachable on every failure path because ? sits inside an unsafe block rather than a closure, and the host reader loop converts a closed-but-unpublished gate into a silent Ok(()) with unread MappedHost chunks and a short Load weights byte total. Both are currently masked by model.rs:1165-1170's cancel-and-close-all-gates fallback, which is why they are Major rather than Blocker — but the invariant lives entirely outside the function that documents it. The headline mechanics — runtime IoPlan sizing, 4 KiB zero-copy/staged-edge splitting, RegistrationGate ordering, 512 MiB registration chunking, ordered 2 MiB pre-faulting, and reverse-order teardown — survived all boundary and adversarial checks I applied (tiny/huge optimal_io_size, ranks = 0/1/N, sub-block tails, straddling chunks, SLOTS = 2*READERS), and I found no hot-path big-O or per-iteration-allocation regression in the changed loops.
Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.
Final review
Recommendation: Changes Requested
PR #726 tackles a real startup bottleneck in the right shared runtime layer (helios/src/runtime_core), and its core mechanics—4 KiB-aligned zero-copy MappedHost reads with staged edges, 512 MiB registration chunking, RegistrationGate ordering, and reverse-order VMA/registration teardown—hold up well under boundary review. However, the PR is not ready to merge as-is: the headline 75.0 s → 45.5 s speedup was measured pre-rebase on the combined feat/gb300-tiered-runtime stack (#710) rather than on head 60d1b6b against main (violating Charter #210 / Principle 12 / AGENTS.md:99-100), and independent verification confirmed four real issues that should be fixed before merge: error-path RegistrationGate::close() bypass in register_pending_mapped_host, silent partial-load Ok(()) / unwoken sibling waiters in load_mapped_host_chunks, unconditional MADV_HUGEPAGE + 8-thread eager pre-faulting reintroducing the #616/#625 THP compaction-stall hazard, and un-updated normative loader/CLI docs paired with a multi-rank staging-cap overshoot in choose_io_plan.
Merge Risk
Level: High
- Shared startup critical path: Rewrites host allocation, weight loading, registration ordering, and background setup orchestration for all cores across
helios/src/runtime_core/{payload,mod,model}.rs(+1,886/−385across 8 files), with only 5 new CPU-only unit tests and no automated GPU or multi-rank startup coverage. - Self-disclosed unrun hardware paths:
host_vmm(Windows and non-identity-mapped Linux GPUs), integrated-GPUmlock,async_transfers, and multi-rank TP startup overlap were not executed on hardware; additionally, the unconditionalMADV_HUGEPAGE+ parallel pre-fault path has not been validated on fragmented SM120/SM121 Linux memory (defrag=madvise). - Stale diff base & active concurrent PRs: The PR diff base predates merged #709/#711/#721 (creating inherited diff noise), duplicates the host-VMA half of open draft #710 by the same author, and overlaps
model.rs/startup.rs/mod.rswith open #696 and #723.
Walkthrough
helios/src/runtime_core/payload.rs(+689/−80): Replaces fixed4 MiB / 4 readers / 4 slotsstaging constants with runtimeIoPlan(choose_io_plan,detect_optimal_io_size,available_host_memory_bytes), splitsDeviceloading (load_device) from CUDA-freeMappedHostloading (collect_mapped_host_chunks,load_mapped_host_chunks), addspush_span_chunks/read_direct_into_hostfor 4 KiB-aligned zero-copyO_DIRECTreads withAlignedBufferbounce fallback for unaligned edges, and introducesRegistrationGate. Adds 3 unit tests.helios/src/runtime_core/mod.rs(+618/−86) &format.rs(+1/−1): DerivesPartialEq, EqonMemory(format.rs:51); splitsallocate()intoallocate_device,allocate_mapped_host_vmm,prepare_mapped_host_vmas(coalescedMAP_FIXED_NOREPLACEVMAs, LinuxMADV_HUGEPAGE, ordered 2 MiB-strided multi-threaded pre-faulting without CUDA context locks),load_device_overlapping_mapped_host, andregister_pending_mapped_host(512 MiBchunkedcuMemHostRegister_v2signalingRegistrationGate, followed bycuMemHostGetDevicePointer_v2identity checks); tracks Unixhost_registrationsandhost_mmap_spansseparately for reverse-order teardown (release_execution_resources). Adds 2 unit tests (startup_overlap_tests).helios/src/runtime_core/model.rs(+402/−152): Overlapsprepare_mapped_host_vmaswithload_device_payloadwhenhost_bytes > 0 && device_payload_bytes > 0, and overlaps chunkedregister_pending_mapped_host+prepare_runtime(kernels, graphs, embedding tables,allocate_caches,prepare_offload) withload_mapped_host_chunkswhenhost_payload_bytes > 0, runningapply_payload_relocationsandprepare_async_transfersafter both join; spawns a backgroundflare-frontend-preloadthread on rank 0.helios/src/startup.rs(+31/−8): Removes#[cfg(test)]fromStartupObservation.completed/completed_phases()and addsStartupProgress::replay_completedto re-emit overlapped background stages with" · overlapped"detail while preserving original elapsed durations.helios/src/server/{config.rs,session.rs}&helios/src/server.rs(+145/−58): Extractsload_frontend_inner, addsPreloadedFrontend/preload_frontend/frontend_cache_key/Bootstrap::load_with_preloaded, and consumesowner.take_preloaded_frontend()inLoadedSession::new.
Pre-merge Checks
- [PASS] Security / malicious screen: Standard read-only
/proc/meminfoand/sys/dev/block/*/queue/optimal_io_sizeprobes plusmmap/madvise/mlock/munmapand existingflare_eosdirect I/O helpers; no new external crates, no env-var behavior switches, no untrusted input parsing hazards. - [WARN] Charter & value fit: Right problem in the right model-agnostic runtime layer with no package/ABI/captured-graph contract changes; however, the performance claim is pre-rebase from combined-stack branch #710 rather than
60d1b6bvsmain(Blocker #1), and unconditionalMADV_HUGEPAGE+ undocumented staging changes conflict with established host-mapping policy (#625) and design docs (Should Fix #3–#4). - [WARN] Related / duplicate / conflict check: Subsumes the host-VMA coalescing/THP/pre-fault portion of the author's own open draft #710 without referencing or resolving ownership between #710 and #726; rebase/merge-order coordination needed with open #696 (
model.rs,startup.rs) and #723 (mod.rs,model.rs). - [WARN] Tests & verification evidence: Reported
--locked --releaseCPU test suites (helios1,919,flare255,flare-cli250) and release build are plausible and consistent with recentmain, with 5 genuinely new unit tests (not 6; see Nits); however, CI status on60d1b6bis pending/unobservable here, and servedflare runA/B benchmarks on60d1b6bvsmainare missing (Blocker #1).
Blockers
- Performance claim is not measured on
60d1b6bagainstmain(combined-stack pre-rebase result from #710) — PR description ("Supporting Evidence and Limitations") vs Charter (#210),docs/design-review.md:109-115(Principle 12), andAGENTS.md:99-100.- Verified issue: The PR states that the
75.0 s → 45.5 scold-start measurement was collected "on the equivalentfeat/gb300-tiered-runtimebuild prior to rebasing cleanly ontomain". That branch is open draft #710, which also includes the host-VMA/THP/pre-fault changes (helios/src/runtime_core/mod.rs+120/−44), speculative cost/forecast changes, and GB300 AOT updates. Charter #210 requires performance PRs to show "an actual speedup overmainon a served workload", andAGENTS.md:99-100explicitly prohibits attributing a combined-stack measurement to a single PR. - Fix: Re-run the
flare runcold-startup A/B benchmark on rebased head60d1b6bdirectly against currentmain(attaching the raw per-phase timing output and hardware/THP configuration) and clarify ownership of the duplicated VMA work relative to #710.
- Verified issue: The PR states that the
Should Fix
-
register_pending_mapped_hostbypassesRegistrationGate::close()on every error path —helios/src/runtime_core/mod.rs:804-847(calleehelios/src/runtime_core/payload.rs:583-630; callerhelios/src/runtime_core/model.rs:1152-1170, 1359-1390).- Verified issue: Lines
804-843place?(805, 810-813, 831-834) andreturn Err(...)(836-839) directly inside anunsafe { ... }block rather than an immediately invoked closure. In Rust, those return immediately fromregister_pending_mapped_host, completely skippingif let Some(gate) = gate { gate.close(); }at844-846. In single-rank startup,model.rs:1165-1170happens to close all gates afterruntime_resultreturns, masking a permanent deadlock—but in multi-rank TP (devices.len() > 1),model.parallel(model.rs:1380-1388) joins every rank thread before returningErrto line1165, so a failing rank leaves its host readers parked until every other rank finishes registering all512 MiBchunks (and any direct caller relying onregister_pending_mapped_host's contract would deadlock permanently). - Fix: Wrap the body in
(|| -> Result<()> { unsafe { ... } })()(or aDropguard that closesgateeven on unwind) sogate.close()is structurally guaranteed on every return path.
- Verified issue: Lines
-
load_mapped_host_chunkssilently returnsOk(())on premature non-cancelled gate closure and does not wake parked sibling readers on I/O error —helios/src/runtime_core/payload.rs:682-696, 754-777(calleepayload.rs:620-629; callermodel.rs:1085-1143, 1180-1181).- Verified issue: Two error-handling defects in the host reader loop:
- At
payload.rs:691-696, when!gate.wait_for(required, cancel), the worker simplybreaks without recording an error. Ifgate.close()occurred before chunkrequiredwas registered whilecancel == false,load_mapped_host_chunksreturnsOk(())with unread/zeroedMappedHostweight chunks and an under-countedLoad weightsprogress total. (Note: whencancel == truedue to an external failure inruntime_result, returningOk(())is needed somodel.rs:1180-1181surfacesruntime_result's root error rather than a synthetic cancellation error—so the error should fire specifically when!cancel.load(Ordering::Relaxed).) - At
payload.rs:754-761, when a reader encounters an I/O error, it setscancel.store(true, Ordering::Relaxed)without callinggate.close(). Any sibling reader on the same rank already parked inCondvar::wait(payload.rs:626) will not wake untilregister_pending_mapped_hostfinishes its in-flight512 MiBcuMemHostRegister_v2call and closes the gate (andmodel.rs:1117cannot close gates untilload_mapped_host_chunksjoins all sibling readers).
- At
- Fix: On
!gate.wait_for(required, cancel)when!cancel.load(Ordering::Relaxed), record an error infirst_error(e.g.invalid("mapped host registration closed before chunk was ready")) and setcancel. On reader error atpayload.rs:754-761, also callif let Some(gate) = gate { gate.close(); }so parked sibling readers wake immediately.
- Verified issue: Two error-handling defects in the host reader loop:
-
Unconditional
MADV_HUGEPAGE+ 8-thread eager pre-faulting reintroduces the #616/#625 THP compaction-stall hazard —helios/src/runtime_core/mod.rs:2260-2265, 2274-2324vsdocs/prefix-cache-offload.md:540-557and merged #625.- Verified issue: Prior
main(pr/721mod.rs:623-658) did not callMADV_HUGEPAGEor pre-faultMappedHostspans. #726 unconditionally issueslibc::madvise(mapped, span_bytes, libc::MADV_HUGEPAGE)on every coalescedMappedHostspan (316.6 GiBin the PR's workload) and immediately faults it at2 MiBstride across up to 8 concurrent threads (mod.rs:2288-2324). Under Linux's default workstation THP settings (enabled=madvise, defrag=madviseordefer+madvise) on fragmented memory, this triggers synchronous direct reclaim/compaction (__GFP_DIRECT_RECLAIM) on every hugepage fault—the exact stall that caused #616 (>15 minutes on119 GiB) and that merged #625 retired ineos::map_host(docs/prefix-cache-offload.md:541-557, where #625 measured128.6 svs31.0 sfor just48 GiBon SM120). - Fix: Inspect
/sys/kernel/mm/transparent_hugepage/{enabled,defrag}(reusing or sharingeos/src/unix.rs's Linux THP policy logic) soMADV_HUGEPAGEis only applied unconditionally under non-blocking defrag policies (defer/never), or falls back cleanly to base pages when huge pages are scarce /compact_stallclimbs; disclose the THP policy behavior explicitly in the PR description.
- Verified issue: Prior
-
Normative loader/CLI design docs contradict the shipped changes, and
choose_io_plancan exceed its stated128 MiBcross-rank staging bound at high rank counts —helios/src/runtime_core/payload.rs:143-150, 205-251,helios/src/startup.rs:178-203,helios/src/runtime_core/model.rs:858-862vsdocs/runtime-core-design.md:1006-1018, 1095,docs/core-format-design.md:853-861,docs/cli-design.md:1589-1607.- Verified issue:
docs/runtime-core-design.md:1010-1018, 1095specifies 4 reader threads, 4 pinned staging buffers of4 MiB / rank_count, a16 MiBprocess-wide staging bound, staging copies for host-resident payloads, and readers joining before module/graph setup.docs/core-format-design.md:857-858states "The staging bound is process-wide; adding ranks must not multiply it."docs/cli-design.md:1589-1607describes startup rows without the new" · overlapped"replay suffix (startup.rs:186) or"(overlapping)"allocation detail (model.rs:859). None of these docs are updated.- In
choose_io_plan(payload.rs:222-244),optimal_io_sizecan roundchunk_bytesup toMAX_CHUNK(8 MiB) without dividing byranks, whileper_rank_budgetclamps at.max(chunk_bytes * 2)(240) andbudget_slotsclamps at.max(2)(242). On multi-rank setups with a largeoptimal_io_sizeor tight RAM (e.g.,ranks = 16, optimal_io_size = 8 MiB), total pinned staging across ranks reaches16 × 2 × 8 MiB = 256 MiB, violating bothdocs/core-format-design.md:857-858and the PR's claimed<= 128 MiBcross-rank cap.
- Fix: Cap
chunk_bytes(including afteroptimal_io_sizerounding) against(total_budget / ranks / 2)so multi-rank staging cannot exceedtotal_budget(<= 128 MiB), add a unit test assertingranks * slots * (chunk_bytes + 2 * BLOCK) <= MAX_STAGING_BYTESacross TP1/TP4/TP8/TP16, and updatedocs/runtime-core-design.md,docs/core-format-design.md, anddocs/cli-design.mdto document the new runtime staging budget, zero-copy host loading, and overlapped stage output.
- Verified issue:
Subtract / Simplify
- Replace four duplicated
cleanup(&mut outcome)sites with RAIIDroponMappedHostAllocation—helios/src/runtime_core/mod.rs:2167-2170, 2230-2258, 2325-2342. ImplementingDropto reverse-munmapself.mappings(disarmed whenattach_mapped_hostdrainsmappingsintoself.host_mmap_spans) eliminates thecleanupclosure and all four manual error/cancel teardown blocks while mechanically enforcing theSAFETYcomment at line2187. - Deduplicate the
read_atshort-read loop inChunk::readandChunk::read_direct_into_host—helios/src/runtime_core/payload.rs:363-422. Both implement identicalInterrupted-retry, EOF, andBLOCK-alignment checks; extracting onefn read_full_at(file: &File, offset: u64, dst: &mut [u8]) -> io::Result<()>removes ~25 duplicated lines. - Hoist the duplicated post-load tail and simplify
pending_registrationsround-tripping inNativeModel::load_agreeing—helios/src/runtime_core/model.rs:882-906, 1146-1155, 1182-1217. The four post-load statements (apply_payload_relocations, integratedrelease_page_cache,load_phase.finish) are identical in both arms (1182-1191and1208-1217), andpending_registrationsis convertedVec → Mutex<Vec<Option>> → Vec → Mutex<Vec<Option>>with silentunwrap_or_default()fallbacks. - Remove dead tuple element from
tier_io_planand redundantoptimal_io_sizebounds check —helios/src/runtime_core/payload.rs:173-175, 222, 482-522, 640, 792. Both callers discardtier_io_plan's second return value(plan, _), andchoose_io_plan:222re-checks the exactBLOCK..=MAX_CHUNK/% BLOCK == 0predicate already enforced bydetect_optimal_io_size:173-175. - Unify
PendingHostRegistrationplatform fields andRegistrationGateemptiness checks —helios/src/runtime_core/mod.rs:2132-2163, 797-856,model.rs:1053-1059,payload.rs:599, 621. MakingPendingHostRegistration.chunks: Vec<(u64, usize, u32)>unconditional (always empty off-Unix) removes redundant#[cfg(not(unix))]arms and duplicated emptiness checks. - Keep
StartupObservation.completedretention opt-in —helios/src/startup.rs:111-113, 136-138, 170-175. Onlymodel.rs:1075(overlapped background phases) and tests callcompleted_phases(); making completion retention opt-in avoids cloning and retaining every completed snapshot across all non-overlapping observed loads.
Nits
- Cluster rank 0 preloads the frontend twice:
helios/src/runtime_core/model.rs:709-720spawnsflare-frontend-preloadwhencluster.is_none_or(|c| c.rank == 0), buttake_preloaded_frontend()is only consumed inLoadedSession::new(helios/src/server/session.rs:27-36, which rejects clustered models); multi-host rank 0 inflare-cli/src/main.rs:638callsBootstrap::loaddirectly, discarding the preloaded frontend. Either gate preloading onmodel.cluster.is_none()or wire cluster rank 0 to consume it. - Silent preload error swallowing:
helios/src/runtime_core/model.rs:717-718, 1224swallows preload errors via.ok()/.flatten(), so a broken preload silently falls back to synchronous loading without telemetry or warning. - PR description test count: The PR body claims "6 new unit tests", whereas 5 are newly added by this PR (
payload.rs:989, 1013, 1071andmod.rs:2433, 2460);model.rs::async_transfers_reject_peer_copy_graphs_at_load_timealready existed on mergedpr/721(model.rs:1517).
Dropped on verification
- Unconfirmed write-after-unmap window during device-payload failure (
mod.rs:721-781+2274-2331) — Dropped (false): Insideprepare_mapped_host_vmas,std::thread::scope(mod.rs:2308-2324) joins every pre-fault worker before line2325and before returning; outside,load_device_overlapping_mapped_host(mod.rs:734-763) joinshost_workerbeforeattach_mapped_hostanddevice_result?(767-768). No fault write can outlive unmap. pub mod host;API expansion andhost_vmmintroduction (mod.rs:22, 369) — Dropped (false / diff-base artifact): Verified directly at mergedpr/721:helios/src/runtime_core/mod.rs:22already hadpub mod host;andmod.rs:365already hadlet host_vmm = host::use_host_vmm(&driver, device)?;.engram::reader::AlignedlacksDropand leaks (helios/src/engram/reader.rs:130-141) — Dropped (false): Verified athelios/src/engram/reader.rs:456-459thatimpl Drop for Alignedexists and callscrate::os::free_aligned(self.0, self.1).helios/src/server/config.rsomitted from the PR description's file list — Dropped (false):helios/src/server/config.rsis explicitly listed in the third bullet of## What Changed.- "All-host cores take the old serial path" (
model.rs:850) — Dropped (inaccurate):overlap_host_alloc(model.rs:850) only gates overlapping host VMA prep withDeviceweight uploads; all-host cores (host_payload_bytes > 0 && device_payload_bytes == 0) still take themodel.rs:1048branch overlappingMappedHostweight loading withprepare_runtime. Load weightsmulti-thread progress accounting defect (Code Correctness Finding 3) — Dropped (duplicate):Phase::advance_bytes(startup.rs:326-336) is mutex-serialized and exact; under-counting only occurs as a secondary symptom of Should Fix #2 (premature gate close).State.elapsedonly used to smuggle duration throughpublish— Dropped (inaccurate):State::render(startup.rs:439-442) also readsself.elapsedwhen writing replayed rows to stderr.- Unobservable CI status and open-PR overlap with #710/#696/#723 as blockers — Dropped from Blockers/Should Fix: Kept appropriately in
## Pre-merge Checksand## Merge Risk.
Classify triage
Selected: triage:review
Threshold: 65%
Triage
- [✓]
triage:review: 96.2% -
triage:validation: 3.3% -
triage:design-review: 0.4% -
triage:investigate: 0.0% -
triage:integration: 0.0% -
none: 0.0% -
triage:partial: 0.0% -
triage:superseded: 0.0% -
triage:verify-for-closure: 0.0%
Apply labels
No label changes Decision to Test: no (100%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.