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
- Major — a documented invariant is reversed: the model worker thread can now block unboundedly.
CopyEngineGate::enter_peer_graphloops on aCondvarwith no timeout whileRankExecutor::submitholds that thread (copy_gate.rs:45-56,ranks.rs:90-101).docs/prefix-cache-offload.md:133/907/1015promise the opposite; nodocs/file is touched. - Major — offload can be starved indefinitely, and the failure mode lands on the warm path the PR's own evidence depends on.
enter_offload_batchwaits whilepeer_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 atQUEUE_DEPTH(transfer.rs:641-645), and stores are abandoned at peak load. - Major — metric/rate span expanded. Gate wait is inside the codec
transform_nstiming (codec.rs:283,290,302;:664,668,688;:749,752,769) and inside the submit→replyelapsedthat feeds tier rate samples (transfer.rs:754→selene/src/memory.rs:1452,1455), which price admission viaworth_fetching(selene/src/store.rs:423-442). Contention-perverted rates persist in a 3-sample median (levels.rs:57-68). - Major — the gated offload branch has zero test coverage in-repo. Every test builds
Copiers::new(...)(gateNone), so both gated arms are dead in tests; there is also no test of guard release viapoll/close. - 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). - 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). - 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-NativeModelArcsharing, consistentgpu.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
- Fence ordering for release is correct. Guards are pushed in submit order (
ranks.rs:102-104) and popped front-first while*fence <= frame.fence(ranks.rs:114-122);FenceisOrd(helios/src/cache.rs:20-22), so out-of-order completions cannot release a live lease. - No guard leak on backpressure.
Ok(None)frominner.submitreturns before the guard is stored, so the binding is dropped and the condvar notified (ranks.rs:97-105). close()draining residual leases afterinner.close()(ranks.rs:170-181) is what letsTransfers::closeunblock instead of erroring.- Index alignment is right.
peer_copy_graphsis filled per graph name (runtime_core/serving.rs:49-59) in lockstep withgraphs, so manifest index → flag mapping matches submission indices. - Backward compatibility is real —
manifest.rs:447-449self.peer_copy_graphs.get(index).copied().unwrap_or(false); no.protoor package-format change in the diff, so existing cores load without re-export. All producers that do not know the field (heliopause/src/python.rs:331,helios/src/model/testing.rs:396,helios/src/model/contract.rs:983) still validate. - Error-path drain ordering in
transfer.rs:398-419is correct:DrainOnDropis declared after the lease, so an error drains the stream before the gate opens, andmem::forget(drain)on success preserves the single explicit sync. - Per-
NativeModelArcsharing is genuine (runtime_core/model.rs:27,662,986-989,1032-1038;server/runtime.rs:719-731). - No platform-parity regression found in the touched code: the gate is host-side Rust with no OS-specific paths, and the CUDA-only call sites are already behind the existing feature gates.
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
- No wire/package contract change, no new flag/env/dependency, no captured-graph op contract — so no AGENTS.md owner-sign-off gate applies, and the model-agnostic rule (#267/#334) is respected: the coordination lives in Helios, not ignition. The four-part PR description (why / what / result / evidence) is present.
- #210 (served-workload A/B for performance PRs) is not satisfied in the direction it asks for. The PR carries the
performancelabel, yet the only comparative datum runs the other way — unpatchedmain"deadlocked during the first burst", patched completed 40/40 at 4.68–4.83 s/burst. There is no speedup-vs-mainmeasurement and none at all of the new per-batch sync cost (F5). Verdict text: the fix is a liveness fix, and labelling it performance while shipping a per-batch serialization with no measurement invites exactly the #497-style regression the tier was just retuned to avoid. - #397 (root cause, not workaround) — flag as a scoping question rather than a defect: #627's own ablation shows serializing offload against itself still deadlocked, so the CE/flag mechanism is not characterised, and this PR is an explicit coordination layer above it. It is the smallest such layer that avoids a core re-export, and the description says "resolves" rather than "diagnoses". Worth an explicit maintainer acknowledgement in the description that the underlying interaction is still unexplained.
- Merge-order note (not a defect):
peer_copy_graphsis a new public field onExecutionManifest(manifest.rs:436-439), the same struct open PR #621 edits — a rebase to sequence is needed. No other open PR touches these hunks.
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
- "zero gate overhead on graphs without peer-copy nodes" — true for submission (
ranks.rs:90-96), false for offload: the gate is attached unconditionally (model.rs:986-989,1032-1038,server/runtime.rs:731), so every prefix-cache run pays mutex + per-16 MiBrecord+synchronize(transfer.rs:398-434). Precise form: zero overhead on the graph path, added per-batch cost on the offload path for all runs. - "Share one
Arc<CopyEngineGate>perNativeModelacross … andNativeModel::attach_offload(Selene pool workers)" — theArcis shared as described, but the claim reads wider than the code:offload/shard.rs:47is ungated andheliopause/src/python.rs:331disables detection (F5b). The Limitations paragraph does concede multi-host TP and live pool serving are untested end-to-end, which is honest but does not identify the ungated path. - "release completed leases in
RankExecutor::poll" — correct (ranks.rs:114-122), but conservative: a lease is released only when a full frame completion (all ranks, including host readback) surfaces frompoll, not when the graph's GPU work retires. Combined with F2 this lengthens offload stalls beyond what the algorithm requires. Worth stating in the description. - Validation counts (5/5, 162/162, 245/245, 200/201, 19/19 + 6/6) are prose only; CI failed on the head commit and no test output or logs are attached, and none of the harnesses cover the gated branch (F4).
Open questions / could not verify
- Which CI job failed on
1870a27and why — not retrievable from the material available; it conflicts with the claimed cleancargo check --locked --all-targetsunder-D warnings. - Whether the per-batch
record+synchronizemeasurably regresses capture/restore throughput (the #497 direction) — no measurement anywhere in the PR or issue, and no benchmark in the diff. - The driver-level mechanism of the CE/flag deadlock. #627's cross-rank-serialization ablation (serializing offload against itself still deadlocked) is not explained by the story the gate implements, so it is unknown whether the gate covers all the interactions that can deadlock (e.g. copies to peer-mapped local
Memory::Deviceallocations, or kernel-driven DMA, which theMemory::Peerstructural test atruntime_core/mod.rs:1149-1156does not mark). - Whether
Memory::Peer-markedNode::Copynodes cover all real in-graph peer transfers in shipped cores. - Live behaviour for multi-host TP (
RankPeers::Processes, one gate per process — a rank's offload is never coordinated against another rank's peer-copy graph), Selene pool serving, CPU KV codec, and non-SM120 GPUs: explicitly untested end-to-end. - Whether the offload starvation in F2 shows up in practice as dropped store windows during sustained prefill — plausible from the code but not measured by the author's burst tests.