Subtraction and simplicity report · NVIDIA/hyperflare-inference #674

Raw Markdown for agents: https://autobot.eidonix.com/p/f0f76449-76c4-4218-9ba9-d430def8970b.md

Subtraction, Simplicity & Conventions — review of #674 @ 19ce4a7b

Key findings

The packaging parts of this diff genuinely subtract (Incoming::clear_pool_lookup, the three-scalar host_lookup_cost, the single-child-role map in helios/src/cache.rs), but four of the new mechanisms re-implement machinery the repo already owns, one adds a 13-parameter function behind a clippy allow, and one threads a bool that only means "someone else already refreshed" — and thereby buys a duplicate refresh. No env vars, feature switches or speculative flags appear in the files I read (AGENTS.md:450-472, Configuration, is respected).

  1. S1 (high) — delete RowRestoreLatency, don't patch it. It is a third copy of selene::levels::Rate (selene/src/levels.rs:36-87, median-of-3, 10 s recovery, in-flight hold) and it is where the one real defect (the decay clock) lives.
  2. S2 (high) — two "half the prefill" predicates. helios/src/server/runtime.rs:225-229 duplicates selene/src/store.rs:459-468, and after this PR the selene one has no non-test production caller left.
  3. S3 (medium) — plan_refreshed: bool (runtime.rs:3296,3303-3309) closes a loop with begin_pool_lookup's new -> bool and produces three refresh_admission_plan_in_place call sites for one admission attempt, two of them on the retry path.
  4. S4 (medium) — Arena::coalescing_block's Some((0, 0)) arm duplicates can_allocate (arena.rs:145-152), is pre-empted by both callers, and costs a free-map clone() on the per-waiter scan path.
  5. S5 (medium) — admit_with_host_store is 13 positional params under #[allow(clippy::too_many_arguments)], six of them new; AGENTS.md:338 asks Helios to be kept as simple as possible.
  6. S6 (low) — Ranking::rates() -> [f64; 4] plus hardcoded positional labels gives one ordered set three representations; also the scan_writeback_waiters_step cursor is derived three ways.

S1 (high) — RowRestoreLatency re-implements selene::levels::Rate; delete the copy instead of fixing its clock

helios/src/server/runtime.rs:270-343 adds ~75 lines:

#[derive(Default)]
struct RowRestoreBucket {
    in_flight: usize,
    samples: [f64; 3],
    count: usize,
    next: usize,
    last_median: Option<(f64, std::time::Instant)>,
}
    fn estimate_seconds(&self, source: RowRestoreSource) -> f64 {
        ...
        if bucket.in_flight > 0 {
            return median;
        }
        median * 0.5f64.powf(last.elapsed().as_secs_f64() / Self::RECOVERY_SECONDS)
    }

selene/src/levels.rs:36-87 is the same object for the same purpose, and already contains the correct in-flight hold that this copy got wrong:

pub(crate) struct Rate {
    seed: f64,
    median: f64,
    samples: [f64; 3],
    count: usize,
    next: usize,
    last: Option<Instant>,
}
    /// A restore started: hold the estimate at the median until it reports.
    pub(crate) fn started(&mut self) {
        if self.median < self.seed {
            self.last = Some(Instant::now());
        }
    }

The copy's start() is exactly where the correctness defect sits — it bumps the decay timestamp unconditionally (runtime.rs:301-303: if let Some((_, last)) = &mut bucket.last_median { *last = now; }), so a finish(false) (:313-315, returns before observe) resets a fully decayed median to 100 % for another 10 s half-life. Delete the copy rather than patch the line.

Replace with: lift Rate to be reusable for seconds-per-op samples (a seed of f64::INFINITY / a "no ceiling" constructor, since Rate::get clamps at seed — levels.rs:69-76), keep HashMap<RowRestoreSource, Rate> plus the per-source in-flight count in Helios if the two-caller hold semantics really differ, and drop RowRestoreBucket/observe/estimate_seconds. That removes ~70 lines and the third divergent copy of median logic after Rate and scheduler::cost::PrefillBucket (helios/src/scheduler/cost.rs:236-262).

Caveat to state: Rate is pub(crate) and decays upward toward seed in bytes/s while this one decays downward in seconds/op, so this is lift-and-generalize (a thin Latency wrapper over Rate), not a drop-in.

S2 (high) — two "half the prefill" predicates; the selene one is production-dead

helios/src/server/runtime.rs:223-229:

/// A host restore is worthwhile when its transfer (plus any accumulated wait)
/// takes less than half the GPU prefill time it replaces.
fn worth_restore(transfer_seconds: f64, prefill_saved_seconds: f64) -> bool {
    transfer_seconds.is_finite()
        && prefill_saved_seconds.is_finite()
        && transfer_seconds < 0.5 * prefill_saved_seconds
}

