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

Raw Markdown for agents: https://autobot.eidonix.com/p/05d7cb36-f90a-4377-91bb-35e1da9d4bf9.md

Subtractions, Simplicity & Conventions review — PR #694 (selene,helios: add write-side NVMe and pool spill profitability gate)

Key findings

The gate itself is small and principled: one worth_restore-based predicate (selene/src/store.rs:496-534), prefill_saved_ns == 0 = "unpriced, keep spilling" (fail-open at selene/src/store.rs:530-532), one PoolSpillPolicy with a documented 5% hysteresis, no env vars, no per-model flags. Nothing about that core should be deleted. The removable weight is in the machinery built around it, and the same PR shows the cheaper form three times.

Five high-value simplifications, ordered by weight:

  1. The GPU-compaction lineage + fork-vote canonicalisation machine (~250 lines, 5 fields, 1 const, 1 new HostStore trait method, 1 helios walker, 8 test stubs) re-derives fork degree that Node::children() already gives — and the same PR gets the same answer without it in memory.rs and disk_store.rs. Highest-value deletion in the diff.
  2. helios recomputes the prefill-savings estimate inline at runtime.rs:2917-2921, duplicating the pre-existing estimated_prefill_saved_seconds helper at runtime.rs:3276-3297 (same call, same .max(1.0) fallback).
  3. memory_pool_standalone_profitable and disk_pool_standalone_profitable are one function written twice, and both re-implement the saved_ns == 0 => true rule that standalone_spill_profitable already applies; "logical chain bytes" is written three times (memory.rs:424-427, disk_store.rs:2186-2189, composite.rs:572-575).
  4. standalone_nvme_bytes returns the same u64 twice (composite.rs:572-577), and the caller immediately divides the identical value by two rates (composite.rs:587-590).
  5. PoolSpillPolicy.level is only ever compared for inequality; it never prices anything (store.rs:280-293), so the policy could be a bare f64 plus hysteresis.

Convention notes (structural, not formatting): the two new Prometheus series are rendered at helios/src/server/metrics.rs:872-885 but are absent from the host-cache counter table in docs/api.md:341-398, which documents every other flare_host_cache_* family; and one unprofitable store is counted twice, in host_store_reasons[6] (helios/src/server/metrics.rs:536) and in spill_skipped_unprofitable[0] (selene/src/composite.rs:1028-1029), even though the DRAM-retained path returns Stored, so the two counters describe the same event differently.


1. (HIGH) Fork-degree memo + compaction lineage: ~250 lines of cache that Node::children() already answers

Where it lives. State at selene/src/composite.rs:137-150:

    /// Keys kept in L1 DRAM only because standalone NVMe restore is unprofitable
    /// and fork deduplication has not yet triggered.
    dram_only: HashSet<PrefixKey>,
    /// Distinct branch descendants duplicating each `dram_only` ancestor's pages.
    dram_only_descendants: HashMap<PrefixKey, HashSet<PrefixKey>>,
    /// GPU compaction lineage (`heir -> evicted`) recorded from `HostStore::evicted`
    /// and `HostStore::compacted` so compacted linear chains do not record a second
    /// fork vote when the heir publishes.
    compacted_parent: HashMap<PrefixKey, PrefixKey>,
    /// FIFO insertion order bounding `compacted_parent`.
    compacted_order: VecDeque<PrefixKey>,
    /// In-flight captures started before a lineage reset (`evictions_lost` or
    /// `compacted_parent` trim) whose fork votes are suppressed upon completion.
    suppressed_fork_votes: HashSet<PrefixKey>,

Plus const MAX_COMPACTED_PARENTS: usize = 4096; (composite.rs:98) and ten functions that maintain it: invalidate_fork_votes (658-670), trim_compacted_parents (672-683), compacted_lineage_root (685-695), canonicalize_voters (697-709), recanonicalize_dram_only_descendants (711-723), record_compacted_parent (725-756), branch_representative (764-808+), record_dram_only_descendant (851-907), plus the HostStore::evicted/HostStore::compacted adapters (2299-2307) and evictions_lost (2309-2313). invalidate_fork_votes alone knocks out and re-suppresses every in-flight key:

    fn invalidate_fork_votes(&mut self) {
        self.dram_only_descendants.clear();
        for &key in self.outbound.keys() {
            if !self.parked.contains_key(&key) {
                self.suppressed_fork_votes.insert(key);
            }
        }
        for key in self.disk.outbound_keys() {
            if !self.dram_only.contains(&key) && !self.parked.contains_key(&key) {
                self.suppressed_fork_votes.insert(key);
            }
        }
    }

(selene/src/composite.rs:658-670)

