#1 [high] S1: three ungated wrapper fns left behind (dead code)
Subtraction finding #1. Three wrapper functions exist only because the gated variant was added alongside instead of replacing them.
(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 anywhere in the repo (searched offload::open, open(prepared across helios, flare, flare-cli, heliopause: the only hits are flare_selene::offload::open at mod.rs:126 and selene's own tests). The single helios caller is helios/src/server/runtime.rs:731 which uses open_with_gate. Delete open and rename open_with_gate -> open.
(b) helios/src/offload/shard.rs:37-61:
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)
}
Only callers are tests: helios/src/offload/shard/tests.rs:20 and helios/src/offload/pool/tests.rs:146. Production caller is flare-cli/src/cluster.rs:254 using join_peer_with_gate. Move join_peer under #[cfg(test)] or delete and have the two tests pass None.
(c) helios/src/offload/transfer.rs:2167-2182:
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(
with_gate is already pub(crate) and None is one extra argument; all ~20 Copiers::new(...) sites are tests. Delete new and let the tests pass None (mechanical, one line each), leaving one constructor.
Net: 3 functions removed, ~25 lines, and one constructor/concept per seam instead of two.
#2 [high] S2: same gated/ungated sync branch written three times
Subtraction finding #2: one concept, three implementations of "gated ⇒ sync per batch; ungated ⇒ one sync at the end".
Site A — helios/src/offload/transfer.rs:316-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 + mem::forget dance exists only to cover the two ? on record/synchronize; the success path has to defuse the guard it just armed.
Site B — helios/src/offload/transfer/codec.rs:979-1033 (copy_spans_batch) repeats the same shape with a second, different guard (struct Fence<'a>(&'a Stream, &'a Event)), its own copy_gate.is_none() test at :1005 and :1028-1031, and its own std::mem::forget(fence).
Site C — helios/src/offload/transfer.rs:459-474 (RankWorker::run):
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()?;
}
A third copy of the is_none() conditional, and it is the same "flush everything now" that site A already performs inside its Some arm.
Concrete simplification: introduce one small type in helios/src/offload/transfer.rs, e.g.
pub(super) struct GatedCopies<'a> { stream: &'a Stream, event: &'a Event, gate: Option<&'a super::CopyEngineGate> }
impl GatedCopies<'_> {
fn batch(&mut self, dsts: &[u64], srcs: &[u64], lens: &[usize]) -> Result<()>; // lease+copy+sync when gated, copy only otherwise
fn finish(&mut self) -> Result<()>; // one sync when ungated; no-op otherwise
}
Then RankWorker::run (site C) and copy_spans_batch (site B) both become a loop of batch(...) plus one finish(); copy_batch_gated shrinks to the body of batch. That removes two of the three copy_gate.is_none() branches, two of the three hand-rolled drop guards, and lets mem::forget disappear (the error drain can be an explicit if let Err(e) = ... { drain_stream(..); return Err(e) }, or batch returning after a drain).
Also worth folding in: drain_stream (transfer.rs:290-296) was extracted in this PR and is already used by RankWorker::drain, both guards — a GatedCopies type is the natural home for the remaining duplication.
#3 [high] S3: gate_wait plumbing is ~60 lines to fudge one metric
Subtraction finding #3 (biggest single slab of new code): gate_wait / max_gate_wait.
The PR makes every transfer function return Duration so that Reply.elapsed can have the gate wait subtracted:
helios/src/offload/transfer.rs:78gate_wait: DurationonRankReply;:85max_gate_wait: DurationonPending;:441accumulator;:459-468+=;:475return;:486-501propagate into the reply;:690init;:780pending.max_gate_wait = pending.max_gate_wait.max(reply.gate_wait);;:795-798:
elapsed: pending
.started
.elapsed()
.saturating_sub(pending.max_gate_wait),
- Signature churn for that one value:
RankWorker::run -> Result<(u64, Duration)>(transfer.rs:415),RankCodec::run -> Result<(u64, Duration)>(codec.rs:158-166),capture_window/restore_window/decode_pages_cpu_batch/copy_spans_batchall gain it (codec.rs:227, 592, 543, 978). - Five GPU-codec sites restructured from
let start = Instant::now(); ... stats.transform_ns += start.elapsed()intolet (stored_len, elapsed, waited) = { ... Some((start.elapsed(), waited)) }triples, e.g. codec.rs:288-305 and codec.rs:673-699:
let gpu_ran = {
if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() {
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();
...
Some((start.elapsed(), waited))
} else { None }
};
if let Some((elapsed, waited)) = gpu_ran {
gate_wait += waited;
stats.transform_ns += elapsed.as_nanos() as u64;
Why this is a subtraction candidate rather than a keeper: the only consumer is Reply.elapsed, which per the PR's own dossier feeds Selene's worth_fetching/worth_transfer scheduling choice (selene/src/memory.rs:1450-1456, selene/src/levels.rs:57-110). Subtracting the wait makes a gate-stalled transfer report as faster, i.e. as more attractive work — the opposite of what the scheduler should learn from a stall, and the max-across-ranks reduction is only an approximation of a per-rank quantity anyway. There is no measurement in the PR showing this adjustment changes any scheduling decision for the better.
Concrete simplification: delete the whole gate_wait channel — RankReply.gate_wait, Pending.max_gate_wait, the saturating_sub at transfer.rs:795-798, the Duration returns from copy_batch_gated/copy_spans_batch/RankCodec::run/capture_window/restore_window/decode_pages_cpu_batch, the gate_wait accumulators at codec.rs:240, 601, 989, and revert the five (stored_len, elapsed, waited) blocks to the original let start = Instant::now(); ... stats.transform_ns += start.elapsed() form (the timers themselves were already correctly moved after gate acquisition). Roughly −60 lines and 8 signature reverts. If a stall metric is genuinely wanted, report it separately (e.g. a counter next to the existing transform counters) rather than biasing elapsed.
Note for the report: keep this framed as "delete, don't patch" — the Correctness lens's concern about the heuristic is downstream of code that simply shouldn't exist.
#5 [high] Research summary
Subtraction/Simplicity/Conventions review of PR #628 (head 76e1813, 19 files, +1,165/−154) done. Four high-value simplifications are on the scratchpad, each with verbatim quotes and file:line citations, and each is a deletion rather than a patch.
-
Three pure-delegation wrappers left behind (zero or test-only callers).
offload::open(helios/src/offload/mod.rs:114-119) has no caller at all in the repo — the sole helios caller,server/runtime.rs:731, usesopen_with_gate.offload::shard::join_peer(shard.rs:37-45) is now called only from two test files, production goes throughjoin_peer_with_gate.Copiers::new(transfer.rs:2168-2171) is#[cfg(test)]and only ever forwardsNonetowith_gate. Collapse each pair to one function. -
One concept, three implementations. "Gated ⇒ lease + sync per batch; ungated ⇒ one sync at window end" is written out three times:
copy_batch_gated(transfer.rs:316-339, with a hand-rolledDrainOnDrop+mem::forget),copy_spans_batch(codec.rs:979-1033, with a second, differently-shapedFenceguard,mem::forget, and its owncopy_gate.is_none()tests at :1005 and :1028), andRankWorker::run(transfer.rs:459-474, a thirdis_none()branch). One smallGatedCopies { stream, event, gate }withbatch()/finish()absorbs all three and removes the duplicate drop guards and bothmem::forgets;drain_stream, extracted by this PR, is its natural home. -
gate_wait/max_gate_waitis ~60 lines of plumbing to bias one metric. Threaded throughRankReply,Pending,RankWorker::run,RankCodec::run,capture_window,restore_window,decode_pages_cpu_batch,copy_spans_batch, and it forces the five GPU-codec sites into(stored_len, elapsed, waited)triples — all to subtract fromReply.elapsedattransfer.rs:795-798. That adjusted elapsed feeds Selene'sworth_fetching/worth_transfer, so a gate-stalled transfer reports as faster and more attractive; the max-across-ranks reduction is an approximation and no measurement in the PR supports the adjustment. Recommend deleting the channel and reverting the signatures/blocks; if stall visibility is wanted, report it separately. -
Fairness machinery with one honouring loop, plus a test-only public API.
Turn,MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING,maybe_arm_offload_wave,should_yield_to_offload, the streak fields and drop-time re-arm (~55 lines,copy_gate.rs:34-68, 94-100, 115-125, 191-196, 211-221, 262-268) are read only byRankExecutor::can_submit(ranks.rs:181-184);serve_ranktakes its lease without checking (parallel.rs:652-656), so onRankPeers::Processesthe machinery never arms. Either delete it (keeping the plain mutual-exclusion gate) or honour it inserve_rank; alsoenter_peer_graph_timeoutispubwith one test-only caller.
Conventions: no AGENTS.md violation of substance found — the gate is model-agnostic, adds no config flag or env switch, no per-model branch, and the RankExecutorInner split, PeerGraphLeases consolidation, drain_stream extraction and dead has_peer_copies removal are genuinely net-negative-line refactors worth praising. I considered but rejected asking to drop the per-graph peer_copy_graphs: Vec<bool> in favour of a single boolean, since per-graph precision is behaviourally different, not redundant. The diff past the four items above is lean.
#6 [high] S5: conventions verdict — clean, plus rejected candidates and praise list
Conventions verdict (report must state this plainly): I found NO substantive AGENTS.md violation in the parts this PR adds.
Checked against AGENTS.md (read in full, AGENTS.md:1-521):
- "No per-model special cases or flags" (
AGENTS.md:455-460, charter "Code Review Standards"): the gate is structural (Memory::Peerendpoint on aNode::Copy), not a model or recipe branch. PASS. - "Configuration: never read an environment variable to choose behavior / no feature toggles or experiment switches" (
AGENTS.md:450-455): the PR adds no flag, no env var, no config field. The gate is derived from exported graph contents and isOption-typed only to keep the ungated path free. PASS. - "Reject unsupported abstractions and churn… no speculative compatibility, fallback layers, or configuration switches without a concrete requirement" (
AGENTS.md:188-193): this is the closest call — theopen/open_with_gate,join_peer/join_peer_with_gate,Copiers::new/with_gatepairs are exactly "two entry points where one would do", which is why they are scratchpad finding S1 rather than a charter violation. The ungatedNonepath is not speculative: it is the single-GPU / non-peer-copy path and removing it would regress those models. - Protobuf/core-compat rules (
AGENTS.md:435-448): no Protobuf change;peer_copy_graphsis an in-processExecutionManifestfield, absent ⇒false, so existing exported cores load unchanged. PASS. - Prose/doc rules (
AGENTS.md:43-60, "record unresolved defects and pending measurements in docs/TODO.txt, not design documents"): the doc edits indocs/prefix-cache-offload.mdare specification wording, not run journals. Residual, low-importance:docs/same-process-tp.md:177-180still lists the parked-rank/checkpoint region as not qualified and was not updated by this PR (file not opened; flagged in the dossier, worth one sentence at most).
Genuine net-negative-line refactors in this PR that should be called out as good (do not ask for changes):
RankExecutorsplit intoRankExecutorInnerwith pure delegation moved onto the inner enum (helios/src/execution/ranks.rs:17-95), soRankExecutoronly adds lease logic. Removes ~20matcharms' worth of duplicatedpub(crate)surface.PeerGraphLeasesconsolidated and reused by bothRankExecutor(ranks.rs:143) andserve_rank(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.- Dead
ExecutionManifest::has_peer_copiesdeleted and the unusedOffloadBatchGuardre-export dropped (author's 12:55 changelog), replaced by avalidate()length check (manifest.rs:835-843).
Rejected subtraction candidates (considered, deliberately NOT recommended — mention briefly so the report does not look under-considered):
- Collapsing
peer_copy_graphs: Vec<bool>to onehas_peer_copiesbool onExecutionManifest. Rejected: gating only the graphs that contain peer copies is behaviourally different on mixed-graph models (prefill vs decode), not redundant. Keep the vector. - Collapsing
PeerGraphGuard/OffloadBatchGuardinto one RAII type. Rejected: the two leases are acquired on different sides and have asymmetric drop semantics (copy_gate.rs:209-240); merging would need a tag and would be less clear, not simpler. - Removing
PEER_GRAPH_GATE_TIMEOUT/enter_peer_graphbounded wait. Rejected for this lens: the timeout is a liveness guarantee, and its downstream effect (worker teardown onExecutionError::Drain) is a Correctness-lens item (dossier 5.4), not removable code. It is also already minimal (copy_gate.rs:25-28, 131-147). - Asking to fold the five GPU-codec lease sites into one helper (
codec.rs:288-303, 318-338, 354-374, 675-696, 760-778). Rejected as scope creep: each site calls a differentgpu_codecentry point with different arguments; the duplication there is thewaitedbookkeeping, which finding S3 removes wholesale by deletinggate_wait. Deleting S3 subsumes it.
Scope note: I did not review heliopause/src/python.rs:331 (peer_copy_graphs: Vec::new()) or helios/src/model/{contract,testing}.rs, execution/tests.rs, transfer/lifecycle_tests.rs beyond confirming they are mechanical field additions forced by the new struct field — no subtraction opportunity there.
#4 [medium] S4: fairness machinery has one consumer, one non-consumer; test-only public API
Subtraction finding #4 (medium; the correctness half belongs to the Correctness lens — dossier finding 5.1).
CopyEngineGate carries fairness state that only one of the two submit loops honours:
helios/src/offload/copy_gate.rs:34MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING,:36-52Turn+ 4 state fields (turn,offload_wave_remaining,peer_entries_while_offload_waiting, plus the streak),:54-68maybe_arm_offload_wave,:94-100should_yield_to_offload,:115-125the turn gate inenter_peer_graph_timeout,:157-165streak accounting,:191-196wave decrement,:211-221drop-time re-arm, and:262-268PeerGraphLeases::should_drain_for_offload.- Sole consumer:
RankExecutor::can_submit(helios/src/execution/ranks.rs:181-184,#[cfg(feature = "server")]), reached fromhelios/src/server/runtime.rs:2261. - Non-consumer:
serve_rank(helios/src/execution/parallel.rs:652-656) takes the lease withleases.enter(graph)?and never asks whether it should pause, so onRankPeers::Processesthe wave never arms and the streak logic is unreachable in effect.
So today ~55 lines of state machine buy nothing on the multi-process layout that the same commit wires into the gate (flare-cli/src/cluster.rs:254-261). Concrete choices: (a) delete the fairness machinery and keep only the plain "peer graph waits for in-flight offload batches; offload waits for peer graphs" gate (then state shrinks to 3 counters and Turn/MAX_PEER_STREAK/maybe_arm_offload_wave/should_yield_to_offload all go, along with PeerGraphLeases::should_drain_for_offload), or (b) honour it in serve_rank too. Deleting is the honest subtraction until a measurement shows starvation on the pipelined in-process path.
Also 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 one caller in the whole repo: the unit test at copy_gate.rs:505-522. Make it #[cfg(test)] (or pub(crate)) rather than widening the crate's public surface for a test knob.
Positive note for the report: the rest of the gate itself (PeerGraphLeases, PeerGraphGuard/OffloadBatchGuard RAII, drain_stream extraction, RankExecutorInner split so the delegating methods live on the inner enum) is lean and idiomatic — those refactors removed more than they added and should be called out as good.