Deep Code Correctness, Invariants & Hot-Path Audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages) @ f26d8a8
Scope decision: 9 files / ~105 changed lines / 2 crates but well under both partition thresholds (>12 files, >900 LOC), so audited directly with batched reads (no sub-agents).
Verdict
No Blocker and no Major code defect found. The new bound is mathematically sound, the value is threaded end-to-end without divergence, monotonicity of the existing capacities binary search is preserved, and no hot-path cost is added (all changed code is startup-only). Two Minor issues and one explicitly-unverified residual risk are reported below; everything else I checked resolved as correct, with the citations given so the claims are checkable.
Verification of the central invariant (the thing this PR rests on)
Claim: no captured chain can exceed max_sequence_pages = ceil(max_sequence_tokens / page_tokens).
- Publications carry
chain_pages: self.cache.page_chain(id)andtail_pages = consumed_tokens/page_tokens - parent.consumed/page_tokens—helios/src/scheduler.rs:2098-2101; alsoscheduler.rs:1981-1990,scheduler.rs:3153,scheduler.rs:3361. chain_pagesis exactly the sum of legalized tails:helios/src/cache.rs:600-606(page_chain= concatenation oftail_pages), andcache.rs:473-486rejects any publication whereconsumed_tokens/page_tokens - parent_len/page_tokens != tail_pages.len().- Every checkpoint endpoint satisfies
consumed_tokens <= execution_limit, andexecution_limitis clamped tolimits.max_sequence_tokens:helios/src/scheduler.rs:1590-1595—(prompt + max_new + extra).min(self.limits.max_sequence_tokens). ⇒chain_len <= floor(max_sequence_tokens / page_tokens) <= ceil(...) = max_sequence_pages. Bound holds, with exact fit at the boundary (catalog.rs:52-55requiresmax_sequence_tokensto be a multiple ofpage_tokens, anddiv_ceilcovers non-multiples anyway). - Draft pages do not inflate the chain:
draft_pages()(helios/src/scheduler.rs:1407-1413) is added only to reservation math (scheduler.rs:1416-1422,1600-1616), never toPublication.tail_pages; grep overhelios/src/scheduler/checkpoints.rsshowsdraft_tokens: 0in fixtures and no draft page ids in anyPublication. The cap therefore does not need a draft correction (unlikepage_ceiling'smaximum,memory.rs:603-607, which legitimately does includedraft * active). intake_slots(layout, inputs.max_active)is indeed left uncapped (selene/src/offload.rs:179), and in capture mode the slab is created withintake = 0(offload.rs:711) sofits()is pureslots <= slot_count(selene/src/memory.rs:1730-1732). The PR's32 × 91 × 2 + 128vs16,384 + 91example is arithmetically consistent withWINDOW_PAGES = 64(selene/src/shared/mod.rs:40(not opened)) androw_slots(selene/src/geometry.rs:217-222).
Units check (the most likely place this kind of change goes wrong — it does not): max_sequence_pages is computed from contract.cache.page_tokens (memory.rs:1007, field CacheContract.page_tokens, helios/src/model/contract.rs:183), and geometry.page_tokens — the layout's page unit — is set from that same field in both the sizing geometry (memory.rs:1031, with the placeholder page_capacity = 1) and the final published geometry (memory.rs:1623-1626, logical_page_tokens). Since Layout::new charges one record per page_capacity step (selene/src/geometry.rs:158-201), pages, geometry.page_capacity, and max_sequence_pages are all in the same (scheduler/logical) page unit, so pages.min(max_sequence_pages.get()) is dimensionally valid. Note the separate physical server_config["page_tokens"] (helios/proto/runtime_core.proto:244, ServingContract.page_tokens = 9) is used only for the default minimum_pages and bytes() extents (memory.rs:905-908, 713, 1490) — consistent with the existing comment at memory.rs:1621-1623 ("Scheduler page ids count the model contract's tokens per page, which exceeds the physical page when pages are sharded across ranks"). No cross-unit min is introduced.
Planning ↔ attach consistency: PlannedHostBudgets.max_sequence_pages (memory.rs:34, produced at memory.rs:1600-1604) is the single source and is passed straight into prepare_offload (helios/src/runtime_core/model.rs:1047-1053) → PrepareInputs (model.rs:1167-1173) → headroom_inner (selene/src/offload.rs:165-180). Both sides therefore clamp identically; there is no path where helios plans with the cap and selene attaches without it. prepare_with_inputs_budget_with_progress forwards the whole inputs struct (selene/src/offload.rs:703-709), so the new .. in the destructuring at offload.rs:622-628 only silences the unused field and cannot drop it.
Binary-search monotonicity preserved: the fits predicate (memory.rs:759-772) previously grew monotonically with pages through capture_growth; pages.min(cap) makes the growth term constant (flat) above the cap, which is still non-decreasing, so the low < high search at memory.rs:785-793 remains valid. capture_growth itself is unchanged and still saturates (memory.rs:684-690).
New helios test is sound (not vacuous): pool_capture_growth_caps_at_max_sequence_pages_without_throttling_gpu_pages (memory.rs:2452-2476) — max_sequence_pages(0,64)/…(1024,0) error, (1025,64)=17, (1_048_576,64)=16_384 are all correct; reserved = (128+row_slots)*page_record_bytes makes capture_growth(…,128,…) = Some(0) (extra = 0), so the capped search reaches the same pages as the uncapped one and pages > max_pages (extent 1024, budget 1 GiB / 4096 B) holds. The capped/unbounded branch added to pool_only_sizes_registered_capture_and_headroom_for_local_ranks (selene/src/offload/tests.rs:528-560) is also satisfiable: with geometry(64,&[("kv",4096)],8192), row_slots = 2, so intake_slots(layout,4) = 144, capped slots = max(144, 64+2) = 144 < 514. No failing or unsatisfiable assertion.
Findings
Minor 1 — max_sequence_pages() is now evaluated unconditionally, adding two new hard load failures unrelated to the prefix cache
helios/src/runtime_core/memory.rs:1002-1008 (diff site) with callees at memory.rs:562-569 and memory.rs:577-584.
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 = max_sequence_pages(context, contract.cache.page_tokens)?;
fn page_ceiling(mode: KvCacheLimit, context: u64, active: u64, contract: &PreparedContract) -> Result<Option<PageLimit>> {
if mode == KvCacheLimit::Memory {
return Ok(None); // <- the only place these two were validated is skipped by default
page_ceiling returns early under the default --kv-cache-limit memory, and the only other consumer of contract.cache.page_tokens (cache_geometry, memory.rs:1020-1040) runs only if cfg.enabled(). The new unconditional call therefore turns two previously-tolerated properties into fatal startup errors even when --prefix-cache-pool/disk/memory are all off:
contract.cache.page_tokens == 0→"model requires a positive cache page size";server_config["max_sequence_tokens"] == 0→"model requires a prepared context ceiling"(pre-PR,as_u64()acceptedSome(0)and planning proceeded underKvCacheLimit::Memory).
Concrete counterexample: a core whose ServingContract.max_sequence_tokens is absent/0 (the inspector explicitly treats 0 as "no prepared ceiling": helios/src/runtime_core/describe.rs:151, (contract.max_sequence_tokens > 0).then_some(...)), loaded through a runtime-core path that does not run catalog::validate (helios/src/model/catalog.rs:46-47, which is where max_sequence_tokens == 0 is normally rejected): pre-PR starts, post-PR fails at "Plan cache". Fix: make it lazy and cache-scoped, e.g.
let capture = options.prefix_cache.pool_only() && self.cluster().is_none();
let max_sequence_pages = capture
.then(|| max_sequence_pages(context, contract.cache.page_tokens))
.transpose()?;
with PlannedHostBudgets::max_sequence_pages: Option<NonZeroU64> (and .unwrap_or(u64::MAX) at the two min sites, memory.rs:1497 and 1563-1566); prepare_offload already takes Option<NonZeroU64> (model.rs:1125).
Minor 2 — the capped buffer can be smaller than one chain when intake_slots exceeds the host budget (pre-existing .min(budget) on the wrong side of .max)
selene/src/offload.rs:168-180 (untouched line 180 in the changed block):
let chain = chain_pages
.checked_add(layout.row_slots() as u64)
.ok_or("pool capture slot count overflow")?;
let budget = ... / layout.page_record_bytes;
if chain > budget { return Err("host budget cannot hold a full pool capture".into()); }
chain
.max(intake_slots(layout, inputs.max_active) as u64)
.min(budget)
The admission test only proves chain <= budget; the .max(intake_slots) then .min(budget) can yield a slot count below chain whenever chain <= budget < intake_slots(max_active). In that case no record can ever be sized (MemoryStore::fits = slots + 0 <= slot_count, selene/src/memory.rs:1730-1732, and allocate returns Ok(None), memory.rs:714-726), so pool-only capture silently captures nothing while startup reports success — the failure mode is an oversize-drop, not the intended host budget cannot hold a full pool capture. The PR narrows chain and thereby makes this window easier to enter (small budget, large max_active × row_slots), though the ordering itself predates this change. Fix: chain.max(intake_slots(...)).min(budget).max(chain) — or, equivalently, clamp the intake floor to budget before the chain comparison: let floor = (intake_slots(...) as u64).min(budget); chain.max(floor), keeping if chain > budget as the only error.
Residual risk (explicitly not verified — flagged, not claimed)
Because the cap is derived from the local max_sequence_tokens, and neither the shared-layout fingerprint (selene/src/geometry.rs:243-265, hashes page_tokens, plane names/sizes, row size) nor offload_identity (helios/src/runtime_core/model.rs:1131) includes max_sequence_tokens, two workers of the same core attached to the same --prefix-cache-pool address can have different caps. A record written by a worker with max_sequence_tokens = 1,048,576 (cap = 16,384 pages) that arrives at a worker with max_sequence_tokens = 131,072 (cap = 2,048) cannot be received into the smaller capture buffer: MemoryStore::allocate → fits (selene/src/memory.rs:1730-1732, 771-777) returns None and the record is treated as oversize — where on main it fit whenever GPU capacity ≥ chain. I could not, within this audit, trace whether a request-level length check bounds such records before they reach the host tier, so I am not reporting this as a defect; it is the one place where the new constraint is not proven safe and is worth a targeted test (two workers, same pool, different max_sequence_tokens).
Checked and found correct (no report-worthy defect)
- Same-loop/state-order tracing: no flag read-then-cleared pattern in the changed code; nothing in this diff is inside a per-step/per-poll loop.
- Hot-path big-O:
capture_growth/capacitiesrun once at cache planning; the addedminis O(1). No per-iteration allocation added; no change insideMemoryStorehot paths. ..destructuring atselene/src/offload.rs:622-628cannot dropmax_sequence_pages: the fullinputsis forwarded atoffload.rs:703-709.- Every
PrepareInputs/prepare_offloadconstruction site is updated (compiles-consistent):helios/src/offload/pool/tests.rs:129-135,helios/src/runtime_core/memory.rs:1136-1142&2038-2044,helios/src/runtime_core/model.rs:1167-1173&1559&1573,selene-manager/tests/client.rs:3250/3504,selene-manager/tests/offload.rs:134,selene/src/offload/tests.rs:9/46/540,selene/src/offload/sharded/tests.rs:113/256/387/553.PrepareInputsstaysCopy(Option<NonZeroU64>). docs/prefix-cache-offload.md:1592-1612matches the implemented formula (min(GPU page capacity, ceil(max_sequence_tokens / page_tokens))+ one row,intake_slotsuncapped) — doc/implementation agreement verified againstselene/src/offload.rs:165-180(wording otherwise out of scope).