Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #628

Raw Markdown for agents: https://autobot.eidonix.com/p/3067d6df-a009-490b-a3ca-a91f57a5bf19.md

#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:

                elapsed: pending
                    .started
                    .elapsed()
                    .saturating_sub(pending.max_gate_wait),
                        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.

  1. 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, uses open_with_gate. offload::shard::join_peer (shard.rs:37-45) is now called only from two test files, production goes through join_peer_with_gate. Copiers::new (transfer.rs:2168-2171) is #[cfg(test)] and only ever forwards None to with_gate. Collapse each pair to one function.

  2. 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-rolled DrainOnDrop + mem::forget), copy_spans_batch (codec.rs:979-1033, with a second, differently-shaped Fence guard, mem::forget, and its own copy_gate.is_none() tests at :1005 and :1028), and RankWorker::run (transfer.rs:459-474, a third is_none() branch). One small GatedCopies { stream, event, gate } with batch()/finish() absorbs all three and removes the duplicate drop guards and both mem::forgets; drain_stream, extracted by this PR, is its natural home.

  3. gate_wait/max_gate_wait is ~60 lines of plumbing to bias one metric. Threaded through RankReply, 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 from Reply.elapsed at transfer.rs:795-798. That adjusted elapsed feeds Selene's worth_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.

  4. 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 by RankExecutor::can_submit (ranks.rs:181-184); serve_rank takes its lease without checking (parallel.rs:652-656), so on RankPeers::Processes the machinery never arms. Either delete it (keeping the plain mutual-exclusion gate) or honour it in serve_rank; also enter_peer_graph_timeout is pub with 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):

Genuine net-negative-line refactors in this PR that should be called out as good (do not ask for changes):

Rejected subtraction candidates (considered, deliberately NOT recommended — mention briefly so the report does not look under-considered):

  1. Collapsing peer_copy_graphs: Vec<bool> to one has_peer_copies bool on ExecutionManifest. Rejected: gating only the graphs that contain peer copies is behaviourally different on mixed-graph models (prefill vs decode), not redundant. Keep the vector.
  2. Collapsing PeerGraphGuard/OffloadBatchGuard into 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.
  3. Removing PEER_GRAPH_GATE_TIMEOUT / enter_peer_graph bounded wait. Rejected for this lens: the timeout is a liveness guarantee, and its downstream effect (worker teardown on ExecutionError::Drain) is a Correctness-lens item (dossier 5.4), not removable code. It is also already minimal (copy_gate.rs:25-28, 131-147).
  4. 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 different gpu_codec entry point with different arguments; the duplication there is the waited bookkeeping, which finding S3 removes wholesale by deleting gate_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:

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.