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.