Deep Code Correctness / Invariants / Hot-Path Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages)
Scope: 9 files, ~150 changed lines across selene + helios (+ tests/docs). Below the 12-file / 900-LOC partition threshold, so audited directly (no sub-agents). All findings verified against the tree at 5021b7a.
Verdict
No verified Blocker or Major code defects, and no hot-path performance regressions. The change is a pure cap on one already-existing sizing expression (pages → pages.min(max_sequence_pages)), applied consistently at all three sites that must agree, and it is provably conservative rather than permissive. Details of what I verified are below, followed by two Minor observations.
1. Callee / enum / design-invariant resolution
max_sequence_pages(helios/src/runtime_core/memory.rs:563-568) —div_ceilonNonZeroU64cannot trap; both degenerate inputs (page_tokens == 0,context == 0) are rejected before division (:564-565error path,:1008and_then(NonZeroU64::new)), so theexpectat:567is genuinely unreachable. It is computed unconditionally at:1012, beforepage_ceiling's early return at:576-578under the default--kv-cache-limit memory— this is exactly the hole the PR description claims to close, and readingpage_ceilingconfirms it::576 if mode == KvCacheLimit::Memory { return Ok(None) }returns before thecontext == 0 || page_tokens == 0validation at:579, so without the new standalone check a zeropage_tokenswould have reacheddiv_ceil.capture_chain_pages(memory.rs:676-678) —pages.min(max_sequence_pages.get())is a monotone, idempotent clamp:f(f(x)) == f(x)andf(x) <= x, so the binary search incapacities(:789-797) keeps its monotonicity precondition, and every caller gets a value no larger than the uncapped one.- Consistency across the three sizing sites — the cap is applied at
:1502(capture_growthfeeding the binary search),:1568(planned_offload_host = Some(tier_host.max(chain_bytes))), and threaded intoPrepareInputs.max_sequence_pagesat:1146, whichheadroom_innerconsumes atselene/src/offload.rs:166-168. The planned host budget and the attach-time slab therefore cannot diverge: both reduce tomin(pages, max_sequence_pages) + layout.row_slots(). Layout::row_slots()(selene/src/geometry.rs:217-222) andpage_record_bytes(:92-94) confirm thechain_pages + row_slots()arithmetic in both crates measures the same record units (max per-rank row bytes over per-rank page bytes), so the "plus one row" term is dimensionally correct inselene/src/offload.rs:169-171andmemory.rs:688.pool_only()(selene/src/offload.rs:117-119) /disk_enabled()(:109-111) — confirmedpool_only()requirespool.is_some() && memory_bytes == 0 && !disk_enabled(), so the capture-buffer branch (:164-181) is genuinely disjoint from the disk branch (:182-193); the cap cannot leak into warm-memory or disk intake sizing.ownerof the bound: doesmax_sequence_tokenstruly upper-bound one capture chain?helios/src/model/catalog.rs:46-55validatesconfig.limits.max_sequence_tokens != 0,<= prepared_sequence_tokens, andis_multiple_of(page_tokens);helios/src/model.rs:268-272(fit_context) additionally clamps it by page capacity. The capture chain for one sequence isconsumed_tokens / page_tokens <= max_sequence_tokens / page_tokens, somin(GPU pages, div_ceil(max_sequence_tokens, page_tokens))cannot truncate a legitimate single-sequence chain. The bound is safe in direction.- Overflow/checked arithmetic —
chain_pages.checked_add(row_slots)(offload.rs:170),slots.checked_add(...)(memory.rs:688), andsaturating_add/saturating_mulatmemory.rs:1568-1570are all unchanged in kind; the cap only shrinks operands, so no new overflow path.
2. Order-of-operations / state-transition tracing
PrepareInputsdestructuring atselene/src/offload.rs:623-629now uses..and dropsmax_sequence_pages;headroom_inneris passed the wholeinputsvalue (:704-710), so the bound still reaches the sizing code. No stale-read or field-shadowing hazard:PrepareInputsisCopy(:332).PlannedHostBudgets::max_sequence_pagesis set in the sameOk(...)that returnsoffload_host(memory.rs:1604-1608) and consumed immediately byNativeModel::prepare_offload(model.rs:1047-1053→:1125), so planning and attach observe one value; it is aCopyNonZeroU64threaded by value, not recomputed.- The binary-search-then-clamp ordering is sound because
fits()(memory.rs:763-776) also receives the clamped page count via the closure at:1502, so the search's feasibility predicate and its finalpagesvalue are consistent;:1561(pages > local_pages) still guards the agreement path. capture_growthreturningNonewhenextra > host_free(:691-693) remains the shrink mechanism; cappingpagesfirst only makesextrasmaller, i.e. it strictly widens the feasible set. No error path is newly reachable, and thehost budget cannot hold a full pool capturefailure atoffload.rs:176-178now triggers on the smaller chain.
3. Adversarial boundary inputs (concrete substitutions)
context = 1025, page_tokens = 64→div_ceil= 17 (asserted atmemory.rs:2459-2465);context = 1, page_tokens = 64→ 1 (NonZeroU64::MIN-equivalent, no zero result);page_tokens = 0→Err(:2458).pages < max_sequence_pages(e.g.pages = 10, limit = 16384) →minreturnspages, identical to pre-PR behaviour; the new assertionif max_sequence_pages.is_some() { assert!(slots < ...) }atselene/src/offload/tests.rs:558-560is only exercised on the(512, Some(64))row, so it cannot be vacuously satisfied.pages == max_sequence_pages→ both bounds equal;capture_chain_pagesidentity, no off-by-one, and+ row_slots()still adds the row exactly once.host_free == 0pastmax_sequence_pages— the new test atmemory.rs:2469-2485constructsreserved = (max_pages + row_slots) * page_record_bytesand assertscapture_growth(&layout, 512, reserved, 0, 1) == None(uncapped exhausts) while the capped call returnsSome(0), then assertspages == uncapped_pagesandpages > max_pages.get(). I traced this againstcapture_growth(:688-694):extra = slots*page_record_bytes - reserved, which is exactly0whenpages == max_pages, soextra > host_free (0)is false andhost_share = 0— the assertions are arithmetically correct, and I confirmedcapacities'fits()(:763-776) folds this todevice + 0 <= budget, so the search terminates at the memory-limited maximum rather than being pinched by the capture term. This is the "does not throttle GPU pages" claim, and the code supports it.shared_ranks = 0(capture_growth'sshared_ranks == 0 → 0branch,:690) andshared_ranks = 1both covered by the test's1argument; no division by zero.
4. Hot-path big-O
All touched code is startup-only: max_sequence_pages and capture_chain_pages are O(1), called once per allocate_caches, and once per capture_growth invocation inside the existing O(log(max_pages)) binary search (:789-797). No per-step, per-request, or per-victim path is touched; no allocation added. The clamp strictly reduces the number of SlabPool slots populated and CUDA-registered (offload.rs:722-754), so the change is a startup-time and host-RSS improvement, not a regression.
Minor observations (non-blocking, offered as hardening only)
Minor 1 — #[non_exhaustive] is claimed but not applied, so the .. is purely forward-looking.
selene/src/offload.rs:332-347:
#[derive(Clone, Copy, Debug)]
pub struct PrepareInputs {
pub max_active: usize,
pub input_staging: u64,
pub shard: Option<(usize, usize)>,
pub integrated: bool,
pub max_sequence_pages: Option<NonZeroU64>,
}
The destructuring at :623-629 was changed to .., but PrepareInputs has no #[non_exhaustive], so external struct-literal construction still breaks on any added field. The .. buys nothing today. Not a bug — helios and selene-manager are the only constructors and they compile — but if the intent is API stability, #[non_exhaustive] (or a builder) is needed. Counterexample: any out-of-tree crate writing PrepareInputs { max_active, input_staging, shard, integrated } breaks on this PR regardless of the ...
Minor 2 — the documented guarantee is weaker than the invariant actually needed on the restore path.
selene/src/offload.rs:343-346 documents the field as "no single sequence chain exceeds limit pages." That is the correct justification for capture. I checked the sibling path that reads slot counts back out (fetch_chain, selene/src/memory.rs:2201-2320, pin_export_chain, :4030-4100, and export_chain, :4105-4125) and the bound is not consulted there at all, so nothing in restore can over-read a truncated chain — fetch_chain validates slots.len() != ticket.pages.len() || slots.len() != chain.pages (:2275-2281) and pin_export_chain validates chain.total_pages against endpoint.consumed_tokens / page_tokens (:4078-4082). The doc comment is therefore accurate for what the field does; my note is only that a future caller adding a multidoc/parallel-chain consumer must not read "single sequence" as "any chain the store may hold." No action required for this PR.
Things I could not fully verify within the turn budget
- I did not exhaustively enumerate every
PrepareInputsliteral inselene/src/offload/tests.rs(lines 1430, 1469, 1488 were not individually opened); they compile via..inputs(n)or explicitmax_sequence_pages: None, and the PR runs 649selenetests green, so a missed literal would have been a build break, not a silent defect. - The live RSS numbers in the PR description (
18.74–19.06 GiBvs7.83–8.04 GiB) are stated to come from av0.6.0build (f705086) rather than an A/B restart on basef46a99220a; that is a provenance caveat for the benefit claim, not a code defect, and it belongs to the evidence-review lens rather than this one.