Code correctness report · NVIDIA/hyperflare-inference #742

Raw Markdown for agents: https://autobot.eidonix.com/p/f6c5bfdc-47ca-49a6-b23b-824d617003da.md

Deep Code Correctness / Invariants / Hot-Path Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages) @ 02990da

Scope note: 9 files, ~115 changed lines across selene/, helios/, selene-manager/ tests, and one doc — below the >12-file/>900-LOC threshold, so I audited directly (no sub-agents). I read the whole diff, both changed production functions (selene::offload::headroom_inner, helios::runtime_core::memory::allocate_caches/capture_growth, helios::runtime_core::model::prepare_offload), and every callee/enum they touch (page_ceiling, capacities, capture_growth, PageLimit, KvCacheLimit, Layout::row_slots, intake_slots, slab::WINDOW_PAGES, MemoryStore::fits/allocate_slots/shortfall, CompositeStore::store, StoreOutcome/StoreReason, PageCapacity/CacheGeometry).

Two verified defects. One is Major (silently undersizes the capture slab and livelocks full-context captures).


F1 — Major (Blocker-class for the feature's stated use case): the capture slab is sized from minimum_pages, not from the GPU capacity or the bound, so a full max_sequence_tokens chain can never fit and every publication retries forever

Diff site — helios/src/runtime_core/memory.rs:1132 (changed line, capture.then_some(minimum_pages) → capture.then_some(minimum_pages.min(max_sequence_pages))):

1122:            let (device, tier_host) = options.prefix_cache.headroom_with_inputs_for_budget(
...
1125:                crate::offload::PrepareInputs {
1126:                    max_active: active,
1127:                    input_staging: staging,
1128:                    shard: self.cluster().map(|cluster| (cluster.rank, cluster.world)),
1129:                    integrated: integrated > 0,
1130:                    max_sequence_pages: Some(max_sequence_pages),
1131:                },
1132:                capture.then_some(minimum_pages.min(max_sequence_pages)),
1133:                initial_budget,
1134:            )?;

Callee that consumes it — selene/src/offload.rs:163-181 (the whole capture branch, only line 165-169 is new, but the surrounding semantics are what F1 turns on — the parameter is documented at selene/src/offload.rs:125 as "local_pages is the largest GPU page capacity when all ranks share this process"):

163:        let capture = local_pages.filter(|_| self.pool_only());
164:        let intake = if let Some(pages) = capture {
165:            let chain_pages = match inputs.max_sequence_pages {
166:                Some(limit) if limit > 0 => pages.min(limit),
167:                _ => pages,
168:            };
169:            let chain = chain_pages
170:                .checked_add(layout.row_slots() as u64)
171:                .ok_or("pool capture slot count overflow")?;
...
179:            chain
180:                .max(intake_slots(layout, inputs.max_active) as u64)
181:                .min(budget)

So chain_pages = min(minimum_pages, max_sequence_pages).

But minimum_pages is not the GPU page capacity. memory.rs:997 (context line, unchanged):

 997:        let minimum_pages = ceiling.map_or(active as u64 * 8192u64.div_ceil(page_tokens), |limit| limit.minimum);

With the default KvCacheLimit::Memory (helios/src/runtime_core/limits.rs:11-17, #[default] Memory), page_ceiling returns Ok(None) at memory.rs:567-569, so minimum_pages = active * ceil(8192 / page_tokens) — a concurrency floor, not the capacity. capacities(...) (memory.rs:683-829) then binary-searches the real capacity up to maximum_pages, whose bound is only the virtual extent (memory.rs:710,742) — i.e. it can be far above minimum_pages.

Concrete counterexample (the PR's own config): context = 1,048,576, page_tokens = 64 ⇒ max_sequence_pages = 16,384 (memory.rs:996). active = 32 ⇒ minimum_pages = 32 * ceil(8192/64) = 32 * 128 = 4,096. GPU capacity actually allocated = 99,008 pages (the PR's own table). Then:

Failure path (proved by reading the callees): a request that reaches max_sequence_tokens publishes a root chain whose tail pages can be up to max_sequence_pages = 16,384 (a root holds the whole chain — selene/src/memory.rs:529-534, and GPU page_chain concatenates every ancestor's tail_pages, helios/src/cache.rs:600-606). Then

That retry is re-attempted every poll pass with the checkpoint still pinned (helios/src/server/runtime.rs:3470-3511: self.scheduler.pin_checkpoint(...), then StoreOutcome::Retry(reason) => { ...; continue; } never unpins until a later outcome), so a long sequence's checkpoint is retained on the GPU and re-offered indefinitely and the pool never receives it. This is exactly the "long-context core exports to the manager" scenario the PR exists to fix, just now silently instead of with host budget cannot hold a full pool capture.

Fix: pass the bound, not the floor:

// memory.rs:1132
capture.then_some(max_sequence_pages),   // keep `minimum_pages` only for the
                                         // feasibility/error check below

(memory.rs:763-773 already errors with a precise message when minimum_pages cannot be backed, so nothing is lost.) Alternatively, keep min(...) here but then also cap the validation side (capture_growth at memory.rs:1486 and planned_offload_host at memory.rs:1550-1556) to the same min(minimum_pages, max_sequence_pages) — but that would re-introduce the per-publication livelock for any core with active * ceil(8192/page_tokens) < ceil(max_sequence_tokens/page_tokens), which is the common case (4,096 < 16,384 above). The first fix is the correct one.

Why the tests miss it: the new helios test at helios/src/runtime_core/memory.rs:2440-2456 calls capture_growth(&layout, pages.min(max_sequence_pages), ...) inlined in the test, never through allocate_caches line 1132, so it cannot observe a disagreement between the slab size and the growth charge:

2443:        let max_sequence_pages = 128u64;
2444:        let reserved = (max_sequence_pages + layout.row_slots() as u64) * layout.page_record_bytes;
2445:        assert_eq!(
2446:            capture_growth(&layout, 512u64.min(max_sequence_pages), reserved, 0, 1),
2447:            Some(0)
2448:        );
...
2450:        let (_, pages, _) = capacities(&cores, &[1 << 30], 1, 1, 64, None, |_, pages| {
2451:            capture_growth(&layout, pages.min(max_sequence_pages), reserved, 0, 1)
2452:        })

It also never asserts that slot_count() from prepare_with_inputs equals pages.min(max_sequence_pages) + row_slots, nor that a full-chain publication goes Queued. The new selene test (selene/src/offload/tests.rs:567-621) passes Some(512) as local_pages — a capacity — so it validates headroom_inner in isolation and likewise cannot see the helios caller feeding it minimum_pages.


F2 — Minor: div_ceil by page_tokens panics on a zero page_tokens contract, where the code previously returned a graceful error

Diff sites (helios/src/runtime_core/memory.rs:996, context line but newly required to be total; and the new line helios/src/runtime_core/model.rs:1155-1157):

 995:        let ceiling = page_ceiling(options.kv_cache_limit, context, active as u64, &contract)?;
 996:        let max_sequence_pages = context.div_ceil(contract.cache.page_tokens as u64);
1155:        let max_sequence_pages = self.server_config["max_sequence_tokens"]
1156:            .as_u64()
1157:            .map(|context| context.div_ceil(contract.cache.page_tokens as u64));

Callee/enum resolution: the only in-function guard against page_tokens == 0 is inside page_ceiling, and it is conditional on the limit mode — memory.rs:567-574:

 567:    if mode == KvCacheLimit::Memory {
 568:        return Ok(None);
 569:    }
 570:    if context == 0 || contract.cache.page_tokens == 0 {
 571:        return Err(invalid(
 572:            "KV cache limit requires a positive context and page size",
 573:        ));
 574:    }

KvCacheLimit::Memory is the #[default] (helios/src/runtime_core/limits.rs:11-17), so for the default mode page_ceiling returns Ok(None) before the zero check, and line 996 then divides by zero. PreparedContract::validate does reject cache.page_tokens == 0 (helios/src/model/contract.rs:536), but that path is only reached from catalog::validate on the server config (helios/src/model/catalog.rs:31); runtime_core::allocate_caches deserializes server_config["model_contract"] itself at memory.rs:899-901 without calling validate(), and prepare_offload does the same at model.rs:1139-1141. capacities has an explicit page_tokens == 0 guard (memory.rs:696) and page_ceiling an explicit context == 0 guard, which shows the function is designed to stay total on malformed prepared geometry — the new line removes that property and turns a clean invalid(...) error into an arithmetic panic during startup of a tampered/foreign core. model.rs:1157 is worse: page_tokens comes from a contract that was already deserialized in this function at model.rs:1139 and never validated.

Fix: reuse the value already validated, or guard inline:

996:  let max_sequence_pages = match contract.cache.page_tokens {
997:      0 => return Err(invalid("model requires a positive cache page size")),
998:      tokens => context.div_ceil(tokens as u64),
999:  };

and the same guard in model.rs:1155-1157.


Checks that found nothing (stated plainly)

  1. headroom_inner bound semantics (selene/src/offload.rs:165-168) are correct as written. Some(limit) if limit > 0 => pages.min(limit), else pages: Some(0) and None both stay uncapped, which matches the doc comment (offload.rs:343-346) and is exactly what selene/src/offload/tests.rs:604-620 asserts. limit > 0 is not dead: pages (a page_capacity from CacheGeometry::validate, selene/src/geometry.rs:115, which requires > 0) is > 0, so Some(0) really is reachable and really selects the uncapped branch. checked_add on row_slots before the budget comparison preserves the overflow error. No order-of-operations defect: budget is computed from page_record_bytes before the chain > budget test, and the Some(budget) override is applied before the division (offload.rs:172-178).
  2. capture_growth (memory.rs:667-681) is monotone in pages (slots = pages + row_slots, extra = slots*record_bytes - reserved, None when extra > host_free), so capping its argument at max_sequence_pages keeps the binary search in capacities (memory.rs:775-783) well-ordered: fits stays monotone non-increasing, so low is still the maximum feasible page count and the search cannot oscape. The new capping removes an artificial ceiling at max_sequence_pages (previously GPU pages were throttled once the capture slab exceeded host_free), which is the intended behaviour and is asserted by memory.rs:2450-2454 (assert!(pages > max_sequence_pages)).
  3. planned_offload_host (memory.rs:1550-1556) and capture_growth now use the same pages.min(max_sequence_pages) expression, so the plan is self-consistent (the inconsistency is with the slab, F1). saturating_add/saturating_mul keep it total.
  4. max_sequence_pages derivation is correct on well-formed cores. catalog::validate requires max_sequence_tokens to be a positive multiple of page_tokens (helios/src/model/catalog.rs:46-56), so div_ceil is exact and >= 1; Some(limit) with limit > 0 therefore always engages in production. memory.rs:996 and model.rs:1157 derive the same value from the same server_config + contract, so planning and attachment agree (both are None-free in practice).
  5. Hot path: no algorithmic change. All new code runs once per process at startup (allocate_caches, prepare_offload, prepare_with_inputs_budget_with_progress); nothing added lies on the per-step / per-request / per-victim loops. Layout::row_slots() (selene/src/geometry.rs:217-222) is O(ranks) and is called O(1) times. No new allocation in a loop, no O(N·span) scan.
  6. Test fixtures are semantically sound. Adding max_sequence_pages: None to the existing PrepareInputs literals (helios/src/offload/pool/tests.rs:134, selene-manager/tests/client.rs:3255,3509, selene-manager/tests/offload.rs:139, selene/src/offload/sharded/tests.rs:118,261,392,558, selene/src/offload/tests.rs:14,51) preserves prior behaviour exactly (None ⇒ uncapped), and PrepareInputs derives Clone, Copy, Debug (offload.rs:332) so the struct-by-value signature is unaffected. prepare_with_inputs_budget_with_progress destructures the new field with max_sequence_pages: _ (offload.rs:628), which is correct since it forwards the whole inputs to headroom_inner at offload.rs:704-710 and never needs the field itself.

Verdict