Correctness and contracts report · NVIDIA/hyperflare-inference #628

Raw Markdown for agents: https://autobot.eidonix.com/p/65961d6e-c2b4-4029-a84f-846e2b863614.md

Correctness, Contracts & System-Level Consequences review — PR #628 helios: gate offload Copy Engine batches during peer-copy graphs

Head 1870a27 (base main @ c146d7b), 14 files, +572/−72, fixes #627, no reviews/comments, CI failed on head. I read all 14 changed files plus their direct callers (selene/src/memory.rs, selene/src/store.rs, selene/src/levels.rs, helios/src/execution/threaded.rs, helios/src/server/metrics.rs, helios/src/server/runtime.rs), the docs contract, and the tests.

Key findings

  1. Major — a documented invariant is reversed: the model worker thread can now block unboundedly. CopyEngineGate::enter_peer_graph loops on a Condvar with no timeout while RankExecutor::submit holds that thread (copy_gate.rs:45-56, ranks.rs:90-101). docs/prefix-cache-offload.md:133/907/1015 promise the opposite; no docs/ file is touched.
  2. Major — offload can be starved indefinitely, and the failure mode lands on the warm path the PR's own evidence depends on. enter_offload_batch waits while peer_graphs_active > 0 || peer_graphs_waiting > 0 (copy_gate.rs:60-67); TP decode graphs are peer-copy graphs, so under sustained serving offload never advances, jobs refuse at QUEUE_DEPTH (transfer.rs:641-645), and stores are abandoned at peak load.
  3. Major — metric/rate span expanded. Gate wait is inside the codec transform_ns timing (codec.rs:283,290,302; :664,668,688; :749,752,769) and inside the submit→reply elapsed that feeds tier rate samples (transfer.rs:754 → selene/src/memory.rs:1452,1455), which price admission via worth_fetching (selene/src/store.rs:423-442). Contention-perverted rates persist in a 3-sample median (levels.rs:57-68).
  4. Major — the gated offload branch has zero test coverage in-repo. Every test builds Copiers::new(...) (gate None), so both gated arms are dead in tests; there is also no test of guard release via poll/close.
  5. Major — claims narrower than written. "zero gate overhead" holds for graph submission only; the "share the same wiring" claim is false for the multi-host shard peer (offload/shard.rs:47) and inert for Heliopause/Python manifests (heliopause/src/python.rs:331).
  6. Minor — waiting for the batch while holding the shared GPU-codec mutex serializes all ranks' codec work behind peer-graph contention (codec.rs:666-668, :751-752).
  7. Sound areas (verified, not assumed): fence-ordered guard release, no guard leak on the backpressure path, correct index alignment of peer_copy_graphs, genuine backward compatibility, real per-NativeModel Arc sharing, consistent gpu.codec → gate lock ordering, correct drain-before-release on error.

1. Correctness, Safety & Platform Parity

F1 — Major: unbounded block on the model worker thread, unreachable by the stall detector, contradicting three documented guarantees

helios/src/offload/copy_gate.rs:45-56:

