Deep Code Correctness Audit — PR #698 (helios/src/server/runtime.rs, +65/−53)
Verdict: no Blocker and no Major defect found. The reordering is semantically safe with respect to every callee I resolved, close_store is a faithful behaviour-preserving extraction, and the startup path is now LIFO-symmetric with the shutdown path as claimed. One Minor correctness divergence is reported below (new store teardown under a false drained: true claim), plus two informational notes. No hot-path code changed.
Because the PR is single-file / single-subsystem (1 file, 118 changed lines, helios/ only), it was audited directly rather than partitioned into sub-agents.
Diff sites audited
helios/src/server/runtime.rs at 501bb0e:
- 657–691 new early
crate::offload::open(...)block (beforeRankExecutor::new) - 692–706
RankExecutor::newfailure path (now also closes the store) - 713–719, 777–783 scheduler construction / configuration failure paths (now
close_storeafterexecutor.close()) - 1137–1157 new free function
close_store - 1353–1355
Worker::close_storenow delegates to the free function - 784–793 unchanged
Worker::new+worker.attach_store(store) - 816–817 unchanged shutdown order (
executor.close()thenworker.close_store())
1. Callee / design-invariant resolution — the reordering is safe
(a) manifest.offload still carries everything RankExecutor::new reads. The moved block calls binding.take() (line 669), which drains Shared::prepared:
// helios/src/offload/mod.rs:78-83
pub fn take(&self) -> Option<(Prepared, Vec<std::sync::Arc<Vec<u8>>>)> {
self.inner
.take()
.map(|prepared| (prepared, self.gpu_cubins.clone()))
}
RankExecutor::new reads only the gate, not the payload:
// helios/src/execution/ranks.rs:123-143
pub(crate) unsafe fn new(manifest: ExecutionManifest, peers: Option<RankPeers>) -> Result<Self> {
let copy_gate = manifest.offload.as_ref().and_then(|b| b.copy_gate());
...
Ok(Self { inner, leases: PeerGraphLeases::new(copy_gate, peer_copy_graphs) })
}
and copy_gate is a plain Arc field on the helios wrapper, unaffected by take() (helios/src/offload/mod.rs:42, 58-60). All three executor constructors (transport.rs:604-611, threaded.rs:625-644, parallel.rs:114-145) read only persistent_workers, graphs, peer_copy_graphs, completion_token_capacity, input_frame_bytes, buffers, tuning_graphs — never offload's taken payload. Contention check on the other manifest.offload readers: threaded.rs:1286-1290 (same_layout → a.shares(b)) and runtime.rs:645 (!binding.sharded()) both resolve against Shared, and selene/src/offload.rs:530-532 / 540-545 compare Arc::ptr_eq and prepared.shards; sharded() is evaluated at line 645, before the take() at 669, so the "requires every rank in one process" guard is not made dead code by the reordering. runtime.rs:609 binding.inputs() clones shared.inputs, also independent of prepared.
(b) offload::open has no dependency on RankExecutor having run. helios/src/offload/mod.rs:135-144 → selene/src/offload.rs:802-891 → Copiers::start (transfer.rs:2190-2210) → Transfers::start_parts → RankWorker::open (transfer.rs:395-421), which does its own Stream::open_lowest_priority(context, device); Stream::bind (cuda.rs:740-756) issues cuCtxSetCurrent itself, so it does not rely on the model thread's current context. The GKV1 module load happens inside RankCodec::new (transfer/codec.rs:102-132) → GpuRankCodec::new → stream.load_module(cubin) (transfer/gpu_codec.rs:282, cuda.rs:1152).
(c) The deadlock premise is confirmed in-tree. The codec module is deliberately skipped during kernel preparation (runtime_core/mod.rs:755-761, skip_module), documented normatively at docs/prefix-cache-offload.md:112-119 ("Helios skips loading that module when compression is off or cpu, and loads it lazily via cuModuleLoadData"), while the persistent worker is launched inside executor construction at transport.rs:793-805 (finish_startup → control.start()?) after tuning graphs have already run (transport.rs:604-611). So before this PR the module load really could be issued while the worker kernel was resident. The new order closes that window for all three peer modes (persistent workers are rejected for RankPeers::Threads/Processes, threaded.rs:632-638, parallel.rs:122-126, so the single-rank GraphExecutor path is the one that matters). The fix is effective.
(d) Reverse deadlock check (does opening first break the executor?) No. Post-open there is no further cuModuleLoadData on any path reachable after a worker launch: all CopierFactory::mapped/unmapped calls (transfer.rs:2213-2232) are reachable only from offload::open, and the multi-host peer path shard::join_peer (selene/src/offload/sharded.rs:477) runs before Server::start from the CLI (flare-cli/src/cluster.rs:254), i.e. before any worker launch. The store's transfer threads are idle at that point (no jobs queued), so control.start() at transport.rs:804 cannot be blocked by them.
(e) close_store extraction is exact. Original Worker::close_store and the new free function are character-identical apart from the Option source:
// helios/src/server/runtime.rs:1137-1157
fn close_store(store: Option<Box<dyn flare_selene::HostStore>>, shutdown: &mut Shutdown) {
let Some(store) = store else { return; };
let mut store = std::mem::ManuallyDrop::new(store);
if !shutdown.drained { return; }
shutdown.drained = false;
match store.close() {
Ok(()) => { shutdown.drained = true; drop(std::mem::ManuallyDrop::into_inner(store)); }
Err(error) => { shutdown.error.get_or_insert(error.into()); }
}
}
self.store.take() is evaluated before the call at 1354, identically to the old let Some(store) = self.store.take() else { return; }, so the "store removed even when not closed" invariant (exercised by phase_tests.rs:2311, 2334, 2359) is preserved. Worker::close_store still exists with the same signature, so phase_tests.rs:1759/2275/2281/2305/2331/2355 still compile and pass unchanged. The early-return-on-!drained leak of ManuallyDrop matches the normative rule at docs/prefix-cache-offload.md:879-883 ("If either drain fails, the store and its resource owners remain alive together with the model resources"). Hot-path cost: zero — close_store is reached only at startup-failure and shutdown, never in the request loop.
2. Order-of-operations / state-transition tracing
The new startup sequence is now store.open → RankExecutor::new → scheduler → attach_store and shutdown is executor.close() → close_store — exact LIFO as the comment at 657-662 claims. Per-branch drain-flag trace:
| path | line | drained before |
close_store behaviour |
result |
|---|---|---|---|---|
| store open fails | 683–690 | true (inlined) |
not called; store is None-transposed Err, nothing to leak |
drained: true, correct — open returns before any store object exists, and its partially started Transfers are joined by Drop for Transfers (transfer.rs:841-851) |
RankExecutor::new fails |
698–705 | true asserted |
store close() + drop |
see Minor finding 1 |
| scheduler construction fails | 713–719 | from executor.close() |
closes only if executor drained | matches doc invariant |
| scheduler configuration fails | 777–783 | from executor.close() |
as above | matches doc invariant |
ready_tx.send(...) now precedes close_store on the RankExecutor::new path; the caller's thread.join() at runtime.rs:851 still synchronizes on the store close, so the reported StartFailure.drained cannot be observed before teardown finishes, and a panic inside close_store still surfaces as drained: false through unwrap_or_else at 851-854. No stale-flag read: shutdown.drained is written at 1147 and re-set at 1150 within the same call, and no later statement in any caller reads it before returning.
3. Adversarial boundary checks
manifest.offload == None→store = Noneat 683,worker.attach_store(None)at 793 →scheduler.enable_publications()/enable_evictions()correctly not called (runtime.rs:1320-1328). Unchanged.offload == Somebut payload already taken (take()→None) → whole chain isNone→ startup proceeds with offload silently disabled. Pre-existing behaviour, not introduced here (identical chain existed pre-PR, just afterexecutor.manifest()); noted only as a latent trap, not counted as a defect of this diff.geometryempty →prepared.geometry.first()isNone,codec_placementskipped;Copiers::startwould reject the empty context/geometry pair attransfer.rs:542-548. Unchanged.log_to_stderrfalse → warning suppressed as before; only its position moved earlier, which cannot flip any metric gate (Metrics::storeatmetrics.rs:566only gains the placement earlier).
4. Hot-path complexity / allocations
No changed line lies on a per-step, per-request, or eviction path. The moved block is one-shot startup: a Vec<Arc<Vec<u8>>> clone of gpu_cubins (offload/mod.rs:81), an Arc clone for the gate, and one Box<dyn HostStore> move — no new per-iteration allocation, no new O(N) scan. close_store adds one indirect call plus a ManuallyDrop wrapper at shutdown only.
Findings
Minor 1 — RankExecutor::new failure now tears down the store under an unverified drained: true
Sites: helios/src/server/runtime.rs:697-705 (diff) vs helios/src/execution/transport.rs:1383-1387 and helios/src/execution/ranks.rs:129-140 (callee).
// helios/src/server/runtime.rs:695-706 (diff)
let mut executor = match unsafe { RankExecutor::new(manifest, peers) } {
Ok(executor) => executor,
Err(error) => {
let mut shutdown = Shutdown { drained: true, error: Some(error.clone()) };
let _ = ready_tx.send(Err(error));
close_store(store, &mut shutdown); // <-- closes + DROPS the store
return shutdown;
}
};
RankExecutor::new can return Err after GPU resources exist and were retained, because a constructed GraphExecutor on the error path is dropped and Drop→close() deliberately leaks on a failed drain:
// helios/src/execution/transport.rs:1383-1387
if drained { drop(resources); } else { std::mem::forget(resources); }
Reachable Err-with-retained-resources paths inside ranks.rs:129-140: GraphExecutor::new's tuning loop and finish_startup() → control.start()? (transport.rs:604-611, 793-805).
Counterexample: a core with a persistent worker whose green-context control.start() fails after partially launching the kernel, or whose tuning graph fails such that cuStreamSynchronize times out. RankExecutor::new returns Err with the resources mem::forget-ed; the new code reports drained: true, calls store.close() and then drop(store) at 1151, releasing the store's registered host slabs and pool device parts on the very contexts whose drain just failed. Pre-PR this was harmless because no store existed yet on that path; post-PR it is a new teardown under a false drain claim. The claim also propagates outward as StartFailure.drained (runtime.rs:864 → server.rs:443 → session.rs:76 → DrainGuard), which is exactly the signal telling the caller it may release the prepared core's CUDA contexts.
Concrete fix: do not assert drain on a constructor that cannot report it. Either (a) keep the store un-closed on this path (Shutdown { drained: false, error }, so close_store hits the !shutdown.drained early return and leaks via ManuallyDrop, matching docs/prefix-cache-offload.md:879-883), or (b) add a RankExecutor::try_new that returns Result<Self> plus the drop-time Shutdown so the true status can be threaded through. Option (a) is a two-line change and is strictly conservative.
Minor 2 — no test covers the new early-error store teardown
The three newly added close_store(store, &mut shutdown) call sites (703, 716, 780) have no counterpart in phase_tests.rs; only the Worker::close_store paths are covered (phase_tests.rs:2263-2363, four tests). The riskiest new branch — RankExecutor::new failure (Minor 1) — is therefore unverified. Suggested test: a FakeStore (already present at phase_tests.rs:2122) attached through a start_retaining_drain failure injected after store opens, asserting close_calls == 0 and drops == 0 when the executor did not drain.
Informational — normative doc now contradicts the code
docs/prefix-cache-offload.md:840-842 states "ModelRuntime::start constructs the configured store on the model thread after the executor exists". That is the invariant this PR intentionally inverts (the doc's shutdown clause at 879-883 is still accurate). Flagged as an invariant-tracking note for the documentation lens, not counted as a code defect.
What I confirmed is not broken (checked, no finding)
binding.take()beforeRankExecutor::newdoes not starve any executor constructor orsame_layout/shardedcheck (all readSharedmetadata or the separatecopy_gate/gpu_cubinsfields).- Gate identity is preserved: the same
Arc<CopyEngineGate>reaches bothPeerGraphLeases::new(ranks.rs:127) and the store'sCopiers(offload/mod.rs:142), so per-graph copy coordination still works after the reordering. - The early paths' move of
storeinside a diverging match arm and its later use at line 793 is accepted by the borrow checker and correct. - Drain semantics of the two scheduler-failure paths match
Worker::close_storeexactly, including the panic-safety property tested atphase_tests.rs:2341-2363. - No hot-path change; no new allocation in any loop.