selene/src/store.rs:458-468 already owns this rule and exports it (selene/src/lib.rs:53 (not opened)):

/// The same rule for `gained_tokens` of prefill replaced by a transfer of `estimated_seconds`.
pub fn worth_transfer(
    gained_tokens: u64,
    estimated_seconds: f64,
    prefill_tokens_per_second: f64,
) -> bool {
    if !estimated_seconds.is_finite() || !prefill_tokens_per_second.is_finite() {
        return false;
    }
    estimated_seconds < 0.5 * gained_tokens as f64 / prefill_tokens_per_second.max(1.0)
}

After this PR the only non-test callers of worth_fetching/worth_transfer are gone: worth_fetching (store.rs:450-456) survives only in tests (selene/src/composite.rs:2920,2923, selene/src/disk_store/coalesce/tests.rs:1798 (not opened),1967,2142,2258).

Replace with: pub fn worth_restore_seconds(transfer_seconds: f64, prefill_saved_seconds: f64) -> bool next to worth_transfer in selene/src/store.rs, with worth_transfer(g, s, tps) expressed through it (worth_restore_seconds(s, g as f64 / tps.max(1.0))); delete worth_restore from Helios and delete worth_fetching from the public surface if tests are all that needs it. One predicate, one home, one pair of finite guards.

S3 (medium) — plan_refreshed: bool exists only to say "already refreshed", and buys a duplicate refresh

