Subtraction, Simplicity & Conventions review — PR #628, head 76e1813
Scope: 19 changed files, +1,165/−154. I checked the whole diff for removable code, duplication, and AGENTS.md violations, and spent most effort on the four largest new slabs: helios/src/offload/copy_gate.rs (new, 584 lines), the gated/un-gated transfer branches, the gate_wait plumbing, and the three new constructor/wrapper seams.
Key findings
- Three pure-delegation wrappers were added next to their gated twins instead of replacing them;
offload::openhas no caller anywhere in the repo,shard::join_peeris now test-only. Net deletion ≈25 lines and one constructor per seam. (§1) - One concept — "gated ⇒ lease + sync per batch, ungated ⇒ one sync at window end" — is implemented three times, with two hand-rolled drop guards and two
std::mem::forgetcalls. One smallGatedCopiestype absorbs all three. (§2) gate_wait/max_gate_waitis ~60 lines of plumbing whose only effect is to makeReply.elapsedsmaller, and that adjusted elapsed feeds a scheduling heuristic, so a gate-stalled transfer reports as faster and more attractive. Delete, don't patch — the downstream concern is a consequence of code that should not exist. (§3)- The fairness state machine has one honouring loop and one non-honouring loop, so on
RankPeers::Processes(newly wired into the gate by this same PR) it never arms; plusenter_peer_graph_timeoutis apubAPI added for one unit test. (§4) - Conventions verdict: clean. No substantive
AGENTS.mdviolation in what this PR adds — no flag, no env var, no config field, no per-model branch. (§5)
Findings 1, 2 and 4 overlap in location with correctness items in the other lens (multi-process fairness, worker teardown). Where that happens I am explicitly asking for deletion rather than a patch, and I say so at each site.
§1 Subtraction — three wrapper functions left behind
(a) helios/src/offload/mod.rs:114-130
pub fn open(
prepared: Prepared,
gpu_cubins: Vec<std::sync::Arc<Vec<u8>>>,
) -> Result<Box<dyn HostStore>> {
open_with_gate(prepared, gpu_cubins, None)
}
pub fn open_with_gate(
prepared: Prepared,
gpu_cubins: Vec<std::sync::Arc<Vec<u8>>>,
copy_gate: Option<std::sync::Arc<CopyEngineGate>>,
) -> Result<Box<dyn HostStore>> {
open has zero callers. Repo-wide search over helios, flare, flare-cli, heliopause finds only the definition and flare_selene::offload::open at mod.rs:126 (a different function). The single helios call site, helios/src/server/runtime.rs:731, already calls crate::offload::open_with_gate(prepared, gpu_cubins, copy_gate).
Remove: delete open (lines 114-119) and rename open_with_gate → open. One function, one name, one caller.
(b) helios/src/offload/shard.rs:37-45
pub fn join_peer(
store: Option<&Shared>,
gpu_cubins: Vec<std::sync::Arc<Vec<u8>>>,
stream: &mut RankStream,
rank: usize,
world: usize,
) -> Result<Option<Service>> {
join_peer_with_gate(store, gpu_cubins, None, stream, rank, world)
}
Production already moved to join_peer_with_gate (flare-cli/src/cluster.rs:254). The only remaining callers of join_peer are helios/src/offload/shard/tests.rs:20 (not opened) and helios/src/offload/pool/tests.rs:146 (not opened).
Remove: delete the wrapper and have those two test sites pass None as the gate argument (mechanical, one line each), keeping a single join_peer name.
(c) helios/src/offload/transfer.rs:2167-2175
impl Copiers {
#[cfg(test)]
pub(crate) fn new(gpu_cubins: Vec<std::sync::Arc<Vec<u8>>>) -> Self {
Self::with_gate(gpu_cubins, None)
}
pub(crate) fn with_gate(
gpu_cubins: Vec<std::sync::Arc<Vec<u8>>>,
copy_gate: Option<std::sync::Arc<super::CopyEngineGate>>,
) -> Self {
with_gate is already pub(crate); new exists only to save the literal None at ~20 test sites (offload/gpu_tests.rs:126 (not opened),286,456,588,650,856,1004,1266,1271,1558, transfer.rs:1555,1898, transfer/codec.rs:1266,1384,1388). A #[cfg(test)] shim that forwards a constant is exactly the kind of two-entry-point seam AGENTS.md:188-193 warns about.
Remove: delete new, rename with_gate → new (the tests then write Copiers::new(Vec::new(), None)), or keep the test-only shim but then have with_gate be the only public path and drop the extra name from the production surface. Either way one constructor, not two.
Combined: 3 functions deleted, ~25 lines, and one concept per seam instead of two.
§2 Simplicity — the gated/ungated sync branch is written three times
The invariant is simple: when there is a gate, hold a lease across one BATCH_BYTES batch and sync before releasing it; when there is no gate, enqueue everything and sync once at the end. That is expressed three separate times.
Site A — helios/src/offload/transfer.rs:308-339 (copy_batch_gated):
if let Some(gate) = copy_gate {
struct DrainOnDrop<'a>(&'a Stream, &'a Event);
impl Drop for DrainOnDrop<'_> {
fn drop(&mut self) {
drain_stream(self.0, self.1);
}
}
let (_ce, waited) = gate.enter_offload_batch();
// Declared after `_ce` so any error drains the stream before releasing the gate.
let drain = DrainOnDrop(stream, event);
unsafe {
stream.copy_batch(destinations, sources, sizes)?;
}
stream.record(event)?;
event.synchronize()?;
std::mem::forget(drain);
Ok(waited)
} else {
unsafe {
stream.copy_batch(destinations, sources, sizes)?;
}
Ok(Duration::ZERO)
}
The guard exists only to cover the two ? on record/synchronize, so the success path has to mem::forget the guard it just armed.
Site B — helios/src/offload/transfer/codec.rs:978-1033 (copy_spans_batch): the same shape with a second, differently-shaped guard and its own is_none() tests:
struct Fence<'a>(&'a Stream, &'a Event);
impl Drop for Fence<'_> {
fn drop(&mut self) {
drain_stream(self.0, self.1);
}
}
…let fence = copy_gate.is_none().then_some(Fence(stream, event)); at :1005, the flush closure at :990-1004, and at :1028-1032:
if copy_gate.is_none() {
stream.record(event)?;
event.synchronize()?;
}
std::mem::forget(fence);
Site C — helios/src/offload/transfer.rs:442-474 (RankWorker::run): a third copy of the conditional —
gate_wait += unsafe {
copy_batch_gated(
&self.stream,
&self.event,
self.copy_gate.as_deref(),
&self.destinations,
&self.sources,
&self.sizes,
)?
};
start = end;
}
if self.copy_gate.is_none() {
self.stream.record(&self.event)?;
self.event.synchronize()?;
}
Site C's trailing "flush now" is the same operation Site A performs inside its Some arm, and Site B's Fence is a strictly worse spelling of Site A's DrainOnDrop (it is then_some-constructed so the drain-on-error only applies on the un-gated path, where there is nothing to protect).
Replace all three with one type in helios/src/offload/transfer.rs:
pub(super) struct GatedCopies<'a> {
stream: &'a Stream,
event: &'a Event,
gate: Option<&'a super::CopyEngineGate>,
}
impl GatedCopies<'_> {
/// Gated: lease, copy, sync, release (drains the stream first on error).
/// Ungated: copy only.
fn batch(&mut self, dsts: &[u64], srcs: &[u64], lens: &[usize]) -> Result<()>;
/// Ungated: the single end-of-window sync. Gated: no-op.
fn finish(&mut self) -> Result<()>;
}
Then RankWorker::run (site C) and copy_spans_batch (site B) are each a loop of batch(...) plus one finish(), and copy_batch_gated collapses into batch's body. That removes two of the three copy_gate.is_none() branches, the whole second drop guard, and both mem::forget calls (the error path becomes an explicit if let Err(e) = res { drain_stream(stream, event); return Err(e) } inside batch, which is what the guards do implicitly and less legibly). drain_stream (already extracted by this PR at transfer.rs:290-296) is the natural home for that error path.
§3 Subtraction — gate_wait/max_gate_wait is ~60 lines to bias one metric. Delete the channel.
The PR makes every transfer function return a Duration so that Reply.elapsed can have gate wait subtracted:
helios/src/offload/transfer.rs:78gate_wait: DurationonRankReply;:85max_gate_waitonPending;:441,459,475accumulate and return it;:480-501propagate it into the reply;:690,1290,1302,1345,1426initialise it;:780reduces it; and:795-798:
elapsed: pending
.started
.elapsed()
.saturating_sub(pending.max_gate_wait),
- Signature churn for that single value:
RankWorker::run -> Result<(u64, Duration)>(transfer.rs:415),RankCodec::run(codec.rs:158-166),capture_window/restore_window/decode_pages_cpu_batch/copy_spans_batch(codec.rs:227,543,592,978), and 15gate_waitaccumulator sites incodec.rsalone (:240,304,339,375,399,470,504,601,635,698,718,781,801,813,989,997,1033). - The five GPU-codec sites were restructured from
let start = Instant::now(); … stats.transform_ns += start.elapsed()into(stored_len, elapsed, waited)triples, e.g.codec.rs:288-305:
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();
…
(stored_len, start.elapsed(), waited)
};
gate_wait += waited;
stats.transform_ns += elapsed.as_nanos() as u64;
(repeated verbatim at :318-340, :354-375, :675-700, :760-781).
The only consumer of the adjusted value is Reply.elapsed → selene/src/memory.rs:1450-1456 (self.outbound_rate.observe(reply.bytes, reply.elapsed)) → Selene's worth_fetching/worth_transfer deferral (selene/src/levels.rs:57-110 (not opened)). So the effect of these 60 lines is that a transfer which spent most of its life blocked on the gate is reported as fast, and therefore as attractive work — the opposite of the signal a scheduler should take from a stall. The max-across-ranks reduction (transfer.rs:780) is additionally an approximation of a per-rank quantity. Nothing in the PR measures a scheduling decision changing for the better.
Remove: the entire gate_wait channel — RankReply.gate_wait (transfer.rs:78), Pending.max_gate_wait (:85), the saturating_sub at :795-798, the Duration returns from copy_batch_gated/copy_spans_batch/RankCodec::run/capture_window/restore_window/decode_pages_cpu_batch, all gate_wait accumulators, and revert the five (stored_len, elapsed, waited) blocks to the pre-PR let start = Instant::now(); … stats.transform_ns += start.elapsed() form. The timers were already correctly moved after gate acquisition, so nothing of value is lost. ≈ −60 lines and 8 signature reverts. If stall visibility is genuinely wanted, add a counter beside the existing transform counters (where transform_ns already lives) rather than biasing elapsed.
This is a "delete, don't patch" call: the Correctness lens's concern about the heuristic is downstream of code that should not exist, so deleting subsumes that discussion.
§4 Subtraction — fairness machinery with one honouring loop, one non-honouring loop; plus a test-only pub API
CopyEngineGate carries a fairness state machine:
helios/src/offload/copy_gate.rs:34MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING,:36-41enum Turn,:43-52six-fieldState(includingpeer_entries_while_offload_waiting,turn,offload_wave_remaining),:54-68maybe_arm_offload_wave,:94-100should_yield_to_offload,:115-125the turn gate insideenter_peer_graph_timeout,:157-165streak accounting,:191-196wave decrement,:211-221drop-time re-arm, and:262-268PeerGraphLeases::should_drain_for_offload.
Sole consumer: 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)
}
reached from helios/src/server/runtime.rs:2261.
Non-consumer: helios/src/execution/parallel.rs:652-656 takes the lease with no such check (let guard = leases.enter(graph)?; then executor.submit(...)), so on RankPeers::Processes — the exact layout this same commit newly wires into the gate via flare-cli/src/cluster.rs:254-261 → helios/src/offload/shard.rs:47-61 — peer_graphs_active need never reach 0, maybe_arm_offload_wave never fires, and ~55 lines of state machine never take effect.
Concrete choice (this lens prefers the first): (a) delete the fairness machinery and keep the plain mutual-exclusion gate — peer-copy graphs wait for in-flight offload batches, offload batches wait for peer graphs — which removes Turn, MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING, maybe_arm_offload_wave, should_yield_to_offload, PeerGraphLeases::should_drain_for_offload and the streak/wave fields, leaving three counters; or (b) honour it in serve_rank too. Until a measurement shows starvation on the pipelined in-process path, (a) is the honest subtraction and also removes the asymmetry the Correctness lens flags.
Second, smaller item — helios/src/offload/copy_gate.rs:109-113:
/// Bounded variant of [`Self::enter_peer_graph`] with an explicit timeout.
pub fn enter_peer_graph_timeout(
self: &Arc<Self>,
timeout: Duration,
) -> Result<PeerGraphGuard> {
is pub but has exactly two callers in the repo, both tests (copy_gate.rs:509,518); the only production path is enter_peer_graph (:105-107). Make it #[cfg(test)] (or pub(crate)) rather than widening the crate's public surface for a test knob. Note the fairness unit test that uses it (offload_makes_forward_progress_under_pipelined_peer_graphs, copy_gate.rs:445-500) simulates the pause rather than driving RankExecutor, which is why it passes regardless of whether the real can_submit wiring exists — another reason the mechanism is unproven and deletable under option (a).
§5 Conventions verdict — clean; praise; rejected candidates
No substantive AGENTS.md violation in the added code. Checked:
- No per-model special cases or flags (
AGENTS.md:455-460): the gate keys on graph structure (Node::Copywith aMemory::Peerendpoint), not on a model, recipe or recipe parameter. - Never read an environment variable to choose behavior; no feature toggles or experiment switches (
AGENTS.md:450-455): the PR adds no flag, env var, or config field.Option<Arc<CopyEngineGate>>is not speculative generality — it is the single-GPU / non-peer-copy path, and removing it would regress those models. - Reject unsupported abstractions and churn; no speculative compatibility or fallback layers (
AGENTS.md:188-193): the closest call, and the reason §1 is a finding rather than a nit —open/open_with_gate,join_peer/join_peer_with_gate,Copiers::new/with_gateare "two entry points where one would do". - Protobuf/core-compat (
AGENTS.md:435-448): untouched;peer_copy_graphsis an in-processExecutionManifestfield defaulting tofalse, so existing exported cores load unchanged. - Docs (
AGENTS.md:43-60): thedocs/prefix-cache-offload.mdedits are specification wording, not run journals. Residual (low):docs/same-process-tp.md:177-180(not opened) still lists the parked-rank/checkpoint region as unqualified and was not updated.
Genuinely net-negative-line refactors in this PR (do not change; worth calling out):
RankExecutorsplit intoRankExecutorInnerwith the delegating methods on the inner enum (helios/src/execution/ranks.rs:17-95,130-145), soRankExecutoronly adds lease logic (:147-195).PeerGraphLeasesconsolidated and reused by both loops (ranks.rs:143,parallel.rs:563-566,652-663,692) — one lease-lifecycle type instead of two.drain_streamextracted (transfer.rs:290-296) and reused byRankWorker::drainand both drop guards.ExecutionManifest::has_peer_copiesdeleted and the unusedOffloadBatchGuardre-export dropped, replaced by avalidate()length check (helios/src/execution/manifest.rs:835-843).
Considered and deliberately NOT recommended:
- Collapsing
peer_copy_graphs: Vec<bool>to a single bool — gating only the graphs that contain peer copies is behaviourally different on mixed prefill/decode models, not redundant. - Merging
PeerGraphGuard/OffloadBatchGuardinto one RAII type — acquired on opposite sides with asymmetric drop semantics (copy_gate.rs:202-240); a tag would be less clear, not simpler. - Removing
PEER_GRAPH_GATE_TIMEOUT/bounded wait (copy_gate.rs:25-28,131-147) — a liveness guarantee, already minimal; its worker-teardown consequence is a Correctness item, not removable code. - Folding the five GPU-codec lease sites into one helper (
codec.rs:288-303,318-340,354-375,675-700,760-781) — each calls a differentgpu_codecentry point with different arguments; the real duplication there is thewaitedbookkeeping, which §3 removes wholesale.
Scope note: heliopause/src/python.rs:331 (not opened), helios/src/model/{contract,testing}.rs, execution/tests.rs, transfer/lifecycle_tests.rs (not opened) are mechanical field additions (peer_copy_graphs/gate_wait: Duration::ZERO) forced by new struct fields — no subtraction opportunity.
Open questions / not found
- No measurement anywhere in the PR justifies the
gate_waitsubtraction (§3); there is still no A/B offload throughput/latency figure and no measured gate cost, so theperformancelabel remains unsupported in the direction the charter asks (dossier §4, #210). - Whether a maintainer wants the fairness machinery kept-but-wired in
serve_rankrather than deleted (§4 option b) is unaddressed by anyone but the bot; no human review exists on76e1813. - I did not find any doc statement that the fairness turn depends on the submitting loop honouring
can_submit, nor any doc for the worker-fails-on-Drainbehaviour — relevant to §4's "honour it everywhere or delete it" decision.