Subtraction, Simplicity & Conventions review — PR #628 helios: gate offload Copy Engine batches during peer-copy graphs
Key findings
The diff is lean overall: no new configuration switch, env var, CLI flag, Protobuf field, serde attribute or dependency; helios/src/offload/copy_gate.rs (263 lines, ~50 of logic + behaviour tests) is a new abstraction with no equivalent anywhere in the repo (CopyEngineGate|PeerGraphGuard|OffloadBatchGuard|copy_gate has hits only inside this PR), and it has no speculative generality — #[derive(Default)] instead of a hand-written initializer, no optional branches. Four things can still be removed or collapsed:
- HIGH —
helios/src/offload/transfer.rs:398-428declares a bespokestruct DrainOnDropinside the batch loop whose body is byte-identical to the pre-existingRankWorker::drain()twelve lines below (transfer.rs:440-444), and duplicates the wholecopy_batchcall plus its SAFETY comment into anelsearm. The same gated/ungated duplication is repeated a third time incodec.rs:976-1001. One small helper removes ~40 lines, three copies of one SAFETY comment, and a nested struct. - HIGH —
helios/src/execution/manifest.rs:445-449:has_peer_copiesis dead public API. Its only references outside its own definition are three assertions in the test that was added in this same PR (helios/src/execution/ranks.rs:198-200); production code duplicates the expression inline atranks.rs:90. Delete the method (or the inline copy), not both. - MEDIUM —
helios/src/execution/ranks.rs:126-168: wrappingRankExecutoraround the newRankExecutorInnerenum forced five pure-delegation methods to grow a 4-linematcheach (net churn ~+25 lines in the diff). Onlysubmit,pollandcloseneed the wrapper; the other five should delegate in one line on the inner enum. - LOW —
helios/src/offload/mod.rs:26:OffloadBatchGuardis never named outsidecopy_gate.rs(every call site bindslet _ce = gate.enter_offload_batch();and infers the type); it does not belong in the re-export list.
Minor convention note: the new per-batch event.synchronize() contradicts prose that this PR leaves standing, including a module doc inside a changed file (helios/src/offload/transfer.rs:17-19, "The model stream never waits on these streams"). AGENTS.md:52-60 requires documents to state implemented behaviour; the substantive doc work is the Documentation lens's call, but that in-file sentence is free to fix here.
1. HIGH — the gated copy arm duplicates RankWorker::drain(), and the whole branch is written twice per file
helios/src/offload/transfer.rs:398-428 (verbatim):
if let Some(gate) = self.copy_gate.as_deref() {
struct DrainOnDrop<'a>(&'a Stream, &'a Event);
impl Drop for DrainOnDrop<'_> {
fn drop(&mut self) {
if self.0.record(self.1).is_err() || self.1.synchronize().is_err() {
let _ = self.0.synchronize();
}
}
}
let _ce = gate.enter_offload_batch();
// Declared after `_ce` so any error drains the stream before releasing the gate.
let drain = DrainOnDrop(&self.stream, &self.event);
// SAFETY: Device ranges lie inside the rank's cache allocations by
// the id checks in `expand`, and the submitting store keeps every
// slab mapped, registered, and unchanged until this job's reply.
unsafe {
self.stream
.copy_batch(&self.destinations, &self.sources, &self.sizes)?;
}
self.stream.record(&self.event)?;
self.event.synchronize()?;
std::mem::forget(drain);
} else {
// SAFETY: Device ranges lie inside the rank's cache allocations by
// the id checks in `expand`, and the submitting store keeps every
// slab mapped, registered, and unchanged until this job's reply.
unsafe {
self.stream
.copy_batch(&self.destinations, &self.sources, &self.sizes)?;
}
}
The Drop body is the pre-existing helper at helios/src/offload/transfer.rs:438-444:
/// Wait for every copy issued so far, sleeping on the blocking event where
/// it can be recorded and spinning on the stream otherwise.
fn drain(&self) {
if self.stream.record(&self.event).is_err() || self.event.synchronize().is_err() {
let _ = self.stream.synchronize();
}
}
and the identical gated/ungated split appears again at helios/src/offload/transfer/codec.rs:976-1001:
if !lens.is_empty() {
if let Some(gate) = copy_gate {
let _ce = gate.enter_offload_batch();
// Declared after `_ce` so any error drains the stream before releasing the gate.
let fence = Fence(stream);
// SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped.
unsafe {
stream.copy_batch(dsts, srcs, lens)?;
}
stream.record(event)?;
event.synchronize()?;
std::mem::forget(fence);
} else {
// SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped.
unsafe {
stream.copy_batch(dsts, srcs, lens)?;
}
}
Concrete simplification. Add one crate-visible helper next to the gate and call it from both files; the drain-on-error guarantee and declaration order are preserved in a single place:
/// Issue one Copy Engine batch, holding the gate lease (when `gate` is set) until
/// the stream has drained, and drain on error before releasing that lease.
pub(crate) fn copy_batch_gated(
stream: &Stream,
event: &Event,
gate: Option<&CopyEngineGate>,
destinations: &[u64],
sources: &[u64],
sizes: &[usize],
) -> Result<()> {
struct DrainOnDrop<'a>(&'a Stream, &'a Event);
impl Drop for DrainOnDrop<'_> {
fn drop(&mut self) {
if self.0.record(self.1).is_err() || self.1.synchronize().is_err() {
let _ = self.0.synchronize();
}
}
}
let _ce = gate.map(CopyEngineGate::enter_offload_batch);
let drain = _ce.is_some().then(|| DrainOnDrop(stream, event));
// SAFETY: Device ranges lie inside the rank's cache allocations by the id
// checks in `expand`, and the submitting store keeps every slab mapped,
// registered, and unchanged until this job's reply.
unsafe { stream.copy_batch(destinations, sources, sizes)? };
if _ce.is_some() {
stream.record(event)?;
event.synchronize()?;
std::mem::forget(drain);
}
Ok(())
}
Call sites then become one line each (transfer.rs: copy_batch_gated(&self.stream, &self.event, self.copy_gate.as_deref(), &self.destinations, &self.sources, &self.sizes)?; in the loop; codec.rs flush: copy_batch_gated(stream, event, copy_gate, dsts, srcs, lens)?;), the trailing if self.copy_gate.is_none() { ... } (transfer.rs:431-434) and if copy_gate.is_none() { ... } (codec.rs:1025-1028) stay as the ungated end-of-job drain, and DrainOnDrop/the codec's duplicated arm disappear. Note the success path must keep propagating record/synchronize errors — do not replace it with RankWorker::drain(), which swallows them; drain() alone stays correct only for the ungated end-of-job path where it is already used.
2. HIGH — has_peer_copies is API with no production caller
helios/src/execution/manifest.rs:445-449:
impl ExecutionManifest {
/// Whether graph `index` executes in-graph peer-to-peer Copy Engine nodes.
pub fn has_peer_copies(&self, index: usize) -> bool {
self.peer_copy_graphs.get(index).copied().unwrap_or(false)
}
Whole-repository references (search_code): the definition, plus helios/src/execution/ranks.rs:198-200, which are assertions added by this PR's own new test:
assert!(!manifest().has_peer_copies(0));
assert!(root.has_peer_copies(1));
assert!(!root.has_peer_copies(99));
The real decision point does not use it, because RankExecutor stores the merged Vec<bool> rather than a manifest (helios/src/execution/ranks.rs:90):
let guard = if self.peer_copy_graphs.get(graph).copied().unwrap_or(false) {
Concrete simplification. Pick one and delete the other: either drop has_peer_copies plus its three assertions (keeping only the merge_peer_copy_graphs assertions, which test real behaviour), or keep the helper and have submit call a free function with the same body instead of re-spelling .get(graph).copied().unwrap_or(false). Shipping both a helper and its inline duplicate, with the helper asserted only by its own test, is the redundancy.
3. MEDIUM — five pure-delegation methods re-grew a match because of the new wrapper enum
helios/src/execution/ranks.rs:126-168 — park, outstanding, manifest, can_submit, next_fence are each now a four-line match &self.inner, e.g. park (verbatim):
/// Wait briefly for this rank's running frame; false when the caller should keep polling.
pub(crate) fn park(&self) -> bool {
match &self.inner {
RankExecutorInner::Local(executor) => executor.park(),
RankExecutorInner::Parallel(executor) => executor.park(),
RankExecutorInner::Threaded(_) => false,
}
}
Before the PR these were match self { Self::Local(..) => ... }; the change added &self.inner to five matches (net +25 lines) purely because RankExecutor became a struct. Only submit, poll and close actually need the wrapper, because only they touch copy_gate/peer_guards.
Concrete simplification. Move the match into impl RankExecutorInner once (fn park(&self) -> bool { match self { Self::Local(e) => e.park(), Self::Parallel(e) => e.park(), Self::Threaded(_) => false } }, same for the other four), and reduce each RankExecutor method to self.inner.park(). ~20 lines removed from the diff, and the inner enum is where they belong.
4. LOW — OffloadBatchGuard is exported but never named
helios/src/offload/mod.rs:26:
pub use copy_gate::{CopyEngineGate, OffloadBatchGuard, PeerGraphGuard};
OffloadBatchGuard appears outside copy_gate.rs nowhere (all call sites are let _ce = gate.enter_offload_batch();, let _ce = copy_gate.map(...), or Option<OffloadBatchGuard>-free); CopyEngineGate and PeerGraphGuard are genuinely imported elsewhere (ranks.rs:14-18, codec.rs). Drop the middle name from the re-export. Trivial, but it is public surface added for nothing.
5. Convention note — prose inside a changed file that the change falsifies
helios/src/offload/transfer.rs:17-19 (module doc, part of the changed file):
//! is reported only after the stream has drained, so destination ids are
//! quiescent when the scheduler frees them. The model stream never waits on
//! these streams: host-observed completion orders later model work after the
//! copies.
With the gate, an offload batch now records and synchronizes per batch and the model worker thread can block in enter_peer_graph until in-flight batches drain (helios/src/offload/copy_gate.rs:45-56, helios/src/execution/ranks.rs:90-96) — exactly the situation docs/prefix-cache-offload.md:133 (not opened) ("Offload work never blocks the model worker thread or the model stream"), :907 and :1015 declare impossible. No docs/ file is in the changed set. AGENTS.md:52-60 requires documents to state what the code implements. The docs rewrite itself belongs to the Documentation lens; the paragraph above is a one-sentence fix available in this PR's own diff, so at minimum it should not be left asserting the opposite of the new behaviour.
Checked and deliberately not proposed (so they are not re-raised)
peer_copy_graphs: Vec<bool>instead of aboolonGraphDescriptor(manifest.rs:185-204):GraphDescriptorliterals are spread across ~40 sites inscheduler/*_tests.rs(not opened),model/testing.rs,execution/tests.rs; the parallel vector is the cheaper choice, and the cross-rank union would still be needed either way.merge_peer_copy_graphs(ranks.rs:39-52) is already minimal (resize+zipOR).copy_gatethreaded through ninecodec.rs/transfer.rssignatures (hence the two new#[allow(clippy::too_many_arguments)]atcodec.rs:152andtransfer.rs:305): a field onRankCodec(codec.rs:44-51) would collapse it, but thetry_locksites (codec.rs:664-668, 749-752) read the gate while holding&mutborrows ofself.gpu, so it would need per-jobArcclones. Not worth the churn; thetoo_many_argumentsallows are the honest price.offload::openkept as aNonewrapper (mod.rs:114-119): no remaining in-repo caller, but it ispubAPI predating the PR — correct to keep.Copiers::newkept aswith_gate(.., None)(transfer.rs, +5 lines): has ~15 test callers (gpu_tests.rs(not opened),codec.rstests), so the wrapper is the right call.copy_gate.rsitself, the detection closure (runtime_core/mod.rs:1149-1156, reusing the existingallocationsmap),serving.rs:56-59,Binding::copy_gate()(mod.rs:58-60, needed becausetake()moves the inner binding), and the mechanicalpeer_copy_graphs: vec![]struct literals (heliopause/src/python.rs:331,execution/tests.rs:206,model/testing.rs:396,model/contract.rs:983) — all minimal; nothing to subtract. The new tests are behaviour tests (barriers, panic unwind, priority, asymmetric union), not source-text checks, so AGENTS.md:194-196 is satisfied.
Open questions / not found
- Whether the per-batch
record+synchronizenow applied on every prefix-cache run (the gate isSomefor every binding aNativeModelbuilds,runtime_core/model.rs:986-989,1032-1038) costs measurable restore throughput — the PR has no measurement, and #497 retuned this same worker for latency. If the cost is real, the per-batch sync is the line to revisit; it is a design question, not a subtraction I can settle from the code. - I could not retrieve which CI job failed on head
1870a27; the PR claims cleancargo check/test runs (the dossier records CI as failed). Nothing in these four suggestions depends on that outcome.