PR #726: helios: overlap startup allocation, registration, and setup with runtime-sized zero-copy weight loading

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/7af77bcf-c5a1-46d4-a1d4-51a6729a838c

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:

Full report · Notes

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

Priority

Type

Area

Model

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

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

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

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:

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

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

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.

Full report

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:

  1. It was not measured on the head 60d1b6b; the body itself says the rebased head has no per-phase numbers.
  2. 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 over main on a served workload", and AGENTS.md:100 requires 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.

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.

Full report

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)

Not confirmed (flagged for the author, not claimed as verified findings)

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

Walkthrough

Pre-merge Checks

Blockers

  1. Performance claim is not measured on 60d1b6b against main (combined-stack pre-rebase result from #710) — PR description ("Supporting Evidence and Limitations") vs Charter (#210), docs/design-review.md:109-115 (Principle 12), and AGENTS.md:99-100.
    • Verified issue: The PR states that the 75.0 s → 45.5 s cold-start measurement was collected "on the equivalent feat/gb300-tiered-runtime build prior to rebasing cleanly onto main". 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 over main on a served workload", and AGENTS.md:99-100 explicitly prohibits attributing a combined-stack measurement to a single PR.
    • Fix: Re-run the flare run cold-startup A/B benchmark on rebased head 60d1b6b directly against current main (attaching the raw per-phase timing output and hardware/THP configuration) and clarify ownership of the duplicated VMA work relative to #710.

Should Fix

  1. register_pending_mapped_host bypasses RegistrationGate::close() on every error path — helios/src/runtime_core/mod.rs:804-847 (callee helios/src/runtime_core/payload.rs:583-630; caller helios/src/runtime_core/model.rs:1152-1170, 1359-1390).

    • Verified issue: Lines 804-843 place ? (805, 810-813, 831-834) and return Err(...) (836-839) directly inside an unsafe { ... } block rather than an immediately invoked closure. In Rust, those return immediately from register_pending_mapped_host, completely skipping if let Some(gate) = gate { gate.close(); } at 844-846. In single-rank startup, model.rs:1165-1170 happens to close all gates after runtime_result returns, masking a permanent deadlock—but in multi-rank TP (devices.len() > 1), model.parallel (model.rs:1380-1388) joins every rank thread before returning Err to line 1165, so a failing rank leaves its host readers parked until every other rank finishes registering all 512 MiB chunks (and any direct caller relying on register_pending_mapped_host's contract would deadlock permanently).
    • Fix: Wrap the body in (|| -> Result<()> { unsafe { ... } })() (or a Drop guard that closes gate even on unwind) so gate.close() is structurally guaranteed on every return path.
  2. load_mapped_host_chunks silently returns Ok(()) 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 (callee payload.rs:620-629; caller model.rs:1085-1143, 1180-1181).

    • Verified issue: Two error-handling defects in the host reader loop:
      1. At payload.rs:691-696, when !gate.wait_for(required, cancel), the worker simply breaks without recording an error. If gate.close() occurred before chunk required was registered while cancel == false, load_mapped_host_chunks returns Ok(()) with unread/zeroed MappedHost weight chunks and an under-counted Load weights progress total. (Note: when cancel == true due to an external failure in runtime_result, returning Ok(()) is needed so model.rs:1180-1181 surfaces runtime_result's root error rather than a synthetic cancellation error—so the error should fire specifically when !cancel.load(Ordering::Relaxed).)
      2. At payload.rs:754-761, when a reader encounters an I/O error, it sets cancel.store(true, Ordering::Relaxed) without calling gate.close(). Any sibling reader on the same rank already parked in Condvar::wait (payload.rs:626) will not wake until register_pending_mapped_host finishes its in-flight 512 MiB cuMemHostRegister_v2 call and closes the gate (and model.rs:1117 cannot close gates until load_mapped_host_chunks joins all sibling readers).
    • Fix: On !gate.wait_for(required, cancel) when !cancel.load(Ordering::Relaxed), record an error in first_error (e.g. invalid("mapped host registration closed before chunk was ready")) and set cancel. On reader error at payload.rs:754-761, also call if let Some(gate) = gate { gate.close(); } so parked sibling readers wake immediately.
  3. 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-2324 vs docs/prefix-cache-offload.md:540-557 and merged #625.

    • Verified issue: Prior main (pr/721 mod.rs:623-658) did not call MADV_HUGEPAGE or pre-fault MappedHost spans. #726 unconditionally issues libc::madvise(mapped, span_bytes, libc::MADV_HUGEPAGE) on every coalesced MappedHost span (316.6 GiB in the PR's workload) and immediately faults it at 2 MiB stride across up to 8 concurrent threads (mod.rs:2288-2324). Under Linux's default workstation THP settings (enabled=madvise, defrag=madvise or defer+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 on 119 GiB) and that merged #625 retired in eos::map_host (docs/prefix-cache-offload.md:541-557, where #625 measured 128.6 s vs 31.0 s for just 48 GiB on SM120).
    • Fix: Inspect /sys/kernel/mm/transparent_hugepage/{enabled,defrag} (reusing or sharing eos/src/unix.rs's Linux THP policy logic) so MADV_HUGEPAGE is only applied unconditionally under non-blocking defrag policies (defer/never), or falls back cleanly to base pages when huge pages are scarce / compact_stall climbs; disclose the THP policy behavior explicitly in the PR description.
  4. Normative loader/CLI design docs contradict the shipped changes, and choose_io_plan can exceed its stated 128 MiB cross-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-862 vs docs/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, 1095 specifies 4 reader threads, 4 pinned staging buffers of 4 MiB / rank_count, a 16 MiB process-wide staging bound, staging copies for host-resident payloads, and readers joining before module/graph setup. docs/core-format-design.md:857-858 states "The staging bound is process-wide; adding ranks must not multiply it." docs/cli-design.md:1589-1607 describes 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_size can round chunk_bytes up to MAX_CHUNK (8 MiB) without dividing by ranks, while per_rank_budget clamps at .max(chunk_bytes * 2) (240) and budget_slots clamps at .max(2) (242). On multi-rank setups with a large optimal_io_size or tight RAM (e.g., ranks = 16, optimal_io_size = 8 MiB), total pinned staging across ranks reaches 16 × 2 × 8 MiB = 256 MiB, violating both docs/core-format-design.md:857-858 and the PR's claimed <= 128 MiB cross-rank cap.
    • Fix: Cap chunk_bytes (including after optimal_io_size rounding) against (total_budget / ranks / 2) so multi-rank staging cannot exceed total_budget (<= 128 MiB), add a unit test asserting ranks * slots * (chunk_bytes + 2 * BLOCK) <= MAX_STAGING_BYTES across TP1/TP4/TP8/TP16, and update docs/runtime-core-design.md, docs/core-format-design.md, and docs/cli-design.md to document the new runtime staging budget, zero-copy host loading, and overlapped stage output.

Subtract / Simplify

  1. Replace four duplicated cleanup(&mut outcome) sites with RAII Drop on MappedHostAllocation — helios/src/runtime_core/mod.rs:2167-2170, 2230-2258, 2325-2342. Implementing Drop to reverse-munmap self.mappings (disarmed when attach_mapped_host drains mappings into self.host_mmap_spans) eliminates the cleanup closure and all four manual error/cancel teardown blocks while mechanically enforcing the SAFETY comment at line 2187.
  2. Deduplicate the read_at short-read loop in Chunk::read and Chunk::read_direct_into_host — helios/src/runtime_core/payload.rs:363-422. Both implement identical Interrupted-retry, EOF, and BLOCK-alignment checks; extracting one fn read_full_at(file: &File, offset: u64, dst: &mut [u8]) -> io::Result<()> removes ~25 duplicated lines.
  3. Hoist the duplicated post-load tail and simplify pending_registrations round-tripping in NativeModel::load_agreeing — helios/src/runtime_core/model.rs:882-906, 1146-1155, 1182-1217. The four post-load statements (apply_payload_relocations, integrated release_page_cache, load_phase.finish) are identical in both arms (1182-1191 and 1208-1217), and pending_registrations is converted Vec → Mutex<Vec<Option>> → Vec → Mutex<Vec<Option>> with silent unwrap_or_default() fallbacks.
  4. Remove dead tuple element from tier_io_plan and redundant optimal_io_size bounds check — helios/src/runtime_core/payload.rs:173-175, 222, 482-522, 640, 792. Both callers discard tier_io_plan's second return value (plan, _), and choose_io_plan:222 re-checks the exact BLOCK..=MAX_CHUNK / % BLOCK == 0 predicate already enforced by detect_optimal_io_size:173-175.
  5. Unify PendingHostRegistration platform fields and RegistrationGate emptiness checks — helios/src/runtime_core/mod.rs:2132-2163, 797-856, model.rs:1053-1059, payload.rs:599, 621. Making PendingHostRegistration.chunks: Vec<(u64, usize, u32)> unconditional (always empty off-Unix) removes redundant #[cfg(not(unix))] arms and duplicated emptiness checks.
  6. Keep StartupObservation.completed retention opt-in — helios/src/startup.rs:111-113, 136-138, 170-175. Only model.rs:1075 (overlapped background phases) and tests call completed_phases(); making completion retention opt-in avoids cloning and retaining every completed snapshot across all non-overlapping observed loads.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

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.