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:
- Slab slots (
offload.rs:169-181) =min(4,096, 16,384) + row_slots= 4,096 + row slots ≈ 2.9 GiB at ~748 KiB/page-record — not the 16,475 slots / 11.8 GiB the PR's table claims. - Planning charges instead
pages.min(max_sequence_pages) + row_slots= 16,384 + row slots = 16,475 slots (memory.rs:1550-1556,memory.rs:1486), so startup logs/accounts 11.8 GiB while ~2.9 GiB is actually mapped.
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
selene/src/memory.rs:4183-4190(MemoryStore::store):if !self.core.fits(record_slots(tail.len(), row))— note this is the only pre-check and it returnsOversize; but the flat/capture store is reached throughCompositeStore, andselene/src/memory.rs:1730-1732:fn fits(&self, slots: usize) -> bool { slots + self.pool.intake_slots() <= self.pool.slot_count() }—slot_count() = 4,096 + row_slots<16,384 + row_slots⇒false; and if it did pass,allocate_slots(memory.rs:771-793) loopswhile self.pool.free_slots() < needed + intake_slots()and returnsNonewhen no candidate is evictable (memory.rs:784-792),- so
start_record→allocatereturnsOk(None)(memory.rs:645-647),store/store_recordreturnsOk(false)(memory.rs:606-608), which surfaces asStoreOutcome::Retry(StoreReason::Slabs)(selene/src/composite.rs:2043-2054andselene/src/memory.rs:4195-4199).
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)
headroom_innerbound semantics (selene/src/offload.rs:165-168) are correct as written.Some(limit) if limit > 0 => pages.min(limit), elsepages:Some(0)andNoneboth stay uncapped, which matches the doc comment (offload.rs:343-346) and is exactly whatselene/src/offload/tests.rs:604-620asserts.limit > 0is not dead:pages(apage_capacityfromCacheGeometry::validate,selene/src/geometry.rs:115, which requires> 0) is> 0, soSome(0)really is reachable and really selects the uncapped branch.checked_addonrow_slotsbefore the budget comparison preserves the overflow error. No order-of-operations defect:budgetis computed frompage_record_bytesbefore thechain > budgettest, and theSome(budget)override is applied before the division (offload.rs:172-178).capture_growth(memory.rs:667-681) is monotone inpages(slots = pages + row_slots,extra = slots*record_bytes - reserved,Nonewhenextra > host_free), so capping its argument atmax_sequence_pageskeeps the binary search incapacities(memory.rs:775-783) well-ordered:fitsstays monotone non-increasing, solowis still the maximum feasible page count and the search cannot oscape. The new capping removes an artificial ceiling atmax_sequence_pages(previously GPU pages were throttled once the capture slab exceededhost_free), which is the intended behaviour and is asserted bymemory.rs:2450-2454(assert!(pages > max_sequence_pages)).planned_offload_host(memory.rs:1550-1556) andcapture_growthnow use the samepages.min(max_sequence_pages)expression, so the plan is self-consistent (the inconsistency is with the slab, F1).saturating_add/saturating_mulkeep it total.max_sequence_pagesderivation is correct on well-formed cores.catalog::validaterequiresmax_sequence_tokensto be a positive multiple ofpage_tokens(helios/src/model/catalog.rs:46-56), sodiv_ceilis exact and>= 1;Some(limit)withlimit > 0therefore always engages in production.memory.rs:996andmodel.rs:1157derive the same value from the sameserver_config+ contract, so planning and attachment agree (both areNone-free in practice).- 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. - Test fixtures are semantically sound. Adding
max_sequence_pages: Noneto the existingPrepareInputsliterals (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), andPrepareInputsderivesClone, Copy, Debug(offload.rs:332) so the struct-by-value signature is unaffected.prepare_with_inputs_budget_with_progressdestructures the new field withmax_sequence_pages: _(offload.rs:628), which is correct since it forwards the wholeinputstoheadroom_inneratoffload.rs:704-710and never needs the field itself.
Verdict
- F1 (Major):
memory.rs:1132must passmax_sequence_pages, notminimum_pages.min(max_sequence_pages), or pool-only capture of any chain longer thanactive * ceil(8192 / page_tokens)pages is permanently un-storable (Retry(Slab)) while the GPU checkpoint stays pinned — and the slab is silently ~4× smaller than the host budget the planner charges for. - F2 (Minor): add an explicit
page_tokens == 0guard atmemory.rs:996/model.rs:1157instead of relying onpage_ceiling, which short-circuits in the defaultKvCacheLimit::Memorymode. - No other correctness, state-ordering, boundary, or hot-path performance defects found in the changed code; the
Some(0)/None/limit == 1boundary behaviour, the overflow guards, and the binary-search monotonicity all check out.