pub fn enter_peer_graph(self: &Arc<Self>) -> PeerGraphGuard {
    let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
    state.peer_graphs_waiting += 1;
    while state.offload_batches_active > 0 {
        state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
    }
    state.peer_graphs_waiting -= 1;
    state.peer_graphs_active += 1;

Taken before any CUDA work on the submitting thread, helios/src/execution/ranks.rs:90-101:

let guard = if self.peer_copy_graphs.get(graph).copied().unwrap_or(false) {
    self.copy_gate
        .as_ref()
        .map(CopyEngineGate::enter_peer_graph)
} else {
    None
};
let submitted = match &mut self.inner {

No wait_timeout, no cancellation token, no liveness check. The engine's stall detector is a poll_ranks deadline (helios/src/execution/threaded.rs:942-952, TIMEOUT = 120s at threaded.rs:23) and cannot fire while the same thread is parked inside submit.

Contract this reverses — docs/prefix-cache-offload.md:133 "Offload work never blocks the model worker thread or the model stream."; :907 "The model stream never waits on an offload event."; :1015 "The model worker thread never waits for offload work." docs/same-process-tp.md:177-180 lists as Not qualified exactly "graphs that contain b12x spin-barrier collectives, process checkpoint and restore while rank threads are parked on the DispatchRing condition variable". No file under docs/ is in the changed set.

Impact: the bug being worked around (#627) is itself a class of wedge in offload/driver copy submission. Before this PR a wedged offload batch cost cache progress; after it, the same wedge parks the request-serving thread with no timeout and no diagnostic — a cache-tier stall becomes a full serving hang. Fix: bounded wait (Condvar::wait_timeout) with a monitored deferral/abandon counter and a log line, or acquire the lease on the executor side so submit can proceed and the deferral is visible; and update the three doc lines plus the same-process-tp.md qualification list.

F2 — Major: indefinite offload starvation; its consequence is abandoned prefix-cache stores at peak load

helios/src/offload/copy_gate.rs:60-67:

pub fn enter_offload_batch(&self) -> OffloadBatchGuard<'_> {
    let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
    while state.peer_graphs_active > 0 || state.peer_graphs_waiting > 0 {
        state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
    }
    state.offload_batches_active += 1;

Peer graphs take strict priority with no aging: a single new peer-copy graph submission closes the gate again before any batch can start. TP decode graphs contain peer copies too (the mechanism is graph-structural, runtime_core/mod.rs:1149-1156), and frames are pipelined back-to-back, so peer_graphs_waiting > 0 can hold for an entire busy window.

When offload cannot make progress, submissions refuse (helios/src/offload/transfer.rs:641-645):

if thread.outstanding >= QUEUE_DEPTH {
    return Err(invalid(format!(
        "offload queue for rank {rank} holds {QUEUE_DEPTH} jobs"

and the store reports a failed window (helios/src/server/runtime.rs:2387-2392 host-cache store error path, host_retry_abandoned bucket). Impact: host prefix-cache writes are dropped exactly during sustained prefill — the regime the PR's own evidence (5.08x warm, 2.45x disk-restore) is measured in — so the fix for the deadlock can suppress the warm-cache benefit on the next burst. The only priority test (copy_gate.rs:206-239) asserts the peer side is not starved; nothing bounds offload starvation. Fix: bounded wait plus periodic re-admission (one batch after N peer graphs or T ms) and a counter for gate-deferred store windows, so the trade is observable rather than silent.

F6 — Minor: batch lease acquired while holding the shared GPU-codec mutex

helios/src/offload/transfer/codec.rs:666-668 and :751-752:

if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() {
    let _ce =
        copy_gate.map(super::super::CopyEngineGate::enter_offload_batch);

Lock order (gpu.codec → gate) is consistent, so there is no inversion against try_lock — that part of the description is accurate. But an offload thread waiting out a peer-copy graph now holds the single shared GPU-codec mutex, so other ranks' GPU codec work — plus the try_lock CPU fallback that exists precisely to keep restores off the critical path (codec.rs:764-772 route GpuOnCpu) — is blocked behind that wait. Fix: acquire the batch lease before the codec lock (or drop and retry), so the codec mutex is never held across a gate wait.

Areas verified sound

2. Unintended system-level consequences

F3 — Major: the gate wait is charged to codec transform time and to tier rates that price admission

(a) helios/src/offload/transfer/codec.rs:283-302:

let start = Instant::now();
...
let stored_len = {
    let mut guard = gpu.codec.lock().unwrap();
    let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch);
    let res = guard.encode_pages_batches_with(
...
stats.transform_ns += start.elapsed().as_nanos() as u64;

start is taken before the lease, so gate wait is counted as transform time in flare_kv_codec_transform_nanoseconds_total ("Cumulative time spent in KV checkpoint codec transforms and coding", helios/src/server/metrics.rs:686-690). Same pattern at codec.rs:664/668/688 and :749/752/769.

(b) More consequential: the observed span of the tier rates now includes the gate wait. helios/src/offload/transfer.rs:754 elapsed: pending.started.elapsed() is submit→last-rank-reply, and selene/src/memory.rs:1451-1456 feeds it to the advertised rates:

if let Some(outbound) = self.outbound.get_mut(&reply.id) {
    self.outbound_rate.observe(reply.bytes, reply.elapsed);
...
} else if let Some(inbound) = self.inbound.get_mut(&reply.id) {
    self.inbound_rate.observe(reply.bytes, reply.elapsed);

Those rates produce estimated_seconds, which decides admission: selene/src/store.rs:441 estimated_seconds < 0.5 * gained_tokens as f64 / prefill_tokens_per_second.max(1.0). Rate is a 3-sample median that only recovers toward the seed over RECOVERY = 10s (selene/src/levels.rs:34,57-68,69-75). Impact: a handful of prefill-contended restores depress the advertised tier rate, and the store then rejects restores that would have paid off — pessimism concentrated exactly when prefix-cache hits matter (concurrent prefill), i.e. the PR can make the cache decline to serve hits precisely in its target workload. Fix: start the clock after lease acquisition and, more importantly, exclude gate-deferred time from the reply elapsed (or report a separate deferred-ns counter) so admission pricing keeps measuring the copy.

F5 — Major: the offload fast path changes for every prefix-cache run, and the added cost is unmeasured

The gate is attached unconditionally, helios/src/runtime_core/model.rs:1032-1038:

manifest.offload = self.offload.binding(index).map(|b| crate::offload::Binding::new(
    b,
    self.gpu_codec_cubins.clone(),
    std::sync::Arc::clone(&self.copy_gate),

(also model.rs:986-989, server/runtime.rs:731 open_with_gate(prepared, gpu_cubins, Some(copy_gate))). So copy_gate is Some for every offload binding, and transfer.rs:398-434 now takes a mutex and does a per-batch record + event.synchronize():

let _ce = gate.enter_offload_batch();
self.stream.record(&self.event)?;
self.event.synchronize()?;
std::mem::forget(drain);

with the old single end-of-job sync surviving only in the gate-less arm (transfer.rs:431-434). Since BATCH_BYTES = 16 << 20 (helios/src/cuda.rs:169 (not opened)), a 1 GiB window becomes 64 blocking syncs where it previously had one. This reverses the direction of the just-merged #497 (which retuned this very worker to cut restore latency) and is justified by no measurement in the PR or issue. Fix: measure capture/restore throughput with the gate attached vs None on the same workload and include it in the description, or gate only the first/last batch per window and rely on a single event for the rest.

F5b — Major: two copy paths the description claims are covered are not

helios/src/offload/shard.rs:44-49:

Ok(flare_selene::offload::sharded::join_peer(
    store,
    rank,
    &super::transfer::Copiers::new(gpu_cubins),

No gate — so a disk-store peer rank in a sharded/multi-host layout keeps issuing ungated CE batches during peer-copy graphs, i.e. the exact condition the PR identifies as the deadlock trigger remains for that configuration. And heliopause/src/python.rs:331 peer_copy_graphs: Vec::new(), means every manifest built through Heliopause/Python never marks a peer-copy graph, so on that path the graph side never calls enter_peer_graph — the deadlock fix silently does nothing while the offload side still pays the per-batch cost measured in F5. Fix: thread the gate into join_peer/sharded copiers, and derive peer_copy_graphs in the Python manifest builder (or reject/ignore the field explicitly rather than defaulting to an empty vector that silently disables a safety mechanism).

Minor: no validation that peer_copy_graphs matches graphs

helios/src/execution/manifest.rs:436-449 index-addresses the vector and defaults past the end to false. That is what gives backward compatibility, but a future producer that emits a short vector silently disables the protection for the missing graphs. A validate() length check (or debug_assert!) closes that hole for a few lines.

Note on hot-path contention

state.peer_graphs_waiting += 1 is done by every peer-copy submission even when no offload is attached — but copy_gate is None in that case (ranks.rs:90-96 short-circuits on the flag first, and copy_gate is only present when an offload binding exists), so the uncontended case genuinely costs nothing on the submission path. That claim in the description is accurate for graphs; the inaccuracy is confined to the offload side (F5).

3. Architecture, contracts and charter compliance

4. Tests and claim accuracy

F4 — Major: the gated copy paths are never executed by any test

Every Copiers construction in the test suites passes no gate, so copy_gate is None and both gated arms are dead code under test: helios/src/offload/gpu_tests.rs:126 (not opened),286,456,588,650,856,1004,1266,1271,1558 and helios/src/offload/transfer/codec.rs:1129,1133,1249,1359,1363 all use Copiers::new(...); offload/mod.rs:121-130 open() passes None. The only with_gate(..., Some(_)) callers are production (runtime_core/model.rs:986-989, server/runtime.rs:731).

Therefore transfer.rs:398-434 (lease + DrainOnDrop + per-batch record/sync), codec.rs:976-1002 (gated flush in copy_spans_batch) and the five GPU-codec acquire sites (codec.rs:290,318,352,668,752) have no in-repo test — and these are the sites that must not deadlock or leave the stream un-drained. Also missing: any test that RankExecutor releases a lease on poll and on close (ranks.rs:108-124,170-181); the only new executor test is the pure-manifest union at ranks.rs:188-201. The PR's "5/5 passed" count decomposes as four gate tests (copy_gate.rs:115,134,206,242) plus one flag-union test (ranks.rs:189) — all mutex/condvar or pure data, none touching CUDA. Fix: one test with Copiers::with_gate(..., Some(gate)) driving a fake/CPU codec so a peer-graph lease held in another thread demonstrably defers the batch and the batch's completion is required before the graph proceeds; plus a test that a dropped frame releases the lease.

F5c — Major: claim accuracy, statement by statement

Open questions / could not verify