The hook that exists only to feed it — a new trait method whose default body is empty, overridden solely by CompositeStore (composite.rs:2305-2307) and forwarded by two pass-through wrappers (selene/src/pool/local.rs:35-38 (not opened), selene/src/pool/store.rs:742-744):

    /// Records GPU compaction lineage when `evicted` was compacted into a
    /// surviving descendant `heir` that was not announced as a pool heir
    /// because it was unready or deferred.
    fn compacted(&mut self, _evicted: PrefixKey, _heir: PrefixKey) {}

(selene/src/store.rs:396-399)

with its only production caller (helios/src/server/runtime.rs:2922-2924):

            for evicted in self.scheduler.compacted_ancestors(publication.id) {
                store.compacted(evicted, publication.key);
            }

and the walker behind that call, RequestScheduler::compacted_ancestors (helios/src/scheduler/sharing.rs:137-156), plus eight fn compacted stubs in test drivers (selene/src/pool/local/tests.rs:41 (not opened), selene/src/pool/cascade.rs:1385,1488,1828,1929,2608 and others).

The same PR already does it in three lines. selene/src/memory.rs:1146-1158:

        let eligible = if !has_row_ancestor {
            false
        } else {
            let standalone =
                memory_pool_standalone_profitable(&self.layout, self.pool_spill_policy, node);
            standalone
                || (node.children() >= 2
                    && crate::store::fork_dedup_profitable(
                        self_pages.saturating_sub(parent_covered_pages),
                        node.children(),

and selene/src/disk_store.rs:2250-2263:

    if disk_pool_standalone_profitable(layout, policy, node) {
        return true;
    }
    if node.children() < 2 {
        return false;
    }
    let marginal_pages =
        (node.key.consumed_tokens / layout.page_tokens).saturating_sub(covered_pages);
    crate::store::fork_dedup_profitable(
        marginal_pages,
        node.children(),

Concrete simplification. Delete the compaction-lineage memo and the vote-suppression machinery: dram_only_descendants, compacted_parent, compacted_order, suppressed_fork_votes, MAX_COMPACTED_PARENTS, and the ten functions listed above. Evaluate the promotion predicate in spill_eligible_nvme (composite.rs:598-609) from the index the way MemoryStore and DiskStore already do — node.children() >= 2 over the disk/memory index (Node::children(), and has_row_below/published_ancestors which the PR already relies on for ancestry) — and keep only dram_only: HashSet<PrefixKey>, which is genuinely needed to find the shadows for evict_blocking_dram_only_for_disk (composite.rs:535-567) and promote_dram_only (composite.rs:611-656). Then delete HostStore::compacted (store.rs:396-399), its two forwards (pool/local.rs:35 (not opened), pool/store.rs:742), the helios caller + compacted_ancestors walker (runtime.rs:2922-2924, sharing.rs:137-156), and the eight test stubs. Net: roughly −250 source lines, −1 trait method, −1 helios scheduler API, and the three stores would then price fork deduplication with one rule instead of two. Note the compaction case (linear GPU eviction making one history look like a fork) is subsumed by requiring children() >= 2 in the host indexes, since a linear chain has one child; if the compaction case does slip through, the failure mode is a spurious promotion of one prefix to durable NVMe — the same fail-toward-spilling behaviour the prefill_saved_ns == 0 default already chooses — which is far cheaper than this cache.

If the author insists the memo is load-bearing, the minimum acceptable reduction is to drop suppressed_fork_votes + invalidate_fork_votes (the "notice reset" correctness patch): those exist only so that a stale vote cannot promote, and the same protection is obtained by canonicalising at read time with the existing branch_representative/compacted_lineage_root instead of eagerly rewriting the maps in recanonicalize_dram_only_descendants.


2. (HIGH) helios computes prefill savings twice, in two shapes

New inline copy (helios/src/server/runtime.rs:2917-2921):

            let c = publication.key.consumed_tokens as usize;
            publication.prefill_saved_ns = self
                .scheduler
                .estimate_prefill_delta_ns(c, 0, c, false, &[], &[])
                .unwrap_or_else(|| ((c as f64 / self.prefill_rate.max(1.0)) * 1e9) as u64);

Pre-existing helper in the same file (helios/src/server/runtime.rs:3276-3297), whose doc comment is the identical rule:

fn estimated_prefill_saved_seconds(
    scheduler: &RequestScheduler,
    spec: &RequestSpec,
    prefill_spans: &[std::ops::Range<usize>],
    conditioned_inputs: &[crate::scheduler::ConditionedInput],
    resident_tokens: u64,
    candidate_tokens: u64,
    fallback_prefill_rate: f64,
) -> f64 {
    if let Some(saved_ns) = scheduler.estimate_prefill_delta_ns(
        spec.prompt.len(),
        resident_tokens as usize,
        candidate_tokens as usize,
        spec.prompt_logprobs,
        prefill_spans,
        conditioned_inputs,
    ) {
        return saved_ns as f64 * 1e-9;
    }
    let gained = candidate_tokens.saturating_sub(resident_tokens);
    gained as f64 / fallback_prefill_rate.max(1.0)
}

Two implementations of "use the graph-timing model when measured, else gained / prefill_rate" now exist, and they already differ: the helper uses (candidate - resident), the new code uses c with the effective resident = 0, and one returns seconds, the other nanoseconds via as u64. Concrete fix: give the helper the tokens instead of the RequestSpec (prompt_tokens, resident, candidate, logprobs, spans, conditioned) and return Option<u64> ns, or add a one-line wrapper estimated_prefill_saved_ns(&scheduler, tokens, rate) that calls it with (tokens, 0, tokens, false, &[], &[]); the publication site then becomes a single call. This removes the second .max(1.0) fallback and the second floor-to-ns cast.


3. (MEDIUM) memory_pool_standalone_profitable / disk_pool_standalone_profitable: one function, two copies, and the saved_ns == 0 rule implemented a third and fourth time

selene/src/memory.rs:422-444:

/// Uncompressed logical chain bytes restored from the pool when starting at zero
/// resident tokens, matching pool admission's byte-rate denominator in O(1).
fn memory_pool_chain_bytes(layout: &Layout, node: &Node<MemoryRecord>) -> u64 {
    let pages = node.key.consumed_tokens / layout.page_tokens;
    layout.record_bytes_for(pages, node.row)
}

fn memory_pool_standalone_profitable(
    layout: &Layout,
    policy: Option<crate::store::PoolSpillPolicy>,
    node: &Node<MemoryRecord>,
) -> bool {
    let Some(policy) = policy else {
        return true;
    };
    let saved_ns = node.prefill_saved_ns;
    if saved_ns == 0 {
        return true;
    }
    let bytes = memory_pool_chain_bytes(layout, node);
    let transfer_seconds = bytes as f64 / policy.rate_bytes_per_sec.max(1.0);
    crate::store::standalone_spill_profitable(transfer_seconds, saved_ns)
}

selene/src/disk_store.rs:2184-2206 is the same body with DiskRecord substituted; the third copy of the byte formula is composite.rs:572-575. saved_ns == 0 => true is already the first branch of standalone_spill_profitable (selene/src/store.rs:526-534), so both functions repeat a rule they then delegate to.

Concrete fix: move the gate onto the policy type that owns the rate —

impl PoolSpillPolicy {
    pub(crate) fn standalone_profitable(&self, bytes: u64, prefill_saved_ns: u64) -> bool {
        crate::store::standalone_spill_profitable(
            bytes as f64 / self.rate_bytes_per_sec.max(1.0),
            prefill_saved_ns,
        )
    }
}

keep one chain_bytes(layout, consumed_tokens, row) helper (the composite formula generalised over the two node types, or simply layout.record_bytes_for(key.consumed_tokens / layout.page_tokens, row) inlined at the three sites), and delete memory_pool_chain_bytes (memory.rs:424-427), disk_pool_chain_bytes_for_node (disk_store.rs:2186-2189), both *_pool_standalone_profitable functions, and the #[cfg(test)] re-export wrappers pool_chain_bytes (memory.rs:1130-1135) and pool_chain_bytes_for_node (disk_store.rs:3559-3562) that exist only so two unit tests can call the helpers indirectly.


4. (MEDIUM) standalone_nvme_bytes returns the same number twice

selene/src/composite.rs:569-590:

    fn standalone_nvme_bytes(&self, key: &PrefixKey, row: bool) -> (u64, u64) {
        let layout = self.disk.layout();
        let total_pages = key.consumed_tokens / layout.page_tokens;
        let raw_bytes = layout.record_bytes_for(total_pages, row);
        (raw_bytes, raw_bytes)
    }

…

        let (disk_bytes, upload_bytes) = self.standalone_nvme_bytes(key, row);
        let disk_rate = self.disk_inbound_rate.get().max(1.0);
        let dram_rate = self.memory.stats().inbound_rate.max(1.0);
        let transfer_seconds = disk_bytes as f64 / disk_rate + upload_bytes as f64 / dram_rate;

The doc comment explains why the two are equal (both charge uncompressed logical bytes), so the tuple carries no information. Concrete fix: return u64 and write let transfer_seconds = bytes as f64 * (1.0 / disk_rate + 1.0 / dram_rate);, keeping the comment on the single return. The tuple also pushes disk_bytes outward as the "bytes charged against disk" at composite.rs:592, so returning u64 loses nothing.


5. (LOW) PoolSpillPolicy.level is compared but never prices

selene/src/store.rs:278-293:

pub struct PoolSpillPolicy {
    pub level: crate::levels::Level,
    pub rate_bytes_per_sec: f64,
}

impl PoolSpillPolicy {
    /// Whether `self` differs meaningfully from `other` (level change or >= 5% rate change),
    /// avoiding clean-slot rescans on small floating-point rate-recovery ticks.
    pub(crate) fn materially_differs_from(&self, other: &Self) -> bool {
        self.level != other.level
            || (self.rate_bytes_per_sec - other.rate_bytes_per_sec).abs()
                >= 0.05 * other.rate_bytes_per_sec.max(1.0)
    }
}

level is read in exactly one place, the inequality above. Both producers already know the level and derive the rate from it (selene/src/pool/store.rs:202-214 and 242-258, which duplicate the "remote ⇒ RemoteNvme else HostNvme, then index rates[2]/rates[3]" selection twice). Concrete fix: either reduce the policy to rate_bytes_per_sec (+ the existing struct-private hysteresis fn, whose doc then just says ">= 5% rate change" — the level-change rescan is redundant because a HostNvme↔RemoteNvme switch changes the rate by far more than 5% in practice), or, if the level switch must force a rescan, keep level and delete the duplicated level→rate match by having pool_spill_policy() (pool/store.rs:242-258) be the only constructor and new() call it (it cannot today because it runs before Self exists — pass rates/remote_manager into a free function used by both). Either way, ~12 lines of duplicated match arms collapse.


6. Convention (structural): new metric family missing from the metric docs; one event counted twice

The new series are rendered at helios/src/server/metrics.rs:872-885:

        text.push_str("# HELP flare_host_cache_spill_skipped_unprofitable_total Spills skipped because standalone restore latency exceeds the profitability threshold.\n# TYPE flare_host_cache_spill_skipped_unprofitable_total counter\n");
        text.push_str("# HELP flare_host_cache_spill_skipped_unprofitable_bytes_total Bytes of spills skipped because standalone restore latency exceeds the profitability threshold.\n# TYPE flare_host_cache_spill_skipped_unprofitable_bytes_total counter\n");

but docs/api.md:341-398 — which lists every other host-cache family in its table (flare_host_cache_hits_total, ..._bytes_out_total, ..._disk_records, …) and then a prose block for the retention counters — was not extended, while docs/prefix-cache-offload.md:685-696 (not opened) and docs/runtime-core-design.md (not opened) were. This metric family is the only user-visible interface the PR adds; add the two rows to the docs/api.md:345-346 area and one sentence on the dram_only retention consequence next to the held/dropped paragraph at docs/api.md:363-366. That also makes the next item resolvable by documentation.

On double counting: helios/src/server/metrics.rs:531-538 maps the outcome to a reason slot —

            StoreOutcome::Oversize => 5,
            StoreOutcome::Unprofitable => 6,
        };
        self.host_store_reasons[reason].fetch_add(1, Ordering::Relaxed);

while selene/src/composite.rs:1023-1035 already records the same skip in the tiered store stats —

            self.stats.spill_skipped_unprofitable[0] += 1;
            self.stats.spill_skipped_unprofitable_bytes[0] += skipped_write_bytes;
            events.push(StoreEvent::Stored {
                checkpoint,
                key,
                result: Ok(bytes),
            });

and returns Stored, so host_store_reasons[6] cannot see it for that path at all (Unprofitable is returned only when nothing is retained). Two counters now claim to count "spills skipped as unprofitable" with different populations. Concrete simplification: keep the tiered spill_skipped_unprofitable pair (it carries bytes and the nvme/pool split) and drop the StoreOutcome::Unprofitable => 6 slot from host_store_reasons (shrinking the array at metrics.rs:275 from 7 back to 6 and the render loop at metrics.rs:932), or keep the outcome slot and document that it counts only the "dropped entirely" case. Either way one of the two should go, otherwise the Correctness lens will have to arbitrate which number is true.


What is already lean (do not touch)

Suggested order of work

  1. Findings 2, 3, 4, 5 are mechanical and safe (≈ −60 lines, no behaviour change); do them regardless of the rest.
  2. Finding 6 costs two doc rows and one counter.
  3. Finding 1 is the only real design question: if it lands, the diff loses ~250 lines, a trait method, a scheduler API, and the three-store divergence in how fork dedup is decided. Ask the author what case suppressed_fork_votes + compacted_order actually catch that children() >= 2 over the host indexes does not, and require a test that fails without the machinery before keeping it.

Open questions / could not verify