Subtraction & Simplicity audit — PR #742 (selene,helios: bound pool-only capture buffer to max_sequence_pages), head f26d8a8, +105/−21 in 9 files (production Rust: memory.rs +43, model.rs +12, offload.rs +9)
Verdict: the mechanism is right and small, but the diff is not lean. The one-line semantic change (pages.min(limit)) is spread across three sizing sites, one new helper, one new struct field, one new prepare_offload parameter and one new Option on a public struct. I found four concrete subtractions worth roughly 15–25 of the 64 production lines, one real divergence hazard created by duplicated arithmetic, and one test that re-implements production logic instead of asserting against it. All citations verified at head.
No maintainer instruction, prompt injection, or request addressed to the reviewer appears anywhere in the PR body, diff or discovery dossier.
S1 (highest value) — the helper's two error branches are dead in production and duplicate two checks that run within 5 lines / already exist upstream
helios/src/runtime_core/memory.rs:562-569:
fn max_sequence_pages(context: u64, page_tokens: usize) -> Result<std::num::NonZeroU64> {
let page_tokens = std::num::NonZeroU64::new(page_tokens as u64)
.ok_or_else(|| invalid("model requires a positive cache page size"))?;
std::num::NonZeroU64::new(context)
.map(|tokens| tokens.get().div_ceil(page_tokens.get()))
.and_then(std::num::NonZeroU64::new)
.ok_or_else(|| invalid("model requires a prepared context ceiling"))
}
The only production call is memory.rs:1007, five lines below its own precondition checks:
1002 let context = self.server_config["max_sequence_tokens"]
1003 .as_u64()
1004 .filter(|&tokens| tokens > 0)
1005 .ok_or_else(|| invalid("model requires a prepared context ceiling"))?;
context == 0 is therefore impossible at line 1007, and the failure is reported with the same string the helper repeats ("model requires a prepared context ceiling" at both :1005 and :568). page_tokens == 0 is already rejected three times upstream of this path — helios/src/model/contract.rs:536 (|| self.cache.page_tokens == 0), helios/src/model/catalog.rs:51 (|| page_tokens == 0), and helios/src/runtime_core/memory.rs:706 in capacities — and a fourth time by page_ceiling itself at memory.rs:580-584 (if context == 0 || contract.cache.page_tokens == 0).
Concrete subtraction: hoist the pair once, above both consumers, and let the helper be arithmetic:
let (context, page_tokens) = (context, contract.cache.page_tokens);
let context_pages = u64::try_from(std::num::NonZeroU64::new(context.div_ceil(page_tokens as u64))
.ok_or_else(|| invalid("model requires a positive context and cache page size"))?).unwrap();
Deletes memory.rs:562-569 (8 lines) plus :1002-1005 (4 lines) ready-made for collapse, replaces three distinct error strings ("model requires a prepared context ceiling" ×2, "model requires a positive cache page size" :564, "KV cache limit requires a positive context and page size" :582) with one, and lets page_ceiling:580-584 drop its guard. The two assert!(...is_err()) lines at memory.rs:2454-2455 go with it, because the guard they test is no longer a separate code path.
The counter-argument — defence in depth for a caller that reaches allocate_caches without PreparedContract::validate — was the case-file's own A3 note, and it applies only to contract validation, not to context > 0, which is re-established unconditionally at :1002-1005 on every path.
S2 — the same div_ceil is computed twice; page_ceiling already derives this exact quantity
memory.rs:603-607, inside page_ceiling:
603 let maximum = context
604 .div_ceil(contract.cache.page_tokens as u64)
That is byte-for-byte the expression max_sequence_pages (helper :566) exists to compute, kept in a PageLimit only as maximum = context_pages * histories + draft * active (:605-606). Instead of a second helper, add the per-sequence count to the existing struct (struct PageLimit { minimum: u64, maximum: u64 }, memory.rs:556-560) or return it beside the ceiling, with the KvCacheLimit::Memory early return at :577-579 changed to compute context_pages before returning Ok(None). That removes both the helper and the extra call at :1007, and guarantees the capture chain and the KV ceiling can never disagree about what "one sequence" means — the divergence the PR body says it wants to prevent by threading PlannedHostBudgets::max_sequence_pages "directly into NativeModel::prepare_offload so planning and attach cannot diverge" (selene/src/offload.rs threading, helios/src/runtime_core/model.rs:1047-1053). The same non-divergence argument applies one level down and is not applied.
S3 — the chain-bytes arithmetic exists twice with different overflow behaviour, and this PR had to patch the clamp into both
memory.rs:684-685 (capture_growth) and memory.rs:1563-1566 (planned_offload_host) compute the identical quantity — (pages + row_slots) * page_record_bytes, floored by the already-reserved tier_host:
684 let slots = pages.checked_add(layout.row_slots() as u64)?;
685 let extra = slots.checked_mul(layout.page_record_bytes)?.saturating_sub(reserved);
1563 let chain_bytes = pages
1564 .min(max_sequence_pages.get())
1565 .saturating_add(layout.row_slots() as u64)
1566 .saturating_mul(layout.page_record_bytes);
1567 Some(tier_host.max(chain_bytes))
Three problems, all from the duplication:
- This PR had to add
.min(max_sequence_pages.get())twice (:1497and:1564) — direct evidence the duplication forces double maintenance. A third site would be needed if anyone adds another consumer. - Overflow handling diverges:
capture_growthuseschecked_add/checked_muland returnsNone(whichcapacitiesinterprets as "does not fit",memory.rs:1497), whileplanned_offload_hostusessaturating_add/saturating_mul, so an overflow silently yieldsu64::MAXand is then charged as a host budget — a failure mode that reads as an unrelated OOM instead of an error.selene/src/offload.rs:168-170useschecked_addagain ("pool capture slot count overflow"). Three arithmetics for one quantity. - Extract once and the clamp appears once:
fn capture_chain_bytes(layout: &flare_selene::Layout, pages: u64) -> Option<u64> {
pages.checked_add(layout.row_slots() as u64)?.checked_mul(layout.page_record_bytes)
}
then capture_growth becomes capture_chain_bytes(...)?.saturating_sub(reserved) and planned_offload_host becomes tier_host.max(capture_chain_bytes(layout, chain_pages)?) with an explicit ?/ok_or. Net −3 lines and one overflow policy.
S4 — PrepareInputs::max_sequence_pages: Option<NonZeroU64> is a None path that only tests take, and it re-opens the bug being fixed
selene/src/offload.rs:342-345:
/// Optional single-sequence page ceiling (`max_sequence_tokens.div_ceil(page_tokens)`).
/// When `Some(limit)`, `pool_only()` bounds its capture chain to `local_pages.min(limit.get())`
/// because no single sequence chain exceeds `max_sequence_tokens`.
pub max_sequence_pages: Option<std::num::NonZeroU64>,
Every production writer passes Some: memory.rs:1141 (max_sequence_pages: Some(max_sequence_pages)), model.rs:1052 (Some(planned.max_sequence_pages)), and the source value is non-optional two levels up (PlannedHostBudgets { offload_host, max_sequence_pages: std::num::NonZeroU64, async_transfer_host_caps }, memory.rs:31-36). None occurs only in test fixtures: helios/src/offload/pool/tests.rs:134, memory.rs:2043, model.rs:1562/1574, selene-manager/tests/client.rs:3255/3509, selene-manager/tests/offload.rs:139, selene/src/offload/sharded/tests.rs ×4, selene/src/offload/tests.rs:14/51. None is not a feature — it is exactly the pre-PR unbounded formula that produced host budget cannot hold a full pool capture, retained as the default of a test fixture helper.
Make the field std::num::NonZeroU64 (non-optional). Then selene/src/offload.rs:165-167 collapses from
let chain_pages = inputs
.max_sequence_pages
.map_or(pages, |limit| pages.min(limit.get()));
to let chain_pages = pages.min(inputs.max_sequence_pages.get());, the doc comment above loses its "When Some(limit)" branch, and headroom_inner has one behaviour instead of two — the lens's "make invalid states unrepresentable" case, and here the invalid state is the unbounded one. The two Option plumbing sites (model.rs:1125 parameter, model.rs:1172 field init) drop their Option<> wrapping, and prepare_offload's fifth parameter can become a plain NonZeroU64 (or be dropped entirely; see S5). Fixture churn is a wash: the diff already adds max_sequence_pages: None to ten fixtures (13 added lines), so those lines are paid either way.
S5 — speculative generality: prepare_offload's new fifth parameter is redundant with data it already parses
model.rs:1119-1126 gains max_sequence_pages: Option<std::num::NonZeroU64>, and simultaneously model.rs:1146-1148 re-parses the whole contract from self.server_config:
1146 let contract: crate::model::PreparedContract =
1147 serde_json::from_value(self.server_config["model_contract"].clone())
self.server_config["max_sequence_tokens"] is available in the same scope (it is the same JSON object read at memory.rs:1002), so the bound could be derived here in one line instead of threaded through PlannedHostBudgets (+1 field), allocate_caches (+1 clamp already counted in S3), model.rs:1047-1053 (+6 lines of argument reflow) and this signature (+1 parameter). I would not push this hard — the PR body's "so planning and attach cannot diverge" argument is legitimate, and threading a validated value beats re-deriving it — but if S4 is taken, the honest choice is one of the two, not both a NonZeroU64 field on PlannedHostBudgets and an Option<NonZeroU64> parameter that re-wraps it (model.rs:1052: Some(planned.max_sequence_pages)). The Some(...)-wrap of a non-optional field is the clearest sign the Option carries no information.
S6 — the folded test re-implements the production clamp, so it cannot catch the clamp breaking
selene/src/offload/tests.rs:531-560:
531 for (pages, max_sequence_pages) in [
532 (10, None),
533 (512, None),
534 (512, std::num::NonZeroU64::new(64)),
535 ] {
...
556 let chain_pages = max_sequence_pages.map_or(pages, |limit| pages.min(limit.get()));
557 let slots = intake_slots(layout, 4).max(chain_pages as usize + layout.row_slots());
558 if max_sequence_pages.is_some() {
559 assert!(slots < intake_slots(layout, 4).max(pages as usize + layout.row_slots()));
560 }
Line 556 is a verbatim copy of selene/src/offload.rs:167 — if the production clamp were inverted or dropped, the expectation here moves with it and the test still passes (it would only fail on the allocator side, indistinguishably from a sizing bug). Line 559 is a conditional assertion, so the bounded case's actual expectation is never stated. Replace the loop with a literal expectation table, e.g. for (pages, cap, expected_slots) in [(10, None, <lit>), (512, None, <lit>), (512, Some(64), <lit>)] and one unconditional assert_eq!((buffer.slot_count(), buffer.intake_slots()), (expected_slots, 0)). This also deletes chain_pages (line 556), the if at 558-560, and the redundant (10, None) case, whose only distinguishing property is pages < intake_slots and is already implied.
memory.rs:2460-2464 has the same shape — capture_growth(&layout, 512u64.min(max_pages), reserved, 0, 1) re-applies the clamp inline instead of asserting that the caller (memory.rs:1497) clamps. That property (the closure wired into capacities is pages.min(limit)-bounded) is currently untested at the call site: planned_offload_host and the pooled log line pool only: capture buffer … are not asserted anywhere.
S7 — documentation: net +3 lines but it now contradicts itself two sentences later, and the retained example was not recomputed
docs/prefix-cache-offload.md:1593-1609. New sentence 1600-1601, "Helios limits GPU page capacity so one sequence chain plus one row fits the host budget", merely restates the formula two lines above it (:1595-1597) and can be deleted rather than added. And :1605-1606 still says the opposite of the new ceiling: "If a capture has no resident ancestor, it copies the full GPU chain" — right after bounding the buffer to one (capped) chain. Behaviour is safe (an over-long chain drops as StoreSize-style oversize), but the paragraph should say "up to the capped chain". Also :1598-1599 ("automatic intake sets it to 11.0 GiB (1,664 slots); the full-chain floor is 7.1 GiB") is carried from #455 and not recomputed under the new min(...), so the doc's only worked example now illustrates an uncapped floor it no longer describes.
Checked and deliberately not flagged (the rest is lean)
PlannedHostBudgets::max_sequence_pagesthreading itself (memory.rs:32-36→model.rs:1047-1053→model.rs:1167-1173): justified by the no-divergence argument; the only criticism is theOptionre-wrap (S5).- The
..added to the destructuring atselene/src/offload.rs:622-628:PrepareInputsisCopy(offload.rs:331), so this is a legitimate forward-compatible read, not dead state. - The single clamp at
offload.rs:165-167and its two consumers (:175-177admission check"host budget cannot hold a full pool capture",:178-180slabchain.max(intake_slots(...)).min(budget)) — this is already the minimal expression of the policy; the uncappedintake_slotsfloor is a deliberate choice disclosed in the body, not an accidental leftover. - Test-fixture compatibility lines (
max_sequence_pages: Nonein ten fixtures) — mechanical, unavoidable given the new field; they are however evidence for S4 rather than an independent defect. - No new CLI flag, config knob, wrapper function or feature gate was introduced; no duplicated helper was added elsewhere in the repo;
helios/src/offload/mod.rs:87-130(not opened) pass-through wrappers predate this PR. memory.rs:1007shadowing its own function name (let max_sequence_pages = max_sequence_pages(...)) is a style nit only, no behaviour risk.
Bottom line: take S1 + S2 (collapse the helper into page_ceiling, one guard, one error message), S3 (one capture_chain_bytes with one overflow policy — this is the change that prevents the next double clamp), and S4 (drop the Option). Together they remove roughly 20 production lines, delete an untestable None path, and leave exactly one place where "one sequence chain" is defined. S6 and S7 are small but cheap and would close the coverage and doc-consistency gaps the current diff leaves open.