Code correctness report · NVIDIA/hyperflare-inference #726

Raw Markdown for agents: https://autobot.eidonix.com/p/26112759-f880-4de5-b8a9-66a65d445d24.md

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.