PR #628 — Correctness, Contracts & System-Level Consequences review (@ 76e1813)
19 files, +1,165/−154. helios/src/offload/copy_gate.rs is the new 584-line gate core. I opened every changed file plus its direct callers (RankExecutor, both rank loops, Worker::submit/teardown, the Selene rate/admission consumers, flare-cli cluster join) and the new tests.
Key findings
- Blocker — offload starvation is unbounded on the multi-process rank layout this PR newly gates.
serve_ranktakes the peer lease on COMMIT with no turn check; the only code that lets active peer leases drain to zero (RankExecutor::can_submit) is consumed solely by the in-process worker loop. Offload waits on an unbounded condvar → permanent hang for restores and checkpoint unpins onRankPeers::Processes/multi-host. - Major — the
Reply.elapsedmetric span shrank by the gate wait and it feeds an admission heuristic (Rate::observe→worth_transfer), so a gate-bound restore is priced as the cheapest one and keeps being admitted. - Major — GPU-codec leases are held across encode/decode compute, contradicting the documented "bounded in-flight 16 MiB batch" drain that the peer-copy path is supposed to wait for.
- Major — a stuck offload batch (120 s) fails the entire served worker and every in-flight request, after the scheduler has already recorded the submission; undocumented.
- Major — the new fairness test hand-simulates the pipelined loop, and the gated copy paths are
#[ignore]/CUDA-only, so the anti-starvation fix is not exercised by anything that runs in CI. - Minor — literal peer-copy detection, per-process (not per-cluster) gate, gate wait surfacing as a graph deadline in
serve_rank, staledocs/same-process-tp.md(not opened). - Charter #210 — no A/B offload number and no gate-cost measurement; the author defers the GPU re-run.
1. Correctness, Safety & Platform Parity
Finding 1 — Blocker — serve_rank can starve offload forever; the gate is wired into that layout by this same PR
helios/src/execution/parallel.rs:652-656:
let guard = leases.enter(graph)?;
if executor.submit(graph, &uploads, grammar)? != Some(fence) {
return Err(invalid("rank lost its prepared submission"));
}
leases.track(Some(fence), guard);
Everything that can give offload its turn lives behind one caller. helios/src/execution/ranks.rs:181-184:
#[cfg(feature = "server")]
pub(crate) fn can_submit(&self, grammar: bool) -> bool {
!self.leases.should_drain_for_offload() && self.inner.can_submit(grammar)
}
and its only consumer is Worker::submit (helios/src/server/runtime.rs:2261: if !executor.can_submit(self.scheduler.plan_requires_feedback(step))). The gate itself only arms an offload wave when no peer graph is active (helios/src/offload/copy_gate.rs:55-68):
fn maybe_arm_offload_wave(&mut self) -> bool {
if self.peer_graphs_active == 0
&& self.turn == Turn::Peer
&& self.offload_batches_waiting > 0
and the offload side waits with no timeout at all (copy_gate.rs:180-187):
let waited = if must_wait(&state) {
let started = Instant::now();
state.offload_batches_waiting += 1;
while must_wait(&state) {
state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
}
serve_rank runs a 2-frame pipeline (started is pushed on every COMMIT, parallel.rs:657, and popped on completion, :664) and submits frames back to back, so a peer-copy lease is essentially always outstanding; peer_graphs_active never returns to 0 while decode is saturating, maybe_arm_offload_wave never fires, and every offload worker in that process blocks in the Condvar::wait above. This layout is newly gated by the PR: flare-cli/src/cluster.rs:254-261 calls join_peer_with_gate(..., owner.copy_gate(), ...) → helios/src/offload/shard.rs:47-61 → Copiers::with_gate.
Impact: multi-process/multi-host TP no longer deadlocks the Copy Engine — it hangs its host tier instead (restores never complete → requests that need a restore stall, checkpoint unpins never return, host store close blocks). That is the same liveness class the PR removes, relocated to the layout the PR just extended the gate to. Note also that should_drain_for_offload is not server-gated but its only consumer is, so any embedder that drives RankExecutor without the server feature cannot honour the turn either.
Fix: in serve_rank, before COMMIT, skip/defer while leases.should_drain_for_offload() (keep polling so active frames drain and the peer-active count reaches zero, then submit); or bound enter_offload_batch and surface a retryable error instead of an unbounded wait. Add a RankPeers::Processes fairness test.
Finding 2 — Major — Reply.elapsed excludes gate wait, and that value prices restores for admission
helios/src/offload/transfer.rs:788-799:
if let Some(pending) = self.pending.remove(&key) {
replies.push(Reply {
id: reply.id,
window: reply.window,
direction: pending.direction,
result: pending.error.map_or(Ok(()), Err),
bytes: pending.bytes,
elapsed: pending
.started
.elapsed()
.saturating_sub(pending.max_gate_wait),
});
max_gate_wait (transfer.rs:780) is the max across ranks of cumulative gate wait, and in the codec paths gate_wait is summed over every batch/wave of the job (helios/src/offload/transfer/codec.rs:304, :339, :375 — gate_wait += waited;), not a wall-clock span, so subtracting it can clamp a fully gate-bound job to near zero.
That number is the only measurement of the host tier: selene/src/memory.rs:1450-1456 (self.outbound_rate.observe(reply.bytes, reply.elapsed)) → Rate::observe (selene/src/levels.rs:57-67) → estimated_seconds → worth_transfer (selene/src/store.rs:433-442):
pub fn worth_transfer(
gained_tokens: u64,
estimated_seconds: f64,
prefill_tokens_per_second: f64,
) -> bool {
...
estimated_seconds < 0.5 * gained_tokens as f64 / prefill_tokens_per_second.max(1.0)
Impact: exactly when the gate is the bottleneck, the measured rate goes up, estimated_seconds goes down, and the most contended tier looks like the cheapest to fetch — so more restores are admitted into the contention, and RestoreWait::defer's budget (helios/src/server/runtime.rs:223-229) is inflated the same way. Worse, Rate::observe drops elapsed.is_zero() samples (levels.rs:58-60), so an over-subtraction that clamps to zero does not correct the estimate, it freezes it. The intent ("measure the copy, not the wait") is defensible, but the implementation confounds a peak of a cumulative sum with a span.
Fix: measure the copy span inside the lease (the codec already starts Instant::now() after acquisition, codec.rs:292) and carry that as elapsed, keeping gate wait in a separate counter/stat rather than subtracting it from a total wall time.
Finding 3 — Major — GPU-codec leases span encode/decode compute, not a copy batch
helios/src/offload/transfer/codec.rs:288-303 (same shape at :318-338 and :354-377):
let (stored_len, elapsed, waited) = {
let mut guard = gpu.codec.lock().unwrap();
let ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch);
let waited = ce.as_ref().map_or(Duration::ZERO, |(_, w)| *w);
let start = Instant::now();
let res = guard.encode_pages_batches_with(
page_plan,
&batch_refs,
&self.gpu_profile,
stream,
event,
|unit, bytes| capture.push_slice(unit, bytes),
);
let stored_len = sync_on_err(stream, res).map_err(decode_error)?;
The guard is alive across the whole multi-batch encode plus its sync_on_err stream sync, so a waiting peer-copy graph can be delayed by codec compute for as long as one MAX_PIPELINE_BATCHES wave takes, not by one 16 MiB copy. The docs understate this: docs/prefix-cache-offload.md:133-136 and :1025-1029 describe the peer graph waiting only for "the bounded Copy Engine drain" / a "bounded in-flight 16 MiB batch drain". Under continuous offload a decode step can absorb that delay repeatedly (each lease is a fresh gate acquisition).
Fix: acquire per stream.copy_batch inside the codec, the way copy_batch_gated does (helios/src/offload/transfer.rs:308-339), or restate the documented bound honestly as "one encode/decode batch, including its kernels and stream sync".
Finding 4 — Major — a stuck offload batch fails the served worker and all in-flight requests
helios/src/offload/copy_gate.rs:136-146:
return Err(Error::execution(
ExecutionError::Drain,
format!(
"timed out after {timeout:?} waiting for offload Copy Engine batches to drain \
(offload_active={}, offload_waiting={}, turn={:?}, wave_remaining={})",
The error propagates: RankExecutor::submit passes it up (helios/src/execution/ranks.rs:153), and Worker::submit uses ? (helios/src/server/runtime.rs:2332-2339):
if executor.submit(
graph,
&uploads,
feedback,
)? != Some(fence)
{
return Err("executor refused a reserved scheduler submission".into());
}
which unwinds Worker::run into the teardown at helios/src/server/runtime.rs:774-777:
worker.fail_all(&final_error);
let mut shutdown = executor.close();
worker.close_store(&mut shutdown);
Impact: a slow disk/PCIe offload batch (or a codec wave holding the gate, Finding 3) can take down the whole model worker and abort every request, not just the affected one. It happens after reserve_and_pack / scheduler.submitted_step already recorded the submission (helios/src/server/runtime.rs:2281-2282), so the scheduler believes a step was submitted and holds its uploads for the whole 120 s. Nothing in docs/prefix-cache-offload.md documents this. Fix: treat gate timeout as a deferral (Ok(false) from Worker::submit, retried next loop) rather than a fatal submit error, and document the bound.
2. Unintended System-Level Consequences
Finding 5 — Minor — multi-process gate wait is laundered into a misleading "deadline expired" error
helios/src/execution/parallel.rs:667-671:
if prepared_at.is_some_and(|time| time.elapsed() > TIMEOUT) {
return Err(invalid("rank commit deadline expired after preparation"));
}
if started.front().is_some_and(|time| time.elapsed() > TIMEOUT) {
return Err(invalid("rank graph completion deadline expired"));
}
The lease is taken at :652 before executor.submit, while started timestamps are pushed after (:657) — so a long gate wait lands in prepared_at's 120 s window and surfaces as "rank commit deadline expired after preparation" in the middle of leases.enter(graph)? rather than as a gate Drain. Impact: on-call diagnostics point at the coordinator/rendezvous instead of the gate; also the two timers are both 120 s so they race. Fix: report gate wait through the gate's own error/counters, or refresh prepared_at semantics around the gated acquisition.
Finding 6 — Minor — the gate is per process, so the two layouts do not share the invariant the PR describes
CopyEngineGate is created per NativeModel (helios/src/runtime_core/model.rs:827-831) and the PeerGraphLeases type is instantiated separately per loop (helios/src/execution/ranks.rs:143 vs helios/src/execution/parallel.rs:563-566). On RankPeers::Processes, each rank process gates its own offload workers against its own peer-copy frames — there is no cross-process coordination, and each process's offload workers can block on a different rank's phase. This is acceptable if documented, but the PR body's "Eliminates the TP2 prefill deadlock … while keeping multi-rank offload concurrency" reads as a cluster-wide statement; it is verified only for the single-process threaded layout (the PR's own Limitations note says multi-host was not tested end-to-end).
Finding 7 — Minor — detection is literal and would silently reopen the deadlock
Per the verified reading of helios/src/runtime_core/mod.rs:1146-1156, a graph is flagged only when a Node::Copy node has an endpoint allocation declared Memory::Peer. Kernel-driven DMA or peer-mapped buffers registered as Memory::Device are not flagged, so such a graph would run ungated against concurrent offload — no error, no warning, the original hang. This is inherent to structural detection rather than a defect in the new code, but it deserves a one-line doc caveat (or a startup log naming which graphs were flagged) so a future recipe author can tell whether their model is protected.
3. Architecture, Contracts & Charter Compliance
- Contract surface is additive and compatible.
ExecutionManifest.peer_copy_graphsis new in this PR, defaults absent entries tofalse, andvalidate()rejects a length mismatch againstgraphs(per verifiedhelios/src/execution/manifest.rs:435-439,835-843). No Protobuf/package-format change; the PR's "no re-export required" claim holds because the flag is derived at graph-reconstruction time, andheliopause/src/python.rs:331(not opened) sends an empty vector on a manifest whoseoffloadisNone, so that path can never engage a gate. - No per-model branches. The gate keys off graph structure, not model identity — consistent with the charter's "keep the runtime model-agnostic" rule.
- Charter #210 (performance evidence) is unmet and the PR says so. The change adds a per-model behavioural gate on every offload batch for peer-copy models, yet there is no A/B offload throughput/latency figure and no measurement of the gate's own cost (mutex + condvar on the hot batch path). The author defers: the gated CUDA tests and a peer-copy A/B offload-latency measurement "have not yet been run on
76e1813". Per the review standard this is the piece a maintainer needs before merge: a before/after restore rate on a peer-copy model, plus a statement of gate cost on a graph set with no peer copies (which the code says is zero —CopyEngineGateisNone,helios/src/runtime_core/model.rs:827-831). - Rules of the road: the PR does not touch wire contracts, API fields, or exported graph op contracts, so no owner sign-off gate applies beyond normal review.
4. Tests & Claim Accuracy
Finding 8 — Major — the fairness test does not drive the code it claims to protect
helios/src/offload/copy_gate.rs:453-461:
// should_drain_for_offload() is true, and otherwise submit up to depth 2.
...
while in_flight.len() < 2 && !leases.should_drain_for_offload() {
The test hand-writes Worker::run's loop condition and therefore passes whether or not RankExecutor::can_submit is wired into Worker::submit, and it cannot see the serve_rank gap in Finding 1 (there is no RankPeers::Processes analogue at all). The other gated coverage does not run in CI: the gated codec test is #[ignore]d (helios/src/offload/transfer/codec.rs:1286-1291) and the gated transfer arm requires two CUDA devices (helios/src/offload/transfer.rs:2013-2053). Combined with the deferred GPU re-run, no gated copy path has executed anywhere yet. Fix: an integration test that drives the real Worker::submit/RankExecutor pair with a fake offload thread, and a serve_rank test with two ranks and a waiting offload batch asserting liveness.
Claim accuracy
- "Eliminates the TP2 prefill deadlock … keeping multi-rank offload concurrency outside peer-copy graphs" — true for the in-process threaded TP2 path validated on SM120; for
RankPeers::Processesthe gate converts the deadlock into unbounded offload starvation (Finding 1). The Limitations section does say multi-host TP was not tested end-to-end, which is honest, but the starvation is a code-path property, not a testing gap. - "wait only for in-flight batches to drain" — understated for GPU codecs (Finding 3).
- "zero gate overhead on graphs without peer-copy nodes" — verified correct (gate is
Noneunless a rank reconstructed a peer-copy graph; the ungated transfer path keeps one record+sync per window).
Verified sound (no finding)
- Peer-copy detection and manifest plumbing, including rank-0 union/padding of asymmetric peer copies (
helios/src/execution/ranks.rs:104-117,merge_peer_copy_graphs). - Lock ordering:
gpu.codecis always taken before the gate (no inversion against thetry_locksites atcodec.rs:673-682,757-775). - RAII release including panic unwind, and lease clearing after executor drain in both loops (
ranks.rs:191-195,parallel.rs:688-693) — host-store close cannot be blocked by leftover leases. PeerGraphGuard::drop/OffloadBatchGuard::dropnotify exactly when their last holder leaves (copy_gate.rs:209-240), and an armed offload wave is not revocable by a new peer graph whilepeer_graphs_active == 0(copy_gate.rs:120-125), which is what prevents peer-graph starvation of offload in the single-threaded loop.- The
prefill_startedbookkeeping move after a successful submit (helios/src/server/runtime.rs:2340-2360) removes a stale-entry leak present before. - The
heliopausepath cannot gate (offload: None), so the empty vector there is harmless.
Open questions / could not find
- Does a maintainer consider the
MAX_PEER_STREAK_WHILE_OFFLOAD_WAITINGfairness scheme sufficient forRankPeers::Processes, given Finding 1 is a code gap rather than a tuning issue? - No A/B offload throughput/latency numbers, and no gate-cost measurement, anywhere in the PR or its discussion.
- No in-repo documentation of the
ExecutionError::Drain-fails-the-worker behaviour (Finding 4) or of the per-process scope of the gate (Finding 6).docs/same-process-tp.md:177-180(not opened) still lists the parked-rank/checkpoint region without the new qualification. - I found no guard/GUC/flag to disable the gate at runtime; if a user hits a pathological interaction on unsupported hardware there is no escape hatch short of not using prefix-cache offload.