Deep Code Correctness / Invariants / Hot-Path Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages), head 66d6af3
PR size: 9 files, ~90 changed lines, 3 crates (selene, helios, selene-manager tests only) — under the >12 files / >900 LOC partitioning threshold, so I audited directly with batched reads instead of spawning sub-agents.
Verdict
No Blocker, no Major, and no hot-path complexity defect found. The changed logic is arithmetically sound: the new bound cannot under-size the capture buffer relative to any real capture chain, it cannot throttle GPU KV pages, and it does not break the sub-100-LOC hot path (it is one min per fits probe, O(1)). Two Minor defects are verified below: a guard that can never fire (with an unguarded division next to it that panics where the author intended an error), and a max() term that is provably a no-op (dead expression) in planned_offload_host.
Invariants I verified (all hold)
- The cap cannot under-size a real chain. A captured record's page count is the logical prefix length in pages.
helium/src/scheduler.rs:2098-2101(not opened) computeschain_pages: self.cache.page_chain(id)/tail_pages: (consumed_tokens / page_tokens - parent.consumed_tokens / page_tokens), so full chain pages =consumed_tokens / page_tokens;helios/src/model/catalog.rs:46-55enforcesmax_sequence_tokens <= prepared_sequence_tokens,max_sequence_tokens.is_multiple_of(page_tokens),page_tokens != 0, andhelios/src/model.rs:268-272(fit_context) only lowers the runtime ceiling, sochain_pages <= max_sequence_tokens / page_tokens = max_sequence_pagesexactly (thediv_ceilatmemory.rs:999is exact, not over/under-shooting). - Planning and attach cannot diverge.
memory.rs:1593-1597returnsPlannedHostBudgets { offload_host, max_sequence_pages, .. };model.rs:1047-1053passesSome(planned.max_sequence_pages)intoprepare_offload, which threads it verbatim intoPrepareInputs { max_sequence_pages, .. }(model.rs:1167-1173) down toselene/src/offload.rs:703-709→headroom_inner, which applies the identicalpages.min(limit.get())formula (offload.rs:165-170). No second caller in production code exists (search_code PrepareInputs\\s*\\{: onlymemory.rs:1129,model.rs:1167, plus test fixtures). - Budget accounting stays conservative.
capture_growth(layout, pages.min(max_seq), tier_host, host_growth, shared)(memory.rs:1490) uses the same clamp asheadroom_inner, so the host byte reservation and the host byte consumption agree;reserved = tier_hostalready contains theintake_slotsfloor, sosaturating_sub(reserved)can only under-stateextra, never over-state (ahost_freeshortfall fails closed withNone). intake_slotsfloor genuinely preserved (offload.rs:178-180:chain.max(intake_slots(layout, inputs.max_active)).min(budget)), so concurrent transfer windows are not starved — matching the PR's stated intent.- The new helios test does discriminate.
pool_capture_growth_caps_at_max_sequence_pages_without_throttling_gpu_pages(memory.rs:2446-2464) is not tautological: withhost_free = 0andreserved = (128 + row_slots) * page_record_bytes, removing.min(max_sequence_pages)makescapture_growthreturnNoneforpages > 128, the binary search (memory.rs:776-784) converges to 128, andassert!(pages > max_sequence_pages)fails. Doubling the cap to 256 also failsassert_eq!(pages, uncapped_pages)(uncapped = 1024, not 256). Good counterexample coverage.
Finding 1 — Minor: new error branch is unreachable, and the reachable path divides by a possibly-zero page_tokens (panic instead of the intended error)
Diff site: helios/src/runtime_core/memory.rs:993-1000
let context = self.server_config["max_sequence_tokens"]
.as_u64()
.filter(|&tokens| tokens > 0)
.ok_or_else(|| invalid("model requires a prepared context ceiling"))?;
let ceiling = page_ceiling(options.kv_cache_limit, context, active as u64, &contract)?;
let max_sequence_pages =
std::num::NonZeroU64::new(context.div_ceil(contract.cache.page_tokens as u64))
.ok_or_else(|| invalid("model requires a positive prepared context ceiling"))?;
Callee resolution (never assume):
page_ceiling(memory.rs:562-609) returns before validating the page size when the limit mode is the defaultMemory:
(if mode == KvCacheLimit::Memory { return Ok(None); } if context == 0 || contract.cache.page_tokens == 0 { return Err(invalid("KV cache limit requires a positive context and page size")); }KvCacheLimit::Memoryis the documented default:memory.rs:1526-1528options.memory_limit.unwrap_or(...)pattern andmemory.rs:1541-1543KvCacheLimit::Memory => {}.)contextis already> 0(line 995).page_tokensthere iscontract.cache.page_tokens: usize(definitionhelios/src/model/contract.rsPageTableView-adjacentCacheContract, andcontract.validatecontract.rs:536rejectspage_tokens == 0— but that validation is not re-run on this deserialized copy:memory.rs:900-902only doesserde_json::from_value).
Two concrete defects, same three lines:
- Unsatisfiable guard / dead error. With
context >= 1andpage_tokens >= 1,u64::div_ceilreturns>= 1, soNonZeroU64::new(...)is neverNone. Error message"model requires a positive prepared context ceiling"is unreachable code. Counterexample:max_sequence_tokens = 1,page_tokens = 8192→1.div_ceil(8192) = 1→Some(1). - Unguarded divisor on the reachable path. Under the default
--kv-cache-limit memory,page_ceilingreturnsOk(None)at line 568-570 and never checkspage_tokens. Counterexample:server_config["model_contract"].cache.page_tokens = 0,max_sequence_tokens = 1024→ line 999 executes1024u64.div_ceil(0)→attempt to divide by zeropanic during model startup, where the surrounding code style (and the author's own new.ok_or_else) clearly intends a recoverableinvalid(...)error. Note this is a new panic site: before this PR nothing divided bycontract.cache.page_tokenson theMemory-mode path (page_ceilingused it only after its zero check).
Fix (validate the divisor itself, and drop the impossible NonZeroU64 failure):
let page_tokens = std::num::NonZeroU64::new(contract.cache.page_tokens as u64)
.ok_or_else(|| invalid("model requires a prepared context ceiling and page size"))?;
let max_sequence_pages = std::num::NonZeroU64::new(context.div_ceil(page_tokens.get()))
.expect("positive context over a positive page size is at least one page");
(or hoist a single if context == 0 || contract.cache.page_tokens == 0 { return Err(...) } above page_ceiling and keep NonZeroU64::new(..).expect(..)).
Side note (not a defect, recorded for completeness): the added .filter(|&tokens| tokens > 0) means a 0 ceiling under KvCacheLimit::Context|Concurrency now reports "model requires a prepared context ceiling" instead of page_ceiling's "KV cache limit requires a positive context and page size". Both are clean startup errors; only the message changes.
Finding 2 — Minor: pages.min(max_sequence_pages.get()) in planned_offload_host is provably a no-op (dead expression), so it neither bounds what it appears to bound nor can detect divergence
Diff site: helios/src/runtime_core/memory.rs:1554-1560
let planned_offload_host = if capture {
let layout = capture_layout.as_ref().unwrap();
let chain_bytes = pages
.min(max_sequence_pages.get())
.saturating_add(layout.row_slots() as u64)
.saturating_mul(layout.page_record_bytes);
Some(tier_host.max(chain_bytes))
Proof of no-op. tier_host is the second tuple element returned by headroom_with_inputs_for_budget (memory.rs:1126-1138), i.e. offload.rs:199-220:
let intake = ...; // slots after .max(intake_slots(..)).min(budget)
let host = memory.checked_add(intake)?; // memory == 0 in pool-only capture
Ok((tiers + pool, host))
and in the pool-only branch chain = min(local_pages, max_sequence_pages) + row_slots (offload.rs:164-180) where local_pages = capture.then_some(minimum_pages) (memory.rs:1136). Also capture_growth during the search raises the reservation to min(pages, max_seq) + row_slots records whenever that exceeds tier_host, and capacities guarantees pages >= minimum_pages (memory.rs:776 let (mut low, mut high) = (minimum_pages, maximum_pages);, returned as the second element and only ever min-reduced by agree.caches to the same value across ranks). Therefore tier_host >= (min(minimum_pages,max_seq)+row_slots)*record >= chain_bytes always, so tier_host.max(chain_bytes) == tier_host in every reachable configuration. Counterexample check for the case the code seems designed for (minimum_pages = 10, max_sequence_pages = 1000, agreed pages = 500, intake_slots = 144): tier_host = 144*record while chain_bytes = 501*record — this looks like the max is doing work, but capture_growth would have returned None for pages = 500 (extra 357*record > host_free) and the search would have converged at 144 - row_slots, so pages = 500 is unreachable; pages is always <= minimum_pages or fully host-funded, and in the latter case tier_host already includes it (memory.rs:1485-1491).
Why it matters: the expression advertises a bound on planned_offload_host that it does not enforce (the real bound is enforced inside capture_growth and inside headroom_inner), and because it is a no-op it would silently mask a future divergence between the GPU-page clamp in capture_growth and the attach-time sizing in selene::offload::headroom_inner — exactly the class of bug the PR says it is removing. It is also a second hand-written copy of the + row_slots / * page_record_bytes formula (offload.rs:168-170, memory.rs:675-676, memory.rs:1556-1559).
Fix: make the invariant explicit instead of redundant — either assert it,
let chain_bytes = pages.min(max_sequence_pages.get())
.saturating_add(layout.row_slots() as u64)
.saturating_mul(layout.page_record_bytes);
debug_assert!(chain_bytes <= tier_host, "attach-sized capture budget diverged from planning");
Some(tier_host)
or make selene the single owner by exposing the plan (flare_selene::offload::pool_capture_slots(layout, chain_pages, max_active)) and calling it from both headroom_inner and capture_growth/planned_offload_host.
Hot-path / complexity check (protocol part 4) — clean
The only per-iteration change is pages.min(max_sequence_pages.get()) inside the fits closure (memory.rs:1485-1491), evaluated O(log(maximum_pages)) times (≈ 17 probes for 150k pages, memory.rs:776-784) — O(1), no allocation. capture_growth remains allocation-free (checked_add/checked_mul/div_ceil only). max_sequence_pages is computed once per startup (memory.rs:998), not per step/request/victim. upstream: None in PrepareInputs keeps Copy semantics, so headroom_with_inputs(.., inputs, ..) callers (offload.rs:133, 147, 703-709, 1063-1120 test fixtures) pass it by value with no clone; adding a NonZeroU64 does not change the struct's Copy-ness or size class materially. No new Vec/HashMap anywhere in the diff.
Nothing found in these areas (checked, clean)
docs/prefix-cache-offload.md(+15/−12) — documentation only; wording accuracy (e.g. the buffer being one full chain vs. theintake_slots/minimum_pagesfloor) is explicitly out of my scope.selene/src/offload.rs:622-628destructuring with..— forward-compatible, andmax_sequence_pagesis consumed through the still-passedinputsvalue at lines 703-709, so the field is not silently dropped.- All test-fixture updates (
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) setmax_sequence_pages: None, whichmap_or(pages, ..)(offload.rs:167) treats as uncapped — identical to pre-PR behavior, so no test silently changes meaning. selene/src/offload/tests.rs:531-574: the(512, NonZeroU64::new(64))case yieldschain = 66,intake_slots(layout,4) = 144, soslots = 144 < 514— the assertion at line 558-560 is meaningful (removing the cap yields 514 and fails it), and theheadroom_with_inputscross-check at 569-574 recomputes the same formula independently of the implementation under test.- No state-machine, refcount/pin/unpin, or retirement/eviction ordering was touched by this diff (
selene/src/memory.rs,composite.rs(not opened),disk_store.rs(not opened) are unmodified), so protocol part 2 (same-loop flag read-before-write) has no new surface here.