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

Raw Markdown for agents: https://autobot.eidonix.com/p/3f2722ef-d501-4b46-9ec2-99c65879f652.md

Subtraction, Simplicity & Conventions review — PR #674 (selene,selene-manager,helios), head 45fb3809

Key findings

Five high-value subtractions, ranked. All verified by me in the tree at 45fb3809, not taken from the review or the PR body.

  1. S1 (highest value) — delete the cold-start prefill EMA instead of repairing it. observe_prefill_rate (helios/src/server/runtime.rs:3052-3075) is unreachable, so ~45 lines plus a dead public flare_selene API (INITIAL_PREFILL_RATE, worth_fetching, worth_transfer) should be removed, not patched.
  2. S2 — RowRestoreLatency re-implements selene::levels::Rate (same 3-sample ring, same 10 s half-life, same sort_by(f64::total_cmp) / [count/2] median), and RowRestoreSource re-models a level that selene/src/levels.rs already has. ~90 new lines collapse to a thin wrapper — and this is the exact block where the correctness lens's median inversion lives.
  3. S3 — a bool parameter and two wrapper functions exist only to choose whether an O(N) map is built (helios/src/cache.rs:732-811); the map is built at most once per pass, so always tracking is simpler. The same 12-line priority closure is also written out twice in production (helios/src/scheduler/cache_memory.rs:394-406, :627-638).
  4. S4 — plan_refreshed is threaded through a call chain only to skip a refresh begin_pool_lookup already performed, producing a three-arm match that reduces to two (runtime.rs:1602-1613, :3288, :3314-3326).
  5. S5 — conditioned_window_ends re-derives the boundaries set_conditioned_inputs computes, and conditioned_inputs_from_images is a five-line wrapper over a method added by this same PR.

The rest of the diff is genuinely lean — several parts are consolidations and should not be touched (see "Already lean" below). No AGENTS.md violation found in scope.


S1 — Remove the dead prefill EMA and its orphaned public API (do not patch it)

helios/src/server/runtime.rs:3052-3075:

    fn observe_prefill_rate(
        &mut self,
        step: &ScheduledStep,
        tokens: u64,
        timing: crate::execution::ExecutionTiming,
    ) {
        let capacity = step.prefill_capacity() as u64;
        if !step.kind.is_prefill()
            || step.lanes.len() != 1
            || capacity == 0
            || (step.lanes[0].tokens as u64).saturating_mul(2) < capacity
        {
            return;
        }

Why it can never run: prefill_capacity() is self.mixed.as_ref().map_or(0, …) (helios/src/scheduler.rs:465-467); mixed is legal only on GraphKind::Mixed, enforced by validate_mixed (helios/src/scheduler.rs:437-462); and is_prefill() covers only Prefill/TerminalPrefill/ScoredPrefill (helios/src/execution/manifest.rs:85-87). capacity == 0 therefore always holds whenever is_prefill() holds. The function returns at the guard on every call, so self.prefill_rate stays at its seed forever.

The correctness lens will file "repair the guard to use token_capacity". The subtraction answer is the opposite: delete it. flare-selene's worth_restore(transfer_seconds, prefill_saved_seconds) is the surviving rule — helios now calls only that (runtime.rs:238, :3362) — and this PR already routes warm pricing through ActionCosts/PrefillPredictor and estimate_prefill_delta_ns (runtime.rs:3257-3265).

Concretely, remove:

    let gained = candidate_tokens.saturating_sub(resident_tokens);
    gained as f64 / fallback_prefill_rate.max(1.0)
}

Replace with the worth_restore-consistent zero/None — an unpriced restore is simply not worth taking, which is what worth_restore already returns for a non-finite or zero saving (selene/src/store.rs:451-455).

Net: about 45 lines and one dead public API removed, versus one bug fixed and a permanently frozen fallback shipped. This also satisfies the repository rule against shipping fallback layers without a concrete requirement (AGENTS.md:188-193).


S2 — Collapse RowRestoreLatency onto the existing pessimistic-estimate ring

helios/src/server/runtime.rs:308-319:

    fn observe(&mut self, source: RowRestoreSource, seconds: f64) {
        if !seconds.is_finite() || seconds <= 0.0 {
            return;
        }
        let bucket = self.buckets.entry(source).or_default();
        bucket.samples[bucket.next] = seconds;
        bucket.next = (bucket.next + 1) % bucket.samples.len();
        bucket.count = (bucket.count + 1).min(bucket.samples.len());
        let mut ordered = bucket.samples;
        ordered[..bucket.count].sort_by(f64::total_cmp);
        bucket.last_median = Some((ordered[bucket.count / 2], std::time::Instant::now()));
    }

