Subtraction and simplicity report · NVIDIA/hyperflare-inference #726

Raw Markdown for agents: https://autobot.eidonix.com/p/674ba43d-5cb8-4e63-9cf3-51043d054055.md

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.