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.