Compare selene/src/levels.rs:57-76, which this PR's own work already uses for per-level pool restore rates:

    pub(crate) fn observe(&mut self, bytes: u64, elapsed: Duration) {
        if bytes == 0 || elapsed.is_zero() {
            return;
        }
        self.samples[self.next] = bytes as f64 / elapsed.as_secs_f64();
        self.next = (self.next + 1) % 3;
        self.count = (self.count + 1).min(3);
        self.last = Some(Instant::now());
        let mut values = self.samples;
        values[..self.count].sort_by(f64::total_cmp);
        self.median = values[self.count / 2];
    }

Same three-sample ring, same median index, same RECOVERY/RECOVERY_SECONDS = 10 s half-life (selene/src/levels.rs:34 vs runtime.rs:282), same in-flight hold (selene/src/levels.rs:78-82 started() vs runtime.rs:328-330). The only real difference is direction: latency is lower-is-better, rate is higher-is-better — which is precisely why the copied [count / 2] index is wrong here (the correctness lens's median inversion) and why a copy was the wrong shape.

RowRestoreSource is the same duplication one level up (runtime.rs:249-260):

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct RowRestoreSource {
    pooled: bool,
    tier: flare_selene::Tier,
}

fn row_restore_source(hit: &flare_selene::HostHit) -> RowRestoreSource {
    RowRestoreSource {
        pooled: hit.pooled,
        tier: hit.tier,
    }
}

selene already models exactly (pooled, tier) as a level: selene/src/levels.rs:10-28 with POOL_LEVELS at :109-114.

Concrete simplification: keep one ring type in selene/src/levels.rs — generalise Rate with a direction/ordering parameter, or add a Latency sibling beside it so the lower-is-better index is written and tested once — and key RowRestoreLatency's map on the existing pool level instead of a hand-rolled (bool, Tier) struct plus a free constructor. ~90 new lines (runtime.rs:246-333) become a thin wrapper, and the duplicated median block that carries the bug disappears rather than being patched in a copy.


S3 — Drop the priority_uses_role_preserving flag and de-duplicate the priority closure

helios/src/cache.rs:732-745:

    fn select_eviction_candidate<K: Ord>(
        &self,
        below: Option<RetentionRank>,
        immediate: bool,
        protected_token_budget: Option<u64>,
        priority_uses_role_preserving: bool,
        mut priority: impl FnMut(&Checkpoint, bool) -> K,
    ) -> Option<(CheckpointId, u64)> {
        let track_role_preserving =
            priority_uses_role_preserving || (below.is_some() && protected_token_budget.is_some());

The flag exists only because there are two public wrappers over the same private function, helios/src/cache.rs:794-811:

    pub(crate) fn eviction_candidate_with_priority<K: Ord>(
        ...
        self.select_eviction_candidate(below, immediate, protected_token_budget, true, priority)
    }

    pub(crate) fn eviction_candidate_within_budget(
        ...
        self.select_eviction_candidate(below, immediate, protected_token_budget, false, |_, _| ())
    }

The five-parameter production caller already hard-codes true (helios/src/scheduler/cache_memory.rs:394-406, :627-638). The map is built at most once per selection pass (cache.rs:744-753), and |_, _| () ignores its contents, so always tracking costs nothing on the within_budget path beyond an allocation that already only happens when below.is_some().

Concrete simplification: delete the priority_uses_role_preserving parameter and the track_role_preserving predicate; compute role_preserving unconditionally in the filter_map. eviction_candidate_within_budget keeps delegating with |_, _| (), which the (Some(rank), Some(budget)) cost match already treats as neutral (cache.rs:768-785). One parameter, one boolean, one conditional removed; behaviour identical.

Separately, the same closure is written out at helios/src/scheduler/cache_memory.rs:394-406:

                    |node, role_preserving| {
                        page_pressure_victim_priority(
                            &self.snapshot_pages,
                            &refs,
                            node,
                            role_preserving,
                        )
                    },

and again at :627-638 with &effective_refs. (A third copy at :1235-1248 is the reference model in tests and is a legitimate independent model — leave it.) Hoist one fn snapshot_page_priority(&self, refs: &[u32], node: &Checkpoint, role_preserving: bool) -> (bool, u64, bool) and call it from both production sites.


S4 — Remove plan_refreshed and the third match arm

helios/src/server/runtime.rs:1602-1613:

            let plan_refreshed = if let Some(store) =
                self.store.as_mut().filter(|store| store.pooled())
            {
                begin_pool_lookup(
                    &mut self.scheduler,
                    store.as_mut(),
                    &self.config.contract.core_parameters,
                    &mut incoming,
                )
            } else {
                false
            };

That bool becomes a field on a nine-field struct (runtime.rs:3288), is destructured at :3311, and is consumed by runtime.rs:3314-3326:

        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(
                &spec,
                core_parameter_defs,
                core_parameters,
            )?,
        };

The flag only exists to skip a refresh that begin_pool_lookup has already performed in place on incoming.pool_plan (runtime.rs:3194-3197, :3209-3212). The clone in the true arm is identical to the clone in the false arm, so the two arms differ only by a no-op refresh on an already-refreshed plan.

Concrete simplification: pass queued_plan: Option<&AdmissionPlan>, always plan.clone(), and delete the flag, the struct field, and one arm:

let plan = match queued_plan {
    Some(plan) => plan.clone(),
    None => scheduler.plan_admission_with_core_parameters(&spec, core_parameter_defs, core_parameters)?,
};

begin_pool_lookup itself has two near-identical "refresh in place, return false on error" blocks (runtime.rs:3194-3197 and :3209-3212) that collapse into one prologue before the ticket check — worth doing in the same edit.


S5 — One window partition, not two; delete the wrapper fn

helios/src/scheduler.rs:2123-2141 (new in this PR):

        let mut ends = Vec::new();
        let mut features = 0usize;
        let mut in_window = false;
        for input in inputs.iter().filter(|input| input.token_span.end > consumed) {
            if !in_window || features + input.feature_range.len() > capacity {
                if in_window {
                    ends.push(input.token_span.start);
                }
                in_window = true;
                features = 0;
            }
            features += input.feature_range.len();
        }

set_conditioned_inputs, 40 lines below, computes the same boundaries (helios/src/scheduler.rs:2184-2196):

            if windows.is_empty() || features + input.feature_range.len() > capacity {
                if let Some(previous) = windows.back_mut() {
                    previous.prefill_end = input.token_span.start;
                }
                windows.push_back(ConditionedWindow {
                    inputs: index..index,
                    token_start: input.token_span.start,
                    prefill_end: request.prompt_tokens,

Two implementations of one partition rule, in the same impl, with different accumulation state — exactly the drift risk the docs this PR added describe. conditioned_window_ends is consumed by the pricing path (helios/src/scheduler/checkpoints.rs:466 (not opened), :482), so a drift between them silently misprices restores.

Concrete simplification: extract fn partition_conditioned_inputs(inputs: &[ConditionedInput], capacity: usize) -> Vec<usize> returning the boundary token index of each window, and build both the ConditionedWindow deque (:2181-2196) and ends from it. One rule, one loop.

Also in this group, helios/src/server/runtime.rs:3271-3278 is a five-line free function that only maps a method this PR added (helios/src/frontend/images/conditioned.rs:151):

fn conditioned_inputs_from_images(
    images: &[crate::frontend::images::PreparedImageInput],
) -> Vec<crate::scheduler::ConditionedInput> {
    images
        .iter()
        .map(crate::frontend::images::PreparedImageInput::conditioned_input)
        .collect()
}

It has exactly two call sites (runtime.rs:1713, :3335). Inline the .iter().map(…).collect() at both and delete the function — the method is already the abstraction.


Minor (mention, not blockers)


Already lean — do not change

Several parts of this diff are subtractions in their own right and should survive review untouched:

Conventions

No material AGENTS.md violation in this lens's scope: no environment-variable toggles (AGENTS.md:452-455), no per-model identity switches or allowlists (:352-364), and no new configuration knobs. The TierStore::retired / pending_pool_drain / HostHit.pooled / StoreStats reserved+rate field signature changes are declared in the PR body's public-API list, which is the required disclosure. The one convention-adjacent item is S1: a dead-but-shipped fallback path falls squarely under the repository's rule against fallback layers without a concrete requirement (AGENTS.md:188-193).

Open questions

  1. S1 direction: the correctness lens will propose repairing observe_prefill_rate to gate on token_capacity. Whether the maintainers want the cold fallback at all is a product question — if they do, S1 reduces to "fix one line, keep the API"; if not, S1 removes ~45 lines and three public functions. Someone with the pricing intent should decide, because the two lenses point opposite ways here.
  2. S2 scope: whether selene::levels::Rate should grow a direction parameter (one type, one median implementation, direction explicit) or gain a sibling Latency type (no parameter, small duplication of the ring). Either way the copied block goes; I did not find a prior-art decision in the repo.
  3. Not verifiable with my tools: the Autobot review artefacts referenced in the PR conversation; nothing in this report depends on them — every claim above was re-read from the tree at 45fb3809.