helios/src/server/runtime.rs:3303-3315:

    let plan = match (queued_plan, plan_refreshed) {
        (Some(plan), true) => plan.clone(),
        (Some(plan), false) => {
            let mut plan = plan.clone();
            scheduler.refresh_admission_plan_in_place(&mut plan)?;
            plan
        }
        (None, _) => scheduler.plan_admission_with_core_parameters(

The flag is produced solely by begin_pool_lookup's new -> bool (runtime.rs:3188), which refreshes in place itself at :3206-3209 and :3221-3224, and is consumed solely at the one call site (runtime.rs:1613-1624 → :1653). That yields three refresh_admission_plan_in_place call sites (:3207, :3222, :3307) for a single admission attempt, so a request that arrives with plan_refreshed == false refreshes twice on the retry path.

Replace with: a single refresh located in admit_with_host_store; begin_pool_lookup returns nothing (()), and the (Some, true) | (Some, false) arms collapse into one Some(plan) => plan.clone() plus one refresh. The as_mut().unwrap() / as_ref().unwrap() at :3206 and :3235 go with it.

S4 (medium) — Arena::coalescing_block's Some((0, 0)) sentinel is unreachable in production and duplicates can_allocate

selene-manager/src/arena.rs:154-175 (doc comment in full):

    /// Returns `Some((0, 0))` when `length` already fits without evicting any
    /// candidate, `Some((block_offset, block_size))` for the first coalesced
    /// buddy block satisfying `length` (so callers need to evict only candidates
    /// inside `[block_offset, block_offset + block_size)`), or `None` when even
    /// releasing every candidate cannot form the required buddy block.
    pub fn coalescing_block(
        &self,
        length: usize,
        candidates: &[(usize, usize)],
    ) -> Option<(usize, usize)> {
        let capacity = length.max(4096).checked_next_power_of_two()?;
        let mut free = self.0.free.lock().unwrap().clone();
        if free
            .range(capacity..)
            .any(|(_, offsets)| !offsets.is_empty())
        {
            return Some((0, 0));
        }

That predicate is can_allocate verbatim (arena.rs:145-152), and both callers rule it out first:

Replace with: drop the free clone, the range scan and the Some((0, 0)) arm; return None when no candidate set coalesces, delete the if block_size > 0 guard at store.rs:2256, and re-point the unit test at arena.rs:390 (its only remaining exerciser of the sentinel). Bonus: store.rs:1567 runs on the per-writeback-waiter scan path, so this removes a free-map clone() from a hot loop.

S5 (medium) — admit_with_host_store is 13 positional parameters under a clippy allow

helios/src/server/runtime.rs:3285-3302:

#[allow(clippy::too_many_arguments)]
fn admit_with_host_store(
    scheduler: &mut RequestScheduler,
    store: &mut dyn flare_selene::HostStore,
    pool_lookup: Option<&flare_selene::pool::LookupTicket>,
    spec: RequestSpec,
    prefill_spans: &[std::ops::Range<usize>],
    conditioned_images: &[crate::frontend::images::PreparedImageInput],

Six of the 13 are new in this PR, and prefill_spans + conditioned_images exist only to feed estimated_prefill_saved_seconds (:3260-3281). AGENTS.md:338 asks that Helios "be kept as simple as possible"; a positional call with six same-shaped arguments (&[...], &[...], &[...], Option<&...>, bool, …) is precisely the swap hazard that struct was invented for.

Replace with: one struct RestoreProbe<'a> { spec: &'a RequestSpec, prefill_spans: &'a [Range<usize>], conditioned_inputs: Vec<ConditionedInput> } built once at the call site, and drop the allow. This also absorbs a real duplication: the identical PreparedImageInput::conditioned_input collection is written twice — runtime.rs:1721-1727 and runtime.rs:3324-3327.

S6 (low, cheap) — Ranking::rates() -> [f64; 4] plus hardcoded positional labels

selene/src/levels.rs:119-128 returns a positional array that silently skips Level::ThisGpu:

    /// Current transfer rates in bytes per second for pool restore levels:
    /// `[NeighbourGpu, HostDram, HostNvme, RemoteNvme]`.
    pub fn rates(&self) -> [f64; 4] {
        [
            self.rates[Level::NeighbourGpu.index()].get(),
            self.rates[Level::HostDram.index()].get(),
            self.rates[Level::HostNvme.index()].get(),
            self.rates[Level::RemoteNvme.index()].get(),
        ]
    }

and helios/src/server/metrics.rs:1418-1423 re-supplies the same four names by index:

            for (level, value) in [
                ("neighbour_gpu", &self.host_pool_inbound_rates[0]),
                ("host_dram", &self.host_pool_inbound_rates[1]),
                ("host_nvme", &self.host_pool_inbound_rates[2]),
                ("remote_nvme", &self.host_pool_inbound_rates[3]),
            ] {

One ordered set, three representations: Option<[f64; 4]> in StoreStats (selene/src/store.rs:248-256), [AtomicU64; 4] + host_pool_rates_present: AtomicBool in Metrics (metrics.rs:312-315, 669-682), and four &str literals in render. Any reordering of the enum silently mislabels the metric.

Replace with: Level::pool_restore_levels() -> impl Iterator<Item = (Level, &'static str)> in selene/src/levels.rs; rates() returning [(Level, f64); 4]; Metrics storing [(AtomicU64, &'static str); 4] and rendering by iteration. Ordered in one place, labelled in one place.

Minor, same area: scan_writeback_waiters_step derives the same cursor three ways (selene-manager/src/store.rs:1641-1645, :1648, :1650-1656); one (cursor, remaining) tail assignment would do. Do not reopen the filter_writeback_waiters/removed_before_cursor question — the dossier's S2 refutation holds: one implementation (store.rs:1443-1475), three callers plus close_operations (:1516, :1719, :3943, :4012-4024), no lost waiters.


What this diff genuinely subtracts (keep it)

Verdict

Not lean. Roughly 100–150 net lines disappear by doing S1–S4 alone, S1 also deletes the PR's one real defect rather than patching it, and S5/S6 remove an allow and a silent index coupling. None of the six asks for new machinery; each is a deletion or a lift-and-generalize.

Scope I actually read / what could not be checked

Judged: helios/src/server/runtime.rs, helios/src/server/metrics.rs, helios/src/cache.rs, helios/src/scheduler.rs (plan-refresh region), selene/src/store.rs, selene/src/levels.rs, selene/src/composite.rs, selene/src/pool/lookup.rs, selene-manager/src/store.rs (waiter/arena regions), selene-manager/src/arena.rs, selene-manager/src/pool/claims.rs, AGENTS.md.

Not opened, so no simplicity verdict is offered on the largest hunks: selene/src/memory.rs (not opened) (+1,150/−200), selene/src/disk.rs (not opened) (+1,017/−57), selene/src/disk_store.rs (not opened) (+990/−77), helios/src/server/runtime/phase_tests.rs (not opened) (+651/−57), helios/src/scheduler/cache_memory.rs (not opened) (+428/−68), helios/src/runtime_core/cache_memory.rs (not opened) (+369/−134), helios/src/scheduler/checkpoints.rs (not opened) (+365/−46). A follow-up pass over memory.rs (not opened) and disk_store.rs (not opened) is where any further duplication of Rate/median or of warps-style helpers would show up.

Open questions: (1) whether Rate can carry a "no ceiling" seed without changing existing restore pricing — that decides whether S1 is a deletion or a small refactor; (2) whether the per-source in-flight hold in RowRestoreLatency is semantically distinct from Rate::started (if not, the whole struct goes); (3) merge order with #665 and #659, which touch helios/src/cache.rs and helios/src/runtime_core/cache_memory.rs (not opened) — S1–S4 are in different files and should not conflict.